@arcteninc/core 0.0.124 → 0.0.126

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 kl=Object.create;var ii=Object.defineProperty;var Ml=Object.getOwnPropertyDescriptor;var El=Object.getOwnPropertyNames;var Nl=Object.getPrototypeOf,Dl=Object.prototype.hasOwnProperty;var Rl=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of El(t))!Dl.call(e,r)&&r!==n&&ii(e,r,{get:()=>t[r],enumerable:!(s=Ml(t,r))||s.enumerable});return e};var Vl=(e,t,n)=>(n=e!=null?kl(Nl(e)):{},Rl(t||!e||!e.__esModule?ii(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),f=require("react"),ne=require("lucide-react"),Po=require("@ai-sdk/react"),gs=require("ai"),Ao=require("@radix-ui/react-slot"),ko=require("class-variance-authority"),Il=require("clsx"),Ol=require("tailwind-merge"),$l=require("@radix-ui/react-tooltip"),oi=require("@radix-ui/react-use-controllable-state"),Ll=require("@radix-ui/react-collapsible"),Fl=require("react-dom"),Bl=require("@radix-ui/react-dialog"),zl=require("./server.cjs");function Ts(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=Ts(f),Zt=Ts($l),gr=Ts(Ll),$t=Ts(Bl);function re(...e){return Ol.twMerge(Il.clsx(e))}const Nt=ko.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=Ge.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?Ao.Slot:"button";return c.jsx(i,{ref:o,"data-slot":"button",className:re(Nt({variant:t,size:n,className:e})),...r})});Ce.displayName="Button";const Ul=ko.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 ks({className:e,variant:t,asChild:n=!1,...s}){const r=n?Ao.Slot:"span";return c.jsx(r,{"data-slot":"badge",className:re(Ul({variant:t}),e),...s})}const _l=({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])},Mo=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 _l({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:re("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)}})});Mo.displayName="AutosizeTextarea";function Xl({delayDuration:e=0,...t}){return c.jsx(Zt.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function yt({...e}){return c.jsx(Xl,{children:c.jsx(Zt.Root,{"data-slot":"tooltip",...e})})}function xt({...e}){return c.jsx(Zt.Trigger,{"data-slot":"tooltip-trigger",...e})}function bt({className:e,sideOffset:t=0,children:n,...s}){return c.jsx(Zt.Portal,{children:c.jsxs(Zt.Content,{"data-slot":"tooltip-content",sideOffset:t,className:re("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(Zt.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function ai({className:e,...t}){return c.jsx("kbd",{"data-slot":"kbd",className:re("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 yr=f.createContext({});function xr(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const br=typeof window<"u",Eo=br?f.useLayoutEffect:f.useEffect,Ss=f.createContext(null);function vr(e,t){e.indexOf(t)===-1&&e.push(t)}function wr(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const at=(e,t,n)=>n>t?t:n<e?e:n;function Ws(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let nn=()=>{},lt=()=>{};process.env.NODE_ENV!=="production"&&(nn=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(Ws(t,n))},lt=(e,t,n)=>{if(!e)throw new Error(Ws(t,n))});const ct={},No=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Do(e){return typeof e=="object"&&e!==null}const Ro=e=>/^0[^.\s]+$/u.test(e);function Tr(e){let t;return()=>(t===void 0&&(t=e()),t)}const ze=e=>e,ql=(e,t)=>n=>t(e(n)),zn=(...e)=>e.reduce(ql),In=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class Sr{constructor(){this.subscriptions=[]}add(t){return vr(this.subscriptions,t),()=>wr(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,Be=e=>e/1e3;function Vo(e,t){return t?e*(1e3/t):0}const li=new Set;function jr(e,t,n){e||li.has(t)||(console.warn(Ws(t,n)),li.add(t))}const Io=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Wl=1e-7,Kl=12;function Gl(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=Io(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>Wl&&++a<Kl);return i}function Un(e,t,n,s){if(e===t&&n===s)return ze;const r=o=>Gl(o,0,1,e,n);return o=>o===0||o===1?o:Io(r(o),t,s)}const Oo=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,$o=e=>t=>1-e(1-t),Lo=Un(.33,1.53,.69,.99),Cr=$o(Lo),Fo=Oo(Cr),Bo=e=>(e*=2)<1?.5*Cr(e):.5*(2-Math.pow(2,-10*(e-1))),Pr=e=>1-Math.sin(Math.acos(e)),zo=$o(Pr),Uo=Oo(Pr),Yl=Un(.42,0,1,1),Hl=Un(0,0,.58,1),_o=Un(.42,0,.58,1),Jl=e=>Array.isArray(e)&&typeof e[0]!="number",Xo=e=>Array.isArray(e)&&typeof e[0]=="number",ci={linear:ze,easeIn:Yl,easeInOut:_o,easeOut:Hl,circIn:Pr,circInOut:Uo,circOut:zo,backIn:Cr,backInOut:Fo,backOut:Lo,anticipate:Bo},Zl=e=>typeof e=="string",ui=e=>{if(Xo(e)){lt(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return Un(t,n,s,r)}else if(Zl(e))return lt(ci[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),ci[e];return e},rs=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Ql(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 w=m&&r?n:s;return h&&i.add(d),w.has(d)||w.add(d),d},cancel:d=>{s.delete(d),i.delete(d)},process:d=>{if(a=d,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(l),n.clear(),r=!1,o&&(o=!1,u.process(d))}};return u}const ec=40;function qo(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=rs.reduce((v,E)=>(v[E]=Ql(o),v),{}),{setup:a,read:l,resolveKeyframes:u,preUpdate:d,update:h,preRender:m,render:p,postRender:w}=i,b=()=>{const v=ct.useManualTiming?r.timestamp:performance.now();n=!1,ct.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(v-r.timestamp,ec),1)),r.timestamp=v,r.isProcessing=!0,a.process(r),l.process(r),u.process(r),d.process(r),h.process(r),m.process(r),p.process(r),w.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(b))},j=()=>{n=!0,s=!0,r.isProcessing||e(b)};return{schedule:rs.reduce((v,E)=>{const D=i[E];return v[E]=($,L=!1,N=!1)=>(n||j(),D.schedule($,L,N)),v},{}),cancel:v=>{for(let E=0;E<rs.length;E++)i[rs[E]].cancel(v)},state:r,steps:i}}const{schedule:de,cancel:wt,state:Se,steps:Ms}=qo(typeof requestAnimationFrame<"u"?requestAnimationFrame:ze,!0);let cs;function tc(){cs=void 0}const Ee={now:()=>(cs===void 0&&Ee.set(Se.isProcessing||ct.useManualTiming?Se.timestamp:performance.now()),cs),set:e=>{cs=e,queueMicrotask(tc)}},Wo=e=>t=>typeof t=="string"&&t.startsWith(e),Ar=Wo("--"),nc=Wo("var(--"),kr=e=>nc(e)?sc.test(e.split("/*")[0].trim()):!1,sc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,sn={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},On={...sn,transform:e=>at(0,1,e)},is={...sn,default:1},Mn=e=>Math.round(e*1e5)/1e5,Mr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function rc(e){return e==null}const ic=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Er=(e,t)=>n=>!!(typeof n=="string"&&ic.test(n)&&n.startsWith(e)||t&&!rc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ko=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Mr);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},oc=e=>at(0,255,e),Es={...sn,transform:e=>Math.round(oc(e))},Rt={test:Er("rgb","red"),parse:Ko("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+Es.transform(e)+", "+Es.transform(t)+", "+Es.transform(n)+", "+Mn(On.transform(s))+")"};function ac(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 Ks={test:Er("#"),parse:ac,transform:Rt.transform},_n=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),vt=_n("deg"),et=_n("%"),G=_n("px"),lc=_n("vh"),cc=_n("vw"),di={...et,parse:e=>et.parse(e)/100,transform:e=>et.transform(e*100)},Wt={test:Er("hsl","hue"),parse:Ko("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+et.transform(Mn(t))+", "+et.transform(Mn(n))+", "+Mn(On.transform(s))+")"},ve={test:e=>Rt.test(e)||Ks.test(e)||Wt.test(e),parse:e=>Rt.test(e)?Rt.parse(e):Wt.test(e)?Wt.parse(e):Ks.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Rt.transform(e):Wt.transform(e),getAnimatableNone:e=>{const t=ve.parse(e);return t.alpha=0,ve.transform(t)}},uc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function dc(e){return isNaN(e)&&typeof e=="string"&&(e.match(Mr)?.length||0)+(e.match(uc)?.length||0)>0}const Go="number",Yo="color",hc="var",fc="var(",hi="${}",mc=/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 $n(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(mc,l=>(ve.test(l)?(s.color.push(o),r.push(Yo),n.push(ve.parse(l))):l.startsWith(fc)?(s.var.push(o),r.push(hc),n.push(l)):(s.number.push(o),r.push(Go),n.push(parseFloat(l))),++o,hi)).split(hi);return{values:n,split:a,indexes:s,types:r}}function Ho(e){return $n(e).values}function Jo(e){const{split:t,types:n}=$n(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===Go?o+=Mn(r[i]):a===Yo?o+=ve.transform(r[i]):o+=r[i]}return o}}const pc=e=>typeof e=="number"?0:ve.test(e)?ve.getAnimatableNone(e):e;function gc(e){const t=Ho(e);return Jo(e)(t.map(pc))}const Tt={test:dc,parse:Ho,createTransformer:Jo,getAnimatableNone:gc};function Ns(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function yc({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=Ns(l,a,e+1/3),o=Ns(l,a,e),i=Ns(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function ys(e,t){return n=>n>0?t:e}const fe=(e,t,n)=>e+(t-e)*n,Ds=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},xc=[Ks,Rt,Wt],bc=e=>xc.find(t=>t.test(e));function fi(e){const t=bc(e);if(nn(!!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===Wt&&(n=yc(n)),n}const mi=(e,t)=>{const n=fi(e),s=fi(t);if(!n||!s)return ys(e,t);const r={...n};return o=>(r.red=Ds(n.red,s.red,o),r.green=Ds(n.green,s.green,o),r.blue=Ds(n.blue,s.blue,o),r.alpha=fe(n.alpha,s.alpha,o),Rt.transform(r))},Gs=new Set(["none","hidden"]);function vc(e,t){return Gs.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function wc(e,t){return n=>fe(e,t,n)}function Nr(e){return typeof e=="number"?wc:typeof e=="string"?kr(e)?ys:ve.test(e)?mi:jc:Array.isArray(e)?Zo:typeof e=="object"?ve.test(e)?mi:Tc:ys}function Zo(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>Nr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Tc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=Nr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Sc(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 jc=(e,t)=>{const n=Tt.createTransformer(t),s=$n(e),r=$n(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?Gs.has(e)&&!r.values.length||Gs.has(t)&&!s.values.length?vc(e,t):zn(Zo(Sc(s,r),r.values),n):(nn(!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"),ys(e,t))};function Qo(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?fe(e,t,n):Nr(e)(e,t)}const Cc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>de.update(t,n),stop:()=>wt(t),now:()=>Se.isProcessing?Se.timestamp:Ee.now()}},ea=(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)})`},xs=2e4;function Dr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<xs;)t+=n,s=e.next(t);return t>=xs?1/0:t}function Pc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(Dr(s),xs);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:Be(r)}}const Ac=5;function ta(e,t,n){const s=Math.max(t-Ac,0);return Vo(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},Rs=.001;function kc({duration:e=he.duration,bounce:t=he.bounce,velocity:n=he.velocity,mass:s=he.mass}){let r,o;nn(e<=Ye(he.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=at(he.minDamping,he.maxDamping,i),e=at(he.minDuration,he.maxDuration,Be(e)),i<1?(r=u=>{const d=u*i,h=d*e,m=d-n,p=Ys(u,i),w=Math.exp(-h);return Rs-m/p*w},o=u=>{const h=u*i*e,m=h*n+n,p=Math.pow(i,2)*Math.pow(u,2)*e,w=Math.exp(-h),b=Ys(Math.pow(u,2),i);return(-r(u)+Rs>0?-1:1)*((m-p)*w)/b}):(r=u=>{const d=Math.exp(-u*e),h=(u-n)*e+1;return-Rs+d*h},o=u=>{const d=Math.exp(-u*e),h=(n-u)*(e*e);return d*h});const a=5/e,l=Ec(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 Mc=12;function Ec(e,t,n){let s=n;for(let r=1;r<Mc;r++)s=s-e(s)/t(s);return s}function Ys(e,t){return e*Math.sqrt(1-t*t)}const Nc=["duration","bounce"],Dc=["stiffness","damping","mass"];function pi(e,t){return t.some(n=>e[n]!==void 0)}function Rc(e){let t={velocity:he.velocity,stiffness:he.stiffness,damping:he.damping,mass:he.mass,isResolvedFromDuration:!1,...e};if(!pi(e,Dc)&&pi(e,Nc))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*at(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:he.mass,stiffness:r,damping:o}}else{const n=kc(e);t={...t,...n,mass:he.mass},t.isResolvedFromDuration=!0}return t}function bs(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}=Rc({...n,velocity:-Be(n.velocity||0)}),w=m||0,b=u/(2*Math.sqrt(l*d)),j=i-o,y=Be(Math.sqrt(l/d)),k=Math.abs(j)<5;s||(s=k?he.restSpeed.granular:he.restSpeed.default),r||(r=k?he.restDelta.granular:he.restDelta.default);let v;if(b<1){const D=Ys(y,b);v=$=>{const L=Math.exp(-b*y*$);return i-L*((w+b*y*j)/D*Math.sin(D*$)+j*Math.cos(D*$))}}else if(b===1)v=D=>i-Math.exp(-y*D)*(j+(w+y*j)*D);else{const D=y*Math.sqrt(b*b-1);v=$=>{const L=Math.exp(-b*y*$),N=Math.min(D*$,300);return i-L*((w+b*y*j)*Math.sinh(N)+D*j*Math.cosh(N))/D}}const E={calculatedDuration:p&&h||null,next:D=>{const $=v(D);if(p)a.done=D>=h;else{let L=D===0?w:0;b<1&&(L=D===0?Ye(w):ta(v,D,$));const N=Math.abs(L)<=s,z=Math.abs(i-$)<=r;a.done=N&&z}return a.value=a.done?i:$,a},toString:()=>{const D=Math.min(Dr(E),xs),$=ea(L=>E.next(D*L).value,D,30);return D+"ms "+$},toTransition:()=>{}};return E}bs.applyToOptions=e=>{const t=Pc(e,100,bs);return e.ease=t.ease,e.duration=Ye(t.duration),e.type="keyframes",e};function Hs({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=N=>a!==void 0&&N<a||l!==void 0&&N>l,w=N=>a===void 0?l:l===void 0||Math.abs(a-N)<Math.abs(l-N)?a:l;let b=n*t;const j=h+b,y=i===void 0?j:i(j);y!==j&&(b=y-h);const k=N=>-b*Math.exp(-N/s),v=N=>y+k(N),E=N=>{const z=k(N),A=v(N);m.done=Math.abs(z)<=u,m.value=m.done?y:A};let D,$;const L=N=>{p(m.value)&&(D=N,$=bs({keyframes:[m.value,w(m.value)],velocity:ta(v,N,m.value),damping:r,stiffness:o,restDelta:u,restSpeed:d}))};return L(0),{calculatedDuration:null,next:N=>{let z=!1;return!$&&D===void 0&&(z=!0,E(N),L(N)),D!==void 0&&N>=D?$.next(N-D):(!z&&E(N),m)}}}function Vc(e,t,n){const s=[],r=n||ct.mix||Qo,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=zn(l,a)}s.push(a)}return s}function Ic(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(lt(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=Vc(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=In(e[h],e[h+1],d);return a[h](m)};return n?d=>u(at(e[0],e[o-1],d)):u}function Oc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=In(0,t,s);e.push(fe(n,1,r))}}function $c(e){const t=[0];return Oc(t,e.length-1),t}function Lc(e,t){return e.map(n=>n*t)}function Fc(e,t){return e.map(()=>t||_o).splice(0,e.length-1)}function Kt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=Jl(s)?s.map(ui):ui(s),o={done:!1,value:t[0]},i=Lc(n&&n.length===t.length?n:$c(t),e),a=Ic(i,t,{ease:Array.isArray(r)?r:Fc(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const Bc=e=>e!==null;function Rr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(Bc),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const zc={decay:Hs,inertia:Hs,tween:Kt,keyframes:Kt,spring:bs};function na(e){typeof e.type=="string"&&(e.type=zc[e.type])}class Vr{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 Uc=e=>e/100;class Ir extends Vr{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==Ee.now()&&this.tick(Ee.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;na(t);const{type:n=Kt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const l=n||Kt;process.env.NODE_ENV!=="production"&&l!==Kt&&lt(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),l!==Kt&&typeof a[0]!="number"&&(this.mixKeyframes=zn(Uc,Qo(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=Dr(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:w,onUpdate:b,finalKeyframe:j}=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),k=this.playbackSpeed>=0?y<0:y>r;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let v=this.currentTime,E=s;if(h){const N=Math.min(this.currentTime,r)/a;let z=Math.floor(N),A=N%1;!A&&N>=1&&(A=1),A===1&&z--,z=Math.min(z,h+1),!!(z%2)&&(m==="reverse"?(A=1-A,p&&(A-=p/a)):m==="mirror"&&(E=i)),v=at(0,1,A)*a}const D=k?{done:!1,value:d[0]}:E.next(v);o&&(D.value=o(D.value));let{done:$}=D;!k&&l!==null&&($=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const L=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&$);return L&&w!==Hs&&(D.value=Rr(d,this.options,j,this.speed)),b&&b(D.value),L&&this.finish(),D}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=Ye(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(Ee.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=Be(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Cc,startTime:n}=this.options;this.driver||(this.driver=t(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Ee.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function _c(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Vt=e=>e*180/Math.PI,Js=e=>{const t=Vt(Math.atan2(e[1],e[0]));return Zs(t)},Xc={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Js,rotateZ:Js,skewX:e=>Vt(Math.atan(e[1])),skewY:e=>Vt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Zs=e=>(e=e%360,e<0&&(e+=360),e),gi=Js,yi=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),xi=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),qc={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:yi,scaleY:xi,scale:e=>(yi(e)+xi(e))/2,rotateX:e=>Zs(Vt(Math.atan2(e[6],e[5]))),rotateY:e=>Zs(Vt(Math.atan2(-e[2],e[0]))),rotateZ:gi,rotate:gi,skewX:e=>Vt(Math.atan(e[4])),skewY:e=>Vt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Qs(e){return e.includes("scale")?1:0}function er(e,t){if(!e||e==="none")return Qs(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=qc,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=Xc,r=a}if(!r)return Qs(t);const o=s[t],i=r[1].split(",").map(Kc);return typeof o=="function"?o(i):i[o]}const Wc=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return er(n,t)};function Kc(e){return parseFloat(e.trim())}const rn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],on=new Set(rn),bi=e=>e===sn||e===G,Gc=new Set(["x","y","z"]),Yc=rn.filter(e=>!Gc.has(e));function Hc(e){const t=[];return Yc.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const It={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>er(t,"x"),y:(e,{transform:t})=>er(t,"y")};It.translateX=It.x;It.translateY=It.y;const Ot=new Set;let tr=!1,nr=!1,sr=!1;function sa(){if(nr){const e=Array.from(Ot).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=Hc(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)})}nr=!1,tr=!1,Ot.forEach(e=>e.complete(sr)),Ot.clear()}function ra(){Ot.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(nr=!0)})}function Jc(){sr=!0,ra(),sa(),sr=!1}class Or{constructor(t,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(Ot.add(this),tr||(tr=!0,de.read(ra),de.resolveKeyframes(sa))):(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])}_c(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Ot.delete(this)}cancel(){this.state==="scheduled"&&(Ot.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Zc=e=>e.startsWith("--");function Qc(e,t,n){Zc(t)?e.style.setProperty(t,n):e.style[t]=n}const eu=Tr(()=>window.ScrollTimeline!==void 0),tu={};function nu(e,t){const n=Tr(e);return()=>tu[t]??n()}const ia=nu(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),An=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,vi={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:An([0,.65,.55,1]),circOut:An([.55,0,1,.45]),backIn:An([.31,.01,.66,-.59]),backOut:An([.33,1.53,.69,.99])};function oa(e,t){if(e)return typeof e=="function"?ia()?ea(e,t):"ease-out":Xo(e)?An(e):Array.isArray(e)?e.map(n=>oa(n,t)||vi.easeOut):vi[e]}function su(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=oa(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 aa(e){return typeof e=="function"&&"applyToOptions"in e}function ru({type:e,...t}){return aa(e)&&ia()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class iu extends Vr{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,lt(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=ru(t);this.animation=su(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Rr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Qc(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=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&&eu()?(this.animation.timeline=t,ze):n(this)}}const la={anticipate:Bo,backInOut:Fo,circInOut:Uo};function ou(e){return e in la}function au(e){typeof e.ease=="string"&&ou(e.ease)&&(e.ease=la[e.ease])}const wi=10;class lu extends iu{constructor(t){au(t),na(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new Ir({...i,autoplay:!1}),l=Ye(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-wi).value,a.sample(l).value,wi),a.stop()}}const Ti=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(Tt.test(e)||e==="0")&&!e.startsWith("url("));function cu(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 uu(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=Ti(r,t),a=Ti(o,t);return nn(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:cu(e)||(n==="spring"||aa(n))&&s}function rr(e){e.duration=0,e.type="keyframes"}const du=new Set(["opacity","clipPath","filter","transform"]),hu=Tr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function fu(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 hu()&&n&&du.has(n)&&(n!=="transform"||!u)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const mu=40;class pu extends Vr{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=Ee.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||Or;this.keyframeResolver=new p(a,(w,b,j)=>this.onKeyframesResolved(w,b,m,!j),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=Ee.now(),uu(t,o,i,a)||((ct.instantAnimations||!l)&&d?.(Rr(t,s,n)),t[0]=t[t.length-1],rr(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>mu?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!u&&fu(m)?new lu({...m,element:m.motionValue.owner.current}):new Ir(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(),Jc()),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 gu=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function yu(e){const t=gu.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const xu=4;function ca(e,t,n=1){lt(n<=xu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=yu(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return No(i)?parseFloat(i):i}return kr(r)?ca(r,t,n+1):r}function $r(e,t){return e?.[t]??e?.default??e}const ua=new Set(["width","height","top","left","right","bottom",...rn]),bu={test:e=>e==="auto",parse:e=>e},da=e=>t=>t.test(e),ha=[sn,G,et,vt,cc,lc,bu],Si=e=>ha.find(da(e));function vu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||Ro(e):!0}const wu=new Set(["brightness","contrast","saturate","opacity"]);function Tu(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(Mr)||[];if(!s)return e;const r=n.replace(s,"");let o=wu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const Su=/\b([a-z-]*)\(.*?\)/gu,ir={...Tt,getAnimatableNone:e=>{const t=e.match(Su);return t?t.map(Tu).join(" "):e}},ji={...sn,transform:Math.round},ju={rotate:vt,rotateX:vt,rotateY:vt,rotateZ:vt,scale:is,scaleX:is,scaleY:is,scaleZ:is,skew:vt,skewX:vt,skewY:vt,distance:G,translateX:G,translateY:G,translateZ:G,x:G,y:G,z:G,perspective:G,transformPerspective:G,opacity:On,originX:di,originY:di,originZ:G},Lr={borderWidth:G,borderTopWidth:G,borderRightWidth:G,borderBottomWidth:G,borderLeftWidth:G,borderRadius:G,radius:G,borderTopLeftRadius:G,borderTopRightRadius:G,borderBottomRightRadius:G,borderBottomLeftRadius:G,width:G,maxWidth:G,height:G,maxHeight:G,top:G,right:G,bottom:G,left:G,padding:G,paddingTop:G,paddingRight:G,paddingBottom:G,paddingLeft:G,margin:G,marginTop:G,marginRight:G,marginBottom:G,marginLeft:G,backgroundPositionX:G,backgroundPositionY:G,...ju,zIndex:ji,fillOpacity:On,strokeOpacity:On,numOctaves:ji},Cu={...Lr,color:ve,backgroundColor:ve,outlineColor:ve,fill:ve,stroke:ve,borderColor:ve,borderTopColor:ve,borderRightColor:ve,borderBottomColor:ve,borderLeftColor:ve,filter:ir,WebkitFilter:ir},fa=e=>Cu[e];function ma(e,t){let n=fa(e);return n!==ir&&(n=Tt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Pu=new Set(["auto","none","0"]);function Au(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!Pu.has(o)&&$n(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=ma(n,r)}class ku extends Or{constructor(t,n,s,r,o){super(t,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<t.length;l++){let u=t[l];if(typeof u=="string"&&(u=u.trim(),kr(u))){const d=ca(u,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!ua.has(s)||t.length!==2)return;const[r,o]=t,i=Si(r),a=Si(o);if(i!==a)if(bi(i)&&bi(a))for(let l=0;l<t.length;l++){const u=t[l];typeof u=="string"&&(t[l]=parseFloat(u))}else It[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||vu(t[r]))&&s.push(r);s.length&&Au(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=It[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(s,r).jump(r,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=It[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,l])=>{t.getValue(a).set(l)}),this.resolveNoneKeyframes()}}function Mu(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 pa=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function ga(e){return Do(e)&&"offsetHeight"in e}const Ci=30,Eu=e=>!isNaN(parseFloat(e));class Nu{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=Ee.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=Ee.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Eu(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&jr(!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 Sr);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=Ee.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Ci)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Ci);return Vo(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 en(e,t){return new Nu(e,t)}const{schedule:Fr}=qo(queueMicrotask,!1),Ke={x:!1,y:!1};function ya(){return Ke.x||Ke.y}function Du(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 xa(e,t){const n=Mu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function Pi(e){return!(e.pointerType==="touch"||ya())}function Ru(e,t,n={}){const[s,r,o]=xa(e,n),i=a=>{if(!Pi(a))return;const{target:l}=a,u=t(l,a);if(typeof u!="function"||!l)return;const d=h=>{Pi(h)&&(u(h),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ba=(e,t)=>t?e===t?!0:ba(e,t.parentElement):!1,Br=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Vu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Iu(e){return Vu.has(e.tagName)||e.tabIndex!==-1}const us=new WeakSet;function Ai(e){return t=>{t.key==="Enter"&&e(t)}}function Vs(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Ou=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Ai(()=>{if(us.has(n))return;Vs(n,"down");const r=Ai(()=>{Vs(n,"up")}),o=()=>Vs(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 ki(e){return Br(e)&&!ya()}function $u(e,t,n={}){const[s,r,o]=xa(e,n),i=a=>{const l=a.currentTarget;if(!ki(a))return;us.add(l);const u=t(l,a),d=(p,w)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),us.has(l)&&us.delete(l),ki(p)&&typeof u=="function"&&u(p,{success:w})},h=p=>{d(p,l===window||l===document||n.useGlobalTarget||ba(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),ga(a)&&(a.addEventListener("focus",u=>Ou(u,r)),!Iu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function va(e){return Do(e)&&"ownerSVGElement"in e}function Lu(e){return va(e)&&e.tagName==="svg"}const je=e=>!!(e&&e.getVelocity),Fu=[...ha,ve,Tt],Bu=e=>Fu.find(da(e)),zr=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function Mi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function zu(...e){return t=>{let n=!1;const s=e.map(r=>{const o=Mi(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():Mi(e[r],null)}}}}function Uu(...e){return Ge.useCallback(zu(...e),e)}class _u extends Ge.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=ga(s)&&s.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=r-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function Xu({children:e,isPresent:t,anchorX:n,root:s}){const r=f.useId(),o=f.useRef(null),i=f.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=f.useContext(zr),l=Uu(o,e?.ref);return f.useInsertionEffect(()=>{const{width:u,height:d,top:h,left:m,right:p}=i.current;if(t||!o.current||!u||!d)return;const w=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const b=document.createElement("style");a&&(b.nonce=a);const j=s??document.head;return j.appendChild(b),b.sheet&&b.sheet.insertRule(`
1
+ "use strict";var kl=Object.create;var ii=Object.defineProperty;var Ml=Object.getOwnPropertyDescriptor;var El=Object.getOwnPropertyNames;var Dl=Object.getPrototypeOf,Nl=Object.prototype.hasOwnProperty;var Rl=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of El(t))!Nl.call(e,r)&&r!==n&&ii(e,r,{get:()=>t[r],enumerable:!(s=Ml(t,r))||s.enumerable});return e};var Vl=(e,t,n)=>(n=e!=null?kl(Dl(e)):{},Rl(t||!e||!e.__esModule?ii(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),f=require("react"),ne=require("lucide-react"),Po=require("@ai-sdk/react"),gs=require("ai"),Ao=require("@radix-ui/react-slot"),ko=require("class-variance-authority"),Il=require("clsx"),Ol=require("tailwind-merge"),$l=require("@radix-ui/react-tooltip"),oi=require("@radix-ui/react-use-controllable-state"),Ll=require("@radix-ui/react-collapsible"),Fl=require("react-dom"),Bl=require("@radix-ui/react-dialog"),zl=require("./server.cjs");function Ts(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=Ts(f),Zt=Ts($l),gr=Ts(Ll),$t=Ts(Bl);function re(...e){return Ol.twMerge(Il.clsx(e))}const Dt=ko.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=Ge.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?Ao.Slot:"button";return c.jsx(i,{ref:o,"data-slot":"button",className:re(Dt({variant:t,size:n,className:e})),...r})});Ce.displayName="Button";const Ul=ko.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 ks({className:e,variant:t,asChild:n=!1,...s}){const r=n?Ao.Slot:"span";return c.jsx(r,{"data-slot":"badge",className:re(Ul({variant:t}),e),...s})}const _l=({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])},Mo=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 _l({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:re("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)}})});Mo.displayName="AutosizeTextarea";function Xl({delayDuration:e=0,...t}){return c.jsx(Zt.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function yt({...e}){return c.jsx(Xl,{children:c.jsx(Zt.Root,{"data-slot":"tooltip",...e})})}function xt({...e}){return c.jsx(Zt.Trigger,{"data-slot":"tooltip-trigger",...e})}function bt({className:e,sideOffset:t=0,children:n,...s}){return c.jsx(Zt.Portal,{children:c.jsxs(Zt.Content,{"data-slot":"tooltip-content",sideOffset:t,className:re("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(Zt.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function ai({className:e,...t}){return c.jsx("kbd",{"data-slot":"kbd",className:re("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 yr=f.createContext({});function xr(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const br=typeof window<"u",Eo=br?f.useLayoutEffect:f.useEffect,Ss=f.createContext(null);function vr(e,t){e.indexOf(t)===-1&&e.push(t)}function wr(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const at=(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 nn=()=>{},lt=()=>{};process.env.NODE_ENV!=="production"&&(nn=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(qs(t,n))},lt=(e,t,n)=>{if(!e)throw new Error(qs(t,n))});const ct={},Do=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function No(e){return typeof e=="object"&&e!==null}const Ro=e=>/^0[^.\s]+$/u.test(e);function Tr(e){let t;return()=>(t===void 0&&(t=e()),t)}const ze=e=>e,Wl=(e,t)=>n=>t(e(n)),zn=(...e)=>e.reduce(Wl),In=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class Sr{constructor(){this.subscriptions=[]}add(t){return vr(this.subscriptions,t),()=>wr(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,Be=e=>e/1e3;function Vo(e,t){return t?e*(1e3/t):0}const li=new Set;function jr(e,t,n){e||li.has(t)||(console.warn(qs(t,n)),li.add(t))}const Io=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,ql=1e-7,Kl=12;function Gl(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=Io(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>ql&&++a<Kl);return i}function Un(e,t,n,s){if(e===t&&n===s)return ze;const r=o=>Gl(o,0,1,e,n);return o=>o===0||o===1?o:Io(r(o),t,s)}const Oo=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,$o=e=>t=>1-e(1-t),Lo=Un(.33,1.53,.69,.99),Cr=$o(Lo),Fo=Oo(Cr),Bo=e=>(e*=2)<1?.5*Cr(e):.5*(2-Math.pow(2,-10*(e-1))),Pr=e=>1-Math.sin(Math.acos(e)),zo=$o(Pr),Uo=Oo(Pr),Yl=Un(.42,0,1,1),Hl=Un(0,0,.58,1),_o=Un(.42,0,.58,1),Jl=e=>Array.isArray(e)&&typeof e[0]!="number",Xo=e=>Array.isArray(e)&&typeof e[0]=="number",ci={linear:ze,easeIn:Yl,easeInOut:_o,easeOut:Hl,circIn:Pr,circInOut:Uo,circOut:zo,backIn:Cr,backInOut:Fo,backOut:Lo,anticipate:Bo},Zl=e=>typeof e=="string",ui=e=>{if(Xo(e)){lt(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return Un(t,n,s,r)}else if(Zl(e))return lt(ci[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),ci[e];return e},rs=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Ql(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 w=m&&r?n:s;return h&&i.add(d),w.has(d)||w.add(d),d},cancel:d=>{s.delete(d),i.delete(d)},process:d=>{if(a=d,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(l),n.clear(),r=!1,o&&(o=!1,u.process(d))}};return u}const ec=40;function Wo(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=rs.reduce((v,E)=>(v[E]=Ql(o),v),{}),{setup:a,read:l,resolveKeyframes:u,preUpdate:d,update:h,preRender:m,render:p,postRender:w}=i,b=()=>{const v=ct.useManualTiming?r.timestamp:performance.now();n=!1,ct.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(v-r.timestamp,ec),1)),r.timestamp=v,r.isProcessing=!0,a.process(r),l.process(r),u.process(r),d.process(r),h.process(r),m.process(r),p.process(r),w.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(b))},j=()=>{n=!0,s=!0,r.isProcessing||e(b)};return{schedule:rs.reduce((v,E)=>{const N=i[E];return v[E]=($,L=!1,D=!1)=>(n||j(),N.schedule($,L,D)),v},{}),cancel:v=>{for(let E=0;E<rs.length;E++)i[rs[E]].cancel(v)},state:r,steps:i}}const{schedule:de,cancel:wt,state:Se,steps:Ms}=Wo(typeof requestAnimationFrame<"u"?requestAnimationFrame:ze,!0);let cs;function tc(){cs=void 0}const Ee={now:()=>(cs===void 0&&Ee.set(Se.isProcessing||ct.useManualTiming?Se.timestamp:performance.now()),cs),set:e=>{cs=e,queueMicrotask(tc)}},qo=e=>t=>typeof t=="string"&&t.startsWith(e),Ar=qo("--"),nc=qo("var(--"),kr=e=>nc(e)?sc.test(e.split("/*")[0].trim()):!1,sc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,sn={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},On={...sn,transform:e=>at(0,1,e)},is={...sn,default:1},Mn=e=>Math.round(e*1e5)/1e5,Mr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function rc(e){return e==null}const ic=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Er=(e,t)=>n=>!!(typeof n=="string"&&ic.test(n)&&n.startsWith(e)||t&&!rc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ko=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Mr);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},oc=e=>at(0,255,e),Es={...sn,transform:e=>Math.round(oc(e))},Rt={test:Er("rgb","red"),parse:Ko("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+Es.transform(e)+", "+Es.transform(t)+", "+Es.transform(n)+", "+Mn(On.transform(s))+")"};function ac(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 Ks={test:Er("#"),parse:ac,transform:Rt.transform},_n=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),vt=_n("deg"),et=_n("%"),G=_n("px"),lc=_n("vh"),cc=_n("vw"),di={...et,parse:e=>et.parse(e)/100,transform:e=>et.transform(e*100)},qt={test:Er("hsl","hue"),parse:Ko("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+et.transform(Mn(t))+", "+et.transform(Mn(n))+", "+Mn(On.transform(s))+")"},ve={test:e=>Rt.test(e)||Ks.test(e)||qt.test(e),parse:e=>Rt.test(e)?Rt.parse(e):qt.test(e)?qt.parse(e):Ks.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Rt.transform(e):qt.transform(e),getAnimatableNone:e=>{const t=ve.parse(e);return t.alpha=0,ve.transform(t)}},uc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function dc(e){return isNaN(e)&&typeof e=="string"&&(e.match(Mr)?.length||0)+(e.match(uc)?.length||0)>0}const Go="number",Yo="color",hc="var",fc="var(",hi="${}",mc=/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 $n(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(mc,l=>(ve.test(l)?(s.color.push(o),r.push(Yo),n.push(ve.parse(l))):l.startsWith(fc)?(s.var.push(o),r.push(hc),n.push(l)):(s.number.push(o),r.push(Go),n.push(parseFloat(l))),++o,hi)).split(hi);return{values:n,split:a,indexes:s,types:r}}function Ho(e){return $n(e).values}function Jo(e){const{split:t,types:n}=$n(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===Go?o+=Mn(r[i]):a===Yo?o+=ve.transform(r[i]):o+=r[i]}return o}}const pc=e=>typeof e=="number"?0:ve.test(e)?ve.getAnimatableNone(e):e;function gc(e){const t=Ho(e);return Jo(e)(t.map(pc))}const Tt={test:dc,parse:Ho,createTransformer:Jo,getAnimatableNone:gc};function Ds(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 yc({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=Ds(l,a,e+1/3),o=Ds(l,a,e),i=Ds(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function ys(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)},xc=[Ks,Rt,qt],bc=e=>xc.find(t=>t.test(e));function fi(e){const t=bc(e);if(nn(!!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===qt&&(n=yc(n)),n}const mi=(e,t)=>{const n=fi(e),s=fi(t);if(!n||!s)return ys(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),Rt.transform(r))},Gs=new Set(["none","hidden"]);function vc(e,t){return Gs.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function wc(e,t){return n=>fe(e,t,n)}function Dr(e){return typeof e=="number"?wc:typeof e=="string"?kr(e)?ys:ve.test(e)?mi:jc:Array.isArray(e)?Zo:typeof e=="object"?ve.test(e)?mi:Tc:ys}function Zo(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>Dr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Tc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=Dr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Sc(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 jc=(e,t)=>{const n=Tt.createTransformer(t),s=$n(e),r=$n(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?Gs.has(e)&&!r.values.length||Gs.has(t)&&!s.values.length?vc(e,t):zn(Zo(Sc(s,r),r.values),n):(nn(!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"),ys(e,t))};function Qo(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?fe(e,t,n):Dr(e)(e,t)}const Cc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>de.update(t,n),stop:()=>wt(t),now:()=>Se.isProcessing?Se.timestamp:Ee.now()}},ea=(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)})`},xs=2e4;function Nr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<xs;)t+=n,s=e.next(t);return t>=xs?1/0:t}function Pc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(Nr(s),xs);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:Be(r)}}const Ac=5;function ta(e,t,n){const s=Math.max(t-Ac,0);return Vo(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},Rs=.001;function kc({duration:e=he.duration,bounce:t=he.bounce,velocity:n=he.velocity,mass:s=he.mass}){let r,o;nn(e<=Ye(he.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=at(he.minDamping,he.maxDamping,i),e=at(he.minDuration,he.maxDuration,Be(e)),i<1?(r=u=>{const d=u*i,h=d*e,m=d-n,p=Ys(u,i),w=Math.exp(-h);return Rs-m/p*w},o=u=>{const h=u*i*e,m=h*n+n,p=Math.pow(i,2)*Math.pow(u,2)*e,w=Math.exp(-h),b=Ys(Math.pow(u,2),i);return(-r(u)+Rs>0?-1:1)*((m-p)*w)/b}):(r=u=>{const d=Math.exp(-u*e),h=(u-n)*e+1;return-Rs+d*h},o=u=>{const d=Math.exp(-u*e),h=(n-u)*(e*e);return d*h});const a=5/e,l=Ec(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 Mc=12;function Ec(e,t,n){let s=n;for(let r=1;r<Mc;r++)s=s-e(s)/t(s);return s}function Ys(e,t){return e*Math.sqrt(1-t*t)}const Dc=["duration","bounce"],Nc=["stiffness","damping","mass"];function pi(e,t){return t.some(n=>e[n]!==void 0)}function Rc(e){let t={velocity:he.velocity,stiffness:he.stiffness,damping:he.damping,mass:he.mass,isResolvedFromDuration:!1,...e};if(!pi(e,Nc)&&pi(e,Dc))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*at(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:he.mass,stiffness:r,damping:o}}else{const n=kc(e);t={...t,...n,mass:he.mass},t.isResolvedFromDuration=!0}return t}function bs(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}=Rc({...n,velocity:-Be(n.velocity||0)}),w=m||0,b=u/(2*Math.sqrt(l*d)),j=i-o,y=Be(Math.sqrt(l/d)),k=Math.abs(j)<5;s||(s=k?he.restSpeed.granular:he.restSpeed.default),r||(r=k?he.restDelta.granular:he.restDelta.default);let v;if(b<1){const N=Ys(y,b);v=$=>{const L=Math.exp(-b*y*$);return i-L*((w+b*y*j)/N*Math.sin(N*$)+j*Math.cos(N*$))}}else if(b===1)v=N=>i-Math.exp(-y*N)*(j+(w+y*j)*N);else{const N=y*Math.sqrt(b*b-1);v=$=>{const L=Math.exp(-b*y*$),D=Math.min(N*$,300);return i-L*((w+b*y*j)*Math.sinh(D)+N*j*Math.cosh(D))/N}}const E={calculatedDuration:p&&h||null,next:N=>{const $=v(N);if(p)a.done=N>=h;else{let L=N===0?w:0;b<1&&(L=N===0?Ye(w):ta(v,N,$));const D=Math.abs(L)<=s,z=Math.abs(i-$)<=r;a.done=D&&z}return a.value=a.done?i:$,a},toString:()=>{const N=Math.min(Nr(E),xs),$=ea(L=>E.next(N*L).value,N,30);return N+"ms "+$},toTransition:()=>{}};return E}bs.applyToOptions=e=>{const t=Pc(e,100,bs);return e.ease=t.ease,e.duration=Ye(t.duration),e.type="keyframes",e};function Hs({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=D=>a!==void 0&&D<a||l!==void 0&&D>l,w=D=>a===void 0?l:l===void 0||Math.abs(a-D)<Math.abs(l-D)?a:l;let b=n*t;const j=h+b,y=i===void 0?j:i(j);y!==j&&(b=y-h);const k=D=>-b*Math.exp(-D/s),v=D=>y+k(D),E=D=>{const z=k(D),A=v(D);m.done=Math.abs(z)<=u,m.value=m.done?y:A};let N,$;const L=D=>{p(m.value)&&(N=D,$=bs({keyframes:[m.value,w(m.value)],velocity:ta(v,D,m.value),damping:r,stiffness:o,restDelta:u,restSpeed:d}))};return L(0),{calculatedDuration:null,next:D=>{let z=!1;return!$&&N===void 0&&(z=!0,E(D),L(D)),N!==void 0&&D>=N?$.next(D-N):(!z&&E(D),m)}}}function Vc(e,t,n){const s=[],r=n||ct.mix||Qo,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=zn(l,a)}s.push(a)}return s}function Ic(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(lt(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=Vc(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=In(e[h],e[h+1],d);return a[h](m)};return n?d=>u(at(e[0],e[o-1],d)):u}function Oc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=In(0,t,s);e.push(fe(n,1,r))}}function $c(e){const t=[0];return Oc(t,e.length-1),t}function Lc(e,t){return e.map(n=>n*t)}function Fc(e,t){return e.map(()=>t||_o).splice(0,e.length-1)}function Kt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=Jl(s)?s.map(ui):ui(s),o={done:!1,value:t[0]},i=Lc(n&&n.length===t.length?n:$c(t),e),a=Ic(i,t,{ease:Array.isArray(r)?r:Fc(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const Bc=e=>e!==null;function Rr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(Bc),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const zc={decay:Hs,inertia:Hs,tween:Kt,keyframes:Kt,spring:bs};function na(e){typeof e.type=="string"&&(e.type=zc[e.type])}class Vr{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 Uc=e=>e/100;class Ir extends Vr{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==Ee.now()&&this.tick(Ee.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;na(t);const{type:n=Kt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const l=n||Kt;process.env.NODE_ENV!=="production"&&l!==Kt&&lt(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),l!==Kt&&typeof a[0]!="number"&&(this.mixKeyframes=zn(Uc,Qo(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:w,onUpdate:b,finalKeyframe:j}=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),k=this.playbackSpeed>=0?y<0:y>r;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let v=this.currentTime,E=s;if(h){const D=Math.min(this.currentTime,r)/a;let z=Math.floor(D),A=D%1;!A&&D>=1&&(A=1),A===1&&z--,z=Math.min(z,h+1),!!(z%2)&&(m==="reverse"?(A=1-A,p&&(A-=p/a)):m==="mirror"&&(E=i)),v=at(0,1,A)*a}const N=k?{done:!1,value:d[0]}:E.next(v);o&&(N.value=o(N.value));let{done:$}=N;!k&&l!==null&&($=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const L=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&$);return L&&w!==Hs&&(N.value=Rr(d,this.options,j,this.speed)),b&&b(N.value),L&&this.finish(),N}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=Ye(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(Ee.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=Be(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Cc,startTime:n}=this.options;this.driver||(this.driver=t(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Ee.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function _c(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Vt=e=>e*180/Math.PI,Js=e=>{const t=Vt(Math.atan2(e[1],e[0]));return Zs(t)},Xc={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Js,rotateZ:Js,skewX:e=>Vt(Math.atan(e[1])),skewY:e=>Vt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Zs=e=>(e=e%360,e<0&&(e+=360),e),gi=Js,yi=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),xi=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),Wc={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:yi,scaleY:xi,scale:e=>(yi(e)+xi(e))/2,rotateX:e=>Zs(Vt(Math.atan2(e[6],e[5]))),rotateY:e=>Zs(Vt(Math.atan2(-e[2],e[0]))),rotateZ:gi,rotate:gi,skewX:e=>Vt(Math.atan(e[4])),skewY:e=>Vt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Qs(e){return e.includes("scale")?1:0}function er(e,t){if(!e||e==="none")return Qs(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=Wc,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=Xc,r=a}if(!r)return Qs(t);const o=s[t],i=r[1].split(",").map(Kc);return typeof o=="function"?o(i):i[o]}const qc=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return er(n,t)};function Kc(e){return parseFloat(e.trim())}const rn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],on=new Set(rn),bi=e=>e===sn||e===G,Gc=new Set(["x","y","z"]),Yc=rn.filter(e=>!Gc.has(e));function Hc(e){const t=[];return Yc.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const It={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>er(t,"x"),y:(e,{transform:t})=>er(t,"y")};It.translateX=It.x;It.translateY=It.y;const Ot=new Set;let tr=!1,nr=!1,sr=!1;function sa(){if(nr){const e=Array.from(Ot).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=Hc(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)})}nr=!1,tr=!1,Ot.forEach(e=>e.complete(sr)),Ot.clear()}function ra(){Ot.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(nr=!0)})}function Jc(){sr=!0,ra(),sa(),sr=!1}class Or{constructor(t,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(Ot.add(this),tr||(tr=!0,de.read(ra),de.resolveKeyframes(sa))):(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])}_c(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Ot.delete(this)}cancel(){this.state==="scheduled"&&(Ot.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Zc=e=>e.startsWith("--");function Qc(e,t,n){Zc(t)?e.style.setProperty(t,n):e.style[t]=n}const eu=Tr(()=>window.ScrollTimeline!==void 0),tu={};function nu(e,t){const n=Tr(e);return()=>tu[t]??n()}const ia=nu(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),An=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,vi={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:An([0,.65,.55,1]),circOut:An([.55,0,1,.45]),backIn:An([.31,.01,.66,-.59]),backOut:An([.33,1.53,.69,.99])};function oa(e,t){if(e)return typeof e=="function"?ia()?ea(e,t):"ease-out":Xo(e)?An(e):Array.isArray(e)?e.map(n=>oa(n,t)||vi.easeOut):vi[e]}function su(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=oa(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 aa(e){return typeof e=="function"&&"applyToOptions"in e}function ru({type:e,...t}){return aa(e)&&ia()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class iu extends Vr{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,lt(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=ru(t);this.animation=su(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Rr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Qc(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=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&&eu()?(this.animation.timeline=t,ze):n(this)}}const la={anticipate:Bo,backInOut:Fo,circInOut:Uo};function ou(e){return e in la}function au(e){typeof e.ease=="string"&&ou(e.ease)&&(e.ease=la[e.ease])}const wi=10;class lu extends iu{constructor(t){au(t),na(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new Ir({...i,autoplay:!1}),l=Ye(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-wi).value,a.sample(l).value,wi),a.stop()}}const Ti=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(Tt.test(e)||e==="0")&&!e.startsWith("url("));function cu(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 uu(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=Ti(r,t),a=Ti(o,t);return nn(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:cu(e)||(n==="spring"||aa(n))&&s}function rr(e){e.duration=0,e.type="keyframes"}const du=new Set(["opacity","clipPath","filter","transform"]),hu=Tr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function fu(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 hu()&&n&&du.has(n)&&(n!=="transform"||!u)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const mu=40;class pu extends Vr{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=Ee.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||Or;this.keyframeResolver=new p(a,(w,b,j)=>this.onKeyframesResolved(w,b,m,!j),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=Ee.now(),uu(t,o,i,a)||((ct.instantAnimations||!l)&&d?.(Rr(t,s,n)),t[0]=t[t.length-1],rr(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>mu?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!u&&fu(m)?new lu({...m,element:m.motionValue.owner.current}):new Ir(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(),Jc()),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 gu=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function yu(e){const t=gu.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const xu=4;function ca(e,t,n=1){lt(n<=xu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=yu(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return Do(i)?parseFloat(i):i}return kr(r)?ca(r,t,n+1):r}function $r(e,t){return e?.[t]??e?.default??e}const ua=new Set(["width","height","top","left","right","bottom",...rn]),bu={test:e=>e==="auto",parse:e=>e},da=e=>t=>t.test(e),ha=[sn,G,et,vt,cc,lc,bu],Si=e=>ha.find(da(e));function vu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||Ro(e):!0}const wu=new Set(["brightness","contrast","saturate","opacity"]);function Tu(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(Mr)||[];if(!s)return e;const r=n.replace(s,"");let o=wu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const Su=/\b([a-z-]*)\(.*?\)/gu,ir={...Tt,getAnimatableNone:e=>{const t=e.match(Su);return t?t.map(Tu).join(" "):e}},ji={...sn,transform:Math.round},ju={rotate:vt,rotateX:vt,rotateY:vt,rotateZ:vt,scale:is,scaleX:is,scaleY:is,scaleZ:is,skew:vt,skewX:vt,skewY:vt,distance:G,translateX:G,translateY:G,translateZ:G,x:G,y:G,z:G,perspective:G,transformPerspective:G,opacity:On,originX:di,originY:di,originZ:G},Lr={borderWidth:G,borderTopWidth:G,borderRightWidth:G,borderBottomWidth:G,borderLeftWidth:G,borderRadius:G,radius:G,borderTopLeftRadius:G,borderTopRightRadius:G,borderBottomRightRadius:G,borderBottomLeftRadius:G,width:G,maxWidth:G,height:G,maxHeight:G,top:G,right:G,bottom:G,left:G,padding:G,paddingTop:G,paddingRight:G,paddingBottom:G,paddingLeft:G,margin:G,marginTop:G,marginRight:G,marginBottom:G,marginLeft:G,backgroundPositionX:G,backgroundPositionY:G,...ju,zIndex:ji,fillOpacity:On,strokeOpacity:On,numOctaves:ji},Cu={...Lr,color:ve,backgroundColor:ve,outlineColor:ve,fill:ve,stroke:ve,borderColor:ve,borderTopColor:ve,borderRightColor:ve,borderBottomColor:ve,borderLeftColor:ve,filter:ir,WebkitFilter:ir},fa=e=>Cu[e];function ma(e,t){let n=fa(e);return n!==ir&&(n=Tt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Pu=new Set(["auto","none","0"]);function Au(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!Pu.has(o)&&$n(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=ma(n,r)}class ku extends Or{constructor(t,n,s,r,o){super(t,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<t.length;l++){let u=t[l];if(typeof u=="string"&&(u=u.trim(),kr(u))){const d=ca(u,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!ua.has(s)||t.length!==2)return;const[r,o]=t,i=Si(r),a=Si(o);if(i!==a)if(bi(i)&&bi(a))for(let l=0;l<t.length;l++){const u=t[l];typeof u=="string"&&(t[l]=parseFloat(u))}else It[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||vu(t[r]))&&s.push(r);s.length&&Au(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=It[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(s,r).jump(r,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=It[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,l])=>{t.getValue(a).set(l)}),this.resolveNoneKeyframes()}}function Mu(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 pa=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function ga(e){return No(e)&&"offsetHeight"in e}const Ci=30,Eu=e=>!isNaN(parseFloat(e));class Du{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=Ee.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=Ee.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Eu(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&jr(!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 Sr);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=Ee.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Ci)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Ci);return Vo(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 en(e,t){return new Du(e,t)}const{schedule:Fr}=Wo(queueMicrotask,!1),Ke={x:!1,y:!1};function ya(){return Ke.x||Ke.y}function Nu(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 xa(e,t){const n=Mu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function Pi(e){return!(e.pointerType==="touch"||ya())}function Ru(e,t,n={}){const[s,r,o]=xa(e,n),i=a=>{if(!Pi(a))return;const{target:l}=a,u=t(l,a);if(typeof u!="function"||!l)return;const d=h=>{Pi(h)&&(u(h),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ba=(e,t)=>t?e===t?!0:ba(e,t.parentElement):!1,Br=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Vu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Iu(e){return Vu.has(e.tagName)||e.tabIndex!==-1}const us=new WeakSet;function Ai(e){return t=>{t.key==="Enter"&&e(t)}}function Vs(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Ou=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Ai(()=>{if(us.has(n))return;Vs(n,"down");const r=Ai(()=>{Vs(n,"up")}),o=()=>Vs(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 ki(e){return Br(e)&&!ya()}function $u(e,t,n={}){const[s,r,o]=xa(e,n),i=a=>{const l=a.currentTarget;if(!ki(a))return;us.add(l);const u=t(l,a),d=(p,w)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),us.has(l)&&us.delete(l),ki(p)&&typeof u=="function"&&u(p,{success:w})},h=p=>{d(p,l===window||l===document||n.useGlobalTarget||ba(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),ga(a)&&(a.addEventListener("focus",u=>Ou(u,r)),!Iu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function va(e){return No(e)&&"ownerSVGElement"in e}function Lu(e){return va(e)&&e.tagName==="svg"}const je=e=>!!(e&&e.getVelocity),Fu=[...ha,ve,Tt],Bu=e=>Fu.find(da(e)),zr=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function Mi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function zu(...e){return t=>{let n=!1;const s=e.map(r=>{const o=Mi(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():Mi(e[r],null)}}}}function Uu(...e){return Ge.useCallback(zu(...e),e)}class _u extends Ge.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=ga(s)&&s.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=r-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function Xu({children:e,isPresent:t,anchorX:n,root:s}){const r=f.useId(),o=f.useRef(null),i=f.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=f.useContext(zr),l=Uu(o,e?.ref);return f.useInsertionEffect(()=>{const{width:u,height:d,top:h,left:m,right:p}=i.current;if(t||!o.current||!u||!d)return;const w=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const b=document.createElement("style");a&&(b.nonce=a);const j=s??document.head;return j.appendChild(b),b.sheet&&b.sheet.insertRule(`
2
2
  [data-motion-pop-id="${r}"] {
3
3
  position: absolute !important;
4
4
  width: ${u}px !important;
@@ -6,7 +6,7 @@
6
6
  ${w}px !important;
7
7
  top: ${h}px !important;
8
8
  }
9
- `),()=>{j.contains(b)&&j.removeChild(b)}},[t]),c.jsx(_u,{isPresent:t,childRef:o,sizeRef:i,children:Ge.cloneElement(e,{ref:l})})}const qu=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const u=xr(Wu),d=f.useId();let h=!0,m=f.useMemo(()=>(h=!1,{id:d,initial:t,isPresent:n,custom:r,onExitComplete:p=>{u.set(p,!0);for(const w of u.values())if(!w)return;s&&s()},register:p=>(u.set(p,!1),()=>u.delete(p))}),[n,u,s]);return o&&h&&(m={...m}),f.useMemo(()=>{u.forEach((p,w)=>u.set(w,!1))},[n]),Ge.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(e=c.jsx(Xu,{isPresent:n,anchorX:a,root:l,children:e})),c.jsx(Ss.Provider,{value:m,children:e})};function Wu(){return new Map}function wa(e=!0){const t=f.useContext(Ss);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 os=e=>e.key||"";function Ei(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const Ku=({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]=wa(i),h=f.useMemo(()=>Ei(e),[e]),m=i&&!u?[]:h.map(os),p=f.useRef(!0),w=f.useRef(h),b=xr(()=>new Map),[j,y]=f.useState(h),[k,v]=f.useState(h);Eo(()=>{p.current=!1,w.current=h;for(let $=0;$<k.length;$++){const L=os(k[$]);m.includes(L)?b.delete(L):b.get(L)!==!0&&b.set(L,!1)}},[k,m.length,m.join("-")]);const E=[];if(h!==j){let $=[...h];for(let L=0;L<k.length;L++){const N=k[L],z=os(N);m.includes(z)||($.splice(L,0,N),E.push(N))}return o==="wait"&&E.length&&($=E),v(Ei($)),y(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&k.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:D}=f.useContext(yr);return c.jsx(c.Fragment,{children:k.map($=>{const L=os($),N=i&&!u?!1:h===k||m.includes(L),z=()=>{if(b.has(L))b.set(L,!0);else return;let A=!0;b.forEach(M=>{M||(A=!1)}),A&&(D?.(),v(w.current),i&&d?.(),s&&s())};return c.jsx(qu,{isPresent:N,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:l,onExitComplete:N?void 0:z,anchorX:a,children:$},L)})})},Ur=f.createContext({strict:!1}),Ni={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},tn={};for(const e in Ni)tn[e]={isEnabled:t=>Ni[e].some(n=>!!t[n])};function or(e){for(const t in e)tn[t]={...tn[t],...e[t]}}function Gu({children:e,features:t,strict:n=!1}){const[,s]=f.useState(!Is(t)),r=f.useRef(void 0);if(!Is(t)){const{renderer:o,...i}=t;r.current=o,or(i)}return f.useEffect(()=>{Is(t)&&t().then(({renderer:o,...i})=>{or(i),r.current=o,s(!0)})},[]),c.jsx(Ur.Provider,{value:{renderer:r.current,strict:n},children:e})}function Is(e){return typeof e=="function"}const Yu=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 vs(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Yu.has(e)}let Ta=e=>!vs(e);function Hu(e){typeof e=="function"&&(Ta=t=>t.startsWith("on")?!vs(t):e(t))}try{Hu(require("@emotion/is-prop-valid").default)}catch{}function Ju(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(Ta(r)||n===!0&&vs(r)||!t&&!vs(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const js=f.createContext({});function Cs(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function Ln(e){return typeof e=="string"||Array.isArray(e)}const _r=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Xr=["initial",..._r];function Ps(e){return Cs(e.animate)||Xr.some(t=>Ln(e[t]))}function Sa(e){return!!(Ps(e)||e.variants)}function Zu(e,t){if(Ps(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Ln(n)?n:void 0,animate:Ln(s)?s:void 0}}return e.inherit!==!1?t:{}}function Qu(e){const{initial:t,animate:n}=Zu(e,f.useContext(js));return f.useMemo(()=>({initial:t,animate:n}),[Di(t),Di(n)])}function Di(e){return Array.isArray(e)?e.join(" "):e}const Fn={};function ed(e){for(const t in e)Fn[t]=e[t],Ar(t)&&(Fn[t].isCSSVariable=!0)}function ja(e,{layout:t,layoutId:n}){return on.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Fn[e]||e==="opacity")}const td={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},nd=rn.length;function sd(e,t,n){let s="",r=!0;for(let o=0;o<nd;o++){const i=rn[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=pa(a,Lr[i]);if(!l){r=!1;const d=td[i]||i;s+=`${d}(${u}) `}n&&(t[i]=u)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function qr(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(on.has(l)){i=!0;continue}else if(Ar(l)){r[l]=u;continue}else{const d=pa(u,Lr[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=sd(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 Wr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Ca(e,t,n){for(const s in t)!je(t[s])&&!ja(s,n)&&(e[s]=t[s])}function rd({transformTemplate:e},t){return f.useMemo(()=>{const n=Wr();return qr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function id(e,t){const n=e.style||{},s={};return Ca(s,n,e),Object.assign(s,rd(e,t)),s}function od(e,t){const n={},s=id(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 ad={offset:"stroke-dashoffset",array:"stroke-dasharray"},ld={offset:"strokeDashoffset",array:"strokeDasharray"};function cd(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?ad:ld;e[o.offset]=G.transform(-s);const i=G.transform(t),a=G.transform(n);e[o.array]=`${i} ${a}`}function Pa(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,u,d){if(qr(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&&cd(h,r,o,i,!1)}const Aa=()=>({...Wr(),attrs:{}}),ka=e=>typeof e=="string"&&e.toLowerCase()==="svg";function ud(e,t,n,s){const r=f.useMemo(()=>{const o=Aa();return Pa(o,t,ka(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Ca(o,e.style,e),r.style={...o,...r.style}}return r}const dd=["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 Kr(e){return typeof e!="string"||e.includes("-")?!1:!!(dd.indexOf(e)>-1||/[A-Z]/u.test(e))}function hd(e,t,n,{latestValues:s},r,o=!1){const a=(Kr(e)?ud:od)(t,s,r,e),l=Ju(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 Ri(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Gr(e,t,n,s){if(typeof t=="function"){const[r,o]=Ri(s);t=t(n!==void 0?n:e.custom,r,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,o]=Ri(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function ds(e){return je(e)?e.get():e}function fd({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:md(n,s,r,e),renderState:t()}}function md(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=ds(o[m]);let{initial:i,animate:a}=e;const l=Ps(e),u=Sa(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"&&!Cs(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p<m.length;p++){const w=Gr(e,m[p]);if(w){const{transitionEnd:b,transition:j,...y}=w;for(const k in y){let v=y[k];if(Array.isArray(v)){const E=d?v.length-1:0;v=v[E]}v!==null&&(r[k]=v)}for(const k in b)r[k]=b[k]}}}return r}const Ma=e=>(t,n)=>{const s=f.useContext(js),r=f.useContext(Ss),o=()=>fd(e,t,s,r);return n?o():xr(o)};function Yr(e,t,n){const{style:s}=e,r={};for(const o in s)(je(s[o])||t.style&&je(t.style[o])||ja(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const pd=Ma({scrapeMotionValuesFromProps:Yr,createRenderState:Wr});function Ea(e,t,n){const s=Yr(e,t,n);for(const r in e)if(je(e[r])||je(t[r])){const o=rn.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const gd=Ma({scrapeMotionValuesFromProps:Ea,createRenderState:Aa}),yd=Symbol.for("motionComponentSymbol");function Gt(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function xd(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):Gt(n)&&(n.current=s))},[t])}const Hr=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),bd="framerAppearId",Na="data-"+Hr(bd),Da=f.createContext({});function vd(e,t,n,s,r){const{visualElement:o}=f.useContext(js),i=f.useContext(Ur),a=f.useContext(Ss),l=f.useContext(zr).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(Da);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&wd(u.current,n,r,h);const m=f.useRef(!1);f.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[Na],w=f.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return Eo(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),w.current&&d.animationState&&d.animationState.animateChanges())}),f.useEffect(()=>{d&&(!w.current&&d.animationState&&d.animationState.animateChanges(),w.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),w.current=!1),d.enteringChildren=void 0)}),d}function wd(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:Ra(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Gt(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:l,layoutRoot:u})}function Ra(e){if(e)return e.options.allowProjection!==!1?e.projection:Ra(e.parent)}function hs(e,{forwardMotionProps:t=!1}={},n,s){n&&or(n);const r=Kr(e)?gd:pd;function o(a,l){let u;const d={...f.useContext(zr),...a,layoutId:Td(a)},{isStatic:h}=d,m=Qu(a),p=r(a,h);if(!h&&br){Sd(d,n);const w=jd(d);u=w.MeasureLayout,m.visualElement=vd(e,p,d,s,w.ProjectionNode)}return c.jsxs(js.Provider,{value:m,children:[u&&m.visualElement?c.jsx(u,{visualElement:m.visualElement,...d}):null,hd(e,a,xd(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[yd]=e,i}function Td({layoutId:e}){const t=f.useContext(yr).id;return t&&e!==void 0?t+"-"+e:e}function Sd(e,t){const n=f.useContext(Ur).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?nn(!1,s,"lazy-strict-mode"):lt(!1,s,"lazy-strict-mode")}}function jd(e){const{drag:t,layout:n}=tn;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Cd(e,t){if(typeof Proxy>"u")return hs;const n=new Map,s=(o,i)=>hs(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&jr(!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,hs(i,void 0,e,t)),n.get(i))})}function Va({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function Pd({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Ad(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 Os(e){return e===void 0||e===1}function ar({scale:e,scaleX:t,scaleY:n}){return!Os(e)||!Os(t)||!Os(n)}function Dt(e){return ar(e)||Ia(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Ia(e){return Vi(e.x)||Vi(e.y)}function Vi(e){return e&&e!=="0%"}function ws(e,t,n){const s=e-n,r=t*s;return n+r}function Ii(e,t,n,s,r){return r!==void 0&&(e=ws(e,r,s)),ws(e,n,s)+t}function lr(e,t=0,n=1,s,r){e.min=Ii(e.min,t,n,s,r),e.max=Ii(e.max,t,n,s,r)}function Oa(e,{x:t,y:n}){lr(e.x,t.translate,t.scale,t.originPoint),lr(e.y,n.translate,n.scale,n.originPoint)}const Oi=.999999999999,$i=1.0000000000001;function kd(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&&Ht(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,Oa(e,i)),s&&Dt(o.latestValues)&&Ht(e,o.latestValues))}t.x<$i&&t.x>Oi&&(t.x=1),t.y<$i&&t.y>Oi&&(t.y=1)}function Yt(e,t){e.min=e.min+t,e.max=e.max+t}function Li(e,t,n,s,r=.5){const o=fe(e.min,e.max,r);lr(e,t,n,o,s)}function Ht(e,t){Li(e.x,t.x,t.scaleX,t.scale,t.originX),Li(e.y,t.y,t.scaleY,t.scale,t.originY)}function $a(e,t){return Va(Ad(e.getBoundingClientRect(),t))}function Md(e,t,n){const s=$a(e,n),{scroll:r}=t;return r&&(Yt(s.x,r.offset.x),Yt(s.y,r.offset.y)),s}const Fi=()=>({translate:0,scale:1,origin:0,originPoint:0}),Jt=()=>({x:Fi(),y:Fi()}),Bi=()=>({min:0,max:0}),ge=()=>({x:Bi(),y:Bi()}),cr={current:null},La={current:!1};function Ed(){if(La.current=!0,!!br)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>cr.current=e.matches;e.addEventListener("change",t),t()}else cr.current=!1}const Nd=new WeakMap;function Dd(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,en(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,en(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const zi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Rd{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Or,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const m=Ee.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=Ps(n),this.isVariantNode=Sa(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,Nd.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),La.current||Ed(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:cr.current,process.env.NODE_ENV!=="production"&&jr(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(),wt(this.notifyUpdate),wt(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=on.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 tn){const n=tn[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<zi.length;s++){const r=zi[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=Dd(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=en(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"&&(No(s)||Ro(s))?s=parseFloat(s):!Bu(s)&&Tt.test(n)&&(s=ma(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=Gr(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 Sr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Fr.render(this.render)}}class Fa extends Rd{constructor(){super(...arguments),this.KeyframeResolver=ku}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 Ba(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 Vd(e){return window.getComputedStyle(e)}class Id extends Fa{constructor(){super(...arguments),this.type="html",this.renderInstance=Ba}readValueFromInstance(t,n){if(on.has(n))return this.projection?.isProjecting?Qs(n):Wc(t,n);{const s=Vd(t),r=(Ar(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return $a(t,n)}build(t,n,s){qr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Yr(t,n,s)}}const za=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 Od(e,t,n,s){Ba(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(za.has(r)?r:Hr(r),t.attrs[r])}class $d extends Fa{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ge}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(on.has(n)){const s=fa(n);return s&&s.default||0}return n=za.has(n)?n:Hr(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return Ea(t,n,s)}build(t,n,s){Pa(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){Od(t,n,s,r)}mount(t){this.isSVGTag=ka(t.tagName),super.mount(t)}}const Ua=(e,t)=>Kr(e)?new $d(t):new Id(t,{allowProjection:e!==f.Fragment});function Qt(e,t,n){const s=e.getProps();return Gr(s,t,n!==void 0?n:s.custom,e)}const ur=e=>Array.isArray(e);function Ld(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,en(n))}function Fd(e){return ur(e)?e[e.length-1]||0:e}function Bd(e,t){const n=Qt(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Fd(o[i]);Ld(e,i,a)}}function zd(e){return!!(je(e)&&e.add)}function dr(e,t){const n=e.getValue("willChange");if(zd(n))return n.add(t);if(!n&&ct.WillChange){const s=new ct.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function _a(e){return e.props[Na]}const Ud=e=>e!==null;function _d(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Ud),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const Xd={type:"spring",stiffness:500,damping:25,restSpeed:10},qd=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Wd={type:"keyframes",duration:.8},Kd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Gd=(e,{keyframes:t})=>t.length>2?Wd:on.has(e)?e.startsWith("scale")?qd(t[1]):Xd:Kd;function Yd({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 Jr=(e,t,n,s={},r,o)=>i=>{const a=$r(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};Yd(a)||Object.assign(d,Gd(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)&&(rr(d),d.delay===0&&(h=!0)),(ct.instantAnimations||ct.skipAnimations)&&(h=!0,rr(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const m=_d(d.keyframes,a);if(m!==void 0){de.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new Ir(d):new pu(d)};function Hd({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function Xa(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&&Hd(u,d))continue;const p={delay:n,...$r(o||{},d)},w=h.get();if(w!==void 0&&!h.isAnimating&&!Array.isArray(m)&&m===w&&!p.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const y=_a(e);if(y){const k=window.MotionHandoffAnimation(y,d,de);k!==null&&(p.startTime=k,b=!0)}}dr(e,d),h.start(Jr(d,h,m,e.shouldReduceMotion&&ua.has(d)?{type:!1}:p,e,b));const j=h.animation;j&&l.push(j)}return i&&Promise.all(l).then(()=>{de.update(()=>{i&&Bd(e,i)})}),l}function qa(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 hr(e,t,n={}){const s=Qt(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(Xa(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=r;return Jd(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 Jd(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(hr(l,t,{...i,delay:n+(typeof s=="function"?0:s)+qa(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function Zd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>hr(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=hr(e,t,n);else{const r=typeof t=="function"?Qt(e,t,n.custom):t;s=Promise.all(Xa(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function Wa(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 Qd=Xr.length;function Ka(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Ka(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<Qd;n++){const s=Xr[n],r=e.props[s];(Ln(r)||r===!1)&&(t[s]=r)}return t}const eh=[..._r].reverse(),th=_r.length;function nh(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Zd(e,n,s)))}function sh(e){let t=nh(e),n=Ui(),s=!0;const r=l=>(u,d)=>{const h=Qt(e,d,l==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:m,transitionEnd:p,...w}=h;u={...u,...w,...p}}return u};function o(l){t=l(e)}function i(l){const{props:u}=e,d=Ka(e.parent)||{},h=[],m=new Set;let p={},w=1/0;for(let j=0;j<th;j++){const y=eh[j],k=n[y],v=u[y]!==void 0?u[y]:d[y],E=Ln(v),D=y===l?k.isActive:null;D===!1&&(w=j);let $=v===d[y]&&v!==u[y]&&E;if($&&s&&e.manuallyAnimateOnMount&&($=!1),k.protectedKeys={...p},!k.isActive&&D===null||!v&&!k.prevProp||Cs(v)||typeof v=="boolean")continue;const L=rh(k.prevProp,v);let N=L||y===l&&k.isActive&&!$&&E||j>w&&E,z=!1;const A=Array.isArray(v)?v:[v];let M=A.reduce(r(y),{});D===!1&&(M={});const{prevResolvedValues:I={}}=k,F={...I,...M},K=X=>{N=!0,m.has(X)&&(z=!0,m.delete(X)),k.needsAnimating[X]=!0;const oe=e.getValue(X);oe&&(oe.liveStyle=!1)};for(const X in F){const oe=M[X],we=I[X];if(p.hasOwnProperty(X))continue;let Te=!1;ur(oe)&&ur(we)?Te=!Wa(oe,we):Te=oe!==we,Te?oe!=null?K(X):m.add(X):oe!==void 0&&m.has(X)?K(X):k.protectedKeys[X]=!0}k.prevProp=v,k.prevResolvedValues=M,k.isActive&&(p={...p,...M}),s&&e.blockInitialAnimation&&(N=!1);const Y=$&&L;N&&(!Y||z)&&h.push(...A.map(X=>{const oe={type:y};if(typeof X=="string"&&s&&!Y&&e.manuallyAnimateOnMount&&e.parent){const{parent:we}=e,Te=Qt(we,X);if(we.enteringChildren&&Te){const{delayChildren:se}=Te.transition||{};oe.delay=qa(we.enteringChildren,e,se)}}return{animation:X,options:oe}}))}if(m.size){const j={};if(typeof u.initial!="boolean"){const y=Qt(e,Array.isArray(u.initial)?u.initial[0]:u.initial);y&&y.transition&&(j.transition=y.transition)}m.forEach(y=>{const k=e.getBaseTarget(y),v=e.getValue(y);v&&(v.liveStyle=!0),j[y]=k??null}),h.push({animation:j})}let b=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(b=!1),s=!1,b?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=Ui()}}}function rh(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!Wa(t,e):!1}function Et(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Ui(){return{animate:Et(!0),whileInView:Et(),whileHover:Et(),whileTap:Et(),whileDrag:Et(),whileFocus:Et(),exit:Et()}}class St{constructor(t){this.isMounted=!1,this.node=t}update(){}}class ih extends St{constructor(t){super(t),t.animationState||(t.animationState=sh(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Cs(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 oh=0;class ah extends St{constructor(){super(...arguments),this.id=oh++}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 Ga={animation:{Feature:ih},exit:{Feature:ah}};function Bn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function Xn(e){return{point:{x:e.pageX,y:e.pageY}}}const lh=e=>t=>Br(t)&&e(t,Xn(t));function En(e,t,n,s){return Bn(e,t,lh(n),s)}const Ya=1e-4,ch=1-Ya,uh=1+Ya,Ha=.01,dh=0-Ha,hh=0+Ha;function Ae(e){return e.max-e.min}function fh(e,t,n){return Math.abs(e-t)<=n}function _i(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>=ch&&e.scale<=uh||isNaN(e.scale))&&(e.scale=1),(e.translate>=dh&&e.translate<=hh||isNaN(e.translate))&&(e.translate=0)}function Nn(e,t,n,s){_i(e.x,t.x,n.x,s?s.originX:void 0),_i(e.y,t.y,n.y,s?s.originY:void 0)}function Xi(e,t,n){e.min=n.min+t.min,e.max=e.min+Ae(t)}function mh(e,t,n){Xi(e.x,t.x,n.x),Xi(e.y,t.y,n.y)}function qi(e,t,n){e.min=t.min-n.min,e.max=e.min+Ae(t)}function Dn(e,t,n){qi(e.x,t.x,n.x),qi(e.y,t.y,n.y)}function Fe(e){return[e("x"),e("y")]}const Ja=({current:e})=>e?e.ownerDocument.defaultView:null,Wi=(e,t)=>Math.abs(e-t);function ph(e,t){const n=Wi(e.x,t.x),s=Wi(e.y,t.y);return Math.sqrt(n**2+s**2)}class Za{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=Ls(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,w=ph(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!w)return;const{point:b}=m,{timestamp:j}=Se;this.history.push({...b,timestamp:j});const{onStart:y,onMove:k}=this.handlers;p||(y&&y(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),k&&k(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=$s(p,this.transformPagePoint),de.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:w,onSessionEnd:b,resumeAnimation:j}=this.handlers;if(this.dragSnapToOrigin&&j&&j(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Ls(m.type==="pointercancel"?this.lastMoveEventInfo:$s(p,this.transformPagePoint),this.history);this.startEvent&&w&&w(m,y),b&&b(m,y)},!Br(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=Xn(t),l=$s(a,this.transformPagePoint),{point:u}=l,{timestamp:d}=Se;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=n;h&&h(t,Ls(l,this.history)),this.removeListeners=zn(En(this.contextWindow,"pointermove",this.handlePointerMove),En(this.contextWindow,"pointerup",this.handlePointerUp),En(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),wt(this.updatePoint)}}function $s(e,t){return t?{point:t(e.point)}:e}function Ki(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Ls({point:e},t){return{point:e,delta:Ki(e,Qa(t)),offset:Ki(e,gh(t)),velocity:yh(t,.1)}}function gh(e){return e[0]}function Qa(e){return e[e.length-1]}function yh(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Qa(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>Ye(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 xh(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 Gi(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 bh(e,{top:t,left:n,bottom:s,right:r}){return{x:Gi(e.x,n,r),y:Gi(e.y,t,s)}}function Yi(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 vh(e,t){return{x:Yi(e.x,t.x),y:Yi(e.y,t.y)}}function wh(e,t){let n=.5;const s=Ae(e),r=Ae(t);return r>s?n=In(t.min,t.max-s,e.min):s>r&&(n=In(e.min,e.max-r,t.min)),at(0,1,n)}function Th(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 fr=.35;function Sh(e=fr){return e===!1?e=0:e===!0&&(e=fr),{x:Hi(e,"left","right"),y:Hi(e,"top","bottom")}}function Hi(e,t,n){return{min:Ji(e,t),max:Ji(e,n)}}function Ji(e,t){return typeof e=="number"?e:e[t]||0}const jh=new WeakMap;class Ch{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(Xn(h).point)},i=(h,m)=>{const{drag:p,dragPropagation:w,onDragStart:b}=this.getProps();if(p&&!w&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Du(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 k=this.getAxisMotionValue(y).get()||0;if(et.test(k)){const{projection:v}=this.visualElement;if(v&&v.layout){const E=v.layout.layoutBox[y];E&&(k=Ae(E)*(parseFloat(k)/100))}}this.originPoint[y]=k}),b&&de.postRender(()=>b(h,m)),dr(this.visualElement,"transform");const{animationState:j}=this.visualElement;j&&j.setActive("whileDrag",!0)},a=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:w,onDirectionLock:b,onDrag:j}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=m;if(w&&this.currentDirection===null){this.currentDirection=Ph(y),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",m.point,y),this.updateAxis("y",m.point,y),this.visualElement.render(),j&&j(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 Za(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Ja(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||!as(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=xh(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&&Gt(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=bh(s.layoutBox,t):this.constraints=!1,this.elastic=Sh(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Fe(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Th(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Gt(t))return!1;const s=t.current;lt(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=Md(s,r.root,this.visualElement.getTransformPagePoint());let i=vh(r.layout.layoutBox,o);if(n){const a=n(Pd(i));this.hasMutatedConstraints=!!a,a&&(i=Va(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(!as(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,w={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(d,w)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return dr(this.visualElement,t),s.start(Jr(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(!as(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(!Gt(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]=wh({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(!as(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;jh.set(this.visualElement,this);const t=this.visualElement.current,n=En(t,"pointerdown",l=>{const{drag:u,dragListener:d=!0}=this.getProps();u&&d&&this.start(l)}),s=()=>{const{dragConstraints:l}=this.getProps();Gt(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=Bn(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=fr,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function as(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Ph(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Ah extends St{constructor(t){super(t),this.removeGroupControls=ze,this.removeListeners=ze,this.controls=new Ch(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 Zi=e=>(t,n)=>{e&&de.postRender(()=>e(t,n))};class kh extends St{constructor(){super(...arguments),this.removePointerDownListener=ze}onPointerDown(t){this.session=new Za(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ja(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Zi(t),onStart:Zi(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&de.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=En(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 fs={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Qi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Pn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(G.test(e))e=parseFloat(e);else return e;const n=Qi(e,t.target.x),s=Qi(e,t.target.y);return`${n}% ${s}%`}},Mh={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=Tt.parse(e);if(r.length>5)return s;const o=Tt.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 Fs=!1;class Eh extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;ed(Nh),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),Fs&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),fs.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Fs=!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(),Fr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Fs=!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 el(e){const[t,n]=wa(),s=f.useContext(yr);return c.jsx(Eh,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(Da),isPresent:t,safeToRemove:n})}const Nh={borderRadius:{...Pn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Pn,borderTopRightRadius:Pn,borderBottomLeftRadius:Pn,borderBottomRightRadius:Pn,boxShadow:Mh};function Dh(e,t,n){const s=je(e)?e:en(e);return s.start(Jr("",s,t,n)),s.animation}const Rh=(e,t)=>e.depth-t.depth;class Vh{constructor(){this.children=[],this.isDirty=!1}add(t){vr(this.children,t),this.isDirty=!0}remove(t){wr(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Rh),this.isDirty=!1,this.children.forEach(t)}}function Ih(e,t){const n=Ee.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(wt(s),e(o-t))};return de.setup(s,!0),()=>wt(s)}const tl=["TopLeft","TopRight","BottomLeft","BottomRight"],Oh=tl.length,eo=e=>typeof e=="string"?parseFloat(e):e,to=e=>typeof e=="number"||G.test(e);function $h(e,t,n,s,r,o){r?(e.opacity=fe(0,n.opacity??1,Lh(s)),e.opacityExit=fe(t.opacity??1,0,Fh(s))):o&&(e.opacity=fe(t.opacity??1,n.opacity??1,s));for(let i=0;i<Oh;i++){const a=`border${tl[i]}Radius`;let l=no(t,a),u=no(n,a);if(l===void 0&&u===void 0)continue;l||(l=0),u||(u=0),l===0||u===0||to(l)===to(u)?(e[a]=Math.max(fe(eo(l),eo(u),s),0),(et.test(u)||et.test(l))&&(e[a]+="%")):e[a]=u}(t.rotate||n.rotate)&&(e.rotate=fe(t.rotate||0,n.rotate||0,s))}function no(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Lh=nl(0,.5,zo),Fh=nl(.5,.95,ze);function nl(e,t,n){return s=>s<e?0:s>t?1:n(In(e,t,s))}function so(e,t){e.min=t.min,e.max=t.max}function Le(e,t){so(e.x,t.x),so(e.y,t.y)}function ro(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function io(e,t,n,s,r){return e-=t,e=ws(e,1/n,s),r!==void 0&&(e=ws(e,1/r,s)),e}function Bh(e,t=0,n=1,s=.5,r,o=e,i=e){if(et.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=io(e.min,t,n,a,r),e.max=io(e.max,t,n,a,r)}function oo(e,t,[n,s,r],o,i){Bh(e,t[n],t[s],t[r],t.scale,o,i)}const zh=["x","scaleX","originX"],Uh=["y","scaleY","originY"];function ao(e,t,n,s){oo(e.x,t,zh,n?n.x:void 0,s?s.x:void 0),oo(e.y,t,Uh,n?n.y:void 0,s?s.y:void 0)}function lo(e){return e.translate===0&&e.scale===1}function sl(e){return lo(e.x)&&lo(e.y)}function co(e,t){return e.min===t.min&&e.max===t.max}function _h(e,t){return co(e.x,t.x)&&co(e.y,t.y)}function uo(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function rl(e,t){return uo(e.x,t.x)&&uo(e.y,t.y)}function ho(e){return Ae(e.x)/Ae(e.y)}function fo(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class Xh{constructor(){this.members=[]}add(t){vr(this.members,t),t.scheduleRender()}remove(t){if(wr(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 qh(e,t,n){let s="";const r=e.x.translate/t.x,o=e.y.translate/t.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:u,rotate:d,rotateX:h,rotateY:m,skewX:p,skewY:w}=n;u&&(s=`perspective(${u}px) ${s}`),d&&(s+=`rotate(${d}deg) `),h&&(s+=`rotateX(${h}deg) `),m&&(s+=`rotateY(${m}deg) `),p&&(s+=`skewX(${p}deg) `),w&&(s+=`skewY(${w}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(s+=`scale(${a}, ${l})`),s||"none"}const Bs=["","X","Y","Z"],Wh=1e3;let Kh=0;function zs(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function il(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=_a(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&&il(s)}function ol({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=Kh++,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(Hh),this.nodes.forEach(ef),this.nodes.forEach(tf),this.nodes.forEach(Jh)},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 Vh)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Sr),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=va(i)&&!Lu(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=Ih(m,250),fs.hasAnimatedSinceResize&&(fs.hasAnimatedSinceResize=!1,this.nodes.forEach(go)))})}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 w=this.options.transition||u.getDefaultTransition()||af,{onLayoutAnimationStart:b,onLayoutAnimationComplete:j}=u.getProps(),y=!this.targetLayout||!rl(this.targetLayout,p),k=!h&&m;if(this.options.layoutRoot||this.resumeFrom||k||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const v={...$r(w,"layout"),onPlay:b,onComplete:j};(u.shouldReduceMotion||this.options.layoutRoot)&&(v.delay=0,v.type=!1),this.startAnimation(v),this.setAnimationOrigin(d,k)}else h||go(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(),wt(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(nf),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&&il(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(mo);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(po);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Qh),this.nodes.forEach(Gh),this.nodes.forEach(Yh)):this.nodes.forEach(po),this.clearAllSnapshots();const a=Ee.now();Se.delta=at(0,1e3/60,a-Se.timestamp),Se.timestamp=a,Se.isProcessing=!0,Ms.update.process(Se),Ms.preRender.process(Se),Ms.render.process(Se),Se.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Fr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Zh),this.sharedNodes.forEach(sf)}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=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&&!sl(this.projectionDelta),l=this.getTransformTemplate(),u=l?l(this.latestValues,""):void 0,d=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Dt(this.latestValues)||d)&&(r(this.instance,u),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return i&&(l=this.removeTransform(l)),lf(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(cf))){const{scroll:u}=this.root;u&&(Yt(a.x,u.offset.x),Yt(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),Yt(a.x,d.offset.x),Yt(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&&Ht(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Dt(d.latestValues)&&Ht(l,d.latestValues)}return Dt(this.latestValues)&&Ht(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||!Dt(u.latestValues))continue;ar(u.latestValues)&&u.updateSnapshot();const d=ge(),h=u.measurePageBox();Le(d,h),ao(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,d)}return Dt(this.latestValues)&&ao(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!==Se.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=Se.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(),Dn(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(),mh(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Le(this.target,this.layout.layoutBox),Oa(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(),Dn(this.relativeTargetOrigin,this.target,m.target),Le(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||ar(this.parent.latestValues)||Ia(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===Se.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;kd(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():(ro(this.prevProjectionDelta.x,this.projectionDelta.x),ro(this.prevProjectionDelta.y,this.projectionDelta.y)),Nn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==m||!fo(this.projectionDelta.x,this.prevProjectionDelta.x)||!fo(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=Jt(),this.projectionDelta=Jt(),this.projectionDeltaWithTransform=Jt()}setAnimationOrigin(i,a=!1){const l=this.snapshot,u=l?l.latestValues:{},d={...this.latestValues},h=Jt();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=ge(),p=l?l.source:void 0,w=this.layout?this.layout.source:void 0,b=p!==w,j=this.getStack(),y=!j||j.members.length<=1,k=!!(b&&!y&&this.options.crossfade===!0&&!this.path.some(of));this.animationProgress=0;let v;this.mixTargetDelta=E=>{const D=E/1e3;yo(h.x,i.x,D),yo(h.y,i.y,D),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Dn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),rf(this.relativeTarget,this.relativeTargetOrigin,m,D),v&&_h(this.relativeTarget,v)&&(this.isProjectionDirty=!1),v||(v=ge()),Le(v,this.relativeTarget)),b&&(this.animationValues=d,$h(d,u,this.latestValues,D,k,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=D},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(wt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=de.update(()=>{fs.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=en(0)),this.currentAnimation=Dh(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(Wh),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&&al(this.options.animationType,this.layout.layoutBox,u.layoutBox)){l=this.target||ge();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}Le(a,l),Ht(a,d),Nn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new Xh),this.sharedNodes.get(i).add(a);const u=a.options.initialPromotionConfig;a.promote({transition:u?u.transition:void 0,preserveFollowOpacity:u&&u.shouldPreserveFollowOpacity?u.shouldPreserveFollowOpacity(a):void 0})}isLead(){const i=this.getStack();return i?i.lead===this:!0}getLead(){const{layoutId:i}=this.options;return i?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:i}=this.options;return i?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:i}=this.options;if(i)return this.root.sharedNodes.get(i)}promote({needsReset:i,transition:a,preserveFollowOpacity: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&&zs("z",i,u,this.animationValues);for(let d=0;d<Bs.length;d++)zs(`rotate${Bs[d]}`,i,u,this.animationValues),zs(`skew${Bs[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=ds(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=ds(a?.pointerEvents)||""),this.hasProjected&&!Dt(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=qh(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 w in Fn){if(d[w]===void 0)continue;const{correct:b,applyTo:j,isCSSVariable:y}=Fn[w],k=h==="none"?d[w]:b(d[w],u);if(j){const v=j.length;for(let E=0;E<v;E++)i[j[E]]=k}else y?this.options.visualElement.renderState.vars[w]=k:i[w]=k}this.options.layoutId&&(i.pointerEvents=u===this?ds(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(mo),this.root.sharedNodes.clear()}}}function Gh(e){e.updateLayout()}function Yh(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=Ae(h);h.min=n[d].min,h.max=h.min+m}):al(r,t.layoutBox,n)&&Fe(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=Jt();Nn(i,n,t.layoutBox);const a=Jt();o?Nn(a,e.applyTransform(s,!0),t.measuredBox):Nn(a,n,t.layoutBox);const l=!sl(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();Dn(p,t.layoutBox,h.layoutBox);const w=ge();Dn(w,n,m.layoutBox),rl(p,w)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=w,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:l,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function Hh(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 Jh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Zh(e){e.clearSnapshot()}function mo(e){e.clearMeasurements()}function po(e){e.isLayoutDirty=!1}function Qh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function go(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function ef(e){e.resolveTargetDelta()}function tf(e){e.calcProjection()}function nf(e){e.resetSkewAndRotation()}function sf(e){e.removeLeadSnapshot()}function yo(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 xo(e,t,n,s){e.min=fe(t.min,n.min,s),e.max=fe(t.max,n.max,s)}function rf(e,t,n,s){xo(e.x,t.x,n.x,s),xo(e.y,t.y,n.y,s)}function of(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const af={duration:.45,ease:[.4,0,.1,1]},bo=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),vo=bo("applewebkit/")&&!bo("chrome/")?Math.round:ze;function wo(e){e.min=vo(e.min),e.max=vo(e.max)}function lf(e){wo(e.x),wo(e.y)}function al(e,t,n){return e==="position"||e==="preserve-aspect"&&!fh(ho(t),ho(n),.2)}function cf(e){return e!==e.root&&e.scroll?.wasRoot}const uf=ol({attachResizeListener:(e,t)=>Bn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Us={current:void 0},ll=ol({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Us.current){const e=new uf({});e.mount(window),e.setOptions({layoutScroll:!0}),Us.current=e}return Us.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),df={pan:{Feature:kh},drag:{Feature:Ah,ProjectionNode:ll,MeasureLayout:el}};function To(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,Xn(t)))}class hf extends St{mount(){const{current:t}=this.node;t&&(this.unmount=Ru(t,(n,s)=>(To(this.node,s,"Start"),r=>To(this.node,r,"End"))))}unmount(){}}class ff extends St{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=zn(Bn(this.node.current,"focus",()=>this.onFocus()),Bn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function So(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,Xn(t)))}class mf extends St{mount(){const{current:t}=this.node;t&&(this.unmount=$u(t,(n,s)=>(So(this.node,s,"Start"),(r,{success:o})=>So(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const mr=new WeakMap,_s=new WeakMap,pf=e=>{const t=mr.get(e.target);t&&t(e)},gf=e=>{e.forEach(pf)};function yf({root:e,...t}){const n=e||document;_s.has(n)||_s.set(n,{});const s=_s.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(gf,{root:e,...t})),s[r]}function xf(e,t,n){const s=yf(t);return mr.set(e,n),s.observe(e),()=>{mr.delete(e),s.unobserve(e)}}const bf={some:0,all:1};class vf extends St{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:bf[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 xf(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(wf(t,n))&&this.startObserver()}unmount(){}}function wf({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const cl={inView:{Feature:vf},tap:{Feature:mf},focus:{Feature:ff},hover:{Feature:hf}},Tf={layout:{ProjectionNode:ll,MeasureLayout:el}},Sf={...Ga,...cl,...df,...Tf},jf=Cd(Sf,Ua),Cf={renderer:Ua,...Ga,...cl};function Zr(e,t){return hs(e,t)}const Pf=Zr("button"),ls=Zr("div"),Af=Zr("p"),Qe=Symbol.for("@arcteninc/core:originalName");function kf(e,t){return e[Qe]=t,e}function Mf(e,t,n,s){if(typeof e!="function")return null;const r=e[Qe];if(r){const a=t[r];if(a&&!n.has(a.name))return{fn:e,meta:a}}const o=e.name;let i;if(o&&(i=t[o],i&&!n.has(i.name)))return e[Qe]=i.name,{fn:e,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=t[a],i))return e[Qe]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(l=>!n.has(l.name)),i)return e[Qe]=i.name,{fn:e,meta:i};return null}function Qr(e,t){if(e.length===0)return[];let n,s;if(!t)throw new Error(`❌ toolMetadata is required when tools are provided!
9
+ `),()=>{j.contains(b)&&j.removeChild(b)}},[t]),c.jsx(_u,{isPresent:t,childRef:o,sizeRef:i,children:Ge.cloneElement(e,{ref:l})})}const Wu=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const u=xr(qu),d=f.useId();let h=!0,m=f.useMemo(()=>(h=!1,{id:d,initial:t,isPresent:n,custom:r,onExitComplete:p=>{u.set(p,!0);for(const w of u.values())if(!w)return;s&&s()},register:p=>(u.set(p,!1),()=>u.delete(p))}),[n,u,s]);return o&&h&&(m={...m}),f.useMemo(()=>{u.forEach((p,w)=>u.set(w,!1))},[n]),Ge.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(e=c.jsx(Xu,{isPresent:n,anchorX:a,root:l,children:e})),c.jsx(Ss.Provider,{value:m,children:e})};function qu(){return new Map}function wa(e=!0){const t=f.useContext(Ss);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 os=e=>e.key||"";function Ei(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const Ku=({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]=wa(i),h=f.useMemo(()=>Ei(e),[e]),m=i&&!u?[]:h.map(os),p=f.useRef(!0),w=f.useRef(h),b=xr(()=>new Map),[j,y]=f.useState(h),[k,v]=f.useState(h);Eo(()=>{p.current=!1,w.current=h;for(let $=0;$<k.length;$++){const L=os(k[$]);m.includes(L)?b.delete(L):b.get(L)!==!0&&b.set(L,!1)}},[k,m.length,m.join("-")]);const E=[];if(h!==j){let $=[...h];for(let L=0;L<k.length;L++){const D=k[L],z=os(D);m.includes(z)||($.splice(L,0,D),E.push(D))}return o==="wait"&&E.length&&($=E),v(Ei($)),y(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&k.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:N}=f.useContext(yr);return c.jsx(c.Fragment,{children:k.map($=>{const L=os($),D=i&&!u?!1:h===k||m.includes(L),z=()=>{if(b.has(L))b.set(L,!0);else return;let A=!0;b.forEach(M=>{M||(A=!1)}),A&&(N?.(),v(w.current),i&&d?.(),s&&s())};return c.jsx(Wu,{isPresent:D,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:l,onExitComplete:D?void 0:z,anchorX:a,children:$},L)})})},Ur=f.createContext({strict:!1}),Di={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"]},tn={};for(const e in Di)tn[e]={isEnabled:t=>Di[e].some(n=>!!t[n])};function or(e){for(const t in e)tn[t]={...tn[t],...e[t]}}function Gu({children:e,features:t,strict:n=!1}){const[,s]=f.useState(!Is(t)),r=f.useRef(void 0);if(!Is(t)){const{renderer:o,...i}=t;r.current=o,or(i)}return f.useEffect(()=>{Is(t)&&t().then(({renderer:o,...i})=>{or(i),r.current=o,s(!0)})},[]),c.jsx(Ur.Provider,{value:{renderer:r.current,strict:n},children:e})}function Is(e){return typeof e=="function"}const Yu=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 vs(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Yu.has(e)}let Ta=e=>!vs(e);function Hu(e){typeof e=="function"&&(Ta=t=>t.startsWith("on")?!vs(t):e(t))}try{Hu(require("@emotion/is-prop-valid").default)}catch{}function Ju(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(Ta(r)||n===!0&&vs(r)||!t&&!vs(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const js=f.createContext({});function Cs(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function Ln(e){return typeof e=="string"||Array.isArray(e)}const _r=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Xr=["initial",..._r];function Ps(e){return Cs(e.animate)||Xr.some(t=>Ln(e[t]))}function Sa(e){return!!(Ps(e)||e.variants)}function Zu(e,t){if(Ps(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Ln(n)?n:void 0,animate:Ln(s)?s:void 0}}return e.inherit!==!1?t:{}}function Qu(e){const{initial:t,animate:n}=Zu(e,f.useContext(js));return f.useMemo(()=>({initial:t,animate:n}),[Ni(t),Ni(n)])}function Ni(e){return Array.isArray(e)?e.join(" "):e}const Fn={};function ed(e){for(const t in e)Fn[t]=e[t],Ar(t)&&(Fn[t].isCSSVariable=!0)}function ja(e,{layout:t,layoutId:n}){return on.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Fn[e]||e==="opacity")}const td={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},nd=rn.length;function sd(e,t,n){let s="",r=!0;for(let o=0;o<nd;o++){const i=rn[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=pa(a,Lr[i]);if(!l){r=!1;const d=td[i]||i;s+=`${d}(${u}) `}n&&(t[i]=u)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function Wr(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(on.has(l)){i=!0;continue}else if(Ar(l)){r[l]=u;continue}else{const d=pa(u,Lr[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=sd(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 Ca(e,t,n){for(const s in t)!je(t[s])&&!ja(s,n)&&(e[s]=t[s])}function rd({transformTemplate:e},t){return f.useMemo(()=>{const n=qr();return Wr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function id(e,t){const n=e.style||{},s={};return Ca(s,n,e),Object.assign(s,rd(e,t)),s}function od(e,t){const n={},s=id(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 ad={offset:"stroke-dashoffset",array:"stroke-dasharray"},ld={offset:"strokeDashoffset",array:"strokeDasharray"};function cd(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?ad:ld;e[o.offset]=G.transform(-s);const i=G.transform(t),a=G.transform(n);e[o.array]=`${i} ${a}`}function Pa(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,u,d){if(Wr(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&&cd(h,r,o,i,!1)}const Aa=()=>({...qr(),attrs:{}}),ka=e=>typeof e=="string"&&e.toLowerCase()==="svg";function ud(e,t,n,s){const r=f.useMemo(()=>{const o=Aa();return Pa(o,t,ka(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Ca(o,e.style,e),r.style={...o,...r.style}}return r}const dd=["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 Kr(e){return typeof e!="string"||e.includes("-")?!1:!!(dd.indexOf(e)>-1||/[A-Z]/u.test(e))}function hd(e,t,n,{latestValues:s},r,o=!1){const a=(Kr(e)?ud:od)(t,s,r,e),l=Ju(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 Ri(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Gr(e,t,n,s){if(typeof t=="function"){const[r,o]=Ri(s);t=t(n!==void 0?n:e.custom,r,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,o]=Ri(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function ds(e){return je(e)?e.get():e}function fd({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:md(n,s,r,e),renderState:t()}}function md(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=ds(o[m]);let{initial:i,animate:a}=e;const l=Ps(e),u=Sa(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"&&!Cs(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p<m.length;p++){const w=Gr(e,m[p]);if(w){const{transitionEnd:b,transition:j,...y}=w;for(const k in y){let v=y[k];if(Array.isArray(v)){const E=d?v.length-1:0;v=v[E]}v!==null&&(r[k]=v)}for(const k in b)r[k]=b[k]}}}return r}const Ma=e=>(t,n)=>{const s=f.useContext(js),r=f.useContext(Ss),o=()=>fd(e,t,s,r);return n?o():xr(o)};function Yr(e,t,n){const{style:s}=e,r={};for(const o in s)(je(s[o])||t.style&&je(t.style[o])||ja(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const pd=Ma({scrapeMotionValuesFromProps:Yr,createRenderState:qr});function Ea(e,t,n){const s=Yr(e,t,n);for(const r in e)if(je(e[r])||je(t[r])){const o=rn.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const gd=Ma({scrapeMotionValuesFromProps:Ea,createRenderState:Aa}),yd=Symbol.for("motionComponentSymbol");function Gt(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function xd(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):Gt(n)&&(n.current=s))},[t])}const Hr=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),bd="framerAppearId",Da="data-"+Hr(bd),Na=f.createContext({});function vd(e,t,n,s,r){const{visualElement:o}=f.useContext(js),i=f.useContext(Ur),a=f.useContext(Ss),l=f.useContext(zr).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(Na);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&wd(u.current,n,r,h);const m=f.useRef(!1);f.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[Da],w=f.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return Eo(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),w.current&&d.animationState&&d.animationState.animateChanges())}),f.useEffect(()=>{d&&(!w.current&&d.animationState&&d.animationState.animateChanges(),w.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),w.current=!1),d.enteringChildren=void 0)}),d}function wd(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:Ra(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Gt(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:l,layoutRoot:u})}function Ra(e){if(e)return e.options.allowProjection!==!1?e.projection:Ra(e.parent)}function hs(e,{forwardMotionProps:t=!1}={},n,s){n&&or(n);const r=Kr(e)?gd:pd;function o(a,l){let u;const d={...f.useContext(zr),...a,layoutId:Td(a)},{isStatic:h}=d,m=Qu(a),p=r(a,h);if(!h&&br){Sd(d,n);const w=jd(d);u=w.MeasureLayout,m.visualElement=vd(e,p,d,s,w.ProjectionNode)}return c.jsxs(js.Provider,{value:m,children:[u&&m.visualElement?c.jsx(u,{visualElement:m.visualElement,...d}):null,hd(e,a,xd(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[yd]=e,i}function Td({layoutId:e}){const t=f.useContext(yr).id;return t&&e!==void 0?t+"-"+e:e}function Sd(e,t){const n=f.useContext(Ur).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?nn(!1,s,"lazy-strict-mode"):lt(!1,s,"lazy-strict-mode")}}function jd(e){const{drag:t,layout:n}=tn;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Cd(e,t){if(typeof Proxy>"u")return hs;const n=new Map,s=(o,i)=>hs(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&jr(!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,hs(i,void 0,e,t)),n.get(i))})}function Va({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function Pd({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Ad(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 Os(e){return e===void 0||e===1}function ar({scale:e,scaleX:t,scaleY:n}){return!Os(e)||!Os(t)||!Os(n)}function Nt(e){return ar(e)||Ia(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Ia(e){return Vi(e.x)||Vi(e.y)}function Vi(e){return e&&e!=="0%"}function ws(e,t,n){const s=e-n,r=t*s;return n+r}function Ii(e,t,n,s,r){return r!==void 0&&(e=ws(e,r,s)),ws(e,n,s)+t}function lr(e,t=0,n=1,s,r){e.min=Ii(e.min,t,n,s,r),e.max=Ii(e.max,t,n,s,r)}function Oa(e,{x:t,y:n}){lr(e.x,t.translate,t.scale,t.originPoint),lr(e.y,n.translate,n.scale,n.originPoint)}const Oi=.999999999999,$i=1.0000000000001;function kd(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&&Ht(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,Oa(e,i)),s&&Nt(o.latestValues)&&Ht(e,o.latestValues))}t.x<$i&&t.x>Oi&&(t.x=1),t.y<$i&&t.y>Oi&&(t.y=1)}function Yt(e,t){e.min=e.min+t,e.max=e.max+t}function Li(e,t,n,s,r=.5){const o=fe(e.min,e.max,r);lr(e,t,n,o,s)}function Ht(e,t){Li(e.x,t.x,t.scaleX,t.scale,t.originX),Li(e.y,t.y,t.scaleY,t.scale,t.originY)}function $a(e,t){return Va(Ad(e.getBoundingClientRect(),t))}function Md(e,t,n){const s=$a(e,n),{scroll:r}=t;return r&&(Yt(s.x,r.offset.x),Yt(s.y,r.offset.y)),s}const Fi=()=>({translate:0,scale:1,origin:0,originPoint:0}),Jt=()=>({x:Fi(),y:Fi()}),Bi=()=>({min:0,max:0}),ge=()=>({x:Bi(),y:Bi()}),cr={current:null},La={current:!1};function Ed(){if(La.current=!0,!!br)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>cr.current=e.matches;e.addEventListener("change",t),t()}else cr.current=!1}const Dd=new WeakMap;function Nd(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,en(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,en(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const zi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Rd{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Or,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const m=Ee.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=Ps(n),this.isVariantNode=Sa(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,Dd.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),La.current||Ed(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:cr.current,process.env.NODE_ENV!=="production"&&jr(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(),wt(this.notifyUpdate),wt(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=on.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 tn){const n=tn[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<zi.length;s++){const r=zi[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=Nd(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=en(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"&&(Do(s)||Ro(s))?s=parseFloat(s):!Bu(s)&&Tt.test(n)&&(s=ma(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=Gr(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 Sr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Fr.render(this.render)}}class Fa extends Rd{constructor(){super(...arguments),this.KeyframeResolver=ku}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 Ba(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 Vd(e){return window.getComputedStyle(e)}class Id extends Fa{constructor(){super(...arguments),this.type="html",this.renderInstance=Ba}readValueFromInstance(t,n){if(on.has(n))return this.projection?.isProjecting?Qs(n):qc(t,n);{const s=Vd(t),r=(Ar(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return $a(t,n)}build(t,n,s){Wr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Yr(t,n,s)}}const za=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 Od(e,t,n,s){Ba(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(za.has(r)?r:Hr(r),t.attrs[r])}class $d extends Fa{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ge}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(on.has(n)){const s=fa(n);return s&&s.default||0}return n=za.has(n)?n:Hr(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return Ea(t,n,s)}build(t,n,s){Pa(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){Od(t,n,s,r)}mount(t){this.isSVGTag=ka(t.tagName),super.mount(t)}}const Ua=(e,t)=>Kr(e)?new $d(t):new Id(t,{allowProjection:e!==f.Fragment});function Qt(e,t,n){const s=e.getProps();return Gr(s,t,n!==void 0?n:s.custom,e)}const ur=e=>Array.isArray(e);function Ld(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,en(n))}function Fd(e){return ur(e)?e[e.length-1]||0:e}function Bd(e,t){const n=Qt(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Fd(o[i]);Ld(e,i,a)}}function zd(e){return!!(je(e)&&e.add)}function dr(e,t){const n=e.getValue("willChange");if(zd(n))return n.add(t);if(!n&&ct.WillChange){const s=new ct.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function _a(e){return e.props[Da]}const Ud=e=>e!==null;function _d(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Ud),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const Xd={type:"spring",stiffness:500,damping:25,restSpeed:10},Wd=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),qd={type:"keyframes",duration:.8},Kd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Gd=(e,{keyframes:t})=>t.length>2?qd:on.has(e)?e.startsWith("scale")?Wd(t[1]):Xd:Kd;function Yd({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 Jr=(e,t,n,s={},r,o)=>i=>{const a=$r(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};Yd(a)||Object.assign(d,Gd(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)&&(rr(d),d.delay===0&&(h=!0)),(ct.instantAnimations||ct.skipAnimations)&&(h=!0,rr(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const m=_d(d.keyframes,a);if(m!==void 0){de.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new Ir(d):new pu(d)};function Hd({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function Xa(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&&Hd(u,d))continue;const p={delay:n,...$r(o||{},d)},w=h.get();if(w!==void 0&&!h.isAnimating&&!Array.isArray(m)&&m===w&&!p.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const y=_a(e);if(y){const k=window.MotionHandoffAnimation(y,d,de);k!==null&&(p.startTime=k,b=!0)}}dr(e,d),h.start(Jr(d,h,m,e.shouldReduceMotion&&ua.has(d)?{type:!1}:p,e,b));const j=h.animation;j&&l.push(j)}return i&&Promise.all(l).then(()=>{de.update(()=>{i&&Bd(e,i)})}),l}function Wa(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 hr(e,t,n={}){const s=Qt(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(Xa(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=r;return Jd(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 Jd(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(hr(l,t,{...i,delay:n+(typeof s=="function"?0:s)+Wa(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function Zd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>hr(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=hr(e,t,n);else{const r=typeof t=="function"?Qt(e,t,n.custom):t;s=Promise.all(Xa(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function qa(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 Qd=Xr.length;function Ka(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Ka(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<Qd;n++){const s=Xr[n],r=e.props[s];(Ln(r)||r===!1)&&(t[s]=r)}return t}const eh=[..._r].reverse(),th=_r.length;function nh(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Zd(e,n,s)))}function sh(e){let t=nh(e),n=Ui(),s=!0;const r=l=>(u,d)=>{const h=Qt(e,d,l==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:m,transitionEnd:p,...w}=h;u={...u,...w,...p}}return u};function o(l){t=l(e)}function i(l){const{props:u}=e,d=Ka(e.parent)||{},h=[],m=new Set;let p={},w=1/0;for(let j=0;j<th;j++){const y=eh[j],k=n[y],v=u[y]!==void 0?u[y]:d[y],E=Ln(v),N=y===l?k.isActive:null;N===!1&&(w=j);let $=v===d[y]&&v!==u[y]&&E;if($&&s&&e.manuallyAnimateOnMount&&($=!1),k.protectedKeys={...p},!k.isActive&&N===null||!v&&!k.prevProp||Cs(v)||typeof v=="boolean")continue;const L=rh(k.prevProp,v);let D=L||y===l&&k.isActive&&!$&&E||j>w&&E,z=!1;const A=Array.isArray(v)?v:[v];let M=A.reduce(r(y),{});N===!1&&(M={});const{prevResolvedValues:I={}}=k,F={...I,...M},K=X=>{D=!0,m.has(X)&&(z=!0,m.delete(X)),k.needsAnimating[X]=!0;const oe=e.getValue(X);oe&&(oe.liveStyle=!1)};for(const X in F){const oe=M[X],we=I[X];if(p.hasOwnProperty(X))continue;let Te=!1;ur(oe)&&ur(we)?Te=!qa(oe,we):Te=oe!==we,Te?oe!=null?K(X):m.add(X):oe!==void 0&&m.has(X)?K(X):k.protectedKeys[X]=!0}k.prevProp=v,k.prevResolvedValues=M,k.isActive&&(p={...p,...M}),s&&e.blockInitialAnimation&&(D=!1);const Y=$&&L;D&&(!Y||z)&&h.push(...A.map(X=>{const oe={type:y};if(typeof X=="string"&&s&&!Y&&e.manuallyAnimateOnMount&&e.parent){const{parent:we}=e,Te=Qt(we,X);if(we.enteringChildren&&Te){const{delayChildren:se}=Te.transition||{};oe.delay=Wa(we.enteringChildren,e,se)}}return{animation:X,options:oe}}))}if(m.size){const j={};if(typeof u.initial!="boolean"){const y=Qt(e,Array.isArray(u.initial)?u.initial[0]:u.initial);y&&y.transition&&(j.transition=y.transition)}m.forEach(y=>{const k=e.getBaseTarget(y),v=e.getValue(y);v&&(v.liveStyle=!0),j[y]=k??null}),h.push({animation:j})}let b=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(b=!1),s=!1,b?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=Ui()}}}function rh(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!qa(t,e):!1}function Et(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Ui(){return{animate:Et(!0),whileInView:Et(),whileHover:Et(),whileTap:Et(),whileDrag:Et(),whileFocus:Et(),exit:Et()}}class St{constructor(t){this.isMounted=!1,this.node=t}update(){}}class ih extends St{constructor(t){super(t),t.animationState||(t.animationState=sh(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Cs(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 oh=0;class ah extends St{constructor(){super(...arguments),this.id=oh++}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 Ga={animation:{Feature:ih},exit:{Feature:ah}};function Bn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function Xn(e){return{point:{x:e.pageX,y:e.pageY}}}const lh=e=>t=>Br(t)&&e(t,Xn(t));function En(e,t,n,s){return Bn(e,t,lh(n),s)}const Ya=1e-4,ch=1-Ya,uh=1+Ya,Ha=.01,dh=0-Ha,hh=0+Ha;function Ae(e){return e.max-e.min}function fh(e,t,n){return Math.abs(e-t)<=n}function _i(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>=ch&&e.scale<=uh||isNaN(e.scale))&&(e.scale=1),(e.translate>=dh&&e.translate<=hh||isNaN(e.translate))&&(e.translate=0)}function Dn(e,t,n,s){_i(e.x,t.x,n.x,s?s.originX:void 0),_i(e.y,t.y,n.y,s?s.originY:void 0)}function Xi(e,t,n){e.min=n.min+t.min,e.max=e.min+Ae(t)}function mh(e,t,n){Xi(e.x,t.x,n.x),Xi(e.y,t.y,n.y)}function Wi(e,t,n){e.min=t.min-n.min,e.max=e.min+Ae(t)}function Nn(e,t,n){Wi(e.x,t.x,n.x),Wi(e.y,t.y,n.y)}function Fe(e){return[e("x"),e("y")]}const Ja=({current:e})=>e?e.ownerDocument.defaultView:null,qi=(e,t)=>Math.abs(e-t);function ph(e,t){const n=qi(e.x,t.x),s=qi(e.y,t.y);return Math.sqrt(n**2+s**2)}class Za{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=Ls(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,w=ph(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!w)return;const{point:b}=m,{timestamp:j}=Se;this.history.push({...b,timestamp:j});const{onStart:y,onMove:k}=this.handlers;p||(y&&y(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),k&&k(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=$s(p,this.transformPagePoint),de.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:w,onSessionEnd:b,resumeAnimation:j}=this.handlers;if(this.dragSnapToOrigin&&j&&j(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Ls(m.type==="pointercancel"?this.lastMoveEventInfo:$s(p,this.transformPagePoint),this.history);this.startEvent&&w&&w(m,y),b&&b(m,y)},!Br(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=Xn(t),l=$s(a,this.transformPagePoint),{point:u}=l,{timestamp:d}=Se;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=n;h&&h(t,Ls(l,this.history)),this.removeListeners=zn(En(this.contextWindow,"pointermove",this.handlePointerMove),En(this.contextWindow,"pointerup",this.handlePointerUp),En(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),wt(this.updatePoint)}}function $s(e,t){return t?{point:t(e.point)}:e}function Ki(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Ls({point:e},t){return{point:e,delta:Ki(e,Qa(t)),offset:Ki(e,gh(t)),velocity:yh(t,.1)}}function gh(e){return e[0]}function Qa(e){return e[e.length-1]}function yh(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Qa(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>Ye(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 xh(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 Gi(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 bh(e,{top:t,left:n,bottom:s,right:r}){return{x:Gi(e.x,n,r),y:Gi(e.y,t,s)}}function Yi(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 vh(e,t){return{x:Yi(e.x,t.x),y:Yi(e.y,t.y)}}function wh(e,t){let n=.5;const s=Ae(e),r=Ae(t);return r>s?n=In(t.min,t.max-s,e.min):s>r&&(n=In(e.min,e.max-r,t.min)),at(0,1,n)}function Th(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 fr=.35;function Sh(e=fr){return e===!1?e=0:e===!0&&(e=fr),{x:Hi(e,"left","right"),y:Hi(e,"top","bottom")}}function Hi(e,t,n){return{min:Ji(e,t),max:Ji(e,n)}}function Ji(e,t){return typeof e=="number"?e:e[t]||0}const jh=new WeakMap;class Ch{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(Xn(h).point)},i=(h,m)=>{const{drag:p,dragPropagation:w,onDragStart:b}=this.getProps();if(p&&!w&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Nu(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 k=this.getAxisMotionValue(y).get()||0;if(et.test(k)){const{projection:v}=this.visualElement;if(v&&v.layout){const E=v.layout.layoutBox[y];E&&(k=Ae(E)*(parseFloat(k)/100))}}this.originPoint[y]=k}),b&&de.postRender(()=>b(h,m)),dr(this.visualElement,"transform");const{animationState:j}=this.visualElement;j&&j.setActive("whileDrag",!0)},a=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:w,onDirectionLock:b,onDrag:j}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=m;if(w&&this.currentDirection===null){this.currentDirection=Ph(y),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",m.point,y),this.updateAxis("y",m.point,y),this.visualElement.render(),j&&j(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 Za(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Ja(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||!as(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=xh(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&&Gt(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=bh(s.layoutBox,t):this.constraints=!1,this.elastic=Sh(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Fe(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Th(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Gt(t))return!1;const s=t.current;lt(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=Md(s,r.root,this.visualElement.getTransformPagePoint());let i=vh(r.layout.layoutBox,o);if(n){const a=n(Pd(i));this.hasMutatedConstraints=!!a,a&&(i=Va(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(!as(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,w={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(d,w)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return dr(this.visualElement,t),s.start(Jr(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(!as(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(!Gt(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]=wh({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(!as(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;jh.set(this.visualElement,this);const t=this.visualElement.current,n=En(t,"pointerdown",l=>{const{drag:u,dragListener:d=!0}=this.getProps();u&&d&&this.start(l)}),s=()=>{const{dragConstraints:l}=this.getProps();Gt(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=Bn(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=fr,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function as(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Ph(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Ah extends St{constructor(t){super(t),this.removeGroupControls=ze,this.removeListeners=ze,this.controls=new Ch(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 Zi=e=>(t,n)=>{e&&de.postRender(()=>e(t,n))};class kh extends St{constructor(){super(...arguments),this.removePointerDownListener=ze}onPointerDown(t){this.session=new Za(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ja(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Zi(t),onStart:Zi(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&de.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=En(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 fs={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Qi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Pn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(G.test(e))e=parseFloat(e);else return e;const n=Qi(e,t.target.x),s=Qi(e,t.target.y);return`${n}% ${s}%`}},Mh={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=Tt.parse(e);if(r.length>5)return s;const o=Tt.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 Fs=!1;class Eh extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;ed(Dh),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),Fs&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),fs.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Fs=!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(),Fr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Fs=!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 el(e){const[t,n]=wa(),s=f.useContext(yr);return c.jsx(Eh,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(Na),isPresent:t,safeToRemove:n})}const Dh={borderRadius:{...Pn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Pn,borderTopRightRadius:Pn,borderBottomLeftRadius:Pn,borderBottomRightRadius:Pn,boxShadow:Mh};function Nh(e,t,n){const s=je(e)?e:en(e);return s.start(Jr("",s,t,n)),s.animation}const Rh=(e,t)=>e.depth-t.depth;class Vh{constructor(){this.children=[],this.isDirty=!1}add(t){vr(this.children,t),this.isDirty=!0}remove(t){wr(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Rh),this.isDirty=!1,this.children.forEach(t)}}function Ih(e,t){const n=Ee.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(wt(s),e(o-t))};return de.setup(s,!0),()=>wt(s)}const tl=["TopLeft","TopRight","BottomLeft","BottomRight"],Oh=tl.length,eo=e=>typeof e=="string"?parseFloat(e):e,to=e=>typeof e=="number"||G.test(e);function $h(e,t,n,s,r,o){r?(e.opacity=fe(0,n.opacity??1,Lh(s)),e.opacityExit=fe(t.opacity??1,0,Fh(s))):o&&(e.opacity=fe(t.opacity??1,n.opacity??1,s));for(let i=0;i<Oh;i++){const a=`border${tl[i]}Radius`;let l=no(t,a),u=no(n,a);if(l===void 0&&u===void 0)continue;l||(l=0),u||(u=0),l===0||u===0||to(l)===to(u)?(e[a]=Math.max(fe(eo(l),eo(u),s),0),(et.test(u)||et.test(l))&&(e[a]+="%")):e[a]=u}(t.rotate||n.rotate)&&(e.rotate=fe(t.rotate||0,n.rotate||0,s))}function no(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Lh=nl(0,.5,zo),Fh=nl(.5,.95,ze);function nl(e,t,n){return s=>s<e?0:s>t?1:n(In(e,t,s))}function so(e,t){e.min=t.min,e.max=t.max}function Le(e,t){so(e.x,t.x),so(e.y,t.y)}function ro(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function io(e,t,n,s,r){return e-=t,e=ws(e,1/n,s),r!==void 0&&(e=ws(e,1/r,s)),e}function Bh(e,t=0,n=1,s=.5,r,o=e,i=e){if(et.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=io(e.min,t,n,a,r),e.max=io(e.max,t,n,a,r)}function oo(e,t,[n,s,r],o,i){Bh(e,t[n],t[s],t[r],t.scale,o,i)}const zh=["x","scaleX","originX"],Uh=["y","scaleY","originY"];function ao(e,t,n,s){oo(e.x,t,zh,n?n.x:void 0,s?s.x:void 0),oo(e.y,t,Uh,n?n.y:void 0,s?s.y:void 0)}function lo(e){return e.translate===0&&e.scale===1}function sl(e){return lo(e.x)&&lo(e.y)}function co(e,t){return e.min===t.min&&e.max===t.max}function _h(e,t){return co(e.x,t.x)&&co(e.y,t.y)}function uo(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function rl(e,t){return uo(e.x,t.x)&&uo(e.y,t.y)}function ho(e){return Ae(e.x)/Ae(e.y)}function fo(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class Xh{constructor(){this.members=[]}add(t){vr(this.members,t),t.scheduleRender()}remove(t){if(wr(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 Wh(e,t,n){let s="";const r=e.x.translate/t.x,o=e.y.translate/t.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:u,rotate:d,rotateX:h,rotateY:m,skewX:p,skewY:w}=n;u&&(s=`perspective(${u}px) ${s}`),d&&(s+=`rotate(${d}deg) `),h&&(s+=`rotateX(${h}deg) `),m&&(s+=`rotateY(${m}deg) `),p&&(s+=`skewX(${p}deg) `),w&&(s+=`skewY(${w}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(s+=`scale(${a}, ${l})`),s||"none"}const Bs=["","X","Y","Z"],qh=1e3;let Kh=0;function zs(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function il(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=_a(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&&il(s)}function ol({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=Kh++,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(Hh),this.nodes.forEach(ef),this.nodes.forEach(tf),this.nodes.forEach(Jh)},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 Vh)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Sr),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=va(i)&&!Lu(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=Ih(m,250),fs.hasAnimatedSinceResize&&(fs.hasAnimatedSinceResize=!1,this.nodes.forEach(go)))})}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 w=this.options.transition||u.getDefaultTransition()||af,{onLayoutAnimationStart:b,onLayoutAnimationComplete:j}=u.getProps(),y=!this.targetLayout||!rl(this.targetLayout,p),k=!h&&m;if(this.options.layoutRoot||this.resumeFrom||k||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const v={...$r(w,"layout"),onPlay:b,onComplete:j};(u.shouldReduceMotion||this.options.layoutRoot)&&(v.delay=0,v.type=!1),this.startAnimation(v),this.setAnimationOrigin(d,k)}else h||go(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(),wt(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(nf),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&&il(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(mo);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(po);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Qh),this.nodes.forEach(Gh),this.nodes.forEach(Yh)):this.nodes.forEach(po),this.clearAllSnapshots();const a=Ee.now();Se.delta=at(0,1e3/60,a-Se.timestamp),Se.timestamp=a,Se.isProcessing=!0,Ms.update.process(Se),Ms.preRender.process(Se),Ms.render.process(Se),Se.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Fr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Zh),this.sharedNodes.forEach(sf)}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=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&&!sl(this.projectionDelta),l=this.getTransformTemplate(),u=l?l(this.latestValues,""):void 0,d=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Nt(this.latestValues)||d)&&(r(this.instance,u),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return i&&(l=this.removeTransform(l)),lf(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(cf))){const{scroll:u}=this.root;u&&(Yt(a.x,u.offset.x),Yt(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),Yt(a.x,d.offset.x),Yt(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&&Ht(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Nt(d.latestValues)&&Ht(l,d.latestValues)}return Nt(this.latestValues)&&Ht(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||!Nt(u.latestValues))continue;ar(u.latestValues)&&u.updateSnapshot();const d=ge(),h=u.measurePageBox();Le(d,h),ao(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,d)}return Nt(this.latestValues)&&ao(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!==Se.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=Se.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ge(),this.relativeTargetOrigin=ge(),Nn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),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(),mh(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Le(this.target,this.layout.layoutBox),Oa(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(),Nn(this.relativeTargetOrigin,this.target,m.target),Le(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||ar(this.parent.latestValues)||Ia(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===Se.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;kd(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():(ro(this.prevProjectionDelta.x,this.projectionDelta.x),ro(this.prevProjectionDelta.y,this.projectionDelta.y)),Dn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==m||!fo(this.projectionDelta.x,this.prevProjectionDelta.x)||!fo(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=Jt(),this.projectionDelta=Jt(),this.projectionDeltaWithTransform=Jt()}setAnimationOrigin(i,a=!1){const l=this.snapshot,u=l?l.latestValues:{},d={...this.latestValues},h=Jt();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=ge(),p=l?l.source:void 0,w=this.layout?this.layout.source:void 0,b=p!==w,j=this.getStack(),y=!j||j.members.length<=1,k=!!(b&&!y&&this.options.crossfade===!0&&!this.path.some(of));this.animationProgress=0;let v;this.mixTargetDelta=E=>{const N=E/1e3;yo(h.x,i.x,N),yo(h.y,i.y,N),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Nn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),rf(this.relativeTarget,this.relativeTargetOrigin,m,N),v&&_h(this.relativeTarget,v)&&(this.isProjectionDirty=!1),v||(v=ge()),Le(v,this.relativeTarget)),b&&(this.animationValues=d,$h(d,u,this.latestValues,N,k,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=N},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(wt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=de.update(()=>{fs.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=en(0)),this.currentAnimation=Nh(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(qh),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&&al(this.options.animationType,this.layout.layoutBox,u.layoutBox)){l=this.target||ge();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}Le(a,l),Ht(a,d),Dn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new Xh),this.sharedNodes.get(i).add(a);const u=a.options.initialPromotionConfig;a.promote({transition:u?u.transition:void 0,preserveFollowOpacity:u&&u.shouldPreserveFollowOpacity?u.shouldPreserveFollowOpacity(a):void 0})}isLead(){const i=this.getStack();return i?i.lead===this:!0}getLead(){const{layoutId:i}=this.options;return i?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:i}=this.options;return i?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:i}=this.options;if(i)return this.root.sharedNodes.get(i)}promote({needsReset:i,transition:a,preserveFollowOpacity: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&&zs("z",i,u,this.animationValues);for(let d=0;d<Bs.length;d++)zs(`rotate${Bs[d]}`,i,u,this.animationValues),zs(`skew${Bs[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=ds(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=ds(a?.pointerEvents)||""),this.hasProjected&&!Nt(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=Wh(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 w in Fn){if(d[w]===void 0)continue;const{correct:b,applyTo:j,isCSSVariable:y}=Fn[w],k=h==="none"?d[w]:b(d[w],u);if(j){const v=j.length;for(let E=0;E<v;E++)i[j[E]]=k}else y?this.options.visualElement.renderState.vars[w]=k:i[w]=k}this.options.layoutId&&(i.pointerEvents=u===this?ds(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(mo),this.root.sharedNodes.clear()}}}function Gh(e){e.updateLayout()}function Yh(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=Ae(h);h.min=n[d].min,h.max=h.min+m}):al(r,t.layoutBox,n)&&Fe(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=Jt();Dn(i,n,t.layoutBox);const a=Jt();o?Dn(a,e.applyTransform(s,!0),t.measuredBox):Dn(a,n,t.layoutBox);const l=!sl(i);let u=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:m}=d;if(h&&m){const p=ge();Nn(p,t.layoutBox,h.layoutBox);const w=ge();Nn(w,n,m.layoutBox),rl(p,w)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=w,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:l,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function Hh(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 Jh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Zh(e){e.clearSnapshot()}function mo(e){e.clearMeasurements()}function po(e){e.isLayoutDirty=!1}function Qh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function go(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function ef(e){e.resolveTargetDelta()}function tf(e){e.calcProjection()}function nf(e){e.resetSkewAndRotation()}function sf(e){e.removeLeadSnapshot()}function yo(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 xo(e,t,n,s){e.min=fe(t.min,n.min,s),e.max=fe(t.max,n.max,s)}function rf(e,t,n,s){xo(e.x,t.x,n.x,s),xo(e.y,t.y,n.y,s)}function of(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const af={duration:.45,ease:[.4,0,.1,1]},bo=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),vo=bo("applewebkit/")&&!bo("chrome/")?Math.round:ze;function wo(e){e.min=vo(e.min),e.max=vo(e.max)}function lf(e){wo(e.x),wo(e.y)}function al(e,t,n){return e==="position"||e==="preserve-aspect"&&!fh(ho(t),ho(n),.2)}function cf(e){return e!==e.root&&e.scroll?.wasRoot}const uf=ol({attachResizeListener:(e,t)=>Bn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Us={current:void 0},ll=ol({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Us.current){const e=new uf({});e.mount(window),e.setOptions({layoutScroll:!0}),Us.current=e}return Us.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),df={pan:{Feature:kh},drag:{Feature:Ah,ProjectionNode:ll,MeasureLayout:el}};function To(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,Xn(t)))}class hf extends St{mount(){const{current:t}=this.node;t&&(this.unmount=Ru(t,(n,s)=>(To(this.node,s,"Start"),r=>To(this.node,r,"End"))))}unmount(){}}class ff extends St{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=zn(Bn(this.node.current,"focus",()=>this.onFocus()),Bn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function So(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,Xn(t)))}class mf extends St{mount(){const{current:t}=this.node;t&&(this.unmount=$u(t,(n,s)=>(So(this.node,s,"Start"),(r,{success:o})=>So(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const mr=new WeakMap,_s=new WeakMap,pf=e=>{const t=mr.get(e.target);t&&t(e)},gf=e=>{e.forEach(pf)};function yf({root:e,...t}){const n=e||document;_s.has(n)||_s.set(n,{});const s=_s.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(gf,{root:e,...t})),s[r]}function xf(e,t,n){const s=yf(t);return mr.set(e,n),s.observe(e),()=>{mr.delete(e),s.unobserve(e)}}const bf={some:0,all:1};class vf extends St{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:bf[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 xf(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(wf(t,n))&&this.startObserver()}unmount(){}}function wf({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const cl={inView:{Feature:vf},tap:{Feature:mf},focus:{Feature:ff},hover:{Feature:hf}},Tf={layout:{ProjectionNode:ll,MeasureLayout:el}},Sf={...Ga,...cl,...df,...Tf},jf=Cd(Sf,Ua),Cf={renderer:Ua,...Ga,...cl};function Zr(e,t){return hs(e,t)}const Pf=Zr("button"),ls=Zr("div"),Af=Zr("p"),Qe=Symbol.for("@arcteninc/core:originalName");function kf(e,t){return e[Qe]=t,e}function Mf(e,t,n,s){if(typeof e!="function")return null;const r=e[Qe];if(r){const a=t[r];if(a&&!n.has(a.name))return{fn:e,meta:a}}const o=e.name;let i;if(o&&(i=t[o],i&&!n.has(i.name)))return e[Qe]=i.name,{fn:e,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=t[a],i))return e[Qe]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(l=>!n.has(l.name)),i)return e[Qe]=i.name,{fn:e,meta:i};return null}function Qr(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,12 +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
-
19
- Note: If you're loading tools from the dashboard (no tools prop), toolMetadata is not required.
20
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=Mf(o,n,r,s);if(!i){const a=o.name,u=o[Qe]||a||"unnamed";return typeof process<"u"&&(process.env.NODE_ENV==="development"||process.env.NODE_ENV!=="production")&&typeof console<"u"&&console.warn&&console.warn(`⚠️ [@arcteninc/core] No metadata found for tool "${u}". This tool will be excluded.
21
- To fix: Run "arcten-extract-types ." and ensure "${u}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}function Ef({toolName: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(ne.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(ne.X,{className:"h-3 w-3"})})]})]})})}function Nf({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(ne.ChevronDown,{className:"h-3 w-3"}):c.jsx(ne.ChevronRight,{className:"h-3 w-3"})}),n?c.jsx(ne.X,{className:"h-3 w-3"}):s?c.jsx(ne.Zap,{className:"h-3 w-3"}):c.jsx(ne.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 Df({...e}){return c.jsx(gr.Root,{"data-slot":"collapsible",...e})}function Rf({...e}){return c.jsx(gr.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function Vf({...e}){return c.jsx(gr.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const If=f.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),ei=f.memo(({className:e,...t})=>typeof window>"u"?null:c.jsx(f.Suspense,{fallback:null,children:c.jsx(If,{className:re("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);ei.displayName="Response";const Of=Object.freeze(Object.defineProperty({__proto__:null,Response:ei},Symbol.toStringTag,{value:"Module"})),$f=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=jf.create(t),i=f.useMemo(()=>(e?.length??0)*r,[e,r]);return c.jsx(o,{animate:{backgroundPosition:"0% center"},className:re("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})},Lf=f.memo($f),ul=f.createContext(null),Ff=()=>{const e=f.useContext(ul);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},Bf=1e3,zf=1e3,dl=f.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,u]=oi.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,h]=oi.useControllableState({prop:o,defaultProp:0}),[m,p]=f.useState(!1),[w,b]=f.useState(null);f.useEffect(()=>{t?w===null&&b(Date.now()):w!==null&&(h(Math.ceil((Date.now()-w)/zf)),b(null))},[t,w,h]),f.useEffect(()=>{if(s&&!t&&l&&!m){const y=setTimeout(()=>{u(!1),p(!0)},Bf);return()=>clearTimeout(y)}},[t,l,s,u,m]);const j=y=>{u(y)};return c.jsx(ul.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:u,duration:d},children:c.jsx(Df,{className:re("not-prose mb-4",e),onOpenChange:j,open:l,...a,children:i})})}),Uf=(e,t)=>e||t===0?c.jsx(Lf,{duration:1,children:"Thinking..."}):t===void 0?c.jsx("p",{children:"Thought for a few seconds"}):c.jsxs("p",{children:["Thought for ",t," seconds"]}),hl=f.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Ff();return c.jsx(Rf,{className:re("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(ne.BrainIcon,{className:"size-4"}),Uf(s,o),c.jsx(ne.ChevronDownIcon,{className:re("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),fl=f.memo(({className:e,children:t,...n})=>c.jsx(Vf,{className:re("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(ei,{className:"grid gap-2",children:t})}));dl.displayName="Reasoning";hl.displayName="ReasoningTrigger";fl.displayName="ReasoningContent";function jo(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function _f({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=jo(s.domain);return c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsxs("button",{className:re("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(bt,{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:re("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:jo(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 Xf({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 j=u.current;let y,k=!1;const v=new WeakSet,E=()=>{if(!u.current||k)return;k=!0;const $=u.current,L=/\[(\d+)\]/g,N=document.createTreeWalker($,NodeFilter.SHOW_TEXT,null),z=[];let A;for(;A=N.nextNode();)if(A.nodeType===Node.TEXT_NODE&&!v.has(A)){const I=A,F=I.textContent||"";let K=I.parentElement,Y=!1;for(;K&&K!==$;){if(K.tagName==="A"||K.tagName==="CODE"||K.tagName==="PRE"){Y=!0;break}K=K.parentElement}if(!Y){const X=Array.from(F.matchAll(L)).filter(oe=>{if(!oe[1])return!1;const we=parseInt(oe[1],10);return n.has(we)});X.length>0&&z.push({node:I,matches:X})}}if(z.length===0){k=!1;return}const M=[];z.forEach(({node:I,matches:F})=>{v.add(I);const K=I.textContent||"",Y=document.createDocumentFragment();let le=0;F.forEach(X=>{if(!X[1])return;X.index!==void 0&&X.index>le&&Y.appendChild(document.createTextNode(K.slice(le,X.index)));const oe=document.createElement("span");oe.className="inline-flex items-center citation-button-container";const we=parseInt(X[1],10);oe.setAttribute("data-citation",X[1]),Y.appendChild(oe),M.push({element:oe,citationNum:we}),le=(X.index||0)+X[0].length}),le<K.length&&Y.appendChild(document.createTextNode(K.slice(le))),I.parentNode&&I.parentNode.replaceChild(Y,I)}),M.length>0&&h(I=>{const F=new Set(I.map(le=>le.element)),K=I.filter(le=>le.element.isConnected),Y=M.filter(le=>!F.has(le.element));return[...K,...Y]}),k=!1},D=new MutationObserver(()=>{clearTimeout(y),y=setTimeout(E,100)});return D.observe(j,{childList:!0,subtree:!0,characterData:!0}),y=setTimeout(E,200),()=>{D.disconnect(),clearTimeout(y)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(j){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(j)}&sz=16`}function w(j){try{return new URL(j).hostname.replace(/^www\./,"")}catch{return j}}const b=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((j,y)=>{const k=j.title||j.baseUrl,v=w(j.url),E=p(v);return c.jsxs("a",{href:j.url,target:"_blank",rel:"noopener noreferrer",className:re("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:E,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:D=>{const $=D.target;$.style.display="none"}}),c.jsx("span",{className:"leading-none",children:k})]},`group-${y}`)}):Array.from(n.entries()).sort(([j],[y])=>j-y).map(([j,y])=>{const k=w(y),v=p(k);return c.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:re("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:v,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:E=>{const D=E.target;D.style.display="none"}}),c.jsx("span",{className:"leading-none",children:y})]},j)})})]}):null;return c.jsxs("div",{className:i,children:[c.jsx("div",{ref:u,children:c.jsx(o,{children:e})}),a&&d.filter(({element:j})=>j.isConnected).map(({element:j,citationNum:y},k)=>{if(!t.find(D=>D.number===y))return null;const E=Array.from(new Map(t.map(D=>{const $=D.url.replace(/\/+$/,""),L=s?.find(N=>N.url.replace(/\/+$/,"")===$);return[$,{number:D.number,url:D.url,domain:w(D.url),title:L?.title}]})).values());return Fl.createPortal(c.jsx(_f,{sources:E,citationNumber:y},`citation-${y}-${j}`),j,`citation-${y}-${k}`)}),b]})}function an({...e}){return c.jsx($t.Root,{"data-slot":"dialog",...e})}function qf({...e}){return c.jsx($t.Portal,{"data-slot":"dialog-portal",...e})}function Wf({className:e,...t}){return c.jsx($t.Overlay,{"data-slot":"dialog-overlay",className:re("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 ln({className:e,children:t,showCloseButton:n=!0,...s}){return c.jsxs(qf,{"data-slot":"dialog-portal",children:[c.jsx(Wf,{}),c.jsxs($t.Content,{"data-slot":"dialog-content",className:re("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($t.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[c.jsx(ne.XIcon,{}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function cn({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-header",className:re("flex flex-col gap-2 text-center sm:text-left",e),...t})}function un({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-footer",className:re("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function dn({className:e,...t}){return c.jsx($t.Title,{"data-slot":"dialog-title",className:re("text-lg leading-none font-semibold",e),...t})}function hn({className:e,...t}){return c.jsx($t.Description,{"data-slot":"dialog-description",className:re("text-muted-foreground text-sm",e),...t})}function fn({className:e,type:t,...n}){return c.jsx("input",{type:t,"data-slot":"input",className:re("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 Kf({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(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:h,children:[c.jsxs(cn,{children:[c.jsx(dn,{children:t}),c.jsx(hn,{children:n})]}),c.jsx("div",{className:"py-4",children:c.jsxs("div",{className:"relative",children:[c.jsx(fn,{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(ne.EyeOff,{className:"h-4 w-4"}):c.jsx(ne.Eye,{className:"h-4 w-4"})})]})}),c.jsxs(un,{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 Gf({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=b=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b),m=b=>{i(b),b.trim()?l(h(b)):l(!0)},p=async b=>{if(b.preventDefault(),!o.trim()||!h(o)){l(!1);return}d(!0);try{r(o)}finally{d(!1)}},w=()=>{i(""),l(!0),r(null)};return c.jsx(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:p,children:[c.jsxs(cn,{children:[c.jsxs(dn,{className:"flex items-center gap-2",children:[c.jsx(ne.Mail,{className:"h-5 w-5"}),t]}),c.jsx(hn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(fn,{type:"email",value:o,onChange:b=>m(b.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(un,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:w,disabled:u,children:"Cancel"}),c.jsx(Ce,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Yf({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=j=>{const y=j.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=j=>j.replace(/\D/g,"").length===10,p=j=>{const y=h(j);i(y),y.trim()?l(m(y)):l(!0)},w=async j=>{if(j.preventDefault(),!o.trim()||!m(o)){l(!1);return}d(!0);try{const y=o.replace(/\D/g,"");r(y)}finally{d(!1)}},b=()=>{i(""),l(!0),r(null)};return c.jsx(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:w,children:[c.jsxs(cn,{children:[c.jsxs(dn,{className:"flex items-center gap-2",children:[c.jsx(ne.Phone,{className:"h-5 w-5"}),t]}),c.jsx(hn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(fn,{type:"tel",value:o,onChange:j=>p(j.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(un,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:b,disabled:u,children:"Cancel"}),c.jsx(Ce,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Hf({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 w=p.replace(/\D/g,"");a(w.slice(0,r))},h=async p=>{if(p.preventDefault(),i.length===r){u(!0);try{o(i)}finally{u(!1)}}},m=()=>{a(""),o(null)};return c.jsx(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:h,children:[c.jsxs(cn,{children:[c.jsxs(dn,{className:"flex items-center gap-2",children:[c.jsx(ne.Shield,{className:"h-5 w-5"}),t]}),c.jsx(hn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(fn,{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(un,{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 Xs({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(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:d,children:[c.jsxs(cn,{children:[c.jsxs(dn,{className:"flex items-center gap-2",children:[c.jsx(ne.Lock,{className:"h-5 w-5"}),t]}),c.jsx(hn,{children:n})]}),c.jsx("div",{className:"py-4",children:c.jsx(fn,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:l})}),c.jsxs(un,{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 Jf({isOpen:e,title:t,description:n,fields:s,onComplete:r,submitText:o="Submit",cancelText:i="Cancel"}){const[a,l]=f.useState(()=>{const A={};return s.forEach(M=>{A[M.name]=M.value||""}),A}),[u,d]=f.useState({}),[h,m]=f.useState({}),[p,w]=f.useState(!1),b=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A)?null:"Please enter a valid email address",j=A=>A.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",y=(A,M=4)=>A.length===M?null:`PIN must be ${M} digits`,k=A=>{const M=A.replace(/\D/g,"");return M.length<=3?M:M.length<=6?`(${M.slice(0,3)}) ${M.slice(3)}`:`(${M.slice(0,3)}) ${M.slice(3,6)}-${M.slice(6,10)}`},v=(A,M,I)=>{let F=M,K=null;switch(I.type){case"phone":F=k(M),F.trim()&&(K=j(F));break;case"email":M.trim()&&(K=b(M));break;case"pin":F=M.replace(/\D/g,"").slice(0,6),F.trim()&&(K=y(F));break}!K&&I.validation&&F.trim()&&(K=I.validation(F)),l(Y=>({...Y,[A]:F})),d(Y=>({...Y,[A]:K||""}))},E=()=>{const A={};let M=!0;return s.forEach(I=>{const F=a[I.name]||"";let K=null;if(I.required&&!F.trim())K=`${I.label} is required`;else if(F.trim()){switch(I.type){case"email":K=b(F);break;case"phone":K=j(F);break;case"pin":K=y(F);break}!K&&I.validation&&(K=I.validation(F))}K&&(A[I.name]=K,M=!1)}),d(A),M},D=async A=>{if(A.preventDefault(),!!E()){w(!0);try{const M={};s.forEach(I=>{const F=a[I.name]?.trim();F&&(I.type==="phone"?M[I.name]=F.replace(/\D/g,""):M[I.name]=F)}),r(M)}finally{w(!1)}}},$=()=>{l({}),d({}),m({}),r(null)},L=A=>{m(M=>({...M,[A]:!M[A]}))},N=A=>{switch(A.type){case"password":return h[A.name]?"text":"password";case"email":return"email";case"phone":return"tel";case"pin":case"ssn":return"password";default:return"text"}},z=A=>{if(A.placeholder)return A.placeholder;switch(A.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 ${A.label.toLowerCase()}...`}};return c.jsx(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,className:"max-w-md",children:c.jsxs("form",{onSubmit:D,children:[c.jsxs(cn,{children:[c.jsx(dn,{children:t}),n&&c.jsx(hn,{children:n})]}),c.jsx("div",{className:"py-4 space-y-4",children:s.map(A=>c.jsxs("div",{children:[c.jsxs("label",{className:"block text-sm font-medium mb-1",children:[A.label,A.required&&c.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),c.jsxs("div",{className:"relative",children:[c.jsx(fn,{type:N(A),value:a[A.name]||"",onChange:M=>v(A.name,M.target.value,A),placeholder:z(A),className:u[A.name]?"border-red-500":"",disabled:p,autoFocus:A===s[0],maxLength:A.type==="pin"?6:A.type==="phone"?14:void 0}),A.type==="password"&&c.jsx("button",{type:"button",onClick:()=>L(A.name),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:p,children:h[A.name]?c.jsx(ne.EyeOff,{className:"h-4 w-4"}):c.jsx(ne.Eye,{className:"h-4 w-4"})})]}),u[A.name]&&c.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[c.jsx(ne.AlertCircle,{className:"h-3 w-3"}),u[A.name]]})]},A.name))}),c.jsxs(un,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:$,disabled:p,children:i}),c.jsx(Ce,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const ml=f.createContext(void 0);function pl(){const e=f.useContext(ml);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function gl({children:e}){const[t,n]=f.useState(null),[s,r]=f.useState(null),o=f.useRef(null),i=f.useRef(null),a=f.useCallback(p=>new Promise(w=>{n(p),o.current=w}),[]),l=f.useCallback(p=>new Promise(w=>{r(p),i.current=w}),[]),u=f.useCallback(p=>{o.current&&(o.current(p),o.current=null),n(null)},[]),d=f.useCallback(p=>{i.current&&(i.current(p),i.current=null),r(null)},[]),h=()=>{if(s){const w=s.fields.map(b=>({name:b.name,type:b.type==="text"?"text":b.type==="password"?"password":b.type==="email"?"email":b.type==="phone"?"phone":b.type==="pin"?"pin":b.type==="ssn"?"ssn":b.type==="creditCard"?"creditCard":"text",label:b.label,placeholder:b.placeholder,required:b.required!==!1,value:b.value}));return c.jsx(Jf,{isOpen:!0,title:s.title,description:s.description,fields:w,onComplete:d})}if(!t)return null;const p={isOpen:!0,title:t.title,description:t.description,placeholder:t.placeholder,onComplete:u};switch(t.type){case"password":return c.jsx(Kf,{...p});case"email":return c.jsx(Gf,{...p});case"phone":return c.jsx(Yf,{...p});case"pin":return c.jsx(Hf,{...p});case"ssn":return c.jsx(Xs,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return c.jsx(Xs,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return c.jsx(Xs,{...p})}},m=f.useMemo(()=>({showSecureModal:a,showSecureForm:l}),[a,l]);return c.jsxs(ml.Provider,{value:m,children:[e,h()]})}function Zf(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 Qf(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 Co(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 N=s[1],z=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let A;for(;(A=z.exec(N))!==null;)if(A[1]&&A[2]){const M=parseInt(A[1],10),I=A[2].replace(/[.,;:!?]+$/,""),F=I.replace(/\/+$/,"");if(a.has(F)||a.set(F,I),i.has(F)||i.set(F,[]),i.get(F).push(M),!l.has(F))l.set(F,M);else{const K=l.get(F);M<K&&l.set(F,M)}}for(const[M,I]of i.entries()){const F=l.get(M);for(const K of I)K!==F&&u.set(K,F)}for(const[M,I]of l.entries()){const F=a.get(M)||M;r.set(I,F),o.push({number:I,url:F})}}let d,h=t;s&&s[0]&&(d=s[0],h=t.replace(n,""));const m=[];let p=0;const w=/```[\s\S]*?```|`[^`]+`/g;let b;for(;(b=w.exec(h))!==null;)b.index>p&&m.push({type:"text",content:h.slice(p,b.index),start:p,end:b.index}),m.push({type:"code",content:b[0],start:b.index,end:b.index+b[0].length}),p=b.index+b[0].length;p<h.length&&m.push({type:"text",content:h.slice(p),start:p,end:h.length});const j=m.map(N=>{if(N.type==="code")return N.content;let z=N.content;return z=z.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(M,I,F)=>{const K=parseInt(I,10),Y=F.replace(/\/+$/,""),le=u.get(K)||K;return l.has(Y)||(l.set(Y,le),r.has(le)||(r.set(le,F),o.push({number:le,url:F}))),`[${le}]`}),z=z.replace(/\[(\d+)\]/g,(M,I)=>{const F=parseInt(I,10);return`[${u.get(F)||F}]`}),z}),y=[];for(const[N,z]of l.entries()){const A=a.get(N)||N,{baseUrl:M,anchor:I}=Zf(A),F=Qf(A);y.push({url:A,baseUrl:M,numbers:[z],anchor:I,title:F})}y.sort((N,z)=>(N.numbers[0]||0)-(z.numbers[0]||0));const k=new Map;let v=1;for(const N of y){const z=N.numbers[0];k.set(z,v),N.numbers=[v],v++}const E=new Map;for(const[N,z]of r.entries()){const A=k.get(N);A&&E.set(A,z)}const D=o.map(N=>{const z=k.get(N.number);return z?{number:z,url:N.url}:N}).filter(N=>k.has(N.number)),$=Array.from(k.entries()).sort((N,z)=>z[0]-N[0]);let L=j.join("");for(const[N,z]of $){const A=new RegExp(`\\[${N}\\](?!\\d)`,"g");L=L.replace(A,`[${z}]`)}return{processedText:L,citations:D.sort((N,z)=>N.number-z.number),citationMap:E,groupedCitations:y,referencesText:d}}function Rn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Rn(t)}catch{return e}if(Array.isArray(e))return e.map(Rn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Rn(s);return t}return e}function qs(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Rn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Rn(e):{}}function em({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="",agentId:w,agentName:b,tokenEndpoint:j="/api/arcten/token",apiBaseUrl:y="https://api.arcten.com",user:k,state:v,onStateChange:E,allowStateEdits:D=!0,sources:$,ragConfig:L,showCitations:N=!0,sensitiveParams:z,autoDetectSensitive:A=!1}){const{showSecureModal:M}=pl(),I=f.useMemo(()=>L!==void 0?L:$&&$.length>0?{enabled:!0,organizationId:$[0],autoExecute:!0,filters:void 0}:{enabled:!1},[$,L]),[F,K]=f.useState(null),Y=f.useRef(null),[le,X]=f.useState(null),[oe,we]=f.useState(null),Te=f.useRef(null),se=v!==void 0,[tt,ut]=f.useState({}),ke=f.useRef({});se&&v?ke.current=v:se||(ke.current=tt);const[He,Lt]=f.useState(!1),[ti,nt]=f.useState(null),st=f.useRef(!1),[Ue,mn]=f.useState(u),[_e,Ft]=f.useState(i),[Bt,qn]=f.useState(600),[pn,jt]=f.useState(!1),[ie,ce]=f.useState(!1),[Ve,Je]=f.useState(!1),[ue,gn]=f.useState({x:100,y:100}),[Wn,zt]=f.useState(!1),[yn,Ct]=f.useState({x:0,y:0}),[Ut,xn]=f.useState(!1),rt=f.useRef(null),Xe=f.useRef(null),[_t,bn]=f.useState(""),[Kn,As]=f.useState(null),[vn,Gn]=f.useState("Thinking..."),[qe,Me]=f.useState(new Set),[Xt,it]=f.useState(""),[Ne,Yn]=f.useState([]),Hn=f.useRef(new Map),dt=f.useRef(!1),wn=f.useRef(""),[Tn,Sn]=f.useState(!1),[Ie,Jn]=f.useState([]),[Oe,Pt]=f.useState(()=>typeof window<"u"?crypto.randomUUID():null),[ht,ft]=f.useState(!1),[Zn,We]=f.useState(!1),[ni,qt]=f.useState([]),Qn=f.useCallback(async(g,P=3)=>{if(!Oe||!Y.current)return;const R=async()=>{const O=`${y.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,U=await fetch(O,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Oe,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 B=0;B<P;B++)try{await R(),nt(null);return}catch(O){if(B===P-1){const ee=O instanceof Error?O:new Error(String(O));throw nt(ee),console.error("Failed to sync state to Convex after retries:",O),ee}await new Promise(ee=>setTimeout(ee,Math.pow(2,B)*100))}},[Oe,y,Y]),mt=f.useMemo(()=>function(){return ke.current},[]),At=f.useMemo(()=>async function(P){const R={...ke.current,...P};ke.current=R,se||ut(R),E&&E(R);try{await Qn(P)}catch(B){throw B}},[Qn,E,se]);f.useEffect(()=>{se&&v&&(ke.current=v)},[se,v]);const ot=f.useMemo(()=>I?.enabled?async function(P,R=20,B){if($&&$.length>1){const ee=$.map(H=>fetch(`${y}/search`,{method:"POST",headers:{"Content-Type":"application/json",...Y.current?{Authorization:`Bearer ${Y.current}`}:{}},body:JSON.stringify({q:P,k:Math.min(R,100),organizationId:H,...Object.keys(U).length>0?{filters:U}:{}})}).then(W=>W.ok?W.json():null)),Z=await Promise.all(ee),te=[];for(const H of Z)H?.candidates&&te.push(...H.candidates);te.sort((H,W)=>{const be=H.scores?.rerank||H.scores?.dense||0;return(W.scores?.rerank||W.scores?.dense||0)-be});const _=te.slice(0,R).map((H,W)=>{const be=H.citation||H.url;return{rank:W+1,doc_id:H.doc_id,block_id:H.block_id,url:H.url,citation:be,title:H.title||"Untitled",snippet:H.snippet,score:H.scores?.rerank||H.scores?.dense||0,metadata:{site:H.metadata?.site,lang:H.metadata?.lang,contentType:H.metadata?.content_type}}});return{success:!0,query:P,total:te.length,results:_,summary:`Found ${te.length} relevant results across ${$.length} source(s) for "${P}". Top result: ${_[0]?.title||"N/A"}`}}const O=I.organizationId&&I.organizationId!=="default"?I.organizationId:void 0,U={...I.filters,...B};try{const ee={q:P,k:Math.min(R,100)};O&&(ee.organizationId=O),Object.keys(U).length>0&&(ee.filters=U);const Z={"Content-Type":"application/json"};Y.current&&(Z.Authorization=`Bearer ${Y.current}`);const te=await fetch(`${y}/search`,{method:"POST",headers:Z,body:JSON.stringify(ee)});if(!te.ok){const W=await te.text();return{success:!1,error:`Search failed: ${te.status} ${W}`}}const _=await te.json(),H=_.candidates.map((W,be)=>{const me=W.citation||W.url;return{rank:be+1,doc_id:W.doc_id,block_id:W.block_id,url:W.url,citation:me,title:W.title||"Untitled",snippet:W.snippet,score:W.scores?.rerank||W.scores?.dense||0,metadata:{site:W.metadata?.site,lang:W.metadata?.lang,contentType:W.metadata?.content_type}}});return{success:!0,query:_.query,total:_.total,results:H,summary:`Found ${_.total} relevant results for "${P}". Top result: ${H[0]?.title||"N/A"}`}}catch(ee){return{success:!1,error:ee instanceof Error?ee.message:"Unknown error occurred"}}}:null,[L,y,Y]),x=f.useMemo(()=>I?.enabled?async function(P,R){const B=I.organizationId&&I.organizationId!=="default"?I.organizationId:$&&$.length>0?$[0]:void 0;try{const O={"Content-Type":"application/json"};Y.current&&(O.Authorization=`Bearer ${Y.current}`);const U=await fetch(`${y}/fetch`,{method:"POST",headers:O,body:JSON.stringify({doc_id:P,block_ids:R,...B?{organizationId:B}:{}})});if(!U.ok){const Z=await U.text();return{success:!1,error:`Fetch failed: ${U.status} ${Z}`}}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(O){return{success:!1,error:O instanceof Error?O.message:"Unknown error occurred"}}}:null,[L,y,Y]),T=f.useMemo(()=>{const g=[...d,...h,mt];return(!se||D)&&g.push(At),I?.enabled&&(ot&&g.push(ot),x&&g.push(x)),g},[d,h,mt,At,ot,x,se,D,I]),S=f.useMemo(()=>Qr(T,m),[T,m]),C=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:[]}}];(!se||D)&&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 I?.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"]}}),[...S,...g,...P]},[S,se,D,I]),V=f.useMemo(()=>new Set(C.map(g=>g.name)),[C]),q=f.useMemo(()=>C.filter(g=>g.name==="getState"?!0:g.name==="setState"?!se||D:V.has(g.name)),[C,V,se,D]),J=f.useMemo(()=>{const g=new Map,P=new Map(S.map(R=>[R.name,R]));return g.set("getState",mt),(!se||D)&&g.set("setState",At),I?.enabled&&(ot&&g.set("searchDocs",ot),x&&g.set("fetchDocContent",x)),T.forEach(R=>{if(R===mt||R===At||R===ot||R===x)return;const B=R[Qe];if(B){const U=P.get(B);if(U){g.set(U.name,R);return}}const O=C.find(U=>U.name===R.name);O&&g.set(O.name,R)}),g},[T,C,mt,At,ot,x,se,D,I]),pe=f.useMemo(()=>{const g=new Set;g.add("getState"),g.add("setState"),I?.enabled&&I.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent"));const P=new Map(C.map(R=>[R.name,R]));return h.forEach(R=>{const B=R[Qe];if(B&&P.has(B))g.add(B);else{const O=C.find(U=>U.name===R.name);O&&g.add(O.name)}}),g},[h,C,I]),ye=["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&&mn(JSON.parse(g));const P=localStorage.getItem("arcten-sidebar-width");P&&Ft(parseInt(P));const R=localStorage.getItem("arcten-sidebar-height");R&&qn(parseInt(R));const B=localStorage.getItem("arcten-sidebar-detached");B&&ce(JSON.parse(B));const O=localStorage.getItem("arcten-sidebar-position");if(O){const ee=JSON.parse(O),Z=50,te=Math.max(Z-i,Math.min(ee.x,window.innerWidth-Z)),_=Math.max(0,Math.min(ee.y,window.innerHeight-Z));gn({x:te,y:_})}const U=localStorage.getItem("arcten-sidebar-minimized");U&&Je(JSON.parse(U)),xn(!0)}},[]);const xe=f.useMemo(()=>k,[k?.id]);f.useEffect(()=>((async()=>{try{const P=await fetch(j,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:xe})});if(!P.ok)throw new Error("Failed to fetch token");const R=await P.json();K(R.clientToken),Y.current=R.clientToken,we(R.expiresAt),X(null)}catch(P){X(P instanceof Error?P.message:"Failed to fetch token")}})(),()=>{Te.current&&clearTimeout(Te.current)}),[j,xe]),f.useEffect(()=>{if(!oe)return;Te.current&&clearTimeout(Te.current);const g=Math.floor(Date.now()/1e3),P=oe-g,B=Math.max(0,P-5);return Te.current=setTimeout(async()=>{try{const O=await fetch(j,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:xe})});if(!O.ok)throw new Error("Failed to refresh token");const U=await O.json();K(U.clientToken),Y.current=U.clientToken,we(U.expiresAt),X(null)}catch(O){console.error("Token refresh failed:",O),X(O instanceof Error?O.message:"Failed to refresh token")}},B*1e3),()=>{Te.current&&clearTimeout(Te.current)}},[oe,j,xe]),f.useEffect(()=>{(async()=>{if(T.length===0)return;const P=T.map(R=>`${R.name}:${R.toString()}`).join("|");if(P!==wn.current&&!dt.current){dt.current=!0,wn.current=P;try{const R=T.map(O=>({name:O.name,code:O.toString()})),B=await fetch(`${y}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:R})});if(B.ok){const O=await B.json();O.tools&&O.tools.forEach(U=>{Hn.current.set(U.name,U)}),Yn(O.tools)}}catch(R){console.error("Failed to fetch tool descriptions:",R)}finally{dt.current=!1}}})()},[T,y]),f.useEffect(()=>{Promise.resolve().then(()=>Of).then(g=>{As(()=>g.Response)})},[]),f.useEffect(()=>{const g=()=>{it(window.location.pathname)};g(),window.addEventListener("popstate",g);const P=setInterval(g,500);return()=>{window.removeEventListener("popstate",g),clearInterval(P)}},[]);const Q=f.useCallback(async()=>{if(!(!xe?.id||!F)){We(!0);try{const P=await(await fetch(`${y}/conversations`,{headers:{Authorization:`Bearer ${F}`}})).json();Jn(P.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{We(!1)}}},[xe?.id,F,y]);f.useEffect(()=>{xe?.id&&F&&Q()},[xe?.id,F,Q]);function ae(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 Ze(){const g=crypto.randomUUID();Pt(g),ss([]),qt([]),ft(!1);const P=se?v||{}:{};ke.current=P,se||ut(P),E&&E(P),st.current=!1}async function kt(g){if(F)try{await fetch(`${y}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${F}`}}),Jn(Ie.filter(P=>P._id!==g)),g===Oe&&Ze()}catch(P){console.error("Failed to delete conversation:",P)}}async function jn(g){Pt(g.chatId),ft(!1),We(!0);try{const P=await fetch(`${y}/conversations/${g.chatId}/messages`,{headers:{Authorization:`Bearer ${Y.current}`}});if(!P.ok)throw new Error(`Failed to fetch messages: ${P.statusText}`);const B=(await P.json()).messages||[];ss(B),qt(B)}catch(P){console.error("Failed to load conversation messages:",P);const R=g.messages||[];ss(R),qt(R)}finally{We(!1)}}const Cn=async(g,P={})=>{const R=P.headers?new Headers(P.headers):new Headers;return R.delete("user-agent"),R.delete("User-Agent"),fetch(g,{...P,headers:R})},{messages:De,sendMessage:es,status:Re,error:ts,stop:ns,addToolResult:Mt,setMessages:ss}=Po.useChat({id:Oe||void 0,transport:new gs.DefaultChatTransport({api:`${y}/chat`,fetch:Cn,headers:()=>{const g={};return Y.current&&(g.Authorization=`Bearer ${Y.current}`),g},body:()=>({tools:q.map(P=>({name:P.name,description:P.description,inputSchema:P.jsonSchema})),...w&&{agentId:w},...b&&{agentName:b},currentRoute:Xt,state:ke.current})}),sendAutomaticallyWhen:gs.lastAssistantMessageIsCompleteWithToolCalls});f.useEffect(()=>{const g=De[De.length-1];if(!g||g.role!=="assistant")return;const P=g.parts?.filter(R=>R.type?.startsWith("tool-")&&R.state==="input-available"&&typeof R.toolCallId=="string"&&R.input!==void 0)||[];for(const R of P){const B=R,O=B.type?.replace("tool-","")||"",U=B.toolCallId;if(pe.has(O)){if(qe.has(U))continue;Me(Z=>Z.has(U)?Z:new Set(Z).add(U)),(async()=>{try{const Z=J.get(O);if(!Z){console.warn(`[ArctenAgent] Tool ${O} not found in toolsMap. Available tools:`,Array.from(J.keys())),Mt({toolCallId:U,tool:O,output:`Error: Tool ${O} not found`}),Me(W=>{const be=new Set(W);return be.delete(U),be});return}const te=qs(B.input),_=q.find(W=>W.name===O);let H;if(_&&_.jsonSchema?.properties){const be=Object.keys(_.jsonSchema.properties).map(me=>te[me]);console.log(`[ArctenAgent] Executing safe tool ${O} with args:`,be),H=await Z(...be)}else if(O==="getState")H=Z();else if(O==="setState"){const W=te.updates||te;H=await Z(W)}else H=await Z(...Object.values(te));console.log(`[ArctenAgent] Tool ${O} completed, result:`,H),Mt({toolCallId:U,tool:O,output:H}),Me(W=>{const be=new Set(W);return be.delete(U),be})}catch(Z){console.error(`[ArctenAgent] Error executing safe tool ${O}:`,Z),Mt({toolCallId:U,tool:O,output:`Error: ${Z instanceof Error?Z.message:String(Z)}`}),Me(te=>{const _=new Set(te);return _.delete(U),_})}})()}}},[De,pe,J,q,Mt]),f.useEffect(()=>{if(!Oe||!Y.current)return;(async()=>{Lt(!0),nt(null);try{const R=`${y.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,B=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Oe},format:"json"})});if(!B.ok){if(B.status===404||B.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${B.status}), using empty state`);const _=se?v||{}:{};ke.current=_,se||ut(_),E&&E(_),st.current=!0,Lt(!1);return}const te=await B.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${B.status} ${te}`)}const U=(await B.json())?.value||{},ee=!st.current;let Z;ee?(Z={...se?v||{}:{},...U},st.current=!0):Z=U,ke.current=Z,se||ut(Z),E&&E(Z)}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 B=P instanceof Error?P:new Error(String(P));if(nt(B),!st.current){const O=se?v||{}:{};ke.current=O,se||ut(O),E&&E(O),st.current=!0}}finally{Lt(!1)}})()},[Oe,y,se,v,E]),f.useEffect(()=>{Ue&&Xe.current&&Xe.current.focus()},[Ue,De]);function vl(){mn(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function wl(){mn(!1),localStorage.setItem("arcten-sidebar-expanded","false")}f.useEffect(()=>{},[Ue]),f.useEffect(()=>{rt.current&&rt.current.scrollIntoView({behavior:"smooth"})},[De]),f.useEffect(()=>{function g(P){P.key==="Escape"&&(Re==="streaming"||Re==="submitted")&&(P.preventDefault(),ns())}return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Re,ns]);function Tl(){const g=crypto.randomUUID();Pt(g),ss([]),qt([]),ft(!1)}function si(g){if(g.preventDefault(),!_t.trim())return;(Re==="streaming"||Re==="submitted")&&ns();const P=ye[Math.floor(Math.random()*ye.length)]||"Thinking...";Gn(P),es({text:_t}),bn("")}function Sl(g){const P=g.target.value;bn(P)}f.useEffect(()=>{if(!pn)return;function g(R){if(ie){const B=R.clientX-ue.x,O=R.clientY-ue.y;B>=a&&B<=l&&Ft(B),O>=400&&O<=1e3&&qn(O)}else{const B=window.innerWidth-R.clientX;B>=a&&B<=l&&Ft(B)}}function P(){jt(!1),localStorage.setItem("arcten-sidebar-width",_e.toString()),localStorage.setItem("arcten-sidebar-height",Bt.toString())}return window.addEventListener("mousemove",g),window.addEventListener("mouseup",P),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",P)}},[pn,_e,Bt,ie,ue,a,l]);function jl(g){g.preventDefault(),jt(!0)}function Cl(){ce(!0),Je(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Pl(){ce(!1),Je(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function ri(){Je(!Ve),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ve))}function Al(g){ie&&(zt(!0),Ct({x:g.clientX-ue.x,y:g.clientY-ue.y}))}return f.useEffect(()=>{if(!ie)return;function g(){gn(P=>{const B=window.innerWidth-50,O=window.innerHeight-50,U=50-_e,ee=0,Z=Math.max(U,Math.min(P.x,B)),te=Math.max(ee,Math.min(P.y,O));if(Z!==P.x||te!==P.y){const _={x:Z,y:te};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(_)),_}return P})}return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[ie,_e]),f.useEffect(()=>{if(!Wn)return;function g(R){const B=R.clientX-yn.x,O=R.clientY-yn.y,U=50,ee=window.innerWidth-U,Z=window.innerHeight-U,te=U-_e,_=0,H=Math.max(te,Math.min(B,ee)),W=Math.max(_,Math.min(O,Z));gn({x:H,y:W})}function P(){zt(!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)}},[Wn,yn,ue,_e]),Ut?le?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: ",le]})}):F?c.jsx(Gu,{features:Cf,children:c.jsx(ls,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:ie?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:ie?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
19
+ To fix: Run "arcten-extract-types ." and ensure "${u}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}function Ef({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(ne.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(ne.X,{className:"h-3 w-3"})})]})]})})}function Df({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(ne.ChevronDown,{className:"h-3 w-3"}):c.jsx(ne.ChevronRight,{className:"h-3 w-3"})}),n?c.jsx(ne.X,{className:"h-3 w-3"}):s?c.jsx(ne.Zap,{className:"h-3 w-3"}):c.jsx(ne.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 Nf({...e}){return c.jsx(gr.Root,{"data-slot":"collapsible",...e})}function Rf({...e}){return c.jsx(gr.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function Vf({...e}){return c.jsx(gr.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const If=f.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),ei=f.memo(({className:e,...t})=>typeof window>"u"?null:c.jsx(f.Suspense,{fallback:null,children:c.jsx(If,{className:re("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);ei.displayName="Response";const Of=Object.freeze(Object.defineProperty({__proto__:null,Response:ei},Symbol.toStringTag,{value:"Module"})),$f=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=jf.create(t),i=f.useMemo(()=>(e?.length??0)*r,[e,r]);return c.jsx(o,{animate:{backgroundPosition:"0% center"},className:re("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})},Lf=f.memo($f),ul=f.createContext(null),Ff=()=>{const e=f.useContext(ul);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},Bf=1e3,zf=1e3,dl=f.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,u]=oi.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,h]=oi.useControllableState({prop:o,defaultProp:0}),[m,p]=f.useState(!1),[w,b]=f.useState(null);f.useEffect(()=>{t?w===null&&b(Date.now()):w!==null&&(h(Math.ceil((Date.now()-w)/zf)),b(null))},[t,w,h]),f.useEffect(()=>{if(s&&!t&&l&&!m){const y=setTimeout(()=>{u(!1),p(!0)},Bf);return()=>clearTimeout(y)}},[t,l,s,u,m]);const j=y=>{u(y)};return c.jsx(ul.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:u,duration:d},children:c.jsx(Nf,{className:re("not-prose mb-4",e),onOpenChange:j,open:l,...a,children:i})})}),Uf=(e,t)=>e||t===0?c.jsx(Lf,{duration:1,children:"Thinking..."}):t===void 0?c.jsx("p",{children:"Thought for a few seconds"}):c.jsxs("p",{children:["Thought for ",t," seconds"]}),hl=f.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Ff();return c.jsx(Rf,{className:re("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(ne.BrainIcon,{className:"size-4"}),Uf(s,o),c.jsx(ne.ChevronDownIcon,{className:re("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),fl=f.memo(({className:e,children:t,...n})=>c.jsx(Vf,{className:re("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(ei,{className:"grid gap-2",children:t})}));dl.displayName="Reasoning";hl.displayName="ReasoningTrigger";fl.displayName="ReasoningContent";function jo(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function _f({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=jo(s.domain);return c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsxs("button",{className:re("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(bt,{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:re("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:jo(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 Xf({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 j=u.current;let y,k=!1;const v=new WeakSet,E=()=>{if(!u.current||k)return;k=!0;const $=u.current,L=/\[(\d+)\]/g,D=document.createTreeWalker($,NodeFilter.SHOW_TEXT,null),z=[];let A;for(;A=D.nextNode();)if(A.nodeType===Node.TEXT_NODE&&!v.has(A)){const I=A,F=I.textContent||"";let K=I.parentElement,Y=!1;for(;K&&K!==$;){if(K.tagName==="A"||K.tagName==="CODE"||K.tagName==="PRE"){Y=!0;break}K=K.parentElement}if(!Y){const X=Array.from(F.matchAll(L)).filter(oe=>{if(!oe[1])return!1;const we=parseInt(oe[1],10);return n.has(we)});X.length>0&&z.push({node:I,matches:X})}}if(z.length===0){k=!1;return}const M=[];z.forEach(({node:I,matches:F})=>{v.add(I);const K=I.textContent||"",Y=document.createDocumentFragment();let le=0;F.forEach(X=>{if(!X[1])return;X.index!==void 0&&X.index>le&&Y.appendChild(document.createTextNode(K.slice(le,X.index)));const oe=document.createElement("span");oe.className="inline-flex items-center citation-button-container";const we=parseInt(X[1],10);oe.setAttribute("data-citation",X[1]),Y.appendChild(oe),M.push({element:oe,citationNum:we}),le=(X.index||0)+X[0].length}),le<K.length&&Y.appendChild(document.createTextNode(K.slice(le))),I.parentNode&&I.parentNode.replaceChild(Y,I)}),M.length>0&&h(I=>{const F=new Set(I.map(le=>le.element)),K=I.filter(le=>le.element.isConnected),Y=M.filter(le=>!F.has(le.element));return[...K,...Y]}),k=!1},N=new MutationObserver(()=>{clearTimeout(y),y=setTimeout(E,100)});return N.observe(j,{childList:!0,subtree:!0,characterData:!0}),y=setTimeout(E,200),()=>{N.disconnect(),clearTimeout(y)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(j){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(j)}&sz=16`}function w(j){try{return new URL(j).hostname.replace(/^www\./,"")}catch{return j}}const b=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((j,y)=>{const k=j.title||j.baseUrl,v=w(j.url),E=p(v);return c.jsxs("a",{href:j.url,target:"_blank",rel:"noopener noreferrer",className:re("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:E,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:N=>{const $=N.target;$.style.display="none"}}),c.jsx("span",{className:"leading-none",children:k})]},`group-${y}`)}):Array.from(n.entries()).sort(([j],[y])=>j-y).map(([j,y])=>{const k=w(y),v=p(k);return c.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:re("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:v,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:E=>{const N=E.target;N.style.display="none"}}),c.jsx("span",{className:"leading-none",children:y})]},j)})})]}):null;return c.jsxs("div",{className:i,children:[c.jsx("div",{ref:u,children:c.jsx(o,{children:e})}),a&&d.filter(({element:j})=>j.isConnected).map(({element:j,citationNum:y},k)=>{if(!t.find(N=>N.number===y))return null;const E=Array.from(new Map(t.map(N=>{const $=N.url.replace(/\/+$/,""),L=s?.find(D=>D.url.replace(/\/+$/,"")===$);return[$,{number:N.number,url:N.url,domain:w(N.url),title:L?.title}]})).values());return Fl.createPortal(c.jsx(_f,{sources:E,citationNumber:y},`citation-${y}-${j}`),j,`citation-${y}-${k}`)}),b]})}function an({...e}){return c.jsx($t.Root,{"data-slot":"dialog",...e})}function Wf({...e}){return c.jsx($t.Portal,{"data-slot":"dialog-portal",...e})}function qf({className:e,...t}){return c.jsx($t.Overlay,{"data-slot":"dialog-overlay",className:re("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 ln({className:e,children:t,showCloseButton:n=!0,...s}){return c.jsxs(Wf,{"data-slot":"dialog-portal",children:[c.jsx(qf,{}),c.jsxs($t.Content,{"data-slot":"dialog-content",className:re("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($t.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[c.jsx(ne.XIcon,{}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function cn({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-header",className:re("flex flex-col gap-2 text-center sm:text-left",e),...t})}function un({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-footer",className:re("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function dn({className:e,...t}){return c.jsx($t.Title,{"data-slot":"dialog-title",className:re("text-lg leading-none font-semibold",e),...t})}function hn({className:e,...t}){return c.jsx($t.Description,{"data-slot":"dialog-description",className:re("text-muted-foreground text-sm",e),...t})}function fn({className:e,type:t,...n}){return c.jsx("input",{type:t,"data-slot":"input",className:re("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 Kf({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(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:h,children:[c.jsxs(cn,{children:[c.jsx(dn,{children:t}),c.jsx(hn,{children:n})]}),c.jsx("div",{className:"py-4",children:c.jsxs("div",{className:"relative",children:[c.jsx(fn,{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(ne.EyeOff,{className:"h-4 w-4"}):c.jsx(ne.Eye,{className:"h-4 w-4"})})]})}),c.jsxs(un,{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 Gf({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=b=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b),m=b=>{i(b),b.trim()?l(h(b)):l(!0)},p=async b=>{if(b.preventDefault(),!o.trim()||!h(o)){l(!1);return}d(!0);try{r(o)}finally{d(!1)}},w=()=>{i(""),l(!0),r(null)};return c.jsx(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:p,children:[c.jsxs(cn,{children:[c.jsxs(dn,{className:"flex items-center gap-2",children:[c.jsx(ne.Mail,{className:"h-5 w-5"}),t]}),c.jsx(hn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(fn,{type:"email",value:o,onChange:b=>m(b.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(un,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:w,disabled:u,children:"Cancel"}),c.jsx(Ce,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Yf({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=j=>{const y=j.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=j=>j.replace(/\D/g,"").length===10,p=j=>{const y=h(j);i(y),y.trim()?l(m(y)):l(!0)},w=async j=>{if(j.preventDefault(),!o.trim()||!m(o)){l(!1);return}d(!0);try{const y=o.replace(/\D/g,"");r(y)}finally{d(!1)}},b=()=>{i(""),l(!0),r(null)};return c.jsx(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:w,children:[c.jsxs(cn,{children:[c.jsxs(dn,{className:"flex items-center gap-2",children:[c.jsx(ne.Phone,{className:"h-5 w-5"}),t]}),c.jsx(hn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(fn,{type:"tel",value:o,onChange:j=>p(j.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(un,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:b,disabled:u,children:"Cancel"}),c.jsx(Ce,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Hf({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 w=p.replace(/\D/g,"");a(w.slice(0,r))},h=async p=>{if(p.preventDefault(),i.length===r){u(!0);try{o(i)}finally{u(!1)}}},m=()=>{a(""),o(null)};return c.jsx(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:h,children:[c.jsxs(cn,{children:[c.jsxs(dn,{className:"flex items-center gap-2",children:[c.jsx(ne.Shield,{className:"h-5 w-5"}),t]}),c.jsx(hn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(fn,{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(un,{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 Xs({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(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:d,children:[c.jsxs(cn,{children:[c.jsxs(dn,{className:"flex items-center gap-2",children:[c.jsx(ne.Lock,{className:"h-5 w-5"}),t]}),c.jsx(hn,{children:n})]}),c.jsx("div",{className:"py-4",children:c.jsx(fn,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:l})}),c.jsxs(un,{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 Jf({isOpen:e,title:t,description:n,fields:s,onComplete:r,submitText:o="Submit",cancelText:i="Cancel"}){const[a,l]=f.useState(()=>{const A={};return s.forEach(M=>{A[M.name]=M.value||""}),A}),[u,d]=f.useState({}),[h,m]=f.useState({}),[p,w]=f.useState(!1),b=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A)?null:"Please enter a valid email address",j=A=>A.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",y=(A,M=4)=>A.length===M?null:`PIN must be ${M} digits`,k=A=>{const M=A.replace(/\D/g,"");return M.length<=3?M:M.length<=6?`(${M.slice(0,3)}) ${M.slice(3)}`:`(${M.slice(0,3)}) ${M.slice(3,6)}-${M.slice(6,10)}`},v=(A,M,I)=>{let F=M,K=null;switch(I.type){case"phone":F=k(M),F.trim()&&(K=j(F));break;case"email":M.trim()&&(K=b(M));break;case"pin":F=M.replace(/\D/g,"").slice(0,6),F.trim()&&(K=y(F));break}!K&&I.validation&&F.trim()&&(K=I.validation(F)),l(Y=>({...Y,[A]:F})),d(Y=>({...Y,[A]:K||""}))},E=()=>{const A={};let M=!0;return s.forEach(I=>{const F=a[I.name]||"";let K=null;if(I.required&&!F.trim())K=`${I.label} is required`;else if(F.trim()){switch(I.type){case"email":K=b(F);break;case"phone":K=j(F);break;case"pin":K=y(F);break}!K&&I.validation&&(K=I.validation(F))}K&&(A[I.name]=K,M=!1)}),d(A),M},N=async A=>{if(A.preventDefault(),!!E()){w(!0);try{const M={};s.forEach(I=>{const F=a[I.name]?.trim();F&&(I.type==="phone"?M[I.name]=F.replace(/\D/g,""):M[I.name]=F)}),r(M)}finally{w(!1)}}},$=()=>{l({}),d({}),m({}),r(null)},L=A=>{m(M=>({...M,[A]:!M[A]}))},D=A=>{switch(A.type){case"password":return h[A.name]?"text":"password";case"email":return"email";case"phone":return"tel";case"pin":case"ssn":return"password";default:return"text"}},z=A=>{if(A.placeholder)return A.placeholder;switch(A.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 ${A.label.toLowerCase()}...`}};return c.jsx(an,{open:e,children:c.jsx(ln,{showCloseButton:!1,className:"max-w-md",children:c.jsxs("form",{onSubmit:N,children:[c.jsxs(cn,{children:[c.jsx(dn,{children:t}),n&&c.jsx(hn,{children:n})]}),c.jsx("div",{className:"py-4 space-y-4",children:s.map(A=>c.jsxs("div",{children:[c.jsxs("label",{className:"block text-sm font-medium mb-1",children:[A.label,A.required&&c.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),c.jsxs("div",{className:"relative",children:[c.jsx(fn,{type:D(A),value:a[A.name]||"",onChange:M=>v(A.name,M.target.value,A),placeholder:z(A),className:u[A.name]?"border-red-500":"",disabled:p,autoFocus:A===s[0],maxLength:A.type==="pin"?6:A.type==="phone"?14:void 0}),A.type==="password"&&c.jsx("button",{type:"button",onClick:()=>L(A.name),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:p,children:h[A.name]?c.jsx(ne.EyeOff,{className:"h-4 w-4"}):c.jsx(ne.Eye,{className:"h-4 w-4"})})]}),u[A.name]&&c.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[c.jsx(ne.AlertCircle,{className:"h-3 w-3"}),u[A.name]]})]},A.name))}),c.jsxs(un,{children:[c.jsx(Ce,{type:"button",variant:"ghost",onClick:$,disabled:p,children:i}),c.jsx(Ce,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const ml=f.createContext(void 0);function pl(){const e=f.useContext(ml);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function gl({children:e}){const[t,n]=f.useState(null),[s,r]=f.useState(null),o=f.useRef(null),i=f.useRef(null),a=f.useCallback(p=>new Promise(w=>{n(p),o.current=w}),[]),l=f.useCallback(p=>new Promise(w=>{r(p),i.current=w}),[]),u=f.useCallback(p=>{o.current&&(o.current(p),o.current=null),n(null)},[]),d=f.useCallback(p=>{i.current&&(i.current(p),i.current=null),r(null)},[]),h=()=>{if(s){const w=s.fields.map(b=>({name:b.name,type:b.type==="text"?"text":b.type==="password"?"password":b.type==="email"?"email":b.type==="phone"?"phone":b.type==="pin"?"pin":b.type==="ssn"?"ssn":b.type==="creditCard"?"creditCard":"text",label:b.label,placeholder:b.placeholder,required:b.required!==!1,value:b.value}));return c.jsx(Jf,{isOpen:!0,title:s.title,description:s.description,fields:w,onComplete:d})}if(!t)return null;const p={isOpen:!0,title:t.title,description:t.description,placeholder:t.placeholder,onComplete:u};switch(t.type){case"password":return c.jsx(Kf,{...p});case"email":return c.jsx(Gf,{...p});case"phone":return c.jsx(Yf,{...p});case"pin":return c.jsx(Hf,{...p});case"ssn":return c.jsx(Xs,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return c.jsx(Xs,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return c.jsx(Xs,{...p})}},m=f.useMemo(()=>({showSecureModal:a,showSecureForm:l}),[a,l]);return c.jsxs(ml.Provider,{value:m,children:[e,h()]})}function Zf(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 Qf(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 Co(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 D=s[1],z=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let A;for(;(A=z.exec(D))!==null;)if(A[1]&&A[2]){const M=parseInt(A[1],10),I=A[2].replace(/[.,;:!?]+$/,""),F=I.replace(/\/+$/,"");if(a.has(F)||a.set(F,I),i.has(F)||i.set(F,[]),i.get(F).push(M),!l.has(F))l.set(F,M);else{const K=l.get(F);M<K&&l.set(F,M)}}for(const[M,I]of i.entries()){const F=l.get(M);for(const K of I)K!==F&&u.set(K,F)}for(const[M,I]of l.entries()){const F=a.get(M)||M;r.set(I,F),o.push({number:I,url:F})}}let d,h=t;s&&s[0]&&(d=s[0],h=t.replace(n,""));const m=[];let p=0;const w=/```[\s\S]*?```|`[^`]+`/g;let b;for(;(b=w.exec(h))!==null;)b.index>p&&m.push({type:"text",content:h.slice(p,b.index),start:p,end:b.index}),m.push({type:"code",content:b[0],start:b.index,end:b.index+b[0].length}),p=b.index+b[0].length;p<h.length&&m.push({type:"text",content:h.slice(p),start:p,end:h.length});const j=m.map(D=>{if(D.type==="code")return D.content;let z=D.content;return z=z.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(M,I,F)=>{const K=parseInt(I,10),Y=F.replace(/\/+$/,""),le=u.get(K)||K;return l.has(Y)||(l.set(Y,le),r.has(le)||(r.set(le,F),o.push({number:le,url:F}))),`[${le}]`}),z=z.replace(/\[(\d+)\]/g,(M,I)=>{const F=parseInt(I,10);return`[${u.get(F)||F}]`}),z}),y=[];for(const[D,z]of l.entries()){const A=a.get(D)||D,{baseUrl:M,anchor:I}=Zf(A),F=Qf(A);y.push({url:A,baseUrl:M,numbers:[z],anchor:I,title:F})}y.sort((D,z)=>(D.numbers[0]||0)-(z.numbers[0]||0));const k=new Map;let v=1;for(const D of y){const z=D.numbers[0];k.set(z,v),D.numbers=[v],v++}const E=new Map;for(const[D,z]of r.entries()){const A=k.get(D);A&&E.set(A,z)}const N=o.map(D=>{const z=k.get(D.number);return z?{number:z,url:D.url}:D}).filter(D=>k.has(D.number)),$=Array.from(k.entries()).sort((D,z)=>z[0]-D[0]);let L=j.join("");for(const[D,z]of $){const A=new RegExp(`\\[${D}\\](?!\\d)`,"g");L=L.replace(A,`[${z}]`)}return{processedText:L,citations:N.sort((D,z)=>D.number-z.number),citationMap:E,groupedCitations:y,referencesText:d}}function Rn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Rn(t)}catch{return e}if(Array.isArray(e))return e.map(Rn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Rn(s);return t}return e}function Ws(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Rn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Rn(e):{}}function em({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="",agentId:w,agentName:b,tokenEndpoint:j="/api/arcten/token",apiBaseUrl:y="https://api.arcten.com",user:k,state:v,onStateChange:E,allowStateEdits:N=!0,sources:$,ragConfig:L,showCitations:D=!0,sensitiveParams:z,autoDetectSensitive:A=!1}){const{showSecureModal:M}=pl(),I=f.useMemo(()=>L!==void 0?L:$&&$.length>0?{enabled:!0,organizationId:$[0],autoExecute:!0,filters:void 0}:{enabled:!1},[$,L]),[F,K]=f.useState(null),Y=f.useRef(null),[le,X]=f.useState(null),[oe,we]=f.useState(null),Te=f.useRef(null),se=v!==void 0,[tt,ut]=f.useState({}),ke=f.useRef({});se&&v?ke.current=v:se||(ke.current=tt);const[He,Lt]=f.useState(!1),[ti,nt]=f.useState(null),st=f.useRef(!1),[Ue,mn]=f.useState(u),[_e,Ft]=f.useState(i),[Bt,Wn]=f.useState(600),[pn,jt]=f.useState(!1),[ie,ce]=f.useState(!1),[Ve,Je]=f.useState(!1),[ue,gn]=f.useState({x:100,y:100}),[qn,zt]=f.useState(!1),[yn,Ct]=f.useState({x:0,y:0}),[Ut,xn]=f.useState(!1),rt=f.useRef(null),Xe=f.useRef(null),[_t,bn]=f.useState(""),[Kn,As]=f.useState(null),[vn,Gn]=f.useState("Thinking..."),[We,Me]=f.useState(new Set),[Xt,it]=f.useState(""),[De,Yn]=f.useState([]),Hn=f.useRef(new Map),dt=f.useRef(!1),wn=f.useRef(""),[Tn,Sn]=f.useState(!1),[Ie,Jn]=f.useState([]),[Oe,Pt]=f.useState(()=>typeof window<"u"?crypto.randomUUID():null),[ht,ft]=f.useState(!1),[Zn,qe]=f.useState(!1),[ni,Wt]=f.useState([]),Qn=f.useCallback(async(g,P=3)=>{if(!Oe||!Y.current)return;const R=async()=>{const O=`${y.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,U=await fetch(O,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Oe,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 B=0;B<P;B++)try{await R(),nt(null);return}catch(O){if(B===P-1){const ee=O instanceof Error?O:new Error(String(O));throw nt(ee),console.error("Failed to sync state to Convex after retries:",O),ee}await new Promise(ee=>setTimeout(ee,Math.pow(2,B)*100))}},[Oe,y,Y]),mt=f.useMemo(()=>function(){return ke.current},[]),At=f.useMemo(()=>async function(P){const R={...ke.current,...P};ke.current=R,se||ut(R),E&&E(R);try{await Qn(P)}catch(B){throw B}},[Qn,E,se]);f.useEffect(()=>{se&&v&&(ke.current=v)},[se,v]);const ot=f.useMemo(()=>I?.enabled?async function(P,R=20,B){if($&&$.length>1){const ee=$.map(H=>fetch(`${y}/search`,{method:"POST",headers:{"Content-Type":"application/json",...Y.current?{Authorization:`Bearer ${Y.current}`}:{}},body:JSON.stringify({q:P,k:Math.min(R,100),organizationId:H,...Object.keys(U).length>0?{filters:U}:{}})}).then(q=>q.ok?q.json():null)),Z=await Promise.all(ee),te=[];for(const H of Z)H?.candidates&&te.push(...H.candidates);te.sort((H,q)=>{const be=H.scores?.rerank||H.scores?.dense||0;return(q.scores?.rerank||q.scores?.dense||0)-be});const _=te.slice(0,R).map((H,q)=>{const be=H.citation||H.url;return{rank:q+1,doc_id:H.doc_id,block_id:H.block_id,url:H.url,citation:be,title:H.title||"Untitled",snippet:H.snippet,score:H.scores?.rerank||H.scores?.dense||0,metadata:{site:H.metadata?.site,lang:H.metadata?.lang,contentType:H.metadata?.content_type}}});return{success:!0,query:P,total:te.length,results:_,summary:`Found ${te.length} relevant results across ${$.length} source(s) for "${P}". Top result: ${_[0]?.title||"N/A"}`}}const O=I.organizationId&&I.organizationId!=="default"?I.organizationId:void 0,U={...I.filters,...B};try{const ee={q:P,k:Math.min(R,100)};O&&(ee.organizationId=O),Object.keys(U).length>0&&(ee.filters=U);const Z={"Content-Type":"application/json"};Y.current&&(Z.Authorization=`Bearer ${Y.current}`);const te=await fetch(`${y}/search`,{method:"POST",headers:Z,body:JSON.stringify(ee)});if(!te.ok){const q=await te.text();return{success:!1,error:`Search failed: ${te.status} ${q}`}}const _=await te.json(),H=_.candidates.map((q,be)=>{const me=q.citation||q.url;return{rank:be+1,doc_id:q.doc_id,block_id:q.block_id,url:q.url,citation:me,title:q.title||"Untitled",snippet:q.snippet,score:q.scores?.rerank||q.scores?.dense||0,metadata:{site:q.metadata?.site,lang:q.metadata?.lang,contentType:q.metadata?.content_type}}});return{success:!0,query:_.query,total:_.total,results:H,summary:`Found ${_.total} relevant results for "${P}". Top result: ${H[0]?.title||"N/A"}`}}catch(ee){return{success:!1,error:ee instanceof Error?ee.message:"Unknown error occurred"}}}:null,[L,y,Y]),x=f.useMemo(()=>I?.enabled?async function(P,R){const B=I.organizationId&&I.organizationId!=="default"?I.organizationId:$&&$.length>0?$[0]:void 0;try{const O={"Content-Type":"application/json"};Y.current&&(O.Authorization=`Bearer ${Y.current}`);const U=await fetch(`${y}/fetch`,{method:"POST",headers:O,body:JSON.stringify({doc_id:P,block_ids:R,...B?{organizationId:B}:{}})});if(!U.ok){const Z=await U.text();return{success:!1,error:`Fetch failed: ${U.status} ${Z}`}}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(O){return{success:!1,error:O instanceof Error?O.message:"Unknown error occurred"}}}:null,[L,y,Y]),T=f.useMemo(()=>{const g=[...d,...h,mt];return(!se||N)&&g.push(At),I?.enabled&&(ot&&g.push(ot),x&&g.push(x)),g},[d,h,mt,At,ot,x,se,N,I]),S=f.useMemo(()=>Qr(T,m),[T,m]),C=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:[]}}];(!se||N)&&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 I?.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"]}}),[...S,...g,...P]},[S,se,N,I]),V=f.useMemo(()=>new Set(C.map(g=>g.name)),[C]),W=f.useMemo(()=>C.filter(g=>g.name==="getState"?!0:g.name==="setState"?!se||N:V.has(g.name)),[C,V,se,N]),J=f.useMemo(()=>{const g=new Map,P=new Map(S.map(R=>[R.name,R]));return g.set("getState",mt),(!se||N)&&g.set("setState",At),I?.enabled&&(ot&&g.set("searchDocs",ot),x&&g.set("fetchDocContent",x)),T.forEach(R=>{if(R===mt||R===At||R===ot||R===x)return;const B=R[Qe];if(B){const U=P.get(B);if(U){g.set(U.name,R);return}}const O=C.find(U=>U.name===R.name);O&&g.set(O.name,R)}),g},[T,C,mt,At,ot,x,se,N,I]),pe=f.useMemo(()=>{const g=new Set;g.add("getState"),g.add("setState"),I?.enabled&&I.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent"));const P=new Map(C.map(R=>[R.name,R]));return h.forEach(R=>{const B=R[Qe];if(B&&P.has(B))g.add(B);else{const O=C.find(U=>U.name===R.name);O&&g.add(O.name)}}),g},[h,C,I]),ye=["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&&mn(JSON.parse(g));const P=localStorage.getItem("arcten-sidebar-width");P&&Ft(parseInt(P));const R=localStorage.getItem("arcten-sidebar-height");R&&Wn(parseInt(R));const B=localStorage.getItem("arcten-sidebar-detached");B&&ce(JSON.parse(B));const O=localStorage.getItem("arcten-sidebar-position");if(O){const ee=JSON.parse(O),Z=50,te=Math.max(Z-i,Math.min(ee.x,window.innerWidth-Z)),_=Math.max(0,Math.min(ee.y,window.innerHeight-Z));gn({x:te,y:_})}const U=localStorage.getItem("arcten-sidebar-minimized");U&&Je(JSON.parse(U)),xn(!0)}},[]);const xe=f.useMemo(()=>k,[k?.id]);f.useEffect(()=>((async()=>{try{const P=await fetch(j,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:xe})});if(!P.ok)throw new Error("Failed to fetch token");const R=await P.json();K(R.clientToken),Y.current=R.clientToken,we(R.expiresAt),X(null)}catch(P){X(P instanceof Error?P.message:"Failed to fetch token")}})(),()=>{Te.current&&clearTimeout(Te.current)}),[j,xe]),f.useEffect(()=>{if(!oe)return;Te.current&&clearTimeout(Te.current);const g=Math.floor(Date.now()/1e3),P=oe-g,B=Math.max(0,P-5);return Te.current=setTimeout(async()=>{try{const O=await fetch(j,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:xe})});if(!O.ok)throw new Error("Failed to refresh token");const U=await O.json();K(U.clientToken),Y.current=U.clientToken,we(U.expiresAt),X(null)}catch(O){console.error("Token refresh failed:",O),X(O instanceof Error?O.message:"Failed to refresh token")}},B*1e3),()=>{Te.current&&clearTimeout(Te.current)}},[oe,j,xe]),f.useEffect(()=>{(async()=>{if(T.length===0)return;const P=T.map(R=>`${R.name}:${R.toString()}`).join("|");if(P!==wn.current&&!dt.current){dt.current=!0,wn.current=P;try{const R=T.map(O=>({name:O.name,code:O.toString()})),B=await fetch(`${y}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:R})});if(B.ok){const O=await B.json();O.tools&&O.tools.forEach(U=>{Hn.current.set(U.name,U)}),Yn(O.tools)}}catch(R){console.error("Failed to fetch tool descriptions:",R)}finally{dt.current=!1}}})()},[T,y]),f.useEffect(()=>{Promise.resolve().then(()=>Of).then(g=>{As(()=>g.Response)})},[]),f.useEffect(()=>{const g=()=>{it(window.location.pathname)};g(),window.addEventListener("popstate",g);const P=setInterval(g,500);return()=>{window.removeEventListener("popstate",g),clearInterval(P)}},[]);const Q=f.useCallback(async()=>{if(!(!xe?.id||!F)){qe(!0);try{const P=await(await fetch(`${y}/conversations`,{headers:{Authorization:`Bearer ${F}`}})).json();Jn(P.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{qe(!1)}}},[xe?.id,F,y]);f.useEffect(()=>{xe?.id&&F&&Q()},[xe?.id,F,Q]);function ae(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 Ze(){const g=crypto.randomUUID();Pt(g),ss([]),Wt([]),ft(!1);const P=se?v||{}:{};ke.current=P,se||ut(P),E&&E(P),st.current=!1}async function kt(g){if(F)try{await fetch(`${y}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${F}`}}),Jn(Ie.filter(P=>P._id!==g)),g===Oe&&Ze()}catch(P){console.error("Failed to delete conversation:",P)}}async function jn(g){Pt(g.chatId),ft(!1),qe(!0);try{const P=await fetch(`${y}/conversations/${g.chatId}/messages`,{headers:{Authorization:`Bearer ${Y.current}`}});if(!P.ok)throw new Error(`Failed to fetch messages: ${P.statusText}`);const B=(await P.json()).messages||[];ss(B),Wt(B)}catch(P){console.error("Failed to load conversation messages:",P);const R=g.messages||[];ss(R),Wt(R)}finally{qe(!1)}}const Cn=async(g,P={})=>{const R=P.headers?new Headers(P.headers):new Headers;return R.delete("user-agent"),R.delete("User-Agent"),fetch(g,{...P,headers:R})},{messages:Ne,sendMessage:es,status:Re,error:ts,stop:ns,addToolResult:Mt,setMessages:ss}=Po.useChat({id:Oe||void 0,transport:new gs.DefaultChatTransport({api:`${y}/chat`,fetch:Cn,headers:()=>{const g={};return Y.current&&(g.Authorization=`Bearer ${Y.current}`),g},body:()=>({tools:W.map(P=>({name:P.name,description:P.description,inputSchema:P.jsonSchema})),...w&&{agentId:w},...b&&{agentName:b},currentRoute:Xt,state:ke.current})}),sendAutomaticallyWhen:gs.lastAssistantMessageIsCompleteWithToolCalls});f.useEffect(()=>{const g=Ne[Ne.length-1];if(!g||g.role!=="assistant")return;const P=g.parts?.filter(R=>R.type?.startsWith("tool-")&&R.state==="input-available"&&typeof R.toolCallId=="string"&&R.input!==void 0)||[];for(const R of P){const B=R,O=B.type?.replace("tool-","")||"",U=B.toolCallId;if(pe.has(O)){if(We.has(U))continue;Me(Z=>Z.has(U)?Z:new Set(Z).add(U)),(async()=>{try{const Z=J.get(O);if(!Z){console.warn(`[ArctenAgent] Tool ${O} not found in toolsMap. Available tools:`,Array.from(J.keys())),Mt({toolCallId:U,tool:O,output:`Error: Tool ${O} not found`}),Me(q=>{const be=new Set(q);return be.delete(U),be});return}const te=Ws(B.input),_=W.find(q=>q.name===O);let H;if(_&&_.jsonSchema?.properties){const be=Object.keys(_.jsonSchema.properties).map(me=>te[me]);console.log(`[ArctenAgent] Executing safe tool ${O} with args:`,be),H=await Z(...be)}else if(O==="getState")H=Z();else if(O==="setState"){const q=te.updates||te;H=await Z(q)}else H=await Z(...Object.values(te));console.log(`[ArctenAgent] Tool ${O} completed, result:`,H),Mt({toolCallId:U,tool:O,output:H}),Me(q=>{const be=new Set(q);return be.delete(U),be})}catch(Z){console.error(`[ArctenAgent] Error executing safe tool ${O}:`,Z),Mt({toolCallId:U,tool:O,output:`Error: ${Z instanceof Error?Z.message:String(Z)}`}),Me(te=>{const _=new Set(te);return _.delete(U),_})}})()}}},[Ne,pe,J,W,Mt]),f.useEffect(()=>{if(!Oe||!Y.current)return;(async()=>{Lt(!0),nt(null);try{const R=`${y.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,B=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Oe},format:"json"})});if(!B.ok){if(B.status===404||B.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${B.status}), using empty state`);const _=se?v||{}:{};ke.current=_,se||ut(_),E&&E(_),st.current=!0,Lt(!1);return}const te=await B.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${B.status} ${te}`)}const U=(await B.json())?.value||{},ee=!st.current;let Z;ee?(Z={...se?v||{}:{},...U},st.current=!0):Z=U,ke.current=Z,se||ut(Z),E&&E(Z)}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 B=P instanceof Error?P:new Error(String(P));if(nt(B),!st.current){const O=se?v||{}:{};ke.current=O,se||ut(O),E&&E(O),st.current=!0}}finally{Lt(!1)}})()},[Oe,y,se,v,E]),f.useEffect(()=>{Ue&&Xe.current&&Xe.current.focus()},[Ue,Ne]);function vl(){mn(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function wl(){mn(!1),localStorage.setItem("arcten-sidebar-expanded","false")}f.useEffect(()=>{},[Ue]),f.useEffect(()=>{rt.current&&rt.current.scrollIntoView({behavior:"smooth"})},[Ne]),f.useEffect(()=>{function g(P){P.key==="Escape"&&(Re==="streaming"||Re==="submitted")&&(P.preventDefault(),ns())}return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Re,ns]);function Tl(){const g=crypto.randomUUID();Pt(g),ss([]),Wt([]),ft(!1)}function si(g){if(g.preventDefault(),!_t.trim())return;(Re==="streaming"||Re==="submitted")&&ns();const P=ye[Math.floor(Math.random()*ye.length)]||"Thinking...";Gn(P),es({text:_t}),bn("")}function Sl(g){const P=g.target.value;bn(P)}f.useEffect(()=>{if(!pn)return;function g(R){if(ie){const B=R.clientX-ue.x,O=R.clientY-ue.y;B>=a&&B<=l&&Ft(B),O>=400&&O<=1e3&&Wn(O)}else{const B=window.innerWidth-R.clientX;B>=a&&B<=l&&Ft(B)}}function P(){jt(!1),localStorage.setItem("arcten-sidebar-width",_e.toString()),localStorage.setItem("arcten-sidebar-height",Bt.toString())}return window.addEventListener("mousemove",g),window.addEventListener("mouseup",P),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",P)}},[pn,_e,Bt,ie,ue,a,l]);function jl(g){g.preventDefault(),jt(!0)}function Cl(){ce(!0),Je(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Pl(){ce(!1),Je(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function ri(){Je(!Ve),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ve))}function Al(g){ie&&(zt(!0),Ct({x:g.clientX-ue.x,y:g.clientY-ue.y}))}return f.useEffect(()=>{if(!ie)return;function g(){gn(P=>{const B=window.innerWidth-50,O=window.innerHeight-50,U=50-_e,ee=0,Z=Math.max(U,Math.min(P.x,B)),te=Math.max(ee,Math.min(P.y,O));if(Z!==P.x||te!==P.y){const _={x:Z,y:te};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(_)),_}return P})}return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[ie,_e]),f.useEffect(()=>{if(!qn)return;function g(R){const B=R.clientX-yn.x,O=R.clientY-yn.y,U=50,ee=window.innerWidth-U,Z=window.innerHeight-U,te=U-_e,_=0,H=Math.max(te,Math.min(B,ee)),q=Math.max(_,Math.min(O,Z));gn({x:H,y:q})}function P(){zt(!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)}},[qn,yn,ue,_e]),Ut?le?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: ",le]})}):F?c.jsx(Gu,{features:Cf,children:c.jsx(ls,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:ie?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:ie?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
22
20
  ${ie?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
23
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"}
24
22
  ${ie?"border border-border":"border-l border-border"}
25
23
  ${Ue?"":"w-[30px]"}
26
- `,style:Ue?ie?{width:`${_e}px`,height:Ve?"auto":`${Bt}px`,left:`${ue.x}px`,top:`${ue.y}px`}:{width:`${_e}px`}:void 0,onClick:Ue?void 0:vl,children:Ue?c.jsxs(c.Fragment,{children:[!ie&&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:jl,children:c.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),ie&&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(),jt(!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(),zt(!0),Ct({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(),jt(!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 ${ie?"cursor-move":""}`,onMouseDown:ie?Al:void 0,children:[c.jsx("h2",{className:`text-base font-semibold ${ie&&Ve?"cursor-pointer":""}`,onClick:ie&&Ve?g=>{g.stopPropagation(),ri()}:void 0,children:r}),c.jsxs("div",{className:"flex items-center gap-1",onClick:g=>g.stopPropagation(),children:[c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Nt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Tl,"aria-label":"New chat",children:c.jsx(ne.Plus,{className:"h-4 w-4"})})}),c.jsx(bt,{children:"Start a new conversation"})]}),c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Nt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ie?Pl:Cl,"aria-label":ie?"Dock sidebar":"Float sidebar",children:ie?c.jsx(ne.Dock,{className:"h-4 w-4"}):c.jsx(ne.PictureInPicture2,{className:"h-4 w-4"})})}),c.jsx(bt,{children:ie?"Dock to sidebar":"Undock to floating window"})]}),c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Nt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ie?ri:wl,"aria-label":ie?Ve?"Maximize":"Minimize":"Close sidebar",children:ie?Ve?c.jsx(ne.Maximize2,{className:"h-4 w-4"}):c.jsx(ne.Minimize2,{className:"h-4 w-4"}):c.jsx(ne.X,{className:"h-4 w-4"})})}),c.jsx(bt,{children:ie?Ve?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ve&&c.jsxs(c.Fragment,{children:[k&&Ie.length>0&&c.jsxs("div",{className:`border-b border-border ${ht?"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:()=>{ht||Q(),ft(!ht)},children:ht?"Show less":"View all"})]}),c.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ht?"flex-1 overflow-y-auto":""}`,children:Ie.slice(0,ht?void 0:3).map(g=>c.jsxs("div",{className:"group relative",children:[c.jsxs(Pf,{type:"button",className:re(Nt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>jn(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:ae(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(),kt(g._id)},"aria-label":"Delete conversation",children:c.jsx(ne.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:De.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?"}),Ne.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:[(Tn?Ne:Ne.slice(0,10)).map(g=>c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{bn(g.sampleUsage),Xe.current?.focus()},children:g.friendlyName})}),c.jsx(bt,{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)),Ne.length>10&&!Tn&&c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsxs(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Sn(!0),children:["+",Ne.length-10," more"]})}),c.jsx(bt,{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:Ne.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"})]})})]}),Tn&&Ne.length>10&&c.jsx(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Sn(!1),children:"Show less"})]})})]}):c.jsxs(c.Fragment,{children:[De.map(g=>{const R=g.parts.filter(_=>_.type==="text").map(_=>_.text).join("");let B=g.parts;g.role==="assistant"&&g.parts.some(H=>H.timestamp)&&(B=[...g.parts].sort((H,W)=>{const be=H.timestamp||0,me=W.timestamp||0;return be-me}));let O=[],U=new Map,ee=[],Z,te=!0;if(g.role==="assistant"){const _=B.filter(me=>me.type==="text"&&me.text),H=[],W=[];_.forEach(me=>{const{citations:pt,citationMap:Pe,groupedCitations:$e,referencesText:gt}=Co(me.text);O.push(...pt),H.push(Pe),$e&&W.push(...$e),gt&&(Z=gt)}),H.forEach(me=>{me.forEach((pt,Pe)=>{U.has(Pe)||U.set(Pe,pt)})}),ee=Array.from(new Map(W.map(me=>[me.url,me])).values()).sort((me,pt)=>(me.numbers[0]||0)-(pt.numbers[0]||0)),te=!(Re==="streaming"&&g.id===De.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(Af,{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:R}):c.jsx("div",{className:"space-y-2",children:B.map((_,H)=>{if(_.type?.startsWith("tool-")){const W=_.type?.replace("tool-","")||"",be=q.find(Pe=>Pe.name===W),me=_.state==="input-available",pt=_.state==="output-available";if(me&&pe.has(W),me){if(pe.has(W))return null;const Pe=qs(_.input);return c.jsx(ls,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:c.jsx(Ef,{toolName:W,description:be?.description||"",args:Pe,onApprove:async()=>{if(qe.has(_.toolCallId))return;Me(gt=>new Set(gt).add(_.toolCallId));const $e=J.get(W);if($e)try{const gt=await $e(...Object.values(Pe));Mt({toolCallId:_.toolCallId,tool:W,output:gt})}catch(gt){Mt({toolCallId:_.toolCallId,tool:W,output:`Error: ${gt}`})}},onDeny:async()=>{qe.has(_.toolCallId)||(Me($e=>new Set($e).add(_.toolCallId)),Mt({toolCallId:_.toolCallId,tool:W,output:"User denied tool execution"}))}})},`${_.toolCallId}-${H}`)}else if(pt){const Pe=_.output==="User denied tool execution",$e=qs(_.input);return c.jsx(Nf,{toolName:W,args:$e,isDenied:Pe,isSafe:pe.has(W)},`${_.toolCallId}-${H}`)}return null}if(_.type==="text"&&_.text&&Kn){const{processedText:W}=Co(_.text),Pe=!B.slice(H+1).some($e=>$e.type==="text"&&$e.text)&&te&&U.size>0;return c.jsx(Xf,{text:W,citations:O,citationMap:U,groupedCitations:Pe?ee:void 0,referencesText:Pe?Z:void 0,ResponseComponent:Kn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:N,showReferences:Pe},`${g.id}-${H}`)}return _.type==="reasoning"&&_.text?c.jsxs(dl,{className:"w-full",isStreaming:Re==="streaming"&&H===g.parts.length-1&&g.id===De.at(-1)?.id,children:[c.jsx(hl,{}),c.jsx(fl,{children:_.text})]},`${g.id}-${H}`):null})})})},g.id)}),c.jsx("div",{ref:rt})]})}),ts&&c.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",ts.message]}),c.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[c.jsx(Ku,{mode:"wait",children:(Re==="streaming"||Re==="submitted")&&c.jsxs(ls,{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(ls,{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:vn})]})}),c.jsxs("form",{onSubmit:si,className:"relative",children:[c.jsx(Mo,{ref:Xe,value:_t,onChange:Sl,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(),si(g))}}),Re==="streaming"||Re==="submitted"?c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Nt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:ns,children:c.jsx(ne.Square,{className:"h-4 w-4"})})}),c.jsxs(bt,{children:[c.jsx(ai,{children:"Escape"})," to stop"]})]}):c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"submit",className:re(Nt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!_t.trim(),children:c.jsx(ne.ArrowRight,{className:"h-4 w-4"})})}),c.jsxs(bt,{children:[c.jsx(ai,{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(ne.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 tm(e){return c.jsx(gl,{children:c.jsx(em,{...e})})}const nm={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 kn(e){for(const[t,n]of Object.entries(nm))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function sm(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 rm(e,t,n){return t.length>0}function im(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=om(s[i]),d={name:i,type:am(l||kn(i)||"text"),label:yl(i),placeholder:lm(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:rm(e,t),fields:r,title:cm(e),description:um(e,r.length)}}function om(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function am(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 lm(e,t){return t?sm(t,e).placeholder:`Enter ${yl(e).toLowerCase()}...`}function cm(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function um(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 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 dm(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 hm(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):{}}const ms="__secureOutput",ps="[hidden for privacy]";function fm(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 mm(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function pm(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 gm(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 pr(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]=pr(r),r&&typeof r=="object"&&Object.assign(n,xl(r,o))}):t&&(n[t]=pr(e)),n}function ym(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:ps,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:ps,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??ps,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function xm(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=ym(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[ms]=r,l}if(n.fields.includes("*"))return bl(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[ms]:{...r,redactedFields:n.fields}};const o=fm(t),i=[],a={};return n.fields.forEach(l=>{const u=mm(l);if(u.length===0)return;const d=pm(o,u),h=pr(d);a[l]=h,gm(o,u,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[ms]=r,o}function bm({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="",agentId:w,agentName:b,initialMessages:j=[],conversationId:y,state:k,onStateChange:v,allowStateEdits:E=!0,onToolCall:D,onFinish:$,sources:L,ragConfig:N,ragFilters:z,secureInputHandler:A}={}){const M=f.useMemo(()=>N!==void 0?N:z?{enabled:!0,filters:z}:L&&L.length>0?{enabled:!0,organizationId:L[0],autoExecute:!0,filters:void 0}:{enabled:!1},[L,N,z]),I=f.useMemo(()=>{const x={};if(l)for(const[T,S]of Object.entries(l))if(x[T]={},Array.isArray(S))for(const C of S){const V=kn(C);x[T][C]=V||"text"}else for(const[C,V]of Object.entries(S))x[T][C]=V;if(a){for(const[T,S]of Object.entries(a))if(S&&typeof S=="object"&&"sensitiveParams"in S){x[T]||(x[T]={});const C=S.sensitiveParams;if(Array.isArray(C))for(const V of C){const q=kn(V);x[T][V]=q||"text"}else if(C&&typeof C=="object")for(const[V,q]of Object.entries(C))x[T][V]=q}}return x},[l,a,d]),F=f.useMemo(()=>xm(u),[u]),K=f.useCallback((x,T)=>{const S=F[x];if(!S)return T;try{return bl(x,T,S)}catch(C){return console.error(`[useAgent] Failed to redact output for ${x}:`,C),{value:ps,[ms]:{tool:x,redacted:!0,error:String(C)}}}},[F]),[Y,le]=f.useState(n||null),X=f.useRef(n||null),[oe,we]=f.useState(null),[Te,se]=f.useState(null),tt=f.useRef(null),[ut,ke]=f.useState([]),[He,Lt]=f.useState(y||(typeof window<"u"?crypto.randomUUID():null)),[ti,nt]=f.useState(!1),[st,Ue]=f.useState(new Set),[mn,_e]=f.useState(new Map),[Ft,Bt]=f.useState(new Map),[qn,pn]=f.useState(new Map),[jt,ie]=f.useState(new Map),ce=k!==void 0,[Ve,Je]=f.useState({}),ue=f.useRef({}),gn=ce?k||{}:Ve;ce&&k?ue.current=k:ce||(ue.current=Ve);const[Wn,zt]=f.useState(!1),[yn,Ct]=f.useState(null),Ut=f.useRef(!1),xn=f.useCallback(async(x,T=3)=>{if(!He||!X.current)return;const S=async()=>{const V=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,q=await fetch(V,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:He,updates:x},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 J=await q.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${q.status} ${J}`)}};for(let C=0;C<T;C++)try{await S(),Ct(null);return}catch(V){if(C===T-1){const J=V instanceof Error?V:new Error(String(V));throw Ct(J),console.error("Failed to sync state to Convex after retries:",V),J}await new Promise(J=>setTimeout(J,Math.pow(2,C)*100))}},[He,e,X]),rt=f.useMemo(()=>function(){return ue.current},[]),Xe=f.useMemo(()=>async function(T){const S={...ue.current,...T};ue.current=S,ce||Je(S),v&&v(S);try{await xn(T)}catch(C){throw C}},[xn,v,ce]);f.useEffect(()=>{ce&&k&&(ue.current=k)},[ce,k]);const _t=f.useCallback(x=>A?A.showSecureModal(x):new Promise(T=>{_e(S=>new Map(S).set(x.id,x)),Bt(S=>new Map(S).set(x.id,T))}),[A]),bn=f.useCallback((x,T)=>{if(A)return;const S=Ft.get(x);S&&(S(T),_e(C=>{const V=new Map(C);return V.delete(x),V}),Bt(C=>{const V=new Map(C);return V.delete(x),V}))},[Ft,A]),Kn=f.useCallback(x=>A?A.showSecureForm(x):new Promise(T=>{pn(S=>new Map(S).set(x.id,x)),ie(S=>new Map(S).set(x.id,T))}),[A]),As=f.useCallback((x,T)=>{if(A)return;const S=jt.get(x);S&&(S(T),pn(C=>{const V=new Map(C);return V.delete(x),V}),ie(C=>{const V=new Map(C);return V.delete(x),V}))},[jt,A]),vn=f.useCallback((x,T)=>{const S=I[x]||{},C=Object.keys(S).length>0;if(d){const V=Object.keys(T).filter(q=>kn(q)!==null);return C||V.length>0}return C},[I,d]),Gn=f.useCallback((x,T)=>{const C={...I[x]||{}};if(d){for(const q of Object.keys(T))if(!(q in C)){const J=kn(q);J&&(C[q]=J)}}const V=Object.entries(C).filter(([q])=>Object.prototype.hasOwnProperty.call(T,q));return V.length>0?Object.fromEntries(V):C},[I,d]),qe=f.useMemo(()=>M?.enabled?async function(T,S=20,C){const V={...M.filters,...C};if(L&&L.length>1){const J=L.map(Q=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...X.current?{Authorization:`Bearer ${X.current}`}:{}},body:JSON.stringify({q:T,k:Math.min(S,100),organizationId:Q,...Object.keys(V).length>0?{filters:V}:{}})}).then(ae=>ae.ok?ae.json():null)),pe=await Promise.all(J),ye=[];for(const Q of pe)Q?.candidates&&ye.push(...Q.candidates);ye.sort((Q,ae)=>{const Ze=Q.scores?.rerank||Q.scores?.dense||0;return(ae.scores?.rerank||ae.scores?.dense||0)-Ze});const xe=ye.slice(0,S).map((Q,ae)=>{const Ze=Q.citation||Q.url;return{rank:ae+1,doc_id:Q.doc_id,block_id:Q.block_id,url:Q.url,citation:Ze,title:Q.title||"Untitled",snippet:Q.snippet,score:Q.scores?.rerank||Q.scores?.dense||0,metadata:{site:Q.metadata?.site,lang:Q.metadata?.lang,contentType:Q.metadata?.content_type}}});return{success:!0,query:T,total:ye.length,results:xe,summary:`Found ${ye.length} relevant results across ${L.length} source(s) for "${T}". Top result: ${xe[0]?.title||"N/A"}`}}const q=M.organizationId&&M.organizationId!=="default"?M.organizationId:L&&L.length>0?L[0]:void 0;try{const J={q:T,k:Math.min(S,100)};q&&(J.organizationId=q),Object.keys(V).length>0&&(J.filters=V);const pe={"Content-Type":"application/json"};X.current&&(pe.Authorization=`Bearer ${X.current}`);const ye=await fetch(`${e}/search`,{method:"POST",headers:pe,body:JSON.stringify(J)});if(!ye.ok){const ae=await ye.text();return{success:!1,error:`Search failed: ${ye.status} ${ae}`}}const xe=await ye.json(),Q=xe.candidates.map((ae,Ze)=>{const kt=ae.citation||ae.url;return{rank:Ze+1,doc_id:ae.doc_id,block_id:ae.block_id,url:ae.url,citation:kt,title:ae.title||"Untitled",snippet:ae.snippet,score:ae.scores?.rerank||ae.scores?.dense||0,metadata:{site:ae.metadata?.site,lang:ae.metadata?.lang,contentType:ae.metadata?.content_type}}});return{success:!0,query:xe.query,total:xe.total,results:Q,summary:`Found ${xe.total} relevant results for "${T}". Top result: ${Q[0]?.title||"N/A"}`}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Unknown error occurred"}}}:null,[M,e,X]),Me=f.useMemo(()=>M?.enabled?async function(T,S){const C=M.organizationId&&M.organizationId!=="default"?M.organizationId:L&&L.length>0?L[0]:void 0;try{const V={"Content-Type":"application/json"};X.current&&(V.Authorization=`Bearer ${X.current}`);const q=await fetch(`${e}/fetch`,{method:"POST",headers:V,body:JSON.stringify({doc_id:T,block_ids:S,...C?{organizationId:C}:{}})});if(!q.ok){const pe=await q.text();return{success:!1,error:`Fetch failed: ${q.status} ${pe}`}}const J=await q.json();return{success:!0,blocks:J.blocks||[],fullContent:J.fullContent||"",pageUrl:J.pageUrl||"",pageTitle:J.pageTitle||"",summary:`Fetched ${J.blocks?.length||0} blocks from ${J.pageTitle||T}`}}catch(V){return{success:!1,error:V instanceof Error?V.message:"Unknown error occurred"}}}:null,[M,e,X]),Xt=f.useMemo(()=>{const x=[...o,...i,rt];return(!ce||E)&&x.push(Xe),M?.enabled&&(qe&&x.push(qe),Me&&x.push(Me)),x},[o,i,rt,Xe,qe,Me,M,ce,E]),it=f.useMemo(()=>Qr(Xt,a),[Xt,a]),Ne=f.useMemo(()=>{const x=new Map,T=new Map(it.map(S=>[S.name,S]));return x.set("getState",rt),(!ce||E)&&x.set("setState",Xe),M?.enabled&&(qe&&x.set("searchDocs",qe),Me&&x.set("fetchDocContent",Me)),Xt.forEach(S=>{if(S===rt||S===Xe||S===qe||S===Me)return;const C=S[Qe];if(C){const q=T.get(C);if(q){x.set(q.name,S);return}}const V=it.find(q=>q.name===S.name);V&&x.set(V.name,S)}),x},[Xt,it,rt,Xe,qe,Me,M,ce,E]),Yn=f.useMemo(()=>new Set(it.map(x=>x.name)),[it]),Hn=f.useMemo(()=>{const x=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!ce||E)&&x.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 T=[];return M?.enabled&&T.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...it,...x,...T]},[it,M,ce,E]),dt=f.useMemo(()=>Hn.filter(x=>x.name==="getState"?!0:x.name==="setState"?!ce||E:M?.enabled&&(x.name==="searchDocs"||x.name==="fetchDocContent")?!0:Yn.has(x.name)),[Hn,Yn,ce,E,M]),wn=f.useMemo(()=>{const x=new Set;return x.add("getState"),x.add("setState"),M?.enabled&&M.autoExecute!==!1&&(x.add("searchDocs"),x.add("fetchDocContent")),i.forEach(T=>{for(const[S,C]of Ne.entries())if(C===T){x.add(S);break}}),x},[i,Ne,M]);f.useEffect(()=>s||n?void 0:((async()=>{try{const T=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!T.ok)throw new Error("Failed to fetch token");const S=await T.json();le(S.clientToken),X.current=S.clientToken,se(S.expiresAt),we(null)}catch(T){console.error("[useAgent] Token fetch failed:",T),we(T instanceof Error?T.message:"Failed to fetch token")}})(),()=>{tt.current&&clearTimeout(tt.current)}),[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!Te||s||n)return;tt.current&&clearTimeout(tt.current);const x=Math.floor(Date.now()/1e3),T=Te-x,C=Math.max(0,T-5);return tt.current=setTimeout(async()=>{try{const V=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!V.ok)throw new Error("Failed to refresh token");const q=await V.json();le(q.clientToken),X.current=q.clientToken,se(q.expiresAt),we(null)}catch(V){console.error("[useAgent] Token refresh failed:",V),we(V instanceof Error?V.message:"Failed to refresh token")}},C*1e3),()=>{tt.current&&clearTimeout(tt.current)}},[Te,t,JSON.stringify(r),s,n]);const Tn=async(x,T={})=>{const S=T.headers?new Headers(T.headers):new Headers;S.delete("user-agent"),S.delete("User-Agent"),console.log("[useAgent] Making request to:",x),console.log("[useAgent] Method:",T.method||"GET"),console.log("[useAgent] Has Authorization header:",S.has("Authorization")),console.log("[useAgent] Client token available:",!!X.current);try{const C=await fetch(x,{...T,headers:S});if(!C.ok){console.error("[useAgent] Request failed:",C.status,C.statusText);const V=await C.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",V)}return C}catch(C){throw console.error("[useAgent] Fetch error:",C),C}},Sn=`${e}/chat`;console.log("[useAgent] Chat API URL:",Sn);const{messages:Ie,sendMessage:Jn,status:Oe,error:Pt,stop:ht,addToolResult:ft,setMessages:Zn}=Po.useChat({id:He||void 0,messages:j,transport:new gs.DefaultChatTransport({api:Sn,fetch:Tn,headers:()=>{const x={};return X.current?(x.Authorization=`Bearer ${X.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),x},body:()=>{console.log("[ArctenAgent] body() agentName =",b);const x=dt.map(C=>({name:C.name,description:C.description,inputSchema:C.jsonSchema})),T=x.filter(C=>C.name==="getState"||C.name==="setState").map(C=>C.name),S=x.filter(C=>C.name==="searchDocs"||C.name==="fetchDocContent").map(C=>C.name);return T.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",T),S.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",S):M?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:x,...w&&{agentId:w},...b&&{agentName:b},state:ue.current,...z&&{ragFilters:z}}}}),sendAutomaticallyWhen:gs.lastAssistantMessageIsCompleteWithToolCalls}),We=f.useCallback((x,T,S)=>{const C=K(x,S);ft({toolCallId:T,tool:x,output:C})},[ft,K]);f.useEffect(()=>{Ie.forEach(x=>{x.role==="assistant"&&x.parts.forEach(T=>{if(!T.type?.startsWith("tool-")||T.state!=="input-available")return;const S=T.type.replace("tool-",""),C=T.toolCallId;if(st.has(C))return;Ue(q=>new Set(q).add(C));const V=hm(T.input);if(vn(S,V)){const q=Gn(S,V),J=Object.entries(q).filter(([Q])=>V[Q]!==void 0),pe=J.length>0?Object.fromEntries(J):q,ye=Object.keys(V),xe=dm(V,pe);(async()=>{try{const Q=im(S,ye,pe,V),ae={id:`${C}-form`,toolName:S,toolCallId:C,title:Q.title,description:Q.description,fields:Q.fields},Ze=await Kn(ae);if(Ze===null){We(S,C,"User cancelled secure input");return}const kt={...xe,...Ze},jn=Ne.get(S);if(!jn)throw new Error(`Tool ${S} not found`);let Cn;const De=dt.find(es=>es.name===S);if(De&&De.jsonSchema?.properties){const Re=Object.keys(De.jsonSchema.properties).map(ts=>kt[ts]);Cn=await jn(...Re)}else Cn=await jn(...Object.values(kt));We(S,C,Cn)}catch(Q){console.error(`[useAgent] Error executing tool with secure input ${S}:`,Q),We(S,C,`Error: ${Q}`)}})();return}if(wn.has(S)&&!vn(S,V)){const q=Ne.get(S);q?(async()=>{try{const J=dt.find(ye=>ye.name===S);let pe;if(J&&J.jsonSchema?.properties){const xe=Object.keys(J.jsonSchema.properties).map(Q=>V[Q]);pe=await q(...xe)}else if(S==="getState")pe=q();else if(S==="setState"){const ye=V.updates||V;pe=await q(ye)}else pe=await q(...Object.values(V));We(S,C,pe)}catch(J){console.error(`[useAgent] Error executing tool ${S}:`,J),We(S,C,`Error: ${J}`)}})():console.warn(`[useAgent] Tool ${S} not found in toolsMap`)}else D&&D({toolCall:{toolCallId:C,toolName:S,args:V}})})})},[Ie,wn,Ne,D,We,st,Xe,dt,vn,Gn,_t]),f.useEffect(()=>{if(Oe==="ready"&&Ie.length>0&&$){const x=Ie[Ie.length-1];x&&x.role==="assistant"&&$({message:x,messages:Ie,isAbort:!1,isDisconnect:!1,isError:!!Pt})}},[Oe,Ie,Pt,$]);async function ni(){if(!(!r?.id||!Y)){nt(!0);try{const T=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${Y}`}})).json();ke(T.conversations||[])}catch(x){console.error("Failed to fetch conversations:",x)}finally{nt(!1)}}}f.useEffect(()=>{r?.id&&Y&&ni()},[JSON.stringify(r),Y,e]),f.useEffect(()=>{if(!He||!X.current)return;(async()=>{zt(!0),Ct(null);try{const T=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:He},format:"json"})});if(!T.ok){const V=await T.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${T.status} ${V}`)}const C=(await T.json())?.value||{};ue.current=C,ce||Je(C),v&&v(C),Ut.current=!0}catch(T){console.error("Failed to fetch state:",T);const S=T instanceof Error?T:new Error(String(T));Ct(S),Ut.current||(ue.current={},ce?v&&v({}):(Je({}),v&&v({})),Ut.current=!0)}finally{zt(!1)}})()},[He,e,ce,v]);async function qt(x){Lt(x),nt(!0);try{const T=await fetch(`${e}/conversations/${x}/messages`,{headers:{Authorization:`Bearer ${X.current}`}});if(!T.ok)throw new Error(`Failed to fetch messages: ${T.statusText}`);const C=(await T.json()).messages||[];Zn(C)}catch(T){console.error("Failed to load conversation messages:",T)}finally{nt(!1)}}async function Qn(x){if(Y)try{await fetch(`${e}/conversations/${x}`,{method:"DELETE",headers:{Authorization:`Bearer ${Y}`}}),ke(ut.filter(T=>T._id!==x)),x===He&&mt()}catch(T){console.error("Failed to delete conversation:",T)}}function mt(){const x=crypto.randomUUID();Lt(x),Zn([]),Ue(new Set),ue.current={},ce?v&&v({}):(Je({}),v&&v({})),Ut.current=!1}function At(x){const T=x.tool||"unknown-tool",S=K(T,x.output);ft({toolCallId:x.toolCallId,tool:T,output:S})}async function ot(x){const T={...ue.current,...x};ue.current=T,ce||Je(T),v&&v(T);try{await xn(x)}catch(S){throw S}}return{id:He,messages:Ie,status:Oe,error:Pt,sendMessage:Jn,stop:ht,addToolOutput:At,setMessages:Zn,conversations:ut,loadConversation:qt,deleteConversation:Qn,startNewConversation:mt,isLoadingConversations:ti,clientToken:Y,tokenError:oe,state:gn,setState:ot,isStateLoading:Wn,stateError:yn,pendingSecureInputs:Array.from(mn.values()),completeSecureInput:bn,pendingSecureForms:Array.from(qn.values()),completeSecureForm:As}}exports.verifyToken=zl.verifyToken;exports.ARCTEN_ORIGINAL_NAME=Qe;exports.ArctenAgent=tm;exports.SecureModalProvider=gl;exports.extractToolsMetadata=Qr;exports.preserveToolName=kf;exports.useAgent=bm;exports.useSecureModal=pl;
24
+ `,style:Ue?ie?{width:`${_e}px`,height:Ve?"auto":`${Bt}px`,left:`${ue.x}px`,top:`${ue.y}px`}:{width:`${_e}px`}:void 0,onClick:Ue?void 0:vl,children:Ue?c.jsxs(c.Fragment,{children:[!ie&&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:jl,children:c.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),ie&&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(),jt(!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(),zt(!0),Ct({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(),jt(!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 ${ie?"cursor-move":""}`,onMouseDown:ie?Al:void 0,children:[c.jsx("h2",{className:`text-base font-semibold ${ie&&Ve?"cursor-pointer":""}`,onClick:ie&&Ve?g=>{g.stopPropagation(),ri()}:void 0,children:r}),c.jsxs("div",{className:"flex items-center gap-1",onClick:g=>g.stopPropagation(),children:[c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Tl,"aria-label":"New chat",children:c.jsx(ne.Plus,{className:"h-4 w-4"})})}),c.jsx(bt,{children:"Start a new conversation"})]}),c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ie?Pl:Cl,"aria-label":ie?"Dock sidebar":"Float sidebar",children:ie?c.jsx(ne.Dock,{className:"h-4 w-4"}):c.jsx(ne.PictureInPicture2,{className:"h-4 w-4"})})}),c.jsx(bt,{children:ie?"Dock to sidebar":"Undock to floating window"})]}),c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ie?ri:wl,"aria-label":ie?Ve?"Maximize":"Minimize":"Close sidebar",children:ie?Ve?c.jsx(ne.Maximize2,{className:"h-4 w-4"}):c.jsx(ne.Minimize2,{className:"h-4 w-4"}):c.jsx(ne.X,{className:"h-4 w-4"})})}),c.jsx(bt,{children:ie?Ve?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ve&&c.jsxs(c.Fragment,{children:[k&&Ie.length>0&&c.jsxs("div",{className:`border-b border-border ${ht?"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:()=>{ht||Q(),ft(!ht)},children:ht?"Show less":"View all"})]}),c.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ht?"flex-1 overflow-y-auto":""}`,children:Ie.slice(0,ht?void 0:3).map(g=>c.jsxs("div",{className:"group relative",children:[c.jsxs(Pf,{type:"button",className:re(Dt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>jn(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:ae(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(),kt(g._id)},"aria-label":"Delete conversation",children:c.jsx(ne.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:Ne.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:[(Tn?De:De.slice(0,10)).map(g=>c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{bn(g.sampleUsage),Xe.current?.focus()},children:g.friendlyName})}),c.jsx(bt,{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&&!Tn&&c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsxs(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Sn(!0),children:["+",De.length-10," more"]})}),c.jsx(bt,{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"})]})})]}),Tn&&De.length>10&&c.jsx(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Sn(!1),children:"Show less"})]})})]}):c.jsxs(c.Fragment,{children:[Ne.map(g=>{const R=g.parts.filter(_=>_.type==="text").map(_=>_.text).join("");let B=g.parts;g.role==="assistant"&&g.parts.some(H=>H.timestamp)&&(B=[...g.parts].sort((H,q)=>{const be=H.timestamp||0,me=q.timestamp||0;return be-me}));let O=[],U=new Map,ee=[],Z,te=!0;if(g.role==="assistant"){const _=B.filter(me=>me.type==="text"&&me.text),H=[],q=[];_.forEach(me=>{const{citations:pt,citationMap:Pe,groupedCitations:$e,referencesText:gt}=Co(me.text);O.push(...pt),H.push(Pe),$e&&q.push(...$e),gt&&(Z=gt)}),H.forEach(me=>{me.forEach((pt,Pe)=>{U.has(Pe)||U.set(Pe,pt)})}),ee=Array.from(new Map(q.map(me=>[me.url,me])).values()).sort((me,pt)=>(me.numbers[0]||0)-(pt.numbers[0]||0)),te=!(Re==="streaming"&&g.id===Ne.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(Af,{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:R}):c.jsx("div",{className:"space-y-2",children:B.map((_,H)=>{if(_.type?.startsWith("tool-")){const q=_.type?.replace("tool-","")||"",be=W.find(Pe=>Pe.name===q),me=_.state==="input-available",pt=_.state==="output-available";if(me&&pe.has(q),me){if(pe.has(q))return null;const Pe=Ws(_.input);return c.jsx(ls,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:c.jsx(Ef,{toolName:q,description:be?.description||"",args:Pe,onApprove:async()=>{if(We.has(_.toolCallId))return;Me(gt=>new Set(gt).add(_.toolCallId));const $e=J.get(q);if($e)try{const gt=await $e(...Object.values(Pe));Mt({toolCallId:_.toolCallId,tool:q,output:gt})}catch(gt){Mt({toolCallId:_.toolCallId,tool:q,output:`Error: ${gt}`})}},onDeny:async()=>{We.has(_.toolCallId)||(Me($e=>new Set($e).add(_.toolCallId)),Mt({toolCallId:_.toolCallId,tool:q,output:"User denied tool execution"}))}})},`${_.toolCallId}-${H}`)}else if(pt){const Pe=_.output==="User denied tool execution",$e=Ws(_.input);return c.jsx(Df,{toolName:q,args:$e,isDenied:Pe,isSafe:pe.has(q)},`${_.toolCallId}-${H}`)}return null}if(_.type==="text"&&_.text&&Kn){const{processedText:q}=Co(_.text),Pe=!B.slice(H+1).some($e=>$e.type==="text"&&$e.text)&&te&&U.size>0;return c.jsx(Xf,{text:q,citations:O,citationMap:U,groupedCitations:Pe?ee:void 0,referencesText:Pe?Z:void 0,ResponseComponent:Kn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:D,showReferences:Pe},`${g.id}-${H}`)}return _.type==="reasoning"&&_.text?c.jsxs(dl,{className:"w-full",isStreaming:Re==="streaming"&&H===g.parts.length-1&&g.id===Ne.at(-1)?.id,children:[c.jsx(hl,{}),c.jsx(fl,{children:_.text})]},`${g.id}-${H}`):null})})})},g.id)}),c.jsx("div",{ref:rt})]})}),ts&&c.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",ts.message]}),c.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[c.jsx(Ku,{mode:"wait",children:(Re==="streaming"||Re==="submitted")&&c.jsxs(ls,{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(ls,{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:vn})]})}),c.jsxs("form",{onSubmit:si,className:"relative",children:[c.jsx(Mo,{ref:Xe,value:_t,onChange:Sl,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(),si(g))}}),Re==="streaming"||Re==="submitted"?c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:ns,children:c.jsx(ne.Square,{className:"h-4 w-4"})})}),c.jsxs(bt,{children:[c.jsx(ai,{children:"Escape"})," to stop"]})]}):c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"submit",className:re(Dt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!_t.trim(),children:c.jsx(ne.ArrowRight,{className:"h-4 w-4"})})}),c.jsxs(bt,{children:[c.jsx(ai,{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(ne.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 tm(e){return c.jsx(gl,{children:c.jsx(em,{...e})})}const nm={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 kn(e){for(const[t,n]of Object.entries(nm))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function sm(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 rm(e,t,n){return t.length>0}function im(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=om(s[i]),d={name:i,type:am(l||kn(i)||"text"),label:yl(i),placeholder:lm(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:rm(e,t),fields:r,title:cm(e),description:um(e,r.length)}}function om(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function am(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 lm(e,t){return t?sm(t,e).placeholder:`Enter ${yl(e).toLowerCase()}...`}function cm(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function um(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 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 dm(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 hm(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):{}}const ms="__secureOutput",ps="[hidden for privacy]";function fm(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 mm(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function pm(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 gm(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 pr(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]=pr(r),r&&typeof r=="object"&&Object.assign(n,xl(r,o))}):t&&(n[t]=pr(e)),n}function ym(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:ps,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:ps,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??ps,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function xm(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=ym(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[ms]=r,l}if(n.fields.includes("*"))return bl(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[ms]:{...r,redactedFields:n.fields}};const o=fm(t),i=[],a={};return n.fields.forEach(l=>{const u=mm(l);if(u.length===0)return;const d=pm(o,u),h=pr(d);a[l]=h,gm(o,u,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[ms]=r,o}function bm({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="",agentId:w,agentName:b,initialMessages:j=[],conversationId:y,state:k,onStateChange:v,allowStateEdits:E=!0,onToolCall:N,onFinish:$,sources:L,ragConfig:D,ragFilters:z,secureInputHandler:A}={}){const M=f.useMemo(()=>D!==void 0?D:z?{enabled:!0,filters:z}:L&&L.length>0?{enabled:!0,organizationId:L[0],autoExecute:!0,filters:void 0}:{enabled:!1},[L,D,z]),I=f.useMemo(()=>{const x={};if(l)for(const[T,S]of Object.entries(l))if(x[T]={},Array.isArray(S))for(const C of S){const V=kn(C);x[T][C]=V||"text"}else for(const[C,V]of Object.entries(S))x[T][C]=V;if(a){for(const[T,S]of Object.entries(a))if(S&&typeof S=="object"&&"sensitiveParams"in S){x[T]||(x[T]={});const C=S.sensitiveParams;if(Array.isArray(C))for(const V of C){const W=kn(V);x[T][V]=W||"text"}else if(C&&typeof C=="object")for(const[V,W]of Object.entries(C))x[T][V]=W}}return x},[l,a,d]),F=f.useMemo(()=>xm(u),[u]),K=f.useCallback((x,T)=>{const S=F[x];if(!S)return T;try{return bl(x,T,S)}catch(C){return console.error(`[useAgent] Failed to redact output for ${x}:`,C),{value:ps,[ms]:{tool:x,redacted:!0,error:String(C)}}}},[F]),[Y,le]=f.useState(n||null),X=f.useRef(n||null),[oe,we]=f.useState(null),[Te,se]=f.useState(null),tt=f.useRef(null),[ut,ke]=f.useState([]),[He,Lt]=f.useState(y||(typeof window<"u"?crypto.randomUUID():null)),[ti,nt]=f.useState(!1),[st,Ue]=f.useState(new Set),[mn,_e]=f.useState(new Map),[Ft,Bt]=f.useState(new Map),[Wn,pn]=f.useState(new Map),[jt,ie]=f.useState(new Map),ce=k!==void 0,[Ve,Je]=f.useState({}),ue=f.useRef({}),gn=ce?k||{}:Ve;ce&&k?ue.current=k:ce||(ue.current=Ve);const[qn,zt]=f.useState(!1),[yn,Ct]=f.useState(null),Ut=f.useRef(!1),xn=f.useCallback(async(x,T=3)=>{if(!He||!X.current)return;const S=async()=>{const V=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,W=await fetch(V,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:He,updates:x},format:"json"})});if(!W.ok){if(W.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const J=await W.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${W.status} ${J}`)}};for(let C=0;C<T;C++)try{await S(),Ct(null);return}catch(V){if(C===T-1){const J=V instanceof Error?V:new Error(String(V));throw Ct(J),console.error("Failed to sync state to Convex after retries:",V),J}await new Promise(J=>setTimeout(J,Math.pow(2,C)*100))}},[He,e,X]),rt=f.useMemo(()=>function(){return ue.current},[]),Xe=f.useMemo(()=>async function(T){const S={...ue.current,...T};ue.current=S,ce||Je(S),v&&v(S);try{await xn(T)}catch(C){throw C}},[xn,v,ce]);f.useEffect(()=>{ce&&k&&(ue.current=k)},[ce,k]);const _t=f.useCallback(x=>A?A.showSecureModal(x):new Promise(T=>{_e(S=>new Map(S).set(x.id,x)),Bt(S=>new Map(S).set(x.id,T))}),[A]),bn=f.useCallback((x,T)=>{if(A)return;const S=Ft.get(x);S&&(S(T),_e(C=>{const V=new Map(C);return V.delete(x),V}),Bt(C=>{const V=new Map(C);return V.delete(x),V}))},[Ft,A]),Kn=f.useCallback(x=>A?A.showSecureForm(x):new Promise(T=>{pn(S=>new Map(S).set(x.id,x)),ie(S=>new Map(S).set(x.id,T))}),[A]),As=f.useCallback((x,T)=>{if(A)return;const S=jt.get(x);S&&(S(T),pn(C=>{const V=new Map(C);return V.delete(x),V}),ie(C=>{const V=new Map(C);return V.delete(x),V}))},[jt,A]),vn=f.useCallback((x,T)=>{const S=I[x]||{},C=Object.keys(S).length>0;if(d){const V=Object.keys(T).filter(W=>kn(W)!==null);return C||V.length>0}return C},[I,d]),Gn=f.useCallback((x,T)=>{const C={...I[x]||{}};if(d){for(const W of Object.keys(T))if(!(W in C)){const J=kn(W);J&&(C[W]=J)}}const V=Object.entries(C).filter(([W])=>Object.prototype.hasOwnProperty.call(T,W));return V.length>0?Object.fromEntries(V):C},[I,d]),We=f.useMemo(()=>M?.enabled?async function(T,S=20,C){const V={...M.filters,...C};if(L&&L.length>1){const J=L.map(Q=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...X.current?{Authorization:`Bearer ${X.current}`}:{}},body:JSON.stringify({q:T,k:Math.min(S,100),organizationId:Q,...Object.keys(V).length>0?{filters:V}:{}})}).then(ae=>ae.ok?ae.json():null)),pe=await Promise.all(J),ye=[];for(const Q of pe)Q?.candidates&&ye.push(...Q.candidates);ye.sort((Q,ae)=>{const Ze=Q.scores?.rerank||Q.scores?.dense||0;return(ae.scores?.rerank||ae.scores?.dense||0)-Ze});const xe=ye.slice(0,S).map((Q,ae)=>{const Ze=Q.citation||Q.url;return{rank:ae+1,doc_id:Q.doc_id,block_id:Q.block_id,url:Q.url,citation:Ze,title:Q.title||"Untitled",snippet:Q.snippet,score:Q.scores?.rerank||Q.scores?.dense||0,metadata:{site:Q.metadata?.site,lang:Q.metadata?.lang,contentType:Q.metadata?.content_type}}});return{success:!0,query:T,total:ye.length,results:xe,summary:`Found ${ye.length} relevant results across ${L.length} source(s) for "${T}". Top result: ${xe[0]?.title||"N/A"}`}}const W=M.organizationId&&M.organizationId!=="default"?M.organizationId:L&&L.length>0?L[0]:void 0;try{const J={q:T,k:Math.min(S,100)};W&&(J.organizationId=W),Object.keys(V).length>0&&(J.filters=V);const pe={"Content-Type":"application/json"};X.current&&(pe.Authorization=`Bearer ${X.current}`);const ye=await fetch(`${e}/search`,{method:"POST",headers:pe,body:JSON.stringify(J)});if(!ye.ok){const ae=await ye.text();return{success:!1,error:`Search failed: ${ye.status} ${ae}`}}const xe=await ye.json(),Q=xe.candidates.map((ae,Ze)=>{const kt=ae.citation||ae.url;return{rank:Ze+1,doc_id:ae.doc_id,block_id:ae.block_id,url:ae.url,citation:kt,title:ae.title||"Untitled",snippet:ae.snippet,score:ae.scores?.rerank||ae.scores?.dense||0,metadata:{site:ae.metadata?.site,lang:ae.metadata?.lang,contentType:ae.metadata?.content_type}}});return{success:!0,query:xe.query,total:xe.total,results:Q,summary:`Found ${xe.total} relevant results for "${T}". Top result: ${Q[0]?.title||"N/A"}`}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Unknown error occurred"}}}:null,[M,e,X]),Me=f.useMemo(()=>M?.enabled?async function(T,S){const C=M.organizationId&&M.organizationId!=="default"?M.organizationId:L&&L.length>0?L[0]:void 0;try{const V={"Content-Type":"application/json"};X.current&&(V.Authorization=`Bearer ${X.current}`);const W=await fetch(`${e}/fetch`,{method:"POST",headers:V,body:JSON.stringify({doc_id:T,block_ids:S,...C?{organizationId:C}:{}})});if(!W.ok){const pe=await W.text();return{success:!1,error:`Fetch failed: ${W.status} ${pe}`}}const J=await W.json();return{success:!0,blocks:J.blocks||[],fullContent:J.fullContent||"",pageUrl:J.pageUrl||"",pageTitle:J.pageTitle||"",summary:`Fetched ${J.blocks?.length||0} blocks from ${J.pageTitle||T}`}}catch(V){return{success:!1,error:V instanceof Error?V.message:"Unknown error occurred"}}}:null,[M,e,X]),Xt=f.useMemo(()=>{const x=[...o,...i,rt];return(!ce||E)&&x.push(Xe),M?.enabled&&(We&&x.push(We),Me&&x.push(Me)),x},[o,i,rt,Xe,We,Me,M,ce,E]),it=f.useMemo(()=>Qr(Xt,a),[Xt,a]),De=f.useMemo(()=>{const x=new Map,T=new Map(it.map(S=>[S.name,S]));return x.set("getState",rt),(!ce||E)&&x.set("setState",Xe),M?.enabled&&(We&&x.set("searchDocs",We),Me&&x.set("fetchDocContent",Me)),Xt.forEach(S=>{if(S===rt||S===Xe||S===We||S===Me)return;const C=S[Qe];if(C){const W=T.get(C);if(W){x.set(W.name,S);return}}const V=it.find(W=>W.name===S.name);V&&x.set(V.name,S)}),x},[Xt,it,rt,Xe,We,Me,M,ce,E]),Yn=f.useMemo(()=>new Set(it.map(x=>x.name)),[it]),Hn=f.useMemo(()=>{const x=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!ce||E)&&x.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 T=[];return M?.enabled&&T.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...it,...x,...T]},[it,M,ce,E]),dt=f.useMemo(()=>Hn.filter(x=>x.name==="getState"?!0:x.name==="setState"?!ce||E:M?.enabled&&(x.name==="searchDocs"||x.name==="fetchDocContent")?!0:Yn.has(x.name)),[Hn,Yn,ce,E,M]),wn=f.useMemo(()=>{const x=new Set;return x.add("getState"),x.add("setState"),M?.enabled&&M.autoExecute!==!1&&(x.add("searchDocs"),x.add("fetchDocContent")),i.forEach(T=>{for(const[S,C]of De.entries())if(C===T){x.add(S);break}}),x},[i,De,M]);f.useEffect(()=>s||n?void 0:((async()=>{try{const T=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!T.ok)throw new Error("Failed to fetch token");const S=await T.json();le(S.clientToken),X.current=S.clientToken,se(S.expiresAt),we(null)}catch(T){console.error("[useAgent] Token fetch failed:",T),we(T instanceof Error?T.message:"Failed to fetch token")}})(),()=>{tt.current&&clearTimeout(tt.current)}),[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!Te||s||n)return;tt.current&&clearTimeout(tt.current);const x=Math.floor(Date.now()/1e3),T=Te-x,C=Math.max(0,T-5);return tt.current=setTimeout(async()=>{try{const V=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!V.ok)throw new Error("Failed to refresh token");const W=await V.json();le(W.clientToken),X.current=W.clientToken,se(W.expiresAt),we(null)}catch(V){console.error("[useAgent] Token refresh failed:",V),we(V instanceof Error?V.message:"Failed to refresh token")}},C*1e3),()=>{tt.current&&clearTimeout(tt.current)}},[Te,t,JSON.stringify(r),s,n]);const Tn=async(x,T={})=>{const S=T.headers?new Headers(T.headers):new Headers;S.delete("user-agent"),S.delete("User-Agent"),console.log("[useAgent] Making request to:",x),console.log("[useAgent] Method:",T.method||"GET"),console.log("[useAgent] Has Authorization header:",S.has("Authorization")),console.log("[useAgent] Client token available:",!!X.current);try{const C=await fetch(x,{...T,headers:S});if(!C.ok){console.error("[useAgent] Request failed:",C.status,C.statusText);const V=await C.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",V)}return C}catch(C){throw console.error("[useAgent] Fetch error:",C),C}},Sn=`${e}/chat`;console.log("[useAgent] Chat API URL:",Sn);const{messages:Ie,sendMessage:Jn,status:Oe,error:Pt,stop:ht,addToolResult:ft,setMessages:Zn}=Po.useChat({id:He||void 0,messages:j,transport:new gs.DefaultChatTransport({api:Sn,fetch:Tn,headers:()=>{const x={};return X.current?(x.Authorization=`Bearer ${X.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),x},body:()=>{console.log("[ArctenAgent] body() agentName =",b);const x=dt.map(C=>({name:C.name,description:C.description,inputSchema:C.jsonSchema})),T=x.filter(C=>C.name==="getState"||C.name==="setState").map(C=>C.name),S=x.filter(C=>C.name==="searchDocs"||C.name==="fetchDocContent").map(C=>C.name);return T.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",T),S.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",S):M?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:x,...w&&{agentId:w},...b&&{agentName:b},state:ue.current,...z&&{ragFilters:z}}}}),sendAutomaticallyWhen:gs.lastAssistantMessageIsCompleteWithToolCalls}),qe=f.useCallback((x,T,S)=>{const C=K(x,S);ft({toolCallId:T,tool:x,output:C})},[ft,K]);f.useEffect(()=>{Ie.forEach(x=>{x.role==="assistant"&&x.parts.forEach(T=>{if(!T.type?.startsWith("tool-")||T.state!=="input-available")return;const S=T.type.replace("tool-",""),C=T.toolCallId;if(st.has(C))return;Ue(W=>new Set(W).add(C));const V=hm(T.input);if(vn(S,V)){const W=Gn(S,V),J=Object.entries(W).filter(([Q])=>V[Q]!==void 0),pe=J.length>0?Object.fromEntries(J):W,ye=Object.keys(V),xe=dm(V,pe);(async()=>{try{const Q=im(S,ye,pe,V),ae={id:`${C}-form`,toolName:S,toolCallId:C,title:Q.title,description:Q.description,fields:Q.fields},Ze=await Kn(ae);if(Ze===null){qe(S,C,"User cancelled secure input");return}const kt={...xe,...Ze},jn=De.get(S);if(!jn)throw new Error(`Tool ${S} not found`);let Cn;const Ne=dt.find(es=>es.name===S);if(Ne&&Ne.jsonSchema?.properties){const Re=Object.keys(Ne.jsonSchema.properties).map(ts=>kt[ts]);Cn=await jn(...Re)}else Cn=await jn(...Object.values(kt));qe(S,C,Cn)}catch(Q){console.error(`[useAgent] Error executing tool with secure input ${S}:`,Q),qe(S,C,`Error: ${Q}`)}})();return}if(wn.has(S)&&!vn(S,V)){const W=De.get(S);W?(async()=>{try{const J=dt.find(ye=>ye.name===S);let pe;if(J&&J.jsonSchema?.properties){const xe=Object.keys(J.jsonSchema.properties).map(Q=>V[Q]);pe=await W(...xe)}else if(S==="getState")pe=W();else if(S==="setState"){const ye=V.updates||V;pe=await W(ye)}else pe=await W(...Object.values(V));qe(S,C,pe)}catch(J){console.error(`[useAgent] Error executing tool ${S}:`,J),qe(S,C,`Error: ${J}`)}})():console.warn(`[useAgent] Tool ${S} not found in toolsMap`)}else N&&N({toolCall:{toolCallId:C,toolName:S,args:V}})})})},[Ie,wn,De,N,qe,st,Xe,dt,vn,Gn,_t]),f.useEffect(()=>{if(Oe==="ready"&&Ie.length>0&&$){const x=Ie[Ie.length-1];x&&x.role==="assistant"&&$({message:x,messages:Ie,isAbort:!1,isDisconnect:!1,isError:!!Pt})}},[Oe,Ie,Pt,$]);async function ni(){if(!(!r?.id||!Y)){nt(!0);try{const T=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${Y}`}})).json();ke(T.conversations||[])}catch(x){console.error("Failed to fetch conversations:",x)}finally{nt(!1)}}}f.useEffect(()=>{r?.id&&Y&&ni()},[JSON.stringify(r),Y,e]),f.useEffect(()=>{if(!He||!X.current)return;(async()=>{zt(!0),Ct(null);try{const T=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:He},format:"json"})});if(!T.ok){const V=await T.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${T.status} ${V}`)}const C=(await T.json())?.value||{};ue.current=C,ce||Je(C),v&&v(C),Ut.current=!0}catch(T){console.error("Failed to fetch state:",T);const S=T instanceof Error?T:new Error(String(T));Ct(S),Ut.current||(ue.current={},ce?v&&v({}):(Je({}),v&&v({})),Ut.current=!0)}finally{zt(!1)}})()},[He,e,ce,v]);async function Wt(x){Lt(x),nt(!0);try{const T=await fetch(`${e}/conversations/${x}/messages`,{headers:{Authorization:`Bearer ${X.current}`}});if(!T.ok)throw new Error(`Failed to fetch messages: ${T.statusText}`);const C=(await T.json()).messages||[];Zn(C)}catch(T){console.error("Failed to load conversation messages:",T)}finally{nt(!1)}}async function Qn(x){if(Y)try{await fetch(`${e}/conversations/${x}`,{method:"DELETE",headers:{Authorization:`Bearer ${Y}`}}),ke(ut.filter(T=>T._id!==x)),x===He&&mt()}catch(T){console.error("Failed to delete conversation:",T)}}function mt(){const x=crypto.randomUUID();Lt(x),Zn([]),Ue(new Set),ue.current={},ce?v&&v({}):(Je({}),v&&v({})),Ut.current=!1}function At(x){const T=x.tool||"unknown-tool",S=K(T,x.output);ft({toolCallId:x.toolCallId,tool:T,output:S})}async function ot(x){const T={...ue.current,...x};ue.current=T,ce||Je(T),v&&v(T);try{await xn(x)}catch(S){throw S}}return{id:He,messages:Ie,status:Oe,error:Pt,sendMessage:Jn,stop:ht,addToolOutput:At,setMessages:Zn,conversations:ut,loadConversation:Wt,deleteConversation:Qn,startNewConversation:mt,isLoadingConversations:ti,clientToken:Y,tokenError:oe,state:gn,setState:ot,isStateLoading:qn,stateError:yn,pendingSecureInputs:Array.from(mn.values()),completeSecureInput:bn,pendingSecureForms:Array.from(Wn.values()),completeSecureForm:As}}exports.verifyToken=zl.verifyToken;exports.ARCTEN_ORIGINAL_NAME=Qe;exports.ArctenAgent=tm;exports.SecureModalProvider=gl;exports.extractToolsMetadata=Qr;exports.preserveToolName=kf;exports.useAgent=bm;exports.useSecureModal=pl;