@arcteninc/core 0.0.102 → 0.0.104

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var vc=Object.create;var Hr=Object.defineProperty;var wc=Object.getOwnPropertyDescriptor;var Tc=Object.getOwnPropertyNames;var Sc=Object.getPrototypeOf,jc=Object.prototype.hasOwnProperty;var Cc=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Tc(t))!jc.call(e,r)&&r!==n&&Hr(e,r,{get:()=>t[r],enumerable:!(s=wc(t,r))||s.enumerable});return e};var Pc=(e,t,n)=>(n=e!=null?vc(Sc(e)):{},Cc(t||!e||!e.__esModule?Hr(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react/jsx-runtime"),f=require("react"),ie=require("lucide-react"),yo=require("@ai-sdk/react"),ls=require("ai"),xo=require("@radix-ui/react-slot"),bo=require("class-variance-authority"),Ac=require("clsx"),kc=require("tailwind-merge"),Mc=require("@radix-ui/react-tooltip"),Jr=require("@radix-ui/react-use-controllable-state"),Ec=require("@radix-ui/react-collapsible"),Nc=require("react-dom"),Dc=require("@radix-ui/react-dialog"),Rc=require("./server.cjs");function ps(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Ge=ps(f),tn=ps(Mc),cr=ps(Ec),$t=ps(Dc);function ae(...e){return kc.twMerge(Ac.clsx(e))}const Nt=bo.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"}}),Se=Ge.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?xo.Slot:"button";return l.jsx(i,{ref:o,"data-slot":"button",className:ae(Nt({variant:t,size:n,className:e})),...r})});Se.displayName="Button";const Vc=bo.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 ws({className:e,variant:t,asChild:n=!1,...s}){const r=n?xo.Slot:"span";return l.jsx(r,{"data-slot":"badge",className:ae(Vc({variant:t}),e),...s})}const Ic=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Ge.useState(!0);Ge.useEffect(()=>{const a=e.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const c=a.scrollHeight;c>n?a.style.height=`${n}px`:a.style.height=`${c+6}px`}},[e.current,t])},vo=Ge.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Ge.useRef(null),[c,u]=Ge.useState("");return Ic({textAreaRef:a,triggerAutoSize:c,maxHeight:e,minHeight:t}),f.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),Ge.useEffect(()=>{u(r)},[o?.defaultValue,r]),l.jsx("textarea",{...o,value:r,ref:a,className:ae("flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",n),onChange:d=>{u(d.target.value),s?.(d)}})});vo.displayName="AutosizeTextarea";function Oc({delayDuration:e=0,...t}){return l.jsx(tn.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function pt({...e}){return l.jsx(Oc,{children:l.jsx(tn.Root,{"data-slot":"tooltip",...e})})}function gt({...e}){return l.jsx(tn.Trigger,{"data-slot":"tooltip-trigger",...e})}function yt({className:e,sideOffset:t=0,children:n,...s}){return l.jsx(tn.Portal,{children:l.jsxs(tn.Content,{"data-slot":"tooltip-content",sideOffset:t,className:ae("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...s,children:[n,l.jsx(tn.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Zr({className:e,...t}){return l.jsx("kbd",{"data-slot":"kbd",className:ae("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}const lr=f.createContext({});function ur(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const dr=typeof window<"u",wo=dr?f.useLayoutEffect:f.useEffect,gs=f.createContext(null);function hr(e,t){e.indexOf(t)===-1&&e.push(t)}function fr(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const rt=(e,t,n)=>n>t?t:n<e?e:n;function Fs(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let on=()=>{},it=()=>{};process.env.NODE_ENV!=="production"&&(on=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(Fs(t,n))},it=(e,t,n)=>{if(!e)throw new Error(Fs(t,n))});const ot={},To=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function So(e){return typeof e=="object"&&e!==null}const jo=e=>/^0[^.\s]+$/u.test(e);function mr(e){let t;return()=>(t===void 0&&(t=e()),t)}const Be=e=>e,$c=(e,t)=>n=>t(e(n)),Bn=(...e)=>e.reduce($c),Vn=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class pr{constructor(){this.subscriptions=[]}add(t){return hr(this.subscriptions,t),()=>fr(this.subscriptions,t)}notify(t,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](t,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const Ye=e=>e*1e3,Fe=e=>e/1e3;function Co(e,t){return t?e*(1e3/t):0}const Qr=new Set;function gr(e,t,n){e||Qr.has(t)||(console.warn(Fs(t,n)),Qr.add(t))}const Po=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Lc=1e-7,Fc=12;function Bc(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=Po(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>Lc&&++a<Fc);return i}function zn(e,t,n,s){if(e===t&&n===s)return Be;const r=o=>Bc(o,0,1,e,n);return o=>o===0||o===1?o:Po(r(o),t,s)}const Ao=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,ko=e=>t=>1-e(1-t),Mo=zn(.33,1.53,.69,.99),yr=ko(Mo),Eo=Ao(yr),No=e=>(e*=2)<1?.5*yr(e):.5*(2-Math.pow(2,-10*(e-1))),xr=e=>1-Math.sin(Math.acos(e)),Do=ko(xr),Ro=Ao(xr),zc=zn(.42,0,1,1),Uc=zn(0,0,.58,1),Vo=zn(.42,0,.58,1),_c=e=>Array.isArray(e)&&typeof e[0]!="number",Io=e=>Array.isArray(e)&&typeof e[0]=="number",ei={linear:Be,easeIn:zc,easeInOut:Vo,easeOut:Uc,circIn:xr,circInOut:Ro,circOut:Do,backIn:yr,backInOut:Eo,backOut:Mo,anticipate:No},Xc=e=>typeof e=="string",ti=e=>{if(Io(e)){it(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return zn(t,n,s,r)}else if(Xc(e))return it(ei[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),ei[e];return e},Qn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Wc(e,t){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(d){i.has(d)&&(u.schedule(d),e()),d(a)}const u={schedule:(d,h=!1,m=!1)=>{const w=m&&r?n:s;return h&&i.add(d),w.has(d)||w.add(d),d},cancel:d=>{s.delete(d),i.delete(d)},process:d=>{if(a=d,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(c),n.clear(),r=!1,o&&(o=!1,u.process(d))}};return u}const qc=40;function Oo(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Qn.reduce((M,N)=>(M[N]=Wc(o),M),{}),{setup:a,read:c,resolveKeyframes:u,preUpdate:d,update:h,preRender:m,render:p,postRender:w}=i,x=()=>{const M=ot.useManualTiming?r.timestamp:performance.now();n=!1,ot.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(M-r.timestamp,qc),1)),r.timestamp=M,r.isProcessing=!0,a.process(r),c.process(r),u.process(r),d.process(r),h.process(r),m.process(r),p.process(r),w.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(x))},b=()=>{n=!0,s=!0,r.isProcessing||e(x)};return{schedule:Qn.reduce((M,N)=>{const D=i[N];return M[N]=(F,B=!1,P=!1)=>(n||b(),D.schedule(F,B,P)),M},{}),cancel:M=>{for(let N=0;N<Qn.length;N++)i[Qn[N]].cancel(M)},state:r,steps:i}}const{schedule:ue,cancel:bt,state:ve,steps:Ts}=Oo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Be,!0);let rs;function Kc(){rs=void 0}const ke={now:()=>(rs===void 0&&ke.set(ve.isProcessing||ot.useManualTiming?ve.timestamp:performance.now()),rs),set:e=>{rs=e,queueMicrotask(Kc)}},$o=e=>t=>typeof t=="string"&&t.startsWith(e),br=$o("--"),Gc=$o("var(--"),vr=e=>Gc(e)?Yc.test(e.split("/*")[0].trim()):!1,Yc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,an={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},In={...an,transform:e=>rt(0,1,e)},es={...an,default:1},kn=e=>Math.round(e*1e5)/1e5,wr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Hc(e){return e==null}const Jc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Tr=(e,t)=>n=>!!(typeof n=="string"&&Jc.test(n)&&n.startsWith(e)||t&&!Hc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Lo=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(wr);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},Zc=e=>rt(0,255,e),Ss={...an,transform:e=>Math.round(Zc(e))},Rt={test:Tr("rgb","red"),parse:Lo("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+Ss.transform(e)+", "+Ss.transform(t)+", "+Ss.transform(n)+", "+kn(In.transform(s))+")"};function Qc(e){let t="",n="",s="",r="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),r=e.substring(4,5),t+=t,n+=n,s+=s,r+=r),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const Bs={test:Tr("#"),parse:Qc,transform:Rt.transform},Un=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),xt=Un("deg"),et=Un("%"),q=Un("px"),el=Un("vh"),tl=Un("vw"),ni={...et,parse:e=>et.parse(e)/100,transform:e=>et.transform(e*100)},Yt={test:Tr("hsl","hue"),parse:Lo("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+et.transform(kn(t))+", "+et.transform(kn(n))+", "+kn(In.transform(s))+")"},xe={test:e=>Rt.test(e)||Bs.test(e)||Yt.test(e),parse:e=>Rt.test(e)?Rt.parse(e):Yt.test(e)?Yt.parse(e):Bs.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Rt.transform(e):Yt.transform(e),getAnimatableNone:e=>{const t=xe.parse(e);return t.alpha=0,xe.transform(t)}},nl=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function sl(e){return isNaN(e)&&typeof e=="string"&&(e.match(wr)?.length||0)+(e.match(nl)?.length||0)>0}const Fo="number",Bo="color",rl="var",il="var(",si="${}",ol=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function On(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(ol,c=>(xe.test(c)?(s.color.push(o),r.push(Bo),n.push(xe.parse(c))):c.startsWith(il)?(s.var.push(o),r.push(rl),n.push(c)):(s.number.push(o),r.push(Fo),n.push(parseFloat(c))),++o,si)).split(si);return{values:n,split:a,indexes:s,types:r}}function zo(e){return On(e).values}function Uo(e){const{split:t,types:n}=On(e),s=t.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=t[i],r[i]!==void 0){const a=n[i];a===Fo?o+=kn(r[i]):a===Bo?o+=xe.transform(r[i]):o+=r[i]}return o}}const al=e=>typeof e=="number"?0:xe.test(e)?xe.getAnimatableNone(e):e;function cl(e){const t=zo(e);return Uo(e)(t.map(al))}const vt={test:sl,parse:zo,createTransformer:Uo,getAnimatableNone:cl};function js(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function ll({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let r=0,o=0,i=0;if(!t)r=o=i=n;else{const a=n<.5?n*(1+t):n+t-n*t,c=2*n-a;r=js(c,a,e+1/3),o=js(c,a,e),i=js(c,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function us(e,t){return n=>n>0?t:e}const me=(e,t,n)=>e+(t-e)*n,Cs=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},ul=[Bs,Rt,Yt],dl=e=>ul.find(t=>t.test(e));function ri(e){const t=dl(e);if(on(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(e);return t===Yt&&(n=ll(n)),n}const ii=(e,t)=>{const n=ri(e),s=ri(t);if(!n||!s)return us(e,t);const r={...n};return o=>(r.red=Cs(n.red,s.red,o),r.green=Cs(n.green,s.green,o),r.blue=Cs(n.blue,s.blue,o),r.alpha=me(n.alpha,s.alpha,o),Rt.transform(r))},zs=new Set(["none","hidden"]);function hl(e,t){return zs.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function fl(e,t){return n=>me(e,t,n)}function Sr(e){return typeof e=="number"?fl:typeof e=="string"?vr(e)?us:xe.test(e)?ii:gl:Array.isArray(e)?_o:typeof e=="object"?xe.test(e)?ii:ml:us}function _o(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>Sr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function ml(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=Sr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function pl(e,t){const n=[],s={color:0,var:0,number:0};for(let r=0;r<t.values.length;r++){const o=t.types[r],i=e.indexes[o][s[o]],a=e.values[i]??0;n[r]=a,s[o]++}return n}const gl=(e,t)=>{const n=vt.createTransformer(t),s=On(e),r=On(t);return s.indexes.var.length===r.indexes.var.length&&s.indexes.color.length===r.indexes.color.length&&s.indexes.number.length>=r.indexes.number.length?zs.has(e)&&!r.values.length||zs.has(t)&&!s.values.length?hl(e,t):Bn(_o(pl(s,r),r.values),n):(on(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),us(e,t))};function Xo(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?me(e,t,n):Sr(e)(e,t)}const yl=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>ue.update(t,n),stop:()=>bt(t),now:()=>ve.isProcessing?ve.timestamp:ke.now()}},Wo=(e,t,n=10)=>{let s="";const r=Math.max(Math.round(t/n),2);for(let o=0;o<r;o++)s+=Math.round(e(o/(r-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},ds=2e4;function jr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<ds;)t+=n,s=e.next(t);return t>=ds?1/0:t}function xl(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(jr(s),ds);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:Fe(r)}}const bl=5;function qo(e,t,n){const s=Math.max(t-bl,0);return Co(n-e(s),t-s)}const fe={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},Ps=.001;function vl({duration:e=fe.duration,bounce:t=fe.bounce,velocity:n=fe.velocity,mass:s=fe.mass}){let r,o;on(e<=Ye(fe.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=rt(fe.minDamping,fe.maxDamping,i),e=rt(fe.minDuration,fe.maxDuration,Fe(e)),i<1?(r=u=>{const d=u*i,h=d*e,m=d-n,p=Us(u,i),w=Math.exp(-h);return Ps-m/p*w},o=u=>{const h=u*i*e,m=h*n+n,p=Math.pow(i,2)*Math.pow(u,2)*e,w=Math.exp(-h),x=Us(Math.pow(u,2),i);return(-r(u)+Ps>0?-1:1)*((m-p)*w)/x}):(r=u=>{const d=Math.exp(-u*e),h=(u-n)*e+1;return-Ps+d*h},o=u=>{const d=Math.exp(-u*e),h=(n-u)*(e*e);return d*h});const a=5/e,c=Tl(r,o,a);if(e=Ye(e),isNaN(c))return{stiffness:fe.stiffness,damping:fe.damping,duration:e};{const u=Math.pow(c,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:e}}}const wl=12;function Tl(e,t,n){let s=n;for(let r=1;r<wl;r++)s=s-e(s)/t(s);return s}function Us(e,t){return e*Math.sqrt(1-t*t)}const Sl=["duration","bounce"],jl=["stiffness","damping","mass"];function oi(e,t){return t.some(n=>e[n]!==void 0)}function Cl(e){let t={velocity:fe.velocity,stiffness:fe.stiffness,damping:fe.damping,mass:fe.mass,isResolvedFromDuration:!1,...e};if(!oi(e,jl)&&oi(e,Sl))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*rt(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:fe.mass,stiffness:r,damping:o}}else{const n=vl(e);t={...t,...n,mass:fe.mass},t.isResolvedFromDuration=!0}return t}function hs(e=fe.visualDuration,t=fe.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:s,restDelta:r}=n;const o=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:c,damping:u,mass:d,duration:h,velocity:m,isResolvedFromDuration:p}=Cl({...n,velocity:-Fe(n.velocity||0)}),w=m||0,x=u/(2*Math.sqrt(c*d)),b=i-o,y=Fe(Math.sqrt(c/d)),j=Math.abs(b)<5;s||(s=j?fe.restSpeed.granular:fe.restSpeed.default),r||(r=j?fe.restDelta.granular:fe.restDelta.default);let M;if(x<1){const D=Us(y,x);M=F=>{const B=Math.exp(-x*y*F);return i-B*((w+x*y*b)/D*Math.sin(D*F)+b*Math.cos(D*F))}}else if(x===1)M=D=>i-Math.exp(-y*D)*(b+(w+y*b)*D);else{const D=y*Math.sqrt(x*x-1);M=F=>{const B=Math.exp(-x*y*F),P=Math.min(D*F,300);return i-B*((w+x*y*b)*Math.sinh(P)+D*b*Math.cosh(P))/D}}const N={calculatedDuration:p&&h||null,next:D=>{const F=M(D);if(p)a.done=D>=h;else{let B=D===0?w:0;x<1&&(B=D===0?Ye(w):qo(M,D,F));const P=Math.abs(B)<=s,z=Math.abs(i-F)<=r;a.done=P&&z}return a.value=a.done?i:F,a},toString:()=>{const D=Math.min(jr(N),ds),F=Wo(B=>N.next(D*B).value,D,30);return D+"ms "+F},toTransition:()=>{}};return N}hs.applyToOptions=e=>{const t=xl(e,100,hs);return e.ease=t.ease,e.duration=Ye(t.duration),e.type="keyframes",e};function _s({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:c,restDelta:u=.5,restSpeed:d}){const h=e[0],m={done:!1,value:h},p=P=>a!==void 0&&P<a||c!==void 0&&P>c,w=P=>a===void 0?c:c===void 0||Math.abs(a-P)<Math.abs(c-P)?a:c;let x=n*t;const b=h+x,y=i===void 0?b:i(b);y!==b&&(x=y-h);const j=P=>-x*Math.exp(-P/s),M=P=>y+j(P),N=P=>{const z=j(P),T=M(P);m.done=Math.abs(z)<=u,m.value=m.done?y:T};let D,F;const B=P=>{p(m.value)&&(D=P,F=hs({keyframes:[m.value,w(m.value)],velocity:qo(M,P,m.value),damping:r,stiffness:o,restDelta:u,restSpeed:d}))};return B(0),{calculatedDuration:null,next:P=>{let z=!1;return!F&&D===void 0&&(z=!0,N(P),B(P)),D!==void 0&&P>=D?F.next(P-D):(!z&&N(P),m)}}}function Pl(e,t,n){const s=[],r=n||ot.mix||Xo,o=e.length-1;for(let i=0;i<o;i++){let a=r(e[i],e[i+1]);if(t){const c=Array.isArray(t)?t[i]||Be:t;a=Bn(c,a)}s.push(a)}return s}function Al(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(it(o===t.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>t[0];if(o===2&&t[0]===t[1])return()=>t[1];const i=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=Pl(t,s,r),c=a.length,u=d=>{if(i&&d<e[0])return t[0];let h=0;if(c>1)for(;h<e.length-2&&!(d<e[h+1]);h++);const m=Vn(e[h],e[h+1],d);return a[h](m)};return n?d=>u(rt(e[0],e[o-1],d)):u}function kl(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=Vn(0,t,s);e.push(me(n,1,r))}}function Ml(e){const t=[0];return kl(t,e.length-1),t}function El(e,t){return e.map(n=>n*t)}function Nl(e,t){return e.map(()=>t||Vo).splice(0,e.length-1)}function Ht({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=_c(s)?s.map(ti):ti(s),o={done:!1,value:t[0]},i=El(n&&n.length===t.length?n:Ml(t),e),a=Al(i,t,{ease:Array.isArray(r)?r:Nl(t,r)});return{calculatedDuration:e,next:c=>(o.value=a(c),o.done=c>=e,o)}}const Dl=e=>e!==null;function Cr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(Dl),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const Rl={decay:_s,inertia:_s,tween:Ht,keyframes:Ht,spring:hs};function Ko(e){typeof e.type=="string"&&(e.type=Rl[e.type])}class Pr{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const Vl=e=>e/100;class Ar extends Pr{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==ke.now()&&this.tick(ke.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;Ko(t);const{type:n=Ht,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const c=n||Ht;process.env.NODE_ENV!=="production"&&c!==Ht&&it(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Ht&&typeof a[0]!="number"&&(this.mixKeyframes=Bn(Vl,Xo(a[0],a[1])),a=[0,100]);const u=c({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...t,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=jr(u));const{calculatedDuration:d}=u;this.calculatedDuration=d,this.resolvedDuration=d+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=u}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:s,totalDuration:r,mixKeyframes:o,mirroredGenerator:i,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:d,repeat:h,repeatType:m,repeatDelay:p,type:w,onUpdate:x,finalKeyframe:b}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-r/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const y=this.currentTime-u*(this.playbackSpeed>=0?1:-1),j=this.playbackSpeed>=0?y<0:y>r;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let M=this.currentTime,N=s;if(h){const P=Math.min(this.currentTime,r)/a;let z=Math.floor(P),T=P%1;!T&&P>=1&&(T=1),T===1&&z--,z=Math.min(z,h+1),!!(z%2)&&(m==="reverse"?(T=1-T,p&&(T-=p/a)):m==="mirror"&&(N=i)),M=rt(0,1,T)*a}const D=j?{done:!1,value:d[0]}:N.next(M);o&&(D.value=o(D.value));let{done:F}=D;!j&&c!==null&&(F=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const B=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&F);return B&&w!==_s&&(D.value=Cr(d,this.options,b,this.speed)),x&&x(D.value),B&&this.finish(),D}then(t,n){return this.finished.then(t,n)}get duration(){return Fe(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Fe(t)}get time(){return Fe(this.currentTime)}set time(t){t=Ye(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(ke.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=Fe(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=yl,startTime:n}=this.options;this.driver||(this.driver=t(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(ke.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function Il(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Vt=e=>e*180/Math.PI,Xs=e=>{const t=Vt(Math.atan2(e[1],e[0]));return Ws(t)},Ol={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Xs,rotateZ:Xs,skewX:e=>Vt(Math.atan(e[1])),skewY:e=>Vt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ws=e=>(e=e%360,e<0&&(e+=360),e),ai=Xs,ci=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),li=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),$l={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ci,scaleY:li,scale:e=>(ci(e)+li(e))/2,rotateX:e=>Ws(Vt(Math.atan2(e[6],e[5]))),rotateY:e=>Ws(Vt(Math.atan2(-e[2],e[0]))),rotateZ:ai,rotate:ai,skewX:e=>Vt(Math.atan(e[4])),skewY:e=>Vt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function qs(e){return e.includes("scale")?1:0}function Ks(e,t){if(!e||e==="none")return qs(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=$l,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=Ol,r=a}if(!r)return qs(t);const o=s[t],i=r[1].split(",").map(Fl);return typeof o=="function"?o(i):i[o]}const Ll=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Ks(n,t)};function Fl(e){return parseFloat(e.trim())}const cn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ln=new Set(cn),ui=e=>e===an||e===q,Bl=new Set(["x","y","z"]),zl=cn.filter(e=>!Bl.has(e));function Ul(e){const t=[];return zl.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const It={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>Ks(t,"x"),y:(e,{transform:t})=>Ks(t,"y")};It.translateX=It.x;It.translateY=It.y;const Ot=new Set;let Gs=!1,Ys=!1,Hs=!1;function Go(){if(Ys){const e=Array.from(Ot).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=Ul(s);r.length&&(n.set(s,r),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),e.forEach(s=>s.measureEndState()),e.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}Ys=!1,Gs=!1,Ot.forEach(e=>e.complete(Hs)),Ot.clear()}function Yo(){Ot.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Ys=!0)})}function _l(){Hs=!0,Yo(),Go(),Hs=!1}class kr{constructor(t,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(Ot.add(this),Gs||(Gs=!0,ue.read(Yo),ue.resolveKeyframes(Go))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:r}=this;if(t[0]===null){const o=r?.get(),i=t[t.length-1];if(o!==void 0)t[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=i),r&&o===void 0&&r.set(t[0])}Il(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Ot.delete(this)}cancel(){this.state==="scheduled"&&(Ot.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Xl=e=>e.startsWith("--");function Wl(e,t,n){Xl(t)?e.style.setProperty(t,n):e.style[t]=n}const ql=mr(()=>window.ScrollTimeline!==void 0),Kl={};function Gl(e,t){const n=mr(e);return()=>Kl[t]??n()}const Ho=Gl(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Pn=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,di={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Pn([0,.65,.55,1]),circOut:Pn([.55,0,1,.45]),backIn:Pn([.31,.01,.66,-.59]),backOut:Pn([.33,1.53,.69,.99])};function Jo(e,t){if(e)return typeof e=="function"?Ho()?Wo(e,t):"ease-out":Io(e)?Pn(e):Array.isArray(e)?e.map(n=>Jo(n,t)||di.easeOut):di[e]}function Yl(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:c}={},u=void 0){const d={[t]:n};c&&(d.offset=c);const h=Jo(a,r);Array.isArray(h)&&(d.easing=h);const m={delay:s,duration:r,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return u&&(m.pseudoElement=u),e.animate(d,m)}function Zo(e){return typeof e=="function"&&"applyToOptions"in e}function Hl({type:e,...t}){return Zo(e)&&Ho()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Jl extends Pr{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:c}=t;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=t,it(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=Hl(t);this.animation=Yl(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Cr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Wl(n,s,d),this.animation.cancel()}c?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return Fe(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Fe(t)}get time(){return Fe(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=Ye(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&ql()?(this.animation.timeline=t,Be):n(this)}}const Qo={anticipate:No,backInOut:Eo,circInOut:Ro};function Zl(e){return e in Qo}function Ql(e){typeof e.ease=="string"&&Zl(e.ease)&&(e.ease=Qo[e.ease])}const hi=10;class eu extends Jl{constructor(t){Ql(t),Ko(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new Ar({...i,autoplay:!1}),c=Ye(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-hi).value,a.sample(c).value,hi),a.stop()}}const fi=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(vt.test(e)||e==="0")&&!e.startsWith("url("));function tu(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function nu(e,t,n,s){const r=e[0];if(r===null)return!1;if(t==="display"||t==="visibility")return!0;const o=e[e.length-1],i=fi(r,t),a=fi(o,t);return on(i===a,`You are trying to animate ${t} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:tu(e)||(n==="spring"||Zo(n))&&s}function Js(e){e.duration=0,e.type="keyframes"}const su=new Set(["opacity","clipPath","filter","transform"]),ru=mr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function iu(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:u}=t.owner.getProps();return ru()&&n&&su.has(n)&&(n!=="transform"||!u)&&!c&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const ou=40;class au extends Pr{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:c,motionValue:u,element:d,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=ke.now();const m={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:c,motionValue:u,element:d,...h},p=d?.KeyframeResolver||kr;this.keyframeResolver=new p(a,(w,x,b)=>this.onKeyframesResolved(w,x,m,!b),c,u,d),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:c,isHandoff:u,onUpdate:d}=s;this.resolvedAt=ke.now(),nu(t,o,i,a)||((ot.instantAnimations||!c)&&d?.(Cr(t,s,n)),t[0]=t[t.length-1],Js(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>ou?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!u&&iu(m)?new eu({...m,element:m.motionValue.owner.current}):new Ar(m);p.finished.then(()=>this.notifyFinished()).catch(Be),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),_l()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const cu=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function lu(e){const t=cu.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const uu=4;function ea(e,t,n=1){it(n<=uu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=lu(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return To(i)?parseFloat(i):i}return vr(r)?ea(r,t,n+1):r}function Mr(e,t){return e?.[t]??e?.default??e}const ta=new Set(["width","height","top","left","right","bottom",...cn]),du={test:e=>e==="auto",parse:e=>e},na=e=>t=>t.test(e),sa=[an,q,et,xt,tl,el,du],mi=e=>sa.find(na(e));function hu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||jo(e):!0}const fu=new Set(["brightness","contrast","saturate","opacity"]);function mu(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(wr)||[];if(!s)return e;const r=n.replace(s,"");let o=fu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const pu=/\b([a-z-]*)\(.*?\)/gu,Zs={...vt,getAnimatableNone:e=>{const t=e.match(pu);return t?t.map(mu).join(" "):e}},pi={...an,transform:Math.round},gu={rotate:xt,rotateX:xt,rotateY:xt,rotateZ:xt,scale:es,scaleX:es,scaleY:es,scaleZ:es,skew:xt,skewX:xt,skewY:xt,distance:q,translateX:q,translateY:q,translateZ:q,x:q,y:q,z:q,perspective:q,transformPerspective:q,opacity:In,originX:ni,originY:ni,originZ:q},Er={borderWidth:q,borderTopWidth:q,borderRightWidth:q,borderBottomWidth:q,borderLeftWidth:q,borderRadius:q,radius:q,borderTopLeftRadius:q,borderTopRightRadius:q,borderBottomRightRadius:q,borderBottomLeftRadius:q,width:q,maxWidth:q,height:q,maxHeight:q,top:q,right:q,bottom:q,left:q,padding:q,paddingTop:q,paddingRight:q,paddingBottom:q,paddingLeft:q,margin:q,marginTop:q,marginRight:q,marginBottom:q,marginLeft:q,backgroundPositionX:q,backgroundPositionY:q,...gu,zIndex:pi,fillOpacity:In,strokeOpacity:In,numOctaves:pi},yu={...Er,color:xe,backgroundColor:xe,outlineColor:xe,fill:xe,stroke:xe,borderColor:xe,borderTopColor:xe,borderRightColor:xe,borderBottomColor:xe,borderLeftColor:xe,filter:Zs,WebkitFilter:Zs},ra=e=>yu[e];function ia(e,t){let n=ra(e);return n!==Zs&&(n=vt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const xu=new Set(["auto","none","0"]);function bu(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!xu.has(o)&&On(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=ia(n,r)}class vu extends kr{constructor(t,n,s,r,o){super(t,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<t.length;c++){let u=t[c];if(typeof u=="string"&&(u=u.trim(),vr(u))){const d=ea(u,n.current);d!==void 0&&(t[c]=d),c===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!ta.has(s)||t.length!==2)return;const[r,o]=t,i=mi(r),a=mi(o);if(i!==a)if(ui(i)&&ui(a))for(let c=0;c<t.length;c++){const u=t[c];typeof u=="string"&&(t[c]=parseFloat(u))}else It[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||hu(t[r]))&&s.push(r);s.length&&bu(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=It[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(s,r).jump(r,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=It[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,c])=>{t.getValue(a).set(c)}),this.resolveNoneKeyframes()}}function wu(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const r=n?.[e]??s.querySelectorAll(e);return r?Array.from(r):[]}return Array.from(e)}const oa=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function aa(e){return So(e)&&"offsetHeight"in e}const gi=30,Tu=e=>!isNaN(parseFloat(e));class Su{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=ke.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=ke.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Tu(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&gr(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new pr);const s=this.events[t].add(n);return t==="change"?()=>{s(),ue.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-s}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=ke.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>gi)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,gi);return Co(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function sn(e,t){return new Su(e,t)}const{schedule:Nr}=Oo(queueMicrotask,!1),Ke={x:!1,y:!1};function ca(){return Ke.x||Ke.y}function ju(e){return e==="x"||e==="y"?Ke[e]?null:(Ke[e]=!0,()=>{Ke[e]=!1}):Ke.x||Ke.y?null:(Ke.x=Ke.y=!0,()=>{Ke.x=Ke.y=!1})}function la(e,t){const n=wu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function yi(e){return!(e.pointerType==="touch"||ca())}function Cu(e,t,n={}){const[s,r,o]=la(e,n),i=a=>{if(!yi(a))return;const{target:c}=a,u=t(c,a);if(typeof u!="function"||!c)return;const d=h=>{yi(h)&&(u(h),c.removeEventListener("pointerleave",d))};c.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ua=(e,t)=>t?e===t?!0:ua(e,t.parentElement):!1,Dr=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Pu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Au(e){return Pu.has(e.tagName)||e.tabIndex!==-1}const is=new WeakSet;function xi(e){return t=>{t.key==="Enter"&&e(t)}}function As(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const ku=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=xi(()=>{if(is.has(n))return;As(n,"down");const r=xi(()=>{As(n,"up")}),o=()=>As(n,"cancel");n.addEventListener("keyup",r,t),n.addEventListener("blur",o,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function bi(e){return Dr(e)&&!ca()}function Mu(e,t,n={}){const[s,r,o]=la(e,n),i=a=>{const c=a.currentTarget;if(!bi(a))return;is.add(c);const u=t(c,a),d=(p,w)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),is.has(c)&&is.delete(c),bi(p)&&typeof u=="function"&&u(p,{success:w})},h=p=>{d(p,c===window||c===document||n.useGlobalTarget||ua(c,p.target))},m=p=>{d(p,!1)};window.addEventListener("pointerup",h,r),window.addEventListener("pointercancel",m,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),aa(a)&&(a.addEventListener("focus",u=>ku(u,r)),!Au(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function da(e){return So(e)&&"ownerSVGElement"in e}function Eu(e){return da(e)&&e.tagName==="svg"}const Te=e=>!!(e&&e.getVelocity),Nu=[...sa,xe,vt],Du=e=>Nu.find(na(e)),Rr=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function vi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ru(...e){return t=>{let n=!1;const s=e.map(r=>{const o=vi(r,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<s.length;r++){const o=s[r];typeof o=="function"?o():vi(e[r],null)}}}}function Vu(...e){return Ge.useCallback(Ru(...e),e)}class Iu extends Ge.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=aa(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 Ou({children:e,isPresent:t,anchorX:n,root:s}){const r=f.useId(),o=f.useRef(null),i=f.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=f.useContext(Rr),c=Vu(o,e?.ref);return f.useInsertionEffect(()=>{const{width:u,height:d,top:h,left:m,right:p}=i.current;if(t||!o.current||!u||!d)return;const w=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const x=document.createElement("style");a&&(x.nonce=a);const b=s??document.head;return b.appendChild(x),x.sheet&&x.sheet.insertRule(`
1
+ "use strict";var vc=Object.create;var Hr=Object.defineProperty;var wc=Object.getOwnPropertyDescriptor;var Tc=Object.getOwnPropertyNames;var Sc=Object.getPrototypeOf,jc=Object.prototype.hasOwnProperty;var Cc=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Tc(t))!jc.call(e,r)&&r!==n&&Hr(e,r,{get:()=>t[r],enumerable:!(s=wc(t,r))||s.enumerable});return e};var Pc=(e,t,n)=>(n=e!=null?vc(Sc(e)):{},Cc(t||!e||!e.__esModule?Hr(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react/jsx-runtime"),f=require("react"),ie=require("lucide-react"),yo=require("@ai-sdk/react"),cs=require("ai"),xo=require("@radix-ui/react-slot"),bo=require("class-variance-authority"),Ac=require("clsx"),kc=require("tailwind-merge"),Mc=require("@radix-ui/react-tooltip"),Jr=require("@radix-ui/react-use-controllable-state"),Ec=require("@radix-ui/react-collapsible"),Nc=require("react-dom"),Dc=require("@radix-ui/react-dialog"),Rc=require("./server.cjs");function ms(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Ge=ms(f),en=ms(Mc),cr=ms(Ec),Ot=ms(Dc);function ce(...e){return kc.twMerge(Ac.clsx(e))}const Et=bo.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive active:scale-95",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),je=Ge.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?xo.Slot:"button";return l.jsx(i,{ref:o,"data-slot":"button",className:ce(Et({variant:t,size:n,className:e})),...r})});je.displayName="Button";const Vc=bo.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 ws({className:e,variant:t,asChild:n=!1,...s}){const r=n?xo.Slot:"span";return l.jsx(r,{"data-slot":"badge",className:ce(Vc({variant:t}),e),...s})}const Ic=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Ge.useState(!0);Ge.useEffect(()=>{const a=e.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const c=a.scrollHeight;c>n?a.style.height=`${n}px`:a.style.height=`${c+6}px`}},[e.current,t])},vo=Ge.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Ge.useRef(null),[c,u]=Ge.useState("");return Ic({textAreaRef:a,triggerAutoSize:c,maxHeight:e,minHeight:t}),f.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),Ge.useEffect(()=>{u(r)},[o?.defaultValue,r]),l.jsx("textarea",{...o,value:r,ref:a,className:ce("flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",n),onChange:d=>{u(d.target.value),s?.(d)}})});vo.displayName="AutosizeTextarea";function Oc({delayDuration:e=0,...t}){return l.jsx(en.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function mt({...e}){return l.jsx(Oc,{children:l.jsx(en.Root,{"data-slot":"tooltip",...e})})}function pt({...e}){return l.jsx(en.Trigger,{"data-slot":"tooltip-trigger",...e})}function gt({className:e,sideOffset:t=0,children:n,...s}){return l.jsx(en.Portal,{children:l.jsxs(en.Content,{"data-slot":"tooltip-content",sideOffset:t,className:ce("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...s,children:[n,l.jsx(en.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Zr({className:e,...t}){return l.jsx("kbd",{"data-slot":"kbd",className:ce("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}const lr=f.createContext({});function ur(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const dr=typeof window<"u",wo=dr?f.useLayoutEffect:f.useEffect,ps=f.createContext(null);function hr(e,t){e.indexOf(t)===-1&&e.push(t)}function fr(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const st=(e,t,n)=>n>t?t:n<e?e:n;function Fs(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let rn=()=>{},rt=()=>{};process.env.NODE_ENV!=="production"&&(rn=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(Fs(t,n))},rt=(e,t,n)=>{if(!e)throw new Error(Fs(t,n))});const it={},To=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function So(e){return typeof e=="object"&&e!==null}const jo=e=>/^0[^.\s]+$/u.test(e);function mr(e){let t;return()=>(t===void 0&&(t=e()),t)}const Ue=e=>e,$c=(e,t)=>n=>t(e(n)),Bn=(...e)=>e.reduce($c),Vn=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class pr{constructor(){this.subscriptions=[]}add(t){return hr(this.subscriptions,t),()=>fr(this.subscriptions,t)}notify(t,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](t,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const Ye=e=>e*1e3,ze=e=>e/1e3;function Co(e,t){return t?e*(1e3/t):0}const Qr=new Set;function gr(e,t,n){e||Qr.has(t)||(console.warn(Fs(t,n)),Qr.add(t))}const Po=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Lc=1e-7,Fc=12;function Bc(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=Po(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>Lc&&++a<Fc);return i}function zn(e,t,n,s){if(e===t&&n===s)return Ue;const r=o=>Bc(o,0,1,e,n);return o=>o===0||o===1?o:Po(r(o),t,s)}const Ao=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,ko=e=>t=>1-e(1-t),Mo=zn(.33,1.53,.69,.99),yr=ko(Mo),Eo=Ao(yr),No=e=>(e*=2)<1?.5*yr(e):.5*(2-Math.pow(2,-10*(e-1))),xr=e=>1-Math.sin(Math.acos(e)),Do=ko(xr),Ro=Ao(xr),zc=zn(.42,0,1,1),Uc=zn(0,0,.58,1),Vo=zn(.42,0,.58,1),_c=e=>Array.isArray(e)&&typeof e[0]!="number",Io=e=>Array.isArray(e)&&typeof e[0]=="number",ei={linear:Ue,easeIn:zc,easeInOut:Vo,easeOut:Uc,circIn:xr,circInOut:Ro,circOut:Do,backIn:yr,backInOut:Eo,backOut:Mo,anticipate:No},Xc=e=>typeof e=="string",ti=e=>{if(Io(e)){rt(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return zn(t,n,s,r)}else if(Xc(e))return rt(ei[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),ei[e];return e},Zn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Wc(e,t){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(d){i.has(d)&&(u.schedule(d),e()),d(a)}const u={schedule:(d,h=!1,m=!1)=>{const w=m&&r?n:s;return h&&i.add(d),w.has(d)||w.add(d),d},cancel:d=>{s.delete(d),i.delete(d)},process:d=>{if(a=d,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(c),n.clear(),r=!1,o&&(o=!1,u.process(d))}};return u}const qc=40;function Oo(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Zn.reduce((M,E)=>(M[E]=Wc(o),M),{}),{setup:a,read:c,resolveKeyframes:u,preUpdate:d,update:h,preRender:m,render:p,postRender:w}=i,x=()=>{const M=it.useManualTiming?r.timestamp:performance.now();n=!1,it.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(M-r.timestamp,qc),1)),r.timestamp=M,r.isProcessing=!0,a.process(r),c.process(r),u.process(r),d.process(r),h.process(r),m.process(r),p.process(r),w.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(x))},b=()=>{n=!0,s=!0,r.isProcessing||e(x)};return{schedule:Zn.reduce((M,E)=>{const D=i[E];return M[E]=(F,B=!1,P=!1)=>(n||b(),D.schedule(F,B,P)),M},{}),cancel:M=>{for(let E=0;E<Zn.length;E++)i[Zn[E]].cancel(M)},state:r,steps:i}}const{schedule:ue,cancel:xt,state:we,steps:Ts}=Oo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ue,!0);let ss;function Kc(){ss=void 0}const Ee={now:()=>(ss===void 0&&Ee.set(we.isProcessing||it.useManualTiming?we.timestamp:performance.now()),ss),set:e=>{ss=e,queueMicrotask(Kc)}},$o=e=>t=>typeof t=="string"&&t.startsWith(e),br=$o("--"),Gc=$o("var(--"),vr=e=>Gc(e)?Yc.test(e.split("/*")[0].trim()):!1,Yc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,on={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},In={...on,transform:e=>st(0,1,e)},Qn={...on,default:1},kn=e=>Math.round(e*1e5)/1e5,wr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Hc(e){return e==null}const Jc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Tr=(e,t)=>n=>!!(typeof n=="string"&&Jc.test(n)&&n.startsWith(e)||t&&!Hc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Lo=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(wr);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},Zc=e=>st(0,255,e),Ss={...on,transform:e=>Math.round(Zc(e))},Dt={test:Tr("rgb","red"),parse:Lo("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+Ss.transform(e)+", "+Ss.transform(t)+", "+Ss.transform(n)+", "+kn(In.transform(s))+")"};function Qc(e){let t="",n="",s="",r="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),r=e.substring(4,5),t+=t,n+=n,s+=s,r+=r),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const Bs={test:Tr("#"),parse:Qc,transform:Dt.transform},Un=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),yt=Un("deg"),Qe=Un("%"),q=Un("px"),el=Un("vh"),tl=Un("vw"),ni={...Qe,parse:e=>Qe.parse(e)/100,transform:e=>Qe.transform(e*100)},Gt={test:Tr("hsl","hue"),parse:Lo("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Qe.transform(kn(t))+", "+Qe.transform(kn(n))+", "+kn(In.transform(s))+")"},xe={test:e=>Dt.test(e)||Bs.test(e)||Gt.test(e),parse:e=>Dt.test(e)?Dt.parse(e):Gt.test(e)?Gt.parse(e):Bs.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Dt.transform(e):Gt.transform(e),getAnimatableNone:e=>{const t=xe.parse(e);return t.alpha=0,xe.transform(t)}},nl=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function sl(e){return isNaN(e)&&typeof e=="string"&&(e.match(wr)?.length||0)+(e.match(nl)?.length||0)>0}const Fo="number",Bo="color",rl="var",il="var(",si="${}",ol=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function On(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(ol,c=>(xe.test(c)?(s.color.push(o),r.push(Bo),n.push(xe.parse(c))):c.startsWith(il)?(s.var.push(o),r.push(rl),n.push(c)):(s.number.push(o),r.push(Fo),n.push(parseFloat(c))),++o,si)).split(si);return{values:n,split:a,indexes:s,types:r}}function zo(e){return On(e).values}function Uo(e){const{split:t,types:n}=On(e),s=t.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=t[i],r[i]!==void 0){const a=n[i];a===Fo?o+=kn(r[i]):a===Bo?o+=xe.transform(r[i]):o+=r[i]}return o}}const al=e=>typeof e=="number"?0:xe.test(e)?xe.getAnimatableNone(e):e;function cl(e){const t=zo(e);return Uo(e)(t.map(al))}const bt={test:sl,parse:zo,createTransformer:Uo,getAnimatableNone:cl};function js(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function ll({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let r=0,o=0,i=0;if(!t)r=o=i=n;else{const a=n<.5?n*(1+t):n+t-n*t,c=2*n-a;r=js(c,a,e+1/3),o=js(c,a,e),i=js(c,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function ls(e,t){return n=>n>0?t:e}const fe=(e,t,n)=>e+(t-e)*n,Cs=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},ul=[Bs,Dt,Gt],dl=e=>ul.find(t=>t.test(e));function ri(e){const t=dl(e);if(rn(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(e);return t===Gt&&(n=ll(n)),n}const ii=(e,t)=>{const n=ri(e),s=ri(t);if(!n||!s)return ls(e,t);const r={...n};return o=>(r.red=Cs(n.red,s.red,o),r.green=Cs(n.green,s.green,o),r.blue=Cs(n.blue,s.blue,o),r.alpha=fe(n.alpha,s.alpha,o),Dt.transform(r))},zs=new Set(["none","hidden"]);function hl(e,t){return zs.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function fl(e,t){return n=>fe(e,t,n)}function Sr(e){return typeof e=="number"?fl:typeof e=="string"?vr(e)?ls:xe.test(e)?ii:gl:Array.isArray(e)?_o:typeof e=="object"?xe.test(e)?ii:ml:ls}function _o(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>Sr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function ml(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=Sr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function pl(e,t){const n=[],s={color:0,var:0,number:0};for(let r=0;r<t.values.length;r++){const o=t.types[r],i=e.indexes[o][s[o]],a=e.values[i]??0;n[r]=a,s[o]++}return n}const gl=(e,t)=>{const n=bt.createTransformer(t),s=On(e),r=On(t);return s.indexes.var.length===r.indexes.var.length&&s.indexes.color.length===r.indexes.color.length&&s.indexes.number.length>=r.indexes.number.length?zs.has(e)&&!r.values.length||zs.has(t)&&!s.values.length?hl(e,t):Bn(_o(pl(s,r),r.values),n):(rn(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),ls(e,t))};function Xo(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?fe(e,t,n):Sr(e)(e,t)}const yl=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>ue.update(t,n),stop:()=>xt(t),now:()=>we.isProcessing?we.timestamp:Ee.now()}},Wo=(e,t,n=10)=>{let s="";const r=Math.max(Math.round(t/n),2);for(let o=0;o<r;o++)s+=Math.round(e(o/(r-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},us=2e4;function jr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<us;)t+=n,s=e.next(t);return t>=us?1/0:t}function xl(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(jr(s),us);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:ze(r)}}const bl=5;function qo(e,t,n){const s=Math.max(t-bl,0);return Co(n-e(s),t-s)}const he={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Ps=.001;function vl({duration:e=he.duration,bounce:t=he.bounce,velocity:n=he.velocity,mass:s=he.mass}){let r,o;rn(e<=Ye(he.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=st(he.minDamping,he.maxDamping,i),e=st(he.minDuration,he.maxDuration,ze(e)),i<1?(r=u=>{const d=u*i,h=d*e,m=d-n,p=Us(u,i),w=Math.exp(-h);return Ps-m/p*w},o=u=>{const h=u*i*e,m=h*n+n,p=Math.pow(i,2)*Math.pow(u,2)*e,w=Math.exp(-h),x=Us(Math.pow(u,2),i);return(-r(u)+Ps>0?-1:1)*((m-p)*w)/x}):(r=u=>{const d=Math.exp(-u*e),h=(u-n)*e+1;return-Ps+d*h},o=u=>{const d=Math.exp(-u*e),h=(n-u)*(e*e);return d*h});const a=5/e,c=Tl(r,o,a);if(e=Ye(e),isNaN(c))return{stiffness:he.stiffness,damping:he.damping,duration:e};{const u=Math.pow(c,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:e}}}const wl=12;function Tl(e,t,n){let s=n;for(let r=1;r<wl;r++)s=s-e(s)/t(s);return s}function Us(e,t){return e*Math.sqrt(1-t*t)}const Sl=["duration","bounce"],jl=["stiffness","damping","mass"];function oi(e,t){return t.some(n=>e[n]!==void 0)}function Cl(e){let t={velocity:he.velocity,stiffness:he.stiffness,damping:he.damping,mass:he.mass,isResolvedFromDuration:!1,...e};if(!oi(e,jl)&&oi(e,Sl))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*st(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:he.mass,stiffness:r,damping:o}}else{const n=vl(e);t={...t,...n,mass:he.mass},t.isResolvedFromDuration=!0}return t}function ds(e=he.visualDuration,t=he.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:s,restDelta:r}=n;const o=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:c,damping:u,mass:d,duration:h,velocity:m,isResolvedFromDuration:p}=Cl({...n,velocity:-ze(n.velocity||0)}),w=m||0,x=u/(2*Math.sqrt(c*d)),b=i-o,y=ze(Math.sqrt(c/d)),j=Math.abs(b)<5;s||(s=j?he.restSpeed.granular:he.restSpeed.default),r||(r=j?he.restDelta.granular:he.restDelta.default);let M;if(x<1){const D=Us(y,x);M=F=>{const B=Math.exp(-x*y*F);return i-B*((w+x*y*b)/D*Math.sin(D*F)+b*Math.cos(D*F))}}else if(x===1)M=D=>i-Math.exp(-y*D)*(b+(w+y*b)*D);else{const D=y*Math.sqrt(x*x-1);M=F=>{const B=Math.exp(-x*y*F),P=Math.min(D*F,300);return i-B*((w+x*y*b)*Math.sinh(P)+D*b*Math.cosh(P))/D}}const E={calculatedDuration:p&&h||null,next:D=>{const F=M(D);if(p)a.done=D>=h;else{let B=D===0?w:0;x<1&&(B=D===0?Ye(w):qo(M,D,F));const P=Math.abs(B)<=s,z=Math.abs(i-F)<=r;a.done=P&&z}return a.value=a.done?i:F,a},toString:()=>{const D=Math.min(jr(E),us),F=Wo(B=>E.next(D*B).value,D,30);return D+"ms "+F},toTransition:()=>{}};return E}ds.applyToOptions=e=>{const t=xl(e,100,ds);return e.ease=t.ease,e.duration=Ye(t.duration),e.type="keyframes",e};function _s({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:c,restDelta:u=.5,restSpeed:d}){const h=e[0],m={done:!1,value:h},p=P=>a!==void 0&&P<a||c!==void 0&&P>c,w=P=>a===void 0?c:c===void 0||Math.abs(a-P)<Math.abs(c-P)?a:c;let x=n*t;const b=h+x,y=i===void 0?b:i(b);y!==b&&(x=y-h);const j=P=>-x*Math.exp(-P/s),M=P=>y+j(P),E=P=>{const z=j(P),T=M(P);m.done=Math.abs(z)<=u,m.value=m.done?y:T};let D,F;const B=P=>{p(m.value)&&(D=P,F=ds({keyframes:[m.value,w(m.value)],velocity:qo(M,P,m.value),damping:r,stiffness:o,restDelta:u,restSpeed:d}))};return B(0),{calculatedDuration:null,next:P=>{let z=!1;return!F&&D===void 0&&(z=!0,E(P),B(P)),D!==void 0&&P>=D?F.next(P-D):(!z&&E(P),m)}}}function Pl(e,t,n){const s=[],r=n||it.mix||Xo,o=e.length-1;for(let i=0;i<o;i++){let a=r(e[i],e[i+1]);if(t){const c=Array.isArray(t)?t[i]||Ue:t;a=Bn(c,a)}s.push(a)}return s}function Al(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(rt(o===t.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>t[0];if(o===2&&t[0]===t[1])return()=>t[1];const i=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=Pl(t,s,r),c=a.length,u=d=>{if(i&&d<e[0])return t[0];let h=0;if(c>1)for(;h<e.length-2&&!(d<e[h+1]);h++);const m=Vn(e[h],e[h+1],d);return a[h](m)};return n?d=>u(st(e[0],e[o-1],d)):u}function kl(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=Vn(0,t,s);e.push(fe(n,1,r))}}function Ml(e){const t=[0];return kl(t,e.length-1),t}function El(e,t){return e.map(n=>n*t)}function Nl(e,t){return e.map(()=>t||Vo).splice(0,e.length-1)}function Yt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=_c(s)?s.map(ti):ti(s),o={done:!1,value:t[0]},i=El(n&&n.length===t.length?n:Ml(t),e),a=Al(i,t,{ease:Array.isArray(r)?r:Nl(t,r)});return{calculatedDuration:e,next:c=>(o.value=a(c),o.done=c>=e,o)}}const Dl=e=>e!==null;function Cr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(Dl),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const Rl={decay:_s,inertia:_s,tween:Yt,keyframes:Yt,spring:ds};function Ko(e){typeof e.type=="string"&&(e.type=Rl[e.type])}class Pr{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const Vl=e=>e/100;class Ar extends Pr{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==Ee.now()&&this.tick(Ee.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;Ko(t);const{type:n=Yt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const c=n||Yt;process.env.NODE_ENV!=="production"&&c!==Yt&&rt(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Yt&&typeof a[0]!="number"&&(this.mixKeyframes=Bn(Vl,Xo(a[0],a[1])),a=[0,100]);const u=c({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...t,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=jr(u));const{calculatedDuration:d}=u;this.calculatedDuration=d,this.resolvedDuration=d+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=u}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:s,totalDuration:r,mixKeyframes:o,mirroredGenerator:i,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:d,repeat:h,repeatType:m,repeatDelay:p,type:w,onUpdate:x,finalKeyframe:b}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-r/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const y=this.currentTime-u*(this.playbackSpeed>=0?1:-1),j=this.playbackSpeed>=0?y<0:y>r;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let M=this.currentTime,E=s;if(h){const P=Math.min(this.currentTime,r)/a;let z=Math.floor(P),T=P%1;!T&&P>=1&&(T=1),T===1&&z--,z=Math.min(z,h+1),!!(z%2)&&(m==="reverse"?(T=1-T,p&&(T-=p/a)):m==="mirror"&&(E=i)),M=st(0,1,T)*a}const D=j?{done:!1,value:d[0]}:E.next(M);o&&(D.value=o(D.value));let{done:F}=D;!j&&c!==null&&(F=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const B=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&F);return B&&w!==_s&&(D.value=Cr(d,this.options,b,this.speed)),x&&x(D.value),B&&this.finish(),D}then(t,n){return this.finished.then(t,n)}get duration(){return ze(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+ze(t)}get time(){return ze(this.currentTime)}set time(t){t=Ye(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(Ee.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=ze(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=yl,startTime:n}=this.options;this.driver||(this.driver=t(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Ee.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function Il(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Rt=e=>e*180/Math.PI,Xs=e=>{const t=Rt(Math.atan2(e[1],e[0]));return Ws(t)},Ol={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Xs,rotateZ:Xs,skewX:e=>Rt(Math.atan(e[1])),skewY:e=>Rt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ws=e=>(e=e%360,e<0&&(e+=360),e),ai=Xs,ci=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),li=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),$l={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ci,scaleY:li,scale:e=>(ci(e)+li(e))/2,rotateX:e=>Ws(Rt(Math.atan2(e[6],e[5]))),rotateY:e=>Ws(Rt(Math.atan2(-e[2],e[0]))),rotateZ:ai,rotate:ai,skewX:e=>Rt(Math.atan(e[4])),skewY:e=>Rt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function qs(e){return e.includes("scale")?1:0}function Ks(e,t){if(!e||e==="none")return qs(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=$l,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=Ol,r=a}if(!r)return qs(t);const o=s[t],i=r[1].split(",").map(Fl);return typeof o=="function"?o(i):i[o]}const Ll=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Ks(n,t)};function Fl(e){return parseFloat(e.trim())}const an=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],cn=new Set(an),ui=e=>e===on||e===q,Bl=new Set(["x","y","z"]),zl=an.filter(e=>!Bl.has(e));function Ul(e){const t=[];return zl.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const Vt={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>Ks(t,"x"),y:(e,{transform:t})=>Ks(t,"y")};Vt.translateX=Vt.x;Vt.translateY=Vt.y;const It=new Set;let Gs=!1,Ys=!1,Hs=!1;function Go(){if(Ys){const e=Array.from(It).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=Ul(s);r.length&&(n.set(s,r),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),e.forEach(s=>s.measureEndState()),e.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}Ys=!1,Gs=!1,It.forEach(e=>e.complete(Hs)),It.clear()}function Yo(){It.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Ys=!0)})}function _l(){Hs=!0,Yo(),Go(),Hs=!1}class kr{constructor(t,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(It.add(this),Gs||(Gs=!0,ue.read(Yo),ue.resolveKeyframes(Go))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:r}=this;if(t[0]===null){const o=r?.get(),i=t[t.length-1];if(o!==void 0)t[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=i),r&&o===void 0&&r.set(t[0])}Il(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),It.delete(this)}cancel(){this.state==="scheduled"&&(It.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Xl=e=>e.startsWith("--");function Wl(e,t,n){Xl(t)?e.style.setProperty(t,n):e.style[t]=n}const ql=mr(()=>window.ScrollTimeline!==void 0),Kl={};function Gl(e,t){const n=mr(e);return()=>Kl[t]??n()}const Ho=Gl(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Pn=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,di={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Pn([0,.65,.55,1]),circOut:Pn([.55,0,1,.45]),backIn:Pn([.31,.01,.66,-.59]),backOut:Pn([.33,1.53,.69,.99])};function Jo(e,t){if(e)return typeof e=="function"?Ho()?Wo(e,t):"ease-out":Io(e)?Pn(e):Array.isArray(e)?e.map(n=>Jo(n,t)||di.easeOut):di[e]}function Yl(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:c}={},u=void 0){const d={[t]:n};c&&(d.offset=c);const h=Jo(a,r);Array.isArray(h)&&(d.easing=h);const m={delay:s,duration:r,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return u&&(m.pseudoElement=u),e.animate(d,m)}function Zo(e){return typeof e=="function"&&"applyToOptions"in e}function Hl({type:e,...t}){return Zo(e)&&Ho()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Jl extends Pr{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:c}=t;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=t,rt(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=Hl(t);this.animation=Yl(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Cr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Wl(n,s,d),this.animation.cancel()}c?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return ze(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+ze(t)}get time(){return ze(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=Ye(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&ql()?(this.animation.timeline=t,Ue):n(this)}}const Qo={anticipate:No,backInOut:Eo,circInOut:Ro};function Zl(e){return e in Qo}function Ql(e){typeof e.ease=="string"&&Zl(e.ease)&&(e.ease=Qo[e.ease])}const hi=10;class eu extends Jl{constructor(t){Ql(t),Ko(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new Ar({...i,autoplay:!1}),c=Ye(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-hi).value,a.sample(c).value,hi),a.stop()}}const fi=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(bt.test(e)||e==="0")&&!e.startsWith("url("));function tu(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function nu(e,t,n,s){const r=e[0];if(r===null)return!1;if(t==="display"||t==="visibility")return!0;const o=e[e.length-1],i=fi(r,t),a=fi(o,t);return rn(i===a,`You are trying to animate ${t} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:tu(e)||(n==="spring"||Zo(n))&&s}function Js(e){e.duration=0,e.type="keyframes"}const su=new Set(["opacity","clipPath","filter","transform"]),ru=mr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function iu(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:u}=t.owner.getProps();return ru()&&n&&su.has(n)&&(n!=="transform"||!u)&&!c&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const ou=40;class au extends Pr{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:c,motionValue:u,element:d,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Ee.now();const m={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:c,motionValue:u,element:d,...h},p=d?.KeyframeResolver||kr;this.keyframeResolver=new p(a,(w,x,b)=>this.onKeyframesResolved(w,x,m,!b),c,u,d),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:c,isHandoff:u,onUpdate:d}=s;this.resolvedAt=Ee.now(),nu(t,o,i,a)||((it.instantAnimations||!c)&&d?.(Cr(t,s,n)),t[0]=t[t.length-1],Js(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>ou?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!u&&iu(m)?new eu({...m,element:m.motionValue.owner.current}):new Ar(m);p.finished.then(()=>this.notifyFinished()).catch(Ue),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),_l()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const cu=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function lu(e){const t=cu.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const uu=4;function ea(e,t,n=1){rt(n<=uu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=lu(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return To(i)?parseFloat(i):i}return vr(r)?ea(r,t,n+1):r}function Mr(e,t){return e?.[t]??e?.default??e}const ta=new Set(["width","height","top","left","right","bottom",...an]),du={test:e=>e==="auto",parse:e=>e},na=e=>t=>t.test(e),sa=[on,q,Qe,yt,tl,el,du],mi=e=>sa.find(na(e));function hu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||jo(e):!0}const fu=new Set(["brightness","contrast","saturate","opacity"]);function mu(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(wr)||[];if(!s)return e;const r=n.replace(s,"");let o=fu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const pu=/\b([a-z-]*)\(.*?\)/gu,Zs={...bt,getAnimatableNone:e=>{const t=e.match(pu);return t?t.map(mu).join(" "):e}},pi={...on,transform:Math.round},gu={rotate:yt,rotateX:yt,rotateY:yt,rotateZ:yt,scale:Qn,scaleX:Qn,scaleY:Qn,scaleZ:Qn,skew:yt,skewX:yt,skewY:yt,distance:q,translateX:q,translateY:q,translateZ:q,x:q,y:q,z:q,perspective:q,transformPerspective:q,opacity:In,originX:ni,originY:ni,originZ:q},Er={borderWidth:q,borderTopWidth:q,borderRightWidth:q,borderBottomWidth:q,borderLeftWidth:q,borderRadius:q,radius:q,borderTopLeftRadius:q,borderTopRightRadius:q,borderBottomRightRadius:q,borderBottomLeftRadius:q,width:q,maxWidth:q,height:q,maxHeight:q,top:q,right:q,bottom:q,left:q,padding:q,paddingTop:q,paddingRight:q,paddingBottom:q,paddingLeft:q,margin:q,marginTop:q,marginRight:q,marginBottom:q,marginLeft:q,backgroundPositionX:q,backgroundPositionY:q,...gu,zIndex:pi,fillOpacity:In,strokeOpacity:In,numOctaves:pi},yu={...Er,color:xe,backgroundColor:xe,outlineColor:xe,fill:xe,stroke:xe,borderColor:xe,borderTopColor:xe,borderRightColor:xe,borderBottomColor:xe,borderLeftColor:xe,filter:Zs,WebkitFilter:Zs},ra=e=>yu[e];function ia(e,t){let n=ra(e);return n!==Zs&&(n=bt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const xu=new Set(["auto","none","0"]);function bu(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!xu.has(o)&&On(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=ia(n,r)}class vu extends kr{constructor(t,n,s,r,o){super(t,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<t.length;c++){let u=t[c];if(typeof u=="string"&&(u=u.trim(),vr(u))){const d=ea(u,n.current);d!==void 0&&(t[c]=d),c===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!ta.has(s)||t.length!==2)return;const[r,o]=t,i=mi(r),a=mi(o);if(i!==a)if(ui(i)&&ui(a))for(let c=0;c<t.length;c++){const u=t[c];typeof u=="string"&&(t[c]=parseFloat(u))}else Vt[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||hu(t[r]))&&s.push(r);s.length&&bu(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Vt[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(s,r).jump(r,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=Vt[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,c])=>{t.getValue(a).set(c)}),this.resolveNoneKeyframes()}}function wu(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const r=n?.[e]??s.querySelectorAll(e);return r?Array.from(r):[]}return Array.from(e)}const oa=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function aa(e){return So(e)&&"offsetHeight"in e}const gi=30,Tu=e=>!isNaN(parseFloat(e));class Su{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=Ee.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=Ee.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Tu(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&gr(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new pr);const s=this.events[t].add(n);return t==="change"?()=>{s(),ue.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-s}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=Ee.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>gi)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,gi);return Co(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function nn(e,t){return new Su(e,t)}const{schedule:Nr}=Oo(queueMicrotask,!1),Ke={x:!1,y:!1};function ca(){return Ke.x||Ke.y}function ju(e){return e==="x"||e==="y"?Ke[e]?null:(Ke[e]=!0,()=>{Ke[e]=!1}):Ke.x||Ke.y?null:(Ke.x=Ke.y=!0,()=>{Ke.x=Ke.y=!1})}function la(e,t){const n=wu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function yi(e){return!(e.pointerType==="touch"||ca())}function Cu(e,t,n={}){const[s,r,o]=la(e,n),i=a=>{if(!yi(a))return;const{target:c}=a,u=t(c,a);if(typeof u!="function"||!c)return;const d=h=>{yi(h)&&(u(h),c.removeEventListener("pointerleave",d))};c.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ua=(e,t)=>t?e===t?!0:ua(e,t.parentElement):!1,Dr=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Pu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Au(e){return Pu.has(e.tagName)||e.tabIndex!==-1}const rs=new WeakSet;function xi(e){return t=>{t.key==="Enter"&&e(t)}}function As(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const ku=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=xi(()=>{if(rs.has(n))return;As(n,"down");const r=xi(()=>{As(n,"up")}),o=()=>As(n,"cancel");n.addEventListener("keyup",r,t),n.addEventListener("blur",o,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function bi(e){return Dr(e)&&!ca()}function Mu(e,t,n={}){const[s,r,o]=la(e,n),i=a=>{const c=a.currentTarget;if(!bi(a))return;rs.add(c);const u=t(c,a),d=(p,w)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),rs.has(c)&&rs.delete(c),bi(p)&&typeof u=="function"&&u(p,{success:w})},h=p=>{d(p,c===window||c===document||n.useGlobalTarget||ua(c,p.target))},m=p=>{d(p,!1)};window.addEventListener("pointerup",h,r),window.addEventListener("pointercancel",m,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),aa(a)&&(a.addEventListener("focus",u=>ku(u,r)),!Au(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function da(e){return So(e)&&"ownerSVGElement"in e}function Eu(e){return da(e)&&e.tagName==="svg"}const Se=e=>!!(e&&e.getVelocity),Nu=[...sa,xe,bt],Du=e=>Nu.find(na(e)),Rr=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function vi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ru(...e){return t=>{let n=!1;const s=e.map(r=>{const o=vi(r,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<s.length;r++){const o=s[r];typeof o=="function"?o():vi(e[r],null)}}}}function Vu(...e){return Ge.useCallback(Ru(...e),e)}class Iu extends Ge.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=aa(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 Ou({children:e,isPresent:t,anchorX:n,root:s}){const r=f.useId(),o=f.useRef(null),i=f.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=f.useContext(Rr),c=Vu(o,e?.ref);return f.useInsertionEffect(()=>{const{width:u,height:d,top:h,left:m,right:p}=i.current;if(t||!o.current||!u||!d)return;const w=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const x=document.createElement("style");a&&(x.nonce=a);const b=s??document.head;return b.appendChild(x),x.sheet&&x.sheet.insertRule(`
2
2
  [data-motion-pop-id="${r}"] {
3
3
  position: absolute !important;
4
4
  width: ${u}px !important;
@@ -6,7 +6,7 @@
6
6
  ${w}px !important;
7
7
  top: ${h}px !important;
8
8
  }
9
- `),()=>{b.contains(x)&&b.removeChild(x)}},[t]),l.jsx(Iu,{isPresent:t,childRef:o,sizeRef:i,children:Ge.cloneElement(e,{ref:c})})}const $u=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:c})=>{const u=ur(Lu),d=f.useId();let h=!0,m=f.useMemo(()=>(h=!1,{id:d,initial:t,isPresent:n,custom:r,onExitComplete:p=>{u.set(p,!0);for(const w of u.values())if(!w)return;s&&s()},register:p=>(u.set(p,!1),()=>u.delete(p))}),[n,u,s]);return o&&h&&(m={...m}),f.useMemo(()=>{u.forEach((p,w)=>u.set(w,!1))},[n]),Ge.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(e=l.jsx(Ou,{isPresent:n,anchorX:a,root:c,children:e})),l.jsx(gs.Provider,{value:m,children:e})};function Lu(){return new Map}function ha(e=!0){const t=f.useContext(gs);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,o=f.useId();f.useEffect(()=>{if(e)return r(o)},[e]);const i=f.useCallback(()=>e&&s&&s(o),[o,s,e]);return!n&&s?[!1,i]:[!0]}const ts=e=>e.key||"";function wi(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const Fu=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:c})=>{const[u,d]=ha(i),h=f.useMemo(()=>wi(e),[e]),m=i&&!u?[]:h.map(ts),p=f.useRef(!0),w=f.useRef(h),x=ur(()=>new Map),[b,y]=f.useState(h),[j,M]=f.useState(h);wo(()=>{p.current=!1,w.current=h;for(let F=0;F<j.length;F++){const B=ts(j[F]);m.includes(B)?x.delete(B):x.get(B)!==!0&&x.set(B,!1)}},[j,m.length,m.join("-")]);const N=[];if(h!==b){let F=[...h];for(let B=0;B<j.length;B++){const P=j[B],z=ts(P);m.includes(z)||(F.splice(B,0,P),N.push(P))}return o==="wait"&&N.length&&(F=N),M(wi(F)),y(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&j.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:D}=f.useContext(lr);return l.jsx(l.Fragment,{children:j.map(F=>{const B=ts(F),P=i&&!u?!1:h===j||m.includes(B),z=()=>{if(x.has(B))x.set(B,!0);else return;let T=!0;x.forEach(V=>{V||(T=!1)}),T&&(D?.(),M(w.current),i&&d?.(),s&&s())};return l.jsx($u,{isPresent:P,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:P?void 0:z,anchorX:a,children:F},B)})})},Vr=f.createContext({strict:!1}),Ti={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"]},rn={};for(const e in Ti)rn[e]={isEnabled:t=>Ti[e].some(n=>!!t[n])};function Qs(e){for(const t in e)rn[t]={...rn[t],...e[t]}}function Bu({children:e,features:t,strict:n=!1}){const[,s]=f.useState(!ks(t)),r=f.useRef(void 0);if(!ks(t)){const{renderer:o,...i}=t;r.current=o,Qs(i)}return f.useEffect(()=>{ks(t)&&t().then(({renderer:o,...i})=>{Qs(i),r.current=o,s(!0)})},[]),l.jsx(Vr.Provider,{value:{renderer:r.current,strict:n},children:e})}function ks(e){return typeof e=="function"}const zu=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 fs(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||zu.has(e)}let fa=e=>!fs(e);function Uu(e){typeof e=="function"&&(fa=t=>t.startsWith("on")?!fs(t):e(t))}try{Uu(require("@emotion/is-prop-valid").default)}catch{}function _u(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(fa(r)||n===!0&&fs(r)||!t&&!fs(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const ys=f.createContext({});function xs(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function $n(e){return typeof e=="string"||Array.isArray(e)}const Ir=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Or=["initial",...Ir];function bs(e){return xs(e.animate)||Or.some(t=>$n(e[t]))}function ma(e){return!!(bs(e)||e.variants)}function Xu(e,t){if(bs(e)){const{initial:n,animate:s}=e;return{initial:n===!1||$n(n)?n:void 0,animate:$n(s)?s:void 0}}return e.inherit!==!1?t:{}}function Wu(e){const{initial:t,animate:n}=Xu(e,f.useContext(ys));return f.useMemo(()=>({initial:t,animate:n}),[Si(t),Si(n)])}function Si(e){return Array.isArray(e)?e.join(" "):e}const Ln={};function qu(e){for(const t in e)Ln[t]=e[t],br(t)&&(Ln[t].isCSSVariable=!0)}function pa(e,{layout:t,layoutId:n}){return ln.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Ln[e]||e==="opacity")}const Ku={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Gu=cn.length;function Yu(e,t,n){let s="",r=!0;for(let o=0;o<Gu;o++){const i=cn[o],a=e[i];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(i.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const u=oa(a,Er[i]);if(!c){r=!1;const d=Ku[i]||i;s+=`${d}(${u}) `}n&&(t[i]=u)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function $r(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const c in t){const u=t[c];if(ln.has(c)){i=!0;continue}else if(br(c)){r[c]=u;continue}else{const d=oa(u,Er[c]);c.startsWith("origin")?(a=!0,o[c]=d):s[c]=d}}if(t.transform||(i||n?s.transform=Yu(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:c="50%",originY:u="50%",originZ:d=0}=o;s.transformOrigin=`${c} ${u} ${d}`}}const Lr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function ga(e,t,n){for(const s in t)!Te(t[s])&&!pa(s,n)&&(e[s]=t[s])}function Hu({transformTemplate:e},t){return f.useMemo(()=>{const n=Lr();return $r(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Ju(e,t){const n=e.style||{},s={};return ga(s,n,e),Object.assign(s,Hu(e,t)),s}function Zu(e,t){const n={},s=Ju(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const Qu={offset:"stroke-dashoffset",array:"stroke-dasharray"},ed={offset:"strokeDashoffset",array:"strokeDasharray"};function td(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?Qu:ed;e[o.offset]=q.transform(-s);const i=q.transform(t),a=q.transform(n);e[o.array]=`${i} ${a}`}function ya(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},c,u,d){if($r(e,a,u),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:h,style:m}=e;h.transform&&(m.transform=h.transform,delete h.transform),(m.transform||h.transformOrigin)&&(m.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),m.transform&&(m.transformBox=d?.transformBox??"fill-box",delete h.transformBox),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),r!==void 0&&td(h,r,o,i,!1)}const xa=()=>({...Lr(),attrs:{}}),ba=e=>typeof e=="string"&&e.toLowerCase()==="svg";function nd(e,t,n,s){const r=f.useMemo(()=>{const o=xa();return ya(o,t,ba(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};ga(o,e.style,e),r.style={...o,...r.style}}return r}const sd=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Fr(e){return typeof e!="string"||e.includes("-")?!1:!!(sd.indexOf(e)>-1||/[A-Z]/u.test(e))}function rd(e,t,n,{latestValues:s},r,o=!1){const a=(Fr(e)?nd:Zu)(t,s,r,e),c=_u(t,typeof e=="string",o),u=e!==f.Fragment?{...c,...a,ref:n}:{},{children:d}=t,h=f.useMemo(()=>Te(d)?d.get():d,[d]);return f.createElement(e,{...u,children:h})}function ji(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Br(e,t,n,s){if(typeof t=="function"){const[r,o]=ji(s);t=t(n!==void 0?n:e.custom,r,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,o]=ji(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function os(e){return Te(e)?e.get():e}function id({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:od(n,s,r,e),renderState:t()}}function od(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=os(o[m]);let{initial:i,animate:a}=e;const c=bs(e),u=ma(e);t&&u&&!c&&e.inherit!==!1&&(i===void 0&&(i=t.initial),a===void 0&&(a=t.animate));let d=n?n.initial===!1:!1;d=d||i===!1;const h=d?a:i;if(h&&typeof h!="boolean"&&!xs(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p<m.length;p++){const w=Br(e,m[p]);if(w){const{transitionEnd:x,transition:b,...y}=w;for(const j in y){let M=y[j];if(Array.isArray(M)){const N=d?M.length-1:0;M=M[N]}M!==null&&(r[j]=M)}for(const j in x)r[j]=x[j]}}}return r}const va=e=>(t,n)=>{const s=f.useContext(ys),r=f.useContext(gs),o=()=>id(e,t,s,r);return n?o():ur(o)};function zr(e,t,n){const{style:s}=e,r={};for(const o in s)(Te(s[o])||t.style&&Te(t.style[o])||pa(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const ad=va({scrapeMotionValuesFromProps:zr,createRenderState:Lr});function wa(e,t,n){const s=zr(e,t,n);for(const r in e)if(Te(e[r])||Te(t[r])){const o=cn.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const cd=va({scrapeMotionValuesFromProps:wa,createRenderState:xa}),ld=Symbol.for("motionComponentSymbol");function Jt(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function ud(e,t,n){return f.useCallback(s=>{s&&e.onMount&&e.onMount(s),t&&(s?t.mount(s):t.unmount()),n&&(typeof n=="function"?n(s):Jt(n)&&(n.current=s))},[t])}const Ur=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),dd="framerAppearId",Ta="data-"+Ur(dd),Sa=f.createContext({});function hd(e,t,n,s,r){const{visualElement:o}=f.useContext(ys),i=f.useContext(Vr),a=f.useContext(gs),c=f.useContext(Rr).reducedMotion,u=f.useRef(null);s=s||i.renderer,!u.current&&s&&(u.current=s(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const d=u.current,h=f.useContext(Sa);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&fd(u.current,n,r,h);const m=f.useRef(!1);f.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[Ta],w=f.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return wo(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),w.current&&d.animationState&&d.animationState.animateChanges())}),f.useEffect(()=>{d&&(!w.current&&d.animationState&&d.animationState.animateChanges(),w.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),w.current=!1),d.enteringChildren=void 0)}),d}function fd(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:c,layoutRoot:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:ja(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Jt(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:c,layoutRoot:u})}function ja(e){if(e)return e.options.allowProjection!==!1?e.projection:ja(e.parent)}function as(e,{forwardMotionProps:t=!1}={},n,s){n&&Qs(n);const r=Fr(e)?cd:ad;function o(a,c){let u;const d={...f.useContext(Rr),...a,layoutId:md(a)},{isStatic:h}=d,m=Wu(a),p=r(a,h);if(!h&&dr){pd(d,n);const w=gd(d);u=w.MeasureLayout,m.visualElement=hd(e,p,d,s,w.ProjectionNode)}return l.jsxs(ys.Provider,{value:m,children:[u&&m.visualElement?l.jsx(u,{visualElement:m.visualElement,...d}):null,rd(e,a,ud(p,m.visualElement,c),p,h,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=f.forwardRef(o);return i[ld]=e,i}function md({layoutId:e}){const t=f.useContext(lr).id;return t&&e!==void 0?t+"-"+e:e}function pd(e,t){const n=f.useContext(Vr).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const s="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?on(!1,s,"lazy-strict-mode"):it(!1,s,"lazy-strict-mode")}}function gd(e){const{drag:t,layout:n}=rn;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function yd(e,t){if(typeof Proxy>"u")return as;const n=new Map,s=(o,i)=>as(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&gr(!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,as(i,void 0,e,t)),n.get(i))})}function Ca({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function xd({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function bd(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),s=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function Ms(e){return e===void 0||e===1}function er({scale:e,scaleX:t,scaleY:n}){return!Ms(e)||!Ms(t)||!Ms(n)}function Dt(e){return er(e)||Pa(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Pa(e){return Ci(e.x)||Ci(e.y)}function Ci(e){return e&&e!=="0%"}function ms(e,t,n){const s=e-n,r=t*s;return n+r}function Pi(e,t,n,s,r){return r!==void 0&&(e=ms(e,r,s)),ms(e,n,s)+t}function tr(e,t=0,n=1,s,r){e.min=Pi(e.min,t,n,s,r),e.max=Pi(e.max,t,n,s,r)}function Aa(e,{x:t,y:n}){tr(e.x,t.translate,t.scale,t.originPoint),tr(e.y,n.translate,n.scale,n.originPoint)}const Ai=.999999999999,ki=1.0000000000001;function vd(e,t,n,s=!1){const r=n.length;if(!r)return;t.x=t.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Qt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,Aa(e,i)),s&&Dt(o.latestValues)&&Qt(e,o.latestValues))}t.x<ki&&t.x>Ai&&(t.x=1),t.y<ki&&t.y>Ai&&(t.y=1)}function Zt(e,t){e.min=e.min+t,e.max=e.max+t}function Mi(e,t,n,s,r=.5){const o=me(e.min,e.max,r);tr(e,t,n,o,s)}function Qt(e,t){Mi(e.x,t.x,t.scaleX,t.scale,t.originX),Mi(e.y,t.y,t.scaleY,t.scale,t.originY)}function ka(e,t){return Ca(bd(e.getBoundingClientRect(),t))}function wd(e,t,n){const s=ka(e,n),{scroll:r}=t;return r&&(Zt(s.x,r.offset.x),Zt(s.y,r.offset.y)),s}const Ei=()=>({translate:0,scale:1,origin:0,originPoint:0}),en=()=>({x:Ei(),y:Ei()}),Ni=()=>({min:0,max:0}),ge=()=>({x:Ni(),y:Ni()}),nr={current:null},Ma={current:!1};function Td(){if(Ma.current=!0,!!dr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>nr.current=e.matches;e.addEventListener("change",t),t()}else nr.current=!1}const Sd=new WeakMap;function jd(e,t,n){for(const s in t){const r=t[s],o=n[s];if(Te(r))e.addValue(s,r);else if(Te(o))e.addValue(s,sn(r,{owner:e}));else if(o!==r)if(e.hasValue(s)){const i=e.getValue(s);i.liveStyle===!0?i.jump(r):i.hasAnimated||i.set(r)}else{const i=e.getStaticValue(s);e.addValue(s,sn(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Di=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Cd{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=kr,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const m=ke.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,ue.render(this.render,!1,!0))};const{latestValues:c,renderState:u}=i;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=u,this.parent=t,this.props=n,this.presenceContext=s,this.depth=t?t.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=bs(n),this.isVariantNode=ma(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:d,...h}=this.scrapeMotionValuesFromProps(n,{},this);for(const m in h){const p=h[m];c[m]!==void 0&&Te(p)&&p.set(c[m])}}mount(t){this.current=t,Sd.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),Ma.current||Td(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:nr.current,process.env.NODE_ENV!=="production"&&gr(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),bt(this.notifyUpdate),bt(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const n=this.features[t];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const s=ln.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&ue.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in rn){const n=rn[t];if(!n)continue;const{isEnabled:s,Feature:r}=n;if(!this.features[t]&&r&&s(this.props)&&(this.features[t]=new r(this)),this.features[t]){const o=this.features[t];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ge()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<Di.length;s++){const r=Di[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=t[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=jd(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const s=this.values.get(t);n!==s&&(s&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let s=this.values.get(t);return s===void 0&&n!==void 0&&(s=sn(n===null?void 0:n,{owner:this}),this.addValue(t,s)),s}readValue(t,n){let s=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return s!=null&&(typeof s=="string"&&(To(s)||jo(s))?s=parseFloat(s):!Du(s)&&vt.test(n)&&(s=ia(t,n)),this.setBaseTarget(t,Te(s)?s.get():s)),Te(s)?s.get():s}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const o=Br(this.props,n,this.presenceContext?.custom);o&&(s=o[t])}if(n&&s!==void 0)return s;const r=this.getBaseTargetFromProps(this.props,t);return r!==void 0&&!Te(r)?r:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new pr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Nr.render(this.render)}}class Ea extends Cd{constructor(){super(...arguments),this.KeyframeResolver=vu}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:s}){delete n[t],delete s[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Te(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Na(e,{style:t,vars:n},s,r){const o=e.style;let i;for(i in t)o[i]=t[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function Pd(e){return window.getComputedStyle(e)}class Ad extends Ea{constructor(){super(...arguments),this.type="html",this.renderInstance=Na}readValueFromInstance(t,n){if(ln.has(n))return this.projection?.isProjecting?qs(n):Ll(t,n);{const s=Pd(t),r=(br(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return ka(t,n)}build(t,n,s){$r(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return zr(t,n,s)}}const Da=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 kd(e,t,n,s){Na(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(Da.has(r)?r:Ur(r),t.attrs[r])}class Md extends Ea{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ge}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(ln.has(n)){const s=ra(n);return s&&s.default||0}return n=Da.has(n)?n:Ur(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return wa(t,n,s)}build(t,n,s){ya(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){kd(t,n,s,r)}mount(t){this.isSVGTag=ba(t.tagName),super.mount(t)}}const Ra=(e,t)=>Fr(e)?new Md(t):new Ad(t,{allowProjection:e!==f.Fragment});function nn(e,t,n){const s=e.getProps();return Br(s,t,n!==void 0?n:s.custom,e)}const sr=e=>Array.isArray(e);function Ed(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,sn(n))}function Nd(e){return sr(e)?e[e.length-1]||0:e}function Dd(e,t){const n=nn(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Nd(o[i]);Ed(e,i,a)}}function Rd(e){return!!(Te(e)&&e.add)}function rr(e,t){const n=e.getValue("willChange");if(Rd(n))return n.add(t);if(!n&&ot.WillChange){const s=new ot.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Va(e){return e.props[Ta]}const Vd=e=>e!==null;function Id(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Vd),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const Od={type:"spring",stiffness:500,damping:25,restSpeed:10},$d=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Ld={type:"keyframes",duration:.8},Fd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Bd=(e,{keyframes:t})=>t.length>2?Ld:ln.has(e)?e.startsWith("scale")?$d(t[1]):Od:Fd;function zd({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:c,elapsed:u,...d}){return!!Object.keys(d).length}const _r=(e,t,n,s={},r,o)=>i=>{const a=Mr(s,e)||{},c=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-Ye(c);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-u,onUpdate:m=>{t.set(m),a.onUpdate&&a.onUpdate(m)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:r};zd(a)||Object.assign(d,Bd(e,d)),d.duration&&(d.duration=Ye(d.duration)),d.repeatDelay&&(d.repeatDelay=Ye(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let h=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(Js(d),d.delay===0&&(h=!0)),(ot.instantAnimations||ot.skipAnimations)&&(h=!0,Js(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const m=Id(d.keyframes,a);if(m!==void 0){ue.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new Ar(d):new au(d)};function Ud({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function Ia(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const c=[],u=r&&e.animationState&&e.animationState.getState()[r];for(const d in a){const h=e.getValue(d,e.latestValues[d]??null),m=a[d];if(m===void 0||u&&Ud(u,d))continue;const p={delay:n,...Mr(o||{},d)},w=h.get();if(w!==void 0&&!h.isAnimating&&!Array.isArray(m)&&m===w&&!p.velocity)continue;let x=!1;if(window.MotionHandoffAnimation){const y=Va(e);if(y){const j=window.MotionHandoffAnimation(y,d,ue);j!==null&&(p.startTime=j,x=!0)}}rr(e,d),h.start(_r(d,h,m,e.shouldReduceMotion&&ta.has(d)?{type:!1}:p,e,x));const b=h.animation;b&&c.push(b)}return i&&Promise.all(c).then(()=>{ue.update(()=>{i&&Dd(e,i)})}),c}function Oa(e,t,n,s=0,r=1){const o=Array.from(e).sort((u,d)=>u.sortNodePosition(d)).indexOf(t),i=e.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function ir(e,t,n={}){const s=nn(e,t,n.type==="exit"?e.presenceContext?.custom:void 0);let{transition:r=e.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(r=n.transitionOverride);const o=s?()=>Promise.all(Ia(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=r;return _d(e,t,c,u,d,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 _d(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const c of e.variantChildren)c.notify("AnimationStart",t),a.push(ir(c,t,{...i,delay:n+(typeof s=="function"?0:s)+Oa(e.variantChildren,c,s,r,o)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(a)}function Xd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>ir(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=ir(e,t,n);else{const r=typeof t=="function"?nn(e,t,n.custom):t;s=Promise.all(Ia(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function $a(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(t[s]!==e[s])return!1;return!0}const Wd=Or.length;function La(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?La(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<Wd;n++){const s=Or[n],r=e.props[s];($n(r)||r===!1)&&(t[s]=r)}return t}const qd=[...Ir].reverse(),Kd=Ir.length;function Gd(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Xd(e,n,s)))}function Yd(e){let t=Gd(e),n=Ri(),s=!0;const r=c=>(u,d)=>{const h=nn(e,d,c==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:m,transitionEnd:p,...w}=h;u={...u,...w,...p}}return u};function o(c){t=c(e)}function i(c){const{props:u}=e,d=La(e.parent)||{},h=[],m=new Set;let p={},w=1/0;for(let b=0;b<Kd;b++){const y=qd[b],j=n[y],M=u[y]!==void 0?u[y]:d[y],N=$n(M),D=y===c?j.isActive:null;D===!1&&(w=b);let F=M===d[y]&&M!==u[y]&&N;if(F&&s&&e.manuallyAnimateOnMount&&(F=!1),j.protectedKeys={...p},!j.isActive&&D===null||!M&&!j.prevProp||xs(M)||typeof M=="boolean")continue;const B=Hd(j.prevProp,M);let P=B||y===c&&j.isActive&&!F&&N||b>w&&N,z=!1;const T=Array.isArray(M)?M:[M];let V=T.reduce(r(y),{});D===!1&&(V={});const{prevResolvedValues:O={}}=j,R={...O,...V},W=Y=>{P=!0,m.has(Y)&&(z=!0,m.delete(Y)),j.needsAnimating[Y]=!0;const te=e.getValue(Y);te&&(te.liveStyle=!1)};for(const Y in R){const te=V[Y],J=O[Y];if(p.hasOwnProperty(Y))continue;let be=!1;sr(te)&&sr(J)?be=!$a(te,J):be=te!==J,be?te!=null?W(Y):m.add(Y):te!==void 0&&m.has(Y)?W(Y):j.protectedKeys[Y]=!0}j.prevProp=M,j.prevResolvedValues=V,j.isActive&&(p={...p,...V}),s&&e.blockInitialAnimation&&(P=!1);const oe=F&&B;P&&(!oe||z)&&h.push(...T.map(Y=>{const te={type:y};if(typeof Y=="string"&&s&&!oe&&e.manuallyAnimateOnMount&&e.parent){const{parent:J}=e,be=nn(J,Y);if(J.enteringChildren&&be){const{delayChildren:He}=be.transition||{};te.delay=Oa(J.enteringChildren,e,He)}}return{animation:Y,options:te}}))}if(m.size){const b={};if(typeof u.initial!="boolean"){const y=nn(e,Array.isArray(u.initial)?u.initial[0]:u.initial);y&&y.transition&&(b.transition=y.transition)}m.forEach(y=>{const j=e.getBaseTarget(y),M=e.getValue(y);M&&(M.liveStyle=!0),b[y]=j??null}),h.push({animation:b})}let x=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(x=!1),s=!1,x?t(h):Promise.resolve()}function a(c,u){if(n[c].isActive===u)return Promise.resolve();e.variantChildren?.forEach(h=>h.animationState?.setActive(c,u)),n[c].isActive=u;const d=i(c);for(const h in n)n[h].protectedKeys={};return d}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Ri()}}}function Hd(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!$a(t,e):!1}function Et(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Ri(){return{animate:Et(!0),whileInView:Et(),whileHover:Et(),whileTap:Et(),whileDrag:Et(),whileFocus:Et(),exit:Et()}}class wt{constructor(t){this.isMounted=!1,this.node=t}update(){}}class Jd extends wt{constructor(t){super(t),t.animationState||(t.animationState=Yd(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();xs(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Zd=0;class Qd extends wt{constructor(){super(...arguments),this.id=Zd++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const Fa={animation:{Feature:Jd},exit:{Feature:Qd}};function Fn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function _n(e){return{point:{x:e.pageX,y:e.pageY}}}const eh=e=>t=>Dr(t)&&e(t,_n(t));function Mn(e,t,n,s){return Fn(e,t,eh(n),s)}const Ba=1e-4,th=1-Ba,nh=1+Ba,za=.01,sh=0-za,rh=0+za;function Ce(e){return e.max-e.min}function ih(e,t,n){return Math.abs(e-t)<=n}function Vi(e,t,n,s=.5){e.origin=s,e.originPoint=me(t.min,t.max,e.origin),e.scale=Ce(n)/Ce(t),e.translate=me(n.min,n.max,e.origin)-e.originPoint,(e.scale>=th&&e.scale<=nh||isNaN(e.scale))&&(e.scale=1),(e.translate>=sh&&e.translate<=rh||isNaN(e.translate))&&(e.translate=0)}function En(e,t,n,s){Vi(e.x,t.x,n.x,s?s.originX:void 0),Vi(e.y,t.y,n.y,s?s.originY:void 0)}function Ii(e,t,n){e.min=n.min+t.min,e.max=e.min+Ce(t)}function oh(e,t,n){Ii(e.x,t.x,n.x),Ii(e.y,t.y,n.y)}function Oi(e,t,n){e.min=t.min-n.min,e.max=e.min+Ce(t)}function Nn(e,t,n){Oi(e.x,t.x,n.x),Oi(e.y,t.y,n.y)}function Le(e){return[e("x"),e("y")]}const Ua=({current:e})=>e?e.ownerDocument.defaultView:null,$i=(e,t)=>Math.abs(e-t);function ah(e,t){const n=$i(e.x,t.x),s=$i(e.y,t.y);return Math.sqrt(n**2+s**2)}class _a{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const m=Ns(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,w=ah(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!w)return;const{point:x}=m,{timestamp:b}=ve;this.history.push({...x,timestamp:b});const{onStart:y,onMove:j}=this.handlers;p||(y&&y(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),j&&j(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=Es(p,this.transformPagePoint),ue.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:w,onSessionEnd:x,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Ns(m.type==="pointercancel"?this.lastMoveEventInfo:Es(p,this.transformPagePoint),this.history);this.startEvent&&w&&w(m,y),x&&x(m,y)},!Dr(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=_n(t),c=Es(a,this.transformPagePoint),{point:u}=c,{timestamp:d}=ve;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=n;h&&h(t,Ns(c,this.history)),this.removeListeners=Bn(Mn(this.contextWindow,"pointermove",this.handlePointerMove),Mn(this.contextWindow,"pointerup",this.handlePointerUp),Mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),bt(this.updatePoint)}}function Es(e,t){return t?{point:t(e.point)}:e}function Li(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Ns({point:e},t){return{point:e,delta:Li(e,Xa(t)),offset:Li(e,ch(t)),velocity:lh(t,.1)}}function ch(e){return e[0]}function Xa(e){return e[e.length-1]}function lh(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Xa(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>Ye(t)));)n--;if(!s)return{x:0,y:0};const o=Fe(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 uh(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?me(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?me(n,e,s.max):Math.min(e,n)),e}function Fi(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function dh(e,{top:t,left:n,bottom:s,right:r}){return{x:Fi(e.x,n,r),y:Fi(e.y,t,s)}}function Bi(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function hh(e,t){return{x:Bi(e.x,t.x),y:Bi(e.y,t.y)}}function fh(e,t){let n=.5;const s=Ce(e),r=Ce(t);return r>s?n=Vn(t.min,t.max-s,e.min):s>r&&(n=Vn(e.min,e.max-r,t.min)),rt(0,1,n)}function mh(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const or=.35;function ph(e=or){return e===!1?e=0:e===!0&&(e=or),{x:zi(e,"left","right"),y:zi(e,"top","bottom")}}function zi(e,t,n){return{min:Ui(e,t),max:Ui(e,n)}}function Ui(e,t){return typeof e=="number"?e:e[t]||0}const gh=new WeakMap;class yh{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ge(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const o=h=>{const{dragSnapToOrigin:m}=this.getProps();m?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(_n(h).point)},i=(h,m)=>{const{drag:p,dragPropagation:w,onDragStart:x}=this.getProps();if(p&&!w&&(this.openDragLock&&this.openDragLock(),this.openDragLock=ju(p),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Le(y=>{let j=this.getAxisMotionValue(y).get()||0;if(et.test(j)){const{projection:M}=this.visualElement;if(M&&M.layout){const N=M.layout.layoutBox[y];N&&(j=Ce(N)*(parseFloat(j)/100))}}this.originPoint[y]=j}),x&&ue.postRender(()=>x(h,m)),rr(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:w,onDirectionLock:x,onDrag:b}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=m;if(w&&this.currentDirection===null){this.currentDirection=xh(y),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",m.point,y),this.updateAxis("y",m.point,y),this.visualElement.render(),b&&b(h,m)},c=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>Le(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:d}=this.getProps();this.panSession=new _a(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Ua(this.visualElement)})}stop(t,n){const s=t||this.latestPointerEvent,r=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!r||!s)return;const{velocity:i}=r;this.startAnimation(i);const{onDragEnd:a}=this.getProps();a&&ue.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,s){const{drag:r}=this.getProps();if(!s||!ns(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=uh(i,this.constraints[t],this.elastic[t])),o.set(i)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&Jt(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=dh(s.layoutBox,t):this.constraints=!1,this.elastic=ph(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Le(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=mh(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Jt(t))return!1;const s=t.current;it(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=wd(s,r.root,this.visualElement.getTransformPagePoint());let i=hh(r.layout.layoutBox,o);if(n){const a=n(xd(i));this.hasMutatedConstraints=!!a,a&&(i=Ca(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},u=Le(d=>{if(!ns(d,n,this.currentDirection))return;let h=c&&c[d]||{};i&&(h={min:0,max:0});const m=r?200:1e6,p=r?40:1e7,w={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(d,w)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return rr(this.visualElement,t),s.start(_r(t,s,0,n,this.visualElement,!1))}stopAnimation(){Le(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Le(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){Le(n=>{const{drag:s}=this.getProps();if(!ns(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,o=this.getAxisMotionValue(n);if(r&&r.layout){const{min:i,max:a}=r.layout.layoutBox[n];o.set(t[n]-me(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Jt(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Le(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const c=a.get();r[i]=fh({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(),Le(i=>{if(!ns(i,t,null))return;const a=this.getAxisMotionValue(i),{min:c,max:u}=this.constraints[i];a.set(me(c,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;gh.set(this.visualElement,this);const t=this.visualElement.current,n=Mn(t,"pointerdown",c=>{const{drag:u,dragListener:d=!0}=this.getProps();u&&d&&this.start(c)}),s=()=>{const{dragConstraints:c}=this.getProps();Jt(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()),ue.read(s);const i=Fn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(Le(d=>{const h=this.getAxisMotionValue(d);h&&(this.originPoint[d]+=c[d].translate,h.set(h.get()+c[d].translate))}),this.visualElement.render())});return()=>{i(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:o=!1,dragElastic:i=or,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function ns(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function xh(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class bh extends wt{constructor(t){super(t),this.removeGroupControls=Be,this.removeListeners=Be,this.controls=new yh(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Be}unmount(){this.removeGroupControls(),this.removeListeners()}}const _i=e=>(t,n)=>{e&&ue.postRender(()=>e(t,n))};class vh extends wt{constructor(){super(...arguments),this.removePointerDownListener=Be}onPointerDown(t){this.session=new _a(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ua(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:_i(t),onStart:_i(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&ue.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=Mn(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const cs={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Xi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Cn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(q.test(e))e=parseFloat(e);else return e;const n=Xi(e,t.target.x),s=Xi(e,t.target.y);return`${n}% ${s}%`}},wh={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=vt.parse(e);if(r.length>5)return s;const o=vt.createTransformer(e),i=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,c=n.y.scale*t.y;r[0+i]/=a,r[1+i]/=c;const u=me(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 Th extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;qu(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()})),cs.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Ds=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||ue.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Nr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Ds=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Wa(e){const[t,n]=ha(),s=f.useContext(lr);return l.jsx(Th,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(Sa),isPresent:t,safeToRemove:n})}const Sh={borderRadius:{...Cn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Cn,borderTopRightRadius:Cn,borderBottomLeftRadius:Cn,borderBottomRightRadius:Cn,boxShadow:wh};function jh(e,t,n){const s=Te(e)?e:sn(e);return s.start(_r("",s,t,n)),s.animation}const Ch=(e,t)=>e.depth-t.depth;class Ph{constructor(){this.children=[],this.isDirty=!1}add(t){hr(this.children,t),this.isDirty=!0}remove(t){fr(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Ch),this.isDirty=!1,this.children.forEach(t)}}function Ah(e,t){const n=ke.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(bt(s),e(o-t))};return ue.setup(s,!0),()=>bt(s)}const qa=["TopLeft","TopRight","BottomLeft","BottomRight"],kh=qa.length,Wi=e=>typeof e=="string"?parseFloat(e):e,qi=e=>typeof e=="number"||q.test(e);function Mh(e,t,n,s,r,o){r?(e.opacity=me(0,n.opacity??1,Eh(s)),e.opacityExit=me(t.opacity??1,0,Nh(s))):o&&(e.opacity=me(t.opacity??1,n.opacity??1,s));for(let i=0;i<kh;i++){const a=`border${qa[i]}Radius`;let c=Ki(t,a),u=Ki(n,a);if(c===void 0&&u===void 0)continue;c||(c=0),u||(u=0),c===0||u===0||qi(c)===qi(u)?(e[a]=Math.max(me(Wi(c),Wi(u),s),0),(et.test(u)||et.test(c))&&(e[a]+="%")):e[a]=u}(t.rotate||n.rotate)&&(e.rotate=me(t.rotate||0,n.rotate||0,s))}function Ki(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Eh=Ka(0,.5,Do),Nh=Ka(.5,.95,Be);function Ka(e,t,n){return s=>s<e?0:s>t?1:n(Vn(e,t,s))}function Gi(e,t){e.min=t.min,e.max=t.max}function $e(e,t){Gi(e.x,t.x),Gi(e.y,t.y)}function Yi(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function Hi(e,t,n,s,r){return e-=t,e=ms(e,1/n,s),r!==void 0&&(e=ms(e,1/r,s)),e}function Dh(e,t=0,n=1,s=.5,r,o=e,i=e){if(et.test(t)&&(t=parseFloat(t),t=me(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=me(o.min,o.max,s);e===o&&(a-=t),e.min=Hi(e.min,t,n,a,r),e.max=Hi(e.max,t,n,a,r)}function Ji(e,t,[n,s,r],o,i){Dh(e,t[n],t[s],t[r],t.scale,o,i)}const Rh=["x","scaleX","originX"],Vh=["y","scaleY","originY"];function Zi(e,t,n,s){Ji(e.x,t,Rh,n?n.x:void 0,s?s.x:void 0),Ji(e.y,t,Vh,n?n.y:void 0,s?s.y:void 0)}function Qi(e){return e.translate===0&&e.scale===1}function Ga(e){return Qi(e.x)&&Qi(e.y)}function eo(e,t){return e.min===t.min&&e.max===t.max}function Ih(e,t){return eo(e.x,t.x)&&eo(e.y,t.y)}function to(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Ya(e,t){return to(e.x,t.x)&&to(e.y,t.y)}function no(e){return Ce(e.x)/Ce(e.y)}function so(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class Oh{constructor(){this.members=[]}add(t){hr(this.members,t),t.scheduleRender()}remove(t){if(fr(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(r=>t===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(t,n){const s=this.lead;if(t!==s&&(this.prevLead=s,this.lead=t,t.show(),s)){s.instance&&s.scheduleRender(),t.scheduleRender(),t.resumeFrom=s,n&&(t.resumeFrom.preserveOpacity=!0),s.snapshot&&(t.snapshot=s.snapshot,t.snapshot.latestValues=s.animationValues||s.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:r}=t.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:s}=t;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function $h(e,t,n){let s="";const r=e.x.translate/t.x,o=e.y.translate/t.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:u,rotate:d,rotateX:h,rotateY:m,skewX:p,skewY:w}=n;u&&(s=`perspective(${u}px) ${s}`),d&&(s+=`rotate(${d}deg) `),h&&(s+=`rotateX(${h}deg) `),m&&(s+=`rotateY(${m}deg) `),p&&(s+=`skewX(${p}deg) `),w&&(s+=`skewY(${w}deg) `)}const a=e.x.scale*t.x,c=e.y.scale*t.y;return(a!==1||c!==1)&&(s+=`scale(${a}, ${c})`),s||"none"}const Rs=["","X","Y","Z"],Lh=1e3;let Fh=0;function Vs(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function Ha(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Va(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",ue,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&Ha(s)}function Ja({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=Fh++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(Uh),this.nodes.forEach(qh),this.nodes.forEach(Kh),this.nodes.forEach(_h)},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 Ph)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new pr),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=da(i)&&!Eu(i),this.instance=i;const{layoutId:a,layout:c,visualElement:u}=this.options;if(u&&!u.current&&u.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),e){let d,h=0;const m=()=>this.root.updateBlockedByResize=!1;ue.read(()=>{h=window.innerWidth}),e(i,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,d&&d(),d=Ah(m,250),cs.hasAnimatedSinceResize&&(cs.hasAnimatedSinceResize=!1,this.nodes.forEach(oo)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||c)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const w=this.options.transition||u.getDefaultTransition()||Zh,{onLayoutAnimationStart:x,onLayoutAnimationComplete:b}=u.getProps(),y=!this.targetLayout||!Ya(this.targetLayout,p),j=!h&&m;if(this.options.layoutRoot||this.resumeFrom||j||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const M={...Mr(w,"layout"),onPlay:x,onComplete:b};(u.shouldReduceMotion||this.options.layoutRoot)&&(M.delay=0,M.type=!1),this.startAnimation(M),this.setAnimationOrigin(d,j)}else h||oo(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const i=this.getStack();i&&i.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),bt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Gh),this.animationId++)}getTransformTemplate(){const{visualElement:i}=this.options;return i&&i.getProps().transformTemplate}willUpdate(i=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Ha(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const h=this.path[d];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:a,layout: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(ro);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(io);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Wh),this.nodes.forEach(Bh),this.nodes.forEach(zh)):this.nodes.forEach(io),this.clearAllSnapshots();const a=ke.now();ve.delta=rt(0,1e3/60,a-ve.timestamp),ve.timestamp=a,ve.isProcessing=!0,Ts.update.process(ve),Ts.preRender.process(ve),Ts.render.process(ve),ve.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Nr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Xh),this.sharedNodes.forEach(Yh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ue.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ue.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ce(this.snapshot.measuredBox.x)&&!Ce(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=ge(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,i?i.layoutBox:void 0)}updateScroll(i="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===i&&(a=!1),a&&this.instance){const 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&&!Ga(this.projectionDelta),c=this.getTransformTemplate(),u=c?c(this.latestValues,""):void 0,d=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Dt(this.latestValues)||d)&&(r(this.instance,u),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let c=this.removeElementScroll(a);return i&&(c=this.removeTransform(c)),Qh(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ge();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(ef))){const{scroll:u}=this.root;u&&(Zt(a.x,u.offset.x),Zt(a.y,u.offset.y))}return a}removeElementScroll(i){const a=ge();if($e(a,i),this.scroll?.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&$e(a,i),Zt(a.x,d.offset.x),Zt(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const c=ge();$e(c,i);for(let u=0;u<this.path.length;u++){const d=this.path[u];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&Qt(c,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Dt(d.latestValues)&&Qt(c,d.latestValues)}return Dt(this.latestValues)&&Qt(c,this.latestValues),c}removeTransform(i){const a=ge();$e(a,i);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!u.instance||!Dt(u.latestValues))continue;er(u.latestValues)&&u.updateSnapshot();const d=ge(),h=u.measurePageBox();$e(d,h),Zi(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,d)}return Dt(this.latestValues)&&Zi(a,this.latestValues),a}setTargetDelta(i){this.targetDelta=i,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(i){this.options={...this.options,...i,crossfade:i.crossfade!==void 0?i.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==ve.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(i=!1){const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(i||c&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:d,layoutId:h}=this.options;if(!(!this.layout||!(d||h))){if(this.resolvedRelativeTargetAt=ve.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ge(),this.relativeTargetOrigin=ge(),Nn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),$e(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ge(),this.targetWithTransforms=ge()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),oh(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):$e(this.target,this.layout.layoutBox),Aa(this.target,this.targetDelta)):$e(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const m=this.getClosestProjectingParent();m&&!!m.resumingFrom==!!this.resumingFrom&&!m.options.layoutScroll&&m.target&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ge(),this.relativeTargetOrigin=ge(),Nn(this.relativeTargetOrigin,this.target,m.target),$e(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||er(this.parent.latestValues)||Pa(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){const i=this.getLead(),a=!!this.resumingFrom||this!==i;let c=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(c=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===ve.timestamp&&(c=!1),c)return;const{layout:u,layoutId:d}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(u||d))return;$e(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,m=this.treeScale.y;vd(this.layoutCorrected,this.treeScale,this.path,a),i.layout&&!i.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(i.target=i.layout.layoutBox,i.targetWithTransforms=ge());const{target:p}=i;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Yi(this.prevProjectionDelta.x,this.projectionDelta.x),Yi(this.prevProjectionDelta.y,this.projectionDelta.y)),En(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==m||!so(this.projectionDelta.x,this.prevProjectionDelta.x)||!so(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}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=en(),this.projectionDelta=en(),this.projectionDeltaWithTransform=en()}setAnimationOrigin(i,a=!1){const c=this.snapshot,u=c?c.latestValues:{},d={...this.latestValues},h=en();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=ge(),p=c?c.source:void 0,w=this.layout?this.layout.source:void 0,x=p!==w,b=this.getStack(),y=!b||b.members.length<=1,j=!!(x&&!y&&this.options.crossfade===!0&&!this.path.some(Jh));this.animationProgress=0;let M;this.mixTargetDelta=N=>{const D=N/1e3;ao(h.x,i.x,D),ao(h.y,i.y,D),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Nn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Hh(this.relativeTarget,this.relativeTargetOrigin,m,D),M&&Ih(this.relativeTarget,M)&&(this.isProjectionDirty=!1),M||(M=ge()),$e(M,this.relativeTarget)),x&&(this.animationValues=d,Mh(d,u,this.latestValues,D,j,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=D},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(bt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ue.update(()=>{cs.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=sn(0)),this.currentAnimation=jh(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(Lh),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:c,layout:u,latestValues:d}=i;if(!(!a||!c||!u)){if(this!==i&&this.layout&&u&&Za(this.options.animationType,this.layout.layoutBox,u.layoutBox)){c=this.target||ge();const h=Ce(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+h;const m=Ce(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+m}$e(a,c),Qt(a,d),En(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new Oh),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&&Vs("z",i,u,this.animationValues);for(let d=0;d<Rs.length;d++)Vs(`rotate${Rs[d]}`,i,u,this.animationValues),Vs(`skew${Rs[d]}`,i,u,this.animationValues);i.render();for(const d in u)i.setStaticValue(d,u[d]),this.animationValues&&(this.animationValues[d]=u[d]);i.scheduleRender()}applyProjectionStyles(i,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){i.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,i.visibility="",i.opacity="",i.pointerEvents=os(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=os(a?.pointerEvents)||""),this.hasProjected&&!Dt(this.latestValues)&&(i.transform=c?c({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=$h(this.projectionDeltaWithTransform,this.treeScale,d);c&&(h=c(d,h)),i.transform=h;const{x:m,y:p}=this.projectionDelta;i.transformOrigin=`${m.origin*100}% ${p.origin*100}% 0`,u.animationValues?i.opacity=u===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:i.opacity=u===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const w in Ln){if(d[w]===void 0)continue;const{correct:x,applyTo:b,isCSSVariable:y}=Ln[w],j=h==="none"?d[w]:x(d[w],u);if(b){const M=b.length;for(let N=0;N<M;N++)i[b[N]]=j}else y?this.options.visualElement.renderState.vars[w]=j:i[w]=j}this.options.layoutId&&(i.pointerEvents=u===this?os(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(ro),this.root.sharedNodes.clear()}}}function Bh(e){e.updateLayout()}function zh(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:r}=e.options,o=t.source!==e.layout.source;r==="size"?Le(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=Ce(h);h.min=n[d].min,h.max=h.min+m}):Za(r,t.layoutBox,n)&&Le(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=Ce(n[d]);h.max=h.min+m,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[d].max=e.relativeTarget[d].min+m)});const i=en();En(i,n,t.layoutBox);const a=en();o?En(a,e.applyTransform(s,!0),t.measuredBox):En(a,n,t.layoutBox);const c=!Ga(i);let u=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:m}=d;if(h&&m){const p=ge();Nn(p,t.layoutBox,h.layoutBox);const w=ge();Nn(w,n,m.layoutBox),Ya(p,w)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=w,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function Uh(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function _h(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Xh(e){e.clearSnapshot()}function ro(e){e.clearMeasurements()}function io(e){e.isLayoutDirty=!1}function Wh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function oo(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function qh(e){e.resolveTargetDelta()}function Kh(e){e.calcProjection()}function Gh(e){e.resetSkewAndRotation()}function Yh(e){e.removeLeadSnapshot()}function ao(e,t,n){e.translate=me(t.translate,0,n),e.scale=me(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function co(e,t,n,s){e.min=me(t.min,n.min,s),e.max=me(t.max,n.max,s)}function Hh(e,t,n,s){co(e.x,t.x,n.x,s),co(e.y,t.y,n.y,s)}function Jh(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const Zh={duration:.45,ease:[.4,0,.1,1]},lo=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),uo=lo("applewebkit/")&&!lo("chrome/")?Math.round:Be;function ho(e){e.min=uo(e.min),e.max=uo(e.max)}function Qh(e){ho(e.x),ho(e.y)}function Za(e,t,n){return e==="position"||e==="preserve-aspect"&&!ih(no(t),no(n),.2)}function ef(e){return e!==e.root&&e.scroll?.wasRoot}const tf=Ja({attachResizeListener:(e,t)=>Fn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Is={current:void 0},Qa=Ja({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Is.current){const e=new tf({});e.mount(window),e.setOptions({layoutScroll:!0}),Is.current=e}return Is.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),nf={pan:{Feature:vh},drag:{Feature:bh,ProjectionNode:Qa,MeasureLayout:Wa}};function fo(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,o=s[r];o&&ue.postRender(()=>o(t,_n(t)))}class sf extends wt{mount(){const{current:t}=this.node;t&&(this.unmount=Cu(t,(n,s)=>(fo(this.node,s,"Start"),r=>fo(this.node,r,"End"))))}unmount(){}}class rf extends wt{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Bn(Fn(this.node.current,"focus",()=>this.onFocus()),Fn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mo(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),o=s[r];o&&ue.postRender(()=>o(t,_n(t)))}class of extends wt{mount(){const{current:t}=this.node;t&&(this.unmount=Mu(t,(n,s)=>(mo(this.node,s,"Start"),(r,{success:o})=>mo(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ar=new WeakMap,Os=new WeakMap,af=e=>{const t=ar.get(e.target);t&&t(e)},cf=e=>{e.forEach(af)};function lf({root:e,...t}){const n=e||document;Os.has(n)||Os.set(n,{});const s=Os.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(cf,{root:e,...t})),s[r]}function uf(e,t,n){const s=lf(t);return ar.set(e,n),s.observe(e),()=>{ar.delete(e),s.unobserve(e)}}const df={some:0,all:1};class hf extends wt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=t,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:df[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:d,onViewportLeave:h}=this.node.getProps(),m=u?d:h;m&&m(c)};return uf(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(ff(t,n))&&this.startObserver()}unmount(){}}function ff({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const ec={inView:{Feature:hf},tap:{Feature:of},focus:{Feature:rf},hover:{Feature:sf}},mf={layout:{ProjectionNode:Qa,MeasureLayout:Wa}},pf={...Fa,...ec,...nf,...mf},gf=yd(pf,Ra),yf={renderer:Ra,...Fa,...ec};function Xr(e,t){return as(e,t)}const xf=Xr("button"),ss=Xr("div"),bf=Xr("p"),Qe=Symbol.for("@arcteninc/core:originalName");function vf(e,t){return e[Qe]=t,e}function wf(e,t,n,s){if(typeof e!="function")return null;const r=e[Qe];if(r){const a=t[r];if(a&&!n.has(a.name))return{fn:e,meta:a}}const o=e.name;let i;if(o&&(i=t[o],i&&!n.has(i.name)))return e[Qe]=i.name,{fn:e,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=t[a],i))return e[Qe]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(c=>!n.has(c.name)),i)return e[Qe]=i.name,{fn:e,meta:i};return null}function tc(e,t){let n,s;if(!t)throw new Error(`❌ toolMetadata is required!
9
+ `),()=>{b.contains(x)&&b.removeChild(x)}},[t]),l.jsx(Iu,{isPresent:t,childRef:o,sizeRef:i,children:Ge.cloneElement(e,{ref:c})})}const $u=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:c})=>{const u=ur(Lu),d=f.useId();let h=!0,m=f.useMemo(()=>(h=!1,{id:d,initial:t,isPresent:n,custom:r,onExitComplete:p=>{u.set(p,!0);for(const w of u.values())if(!w)return;s&&s()},register:p=>(u.set(p,!1),()=>u.delete(p))}),[n,u,s]);return o&&h&&(m={...m}),f.useMemo(()=>{u.forEach((p,w)=>u.set(w,!1))},[n]),Ge.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(e=l.jsx(Ou,{isPresent:n,anchorX:a,root:c,children:e})),l.jsx(ps.Provider,{value:m,children:e})};function Lu(){return new Map}function ha(e=!0){const t=f.useContext(ps);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,o=f.useId();f.useEffect(()=>{if(e)return r(o)},[e]);const i=f.useCallback(()=>e&&s&&s(o),[o,s,e]);return!n&&s?[!1,i]:[!0]}const es=e=>e.key||"";function wi(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const Fu=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:c})=>{const[u,d]=ha(i),h=f.useMemo(()=>wi(e),[e]),m=i&&!u?[]:h.map(es),p=f.useRef(!0),w=f.useRef(h),x=ur(()=>new Map),[b,y]=f.useState(h),[j,M]=f.useState(h);wo(()=>{p.current=!1,w.current=h;for(let F=0;F<j.length;F++){const B=es(j[F]);m.includes(B)?x.delete(B):x.get(B)!==!0&&x.set(B,!1)}},[j,m.length,m.join("-")]);const E=[];if(h!==b){let F=[...h];for(let B=0;B<j.length;B++){const P=j[B],z=es(P);m.includes(z)||(F.splice(B,0,P),E.push(P))}return o==="wait"&&E.length&&(F=E),M(wi(F)),y(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&j.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:D}=f.useContext(lr);return l.jsx(l.Fragment,{children:j.map(F=>{const B=es(F),P=i&&!u?!1:h===j||m.includes(B),z=()=>{if(x.has(B))x.set(B,!0);else return;let T=!0;x.forEach(V=>{V||(T=!1)}),T&&(D?.(),M(w.current),i&&d?.(),s&&s())};return l.jsx($u,{isPresent:P,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:P?void 0:z,anchorX:a,children:F},B)})})},Vr=f.createContext({strict:!1}),Ti={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},sn={};for(const e in Ti)sn[e]={isEnabled:t=>Ti[e].some(n=>!!t[n])};function Qs(e){for(const t in e)sn[t]={...sn[t],...e[t]}}function Bu({children:e,features:t,strict:n=!1}){const[,s]=f.useState(!ks(t)),r=f.useRef(void 0);if(!ks(t)){const{renderer:o,...i}=t;r.current=o,Qs(i)}return f.useEffect(()=>{ks(t)&&t().then(({renderer:o,...i})=>{Qs(i),r.current=o,s(!0)})},[]),l.jsx(Vr.Provider,{value:{renderer:r.current,strict:n},children:e})}function ks(e){return typeof e=="function"}const zu=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 hs(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||zu.has(e)}let fa=e=>!hs(e);function Uu(e){typeof e=="function"&&(fa=t=>t.startsWith("on")?!hs(t):e(t))}try{Uu(require("@emotion/is-prop-valid").default)}catch{}function _u(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(fa(r)||n===!0&&hs(r)||!t&&!hs(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const gs=f.createContext({});function ys(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function $n(e){return typeof e=="string"||Array.isArray(e)}const Ir=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Or=["initial",...Ir];function xs(e){return ys(e.animate)||Or.some(t=>$n(e[t]))}function ma(e){return!!(xs(e)||e.variants)}function Xu(e,t){if(xs(e)){const{initial:n,animate:s}=e;return{initial:n===!1||$n(n)?n:void 0,animate:$n(s)?s:void 0}}return e.inherit!==!1?t:{}}function Wu(e){const{initial:t,animate:n}=Xu(e,f.useContext(gs));return f.useMemo(()=>({initial:t,animate:n}),[Si(t),Si(n)])}function Si(e){return Array.isArray(e)?e.join(" "):e}const Ln={};function qu(e){for(const t in e)Ln[t]=e[t],br(t)&&(Ln[t].isCSSVariable=!0)}function pa(e,{layout:t,layoutId:n}){return cn.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Ln[e]||e==="opacity")}const Ku={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Gu=an.length;function Yu(e,t,n){let s="",r=!0;for(let o=0;o<Gu;o++){const i=an[o],a=e[i];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(i.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const u=oa(a,Er[i]);if(!c){r=!1;const d=Ku[i]||i;s+=`${d}(${u}) `}n&&(t[i]=u)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function $r(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const c in t){const u=t[c];if(cn.has(c)){i=!0;continue}else if(br(c)){r[c]=u;continue}else{const d=oa(u,Er[c]);c.startsWith("origin")?(a=!0,o[c]=d):s[c]=d}}if(t.transform||(i||n?s.transform=Yu(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:c="50%",originY:u="50%",originZ:d=0}=o;s.transformOrigin=`${c} ${u} ${d}`}}const Lr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function ga(e,t,n){for(const s in t)!Se(t[s])&&!pa(s,n)&&(e[s]=t[s])}function Hu({transformTemplate:e},t){return f.useMemo(()=>{const n=Lr();return $r(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Ju(e,t){const n=e.style||{},s={};return ga(s,n,e),Object.assign(s,Hu(e,t)),s}function Zu(e,t){const n={},s=Ju(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const Qu={offset:"stroke-dashoffset",array:"stroke-dasharray"},ed={offset:"strokeDashoffset",array:"strokeDasharray"};function td(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?Qu:ed;e[o.offset]=q.transform(-s);const i=q.transform(t),a=q.transform(n);e[o.array]=`${i} ${a}`}function ya(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},c,u,d){if($r(e,a,u),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:h,style:m}=e;h.transform&&(m.transform=h.transform,delete h.transform),(m.transform||h.transformOrigin)&&(m.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),m.transform&&(m.transformBox=d?.transformBox??"fill-box",delete h.transformBox),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),r!==void 0&&td(h,r,o,i,!1)}const xa=()=>({...Lr(),attrs:{}}),ba=e=>typeof e=="string"&&e.toLowerCase()==="svg";function nd(e,t,n,s){const r=f.useMemo(()=>{const o=xa();return ya(o,t,ba(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};ga(o,e.style,e),r.style={...o,...r.style}}return r}const sd=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Fr(e){return typeof e!="string"||e.includes("-")?!1:!!(sd.indexOf(e)>-1||/[A-Z]/u.test(e))}function rd(e,t,n,{latestValues:s},r,o=!1){const a=(Fr(e)?nd:Zu)(t,s,r,e),c=_u(t,typeof e=="string",o),u=e!==f.Fragment?{...c,...a,ref:n}:{},{children:d}=t,h=f.useMemo(()=>Se(d)?d.get():d,[d]);return f.createElement(e,{...u,children:h})}function ji(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Br(e,t,n,s){if(typeof t=="function"){const[r,o]=ji(s);t=t(n!==void 0?n:e.custom,r,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,o]=ji(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function is(e){return Se(e)?e.get():e}function id({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:od(n,s,r,e),renderState:t()}}function od(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=is(o[m]);let{initial:i,animate:a}=e;const c=xs(e),u=ma(e);t&&u&&!c&&e.inherit!==!1&&(i===void 0&&(i=t.initial),a===void 0&&(a=t.animate));let d=n?n.initial===!1:!1;d=d||i===!1;const h=d?a:i;if(h&&typeof h!="boolean"&&!ys(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p<m.length;p++){const w=Br(e,m[p]);if(w){const{transitionEnd:x,transition:b,...y}=w;for(const j in y){let M=y[j];if(Array.isArray(M)){const E=d?M.length-1:0;M=M[E]}M!==null&&(r[j]=M)}for(const j in x)r[j]=x[j]}}}return r}const va=e=>(t,n)=>{const s=f.useContext(gs),r=f.useContext(ps),o=()=>id(e,t,s,r);return n?o():ur(o)};function zr(e,t,n){const{style:s}=e,r={};for(const o in s)(Se(s[o])||t.style&&Se(t.style[o])||pa(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const ad=va({scrapeMotionValuesFromProps:zr,createRenderState:Lr});function wa(e,t,n){const s=zr(e,t,n);for(const r in e)if(Se(e[r])||Se(t[r])){const o=an.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const cd=va({scrapeMotionValuesFromProps:wa,createRenderState:xa}),ld=Symbol.for("motionComponentSymbol");function Ht(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function ud(e,t,n){return f.useCallback(s=>{s&&e.onMount&&e.onMount(s),t&&(s?t.mount(s):t.unmount()),n&&(typeof n=="function"?n(s):Ht(n)&&(n.current=s))},[t])}const Ur=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),dd="framerAppearId",Ta="data-"+Ur(dd),Sa=f.createContext({});function hd(e,t,n,s,r){const{visualElement:o}=f.useContext(gs),i=f.useContext(Vr),a=f.useContext(ps),c=f.useContext(Rr).reducedMotion,u=f.useRef(null);s=s||i.renderer,!u.current&&s&&(u.current=s(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const d=u.current,h=f.useContext(Sa);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&fd(u.current,n,r,h);const m=f.useRef(!1);f.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[Ta],w=f.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return wo(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),w.current&&d.animationState&&d.animationState.animateChanges())}),f.useEffect(()=>{d&&(!w.current&&d.animationState&&d.animationState.animateChanges(),w.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),w.current=!1),d.enteringChildren=void 0)}),d}function fd(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:c,layoutRoot:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:ja(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Ht(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:c,layoutRoot:u})}function ja(e){if(e)return e.options.allowProjection!==!1?e.projection:ja(e.parent)}function os(e,{forwardMotionProps:t=!1}={},n,s){n&&Qs(n);const r=Fr(e)?cd:ad;function o(a,c){let u;const d={...f.useContext(Rr),...a,layoutId:md(a)},{isStatic:h}=d,m=Wu(a),p=r(a,h);if(!h&&dr){pd(d,n);const w=gd(d);u=w.MeasureLayout,m.visualElement=hd(e,p,d,s,w.ProjectionNode)}return l.jsxs(gs.Provider,{value:m,children:[u&&m.visualElement?l.jsx(u,{visualElement:m.visualElement,...d}):null,rd(e,a,ud(p,m.visualElement,c),p,h,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=f.forwardRef(o);return i[ld]=e,i}function md({layoutId:e}){const t=f.useContext(lr).id;return t&&e!==void 0?t+"-"+e:e}function pd(e,t){const n=f.useContext(Vr).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const s="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?rn(!1,s,"lazy-strict-mode"):rt(!1,s,"lazy-strict-mode")}}function gd(e){const{drag:t,layout:n}=sn;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function yd(e,t){if(typeof Proxy>"u")return os;const n=new Map,s=(o,i)=>os(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&gr(!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,os(i,void 0,e,t)),n.get(i))})}function Ca({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function xd({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function bd(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),s=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function Ms(e){return e===void 0||e===1}function er({scale:e,scaleX:t,scaleY:n}){return!Ms(e)||!Ms(t)||!Ms(n)}function Nt(e){return er(e)||Pa(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Pa(e){return Ci(e.x)||Ci(e.y)}function Ci(e){return e&&e!=="0%"}function fs(e,t,n){const s=e-n,r=t*s;return n+r}function Pi(e,t,n,s,r){return r!==void 0&&(e=fs(e,r,s)),fs(e,n,s)+t}function tr(e,t=0,n=1,s,r){e.min=Pi(e.min,t,n,s,r),e.max=Pi(e.max,t,n,s,r)}function Aa(e,{x:t,y:n}){tr(e.x,t.translate,t.scale,t.originPoint),tr(e.y,n.translate,n.scale,n.originPoint)}const Ai=.999999999999,ki=1.0000000000001;function vd(e,t,n,s=!1){const r=n.length;if(!r)return;t.x=t.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Zt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,Aa(e,i)),s&&Nt(o.latestValues)&&Zt(e,o.latestValues))}t.x<ki&&t.x>Ai&&(t.x=1),t.y<ki&&t.y>Ai&&(t.y=1)}function Jt(e,t){e.min=e.min+t,e.max=e.max+t}function Mi(e,t,n,s,r=.5){const o=fe(e.min,e.max,r);tr(e,t,n,o,s)}function Zt(e,t){Mi(e.x,t.x,t.scaleX,t.scale,t.originX),Mi(e.y,t.y,t.scaleY,t.scale,t.originY)}function ka(e,t){return Ca(bd(e.getBoundingClientRect(),t))}function wd(e,t,n){const s=ka(e,n),{scroll:r}=t;return r&&(Jt(s.x,r.offset.x),Jt(s.y,r.offset.y)),s}const Ei=()=>({translate:0,scale:1,origin:0,originPoint:0}),Qt=()=>({x:Ei(),y:Ei()}),Ni=()=>({min:0,max:0}),pe=()=>({x:Ni(),y:Ni()}),nr={current:null},Ma={current:!1};function Td(){if(Ma.current=!0,!!dr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>nr.current=e.matches;e.addEventListener("change",t),t()}else nr.current=!1}const Sd=new WeakMap;function jd(e,t,n){for(const s in t){const r=t[s],o=n[s];if(Se(r))e.addValue(s,r);else if(Se(o))e.addValue(s,nn(r,{owner:e}));else if(o!==r)if(e.hasValue(s)){const i=e.getValue(s);i.liveStyle===!0?i.jump(r):i.hasAnimated||i.set(r)}else{const i=e.getStaticValue(s);e.addValue(s,nn(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Di=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Cd{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=kr,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const m=Ee.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,ue.render(this.render,!1,!0))};const{latestValues:c,renderState:u}=i;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=u,this.parent=t,this.props=n,this.presenceContext=s,this.depth=t?t.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=xs(n),this.isVariantNode=ma(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:d,...h}=this.scrapeMotionValuesFromProps(n,{},this);for(const m in h){const p=h[m];c[m]!==void 0&&Se(p)&&p.set(c[m])}}mount(t){this.current=t,Sd.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),Ma.current||Td(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:nr.current,process.env.NODE_ENV!=="production"&&gr(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(),xt(this.notifyUpdate),xt(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const n=this.features[t];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const s=cn.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&ue.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in sn){const n=sn[t];if(!n)continue;const{isEnabled:s,Feature:r}=n;if(!this.features[t]&&r&&s(this.props)&&(this.features[t]=new r(this)),this.features[t]){const o=this.features[t];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):pe()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<Di.length;s++){const r=Di[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=t[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=jd(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const s=this.values.get(t);n!==s&&(s&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let s=this.values.get(t);return s===void 0&&n!==void 0&&(s=nn(n===null?void 0:n,{owner:this}),this.addValue(t,s)),s}readValue(t,n){let s=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return s!=null&&(typeof s=="string"&&(To(s)||jo(s))?s=parseFloat(s):!Du(s)&&bt.test(n)&&(s=ia(t,n)),this.setBaseTarget(t,Se(s)?s.get():s)),Se(s)?s.get():s}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const o=Br(this.props,n,this.presenceContext?.custom);o&&(s=o[t])}if(n&&s!==void 0)return s;const r=this.getBaseTargetFromProps(this.props,t);return r!==void 0&&!Se(r)?r:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new pr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Nr.render(this.render)}}class Ea extends Cd{constructor(){super(...arguments),this.KeyframeResolver=vu}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:s}){delete n[t],delete s[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Se(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Na(e,{style:t,vars:n},s,r){const o=e.style;let i;for(i in t)o[i]=t[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function Pd(e){return window.getComputedStyle(e)}class Ad extends Ea{constructor(){super(...arguments),this.type="html",this.renderInstance=Na}readValueFromInstance(t,n){if(cn.has(n))return this.projection?.isProjecting?qs(n):Ll(t,n);{const s=Pd(t),r=(br(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return ka(t,n)}build(t,n,s){$r(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return zr(t,n,s)}}const Da=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 kd(e,t,n,s){Na(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(Da.has(r)?r:Ur(r),t.attrs[r])}class Md extends Ea{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=pe}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(cn.has(n)){const s=ra(n);return s&&s.default||0}return n=Da.has(n)?n:Ur(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return wa(t,n,s)}build(t,n,s){ya(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){kd(t,n,s,r)}mount(t){this.isSVGTag=ba(t.tagName),super.mount(t)}}const Ra=(e,t)=>Fr(e)?new Md(t):new Ad(t,{allowProjection:e!==f.Fragment});function tn(e,t,n){const s=e.getProps();return Br(s,t,n!==void 0?n:s.custom,e)}const sr=e=>Array.isArray(e);function Ed(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,nn(n))}function Nd(e){return sr(e)?e[e.length-1]||0:e}function Dd(e,t){const n=tn(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Nd(o[i]);Ed(e,i,a)}}function Rd(e){return!!(Se(e)&&e.add)}function rr(e,t){const n=e.getValue("willChange");if(Rd(n))return n.add(t);if(!n&&it.WillChange){const s=new it.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Va(e){return e.props[Ta]}const Vd=e=>e!==null;function Id(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Vd),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const Od={type:"spring",stiffness:500,damping:25,restSpeed:10},$d=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Ld={type:"keyframes",duration:.8},Fd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Bd=(e,{keyframes:t})=>t.length>2?Ld:cn.has(e)?e.startsWith("scale")?$d(t[1]):Od:Fd;function zd({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:c,elapsed:u,...d}){return!!Object.keys(d).length}const _r=(e,t,n,s={},r,o)=>i=>{const a=Mr(s,e)||{},c=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-Ye(c);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-u,onUpdate:m=>{t.set(m),a.onUpdate&&a.onUpdate(m)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:r};zd(a)||Object.assign(d,Bd(e,d)),d.duration&&(d.duration=Ye(d.duration)),d.repeatDelay&&(d.repeatDelay=Ye(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let h=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(Js(d),d.delay===0&&(h=!0)),(it.instantAnimations||it.skipAnimations)&&(h=!0,Js(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const m=Id(d.keyframes,a);if(m!==void 0){ue.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new Ar(d):new au(d)};function Ud({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function Ia(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const c=[],u=r&&e.animationState&&e.animationState.getState()[r];for(const d in a){const h=e.getValue(d,e.latestValues[d]??null),m=a[d];if(m===void 0||u&&Ud(u,d))continue;const p={delay:n,...Mr(o||{},d)},w=h.get();if(w!==void 0&&!h.isAnimating&&!Array.isArray(m)&&m===w&&!p.velocity)continue;let x=!1;if(window.MotionHandoffAnimation){const y=Va(e);if(y){const j=window.MotionHandoffAnimation(y,d,ue);j!==null&&(p.startTime=j,x=!0)}}rr(e,d),h.start(_r(d,h,m,e.shouldReduceMotion&&ta.has(d)?{type:!1}:p,e,x));const b=h.animation;b&&c.push(b)}return i&&Promise.all(c).then(()=>{ue.update(()=>{i&&Dd(e,i)})}),c}function Oa(e,t,n,s=0,r=1){const o=Array.from(e).sort((u,d)=>u.sortNodePosition(d)).indexOf(t),i=e.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function ir(e,t,n={}){const s=tn(e,t,n.type==="exit"?e.presenceContext?.custom:void 0);let{transition:r=e.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(r=n.transitionOverride);const o=s?()=>Promise.all(Ia(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=r;return _d(e,t,c,u,d,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 _d(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const c of e.variantChildren)c.notify("AnimationStart",t),a.push(ir(c,t,{...i,delay:n+(typeof s=="function"?0:s)+Oa(e.variantChildren,c,s,r,o)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(a)}function Xd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>ir(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=ir(e,t,n);else{const r=typeof t=="function"?tn(e,t,n.custom):t;s=Promise.all(Ia(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function $a(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(t[s]!==e[s])return!1;return!0}const Wd=Or.length;function La(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?La(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<Wd;n++){const s=Or[n],r=e.props[s];($n(r)||r===!1)&&(t[s]=r)}return t}const qd=[...Ir].reverse(),Kd=Ir.length;function Gd(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Xd(e,n,s)))}function Yd(e){let t=Gd(e),n=Ri(),s=!0;const r=c=>(u,d)=>{const h=tn(e,d,c==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:m,transitionEnd:p,...w}=h;u={...u,...w,...p}}return u};function o(c){t=c(e)}function i(c){const{props:u}=e,d=La(e.parent)||{},h=[],m=new Set;let p={},w=1/0;for(let b=0;b<Kd;b++){const y=qd[b],j=n[y],M=u[y]!==void 0?u[y]:d[y],E=$n(M),D=y===c?j.isActive:null;D===!1&&(w=b);let F=M===d[y]&&M!==u[y]&&E;if(F&&s&&e.manuallyAnimateOnMount&&(F=!1),j.protectedKeys={...p},!j.isActive&&D===null||!M&&!j.prevProp||ys(M)||typeof M=="boolean")continue;const B=Hd(j.prevProp,M);let P=B||y===c&&j.isActive&&!F&&E||b>w&&E,z=!1;const T=Array.isArray(M)?M:[M];let V=T.reduce(r(y),{});D===!1&&(V={});const{prevResolvedValues:O={}}=j,R={...O,...V},W=Y=>{P=!0,m.has(Y)&&(z=!0,m.delete(Y)),j.needsAnimating[Y]=!0;const te=e.getValue(Y);te&&(te.liveStyle=!1)};for(const Y in R){const te=V[Y],J=O[Y];if(p.hasOwnProperty(Y))continue;let be=!1;sr(te)&&sr(J)?be=!$a(te,J):be=te!==J,be?te!=null?W(Y):m.add(Y):te!==void 0&&m.has(Y)?W(Y):j.protectedKeys[Y]=!0}j.prevProp=M,j.prevResolvedValues=V,j.isActive&&(p={...p,...V}),s&&e.blockInitialAnimation&&(P=!1);const oe=F&&B;P&&(!oe||z)&&h.push(...T.map(Y=>{const te={type:y};if(typeof Y=="string"&&s&&!oe&&e.manuallyAnimateOnMount&&e.parent){const{parent:J}=e,be=tn(J,Y);if(J.enteringChildren&&be){const{delayChildren:He}=be.transition||{};te.delay=Oa(J.enteringChildren,e,He)}}return{animation:Y,options:te}}))}if(m.size){const b={};if(typeof u.initial!="boolean"){const y=tn(e,Array.isArray(u.initial)?u.initial[0]:u.initial);y&&y.transition&&(b.transition=y.transition)}m.forEach(y=>{const j=e.getBaseTarget(y),M=e.getValue(y);M&&(M.liveStyle=!0),b[y]=j??null}),h.push({animation:b})}let x=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(x=!1),s=!1,x?t(h):Promise.resolve()}function a(c,u){if(n[c].isActive===u)return Promise.resolve();e.variantChildren?.forEach(h=>h.animationState?.setActive(c,u)),n[c].isActive=u;const d=i(c);for(const h in n)n[h].protectedKeys={};return d}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Ri()}}}function Hd(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!$a(t,e):!1}function Mt(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Ri(){return{animate:Mt(!0),whileInView:Mt(),whileHover:Mt(),whileTap:Mt(),whileDrag:Mt(),whileFocus:Mt(),exit:Mt()}}class vt{constructor(t){this.isMounted=!1,this.node=t}update(){}}class Jd extends vt{constructor(t){super(t),t.animationState||(t.animationState=Yd(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();ys(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Zd=0;class Qd extends vt{constructor(){super(...arguments),this.id=Zd++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const Fa={animation:{Feature:Jd},exit:{Feature:Qd}};function Fn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function _n(e){return{point:{x:e.pageX,y:e.pageY}}}const eh=e=>t=>Dr(t)&&e(t,_n(t));function Mn(e,t,n,s){return Fn(e,t,eh(n),s)}const Ba=1e-4,th=1-Ba,nh=1+Ba,za=.01,sh=0-za,rh=0+za;function Pe(e){return e.max-e.min}function ih(e,t,n){return Math.abs(e-t)<=n}function Vi(e,t,n,s=.5){e.origin=s,e.originPoint=fe(t.min,t.max,e.origin),e.scale=Pe(n)/Pe(t),e.translate=fe(n.min,n.max,e.origin)-e.originPoint,(e.scale>=th&&e.scale<=nh||isNaN(e.scale))&&(e.scale=1),(e.translate>=sh&&e.translate<=rh||isNaN(e.translate))&&(e.translate=0)}function En(e,t,n,s){Vi(e.x,t.x,n.x,s?s.originX:void 0),Vi(e.y,t.y,n.y,s?s.originY:void 0)}function Ii(e,t,n){e.min=n.min+t.min,e.max=e.min+Pe(t)}function oh(e,t,n){Ii(e.x,t.x,n.x),Ii(e.y,t.y,n.y)}function Oi(e,t,n){e.min=t.min-n.min,e.max=e.min+Pe(t)}function Nn(e,t,n){Oi(e.x,t.x,n.x),Oi(e.y,t.y,n.y)}function Be(e){return[e("x"),e("y")]}const Ua=({current:e})=>e?e.ownerDocument.defaultView:null,$i=(e,t)=>Math.abs(e-t);function ah(e,t){const n=$i(e.x,t.x),s=$i(e.y,t.y);return Math.sqrt(n**2+s**2)}class _a{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const m=Ns(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,w=ah(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!w)return;const{point:x}=m,{timestamp:b}=we;this.history.push({...x,timestamp:b});const{onStart:y,onMove:j}=this.handlers;p||(y&&y(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),j&&j(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=Es(p,this.transformPagePoint),ue.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:w,onSessionEnd:x,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Ns(m.type==="pointercancel"?this.lastMoveEventInfo:Es(p,this.transformPagePoint),this.history);this.startEvent&&w&&w(m,y),x&&x(m,y)},!Dr(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=_n(t),c=Es(a,this.transformPagePoint),{point:u}=c,{timestamp:d}=we;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=n;h&&h(t,Ns(c,this.history)),this.removeListeners=Bn(Mn(this.contextWindow,"pointermove",this.handlePointerMove),Mn(this.contextWindow,"pointerup",this.handlePointerUp),Mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),xt(this.updatePoint)}}function Es(e,t){return t?{point:t(e.point)}:e}function Li(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Ns({point:e},t){return{point:e,delta:Li(e,Xa(t)),offset:Li(e,ch(t)),velocity:lh(t,.1)}}function ch(e){return e[0]}function Xa(e){return e[e.length-1]}function lh(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Xa(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>Ye(t)));)n--;if(!s)return{x:0,y:0};const o=ze(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 uh(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?fe(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?fe(n,e,s.max):Math.min(e,n)),e}function Fi(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function dh(e,{top:t,left:n,bottom:s,right:r}){return{x:Fi(e.x,n,r),y:Fi(e.y,t,s)}}function Bi(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function hh(e,t){return{x:Bi(e.x,t.x),y:Bi(e.y,t.y)}}function fh(e,t){let n=.5;const s=Pe(e),r=Pe(t);return r>s?n=Vn(t.min,t.max-s,e.min):s>r&&(n=Vn(e.min,e.max-r,t.min)),st(0,1,n)}function mh(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const or=.35;function ph(e=or){return e===!1?e=0:e===!0&&(e=or),{x:zi(e,"left","right"),y:zi(e,"top","bottom")}}function zi(e,t,n){return{min:Ui(e,t),max:Ui(e,n)}}function Ui(e,t){return typeof e=="number"?e:e[t]||0}const gh=new WeakMap;class yh{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=pe(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const o=h=>{const{dragSnapToOrigin:m}=this.getProps();m?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(_n(h).point)},i=(h,m)=>{const{drag:p,dragPropagation:w,onDragStart:x}=this.getProps();if(p&&!w&&(this.openDragLock&&this.openDragLock(),this.openDragLock=ju(p),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Be(y=>{let j=this.getAxisMotionValue(y).get()||0;if(Qe.test(j)){const{projection:M}=this.visualElement;if(M&&M.layout){const E=M.layout.layoutBox[y];E&&(j=Pe(E)*(parseFloat(j)/100))}}this.originPoint[y]=j}),x&&ue.postRender(()=>x(h,m)),rr(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:w,onDirectionLock:x,onDrag:b}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=m;if(w&&this.currentDirection===null){this.currentDirection=xh(y),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",m.point,y),this.updateAxis("y",m.point,y),this.visualElement.render(),b&&b(h,m)},c=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>Be(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:d}=this.getProps();this.panSession=new _a(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Ua(this.visualElement)})}stop(t,n){const s=t||this.latestPointerEvent,r=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!r||!s)return;const{velocity:i}=r;this.startAnimation(i);const{onDragEnd:a}=this.getProps();a&&ue.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,s){const{drag:r}=this.getProps();if(!s||!ts(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=uh(i,this.constraints[t],this.elastic[t])),o.set(i)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&Ht(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=dh(s.layoutBox,t):this.constraints=!1,this.elastic=ph(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Be(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=mh(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Ht(t))return!1;const s=t.current;rt(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=wd(s,r.root,this.visualElement.getTransformPagePoint());let i=hh(r.layout.layoutBox,o);if(n){const a=n(xd(i));this.hasMutatedConstraints=!!a,a&&(i=Ca(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},u=Be(d=>{if(!ts(d,n,this.currentDirection))return;let h=c&&c[d]||{};i&&(h={min:0,max:0});const m=r?200:1e6,p=r?40:1e7,w={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(d,w)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return rr(this.visualElement,t),s.start(_r(t,s,0,n,this.visualElement,!1))}stopAnimation(){Be(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Be(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){Be(n=>{const{drag:s}=this.getProps();if(!ts(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,o=this.getAxisMotionValue(n);if(r&&r.layout){const{min:i,max:a}=r.layout.layoutBox[n];o.set(t[n]-fe(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Ht(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Be(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const c=a.get();r[i]=fh({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(),Be(i=>{if(!ts(i,t,null))return;const a=this.getAxisMotionValue(i),{min:c,max:u}=this.constraints[i];a.set(fe(c,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;gh.set(this.visualElement,this);const t=this.visualElement.current,n=Mn(t,"pointerdown",c=>{const{drag:u,dragListener:d=!0}=this.getProps();u&&d&&this.start(c)}),s=()=>{const{dragConstraints:c}=this.getProps();Ht(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()),ue.read(s);const i=Fn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(Be(d=>{const h=this.getAxisMotionValue(d);h&&(this.originPoint[d]+=c[d].translate,h.set(h.get()+c[d].translate))}),this.visualElement.render())});return()=>{i(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:o=!1,dragElastic:i=or,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function ts(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function xh(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class bh extends vt{constructor(t){super(t),this.removeGroupControls=Ue,this.removeListeners=Ue,this.controls=new yh(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ue}unmount(){this.removeGroupControls(),this.removeListeners()}}const _i=e=>(t,n)=>{e&&ue.postRender(()=>e(t,n))};class vh extends vt{constructor(){super(...arguments),this.removePointerDownListener=Ue}onPointerDown(t){this.session=new _a(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ua(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:_i(t),onStart:_i(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&ue.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=Mn(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const as={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Xi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Cn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(q.test(e))e=parseFloat(e);else return e;const n=Xi(e,t.target.x),s=Xi(e,t.target.y);return`${n}% ${s}%`}},wh={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=bt.parse(e);if(r.length>5)return s;const o=bt.createTransformer(e),i=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,c=n.y.scale*t.y;r[0+i]/=a,r[1+i]/=c;const u=fe(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 Th extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;qu(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()})),as.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Ds=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||ue.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Nr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Ds=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Wa(e){const[t,n]=ha(),s=f.useContext(lr);return l.jsx(Th,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(Sa),isPresent:t,safeToRemove:n})}const Sh={borderRadius:{...Cn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Cn,borderTopRightRadius:Cn,borderBottomLeftRadius:Cn,borderBottomRightRadius:Cn,boxShadow:wh};function jh(e,t,n){const s=Se(e)?e:nn(e);return s.start(_r("",s,t,n)),s.animation}const Ch=(e,t)=>e.depth-t.depth;class Ph{constructor(){this.children=[],this.isDirty=!1}add(t){hr(this.children,t),this.isDirty=!0}remove(t){fr(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Ch),this.isDirty=!1,this.children.forEach(t)}}function Ah(e,t){const n=Ee.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(xt(s),e(o-t))};return ue.setup(s,!0),()=>xt(s)}const qa=["TopLeft","TopRight","BottomLeft","BottomRight"],kh=qa.length,Wi=e=>typeof e=="string"?parseFloat(e):e,qi=e=>typeof e=="number"||q.test(e);function Mh(e,t,n,s,r,o){r?(e.opacity=fe(0,n.opacity??1,Eh(s)),e.opacityExit=fe(t.opacity??1,0,Nh(s))):o&&(e.opacity=fe(t.opacity??1,n.opacity??1,s));for(let i=0;i<kh;i++){const a=`border${qa[i]}Radius`;let c=Ki(t,a),u=Ki(n,a);if(c===void 0&&u===void 0)continue;c||(c=0),u||(u=0),c===0||u===0||qi(c)===qi(u)?(e[a]=Math.max(fe(Wi(c),Wi(u),s),0),(Qe.test(u)||Qe.test(c))&&(e[a]+="%")):e[a]=u}(t.rotate||n.rotate)&&(e.rotate=fe(t.rotate||0,n.rotate||0,s))}function Ki(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Eh=Ka(0,.5,Do),Nh=Ka(.5,.95,Ue);function Ka(e,t,n){return s=>s<e?0:s>t?1:n(Vn(e,t,s))}function Gi(e,t){e.min=t.min,e.max=t.max}function Fe(e,t){Gi(e.x,t.x),Gi(e.y,t.y)}function Yi(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function Hi(e,t,n,s,r){return e-=t,e=fs(e,1/n,s),r!==void 0&&(e=fs(e,1/r,s)),e}function Dh(e,t=0,n=1,s=.5,r,o=e,i=e){if(Qe.test(t)&&(t=parseFloat(t),t=fe(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=fe(o.min,o.max,s);e===o&&(a-=t),e.min=Hi(e.min,t,n,a,r),e.max=Hi(e.max,t,n,a,r)}function Ji(e,t,[n,s,r],o,i){Dh(e,t[n],t[s],t[r],t.scale,o,i)}const Rh=["x","scaleX","originX"],Vh=["y","scaleY","originY"];function Zi(e,t,n,s){Ji(e.x,t,Rh,n?n.x:void 0,s?s.x:void 0),Ji(e.y,t,Vh,n?n.y:void 0,s?s.y:void 0)}function Qi(e){return e.translate===0&&e.scale===1}function Ga(e){return Qi(e.x)&&Qi(e.y)}function eo(e,t){return e.min===t.min&&e.max===t.max}function Ih(e,t){return eo(e.x,t.x)&&eo(e.y,t.y)}function to(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Ya(e,t){return to(e.x,t.x)&&to(e.y,t.y)}function no(e){return Pe(e.x)/Pe(e.y)}function so(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class Oh{constructor(){this.members=[]}add(t){hr(this.members,t),t.scheduleRender()}remove(t){if(fr(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(r=>t===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(t,n){const s=this.lead;if(t!==s&&(this.prevLead=s,this.lead=t,t.show(),s)){s.instance&&s.scheduleRender(),t.scheduleRender(),t.resumeFrom=s,n&&(t.resumeFrom.preserveOpacity=!0),s.snapshot&&(t.snapshot=s.snapshot,t.snapshot.latestValues=s.animationValues||s.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:r}=t.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:s}=t;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function $h(e,t,n){let s="";const r=e.x.translate/t.x,o=e.y.translate/t.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:u,rotate:d,rotateX:h,rotateY:m,skewX:p,skewY:w}=n;u&&(s=`perspective(${u}px) ${s}`),d&&(s+=`rotate(${d}deg) `),h&&(s+=`rotateX(${h}deg) `),m&&(s+=`rotateY(${m}deg) `),p&&(s+=`skewX(${p}deg) `),w&&(s+=`skewY(${w}deg) `)}const a=e.x.scale*t.x,c=e.y.scale*t.y;return(a!==1||c!==1)&&(s+=`scale(${a}, ${c})`),s||"none"}const Rs=["","X","Y","Z"],Lh=1e3;let Fh=0;function Vs(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function Ha(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Va(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",ue,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&Ha(s)}function Ja({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=Fh++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(Uh),this.nodes.forEach(qh),this.nodes.forEach(Kh),this.nodes.forEach(_h)},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 Ph)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new pr),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=da(i)&&!Eu(i),this.instance=i;const{layoutId:a,layout:c,visualElement:u}=this.options;if(u&&!u.current&&u.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),e){let d,h=0;const m=()=>this.root.updateBlockedByResize=!1;ue.read(()=>{h=window.innerWidth}),e(i,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,d&&d(),d=Ah(m,250),as.hasAnimatedSinceResize&&(as.hasAnimatedSinceResize=!1,this.nodes.forEach(oo)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||c)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const w=this.options.transition||u.getDefaultTransition()||Zh,{onLayoutAnimationStart:x,onLayoutAnimationComplete:b}=u.getProps(),y=!this.targetLayout||!Ya(this.targetLayout,p),j=!h&&m;if(this.options.layoutRoot||this.resumeFrom||j||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const M={...Mr(w,"layout"),onPlay:x,onComplete:b};(u.shouldReduceMotion||this.options.layoutRoot)&&(M.delay=0,M.type=!1),this.startAnimation(M),this.setAnimationOrigin(d,j)}else h||oo(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}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(),xt(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(Gh),this.animationId++)}getTransformTemplate(){const{visualElement:i}=this.options;return i&&i.getProps().transformTemplate}willUpdate(i=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Ha(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const h=this.path[d];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:a,layout: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(ro);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(io);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Wh),this.nodes.forEach(Bh),this.nodes.forEach(zh)):this.nodes.forEach(io),this.clearAllSnapshots();const a=Ee.now();we.delta=st(0,1e3/60,a-we.timestamp),we.timestamp=a,we.isProcessing=!0,Ts.update.process(we),Ts.preRender.process(we),Ts.render.process(we),we.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Nr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Xh),this.sharedNodes.forEach(Yh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ue.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ue.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Pe(this.snapshot.measuredBox.x)&&!Pe(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=pe(),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&&!Ga(this.projectionDelta),c=this.getTransformTemplate(),u=c?c(this.latestValues,""):void 0,d=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Nt(this.latestValues)||d)&&(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)),Qh(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return pe();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(ef))){const{scroll:u}=this.root;u&&(Jt(a.x,u.offset.x),Jt(a.y,u.offset.y))}return a}removeElementScroll(i){const a=pe();if(Fe(a,i),this.scroll?.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&Fe(a,i),Jt(a.x,d.offset.x),Jt(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const c=pe();Fe(c,i);for(let u=0;u<this.path.length;u++){const d=this.path[u];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&Zt(c,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Nt(d.latestValues)&&Zt(c,d.latestValues)}return Nt(this.latestValues)&&Zt(c,this.latestValues),c}removeTransform(i){const a=pe();Fe(a,i);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!u.instance||!Nt(u.latestValues))continue;er(u.latestValues)&&u.updateSnapshot();const d=pe(),h=u.measurePageBox();Fe(d,h),Zi(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,d)}return Nt(this.latestValues)&&Zi(a,this.latestValues),a}setTargetDelta(i){this.targetDelta=i,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(i){this.options={...this.options,...i,crossfade:i.crossfade!==void 0?i.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==we.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(i=!1){const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(i||c&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:d,layoutId:h}=this.options;if(!(!this.layout||!(d||h))){if(this.resolvedRelativeTargetAt=we.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=pe(),this.relativeTargetOrigin=pe(),Nn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Fe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=pe(),this.targetWithTransforms=pe()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),oh(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Fe(this.target,this.layout.layoutBox),Aa(this.target,this.targetDelta)):Fe(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const m=this.getClosestProjectingParent();m&&!!m.resumingFrom==!!this.resumingFrom&&!m.options.layoutScroll&&m.target&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=pe(),this.relativeTargetOrigin=pe(),Nn(this.relativeTargetOrigin,this.target,m.target),Fe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||er(this.parent.latestValues)||Pa(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===we.timestamp&&(c=!1),c)return;const{layout:u,layoutId:d}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(u||d))return;Fe(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,m=this.treeScale.y;vd(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=pe());const{target:p}=i;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Yi(this.prevProjectionDelta.x,this.projectionDelta.x),Yi(this.prevProjectionDelta.y,this.projectionDelta.y)),En(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==m||!so(this.projectionDelta.x,this.prevProjectionDelta.x)||!so(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(i=!0){if(this.options.visualElement?.scheduleRender(),i){const a=this.getStack();a&&a.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Qt(),this.projectionDelta=Qt(),this.projectionDeltaWithTransform=Qt()}setAnimationOrigin(i,a=!1){const c=this.snapshot,u=c?c.latestValues:{},d={...this.latestValues},h=Qt();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=pe(),p=c?c.source:void 0,w=this.layout?this.layout.source:void 0,x=p!==w,b=this.getStack(),y=!b||b.members.length<=1,j=!!(x&&!y&&this.options.crossfade===!0&&!this.path.some(Jh));this.animationProgress=0;let M;this.mixTargetDelta=E=>{const D=E/1e3;ao(h.x,i.x,D),ao(h.y,i.y,D),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Nn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Hh(this.relativeTarget,this.relativeTargetOrigin,m,D),M&&Ih(this.relativeTarget,M)&&(this.isProjectionDirty=!1),M||(M=pe()),Fe(M,this.relativeTarget)),x&&(this.animationValues=d,Mh(d,u,this.latestValues,D,j,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=D},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(xt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ue.update(()=>{as.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=nn(0)),this.currentAnimation=jh(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(Lh),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:c,layout:u,latestValues:d}=i;if(!(!a||!c||!u)){if(this!==i&&this.layout&&u&&Za(this.options.animationType,this.layout.layoutBox,u.layoutBox)){c=this.target||pe();const h=Pe(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+h;const m=Pe(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+m}Fe(a,c),Zt(a,d),En(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new Oh),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&&Vs("z",i,u,this.animationValues);for(let d=0;d<Rs.length;d++)Vs(`rotate${Rs[d]}`,i,u,this.animationValues),Vs(`skew${Rs[d]}`,i,u,this.animationValues);i.render();for(const d in u)i.setStaticValue(d,u[d]),this.animationValues&&(this.animationValues[d]=u[d]);i.scheduleRender()}applyProjectionStyles(i,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){i.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,i.visibility="",i.opacity="",i.pointerEvents=is(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=is(a?.pointerEvents)||""),this.hasProjected&&!Nt(this.latestValues)&&(i.transform=c?c({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=$h(this.projectionDeltaWithTransform,this.treeScale,d);c&&(h=c(d,h)),i.transform=h;const{x:m,y:p}=this.projectionDelta;i.transformOrigin=`${m.origin*100}% ${p.origin*100}% 0`,u.animationValues?i.opacity=u===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:i.opacity=u===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const w in Ln){if(d[w]===void 0)continue;const{correct:x,applyTo:b,isCSSVariable:y}=Ln[w],j=h==="none"?d[w]:x(d[w],u);if(b){const M=b.length;for(let E=0;E<M;E++)i[b[E]]=j}else y?this.options.visualElement.renderState.vars[w]=j:i[w]=j}this.options.layoutId&&(i.pointerEvents=u===this?is(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(ro),this.root.sharedNodes.clear()}}}function Bh(e){e.updateLayout()}function zh(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:r}=e.options,o=t.source!==e.layout.source;r==="size"?Be(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=Pe(h);h.min=n[d].min,h.max=h.min+m}):Za(r,t.layoutBox,n)&&Be(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=Pe(n[d]);h.max=h.min+m,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[d].max=e.relativeTarget[d].min+m)});const i=Qt();En(i,n,t.layoutBox);const a=Qt();o?En(a,e.applyTransform(s,!0),t.measuredBox):En(a,n,t.layoutBox);const c=!Ga(i);let u=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:m}=d;if(h&&m){const p=pe();Nn(p,t.layoutBox,h.layoutBox);const w=pe();Nn(w,n,m.layoutBox),Ya(p,w)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=w,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function Uh(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function _h(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Xh(e){e.clearSnapshot()}function ro(e){e.clearMeasurements()}function io(e){e.isLayoutDirty=!1}function Wh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function oo(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function qh(e){e.resolveTargetDelta()}function Kh(e){e.calcProjection()}function Gh(e){e.resetSkewAndRotation()}function Yh(e){e.removeLeadSnapshot()}function ao(e,t,n){e.translate=fe(t.translate,0,n),e.scale=fe(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function co(e,t,n,s){e.min=fe(t.min,n.min,s),e.max=fe(t.max,n.max,s)}function Hh(e,t,n,s){co(e.x,t.x,n.x,s),co(e.y,t.y,n.y,s)}function Jh(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const Zh={duration:.45,ease:[.4,0,.1,1]},lo=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),uo=lo("applewebkit/")&&!lo("chrome/")?Math.round:Ue;function ho(e){e.min=uo(e.min),e.max=uo(e.max)}function Qh(e){ho(e.x),ho(e.y)}function Za(e,t,n){return e==="position"||e==="preserve-aspect"&&!ih(no(t),no(n),.2)}function ef(e){return e!==e.root&&e.scroll?.wasRoot}const tf=Ja({attachResizeListener:(e,t)=>Fn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Is={current:void 0},Qa=Ja({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Is.current){const e=new tf({});e.mount(window),e.setOptions({layoutScroll:!0}),Is.current=e}return Is.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),nf={pan:{Feature:vh},drag:{Feature:bh,ProjectionNode:Qa,MeasureLayout:Wa}};function fo(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,o=s[r];o&&ue.postRender(()=>o(t,_n(t)))}class sf extends vt{mount(){const{current:t}=this.node;t&&(this.unmount=Cu(t,(n,s)=>(fo(this.node,s,"Start"),r=>fo(this.node,r,"End"))))}unmount(){}}class rf extends vt{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Bn(Fn(this.node.current,"focus",()=>this.onFocus()),Fn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mo(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),o=s[r];o&&ue.postRender(()=>o(t,_n(t)))}class of extends vt{mount(){const{current:t}=this.node;t&&(this.unmount=Mu(t,(n,s)=>(mo(this.node,s,"Start"),(r,{success:o})=>mo(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ar=new WeakMap,Os=new WeakMap,af=e=>{const t=ar.get(e.target);t&&t(e)},cf=e=>{e.forEach(af)};function lf({root:e,...t}){const n=e||document;Os.has(n)||Os.set(n,{});const s=Os.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(cf,{root:e,...t})),s[r]}function uf(e,t,n){const s=lf(t);return ar.set(e,n),s.observe(e),()=>{ar.delete(e),s.unobserve(e)}}const df={some:0,all:1};class hf extends vt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=t,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:df[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:d,onViewportLeave:h}=this.node.getProps(),m=u?d:h;m&&m(c)};return uf(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(ff(t,n))&&this.startObserver()}unmount(){}}function ff({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const ec={inView:{Feature:hf},tap:{Feature:of},focus:{Feature:rf},hover:{Feature:sf}},mf={layout:{ProjectionNode:Qa,MeasureLayout:Wa}},pf={...Fa,...ec,...nf,...mf},gf=yd(pf,Ra),yf={renderer:Ra,...Fa,...ec};function Xr(e,t){return os(e,t)}const xf=Xr("button"),ns=Xr("div"),bf=Xr("p"),Ze=Symbol.for("@arcteninc/core:originalName");function vf(e,t){return e[Ze]=t,e}function wf(e,t,n,s){if(typeof e!="function")return null;const r=e[Ze];if(r){const a=t[r];if(a&&!n.has(a.name))return{fn:e,meta:a}}const o=e.name;let i;if(o&&(i=t[o],i&&!n.has(i.name)))return e[Ze]=i.name,{fn:e,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=t[a],i))return e[Ze]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(c=>!n.has(c.name)),i)return e[Ze]=i.name,{fn:e,meta:i};return null}function tc(e,t){let n,s;if(!t)throw new Error(`❌ toolMetadata is required!
10
10
 
11
11
  Please:
12
12
  1. Run "arcten-extract-types ." before build (add to package.json scripts)
@@ -15,10 +15,10 @@ Please:
15
15
  3. Pass it to useAgent/ArctenAgent:
16
16
  useAgent({ tools: [...], toolMetadata: toolMetadata })
17
17
  (Pass the full object for better minification support, or toolMetadata.functions for backward compatibility)
18
- `);if("functions"in t&&typeof t.functions=="object"){const o=t;n=o.functions,s=o.toolOrder}else n=t,s=void 0;const r=new Set;return e.map(o=>{const i=wf(o,n,r,s);if(!i){const a=o.name,u=o[Qe]||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 Tf({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return l.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:l.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&l.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>l.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[l.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),l.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),l.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[l.jsxs(Se,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[l.jsx(ie.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),l.jsx(Se,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:l.jsx(ie.X,{className:"h-3 w-3"})})]})]})})}function Sf({toolName:e,args:t,isDenied:n,isSafe:s}){const[r,o]=f.useState(!1);if(e==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];e==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(t).filter(([u])=>!i.includes(u))),c=Object.keys(a).length>0;return l.jsxs("div",{className:"my-1",children:[l.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&&l.jsx("span",{className:"transition-transform duration-200",children:r?l.jsx(ie.ChevronDown,{className:"h-3 w-3"}):l.jsx(ie.ChevronRight,{className:"h-3 w-3"})}),n?l.jsx(ie.X,{className:"h-3 w-3"}):s?l.jsx(ie.Zap,{className:"h-3 w-3"}):l.jsx(ie.Check,{className:"h-3 w-3"}),l.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&c&&l.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:l.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,d])=>l.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[l.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),l.jsx("span",{className:"font-mono text-foreground",children:typeof d=="string"?d:JSON.stringify(d)})]},u))})})]})}function jf({...e}){return l.jsx(cr.Root,{"data-slot":"collapsible",...e})}function Cf({...e}){return l.jsx(cr.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function Pf({...e}){return l.jsx(cr.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const Af=f.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Wr=f.memo(({className:e,...t})=>typeof window>"u"?null:l.jsx(f.Suspense,{fallback:null,children:l.jsx(Af,{className:ae("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Wr.displayName="Response";const kf=Object.freeze(Object.defineProperty({__proto__:null,Response:Wr},Symbol.toStringTag,{value:"Module"})),Mf=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=gf.create(t),i=f.useMemo(()=>(e?.length??0)*r,[e,r]);return l.jsx(o,{animate:{backgroundPosition:"0% center"},className:ae("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:e})},Ef=f.memo(Mf),nc=f.createContext(null),Nf=()=>{const e=f.useContext(nc);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},Df=1e3,Rf=1e3,sc=f.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,u]=Jr.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,h]=Jr.useControllableState({prop:o,defaultProp:0}),[m,p]=f.useState(!1),[w,x]=f.useState(null);f.useEffect(()=>{t?w===null&&x(Date.now()):w!==null&&(h(Math.ceil((Date.now()-w)/Rf)),x(null))},[t,w,h]),f.useEffect(()=>{if(s&&!t&&c&&!m){const y=setTimeout(()=>{u(!1),p(!0)},Df);return()=>clearTimeout(y)}},[t,c,s,u,m]);const b=y=>{u(y)};return l.jsx(nc.Provider,{value:{isStreaming:t,isOpen:c,setIsOpen:u,duration:d},children:l.jsx(jf,{className:ae("not-prose mb-4",e),onOpenChange:b,open:c,...a,children:i})})}),Vf=(e,t)=>e||t===0?l.jsx(Ef,{duration:1,children:"Thinking..."}):t===void 0?l.jsx("p",{children:"Thought for a few seconds"}):l.jsxs("p",{children:["Thought for ",t," seconds"]}),rc=f.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Nf();return l.jsx(Cf,{className:ae("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??l.jsxs(l.Fragment,{children:[l.jsx(ie.BrainIcon,{className:"size-4"}),Vf(s,o),l.jsx(ie.ChevronDownIcon,{className:ae("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),ic=f.memo(({className:e,children:t,...n})=>l.jsx(Pf,{className:ae("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...n,children:l.jsx(Wr,{className:"grid gap-2",children:t})}));sc.displayName="Reasoning";rc.displayName="ReasoningTrigger";ic.displayName="ReasoningContent";function po(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function If({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=po(s.domain);return l.jsxs(pt,{children:[l.jsx(gt,{asChild:!0,children:l.jsxs("button",{className:ae("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[l.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),l.jsx("span",{className:"leading-none",children:s.domain})]})}),l.jsx(yt,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",e.length]}),e.map(o=>{const i=o.title||o.domain;return l.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:ae("flex items-center gap-2 p-2 rounded-md hover:bg-stone-700/50 dark:hover:bg-stone-700/50 transition-colors","text-stone-300 dark:text-stone-300 hover:text-white dark:hover:text-white"),onClick:a=>a.stopPropagation(),children:[l.jsx("img",{src:po(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const c=a.target;c.style.display="none"}}),l.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function Of({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:c=!0}){const u=f.useRef(null),[d,h]=f.useState([]);f.useEffect(()=>{if(!a||!u.current||t.length===0||n.size===0){(n.size===0||!a)&&h([]);return}const b=u.current;let y,j=!1;const M=new WeakSet,N=()=>{if(!u.current||j)return;j=!0;const F=u.current,B=/\[(\d+)\]/g,P=document.createTreeWalker(F,NodeFilter.SHOW_TEXT,null),z=[];let T;for(;T=P.nextNode();)if(T.nodeType===Node.TEXT_NODE&&!M.has(T)){const O=T,R=O.textContent||"";let W=O.parentElement,oe=!1;for(;W&&W!==F;){if(W.tagName==="A"||W.tagName==="CODE"||W.tagName==="PRE"){oe=!0;break}W=W.parentElement}if(!oe){const Y=Array.from(R.matchAll(B)).filter(te=>{if(!te[1])return!1;const J=parseInt(te[1],10);return n.has(J)});Y.length>0&&z.push({node:O,matches:Y})}}if(z.length===0){j=!1;return}const V=[];z.forEach(({node:O,matches:R})=>{M.add(O);const W=O.textContent||"",oe=document.createDocumentFragment();let ce=0;R.forEach(Y=>{if(!Y[1])return;Y.index!==void 0&&Y.index>ce&&oe.appendChild(document.createTextNode(W.slice(ce,Y.index)));const te=document.createElement("span");te.className="inline-flex items-center citation-button-container";const J=parseInt(Y[1],10);te.setAttribute("data-citation",Y[1]),oe.appendChild(te),V.push({element:te,citationNum:J}),ce=(Y.index||0)+Y[0].length}),ce<W.length&&oe.appendChild(document.createTextNode(W.slice(ce))),O.parentNode&&O.parentNode.replaceChild(oe,O)}),V.length>0&&h(O=>{const R=new Set(O.map(ce=>ce.element)),W=O.filter(ce=>ce.element.isConnected),oe=V.filter(ce=>!R.has(ce.element));return[...W,...oe]}),j=!1},D=new MutationObserver(()=>{clearTimeout(y),y=setTimeout(N,100)});return D.observe(b,{childList:!0,subtree:!0,characterData:!0}),y=setTimeout(N,200),()=>{D.disconnect(),clearTimeout(y)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(b){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(b)}&sz=16`}function w(b){try{return new URL(b).hostname.replace(/^www\./,"")}catch{return b}}const x=a&&c&&m?l.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[l.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((b,y)=>{const j=b.title||b.baseUrl,M=w(b.url),N=p(M);return l.jsxs("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",className:ae("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[l.jsx("img",{src:N,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:D=>{const F=D.target;F.style.display="none"}}),l.jsx("span",{className:"leading-none",children:j})]},`group-${y}`)}):Array.from(n.entries()).sort(([b],[y])=>b-y).map(([b,y])=>{const j=w(y),M=p(j);return l.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:ae("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[l.jsx("img",{src:M,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:N=>{const D=N.target;D.style.display="none"}}),l.jsx("span",{className:"leading-none",children:y})]},b)})})]}):null;return l.jsxs("div",{className:i,children:[l.jsx("div",{ref:u,children:l.jsx(o,{children:e})}),a&&d.filter(({element:b})=>b.isConnected).map(({element:b,citationNum:y},j)=>{if(!t.find(D=>D.number===y))return null;const N=Array.from(new Map(t.map(D=>{const F=D.url.replace(/\/+$/,""),B=s?.find(P=>P.url.replace(/\/+$/,"")===F);return[F,{number:D.number,url:D.url,domain:w(D.url),title:B?.title}]})).values());return Nc.createPortal(l.jsx(If,{sources:N,citationNumber:y},`citation-${y}-${b}`),b,`citation-${y}-${j}`)}),x]})}function un({...e}){return l.jsx($t.Root,{"data-slot":"dialog",...e})}function $f({...e}){return l.jsx($t.Portal,{"data-slot":"dialog-portal",...e})}function Lf({className:e,...t}){return l.jsx($t.Overlay,{"data-slot":"dialog-overlay",className:ae("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function dn({className:e,children:t,showCloseButton:n=!0,...s}){return l.jsxs($f,{"data-slot":"dialog-portal",children:[l.jsx(Lf,{}),l.jsxs($t.Content,{"data-slot":"dialog-content",className:ae("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...s,children:[t,n&&l.jsxs($t.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[l.jsx(ie.XIcon,{}),l.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function hn({className:e,...t}){return l.jsx("div",{"data-slot":"dialog-header",className:ae("flex flex-col gap-2 text-center sm:text-left",e),...t})}function fn({className:e,...t}){return l.jsx("div",{"data-slot":"dialog-footer",className:ae("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function mn({className:e,...t}){return l.jsx($t.Title,{"data-slot":"dialog-title",className:ae("text-lg leading-none font-semibold",e),...t})}function pn({className:e,...t}){return l.jsx($t.Description,{"data-slot":"dialog-description",className:ae("text-muted-foreground text-sm",e),...t})}function gn({className:e,type:t,...n}){return l.jsx("input",{type:t,"data-slot":"input",className:ae("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-white px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...n})}function Ff({isOpen:e,title:t="Password Required",description:n="Please enter your password to continue",placeholder:s="Enter password...",onComplete:r}){const[o,i]=f.useState(""),[a,c]=f.useState(!1),[u,d]=f.useState(!1),h=async p=>{if(p.preventDefault(),!!o.trim()){d(!0);try{r(o)}finally{d(!1)}}},m=()=>{i(""),r(null)};return l.jsx(un,{open:e,children:l.jsx(dn,{showCloseButton:!1,children:l.jsxs("form",{onSubmit:h,children:[l.jsxs(hn,{children:[l.jsx(mn,{children:t}),l.jsx(pn,{children:n})]}),l.jsx("div",{className:"py-4",children:l.jsxs("div",{className:"relative",children:[l.jsx(gn,{type:a?"text":"password",value:o,onChange:p=>i(p.target.value),placeholder:s,className:"pr-10",autoFocus:!0,disabled:u}),l.jsx("button",{type:"button",onClick:()=>c(!a),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:u,children:a?l.jsx(ie.EyeOff,{className:"h-4 w-4"}):l.jsx(ie.Eye,{className:"h-4 w-4"})})]})}),l.jsxs(fn,{children:[l.jsx(Se,{type:"button",variant:"ghost",onClick:m,disabled:u,children:"Cancel"}),l.jsx(Se,{type:"submit",disabled:!o.trim()||u,children:u?"Submitting...":"Submit"})]})]})})})}function Bf({isOpen:e,title:t="Email Required",description:n="Please enter your email address",placeholder:s="Enter email address...",onComplete:r}){const[o,i]=f.useState(""),[a,c]=f.useState(!0),[u,d]=f.useState(!1),h=x=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(x),m=x=>{i(x),x.trim()?c(h(x)):c(!0)},p=async x=>{if(x.preventDefault(),!o.trim()||!h(o)){c(!1);return}d(!0);try{r(o)}finally{d(!1)}},w=()=>{i(""),c(!0),r(null)};return l.jsx(un,{open:e,children:l.jsx(dn,{showCloseButton:!1,children:l.jsxs("form",{onSubmit:p,children:[l.jsxs(hn,{children:[l.jsxs(mn,{className:"flex items-center gap-2",children:[l.jsx(ie.Mail,{className:"h-5 w-5"}),t]}),l.jsx(pn,{children:n})]}),l.jsxs("div",{className:"py-4",children:[l.jsx(gn,{type:"email",value:o,onChange:x=>m(x.target.value),placeholder:s,className:a?"":"border-red-500",autoFocus:!0,disabled:u}),!a&&l.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid email address"})]}),l.jsxs(fn,{children:[l.jsx(Se,{type:"button",variant:"ghost",onClick:w,disabled:u,children:"Cancel"}),l.jsx(Se,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function zf({isOpen:e,title:t="Phone Number Required",description:n="Please enter your phone number",placeholder:s="Enter phone number...",onComplete:r}){const[o,i]=f.useState(""),[a,c]=f.useState(!0),[u,d]=f.useState(!1),h=b=>{const y=b.replace(/\D/g,"");return y.length<=3?y:y.length<=6?`(${y.slice(0,3)}) ${y.slice(3)}`:`(${y.slice(0,3)}) ${y.slice(3,6)}-${y.slice(6,10)}`},m=b=>b.replace(/\D/g,"").length===10,p=b=>{const y=h(b);i(y),y.trim()?c(m(y)):c(!0)},w=async b=>{if(b.preventDefault(),!o.trim()||!m(o)){c(!1);return}d(!0);try{const y=o.replace(/\D/g,"");r(y)}finally{d(!1)}},x=()=>{i(""),c(!0),r(null)};return l.jsx(un,{open:e,children:l.jsx(dn,{showCloseButton:!1,children:l.jsxs("form",{onSubmit:w,children:[l.jsxs(hn,{children:[l.jsxs(mn,{className:"flex items-center gap-2",children:[l.jsx(ie.Phone,{className:"h-5 w-5"}),t]}),l.jsx(pn,{children:n})]}),l.jsxs("div",{className:"py-4",children:[l.jsx(gn,{type:"tel",value:o,onChange:b=>p(b.target.value),placeholder:s,className:a?"":"border-red-500",maxLength:14,autoFocus:!0,disabled:u}),!a&&l.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid 10-digit phone number"})]}),l.jsxs(fn,{children:[l.jsx(Se,{type:"button",variant:"ghost",onClick:x,disabled:u,children:"Cancel"}),l.jsx(Se,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Uf({isOpen:e,title:t="PIN Required",description:n="Please enter your PIN",placeholder:s="Enter PIN...",length:r=4,onComplete:o}){const[i,a]=f.useState(""),[c,u]=f.useState(!1),d=p=>{const w=p.replace(/\D/g,"");a(w.slice(0,r))},h=async p=>{if(p.preventDefault(),i.length===r){u(!0);try{o(i)}finally{u(!1)}}},m=()=>{a(""),o(null)};return l.jsx(un,{open:e,children:l.jsx(dn,{showCloseButton:!1,children:l.jsxs("form",{onSubmit:h,children:[l.jsxs(hn,{children:[l.jsxs(mn,{className:"flex items-center gap-2",children:[l.jsx(ie.Shield,{className:"h-5 w-5"}),t]}),l.jsx(pn,{children:n})]}),l.jsxs("div",{className:"py-4",children:[l.jsx(gn,{type:"password",value:i,onChange:p=>d(p.target.value),placeholder:s,className:"text-center text-lg tracking-widest",maxLength:r,autoFocus:!0,disabled:c}),l.jsxs("p",{className:"text-sm text-gray-500 mt-1 text-center",children:["Enter ",r,"-digit PIN"]})]}),l.jsxs(fn,{children:[l.jsx(Se,{type:"button",variant:"ghost",onClick:m,disabled:c,children:"Cancel"}),l.jsx(Se,{type:"submit",disabled:i.length!==r||c,children:c?"Submitting...":"Submit"})]})]})})})}function $s({isOpen:e,title:t="Secure Input Required",description:n="Please enter the requested information",placeholder:s="Enter value...",type:r="password",onComplete:o}){const[i,a]=f.useState(""),[c,u]=f.useState(!1),d=async m=>{if(m.preventDefault(),!!i.trim()){u(!0);try{o(i)}finally{u(!1)}}},h=()=>{a(""),o(null)};return l.jsx(un,{open:e,children:l.jsx(dn,{showCloseButton:!1,children:l.jsxs("form",{onSubmit:d,children:[l.jsxs(hn,{children:[l.jsxs(mn,{className:"flex items-center gap-2",children:[l.jsx(ie.Lock,{className:"h-5 w-5"}),t]}),l.jsx(pn,{children:n})]}),l.jsx("div",{className:"py-4",children:l.jsx(gn,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:c})}),l.jsxs(fn,{children:[l.jsx(Se,{type:"button",variant:"ghost",onClick:h,disabled:c,children:"Cancel"}),l.jsx(Se,{type:"submit",disabled:!i.trim()||c,children:c?"Submitting...":"Submit"})]})]})})})}function _f({isOpen:e,title:t,description:n,fields:s,onComplete:r,submitText:o="Submit",cancelText:i="Cancel"}){const[a,c]=f.useState(()=>{const T={};return s.forEach(V=>{T[V.name]=V.value||""}),T}),[u,d]=f.useState({}),[h,m]=f.useState({}),[p,w]=f.useState(!1),x=T=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(T)?null:"Please enter a valid email address",b=T=>T.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",y=(T,V=4)=>T.length===V?null:`PIN must be ${V} digits`,j=T=>{const V=T.replace(/\D/g,"");return V.length<=3?V:V.length<=6?`(${V.slice(0,3)}) ${V.slice(3)}`:`(${V.slice(0,3)}) ${V.slice(3,6)}-${V.slice(6,10)}`},M=(T,V,O)=>{let R=V,W=null;switch(O.type){case"phone":R=j(V),R.trim()&&(W=b(R));break;case"email":V.trim()&&(W=x(V));break;case"pin":R=V.replace(/\D/g,"").slice(0,6),R.trim()&&(W=y(R));break}!W&&O.validation&&R.trim()&&(W=O.validation(R)),c(oe=>({...oe,[T]:R})),d(oe=>({...oe,[T]:W||""}))},N=()=>{const T={};let V=!0;return s.forEach(O=>{const R=a[O.name]||"";let W=null;if(O.required&&!R.trim())W=`${O.label} is required`;else if(R.trim()){switch(O.type){case"email":W=x(R);break;case"phone":W=b(R);break;case"pin":W=y(R);break}!W&&O.validation&&(W=O.validation(R))}W&&(T[O.name]=W,V=!1)}),d(T),V},D=async T=>{if(T.preventDefault(),!!N()){w(!0);try{const V={};s.forEach(O=>{const R=a[O.name]?.trim();R&&(O.type==="phone"?V[O.name]=R.replace(/\D/g,""):V[O.name]=R)}),r(V)}finally{w(!1)}}},F=()=>{c({}),d({}),m({}),r(null)},B=T=>{m(V=>({...V,[T]:!V[T]}))},P=T=>{switch(T.type){case"password":return h[T.name]?"text":"password";case"email":return"email";case"phone":return"tel";case"pin":case"ssn":return"password";default:return"text"}},z=T=>{if(T.placeholder)return T.placeholder;switch(T.type){case"email":return"Enter email address...";case"phone":return"Enter phone number...";case"password":return"Enter password...";case"pin":return"Enter PIN...";case"ssn":return"XXX-XX-XXXX";case"creditCard":return"XXXX XXXX XXXX XXXX";default:return`Enter ${T.label.toLowerCase()}...`}};return l.jsx(un,{open:e,children:l.jsx(dn,{showCloseButton:!1,className:"max-w-md",children:l.jsxs("form",{onSubmit:D,children:[l.jsxs(hn,{children:[l.jsx(mn,{children:t}),n&&l.jsx(pn,{children:n})]}),l.jsx("div",{className:"py-4 space-y-4",children:s.map(T=>l.jsxs("div",{children:[l.jsxs("label",{className:"block text-sm font-medium mb-1",children:[T.label,T.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsxs("div",{className:"relative",children:[l.jsx(gn,{type:P(T),value:a[T.name]||"",onChange:V=>M(T.name,V.target.value,T),placeholder:z(T),className:u[T.name]?"border-red-500":"",disabled:p,autoFocus:T===s[0],maxLength:T.type==="pin"?6:T.type==="phone"?14:void 0}),T.type==="password"&&l.jsx("button",{type:"button",onClick:()=>B(T.name),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:p,children:h[T.name]?l.jsx(ie.EyeOff,{className:"h-4 w-4"}):l.jsx(ie.Eye,{className:"h-4 w-4"})})]}),u[T.name]&&l.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[l.jsx(ie.AlertCircle,{className:"h-3 w-3"}),u[T.name]]})]},T.name))}),l.jsxs(fn,{children:[l.jsx(Se,{type:"button",variant:"ghost",onClick:F,disabled:p,children:i}),l.jsx(Se,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const oc=f.createContext(void 0);function ac(){const e=f.useContext(oc);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function cc({children:e}){const[t,n]=f.useState(null),[s,r]=f.useState(null),o=f.useRef(null),i=f.useRef(null),a=f.useCallback(p=>new Promise(w=>{n(p),o.current=w}),[]),c=f.useCallback(p=>new Promise(w=>{r(p),i.current=w}),[]),u=f.useCallback(p=>{o.current&&(o.current(p),o.current=null),n(null)},[]),d=f.useCallback(p=>{i.current&&(i.current(p),i.current=null),r(null)},[]),h=()=>{if(s){const w=s.fields.map(x=>({name:x.name,type:x.type==="text"?"text":x.type==="password"?"password":x.type==="email"?"email":x.type==="phone"?"phone":x.type==="pin"?"pin":x.type==="ssn"?"ssn":x.type==="creditCard"?"creditCard":"text",label:x.label,placeholder:x.placeholder,required:x.required!==!1,value:x.value}));return l.jsx(_f,{isOpen:!0,title:s.title,description:s.description,fields:w,onComplete:d})}if(!t)return null;const p={isOpen:!0,title:t.title,description:t.description,placeholder:t.placeholder,onComplete:u};switch(t.type){case"password":return l.jsx(Ff,{...p});case"email":return l.jsx(Bf,{...p});case"phone":return l.jsx(zf,{...p});case"pin":return l.jsx(Uf,{...p});case"ssn":return l.jsx($s,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return l.jsx($s,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return l.jsx($s,{...p})}},m=f.useMemo(()=>({showSecureModal:a,showSecureForm:c}),[a,c]);return l.jsxs(oc.Provider,{value:m,children:[e,h()]})}function Xf(e){try{const t=new URL(e),n=`${t.protocol}//${t.host}${t.pathname}`,s=t.hash?t.hash.substring(1):void 0;return{baseUrl:n,anchor:s}}catch{const t=e.indexOf("#");return t!==-1?{baseUrl:e.substring(0,t),anchor:e.substring(t+1)}:{baseUrl:e}}}function Wf(e){try{const t=new URL(e),s=t.pathname.split("/").filter(a=>a.length>0);if(s.length===0)return t.hostname;const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||t.hostname}catch{const t=e.indexOf("#"),n=t!==-1?e.substring(0,t):e,s=n.split("/").filter(r=>r.length>0);if(s.length>0){const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||n}return n}}function go(e){let t=e.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=t.match(n),r=new Map,o=[],i=new Map,a=new Map,c=new Map,u=new Map;if(s&&s[1]){const P=s[1],z=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let T;for(;(T=z.exec(P))!==null;)if(T[1]&&T[2]){const V=parseInt(T[1],10),O=T[2].replace(/[.,;:!?]+$/,""),R=O.replace(/\/+$/,"");if(a.has(R)||a.set(R,O),i.has(R)||i.set(R,[]),i.get(R).push(V),!c.has(R))c.set(R,V);else{const W=c.get(R);V<W&&c.set(R,V)}}for(const[V,O]of i.entries()){const R=c.get(V);for(const W of O)W!==R&&u.set(W,R)}for(const[V,O]of c.entries()){const R=a.get(V)||V;r.set(O,R),o.push({number:O,url:R})}}let d,h=t;s&&s[0]&&(d=s[0],h=t.replace(n,""));const m=[];let p=0;const w=/```[\s\S]*?```|`[^`]+`/g;let x;for(;(x=w.exec(h))!==null;)x.index>p&&m.push({type:"text",content:h.slice(p,x.index),start:p,end:x.index}),m.push({type:"code",content:x[0],start:x.index,end:x.index+x[0].length}),p=x.index+x[0].length;p<h.length&&m.push({type:"text",content:h.slice(p),start:p,end:h.length});const b=m.map(P=>{if(P.type==="code")return P.content;let z=P.content;return z=z.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(V,O,R)=>{const W=parseInt(O,10),oe=R.replace(/\/+$/,""),ce=u.get(W)||W;return c.has(oe)||(c.set(oe,ce),r.has(ce)||(r.set(ce,R),o.push({number:ce,url:R}))),`[${ce}]`}),z=z.replace(/\[(\d+)\]/g,(V,O)=>{const R=parseInt(O,10);return`[${u.get(R)||R}]`}),z}),y=[];for(const[P,z]of c.entries()){const T=a.get(P)||P,{baseUrl:V,anchor:O}=Xf(T),R=Wf(T);y.push({url:T,baseUrl:V,numbers:[z],anchor:O,title:R})}y.sort((P,z)=>(P.numbers[0]||0)-(z.numbers[0]||0));const j=new Map;let M=1;for(const P of y){const z=P.numbers[0];j.set(z,M),P.numbers=[M],M++}const N=new Map;for(const[P,z]of r.entries()){const T=j.get(P);T&&N.set(T,z)}const D=o.map(P=>{const z=j.get(P.number);return z?{number:z,url:P.url}:P}).filter(P=>j.has(P.number)),F=Array.from(j.entries()).sort((P,z)=>z[0]-P[0]);let B=b.join("");for(const[P,z]of F){const T=new RegExp(`\\[${P}\\](?!\\d)`,"g");B=B.replace(T,`[${z}]`)}return{processedText:B,citations:D.sort((P,z)=>P.number-z.number),citationMap:N,groupedCitations:y,referencesText:d}}function Dn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Dn(t)}catch{return e}if(Array.isArray(e))return e.map(Dn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Dn(s);return t}return e}function Ls(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Dn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Dn(e):{}}function qf({theme:e="auto",layout:t="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:c=800,initiallyExpanded:u=!1,tools:d=[],safeTools:h=[],toolMetadata:m,systemPrompt:p="",tokenEndpoint:w="/api/arcten/token",apiBaseUrl:x="https://api.arcten.com",user:b,state:y,onStateChange:j,allowStateEdits:M=!0,sources:N,ragConfig:D,showCitations:F=!0,sensitiveParams:B,autoDetectSensitive:P=!1}){const{showSecureModal:z}=ac(),T=f.useMemo(()=>D!==void 0?D:N&&N.length>0?{enabled:!0,organizationId:N[0],autoExecute:!0,filters:void 0}:{enabled:!1},[N,D]),[V,O]=f.useState(null),R=f.useRef(null),[W,oe]=f.useState(null),[ce,Y]=f.useState(null),te=f.useRef(null),J=y!==void 0,[be,He]=f.useState({}),Me=f.useRef({});J&&y?Me.current=y:J||(Me.current=be);const[yn,Lt]=f.useState(!1),[vs,Ft]=f.useState(null),tt=f.useRef(!1),[ze,Bt]=f.useState(u),[Je,zt]=f.useState(i),[Ut,xn]=f.useState(600),[de,Tt]=f.useState(!1),[ne,we]=f.useState(!1),[Ue,_t]=f.useState(!1),[Pe,bn]=f.useState({x:100,y:100}),[St,at]=f.useState(!1),[jt,ct]=f.useState({x:0,y:0}),[lt,Xn]=f.useState(!1),vn=f.useRef(null),Xt=f.useRef(null),[Wt,Ct]=f.useState(""),[wn,nt]=f.useState(null),[st,qt]=f.useState("Thinking..."),[_e,De]=f.useState(new Set),[Wn,qn]=f.useState(""),[Re,Kn]=f.useState([]),[Tn,Sn]=f.useState(!1),[Ve,Gn]=f.useState([]),[Ie,Pt]=f.useState(()=>typeof window<"u"?crypto.randomUUID():null),[ut,Ee]=f.useState(!1),[Yn,Kt]=f.useState(!1),[qr,Gt]=f.useState([]),jn=f.useCallback(async(g,C=3)=>{if(!Ie||!R.current)return;const I=async()=>{const L=`${x.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,_=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${R.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Ie,updates:g},format:"json"})});if(!_.ok){if(_.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const ee=await _.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${_.status} ${ee}`)}};for(let $=0;$<C;$++)try{await I(),Ft(null);return}catch(L){if($===C-1){const ee=L instanceof Error?L:new Error(String(L));throw Ft(ee),console.error("Failed to sync state to Convex after retries:",L),ee}await new Promise(ee=>setTimeout(ee,Math.pow(2,$)*100))}},[Ie,x,R]),At=f.useMemo(()=>function(){return Me.current},[]),kt=f.useMemo(()=>async function(C){const I={...Me.current,...C};Me.current=I,J||He(I),j&&j(I);try{await jn(C)}catch($){throw $}},[jn,j,J]);f.useEffect(()=>{J&&y&&(Me.current=y)},[J,y]);const v=f.useMemo(()=>T?.enabled?async function(C,I=20,$){if(N&&N.length>1){const ee=N.map(K=>fetch(`${x}/search`,{method:"POST",headers:{"Content-Type":"application/json",...R.current?{Authorization:`Bearer ${R.current}`}:{}},body:JSON.stringify({q:C,k:Math.min(I,100),organizationId:K,...Object.keys(_).length>0?{filters:_}:{}})}).then(X=>X.ok?X.json():null)),H=await Promise.all(ee),re=[];for(const K of H)K?.candidates&&re.push(...K.candidates);re.sort((K,X)=>{const ye=K.scores?.rerank||K.scores?.dense||0;return(X.scores?.rerank||X.scores?.dense||0)-ye});const U=re.slice(0,I).map((K,X)=>{const ye=K.citation||K.url;return{rank:X+1,doc_id:K.doc_id,block_id:K.block_id,url:K.url,citation:ye,title:K.title||"Untitled",snippet:K.snippet,score:K.scores?.rerank||K.scores?.dense||0,metadata:{site:K.metadata?.site,lang:K.metadata?.lang,contentType:K.metadata?.content_type}}});return{success:!0,query:C,total:re.length,results:U,summary:`Found ${re.length} relevant results across ${N.length} source(s) for "${C}". Top result: ${U[0]?.title||"N/A"}`}}const L=T.organizationId&&T.organizationId!=="default"?T.organizationId:void 0,_={...T.filters,...$};try{const ee={q:C,k:Math.min(I,100)};L&&(ee.organizationId=L),Object.keys(_).length>0&&(ee.filters=_);const H={"Content-Type":"application/json"};R.current&&(H.Authorization=`Bearer ${R.current}`);const re=await fetch(`${x}/search`,{method:"POST",headers:H,body:JSON.stringify(ee)});if(!re.ok){const X=await re.text();return{success:!1,error:`Search failed: ${re.status} ${X}`}}const U=await re.json(),K=U.candidates.map((X,ye)=>{const pe=X.citation||X.url;return{rank:ye+1,doc_id:X.doc_id,block_id:X.block_id,url:X.url,citation:pe,title:X.title||"Untitled",snippet:X.snippet,score:X.scores?.rerank||X.scores?.dense||0,metadata:{site:X.metadata?.site,lang:X.metadata?.lang,contentType:X.metadata?.content_type}}});return{success:!0,query:U.query,total:U.total,results:K,summary:`Found ${U.total} relevant results for "${C}". Top result: ${K[0]?.title||"N/A"}`}}catch(ee){return{success:!1,error:ee instanceof Error?ee.message:"Unknown error occurred"}}}:null,[D,x,R]),A=f.useMemo(()=>T?.enabled?async function(C,I){const $=T.organizationId&&T.organizationId!=="default"?T.organizationId:N&&N.length>0?N[0]:void 0;try{const L={"Content-Type":"application/json"};R.current&&(L.Authorization=`Bearer ${R.current}`);const _=await fetch(`${x}/fetch`,{method:"POST",headers:L,body:JSON.stringify({doc_id:C,block_ids:I,...$?{organizationId:$}:{}})});if(!_.ok){const H=await _.text();return{success:!1,error:`Fetch failed: ${_.status} ${H}`}}const ee=await _.json();return{success:!0,blocks:ee.blocks||[],fullContent:ee.fullContent||"",pageUrl:ee.pageUrl||"",pageTitle:ee.pageTitle||"",summary:`Fetched ${ee.blocks?.length||0} blocks from ${ee.pageTitle||C}`}}catch(L){return{success:!1,error:L instanceof Error?L.message:"Unknown error occurred"}}}:null,[D,x,R]),S=f.useMemo(()=>{const g=[...d,...h,At];return(!J||M)&&g.push(kt),T?.enabled&&(v&&g.push(v),A&&g.push(A)),g},[d,h,At,kt,v,A,J,M,T]),k=f.useMemo(()=>tc(S,m),[S,m]),E=f.useMemo(()=>{const g=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!J||M)&&g.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const C=[];return T?.enabled&&C.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...k,...g,...C]},[k,J,M,T]),G=f.useMemo(()=>new Set(E.map(g=>g.name)),[E]),Z=f.useMemo(()=>E.filter(g=>g.name==="getState"?!0:g.name==="setState"?!J||M:G.has(g.name)),[E,G,J,M]),le=f.useMemo(()=>{const g=new Map,C=new Map(k.map(I=>[I.name,I]));return g.set("getState",At),(!J||M)&&g.set("setState",kt),T?.enabled&&(v&&g.set("searchDocs",v),A&&g.set("fetchDocContent",A)),S.forEach(I=>{if(I===At||I===kt||I===v||I===A)return;const $=I[Qe];if($){const _=C.get($);if(_){g.set(_.name,I);return}}const L=E.find(_=>_.name===I.name);L&&g.set(L.name,I)}),g},[S,E,At,kt,v,A,J,M,T]),he=f.useMemo(()=>{const g=new Set;g.add("getState"),g.add("setState"),T?.enabled&&T.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent"));const C=new Map(E.map(I=>[I.name,I]));return h.forEach(I=>{const $=I[Qe];if($&&C.has($))g.add($);else{const L=E.find(_=>_.name===I.name);L&&g.add(L.name)}}),g},[h,E,T]),Ne=["Thinking...","Pondering...","Contemplating...","Considering...","Analyzing...","Processing...","Reasoning...","Mulling it over...","Computing...","Cooking up a response...","Brewing ideas...","Connecting the dots...","Piecing it together...","Spinning up thoughts...","Loading brain cells...","Sharpening pencils...","Herding ideas...","Warming up neurons...","Stirring the think-pot...","Plotting a plan...","Wiggling the logic wires...","Rolling ideas around...","Charging the brainstorm...","Booting the brain...","Dusting off the cortex...","Running mental diagnostics...","Fetching cleverness...","Whisking up notions...","Tuning the idea radio...","Juggling possibilities...","Breathing in inspiration...","Squeezing the thought sponge...","Tickling the gray matter...","Bubbling up insights...","Spicing the soup of thought...","Lacing up hypotheses...","Winding the idea clock...","Casting the net for clues...","Polishing the crystal ball...","Mapping the maze...","Crunching the brain-biscuits...","Cueing the eureka moment...","Summoning the muse...","Knocking on insight’s door...","Combing the noodle...","Sailing the think-ship...","Scooping brain gelato...","Testing wild hunches...","Tick-tocking the neurons...","Planting idea seeds...","Shaking the thought snow globe...","Unlocking the mental toolbox...","Nudging the puzzle pieces...","Lighting the idea bulb...","Preheating the oven of insight...","Mixing the mental trail mix...","Spooling up reasoning reels...","Skimming the mind-palace index...","Surfing the thought waves...","Kicking the tires on ideas...","Rattling the idea can...","Waving the logic wand..."];f.useEffect(()=>{if(typeof window<"u"){const g=localStorage.getItem("arcten-sidebar-expanded");g&&Bt(JSON.parse(g));const C=localStorage.getItem("arcten-sidebar-width");C&&zt(parseInt(C));const I=localStorage.getItem("arcten-sidebar-height");I&&xn(parseInt(I));const $=localStorage.getItem("arcten-sidebar-detached");$&&we(JSON.parse($));const L=localStorage.getItem("arcten-sidebar-position");if(L){const ee=JSON.parse(L),H=50,re=Math.max(H-i,Math.min(ee.x,window.innerWidth-H)),U=Math.max(0,Math.min(ee.y,window.innerHeight-H));bn({x:re,y:U})}const _=localStorage.getItem("arcten-sidebar-minimized");_&&_t(JSON.parse(_)),Xn(!0)}},[]);const Q=f.useMemo(()=>b,[b?.id]);f.useEffect(()=>((async()=>{try{const C=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Q})});if(!C.ok)throw new Error("Failed to fetch token");const I=await C.json();O(I.clientToken),R.current=I.clientToken,Y(I.expiresAt),oe(null)}catch(C){oe(C instanceof Error?C.message:"Failed to fetch token")}})(),()=>{te.current&&clearTimeout(te.current)}),[w,Q]),f.useEffect(()=>{if(!ce)return;te.current&&clearTimeout(te.current);const g=Math.floor(Date.now()/1e3),C=ce-g,$=Math.max(0,C-5);return te.current=setTimeout(async()=>{try{const L=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Q})});if(!L.ok)throw new Error("Failed to refresh token");const _=await L.json();O(_.clientToken),R.current=_.clientToken,Y(_.expiresAt),oe(null)}catch(L){console.error("Token refresh failed:",L),oe(L instanceof Error?L.message:"Failed to refresh token")}},$*1e3),()=>{te.current&&clearTimeout(te.current)}},[ce,w,Q]),f.useEffect(()=>{(async()=>{if(S.length!==0)try{const C=S.map($=>({name:$.name,code:$.toString()})),I=await fetch(`${x}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:C})});if(I.ok){const $=await I.json();Kn($.tools)}}catch(C){console.error("Failed to fetch tool descriptions:",C)}})()},[S]),f.useEffect(()=>{Promise.resolve().then(()=>kf).then(g=>{nt(()=>g.Response)})},[]),f.useEffect(()=>{const g=()=>{qn(window.location.pathname)};g(),window.addEventListener("popstate",g);const C=setInterval(g,500);return()=>{window.removeEventListener("popstate",g),clearInterval(C)}},[]);const se=f.useCallback(async()=>{if(!(!Q?.id||!V)){Kt(!0);try{const C=await(await fetch(`${x}/conversations`,{headers:{Authorization:`Bearer ${V}`}})).json();Gn(C.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{Kt(!1)}}},[Q?.id,V,x]);f.useEffect(()=>{Q?.id&&V&&se()},[Q?.id,V,se]);function Xe(g){const C=Math.floor((Date.now()-g)/1e3);return C<60?"now":C<3600?`${Math.floor(C/60)}m`:C<86400?`${Math.floor(C/3600)}h`:`${Math.floor(C/86400)}d`}function dt(){const g=crypto.randomUUID();Pt(g),Zn([]),Gt([]),Ee(!1);const C=J?y||{}:{};Me.current=C,J||He(C),j&&j(C),tt.current=!1}async function Ae(g){if(V)try{await fetch(`${x}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${V}`}}),Gn(Ve.filter(C=>C._id!==g)),g===Ie&&dt()}catch(C){console.error("Failed to delete conversation:",C)}}async function ht(g){Pt(g.chatId),Ee(!1),Kt(!0);try{const C=await fetch(`${x}/conversations/${g.chatId}/messages`,{headers:{Authorization:`Bearer ${R.current}`}});if(!C.ok)throw new Error(`Failed to fetch messages: ${C.statusText}`);const $=(await C.json()).messages||[];Zn($),Gt($)}catch(C){console.error("Failed to load conversation messages:",C);const I=g.messages||[];Zn(I),Gt(I)}finally{Kt(!1)}}const Ze=async(g,C={})=>{const I=C.headers?new Headers(C.headers):new Headers;return I.delete("user-agent"),I.delete("User-Agent"),fetch(g,{...C,headers:I})},{messages:We,sendMessage:Hn,status:qe,error:Kr,stop:Jn,addToolResult:Mt,setMessages:Zn}=yo.useChat({id:Ie||void 0,transport:new ls.DefaultChatTransport({api:`${x}/chat`,fetch:Ze,headers:()=>{const g={};return R.current&&(g.Authorization=`Bearer ${R.current}`),g},body:()=>({tools:Z.map(C=>({name:C.name,description:C.description,inputSchema:C.jsonSchema})),systemPrompt:p,currentRoute:Wn,state:Me.current})}),sendAutomaticallyWhen:ls.lastAssistantMessageIsCompleteWithToolCalls});f.useEffect(()=>{const g=We[We.length-1];if(!g||g.role!=="assistant")return;const C=g.parts?.filter(I=>I.type?.startsWith("tool-")&&I.state==="input-available"&&typeof I.toolCallId=="string"&&I.input!==void 0)||[];for(const I of C){const $=I,L=$.type?.replace("tool-","")||"",_=$.toolCallId;if(he.has(L)){if(_e.has(_))continue;De(H=>H.has(_)?H:new Set(H).add(_)),(async()=>{try{const H=le.get(L);if(!H){console.warn(`[ArctenAgent] Tool ${L} not found in toolsMap. Available tools:`,Array.from(le.keys())),Mt({toolCallId:_,tool:L,output:`Error: Tool ${L} not found`}),De(X=>{const ye=new Set(X);return ye.delete(_),ye});return}const re=Ls($.input),U=Z.find(X=>X.name===L);let K;if(U&&U.jsonSchema?.properties){const ye=Object.keys(U.jsonSchema.properties).map(pe=>re[pe]);console.log(`[ArctenAgent] Executing safe tool ${L} with args:`,ye),K=await H(...ye)}else if(L==="getState")K=H();else if(L==="setState"){const X=re.updates||re;K=await H(X)}else K=await H(...Object.values(re));console.log(`[ArctenAgent] Tool ${L} completed, result:`,K),Mt({toolCallId:_,tool:L,output:K}),De(X=>{const ye=new Set(X);return ye.delete(_),ye})}catch(H){console.error(`[ArctenAgent] Error executing safe tool ${L}:`,H),Mt({toolCallId:_,tool:L,output:`Error: ${H instanceof Error?H.message:String(H)}`}),De(re=>{const U=new Set(re);return U.delete(_),U})}})()}}},[We,he,le,Z,Mt]),f.useEffect(()=>{if(!Ie||!R.current)return;(async()=>{Lt(!0),Ft(null);try{const I=`${x.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,$=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${R.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Ie},format:"json"})});if(!$.ok){if($.status===404||$.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${$.status}), using empty state`);const U=J?y||{}:{};Me.current=U,J||He(U),j&&j(U),tt.current=!0,Lt(!1);return}const re=await $.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${$.status} ${re}`)}const _=(await $.json())?.value||{},ee=!tt.current;let H;ee?(H={...J?y||{}:{},..._},tt.current=!0):H=_,Me.current=H,J||He(H),j&&j(H)}catch(C){C instanceof TypeError&&C.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",C):console.error("[ArctenAgent] Failed to fetch state:",C);const $=C instanceof Error?C:new Error(String(C));if(Ft($),!tt.current){const L=J?y||{}:{};Me.current=L,J||He(L),j&&j(L),tt.current=!0}}finally{Lt(!1)}})()},[Ie,x,J,y,j]),f.useEffect(()=>{ze&&Xt.current&&Xt.current.focus()},[ze,We]);function hc(){Bt(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function fc(){Bt(!1),localStorage.setItem("arcten-sidebar-expanded","false")}f.useEffect(()=>{},[ze]),f.useEffect(()=>{vn.current&&vn.current.scrollIntoView({behavior:"smooth"})},[We]),f.useEffect(()=>{function g(C){C.key==="Escape"&&(qe==="streaming"||qe==="submitted")&&(C.preventDefault(),Jn())}return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[qe,Jn]);function mc(){const g=crypto.randomUUID();Pt(g),Zn([]),Gt([]),Ee(!1)}function Gr(g){if(g.preventDefault(),!Wt.trim())return;(qe==="streaming"||qe==="submitted")&&Jn();const C=Ne[Math.floor(Math.random()*Ne.length)]||"Thinking...";qt(C),Hn({text:Wt}),Ct("")}function pc(g){const C=g.target.value;Ct(C)}f.useEffect(()=>{if(!de)return;function g(I){if(ne){const $=I.clientX-Pe.x,L=I.clientY-Pe.y;$>=a&&$<=c&&zt($),L>=400&&L<=1e3&&xn(L)}else{const $=window.innerWidth-I.clientX;$>=a&&$<=c&&zt($)}}function C(){Tt(!1),localStorage.setItem("arcten-sidebar-width",Je.toString()),localStorage.setItem("arcten-sidebar-height",Ut.toString())}return window.addEventListener("mousemove",g),window.addEventListener("mouseup",C),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",C)}},[de,Je,Ut,ne,Pe,a,c]);function gc(g){g.preventDefault(),Tt(!0)}function yc(){we(!0),_t(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function xc(){we(!1),_t(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Yr(){_t(!Ue),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ue))}function bc(g){ne&&(at(!0),ct({x:g.clientX-Pe.x,y:g.clientY-Pe.y}))}return f.useEffect(()=>{if(!ne)return;function g(){bn(C=>{const $=window.innerWidth-50,L=window.innerHeight-50,_=50-Je,ee=0,H=Math.max(_,Math.min(C.x,$)),re=Math.max(ee,Math.min(C.y,L));if(H!==C.x||re!==C.y){const U={x:H,y:re};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(U)),U}return C})}return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[ne,Je]),f.useEffect(()=>{if(!St)return;function g(I){const $=I.clientX-jt.x,L=I.clientY-jt.y,_=50,ee=window.innerWidth-_,H=window.innerHeight-_,re=_-Je,U=0,K=Math.max(re,Math.min($,ee)),X=Math.max(U,Math.min(L,H));bn({x:K,y:X})}function C(){at(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(Pe))}return window.addEventListener("mousemove",g),window.addEventListener("mouseup",C),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",C)}},[St,jt,Pe,Je]),lt?W?l.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:l.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",W]})}):V?l.jsx(Bu,{features:yf,children:l.jsx(ss,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:ne?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:ne?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
18
+ `);if("functions"in t&&typeof t.functions=="object"){const o=t;n=o.functions,s=o.toolOrder}else n=t,s=void 0;const r=new Set;return e.map(o=>{const i=wf(o,n,r,s);if(!i){const a=o.name,u=o[Ze]||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 Tf({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return l.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:l.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&l.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>l.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[l.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),l.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),l.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[l.jsxs(je,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[l.jsx(ie.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),l.jsx(je,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:l.jsx(ie.X,{className:"h-3 w-3"})})]})]})})}function Sf({toolName:e,args:t,isDenied:n,isSafe:s}){const[r,o]=f.useState(!1);if(e==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];e==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(t).filter(([u])=>!i.includes(u))),c=Object.keys(a).length>0;return l.jsxs("div",{className:"my-1",children:[l.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&&l.jsx("span",{className:"transition-transform duration-200",children:r?l.jsx(ie.ChevronDown,{className:"h-3 w-3"}):l.jsx(ie.ChevronRight,{className:"h-3 w-3"})}),n?l.jsx(ie.X,{className:"h-3 w-3"}):s?l.jsx(ie.Zap,{className:"h-3 w-3"}):l.jsx(ie.Check,{className:"h-3 w-3"}),l.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&c&&l.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:l.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,d])=>l.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[l.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),l.jsx("span",{className:"font-mono text-foreground",children:typeof d=="string"?d:JSON.stringify(d)})]},u))})})]})}function jf({...e}){return l.jsx(cr.Root,{"data-slot":"collapsible",...e})}function Cf({...e}){return l.jsx(cr.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function Pf({...e}){return l.jsx(cr.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const Af=f.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Wr=f.memo(({className:e,...t})=>typeof window>"u"?null:l.jsx(f.Suspense,{fallback:null,children:l.jsx(Af,{className:ce("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Wr.displayName="Response";const kf=Object.freeze(Object.defineProperty({__proto__:null,Response:Wr},Symbol.toStringTag,{value:"Module"})),Mf=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=gf.create(t),i=f.useMemo(()=>(e?.length??0)*r,[e,r]);return l.jsx(o,{animate:{backgroundPosition:"0% center"},className:ce("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:e})},Ef=f.memo(Mf),nc=f.createContext(null),Nf=()=>{const e=f.useContext(nc);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},Df=1e3,Rf=1e3,sc=f.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,u]=Jr.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,h]=Jr.useControllableState({prop:o,defaultProp:0}),[m,p]=f.useState(!1),[w,x]=f.useState(null);f.useEffect(()=>{t?w===null&&x(Date.now()):w!==null&&(h(Math.ceil((Date.now()-w)/Rf)),x(null))},[t,w,h]),f.useEffect(()=>{if(s&&!t&&c&&!m){const y=setTimeout(()=>{u(!1),p(!0)},Df);return()=>clearTimeout(y)}},[t,c,s,u,m]);const b=y=>{u(y)};return l.jsx(nc.Provider,{value:{isStreaming:t,isOpen:c,setIsOpen:u,duration:d},children:l.jsx(jf,{className:ce("not-prose mb-4",e),onOpenChange:b,open:c,...a,children:i})})}),Vf=(e,t)=>e||t===0?l.jsx(Ef,{duration:1,children:"Thinking..."}):t===void 0?l.jsx("p",{children:"Thought for a few seconds"}):l.jsxs("p",{children:["Thought for ",t," seconds"]}),rc=f.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Nf();return l.jsx(Cf,{className:ce("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??l.jsxs(l.Fragment,{children:[l.jsx(ie.BrainIcon,{className:"size-4"}),Vf(s,o),l.jsx(ie.ChevronDownIcon,{className:ce("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),ic=f.memo(({className:e,children:t,...n})=>l.jsx(Pf,{className:ce("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...n,children:l.jsx(Wr,{className:"grid gap-2",children:t})}));sc.displayName="Reasoning";rc.displayName="ReasoningTrigger";ic.displayName="ReasoningContent";function po(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function If({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=po(s.domain);return l.jsxs(mt,{children:[l.jsx(pt,{asChild:!0,children:l.jsxs("button",{className:ce("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:[l.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),l.jsx("span",{className:"leading-none",children:s.domain})]})}),l.jsx(gt,{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:l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",e.length]}),e.map(o=>{const i=o.title||o.domain;return l.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:ce("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:[l.jsx("img",{src:po(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const c=a.target;c.style.display="none"}}),l.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function Of({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:c=!0}){const u=f.useRef(null),[d,h]=f.useState([]);f.useEffect(()=>{if(!a||!u.current||t.length===0||n.size===0){(n.size===0||!a)&&h([]);return}const b=u.current;let y,j=!1;const M=new WeakSet,E=()=>{if(!u.current||j)return;j=!0;const F=u.current,B=/\[(\d+)\]/g,P=document.createTreeWalker(F,NodeFilter.SHOW_TEXT,null),z=[];let T;for(;T=P.nextNode();)if(T.nodeType===Node.TEXT_NODE&&!M.has(T)){const O=T,R=O.textContent||"";let W=O.parentElement,oe=!1;for(;W&&W!==F;){if(W.tagName==="A"||W.tagName==="CODE"||W.tagName==="PRE"){oe=!0;break}W=W.parentElement}if(!oe){const Y=Array.from(R.matchAll(B)).filter(te=>{if(!te[1])return!1;const J=parseInt(te[1],10);return n.has(J)});Y.length>0&&z.push({node:O,matches:Y})}}if(z.length===0){j=!1;return}const V=[];z.forEach(({node:O,matches:R})=>{M.add(O);const W=O.textContent||"",oe=document.createDocumentFragment();let le=0;R.forEach(Y=>{if(!Y[1])return;Y.index!==void 0&&Y.index>le&&oe.appendChild(document.createTextNode(W.slice(le,Y.index)));const te=document.createElement("span");te.className="inline-flex items-center citation-button-container";const J=parseInt(Y[1],10);te.setAttribute("data-citation",Y[1]),oe.appendChild(te),V.push({element:te,citationNum:J}),le=(Y.index||0)+Y[0].length}),le<W.length&&oe.appendChild(document.createTextNode(W.slice(le))),O.parentNode&&O.parentNode.replaceChild(oe,O)}),V.length>0&&h(O=>{const R=new Set(O.map(le=>le.element)),W=O.filter(le=>le.element.isConnected),oe=V.filter(le=>!R.has(le.element));return[...W,...oe]}),j=!1},D=new MutationObserver(()=>{clearTimeout(y),y=setTimeout(E,100)});return D.observe(b,{childList:!0,subtree:!0,characterData:!0}),y=setTimeout(E,200),()=>{D.disconnect(),clearTimeout(y)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(b){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(b)}&sz=16`}function w(b){try{return new URL(b).hostname.replace(/^www\./,"")}catch{return b}}const x=a&&c&&m?l.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[l.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((b,y)=>{const j=b.title||b.baseUrl,M=w(b.url),E=p(M);return l.jsxs("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",className:ce("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:[l.jsx("img",{src:E,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:D=>{const F=D.target;F.style.display="none"}}),l.jsx("span",{className:"leading-none",children:j})]},`group-${y}`)}):Array.from(n.entries()).sort(([b],[y])=>b-y).map(([b,y])=>{const j=w(y),M=p(j);return l.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:ce("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:[l.jsx("img",{src:M,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:E=>{const D=E.target;D.style.display="none"}}),l.jsx("span",{className:"leading-none",children:y})]},b)})})]}):null;return l.jsxs("div",{className:i,children:[l.jsx("div",{ref:u,children:l.jsx(o,{children:e})}),a&&d.filter(({element:b})=>b.isConnected).map(({element:b,citationNum:y},j)=>{if(!t.find(D=>D.number===y))return null;const E=Array.from(new Map(t.map(D=>{const F=D.url.replace(/\/+$/,""),B=s?.find(P=>P.url.replace(/\/+$/,"")===F);return[F,{number:D.number,url:D.url,domain:w(D.url),title:B?.title}]})).values());return Nc.createPortal(l.jsx(If,{sources:E,citationNumber:y},`citation-${y}-${b}`),b,`citation-${y}-${j}`)}),x]})}function ln({...e}){return l.jsx(Ot.Root,{"data-slot":"dialog",...e})}function $f({...e}){return l.jsx(Ot.Portal,{"data-slot":"dialog-portal",...e})}function Lf({className:e,...t}){return l.jsx(Ot.Overlay,{"data-slot":"dialog-overlay",className:ce("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function un({className:e,children:t,showCloseButton:n=!0,...s}){return l.jsxs($f,{"data-slot":"dialog-portal",children:[l.jsx(Lf,{}),l.jsxs(Ot.Content,{"data-slot":"dialog-content",className:ce("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...s,children:[t,n&&l.jsxs(Ot.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[l.jsx(ie.XIcon,{}),l.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function dn({className:e,...t}){return l.jsx("div",{"data-slot":"dialog-header",className:ce("flex flex-col gap-2 text-center sm:text-left",e),...t})}function hn({className:e,...t}){return l.jsx("div",{"data-slot":"dialog-footer",className:ce("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function fn({className:e,...t}){return l.jsx(Ot.Title,{"data-slot":"dialog-title",className:ce("text-lg leading-none font-semibold",e),...t})}function mn({className:e,...t}){return l.jsx(Ot.Description,{"data-slot":"dialog-description",className:ce("text-muted-foreground text-sm",e),...t})}function pn({className:e,type:t,...n}){return l.jsx("input",{type:t,"data-slot":"input",className:ce("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-white px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...n})}function Ff({isOpen:e,title:t="Password Required",description:n="Please enter your password to continue",placeholder:s="Enter password...",onComplete:r}){const[o,i]=f.useState(""),[a,c]=f.useState(!1),[u,d]=f.useState(!1),h=async p=>{if(p.preventDefault(),!!o.trim()){d(!0);try{r(o)}finally{d(!1)}}},m=()=>{i(""),r(null)};return l.jsx(ln,{open:e,children:l.jsx(un,{showCloseButton:!1,children:l.jsxs("form",{onSubmit:h,children:[l.jsxs(dn,{children:[l.jsx(fn,{children:t}),l.jsx(mn,{children:n})]}),l.jsx("div",{className:"py-4",children:l.jsxs("div",{className:"relative",children:[l.jsx(pn,{type:a?"text":"password",value:o,onChange:p=>i(p.target.value),placeholder:s,className:"pr-10",autoFocus:!0,disabled:u}),l.jsx("button",{type:"button",onClick:()=>c(!a),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:u,children:a?l.jsx(ie.EyeOff,{className:"h-4 w-4"}):l.jsx(ie.Eye,{className:"h-4 w-4"})})]})}),l.jsxs(hn,{children:[l.jsx(je,{type:"button",variant:"ghost",onClick:m,disabled:u,children:"Cancel"}),l.jsx(je,{type:"submit",disabled:!o.trim()||u,children:u?"Submitting...":"Submit"})]})]})})})}function Bf({isOpen:e,title:t="Email Required",description:n="Please enter your email address",placeholder:s="Enter email address...",onComplete:r}){const[o,i]=f.useState(""),[a,c]=f.useState(!0),[u,d]=f.useState(!1),h=x=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(x),m=x=>{i(x),x.trim()?c(h(x)):c(!0)},p=async x=>{if(x.preventDefault(),!o.trim()||!h(o)){c(!1);return}d(!0);try{r(o)}finally{d(!1)}},w=()=>{i(""),c(!0),r(null)};return l.jsx(ln,{open:e,children:l.jsx(un,{showCloseButton:!1,children:l.jsxs("form",{onSubmit:p,children:[l.jsxs(dn,{children:[l.jsxs(fn,{className:"flex items-center gap-2",children:[l.jsx(ie.Mail,{className:"h-5 w-5"}),t]}),l.jsx(mn,{children:n})]}),l.jsxs("div",{className:"py-4",children:[l.jsx(pn,{type:"email",value:o,onChange:x=>m(x.target.value),placeholder:s,className:a?"":"border-red-500",autoFocus:!0,disabled:u}),!a&&l.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid email address"})]}),l.jsxs(hn,{children:[l.jsx(je,{type:"button",variant:"ghost",onClick:w,disabled:u,children:"Cancel"}),l.jsx(je,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function zf({isOpen:e,title:t="Phone Number Required",description:n="Please enter your phone number",placeholder:s="Enter phone number...",onComplete:r}){const[o,i]=f.useState(""),[a,c]=f.useState(!0),[u,d]=f.useState(!1),h=b=>{const y=b.replace(/\D/g,"");return y.length<=3?y:y.length<=6?`(${y.slice(0,3)}) ${y.slice(3)}`:`(${y.slice(0,3)}) ${y.slice(3,6)}-${y.slice(6,10)}`},m=b=>b.replace(/\D/g,"").length===10,p=b=>{const y=h(b);i(y),y.trim()?c(m(y)):c(!0)},w=async b=>{if(b.preventDefault(),!o.trim()||!m(o)){c(!1);return}d(!0);try{const y=o.replace(/\D/g,"");r(y)}finally{d(!1)}},x=()=>{i(""),c(!0),r(null)};return l.jsx(ln,{open:e,children:l.jsx(un,{showCloseButton:!1,children:l.jsxs("form",{onSubmit:w,children:[l.jsxs(dn,{children:[l.jsxs(fn,{className:"flex items-center gap-2",children:[l.jsx(ie.Phone,{className:"h-5 w-5"}),t]}),l.jsx(mn,{children:n})]}),l.jsxs("div",{className:"py-4",children:[l.jsx(pn,{type:"tel",value:o,onChange:b=>p(b.target.value),placeholder:s,className:a?"":"border-red-500",maxLength:14,autoFocus:!0,disabled:u}),!a&&l.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid 10-digit phone number"})]}),l.jsxs(hn,{children:[l.jsx(je,{type:"button",variant:"ghost",onClick:x,disabled:u,children:"Cancel"}),l.jsx(je,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Uf({isOpen:e,title:t="PIN Required",description:n="Please enter your PIN",placeholder:s="Enter PIN...",length:r=4,onComplete:o}){const[i,a]=f.useState(""),[c,u]=f.useState(!1),d=p=>{const w=p.replace(/\D/g,"");a(w.slice(0,r))},h=async p=>{if(p.preventDefault(),i.length===r){u(!0);try{o(i)}finally{u(!1)}}},m=()=>{a(""),o(null)};return l.jsx(ln,{open:e,children:l.jsx(un,{showCloseButton:!1,children:l.jsxs("form",{onSubmit:h,children:[l.jsxs(dn,{children:[l.jsxs(fn,{className:"flex items-center gap-2",children:[l.jsx(ie.Shield,{className:"h-5 w-5"}),t]}),l.jsx(mn,{children:n})]}),l.jsxs("div",{className:"py-4",children:[l.jsx(pn,{type:"password",value:i,onChange:p=>d(p.target.value),placeholder:s,className:"text-center text-lg tracking-widest",maxLength:r,autoFocus:!0,disabled:c}),l.jsxs("p",{className:"text-sm text-gray-500 mt-1 text-center",children:["Enter ",r,"-digit PIN"]})]}),l.jsxs(hn,{children:[l.jsx(je,{type:"button",variant:"ghost",onClick:m,disabled:c,children:"Cancel"}),l.jsx(je,{type:"submit",disabled:i.length!==r||c,children:c?"Submitting...":"Submit"})]})]})})})}function $s({isOpen:e,title:t="Secure Input Required",description:n="Please enter the requested information",placeholder:s="Enter value...",type:r="password",onComplete:o}){const[i,a]=f.useState(""),[c,u]=f.useState(!1),d=async m=>{if(m.preventDefault(),!!i.trim()){u(!0);try{o(i)}finally{u(!1)}}},h=()=>{a(""),o(null)};return l.jsx(ln,{open:e,children:l.jsx(un,{showCloseButton:!1,children:l.jsxs("form",{onSubmit:d,children:[l.jsxs(dn,{children:[l.jsxs(fn,{className:"flex items-center gap-2",children:[l.jsx(ie.Lock,{className:"h-5 w-5"}),t]}),l.jsx(mn,{children:n})]}),l.jsx("div",{className:"py-4",children:l.jsx(pn,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:c})}),l.jsxs(hn,{children:[l.jsx(je,{type:"button",variant:"ghost",onClick:h,disabled:c,children:"Cancel"}),l.jsx(je,{type:"submit",disabled:!i.trim()||c,children:c?"Submitting...":"Submit"})]})]})})})}function _f({isOpen:e,title:t,description:n,fields:s,onComplete:r,submitText:o="Submit",cancelText:i="Cancel"}){const[a,c]=f.useState(()=>{const T={};return s.forEach(V=>{T[V.name]=V.value||""}),T}),[u,d]=f.useState({}),[h,m]=f.useState({}),[p,w]=f.useState(!1),x=T=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(T)?null:"Please enter a valid email address",b=T=>T.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",y=(T,V=4)=>T.length===V?null:`PIN must be ${V} digits`,j=T=>{const V=T.replace(/\D/g,"");return V.length<=3?V:V.length<=6?`(${V.slice(0,3)}) ${V.slice(3)}`:`(${V.slice(0,3)}) ${V.slice(3,6)}-${V.slice(6,10)}`},M=(T,V,O)=>{let R=V,W=null;switch(O.type){case"phone":R=j(V),R.trim()&&(W=b(R));break;case"email":V.trim()&&(W=x(V));break;case"pin":R=V.replace(/\D/g,"").slice(0,6),R.trim()&&(W=y(R));break}!W&&O.validation&&R.trim()&&(W=O.validation(R)),c(oe=>({...oe,[T]:R})),d(oe=>({...oe,[T]:W||""}))},E=()=>{const T={};let V=!0;return s.forEach(O=>{const R=a[O.name]||"";let W=null;if(O.required&&!R.trim())W=`${O.label} is required`;else if(R.trim()){switch(O.type){case"email":W=x(R);break;case"phone":W=b(R);break;case"pin":W=y(R);break}!W&&O.validation&&(W=O.validation(R))}W&&(T[O.name]=W,V=!1)}),d(T),V},D=async T=>{if(T.preventDefault(),!!E()){w(!0);try{const V={};s.forEach(O=>{const R=a[O.name]?.trim();R&&(O.type==="phone"?V[O.name]=R.replace(/\D/g,""):V[O.name]=R)}),r(V)}finally{w(!1)}}},F=()=>{c({}),d({}),m({}),r(null)},B=T=>{m(V=>({...V,[T]:!V[T]}))},P=T=>{switch(T.type){case"password":return h[T.name]?"text":"password";case"email":return"email";case"phone":return"tel";case"pin":case"ssn":return"password";default:return"text"}},z=T=>{if(T.placeholder)return T.placeholder;switch(T.type){case"email":return"Enter email address...";case"phone":return"Enter phone number...";case"password":return"Enter password...";case"pin":return"Enter PIN...";case"ssn":return"XXX-XX-XXXX";case"creditCard":return"XXXX XXXX XXXX XXXX";default:return`Enter ${T.label.toLowerCase()}...`}};return l.jsx(ln,{open:e,children:l.jsx(un,{showCloseButton:!1,className:"max-w-md",children:l.jsxs("form",{onSubmit:D,children:[l.jsxs(dn,{children:[l.jsx(fn,{children:t}),n&&l.jsx(mn,{children:n})]}),l.jsx("div",{className:"py-4 space-y-4",children:s.map(T=>l.jsxs("div",{children:[l.jsxs("label",{className:"block text-sm font-medium mb-1",children:[T.label,T.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsxs("div",{className:"relative",children:[l.jsx(pn,{type:P(T),value:a[T.name]||"",onChange:V=>M(T.name,V.target.value,T),placeholder:z(T),className:u[T.name]?"border-red-500":"",disabled:p,autoFocus:T===s[0],maxLength:T.type==="pin"?6:T.type==="phone"?14:void 0}),T.type==="password"&&l.jsx("button",{type:"button",onClick:()=>B(T.name),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:p,children:h[T.name]?l.jsx(ie.EyeOff,{className:"h-4 w-4"}):l.jsx(ie.Eye,{className:"h-4 w-4"})})]}),u[T.name]&&l.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[l.jsx(ie.AlertCircle,{className:"h-3 w-3"}),u[T.name]]})]},T.name))}),l.jsxs(hn,{children:[l.jsx(je,{type:"button",variant:"ghost",onClick:F,disabled:p,children:i}),l.jsx(je,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const oc=f.createContext(void 0);function ac(){const e=f.useContext(oc);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function cc({children:e}){const[t,n]=f.useState(null),[s,r]=f.useState(null),o=f.useRef(null),i=f.useRef(null),a=f.useCallback(p=>new Promise(w=>{n(p),o.current=w}),[]),c=f.useCallback(p=>new Promise(w=>{r(p),i.current=w}),[]),u=f.useCallback(p=>{o.current&&(o.current(p),o.current=null),n(null)},[]),d=f.useCallback(p=>{i.current&&(i.current(p),i.current=null),r(null)},[]),h=()=>{if(s){const w=s.fields.map(x=>({name:x.name,type:x.type==="text"?"text":x.type==="password"?"password":x.type==="email"?"email":x.type==="phone"?"phone":x.type==="pin"?"pin":x.type==="ssn"?"ssn":x.type==="creditCard"?"creditCard":"text",label:x.label,placeholder:x.placeholder,required:x.required!==!1,value:x.value}));return l.jsx(_f,{isOpen:!0,title:s.title,description:s.description,fields:w,onComplete:d})}if(!t)return null;const p={isOpen:!0,title:t.title,description:t.description,placeholder:t.placeholder,onComplete:u};switch(t.type){case"password":return l.jsx(Ff,{...p});case"email":return l.jsx(Bf,{...p});case"phone":return l.jsx(zf,{...p});case"pin":return l.jsx(Uf,{...p});case"ssn":return l.jsx($s,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return l.jsx($s,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return l.jsx($s,{...p})}},m=f.useMemo(()=>({showSecureModal:a,showSecureForm:c}),[a,c]);return l.jsxs(oc.Provider,{value:m,children:[e,h()]})}function Xf(e){try{const t=new URL(e),n=`${t.protocol}//${t.host}${t.pathname}`,s=t.hash?t.hash.substring(1):void 0;return{baseUrl:n,anchor:s}}catch{const t=e.indexOf("#");return t!==-1?{baseUrl:e.substring(0,t),anchor:e.substring(t+1)}:{baseUrl:e}}}function Wf(e){try{const t=new URL(e),s=t.pathname.split("/").filter(a=>a.length>0);if(s.length===0)return t.hostname;const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||t.hostname}catch{const t=e.indexOf("#"),n=t!==-1?e.substring(0,t):e,s=n.split("/").filter(r=>r.length>0);if(s.length>0){const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||n}return n}}function go(e){let t=e.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=t.match(n),r=new Map,o=[],i=new Map,a=new Map,c=new Map,u=new Map;if(s&&s[1]){const P=s[1],z=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let T;for(;(T=z.exec(P))!==null;)if(T[1]&&T[2]){const V=parseInt(T[1],10),O=T[2].replace(/[.,;:!?]+$/,""),R=O.replace(/\/+$/,"");if(a.has(R)||a.set(R,O),i.has(R)||i.set(R,[]),i.get(R).push(V),!c.has(R))c.set(R,V);else{const W=c.get(R);V<W&&c.set(R,V)}}for(const[V,O]of i.entries()){const R=c.get(V);for(const W of O)W!==R&&u.set(W,R)}for(const[V,O]of c.entries()){const R=a.get(V)||V;r.set(O,R),o.push({number:O,url:R})}}let d,h=t;s&&s[0]&&(d=s[0],h=t.replace(n,""));const m=[];let p=0;const w=/```[\s\S]*?```|`[^`]+`/g;let x;for(;(x=w.exec(h))!==null;)x.index>p&&m.push({type:"text",content:h.slice(p,x.index),start:p,end:x.index}),m.push({type:"code",content:x[0],start:x.index,end:x.index+x[0].length}),p=x.index+x[0].length;p<h.length&&m.push({type:"text",content:h.slice(p),start:p,end:h.length});const b=m.map(P=>{if(P.type==="code")return P.content;let z=P.content;return z=z.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(V,O,R)=>{const W=parseInt(O,10),oe=R.replace(/\/+$/,""),le=u.get(W)||W;return c.has(oe)||(c.set(oe,le),r.has(le)||(r.set(le,R),o.push({number:le,url:R}))),`[${le}]`}),z=z.replace(/\[(\d+)\]/g,(V,O)=>{const R=parseInt(O,10);return`[${u.get(R)||R}]`}),z}),y=[];for(const[P,z]of c.entries()){const T=a.get(P)||P,{baseUrl:V,anchor:O}=Xf(T),R=Wf(T);y.push({url:T,baseUrl:V,numbers:[z],anchor:O,title:R})}y.sort((P,z)=>(P.numbers[0]||0)-(z.numbers[0]||0));const j=new Map;let M=1;for(const P of y){const z=P.numbers[0];j.set(z,M),P.numbers=[M],M++}const E=new Map;for(const[P,z]of r.entries()){const T=j.get(P);T&&E.set(T,z)}const D=o.map(P=>{const z=j.get(P.number);return z?{number:z,url:P.url}:P}).filter(P=>j.has(P.number)),F=Array.from(j.entries()).sort((P,z)=>z[0]-P[0]);let B=b.join("");for(const[P,z]of F){const T=new RegExp(`\\[${P}\\](?!\\d)`,"g");B=B.replace(T,`[${z}]`)}return{processedText:B,citations:D.sort((P,z)=>P.number-z.number),citationMap:E,groupedCitations:y,referencesText:d}}function Dn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Dn(t)}catch{return e}if(Array.isArray(e))return e.map(Dn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Dn(s);return t}return e}function Ls(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Dn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Dn(e):{}}function qf({theme:e="auto",layout:t="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:c=800,initiallyExpanded:u=!1,tools:d=[],safeTools:h=[],toolMetadata:m,systemPrompt:p="",tokenEndpoint:w="/api/arcten/token",apiBaseUrl:x="https://api.arcten.com",user:b,state:y,onStateChange:j,allowStateEdits:M=!0,sources:E,ragConfig:D,showCitations:F=!0,sensitiveParams:B,autoDetectSensitive:P=!1}){const{showSecureModal:z}=ac(),T=f.useMemo(()=>D!==void 0?D:E&&E.length>0?{enabled:!0,organizationId:E[0],autoExecute:!0,filters:void 0}:{enabled:!1},[E,D]),[V,O]=f.useState(null),R=f.useRef(null),[W,oe]=f.useState(null),[le,Y]=f.useState(null),te=f.useRef(null),J=y!==void 0,[be,He]=f.useState({}),Ne=f.useRef({});J&&y?Ne.current=y:J||(Ne.current=be);const[gn,$t]=f.useState(!1),[bs,Lt]=f.useState(null),et=f.useRef(!1),[_e,Ft]=f.useState(u),[Je,Bt]=f.useState(i),[zt,yn]=f.useState(600),[de,wt]=f.useState(!1),[ne,Te]=f.useState(!1),[Xe,Ut]=f.useState(!1),[Ae,xn]=f.useState({x:100,y:100}),[Tt,ot]=f.useState(!1),[St,at]=f.useState({x:0,y:0}),[ct,Xn]=f.useState(!1),bn=f.useRef(null),_t=f.useRef(null),[Xt,jt]=f.useState(""),[vn,tt]=f.useState(null),[nt,Wt]=f.useState("Thinking..."),[We,Ve]=f.useState(new Set),[Wn,qn]=f.useState(""),[Ie,Kn]=f.useState([]),[wn,Tn]=f.useState(!1),[Oe,Gn]=f.useState([]),[$e,Ct]=f.useState(()=>typeof window<"u"?crypto.randomUUID():null),[lt,De]=f.useState(!1),[Yn,qt]=f.useState(!1),[qr,Kt]=f.useState([]),Sn=f.useCallback(async(g,C=3)=>{if(!$e||!R.current)return;const I=async()=>{const L=`${x.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,_=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${R.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:$e,updates:g},format:"json"})});if(!_.ok){if(_.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const ee=await _.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${_.status} ${ee}`)}};for(let $=0;$<C;$++)try{await I(),Lt(null);return}catch(L){if($===C-1){const ee=L instanceof Error?L:new Error(String(L));throw Lt(ee),console.error("Failed to sync state to Convex after retries:",L),ee}await new Promise(ee=>setTimeout(ee,Math.pow(2,$)*100))}},[$e,x,R]),Pt=f.useMemo(()=>function(){return Ne.current},[]),At=f.useMemo(()=>async function(C){const I={...Ne.current,...C};Ne.current=I,J||He(I),j&&j(I);try{await Sn(C)}catch($){throw $}},[Sn,j,J]);f.useEffect(()=>{J&&y&&(Ne.current=y)},[J,y]);const v=f.useMemo(()=>T?.enabled?async function(C,I=20,$){if(E&&E.length>1){const ee=E.map(G=>fetch(`${x}/search`,{method:"POST",headers:{"Content-Type":"application/json",...R.current?{Authorization:`Bearer ${R.current}`}:{}},body:JSON.stringify({q:C,k:Math.min(I,100),organizationId:G,...Object.keys(_).length>0?{filters:_}:{}})}).then(X=>X.ok?X.json():null)),H=await Promise.all(ee),se=[];for(const G of H)G?.candidates&&se.push(...G.candidates);se.sort((G,X)=>{const ye=G.scores?.rerank||G.scores?.dense||0;return(X.scores?.rerank||X.scores?.dense||0)-ye});const U=se.slice(0,I).map((G,X)=>{const ye=G.citation||G.url;return{rank:X+1,doc_id:G.doc_id,block_id:G.block_id,url:G.url,citation:ye,title:G.title||"Untitled",snippet:G.snippet,score:G.scores?.rerank||G.scores?.dense||0,metadata:{site:G.metadata?.site,lang:G.metadata?.lang,contentType:G.metadata?.content_type}}});return{success:!0,query:C,total:se.length,results:U,summary:`Found ${se.length} relevant results across ${E.length} source(s) for "${C}". Top result: ${U[0]?.title||"N/A"}`}}const L=T.organizationId&&T.organizationId!=="default"?T.organizationId:void 0,_={...T.filters,...$};try{const ee={q:C,k:Math.min(I,100)};L&&(ee.organizationId=L),Object.keys(_).length>0&&(ee.filters=_);const H={"Content-Type":"application/json"};R.current&&(H.Authorization=`Bearer ${R.current}`);const se=await fetch(`${x}/search`,{method:"POST",headers:H,body:JSON.stringify(ee)});if(!se.ok){const X=await se.text();return{success:!1,error:`Search failed: ${se.status} ${X}`}}const U=await se.json(),G=U.candidates.map((X,ye)=>{const me=X.citation||X.url;return{rank:ye+1,doc_id:X.doc_id,block_id:X.block_id,url:X.url,citation:me,title:X.title||"Untitled",snippet:X.snippet,score:X.scores?.rerank||X.scores?.dense||0,metadata:{site:X.metadata?.site,lang:X.metadata?.lang,contentType:X.metadata?.content_type}}});return{success:!0,query:U.query,total:U.total,results:G,summary:`Found ${U.total} relevant results for "${C}". Top result: ${G[0]?.title||"N/A"}`}}catch(ee){return{success:!1,error:ee instanceof Error?ee.message:"Unknown error occurred"}}}:null,[D,x,R]),A=f.useMemo(()=>T?.enabled?async function(C,I){const $=T.organizationId&&T.organizationId!=="default"?T.organizationId:E&&E.length>0?E[0]:void 0;try{const L={"Content-Type":"application/json"};R.current&&(L.Authorization=`Bearer ${R.current}`);const _=await fetch(`${x}/fetch`,{method:"POST",headers:L,body:JSON.stringify({doc_id:C,block_ids:I,...$?{organizationId:$}:{}})});if(!_.ok){const H=await _.text();return{success:!1,error:`Fetch failed: ${_.status} ${H}`}}const ee=await _.json();return{success:!0,blocks:ee.blocks||[],fullContent:ee.fullContent||"",pageUrl:ee.pageUrl||"",pageTitle:ee.pageTitle||"",summary:`Fetched ${ee.blocks?.length||0} blocks from ${ee.pageTitle||C}`}}catch(L){return{success:!1,error:L instanceof Error?L.message:"Unknown error occurred"}}}:null,[D,x,R]),S=f.useMemo(()=>{const g=[...d,...h,Pt];return(!J||M)&&g.push(At),T?.enabled&&(v&&g.push(v),A&&g.push(A)),g},[d,h,Pt,At,v,A,J,M,T]),k=f.useMemo(()=>tc(S,m),[S,m]),N=f.useMemo(()=>{const g=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!J||M)&&g.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const C=[];return T?.enabled&&C.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...k,...g,...C]},[k,J,M,T]),K=f.useMemo(()=>new Set(N.map(g=>g.name)),[N]),Z=f.useMemo(()=>N.filter(g=>g.name==="getState"?!0:g.name==="setState"?!J||M:K.has(g.name)),[N,K,J,M]),ge=f.useMemo(()=>{const g=new Map,C=new Map(k.map(I=>[I.name,I]));return g.set("getState",Pt),(!J||M)&&g.set("setState",At),T?.enabled&&(v&&g.set("searchDocs",v),A&&g.set("fetchDocContent",A)),S.forEach(I=>{if(I===Pt||I===At||I===v||I===A)return;const $=I[Ze];if($){const _=C.get($);if(_){g.set(_.name,I);return}}const L=N.find(_=>_.name===I.name);L&&g.set(L.name,I)}),g},[S,N,Pt,At,v,A,J,M,T]),ae=f.useMemo(()=>{const g=new Set;g.add("getState"),g.add("setState"),T?.enabled&&T.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent"));const C=new Map(N.map(I=>[I.name,I]));return h.forEach(I=>{const $=I[Ze];if($&&C.has($))g.add($);else{const L=N.find(_=>_.name===I.name);L&&g.add(L.name)}}),g},[h,N,T]),ke=["Thinking...","Pondering...","Contemplating...","Considering...","Analyzing...","Processing...","Reasoning...","Mulling it over...","Computing...","Cooking up a response...","Brewing ideas...","Connecting the dots...","Piecing it together...","Spinning up thoughts...","Loading brain cells...","Sharpening pencils...","Herding ideas...","Warming up neurons...","Stirring the think-pot...","Plotting a plan...","Wiggling the logic wires...","Rolling ideas around...","Charging the brainstorm...","Booting the brain...","Dusting off the cortex...","Running mental diagnostics...","Fetching cleverness...","Whisking up notions...","Tuning the idea radio...","Juggling possibilities...","Breathing in inspiration...","Squeezing the thought sponge...","Tickling the gray matter...","Bubbling up insights...","Spicing the soup of thought...","Lacing up hypotheses...","Winding the idea clock...","Casting the net for clues...","Polishing the crystal ball...","Mapping the maze...","Crunching the brain-biscuits...","Cueing the eureka moment...","Summoning the muse...","Knocking on insight’s door...","Combing the noodle...","Sailing the think-ship...","Scooping brain gelato...","Testing wild hunches...","Tick-tocking the neurons...","Planting idea seeds...","Shaking the thought snow globe...","Unlocking the mental toolbox...","Nudging the puzzle pieces...","Lighting the idea bulb...","Preheating the oven of insight...","Mixing the mental trail mix...","Spooling up reasoning reels...","Skimming the mind-palace index...","Surfing the thought waves...","Kicking the tires on ideas...","Rattling the idea can...","Waving the logic wand..."];f.useEffect(()=>{if(typeof window<"u"){const g=localStorage.getItem("arcten-sidebar-expanded");g&&Ft(JSON.parse(g));const C=localStorage.getItem("arcten-sidebar-width");C&&Bt(parseInt(C));const I=localStorage.getItem("arcten-sidebar-height");I&&yn(parseInt(I));const $=localStorage.getItem("arcten-sidebar-detached");$&&Te(JSON.parse($));const L=localStorage.getItem("arcten-sidebar-position");if(L){const ee=JSON.parse(L),H=50,se=Math.max(H-i,Math.min(ee.x,window.innerWidth-H)),U=Math.max(0,Math.min(ee.y,window.innerHeight-H));xn({x:se,y:U})}const _=localStorage.getItem("arcten-sidebar-minimized");_&&Ut(JSON.parse(_)),Xn(!0)}},[]);const Q=f.useMemo(()=>b,[b?.id]);f.useEffect(()=>((async()=>{try{const C=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Q})});if(!C.ok)throw new Error("Failed to fetch token");const I=await C.json();O(I.clientToken),R.current=I.clientToken,Y(I.expiresAt),oe(null)}catch(C){oe(C instanceof Error?C.message:"Failed to fetch token")}})(),()=>{te.current&&clearTimeout(te.current)}),[w,Q]),f.useEffect(()=>{if(!le)return;te.current&&clearTimeout(te.current);const g=Math.floor(Date.now()/1e3),C=le-g,$=Math.max(0,C-5);return te.current=setTimeout(async()=>{try{const L=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Q})});if(!L.ok)throw new Error("Failed to refresh token");const _=await L.json();O(_.clientToken),R.current=_.clientToken,Y(_.expiresAt),oe(null)}catch(L){console.error("Token refresh failed:",L),oe(L instanceof Error?L.message:"Failed to refresh token")}},$*1e3),()=>{te.current&&clearTimeout(te.current)}},[le,w,Q]),f.useEffect(()=>{(async()=>{if(S.length!==0)try{const C=S.map($=>({name:$.name,code:$.toString()})),I=await fetch(`${x}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:C})});if(I.ok){const $=await I.json();Kn($.tools)}}catch(C){console.error("Failed to fetch tool descriptions:",C)}})()},[S]),f.useEffect(()=>{Promise.resolve().then(()=>kf).then(g=>{tt(()=>g.Response)})},[]),f.useEffect(()=>{const g=()=>{qn(window.location.pathname)};g(),window.addEventListener("popstate",g);const C=setInterval(g,500);return()=>{window.removeEventListener("popstate",g),clearInterval(C)}},[]);const re=f.useCallback(async()=>{if(!(!Q?.id||!V)){qt(!0);try{const C=await(await fetch(`${x}/conversations`,{headers:{Authorization:`Bearer ${V}`}})).json();Gn(C.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{qt(!1)}}},[Q?.id,V,x]);f.useEffect(()=>{Q?.id&&V&&re()},[Q?.id,V,re]);function qe(g){const C=Math.floor((Date.now()-g)/1e3);return C<60?"now":C<3600?`${Math.floor(C/60)}m`:C<86400?`${Math.floor(C/3600)}h`:`${Math.floor(C/86400)}d`}function ut(){const g=crypto.randomUUID();Ct(g),Jn([]),Kt([]),De(!1);const C=J?y||{}:{};Ne.current=C,J||He(C),j&&j(C),et.current=!1}async function jn(g){if(V)try{await fetch(`${x}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${V}`}}),Gn(Oe.filter(C=>C._id!==g)),g===$e&&ut()}catch(C){console.error("Failed to delete conversation:",C)}}async function Re(g){Ct(g.chatId),De(!1),qt(!0);try{const C=await fetch(`${x}/conversations/${g.chatId}/messages`,{headers:{Authorization:`Bearer ${R.current}`}});if(!C.ok)throw new Error(`Failed to fetch messages: ${C.statusText}`);const $=(await C.json()).messages||[];Jn($),Kt($)}catch(C){console.error("Failed to load conversation messages:",C);const I=g.messages||[];Jn(I),Kt(I)}finally{qt(!1)}}const dt=async(g,C={})=>{const I=C.headers?new Headers(C.headers):new Headers;return I.delete("user-agent"),I.delete("User-Agent"),fetch(g,{...C,headers:I})},{messages:ve,sendMessage:vs,status:Me,error:Kr,stop:Hn,addToolResult:kt,setMessages:Jn}=yo.useChat({id:$e||void 0,transport:new cs.DefaultChatTransport({api:`${x}/chat`,fetch:dt,headers:()=>{const g={};return R.current&&(g.Authorization=`Bearer ${R.current}`),g},body:()=>({tools:Z.map(C=>({name:C.name,description:C.description,inputSchema:C.jsonSchema})),systemPrompt:p,currentRoute:Wn,state:Ne.current})}),sendAutomaticallyWhen:cs.lastAssistantMessageIsCompleteWithToolCalls});f.useEffect(()=>{const g=ve[ve.length-1];if(!g||g.role!=="assistant")return;const C=g.parts?.filter(I=>I.type?.startsWith("tool-")&&I.state==="input-available"&&typeof I.toolCallId=="string"&&I.input!==void 0)||[];for(const I of C){const $=I,L=$.type?.replace("tool-","")||"",_=$.toolCallId;if(ae.has(L)){if(We.has(_))continue;Ve(H=>H.has(_)?H:new Set(H).add(_)),(async()=>{try{const H=ge.get(L);if(!H){console.warn(`[ArctenAgent] Tool ${L} not found in toolsMap. Available tools:`,Array.from(ge.keys())),kt({toolCallId:_,tool:L,output:`Error: Tool ${L} not found`}),Ve(X=>{const ye=new Set(X);return ye.delete(_),ye});return}const se=Ls($.input),U=Z.find(X=>X.name===L);let G;if(U&&U.jsonSchema?.properties){const ye=Object.keys(U.jsonSchema.properties).map(me=>se[me]);console.log(`[ArctenAgent] Executing safe tool ${L} with args:`,ye),G=await H(...ye)}else if(L==="getState")G=H();else if(L==="setState"){const X=se.updates||se;G=await H(X)}else G=await H(...Object.values(se));console.log(`[ArctenAgent] Tool ${L} completed, result:`,G),kt({toolCallId:_,tool:L,output:G}),Ve(X=>{const ye=new Set(X);return ye.delete(_),ye})}catch(H){console.error(`[ArctenAgent] Error executing safe tool ${L}:`,H),kt({toolCallId:_,tool:L,output:`Error: ${H instanceof Error?H.message:String(H)}`}),Ve(se=>{const U=new Set(se);return U.delete(_),U})}})()}}},[ve,ae,ge,Z,kt]),f.useEffect(()=>{if(!$e||!R.current)return;(async()=>{$t(!0),Lt(null);try{const I=`${x.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,$=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${R.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:$e},format:"json"})});if(!$.ok){if($.status===404||$.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${$.status}), using empty state`);const U=J?y||{}:{};Ne.current=U,J||He(U),j&&j(U),et.current=!0,$t(!1);return}const se=await $.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${$.status} ${se}`)}const _=(await $.json())?.value||{},ee=!et.current;let H;ee?(H={...J?y||{}:{},..._},et.current=!0):H=_,Ne.current=H,J||He(H),j&&j(H)}catch(C){C instanceof TypeError&&C.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",C):console.error("[ArctenAgent] Failed to fetch state:",C);const $=C instanceof Error?C:new Error(String(C));if(Lt($),!et.current){const L=J?y||{}:{};Ne.current=L,J||He(L),j&&j(L),et.current=!0}}finally{$t(!1)}})()},[$e,x,J,y,j]),f.useEffect(()=>{_e&&_t.current&&_t.current.focus()},[_e,ve]);function hc(){Ft(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function fc(){Ft(!1),localStorage.setItem("arcten-sidebar-expanded","false")}f.useEffect(()=>{},[_e]),f.useEffect(()=>{bn.current&&bn.current.scrollIntoView({behavior:"smooth"})},[ve]),f.useEffect(()=>{function g(C){C.key==="Escape"&&(Me==="streaming"||Me==="submitted")&&(C.preventDefault(),Hn())}return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Me,Hn]);function mc(){const g=crypto.randomUUID();Ct(g),Jn([]),Kt([]),De(!1)}function Gr(g){if(g.preventDefault(),!Xt.trim())return;(Me==="streaming"||Me==="submitted")&&Hn();const C=ke[Math.floor(Math.random()*ke.length)]||"Thinking...";Wt(C),vs({text:Xt}),jt("")}function pc(g){const C=g.target.value;jt(C)}f.useEffect(()=>{if(!de)return;function g(I){if(ne){const $=I.clientX-Ae.x,L=I.clientY-Ae.y;$>=a&&$<=c&&Bt($),L>=400&&L<=1e3&&yn(L)}else{const $=window.innerWidth-I.clientX;$>=a&&$<=c&&Bt($)}}function C(){wt(!1),localStorage.setItem("arcten-sidebar-width",Je.toString()),localStorage.setItem("arcten-sidebar-height",zt.toString())}return window.addEventListener("mousemove",g),window.addEventListener("mouseup",C),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",C)}},[de,Je,zt,ne,Ae,a,c]);function gc(g){g.preventDefault(),wt(!0)}function yc(){Te(!0),Ut(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function xc(){Te(!1),Ut(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Yr(){Ut(!Xe),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Xe))}function bc(g){ne&&(ot(!0),at({x:g.clientX-Ae.x,y:g.clientY-Ae.y}))}return f.useEffect(()=>{if(!ne)return;function g(){xn(C=>{const $=window.innerWidth-50,L=window.innerHeight-50,_=50-Je,ee=0,H=Math.max(_,Math.min(C.x,$)),se=Math.max(ee,Math.min(C.y,L));if(H!==C.x||se!==C.y){const U={x:H,y:se};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(U)),U}return C})}return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[ne,Je]),f.useEffect(()=>{if(!Tt)return;function g(I){const $=I.clientX-St.x,L=I.clientY-St.y,_=50,ee=window.innerWidth-_,H=window.innerHeight-_,se=_-Je,U=0,G=Math.max(se,Math.min($,ee)),X=Math.max(U,Math.min(L,H));xn({x:G,y:X})}function C(){ot(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(Ae))}return window.addEventListener("mousemove",g),window.addEventListener("mouseup",C),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",C)}},[Tt,St,Ae,Je]),ct?W?l.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:l.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",W]})}):V?l.jsx(Bu,{features:yf,children:l.jsx(ns,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:ne?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:ne?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
20
20
  ${ne?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
21
- ${ze?"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"}
21
+ ${_e?"bg-stone-50 dark:bg-stone-900":"bg-stone-100 dark:bg-stone-800 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors duration-200"}
22
22
  ${ne?"border border-border":"border-l border-border"}
23
- ${ze?"":"w-[30px]"}
24
- `,style:ze?ne?{width:`${Je}px`,height:Ue?"auto":`${Ut}px`,left:`${Pe.x}px`,top:`${Pe.y}px`}:{width:`${Je}px`}:void 0,onClick:ze?void 0:hc,children:ze?l.jsxs(l.Fragment,{children:[!ne&&l.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:gc,children:l.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),ne&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:g=>{g.preventDefault(),Tt(!0)}}),l.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:g=>{g.preventDefault(),g.stopPropagation(),at(!0),ct({x:g.clientX-Pe.x,y:g.clientY-Pe.y})},children:l.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"})}),l.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:g=>{g.preventDefault(),Tt(!0)}})]}),l.jsxs("div",{className:"flex flex-col h-full",children:[l.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${ne?"cursor-move":""}`,onMouseDown:ne?bc:void 0,children:[l.jsx("h2",{className:`text-base font-semibold ${ne&&Ue?"cursor-pointer":""}`,onClick:ne&&Ue?g=>{g.stopPropagation(),Yr()}:void 0,children:r}),l.jsxs("div",{className:"flex items-center gap-1",onClick:g=>g.stopPropagation(),children:[l.jsxs(pt,{children:[l.jsx(gt,{asChild:!0,children:l.jsx("button",{type:"button",className:ae(Nt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:mc,"aria-label":"New chat",children:l.jsx(ie.Plus,{className:"h-4 w-4"})})}),l.jsx(yt,{children:"Start a new conversation"})]}),l.jsxs(pt,{children:[l.jsx(gt,{asChild:!0,children:l.jsx("button",{type:"button",className:ae(Nt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ne?xc:yc,"aria-label":ne?"Dock sidebar":"Float sidebar",children:ne?l.jsx(ie.Dock,{className:"h-4 w-4"}):l.jsx(ie.PictureInPicture2,{className:"h-4 w-4"})})}),l.jsx(yt,{children:ne?"Dock to sidebar":"Undock to floating window"})]}),l.jsxs(pt,{children:[l.jsx(gt,{asChild:!0,children:l.jsx("button",{type:"button",className:ae(Nt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ne?Yr:fc,"aria-label":ne?Ue?"Maximize":"Minimize":"Close sidebar",children:ne?Ue?l.jsx(ie.Maximize2,{className:"h-4 w-4"}):l.jsx(ie.Minimize2,{className:"h-4 w-4"}):l.jsx(ie.X,{className:"h-4 w-4"})})}),l.jsx(yt,{children:ne?Ue?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ue&&l.jsxs(l.Fragment,{children:[b&&Ve.length>0&&l.jsxs("div",{className:`border-b border-border ${ut?"flex flex-col flex-1":""}`,children:[l.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[l.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),l.jsx(Se,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{ut||se(),Ee(!ut)},children:ut?"Show less":"View all"})]}),l.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ut?"flex-1 overflow-y-auto":""}`,children:Ve.slice(0,ut?void 0:3).map(g=>l.jsxs("div",{className:"group relative",children:[l.jsxs(xf,{type:"button",className:ae(Nt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>ht(g),children:[l.jsx("span",{className:"text-xs truncate",children:g.title}),l.jsx("div",{className:"ml-2 flex items-center",children:l.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:Xe(g.updatedAt)})})]}),l.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:C=>{C.stopPropagation(),Ae(g._id)},"aria-label":"Delete conversation",children:l.jsx(ie.X,{className:"h-3 w-3"})})]},g._id))})]}),l.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[l.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:We.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&l.jsx("div",{className:"mb-6",children:o}),l.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),Re.length>0&&l.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:l.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(Tn?Re:Re.slice(0,10)).map(g=>l.jsxs(pt,{children:[l.jsx(gt,{asChild:!0,children:l.jsx(ws,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Ct(g.sampleUsage),Xt.current?.focus()},children:g.friendlyName})}),l.jsx(yt,{children:l.jsxs("div",{className:"max-w-xs",children:[l.jsx("p",{className:"font-medium",children:g.description}),l.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[l.jsx("span",{className:"font-medium",children:"Example:"}),' "',g.sampleUsage,'"']}),g.paramCount>0&&l.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[l.jsx("span",{className:"font-medium",children:"Parameters:"})," ",g.params.join(", ")]})]})})]},g.name)),Re.length>10&&!Tn&&l.jsxs(pt,{children:[l.jsx(gt,{asChild:!0,children:l.jsxs(ws,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Sn(!0),children:["+",Re.length-10," more"]})}),l.jsx(yt,{children:l.jsxs("div",{className:"max-w-xs",children:[l.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),l.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:Re.slice(10).map(g=>l.jsxs("div",{children:[l.jsxs("span",{className:"font-medium text-xs",children:[g.friendlyName,":"]}),l.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:g.description})]},g.name))}),l.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),Tn&&Re.length>10&&l.jsx(ws,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Sn(!1),children:"Show less"})]})})]}):l.jsxs(l.Fragment,{children:[We.map(g=>{const I=g.parts.filter(U=>U.type==="text").map(U=>U.text).join("");let $=g.parts;g.role==="assistant"&&g.parts.some(K=>K.timestamp)&&($=[...g.parts].sort((K,X)=>{const ye=K.timestamp||0,pe=X.timestamp||0;return ye-pe}));let L=[],_=new Map,ee=[],H,re=!0;if(g.role==="assistant"){const U=$.filter(pe=>pe.type==="text"&&pe.text),K=[],X=[];U.forEach(pe=>{const{citations:ft,citationMap:je,groupedCitations:Oe,referencesText:mt}=go(pe.text);L.push(...ft),K.push(je),Oe&&X.push(...Oe),mt&&(H=mt)}),K.forEach(pe=>{pe.forEach((ft,je)=>{_.has(je)||_.set(je,ft)})}),ee=Array.from(new Map(X.map(pe=>[pe.url,pe])).values()).sort((pe,ft)=>(pe.numbers[0]||0)-(ft.numbers[0]||0)),re=!(qe==="streaming"&&g.id===We.at(-1)?.id)}return l.jsx("div",{className:`${g.role==="user"?"flex justify-end":"w-full"}`,children:l.jsx("div",{className:`${g.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:g.role==="user"?l.jsx(bf,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:I}):l.jsx("div",{className:"space-y-2",children:$.map((U,K)=>{if(U.type?.startsWith("tool-")){const X=U.type?.replace("tool-","")||"",ye=Z.find(je=>je.name===X),pe=U.state==="input-available",ft=U.state==="output-available";if(pe&&he.has(X),pe){if(he.has(X))return null;const je=Ls(U.input);return l.jsx(ss,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:l.jsx(Tf,{toolName:X,description:ye?.description||"",args:je,onApprove:async()=>{if(_e.has(U.toolCallId))return;De(mt=>new Set(mt).add(U.toolCallId));const Oe=le.get(X);if(Oe)try{const mt=await Oe(...Object.values(je));Mt({toolCallId:U.toolCallId,tool:X,output:mt})}catch(mt){Mt({toolCallId:U.toolCallId,tool:X,output:`Error: ${mt}`})}},onDeny:async()=>{_e.has(U.toolCallId)||(De(Oe=>new Set(Oe).add(U.toolCallId)),Mt({toolCallId:U.toolCallId,tool:X,output:"User denied tool execution"}))}})},`${U.toolCallId}-${K}`)}else if(ft){const je=U.output==="User denied tool execution",Oe=Ls(U.input);return l.jsx(Sf,{toolName:X,args:Oe,isDenied:je,isSafe:he.has(X)},`${U.toolCallId}-${K}`)}return null}if(U.type==="text"&&U.text&&wn){const{processedText:X}=go(U.text),je=!$.slice(K+1).some(Oe=>Oe.type==="text"&&Oe.text)&&re&&_.size>0;return l.jsx(Of,{text:X,citations:L,citationMap:_,groupedCitations:je?ee:void 0,referencesText:je?H:void 0,ResponseComponent:wn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:F,showReferences:je},`${g.id}-${K}`)}return U.type==="reasoning"&&U.text?l.jsxs(sc,{className:"w-full",isStreaming:qe==="streaming"&&K===g.parts.length-1&&g.id===We.at(-1)?.id,children:[l.jsx(rc,{}),l.jsx(ic,{children:U.text})]},`${g.id}-${K}`):null})})})},g.id)}),l.jsx("div",{ref:vn})]})}),Kr&&l.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Kr.message]}),l.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[l.jsx(Fu,{mode:"wait",children:(qe==="streaming"||qe==="submitted")&&l.jsxs(ss,{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:[l.jsx(ss,{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]}}),l.jsx("p",{className:"text-xs text-muted-foreground",children:st})]})}),l.jsxs("form",{onSubmit:Gr,className:"relative",children:[l.jsx(vo,{ref:Xt,value:Wt,onChange:pc,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),Gr(g))}}),qe==="streaming"||qe==="submitted"?l.jsxs(pt,{children:[l.jsx(gt,{asChild:!0,children:l.jsx("button",{type:"button",className:ae(Nt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:Jn,children:l.jsx(ie.Square,{className:"h-4 w-4"})})}),l.jsxs(yt,{children:[l.jsx(Zr,{children:"Escape"})," to stop"]})]}):l.jsxs(pt,{children:[l.jsx(gt,{asChild:!0,children:l.jsx("button",{type:"submit",className:ae(Nt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Wt.trim(),children:l.jsx(ie.ArrowRight,{className:"h-4 w-4"})})}),l.jsxs(yt,{children:[l.jsx(Zr,{children:"Enter"})," to send"]})]})]})]})]}),l.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:[l.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),l.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),l.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):l.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[l.jsx(ie.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),l.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):l.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:l.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function Kf(e){return l.jsx(cc,{children:l.jsx(qf,{...e})})}const Gf={password:[/^password$/i,/^pwd$/i,/^pass$/i,/^newPassword$/i,/^oldPassword$/i,/^currentPassword$/i,/^confirmPassword$/i,/.*password.*/i],email:[/^email$/i,/^emailAddress$/i,/^mail$/i,/.*email.*/i],phone:[/^phone$/i,/^phoneNumber$/i,/^mobile$/i,/^cell$/i,/^cellPhone$/i,/^telephone$/i,/.*phone.*/i,/.*mobile.*/i],pin:[/^pin$/i,/^pinCode$/i,/^securityPin$/i,/^accessPin$/i,/.*pin$/i],ssn:[/^ssn$/i,/^socialSecurityNumber$/i,/^social$/i,/.*ssn.*/i,/.*social.*/i],creditCard:[/^creditCard$/i,/^cardNumber$/i,/^card$/i,/^ccNumber$/i,/^creditCardNumber$/i,/.*card.*/i,/^cvv$/i,/^cvc$/i,/^cvn$/i,/^securityCode$/i],text:[]};function An(e){for(const[t,n]of Object.entries(Gf))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function lc(e,t){return{password:{title:"Password Required",description:"Please enter your password to continue",placeholder:"Enter password..."},email:{title:"Email Required",description:"Please enter your email address",placeholder:"Enter email address..."},phone:{title:"Phone Number Required",description:"Please enter your phone number",placeholder:"Enter phone number..."},pin:{title:"PIN Required",description:"Please enter your PIN",placeholder:"Enter PIN..."},ssn:{title:"Social Security Number Required",description:"Please enter your Social Security Number",placeholder:"XXX-XX-XXXX"},creditCard:{title:"Credit Card Required",description:"Please enter your credit card information",placeholder:"XXXX XXXX XXXX XXXX"},text:{title:"Secure Input Required",description:`Please enter your ${t}`,placeholder:`Enter ${t}...`}}[e]}function uc(e,t,n){const s=Object.keys(n).length,r=t.length;return r>=3||s>=2||s>0&&s<r}function Yf(e,t,n,s={}){const r=[];return new Set([...t,...Object.keys(n)]).forEach(i=>{const a=i in n,c=n[i];if(!a&&s[i]!==void 0)return;const u={name:i,type:Hf(c||An(i)||"text"),label:dc(i),placeholder:Jf(i,c),required:!0,value:s[i]||void 0};u.type==="password"&&(u.validation=d=>d.length<8?"Password must be at least 8 characters":null),r.push(u)}),r.sort((i,a)=>{const c=i.name in n,u=a.name in n;return c===u?0:c?1:-1}),{shouldUseForm:uc(e,t,n),fields:r,title:Zf(e),description:Qf(e,r.length)}}function Hf(e){switch(e){case"password":return"password";case"email":return"email";case"phone":return"phone";case"pin":return"pin";case"ssn":return"ssn";case"creditCard":return"creditCard";default:return"text"}}function dc(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Jf(e,t){return t?lc(t,e).placeholder:`Enter ${dc(e).toLowerCase()}...`}function Zf(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Qf(e,t){const n=e.toLowerCase();return t<=2?`Please provide the required information to ${n}.`:`Please fill out the form below to ${n}. Required fields are marked with *.`}function Rn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Rn(t)}catch{return e}if(Array.isArray(e))return e.map(Rn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Rn(s);return t}return e}function em(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Rn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Rn(e):{}}function tm({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,sensitiveParams:c,autoDetectSensitive:u=!1,autoFormGeneration:d=!1,formMode:h="auto",systemPrompt:m="",initialMessages:p=[],conversationId:w,state:x,onStateChange:b,allowStateEdits:y=!0,onToolCall:j,onFinish:M,sources:N,ragConfig:D,ragFilters:F,secureInputHandler:B}={}){const P=f.useMemo(()=>D!==void 0?D:F?{enabled:!0,filters:F}:N&&N.length>0?{enabled:!0,organizationId:N[0],autoExecute:!0,filters:void 0}:{enabled:!1},[N,D,F]),z=f.useMemo(()=>{const v={};if(c)for(const[A,S]of Object.entries(c))if(v[A]={},Array.isArray(S))for(const k of S){const E=An(k);v[A][k]=E||"text"}else for(const[k,E]of Object.entries(S))v[A][k]=E;if(a){for(const[A,S]of Object.entries(a))if(S&&typeof S=="object"&&"sensitiveParams"in S){v[A]||(v[A]={});const k=S.sensitiveParams;if(Array.isArray(k))for(const E of k){const G=An(E);v[A][E]=G||"text"}else if(k&&typeof k=="object")for(const[E,G]of Object.entries(k))v[A][E]=G}}return v},[c,a,u]),[T,V]=f.useState(n||null),O=f.useRef(n||null),[R,W]=f.useState(null),[oe,ce]=f.useState(null),Y=f.useRef(null),[te,J]=f.useState([]),[be,He]=f.useState(w||(typeof window<"u"?crypto.randomUUID():null)),[Me,yn]=f.useState(!1),[Lt,vs]=f.useState(new Set),[Ft,tt]=f.useState(new Map),[ze,Bt]=f.useState(new Map),[Je,zt]=f.useState(new Map),[Ut,xn]=f.useState(new Map),de=x!==void 0,[Tt,ne]=f.useState({}),we=f.useRef({}),Ue=de?x||{}:Tt;de&&x?we.current=x:de||(we.current=Tt);const[_t,Pe]=f.useState(!1),[bn,St]=f.useState(null),at=f.useRef(!1),jt=f.useCallback(async(v,A=3)=>{if(!be||!O.current)return;const S=async()=>{const E=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,G=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:be,updates:v},format:"json"})});if(!G.ok){if(G.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const Z=await G.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${G.status} ${Z}`)}};for(let k=0;k<A;k++)try{await S(),St(null);return}catch(E){if(k===A-1){const Z=E instanceof Error?E:new Error(String(E));throw St(Z),console.error("Failed to sync state to Convex after retries:",E),Z}await new Promise(Z=>setTimeout(Z,Math.pow(2,k)*100))}},[be,e,O]),ct=f.useMemo(()=>function(){return we.current},[]),lt=f.useMemo(()=>async function(A){const S={...we.current,...A};we.current=S,de||ne(S),b&&b(S);try{await jt(A)}catch(k){throw k}},[jt,b,de]);f.useEffect(()=>{de&&x&&(we.current=x)},[de,x]);const Xn=f.useCallback(v=>B?B.showSecureModal(v):new Promise(A=>{tt(S=>new Map(S).set(v.id,v)),Bt(S=>new Map(S).set(v.id,A))}),[B]),vn=f.useCallback((v,A)=>{if(B)return;const S=ze.get(v);S&&(S(A),tt(k=>{const E=new Map(k);return E.delete(v),E}),Bt(k=>{const E=new Map(k);return E.delete(v),E}))},[ze,B]),Xt=f.useCallback(v=>B?B.showSecureForm(v):new Promise(A=>{zt(S=>new Map(S).set(v.id,v)),xn(S=>new Map(S).set(v.id,A))}),[B]),Wt=f.useCallback((v,A)=>{if(B)return;const S=Ut.get(v);S&&(S(A),zt(k=>{const E=new Map(k);return E.delete(v),E}),xn(k=>{const E=new Map(k);return E.delete(v),E}))},[Ut,B]),Ct=f.useCallback((v,A)=>{const S=z[v]||{},k=Object.keys(S).length>0;if(u){const E=Object.keys(A).filter(G=>An(G)!==null);return k||E.length>0}return k},[z,u]),wn=f.useCallback((v,A)=>{const S={...z[v]||{}};if(u){for(const k of Object.keys(A))if(!(k in S)){const E=An(k);E&&(S[k]=E)}}return S},[z,u]),nt=f.useMemo(()=>P?.enabled?async function(A,S=20,k){const E={...P.filters,...k};if(N&&N.length>1){const Z=N.map(Q=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...O.current?{Authorization:`Bearer ${O.current}`}:{}},body:JSON.stringify({q:A,k:Math.min(S,100),organizationId:Q,...Object.keys(E).length>0?{filters:E}:{}})}).then(se=>se.ok?se.json():null)),le=await Promise.all(Z),he=[];for(const Q of le)Q?.candidates&&he.push(...Q.candidates);he.sort((Q,se)=>{const Xe=Q.scores?.rerank||Q.scores?.dense||0;return(se.scores?.rerank||se.scores?.dense||0)-Xe});const Ne=he.slice(0,S).map((Q,se)=>{const Xe=Q.citation||Q.url;return{rank:se+1,doc_id:Q.doc_id,block_id:Q.block_id,url:Q.url,citation:Xe,title:Q.title||"Untitled",snippet:Q.snippet,score:Q.scores?.rerank||Q.scores?.dense||0,metadata:{site:Q.metadata?.site,lang:Q.metadata?.lang,contentType:Q.metadata?.content_type}}});return{success:!0,query:A,total:he.length,results:Ne,summary:`Found ${he.length} relevant results across ${N.length} source(s) for "${A}". Top result: ${Ne[0]?.title||"N/A"}`}}const G=P.organizationId&&P.organizationId!=="default"?P.organizationId:N&&N.length>0?N[0]:void 0;try{const Z={q:A,k:Math.min(S,100)};G&&(Z.organizationId=G),Object.keys(E).length>0&&(Z.filters=E);const le={"Content-Type":"application/json"};O.current&&(le.Authorization=`Bearer ${O.current}`);const he=await fetch(`${e}/search`,{method:"POST",headers:le,body:JSON.stringify(Z)});if(!he.ok){const se=await he.text();return{success:!1,error:`Search failed: ${he.status} ${se}`}}const Ne=await he.json(),Q=Ne.candidates.map((se,Xe)=>{const dt=se.citation||se.url;return{rank:Xe+1,doc_id:se.doc_id,block_id:se.block_id,url:se.url,citation:dt,title:se.title||"Untitled",snippet:se.snippet,score:se.scores?.rerank||se.scores?.dense||0,metadata:{site:se.metadata?.site,lang:se.metadata?.lang,contentType:se.metadata?.content_type}}});return{success:!0,query:Ne.query,total:Ne.total,results:Q,summary:`Found ${Ne.total} relevant results for "${A}". Top result: ${Q[0]?.title||"N/A"}`}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Unknown error occurred"}}}:null,[P,e,O]),st=f.useMemo(()=>P?.enabled?async function(A,S){const k=P.organizationId&&P.organizationId!=="default"?P.organizationId:N&&N.length>0?N[0]:void 0;try{const E={"Content-Type":"application/json"};O.current&&(E.Authorization=`Bearer ${O.current}`);const G=await fetch(`${e}/fetch`,{method:"POST",headers:E,body:JSON.stringify({doc_id:A,block_ids:S,...k?{organizationId:k}:{}})});if(!G.ok){const le=await G.text();return{success:!1,error:`Fetch failed: ${G.status} ${le}`}}const Z=await G.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||A}`}}catch(E){return{success:!1,error:E instanceof Error?E.message:"Unknown error occurred"}}}:null,[P,e,O]),qt=f.useMemo(()=>{const v=[...o,...i,ct];return(!de||y)&&v.push(lt),P?.enabled&&(nt&&v.push(nt),st&&v.push(st)),v},[o,i,ct,lt,nt,st,P,de,y]),_e=f.useMemo(()=>tc(qt,a),[qt,a]),De=f.useMemo(()=>{const v=new Map,A=new Map(_e.map(S=>[S.name,S]));return v.set("getState",ct),(!de||y)&&v.set("setState",lt),P?.enabled&&(nt&&v.set("searchDocs",nt),st&&v.set("fetchDocContent",st)),qt.forEach(S=>{if(S===ct||S===lt||S===nt||S===st)return;const k=S[Qe];if(k){const G=A.get(k);if(G){v.set(G.name,S);return}}const E=_e.find(G=>G.name===S.name);E&&v.set(E.name,S)}),v},[qt,_e,ct,lt,nt,st,P,de,y]),Wn=f.useMemo(()=>new Set(_e.map(v=>v.name)),[_e]),qn=f.useMemo(()=>{const v=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!de||y)&&v.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 A=[];return P?.enabled&&A.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[..._e,...v,...A]},[_e,P,de,y]),Re=f.useMemo(()=>qn.filter(v=>v.name==="getState"?!0:v.name==="setState"?!de||y:P?.enabled&&(v.name==="searchDocs"||v.name==="fetchDocContent")?!0:Wn.has(v.name)),[qn,Wn,de,y,P]),Kn=f.useMemo(()=>{const v=new Set;return v.add("getState"),v.add("setState"),P?.enabled&&P.autoExecute!==!1&&(v.add("searchDocs"),v.add("fetchDocContent")),i.forEach(A=>{for(const[S,k]of De.entries())if(k===A){v.add(S);break}}),v},[i,De,P]);f.useEffect(()=>s||n?void 0:((async()=>{try{const A=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!A.ok)throw new Error("Failed to fetch token");const S=await A.json();V(S.clientToken),O.current=S.clientToken,ce(S.expiresAt),W(null)}catch(A){console.error("[useAgent] Token fetch failed:",A),W(A instanceof Error?A.message:"Failed to fetch token")}})(),()=>{Y.current&&clearTimeout(Y.current)}),[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!oe||s||n)return;Y.current&&clearTimeout(Y.current);const v=Math.floor(Date.now()/1e3),A=oe-v,k=Math.max(0,A-5);return Y.current=setTimeout(async()=>{try{const E=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!E.ok)throw new Error("Failed to refresh token");const G=await E.json();V(G.clientToken),O.current=G.clientToken,ce(G.expiresAt),W(null)}catch(E){console.error("[useAgent] Token refresh failed:",E),W(E instanceof Error?E.message:"Failed to refresh token")}},k*1e3),()=>{Y.current&&clearTimeout(Y.current)}},[oe,t,JSON.stringify(r),s,n]);const Tn=async(v,A={})=>{const S=A.headers?new Headers(A.headers):new Headers;S.delete("user-agent"),S.delete("User-Agent"),console.log("[useAgent] Making request to:",v),console.log("[useAgent] Method:",A.method||"GET"),console.log("[useAgent] Has Authorization header:",S.has("Authorization")),console.log("[useAgent] Client token available:",!!O.current);try{const k=await fetch(v,{...A,headers:S});if(!k.ok){console.error("[useAgent] Request failed:",k.status,k.statusText);const E=await k.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",E)}return k}catch(k){throw console.error("[useAgent] Fetch error:",k),k}},Sn=`${e}/chat`;console.log("[useAgent] Chat API URL:",Sn);const{messages:Ve,sendMessage:Gn,status:Ie,error:Pt,stop:ut,addToolResult:Ee,setMessages:Yn}=yo.useChat({id:be||void 0,messages:p,transport:new ls.DefaultChatTransport({api:Sn,fetch:Tn,headers:()=>{const v={};return O.current?(v.Authorization=`Bearer ${O.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),v},body:()=>{const v=Re.map(k=>({name:k.name,description:k.description,inputSchema:k.jsonSchema})),A=v.filter(k=>k.name==="getState"||k.name==="setState").map(k=>k.name),S=v.filter(k=>k.name==="searchDocs"||k.name==="fetchDocContent").map(k=>k.name);return A.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",A),S.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",S):P?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:v,systemPrompt:m,state:we.current,...F&&{ragFilters:F}}}}),sendAutomaticallyWhen:ls.lastAssistantMessageIsCompleteWithToolCalls});f.useEffect(()=>{Ve.forEach(v=>{v.role==="assistant"&&v.parts.forEach(A=>{if(!A.type?.startsWith("tool-")||A.state!=="input-available")return;const S=A.type.replace("tool-",""),k=A.toolCallId;if(Lt.has(k))return;vs(G=>new Set(G).add(k));const E=em(A.input);if(Ct(S,E)){const G=wn(S,E),Z=Object.keys(E);(async()=>{try{let le={};const he=[...new Set([...Z,...Object.keys(G)])];if(d&&(h==="batch"||h==="auto"&&uc(S,he,G))){const Ae=Yf(S,Z,G,E),ht={id:`${k}-form`,toolName:S,toolCallId:k,title:Ae.title,description:Ae.description,fields:Ae.fields},Ze=await Xt(ht);if(Ze===null){Ee({toolCallId:k,tool:S,output:"User cancelled secure input"});return}le=Ze}else for(const[Ae,ht]of Object.entries(G)){if(E[Ae]!==void 0)continue;const Ze=lc(ht,Ae),We={id:`${k}-${Ae}`,type:ht,paramName:Ae,toolName:S,toolCallId:k,title:Ze.title,description:Ze.description,placeholder:Ze.placeholder},Hn=await Xn(We);if(Hn===null){Ee({toolCallId:k,tool:S,output:"User cancelled secure input"});return}le[Ae]=Hn}const Q={...E,...le},se=De.get(S);if(!se)throw new Error(`Tool ${S} not found`);let Xe;const dt=Re.find(Ae=>Ae.name===S);if(dt&&dt.jsonSchema?.properties){const ht=Object.keys(dt.jsonSchema.properties).map(Ze=>Q[Ze]);Xe=await se(...ht)}else Xe=await se(...Object.values(Q));Ee({toolCallId:k,tool:S,output:Xe})}catch(le){console.error(`[useAgent] Error executing tool with secure input ${S}:`,le),Ee({toolCallId:k,tool:S,output:`Error: ${le}`})}})();return}if(Kn.has(S)&&!Ct(S,E)){const G=De.get(S);G?(async()=>{try{const Z=Re.find(he=>he.name===S);let le;if(Z&&Z.jsonSchema?.properties){const Ne=Object.keys(Z.jsonSchema.properties).map(Q=>E[Q]);le=await G(...Ne)}else if(S==="getState")le=G();else if(S==="setState"){const he=E.updates||E;le=await G(he)}else le=await G(...Object.values(E));Ee({toolCallId:k,tool:S,output:le})}catch(Z){console.error(`[useAgent] Error executing tool ${S}:`,Z),Ee({toolCallId:k,tool:S,output:`Error: ${Z}`})}})():console.warn(`[useAgent] Tool ${S} not found in toolsMap`)}else j&&j({toolCall:{toolCallId:k,toolName:S,args:E}})})})},[Ve,Kn,De,j,Ee,Lt,lt,Re,Ct,wn,Xn]),f.useEffect(()=>{if(Ie==="ready"&&Ve.length>0&&M){const v=Ve[Ve.length-1];v&&v.role==="assistant"&&M({message:v,messages:Ve,isAbort:!1,isDisconnect:!1,isError:!!Pt})}},[Ie,Ve,Pt,M]);async function Kt(){if(!(!r?.id||!T)){yn(!0);try{const A=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${T}`}})).json();J(A.conversations||[])}catch(v){console.error("Failed to fetch conversations:",v)}finally{yn(!1)}}}f.useEffect(()=>{r?.id&&T&&Kt()},[JSON.stringify(r),T,e]),f.useEffect(()=>{if(!be||!O.current)return;(async()=>{Pe(!0),St(null);try{const A=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:be},format:"json"})});if(!A.ok){const E=await A.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${A.status} ${E}`)}const k=(await A.json())?.value||{};we.current=k,de||ne(k),b&&b(k),at.current=!0}catch(A){console.error("Failed to fetch state:",A);const S=A instanceof Error?A:new Error(String(A));St(S),at.current||(we.current={},de?b&&b({}):(ne({}),b&&b({})),at.current=!0)}finally{Pe(!1)}})()},[be,e,de,b]);async function qr(v){He(v),yn(!0);try{const A=await fetch(`${e}/conversations/${v}/messages`,{headers:{Authorization:`Bearer ${O.current}`}});if(!A.ok)throw new Error(`Failed to fetch messages: ${A.statusText}`);const k=(await A.json()).messages||[];Yn(k)}catch(A){console.error("Failed to load conversation messages:",A)}finally{yn(!1)}}async function Gt(v){if(T)try{await fetch(`${e}/conversations/${v}`,{method:"DELETE",headers:{Authorization:`Bearer ${T}`}}),J(te.filter(A=>A._id!==v)),v===be&&jn()}catch(A){console.error("Failed to delete conversation:",A)}}function jn(){const v=crypto.randomUUID();He(v),Yn([]),vs(new Set),we.current={},de?b&&b({}):(ne({}),b&&b({})),at.current=!1}function At(v){Ee(v)}async function kt(v){const A={...we.current,...v};we.current=A,de||ne(A),b&&b(A);try{await jt(v)}catch(S){throw S}}return{id:be,messages:Ve,status:Ie,error:Pt,sendMessage:Gn,stop:ut,addToolOutput:At,setMessages:Yn,conversations:te,loadConversation:qr,deleteConversation:Gt,startNewConversation:jn,isLoadingConversations:Me,clientToken:T,tokenError:R,state:Ue,setState:kt,isStateLoading:_t,stateError:bn,pendingSecureInputs:Array.from(Ft.values()),completeSecureInput:vn,pendingSecureForms:Array.from(Je.values()),completeSecureForm:Wt}}exports.verifyToken=Rc.verifyToken;exports.ARCTEN_ORIGINAL_NAME=Qe;exports.ArctenAgent=Kf;exports.SecureModalProvider=cc;exports.preserveToolName=vf;exports.useAgent=tm;exports.useSecureModal=ac;
23
+ ${_e?"":"w-[30px]"}
24
+ `,style:_e?ne?{width:`${Je}px`,height:Xe?"auto":`${zt}px`,left:`${Ae.x}px`,top:`${Ae.y}px`}:{width:`${Je}px`}:void 0,onClick:_e?void 0:hc,children:_e?l.jsxs(l.Fragment,{children:[!ne&&l.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:gc,children:l.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),ne&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:g=>{g.preventDefault(),wt(!0)}}),l.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:g=>{g.preventDefault(),g.stopPropagation(),ot(!0),at({x:g.clientX-Ae.x,y:g.clientY-Ae.y})},children:l.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"})}),l.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:g=>{g.preventDefault(),wt(!0)}})]}),l.jsxs("div",{className:"flex flex-col h-full",children:[l.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${ne?"cursor-move":""}`,onMouseDown:ne?bc:void 0,children:[l.jsx("h2",{className:`text-base font-semibold ${ne&&Xe?"cursor-pointer":""}`,onClick:ne&&Xe?g=>{g.stopPropagation(),Yr()}:void 0,children:r}),l.jsxs("div",{className:"flex items-center gap-1",onClick:g=>g.stopPropagation(),children:[l.jsxs(mt,{children:[l.jsx(pt,{asChild:!0,children:l.jsx("button",{type:"button",className:ce(Et({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:mc,"aria-label":"New chat",children:l.jsx(ie.Plus,{className:"h-4 w-4"})})}),l.jsx(gt,{children:"Start a new conversation"})]}),l.jsxs(mt,{children:[l.jsx(pt,{asChild:!0,children:l.jsx("button",{type:"button",className:ce(Et({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ne?xc:yc,"aria-label":ne?"Dock sidebar":"Float sidebar",children:ne?l.jsx(ie.Dock,{className:"h-4 w-4"}):l.jsx(ie.PictureInPicture2,{className:"h-4 w-4"})})}),l.jsx(gt,{children:ne?"Dock to sidebar":"Undock to floating window"})]}),l.jsxs(mt,{children:[l.jsx(pt,{asChild:!0,children:l.jsx("button",{type:"button",className:ce(Et({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ne?Yr:fc,"aria-label":ne?Xe?"Maximize":"Minimize":"Close sidebar",children:ne?Xe?l.jsx(ie.Maximize2,{className:"h-4 w-4"}):l.jsx(ie.Minimize2,{className:"h-4 w-4"}):l.jsx(ie.X,{className:"h-4 w-4"})})}),l.jsx(gt,{children:ne?Xe?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Xe&&l.jsxs(l.Fragment,{children:[b&&Oe.length>0&&l.jsxs("div",{className:`border-b border-border ${lt?"flex flex-col flex-1":""}`,children:[l.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[l.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),l.jsx(je,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{lt||re(),De(!lt)},children:lt?"Show less":"View all"})]}),l.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${lt?"flex-1 overflow-y-auto":""}`,children:Oe.slice(0,lt?void 0:3).map(g=>l.jsxs("div",{className:"group relative",children:[l.jsxs(xf,{type:"button",className:ce(Et({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>Re(g),children:[l.jsx("span",{className:"text-xs truncate",children:g.title}),l.jsx("div",{className:"ml-2 flex items-center",children:l.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:qe(g.updatedAt)})})]}),l.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:C=>{C.stopPropagation(),jn(g._id)},"aria-label":"Delete conversation",children:l.jsx(ie.X,{className:"h-3 w-3"})})]},g._id))})]}),l.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[l.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:ve.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&l.jsx("div",{className:"mb-6",children:o}),l.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),Ie.length>0&&l.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:l.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(wn?Ie:Ie.slice(0,10)).map(g=>l.jsxs(mt,{children:[l.jsx(pt,{asChild:!0,children:l.jsx(ws,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{jt(g.sampleUsage),_t.current?.focus()},children:g.friendlyName})}),l.jsx(gt,{children:l.jsxs("div",{className:"max-w-xs",children:[l.jsx("p",{className:"font-medium",children:g.description}),l.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[l.jsx("span",{className:"font-medium",children:"Example:"}),' "',g.sampleUsage,'"']}),g.paramCount>0&&l.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[l.jsx("span",{className:"font-medium",children:"Parameters:"})," ",g.params.join(", ")]})]})})]},g.name)),Ie.length>10&&!wn&&l.jsxs(mt,{children:[l.jsx(pt,{asChild:!0,children:l.jsxs(ws,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Tn(!0),children:["+",Ie.length-10," more"]})}),l.jsx(gt,{children:l.jsxs("div",{className:"max-w-xs",children:[l.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),l.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:Ie.slice(10).map(g=>l.jsxs("div",{children:[l.jsxs("span",{className:"font-medium text-xs",children:[g.friendlyName,":"]}),l.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:g.description})]},g.name))}),l.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),wn&&Ie.length>10&&l.jsx(ws,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Tn(!1),children:"Show less"})]})})]}):l.jsxs(l.Fragment,{children:[ve.map(g=>{const I=g.parts.filter(U=>U.type==="text").map(U=>U.text).join("");let $=g.parts;g.role==="assistant"&&g.parts.some(G=>G.timestamp)&&($=[...g.parts].sort((G,X)=>{const ye=G.timestamp||0,me=X.timestamp||0;return ye-me}));let L=[],_=new Map,ee=[],H,se=!0;if(g.role==="assistant"){const U=$.filter(me=>me.type==="text"&&me.text),G=[],X=[];U.forEach(me=>{const{citations:ht,citationMap:Ce,groupedCitations:Le,referencesText:ft}=go(me.text);L.push(...ht),G.push(Ce),Le&&X.push(...Le),ft&&(H=ft)}),G.forEach(me=>{me.forEach((ht,Ce)=>{_.has(Ce)||_.set(Ce,ht)})}),ee=Array.from(new Map(X.map(me=>[me.url,me])).values()).sort((me,ht)=>(me.numbers[0]||0)-(ht.numbers[0]||0)),se=!(Me==="streaming"&&g.id===ve.at(-1)?.id)}return l.jsx("div",{className:`${g.role==="user"?"flex justify-end":"w-full"}`,children:l.jsx("div",{className:`${g.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:g.role==="user"?l.jsx(bf,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:I}):l.jsx("div",{className:"space-y-2",children:$.map((U,G)=>{if(U.type?.startsWith("tool-")){const X=U.type?.replace("tool-","")||"",ye=Z.find(Ce=>Ce.name===X),me=U.state==="input-available",ht=U.state==="output-available";if(me&&ae.has(X),me){if(ae.has(X))return null;const Ce=Ls(U.input);return l.jsx(ns,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:l.jsx(Tf,{toolName:X,description:ye?.description||"",args:Ce,onApprove:async()=>{if(We.has(U.toolCallId))return;Ve(ft=>new Set(ft).add(U.toolCallId));const Le=ge.get(X);if(Le)try{const ft=await Le(...Object.values(Ce));kt({toolCallId:U.toolCallId,tool:X,output:ft})}catch(ft){kt({toolCallId:U.toolCallId,tool:X,output:`Error: ${ft}`})}},onDeny:async()=>{We.has(U.toolCallId)||(Ve(Le=>new Set(Le).add(U.toolCallId)),kt({toolCallId:U.toolCallId,tool:X,output:"User denied tool execution"}))}})},`${U.toolCallId}-${G}`)}else if(ht){const Ce=U.output==="User denied tool execution",Le=Ls(U.input);return l.jsx(Sf,{toolName:X,args:Le,isDenied:Ce,isSafe:ae.has(X)},`${U.toolCallId}-${G}`)}return null}if(U.type==="text"&&U.text&&vn){const{processedText:X}=go(U.text),Ce=!$.slice(G+1).some(Le=>Le.type==="text"&&Le.text)&&se&&_.size>0;return l.jsx(Of,{text:X,citations:L,citationMap:_,groupedCitations:Ce?ee:void 0,referencesText:Ce?H:void 0,ResponseComponent:vn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:F,showReferences:Ce},`${g.id}-${G}`)}return U.type==="reasoning"&&U.text?l.jsxs(sc,{className:"w-full",isStreaming:Me==="streaming"&&G===g.parts.length-1&&g.id===ve.at(-1)?.id,children:[l.jsx(rc,{}),l.jsx(ic,{children:U.text})]},`${g.id}-${G}`):null})})})},g.id)}),l.jsx("div",{ref:bn})]})}),Kr&&l.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Kr.message]}),l.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[l.jsx(Fu,{mode:"wait",children:(Me==="streaming"||Me==="submitted")&&l.jsxs(ns,{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:[l.jsx(ns,{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]}}),l.jsx("p",{className:"text-xs text-muted-foreground",children:nt})]})}),l.jsxs("form",{onSubmit:Gr,className:"relative",children:[l.jsx(vo,{ref:_t,value:Xt,onChange:pc,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),Gr(g))}}),Me==="streaming"||Me==="submitted"?l.jsxs(mt,{children:[l.jsx(pt,{asChild:!0,children:l.jsx("button",{type:"button",className:ce(Et({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:Hn,children:l.jsx(ie.Square,{className:"h-4 w-4"})})}),l.jsxs(gt,{children:[l.jsx(Zr,{children:"Escape"})," to stop"]})]}):l.jsxs(mt,{children:[l.jsx(pt,{asChild:!0,children:l.jsx("button",{type:"submit",className:ce(Et({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Xt.trim(),children:l.jsx(ie.ArrowRight,{className:"h-4 w-4"})})}),l.jsxs(gt,{children:[l.jsx(Zr,{children:"Enter"})," to send"]})]})]})]})]}),l.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:[l.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),l.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),l.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):l.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[l.jsx(ie.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),l.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):l.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:l.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function Kf(e){return l.jsx(cc,{children:l.jsx(qf,{...e})})}const Gf={password:[/^password$/i,/^pwd$/i,/^pass$/i,/^newPassword$/i,/^oldPassword$/i,/^currentPassword$/i,/^confirmPassword$/i,/.*password.*/i],email:[/^email$/i,/^emailAddress$/i,/^mail$/i,/.*email.*/i],phone:[/^phone$/i,/^phoneNumber$/i,/^mobile$/i,/^cell$/i,/^cellPhone$/i,/^telephone$/i,/.*phone.*/i,/.*mobile.*/i],pin:[/^pin$/i,/^pinCode$/i,/^securityPin$/i,/^accessPin$/i,/.*pin$/i],ssn:[/^ssn$/i,/^socialSecurityNumber$/i,/^social$/i,/.*ssn.*/i,/.*social.*/i],creditCard:[/^creditCard$/i,/^cardNumber$/i,/^card$/i,/^ccNumber$/i,/^creditCardNumber$/i,/.*card.*/i,/^cvv$/i,/^cvc$/i,/^cvn$/i,/^securityCode$/i],text:[]};function An(e){for(const[t,n]of Object.entries(Gf))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function lc(e,t){return{password:{title:"Password Required",description:"Please enter your password to continue",placeholder:"Enter password..."},email:{title:"Email Required",description:"Please enter your email address",placeholder:"Enter email address..."},phone:{title:"Phone Number Required",description:"Please enter your phone number",placeholder:"Enter phone number..."},pin:{title:"PIN Required",description:"Please enter your PIN",placeholder:"Enter PIN..."},ssn:{title:"Social Security Number Required",description:"Please enter your Social Security Number",placeholder:"XXX-XX-XXXX"},creditCard:{title:"Credit Card Required",description:"Please enter your credit card information",placeholder:"XXXX XXXX XXXX XXXX"},text:{title:"Secure Input Required",description:`Please enter your ${t}`,placeholder:`Enter ${t}...`}}[e]}function uc(e,t,n){const s=Object.keys(n).length,r=t.length;return r>=3||s>=2||s>0&&s<r}function Yf(e,t,n,s={}){const r=[];return new Set([...t,...Object.keys(n)]).forEach(i=>{const a=i in n,c=n[i];if(!a&&s[i]!==void 0)return;const u=a?void 0:s[i],d={name:i,type:Hf(c||An(i)||"text"),label:dc(i),placeholder:Jf(i,c),required:!0,value:u};d.type==="password"&&(d.validation=h=>h.length<8?"Password must be at least 8 characters":null),r.push(d)}),r.sort((i,a)=>{const c=i.name in n,u=a.name in n;return c===u?0:c?1:-1}),{shouldUseForm:uc(e,t,n),fields:r,title:Zf(e),description:Qf(e,r.length)}}function Hf(e){switch(e){case"password":return"password";case"email":return"email";case"phone":return"phone";case"pin":return"pin";case"ssn":return"ssn";case"creditCard":return"creditCard";default:return"text"}}function dc(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Jf(e,t){return t?lc(t,e).placeholder:`Enter ${dc(e).toLowerCase()}...`}function Zf(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Qf(e,t){const n=e.toLowerCase();return t<=2?`Please provide the required information to ${n}.`:`Please fill out the form below to ${n}. Required fields are marked with *.`}function Rn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Rn(t)}catch{return e}if(Array.isArray(e))return e.map(Rn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Rn(s);return t}return e}function em(e,t){if(!t||Object.keys(t).length===0)return e;const n={...e};return Object.keys(t).forEach(s=>{s in n&&delete n[s]}),n}function tm(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Rn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Rn(e):{}}function nm({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,sensitiveParams:c,autoDetectSensitive:u=!1,autoFormGeneration:d=!1,formMode:h="auto",systemPrompt:m="",initialMessages:p=[],conversationId:w,state:x,onStateChange:b,allowStateEdits:y=!0,onToolCall:j,onFinish:M,sources:E,ragConfig:D,ragFilters:F,secureInputHandler:B}={}){const P=f.useMemo(()=>D!==void 0?D:F?{enabled:!0,filters:F}:E&&E.length>0?{enabled:!0,organizationId:E[0],autoExecute:!0,filters:void 0}:{enabled:!1},[E,D,F]),z=f.useMemo(()=>{const v={};if(c)for(const[A,S]of Object.entries(c))if(v[A]={},Array.isArray(S))for(const k of S){const N=An(k);v[A][k]=N||"text"}else for(const[k,N]of Object.entries(S))v[A][k]=N;if(a){for(const[A,S]of Object.entries(a))if(S&&typeof S=="object"&&"sensitiveParams"in S){v[A]||(v[A]={});const k=S.sensitiveParams;if(Array.isArray(k))for(const N of k){const K=An(N);v[A][N]=K||"text"}else if(k&&typeof k=="object")for(const[N,K]of Object.entries(k))v[A][N]=K}}return v},[c,a,u]),[T,V]=f.useState(n||null),O=f.useRef(n||null),[R,W]=f.useState(null),[oe,le]=f.useState(null),Y=f.useRef(null),[te,J]=f.useState([]),[be,He]=f.useState(w||(typeof window<"u"?crypto.randomUUID():null)),[Ne,gn]=f.useState(!1),[$t,bs]=f.useState(new Set),[Lt,et]=f.useState(new Map),[_e,Ft]=f.useState(new Map),[Je,Bt]=f.useState(new Map),[zt,yn]=f.useState(new Map),de=x!==void 0,[wt,ne]=f.useState({}),Te=f.useRef({}),Xe=de?x||{}:wt;de&&x?Te.current=x:de||(Te.current=wt);const[Ut,Ae]=f.useState(!1),[xn,Tt]=f.useState(null),ot=f.useRef(!1),St=f.useCallback(async(v,A=3)=>{if(!be||!O.current)return;const S=async()=>{const N=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,K=await fetch(N,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:be,updates:v},format:"json"})});if(!K.ok){if(K.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const Z=await K.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${K.status} ${Z}`)}};for(let k=0;k<A;k++)try{await S(),Tt(null);return}catch(N){if(k===A-1){const Z=N instanceof Error?N:new Error(String(N));throw Tt(Z),console.error("Failed to sync state to Convex after retries:",N),Z}await new Promise(Z=>setTimeout(Z,Math.pow(2,k)*100))}},[be,e,O]),at=f.useMemo(()=>function(){return Te.current},[]),ct=f.useMemo(()=>async function(A){const S={...Te.current,...A};Te.current=S,de||ne(S),b&&b(S);try{await St(A)}catch(k){throw k}},[St,b,de]);f.useEffect(()=>{de&&x&&(Te.current=x)},[de,x]);const Xn=f.useCallback(v=>B?B.showSecureModal(v):new Promise(A=>{et(S=>new Map(S).set(v.id,v)),Ft(S=>new Map(S).set(v.id,A))}),[B]),bn=f.useCallback((v,A)=>{if(B)return;const S=_e.get(v);S&&(S(A),et(k=>{const N=new Map(k);return N.delete(v),N}),Ft(k=>{const N=new Map(k);return N.delete(v),N}))},[_e,B]),_t=f.useCallback(v=>B?B.showSecureForm(v):new Promise(A=>{Bt(S=>new Map(S).set(v.id,v)),yn(S=>new Map(S).set(v.id,A))}),[B]),Xt=f.useCallback((v,A)=>{if(B)return;const S=zt.get(v);S&&(S(A),Bt(k=>{const N=new Map(k);return N.delete(v),N}),yn(k=>{const N=new Map(k);return N.delete(v),N}))},[zt,B]),jt=f.useCallback((v,A)=>{const S=z[v]||{},k=Object.keys(S).length>0;if(u){const N=Object.keys(A).filter(K=>An(K)!==null);return k||N.length>0}return k},[z,u]),vn=f.useCallback((v,A)=>{const S={...z[v]||{}};if(u){for(const k of Object.keys(A))if(!(k in S)){const N=An(k);N&&(S[k]=N)}}return S},[z,u]),tt=f.useMemo(()=>P?.enabled?async function(A,S=20,k){const N={...P.filters,...k};if(E&&E.length>1){const Z=E.map(Q=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...O.current?{Authorization:`Bearer ${O.current}`}:{}},body:JSON.stringify({q:A,k:Math.min(S,100),organizationId:Q,...Object.keys(N).length>0?{filters:N}:{}})}).then(re=>re.ok?re.json():null)),ge=await Promise.all(Z),ae=[];for(const Q of ge)Q?.candidates&&ae.push(...Q.candidates);ae.sort((Q,re)=>{const qe=Q.scores?.rerank||Q.scores?.dense||0;return(re.scores?.rerank||re.scores?.dense||0)-qe});const ke=ae.slice(0,S).map((Q,re)=>{const qe=Q.citation||Q.url;return{rank:re+1,doc_id:Q.doc_id,block_id:Q.block_id,url:Q.url,citation:qe,title:Q.title||"Untitled",snippet:Q.snippet,score:Q.scores?.rerank||Q.scores?.dense||0,metadata:{site:Q.metadata?.site,lang:Q.metadata?.lang,contentType:Q.metadata?.content_type}}});return{success:!0,query:A,total:ae.length,results:ke,summary:`Found ${ae.length} relevant results across ${E.length} source(s) for "${A}". Top result: ${ke[0]?.title||"N/A"}`}}const K=P.organizationId&&P.organizationId!=="default"?P.organizationId:E&&E.length>0?E[0]:void 0;try{const Z={q:A,k:Math.min(S,100)};K&&(Z.organizationId=K),Object.keys(N).length>0&&(Z.filters=N);const ge={"Content-Type":"application/json"};O.current&&(ge.Authorization=`Bearer ${O.current}`);const ae=await fetch(`${e}/search`,{method:"POST",headers:ge,body:JSON.stringify(Z)});if(!ae.ok){const re=await ae.text();return{success:!1,error:`Search failed: ${ae.status} ${re}`}}const ke=await ae.json(),Q=ke.candidates.map((re,qe)=>{const ut=re.citation||re.url;return{rank:qe+1,doc_id:re.doc_id,block_id:re.block_id,url:re.url,citation:ut,title:re.title||"Untitled",snippet:re.snippet,score:re.scores?.rerank||re.scores?.dense||0,metadata:{site:re.metadata?.site,lang:re.metadata?.lang,contentType:re.metadata?.content_type}}});return{success:!0,query:ke.query,total:ke.total,results:Q,summary:`Found ${ke.total} relevant results for "${A}". Top result: ${Q[0]?.title||"N/A"}`}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Unknown error occurred"}}}:null,[P,e,O]),nt=f.useMemo(()=>P?.enabled?async function(A,S){const k=P.organizationId&&P.organizationId!=="default"?P.organizationId:E&&E.length>0?E[0]:void 0;try{const N={"Content-Type":"application/json"};O.current&&(N.Authorization=`Bearer ${O.current}`);const K=await fetch(`${e}/fetch`,{method:"POST",headers:N,body:JSON.stringify({doc_id:A,block_ids:S,...k?{organizationId:k}:{}})});if(!K.ok){const ge=await K.text();return{success:!1,error:`Fetch failed: ${K.status} ${ge}`}}const Z=await K.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||A}`}}catch(N){return{success:!1,error:N instanceof Error?N.message:"Unknown error occurred"}}}:null,[P,e,O]),Wt=f.useMemo(()=>{const v=[...o,...i,at];return(!de||y)&&v.push(ct),P?.enabled&&(tt&&v.push(tt),nt&&v.push(nt)),v},[o,i,at,ct,tt,nt,P,de,y]),We=f.useMemo(()=>tc(Wt,a),[Wt,a]),Ve=f.useMemo(()=>{const v=new Map,A=new Map(We.map(S=>[S.name,S]));return v.set("getState",at),(!de||y)&&v.set("setState",ct),P?.enabled&&(tt&&v.set("searchDocs",tt),nt&&v.set("fetchDocContent",nt)),Wt.forEach(S=>{if(S===at||S===ct||S===tt||S===nt)return;const k=S[Ze];if(k){const K=A.get(k);if(K){v.set(K.name,S);return}}const N=We.find(K=>K.name===S.name);N&&v.set(N.name,S)}),v},[Wt,We,at,ct,tt,nt,P,de,y]),Wn=f.useMemo(()=>new Set(We.map(v=>v.name)),[We]),qn=f.useMemo(()=>{const v=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!de||y)&&v.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 A=[];return P?.enabled&&A.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...We,...v,...A]},[We,P,de,y]),Ie=f.useMemo(()=>qn.filter(v=>v.name==="getState"?!0:v.name==="setState"?!de||y:P?.enabled&&(v.name==="searchDocs"||v.name==="fetchDocContent")?!0:Wn.has(v.name)),[qn,Wn,de,y,P]),Kn=f.useMemo(()=>{const v=new Set;return v.add("getState"),v.add("setState"),P?.enabled&&P.autoExecute!==!1&&(v.add("searchDocs"),v.add("fetchDocContent")),i.forEach(A=>{for(const[S,k]of Ve.entries())if(k===A){v.add(S);break}}),v},[i,Ve,P]);f.useEffect(()=>s||n?void 0:((async()=>{try{const A=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!A.ok)throw new Error("Failed to fetch token");const S=await A.json();V(S.clientToken),O.current=S.clientToken,le(S.expiresAt),W(null)}catch(A){console.error("[useAgent] Token fetch failed:",A),W(A instanceof Error?A.message:"Failed to fetch token")}})(),()=>{Y.current&&clearTimeout(Y.current)}),[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!oe||s||n)return;Y.current&&clearTimeout(Y.current);const v=Math.floor(Date.now()/1e3),A=oe-v,k=Math.max(0,A-5);return Y.current=setTimeout(async()=>{try{const N=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!N.ok)throw new Error("Failed to refresh token");const K=await N.json();V(K.clientToken),O.current=K.clientToken,le(K.expiresAt),W(null)}catch(N){console.error("[useAgent] Token refresh failed:",N),W(N instanceof Error?N.message:"Failed to refresh token")}},k*1e3),()=>{Y.current&&clearTimeout(Y.current)}},[oe,t,JSON.stringify(r),s,n]);const wn=async(v,A={})=>{const S=A.headers?new Headers(A.headers):new Headers;S.delete("user-agent"),S.delete("User-Agent"),console.log("[useAgent] Making request to:",v),console.log("[useAgent] Method:",A.method||"GET"),console.log("[useAgent] Has Authorization header:",S.has("Authorization")),console.log("[useAgent] Client token available:",!!O.current);try{const k=await fetch(v,{...A,headers:S});if(!k.ok){console.error("[useAgent] Request failed:",k.status,k.statusText);const N=await k.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",N)}return k}catch(k){throw console.error("[useAgent] Fetch error:",k),k}},Tn=`${e}/chat`;console.log("[useAgent] Chat API URL:",Tn);const{messages:Oe,sendMessage:Gn,status:$e,error:Ct,stop:lt,addToolResult:De,setMessages:Yn}=yo.useChat({id:be||void 0,messages:p,transport:new cs.DefaultChatTransport({api:Tn,fetch:wn,headers:()=>{const v={};return O.current?(v.Authorization=`Bearer ${O.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),v},body:()=>{const v=Ie.map(k=>({name:k.name,description:k.description,inputSchema:k.jsonSchema})),A=v.filter(k=>k.name==="getState"||k.name==="setState").map(k=>k.name),S=v.filter(k=>k.name==="searchDocs"||k.name==="fetchDocContent").map(k=>k.name);return A.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",A),S.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",S):P?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:v,systemPrompt:m,state:Te.current,...F&&{ragFilters:F}}}}),sendAutomaticallyWhen:cs.lastAssistantMessageIsCompleteWithToolCalls});f.useEffect(()=>{Oe.forEach(v=>{v.role==="assistant"&&v.parts.forEach(A=>{if(!A.type?.startsWith("tool-")||A.state!=="input-available")return;const S=A.type.replace("tool-",""),k=A.toolCallId;if($t.has(k))return;bs(K=>new Set(K).add(k));const N=tm(A.input);if(jt(S,N)){const K=vn(S,N),Z=Object.keys(N),ge=em(N,K);(async()=>{try{let ae={};const ke=[...new Set([...Z,...Object.keys(K)])];if(d&&(h==="batch"||h==="auto"&&uc(S,ke,K))){const Re=Yf(S,Z,K,ge),dt={id:`${k}-form`,toolName:S,toolCallId:k,title:Re.title,description:Re.description,fields:Re.fields},ve=await _t(dt);if(ve===null){De({toolCallId:k,tool:S,output:"User cancelled secure input"});return}ae=ve}else for(const[Re,dt]of Object.entries(K)){const ve=lc(dt,Re),vs={id:`${k}-${Re}`,type:dt,paramName:Re,toolName:S,toolCallId:k,title:ve.title,description:ve.description,placeholder:ve.placeholder},Me=await Xn(vs);if(Me===null){De({toolCallId:k,tool:S,output:"User cancelled secure input"});return}ae[Re]=Me}const re={...ge,...ae},qe=Ve.get(S);if(!qe)throw new Error(`Tool ${S} not found`);let ut;const jn=Ie.find(Re=>Re.name===S);if(jn&&jn.jsonSchema?.properties){const dt=Object.keys(jn.jsonSchema.properties).map(ve=>re[ve]);ut=await qe(...dt)}else ut=await qe(...Object.values(re));De({toolCallId:k,tool:S,output:ut})}catch(ae){console.error(`[useAgent] Error executing tool with secure input ${S}:`,ae),De({toolCallId:k,tool:S,output:`Error: ${ae}`})}})();return}if(Kn.has(S)&&!jt(S,N)){const K=Ve.get(S);K?(async()=>{try{const Z=Ie.find(ae=>ae.name===S);let ge;if(Z&&Z.jsonSchema?.properties){const ke=Object.keys(Z.jsonSchema.properties).map(Q=>N[Q]);ge=await K(...ke)}else if(S==="getState")ge=K();else if(S==="setState"){const ae=N.updates||N;ge=await K(ae)}else ge=await K(...Object.values(N));De({toolCallId:k,tool:S,output:ge})}catch(Z){console.error(`[useAgent] Error executing tool ${S}:`,Z),De({toolCallId:k,tool:S,output:`Error: ${Z}`})}})():console.warn(`[useAgent] Tool ${S} not found in toolsMap`)}else j&&j({toolCall:{toolCallId:k,toolName:S,args:N}})})})},[Oe,Kn,Ve,j,De,$t,ct,Ie,jt,vn,Xn]),f.useEffect(()=>{if($e==="ready"&&Oe.length>0&&M){const v=Oe[Oe.length-1];v&&v.role==="assistant"&&M({message:v,messages:Oe,isAbort:!1,isDisconnect:!1,isError:!!Ct})}},[$e,Oe,Ct,M]);async function qt(){if(!(!r?.id||!T)){gn(!0);try{const A=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${T}`}})).json();J(A.conversations||[])}catch(v){console.error("Failed to fetch conversations:",v)}finally{gn(!1)}}}f.useEffect(()=>{r?.id&&T&&qt()},[JSON.stringify(r),T,e]),f.useEffect(()=>{if(!be||!O.current)return;(async()=>{Ae(!0),Tt(null);try{const A=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:be},format:"json"})});if(!A.ok){const N=await A.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${A.status} ${N}`)}const k=(await A.json())?.value||{};Te.current=k,de||ne(k),b&&b(k),ot.current=!0}catch(A){console.error("Failed to fetch state:",A);const S=A instanceof Error?A:new Error(String(A));Tt(S),ot.current||(Te.current={},de?b&&b({}):(ne({}),b&&b({})),ot.current=!0)}finally{Ae(!1)}})()},[be,e,de,b]);async function qr(v){He(v),gn(!0);try{const A=await fetch(`${e}/conversations/${v}/messages`,{headers:{Authorization:`Bearer ${O.current}`}});if(!A.ok)throw new Error(`Failed to fetch messages: ${A.statusText}`);const k=(await A.json()).messages||[];Yn(k)}catch(A){console.error("Failed to load conversation messages:",A)}finally{gn(!1)}}async function Kt(v){if(T)try{await fetch(`${e}/conversations/${v}`,{method:"DELETE",headers:{Authorization:`Bearer ${T}`}}),J(te.filter(A=>A._id!==v)),v===be&&Sn()}catch(A){console.error("Failed to delete conversation:",A)}}function Sn(){const v=crypto.randomUUID();He(v),Yn([]),bs(new Set),Te.current={},de?b&&b({}):(ne({}),b&&b({})),ot.current=!1}function Pt(v){De(v)}async function At(v){const A={...Te.current,...v};Te.current=A,de||ne(A),b&&b(A);try{await St(v)}catch(S){throw S}}return{id:be,messages:Oe,status:$e,error:Ct,sendMessage:Gn,stop:lt,addToolOutput:Pt,setMessages:Yn,conversations:te,loadConversation:qr,deleteConversation:Kt,startNewConversation:Sn,isLoadingConversations:Ne,clientToken:T,tokenError:R,state:Xe,setState:At,isStateLoading:Ut,stateError:xn,pendingSecureInputs:Array.from(Lt.values()),completeSecureInput:bn,pendingSecureForms:Array.from(Je.values()),completeSecureForm:Xt}}exports.verifyToken=Rc.verifyToken;exports.ARCTEN_ORIGINAL_NAME=Ze;exports.ArctenAgent=Kf;exports.SecureModalProvider=cc;exports.preserveToolName=vf;exports.useAgent=nm;exports.useSecureModal=ac;