@arcteninc/core 0.0.107 → 0.0.108

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 Cl=Object.create;var ni=Object.defineProperty;var Pl=Object.getOwnPropertyDescriptor;var Al=Object.getOwnPropertyNames;var kl=Object.getPrototypeOf,Ml=Object.prototype.hasOwnProperty;var El=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Al(t))!Ml.call(e,r)&&r!==n&&ni(e,r,{get:()=>t[r],enumerable:!(s=Pl(t,r))||s.enumerable});return e};var Nl=(e,t,n)=>(n=e!=null?Cl(kl(e)):{},El(t||!e||!e.__esModule?ni(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),f=require("react"),ie=require("lucide-react"),So=require("@ai-sdk/react"),ms=require("ai"),jo=require("@radix-ui/react-slot"),Co=require("class-variance-authority"),Dl=require("clsx"),Rl=require("tailwind-merge"),Vl=require("@radix-ui/react-tooltip"),si=require("@radix-ui/react-use-controllable-state"),Il=require("@radix-ui/react-collapsible"),Ol=require("react-dom"),$l=require("@radix-ui/react-dialog"),Ll=require("./server.cjs");function vs(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=vs(f),sn=vs(Vl),pr=vs(Il),Bt=vs($l);function oe(...e){return Rl.twMerge(Dl.clsx(e))}const Vt=Co.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?jo.Slot:"button";return c.jsx(i,{ref:o,"data-slot":"button",className:oe(Vt({variant:t,size:n,className:e})),...r})});je.displayName="Button";const Fl=Co.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 As({className:e,variant:t,asChild:n=!1,...s}){const r=n?jo.Slot:"span";return c.jsx(r,{"data-slot":"badge",className:oe(Fl({variant:t}),e),...s})}const Bl=({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 l=a.scrollHeight;l>n?a.style.height=`${n}px`:a.style.height=`${l+6}px`}},[e.current,t])},Po=Ge.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Ge.useRef(null),[l,u]=Ge.useState("");return Bl({textAreaRef:a,triggerAutoSize:l,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]),c.jsx("textarea",{...o,value:r,ref:a,className:oe("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)}})});Po.displayName="AutosizeTextarea";function zl({delayDuration:e=0,...t}){return c.jsx(sn.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function vt({...e}){return c.jsx(zl,{children:c.jsx(sn.Root,{"data-slot":"tooltip",...e})})}function wt({...e}){return c.jsx(sn.Trigger,{"data-slot":"tooltip-trigger",...e})}function Tt({className:e,sideOffset:t=0,children:n,...s}){return c.jsx(sn.Portal,{children:c.jsxs(sn.Content,{"data-slot":"tooltip-content",sideOffset:t,className:oe("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,c.jsx(sn.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function ri({className:e,...t}){return c.jsx("kbd",{"data-slot":"kbd",className:oe("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 gr=f.createContext({});function yr(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const xr=typeof window<"u",Ao=xr?f.useLayoutEffect:f.useEffect,ws=f.createContext(null);function br(e,t){e.indexOf(t)===-1&&e.push(t)}function vr(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const dt=(e,t,n)=>n>t?t:n<e?e:n;function qs(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let ln=()=>{},ht=()=>{};process.env.NODE_ENV!=="production"&&(ln=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(qs(t,n))},ht=(e,t,n)=>{if(!e)throw new Error(qs(t,n))});const ft={},ko=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Mo(e){return typeof e=="object"&&e!==null}const Eo=e=>/^0[^.\s]+$/u.test(e);function wr(e){let t;return()=>(t===void 0&&(t=e()),t)}const Be=e=>e,Ul=(e,t)=>n=>t(e(n)),Un=(...e)=>e.reduce(Ul),On=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class Tr{constructor(){this.subscriptions=[]}add(t){return br(this.subscriptions,t),()=>vr(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 No(e,t){return t?e*(1e3/t):0}const ii=new Set;function Sr(e,t,n){e||ii.has(t)||(console.warn(qs(t,n)),ii.add(t))}const Do=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,_l=1e-7,Xl=12;function ql(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=Do(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>_l&&++a<Xl);return i}function _n(e,t,n,s){if(e===t&&n===s)return Be;const r=o=>ql(o,0,1,e,n);return o=>o===0||o===1?o:Do(r(o),t,s)}const Ro=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Vo=e=>t=>1-e(1-t),Io=_n(.33,1.53,.69,.99),jr=Vo(Io),Oo=Ro(jr),$o=e=>(e*=2)<1?.5*jr(e):.5*(2-Math.pow(2,-10*(e-1))),Cr=e=>1-Math.sin(Math.acos(e)),Lo=Vo(Cr),Fo=Ro(Cr),Wl=_n(.42,0,1,1),Kl=_n(0,0,.58,1),Bo=_n(.42,0,.58,1),Gl=e=>Array.isArray(e)&&typeof e[0]!="number",zo=e=>Array.isArray(e)&&typeof e[0]=="number",oi={linear:Be,easeIn:Wl,easeInOut:Bo,easeOut:Kl,circIn:Cr,circInOut:Fo,circOut:Lo,backIn:jr,backInOut:Oo,backOut:Io,anticipate:$o},Yl=e=>typeof e=="string",ai=e=>{if(zo(e)){ht(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return _n(t,n,s,r)}else if(Yl(e))return ht(oi[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),oi[e];return e},ns=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Hl(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 l(d){i.has(d)&&(u.schedule(d),e()),d(a)}const u={schedule:(d,h=!1,m=!1)=>{const v=m&&r?n:s;return h&&i.add(d),v.has(d)||v.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(l),n.clear(),r=!1,o&&(o=!1,u.process(d))}};return u}const Jl=40;function Uo(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=ns.reduce((k,O)=>(k[O]=Hl(o),k),{}),{setup:a,read:l,resolveKeyframes:u,preUpdate:d,update:h,preRender:m,render:p,postRender:v}=i,x=()=>{const k=ft.useManualTiming?r.timestamp:performance.now();n=!1,ft.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(k-r.timestamp,Jl),1)),r.timestamp=k,r.isProcessing=!0,a.process(r),l.process(r),u.process(r),d.process(r),h.process(r),m.process(r),p.process(r),v.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(x))},T=()=>{n=!0,s=!0,r.isProcessing||e(x)};return{schedule:ns.reduce((k,O)=>{const E=i[O];return k[O]=(B,_=!1,M=!1)=>(n||T(),E.schedule(B,_,M)),k},{}),cancel:k=>{for(let O=0;O<ns.length;O++)i[ns[O]].cancel(k)},state:r,steps:i}}const{schedule:de,cancel:jt,state:we,steps:ks}=Uo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Be,!0);let as;function Zl(){as=void 0}const Ne={now:()=>(as===void 0&&Ne.set(we.isProcessing||ft.useManualTiming?we.timestamp:performance.now()),as),set:e=>{as=e,queueMicrotask(Zl)}},_o=e=>t=>typeof t=="string"&&t.startsWith(e),Pr=_o("--"),Ql=_o("var(--"),Ar=e=>Ql(e)?ec.test(e.split("/*")[0].trim()):!1,ec=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,cn={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},$n={...cn,transform:e=>dt(0,1,e)},ss={...cn,default:1},En=e=>Math.round(e*1e5)/1e5,kr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function tc(e){return e==null}const nc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Mr=(e,t)=>n=>!!(typeof n=="string"&&nc.test(n)&&n.startsWith(e)||t&&!tc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Xo=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(kr);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},sc=e=>dt(0,255,e),Ms={...cn,transform:e=>Math.round(sc(e))},Ot={test:Mr("rgb","red"),parse:Xo("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+Ms.transform(e)+", "+Ms.transform(t)+", "+Ms.transform(n)+", "+En($n.transform(s))+")"};function rc(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 Ws={test:Mr("#"),parse:rc,transform:Ot.transform},Xn=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),St=Xn("deg"),st=Xn("%"),W=Xn("px"),ic=Xn("vh"),oc=Xn("vw"),li={...st,parse:e=>st.parse(e)/100,transform:e=>st.transform(e*100)},Jt={test:Mr("hsl","hue"),parse:Xo("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+st.transform(En(t))+", "+st.transform(En(n))+", "+En($n.transform(s))+")"},be={test:e=>Ot.test(e)||Ws.test(e)||Jt.test(e),parse:e=>Ot.test(e)?Ot.parse(e):Jt.test(e)?Jt.parse(e):Ws.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Ot.transform(e):Jt.transform(e),getAnimatableNone:e=>{const t=be.parse(e);return t.alpha=0,be.transform(t)}},ac=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function lc(e){return isNaN(e)&&typeof e=="string"&&(e.match(kr)?.length||0)+(e.match(ac)?.length||0)>0}const qo="number",Wo="color",cc="var",uc="var(",ci="${}",dc=/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 Ln(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(dc,l=>(be.test(l)?(s.color.push(o),r.push(Wo),n.push(be.parse(l))):l.startsWith(uc)?(s.var.push(o),r.push(cc),n.push(l)):(s.number.push(o),r.push(qo),n.push(parseFloat(l))),++o,ci)).split(ci);return{values:n,split:a,indexes:s,types:r}}function Ko(e){return Ln(e).values}function Go(e){const{split:t,types:n}=Ln(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===qo?o+=En(r[i]):a===Wo?o+=be.transform(r[i]):o+=r[i]}return o}}const hc=e=>typeof e=="number"?0:be.test(e)?be.getAnimatableNone(e):e;function fc(e){const t=Ko(e);return Go(e)(t.map(hc))}const Ct={test:lc,parse:Ko,createTransformer:Go,getAnimatableNone:fc};function Es(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 mc({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,l=2*n-a;r=Es(l,a,e+1/3),o=Es(l,a,e),i=Es(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function ps(e,t){return n=>n>0?t:e}const fe=(e,t,n)=>e+(t-e)*n,Ns=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},pc=[Ws,Ot,Jt],gc=e=>pc.find(t=>t.test(e));function ui(e){const t=gc(e);if(ln(!!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===Jt&&(n=mc(n)),n}const di=(e,t)=>{const n=ui(e),s=ui(t);if(!n||!s)return ps(e,t);const r={...n};return o=>(r.red=Ns(n.red,s.red,o),r.green=Ns(n.green,s.green,o),r.blue=Ns(n.blue,s.blue,o),r.alpha=fe(n.alpha,s.alpha,o),Ot.transform(r))},Ks=new Set(["none","hidden"]);function yc(e,t){return Ks.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function xc(e,t){return n=>fe(e,t,n)}function Er(e){return typeof e=="number"?xc:typeof e=="string"?Ar(e)?ps:be.test(e)?di:wc:Array.isArray(e)?Yo:typeof e=="object"?be.test(e)?di:bc:ps}function Yo(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>Er(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function bc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=Er(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function vc(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 wc=(e,t)=>{const n=Ct.createTransformer(t),s=Ln(e),r=Ln(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?Ks.has(e)&&!r.values.length||Ks.has(t)&&!s.values.length?yc(e,t):Un(Yo(vc(s,r),r.values),n):(ln(!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"),ps(e,t))};function Ho(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?fe(e,t,n):Er(e)(e,t)}const Tc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>de.update(t,n),stop:()=>jt(t),now:()=>we.isProcessing?we.timestamp:Ne.now()}},Jo=(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)})`},gs=2e4;function Nr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<gs;)t+=n,s=e.next(t);return t>=gs?1/0:t}function Sc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(Nr(s),gs);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:Fe(r)}}const jc=5;function Zo(e,t,n){const s=Math.max(t-jc,0);return No(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},Ds=.001;function Cc({duration:e=he.duration,bounce:t=he.bounce,velocity:n=he.velocity,mass:s=he.mass}){let r,o;ln(e<=Ye(he.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=dt(he.minDamping,he.maxDamping,i),e=dt(he.minDuration,he.maxDuration,Fe(e)),i<1?(r=u=>{const d=u*i,h=d*e,m=d-n,p=Gs(u,i),v=Math.exp(-h);return Ds-m/p*v},o=u=>{const h=u*i*e,m=h*n+n,p=Math.pow(i,2)*Math.pow(u,2)*e,v=Math.exp(-h),x=Gs(Math.pow(u,2),i);return(-r(u)+Ds>0?-1:1)*((m-p)*v)/x}):(r=u=>{const d=Math.exp(-u*e),h=(u-n)*e+1;return-Ds+d*h},o=u=>{const d=Math.exp(-u*e),h=(n-u)*(e*e);return d*h});const a=5/e,l=Ac(r,o,a);if(e=Ye(e),isNaN(l))return{stiffness:he.stiffness,damping:he.damping,duration:e};{const u=Math.pow(l,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:e}}}const Pc=12;function Ac(e,t,n){let s=n;for(let r=1;r<Pc;r++)s=s-e(s)/t(s);return s}function Gs(e,t){return e*Math.sqrt(1-t*t)}const kc=["duration","bounce"],Mc=["stiffness","damping","mass"];function hi(e,t){return t.some(n=>e[n]!==void 0)}function Ec(e){let t={velocity:he.velocity,stiffness:he.stiffness,damping:he.damping,mass:he.mass,isResolvedFromDuration:!1,...e};if(!hi(e,Mc)&&hi(e,kc))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*dt(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:he.mass,stiffness:r,damping:o}}else{const n=Cc(e);t={...t,...n,mass:he.mass},t.isResolvedFromDuration=!0}return t}function ys(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:l,damping:u,mass:d,duration:h,velocity:m,isResolvedFromDuration:p}=Ec({...n,velocity:-Fe(n.velocity||0)}),v=m||0,x=u/(2*Math.sqrt(l*d)),T=i-o,y=Fe(Math.sqrt(l/d)),w=Math.abs(T)<5;s||(s=w?he.restSpeed.granular:he.restSpeed.default),r||(r=w?he.restDelta.granular:he.restDelta.default);let k;if(x<1){const E=Gs(y,x);k=B=>{const _=Math.exp(-x*y*B);return i-_*((v+x*y*T)/E*Math.sin(E*B)+T*Math.cos(E*B))}}else if(x===1)k=E=>i-Math.exp(-y*E)*(T+(v+y*T)*E);else{const E=y*Math.sqrt(x*x-1);k=B=>{const _=Math.exp(-x*y*B),M=Math.min(E*B,300);return i-_*((v+x*y*T)*Math.sinh(M)+E*T*Math.cosh(M))/E}}const O={calculatedDuration:p&&h||null,next:E=>{const B=k(E);if(p)a.done=E>=h;else{let _=E===0?v:0;x<1&&(_=E===0?Ye(v):Zo(k,E,B));const M=Math.abs(_)<=s,R=Math.abs(i-B)<=r;a.done=M&&R}return a.value=a.done?i:B,a},toString:()=>{const E=Math.min(Nr(O),gs),B=Jo(_=>O.next(E*_).value,E,30);return E+"ms "+B},toTransition:()=>{}};return O}ys.applyToOptions=e=>{const t=Sc(e,100,ys);return e.ease=t.ease,e.duration=Ye(t.duration),e.type="keyframes",e};function Ys({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:l,restDelta:u=.5,restSpeed:d}){const h=e[0],m={done:!1,value:h},p=M=>a!==void 0&&M<a||l!==void 0&&M>l,v=M=>a===void 0?l:l===void 0||Math.abs(a-M)<Math.abs(l-M)?a:l;let x=n*t;const T=h+x,y=i===void 0?T:i(T);y!==T&&(x=y-h);const w=M=>-x*Math.exp(-M/s),k=M=>y+w(M),O=M=>{const R=w(M),j=k(M);m.done=Math.abs(R)<=u,m.value=m.done?y:j};let E,B;const _=M=>{p(m.value)&&(E=M,B=ys({keyframes:[m.value,v(m.value)],velocity:Zo(k,M,m.value),damping:r,stiffness:o,restDelta:u,restSpeed:d}))};return _(0),{calculatedDuration:null,next:M=>{let R=!1;return!B&&E===void 0&&(R=!0,O(M),_(M)),E!==void 0&&M>=E?B.next(M-E):(!R&&O(M),m)}}}function Nc(e,t,n){const s=[],r=n||ft.mix||Ho,o=e.length-1;for(let i=0;i<o;i++){let a=r(e[i],e[i+1]);if(t){const l=Array.isArray(t)?t[i]||Be:t;a=Un(l,a)}s.push(a)}return s}function Dc(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(ht(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=Nc(t,s,r),l=a.length,u=d=>{if(i&&d<e[0])return t[0];let h=0;if(l>1)for(;h<e.length-2&&!(d<e[h+1]);h++);const m=On(e[h],e[h+1],d);return a[h](m)};return n?d=>u(dt(e[0],e[o-1],d)):u}function Rc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=On(0,t,s);e.push(fe(n,1,r))}}function Vc(e){const t=[0];return Rc(t,e.length-1),t}function Ic(e,t){return e.map(n=>n*t)}function Oc(e,t){return e.map(()=>t||Bo).splice(0,e.length-1)}function Zt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=Gl(s)?s.map(ai):ai(s),o={done:!1,value:t[0]},i=Ic(n&&n.length===t.length?n:Vc(t),e),a=Dc(i,t,{ease:Array.isArray(r)?r:Oc(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const $c=e=>e!==null;function Dr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter($c),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const Lc={decay:Ys,inertia:Ys,tween:Zt,keyframes:Zt,spring:ys};function Qo(e){typeof e.type=="string"&&(e.type=Lc[e.type])}class Rr{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const Fc=e=>e/100;class Vr extends Rr{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==Ne.now()&&this.tick(Ne.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;Qo(t);const{type:n=Zt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const l=n||Zt;process.env.NODE_ENV!=="production"&&l!==Zt&&ht(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),l!==Zt&&typeof a[0]!="number"&&(this.mixKeyframes=Un(Fc,Ho(a[0],a[1])),a=[0,100]);const u=l({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...t,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=Nr(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:l}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:d,repeat:h,repeatType:m,repeatDelay:p,type:v,onUpdate:x,finalKeyframe:T}=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),w=this.playbackSpeed>=0?y<0:y>r;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let k=this.currentTime,O=s;if(h){const M=Math.min(this.currentTime,r)/a;let R=Math.floor(M),j=M%1;!j&&M>=1&&(j=1),j===1&&R--,R=Math.min(R,h+1),!!(R%2)&&(m==="reverse"?(j=1-j,p&&(j-=p/a)):m==="mirror"&&(O=i)),k=dt(0,1,j)*a}const E=w?{done:!1,value:d[0]}:O.next(k);o&&(E.value=o(E.value));let{done:B}=E;!w&&l!==null&&(B=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const _=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&B);return _&&v!==Ys&&(E.value=Dr(d,this.options,T,this.speed)),x&&x(E.value),_&&this.finish(),E}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(Ne.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=Fe(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Tc,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(Ne.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 Bc(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const $t=e=>e*180/Math.PI,Hs=e=>{const t=$t(Math.atan2(e[1],e[0]));return Js(t)},zc={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Hs,rotateZ:Hs,skewX:e=>$t(Math.atan(e[1])),skewY:e=>$t(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Js=e=>(e=e%360,e<0&&(e+=360),e),fi=Hs,mi=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),pi=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),Uc={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:mi,scaleY:pi,scale:e=>(mi(e)+pi(e))/2,rotateX:e=>Js($t(Math.atan2(e[6],e[5]))),rotateY:e=>Js($t(Math.atan2(-e[2],e[0]))),rotateZ:fi,rotate:fi,skewX:e=>$t(Math.atan(e[4])),skewY:e=>$t(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Zs(e){return e.includes("scale")?1:0}function Qs(e,t){if(!e||e==="none")return Zs(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=Uc,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=zc,r=a}if(!r)return Zs(t);const o=s[t],i=r[1].split(",").map(Xc);return typeof o=="function"?o(i):i[o]}const _c=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Qs(n,t)};function Xc(e){return parseFloat(e.trim())}const un=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],dn=new Set(un),gi=e=>e===cn||e===W,qc=new Set(["x","y","z"]),Wc=un.filter(e=>!qc.has(e));function Kc(e){const t=[];return Wc.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const Lt={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})=>Qs(t,"x"),y:(e,{transform:t})=>Qs(t,"y")};Lt.translateX=Lt.x;Lt.translateY=Lt.y;const Ft=new Set;let er=!1,tr=!1,nr=!1;function ea(){if(tr){const e=Array.from(Ft).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=Kc(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)})}tr=!1,er=!1,Ft.forEach(e=>e.complete(nr)),Ft.clear()}function ta(){Ft.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(tr=!0)})}function Gc(){nr=!0,ta(),ea(),nr=!1}class Ir{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?(Ft.add(this),er||(er=!0,de.read(ta),de.resolveKeyframes(ea))):(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])}Bc(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Ft.delete(this)}cancel(){this.state==="scheduled"&&(Ft.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Yc=e=>e.startsWith("--");function Hc(e,t,n){Yc(t)?e.style.setProperty(t,n):e.style[t]=n}const Jc=wr(()=>window.ScrollTimeline!==void 0),Zc={};function Qc(e,t){const n=wr(e);return()=>Zc[t]??n()}const na=Qc(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),kn=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,yi={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:kn([0,.65,.55,1]),circOut:kn([.55,0,1,.45]),backIn:kn([.31,.01,.66,-.59]),backOut:kn([.33,1.53,.69,.99])};function sa(e,t){if(e)return typeof e=="function"?na()?Jo(e,t):"ease-out":zo(e)?kn(e):Array.isArray(e)?e.map(n=>sa(n,t)||yi.easeOut):yi[e]}function eu(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:l}={},u=void 0){const d={[t]:n};l&&(d.offset=l);const h=sa(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 ra(e){return typeof e=="function"&&"applyToOptions"in e}function tu({type:e,...t}){return ra(e)&&na()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class nu extends Rr{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:l}=t;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=t,ht(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=tu(t);this.animation=eu(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Dr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Hc(n,s,d),this.animation.cancel()}l?.(),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&&Jc()?(this.animation.timeline=t,Be):n(this)}}const ia={anticipate:$o,backInOut:Oo,circInOut:Fo};function su(e){return e in ia}function ru(e){typeof e.ease=="string"&&su(e.ease)&&(e.ease=ia[e.ease])}const xi=10;class iu extends nu{constructor(t){ru(t),Qo(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 Vr({...i,autoplay:!1}),l=Ye(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-xi).value,a.sample(l).value,xi),a.stop()}}const bi=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(Ct.test(e)||e==="0")&&!e.startsWith("url("));function ou(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 au(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=bi(r,t),a=bi(o,t);return ln(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:ou(e)||(n==="spring"||ra(n))&&s}function sr(e){e.duration=0,e.type="keyframes"}const lu=new Set(["opacity","clipPath","filter","transform"]),cu=wr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function uu(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:l,transformTemplate:u}=t.owner.getProps();return cu()&&n&&lu.has(n)&&(n!=="transform"||!u)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const du=40;class hu extends Rr{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:l,motionValue:u,element:d,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Ne.now();const m={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:l,motionValue:u,element:d,...h},p=d?.KeyframeResolver||Ir;this.keyframeResolver=new p(a,(v,x,T)=>this.onKeyframesResolved(v,x,m,!T),l,u,d),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:l,isHandoff:u,onUpdate:d}=s;this.resolvedAt=Ne.now(),au(t,o,i,a)||((ft.instantAnimations||!l)&&d?.(Dr(t,s,n)),t[0]=t[t.length-1],sr(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>du?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!u&&uu(m)?new iu({...m,element:m.motionValue.owner.current}):new Vr(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(),Gc()),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 fu=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function mu(e){const t=fu.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const pu=4;function oa(e,t,n=1){ht(n<=pu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=mu(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return ko(i)?parseFloat(i):i}return Ar(r)?oa(r,t,n+1):r}function Or(e,t){return e?.[t]??e?.default??e}const aa=new Set(["width","height","top","left","right","bottom",...un]),gu={test:e=>e==="auto",parse:e=>e},la=e=>t=>t.test(e),ca=[cn,W,st,St,oc,ic,gu],vi=e=>ca.find(la(e));function yu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||Eo(e):!0}const xu=new Set(["brightness","contrast","saturate","opacity"]);function bu(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(kr)||[];if(!s)return e;const r=n.replace(s,"");let o=xu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const vu=/\b([a-z-]*)\(.*?\)/gu,rr={...Ct,getAnimatableNone:e=>{const t=e.match(vu);return t?t.map(bu).join(" "):e}},wi={...cn,transform:Math.round},wu={rotate:St,rotateX:St,rotateY:St,rotateZ:St,scale:ss,scaleX:ss,scaleY:ss,scaleZ:ss,skew:St,skewX:St,skewY:St,distance:W,translateX:W,translateY:W,translateZ:W,x:W,y:W,z:W,perspective:W,transformPerspective:W,opacity:$n,originX:li,originY:li,originZ:W},$r={borderWidth:W,borderTopWidth:W,borderRightWidth:W,borderBottomWidth:W,borderLeftWidth:W,borderRadius:W,radius:W,borderTopLeftRadius:W,borderTopRightRadius:W,borderBottomRightRadius:W,borderBottomLeftRadius:W,width:W,maxWidth:W,height:W,maxHeight:W,top:W,right:W,bottom:W,left:W,padding:W,paddingTop:W,paddingRight:W,paddingBottom:W,paddingLeft:W,margin:W,marginTop:W,marginRight:W,marginBottom:W,marginLeft:W,backgroundPositionX:W,backgroundPositionY:W,...wu,zIndex:wi,fillOpacity:$n,strokeOpacity:$n,numOctaves:wi},Tu={...$r,color:be,backgroundColor:be,outlineColor:be,fill:be,stroke:be,borderColor:be,borderTopColor:be,borderRightColor:be,borderBottomColor:be,borderLeftColor:be,filter:rr,WebkitFilter:rr},ua=e=>Tu[e];function da(e,t){let n=ua(e);return n!==rr&&(n=Ct),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Su=new Set(["auto","none","0"]);function ju(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!Su.has(o)&&Ln(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=da(n,r)}class Cu extends Ir{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 l=0;l<t.length;l++){let u=t[l];if(typeof u=="string"&&(u=u.trim(),Ar(u))){const d=oa(u,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!aa.has(s)||t.length!==2)return;const[r,o]=t,i=vi(r),a=vi(o);if(i!==a)if(gi(i)&&gi(a))for(let l=0;l<t.length;l++){const u=t[l];typeof u=="string"&&(t[l]=parseFloat(u))}else Lt[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||yu(t[r]))&&s.push(r);s.length&&ju(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=Lt[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]=Lt[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,l])=>{t.getValue(a).set(l)}),this.resolveNoneKeyframes()}}function Pu(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 ha=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function fa(e){return Mo(e)&&"offsetHeight"in e}const Ti=30,Au=e=>!isNaN(parseFloat(e));class ku{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=Ne.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=Ne.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Au(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&Sr(!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 Tr);const s=this.events[t].add(n);return t==="change"?()=>{s(),de.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=Ne.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Ti)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Ti);return No(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 on(e,t){return new ku(e,t)}const{schedule:Lr}=Uo(queueMicrotask,!1),Ke={x:!1,y:!1};function ma(){return Ke.x||Ke.y}function Mu(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 pa(e,t){const n=Pu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function Si(e){return!(e.pointerType==="touch"||ma())}function Eu(e,t,n={}){const[s,r,o]=pa(e,n),i=a=>{if(!Si(a))return;const{target:l}=a,u=t(l,a);if(typeof u!="function"||!l)return;const d=h=>{Si(h)&&(u(h),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ga=(e,t)=>t?e===t?!0:ga(e,t.parentElement):!1,Fr=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Nu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Du(e){return Nu.has(e.tagName)||e.tabIndex!==-1}const ls=new WeakSet;function ji(e){return t=>{t.key==="Enter"&&e(t)}}function Rs(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Ru=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=ji(()=>{if(ls.has(n))return;Rs(n,"down");const r=ji(()=>{Rs(n,"up")}),o=()=>Rs(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 Ci(e){return Fr(e)&&!ma()}function Vu(e,t,n={}){const[s,r,o]=pa(e,n),i=a=>{const l=a.currentTarget;if(!Ci(a))return;ls.add(l);const u=t(l,a),d=(p,v)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),ls.has(l)&&ls.delete(l),Ci(p)&&typeof u=="function"&&u(p,{success:v})},h=p=>{d(p,l===window||l===document||n.useGlobalTarget||ga(l,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),fa(a)&&(a.addEventListener("focus",u=>Ru(u,r)),!Du(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function ya(e){return Mo(e)&&"ownerSVGElement"in e}function Iu(e){return ya(e)&&e.tagName==="svg"}const Se=e=>!!(e&&e.getVelocity),Ou=[...ca,be,Ct],$u=e=>Ou.find(la(e)),Br=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function Pi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Lu(...e){return t=>{let n=!1;const s=e.map(r=>{const o=Pi(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():Pi(e[r],null)}}}}function Fu(...e){return Ge.useCallback(Lu(...e),e)}class Bu extends Ge.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=fa(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 zu({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(Br),l=Fu(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 v=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const x=document.createElement("style");a&&(x.nonce=a);const T=s??document.head;return T.appendChild(x),x.sheet&&x.sheet.insertRule(`
1
+ "use strict";var Cl=Object.create;var ei=Object.defineProperty;var Pl=Object.getOwnPropertyDescriptor;var Al=Object.getOwnPropertyNames;var kl=Object.getPrototypeOf,Ml=Object.prototype.hasOwnProperty;var El=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Al(t))!Ml.call(e,r)&&r!==n&&ei(e,r,{get:()=>t[r],enumerable:!(s=Pl(t,r))||s.enumerable});return e};var Nl=(e,t,n)=>(n=e!=null?Cl(kl(e)):{},El(t||!e||!e.__esModule?ei(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),f=require("react"),re=require("lucide-react"),wo=require("@ai-sdk/react"),fs=require("ai"),To=require("@radix-ui/react-slot"),So=require("class-variance-authority"),Dl=require("clsx"),Rl=require("tailwind-merge"),Vl=require("@radix-ui/react-tooltip"),ti=require("@radix-ui/react-use-controllable-state"),Il=require("@radix-ui/react-collapsible"),Ol=require("react-dom"),$l=require("@radix-ui/react-dialog"),Ll=require("./server.cjs");function bs(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 Ye=bs(f),nn=bs(Vl),fr=bs(Il),Ft=bs($l);function ie(...e){return Rl.twMerge(Dl.clsx(e))}const Rt=So.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"}}),Ce=Ye.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?To.Slot:"button";return c.jsx(i,{ref:o,"data-slot":"button",className:ie(Rt({variant:t,size:n,className:e})),...r})});Ce.displayName="Button";const Fl=So.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 Cs({className:e,variant:t,asChild:n=!1,...s}){const r=n?To.Slot:"span";return c.jsx(r,{"data-slot":"badge",className:ie(Fl({variant:t}),e),...s})}const Bl=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Ye.useState(!0);Ye.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 l=a.scrollHeight;l>n?a.style.height=`${n}px`:a.style.height=`${l+6}px`}},[e.current,t])},jo=Ye.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Ye.useRef(null),[l,u]=Ye.useState("");return Bl({textAreaRef:a,triggerAutoSize:l,maxHeight:e,minHeight:t}),f.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),Ye.useEffect(()=>{u(r)},[o?.defaultValue,r]),c.jsx("textarea",{...o,value:r,ref:a,className:ie("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)}})});jo.displayName="AutosizeTextarea";function zl({delayDuration:e=0,...t}){return c.jsx(nn.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function bt({...e}){return c.jsx(zl,{children:c.jsx(nn.Root,{"data-slot":"tooltip",...e})})}function vt({...e}){return c.jsx(nn.Trigger,{"data-slot":"tooltip-trigger",...e})}function wt({className:e,sideOffset:t=0,children:n,...s}){return c.jsx(nn.Portal,{children:c.jsxs(nn.Content,{"data-slot":"tooltip-content",sideOffset:t,className:ie("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,c.jsx(nn.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function ni({className:e,...t}){return c.jsx("kbd",{"data-slot":"kbd",className:ie("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 mr=f.createContext({});function pr(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const gr=typeof window<"u",Co=gr?f.useLayoutEffect:f.useEffect,vs=f.createContext(null);function yr(e,t){e.indexOf(t)===-1&&e.push(t)}function xr(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const dt=(e,t,n)=>n>t?t:n<e?e:n;function _s(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let an=()=>{},ht=()=>{};process.env.NODE_ENV!=="production"&&(an=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(_s(t,n))},ht=(e,t,n)=>{if(!e)throw new Error(_s(t,n))});const ft={},Po=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Ao(e){return typeof e=="object"&&e!==null}const ko=e=>/^0[^.\s]+$/u.test(e);function br(e){let t;return()=>(t===void 0&&(t=e()),t)}const ze=e=>e,Ul=(e,t)=>n=>t(e(n)),Un=(...e)=>e.reduce(Ul),On=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class vr{constructor(){this.subscriptions=[]}add(t){return yr(this.subscriptions,t),()=>xr(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 He=e=>e*1e3,Be=e=>e/1e3;function Mo(e,t){return t?e*(1e3/t):0}const si=new Set;function wr(e,t,n){e||si.has(t)||(console.warn(_s(t,n)),si.add(t))}const Eo=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,_l=1e-7,Xl=12;function ql(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=Eo(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>_l&&++a<Xl);return i}function _n(e,t,n,s){if(e===t&&n===s)return ze;const r=o=>ql(o,0,1,e,n);return o=>o===0||o===1?o:Eo(r(o),t,s)}const No=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Do=e=>t=>1-e(1-t),Ro=_n(.33,1.53,.69,.99),Tr=Do(Ro),Vo=No(Tr),Io=e=>(e*=2)<1?.5*Tr(e):.5*(2-Math.pow(2,-10*(e-1))),Sr=e=>1-Math.sin(Math.acos(e)),Oo=Do(Sr),$o=No(Sr),Wl=_n(.42,0,1,1),Kl=_n(0,0,.58,1),Lo=_n(.42,0,.58,1),Gl=e=>Array.isArray(e)&&typeof e[0]!="number",Fo=e=>Array.isArray(e)&&typeof e[0]=="number",ri={linear:ze,easeIn:Wl,easeInOut:Lo,easeOut:Kl,circIn:Sr,circInOut:$o,circOut:Oo,backIn:Tr,backInOut:Vo,backOut:Ro,anticipate:Io},Yl=e=>typeof e=="string",ii=e=>{if(Fo(e)){ht(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return _n(t,n,s,r)}else if(Yl(e))return ht(ri[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),ri[e];return e},ts=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Hl(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 l(d){i.has(d)&&(u.schedule(d),e()),d(a)}const u={schedule:(d,h=!1,m=!1)=>{const v=m&&r?n:s;return h&&i.add(d),v.has(d)||v.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(l),n.clear(),r=!1,o&&(o=!1,u.process(d))}};return u}const Jl=40;function Bo(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=ts.reduce((k,O)=>(k[O]=Hl(o),k),{}),{setup:a,read:l,resolveKeyframes:u,preUpdate:d,update:h,preRender:m,render:p,postRender:v}=i,x=()=>{const k=ft.useManualTiming?r.timestamp:performance.now();n=!1,ft.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(k-r.timestamp,Jl),1)),r.timestamp=k,r.isProcessing=!0,a.process(r),l.process(r),u.process(r),d.process(r),h.process(r),m.process(r),p.process(r),v.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(x))},T=()=>{n=!0,s=!0,r.isProcessing||e(x)};return{schedule:ts.reduce((k,O)=>{const E=i[O];return k[O]=(B,_=!1,M=!1)=>(n||T(),E.schedule(B,_,M)),k},{}),cancel:k=>{for(let O=0;O<ts.length;O++)i[ts[O]].cancel(k)},state:r,steps:i}}const{schedule:de,cancel:St,state:ve,steps:Ps}=Bo(typeof requestAnimationFrame<"u"?requestAnimationFrame:ze,!0);let os;function Zl(){os=void 0}const De={now:()=>(os===void 0&&De.set(ve.isProcessing||ft.useManualTiming?ve.timestamp:performance.now()),os),set:e=>{os=e,queueMicrotask(Zl)}},zo=e=>t=>typeof t=="string"&&t.startsWith(e),jr=zo("--"),Ql=zo("var(--"),Cr=e=>Ql(e)?ec.test(e.split("/*")[0].trim()):!1,ec=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,ln={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},$n={...ln,transform:e=>dt(0,1,e)},ns={...ln,default:1},En=e=>Math.round(e*1e5)/1e5,Pr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function tc(e){return e==null}const nc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Ar=(e,t)=>n=>!!(typeof n=="string"&&nc.test(n)&&n.startsWith(e)||t&&!tc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Uo=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Pr);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},sc=e=>dt(0,255,e),As={...ln,transform:e=>Math.round(sc(e))},It={test:Ar("rgb","red"),parse:Uo("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+As.transform(e)+", "+As.transform(t)+", "+As.transform(n)+", "+En($n.transform(s))+")"};function rc(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 Xs={test:Ar("#"),parse:rc,transform:It.transform},Xn=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Tt=Xn("deg"),rt=Xn("%"),W=Xn("px"),ic=Xn("vh"),oc=Xn("vw"),oi={...rt,parse:e=>rt.parse(e)/100,transform:e=>rt.transform(e*100)},Ht={test:Ar("hsl","hue"),parse:Uo("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+rt.transform(En(t))+", "+rt.transform(En(n))+", "+En($n.transform(s))+")"},be={test:e=>It.test(e)||Xs.test(e)||Ht.test(e),parse:e=>It.test(e)?It.parse(e):Ht.test(e)?Ht.parse(e):Xs.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?It.transform(e):Ht.transform(e),getAnimatableNone:e=>{const t=be.parse(e);return t.alpha=0,be.transform(t)}},ac=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function lc(e){return isNaN(e)&&typeof e=="string"&&(e.match(Pr)?.length||0)+(e.match(ac)?.length||0)>0}const _o="number",Xo="color",cc="var",uc="var(",ai="${}",dc=/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 Ln(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(dc,l=>(be.test(l)?(s.color.push(o),r.push(Xo),n.push(be.parse(l))):l.startsWith(uc)?(s.var.push(o),r.push(cc),n.push(l)):(s.number.push(o),r.push(_o),n.push(parseFloat(l))),++o,ai)).split(ai);return{values:n,split:a,indexes:s,types:r}}function qo(e){return Ln(e).values}function Wo(e){const{split:t,types:n}=Ln(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===_o?o+=En(r[i]):a===Xo?o+=be.transform(r[i]):o+=r[i]}return o}}const hc=e=>typeof e=="number"?0:be.test(e)?be.getAnimatableNone(e):e;function fc(e){const t=qo(e);return Wo(e)(t.map(hc))}const jt={test:lc,parse:qo,createTransformer:Wo,getAnimatableNone:fc};function ks(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 mc({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,l=2*n-a;r=ks(l,a,e+1/3),o=ks(l,a,e),i=ks(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function ms(e,t){return n=>n>0?t:e}const fe=(e,t,n)=>e+(t-e)*n,Ms=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},pc=[Xs,It,Ht],gc=e=>pc.find(t=>t.test(e));function li(e){const t=gc(e);if(an(!!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===Ht&&(n=mc(n)),n}const ci=(e,t)=>{const n=li(e),s=li(t);if(!n||!s)return ms(e,t);const r={...n};return o=>(r.red=Ms(n.red,s.red,o),r.green=Ms(n.green,s.green,o),r.blue=Ms(n.blue,s.blue,o),r.alpha=fe(n.alpha,s.alpha,o),It.transform(r))},qs=new Set(["none","hidden"]);function yc(e,t){return qs.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function xc(e,t){return n=>fe(e,t,n)}function kr(e){return typeof e=="number"?xc:typeof e=="string"?Cr(e)?ms:be.test(e)?ci:wc:Array.isArray(e)?Ko:typeof e=="object"?be.test(e)?ci:bc:ms}function Ko(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>kr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function bc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=kr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function vc(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 wc=(e,t)=>{const n=jt.createTransformer(t),s=Ln(e),r=Ln(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?qs.has(e)&&!r.values.length||qs.has(t)&&!s.values.length?yc(e,t):Un(Ko(vc(s,r),r.values),n):(an(!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"),ms(e,t))};function Go(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?fe(e,t,n):kr(e)(e,t)}const Tc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>de.update(t,n),stop:()=>St(t),now:()=>ve.isProcessing?ve.timestamp:De.now()}},Yo=(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)})`},ps=2e4;function Mr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<ps;)t+=n,s=e.next(t);return t>=ps?1/0:t}function Sc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(Mr(s),ps);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:Be(r)}}const jc=5;function Ho(e,t,n){const s=Math.max(t-jc,0);return Mo(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},Es=.001;function Cc({duration:e=he.duration,bounce:t=he.bounce,velocity:n=he.velocity,mass:s=he.mass}){let r,o;an(e<=He(he.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=dt(he.minDamping,he.maxDamping,i),e=dt(he.minDuration,he.maxDuration,Be(e)),i<1?(r=u=>{const d=u*i,h=d*e,m=d-n,p=Ws(u,i),v=Math.exp(-h);return Es-m/p*v},o=u=>{const h=u*i*e,m=h*n+n,p=Math.pow(i,2)*Math.pow(u,2)*e,v=Math.exp(-h),x=Ws(Math.pow(u,2),i);return(-r(u)+Es>0?-1:1)*((m-p)*v)/x}):(r=u=>{const d=Math.exp(-u*e),h=(u-n)*e+1;return-Es+d*h},o=u=>{const d=Math.exp(-u*e),h=(n-u)*(e*e);return d*h});const a=5/e,l=Ac(r,o,a);if(e=He(e),isNaN(l))return{stiffness:he.stiffness,damping:he.damping,duration:e};{const u=Math.pow(l,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:e}}}const Pc=12;function Ac(e,t,n){let s=n;for(let r=1;r<Pc;r++)s=s-e(s)/t(s);return s}function Ws(e,t){return e*Math.sqrt(1-t*t)}const kc=["duration","bounce"],Mc=["stiffness","damping","mass"];function ui(e,t){return t.some(n=>e[n]!==void 0)}function Ec(e){let t={velocity:he.velocity,stiffness:he.stiffness,damping:he.damping,mass:he.mass,isResolvedFromDuration:!1,...e};if(!ui(e,Mc)&&ui(e,kc))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*dt(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:he.mass,stiffness:r,damping:o}}else{const n=Cc(e);t={...t,...n,mass:he.mass},t.isResolvedFromDuration=!0}return t}function gs(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:l,damping:u,mass:d,duration:h,velocity:m,isResolvedFromDuration:p}=Ec({...n,velocity:-Be(n.velocity||0)}),v=m||0,x=u/(2*Math.sqrt(l*d)),T=i-o,y=Be(Math.sqrt(l/d)),w=Math.abs(T)<5;s||(s=w?he.restSpeed.granular:he.restSpeed.default),r||(r=w?he.restDelta.granular:he.restDelta.default);let k;if(x<1){const E=Ws(y,x);k=B=>{const _=Math.exp(-x*y*B);return i-_*((v+x*y*T)/E*Math.sin(E*B)+T*Math.cos(E*B))}}else if(x===1)k=E=>i-Math.exp(-y*E)*(T+(v+y*T)*E);else{const E=y*Math.sqrt(x*x-1);k=B=>{const _=Math.exp(-x*y*B),M=Math.min(E*B,300);return i-_*((v+x*y*T)*Math.sinh(M)+E*T*Math.cosh(M))/E}}const O={calculatedDuration:p&&h||null,next:E=>{const B=k(E);if(p)a.done=E>=h;else{let _=E===0?v:0;x<1&&(_=E===0?He(v):Ho(k,E,B));const M=Math.abs(_)<=s,R=Math.abs(i-B)<=r;a.done=M&&R}return a.value=a.done?i:B,a},toString:()=>{const E=Math.min(Mr(O),ps),B=Yo(_=>O.next(E*_).value,E,30);return E+"ms "+B},toTransition:()=>{}};return O}gs.applyToOptions=e=>{const t=Sc(e,100,gs);return e.ease=t.ease,e.duration=He(t.duration),e.type="keyframes",e};function Ks({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:l,restDelta:u=.5,restSpeed:d}){const h=e[0],m={done:!1,value:h},p=M=>a!==void 0&&M<a||l!==void 0&&M>l,v=M=>a===void 0?l:l===void 0||Math.abs(a-M)<Math.abs(l-M)?a:l;let x=n*t;const T=h+x,y=i===void 0?T:i(T);y!==T&&(x=y-h);const w=M=>-x*Math.exp(-M/s),k=M=>y+w(M),O=M=>{const R=w(M),j=k(M);m.done=Math.abs(R)<=u,m.value=m.done?y:j};let E,B;const _=M=>{p(m.value)&&(E=M,B=gs({keyframes:[m.value,v(m.value)],velocity:Ho(k,M,m.value),damping:r,stiffness:o,restDelta:u,restSpeed:d}))};return _(0),{calculatedDuration:null,next:M=>{let R=!1;return!B&&E===void 0&&(R=!0,O(M),_(M)),E!==void 0&&M>=E?B.next(M-E):(!R&&O(M),m)}}}function Nc(e,t,n){const s=[],r=n||ft.mix||Go,o=e.length-1;for(let i=0;i<o;i++){let a=r(e[i],e[i+1]);if(t){const l=Array.isArray(t)?t[i]||ze:t;a=Un(l,a)}s.push(a)}return s}function Dc(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(ht(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=Nc(t,s,r),l=a.length,u=d=>{if(i&&d<e[0])return t[0];let h=0;if(l>1)for(;h<e.length-2&&!(d<e[h+1]);h++);const m=On(e[h],e[h+1],d);return a[h](m)};return n?d=>u(dt(e[0],e[o-1],d)):u}function Rc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=On(0,t,s);e.push(fe(n,1,r))}}function Vc(e){const t=[0];return Rc(t,e.length-1),t}function Ic(e,t){return e.map(n=>n*t)}function Oc(e,t){return e.map(()=>t||Lo).splice(0,e.length-1)}function Jt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=Gl(s)?s.map(ii):ii(s),o={done:!1,value:t[0]},i=Ic(n&&n.length===t.length?n:Vc(t),e),a=Dc(i,t,{ease:Array.isArray(r)?r:Oc(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const $c=e=>e!==null;function Er(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter($c),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const Lc={decay:Ks,inertia:Ks,tween:Jt,keyframes:Jt,spring:gs};function Jo(e){typeof e.type=="string"&&(e.type=Lc[e.type])}class Nr{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 Fc=e=>e/100;class Dr extends Nr{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!==De.now()&&this.tick(De.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;Jo(t);const{type:n=Jt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const l=n||Jt;process.env.NODE_ENV!=="production"&&l!==Jt&&ht(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),l!==Jt&&typeof a[0]!="number"&&(this.mixKeyframes=Un(Fc,Go(a[0],a[1])),a=[0,100]);const u=l({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...t,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=Mr(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:l}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:d,repeat:h,repeatType:m,repeatDelay:p,type:v,onUpdate:x,finalKeyframe:T}=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),w=this.playbackSpeed>=0?y<0:y>r;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let k=this.currentTime,O=s;if(h){const M=Math.min(this.currentTime,r)/a;let R=Math.floor(M),j=M%1;!j&&M>=1&&(j=1),j===1&&R--,R=Math.min(R,h+1),!!(R%2)&&(m==="reverse"?(j=1-j,p&&(j-=p/a)):m==="mirror"&&(O=i)),k=dt(0,1,j)*a}const E=w?{done:!1,value:d[0]}:O.next(k);o&&(E.value=o(E.value));let{done:B}=E;!w&&l!==null&&(B=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const _=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&B);return _&&v!==Ks&&(E.value=Er(d,this.options,T,this.speed)),x&&x(E.value),_&&this.finish(),E}then(t,n){return this.finished.then(t,n)}get duration(){return Be(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Be(t)}get time(){return Be(this.currentTime)}set time(t){t=He(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(De.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=Be(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Tc,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(De.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 Bc(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Ot=e=>e*180/Math.PI,Gs=e=>{const t=Ot(Math.atan2(e[1],e[0]));return Ys(t)},zc={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Gs,rotateZ:Gs,skewX:e=>Ot(Math.atan(e[1])),skewY:e=>Ot(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ys=e=>(e=e%360,e<0&&(e+=360),e),di=Gs,hi=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),fi=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),Uc={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:hi,scaleY:fi,scale:e=>(hi(e)+fi(e))/2,rotateX:e=>Ys(Ot(Math.atan2(e[6],e[5]))),rotateY:e=>Ys(Ot(Math.atan2(-e[2],e[0]))),rotateZ:di,rotate:di,skewX:e=>Ot(Math.atan(e[4])),skewY:e=>Ot(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Hs(e){return e.includes("scale")?1:0}function Js(e,t){if(!e||e==="none")return Hs(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=Uc,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=zc,r=a}if(!r)return Hs(t);const o=s[t],i=r[1].split(",").map(Xc);return typeof o=="function"?o(i):i[o]}const _c=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Js(n,t)};function Xc(e){return parseFloat(e.trim())}const cn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],un=new Set(cn),mi=e=>e===ln||e===W,qc=new Set(["x","y","z"]),Wc=cn.filter(e=>!qc.has(e));function Kc(e){const t=[];return Wc.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const $t={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})=>Js(t,"x"),y:(e,{transform:t})=>Js(t,"y")};$t.translateX=$t.x;$t.translateY=$t.y;const Lt=new Set;let Zs=!1,Qs=!1,er=!1;function Zo(){if(Qs){const e=Array.from(Lt).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=Kc(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)})}Qs=!1,Zs=!1,Lt.forEach(e=>e.complete(er)),Lt.clear()}function Qo(){Lt.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Qs=!0)})}function Gc(){er=!0,Qo(),Zo(),er=!1}class Rr{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?(Lt.add(this),Zs||(Zs=!0,de.read(Qo),de.resolveKeyframes(Zo))):(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])}Bc(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Lt.delete(this)}cancel(){this.state==="scheduled"&&(Lt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Yc=e=>e.startsWith("--");function Hc(e,t,n){Yc(t)?e.style.setProperty(t,n):e.style[t]=n}const Jc=br(()=>window.ScrollTimeline!==void 0),Zc={};function Qc(e,t){const n=br(e);return()=>Zc[t]??n()}const ea=Qc(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),kn=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,pi={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:kn([0,.65,.55,1]),circOut:kn([.55,0,1,.45]),backIn:kn([.31,.01,.66,-.59]),backOut:kn([.33,1.53,.69,.99])};function ta(e,t){if(e)return typeof e=="function"?ea()?Yo(e,t):"ease-out":Fo(e)?kn(e):Array.isArray(e)?e.map(n=>ta(n,t)||pi.easeOut):pi[e]}function eu(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:l}={},u=void 0){const d={[t]:n};l&&(d.offset=l);const h=ta(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 na(e){return typeof e=="function"&&"applyToOptions"in e}function tu({type:e,...t}){return na(e)&&ea()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class nu extends Nr{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:l}=t;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=t,ht(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=tu(t);this.animation=eu(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Er(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Hc(n,s,d),this.animation.cancel()}l?.(),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 Be(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Be(t)}get time(){return Be(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=He(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&&Jc()?(this.animation.timeline=t,ze):n(this)}}const sa={anticipate:Io,backInOut:Vo,circInOut:$o};function su(e){return e in sa}function ru(e){typeof e.ease=="string"&&su(e.ease)&&(e.ease=sa[e.ease])}const gi=10;class iu extends nu{constructor(t){ru(t),Jo(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new Dr({...i,autoplay:!1}),l=He(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-gi).value,a.sample(l).value,gi),a.stop()}}const yi=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(jt.test(e)||e==="0")&&!e.startsWith("url("));function ou(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 au(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=yi(r,t),a=yi(o,t);return an(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:ou(e)||(n==="spring"||na(n))&&s}function tr(e){e.duration=0,e.type="keyframes"}const lu=new Set(["opacity","clipPath","filter","transform"]),cu=br(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function uu(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:l,transformTemplate:u}=t.owner.getProps();return cu()&&n&&lu.has(n)&&(n!=="transform"||!u)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const du=40;class hu extends Nr{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:l,motionValue:u,element:d,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=De.now();const m={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:l,motionValue:u,element:d,...h},p=d?.KeyframeResolver||Rr;this.keyframeResolver=new p(a,(v,x,T)=>this.onKeyframesResolved(v,x,m,!T),l,u,d),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:l,isHandoff:u,onUpdate:d}=s;this.resolvedAt=De.now(),au(t,o,i,a)||((ft.instantAnimations||!l)&&d?.(Er(t,s,n)),t[0]=t[t.length-1],tr(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>du?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!u&&uu(m)?new iu({...m,element:m.motionValue.owner.current}):new Dr(m);p.finished.then(()=>this.notifyFinished()).catch(ze),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(),Gc()),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 fu=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function mu(e){const t=fu.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const pu=4;function ra(e,t,n=1){ht(n<=pu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=mu(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return Po(i)?parseFloat(i):i}return Cr(r)?ra(r,t,n+1):r}function Vr(e,t){return e?.[t]??e?.default??e}const ia=new Set(["width","height","top","left","right","bottom",...cn]),gu={test:e=>e==="auto",parse:e=>e},oa=e=>t=>t.test(e),aa=[ln,W,rt,Tt,oc,ic,gu],xi=e=>aa.find(oa(e));function yu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||ko(e):!0}const xu=new Set(["brightness","contrast","saturate","opacity"]);function bu(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(Pr)||[];if(!s)return e;const r=n.replace(s,"");let o=xu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const vu=/\b([a-z-]*)\(.*?\)/gu,nr={...jt,getAnimatableNone:e=>{const t=e.match(vu);return t?t.map(bu).join(" "):e}},bi={...ln,transform:Math.round},wu={rotate:Tt,rotateX:Tt,rotateY:Tt,rotateZ:Tt,scale:ns,scaleX:ns,scaleY:ns,scaleZ:ns,skew:Tt,skewX:Tt,skewY:Tt,distance:W,translateX:W,translateY:W,translateZ:W,x:W,y:W,z:W,perspective:W,transformPerspective:W,opacity:$n,originX:oi,originY:oi,originZ:W},Ir={borderWidth:W,borderTopWidth:W,borderRightWidth:W,borderBottomWidth:W,borderLeftWidth:W,borderRadius:W,radius:W,borderTopLeftRadius:W,borderTopRightRadius:W,borderBottomRightRadius:W,borderBottomLeftRadius:W,width:W,maxWidth:W,height:W,maxHeight:W,top:W,right:W,bottom:W,left:W,padding:W,paddingTop:W,paddingRight:W,paddingBottom:W,paddingLeft:W,margin:W,marginTop:W,marginRight:W,marginBottom:W,marginLeft:W,backgroundPositionX:W,backgroundPositionY:W,...wu,zIndex:bi,fillOpacity:$n,strokeOpacity:$n,numOctaves:bi},Tu={...Ir,color:be,backgroundColor:be,outlineColor:be,fill:be,stroke:be,borderColor:be,borderTopColor:be,borderRightColor:be,borderBottomColor:be,borderLeftColor:be,filter:nr,WebkitFilter:nr},la=e=>Tu[e];function ca(e,t){let n=la(e);return n!==nr&&(n=jt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Su=new Set(["auto","none","0"]);function ju(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!Su.has(o)&&Ln(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=ca(n,r)}class Cu extends Rr{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 l=0;l<t.length;l++){let u=t[l];if(typeof u=="string"&&(u=u.trim(),Cr(u))){const d=ra(u,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!ia.has(s)||t.length!==2)return;const[r,o]=t,i=xi(r),a=xi(o);if(i!==a)if(mi(i)&&mi(a))for(let l=0;l<t.length;l++){const u=t[l];typeof u=="string"&&(t[l]=parseFloat(u))}else $t[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||yu(t[r]))&&s.push(r);s.length&&ju(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=$t[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]=$t[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,l])=>{t.getValue(a).set(l)}),this.resolveNoneKeyframes()}}function Pu(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 ua=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function da(e){return Ao(e)&&"offsetHeight"in e}const vi=30,Au=e=>!isNaN(parseFloat(e));class ku{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=De.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=De.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Au(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&wr(!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 vr);const s=this.events[t].add(n);return t==="change"?()=>{s(),de.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=De.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>vi)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,vi);return Mo(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 rn(e,t){return new ku(e,t)}const{schedule:Or}=Bo(queueMicrotask,!1),Ge={x:!1,y:!1};function ha(){return Ge.x||Ge.y}function Mu(e){return e==="x"||e==="y"?Ge[e]?null:(Ge[e]=!0,()=>{Ge[e]=!1}):Ge.x||Ge.y?null:(Ge.x=Ge.y=!0,()=>{Ge.x=Ge.y=!1})}function fa(e,t){const n=Pu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function wi(e){return!(e.pointerType==="touch"||ha())}function Eu(e,t,n={}){const[s,r,o]=fa(e,n),i=a=>{if(!wi(a))return;const{target:l}=a,u=t(l,a);if(typeof u!="function"||!l)return;const d=h=>{wi(h)&&(u(h),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ma=(e,t)=>t?e===t?!0:ma(e,t.parentElement):!1,$r=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Nu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Du(e){return Nu.has(e.tagName)||e.tabIndex!==-1}const as=new WeakSet;function Ti(e){return t=>{t.key==="Enter"&&e(t)}}function Ns(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Ru=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Ti(()=>{if(as.has(n))return;Ns(n,"down");const r=Ti(()=>{Ns(n,"up")}),o=()=>Ns(n,"cancel");n.addEventListener("keyup",r,t),n.addEventListener("blur",o,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function Si(e){return $r(e)&&!ha()}function Vu(e,t,n={}){const[s,r,o]=fa(e,n),i=a=>{const l=a.currentTarget;if(!Si(a))return;as.add(l);const u=t(l,a),d=(p,v)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),as.has(l)&&as.delete(l),Si(p)&&typeof u=="function"&&u(p,{success:v})},h=p=>{d(p,l===window||l===document||n.useGlobalTarget||ma(l,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),da(a)&&(a.addEventListener("focus",u=>Ru(u,r)),!Du(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function pa(e){return Ao(e)&&"ownerSVGElement"in e}function Iu(e){return pa(e)&&e.tagName==="svg"}const je=e=>!!(e&&e.getVelocity),Ou=[...aa,be,jt],$u=e=>Ou.find(oa(e)),Lr=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function ji(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Lu(...e){return t=>{let n=!1;const s=e.map(r=>{const o=ji(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():ji(e[r],null)}}}}function Fu(...e){return Ye.useCallback(Lu(...e),e)}class Bu extends Ye.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=da(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 zu({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(Lr),l=Fu(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 v=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const x=document.createElement("style");a&&(x.nonce=a);const T=s??document.head;return T.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
  ${v}px !important;
7
7
  top: ${h}px !important;
8
8
  }
9
- `),()=>{T.contains(x)&&T.removeChild(x)}},[t]),c.jsx(Bu,{isPresent:t,childRef:o,sizeRef:i,children:Ge.cloneElement(e,{ref:l})})}const Uu=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const u=yr(_u),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 v of u.values())if(!v)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,v)=>u.set(v,!1))},[n]),Ge.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(e=c.jsx(zu,{isPresent:n,anchorX:a,root:l,children:e})),c.jsx(ws.Provider,{value:m,children:e})};function _u(){return new Map}function xa(e=!0){const t=f.useContext(ws);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 rs=e=>e.key||"";function Ai(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const Xu=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:l})=>{const[u,d]=xa(i),h=f.useMemo(()=>Ai(e),[e]),m=i&&!u?[]:h.map(rs),p=f.useRef(!0),v=f.useRef(h),x=yr(()=>new Map),[T,y]=f.useState(h),[w,k]=f.useState(h);Ao(()=>{p.current=!1,v.current=h;for(let B=0;B<w.length;B++){const _=rs(w[B]);m.includes(_)?x.delete(_):x.get(_)!==!0&&x.set(_,!1)}},[w,m.length,m.join("-")]);const O=[];if(h!==T){let B=[...h];for(let _=0;_<w.length;_++){const M=w[_],R=rs(M);m.includes(R)||(B.splice(_,0,M),O.push(M))}return o==="wait"&&O.length&&(B=O),k(Ai(B)),y(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&w.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:E}=f.useContext(gr);return c.jsx(c.Fragment,{children:w.map(B=>{const _=rs(B),M=i&&!u?!1:h===w||m.includes(_),R=()=>{if(x.has(_))x.set(_,!0);else return;let j=!0;x.forEach(V=>{V||(j=!1)}),j&&(E?.(),k(v.current),i&&d?.(),s&&s())};return c.jsx(Uu,{isPresent:M,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:l,onExitComplete:M?void 0:R,anchorX:a,children:B},_)})})},zr=f.createContext({strict:!1}),ki={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"]},an={};for(const e in ki)an[e]={isEnabled:t=>ki[e].some(n=>!!t[n])};function ir(e){for(const t in e)an[t]={...an[t],...e[t]}}function qu({children:e,features:t,strict:n=!1}){const[,s]=f.useState(!Vs(t)),r=f.useRef(void 0);if(!Vs(t)){const{renderer:o,...i}=t;r.current=o,ir(i)}return f.useEffect(()=>{Vs(t)&&t().then(({renderer:o,...i})=>{ir(i),r.current=o,s(!0)})},[]),c.jsx(zr.Provider,{value:{renderer:r.current,strict:n},children:e})}function Vs(e){return typeof e=="function"}const Wu=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function xs(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Wu.has(e)}let ba=e=>!xs(e);function Ku(e){typeof e=="function"&&(ba=t=>t.startsWith("on")?!xs(t):e(t))}try{Ku(require("@emotion/is-prop-valid").default)}catch{}function Gu(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(ba(r)||n===!0&&xs(r)||!t&&!xs(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const Ts=f.createContext({});function Ss(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function Fn(e){return typeof e=="string"||Array.isArray(e)}const Ur=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],_r=["initial",...Ur];function js(e){return Ss(e.animate)||_r.some(t=>Fn(e[t]))}function va(e){return!!(js(e)||e.variants)}function Yu(e,t){if(js(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Fn(n)?n:void 0,animate:Fn(s)?s:void 0}}return e.inherit!==!1?t:{}}function Hu(e){const{initial:t,animate:n}=Yu(e,f.useContext(Ts));return f.useMemo(()=>({initial:t,animate:n}),[Mi(t),Mi(n)])}function Mi(e){return Array.isArray(e)?e.join(" "):e}const Bn={};function Ju(e){for(const t in e)Bn[t]=e[t],Pr(t)&&(Bn[t].isCSSVariable=!0)}function wa(e,{layout:t,layoutId:n}){return dn.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Bn[e]||e==="opacity")}const Zu={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Qu=un.length;function ed(e,t,n){let s="",r=!0;for(let o=0;o<Qu;o++){const i=un[o],a=e[i];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(i.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const u=ha(a,$r[i]);if(!l){r=!1;const d=Zu[i]||i;s+=`${d}(${u}) `}n&&(t[i]=u)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function Xr(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const l in t){const u=t[l];if(dn.has(l)){i=!0;continue}else if(Pr(l)){r[l]=u;continue}else{const d=ha(u,$r[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=ed(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:l="50%",originY:u="50%",originZ:d=0}=o;s.transformOrigin=`${l} ${u} ${d}`}}const qr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Ta(e,t,n){for(const s in t)!Se(t[s])&&!wa(s,n)&&(e[s]=t[s])}function td({transformTemplate:e},t){return f.useMemo(()=>{const n=qr();return Xr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function nd(e,t){const n=e.style||{},s={};return Ta(s,n,e),Object.assign(s,td(e,t)),s}function sd(e,t){const n={},s=nd(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 rd={offset:"stroke-dashoffset",array:"stroke-dasharray"},id={offset:"strokeDashoffset",array:"strokeDasharray"};function od(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?rd:id;e[o.offset]=W.transform(-s);const i=W.transform(t),a=W.transform(n);e[o.array]=`${i} ${a}`}function Sa(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,u,d){if(Xr(e,a,u),l){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&&od(h,r,o,i,!1)}const ja=()=>({...qr(),attrs:{}}),Ca=e=>typeof e=="string"&&e.toLowerCase()==="svg";function ad(e,t,n,s){const r=f.useMemo(()=>{const o=ja();return Sa(o,t,Ca(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Ta(o,e.style,e),r.style={...o,...r.style}}return r}const ld=["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 Wr(e){return typeof e!="string"||e.includes("-")?!1:!!(ld.indexOf(e)>-1||/[A-Z]/u.test(e))}function cd(e,t,n,{latestValues:s},r,o=!1){const a=(Wr(e)?ad:sd)(t,s,r,e),l=Gu(t,typeof e=="string",o),u=e!==f.Fragment?{...l,...a,ref:n}:{},{children:d}=t,h=f.useMemo(()=>Se(d)?d.get():d,[d]);return f.createElement(e,{...u,children:h})}function Ei(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Kr(e,t,n,s){if(typeof t=="function"){const[r,o]=Ei(s);t=t(n!==void 0?n:e.custom,r,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,o]=Ei(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function cs(e){return Se(e)?e.get():e}function ud({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:dd(n,s,r,e),renderState:t()}}function dd(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=cs(o[m]);let{initial:i,animate:a}=e;const l=js(e),u=va(e);t&&u&&!l&&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"&&!Ss(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p<m.length;p++){const v=Kr(e,m[p]);if(v){const{transitionEnd:x,transition:T,...y}=v;for(const w in y){let k=y[w];if(Array.isArray(k)){const O=d?k.length-1:0;k=k[O]}k!==null&&(r[w]=k)}for(const w in x)r[w]=x[w]}}}return r}const Pa=e=>(t,n)=>{const s=f.useContext(Ts),r=f.useContext(ws),o=()=>ud(e,t,s,r);return n?o():yr(o)};function Gr(e,t,n){const{style:s}=e,r={};for(const o in s)(Se(s[o])||t.style&&Se(t.style[o])||wa(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const hd=Pa({scrapeMotionValuesFromProps:Gr,createRenderState:qr});function Aa(e,t,n){const s=Gr(e,t,n);for(const r in e)if(Se(e[r])||Se(t[r])){const o=un.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const fd=Pa({scrapeMotionValuesFromProps:Aa,createRenderState:ja}),md=Symbol.for("motionComponentSymbol");function Qt(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function pd(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):Qt(n)&&(n.current=s))},[t])}const Yr=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),gd="framerAppearId",ka="data-"+Yr(gd),Ma=f.createContext({});function yd(e,t,n,s,r){const{visualElement:o}=f.useContext(Ts),i=f.useContext(zr),a=f.useContext(ws),l=f.useContext(Br).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:l}));const d=u.current,h=f.useContext(Ma);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&xd(u.current,n,r,h);const m=f.useRef(!1);f.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[ka],v=f.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return Ao(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),v.current&&d.animationState&&d.animationState.animateChanges())}),f.useEffect(()=>{d&&(!v.current&&d.animationState&&d.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),v.current=!1),d.enteringChildren=void 0)}),d}function xd(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:l,layoutRoot:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Ea(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Qt(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:l,layoutRoot:u})}function Ea(e){if(e)return e.options.allowProjection!==!1?e.projection:Ea(e.parent)}function us(e,{forwardMotionProps:t=!1}={},n,s){n&&ir(n);const r=Wr(e)?fd:hd;function o(a,l){let u;const d={...f.useContext(Br),...a,layoutId:bd(a)},{isStatic:h}=d,m=Hu(a),p=r(a,h);if(!h&&xr){vd(d,n);const v=wd(d);u=v.MeasureLayout,m.visualElement=yd(e,p,d,s,v.ProjectionNode)}return c.jsxs(Ts.Provider,{value:m,children:[u&&m.visualElement?c.jsx(u,{visualElement:m.visualElement,...d}):null,cd(e,a,pd(p,m.visualElement,l),p,h,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=f.forwardRef(o);return i[md]=e,i}function bd({layoutId:e}){const t=f.useContext(gr).id;return t&&e!==void 0?t+"-"+e:e}function vd(e,t){const n=f.useContext(zr).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?ln(!1,s,"lazy-strict-mode"):ht(!1,s,"lazy-strict-mode")}}function wd(e){const{drag:t,layout:n}=an;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Td(e,t){if(typeof Proxy>"u")return us;const n=new Map,s=(o,i)=>us(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Sr(!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,us(i,void 0,e,t)),n.get(i))})}function Na({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function Sd({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function jd(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 Is(e){return e===void 0||e===1}function or({scale:e,scaleX:t,scaleY:n}){return!Is(e)||!Is(t)||!Is(n)}function It(e){return or(e)||Da(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Da(e){return Ni(e.x)||Ni(e.y)}function Ni(e){return e&&e!=="0%"}function bs(e,t,n){const s=e-n,r=t*s;return n+r}function Di(e,t,n,s,r){return r!==void 0&&(e=bs(e,r,s)),bs(e,n,s)+t}function ar(e,t=0,n=1,s,r){e.min=Di(e.min,t,n,s,r),e.max=Di(e.max,t,n,s,r)}function Ra(e,{x:t,y:n}){ar(e.x,t.translate,t.scale,t.originPoint),ar(e.y,n.translate,n.scale,n.originPoint)}const Ri=.999999999999,Vi=1.0000000000001;function Cd(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:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&tn(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,Ra(e,i)),s&&It(o.latestValues)&&tn(e,o.latestValues))}t.x<Vi&&t.x>Ri&&(t.x=1),t.y<Vi&&t.y>Ri&&(t.y=1)}function en(e,t){e.min=e.min+t,e.max=e.max+t}function Ii(e,t,n,s,r=.5){const o=fe(e.min,e.max,r);ar(e,t,n,o,s)}function tn(e,t){Ii(e.x,t.x,t.scaleX,t.scale,t.originX),Ii(e.y,t.y,t.scaleY,t.scale,t.originY)}function Va(e,t){return Na(jd(e.getBoundingClientRect(),t))}function Pd(e,t,n){const s=Va(e,n),{scroll:r}=t;return r&&(en(s.x,r.offset.x),en(s.y,r.offset.y)),s}const Oi=()=>({translate:0,scale:1,origin:0,originPoint:0}),nn=()=>({x:Oi(),y:Oi()}),$i=()=>({min:0,max:0}),ye=()=>({x:$i(),y:$i()}),lr={current:null},Ia={current:!1};function Ad(){if(Ia.current=!0,!!xr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>lr.current=e.matches;e.addEventListener("change",t),t()}else lr.current=!1}const kd=new WeakMap;function Md(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,on(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,on(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Li=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Ed{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Ir,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=Ne.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,de.render(this.render,!1,!0))};const{latestValues:l,renderState:u}=i;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},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=js(n),this.isVariantNode=va(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];l[m]!==void 0&&Se(p)&&p.set(l[m])}}mount(t){this.current=t,kd.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)),Ia.current||Ad(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:lr.current,process.env.NODE_ENV!=="production"&&Sr(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(),jt(this.notifyUpdate),jt(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=dn.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&de.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 an){const n=an[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):ye()}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<Li.length;s++){const r=Li[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=Md(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=on(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"&&(ko(s)||Eo(s))?s=parseFloat(s):!$u(s)&&Ct.test(n)&&(s=da(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=Kr(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 Tr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Lr.render(this.render)}}class Oa extends Ed{constructor(){super(...arguments),this.KeyframeResolver=Cu}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 $a(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 Nd(e){return window.getComputedStyle(e)}class Dd extends Oa{constructor(){super(...arguments),this.type="html",this.renderInstance=$a}readValueFromInstance(t,n){if(dn.has(n))return this.projection?.isProjecting?Zs(n):_c(t,n);{const s=Nd(t),r=(Pr(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Va(t,n)}build(t,n,s){Xr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Gr(t,n,s)}}const La=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 Rd(e,t,n,s){$a(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(La.has(r)?r:Yr(r),t.attrs[r])}class Vd extends Oa{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ye}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(dn.has(n)){const s=ua(n);return s&&s.default||0}return n=La.has(n)?n:Yr(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return Aa(t,n,s)}build(t,n,s){Sa(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){Rd(t,n,s,r)}mount(t){this.isSVGTag=Ca(t.tagName),super.mount(t)}}const Fa=(e,t)=>Wr(e)?new Vd(t):new Dd(t,{allowProjection:e!==f.Fragment});function rn(e,t,n){const s=e.getProps();return Kr(s,t,n!==void 0?n:s.custom,e)}const cr=e=>Array.isArray(e);function Id(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,on(n))}function Od(e){return cr(e)?e[e.length-1]||0:e}function $d(e,t){const n=rn(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Od(o[i]);Id(e,i,a)}}function Ld(e){return!!(Se(e)&&e.add)}function ur(e,t){const n=e.getValue("willChange");if(Ld(n))return n.add(t);if(!n&&ft.WillChange){const s=new ft.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Ba(e){return e.props[ka]}const Fd=e=>e!==null;function Bd(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Fd),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const zd={type:"spring",stiffness:500,damping:25,restSpeed:10},Ud=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),_d={type:"keyframes",duration:.8},Xd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},qd=(e,{keyframes:t})=>t.length>2?_d:dn.has(e)?e.startsWith("scale")?Ud(t[1]):zd:Xd;function Wd({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:l,elapsed:u,...d}){return!!Object.keys(d).length}const Hr=(e,t,n,s={},r,o)=>i=>{const a=Or(s,e)||{},l=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-Ye(l);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};Wd(a)||Object.assign(d,qd(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)&&(sr(d),d.delay===0&&(h=!0)),(ft.instantAnimations||ft.skipAnimations)&&(h=!0,sr(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const m=Bd(d.keyframes,a);if(m!==void 0){de.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new Vr(d):new hu(d)};function Kd({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function za(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const l=[],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&&Kd(u,d))continue;const p={delay:n,...Or(o||{},d)},v=h.get();if(v!==void 0&&!h.isAnimating&&!Array.isArray(m)&&m===v&&!p.velocity)continue;let x=!1;if(window.MotionHandoffAnimation){const y=Ba(e);if(y){const w=window.MotionHandoffAnimation(y,d,de);w!==null&&(p.startTime=w,x=!0)}}ur(e,d),h.start(Hr(d,h,m,e.shouldReduceMotion&&aa.has(d)?{type:!1}:p,e,x));const T=h.animation;T&&l.push(T)}return i&&Promise.all(l).then(()=>{de.update(()=>{i&&$d(e,i)})}),l}function Ua(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 dr(e,t,n={}){const s=rn(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(za(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=r;return Gd(e,t,l,u,d,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[l,u]=a==="beforeChildren"?[o,i]:[i,o];return l().then(()=>u())}else return Promise.all([o(),i(n.delay)])}function Gd(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const l of e.variantChildren)l.notify("AnimationStart",t),a.push(dr(l,t,{...i,delay:n+(typeof s=="function"?0:s)+Ua(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function Yd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>dr(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=dr(e,t,n);else{const r=typeof t=="function"?rn(e,t,n.custom):t;s=Promise.all(za(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 Hd=_r.length;function Xa(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Xa(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<Hd;n++){const s=_r[n],r=e.props[s];(Fn(r)||r===!1)&&(t[s]=r)}return t}const Jd=[...Ur].reverse(),Zd=Ur.length;function Qd(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Yd(e,n,s)))}function eh(e){let t=Qd(e),n=Fi(),s=!0;const r=l=>(u,d)=>{const h=rn(e,d,l==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:m,transitionEnd:p,...v}=h;u={...u,...v,...p}}return u};function o(l){t=l(e)}function i(l){const{props:u}=e,d=Xa(e.parent)||{},h=[],m=new Set;let p={},v=1/0;for(let T=0;T<Zd;T++){const y=Jd[T],w=n[y],k=u[y]!==void 0?u[y]:d[y],O=Fn(k),E=y===l?w.isActive:null;E===!1&&(v=T);let B=k===d[y]&&k!==u[y]&&O;if(B&&s&&e.manuallyAnimateOnMount&&(B=!1),w.protectedKeys={...p},!w.isActive&&E===null||!k&&!w.prevProp||Ss(k)||typeof k=="boolean")continue;const _=th(w.prevProp,k);let M=_||y===l&&w.isActive&&!B&&O||T>v&&O,R=!1;const j=Array.isArray(k)?k:[k];let V=j.reduce(r(y),{});E===!1&&(V={});const{prevResolvedValues:z={}}=w,N={...z,...V},K=Q=>{M=!0,m.has(Q)&&(R=!0,m.delete(Q)),w.needsAnimating[Q]=!0;const ne=e.getValue(Q);ne&&(ne.liveStyle=!1)};for(const Q in N){const ne=V[Q],Z=z[Q];if(p.hasOwnProperty(Q))continue;let Te=!1;cr(ne)&&cr(Z)?Te=!_a(ne,Z):Te=ne!==Z,Te?ne!=null?K(Q):m.add(Q):ne!==void 0&&m.has(Q)?K(Q):w.protectedKeys[Q]=!0}w.prevProp=k,w.prevResolvedValues=V,w.isActive&&(p={...p,...V}),s&&e.blockInitialAnimation&&(M=!1);const Y=B&&_;M&&(!Y||R)&&h.push(...j.map(Q=>{const ne={type:y};if(typeof Q=="string"&&s&&!Y&&e.manuallyAnimateOnMount&&e.parent){const{parent:Z}=e,Te=rn(Z,Q);if(Z.enteringChildren&&Te){const{delayChildren:He}=Te.transition||{};ne.delay=Ua(Z.enteringChildren,e,He)}}return{animation:Q,options:ne}}))}if(m.size){const T={};if(typeof u.initial!="boolean"){const y=rn(e,Array.isArray(u.initial)?u.initial[0]:u.initial);y&&y.transition&&(T.transition=y.transition)}m.forEach(y=>{const w=e.getBaseTarget(y),k=e.getValue(y);k&&(k.liveStyle=!0),T[y]=w??null}),h.push({animation:T})}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(l,u){if(n[l].isActive===u)return Promise.resolve();e.variantChildren?.forEach(h=>h.animationState?.setActive(l,u)),n[l].isActive=u;const d=i(l);for(const h in n)n[h].protectedKeys={};return d}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Fi()}}}function th(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!_a(t,e):!1}function Rt(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Fi(){return{animate:Rt(!0),whileInView:Rt(),whileHover:Rt(),whileTap:Rt(),whileDrag:Rt(),whileFocus:Rt(),exit:Rt()}}class Pt{constructor(t){this.isMounted=!1,this.node=t}update(){}}class nh extends Pt{constructor(t){super(t),t.animationState||(t.animationState=eh(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Ss(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 sh=0;class rh extends Pt{constructor(){super(...arguments),this.id=sh++}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 qa={animation:{Feature:nh},exit:{Feature:rh}};function zn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function qn(e){return{point:{x:e.pageX,y:e.pageY}}}const ih=e=>t=>Fr(t)&&e(t,qn(t));function Nn(e,t,n,s){return zn(e,t,ih(n),s)}const Wa=1e-4,oh=1-Wa,ah=1+Wa,Ka=.01,lh=0-Ka,ch=0+Ka;function Ae(e){return e.max-e.min}function uh(e,t,n){return Math.abs(e-t)<=n}function Bi(e,t,n,s=.5){e.origin=s,e.originPoint=fe(t.min,t.max,e.origin),e.scale=Ae(n)/Ae(t),e.translate=fe(n.min,n.max,e.origin)-e.originPoint,(e.scale>=oh&&e.scale<=ah||isNaN(e.scale))&&(e.scale=1),(e.translate>=lh&&e.translate<=ch||isNaN(e.translate))&&(e.translate=0)}function Dn(e,t,n,s){Bi(e.x,t.x,n.x,s?s.originX:void 0),Bi(e.y,t.y,n.y,s?s.originY:void 0)}function zi(e,t,n){e.min=n.min+t.min,e.max=e.min+Ae(t)}function dh(e,t,n){zi(e.x,t.x,n.x),zi(e.y,t.y,n.y)}function Ui(e,t,n){e.min=t.min-n.min,e.max=e.min+Ae(t)}function Rn(e,t,n){Ui(e.x,t.x,n.x),Ui(e.y,t.y,n.y)}function Le(e){return[e("x"),e("y")]}const Ga=({current:e})=>e?e.ownerDocument.defaultView:null,_i=(e,t)=>Math.abs(e-t);function hh(e,t){const n=_i(e.x,t.x),s=_i(e.y,t.y);return Math.sqrt(n**2+s**2)}class Ya{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=$s(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,v=hh(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!v)return;const{point:x}=m,{timestamp:T}=we;this.history.push({...x,timestamp:T});const{onStart:y,onMove:w}=this.handlers;p||(y&&y(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),w&&w(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=Os(p,this.transformPagePoint),de.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:v,onSessionEnd:x,resumeAnimation:T}=this.handlers;if(this.dragSnapToOrigin&&T&&T(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=$s(m.type==="pointercancel"?this.lastMoveEventInfo:Os(p,this.transformPagePoint),this.history);this.startEvent&&v&&v(m,y),x&&x(m,y)},!Fr(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=qn(t),l=Os(a,this.transformPagePoint),{point:u}=l,{timestamp:d}=we;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=n;h&&h(t,$s(l,this.history)),this.removeListeners=Un(Nn(this.contextWindow,"pointermove",this.handlePointerMove),Nn(this.contextWindow,"pointerup",this.handlePointerUp),Nn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),jt(this.updatePoint)}}function Os(e,t){return t?{point:t(e.point)}:e}function Xi(e,t){return{x:e.x-t.x,y:e.y-t.y}}function $s({point:e},t){return{point:e,delta:Xi(e,Ha(t)),offset:Xi(e,fh(t)),velocity:mh(t,.1)}}function fh(e){return e[0]}function Ha(e){return e[e.length-1]}function mh(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Ha(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 ph(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 qi(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 gh(e,{top:t,left:n,bottom:s,right:r}){return{x:qi(e.x,n,r),y:qi(e.y,t,s)}}function Wi(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 yh(e,t){return{x:Wi(e.x,t.x),y:Wi(e.y,t.y)}}function xh(e,t){let n=.5;const s=Ae(e),r=Ae(t);return r>s?n=On(t.min,t.max-s,e.min):s>r&&(n=On(e.min,e.max-r,t.min)),dt(0,1,n)}function bh(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 hr=.35;function vh(e=hr){return e===!1?e=0:e===!0&&(e=hr),{x:Ki(e,"left","right"),y:Ki(e,"top","bottom")}}function Ki(e,t,n){return{min:Gi(e,t),max:Gi(e,n)}}function Gi(e,t){return typeof e=="number"?e:e[t]||0}const wh=new WeakMap;class Th{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=ye(),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(qn(h).point)},i=(h,m)=>{const{drag:p,dragPropagation:v,onDragStart:x}=this.getProps();if(p&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Mu(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 w=this.getAxisMotionValue(y).get()||0;if(st.test(w)){const{projection:k}=this.visualElement;if(k&&k.layout){const O=k.layout.layoutBox[y];O&&(w=Ae(O)*(parseFloat(w)/100))}}this.originPoint[y]=w}),x&&de.postRender(()=>x(h,m)),ur(this.visualElement,"transform");const{animationState:T}=this.visualElement;T&&T.setActive("whileDrag",!0)},a=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:v,onDirectionLock:x,onDrag:T}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=m;if(v&&this.currentDirection===null){this.currentDirection=Sh(y),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",m.point,y),this.updateAxis("y",m.point,y),this.visualElement.render(),T&&T(h,m)},l=(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 Ya(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Ga(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&&de.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||!is(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=ph(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&&Qt(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=gh(s.layoutBox,t):this.constraints=!1,this.elastic=vh(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Le(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=bh(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Qt(t))return!1;const s=t.current;ht(s!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const o=Pd(s,r.root,this.visualElement.getTransformPagePoint());let i=yh(r.layout.layoutBox,o);if(n){const a=n(Sd(i));this.hasMutatedConstraints=!!a,a&&(i=Na(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},u=Le(d=>{if(!is(d,n,this.currentDirection))return;let h=l&&l[d]||{};i&&(h={min:0,max:0});const m=r?200:1e6,p=r?40:1e7,v={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(d,v)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return ur(this.visualElement,t),s.start(Hr(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(!is(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(!Qt(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 l=a.get();r[i]=xh({min:l,max:l},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(!is(i,t,null))return;const a=this.getAxisMotionValue(i),{min:l,max:u}=this.constraints[i];a.set(fe(l,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;wh.set(this.visualElement,this);const t=this.visualElement.current,n=Nn(t,"pointerdown",l=>{const{drag:u,dragListener:d=!0}=this.getProps();u&&d&&this.start(l)}),s=()=>{const{dragConstraints:l}=this.getProps();Qt(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,o=r.addEventListener("measure",s);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),de.read(s);const i=zn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:l,hasLayoutChanged:u})=>{this.isDragging&&u&&(Le(d=>{const h=this.getAxisMotionValue(d);h&&(this.originPoint[d]+=l[d].translate,h.set(h.get()+l[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=hr,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function is(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Sh(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class jh extends Pt{constructor(t){super(t),this.removeGroupControls=Be,this.removeListeners=Be,this.controls=new Th(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 Yi=e=>(t,n)=>{e&&de.postRender(()=>e(t,n))};class Ch extends Pt{constructor(){super(...arguments),this.removePointerDownListener=Be}onPointerDown(t){this.session=new Ya(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ga(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Yi(t),onStart:Yi(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&de.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=Nn(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 ds={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Hi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const An={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(W.test(e))e=parseFloat(e);else return e;const n=Hi(e,t.target.x),s=Hi(e,t.target.y);return`${n}% ${s}%`}},Ph={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=Ct.parse(e);if(r.length>5)return s;const o=Ct.createTransformer(e),i=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;r[0+i]/=a,r[1+i]/=l;const u=fe(a,l,.5);return typeof r[2+i]=="number"&&(r[2+i]/=u),typeof r[3+i]=="number"&&(r[3+i]/=u),o(r)}};let Ls=!1;class Ah extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;Ju(kh),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),Ls&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),ds.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Ls=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||de.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Lr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Ls=!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 Ja(e){const[t,n]=xa(),s=f.useContext(gr);return c.jsx(Ah,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(Ma),isPresent:t,safeToRemove:n})}const kh={borderRadius:{...An,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:An,borderTopRightRadius:An,borderBottomLeftRadius:An,borderBottomRightRadius:An,boxShadow:Ph};function Mh(e,t,n){const s=Se(e)?e:on(e);return s.start(Hr("",s,t,n)),s.animation}const Eh=(e,t)=>e.depth-t.depth;class Nh{constructor(){this.children=[],this.isDirty=!1}add(t){br(this.children,t),this.isDirty=!0}remove(t){vr(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Eh),this.isDirty=!1,this.children.forEach(t)}}function Dh(e,t){const n=Ne.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(jt(s),e(o-t))};return de.setup(s,!0),()=>jt(s)}const Za=["TopLeft","TopRight","BottomLeft","BottomRight"],Rh=Za.length,Ji=e=>typeof e=="string"?parseFloat(e):e,Zi=e=>typeof e=="number"||W.test(e);function Vh(e,t,n,s,r,o){r?(e.opacity=fe(0,n.opacity??1,Ih(s)),e.opacityExit=fe(t.opacity??1,0,Oh(s))):o&&(e.opacity=fe(t.opacity??1,n.opacity??1,s));for(let i=0;i<Rh;i++){const a=`border${Za[i]}Radius`;let l=Qi(t,a),u=Qi(n,a);if(l===void 0&&u===void 0)continue;l||(l=0),u||(u=0),l===0||u===0||Zi(l)===Zi(u)?(e[a]=Math.max(fe(Ji(l),Ji(u),s),0),(st.test(u)||st.test(l))&&(e[a]+="%")):e[a]=u}(t.rotate||n.rotate)&&(e.rotate=fe(t.rotate||0,n.rotate||0,s))}function Qi(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Ih=Qa(0,.5,Lo),Oh=Qa(.5,.95,Be);function Qa(e,t,n){return s=>s<e?0:s>t?1:n(On(e,t,s))}function eo(e,t){e.min=t.min,e.max=t.max}function $e(e,t){eo(e.x,t.x),eo(e.y,t.y)}function to(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function no(e,t,n,s,r){return e-=t,e=bs(e,1/n,s),r!==void 0&&(e=bs(e,1/r,s)),e}function $h(e,t=0,n=1,s=.5,r,o=e,i=e){if(st.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=no(e.min,t,n,a,r),e.max=no(e.max,t,n,a,r)}function so(e,t,[n,s,r],o,i){$h(e,t[n],t[s],t[r],t.scale,o,i)}const Lh=["x","scaleX","originX"],Fh=["y","scaleY","originY"];function ro(e,t,n,s){so(e.x,t,Lh,n?n.x:void 0,s?s.x:void 0),so(e.y,t,Fh,n?n.y:void 0,s?s.y:void 0)}function io(e){return e.translate===0&&e.scale===1}function el(e){return io(e.x)&&io(e.y)}function oo(e,t){return e.min===t.min&&e.max===t.max}function Bh(e,t){return oo(e.x,t.x)&&oo(e.y,t.y)}function ao(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function tl(e,t){return ao(e.x,t.x)&&ao(e.y,t.y)}function lo(e){return Ae(e.x)/Ae(e.y)}function co(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class zh{constructor(){this.members=[]}add(t){br(this.members,t),t.scheduleRender()}remove(t){if(vr(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 Uh(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:v}=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) `),v&&(s+=`skewY(${v}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(s+=`scale(${a}, ${l})`),s||"none"}const Fs=["","X","Y","Z"],_h=1e3;let Xh=0;function Bs(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function nl(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Ba(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",de,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&nl(s)}function sl({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=Xh++,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(Kh),this.nodes.forEach(Jh),this.nodes.forEach(Zh),this.nodes.forEach(Gh)},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 l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new Nh)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Tr),this.eventHandlers.get(i).add(a)}notifyListeners(i,...a){const l=this.eventHandlers.get(i);l&&l.notify(...a)}hasListeners(i){return this.eventHandlers.has(i)}mount(i){if(this.instance)return;this.isSVG=ya(i)&&!Iu(i),this.instance=i;const{layoutId:a,layout:l,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&&(l||a)&&(this.isLayoutDirty=!0),e){let d,h=0;const m=()=>this.root.updateBlockedByResize=!1;de.read(()=>{h=window.innerWidth}),e(i,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,d&&d(),d=Dh(m,250),ds.hasAnimatedSinceResize&&(ds.hasAnimatedSinceResize=!1,this.nodes.forEach(fo)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||u.getDefaultTransition()||sf,{onLayoutAnimationStart:x,onLayoutAnimationComplete:T}=u.getProps(),y=!this.targetLayout||!tl(this.targetLayout,p),w=!h&&m;if(this.options.layoutRoot||this.resumeFrom||w||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...Or(v,"layout"),onPlay:x,onComplete:T};(u.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(d,w)}else h||fo(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(),jt(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(Qh),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&&nl(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:l}=this.options;if(a===void 0&&!l)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(uo);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(ho);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Hh),this.nodes.forEach(qh),this.nodes.forEach(Wh)):this.nodes.forEach(ho),this.clearAllSnapshots();const a=Ne.now();we.delta=dt(0,1e3/60,a-we.timestamp),we.timestamp=a,we.isProcessing=!0,ks.update.process(we),ks.preRender.process(we),ks.render.process(we),we.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Lr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Yh),this.sharedNodes.forEach(ef)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,de.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){de.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ae(this.snapshot.measuredBox.x)&&!Ae(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 l=0;l<this.path.length;l++)this.path[l].updateScroll();const i=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ye(),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 l=s(this.instance);this.scroll={animationId:this.root.animationId,phase:i,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!r)return;const i=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!el(this.projectionDelta),l=this.getTransformTemplate(),u=l?l(this.latestValues,""):void 0,d=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||It(this.latestValues)||d)&&(r(this.instance,u),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return i&&(l=this.removeTransform(l)),rf(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ye();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(of))){const{scroll:u}=this.root;u&&(en(a.x,u.offset.x),en(a.y,u.offset.y))}return a}removeElementScroll(i){const a=ye();if($e(a,i),this.scroll?.wasRoot)return a;for(let l=0;l<this.path.length;l++){const u=this.path[l],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&$e(a,i),en(a.x,d.offset.x),en(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const l=ye();$e(l,i);for(let u=0;u<this.path.length;u++){const d=this.path[u];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&tn(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),It(d.latestValues)&&tn(l,d.latestValues)}return It(this.latestValues)&&tn(l,this.latestValues),l}removeTransform(i){const a=ye();$e(a,i);for(let l=0;l<this.path.length;l++){const u=this.path[l];if(!u.instance||!It(u.latestValues))continue;or(u.latestValues)&&u.updateSnapshot();const d=ye(),h=u.measurePageBox();$e(d,h),ro(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,d)}return It(this.latestValues)&&ro(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 l=!!this.resumingFrom||this!==a;if(!(i||l&&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=ye(),this.relativeTargetOrigin=ye(),Rn(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=ye(),this.targetWithTransforms=ye()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),dh(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):$e(this.target,this.layout.layoutBox),Ra(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=ye(),this.relativeTargetOrigin=ye(),Rn(this.relativeTargetOrigin,this.target,m.target),$e(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||or(this.parent.latestValues)||Da(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 l=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===we.timestamp&&(l=!1),l)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;Cd(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=ye());const{target:p}=i;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(to(this.prevProjectionDelta.x,this.projectionDelta.x),to(this.prevProjectionDelta.y,this.projectionDelta.y)),Dn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==m||!co(this.projectionDelta.x,this.prevProjectionDelta.x)||!co(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=nn(),this.projectionDelta=nn(),this.projectionDeltaWithTransform=nn()}setAnimationOrigin(i,a=!1){const l=this.snapshot,u=l?l.latestValues:{},d={...this.latestValues},h=nn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=ye(),p=l?l.source:void 0,v=this.layout?this.layout.source:void 0,x=p!==v,T=this.getStack(),y=!T||T.members.length<=1,w=!!(x&&!y&&this.options.crossfade===!0&&!this.path.some(nf));this.animationProgress=0;let k;this.mixTargetDelta=O=>{const E=O/1e3;mo(h.x,i.x,E),mo(h.y,i.y,E),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Rn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),tf(this.relativeTarget,this.relativeTargetOrigin,m,E),k&&Bh(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ye()),$e(k,this.relativeTarget)),x&&(this.animationValues=d,Vh(d,u,this.latestValues,E,w,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=E},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(jt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=de.update(()=>{ds.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=on(0)),this.currentAnimation=Mh(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(_h),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:l,layout:u,latestValues:d}=i;if(!(!a||!l||!u)){if(this!==i&&this.layout&&u&&rl(this.options.animationType,this.layout.layoutBox,u.layoutBox)){l=this.target||ye();const h=Ae(this.layout.layoutBox.x);l.x.min=i.target.x.min,l.x.max=l.x.min+h;const m=Ae(this.layout.layoutBox.y);l.y.min=i.target.y.min,l.y.max=l.y.min+m}$e(a,l),tn(a,d),Dn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new zh),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:l}={}){const u=this.getStack();u&&u.promote(this,l),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:l}=i;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const u={};l.z&&Bs("z",i,u,this.animationValues);for(let d=0;d<Fs.length;d++)Bs(`rotate${Fs[d]}`,i,u,this.animationValues),Bs(`skew${Fs[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 l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,i.visibility="",i.opacity="",i.pointerEvents=cs(a?.pointerEvents)||"",i.transform=l?l(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=cs(a?.pointerEvents)||""),this.hasProjected&&!It(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=Uh(this.projectionDeltaWithTransform,this.treeScale,d);l&&(h=l(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 v in Bn){if(d[v]===void 0)continue;const{correct:x,applyTo:T,isCSSVariable:y}=Bn[v],w=h==="none"?d[v]:x(d[v],u);if(T){const k=T.length;for(let O=0;O<k;O++)i[T[O]]=w}else y?this.options.visualElement.renderState.vars[v]=w:i[v]=w}this.options.layoutId&&(i.pointerEvents=u===this?cs(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(uo),this.root.sharedNodes.clear()}}}function qh(e){e.updateLayout()}function Wh(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=Ae(h);h.min=n[d].min,h.max=h.min+m}):rl(r,t.layoutBox,n)&&Le(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=Ae(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=nn();Dn(i,n,t.layoutBox);const a=nn();o?Dn(a,e.applyTransform(s,!0),t.measuredBox):Dn(a,n,t.layoutBox);const l=!el(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=ye();Rn(p,t.layoutBox,h.layoutBox);const v=ye();Rn(v,n,m.layoutBox),tl(p,v)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=v,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:l,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function Kh(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 Gh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Yh(e){e.clearSnapshot()}function uo(e){e.clearMeasurements()}function ho(e){e.isLayoutDirty=!1}function Hh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function fo(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Jh(e){e.resolveTargetDelta()}function Zh(e){e.calcProjection()}function Qh(e){e.resetSkewAndRotation()}function ef(e){e.removeLeadSnapshot()}function mo(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 po(e,t,n,s){e.min=fe(t.min,n.min,s),e.max=fe(t.max,n.max,s)}function tf(e,t,n,s){po(e.x,t.x,n.x,s),po(e.y,t.y,n.y,s)}function nf(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const sf={duration:.45,ease:[.4,0,.1,1]},go=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),yo=go("applewebkit/")&&!go("chrome/")?Math.round:Be;function xo(e){e.min=yo(e.min),e.max=yo(e.max)}function rf(e){xo(e.x),xo(e.y)}function rl(e,t,n){return e==="position"||e==="preserve-aspect"&&!uh(lo(t),lo(n),.2)}function of(e){return e!==e.root&&e.scroll?.wasRoot}const af=sl({attachResizeListener:(e,t)=>zn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),zs={current:void 0},il=sl({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!zs.current){const e=new af({});e.mount(window),e.setOptions({layoutScroll:!0}),zs.current=e}return zs.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),lf={pan:{Feature:Ch},drag:{Feature:jh,ProjectionNode:il,MeasureLayout:Ja}};function bo(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&&de.postRender(()=>o(t,qn(t)))}class cf extends Pt{mount(){const{current:t}=this.node;t&&(this.unmount=Eu(t,(n,s)=>(bo(this.node,s,"Start"),r=>bo(this.node,r,"End"))))}unmount(){}}class uf extends Pt{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=Un(zn(this.node.current,"focus",()=>this.onFocus()),zn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function vo(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&&de.postRender(()=>o(t,qn(t)))}class df extends Pt{mount(){const{current:t}=this.node;t&&(this.unmount=Vu(t,(n,s)=>(vo(this.node,s,"Start"),(r,{success:o})=>vo(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const fr=new WeakMap,Us=new WeakMap,hf=e=>{const t=fr.get(e.target);t&&t(e)},ff=e=>{e.forEach(hf)};function mf({root:e,...t}){const n=e||document;Us.has(n)||Us.set(n,{});const s=Us.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(ff,{root:e,...t})),s[r]}function pf(e,t,n){const s=mf(t);return fr.set(e,n),s.observe(e),()=>{fr.delete(e),s.unobserve(e)}}const gf={some:0,all:1};class yf extends Pt{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:gf[r]},a=l=>{const{isIntersecting:u}=l;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(l)};return pf(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(xf(t,n))&&this.startObserver()}unmount(){}}function xf({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const ol={inView:{Feature:yf},tap:{Feature:df},focus:{Feature:uf},hover:{Feature:cf}},bf={layout:{ProjectionNode:il,MeasureLayout:Ja}},vf={...qa,...ol,...lf,...bf},wf=Td(vf,Fa),Tf={renderer:Fa,...qa,...ol};function Jr(e,t){return us(e,t)}const Sf=Jr("button"),os=Jr("div"),jf=Jr("p"),nt=Symbol.for("@arcteninc/core:originalName");function Cf(e,t){return e[nt]=t,e}function Pf(e,t,n,s){if(typeof e!="function")return null;const r=e[nt];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[nt]=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[nt]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(l=>!n.has(l.name)),i)return e[nt]=i.name,{fn:e,meta:i};return null}function al(e,t){let n,s;if(!t)throw new Error(`❌ toolMetadata is required!
9
+ `),()=>{T.contains(x)&&T.removeChild(x)}},[t]),c.jsx(Bu,{isPresent:t,childRef:o,sizeRef:i,children:Ye.cloneElement(e,{ref:l})})}const Uu=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const u=pr(_u),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 v of u.values())if(!v)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,v)=>u.set(v,!1))},[n]),Ye.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(e=c.jsx(zu,{isPresent:n,anchorX:a,root:l,children:e})),c.jsx(vs.Provider,{value:m,children:e})};function _u(){return new Map}function ga(e=!0){const t=f.useContext(vs);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 ss=e=>e.key||"";function Ci(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const Xu=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:l})=>{const[u,d]=ga(i),h=f.useMemo(()=>Ci(e),[e]),m=i&&!u?[]:h.map(ss),p=f.useRef(!0),v=f.useRef(h),x=pr(()=>new Map),[T,y]=f.useState(h),[w,k]=f.useState(h);Co(()=>{p.current=!1,v.current=h;for(let B=0;B<w.length;B++){const _=ss(w[B]);m.includes(_)?x.delete(_):x.get(_)!==!0&&x.set(_,!1)}},[w,m.length,m.join("-")]);const O=[];if(h!==T){let B=[...h];for(let _=0;_<w.length;_++){const M=w[_],R=ss(M);m.includes(R)||(B.splice(_,0,M),O.push(M))}return o==="wait"&&O.length&&(B=O),k(Ci(B)),y(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&w.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:E}=f.useContext(mr);return c.jsx(c.Fragment,{children:w.map(B=>{const _=ss(B),M=i&&!u?!1:h===w||m.includes(_),R=()=>{if(x.has(_))x.set(_,!0);else return;let j=!0;x.forEach(V=>{V||(j=!1)}),j&&(E?.(),k(v.current),i&&d?.(),s&&s())};return c.jsx(Uu,{isPresent:M,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:l,onExitComplete:M?void 0:R,anchorX:a,children:B},_)})})},Fr=f.createContext({strict:!1}),Pi={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"]},on={};for(const e in Pi)on[e]={isEnabled:t=>Pi[e].some(n=>!!t[n])};function sr(e){for(const t in e)on[t]={...on[t],...e[t]}}function qu({children:e,features:t,strict:n=!1}){const[,s]=f.useState(!Ds(t)),r=f.useRef(void 0);if(!Ds(t)){const{renderer:o,...i}=t;r.current=o,sr(i)}return f.useEffect(()=>{Ds(t)&&t().then(({renderer:o,...i})=>{sr(i),r.current=o,s(!0)})},[]),c.jsx(Fr.Provider,{value:{renderer:r.current,strict:n},children:e})}function Ds(e){return typeof e=="function"}const Wu=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function ys(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Wu.has(e)}let ya=e=>!ys(e);function Ku(e){typeof e=="function"&&(ya=t=>t.startsWith("on")?!ys(t):e(t))}try{Ku(require("@emotion/is-prop-valid").default)}catch{}function Gu(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(ya(r)||n===!0&&ys(r)||!t&&!ys(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const ws=f.createContext({});function Ts(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function Fn(e){return typeof e=="string"||Array.isArray(e)}const Br=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],zr=["initial",...Br];function Ss(e){return Ts(e.animate)||zr.some(t=>Fn(e[t]))}function xa(e){return!!(Ss(e)||e.variants)}function Yu(e,t){if(Ss(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Fn(n)?n:void 0,animate:Fn(s)?s:void 0}}return e.inherit!==!1?t:{}}function Hu(e){const{initial:t,animate:n}=Yu(e,f.useContext(ws));return f.useMemo(()=>({initial:t,animate:n}),[Ai(t),Ai(n)])}function Ai(e){return Array.isArray(e)?e.join(" "):e}const Bn={};function Ju(e){for(const t in e)Bn[t]=e[t],jr(t)&&(Bn[t].isCSSVariable=!0)}function ba(e,{layout:t,layoutId:n}){return un.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Bn[e]||e==="opacity")}const Zu={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Qu=cn.length;function ed(e,t,n){let s="",r=!0;for(let o=0;o<Qu;o++){const i=cn[o],a=e[i];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(i.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const u=ua(a,Ir[i]);if(!l){r=!1;const d=Zu[i]||i;s+=`${d}(${u}) `}n&&(t[i]=u)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function Ur(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const l in t){const u=t[l];if(un.has(l)){i=!0;continue}else if(jr(l)){r[l]=u;continue}else{const d=ua(u,Ir[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=ed(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:l="50%",originY:u="50%",originZ:d=0}=o;s.transformOrigin=`${l} ${u} ${d}`}}const _r=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function va(e,t,n){for(const s in t)!je(t[s])&&!ba(s,n)&&(e[s]=t[s])}function td({transformTemplate:e},t){return f.useMemo(()=>{const n=_r();return Ur(n,t,e),Object.assign({},n.vars,n.style)},[t])}function nd(e,t){const n=e.style||{},s={};return va(s,n,e),Object.assign(s,td(e,t)),s}function sd(e,t){const n={},s=nd(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 rd={offset:"stroke-dashoffset",array:"stroke-dasharray"},id={offset:"strokeDashoffset",array:"strokeDasharray"};function od(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?rd:id;e[o.offset]=W.transform(-s);const i=W.transform(t),a=W.transform(n);e[o.array]=`${i} ${a}`}function wa(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,u,d){if(Ur(e,a,u),l){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&&od(h,r,o,i,!1)}const Ta=()=>({..._r(),attrs:{}}),Sa=e=>typeof e=="string"&&e.toLowerCase()==="svg";function ad(e,t,n,s){const r=f.useMemo(()=>{const o=Ta();return wa(o,t,Sa(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};va(o,e.style,e),r.style={...o,...r.style}}return r}const ld=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Xr(e){return typeof e!="string"||e.includes("-")?!1:!!(ld.indexOf(e)>-1||/[A-Z]/u.test(e))}function cd(e,t,n,{latestValues:s},r,o=!1){const a=(Xr(e)?ad:sd)(t,s,r,e),l=Gu(t,typeof e=="string",o),u=e!==f.Fragment?{...l,...a,ref:n}:{},{children:d}=t,h=f.useMemo(()=>je(d)?d.get():d,[d]);return f.createElement(e,{...u,children:h})}function ki(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function qr(e,t,n,s){if(typeof t=="function"){const[r,o]=ki(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]=ki(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function ls(e){return je(e)?e.get():e}function ud({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:dd(n,s,r,e),renderState:t()}}function dd(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=ls(o[m]);let{initial:i,animate:a}=e;const l=Ss(e),u=xa(e);t&&u&&!l&&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"&&!Ts(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p<m.length;p++){const v=qr(e,m[p]);if(v){const{transitionEnd:x,transition:T,...y}=v;for(const w in y){let k=y[w];if(Array.isArray(k)){const O=d?k.length-1:0;k=k[O]}k!==null&&(r[w]=k)}for(const w in x)r[w]=x[w]}}}return r}const ja=e=>(t,n)=>{const s=f.useContext(ws),r=f.useContext(vs),o=()=>ud(e,t,s,r);return n?o():pr(o)};function Wr(e,t,n){const{style:s}=e,r={};for(const o in s)(je(s[o])||t.style&&je(t.style[o])||ba(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const hd=ja({scrapeMotionValuesFromProps:Wr,createRenderState:_r});function Ca(e,t,n){const s=Wr(e,t,n);for(const r in e)if(je(e[r])||je(t[r])){const o=cn.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const fd=ja({scrapeMotionValuesFromProps:Ca,createRenderState:Ta}),md=Symbol.for("motionComponentSymbol");function Zt(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function pd(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):Zt(n)&&(n.current=s))},[t])}const Kr=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),gd="framerAppearId",Pa="data-"+Kr(gd),Aa=f.createContext({});function yd(e,t,n,s,r){const{visualElement:o}=f.useContext(ws),i=f.useContext(Fr),a=f.useContext(vs),l=f.useContext(Lr).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:l}));const d=u.current,h=f.useContext(Aa);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&xd(u.current,n,r,h);const m=f.useRef(!1);f.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[Pa],v=f.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return Co(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),v.current&&d.animationState&&d.animationState.animateChanges())}),f.useEffect(()=>{d&&(!v.current&&d.animationState&&d.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),v.current=!1),d.enteringChildren=void 0)}),d}function xd(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:l,layoutRoot:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:ka(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Zt(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:l,layoutRoot:u})}function ka(e){if(e)return e.options.allowProjection!==!1?e.projection:ka(e.parent)}function cs(e,{forwardMotionProps:t=!1}={},n,s){n&&sr(n);const r=Xr(e)?fd:hd;function o(a,l){let u;const d={...f.useContext(Lr),...a,layoutId:bd(a)},{isStatic:h}=d,m=Hu(a),p=r(a,h);if(!h&&gr){vd(d,n);const v=wd(d);u=v.MeasureLayout,m.visualElement=yd(e,p,d,s,v.ProjectionNode)}return c.jsxs(ws.Provider,{value:m,children:[u&&m.visualElement?c.jsx(u,{visualElement:m.visualElement,...d}):null,cd(e,a,pd(p,m.visualElement,l),p,h,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=f.forwardRef(o);return i[md]=e,i}function bd({layoutId:e}){const t=f.useContext(mr).id;return t&&e!==void 0?t+"-"+e:e}function vd(e,t){const n=f.useContext(Fr).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?an(!1,s,"lazy-strict-mode"):ht(!1,s,"lazy-strict-mode")}}function wd(e){const{drag:t,layout:n}=on;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Td(e,t){if(typeof Proxy>"u")return cs;const n=new Map,s=(o,i)=>cs(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&wr(!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,cs(i,void 0,e,t)),n.get(i))})}function Ma({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function Sd({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function jd(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),s=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function Rs(e){return e===void 0||e===1}function rr({scale:e,scaleX:t,scaleY:n}){return!Rs(e)||!Rs(t)||!Rs(n)}function Vt(e){return rr(e)||Ea(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Ea(e){return Mi(e.x)||Mi(e.y)}function Mi(e){return e&&e!=="0%"}function xs(e,t,n){const s=e-n,r=t*s;return n+r}function Ei(e,t,n,s,r){return r!==void 0&&(e=xs(e,r,s)),xs(e,n,s)+t}function ir(e,t=0,n=1,s,r){e.min=Ei(e.min,t,n,s,r),e.max=Ei(e.max,t,n,s,r)}function Na(e,{x:t,y:n}){ir(e.x,t.translate,t.scale,t.originPoint),ir(e.y,n.translate,n.scale,n.originPoint)}const Ni=.999999999999,Di=1.0000000000001;function Cd(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:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&en(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,Na(e,i)),s&&Vt(o.latestValues)&&en(e,o.latestValues))}t.x<Di&&t.x>Ni&&(t.x=1),t.y<Di&&t.y>Ni&&(t.y=1)}function Qt(e,t){e.min=e.min+t,e.max=e.max+t}function Ri(e,t,n,s,r=.5){const o=fe(e.min,e.max,r);ir(e,t,n,o,s)}function en(e,t){Ri(e.x,t.x,t.scaleX,t.scale,t.originX),Ri(e.y,t.y,t.scaleY,t.scale,t.originY)}function Da(e,t){return Ma(jd(e.getBoundingClientRect(),t))}function Pd(e,t,n){const s=Da(e,n),{scroll:r}=t;return r&&(Qt(s.x,r.offset.x),Qt(s.y,r.offset.y)),s}const Vi=()=>({translate:0,scale:1,origin:0,originPoint:0}),tn=()=>({x:Vi(),y:Vi()}),Ii=()=>({min:0,max:0}),ge=()=>({x:Ii(),y:Ii()}),or={current:null},Ra={current:!1};function Ad(){if(Ra.current=!0,!!gr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>or.current=e.matches;e.addEventListener("change",t),t()}else or.current=!1}const kd=new WeakMap;function Md(e,t,n){for(const s in t){const r=t[s],o=n[s];if(je(r))e.addValue(s,r);else if(je(o))e.addValue(s,rn(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,rn(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Oi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Ed{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Rr,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=De.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,de.render(this.render,!1,!0))};const{latestValues:l,renderState:u}=i;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},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=Ss(n),this.isVariantNode=xa(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];l[m]!==void 0&&je(p)&&p.set(l[m])}}mount(t){this.current=t,kd.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),Ra.current||Ad(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:or.current,process.env.NODE_ENV!=="production"&&wr(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(),St(this.notifyUpdate),St(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=un.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&de.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 on){const n=on[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<Oi.length;s++){const r=Oi[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=Md(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=rn(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"&&(Po(s)||ko(s))?s=parseFloat(s):!$u(s)&&jt.test(n)&&(s=ca(t,n)),this.setBaseTarget(t,je(s)?s.get():s)),je(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=qr(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&&!je(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 vr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Or.render(this.render)}}class Va extends Ed{constructor(){super(...arguments),this.KeyframeResolver=Cu}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;je(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Ia(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 Nd(e){return window.getComputedStyle(e)}class Dd extends Va{constructor(){super(...arguments),this.type="html",this.renderInstance=Ia}readValueFromInstance(t,n){if(un.has(n))return this.projection?.isProjecting?Hs(n):_c(t,n);{const s=Nd(t),r=(jr(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Da(t,n)}build(t,n,s){Ur(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Wr(t,n,s)}}const Oa=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function Rd(e,t,n,s){Ia(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(Oa.has(r)?r:Kr(r),t.attrs[r])}class Vd extends Va{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ge}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(un.has(n)){const s=la(n);return s&&s.default||0}return n=Oa.has(n)?n:Kr(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return Ca(t,n,s)}build(t,n,s){wa(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){Rd(t,n,s,r)}mount(t){this.isSVGTag=Sa(t.tagName),super.mount(t)}}const $a=(e,t)=>Xr(e)?new Vd(t):new Dd(t,{allowProjection:e!==f.Fragment});function sn(e,t,n){const s=e.getProps();return qr(s,t,n!==void 0?n:s.custom,e)}const ar=e=>Array.isArray(e);function Id(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,rn(n))}function Od(e){return ar(e)?e[e.length-1]||0:e}function $d(e,t){const n=sn(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Od(o[i]);Id(e,i,a)}}function Ld(e){return!!(je(e)&&e.add)}function lr(e,t){const n=e.getValue("willChange");if(Ld(n))return n.add(t);if(!n&&ft.WillChange){const s=new ft.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function La(e){return e.props[Pa]}const Fd=e=>e!==null;function Bd(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Fd),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const zd={type:"spring",stiffness:500,damping:25,restSpeed:10},Ud=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),_d={type:"keyframes",duration:.8},Xd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},qd=(e,{keyframes:t})=>t.length>2?_d:un.has(e)?e.startsWith("scale")?Ud(t[1]):zd:Xd;function Wd({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:l,elapsed:u,...d}){return!!Object.keys(d).length}const Gr=(e,t,n,s={},r,o)=>i=>{const a=Vr(s,e)||{},l=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-He(l);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};Wd(a)||Object.assign(d,qd(e,d)),d.duration&&(d.duration=He(d.duration)),d.repeatDelay&&(d.repeatDelay=He(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let h=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(tr(d),d.delay===0&&(h=!0)),(ft.instantAnimations||ft.skipAnimations)&&(h=!0,tr(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const m=Bd(d.keyframes,a);if(m!==void 0){de.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new Dr(d):new hu(d)};function Kd({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function Fa(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const l=[],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&&Kd(u,d))continue;const p={delay:n,...Vr(o||{},d)},v=h.get();if(v!==void 0&&!h.isAnimating&&!Array.isArray(m)&&m===v&&!p.velocity)continue;let x=!1;if(window.MotionHandoffAnimation){const y=La(e);if(y){const w=window.MotionHandoffAnimation(y,d,de);w!==null&&(p.startTime=w,x=!0)}}lr(e,d),h.start(Gr(d,h,m,e.shouldReduceMotion&&ia.has(d)?{type:!1}:p,e,x));const T=h.animation;T&&l.push(T)}return i&&Promise.all(l).then(()=>{de.update(()=>{i&&$d(e,i)})}),l}function Ba(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 cr(e,t,n={}){const s=sn(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(Fa(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=r;return Gd(e,t,l,u,d,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[l,u]=a==="beforeChildren"?[o,i]:[i,o];return l().then(()=>u())}else return Promise.all([o(),i(n.delay)])}function Gd(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const l of e.variantChildren)l.notify("AnimationStart",t),a.push(cr(l,t,{...i,delay:n+(typeof s=="function"?0:s)+Ba(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function Yd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>cr(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=cr(e,t,n);else{const r=typeof t=="function"?sn(e,t,n.custom):t;s=Promise.all(Fa(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function za(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 Hd=zr.length;function Ua(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Ua(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<Hd;n++){const s=zr[n],r=e.props[s];(Fn(r)||r===!1)&&(t[s]=r)}return t}const Jd=[...Br].reverse(),Zd=Br.length;function Qd(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Yd(e,n,s)))}function eh(e){let t=Qd(e),n=$i(),s=!0;const r=l=>(u,d)=>{const h=sn(e,d,l==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:m,transitionEnd:p,...v}=h;u={...u,...v,...p}}return u};function o(l){t=l(e)}function i(l){const{props:u}=e,d=Ua(e.parent)||{},h=[],m=new Set;let p={},v=1/0;for(let T=0;T<Zd;T++){const y=Jd[T],w=n[y],k=u[y]!==void 0?u[y]:d[y],O=Fn(k),E=y===l?w.isActive:null;E===!1&&(v=T);let B=k===d[y]&&k!==u[y]&&O;if(B&&s&&e.manuallyAnimateOnMount&&(B=!1),w.protectedKeys={...p},!w.isActive&&E===null||!k&&!w.prevProp||Ts(k)||typeof k=="boolean")continue;const _=th(w.prevProp,k);let M=_||y===l&&w.isActive&&!B&&O||T>v&&O,R=!1;const j=Array.isArray(k)?k:[k];let V=j.reduce(r(y),{});E===!1&&(V={});const{prevResolvedValues:z={}}=w,N={...z,...V},K=Q=>{M=!0,m.has(Q)&&(R=!0,m.delete(Q)),w.needsAnimating[Q]=!0;const ne=e.getValue(Q);ne&&(ne.liveStyle=!1)};for(const Q in N){const ne=V[Q],Z=z[Q];if(p.hasOwnProperty(Q))continue;let we=!1;ar(ne)&&ar(Z)?we=!za(ne,Z):we=ne!==Z,we?ne!=null?K(Q):m.add(Q):ne!==void 0&&m.has(Q)?K(Q):w.protectedKeys[Q]=!0}w.prevProp=k,w.prevResolvedValues=V,w.isActive&&(p={...p,...V}),s&&e.blockInitialAnimation&&(M=!1);const Y=B&&_;M&&(!Y||R)&&h.push(...j.map(Q=>{const ne={type:y};if(typeof Q=="string"&&s&&!Y&&e.manuallyAnimateOnMount&&e.parent){const{parent:Z}=e,we=sn(Z,Q);if(Z.enteringChildren&&we){const{delayChildren:Je}=we.transition||{};ne.delay=Ba(Z.enteringChildren,e,Je)}}return{animation:Q,options:ne}}))}if(m.size){const T={};if(typeof u.initial!="boolean"){const y=sn(e,Array.isArray(u.initial)?u.initial[0]:u.initial);y&&y.transition&&(T.transition=y.transition)}m.forEach(y=>{const w=e.getBaseTarget(y),k=e.getValue(y);k&&(k.liveStyle=!0),T[y]=w??null}),h.push({animation:T})}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(l,u){if(n[l].isActive===u)return Promise.resolve();e.variantChildren?.forEach(h=>h.animationState?.setActive(l,u)),n[l].isActive=u;const d=i(l);for(const h in n)n[h].protectedKeys={};return d}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=$i()}}}function th(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!za(t,e):!1}function Dt(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function $i(){return{animate:Dt(!0),whileInView:Dt(),whileHover:Dt(),whileTap:Dt(),whileDrag:Dt(),whileFocus:Dt(),exit:Dt()}}class Ct{constructor(t){this.isMounted=!1,this.node=t}update(){}}class nh extends Ct{constructor(t){super(t),t.animationState||(t.animationState=eh(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Ts(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 sh=0;class rh extends Ct{constructor(){super(...arguments),this.id=sh++}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 _a={animation:{Feature:nh},exit:{Feature:rh}};function zn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function qn(e){return{point:{x:e.pageX,y:e.pageY}}}const ih=e=>t=>$r(t)&&e(t,qn(t));function Nn(e,t,n,s){return zn(e,t,ih(n),s)}const Xa=1e-4,oh=1-Xa,ah=1+Xa,qa=.01,lh=0-qa,ch=0+qa;function ke(e){return e.max-e.min}function uh(e,t,n){return Math.abs(e-t)<=n}function Li(e,t,n,s=.5){e.origin=s,e.originPoint=fe(t.min,t.max,e.origin),e.scale=ke(n)/ke(t),e.translate=fe(n.min,n.max,e.origin)-e.originPoint,(e.scale>=oh&&e.scale<=ah||isNaN(e.scale))&&(e.scale=1),(e.translate>=lh&&e.translate<=ch||isNaN(e.translate))&&(e.translate=0)}function Dn(e,t,n,s){Li(e.x,t.x,n.x,s?s.originX:void 0),Li(e.y,t.y,n.y,s?s.originY:void 0)}function Fi(e,t,n){e.min=n.min+t.min,e.max=e.min+ke(t)}function dh(e,t,n){Fi(e.x,t.x,n.x),Fi(e.y,t.y,n.y)}function Bi(e,t,n){e.min=t.min-n.min,e.max=e.min+ke(t)}function Rn(e,t,n){Bi(e.x,t.x,n.x),Bi(e.y,t.y,n.y)}function Fe(e){return[e("x"),e("y")]}const Wa=({current:e})=>e?e.ownerDocument.defaultView:null,zi=(e,t)=>Math.abs(e-t);function hh(e,t){const n=zi(e.x,t.x),s=zi(e.y,t.y);return Math.sqrt(n**2+s**2)}class Ka{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=Is(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,v=hh(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!v)return;const{point:x}=m,{timestamp:T}=ve;this.history.push({...x,timestamp:T});const{onStart:y,onMove:w}=this.handlers;p||(y&&y(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),w&&w(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=Vs(p,this.transformPagePoint),de.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:v,onSessionEnd:x,resumeAnimation:T}=this.handlers;if(this.dragSnapToOrigin&&T&&T(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Is(m.type==="pointercancel"?this.lastMoveEventInfo:Vs(p,this.transformPagePoint),this.history);this.startEvent&&v&&v(m,y),x&&x(m,y)},!$r(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=qn(t),l=Vs(a,this.transformPagePoint),{point:u}=l,{timestamp:d}=ve;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=n;h&&h(t,Is(l,this.history)),this.removeListeners=Un(Nn(this.contextWindow,"pointermove",this.handlePointerMove),Nn(this.contextWindow,"pointerup",this.handlePointerUp),Nn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),St(this.updatePoint)}}function Vs(e,t){return t?{point:t(e.point)}:e}function Ui(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Is({point:e},t){return{point:e,delta:Ui(e,Ga(t)),offset:Ui(e,fh(t)),velocity:mh(t,.1)}}function fh(e){return e[0]}function Ga(e){return e[e.length-1]}function mh(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Ga(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>He(t)));)n--;if(!s)return{x:0,y:0};const o=Be(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 ph(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 _i(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 gh(e,{top:t,left:n,bottom:s,right:r}){return{x:_i(e.x,n,r),y:_i(e.y,t,s)}}function Xi(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 yh(e,t){return{x:Xi(e.x,t.x),y:Xi(e.y,t.y)}}function xh(e,t){let n=.5;const s=ke(e),r=ke(t);return r>s?n=On(t.min,t.max-s,e.min):s>r&&(n=On(e.min,e.max-r,t.min)),dt(0,1,n)}function bh(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 ur=.35;function vh(e=ur){return e===!1?e=0:e===!0&&(e=ur),{x:qi(e,"left","right"),y:qi(e,"top","bottom")}}function qi(e,t,n){return{min:Wi(e,t),max:Wi(e,n)}}function Wi(e,t){return typeof e=="number"?e:e[t]||0}const wh=new WeakMap;class Th{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(qn(h).point)},i=(h,m)=>{const{drag:p,dragPropagation:v,onDragStart:x}=this.getProps();if(p&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Mu(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),Fe(y=>{let w=this.getAxisMotionValue(y).get()||0;if(rt.test(w)){const{projection:k}=this.visualElement;if(k&&k.layout){const O=k.layout.layoutBox[y];O&&(w=ke(O)*(parseFloat(w)/100))}}this.originPoint[y]=w}),x&&de.postRender(()=>x(h,m)),lr(this.visualElement,"transform");const{animationState:T}=this.visualElement;T&&T.setActive("whileDrag",!0)},a=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:v,onDirectionLock:x,onDrag:T}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=m;if(v&&this.currentDirection===null){this.currentDirection=Sh(y),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",m.point,y),this.updateAxis("y",m.point,y),this.visualElement.render(),T&&T(h,m)},l=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>Fe(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:d}=this.getProps();this.panSession=new Ka(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Wa(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&&de.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||!rs(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=ph(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&&Zt(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=gh(s.layoutBox,t):this.constraints=!1,this.elastic=vh(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Fe(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=bh(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Zt(t))return!1;const s=t.current;ht(s!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const o=Pd(s,r.root,this.visualElement.getTransformPagePoint());let i=yh(r.layout.layoutBox,o);if(n){const a=n(Sd(i));this.hasMutatedConstraints=!!a,a&&(i=Ma(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},u=Fe(d=>{if(!rs(d,n,this.currentDirection))return;let h=l&&l[d]||{};i&&(h={min:0,max:0});const m=r?200:1e6,p=r?40:1e7,v={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(d,v)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return lr(this.visualElement,t),s.start(Gr(t,s,0,n,this.visualElement,!1))}stopAnimation(){Fe(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Fe(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){Fe(n=>{const{drag:s}=this.getProps();if(!rs(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(!Zt(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Fe(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const l=a.get();r[i]=xh({min:l,max:l},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(),Fe(i=>{if(!rs(i,t,null))return;const a=this.getAxisMotionValue(i),{min:l,max:u}=this.constraints[i];a.set(fe(l,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;wh.set(this.visualElement,this);const t=this.visualElement.current,n=Nn(t,"pointerdown",l=>{const{drag:u,dragListener:d=!0}=this.getProps();u&&d&&this.start(l)}),s=()=>{const{dragConstraints:l}=this.getProps();Zt(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,o=r.addEventListener("measure",s);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),de.read(s);const i=zn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:l,hasLayoutChanged:u})=>{this.isDragging&&u&&(Fe(d=>{const h=this.getAxisMotionValue(d);h&&(this.originPoint[d]+=l[d].translate,h.set(h.get()+l[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=ur,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function rs(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Sh(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class jh extends Ct{constructor(t){super(t),this.removeGroupControls=ze,this.removeListeners=ze,this.controls=new Th(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ze}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ki=e=>(t,n)=>{e&&de.postRender(()=>e(t,n))};class Ch extends Ct{constructor(){super(...arguments),this.removePointerDownListener=ze}onPointerDown(t){this.session=new Ka(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Wa(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ki(t),onStart:Ki(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&de.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=Nn(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 us={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Gi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const An={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(W.test(e))e=parseFloat(e);else return e;const n=Gi(e,t.target.x),s=Gi(e,t.target.y);return`${n}% ${s}%`}},Ph={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=jt.parse(e);if(r.length>5)return s;const o=jt.createTransformer(e),i=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;r[0+i]/=a,r[1+i]/=l;const u=fe(a,l,.5);return typeof r[2+i]=="number"&&(r[2+i]/=u),typeof r[3+i]=="number"&&(r[3+i]/=u),o(r)}};let Os=!1;class Ah extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;Ju(kh),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),Os&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),us.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Os=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||de.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Or.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Os=!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 Ya(e){const[t,n]=ga(),s=f.useContext(mr);return c.jsx(Ah,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(Aa),isPresent:t,safeToRemove:n})}const kh={borderRadius:{...An,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:An,borderTopRightRadius:An,borderBottomLeftRadius:An,borderBottomRightRadius:An,boxShadow:Ph};function Mh(e,t,n){const s=je(e)?e:rn(e);return s.start(Gr("",s,t,n)),s.animation}const Eh=(e,t)=>e.depth-t.depth;class Nh{constructor(){this.children=[],this.isDirty=!1}add(t){yr(this.children,t),this.isDirty=!0}remove(t){xr(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Eh),this.isDirty=!1,this.children.forEach(t)}}function Dh(e,t){const n=De.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(St(s),e(o-t))};return de.setup(s,!0),()=>St(s)}const Ha=["TopLeft","TopRight","BottomLeft","BottomRight"],Rh=Ha.length,Yi=e=>typeof e=="string"?parseFloat(e):e,Hi=e=>typeof e=="number"||W.test(e);function Vh(e,t,n,s,r,o){r?(e.opacity=fe(0,n.opacity??1,Ih(s)),e.opacityExit=fe(t.opacity??1,0,Oh(s))):o&&(e.opacity=fe(t.opacity??1,n.opacity??1,s));for(let i=0;i<Rh;i++){const a=`border${Ha[i]}Radius`;let l=Ji(t,a),u=Ji(n,a);if(l===void 0&&u===void 0)continue;l||(l=0),u||(u=0),l===0||u===0||Hi(l)===Hi(u)?(e[a]=Math.max(fe(Yi(l),Yi(u),s),0),(rt.test(u)||rt.test(l))&&(e[a]+="%")):e[a]=u}(t.rotate||n.rotate)&&(e.rotate=fe(t.rotate||0,n.rotate||0,s))}function Ji(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Ih=Ja(0,.5,Oo),Oh=Ja(.5,.95,ze);function Ja(e,t,n){return s=>s<e?0:s>t?1:n(On(e,t,s))}function Zi(e,t){e.min=t.min,e.max=t.max}function Le(e,t){Zi(e.x,t.x),Zi(e.y,t.y)}function Qi(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function eo(e,t,n,s,r){return e-=t,e=xs(e,1/n,s),r!==void 0&&(e=xs(e,1/r,s)),e}function $h(e,t=0,n=1,s=.5,r,o=e,i=e){if(rt.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=eo(e.min,t,n,a,r),e.max=eo(e.max,t,n,a,r)}function to(e,t,[n,s,r],o,i){$h(e,t[n],t[s],t[r],t.scale,o,i)}const Lh=["x","scaleX","originX"],Fh=["y","scaleY","originY"];function no(e,t,n,s){to(e.x,t,Lh,n?n.x:void 0,s?s.x:void 0),to(e.y,t,Fh,n?n.y:void 0,s?s.y:void 0)}function so(e){return e.translate===0&&e.scale===1}function Za(e){return so(e.x)&&so(e.y)}function ro(e,t){return e.min===t.min&&e.max===t.max}function Bh(e,t){return ro(e.x,t.x)&&ro(e.y,t.y)}function io(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Qa(e,t){return io(e.x,t.x)&&io(e.y,t.y)}function oo(e){return ke(e.x)/ke(e.y)}function ao(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class zh{constructor(){this.members=[]}add(t){yr(this.members,t),t.scheduleRender()}remove(t){if(xr(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 Uh(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:v}=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) `),v&&(s+=`skewY(${v}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(s+=`scale(${a}, ${l})`),s||"none"}const $s=["","X","Y","Z"],_h=1e3;let Xh=0;function Ls(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function el(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=La(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",de,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&el(s)}function tl({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=Xh++,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(Kh),this.nodes.forEach(Jh),this.nodes.forEach(Zh),this.nodes.forEach(Gh)},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 l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new Nh)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new vr),this.eventHandlers.get(i).add(a)}notifyListeners(i,...a){const l=this.eventHandlers.get(i);l&&l.notify(...a)}hasListeners(i){return this.eventHandlers.has(i)}mount(i){if(this.instance)return;this.isSVG=pa(i)&&!Iu(i),this.instance=i;const{layoutId:a,layout:l,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&&(l||a)&&(this.isLayoutDirty=!0),e){let d,h=0;const m=()=>this.root.updateBlockedByResize=!1;de.read(()=>{h=window.innerWidth}),e(i,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,d&&d(),d=Dh(m,250),us.hasAnimatedSinceResize&&(us.hasAnimatedSinceResize=!1,this.nodes.forEach(uo)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||u.getDefaultTransition()||sf,{onLayoutAnimationStart:x,onLayoutAnimationComplete:T}=u.getProps(),y=!this.targetLayout||!Qa(this.targetLayout,p),w=!h&&m;if(this.options.layoutRoot||this.resumeFrom||w||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...Vr(v,"layout"),onPlay:x,onComplete:T};(u.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(d,w)}else h||uo(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(),St(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(Qh),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&&el(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:l}=this.options;if(a===void 0&&!l)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(lo);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(co);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Hh),this.nodes.forEach(qh),this.nodes.forEach(Wh)):this.nodes.forEach(co),this.clearAllSnapshots();const a=De.now();ve.delta=dt(0,1e3/60,a-ve.timestamp),ve.timestamp=a,ve.isProcessing=!0,Ps.update.process(ve),Ps.preRender.process(ve),Ps.render.process(ve),ve.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Or.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Yh),this.sharedNodes.forEach(ef)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,de.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){de.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!ke(this.snapshot.measuredBox.x)&&!ke(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 l=0;l<this.path.length;l++)this.path[l].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 l=s(this.instance);this.scroll={animationId:this.root.animationId,phase:i,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!r)return;const i=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Za(this.projectionDelta),l=this.getTransformTemplate(),u=l?l(this.latestValues,""):void 0,d=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Vt(this.latestValues)||d)&&(r(this.instance,u),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return i&&(l=this.removeTransform(l)),rf(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,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(of))){const{scroll:u}=this.root;u&&(Qt(a.x,u.offset.x),Qt(a.y,u.offset.y))}return a}removeElementScroll(i){const a=ge();if(Le(a,i),this.scroll?.wasRoot)return a;for(let l=0;l<this.path.length;l++){const u=this.path[l],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&Le(a,i),Qt(a.x,d.offset.x),Qt(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const l=ge();Le(l,i);for(let u=0;u<this.path.length;u++){const d=this.path[u];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&en(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Vt(d.latestValues)&&en(l,d.latestValues)}return Vt(this.latestValues)&&en(l,this.latestValues),l}removeTransform(i){const a=ge();Le(a,i);for(let l=0;l<this.path.length;l++){const u=this.path[l];if(!u.instance||!Vt(u.latestValues))continue;rr(u.latestValues)&&u.updateSnapshot();const d=ge(),h=u.measurePageBox();Le(d,h),no(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,d)}return Vt(this.latestValues)&&no(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 l=!!this.resumingFrom||this!==a;if(!(i||l&&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(),Rn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Le(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(),dh(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Le(this.target,this.layout.layoutBox),Na(this.target,this.targetDelta)):Le(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(),Rn(this.relativeTargetOrigin,this.target,m.target),Le(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||rr(this.parent.latestValues)||Ea(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 l=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===ve.timestamp&&(l=!1),l)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;Le(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,m=this.treeScale.y;Cd(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():(Qi(this.prevProjectionDelta.x,this.projectionDelta.x),Qi(this.prevProjectionDelta.y,this.projectionDelta.y)),Dn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==m||!ao(this.projectionDelta.x,this.prevProjectionDelta.x)||!ao(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=tn(),this.projectionDelta=tn(),this.projectionDeltaWithTransform=tn()}setAnimationOrigin(i,a=!1){const l=this.snapshot,u=l?l.latestValues:{},d={...this.latestValues},h=tn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=ge(),p=l?l.source:void 0,v=this.layout?this.layout.source:void 0,x=p!==v,T=this.getStack(),y=!T||T.members.length<=1,w=!!(x&&!y&&this.options.crossfade===!0&&!this.path.some(nf));this.animationProgress=0;let k;this.mixTargetDelta=O=>{const E=O/1e3;ho(h.x,i.x,E),ho(h.y,i.y,E),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Rn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),tf(this.relativeTarget,this.relativeTargetOrigin,m,E),k&&Bh(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ge()),Le(k,this.relativeTarget)),x&&(this.animationValues=d,Vh(d,u,this.latestValues,E,w,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=E},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(St(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=de.update(()=>{us.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=rn(0)),this.currentAnimation=Mh(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(_h),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:l,layout:u,latestValues:d}=i;if(!(!a||!l||!u)){if(this!==i&&this.layout&&u&&nl(this.options.animationType,this.layout.layoutBox,u.layoutBox)){l=this.target||ge();const h=ke(this.layout.layoutBox.x);l.x.min=i.target.x.min,l.x.max=l.x.min+h;const m=ke(this.layout.layoutBox.y);l.y.min=i.target.y.min,l.y.max=l.y.min+m}Le(a,l),en(a,d),Dn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new zh),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:l}={}){const u=this.getStack();u&&u.promote(this,l),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:l}=i;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const u={};l.z&&Ls("z",i,u,this.animationValues);for(let d=0;d<$s.length;d++)Ls(`rotate${$s[d]}`,i,u,this.animationValues),Ls(`skew${$s[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 l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,i.visibility="",i.opacity="",i.pointerEvents=ls(a?.pointerEvents)||"",i.transform=l?l(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=ls(a?.pointerEvents)||""),this.hasProjected&&!Vt(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=Uh(this.projectionDeltaWithTransform,this.treeScale,d);l&&(h=l(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 v in Bn){if(d[v]===void 0)continue;const{correct:x,applyTo:T,isCSSVariable:y}=Bn[v],w=h==="none"?d[v]:x(d[v],u);if(T){const k=T.length;for(let O=0;O<k;O++)i[T[O]]=w}else y?this.options.visualElement.renderState.vars[v]=w:i[v]=w}this.options.layoutId&&(i.pointerEvents=u===this?ls(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(lo),this.root.sharedNodes.clear()}}}function qh(e){e.updateLayout()}function Wh(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"?Fe(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=ke(h);h.min=n[d].min,h.max=h.min+m}):nl(r,t.layoutBox,n)&&Fe(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=ke(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=tn();Dn(i,n,t.layoutBox);const a=tn();o?Dn(a,e.applyTransform(s,!0),t.measuredBox):Dn(a,n,t.layoutBox);const l=!Za(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();Rn(p,t.layoutBox,h.layoutBox);const v=ge();Rn(v,n,m.layoutBox),Qa(p,v)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=v,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:l,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function Kh(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 Gh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Yh(e){e.clearSnapshot()}function lo(e){e.clearMeasurements()}function co(e){e.isLayoutDirty=!1}function Hh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function uo(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Jh(e){e.resolveTargetDelta()}function Zh(e){e.calcProjection()}function Qh(e){e.resetSkewAndRotation()}function ef(e){e.removeLeadSnapshot()}function ho(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 fo(e,t,n,s){e.min=fe(t.min,n.min,s),e.max=fe(t.max,n.max,s)}function tf(e,t,n,s){fo(e.x,t.x,n.x,s),fo(e.y,t.y,n.y,s)}function nf(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const sf={duration:.45,ease:[.4,0,.1,1]},mo=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),po=mo("applewebkit/")&&!mo("chrome/")?Math.round:ze;function go(e){e.min=po(e.min),e.max=po(e.max)}function rf(e){go(e.x),go(e.y)}function nl(e,t,n){return e==="position"||e==="preserve-aspect"&&!uh(oo(t),oo(n),.2)}function of(e){return e!==e.root&&e.scroll?.wasRoot}const af=tl({attachResizeListener:(e,t)=>zn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Fs={current:void 0},sl=tl({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Fs.current){const e=new af({});e.mount(window),e.setOptions({layoutScroll:!0}),Fs.current=e}return Fs.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),lf={pan:{Feature:Ch},drag:{Feature:jh,ProjectionNode:sl,MeasureLayout:Ya}};function yo(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&&de.postRender(()=>o(t,qn(t)))}class cf extends Ct{mount(){const{current:t}=this.node;t&&(this.unmount=Eu(t,(n,s)=>(yo(this.node,s,"Start"),r=>yo(this.node,r,"End"))))}unmount(){}}class uf extends Ct{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Un(zn(this.node.current,"focus",()=>this.onFocus()),zn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function xo(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&&de.postRender(()=>o(t,qn(t)))}class df extends Ct{mount(){const{current:t}=this.node;t&&(this.unmount=Vu(t,(n,s)=>(xo(this.node,s,"Start"),(r,{success:o})=>xo(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const dr=new WeakMap,Bs=new WeakMap,hf=e=>{const t=dr.get(e.target);t&&t(e)},ff=e=>{e.forEach(hf)};function mf({root:e,...t}){const n=e||document;Bs.has(n)||Bs.set(n,{});const s=Bs.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(ff,{root:e,...t})),s[r]}function pf(e,t,n){const s=mf(t);return dr.set(e,n),s.observe(e),()=>{dr.delete(e),s.unobserve(e)}}const gf={some:0,all:1};class yf extends Ct{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=t,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:gf[r]},a=l=>{const{isIntersecting:u}=l;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(l)};return pf(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(xf(t,n))&&this.startObserver()}unmount(){}}function xf({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const rl={inView:{Feature:yf},tap:{Feature:df},focus:{Feature:uf},hover:{Feature:cf}},bf={layout:{ProjectionNode:sl,MeasureLayout:Ya}},vf={..._a,...rl,...lf,...bf},wf=Td(vf,$a),Tf={renderer:$a,..._a,...rl};function Yr(e,t){return cs(e,t)}const Sf=Yr("button"),is=Yr("div"),jf=Yr("p"),st=Symbol.for("@arcteninc/core:originalName");function Cf(e,t){return e[st]=t,e}function Pf(e,t,n,s){if(typeof e!="function")return null;const r=e[st];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[st]=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[st]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(l=>!n.has(l.name)),i)return e[st]=i.name,{fn:e,meta:i};return null}function il(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=Pf(o,n,r,s);if(!i){const a=o.name,u=o[nt]||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 Af({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return c.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:c.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&c.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>c.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[c.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),c.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),c.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[c.jsxs(je,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[c.jsx(ie.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),c.jsx(je,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:c.jsx(ie.X,{className:"h-3 w-3"})})]})]})})}function kf({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))),l=Object.keys(a).length>0;return c.jsxs("div",{className:"my-1",children:[c.jsxs("button",{onClick:()=>l&&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 ${l?"cursor-pointer hover:bg-muted/80":""}`,children:[l&&c.jsx("span",{className:"transition-transform duration-200",children:r?c.jsx(ie.ChevronDown,{className:"h-3 w-3"}):c.jsx(ie.ChevronRight,{className:"h-3 w-3"})}),n?c.jsx(ie.X,{className:"h-3 w-3"}):s?c.jsx(ie.Zap,{className:"h-3 w-3"}):c.jsx(ie.Check,{className:"h-3 w-3"}),c.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&l&&c.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:c.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,d])=>c.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[c.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),c.jsx("span",{className:"font-mono text-foreground",children:typeof d=="string"?d:JSON.stringify(d)})]},u))})})]})}function Mf({...e}){return c.jsx(pr.Root,{"data-slot":"collapsible",...e})}function Ef({...e}){return c.jsx(pr.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function Nf({...e}){return c.jsx(pr.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const Df=f.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Zr=f.memo(({className:e,...t})=>typeof window>"u"?null:c.jsx(f.Suspense,{fallback:null,children:c.jsx(Df,{className:oe("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Zr.displayName="Response";const Rf=Object.freeze(Object.defineProperty({__proto__:null,Response:Zr},Symbol.toStringTag,{value:"Module"})),Vf=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=wf.create(t),i=f.useMemo(()=>(e?.length??0)*r,[e,r]);return c.jsx(o,{animate:{backgroundPosition:"0% center"},className:oe("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})},If=f.memo(Vf),ll=f.createContext(null),Of=()=>{const e=f.useContext(ll);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},$f=1e3,Lf=1e3,cl=f.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,u]=si.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,h]=si.useControllableState({prop:o,defaultProp:0}),[m,p]=f.useState(!1),[v,x]=f.useState(null);f.useEffect(()=>{t?v===null&&x(Date.now()):v!==null&&(h(Math.ceil((Date.now()-v)/Lf)),x(null))},[t,v,h]),f.useEffect(()=>{if(s&&!t&&l&&!m){const y=setTimeout(()=>{u(!1),p(!0)},$f);return()=>clearTimeout(y)}},[t,l,s,u,m]);const T=y=>{u(y)};return c.jsx(ll.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:u,duration:d},children:c.jsx(Mf,{className:oe("not-prose mb-4",e),onOpenChange:T,open:l,...a,children:i})})}),Ff=(e,t)=>e||t===0?c.jsx(If,{duration:1,children:"Thinking..."}):t===void 0?c.jsx("p",{children:"Thought for a few seconds"}):c.jsxs("p",{children:["Thought for ",t," seconds"]}),ul=f.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Of();return c.jsx(Ef,{className:oe("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??c.jsxs(c.Fragment,{children:[c.jsx(ie.BrainIcon,{className:"size-4"}),Ff(s,o),c.jsx(ie.ChevronDownIcon,{className:oe("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),dl=f.memo(({className:e,children:t,...n})=>c.jsx(Nf,{className:oe("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:c.jsx(Zr,{className:"grid gap-2",children:t})}));cl.displayName="Reasoning";ul.displayName="ReasoningTrigger";dl.displayName="ReasoningContent";function wo(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function Bf({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=wo(s.domain);return c.jsxs(vt,{children:[c.jsx(wt,{asChild:!0,children:c.jsxs("button",{className:oe("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:[c.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),c.jsx("span",{className:"leading-none",children:s.domain})]})}),c.jsx(Tt,{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:c.jsxs("div",{className:"space-y-1.5",children:[c.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 c.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:oe("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:[c.jsx("img",{src:wo(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const l=a.target;l.style.display="none"}}),c.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function zf({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:l=!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 T=u.current;let y,w=!1;const k=new WeakSet,O=()=>{if(!u.current||w)return;w=!0;const B=u.current,_=/\[(\d+)\]/g,M=document.createTreeWalker(B,NodeFilter.SHOW_TEXT,null),R=[];let j;for(;j=M.nextNode();)if(j.nodeType===Node.TEXT_NODE&&!k.has(j)){const z=j,N=z.textContent||"";let K=z.parentElement,Y=!1;for(;K&&K!==B;){if(K.tagName==="A"||K.tagName==="CODE"||K.tagName==="PRE"){Y=!0;break}K=K.parentElement}if(!Y){const Q=Array.from(N.matchAll(_)).filter(ne=>{if(!ne[1])return!1;const Z=parseInt(ne[1],10);return n.has(Z)});Q.length>0&&R.push({node:z,matches:Q})}}if(R.length===0){w=!1;return}const V=[];R.forEach(({node:z,matches:N})=>{k.add(z);const K=z.textContent||"",Y=document.createDocumentFragment();let le=0;N.forEach(Q=>{if(!Q[1])return;Q.index!==void 0&&Q.index>le&&Y.appendChild(document.createTextNode(K.slice(le,Q.index)));const ne=document.createElement("span");ne.className="inline-flex items-center citation-button-container";const Z=parseInt(Q[1],10);ne.setAttribute("data-citation",Q[1]),Y.appendChild(ne),V.push({element:ne,citationNum:Z}),le=(Q.index||0)+Q[0].length}),le<K.length&&Y.appendChild(document.createTextNode(K.slice(le))),z.parentNode&&z.parentNode.replaceChild(Y,z)}),V.length>0&&h(z=>{const N=new Set(z.map(le=>le.element)),K=z.filter(le=>le.element.isConnected),Y=V.filter(le=>!N.has(le.element));return[...K,...Y]}),w=!1},E=new MutationObserver(()=>{clearTimeout(y),y=setTimeout(O,100)});return E.observe(T,{childList:!0,subtree:!0,characterData:!0}),y=setTimeout(O,200),()=>{E.disconnect(),clearTimeout(y)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(T){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(T)}&sz=16`}function v(T){try{return new URL(T).hostname.replace(/^www\./,"")}catch{return T}}const x=a&&l&&m?c.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[c.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((T,y)=>{const w=T.title||T.baseUrl,k=v(T.url),O=p(k);return c.jsxs("a",{href:T.url,target:"_blank",rel:"noopener noreferrer",className:oe("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:[c.jsx("img",{src:O,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:E=>{const B=E.target;B.style.display="none"}}),c.jsx("span",{className:"leading-none",children:w})]},`group-${y}`)}):Array.from(n.entries()).sort(([T],[y])=>T-y).map(([T,y])=>{const w=v(y),k=p(w);return c.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:oe("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:[c.jsx("img",{src:k,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:O=>{const E=O.target;E.style.display="none"}}),c.jsx("span",{className:"leading-none",children:y})]},T)})})]}):null;return c.jsxs("div",{className:i,children:[c.jsx("div",{ref:u,children:c.jsx(o,{children:e})}),a&&d.filter(({element:T})=>T.isConnected).map(({element:T,citationNum:y},w)=>{if(!t.find(E=>E.number===y))return null;const O=Array.from(new Map(t.map(E=>{const B=E.url.replace(/\/+$/,""),_=s?.find(M=>M.url.replace(/\/+$/,"")===B);return[B,{number:E.number,url:E.url,domain:v(E.url),title:_?.title}]})).values());return Ol.createPortal(c.jsx(Bf,{sources:O,citationNumber:y},`citation-${y}-${T}`),T,`citation-${y}-${w}`)}),x]})}function hn({...e}){return c.jsx(Bt.Root,{"data-slot":"dialog",...e})}function Uf({...e}){return c.jsx(Bt.Portal,{"data-slot":"dialog-portal",...e})}function _f({className:e,...t}){return c.jsx(Bt.Overlay,{"data-slot":"dialog-overlay",className:oe("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 fn({className:e,children:t,showCloseButton:n=!0,...s}){return c.jsxs(Uf,{"data-slot":"dialog-portal",children:[c.jsx(_f,{}),c.jsxs(Bt.Content,{"data-slot":"dialog-content",className:oe("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&&c.jsxs(Bt.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:[c.jsx(ie.XIcon,{}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function mn({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-header",className:oe("flex flex-col gap-2 text-center sm:text-left",e),...t})}function pn({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-footer",className:oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function gn({className:e,...t}){return c.jsx(Bt.Title,{"data-slot":"dialog-title",className:oe("text-lg leading-none font-semibold",e),...t})}function yn({className:e,...t}){return c.jsx(Bt.Description,{"data-slot":"dialog-description",className:oe("text-muted-foreground text-sm",e),...t})}function xn({className:e,type:t,...n}){return c.jsx("input",{type:t,"data-slot":"input",className:oe("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 Xf({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,l]=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 c.jsx(hn,{open:e,children:c.jsx(fn,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:h,children:[c.jsxs(mn,{children:[c.jsx(gn,{children:t}),c.jsx(yn,{children:n})]}),c.jsx("div",{className:"py-4",children:c.jsxs("div",{className:"relative",children:[c.jsx(xn,{type:a?"text":"password",value:o,onChange:p=>i(p.target.value),placeholder:s,className:"pr-10",autoFocus:!0,disabled:u}),c.jsx("button",{type:"button",onClick:()=>l(!a),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:u,children:a?c.jsx(ie.EyeOff,{className:"h-4 w-4"}):c.jsx(ie.Eye,{className:"h-4 w-4"})})]})}),c.jsxs(pn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:m,disabled:u,children:"Cancel"}),c.jsx(je,{type:"submit",disabled:!o.trim()||u,children:u?"Submitting...":"Submit"})]})]})})})}function qf({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,l]=f.useState(!0),[u,d]=f.useState(!1),h=x=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(x),m=x=>{i(x),x.trim()?l(h(x)):l(!0)},p=async x=>{if(x.preventDefault(),!o.trim()||!h(o)){l(!1);return}d(!0);try{r(o)}finally{d(!1)}},v=()=>{i(""),l(!0),r(null)};return c.jsx(hn,{open:e,children:c.jsx(fn,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:p,children:[c.jsxs(mn,{children:[c.jsxs(gn,{className:"flex items-center gap-2",children:[c.jsx(ie.Mail,{className:"h-5 w-5"}),t]}),c.jsx(yn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(xn,{type:"email",value:o,onChange:x=>m(x.target.value),placeholder:s,className:a?"":"border-red-500",autoFocus:!0,disabled:u}),!a&&c.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid email address"})]}),c.jsxs(pn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:v,disabled:u,children:"Cancel"}),c.jsx(je,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Wf({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,l]=f.useState(!0),[u,d]=f.useState(!1),h=T=>{const y=T.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=T=>T.replace(/\D/g,"").length===10,p=T=>{const y=h(T);i(y),y.trim()?l(m(y)):l(!0)},v=async T=>{if(T.preventDefault(),!o.trim()||!m(o)){l(!1);return}d(!0);try{const y=o.replace(/\D/g,"");r(y)}finally{d(!1)}},x=()=>{i(""),l(!0),r(null)};return c.jsx(hn,{open:e,children:c.jsx(fn,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:v,children:[c.jsxs(mn,{children:[c.jsxs(gn,{className:"flex items-center gap-2",children:[c.jsx(ie.Phone,{className:"h-5 w-5"}),t]}),c.jsx(yn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(xn,{type:"tel",value:o,onChange:T=>p(T.target.value),placeholder:s,className:a?"":"border-red-500",maxLength:14,autoFocus:!0,disabled:u}),!a&&c.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid 10-digit phone number"})]}),c.jsxs(pn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:x,disabled:u,children:"Cancel"}),c.jsx(je,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Kf({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(""),[l,u]=f.useState(!1),d=p=>{const v=p.replace(/\D/g,"");a(v.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 c.jsx(hn,{open:e,children:c.jsx(fn,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:h,children:[c.jsxs(mn,{children:[c.jsxs(gn,{className:"flex items-center gap-2",children:[c.jsx(ie.Shield,{className:"h-5 w-5"}),t]}),c.jsx(yn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(xn,{type:"password",value:i,onChange:p=>d(p.target.value),placeholder:s,className:"text-center text-lg tracking-widest",maxLength:r,autoFocus:!0,disabled:l}),c.jsxs("p",{className:"text-sm text-gray-500 mt-1 text-center",children:["Enter ",r,"-digit PIN"]})]}),c.jsxs(pn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:m,disabled:l,children:"Cancel"}),c.jsx(je,{type:"submit",disabled:i.length!==r||l,children:l?"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(""),[l,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 c.jsx(hn,{open:e,children:c.jsx(fn,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:d,children:[c.jsxs(mn,{children:[c.jsxs(gn,{className:"flex items-center gap-2",children:[c.jsx(ie.Lock,{className:"h-5 w-5"}),t]}),c.jsx(yn,{children:n})]}),c.jsx("div",{className:"py-4",children:c.jsx(xn,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:l})}),c.jsxs(pn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:h,disabled:l,children:"Cancel"}),c.jsx(je,{type:"submit",disabled:!i.trim()||l,children:l?"Submitting...":"Submit"})]})]})})})}function Gf({isOpen:e,title:t,description:n,fields:s,onComplete:r,submitText:o="Submit",cancelText:i="Cancel"}){const[a,l]=f.useState(()=>{const j={};return s.forEach(V=>{j[V.name]=V.value||""}),j}),[u,d]=f.useState({}),[h,m]=f.useState({}),[p,v]=f.useState(!1),x=j=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(j)?null:"Please enter a valid email address",T=j=>j.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",y=(j,V=4)=>j.length===V?null:`PIN must be ${V} digits`,w=j=>{const V=j.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)}`},k=(j,V,z)=>{let N=V,K=null;switch(z.type){case"phone":N=w(V),N.trim()&&(K=T(N));break;case"email":V.trim()&&(K=x(V));break;case"pin":N=V.replace(/\D/g,"").slice(0,6),N.trim()&&(K=y(N));break}!K&&z.validation&&N.trim()&&(K=z.validation(N)),l(Y=>({...Y,[j]:N})),d(Y=>({...Y,[j]:K||""}))},O=()=>{const j={};let V=!0;return s.forEach(z=>{const N=a[z.name]||"";let K=null;if(z.required&&!N.trim())K=`${z.label} is required`;else if(N.trim()){switch(z.type){case"email":K=x(N);break;case"phone":K=T(N);break;case"pin":K=y(N);break}!K&&z.validation&&(K=z.validation(N))}K&&(j[z.name]=K,V=!1)}),d(j),V},E=async j=>{if(j.preventDefault(),!!O()){v(!0);try{const V={};s.forEach(z=>{const N=a[z.name]?.trim();N&&(z.type==="phone"?V[z.name]=N.replace(/\D/g,""):V[z.name]=N)}),r(V)}finally{v(!1)}}},B=()=>{l({}),d({}),m({}),r(null)},_=j=>{m(V=>({...V,[j]:!V[j]}))},M=j=>{switch(j.type){case"password":return h[j.name]?"text":"password";case"email":return"email";case"phone":return"tel";case"pin":case"ssn":return"password";default:return"text"}},R=j=>{if(j.placeholder)return j.placeholder;switch(j.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 ${j.label.toLowerCase()}...`}};return c.jsx(hn,{open:e,children:c.jsx(fn,{showCloseButton:!1,className:"max-w-md",children:c.jsxs("form",{onSubmit:E,children:[c.jsxs(mn,{children:[c.jsx(gn,{children:t}),n&&c.jsx(yn,{children:n})]}),c.jsx("div",{className:"py-4 space-y-4",children:s.map(j=>c.jsxs("div",{children:[c.jsxs("label",{className:"block text-sm font-medium mb-1",children:[j.label,j.required&&c.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),c.jsxs("div",{className:"relative",children:[c.jsx(xn,{type:M(j),value:a[j.name]||"",onChange:V=>k(j.name,V.target.value,j),placeholder:R(j),className:u[j.name]?"border-red-500":"",disabled:p,autoFocus:j===s[0],maxLength:j.type==="pin"?6:j.type==="phone"?14:void 0}),j.type==="password"&&c.jsx("button",{type:"button",onClick:()=>_(j.name),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:p,children:h[j.name]?c.jsx(ie.EyeOff,{className:"h-4 w-4"}):c.jsx(ie.Eye,{className:"h-4 w-4"})})]}),u[j.name]&&c.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[c.jsx(ie.AlertCircle,{className:"h-3 w-3"}),u[j.name]]})]},j.name))}),c.jsxs(pn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:B,disabled:p,children:i}),c.jsx(je,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const hl=f.createContext(void 0);function fl(){const e=f.useContext(hl);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function ml({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(v=>{n(p),o.current=v}),[]),l=f.useCallback(p=>new Promise(v=>{r(p),i.current=v}),[]),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 v=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 c.jsx(Gf,{isOpen:!0,title:s.title,description:s.description,fields:v,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 c.jsx(Xf,{...p});case"email":return c.jsx(qf,{...p});case"phone":return c.jsx(Wf,{...p});case"pin":return c.jsx(Kf,{...p});case"ssn":return c.jsx(_s,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return c.jsx(_s,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return c.jsx(_s,{...p})}},m=f.useMemo(()=>({showSecureModal:a,showSecureForm:l}),[a,l]);return c.jsxs(hl.Provider,{value:m,children:[e,h()]})}function Yf(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 Hf(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 To(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,l=new Map,u=new Map;if(s&&s[1]){const M=s[1],R=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let j;for(;(j=R.exec(M))!==null;)if(j[1]&&j[2]){const V=parseInt(j[1],10),z=j[2].replace(/[.,;:!?]+$/,""),N=z.replace(/\/+$/,"");if(a.has(N)||a.set(N,z),i.has(N)||i.set(N,[]),i.get(N).push(V),!l.has(N))l.set(N,V);else{const K=l.get(N);V<K&&l.set(N,V)}}for(const[V,z]of i.entries()){const N=l.get(V);for(const K of z)K!==N&&u.set(K,N)}for(const[V,z]of l.entries()){const N=a.get(V)||V;r.set(z,N),o.push({number:z,url:N})}}let d,h=t;s&&s[0]&&(d=s[0],h=t.replace(n,""));const m=[];let p=0;const v=/```[\s\S]*?```|`[^`]+`/g;let x;for(;(x=v.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 T=m.map(M=>{if(M.type==="code")return M.content;let R=M.content;return R=R.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(V,z,N)=>{const K=parseInt(z,10),Y=N.replace(/\/+$/,""),le=u.get(K)||K;return l.has(Y)||(l.set(Y,le),r.has(le)||(r.set(le,N),o.push({number:le,url:N}))),`[${le}]`}),R=R.replace(/\[(\d+)\]/g,(V,z)=>{const N=parseInt(z,10);return`[${u.get(N)||N}]`}),R}),y=[];for(const[M,R]of l.entries()){const j=a.get(M)||M,{baseUrl:V,anchor:z}=Yf(j),N=Hf(j);y.push({url:j,baseUrl:V,numbers:[R],anchor:z,title:N})}y.sort((M,R)=>(M.numbers[0]||0)-(R.numbers[0]||0));const w=new Map;let k=1;for(const M of y){const R=M.numbers[0];w.set(R,k),M.numbers=[k],k++}const O=new Map;for(const[M,R]of r.entries()){const j=w.get(M);j&&O.set(j,R)}const E=o.map(M=>{const R=w.get(M.number);return R?{number:R,url:M.url}:M}).filter(M=>w.has(M.number)),B=Array.from(w.entries()).sort((M,R)=>R[0]-M[0]);let _=T.join("");for(const[M,R]of B){const j=new RegExp(`\\[${M}\\](?!\\d)`,"g");_=_.replace(j,`[${R}]`)}return{processedText:_,citations:E.sort((M,R)=>M.number-R.number),citationMap:O,groupedCitations:y,referencesText:d}}function Vn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Vn(t)}catch{return e}if(Array.isArray(e))return e.map(Vn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Vn(s);return t}return e}function Xs(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Vn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Vn(e):{}}function Jf({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:l=800,initiallyExpanded:u=!1,tools:d=[],safeTools:h=[],toolMetadata:m,systemPrompt:p="",tokenEndpoint:v="/api/arcten/token",apiBaseUrl:x="https://api.arcten.com",user:T,state:y,onStateChange:w,allowStateEdits:k=!0,sources:O,ragConfig:E,showCitations:B=!0,sensitiveParams:_,autoDetectSensitive:M=!1}){const{showSecureModal:R}=fl(),j=f.useMemo(()=>E!==void 0?E:O&&O.length>0?{enabled:!0,organizationId:O[0],autoExecute:!0,filters:void 0}:{enabled:!1},[O,E]),[V,z]=f.useState(null),N=f.useRef(null),[K,Y]=f.useState(null),[le,Q]=f.useState(null),ne=f.useRef(null),Z=y!==void 0,[Te,He]=f.useState({}),ke=f.useRef({});Z&&y?ke.current=y:Z||(ke.current=Te);const[Je,zt]=f.useState(!1),[Qr,rt]=f.useState(null),it=f.useRef(!1),[ze,bn]=f.useState(u),[Ue,Ut]=f.useState(i),[_t,Wn]=f.useState(600),[vn,At]=f.useState(!1),[ae,ce]=f.useState(!1),[Ve,Ze]=f.useState(!1),[ue,wn]=f.useState({x:100,y:100}),[Kn,Xt]=f.useState(!1),[Tn,kt]=f.useState({x:0,y:0}),[qt,Sn]=f.useState(!1),ot=f.useRef(null),_e=f.useRef(null),[Mt,jn]=f.useState(""),[Gn,Cs]=f.useState(null),[Cn,Yn]=f.useState("Thinking..."),[Xe,Me]=f.useState(new Set),[Wt,at]=f.useState(""),[De,Hn]=f.useState([]),[Kt,Et]=f.useState(!1),[Gt,Jn]=f.useState([]),[qe,Ie]=f.useState(()=>typeof window<"u"?crypto.randomUUID():null),[mt,pt]=f.useState(!1),[Zn,Yt]=f.useState(!1),[Qn,gt]=f.useState([]),Qe=f.useCallback(async(g,P=3)=>{if(!qe||!N.current)return;const I=async()=>{const L=`${x.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,U=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${N.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:qe,updates:g},format:"json"})});if(!U.ok){if(U.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const ee=await U.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${U.status} ${ee}`)}};for(let $=0;$<P;$++)try{await I(),rt(null);return}catch(L){if($===P-1){const ee=L instanceof Error?L:new Error(String(L));throw rt(ee),console.error("Failed to sync state to Convex after retries:",L),ee}await new Promise(ee=>setTimeout(ee,Math.pow(2,$)*100))}},[qe,x,N]),Nt=f.useMemo(()=>function(){return ke.current},[]),Dt=f.useMemo(()=>async function(P){const I={...ke.current,...P};ke.current=I,Z||He(I),w&&w(I);try{await Qe(P)}catch($){throw $}},[Qe,w,Z]);f.useEffect(()=>{Z&&y&&(ke.current=y)},[Z,y]);const lt=f.useMemo(()=>j?.enabled?async function(P,I=20,$){if(O&&O.length>1){const ee=O.map(G=>fetch(`${x}/search`,{method:"POST",headers:{"Content-Type":"application/json",...N.current?{Authorization:`Bearer ${N.current}`}:{}},body:JSON.stringify({q:P,k:Math.min(I,100),organizationId:G,...Object.keys(U).length>0?{filters:U}:{}})}).then(X=>X.ok?X.json():null)),J=await Promise.all(ee),se=[];for(const G of J)G?.candidates&&se.push(...G.candidates);se.sort((G,X)=>{const xe=G.scores?.rerank||G.scores?.dense||0;return(X.scores?.rerank||X.scores?.dense||0)-xe});const F=se.slice(0,I).map((G,X)=>{const xe=G.citation||G.url;return{rank:X+1,doc_id:G.doc_id,block_id:G.block_id,url:G.url,citation:xe,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:P,total:se.length,results:F,summary:`Found ${se.length} relevant results across ${O.length} source(s) for "${P}". Top result: ${F[0]?.title||"N/A"}`}}const L=j.organizationId&&j.organizationId!=="default"?j.organizationId:void 0,U={...j.filters,...$};try{const ee={q:P,k:Math.min(I,100)};L&&(ee.organizationId=L),Object.keys(U).length>0&&(ee.filters=U);const J={"Content-Type":"application/json"};N.current&&(J.Authorization=`Bearer ${N.current}`);const se=await fetch(`${x}/search`,{method:"POST",headers:J,body:JSON.stringify(ee)});if(!se.ok){const X=await se.text();return{success:!1,error:`Search failed: ${se.status} ${X}`}}const F=await se.json(),G=F.candidates.map((X,xe)=>{const me=X.citation||X.url;return{rank:xe+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:F.query,total:F.total,results:G,summary:`Found ${F.total} relevant results for "${P}". Top result: ${G[0]?.title||"N/A"}`}}catch(ee){return{success:!1,error:ee instanceof Error?ee.message:"Unknown error occurred"}}}:null,[E,x,N]),et=f.useMemo(()=>j?.enabled?async function(P,I){const $=j.organizationId&&j.organizationId!=="default"?j.organizationId:O&&O.length>0?O[0]:void 0;try{const L={"Content-Type":"application/json"};N.current&&(L.Authorization=`Bearer ${N.current}`);const U=await fetch(`${x}/fetch`,{method:"POST",headers:L,body:JSON.stringify({doc_id:P,block_ids:I,...$?{organizationId:$}:{}})});if(!U.ok){const J=await U.text();return{success:!1,error:`Fetch failed: ${U.status} ${J}`}}const ee=await U.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||P}`}}catch(L){return{success:!1,error:L instanceof Error?L.message:"Unknown error occurred"}}}:null,[E,x,N]),ct=f.useMemo(()=>{const g=[...d,...h,Nt];return(!Z||k)&&g.push(Dt),j?.enabled&&(lt&&g.push(lt),et&&g.push(et)),g},[d,h,Nt,Dt,lt,et,Z,k,j]),Pn=f.useMemo(()=>al(ct,m),[ct,m]),b=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:[]}}];(!Z||k)&&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 P=[];return j?.enabled&&P.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...Pn,...g,...P]},[Pn,Z,k,j]),C=f.useMemo(()=>new Set(b.map(g=>g.name)),[b]),S=f.useMemo(()=>b.filter(g=>g.name==="getState"?!0:g.name==="setState"?!Z||k:C.has(g.name)),[b,C,Z,k]),A=f.useMemo(()=>{const g=new Map,P=new Map(Pn.map(I=>[I.name,I]));return g.set("getState",Nt),(!Z||k)&&g.set("setState",Dt),j?.enabled&&(lt&&g.set("searchDocs",lt),et&&g.set("fetchDocContent",et)),ct.forEach(I=>{if(I===Nt||I===Dt||I===lt||I===et)return;const $=I[nt];if($){const U=P.get($);if(U){g.set(U.name,I);return}}const L=b.find(U=>U.name===I.name);L&&g.set(L.name,I)}),g},[ct,b,Nt,Dt,lt,et,Z,k,j]),D=f.useMemo(()=>{const g=new Set;g.add("getState"),g.add("setState"),j?.enabled&&j.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent"));const P=new Map(b.map(I=>[I.name,I]));return h.forEach(I=>{const $=I[nt];if($&&P.has($))g.add($);else{const L=b.find(U=>U.name===I.name);L&&g.add(L.name)}}),g},[h,b,j]),q=["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&&bn(JSON.parse(g));const P=localStorage.getItem("arcten-sidebar-width");P&&Ut(parseInt(P));const I=localStorage.getItem("arcten-sidebar-height");I&&Wn(parseInt(I));const $=localStorage.getItem("arcten-sidebar-detached");$&&ce(JSON.parse($));const L=localStorage.getItem("arcten-sidebar-position");if(L){const ee=JSON.parse(L),J=50,se=Math.max(J-i,Math.min(ee.x,window.innerWidth-J)),F=Math.max(0,Math.min(ee.y,window.innerHeight-J));wn({x:se,y:F})}const U=localStorage.getItem("arcten-sidebar-minimized");U&&Ze(JSON.parse(U)),Sn(!0)}},[]);const H=f.useMemo(()=>T,[T?.id]);f.useEffect(()=>((async()=>{try{const P=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:H})});if(!P.ok)throw new Error("Failed to fetch token");const I=await P.json();z(I.clientToken),N.current=I.clientToken,Q(I.expiresAt),Y(null)}catch(P){Y(P instanceof Error?P.message:"Failed to fetch token")}})(),()=>{ne.current&&clearTimeout(ne.current)}),[v,H]),f.useEffect(()=>{if(!le)return;ne.current&&clearTimeout(ne.current);const g=Math.floor(Date.now()/1e3),P=le-g,$=Math.max(0,P-5);return ne.current=setTimeout(async()=>{try{const L=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:H})});if(!L.ok)throw new Error("Failed to refresh token");const U=await L.json();z(U.clientToken),N.current=U.clientToken,Q(U.expiresAt),Y(null)}catch(L){console.error("Token refresh failed:",L),Y(L instanceof Error?L.message:"Failed to refresh token")}},$*1e3),()=>{ne.current&&clearTimeout(ne.current)}},[le,v,H]),f.useEffect(()=>{(async()=>{if(ct.length!==0)try{const P=ct.map($=>({name:$.name,code:$.toString()})),I=await fetch(`${x}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:P})});if(I.ok){const $=await I.json();Hn($.tools)}}catch(P){console.error("Failed to fetch tool descriptions:",P)}})()},[ct]),f.useEffect(()=>{Promise.resolve().then(()=>Rf).then(g=>{Cs(()=>g.Response)})},[]),f.useEffect(()=>{const g=()=>{at(window.location.pathname)};g(),window.addEventListener("popstate",g);const P=setInterval(g,500);return()=>{window.removeEventListener("popstate",g),clearInterval(P)}},[]);const pe=f.useCallback(async()=>{if(!(!H?.id||!V)){Yt(!0);try{const P=await(await fetch(`${x}/conversations`,{headers:{Authorization:`Bearer ${V}`}})).json();Jn(P.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{Yt(!1)}}},[H?.id,V,x]);f.useEffect(()=>{H?.id&&V&&pe()},[H?.id,V,pe]);function ge(g){const P=Math.floor((Date.now()-g)/1e3);return P<60?"now":P<3600?`${Math.floor(P/60)}m`:P<86400?`${Math.floor(P/3600)}h`:`${Math.floor(P/86400)}d`}function Ee(){const g=crypto.randomUUID();Ie(g),We([]),gt([]),pt(!1);const P=Z?y||{}:{};ke.current=P,Z||He(P),w&&w(P),it.current=!1}async function re(g){if(V)try{await fetch(`${x}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${V}`}}),Jn(Gt.filter(P=>P._id!==g)),g===qe&&Ee()}catch(P){console.error("Failed to delete conversation:",P)}}async function te(g){Ie(g.chatId),pt(!1),Yt(!0);try{const P=await fetch(`${x}/conversations/${g.chatId}/messages`,{headers:{Authorization:`Bearer ${N.current}`}});if(!P.ok)throw new Error(`Failed to fetch messages: ${P.statusText}`);const $=(await P.json()).messages||[];We($),gt($)}catch(P){console.error("Failed to load conversation messages:",P);const I=g.messages||[];We(I),gt(I)}finally{Yt(!1)}}const ut=async(g,P={})=>{const I=P.headers?new Headers(P.headers):new Headers;return I.delete("user-agent"),I.delete("User-Agent"),fetch(g,{...P,headers:I})},{messages:Re,sendMessage:es,status:Ce,error:Ht,stop:yt,addToolResult:ve,setMessages:We}=So.useChat({id:qe||void 0,transport:new ms.DefaultChatTransport({api:`${x}/chat`,fetch:ut,headers:()=>{const g={};return N.current&&(g.Authorization=`Bearer ${N.current}`),g},body:()=>({tools:S.map(P=>({name:P.name,description:P.description,inputSchema:P.jsonSchema})),systemPrompt:p,currentRoute:Wt,state:ke.current})}),sendAutomaticallyWhen:ms.lastAssistantMessageIsCompleteWithToolCalls});f.useEffect(()=>{const g=Re[Re.length-1];if(!g||g.role!=="assistant")return;const P=g.parts?.filter(I=>I.type?.startsWith("tool-")&&I.state==="input-available"&&typeof I.toolCallId=="string"&&I.input!==void 0)||[];for(const I of P){const $=I,L=$.type?.replace("tool-","")||"",U=$.toolCallId;if(D.has(L)){if(Xe.has(U))continue;Me(J=>J.has(U)?J:new Set(J).add(U)),(async()=>{try{const J=A.get(L);if(!J){console.warn(`[ArctenAgent] Tool ${L} not found in toolsMap. Available tools:`,Array.from(A.keys())),ve({toolCallId:U,tool:L,output:`Error: Tool ${L} not found`}),Me(X=>{const xe=new Set(X);return xe.delete(U),xe});return}const se=Xs($.input),F=S.find(X=>X.name===L);let G;if(F&&F.jsonSchema?.properties){const xe=Object.keys(F.jsonSchema.properties).map(me=>se[me]);console.log(`[ArctenAgent] Executing safe tool ${L} with args:`,xe),G=await J(...xe)}else if(L==="getState")G=J();else if(L==="setState"){const X=se.updates||se;G=await J(X)}else G=await J(...Object.values(se));console.log(`[ArctenAgent] Tool ${L} completed, result:`,G),ve({toolCallId:U,tool:L,output:G}),Me(X=>{const xe=new Set(X);return xe.delete(U),xe})}catch(J){console.error(`[ArctenAgent] Error executing safe tool ${L}:`,J),ve({toolCallId:U,tool:L,output:`Error: ${J instanceof Error?J.message:String(J)}`}),Me(se=>{const F=new Set(se);return F.delete(U),F})}})()}}},[Re,D,A,S,ve]),f.useEffect(()=>{if(!qe||!N.current)return;(async()=>{zt(!0),rt(null);try{const I=`${x.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,$=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${N.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:qe},format:"json"})});if(!$.ok){if($.status===404||$.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${$.status}), using empty state`);const F=Z?y||{}:{};ke.current=F,Z||He(F),w&&w(F),it.current=!0,zt(!1);return}const se=await $.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${$.status} ${se}`)}const U=(await $.json())?.value||{},ee=!it.current;let J;ee?(J={...Z?y||{}:{},...U},it.current=!0):J=U,ke.current=J,Z||He(J),w&&w(J)}catch(P){P instanceof TypeError&&P.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",P):console.error("[ArctenAgent] Failed to fetch state:",P);const $=P instanceof Error?P:new Error(String(P));if(rt($),!it.current){const L=Z?y||{}:{};ke.current=L,Z||He(L),w&&w(L),it.current=!0}}finally{zt(!1)}})()},[qe,x,Z,y,w]),f.useEffect(()=>{ze&&_e.current&&_e.current.focus()},[ze,Re]);function tt(){bn(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ps(){bn(!1),localStorage.setItem("arcten-sidebar-expanded","false")}f.useEffect(()=>{},[ze]),f.useEffect(()=>{ot.current&&ot.current.scrollIntoView({behavior:"smooth"})},[Re]),f.useEffect(()=>{function g(P){P.key==="Escape"&&(Ce==="streaming"||Ce==="submitted")&&(P.preventDefault(),yt())}return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Ce,yt]);function ts(){const g=crypto.randomUUID();Ie(g),We([]),gt([]),pt(!1)}function ei(g){if(g.preventDefault(),!Mt.trim())return;(Ce==="streaming"||Ce==="submitted")&&yt();const P=q[Math.floor(Math.random()*q.length)]||"Thinking...";Yn(P),es({text:Mt}),jn("")}function vl(g){const P=g.target.value;jn(P)}f.useEffect(()=>{if(!vn)return;function g(I){if(ae){const $=I.clientX-ue.x,L=I.clientY-ue.y;$>=a&&$<=l&&Ut($),L>=400&&L<=1e3&&Wn(L)}else{const $=window.innerWidth-I.clientX;$>=a&&$<=l&&Ut($)}}function P(){At(!1),localStorage.setItem("arcten-sidebar-width",Ue.toString()),localStorage.setItem("arcten-sidebar-height",_t.toString())}return window.addEventListener("mousemove",g),window.addEventListener("mouseup",P),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",P)}},[vn,Ue,_t,ae,ue,a,l]);function wl(g){g.preventDefault(),At(!0)}function Tl(){ce(!0),Ze(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Sl(){ce(!1),Ze(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function ti(){Ze(!Ve),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ve))}function jl(g){ae&&(Xt(!0),kt({x:g.clientX-ue.x,y:g.clientY-ue.y}))}return f.useEffect(()=>{if(!ae)return;function g(){wn(P=>{const $=window.innerWidth-50,L=window.innerHeight-50,U=50-Ue,ee=0,J=Math.max(U,Math.min(P.x,$)),se=Math.max(ee,Math.min(P.y,L));if(J!==P.x||se!==P.y){const F={x:J,y:se};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(F)),F}return P})}return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[ae,Ue]),f.useEffect(()=>{if(!Kn)return;function g(I){const $=I.clientX-Tn.x,L=I.clientY-Tn.y,U=50,ee=window.innerWidth-U,J=window.innerHeight-U,se=U-Ue,F=0,G=Math.max(se,Math.min($,ee)),X=Math.max(F,Math.min(L,J));wn({x:G,y:X})}function P(){Xt(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(ue))}return window.addEventListener("mousemove",g),window.addEventListener("mouseup",P),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",P)}},[Kn,Tn,ue,Ue]),qt?K?c.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:c.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",K]})}):V?c.jsx(qu,{features:Tf,children:c.jsx(os,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:ae?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:ae?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
20
- ${ae?"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"}
22
- ${ae?"border border-border":"border-l border-border"}
23
- ${ze?"":"w-[30px]"}
24
- `,style:ze?ae?{width:`${Ue}px`,height:Ve?"auto":`${_t}px`,left:`${ue.x}px`,top:`${ue.y}px`}:{width:`${Ue}px`}:void 0,onClick:ze?void 0:tt,children:ze?c.jsxs(c.Fragment,{children:[!ae&&c.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:wl,children:c.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),ae&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:g=>{g.preventDefault(),At(!0)}}),c.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(),Xt(!0),kt({x:g.clientX-ue.x,y:g.clientY-ue.y})},children:c.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"})}),c.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:g=>{g.preventDefault(),At(!0)}})]}),c.jsxs("div",{className:"flex flex-col h-full",children:[c.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${ae?"cursor-move":""}`,onMouseDown:ae?jl:void 0,children:[c.jsx("h2",{className:`text-base font-semibold ${ae&&Ve?"cursor-pointer":""}`,onClick:ae&&Ve?g=>{g.stopPropagation(),ti()}:void 0,children:r}),c.jsxs("div",{className:"flex items-center gap-1",onClick:g=>g.stopPropagation(),children:[c.jsxs(vt,{children:[c.jsx(wt,{asChild:!0,children:c.jsx("button",{type:"button",className:oe(Vt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ts,"aria-label":"New chat",children:c.jsx(ie.Plus,{className:"h-4 w-4"})})}),c.jsx(Tt,{children:"Start a new conversation"})]}),c.jsxs(vt,{children:[c.jsx(wt,{asChild:!0,children:c.jsx("button",{type:"button",className:oe(Vt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ae?Sl:Tl,"aria-label":ae?"Dock sidebar":"Float sidebar",children:ae?c.jsx(ie.Dock,{className:"h-4 w-4"}):c.jsx(ie.PictureInPicture2,{className:"h-4 w-4"})})}),c.jsx(Tt,{children:ae?"Dock to sidebar":"Undock to floating window"})]}),c.jsxs(vt,{children:[c.jsx(wt,{asChild:!0,children:c.jsx("button",{type:"button",className:oe(Vt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ae?ti:Ps,"aria-label":ae?Ve?"Maximize":"Minimize":"Close sidebar",children:ae?Ve?c.jsx(ie.Maximize2,{className:"h-4 w-4"}):c.jsx(ie.Minimize2,{className:"h-4 w-4"}):c.jsx(ie.X,{className:"h-4 w-4"})})}),c.jsx(Tt,{children:ae?Ve?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ve&&c.jsxs(c.Fragment,{children:[T&&Gt.length>0&&c.jsxs("div",{className:`border-b border-border ${mt?"flex flex-col flex-1":""}`,children:[c.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[c.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),c.jsx(je,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{mt||pe(),pt(!mt)},children:mt?"Show less":"View all"})]}),c.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${mt?"flex-1 overflow-y-auto":""}`,children:Gt.slice(0,mt?void 0:3).map(g=>c.jsxs("div",{className:"group relative",children:[c.jsxs(Sf,{type:"button",className:oe(Vt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>te(g),children:[c.jsx("span",{className:"text-xs truncate",children:g.title}),c.jsx("div",{className:"ml-2 flex items-center",children:c.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:ge(g.updatedAt)})})]}),c.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:P=>{P.stopPropagation(),re(g._id)},"aria-label":"Delete conversation",children:c.jsx(ie.X,{className:"h-3 w-3"})})]},g._id))})]}),c.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[c.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Re.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&c.jsx("div",{className:"mb-6",children:o}),c.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),De.length>0&&c.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:c.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(Kt?De:De.slice(0,10)).map(g=>c.jsxs(vt,{children:[c.jsx(wt,{asChild:!0,children:c.jsx(As,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{jn(g.sampleUsage),_e.current?.focus()},children:g.friendlyName})}),c.jsx(Tt,{children:c.jsxs("div",{className:"max-w-xs",children:[c.jsx("p",{className:"font-medium",children:g.description}),c.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[c.jsx("span",{className:"font-medium",children:"Example:"}),' "',g.sampleUsage,'"']}),g.paramCount>0&&c.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[c.jsx("span",{className:"font-medium",children:"Parameters:"})," ",g.params.join(", ")]})]})})]},g.name)),De.length>10&&!Kt&&c.jsxs(vt,{children:[c.jsx(wt,{asChild:!0,children:c.jsxs(As,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Et(!0),children:["+",De.length-10," more"]})}),c.jsx(Tt,{children:c.jsxs("div",{className:"max-w-xs",children:[c.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),c.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:De.slice(10).map(g=>c.jsxs("div",{children:[c.jsxs("span",{className:"font-medium text-xs",children:[g.friendlyName,":"]}),c.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:g.description})]},g.name))}),c.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),Kt&&De.length>10&&c.jsx(As,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Et(!1),children:"Show less"})]})})]}):c.jsxs(c.Fragment,{children:[Re.map(g=>{const I=g.parts.filter(F=>F.type==="text").map(F=>F.text).join("");let $=g.parts;g.role==="assistant"&&g.parts.some(G=>G.timestamp)&&($=[...g.parts].sort((G,X)=>{const xe=G.timestamp||0,me=X.timestamp||0;return xe-me}));let L=[],U=new Map,ee=[],J,se=!0;if(g.role==="assistant"){const F=$.filter(me=>me.type==="text"&&me.text),G=[],X=[];F.forEach(me=>{const{citations:xt,citationMap:Pe,groupedCitations:Oe,referencesText:bt}=To(me.text);L.push(...xt),G.push(Pe),Oe&&X.push(...Oe),bt&&(J=bt)}),G.forEach(me=>{me.forEach((xt,Pe)=>{U.has(Pe)||U.set(Pe,xt)})}),ee=Array.from(new Map(X.map(me=>[me.url,me])).values()).sort((me,xt)=>(me.numbers[0]||0)-(xt.numbers[0]||0)),se=!(Ce==="streaming"&&g.id===Re.at(-1)?.id)}return c.jsx("div",{className:`${g.role==="user"?"flex justify-end":"w-full"}`,children:c.jsx("div",{className:`${g.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:g.role==="user"?c.jsx(jf,{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}):c.jsx("div",{className:"space-y-2",children:$.map((F,G)=>{if(F.type?.startsWith("tool-")){const X=F.type?.replace("tool-","")||"",xe=S.find(Pe=>Pe.name===X),me=F.state==="input-available",xt=F.state==="output-available";if(me&&D.has(X),me){if(D.has(X))return null;const Pe=Xs(F.input);return c.jsx(os,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:c.jsx(Af,{toolName:X,description:xe?.description||"",args:Pe,onApprove:async()=>{if(Xe.has(F.toolCallId))return;Me(bt=>new Set(bt).add(F.toolCallId));const Oe=A.get(X);if(Oe)try{const bt=await Oe(...Object.values(Pe));ve({toolCallId:F.toolCallId,tool:X,output:bt})}catch(bt){ve({toolCallId:F.toolCallId,tool:X,output:`Error: ${bt}`})}},onDeny:async()=>{Xe.has(F.toolCallId)||(Me(Oe=>new Set(Oe).add(F.toolCallId)),ve({toolCallId:F.toolCallId,tool:X,output:"User denied tool execution"}))}})},`${F.toolCallId}-${G}`)}else if(xt){const Pe=F.output==="User denied tool execution",Oe=Xs(F.input);return c.jsx(kf,{toolName:X,args:Oe,isDenied:Pe,isSafe:D.has(X)},`${F.toolCallId}-${G}`)}return null}if(F.type==="text"&&F.text&&Gn){const{processedText:X}=To(F.text),Pe=!$.slice(G+1).some(Oe=>Oe.type==="text"&&Oe.text)&&se&&U.size>0;return c.jsx(zf,{text:X,citations:L,citationMap:U,groupedCitations:Pe?ee:void 0,referencesText:Pe?J:void 0,ResponseComponent:Gn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:B,showReferences:Pe},`${g.id}-${G}`)}return F.type==="reasoning"&&F.text?c.jsxs(cl,{className:"w-full",isStreaming:Ce==="streaming"&&G===g.parts.length-1&&g.id===Re.at(-1)?.id,children:[c.jsx(ul,{}),c.jsx(dl,{children:F.text})]},`${g.id}-${G}`):null})})})},g.id)}),c.jsx("div",{ref:ot})]})}),Ht&&c.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Ht.message]}),c.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[c.jsx(Xu,{mode:"wait",children:(Ce==="streaming"||Ce==="submitted")&&c.jsxs(os,{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:[c.jsx(os,{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]}}),c.jsx("p",{className:"text-xs text-muted-foreground",children:Cn})]})}),c.jsxs("form",{onSubmit:ei,className:"relative",children:[c.jsx(Po,{ref:_e,value:Mt,onChange:vl,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(),ei(g))}}),Ce==="streaming"||Ce==="submitted"?c.jsxs(vt,{children:[c.jsx(wt,{asChild:!0,children:c.jsx("button",{type:"button",className:oe(Vt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:yt,children:c.jsx(ie.Square,{className:"h-4 w-4"})})}),c.jsxs(Tt,{children:[c.jsx(ri,{children:"Escape"})," to stop"]})]}):c.jsxs(vt,{children:[c.jsx(wt,{asChild:!0,children:c.jsx("button",{type:"submit",className:oe(Vt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Mt.trim(),children:c.jsx(ie.ArrowRight,{className:"h-4 w-4"})})}),c.jsxs(Tt,{children:[c.jsx(ri,{children:"Enter"})," to send"]})]})]})]})]}),c.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:[c.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),c.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),c.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):c.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[c.jsx(ie.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),c.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):c.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:c.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function Zf(e){return c.jsx(ml,{children:c.jsx(Jf,{...e})})}const Qf={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 Mn(e){for(const[t,n]of Object.entries(Qf))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function pl(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 gl(e,t,n){const s=Object.keys(n).length,r=t.length;return r>=3||s>=2||s>0&&s<r}function em(e,t,n,s={}){const r=[];return new Set([...t,...Object.keys(n)]).forEach(i=>{const a=i in n,l=n[i];if(!a&&s[i]!==void 0)return;const u=tm(s[i]),d={name:i,type:nm(l||Mn(i)||"text"),label:yl(i),placeholder:sm(i,l),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 l=i.name in n,u=a.name in n;return l===u?0:l?1:-1}),{shouldUseForm:gl(e,t,n),fields:r,title:rm(e),description:im(e,r.length)}}function tm(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function nm(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 yl(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function sm(e,t){return t?pl(t,e).placeholder:`Enter ${yl(e).toLowerCase()}...`}function rm(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function im(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 In(e){if(typeof e=="string")try{const t=JSON.parse(e);return In(t)}catch{return e}if(Array.isArray(e))return e.map(In);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=In(s);return t}return e}function om(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 am(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return In(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?In(e):{}}const hs="__secureOutput",fs="[hidden for privacy]";function lm(e){if(typeof globalThis.structuredClone=="function")return globalThis.structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn("[useAgent] Failed to clone value for redaction:",t),e}}function cm(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function um(e,t){if(t.length===0)return e;if(!e||typeof e!="object")return;let n=e;for(const s of t){if(!n||typeof n!="object")return;n=n[s]}return n}function dm(e,t,n){if(!e||typeof e!="object"||t.length===0)return!1;let s=e;for(let o=0;o<t.length-1;o++){if(!s||typeof s!="object")return!1;const i=s,a=t[o];if(a===void 0)return!1;const l=i[a];if(l==null||typeof l!="object")return!1;s=l}if(!s)return!1;const r=t[t.length-1];return!r||!(r in s)?!1:(s[r]=n,!0)}function mr(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function xl(e,t=""){const n={};return e&&typeof e=="object"?Object.entries(e).forEach(([s,r])=>{const o=t?`${t}.${s}`:s;n[o]=mr(r),r&&typeof r=="object"&&Object.assign(n,xl(r,o))}):t&&(n[t]=mr(e)),n}function hm(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:fs,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:fs,includeFieldStatus:!1,preserve:[]};const t=e.strategy??(e.fields&&e.fields.length>0?"fields":"full");return{strategy:t,fields:t==="fields"?e.fields??[]:[],placeholder:e.placeholder??fs,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function fm(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=hm(s);r&&(t[n]=r)}return t}function bl(e,t,n){const s=n.placeholder,r={tool:e,redacted:!0,strategy:n.strategy,placeholder:s};if(n.strategy==="full"){n.includeFieldStatus&&typeof t=="object"&&t!==null&&(r.fieldStatus=xl(t)),r.redactedFields=["*"];let l={};return n.preserve.length>0&&t&&typeof t=="object"&&n.preserve.forEach(u=>{u in t&&(l[u]=t[u])}),l[hs]=r,l}if(n.fields.includes("*"))return bl(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[hs]:{...r,redactedFields:n.fields}};const o=lm(t),i=[],a={};return n.fields.forEach(l=>{const u=cm(l);if(u.length===0)return;const d=um(o,u),h=mr(d);a[l]=h,dm(o,u,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[hs]=r,o}function mm({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:l,sensitiveOutputs:u,autoDetectSensitive:d=!1,autoFormGeneration:h=!1,formMode:m="auto",systemPrompt:p="",initialMessages:v=[],conversationId:x,state:T,onStateChange:y,allowStateEdits:w=!0,onToolCall:k,onFinish:O,sources:E,ragConfig:B,ragFilters:_,secureInputHandler:M}={}){const R=f.useMemo(()=>B!==void 0?B:_?{enabled:!0,filters:_}:E&&E.length>0?{enabled:!0,organizationId:E[0],autoExecute:!0,filters:void 0}:{enabled:!1},[E,B,_]),j=f.useMemo(()=>{const b={};if(l)for(const[C,S]of Object.entries(l))if(b[C]={},Array.isArray(S))for(const A of S){const D=Mn(A);b[C][A]=D||"text"}else for(const[A,D]of Object.entries(S))b[C][A]=D;if(a){for(const[C,S]of Object.entries(a))if(S&&typeof S=="object"&&"sensitiveParams"in S){b[C]||(b[C]={});const A=S.sensitiveParams;if(Array.isArray(A))for(const D of A){const q=Mn(D);b[C][D]=q||"text"}else if(A&&typeof A=="object")for(const[D,q]of Object.entries(A))b[C][D]=q}}return b},[l,a,d]),V=f.useMemo(()=>fm(u),[u]),z=f.useCallback((b,C)=>{const S=V[b];if(!S)return C;try{return bl(b,C,S)}catch(A){return console.error(`[useAgent] Failed to redact output for ${b}:`,A),{value:fs,[hs]:{tool:b,redacted:!0,error:String(A)}}}},[V]),[N,K]=f.useState(n||null),Y=f.useRef(n||null),[le,Q]=f.useState(null),[ne,Z]=f.useState(null),Te=f.useRef(null),[He,ke]=f.useState([]),[Je,zt]=f.useState(x||(typeof window<"u"?crypto.randomUUID():null)),[Qr,rt]=f.useState(!1),[it,ze]=f.useState(new Set),[bn,Ue]=f.useState(new Map),[Ut,_t]=f.useState(new Map),[Wn,vn]=f.useState(new Map),[At,ae]=f.useState(new Map),ce=T!==void 0,[Ve,Ze]=f.useState({}),ue=f.useRef({}),wn=ce?T||{}:Ve;ce&&T?ue.current=T:ce||(ue.current=Ve);const[Kn,Xt]=f.useState(!1),[Tn,kt]=f.useState(null),qt=f.useRef(!1),Sn=f.useCallback(async(b,C=3)=>{if(!Je||!Y.current)return;const S=async()=>{const D=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,q=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Je,updates:b},format:"json"})});if(!q.ok){if(q.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const H=await q.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${q.status} ${H}`)}};for(let A=0;A<C;A++)try{await S(),kt(null);return}catch(D){if(A===C-1){const H=D instanceof Error?D:new Error(String(D));throw kt(H),console.error("Failed to sync state to Convex after retries:",D),H}await new Promise(H=>setTimeout(H,Math.pow(2,A)*100))}},[Je,e,Y]),ot=f.useMemo(()=>function(){return ue.current},[]),_e=f.useMemo(()=>async function(C){const S={...ue.current,...C};ue.current=S,ce||Ze(S),y&&y(S);try{await Sn(C)}catch(A){throw A}},[Sn,y,ce]);f.useEffect(()=>{ce&&T&&(ue.current=T)},[ce,T]);const Mt=f.useCallback(b=>M?M.showSecureModal(b):new Promise(C=>{Ue(S=>new Map(S).set(b.id,b)),_t(S=>new Map(S).set(b.id,C))}),[M]),jn=f.useCallback((b,C)=>{if(M)return;const S=Ut.get(b);S&&(S(C),Ue(A=>{const D=new Map(A);return D.delete(b),D}),_t(A=>{const D=new Map(A);return D.delete(b),D}))},[Ut,M]),Gn=f.useCallback(b=>M?M.showSecureForm(b):new Promise(C=>{vn(S=>new Map(S).set(b.id,b)),ae(S=>new Map(S).set(b.id,C))}),[M]),Cs=f.useCallback((b,C)=>{if(M)return;const S=At.get(b);S&&(S(C),vn(A=>{const D=new Map(A);return D.delete(b),D}),ae(A=>{const D=new Map(A);return D.delete(b),D}))},[At,M]),Cn=f.useCallback((b,C)=>{const S=j[b]||{},A=Object.keys(S).length>0;if(d){const D=Object.keys(C).filter(q=>Mn(q)!==null);return A||D.length>0}return A},[j,d]),Yn=f.useCallback((b,C)=>{const A={...j[b]||{}};if(d){for(const q of Object.keys(C))if(!(q in A)){const H=Mn(q);H&&(A[q]=H)}}const D=Object.entries(A).filter(([q])=>Object.prototype.hasOwnProperty.call(C,q));return D.length>0?Object.fromEntries(D):A},[j,d]),Xe=f.useMemo(()=>R?.enabled?async function(C,S=20,A){const D={...R.filters,...A};if(E&&E.length>1){const H=E.map(re=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...Y.current?{Authorization:`Bearer ${Y.current}`}:{}},body:JSON.stringify({q:C,k:Math.min(S,100),organizationId:re,...Object.keys(D).length>0?{filters:D}:{}})}).then(te=>te.ok?te.json():null)),pe=await Promise.all(H),ge=[];for(const re of pe)re?.candidates&&ge.push(...re.candidates);ge.sort((re,te)=>{const ut=re.scores?.rerank||re.scores?.dense||0;return(te.scores?.rerank||te.scores?.dense||0)-ut});const Ee=ge.slice(0,S).map((re,te)=>{const ut=re.citation||re.url;return{rank:te+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:C,total:ge.length,results:Ee,summary:`Found ${ge.length} relevant results across ${E.length} source(s) for "${C}". Top result: ${Ee[0]?.title||"N/A"}`}}const q=R.organizationId&&R.organizationId!=="default"?R.organizationId:E&&E.length>0?E[0]:void 0;try{const H={q:C,k:Math.min(S,100)};q&&(H.organizationId=q),Object.keys(D).length>0&&(H.filters=D);const pe={"Content-Type":"application/json"};Y.current&&(pe.Authorization=`Bearer ${Y.current}`);const ge=await fetch(`${e}/search`,{method:"POST",headers:pe,body:JSON.stringify(H)});if(!ge.ok){const te=await ge.text();return{success:!1,error:`Search failed: ${ge.status} ${te}`}}const Ee=await ge.json(),re=Ee.candidates.map((te,ut)=>{const Re=te.citation||te.url;return{rank:ut+1,doc_id:te.doc_id,block_id:te.block_id,url:te.url,citation:Re,title:te.title||"Untitled",snippet:te.snippet,score:te.scores?.rerank||te.scores?.dense||0,metadata:{site:te.metadata?.site,lang:te.metadata?.lang,contentType:te.metadata?.content_type}}});return{success:!0,query:Ee.query,total:Ee.total,results:re,summary:`Found ${Ee.total} relevant results for "${C}". Top result: ${re[0]?.title||"N/A"}`}}catch(H){return{success:!1,error:H instanceof Error?H.message:"Unknown error occurred"}}}:null,[R,e,Y]),Me=f.useMemo(()=>R?.enabled?async function(C,S){const A=R.organizationId&&R.organizationId!=="default"?R.organizationId:E&&E.length>0?E[0]:void 0;try{const D={"Content-Type":"application/json"};Y.current&&(D.Authorization=`Bearer ${Y.current}`);const q=await fetch(`${e}/fetch`,{method:"POST",headers:D,body:JSON.stringify({doc_id:C,block_ids:S,...A?{organizationId:A}:{}})});if(!q.ok){const pe=await q.text();return{success:!1,error:`Fetch failed: ${q.status} ${pe}`}}const H=await q.json();return{success:!0,blocks:H.blocks||[],fullContent:H.fullContent||"",pageUrl:H.pageUrl||"",pageTitle:H.pageTitle||"",summary:`Fetched ${H.blocks?.length||0} blocks from ${H.pageTitle||C}`}}catch(D){return{success:!1,error:D instanceof Error?D.message:"Unknown error occurred"}}}:null,[R,e,Y]),Wt=f.useMemo(()=>{const b=[...o,...i,ot];return(!ce||w)&&b.push(_e),R?.enabled&&(Xe&&b.push(Xe),Me&&b.push(Me)),b},[o,i,ot,_e,Xe,Me,R,ce,w]),at=f.useMemo(()=>al(Wt,a),[Wt,a]),De=f.useMemo(()=>{const b=new Map,C=new Map(at.map(S=>[S.name,S]));return b.set("getState",ot),(!ce||w)&&b.set("setState",_e),R?.enabled&&(Xe&&b.set("searchDocs",Xe),Me&&b.set("fetchDocContent",Me)),Wt.forEach(S=>{if(S===ot||S===_e||S===Xe||S===Me)return;const A=S[nt];if(A){const q=C.get(A);if(q){b.set(q.name,S);return}}const D=at.find(q=>q.name===S.name);D&&b.set(D.name,S)}),b},[Wt,at,ot,_e,Xe,Me,R,ce,w]),Hn=f.useMemo(()=>new Set(at.map(b=>b.name)),[at]),Kt=f.useMemo(()=>{const b=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!ce||w)&&b.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 R?.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"]}}),[...at,...b,...C]},[at,R,ce,w]),Et=f.useMemo(()=>Kt.filter(b=>b.name==="getState"?!0:b.name==="setState"?!ce||w:R?.enabled&&(b.name==="searchDocs"||b.name==="fetchDocContent")?!0:Hn.has(b.name)),[Kt,Hn,ce,w,R]),Gt=f.useMemo(()=>{const b=new Set;return b.add("getState"),b.add("setState"),R?.enabled&&R.autoExecute!==!1&&(b.add("searchDocs"),b.add("fetchDocContent")),i.forEach(C=>{for(const[S,A]of De.entries())if(A===C){b.add(S);break}}),b},[i,De,R]);f.useEffect(()=>s||n?void 0:((async()=>{try{const C=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!C.ok)throw new Error("Failed to fetch token");const S=await C.json();K(S.clientToken),Y.current=S.clientToken,Z(S.expiresAt),Q(null)}catch(C){console.error("[useAgent] Token fetch failed:",C),Q(C instanceof Error?C.message:"Failed to fetch token")}})(),()=>{Te.current&&clearTimeout(Te.current)}),[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!ne||s||n)return;Te.current&&clearTimeout(Te.current);const b=Math.floor(Date.now()/1e3),C=ne-b,A=Math.max(0,C-5);return Te.current=setTimeout(async()=>{try{const D=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!D.ok)throw new Error("Failed to refresh token");const q=await D.json();K(q.clientToken),Y.current=q.clientToken,Z(q.expiresAt),Q(null)}catch(D){console.error("[useAgent] Token refresh failed:",D),Q(D instanceof Error?D.message:"Failed to refresh token")}},A*1e3),()=>{Te.current&&clearTimeout(Te.current)}},[ne,t,JSON.stringify(r),s,n]);const Jn=async(b,C={})=>{const S=C.headers?new Headers(C.headers):new Headers;S.delete("user-agent"),S.delete("User-Agent"),console.log("[useAgent] Making request to:",b),console.log("[useAgent] Method:",C.method||"GET"),console.log("[useAgent] Has Authorization header:",S.has("Authorization")),console.log("[useAgent] Client token available:",!!Y.current);try{const A=await fetch(b,{...C,headers:S});if(!A.ok){console.error("[useAgent] Request failed:",A.status,A.statusText);const D=await A.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",D)}return A}catch(A){throw console.error("[useAgent] Fetch error:",A),A}},qe=`${e}/chat`;console.log("[useAgent] Chat API URL:",qe);const{messages:Ie,sendMessage:mt,status:pt,error:Zn,stop:Yt,addToolResult:Qn,setMessages:gt}=So.useChat({id:Je||void 0,messages:v,transport:new ms.DefaultChatTransport({api:qe,fetch:Jn,headers:()=>{const b={};return Y.current?(b.Authorization=`Bearer ${Y.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),b},body:()=>{const b=Et.map(A=>({name:A.name,description:A.description,inputSchema:A.jsonSchema})),C=b.filter(A=>A.name==="getState"||A.name==="setState").map(A=>A.name),S=b.filter(A=>A.name==="searchDocs"||A.name==="fetchDocContent").map(A=>A.name);return C.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",C),S.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",S):R?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:b,systemPrompt:p,state:ue.current,..._&&{ragFilters:_}}}}),sendAutomaticallyWhen:ms.lastAssistantMessageIsCompleteWithToolCalls}),Qe=f.useCallback((b,C,S)=>{const A=z(b,S);Qn({toolCallId:C,tool:b,output:A})},[Qn,z]);f.useEffect(()=>{Ie.forEach(b=>{b.role==="assistant"&&b.parts.forEach(C=>{if(!C.type?.startsWith("tool-")||C.state!=="input-available")return;const S=C.type.replace("tool-",""),A=C.toolCallId;if(it.has(A))return;ze(q=>new Set(q).add(A));const D=am(C.input);if(Cn(S,D)){const q=Yn(S,D),H=Object.entries(q).filter(([te])=>D[te]!==void 0),pe=H.length>0?Object.fromEntries(H):q,ge=Object.keys(pe),Ee=ge.length>0?ge:Object.keys(D),re=om(D,pe);(async()=>{try{let te={};const ut=[...new Set([...Ee,...ge])];if(h&&(m==="batch"||m==="auto"&&gl(S,ut,q))){const ve=em(S,Ee,pe,D),We={id:`${A}-form`,toolName:S,toolCallId:A,title:ve.title,description:ve.description,fields:ve.fields},tt=await Gn(We);if(tt===null){Qe(S,A,"User cancelled secure input");return}te=tt}else for(const[ve,We]of Object.entries(pe)){const tt=pl(We,ve),Ps={id:`${A}-${ve}`,type:We,paramName:ve,toolName:S,toolCallId:A,title:tt.title,description:tt.description,placeholder:tt.placeholder},ts=await Mt(Ps);if(ts===null){Qe(S,A,"User cancelled secure input");return}te[ve]=ts}const es={...re,...te},Ce=De.get(S);if(!Ce)throw new Error(`Tool ${S} not found`);let Ht;const yt=Et.find(ve=>ve.name===S);if(yt&&yt.jsonSchema?.properties){const We=Object.keys(yt.jsonSchema.properties).map(tt=>es[tt]);Ht=await Ce(...We)}else Ht=await Ce(...Object.values(es));Qe(S,A,Ht)}catch(te){console.error(`[useAgent] Error executing tool with secure input ${S}:`,te),Qe(S,A,`Error: ${te}`)}})();return}if(Gt.has(S)&&!Cn(S,D)){const q=De.get(S);q?(async()=>{try{const H=Et.find(ge=>ge.name===S);let pe;if(H&&H.jsonSchema?.properties){const Ee=Object.keys(H.jsonSchema.properties).map(re=>D[re]);pe=await q(...Ee)}else if(S==="getState")pe=q();else if(S==="setState"){const ge=D.updates||D;pe=await q(ge)}else pe=await q(...Object.values(D));Qe(S,A,pe)}catch(H){console.error(`[useAgent] Error executing tool ${S}:`,H),Qe(S,A,`Error: ${H}`)}})():console.warn(`[useAgent] Tool ${S} not found in toolsMap`)}else k&&k({toolCall:{toolCallId:A,toolName:S,args:D}})})})},[Ie,Gt,De,k,Qe,it,_e,Et,Cn,Yn,Mt]),f.useEffect(()=>{if(pt==="ready"&&Ie.length>0&&O){const b=Ie[Ie.length-1];b&&b.role==="assistant"&&O({message:b,messages:Ie,isAbort:!1,isDisconnect:!1,isError:!!Zn})}},[pt,Ie,Zn,O]);async function Nt(){if(!(!r?.id||!N)){rt(!0);try{const C=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${N}`}})).json();ke(C.conversations||[])}catch(b){console.error("Failed to fetch conversations:",b)}finally{rt(!1)}}}f.useEffect(()=>{r?.id&&N&&Nt()},[JSON.stringify(r),N,e]),f.useEffect(()=>{if(!Je||!Y.current)return;(async()=>{Xt(!0),kt(null);try{const C=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Je},format:"json"})});if(!C.ok){const D=await C.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${C.status} ${D}`)}const A=(await C.json())?.value||{};ue.current=A,ce||Ze(A),y&&y(A),qt.current=!0}catch(C){console.error("Failed to fetch state:",C);const S=C instanceof Error?C:new Error(String(C));kt(S),qt.current||(ue.current={},ce?y&&y({}):(Ze({}),y&&y({})),qt.current=!0)}finally{Xt(!1)}})()},[Je,e,ce,y]);async function Dt(b){zt(b),rt(!0);try{const C=await fetch(`${e}/conversations/${b}/messages`,{headers:{Authorization:`Bearer ${Y.current}`}});if(!C.ok)throw new Error(`Failed to fetch messages: ${C.statusText}`);const A=(await C.json()).messages||[];gt(A)}catch(C){console.error("Failed to load conversation messages:",C)}finally{rt(!1)}}async function lt(b){if(N)try{await fetch(`${e}/conversations/${b}`,{method:"DELETE",headers:{Authorization:`Bearer ${N}`}}),ke(He.filter(C=>C._id!==b)),b===Je&&et()}catch(C){console.error("Failed to delete conversation:",C)}}function et(){const b=crypto.randomUUID();zt(b),gt([]),ze(new Set),ue.current={},ce?y&&y({}):(Ze({}),y&&y({})),qt.current=!1}function ct(b){const C=b.tool||"unknown-tool",S=z(C,b.output);Qn({toolCallId:b.toolCallId,tool:C,output:S})}async function Pn(b){const C={...ue.current,...b};ue.current=C,ce||Ze(C),y&&y(C);try{await Sn(b)}catch(S){throw S}}return{id:Je,messages:Ie,status:pt,error:Zn,sendMessage:mt,stop:Yt,addToolOutput:ct,setMessages:gt,conversations:He,loadConversation:Dt,deleteConversation:lt,startNewConversation:et,isLoadingConversations:Qr,clientToken:N,tokenError:le,state:wn,setState:Pn,isStateLoading:Kn,stateError:Tn,pendingSecureInputs:Array.from(bn.values()),completeSecureInput:jn,pendingSecureForms:Array.from(Wn.values()),completeSecureForm:Cs}}exports.verifyToken=Ll.verifyToken;exports.ARCTEN_ORIGINAL_NAME=nt;exports.ArctenAgent=Zf;exports.SecureModalProvider=ml;exports.preserveToolName=Cf;exports.useAgent=mm;exports.useSecureModal=fl;
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=Pf(o,n,r,s);if(!i){const a=o.name,u=o[st]||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 Af({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return c.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:c.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&c.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>c.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[c.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),c.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),c.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[c.jsxs(Ce,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[c.jsx(re.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),c.jsx(Ce,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:c.jsx(re.X,{className:"h-3 w-3"})})]})]})})}function kf({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))),l=Object.keys(a).length>0;return c.jsxs("div",{className:"my-1",children:[c.jsxs("button",{onClick:()=>l&&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 ${l?"cursor-pointer hover:bg-muted/80":""}`,children:[l&&c.jsx("span",{className:"transition-transform duration-200",children:r?c.jsx(re.ChevronDown,{className:"h-3 w-3"}):c.jsx(re.ChevronRight,{className:"h-3 w-3"})}),n?c.jsx(re.X,{className:"h-3 w-3"}):s?c.jsx(re.Zap,{className:"h-3 w-3"}):c.jsx(re.Check,{className:"h-3 w-3"}),c.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&l&&c.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:c.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,d])=>c.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[c.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),c.jsx("span",{className:"font-mono text-foreground",children:typeof d=="string"?d:JSON.stringify(d)})]},u))})})]})}function Mf({...e}){return c.jsx(fr.Root,{"data-slot":"collapsible",...e})}function Ef({...e}){return c.jsx(fr.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function Nf({...e}){return c.jsx(fr.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const Df=f.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Hr=f.memo(({className:e,...t})=>typeof window>"u"?null:c.jsx(f.Suspense,{fallback:null,children:c.jsx(Df,{className:ie("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Hr.displayName="Response";const Rf=Object.freeze(Object.defineProperty({__proto__:null,Response:Hr},Symbol.toStringTag,{value:"Module"})),Vf=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=wf.create(t),i=f.useMemo(()=>(e?.length??0)*r,[e,r]);return c.jsx(o,{animate:{backgroundPosition:"0% center"},className:ie("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})},If=f.memo(Vf),ol=f.createContext(null),Of=()=>{const e=f.useContext(ol);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},$f=1e3,Lf=1e3,al=f.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,u]=ti.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,h]=ti.useControllableState({prop:o,defaultProp:0}),[m,p]=f.useState(!1),[v,x]=f.useState(null);f.useEffect(()=>{t?v===null&&x(Date.now()):v!==null&&(h(Math.ceil((Date.now()-v)/Lf)),x(null))},[t,v,h]),f.useEffect(()=>{if(s&&!t&&l&&!m){const y=setTimeout(()=>{u(!1),p(!0)},$f);return()=>clearTimeout(y)}},[t,l,s,u,m]);const T=y=>{u(y)};return c.jsx(ol.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:u,duration:d},children:c.jsx(Mf,{className:ie("not-prose mb-4",e),onOpenChange:T,open:l,...a,children:i})})}),Ff=(e,t)=>e||t===0?c.jsx(If,{duration:1,children:"Thinking..."}):t===void 0?c.jsx("p",{children:"Thought for a few seconds"}):c.jsxs("p",{children:["Thought for ",t," seconds"]}),ll=f.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Of();return c.jsx(Ef,{className:ie("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??c.jsxs(c.Fragment,{children:[c.jsx(re.BrainIcon,{className:"size-4"}),Ff(s,o),c.jsx(re.ChevronDownIcon,{className:ie("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),cl=f.memo(({className:e,children:t,...n})=>c.jsx(Nf,{className:ie("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:c.jsx(Hr,{className:"grid gap-2",children:t})}));al.displayName="Reasoning";ll.displayName="ReasoningTrigger";cl.displayName="ReasoningContent";function bo(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function Bf({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=bo(s.domain);return c.jsxs(bt,{children:[c.jsx(vt,{asChild:!0,children:c.jsxs("button",{className:ie("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:[c.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),c.jsx("span",{className:"leading-none",children:s.domain})]})}),c.jsx(wt,{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:c.jsxs("div",{className:"space-y-1.5",children:[c.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 c.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:ie("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:[c.jsx("img",{src:bo(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const l=a.target;l.style.display="none"}}),c.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function zf({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:l=!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 T=u.current;let y,w=!1;const k=new WeakSet,O=()=>{if(!u.current||w)return;w=!0;const B=u.current,_=/\[(\d+)\]/g,M=document.createTreeWalker(B,NodeFilter.SHOW_TEXT,null),R=[];let j;for(;j=M.nextNode();)if(j.nodeType===Node.TEXT_NODE&&!k.has(j)){const z=j,N=z.textContent||"";let K=z.parentElement,Y=!1;for(;K&&K!==B;){if(K.tagName==="A"||K.tagName==="CODE"||K.tagName==="PRE"){Y=!0;break}K=K.parentElement}if(!Y){const Q=Array.from(N.matchAll(_)).filter(ne=>{if(!ne[1])return!1;const Z=parseInt(ne[1],10);return n.has(Z)});Q.length>0&&R.push({node:z,matches:Q})}}if(R.length===0){w=!1;return}const V=[];R.forEach(({node:z,matches:N})=>{k.add(z);const K=z.textContent||"",Y=document.createDocumentFragment();let ae=0;N.forEach(Q=>{if(!Q[1])return;Q.index!==void 0&&Q.index>ae&&Y.appendChild(document.createTextNode(K.slice(ae,Q.index)));const ne=document.createElement("span");ne.className="inline-flex items-center citation-button-container";const Z=parseInt(Q[1],10);ne.setAttribute("data-citation",Q[1]),Y.appendChild(ne),V.push({element:ne,citationNum:Z}),ae=(Q.index||0)+Q[0].length}),ae<K.length&&Y.appendChild(document.createTextNode(K.slice(ae))),z.parentNode&&z.parentNode.replaceChild(Y,z)}),V.length>0&&h(z=>{const N=new Set(z.map(ae=>ae.element)),K=z.filter(ae=>ae.element.isConnected),Y=V.filter(ae=>!N.has(ae.element));return[...K,...Y]}),w=!1},E=new MutationObserver(()=>{clearTimeout(y),y=setTimeout(O,100)});return E.observe(T,{childList:!0,subtree:!0,characterData:!0}),y=setTimeout(O,200),()=>{E.disconnect(),clearTimeout(y)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(T){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(T)}&sz=16`}function v(T){try{return new URL(T).hostname.replace(/^www\./,"")}catch{return T}}const x=a&&l&&m?c.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[c.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((T,y)=>{const w=T.title||T.baseUrl,k=v(T.url),O=p(k);return c.jsxs("a",{href:T.url,target:"_blank",rel:"noopener noreferrer",className:ie("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:[c.jsx("img",{src:O,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:E=>{const B=E.target;B.style.display="none"}}),c.jsx("span",{className:"leading-none",children:w})]},`group-${y}`)}):Array.from(n.entries()).sort(([T],[y])=>T-y).map(([T,y])=>{const w=v(y),k=p(w);return c.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:ie("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:[c.jsx("img",{src:k,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:O=>{const E=O.target;E.style.display="none"}}),c.jsx("span",{className:"leading-none",children:y})]},T)})})]}):null;return c.jsxs("div",{className:i,children:[c.jsx("div",{ref:u,children:c.jsx(o,{children:e})}),a&&d.filter(({element:T})=>T.isConnected).map(({element:T,citationNum:y},w)=>{if(!t.find(E=>E.number===y))return null;const O=Array.from(new Map(t.map(E=>{const B=E.url.replace(/\/+$/,""),_=s?.find(M=>M.url.replace(/\/+$/,"")===B);return[B,{number:E.number,url:E.url,domain:v(E.url),title:_?.title}]})).values());return Ol.createPortal(c.jsx(Bf,{sources:O,citationNumber:y},`citation-${y}-${T}`),T,`citation-${y}-${w}`)}),x]})}function dn({...e}){return c.jsx(Ft.Root,{"data-slot":"dialog",...e})}function Uf({...e}){return c.jsx(Ft.Portal,{"data-slot":"dialog-portal",...e})}function _f({className:e,...t}){return c.jsx(Ft.Overlay,{"data-slot":"dialog-overlay",className:ie("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 hn({className:e,children:t,showCloseButton:n=!0,...s}){return c.jsxs(Uf,{"data-slot":"dialog-portal",children:[c.jsx(_f,{}),c.jsxs(Ft.Content,{"data-slot":"dialog-content",className:ie("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&&c.jsxs(Ft.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:[c.jsx(re.XIcon,{}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function fn({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-header",className:ie("flex flex-col gap-2 text-center sm:text-left",e),...t})}function mn({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-footer",className:ie("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function pn({className:e,...t}){return c.jsx(Ft.Title,{"data-slot":"dialog-title",className:ie("text-lg leading-none font-semibold",e),...t})}function gn({className:e,...t}){return c.jsx(Ft.Description,{"data-slot":"dialog-description",className:ie("text-muted-foreground text-sm",e),...t})}function yn({className:e,type:t,...n}){return c.jsx("input",{type:t,"data-slot":"input",className:ie("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 Xf({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,l]=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 c.jsx(dn,{open:e,children:c.jsx(hn,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:h,children:[c.jsxs(fn,{children:[c.jsx(pn,{children:t}),c.jsx(gn,{children:n})]}),c.jsx("div",{className:"py-4",children:c.jsxs("div",{className:"relative",children:[c.jsx(yn,{type:a?"text":"password",value:o,onChange:p=>i(p.target.value),placeholder:s,className:"pr-10",autoFocus:!0,disabled:u}),c.jsx("button",{type:"button",onClick:()=>l(!a),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:u,children:a?c.jsx(re.EyeOff,{className:"h-4 w-4"}):c.jsx(re.Eye,{className:"h-4 w-4"})})]})}),c.jsxs(mn,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:m,disabled:u,children:"Cancel"}),c.jsx(Ce,{type:"submit",disabled:!o.trim()||u,children:u?"Submitting...":"Submit"})]})]})})})}function qf({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,l]=f.useState(!0),[u,d]=f.useState(!1),h=x=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(x),m=x=>{i(x),x.trim()?l(h(x)):l(!0)},p=async x=>{if(x.preventDefault(),!o.trim()||!h(o)){l(!1);return}d(!0);try{r(o)}finally{d(!1)}},v=()=>{i(""),l(!0),r(null)};return c.jsx(dn,{open:e,children:c.jsx(hn,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:p,children:[c.jsxs(fn,{children:[c.jsxs(pn,{className:"flex items-center gap-2",children:[c.jsx(re.Mail,{className:"h-5 w-5"}),t]}),c.jsx(gn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(yn,{type:"email",value:o,onChange:x=>m(x.target.value),placeholder:s,className:a?"":"border-red-500",autoFocus:!0,disabled:u}),!a&&c.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid email address"})]}),c.jsxs(mn,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:v,disabled:u,children:"Cancel"}),c.jsx(Ce,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Wf({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,l]=f.useState(!0),[u,d]=f.useState(!1),h=T=>{const y=T.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=T=>T.replace(/\D/g,"").length===10,p=T=>{const y=h(T);i(y),y.trim()?l(m(y)):l(!0)},v=async T=>{if(T.preventDefault(),!o.trim()||!m(o)){l(!1);return}d(!0);try{const y=o.replace(/\D/g,"");r(y)}finally{d(!1)}},x=()=>{i(""),l(!0),r(null)};return c.jsx(dn,{open:e,children:c.jsx(hn,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:v,children:[c.jsxs(fn,{children:[c.jsxs(pn,{className:"flex items-center gap-2",children:[c.jsx(re.Phone,{className:"h-5 w-5"}),t]}),c.jsx(gn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(yn,{type:"tel",value:o,onChange:T=>p(T.target.value),placeholder:s,className:a?"":"border-red-500",maxLength:14,autoFocus:!0,disabled:u}),!a&&c.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid 10-digit phone number"})]}),c.jsxs(mn,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:x,disabled:u,children:"Cancel"}),c.jsx(Ce,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Kf({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(""),[l,u]=f.useState(!1),d=p=>{const v=p.replace(/\D/g,"");a(v.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 c.jsx(dn,{open:e,children:c.jsx(hn,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:h,children:[c.jsxs(fn,{children:[c.jsxs(pn,{className:"flex items-center gap-2",children:[c.jsx(re.Shield,{className:"h-5 w-5"}),t]}),c.jsx(gn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(yn,{type:"password",value:i,onChange:p=>d(p.target.value),placeholder:s,className:"text-center text-lg tracking-widest",maxLength:r,autoFocus:!0,disabled:l}),c.jsxs("p",{className:"text-sm text-gray-500 mt-1 text-center",children:["Enter ",r,"-digit PIN"]})]}),c.jsxs(mn,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:m,disabled:l,children:"Cancel"}),c.jsx(Ce,{type:"submit",disabled:i.length!==r||l,children:l?"Submitting...":"Submit"})]})]})})})}function zs({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(""),[l,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 c.jsx(dn,{open:e,children:c.jsx(hn,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:d,children:[c.jsxs(fn,{children:[c.jsxs(pn,{className:"flex items-center gap-2",children:[c.jsx(re.Lock,{className:"h-5 w-5"}),t]}),c.jsx(gn,{children:n})]}),c.jsx("div",{className:"py-4",children:c.jsx(yn,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:l})}),c.jsxs(mn,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:h,disabled:l,children:"Cancel"}),c.jsx(Ce,{type:"submit",disabled:!i.trim()||l,children:l?"Submitting...":"Submit"})]})]})})})}function Gf({isOpen:e,title:t,description:n,fields:s,onComplete:r,submitText:o="Submit",cancelText:i="Cancel"}){const[a,l]=f.useState(()=>{const j={};return s.forEach(V=>{j[V.name]=V.value||""}),j}),[u,d]=f.useState({}),[h,m]=f.useState({}),[p,v]=f.useState(!1),x=j=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(j)?null:"Please enter a valid email address",T=j=>j.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",y=(j,V=4)=>j.length===V?null:`PIN must be ${V} digits`,w=j=>{const V=j.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)}`},k=(j,V,z)=>{let N=V,K=null;switch(z.type){case"phone":N=w(V),N.trim()&&(K=T(N));break;case"email":V.trim()&&(K=x(V));break;case"pin":N=V.replace(/\D/g,"").slice(0,6),N.trim()&&(K=y(N));break}!K&&z.validation&&N.trim()&&(K=z.validation(N)),l(Y=>({...Y,[j]:N})),d(Y=>({...Y,[j]:K||""}))},O=()=>{const j={};let V=!0;return s.forEach(z=>{const N=a[z.name]||"";let K=null;if(z.required&&!N.trim())K=`${z.label} is required`;else if(N.trim()){switch(z.type){case"email":K=x(N);break;case"phone":K=T(N);break;case"pin":K=y(N);break}!K&&z.validation&&(K=z.validation(N))}K&&(j[z.name]=K,V=!1)}),d(j),V},E=async j=>{if(j.preventDefault(),!!O()){v(!0);try{const V={};s.forEach(z=>{const N=a[z.name]?.trim();N&&(z.type==="phone"?V[z.name]=N.replace(/\D/g,""):V[z.name]=N)}),r(V)}finally{v(!1)}}},B=()=>{l({}),d({}),m({}),r(null)},_=j=>{m(V=>({...V,[j]:!V[j]}))},M=j=>{switch(j.type){case"password":return h[j.name]?"text":"password";case"email":return"email";case"phone":return"tel";case"pin":case"ssn":return"password";default:return"text"}},R=j=>{if(j.placeholder)return j.placeholder;switch(j.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 ${j.label.toLowerCase()}...`}};return c.jsx(dn,{open:e,children:c.jsx(hn,{showCloseButton:!1,className:"max-w-md",children:c.jsxs("form",{onSubmit:E,children:[c.jsxs(fn,{children:[c.jsx(pn,{children:t}),n&&c.jsx(gn,{children:n})]}),c.jsx("div",{className:"py-4 space-y-4",children:s.map(j=>c.jsxs("div",{children:[c.jsxs("label",{className:"block text-sm font-medium mb-1",children:[j.label,j.required&&c.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),c.jsxs("div",{className:"relative",children:[c.jsx(yn,{type:M(j),value:a[j.name]||"",onChange:V=>k(j.name,V.target.value,j),placeholder:R(j),className:u[j.name]?"border-red-500":"",disabled:p,autoFocus:j===s[0],maxLength:j.type==="pin"?6:j.type==="phone"?14:void 0}),j.type==="password"&&c.jsx("button",{type:"button",onClick:()=>_(j.name),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:p,children:h[j.name]?c.jsx(re.EyeOff,{className:"h-4 w-4"}):c.jsx(re.Eye,{className:"h-4 w-4"})})]}),u[j.name]&&c.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[c.jsx(re.AlertCircle,{className:"h-3 w-3"}),u[j.name]]})]},j.name))}),c.jsxs(mn,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:B,disabled:p,children:i}),c.jsx(Ce,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const ul=f.createContext(void 0);function dl(){const e=f.useContext(ul);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function hl({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(v=>{n(p),o.current=v}),[]),l=f.useCallback(p=>new Promise(v=>{r(p),i.current=v}),[]),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 v=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 c.jsx(Gf,{isOpen:!0,title:s.title,description:s.description,fields:v,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 c.jsx(Xf,{...p});case"email":return c.jsx(qf,{...p});case"phone":return c.jsx(Wf,{...p});case"pin":return c.jsx(Kf,{...p});case"ssn":return c.jsx(zs,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return c.jsx(zs,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return c.jsx(zs,{...p})}},m=f.useMemo(()=>({showSecureModal:a,showSecureForm:l}),[a,l]);return c.jsxs(ul.Provider,{value:m,children:[e,h()]})}function Yf(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 Hf(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 vo(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,l=new Map,u=new Map;if(s&&s[1]){const M=s[1],R=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let j;for(;(j=R.exec(M))!==null;)if(j[1]&&j[2]){const V=parseInt(j[1],10),z=j[2].replace(/[.,;:!?]+$/,""),N=z.replace(/\/+$/,"");if(a.has(N)||a.set(N,z),i.has(N)||i.set(N,[]),i.get(N).push(V),!l.has(N))l.set(N,V);else{const K=l.get(N);V<K&&l.set(N,V)}}for(const[V,z]of i.entries()){const N=l.get(V);for(const K of z)K!==N&&u.set(K,N)}for(const[V,z]of l.entries()){const N=a.get(V)||V;r.set(z,N),o.push({number:z,url:N})}}let d,h=t;s&&s[0]&&(d=s[0],h=t.replace(n,""));const m=[];let p=0;const v=/```[\s\S]*?```|`[^`]+`/g;let x;for(;(x=v.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 T=m.map(M=>{if(M.type==="code")return M.content;let R=M.content;return R=R.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(V,z,N)=>{const K=parseInt(z,10),Y=N.replace(/\/+$/,""),ae=u.get(K)||K;return l.has(Y)||(l.set(Y,ae),r.has(ae)||(r.set(ae,N),o.push({number:ae,url:N}))),`[${ae}]`}),R=R.replace(/\[(\d+)\]/g,(V,z)=>{const N=parseInt(z,10);return`[${u.get(N)||N}]`}),R}),y=[];for(const[M,R]of l.entries()){const j=a.get(M)||M,{baseUrl:V,anchor:z}=Yf(j),N=Hf(j);y.push({url:j,baseUrl:V,numbers:[R],anchor:z,title:N})}y.sort((M,R)=>(M.numbers[0]||0)-(R.numbers[0]||0));const w=new Map;let k=1;for(const M of y){const R=M.numbers[0];w.set(R,k),M.numbers=[k],k++}const O=new Map;for(const[M,R]of r.entries()){const j=w.get(M);j&&O.set(j,R)}const E=o.map(M=>{const R=w.get(M.number);return R?{number:R,url:M.url}:M}).filter(M=>w.has(M.number)),B=Array.from(w.entries()).sort((M,R)=>R[0]-M[0]);let _=T.join("");for(const[M,R]of B){const j=new RegExp(`\\[${M}\\](?!\\d)`,"g");_=_.replace(j,`[${R}]`)}return{processedText:_,citations:E.sort((M,R)=>M.number-R.number),citationMap:O,groupedCitations:y,referencesText:d}}function Vn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Vn(t)}catch{return e}if(Array.isArray(e))return e.map(Vn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Vn(s);return t}return e}function Us(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Vn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Vn(e):{}}function Jf({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:l=800,initiallyExpanded:u=!1,tools:d=[],safeTools:h=[],toolMetadata:m,systemPrompt:p="",tokenEndpoint:v="/api/arcten/token",apiBaseUrl:x="https://api.arcten.com",user:T,state:y,onStateChange:w,allowStateEdits:k=!0,sources:O,ragConfig:E,showCitations:B=!0,sensitiveParams:_,autoDetectSensitive:M=!1}){const{showSecureModal:R}=dl(),j=f.useMemo(()=>E!==void 0?E:O&&O.length>0?{enabled:!0,organizationId:O[0],autoExecute:!0,filters:void 0}:{enabled:!1},[O,E]),[V,z]=f.useState(null),N=f.useRef(null),[K,Y]=f.useState(null),[ae,Q]=f.useState(null),ne=f.useRef(null),Z=y!==void 0,[we,Je]=f.useState({}),Me=f.useRef({});Z&&y?Me.current=y:Z||(Me.current=we);const[Ze,Bt]=f.useState(!1),[Jr,it]=f.useState(null),ot=f.useRef(!1),[Ue,xn]=f.useState(u),[_e,zt]=f.useState(i),[Ut,Wn]=f.useState(600),[bn,Pt]=f.useState(!1),[oe,ce]=f.useState(!1),[Ie,Qe]=f.useState(!1),[ue,vn]=f.useState({x:100,y:100}),[Kn,_t]=f.useState(!1),[wn,At]=f.useState({x:0,y:0}),[Xt,Tn]=f.useState(!1),at=f.useRef(null),Xe=f.useRef(null),[kt,Sn]=f.useState(""),[Gn,js]=f.useState(null),[jn,Yn]=f.useState("Thinking..."),[qe,Ee]=f.useState(new Set),[qt,lt]=f.useState(""),[Re,Hn]=f.useState([]),[Wt,Mt]=f.useState(!1),[Kt,Jn]=f.useState([]),[We,Oe]=f.useState(()=>typeof window<"u"?crypto.randomUUID():null),[mt,pt]=f.useState(!1),[Zn,Gt]=f.useState(!1),[Qn,gt]=f.useState([]),et=f.useCallback(async(g,P=3)=>{if(!We||!N.current)return;const I=async()=>{const L=`${x.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,U=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${N.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:We,updates:g},format:"json"})});if(!U.ok){if(U.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const te=await U.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${U.status} ${te}`)}};for(let $=0;$<P;$++)try{await I(),it(null);return}catch(L){if($===P-1){const te=L instanceof Error?L:new Error(String(L));throw it(te),console.error("Failed to sync state to Convex after retries:",L),te}await new Promise(te=>setTimeout(te,Math.pow(2,$)*100))}},[We,x,N]),Et=f.useMemo(()=>function(){return Me.current},[]),Nt=f.useMemo(()=>async function(P){const I={...Me.current,...P};Me.current=I,Z||Je(I),w&&w(I);try{await et(P)}catch($){throw $}},[et,w,Z]);f.useEffect(()=>{Z&&y&&(Me.current=y)},[Z,y]);const ct=f.useMemo(()=>j?.enabled?async function(P,I=20,$){if(O&&O.length>1){const te=O.map(G=>fetch(`${x}/search`,{method:"POST",headers:{"Content-Type":"application/json",...N.current?{Authorization:`Bearer ${N.current}`}:{}},body:JSON.stringify({q:P,k:Math.min(I,100),organizationId:G,...Object.keys(U).length>0?{filters:U}:{}})}).then(X=>X.ok?X.json():null)),J=await Promise.all(te),se=[];for(const G of J)G?.candidates&&se.push(...G.candidates);se.sort((G,X)=>{const xe=G.scores?.rerank||G.scores?.dense||0;return(X.scores?.rerank||X.scores?.dense||0)-xe});const F=se.slice(0,I).map((G,X)=>{const xe=G.citation||G.url;return{rank:X+1,doc_id:G.doc_id,block_id:G.block_id,url:G.url,citation:xe,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:P,total:se.length,results:F,summary:`Found ${se.length} relevant results across ${O.length} source(s) for "${P}". Top result: ${F[0]?.title||"N/A"}`}}const L=j.organizationId&&j.organizationId!=="default"?j.organizationId:void 0,U={...j.filters,...$};try{const te={q:P,k:Math.min(I,100)};L&&(te.organizationId=L),Object.keys(U).length>0&&(te.filters=U);const J={"Content-Type":"application/json"};N.current&&(J.Authorization=`Bearer ${N.current}`);const se=await fetch(`${x}/search`,{method:"POST",headers:J,body:JSON.stringify(te)});if(!se.ok){const X=await se.text();return{success:!1,error:`Search failed: ${se.status} ${X}`}}const F=await se.json(),G=F.candidates.map((X,xe)=>{const me=X.citation||X.url;return{rank:xe+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:F.query,total:F.total,results:G,summary:`Found ${F.total} relevant results for "${P}". Top result: ${G[0]?.title||"N/A"}`}}catch(te){return{success:!1,error:te instanceof Error?te.message:"Unknown error occurred"}}}:null,[E,x,N]),tt=f.useMemo(()=>j?.enabled?async function(P,I){const $=j.organizationId&&j.organizationId!=="default"?j.organizationId:O&&O.length>0?O[0]:void 0;try{const L={"Content-Type":"application/json"};N.current&&(L.Authorization=`Bearer ${N.current}`);const U=await fetch(`${x}/fetch`,{method:"POST",headers:L,body:JSON.stringify({doc_id:P,block_ids:I,...$?{organizationId:$}:{}})});if(!U.ok){const J=await U.text();return{success:!1,error:`Fetch failed: ${U.status} ${J}`}}const te=await U.json();return{success:!0,blocks:te.blocks||[],fullContent:te.fullContent||"",pageUrl:te.pageUrl||"",pageTitle:te.pageTitle||"",summary:`Fetched ${te.blocks?.length||0} blocks from ${te.pageTitle||P}`}}catch(L){return{success:!1,error:L instanceof Error?L.message:"Unknown error occurred"}}}:null,[E,x,N]),ut=f.useMemo(()=>{const g=[...d,...h,Et];return(!Z||k)&&g.push(Nt),j?.enabled&&(ct&&g.push(ct),tt&&g.push(tt)),g},[d,h,Et,Nt,ct,tt,Z,k,j]),Cn=f.useMemo(()=>il(ut,m),[ut,m]),b=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:[]}}];(!Z||k)&&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 P=[];return j?.enabled&&P.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...Cn,...g,...P]},[Cn,Z,k,j]),C=f.useMemo(()=>new Set(b.map(g=>g.name)),[b]),S=f.useMemo(()=>b.filter(g=>g.name==="getState"?!0:g.name==="setState"?!Z||k:C.has(g.name)),[b,C,Z,k]),A=f.useMemo(()=>{const g=new Map,P=new Map(Cn.map(I=>[I.name,I]));return g.set("getState",Et),(!Z||k)&&g.set("setState",Nt),j?.enabled&&(ct&&g.set("searchDocs",ct),tt&&g.set("fetchDocContent",tt)),ut.forEach(I=>{if(I===Et||I===Nt||I===ct||I===tt)return;const $=I[st];if($){const U=P.get($);if(U){g.set(U.name,I);return}}const L=b.find(U=>U.name===I.name);L&&g.set(L.name,I)}),g},[ut,b,Et,Nt,ct,tt,Z,k,j]),D=f.useMemo(()=>{const g=new Set;g.add("getState"),g.add("setState"),j?.enabled&&j.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent"));const P=new Map(b.map(I=>[I.name,I]));return h.forEach(I=>{const $=I[st];if($&&P.has($))g.add($);else{const L=b.find(U=>U.name===I.name);L&&g.add(L.name)}}),g},[h,b,j]),q=["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&&xn(JSON.parse(g));const P=localStorage.getItem("arcten-sidebar-width");P&&zt(parseInt(P));const I=localStorage.getItem("arcten-sidebar-height");I&&Wn(parseInt(I));const $=localStorage.getItem("arcten-sidebar-detached");$&&ce(JSON.parse($));const L=localStorage.getItem("arcten-sidebar-position");if(L){const te=JSON.parse(L),J=50,se=Math.max(J-i,Math.min(te.x,window.innerWidth-J)),F=Math.max(0,Math.min(te.y,window.innerHeight-J));vn({x:se,y:F})}const U=localStorage.getItem("arcten-sidebar-minimized");U&&Qe(JSON.parse(U)),Tn(!0)}},[]);const H=f.useMemo(()=>T,[T?.id]);f.useEffect(()=>((async()=>{try{const P=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:H})});if(!P.ok)throw new Error("Failed to fetch token");const I=await P.json();z(I.clientToken),N.current=I.clientToken,Q(I.expiresAt),Y(null)}catch(P){Y(P instanceof Error?P.message:"Failed to fetch token")}})(),()=>{ne.current&&clearTimeout(ne.current)}),[v,H]),f.useEffect(()=>{if(!ae)return;ne.current&&clearTimeout(ne.current);const g=Math.floor(Date.now()/1e3),P=ae-g,$=Math.max(0,P-5);return ne.current=setTimeout(async()=>{try{const L=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:H})});if(!L.ok)throw new Error("Failed to refresh token");const U=await L.json();z(U.clientToken),N.current=U.clientToken,Q(U.expiresAt),Y(null)}catch(L){console.error("Token refresh failed:",L),Y(L instanceof Error?L.message:"Failed to refresh token")}},$*1e3),()=>{ne.current&&clearTimeout(ne.current)}},[ae,v,H]),f.useEffect(()=>{(async()=>{if(ut.length!==0)try{const P=ut.map($=>({name:$.name,code:$.toString()})),I=await fetch(`${x}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:P})});if(I.ok){const $=await I.json();Hn($.tools)}}catch(P){console.error("Failed to fetch tool descriptions:",P)}})()},[ut]),f.useEffect(()=>{Promise.resolve().then(()=>Rf).then(g=>{js(()=>g.Response)})},[]),f.useEffect(()=>{const g=()=>{lt(window.location.pathname)};g(),window.addEventListener("popstate",g);const P=setInterval(g,500);return()=>{window.removeEventListener("popstate",g),clearInterval(P)}},[]);const pe=f.useCallback(async()=>{if(!(!H?.id||!V)){Gt(!0);try{const P=await(await fetch(`${x}/conversations`,{headers:{Authorization:`Bearer ${V}`}})).json();Jn(P.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{Gt(!1)}}},[H?.id,V,x]);f.useEffect(()=>{H?.id&&V&&pe()},[H?.id,V,pe]);function ye(g){const P=Math.floor((Date.now()-g)/1e3);return P<60?"now":P<3600?`${Math.floor(P/60)}m`:P<86400?`${Math.floor(P/3600)}h`:`${Math.floor(P/86400)}d`}function Ve(){const g=crypto.randomUUID();Oe(g),Yt([]),gt([]),pt(!1);const P=Z?y||{}:{};Me.current=P,Z||Je(P),w&&w(P),ot.current=!1}async function ee(g){if(V)try{await fetch(`${x}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${V}`}}),Jn(Kt.filter(P=>P._id!==g)),g===We&&Ve()}catch(P){console.error("Failed to delete conversation:",P)}}async function le(g){Oe(g.chatId),pt(!1),Gt(!0);try{const P=await fetch(`${x}/conversations/${g.chatId}/messages`,{headers:{Authorization:`Bearer ${N.current}`}});if(!P.ok)throw new Error(`Failed to fetch messages: ${P.statusText}`);const $=(await P.json()).messages||[];Yt($),gt($)}catch(P){console.error("Failed to load conversation messages:",P);const I=g.messages||[];Yt(I),gt(I)}finally{Gt(!1)}}const nt=async(g,P={})=>{const I=P.headers?new Headers(P.headers):new Headers;return I.delete("user-agent"),I.delete("User-Agent"),fetch(g,{...P,headers:I})},{messages:Te,sendMessage:Pn,status:Pe,error:Ne,stop:Ke,addToolResult:Se,setMessages:Yt}=wo.useChat({id:We||void 0,transport:new fs.DefaultChatTransport({api:`${x}/chat`,fetch:nt,headers:()=>{const g={};return N.current&&(g.Authorization=`Bearer ${N.current}`),g},body:()=>({tools:S.map(P=>({name:P.name,description:P.description,inputSchema:P.jsonSchema})),systemPrompt:p,currentRoute:qt,state:Me.current})}),sendAutomaticallyWhen:fs.lastAssistantMessageIsCompleteWithToolCalls});f.useEffect(()=>{const g=Te[Te.length-1];if(!g||g.role!=="assistant")return;const P=g.parts?.filter(I=>I.type?.startsWith("tool-")&&I.state==="input-available"&&typeof I.toolCallId=="string"&&I.input!==void 0)||[];for(const I of P){const $=I,L=$.type?.replace("tool-","")||"",U=$.toolCallId;if(D.has(L)){if(qe.has(U))continue;Ee(J=>J.has(U)?J:new Set(J).add(U)),(async()=>{try{const J=A.get(L);if(!J){console.warn(`[ArctenAgent] Tool ${L} not found in toolsMap. Available tools:`,Array.from(A.keys())),Se({toolCallId:U,tool:L,output:`Error: Tool ${L} not found`}),Ee(X=>{const xe=new Set(X);return xe.delete(U),xe});return}const se=Us($.input),F=S.find(X=>X.name===L);let G;if(F&&F.jsonSchema?.properties){const xe=Object.keys(F.jsonSchema.properties).map(me=>se[me]);console.log(`[ArctenAgent] Executing safe tool ${L} with args:`,xe),G=await J(...xe)}else if(L==="getState")G=J();else if(L==="setState"){const X=se.updates||se;G=await J(X)}else G=await J(...Object.values(se));console.log(`[ArctenAgent] Tool ${L} completed, result:`,G),Se({toolCallId:U,tool:L,output:G}),Ee(X=>{const xe=new Set(X);return xe.delete(U),xe})}catch(J){console.error(`[ArctenAgent] Error executing safe tool ${L}:`,J),Se({toolCallId:U,tool:L,output:`Error: ${J instanceof Error?J.message:String(J)}`}),Ee(se=>{const F=new Set(se);return F.delete(U),F})}})()}}},[Te,D,A,S,Se]),f.useEffect(()=>{if(!We||!N.current)return;(async()=>{Bt(!0),it(null);try{const I=`${x.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,$=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${N.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:We},format:"json"})});if(!$.ok){if($.status===404||$.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${$.status}), using empty state`);const F=Z?y||{}:{};Me.current=F,Z||Je(F),w&&w(F),ot.current=!0,Bt(!1);return}const se=await $.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${$.status} ${se}`)}const U=(await $.json())?.value||{},te=!ot.current;let J;te?(J={...Z?y||{}:{},...U},ot.current=!0):J=U,Me.current=J,Z||Je(J),w&&w(J)}catch(P){P instanceof TypeError&&P.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",P):console.error("[ArctenAgent] Failed to fetch state:",P);const $=P instanceof Error?P:new Error(String(P));if(it($),!ot.current){const L=Z?y||{}:{};Me.current=L,Z||Je(L),w&&w(L),ot.current=!0}}finally{Bt(!1)}})()},[We,x,Z,y,w]),f.useEffect(()=>{Ue&&Xe.current&&Xe.current.focus()},[Ue,Te]);function es(){xn(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function xl(){xn(!1),localStorage.setItem("arcten-sidebar-expanded","false")}f.useEffect(()=>{},[Ue]),f.useEffect(()=>{at.current&&at.current.scrollIntoView({behavior:"smooth"})},[Te]),f.useEffect(()=>{function g(P){P.key==="Escape"&&(Pe==="streaming"||Pe==="submitted")&&(P.preventDefault(),Ke())}return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Pe,Ke]);function bl(){const g=crypto.randomUUID();Oe(g),Yt([]),gt([]),pt(!1)}function Zr(g){if(g.preventDefault(),!kt.trim())return;(Pe==="streaming"||Pe==="submitted")&&Ke();const P=q[Math.floor(Math.random()*q.length)]||"Thinking...";Yn(P),Pn({text:kt}),Sn("")}function vl(g){const P=g.target.value;Sn(P)}f.useEffect(()=>{if(!bn)return;function g(I){if(oe){const $=I.clientX-ue.x,L=I.clientY-ue.y;$>=a&&$<=l&&zt($),L>=400&&L<=1e3&&Wn(L)}else{const $=window.innerWidth-I.clientX;$>=a&&$<=l&&zt($)}}function P(){Pt(!1),localStorage.setItem("arcten-sidebar-width",_e.toString()),localStorage.setItem("arcten-sidebar-height",Ut.toString())}return window.addEventListener("mousemove",g),window.addEventListener("mouseup",P),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",P)}},[bn,_e,Ut,oe,ue,a,l]);function wl(g){g.preventDefault(),Pt(!0)}function Tl(){ce(!0),Qe(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Sl(){ce(!1),Qe(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Qr(){Qe(!Ie),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ie))}function jl(g){oe&&(_t(!0),At({x:g.clientX-ue.x,y:g.clientY-ue.y}))}return f.useEffect(()=>{if(!oe)return;function g(){vn(P=>{const $=window.innerWidth-50,L=window.innerHeight-50,U=50-_e,te=0,J=Math.max(U,Math.min(P.x,$)),se=Math.max(te,Math.min(P.y,L));if(J!==P.x||se!==P.y){const F={x:J,y:se};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(F)),F}return P})}return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[oe,_e]),f.useEffect(()=>{if(!Kn)return;function g(I){const $=I.clientX-wn.x,L=I.clientY-wn.y,U=50,te=window.innerWidth-U,J=window.innerHeight-U,se=U-_e,F=0,G=Math.max(se,Math.min($,te)),X=Math.max(F,Math.min(L,J));vn({x:G,y:X})}function P(){_t(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(ue))}return window.addEventListener("mousemove",g),window.addEventListener("mouseup",P),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",P)}},[Kn,wn,ue,_e]),Xt?K?c.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:c.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",K]})}):V?c.jsx(qu,{features:Tf,children:c.jsx(is,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:oe?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:oe?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
20
+ ${oe?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
21
+ ${Ue?"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
+ ${oe?"border border-border":"border-l border-border"}
23
+ ${Ue?"":"w-[30px]"}
24
+ `,style:Ue?oe?{width:`${_e}px`,height:Ie?"auto":`${Ut}px`,left:`${ue.x}px`,top:`${ue.y}px`}:{width:`${_e}px`}:void 0,onClick:Ue?void 0:es,children:Ue?c.jsxs(c.Fragment,{children:[!oe&&c.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:wl,children:c.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),oe&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:g=>{g.preventDefault(),Pt(!0)}}),c.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(),_t(!0),At({x:g.clientX-ue.x,y:g.clientY-ue.y})},children:c.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"})}),c.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:g=>{g.preventDefault(),Pt(!0)}})]}),c.jsxs("div",{className:"flex flex-col h-full",children:[c.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${oe?"cursor-move":""}`,onMouseDown:oe?jl:void 0,children:[c.jsx("h2",{className:`text-base font-semibold ${oe&&Ie?"cursor-pointer":""}`,onClick:oe&&Ie?g=>{g.stopPropagation(),Qr()}:void 0,children:r}),c.jsxs("div",{className:"flex items-center gap-1",onClick:g=>g.stopPropagation(),children:[c.jsxs(bt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx("button",{type:"button",className:ie(Rt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:bl,"aria-label":"New chat",children:c.jsx(re.Plus,{className:"h-4 w-4"})})}),c.jsx(wt,{children:"Start a new conversation"})]}),c.jsxs(bt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx("button",{type:"button",className:ie(Rt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:oe?Sl:Tl,"aria-label":oe?"Dock sidebar":"Float sidebar",children:oe?c.jsx(re.Dock,{className:"h-4 w-4"}):c.jsx(re.PictureInPicture2,{className:"h-4 w-4"})})}),c.jsx(wt,{children:oe?"Dock to sidebar":"Undock to floating window"})]}),c.jsxs(bt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx("button",{type:"button",className:ie(Rt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:oe?Qr:xl,"aria-label":oe?Ie?"Maximize":"Minimize":"Close sidebar",children:oe?Ie?c.jsx(re.Maximize2,{className:"h-4 w-4"}):c.jsx(re.Minimize2,{className:"h-4 w-4"}):c.jsx(re.X,{className:"h-4 w-4"})})}),c.jsx(wt,{children:oe?Ie?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ie&&c.jsxs(c.Fragment,{children:[T&&Kt.length>0&&c.jsxs("div",{className:`border-b border-border ${mt?"flex flex-col flex-1":""}`,children:[c.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[c.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),c.jsx(Ce,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{mt||pe(),pt(!mt)},children:mt?"Show less":"View all"})]}),c.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${mt?"flex-1 overflow-y-auto":""}`,children:Kt.slice(0,mt?void 0:3).map(g=>c.jsxs("div",{className:"group relative",children:[c.jsxs(Sf,{type:"button",className:ie(Rt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>le(g),children:[c.jsx("span",{className:"text-xs truncate",children:g.title}),c.jsx("div",{className:"ml-2 flex items-center",children:c.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:ye(g.updatedAt)})})]}),c.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:P=>{P.stopPropagation(),ee(g._id)},"aria-label":"Delete conversation",children:c.jsx(re.X,{className:"h-3 w-3"})})]},g._id))})]}),c.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[c.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Te.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&c.jsx("div",{className:"mb-6",children:o}),c.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),Re.length>0&&c.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:c.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(Wt?Re:Re.slice(0,10)).map(g=>c.jsxs(bt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx(Cs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Sn(g.sampleUsage),Xe.current?.focus()},children:g.friendlyName})}),c.jsx(wt,{children:c.jsxs("div",{className:"max-w-xs",children:[c.jsx("p",{className:"font-medium",children:g.description}),c.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[c.jsx("span",{className:"font-medium",children:"Example:"}),' "',g.sampleUsage,'"']}),g.paramCount>0&&c.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[c.jsx("span",{className:"font-medium",children:"Parameters:"})," ",g.params.join(", ")]})]})})]},g.name)),Re.length>10&&!Wt&&c.jsxs(bt,{children:[c.jsx(vt,{asChild:!0,children:c.jsxs(Cs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Mt(!0),children:["+",Re.length-10," more"]})}),c.jsx(wt,{children:c.jsxs("div",{className:"max-w-xs",children:[c.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),c.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:Re.slice(10).map(g=>c.jsxs("div",{children:[c.jsxs("span",{className:"font-medium text-xs",children:[g.friendlyName,":"]}),c.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:g.description})]},g.name))}),c.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),Wt&&Re.length>10&&c.jsx(Cs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Mt(!1),children:"Show less"})]})})]}):c.jsxs(c.Fragment,{children:[Te.map(g=>{const I=g.parts.filter(F=>F.type==="text").map(F=>F.text).join("");let $=g.parts;g.role==="assistant"&&g.parts.some(G=>G.timestamp)&&($=[...g.parts].sort((G,X)=>{const xe=G.timestamp||0,me=X.timestamp||0;return xe-me}));let L=[],U=new Map,te=[],J,se=!0;if(g.role==="assistant"){const F=$.filter(me=>me.type==="text"&&me.text),G=[],X=[];F.forEach(me=>{const{citations:yt,citationMap:Ae,groupedCitations:$e,referencesText:xt}=vo(me.text);L.push(...yt),G.push(Ae),$e&&X.push(...$e),xt&&(J=xt)}),G.forEach(me=>{me.forEach((yt,Ae)=>{U.has(Ae)||U.set(Ae,yt)})}),te=Array.from(new Map(X.map(me=>[me.url,me])).values()).sort((me,yt)=>(me.numbers[0]||0)-(yt.numbers[0]||0)),se=!(Pe==="streaming"&&g.id===Te.at(-1)?.id)}return c.jsx("div",{className:`${g.role==="user"?"flex justify-end":"w-full"}`,children:c.jsx("div",{className:`${g.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:g.role==="user"?c.jsx(jf,{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}):c.jsx("div",{className:"space-y-2",children:$.map((F,G)=>{if(F.type?.startsWith("tool-")){const X=F.type?.replace("tool-","")||"",xe=S.find(Ae=>Ae.name===X),me=F.state==="input-available",yt=F.state==="output-available";if(me&&D.has(X),me){if(D.has(X))return null;const Ae=Us(F.input);return c.jsx(is,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:c.jsx(Af,{toolName:X,description:xe?.description||"",args:Ae,onApprove:async()=>{if(qe.has(F.toolCallId))return;Ee(xt=>new Set(xt).add(F.toolCallId));const $e=A.get(X);if($e)try{const xt=await $e(...Object.values(Ae));Se({toolCallId:F.toolCallId,tool:X,output:xt})}catch(xt){Se({toolCallId:F.toolCallId,tool:X,output:`Error: ${xt}`})}},onDeny:async()=>{qe.has(F.toolCallId)||(Ee($e=>new Set($e).add(F.toolCallId)),Se({toolCallId:F.toolCallId,tool:X,output:"User denied tool execution"}))}})},`${F.toolCallId}-${G}`)}else if(yt){const Ae=F.output==="User denied tool execution",$e=Us(F.input);return c.jsx(kf,{toolName:X,args:$e,isDenied:Ae,isSafe:D.has(X)},`${F.toolCallId}-${G}`)}return null}if(F.type==="text"&&F.text&&Gn){const{processedText:X}=vo(F.text),Ae=!$.slice(G+1).some($e=>$e.type==="text"&&$e.text)&&se&&U.size>0;return c.jsx(zf,{text:X,citations:L,citationMap:U,groupedCitations:Ae?te:void 0,referencesText:Ae?J:void 0,ResponseComponent:Gn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:B,showReferences:Ae},`${g.id}-${G}`)}return F.type==="reasoning"&&F.text?c.jsxs(al,{className:"w-full",isStreaming:Pe==="streaming"&&G===g.parts.length-1&&g.id===Te.at(-1)?.id,children:[c.jsx(ll,{}),c.jsx(cl,{children:F.text})]},`${g.id}-${G}`):null})})})},g.id)}),c.jsx("div",{ref:at})]})}),Ne&&c.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Ne.message]}),c.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[c.jsx(Xu,{mode:"wait",children:(Pe==="streaming"||Pe==="submitted")&&c.jsxs(is,{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:[c.jsx(is,{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]}}),c.jsx("p",{className:"text-xs text-muted-foreground",children:jn})]})}),c.jsxs("form",{onSubmit:Zr,className:"relative",children:[c.jsx(jo,{ref:Xe,value:kt,onChange:vl,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(),Zr(g))}}),Pe==="streaming"||Pe==="submitted"?c.jsxs(bt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx("button",{type:"button",className:ie(Rt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:Ke,children:c.jsx(re.Square,{className:"h-4 w-4"})})}),c.jsxs(wt,{children:[c.jsx(ni,{children:"Escape"})," to stop"]})]}):c.jsxs(bt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx("button",{type:"submit",className:ie(Rt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!kt.trim(),children:c.jsx(re.ArrowRight,{className:"h-4 w-4"})})}),c.jsxs(wt,{children:[c.jsx(ni,{children:"Enter"})," to send"]})]})]})]})]}),c.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:[c.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),c.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),c.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):c.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[c.jsx(re.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),c.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):c.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:c.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function Zf(e){return c.jsx(hl,{children:c.jsx(Jf,{...e})})}const Qf={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 Mn(e){for(const[t,n]of Object.entries(Qf))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function fl(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 ml(e,t,n){const s=Object.keys(n).length,r=t.length;return r>=3||s>=2||s>0&&s<r}function em(e,t,n,s={}){const r=[];return Object.keys(s).forEach(i=>{const a=i in n,l=n[i];if(!a){const h=s[i];if(h!=null&&h!=="")return}const u=tm(s[i]),d={name:i,type:nm(l||Mn(i)||"text"),label:pl(i),placeholder:sm(i,l),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 l=i.name in n,u=a.name in n;return l===u?0:l?1:-1}),{shouldUseForm:ml(e,t,n),fields:r,title:rm(e),description:im(e,r.length)}}function tm(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function nm(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 pl(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function sm(e,t){return t?fl(t,e).placeholder:`Enter ${pl(e).toLowerCase()}...`}function rm(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function im(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 In(e){if(typeof e=="string")try{const t=JSON.parse(e);return In(t)}catch{return e}if(Array.isArray(e))return e.map(In);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=In(s);return t}return e}function om(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 am(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return In(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?In(e):{}}const ds="__secureOutput",hs="[hidden for privacy]";function lm(e){if(typeof globalThis.structuredClone=="function")return globalThis.structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn("[useAgent] Failed to clone value for redaction:",t),e}}function cm(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function um(e,t){if(t.length===0)return e;if(!e||typeof e!="object")return;let n=e;for(const s of t){if(!n||typeof n!="object")return;n=n[s]}return n}function dm(e,t,n){if(!e||typeof e!="object"||t.length===0)return!1;let s=e;for(let o=0;o<t.length-1;o++){if(!s||typeof s!="object")return!1;const i=s,a=t[o];if(a===void 0)return!1;const l=i[a];if(l==null||typeof l!="object")return!1;s=l}if(!s)return!1;const r=t[t.length-1];return!r||!(r in s)?!1:(s[r]=n,!0)}function hr(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function gl(e,t=""){const n={};return e&&typeof e=="object"?Object.entries(e).forEach(([s,r])=>{const o=t?`${t}.${s}`:s;n[o]=hr(r),r&&typeof r=="object"&&Object.assign(n,gl(r,o))}):t&&(n[t]=hr(e)),n}function hm(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:hs,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:hs,includeFieldStatus:!1,preserve:[]};const t=e.strategy??(e.fields&&e.fields.length>0?"fields":"full");return{strategy:t,fields:t==="fields"?e.fields??[]:[],placeholder:e.placeholder??hs,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function fm(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=hm(s);r&&(t[n]=r)}return t}function yl(e,t,n){const s=n.placeholder,r={tool:e,redacted:!0,strategy:n.strategy,placeholder:s};if(n.strategy==="full"){n.includeFieldStatus&&typeof t=="object"&&t!==null&&(r.fieldStatus=gl(t)),r.redactedFields=["*"];let l={};return n.preserve.length>0&&t&&typeof t=="object"&&n.preserve.forEach(u=>{u in t&&(l[u]=t[u])}),l[ds]=r,l}if(n.fields.includes("*"))return yl(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[ds]:{...r,redactedFields:n.fields}};const o=lm(t),i=[],a={};return n.fields.forEach(l=>{const u=cm(l);if(u.length===0)return;const d=um(o,u),h=hr(d);a[l]=h,dm(o,u,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[ds]=r,o}function mm({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:l,sensitiveOutputs:u,autoDetectSensitive:d=!1,autoFormGeneration:h=!1,formMode:m="auto",systemPrompt:p="",initialMessages:v=[],conversationId:x,state:T,onStateChange:y,allowStateEdits:w=!0,onToolCall:k,onFinish:O,sources:E,ragConfig:B,ragFilters:_,secureInputHandler:M}={}){const R=f.useMemo(()=>B!==void 0?B:_?{enabled:!0,filters:_}:E&&E.length>0?{enabled:!0,organizationId:E[0],autoExecute:!0,filters:void 0}:{enabled:!1},[E,B,_]),j=f.useMemo(()=>{const b={};if(l)for(const[C,S]of Object.entries(l))if(b[C]={},Array.isArray(S))for(const A of S){const D=Mn(A);b[C][A]=D||"text"}else for(const[A,D]of Object.entries(S))b[C][A]=D;if(a){for(const[C,S]of Object.entries(a))if(S&&typeof S=="object"&&"sensitiveParams"in S){b[C]||(b[C]={});const A=S.sensitiveParams;if(Array.isArray(A))for(const D of A){const q=Mn(D);b[C][D]=q||"text"}else if(A&&typeof A=="object")for(const[D,q]of Object.entries(A))b[C][D]=q}}return b},[l,a,d]),V=f.useMemo(()=>fm(u),[u]),z=f.useCallback((b,C)=>{const S=V[b];if(!S)return C;try{return yl(b,C,S)}catch(A){return console.error(`[useAgent] Failed to redact output for ${b}:`,A),{value:hs,[ds]:{tool:b,redacted:!0,error:String(A)}}}},[V]),[N,K]=f.useState(n||null),Y=f.useRef(n||null),[ae,Q]=f.useState(null),[ne,Z]=f.useState(null),we=f.useRef(null),[Je,Me]=f.useState([]),[Ze,Bt]=f.useState(x||(typeof window<"u"?crypto.randomUUID():null)),[Jr,it]=f.useState(!1),[ot,Ue]=f.useState(new Set),[xn,_e]=f.useState(new Map),[zt,Ut]=f.useState(new Map),[Wn,bn]=f.useState(new Map),[Pt,oe]=f.useState(new Map),ce=T!==void 0,[Ie,Qe]=f.useState({}),ue=f.useRef({}),vn=ce?T||{}:Ie;ce&&T?ue.current=T:ce||(ue.current=Ie);const[Kn,_t]=f.useState(!1),[wn,At]=f.useState(null),Xt=f.useRef(!1),Tn=f.useCallback(async(b,C=3)=>{if(!Ze||!Y.current)return;const S=async()=>{const D=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,q=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Ze,updates:b},format:"json"})});if(!q.ok){if(q.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const H=await q.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${q.status} ${H}`)}};for(let A=0;A<C;A++)try{await S(),At(null);return}catch(D){if(A===C-1){const H=D instanceof Error?D:new Error(String(D));throw At(H),console.error("Failed to sync state to Convex after retries:",D),H}await new Promise(H=>setTimeout(H,Math.pow(2,A)*100))}},[Ze,e,Y]),at=f.useMemo(()=>function(){return ue.current},[]),Xe=f.useMemo(()=>async function(C){const S={...ue.current,...C};ue.current=S,ce||Qe(S),y&&y(S);try{await Tn(C)}catch(A){throw A}},[Tn,y,ce]);f.useEffect(()=>{ce&&T&&(ue.current=T)},[ce,T]);const kt=f.useCallback(b=>M?M.showSecureModal(b):new Promise(C=>{_e(S=>new Map(S).set(b.id,b)),Ut(S=>new Map(S).set(b.id,C))}),[M]),Sn=f.useCallback((b,C)=>{if(M)return;const S=zt.get(b);S&&(S(C),_e(A=>{const D=new Map(A);return D.delete(b),D}),Ut(A=>{const D=new Map(A);return D.delete(b),D}))},[zt,M]),Gn=f.useCallback(b=>M?M.showSecureForm(b):new Promise(C=>{bn(S=>new Map(S).set(b.id,b)),oe(S=>new Map(S).set(b.id,C))}),[M]),js=f.useCallback((b,C)=>{if(M)return;const S=Pt.get(b);S&&(S(C),bn(A=>{const D=new Map(A);return D.delete(b),D}),oe(A=>{const D=new Map(A);return D.delete(b),D}))},[Pt,M]),jn=f.useCallback((b,C)=>{const S=j[b]||{},A=Object.keys(S).length>0;if(d){const D=Object.keys(C).filter(q=>Mn(q)!==null);return A||D.length>0}return A},[j,d]),Yn=f.useCallback((b,C)=>{const A={...j[b]||{}};if(d){for(const q of Object.keys(C))if(!(q in A)){const H=Mn(q);H&&(A[q]=H)}}const D=Object.entries(A).filter(([q])=>Object.prototype.hasOwnProperty.call(C,q));return D.length>0?Object.fromEntries(D):A},[j,d]),qe=f.useMemo(()=>R?.enabled?async function(C,S=20,A){const D={...R.filters,...A};if(E&&E.length>1){const H=E.map(ee=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...Y.current?{Authorization:`Bearer ${Y.current}`}:{}},body:JSON.stringify({q:C,k:Math.min(S,100),organizationId:ee,...Object.keys(D).length>0?{filters:D}:{}})}).then(le=>le.ok?le.json():null)),pe=await Promise.all(H),ye=[];for(const ee of pe)ee?.candidates&&ye.push(...ee.candidates);ye.sort((ee,le)=>{const nt=ee.scores?.rerank||ee.scores?.dense||0;return(le.scores?.rerank||le.scores?.dense||0)-nt});const Ve=ye.slice(0,S).map((ee,le)=>{const nt=ee.citation||ee.url;return{rank:le+1,doc_id:ee.doc_id,block_id:ee.block_id,url:ee.url,citation:nt,title:ee.title||"Untitled",snippet:ee.snippet,score:ee.scores?.rerank||ee.scores?.dense||0,metadata:{site:ee.metadata?.site,lang:ee.metadata?.lang,contentType:ee.metadata?.content_type}}});return{success:!0,query:C,total:ye.length,results:Ve,summary:`Found ${ye.length} relevant results across ${E.length} source(s) for "${C}". Top result: ${Ve[0]?.title||"N/A"}`}}const q=R.organizationId&&R.organizationId!=="default"?R.organizationId:E&&E.length>0?E[0]:void 0;try{const H={q:C,k:Math.min(S,100)};q&&(H.organizationId=q),Object.keys(D).length>0&&(H.filters=D);const pe={"Content-Type":"application/json"};Y.current&&(pe.Authorization=`Bearer ${Y.current}`);const ye=await fetch(`${e}/search`,{method:"POST",headers:pe,body:JSON.stringify(H)});if(!ye.ok){const le=await ye.text();return{success:!1,error:`Search failed: ${ye.status} ${le}`}}const Ve=await ye.json(),ee=Ve.candidates.map((le,nt)=>{const Te=le.citation||le.url;return{rank:nt+1,doc_id:le.doc_id,block_id:le.block_id,url:le.url,citation:Te,title:le.title||"Untitled",snippet:le.snippet,score:le.scores?.rerank||le.scores?.dense||0,metadata:{site:le.metadata?.site,lang:le.metadata?.lang,contentType:le.metadata?.content_type}}});return{success:!0,query:Ve.query,total:Ve.total,results:ee,summary:`Found ${Ve.total} relevant results for "${C}". Top result: ${ee[0]?.title||"N/A"}`}}catch(H){return{success:!1,error:H instanceof Error?H.message:"Unknown error occurred"}}}:null,[R,e,Y]),Ee=f.useMemo(()=>R?.enabled?async function(C,S){const A=R.organizationId&&R.organizationId!=="default"?R.organizationId:E&&E.length>0?E[0]:void 0;try{const D={"Content-Type":"application/json"};Y.current&&(D.Authorization=`Bearer ${Y.current}`);const q=await fetch(`${e}/fetch`,{method:"POST",headers:D,body:JSON.stringify({doc_id:C,block_ids:S,...A?{organizationId:A}:{}})});if(!q.ok){const pe=await q.text();return{success:!1,error:`Fetch failed: ${q.status} ${pe}`}}const H=await q.json();return{success:!0,blocks:H.blocks||[],fullContent:H.fullContent||"",pageUrl:H.pageUrl||"",pageTitle:H.pageTitle||"",summary:`Fetched ${H.blocks?.length||0} blocks from ${H.pageTitle||C}`}}catch(D){return{success:!1,error:D instanceof Error?D.message:"Unknown error occurred"}}}:null,[R,e,Y]),qt=f.useMemo(()=>{const b=[...o,...i,at];return(!ce||w)&&b.push(Xe),R?.enabled&&(qe&&b.push(qe),Ee&&b.push(Ee)),b},[o,i,at,Xe,qe,Ee,R,ce,w]),lt=f.useMemo(()=>il(qt,a),[qt,a]),Re=f.useMemo(()=>{const b=new Map,C=new Map(lt.map(S=>[S.name,S]));return b.set("getState",at),(!ce||w)&&b.set("setState",Xe),R?.enabled&&(qe&&b.set("searchDocs",qe),Ee&&b.set("fetchDocContent",Ee)),qt.forEach(S=>{if(S===at||S===Xe||S===qe||S===Ee)return;const A=S[st];if(A){const q=C.get(A);if(q){b.set(q.name,S);return}}const D=lt.find(q=>q.name===S.name);D&&b.set(D.name,S)}),b},[qt,lt,at,Xe,qe,Ee,R,ce,w]),Hn=f.useMemo(()=>new Set(lt.map(b=>b.name)),[lt]),Wt=f.useMemo(()=>{const b=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!ce||w)&&b.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 R?.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"]}}),[...lt,...b,...C]},[lt,R,ce,w]),Mt=f.useMemo(()=>Wt.filter(b=>b.name==="getState"?!0:b.name==="setState"?!ce||w:R?.enabled&&(b.name==="searchDocs"||b.name==="fetchDocContent")?!0:Hn.has(b.name)),[Wt,Hn,ce,w,R]),Kt=f.useMemo(()=>{const b=new Set;return b.add("getState"),b.add("setState"),R?.enabled&&R.autoExecute!==!1&&(b.add("searchDocs"),b.add("fetchDocContent")),i.forEach(C=>{for(const[S,A]of Re.entries())if(A===C){b.add(S);break}}),b},[i,Re,R]);f.useEffect(()=>s||n?void 0:((async()=>{try{const C=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!C.ok)throw new Error("Failed to fetch token");const S=await C.json();K(S.clientToken),Y.current=S.clientToken,Z(S.expiresAt),Q(null)}catch(C){console.error("[useAgent] Token fetch failed:",C),Q(C instanceof Error?C.message:"Failed to fetch token")}})(),()=>{we.current&&clearTimeout(we.current)}),[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!ne||s||n)return;we.current&&clearTimeout(we.current);const b=Math.floor(Date.now()/1e3),C=ne-b,A=Math.max(0,C-5);return we.current=setTimeout(async()=>{try{const D=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!D.ok)throw new Error("Failed to refresh token");const q=await D.json();K(q.clientToken),Y.current=q.clientToken,Z(q.expiresAt),Q(null)}catch(D){console.error("[useAgent] Token refresh failed:",D),Q(D instanceof Error?D.message:"Failed to refresh token")}},A*1e3),()=>{we.current&&clearTimeout(we.current)}},[ne,t,JSON.stringify(r),s,n]);const Jn=async(b,C={})=>{const S=C.headers?new Headers(C.headers):new Headers;S.delete("user-agent"),S.delete("User-Agent"),console.log("[useAgent] Making request to:",b),console.log("[useAgent] Method:",C.method||"GET"),console.log("[useAgent] Has Authorization header:",S.has("Authorization")),console.log("[useAgent] Client token available:",!!Y.current);try{const A=await fetch(b,{...C,headers:S});if(!A.ok){console.error("[useAgent] Request failed:",A.status,A.statusText);const D=await A.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",D)}return A}catch(A){throw console.error("[useAgent] Fetch error:",A),A}},We=`${e}/chat`;console.log("[useAgent] Chat API URL:",We);const{messages:Oe,sendMessage:mt,status:pt,error:Zn,stop:Gt,addToolResult:Qn,setMessages:gt}=wo.useChat({id:Ze||void 0,messages:v,transport:new fs.DefaultChatTransport({api:We,fetch:Jn,headers:()=>{const b={};return Y.current?(b.Authorization=`Bearer ${Y.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),b},body:()=>{const b=Mt.map(A=>({name:A.name,description:A.description,inputSchema:A.jsonSchema})),C=b.filter(A=>A.name==="getState"||A.name==="setState").map(A=>A.name),S=b.filter(A=>A.name==="searchDocs"||A.name==="fetchDocContent").map(A=>A.name);return C.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",C),S.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",S):R?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:b,systemPrompt:p,state:ue.current,..._&&{ragFilters:_}}}}),sendAutomaticallyWhen:fs.lastAssistantMessageIsCompleteWithToolCalls}),et=f.useCallback((b,C,S)=>{const A=z(b,S);Qn({toolCallId:C,tool:b,output:A})},[Qn,z]);f.useEffect(()=>{Oe.forEach(b=>{b.role==="assistant"&&b.parts.forEach(C=>{if(!C.type?.startsWith("tool-")||C.state!=="input-available")return;const S=C.type.replace("tool-",""),A=C.toolCallId;if(ot.has(A))return;Ue(q=>new Set(q).add(A));const D=am(C.input);if(jn(S,D)){const q=Yn(S,D),H=Object.entries(q).filter(([ee])=>D[ee]!==void 0),pe=H.length>0?Object.fromEntries(H):q,ye=Object.keys(D),Ve=om(D,pe);(async()=>{try{let ee={};if(h&&(m==="batch"||m==="auto"&&ml(S,ye,pe))){const Ne=em(S,ye,pe,D),Ke={id:`${A}-form`,toolName:S,toolCallId:A,title:Ne.title,description:Ne.description,fields:Ne.fields},Se=await Gn(Ke);if(Se===null){et(S,A,"User cancelled secure input");return}ee=Se}else for(const[Ne,Ke]of Object.entries(pe)){const Se=fl(Ke,Ne),Yt={id:`${A}-${Ne}`,type:Ke,paramName:Ne,toolName:S,toolCallId:A,title:Se.title,description:Se.description,placeholder:Se.placeholder},es=await kt(Yt);if(es===null){et(S,A,"User cancelled secure input");return}ee[Ne]=es}const nt={...Ve,...ee},Te=Re.get(S);if(!Te)throw new Error(`Tool ${S} not found`);let Pn;const Pe=Mt.find(Ne=>Ne.name===S);if(Pe&&Pe.jsonSchema?.properties){const Ke=Object.keys(Pe.jsonSchema.properties).map(Se=>nt[Se]);Pn=await Te(...Ke)}else Pn=await Te(...Object.values(nt));et(S,A,Pn)}catch(ee){console.error(`[useAgent] Error executing tool with secure input ${S}:`,ee),et(S,A,`Error: ${ee}`)}})();return}if(Kt.has(S)&&!jn(S,D)){const q=Re.get(S);q?(async()=>{try{const H=Mt.find(ye=>ye.name===S);let pe;if(H&&H.jsonSchema?.properties){const Ve=Object.keys(H.jsonSchema.properties).map(ee=>D[ee]);pe=await q(...Ve)}else if(S==="getState")pe=q();else if(S==="setState"){const ye=D.updates||D;pe=await q(ye)}else pe=await q(...Object.values(D));et(S,A,pe)}catch(H){console.error(`[useAgent] Error executing tool ${S}:`,H),et(S,A,`Error: ${H}`)}})():console.warn(`[useAgent] Tool ${S} not found in toolsMap`)}else k&&k({toolCall:{toolCallId:A,toolName:S,args:D}})})})},[Oe,Kt,Re,k,et,ot,Xe,Mt,jn,Yn,kt]),f.useEffect(()=>{if(pt==="ready"&&Oe.length>0&&O){const b=Oe[Oe.length-1];b&&b.role==="assistant"&&O({message:b,messages:Oe,isAbort:!1,isDisconnect:!1,isError:!!Zn})}},[pt,Oe,Zn,O]);async function Et(){if(!(!r?.id||!N)){it(!0);try{const C=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${N}`}})).json();Me(C.conversations||[])}catch(b){console.error("Failed to fetch conversations:",b)}finally{it(!1)}}}f.useEffect(()=>{r?.id&&N&&Et()},[JSON.stringify(r),N,e]),f.useEffect(()=>{if(!Ze||!Y.current)return;(async()=>{_t(!0),At(null);try{const C=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Ze},format:"json"})});if(!C.ok){const D=await C.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${C.status} ${D}`)}const A=(await C.json())?.value||{};ue.current=A,ce||Qe(A),y&&y(A),Xt.current=!0}catch(C){console.error("Failed to fetch state:",C);const S=C instanceof Error?C:new Error(String(C));At(S),Xt.current||(ue.current={},ce?y&&y({}):(Qe({}),y&&y({})),Xt.current=!0)}finally{_t(!1)}})()},[Ze,e,ce,y]);async function Nt(b){Bt(b),it(!0);try{const C=await fetch(`${e}/conversations/${b}/messages`,{headers:{Authorization:`Bearer ${Y.current}`}});if(!C.ok)throw new Error(`Failed to fetch messages: ${C.statusText}`);const A=(await C.json()).messages||[];gt(A)}catch(C){console.error("Failed to load conversation messages:",C)}finally{it(!1)}}async function ct(b){if(N)try{await fetch(`${e}/conversations/${b}`,{method:"DELETE",headers:{Authorization:`Bearer ${N}`}}),Me(Je.filter(C=>C._id!==b)),b===Ze&&tt()}catch(C){console.error("Failed to delete conversation:",C)}}function tt(){const b=crypto.randomUUID();Bt(b),gt([]),Ue(new Set),ue.current={},ce?y&&y({}):(Qe({}),y&&y({})),Xt.current=!1}function ut(b){const C=b.tool||"unknown-tool",S=z(C,b.output);Qn({toolCallId:b.toolCallId,tool:C,output:S})}async function Cn(b){const C={...ue.current,...b};ue.current=C,ce||Qe(C),y&&y(C);try{await Tn(b)}catch(S){throw S}}return{id:Ze,messages:Oe,status:pt,error:Zn,sendMessage:mt,stop:Gt,addToolOutput:ut,setMessages:gt,conversations:Je,loadConversation:Nt,deleteConversation:ct,startNewConversation:tt,isLoadingConversations:Jr,clientToken:N,tokenError:ae,state:vn,setState:Cn,isStateLoading:Kn,stateError:wn,pendingSecureInputs:Array.from(xn.values()),completeSecureInput:Sn,pendingSecureForms:Array.from(Wn.values()),completeSecureForm:js}}exports.verifyToken=Ll.verifyToken;exports.ARCTEN_ORIGINAL_NAME=st;exports.ArctenAgent=Zf;exports.SecureModalProvider=hl;exports.preserveToolName=Cf;exports.useAgent=mm;exports.useSecureModal=dl;