@arcteninc/core 0.0.174 → 0.0.175

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,7 +1,5 @@
1
- "use strict";var il=Object.create;var Ur=Object.defineProperty;var ol=Object.getOwnPropertyDescriptor;var al=Object.getOwnPropertyNames;var ll=Object.getPrototypeOf,cl=Object.prototype.hasOwnProperty;var ul=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of al(t))!cl.call(e,r)&&r!==n&&Ur(e,r,{get:()=>t[r],enumerable:!(s=ol(t,r))||s.enumerable});return e};var dl=(e,t,n)=>(n=e!=null?il(ll(e)):{},ul(t||!e||!e.__esModule?Ur(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),f=require("react"),Z=require("lucide-react"),hl=require("@ai-sdk/react"),zr=require("ai"),lo=require("@radix-ui/react-slot"),co=require("class-variance-authority"),fl=require("clsx"),ml=require("tailwind-merge"),pl=require("@radix-ui/react-tooltip"),_r=require("@radix-ui/react-use-controllable-state"),gl=require("@radix-ui/react-collapsible"),yl=require("react-dom"),xl=require("@radix-ui/react-dialog");function Zn(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 Ie=Zn(f),Ot=Zn(pl),er=Zn(gl),vt=Zn(xl),Me=Symbol.for("@arcteninc/core:originalName");function bl(e,t){return e[Me]=t,e}function vl(e,t,n,s){if(typeof e!="function")return null;const r=e[Me];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[Me]=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[Me]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(l=>!n.has(l.name)),i)return e[Me]=i.name,{fn:e,meta:i};return null}function tr(e,t){if(!t)return[];let n,s;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=vl(o,n,r,s);if(!i){const a=o.name,c=o[Me]||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 "${c}". This tool will be excluded.
2
- To fix: Run "arcten-extract-types ." and ensure "${c}" 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)}const wl={password:[/^password$/i,/^pwd$/i,/^pass$/i,/^newPassword$/i,/^oldPassword$/i,/^currentPassword$/i,/^confirmPassword$/i,/.*password.*/i],email:[/^email$/i,/^emailAddress$/i,/^mail$/i,/.*email.*/i],phone:[/^phone$/i,/^phoneNumber$/i,/^mobile$/i,/^cell$/i,/^cellPhone$/i,/^telephone$/i,/.*phone.*/i,/.*mobile.*/i],pin:[/^pin$/i,/^pinCode$/i,/^securityPin$/i,/^accessPin$/i,/.*pin$/i],ssn:[/^ssn$/i,/^socialSecurityNumber$/i,/^social$/i,/.*ssn.*/i,/.*social.*/i],creditCard:[/^creditCard$/i,/^cardNumber$/i,/^card$/i,/^ccNumber$/i,/^creditCardNumber$/i,/.*card.*/i,/^cvv$/i,/^cvc$/i,/^cvn$/i,/^securityCode$/i],text:[]};function an(e){for(const[t,n]of Object.entries(wl))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function Sl(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 Tl(e,t,n){return t.length>0}function Cl(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 c=jl(s[i]),d={name:i,type:Pl(l||an(i)||"text"),label:uo(i),placeholder:Al(i,l),required:!0,value:c};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,c=a.name in n;return l===c?0:l?1:-1}),{shouldUseForm:Tl(e,t),fields:r,title:El(e),description:Ml(e,r.length)}}function jl(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function Pl(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 uo(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Al(e,t){return t?Sl(t,e).placeholder:`Enter ${uo(e).toLowerCase()}...`}function El(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Ml(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 cn(e){if(typeof e=="string")try{const t=JSON.parse(e);return cn(t)}catch{return e}if(Array.isArray(e))return e.map(cn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=cn(s);return t}return e}function kl(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 Nl(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return cn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?cn(e):{}}const Bn="__secureOutput",Un="[hidden for privacy]";function Rl(e,t){if(!e||e.length===0)return t;const n=new Map;t.forEach(o=>{const i=o[Me]||o.name;i&&n.set(i,o)});const s=new Map(e.map(o=>[o.name,o])),r=[];return e.forEach(o=>{const i=n.get(o.name);if(!i){console.log(`[useAgent] Skipping server-only tool: ${o.name}`);return}if(!o.isEnabled&&!o.isOverridable){console.log(`[useAgent] Blocking non-overridable disabled tool: ${o.name}`);return}if(!o.isEnabled&&o.isOverridable&&i){console.log(`[useAgent] Allowing overridable disabled tool with local implementation: ${o.name}`),r.push(i);return}o.isEnabled&&i&&r.push(i)}),t.forEach(o=>{const i=o[Me]||o.name;i&&!s.has(i)&&(console.log(`[useAgent] Allowing client-only tool (forward compatible): ${i}`),r.push(o))}),r}function Dl(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 Vl(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function Il(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 Ol(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 ks(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 ho(e,t=""){const n={};return e&&typeof e=="object"?Object.entries(e).forEach(([s,r])=>{const o=t?`${t}.${s}`:s;n[o]=ks(r),r&&typeof r=="object"&&Object.assign(n,ho(r,o))}):t&&(n[t]=ks(e)),n}function $l(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:Un,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:Un,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??Un,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function Ll(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=$l(s);r&&(t[n]=r)}return t}function fo(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=ho(t)),r.redactedFields=["*"];let l={};return n.preserve.length>0&&t&&typeof t=="object"&&n.preserve.forEach(c=>{c in t&&(l[c]=t[c])}),l[Bn]=r,l}if(n.fields.includes("*"))return fo(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[Bn]:{...r,redactedFields:n.fields}};const o=Dl(t),i=[],a={};return n.fields.forEach(l=>{const c=Vl(l);if(c.length===0)return;const d=Il(o,c),h=ks(d);a[l]=h,Ol(o,c,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[Bn]=r,o}function mo({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],safeToolNames:a,toolMetadata:l,sensitiveParams:c,sensitiveOutputs:d,autoDetectSensitive:h=!1,autoFormGeneration:m=!1,formMode:p="auto",systemPrompt:v="",agentId:w,agentName:T,projectId:S,enableRemoteConfig:k,remoteConfigUrl:E,initialMessages:U=[],conversationId:D,state:$,onToolCall:F,onFinish:M,sources:R,ragConfig:A,ragFilters:V,secureInputHandler:L}={}){const I=e.replace(/\/+$/,""),[B,H]=f.useState(null),[te,G]=f.useState(!1),[ee,de]=f.useState(null),xe=f.useMemo(()=>{const g=R||[],x=B?.config?.sources||[];return[...new Set([...g,...x])]},[R,B]),oe=f.useMemo(()=>A!==void 0?A:V?{enabled:!0,filters:V}:xe&&xe.length>0?{enabled:!0,organizationId:xe[0],autoExecute:!0,filters:void 0}:{enabled:!1},[xe,A,V]),rt=f.useMemo(()=>k===!1?!1:!!S,[S,k]);f.useEffect(()=>{if(!rt||!le.current)return;(async()=>{G(!0),de(null);try{const y=`${E||I.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,b=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${le.current}`},body:JSON.stringify({path:"agents:getConfigForClient",args:{projectId:S,agentName:T,agentId:w},format:"json"})});if(!b.ok){if(b.status===404){console.warn("[useAgent] Remote config endpoint not found (404), using local tools only"),H(null);return}const P=await b.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch remote config: ${b.status} ${P}`)}const j=await b.json();H(j?.value||null),console.log("[useAgent] Remote config loaded successfully:",j?.value)}catch(x){console.error("[useAgent] Failed to fetch remote config:",x);const y=x instanceof Error?x:new Error(String(x));de(y),H(null)}finally{G(!1)}})()},[rt,S,T,w,I,E]);const J=f.useMemo(()=>{const g={};if(c)for(const[x,y]of Object.entries(c))if(g[x]={},Array.isArray(y))for(const b of y){const j=an(b);g[x][b]=j||"text"}else for(const[b,j]of Object.entries(y))g[x][b]=j;if(l){for(const[x,y]of Object.entries(l))if(y&&typeof y=="object"&&"sensitiveParams"in y){g[x]||(g[x]={});const b=y.sensitiveParams;if(Array.isArray(b))for(const j of b){const P=an(j);g[x][j]=P||"text"}else if(b&&typeof b=="object")for(const[j,P]of Object.entries(b))g[x][j]=P}}return g},[c,l,h]),wt=f.useMemo(()=>Ll(d),[d]),ve=f.useCallback((g,x)=>{const y=wt[g];if(!y)return x;try{return fo(g,x,y)}catch(b){return console.error(`[useAgent] Failed to redact output for ${g}:`,b),{value:Un,[Bn]:{tool:g,redacted:!0,error:String(b)}}}},[wt]),[Te,ge]=f.useState(n||null),le=f.useRef(n||null),[jn,Ue]=f.useState(null),[$e,St]=f.useState(null),ze=f.useRef(null),[Pn,Tt]=f.useState([]),[He,it]=f.useState(D||(typeof window<"u"?crypto.randomUUID():null)),[Jt,ot]=f.useState(!1),Ct=f.useRef(new Set),Zt=f.useRef(new Set),at=f.useRef(new Set),[jt,_e]=f.useState(new Map),[ss,An]=f.useState(new Map),[Xe,En]=f.useState(new Map),[Mn,Pt]=f.useState(new Map),At=f.useRef(void 0);f.useEffect(()=>{if($){const g=At.current,x=g===void 0,y=!x&&JSON.stringify(g)!==JSON.stringify($);(x||y)&&ht(b=>[...b,{id:crypto.randomUUID(),role:"system",content:x?`[Initial State]
3
- ${JSON.stringify($,null,2)}`:`[State Updated]
4
- ${JSON.stringify($,null,2)}`}]),At.current=$}},[$,ht]);const Qt=f.useCallback(g=>L?L.showSecureModal(g):new Promise(x=>{_e(y=>new Map(y).set(g.id,g)),An(y=>new Map(y).set(g.id,x))}),[L]),kn=f.useCallback((g,x)=>{if(L)return;const y=ss.get(g);y&&(y(x),_e(b=>{const j=new Map(b);return j.delete(g),j}),An(b=>{const j=new Map(b);return j.delete(g),j}))},[ss,L]),lt=f.useCallback(g=>L?L.showSecureForm(g):new Promise(x=>{En(y=>new Map(y).set(g.id,g)),Pt(y=>new Map(y).set(g.id,x))}),[L]),en=f.useCallback((g,x)=>{if(L)return;const y=Mn.get(g);y&&(y(x),En(b=>{const j=new Map(b);return j.delete(g),j}),Pt(b=>{const j=new Map(b);return j.delete(g),j}))},[Mn,L]),Ce=f.useCallback((g,x)=>{const y=J[g]||{},b=Object.keys(y).length>0;if(h){const j=Object.keys(x).filter(P=>an(P)!==null);return b||j.length>0}return b},[J,h]),je=f.useCallback((g,x)=>{const b={...J[g]||{}};if(h){for(const P of Object.keys(x))if(!(P in b)){const z=an(P);z&&(b[P]=z)}}const j=Object.entries(b).filter(([P])=>Object.prototype.hasOwnProperty.call(x,P));return j.length>0?Object.fromEntries(j):b},[J,h]),Re=f.useMemo(()=>oe?.enabled?async function(x,y=20,b){const j={...oe.filters,...b};if(R&&R.length>1){const z=R.map(X=>fetch(`${I}/search`,{method:"POST",headers:{"Content-Type":"application/json",...le.current?{Authorization:`Bearer ${le.current}`}:{}},body:JSON.stringify({q:x,k:Math.min(y,100),organizationId:X,...Object.keys(j).length>0?{filters:j}:{}})}).then(_=>_.ok?_.json():null)),N=await Promise.all(z),O=[];for(const X of N)X?.candidates&&O.push(...X.candidates);O.sort((X,_)=>{const Y=X.scores?.rerank||X.scores?.dense||0;return(_.scores?.rerank||_.scores?.dense||0)-Y});const W=O.slice(0,y).map((X,_)=>{const Y=X.citation||X.url;return{rank:_+1,doc_id:X.doc_id,block_id:X.block_id,url:X.url,citation:Y,title:X.title||"Untitled",snippet:X.snippet,score:X.scores?.rerank||X.scores?.dense||0,metadata:{site:X.metadata?.site,lang:X.metadata?.lang,contentType:X.metadata?.content_type}}});return{success:!0,query:x,total:O.length,results:W,summary:`Found ${O.length} relevant results across ${R.length} source(s) for "${x}". Top result: ${W[0]?.title||"N/A"}`}}const P=oe.organizationId&&oe.organizationId!=="default"?oe.organizationId:R&&R.length>0?R[0]:void 0;try{const z={q:x,k:Math.min(y,100)};P&&(z.organizationId=P),Object.keys(j).length>0&&(z.filters=j);const N={"Content-Type":"application/json"};le.current&&(N.Authorization=`Bearer ${le.current}`);const O=await fetch(`${I}/search`,{method:"POST",headers:N,body:JSON.stringify(z)});if(!O.ok){const _=await O.text();return{success:!1,error:`Search failed: ${O.status} ${_}`}}const W=await O.json(),X=W.candidates.map((_,Y)=>{const ie=_.citation||_.url;return{rank:Y+1,doc_id:_.doc_id,block_id:_.block_id,url:_.url,citation:ie,title:_.title||"Untitled",snippet:_.snippet,score:_.scores?.rerank||_.scores?.dense||0,metadata:{site:_.metadata?.site,lang:_.metadata?.lang,contentType:_.metadata?.content_type}}});return{success:!0,query:W.query,total:W.total,results:X,summary:`Found ${W.total} relevant results for "${x}". Top result: ${X[0]?.title||"N/A"}`}}catch(z){return{success:!1,error:z instanceof Error?z.message:"Unknown error occurred"}}}:null,[oe,I,le]),we=f.useMemo(()=>oe?.enabled?async function(x,y){const b=oe.organizationId&&oe.organizationId!=="default"?oe.organizationId:R&&R.length>0?R[0]:void 0;try{const j={"Content-Type":"application/json"};le.current&&(j.Authorization=`Bearer ${le.current}`);const P=await fetch(`${I}/fetch`,{method:"POST",headers:j,body:JSON.stringify({doc_id:x,block_ids:y,...b?{organizationId:b}:{}})});if(!P.ok){const N=await P.text();return{success:!1,error:`Fetch failed: ${P.status} ${N}`}}const z=await P.json();return{success:!0,blocks:z.blocks||[],fullContent:z.fullContent||"",pageUrl:z.pageUrl||"",pageTitle:z.pageTitle||"",summary:`Fetched ${z.blocks?.length||0} blocks from ${z.pageTitle||x}`}}catch(j){return{success:!1,error:j instanceof Error?j.message:"Unknown error occurred"}}}:null,[oe,I,le]),ct=f.useMemo(()=>{if(B&&B.config?.tools){const g=Rl(B.config.tools,o);return console.log("[useAgent] Merged remote config:",{remoteToolCount:B.config.tools.length,localToolCount:o.length,mergedToolCount:g.length}),g}return o},[B,o]),We=B?.enableRagTools??oe?.enabled??!1,Pe=f.useMemo(()=>{const g=[...ct,...i];return We&&(Re&&g.push(Re),we&&g.push(we)),g},[ct,i,Re,we,We]),Nn=f.useMemo(()=>[...ct,...i],[ct,i]),ue=f.useMemo(()=>tr(Nn,l),[Nn,l]),Ye=f.useMemo(()=>{const g=new Map,x=new Map(ue.map(y=>[y.name,y]));return oe?.enabled&&(Re&&g.set("searchDocs",Re),we&&g.set("fetchDocContent",we)),Pe.forEach(y=>{if(y===Re||y===we)return;const b=y[Me];if(b){const P=x.get(b);if(P){g.set(P.name,y);return}}const j=ue.find(P=>P.name===y.name);j&&g.set(j.name,y)}),g},[Pe,ue,Re,we,oe]),ut=f.useMemo(()=>new Set(ue.map(g=>g.name)),[ue]),Le=f.useMemo(()=>{const g=[];We&&g.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"]}});const x=[];return B?.config?.workflows&&B.config.workflows.forEach(y=>{const b={},j=[];y.parameters&&y.parameters.forEach(P=>{b[P.name]={type:P.type||"string",description:P.description},P.required&&j.push(P.name)}),x.push({name:`workflow_${y.name.replace(/\s+/g,"_").toLowerCase()}`,description:y.description||`Execute the "${y.name}" workflow. ${y.contentPlaintext?.slice(0,200)||""}`,jsonSchema:{type:"object",properties:b,required:j},_workflow:y})}),[...ue,...g,...x]},[ue,We,B]),dt=f.useMemo(()=>Le.filter(g=>g.name==="searchDocs"||g.name==="fetchDocContent"?We:g.name.startsWith("workflow_")?!0:ut.has(g.name)),[Le,ut,We]),Et=f.useMemo(()=>{const g=new Set;return We&&oe?.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent")),B?.config?.tools?B.config.tools.forEach(x=>{x.isEnabled&&!x.requiresApproval&&g.add(x.name)}):(i.forEach(x=>{for(const[y,b]of Ye.entries())if(b===x){g.add(y);break}}),a&&Array.isArray(a)&&a.forEach(x=>{typeof x=="string"&&g.add(x)})),B?.config?.workflows&&B.config.workflows.forEach(x=>{const y=`workflow_${x.name.replace(/\s+/g,"_").toLowerCase()}`;x.requiresApproval||g.add(y)}),g},[B,i,a,Ye,We,oe]);f.useEffect(()=>{if(s||n)return;let g=!1,x=null;const y=async(b=1,j=3)=>{if(!g)try{const P=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!P.ok)throw new Error("Failed to fetch token");const z=await P.json();g||(ge(z.clientToken),le.current=z.clientToken,St(z.expiresAt),Ue(null))}catch(P){if(console.error(`[useAgent] Token fetch failed (attempt ${b}/${j}):`,P),b<j&&!g){const z=Math.pow(2,b-1)*1e3;x=setTimeout(()=>y(b+1,j),z)}else g||Ue(P instanceof Error?P.message:"Failed to fetch token")}};return y(),()=>{g=!0,x&&clearTimeout(x),ze.current&&clearTimeout(ze.current)}},[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!$e||s||n)return;ze.current&&clearTimeout(ze.current);const g=async(P=1,z=3)=>{try{const N=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!N.ok)throw new Error("Failed to refresh token");const O=await N.json();ge(O.clientToken),le.current=O.clientToken,St(O.expiresAt),Ue(null)}catch(N){if(console.error(`[useAgent] Token refresh failed (attempt ${P}/${z}):`,N),P<z){const O=Math.pow(2,P-1)*1e3;setTimeout(()=>g(P+1,z),O)}else Ue(N instanceof Error?N.message:"Failed to refresh token")}},x=Math.floor(Date.now()/1e3),y=$e-x,j=Math.max(0,y-5);return ze.current=setTimeout(()=>g(),j*1e3),()=>{ze.current&&clearTimeout(ze.current)}},[$e,t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(s||n)return;const g=async()=>{if(document.visibilityState!=="visible")return;const x=Math.floor(Date.now()/1e3);if(!$e||$e<=x+5){console.log("[useAgent] Tab visible, token expired - refreshing");try{const b=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(b.ok){const j=await b.json();ge(j.clientToken),le.current=j.clientToken,St(j.expiresAt),Ue(null)}}catch(b){console.error("[useAgent] Token refresh on visibility change failed:",b)}}};return document.addEventListener("visibilitychange",g),()=>document.removeEventListener("visibilitychange",g)},[t,JSON.stringify(r),$e,s,n]);const Rn=async(g,x={})=>{const y=x.headers?new Headers(x.headers):new Headers;return y.delete("user-agent"),y.delete("User-Agent"),fetch(g,{...x,headers:y})},Mt=f.useRef(null),Fr=`${I}/chat`,{messages:Fe,sendMessage:rs,status:tn,error:nn,stop:is,addToolResult:sn,setMessages:ht}=hl.useChat({id:He||void 0,messages:U,transport:new zr.DefaultChatTransport({api:Fr,fetch:Rn,headers:()=>{const g={};return le.current&&(g.Authorization=`Bearer ${le.current}`),g},body:()=>({tools:dt.map(x=>({name:x.name,description:x.description,inputSchema:x.jsonSchema})),...w&&{agentId:w},...T&&{agentName:T},...V&&{ragFilters:V},...$&&{state:$}})}),sendAutomaticallyWhen:g=>{const x=g.messages;if(x[x.length-1]?.role!=="assistant")return!1;const j=[...x].reverse().find(z=>z.role==="user")?.id;if(j&&Mt.current===j)return!1;const P=zr.lastAssistantMessageIsCompleteWithToolCalls(g);return P&&j&&(Mt.current=j),P}}),rn=rs,os=f.useCallback(g=>(Mt.current=null,at.current=new Set,rn(g)),[rn]),Se=f.useCallback((g,x,y)=>{const b=ve(g,y);sn({toolCallId:x,tool:g,output:b})},[sn,ve]);f.useEffect(()=>{Fe.forEach(g=>{g.role==="assistant"&&g.parts.forEach(x=>{if(!x.type?.startsWith("tool-")||x.state!=="input-available")return;const y=x.type.replace("tool-",""),b=x.toolCallId;if(Ct.current.has(b)||Zt.current.has(b)){console.log(`[useAgent] Skipping ${y} (${b}) - already processing or completed`);return}console.log(`[useAgent] Starting ${y} (${b})`),Ct.current.add(b);const j=N=>{console.log(`[useAgent] Completed ${y} (${N})`),Zt.current.add(N),Ct.current.delete(N)},P=Nl(x.input),z=`${y}:${JSON.stringify(P)}`;if(at.current.has(z)){console.log(`[useAgent] Skipping duplicate tool call: ${z}`),Se(y,b,"This tool was already called successfully with the same arguments in this response. Using previous result."),j(b);return}if(Ce(y,P)){const N=je(y,P),O=Object.entries(N).filter(([Y])=>P[Y]!==void 0),W=O.length>0?Object.fromEntries(O):N,X=Object.keys(P),_=kl(P,W);(async()=>{try{const Y=Cl(y,X,W,P),ie={id:`${b}-form`,toolName:y,toolCallId:b,title:Y.title,description:Y.description,fields:Y.fields},he=await lt(ie);if(he===null){Se(y,b,"User cancelled secure input"),j(b);return}const De={..._,...he},cs=Ye.get(y);if(!cs)throw new Error(`Tool ${y} not found`);let us;const ds=dt.find(Br=>Br.name===y);if(ds&&ds.jsonSchema?.properties){const sl=Object.keys(ds.jsonSchema.properties).map(rl=>De[rl]);us=await cs(...sl)}else us=await cs(...Object.values(De));j(b),Se(y,b,us),at.current.add(z)}catch(Y){console.error(`[useAgent] Error executing tool with secure input ${y}:`,Y),j(b),Se(y,b,`Error: ${Y}`)}})();return}if(y.startsWith("workflow_")&&Et.has(y)){(async()=>{try{const O=dt.find(X=>X.name===y)?._workflow;if(!O)throw new Error(`Workflow metadata not found for ${y}`);let W;if(O.webhook?.url){let X=P;if(O.webhook.bodyTemplate){let Y=O.webhook.bodyTemplate;Object.entries(P).forEach(([ie,he])=>{Y=Y.replace(new RegExp(`\\{\\{${ie}\\}\\}`,"g"),String(he))}),X=JSON.parse(Y)}const _=await fetch(O.webhook.url,{method:O.webhook.method||"POST",headers:{"Content-Type":"application/json",...O.webhook.headers||{}},body:JSON.stringify(X)});if(_.ok)W={success:!0,data:await _.json().catch(()=>({success:!0}))};else{const Y=await _.text();W={success:!1,error:`Webhook failed: ${_.status} ${Y}`}}}else W={success:!0,message:`Workflow "${O.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:O.contentPlaintext};j(b),Se(y,b,W),at.current.add(z)}catch(N){console.error(`[useAgent] Error executing workflow ${y}:`,N),j(b),Se(y,b,`Error: ${N}`)}})();return}if(Et.has(y)&&!Ce(y,P)){const N=Ye.get(y);N?(async()=>{try{const O=dt.find(X=>X.name===y);let W;if(O&&O.jsonSchema?.properties){const _=Object.keys(O.jsonSchema.properties).map(Y=>P[Y]);W=await N(..._)}else W=await N(...Object.values(P));j(b),Se(y,b,W),at.current.add(z)}catch(O){console.error(`[useAgent] Error executing tool ${y}:`,O),j(b),Se(y,b,`Error: ${O}`)}})():(console.warn(`[useAgent] Tool ${y} not found in toolsMap`),Se(y,b,`Error: Tool "${y}" not found. The tool may not be registered or available.`),j(b))}else y.startsWith("workflow_")&&F?F({toolCall:{toolCallId:b,toolName:y,args:P}}):F?F({toolCall:{toolCallId:b,toolName:y,args:P}}):(console.warn(`[useAgent] No handler for tool ${y} - tool is not safe and no onToolCall callback provided`),Se(y,b,`Error: Tool "${y}" cannot be executed. No handler is available for this tool.`),j(b))})})},[Fe,Et,Ye,F,Se,builtInSetState,dt,Ce,je,Qt]),f.useEffect(()=>{if(tn==="ready"&&Fe.length>0&&M){const g=Fe[Fe.length-1];g&&g.role==="assistant"&&M({message:g,messages:Fe,isAbort:!1,isDisconnect:!1,isError:!!nn})}},[tn,Fe,nn,M]);async function as(){if(!(!r?.id||!Te)){ot(!0);try{const x=await(await fetch(`${I}/conversations`,{headers:{Authorization:`Bearer ${Te}`}})).json();Tt(x.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{ot(!1)}}}f.useEffect(()=>{r?.id&&Te&&as()},[JSON.stringify(r),Te,I]);async function ls(g){it(g),ot(!0);try{const x=await fetch(`${I}/conversations/${g}/messages`,{headers:{Authorization:`Bearer ${le.current}`}});if(!x.ok)throw new Error(`Failed to fetch messages: ${x.statusText}`);const b=(await x.json()).messages||[];ht(b)}catch(x){console.error("Failed to load conversation messages:",x)}finally{ot(!1)}}async function Dn(g){if(Te)try{await fetch(`${I}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${Te}`}}),Tt(Pn.filter(x=>x._id!==g)),g===He&&Vn()}catch(x){console.error("Failed to delete conversation:",x)}}function Vn(){const g=crypto.randomUUID();it(g),ht([]),Ct.current=new Set,Zt.current=new Set,At.current=void 0}function C(g){const x=g.tool||"unknown-tool",y=ve(x,g.output);sn({toolCallId:g.toolCallId,tool:x,output:y})}async function q(g,x,y){if(!x.startsWith("workflow_"))throw new Error(`${x} is not a workflow tool`);try{const j=dt.find(z=>z.name===x)?._workflow;if(!j)throw new Error(`Workflow metadata not found for ${x}`);let P;if(j.webhook?.url){let z=y;if(j.webhook.bodyTemplate){let O=j.webhook.bodyTemplate;Object.entries(y).forEach(([W,X])=>{O=O.replace(new RegExp(`\\{\\{${W}\\}\\}`,"g"),String(X))}),z=JSON.parse(O)}const N=await fetch(j.webhook.url,{method:j.webhook.method||"POST",headers:{"Content-Type":"application/json",...j.webhook.headers||{}},body:JSON.stringify(z)});if(N.ok)P={success:!0,data:await N.json().catch(()=>({success:!0}))};else{const O=await N.text();P={success:!1,error:`Webhook failed: ${N.status} ${O}`}}}else P={success:!0,message:`Workflow "${j.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:j.contentPlaintext};return C({toolCallId:g,tool:x,output:P}),P}catch(b){const j={success:!1,error:String(b)};throw C({toolCallId:g,tool:x,output:j}),b}}return{id:He,messages:Fe,status:tn,error:nn,sendMessage:os,stop:is,addToolOutput:C,executeWorkflowTool:q,setMessages:ht,conversations:Pn,loadConversation:ls,deleteConversation:Dn,startNewConversation:Vn,isLoadingConversations:Jt,clientToken:Te,tokenError:jn,pendingSecureInputs:Array.from(jt.values()),completeSecureInput:kn,pendingSecureForms:Array.from(Xe.values()),completeSecureForm:en,safeToolNames:Et}}function Q(...e){return ml.twMerge(fl.clsx(e))}const mt=co.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive active:scale-95",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),pe=Ie.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?lo.Slot:"button";return u.jsx(i,{ref:o,"data-slot":"button",className:Q(mt({variant:t,size:n,className:e})),...r})});pe.displayName="Button";const Fl=co.cva("inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function hs({className:e,variant:t,asChild:n=!1,...s}){const r=n?lo.Slot:"span";return u.jsx(r,{"data-slot":"badge",className:Q(Fl({variant:t}),e),...s})}const Bl=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Ie.useState(!0);Ie.useEffect(()=>{const a=e.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const l=a.scrollHeight;l>n?a.style.height=`${n}px`:a.style.height=`${l+6}px`}},[e.current,t])},po=Ie.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Ie.useRef(null),[l,c]=Ie.useState("");return Bl({textAreaRef:a,triggerAutoSize:l,maxHeight:e,minHeight:t}),f.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),Ie.useEffect(()=>{c(r)},[o?.defaultValue,r]),u.jsx("textarea",{...o,value:r,ref:a,className:Q("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=>{c(d.target.value),s?.(d)}})});po.displayName="AutosizeTextarea";function Ul({delayDuration:e=0,...t}){return u.jsx(Ot.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Je({...e}){return u.jsx(Ul,{children:u.jsx(Ot.Root,{"data-slot":"tooltip",...e})})}function Ze({...e}){return u.jsx(Ot.Trigger,{"data-slot":"tooltip-trigger",...e})}function Qe({className:e,sideOffset:t=0,children:n,...s}){return u.jsx(Ot.Portal,{children:u.jsxs(Ot.Content,{"data-slot":"tooltip-content",sideOffset:t,className:Q("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,u.jsx(Ot.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Xr({className:e,...t}){return u.jsx("kbd",{"data-slot":"kbd",className:Q("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 nr=f.createContext({});function sr(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const rr=typeof window<"u",go=rr?f.useLayoutEffect:f.useEffect,Qn=f.createContext(null);function ir(e,t){e.indexOf(t)===-1&&e.push(t)}function or(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const Ke=(e,t,n)=>n>t?t:n<e?e:n;function Ns(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let Bt=()=>{},qe=()=>{};process.env.NODE_ENV!=="production"&&(Bt=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(Ns(t,n))},qe=(e,t,n)=>{if(!e)throw new Error(Ns(t,n))});const Ge={},yo=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function xo(e){return typeof e=="object"&&e!==null}const bo=e=>/^0[^.\s]+$/u.test(e);function ar(e){let t;return()=>(t===void 0&&(t=e()),t)}const Ne=e=>e,zl=(e,t)=>n=>t(e(n)),wn=(...e)=>e.reduce(zl),pn=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class lr{constructor(){this.subscriptions=[]}add(t){return ir(this.subscriptions,t),()=>or(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 Oe=e=>e*1e3,ke=e=>e/1e3;function vo(e,t){return t?e*(1e3/t):0}const Wr=new Set;function cr(e,t,n){e||Wr.has(t)||(console.warn(Ns(t,n)),Wr.add(t))}const wo=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,_l=1e-7,Xl=12;function Wl(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=wo(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>_l&&++a<Xl);return i}function Sn(e,t,n,s){if(e===t&&n===s)return Ne;const r=o=>Wl(o,0,1,e,n);return o=>o===0||o===1?o:wo(r(o),t,s)}const So=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,To=e=>t=>1-e(1-t),Co=Sn(.33,1.53,.69,.99),ur=To(Co),jo=So(ur),Po=e=>(e*=2)<1?.5*ur(e):.5*(2-Math.pow(2,-10*(e-1))),dr=e=>1-Math.sin(Math.acos(e)),Ao=To(dr),Eo=So(dr),Kl=Sn(.42,0,1,1),ql=Sn(0,0,.58,1),Mo=Sn(.42,0,.58,1),Gl=e=>Array.isArray(e)&&typeof e[0]!="number",ko=e=>Array.isArray(e)&&typeof e[0]=="number",Kr={linear:Ne,easeIn:Kl,easeInOut:Mo,easeOut:ql,circIn:dr,circInOut:Eo,circOut:Ao,backIn:ur,backInOut:jo,backOut:Co,anticipate:Po},Hl=e=>typeof e=="string",qr=e=>{if(ko(e)){qe(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return Sn(t,n,s,r)}else if(Hl(e))return qe(Kr[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),Kr[e];return e},In=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Yl(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)&&(c.schedule(d),e()),d(a)}const c={schedule:(d,h=!1,m=!1)=>{const v=m&&r?n:s;return h&&i.add(d),v.has(d)||v.add(d),d},cancel:d=>{s.delete(d),i.delete(d)},process:d=>{if(a=d,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(l),n.clear(),r=!1,o&&(o=!1,c.process(d))}};return c}const Jl=40;function No(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=In.reduce((E,U)=>(E[U]=Yl(o),E),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:h,preRender:m,render:p,postRender:v}=i,w=()=>{const E=Ge.useManualTiming?r.timestamp:performance.now();n=!1,Ge.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(E-r.timestamp,Jl),1)),r.timestamp=E,r.isProcessing=!0,a.process(r),l.process(r),c.process(r),d.process(r),h.process(r),m.process(r),p.process(r),v.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(w))},T=()=>{n=!0,s=!0,r.isProcessing||e(w)};return{schedule:In.reduce((E,U)=>{const D=i[U];return E[U]=($,F=!1,M=!1)=>(n||T(),D.schedule($,F,M)),E},{}),cancel:E=>{for(let U=0;U<In.length;U++)i[In[U]].cancel(E)},state:r,steps:i}}const{schedule:ne,cancel:tt,state:fe,steps:fs}=No(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ne,!0);let zn;function Zl(){zn=void 0}const be={now:()=>(zn===void 0&&be.set(fe.isProcessing||Ge.useManualTiming?fe.timestamp:performance.now()),zn),set:e=>{zn=e,queueMicrotask(Zl)}},Ro=e=>t=>typeof t=="string"&&t.startsWith(e),hr=Ro("--"),Ql=Ro("var(--"),fr=e=>Ql(e)?ec.test(e.split("/*")[0].trim()):!1,ec=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Ut={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},gn={...Ut,transform:e=>Ke(0,1,e)},On={...Ut,default:1},un=e=>Math.round(e*1e5)/1e5,mr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function tc(e){return e==null}const nc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,pr=(e,t)=>n=>!!(typeof n=="string"&&nc.test(n)&&n.startsWith(e)||t&&!tc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Do=(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}},sc=e=>Ke(0,255,e),ms={...Ut,transform:e=>Math.round(sc(e))},gt={test:pr("rgb","red"),parse:Do("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+ms.transform(e)+", "+ms.transform(t)+", "+ms.transform(n)+", "+un(gn.transform(s))+")"};function rc(e){let t="",n="",s="",r="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),r=e.substring(4,5),t+=t,n+=n,s+=s,r+=r),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const Rs={test:pr("#"),parse:rc,transform:gt.transform},Tn=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),et=Tn("deg"),Be=Tn("%"),K=Tn("px"),ic=Tn("vh"),oc=Tn("vw"),Gr={...Be,parse:e=>Be.parse(e)/100,transform:e=>Be.transform(e*100)},kt={test:pr("hsl","hue"),parse:Do("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Be.transform(un(t))+", "+Be.transform(un(n))+", "+un(gn.transform(s))+")"},ce={test:e=>gt.test(e)||Rs.test(e)||kt.test(e),parse:e=>gt.test(e)?gt.parse(e):kt.test(e)?kt.parse(e):Rs.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?gt.transform(e):kt.transform(e),getAnimatableNone:e=>{const t=ce.parse(e);return t.alpha=0,ce.transform(t)}},ac=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function lc(e){return isNaN(e)&&typeof e=="string"&&(e.match(mr)?.length||0)+(e.match(ac)?.length||0)>0}const Vo="number",Io="color",cc="var",uc="var(",Hr="${}",dc=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function yn(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(dc,l=>(ce.test(l)?(s.color.push(o),r.push(Io),n.push(ce.parse(l))):l.startsWith(uc)?(s.var.push(o),r.push(cc),n.push(l)):(s.number.push(o),r.push(Vo),n.push(parseFloat(l))),++o,Hr)).split(Hr);return{values:n,split:a,indexes:s,types:r}}function Oo(e){return yn(e).values}function $o(e){const{split:t,types:n}=yn(e),s=t.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=t[i],r[i]!==void 0){const a=n[i];a===Vo?o+=un(r[i]):a===Io?o+=ce.transform(r[i]):o+=r[i]}return o}}const hc=e=>typeof e=="number"?0:ce.test(e)?ce.getAnimatableNone(e):e;function fc(e){const t=Oo(e);return $o(e)(t.map(hc))}const nt={test:lc,parse:Oo,createTransformer:$o,getAnimatableNone:fc};function ps(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function mc({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let r=0,o=0,i=0;if(!t)r=o=i=n;else{const a=n<.5?n*(1+t):n+t-n*t,l=2*n-a;r=ps(l,a,e+1/3),o=ps(l,a,e),i=ps(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function qn(e,t){return n=>n>0?t:e}const re=(e,t,n)=>e+(t-e)*n,gs=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},pc=[Rs,gt,kt],gc=e=>pc.find(t=>t.test(e));function Yr(e){const t=gc(e);if(Bt(!!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===kt&&(n=mc(n)),n}const Jr=(e,t)=>{const n=Yr(e),s=Yr(t);if(!n||!s)return qn(e,t);const r={...n};return o=>(r.red=gs(n.red,s.red,o),r.green=gs(n.green,s.green,o),r.blue=gs(n.blue,s.blue,o),r.alpha=re(n.alpha,s.alpha,o),gt.transform(r))},Ds=new Set(["none","hidden"]);function yc(e,t){return Ds.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function xc(e,t){return n=>re(e,t,n)}function gr(e){return typeof e=="number"?xc:typeof e=="string"?fr(e)?qn:ce.test(e)?Jr:wc:Array.isArray(e)?Lo:typeof e=="object"?ce.test(e)?Jr:bc:qn}function Lo(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>gr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function bc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=gr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function vc(e,t){const n=[],s={color:0,var:0,number:0};for(let r=0;r<t.values.length;r++){const o=t.types[r],i=e.indexes[o][s[o]],a=e.values[i]??0;n[r]=a,s[o]++}return n}const wc=(e,t)=>{const n=nt.createTransformer(t),s=yn(e),r=yn(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?Ds.has(e)&&!r.values.length||Ds.has(t)&&!s.values.length?yc(e,t):wn(Lo(vc(s,r),r.values),n):(Bt(!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"),qn(e,t))};function Fo(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?re(e,t,n):gr(e)(e,t)}const Sc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>ne.update(t,n),stop:()=>tt(t),now:()=>fe.isProcessing?fe.timestamp:be.now()}},Bo=(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)})`},Gn=2e4;function yr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<Gn;)t+=n,s=e.next(t);return t>=Gn?1/0:t}function Tc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(yr(s),Gn);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:ke(r)}}const Cc=5;function Uo(e,t,n){const s=Math.max(t-Cc,0);return vo(n-e(s),t-s)}const se={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},ys=.001;function jc({duration:e=se.duration,bounce:t=se.bounce,velocity:n=se.velocity,mass:s=se.mass}){let r,o;Bt(e<=Oe(se.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=Ke(se.minDamping,se.maxDamping,i),e=Ke(se.minDuration,se.maxDuration,ke(e)),i<1?(r=c=>{const d=c*i,h=d*e,m=d-n,p=Vs(c,i),v=Math.exp(-h);return ys-m/p*v},o=c=>{const h=c*i*e,m=h*n+n,p=Math.pow(i,2)*Math.pow(c,2)*e,v=Math.exp(-h),w=Vs(Math.pow(c,2),i);return(-r(c)+ys>0?-1:1)*((m-p)*v)/w}):(r=c=>{const d=Math.exp(-c*e),h=(c-n)*e+1;return-ys+d*h},o=c=>{const d=Math.exp(-c*e),h=(n-c)*(e*e);return d*h});const a=5/e,l=Ac(r,o,a);if(e=Oe(e),isNaN(l))return{stiffness:se.stiffness,damping:se.damping,duration:e};{const c=Math.pow(l,2)*s;return{stiffness:c,damping:i*2*Math.sqrt(s*c),duration:e}}}const Pc=12;function Ac(e,t,n){let s=n;for(let r=1;r<Pc;r++)s=s-e(s)/t(s);return s}function Vs(e,t){return e*Math.sqrt(1-t*t)}const Ec=["duration","bounce"],Mc=["stiffness","damping","mass"];function Zr(e,t){return t.some(n=>e[n]!==void 0)}function kc(e){let t={velocity:se.velocity,stiffness:se.stiffness,damping:se.damping,mass:se.mass,isResolvedFromDuration:!1,...e};if(!Zr(e,Mc)&&Zr(e,Ec))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*Ke(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:se.mass,stiffness:r,damping:o}}else{const n=jc(e);t={...t,...n,mass:se.mass},t.isResolvedFromDuration=!0}return t}function Hn(e=se.visualDuration,t=se.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:c,mass:d,duration:h,velocity:m,isResolvedFromDuration:p}=kc({...n,velocity:-ke(n.velocity||0)}),v=m||0,w=c/(2*Math.sqrt(l*d)),T=i-o,S=ke(Math.sqrt(l/d)),k=Math.abs(T)<5;s||(s=k?se.restSpeed.granular:se.restSpeed.default),r||(r=k?se.restDelta.granular:se.restDelta.default);let E;if(w<1){const D=Vs(S,w);E=$=>{const F=Math.exp(-w*S*$);return i-F*((v+w*S*T)/D*Math.sin(D*$)+T*Math.cos(D*$))}}else if(w===1)E=D=>i-Math.exp(-S*D)*(T+(v+S*T)*D);else{const D=S*Math.sqrt(w*w-1);E=$=>{const F=Math.exp(-w*S*$),M=Math.min(D*$,300);return i-F*((v+w*S*T)*Math.sinh(M)+D*T*Math.cosh(M))/D}}const U={calculatedDuration:p&&h||null,next:D=>{const $=E(D);if(p)a.done=D>=h;else{let F=D===0?v:0;w<1&&(F=D===0?Oe(v):Uo(E,D,$));const M=Math.abs(F)<=s,R=Math.abs(i-$)<=r;a.done=M&&R}return a.value=a.done?i:$,a},toString:()=>{const D=Math.min(yr(U),Gn),$=Bo(F=>U.next(D*F).value,D,30);return D+"ms "+$},toTransition:()=>{}};return U}Hn.applyToOptions=e=>{const t=Tc(e,100,Hn);return e.ease=t.ease,e.duration=Oe(t.duration),e.type="keyframes",e};function Is({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:l,restDelta:c=.5,restSpeed:d}){const h=e[0],m={done:!1,value:h},p=M=>a!==void 0&&M<a||l!==void 0&&M>l,v=M=>a===void 0?l:l===void 0||Math.abs(a-M)<Math.abs(l-M)?a:l;let w=n*t;const T=h+w,S=i===void 0?T:i(T);S!==T&&(w=S-h);const k=M=>-w*Math.exp(-M/s),E=M=>S+k(M),U=M=>{const R=k(M),A=E(M);m.done=Math.abs(R)<=c,m.value=m.done?S:A};let D,$;const F=M=>{p(m.value)&&(D=M,$=Hn({keyframes:[m.value,v(m.value)],velocity:Uo(E,M,m.value),damping:r,stiffness:o,restDelta:c,restSpeed:d}))};return F(0),{calculatedDuration:null,next:M=>{let R=!1;return!$&&D===void 0&&(R=!0,U(M),F(M)),D!==void 0&&M>=D?$.next(M-D):(!R&&U(M),m)}}}function Nc(e,t,n){const s=[],r=n||Ge.mix||Fo,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]||Ne:t;a=wn(l,a)}s.push(a)}return s}function Rc(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(qe(o===t.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>t[0];if(o===2&&t[0]===t[1])return()=>t[1];const i=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=Nc(t,s,r),l=a.length,c=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=pn(e[h],e[h+1],d);return a[h](m)};return n?d=>c(Ke(e[0],e[o-1],d)):c}function Dc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=pn(0,t,s);e.push(re(n,1,r))}}function Vc(e){const t=[0];return Dc(t,e.length-1),t}function Ic(e,t){return e.map(n=>n*t)}function Oc(e,t){return e.map(()=>t||Mo).splice(0,e.length-1)}function Nt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=Gl(s)?s.map(qr):qr(s),o={done:!1,value:t[0]},i=Ic(n&&n.length===t.length?n:Vc(t),e),a=Rc(i,t,{ease:Array.isArray(r)?r:Oc(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const $c=e=>e!==null;function xr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter($c),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const Lc={decay:Is,inertia:Is,tween:Nt,keyframes:Nt,spring:Hn};function zo(e){typeof e.type=="string"&&(e.type=Lc[e.type])}class br{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const Fc=e=>e/100;class vr extends br{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!==be.now()&&this.tick(be.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;zo(t);const{type:n=Nt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const l=n||Nt;process.env.NODE_ENV!=="production"&&l!==Nt&&qe(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),l!==Nt&&typeof a[0]!="number"&&(this.mixKeyframes=wn(Fc,Fo(a[0],a[1])),a=[0,100]);const c=l({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...t,keyframes:[...a].reverse(),velocity:-i})),c.calculatedDuration===null&&(c.calculatedDuration=yr(c));const{calculatedDuration:d}=c;this.calculatedDuration=d,this.resolvedDuration=d+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=c}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:c=0,keyframes:d,repeat:h,repeatType:m,repeatDelay:p,type:v,onUpdate:w,finalKeyframe:T}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-r/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const S=this.currentTime-c*(this.playbackSpeed>=0?1:-1),k=this.playbackSpeed>=0?S<0:S>r;this.currentTime=Math.max(S,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let E=this.currentTime,U=s;if(h){const M=Math.min(this.currentTime,r)/a;let R=Math.floor(M),A=M%1;!A&&M>=1&&(A=1),A===1&&R--,R=Math.min(R,h+1),!!(R%2)&&(m==="reverse"?(A=1-A,p&&(A-=p/a)):m==="mirror"&&(U=i)),E=Ke(0,1,A)*a}const D=k?{done:!1,value:d[0]}:U.next(E);o&&(D.value=o(D.value));let{done:$}=D;!k&&l!==null&&($=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const F=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&$);return F&&v!==Is&&(D.value=xr(d,this.options,T,this.speed)),w&&w(D.value),F&&this.finish(),D}then(t,n){return this.finished.then(t,n)}get duration(){return ke(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+ke(t)}get time(){return ke(this.currentTime)}set time(t){t=Oe(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(be.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=ke(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Sc,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(be.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function Bc(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const yt=e=>e*180/Math.PI,Os=e=>{const t=yt(Math.atan2(e[1],e[0]));return $s(t)},Uc={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Os,rotateZ:Os,skewX:e=>yt(Math.atan(e[1])),skewY:e=>yt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},$s=e=>(e=e%360,e<0&&(e+=360),e),Qr=Os,ei=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),ti=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),zc={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ei,scaleY:ti,scale:e=>(ei(e)+ti(e))/2,rotateX:e=>$s(yt(Math.atan2(e[6],e[5]))),rotateY:e=>$s(yt(Math.atan2(-e[2],e[0]))),rotateZ:Qr,rotate:Qr,skewX:e=>yt(Math.atan(e[4])),skewY:e=>yt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Ls(e){return e.includes("scale")?1:0}function Fs(e,t){if(!e||e==="none")return Ls(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=zc,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=Uc,r=a}if(!r)return Ls(t);const o=s[t],i=r[1].split(",").map(Xc);return typeof o=="function"?o(i):i[o]}const _c=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Fs(n,t)};function Xc(e){return parseFloat(e.trim())}const zt=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],_t=new Set(zt),ni=e=>e===Ut||e===K,Wc=new Set(["x","y","z"]),Kc=zt.filter(e=>!Wc.has(e));function qc(e){const t=[];return Kc.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const xt={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})=>Fs(t,"x"),y:(e,{transform:t})=>Fs(t,"y")};xt.translateX=xt.x;xt.translateY=xt.y;const bt=new Set;let Bs=!1,Us=!1,zs=!1;function _o(){if(Us){const e=Array.from(bt).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=qc(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)})}Us=!1,Bs=!1,bt.forEach(e=>e.complete(zs)),bt.clear()}function Xo(){bt.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Us=!0)})}function Gc(){zs=!0,Xo(),_o(),zs=!1}class wr{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?(bt.add(this),Bs||(Bs=!0,ne.read(Xo),ne.resolveKeyframes(_o))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:r}=this;if(t[0]===null){const o=r?.get(),i=t[t.length-1];if(o!==void 0)t[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=i),r&&o===void 0&&r.set(t[0])}Bc(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),bt.delete(this)}cancel(){this.state==="scheduled"&&(bt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Hc=e=>e.startsWith("--");function Yc(e,t,n){Hc(t)?e.style.setProperty(t,n):e.style[t]=n}const Jc=ar(()=>window.ScrollTimeline!==void 0),Zc={};function Qc(e,t){const n=ar(e);return()=>Zc[t]??n()}const Wo=Qc(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),ln=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,si={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:ln([0,.65,.55,1]),circOut:ln([.55,0,1,.45]),backIn:ln([.31,.01,.66,-.59]),backOut:ln([.33,1.53,.69,.99])};function Ko(e,t){if(e)return typeof e=="function"?Wo()?Bo(e,t):"ease-out":ko(e)?ln(e):Array.isArray(e)?e.map(n=>Ko(n,t)||si.easeOut):si[e]}function eu(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:l}={},c=void 0){const d={[t]:n};l&&(d.offset=l);const h=Ko(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 c&&(m.pseudoElement=c),e.animate(d,m)}function qo(e){return typeof e=="function"&&"applyToOptions"in e}function tu({type:e,...t}){return qo(e)&&Wo()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class nu extends br{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,qe(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const c=tu(t);this.animation=eu(n,s,r,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=xr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Yc(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 ke(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+ke(t)}get time(){return ke(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=Oe(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&Jc()?(this.animation.timeline=t,Ne):n(this)}}const Go={anticipate:Po,backInOut:jo,circInOut:Eo};function su(e){return e in Go}function ru(e){typeof e.ease=="string"&&su(e.ease)&&(e.ease=Go[e.ease])}const ri=10;class iu extends nu{constructor(t){ru(t),zo(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new vr({...i,autoplay:!1}),l=Oe(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-ri).value,a.sample(l).value,ri),a.stop()}}const ii=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(nt.test(e)||e==="0")&&!e.startsWith("url("));function ou(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function au(e,t,n,s){const r=e[0];if(r===null)return!1;if(t==="display"||t==="visibility")return!0;const o=e[e.length-1],i=ii(r,t),a=ii(o,t);return Bt(i===a,`You are trying to animate ${t} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:ou(e)||(n==="spring"||qo(n))&&s}function _s(e){e.duration=0,e.type="keyframes"}const lu=new Set(["opacity","clipPath","filter","transform"]),cu=ar(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function uu(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:l,transformTemplate:c}=t.owner.getProps();return cu()&&n&&lu.has(n)&&(n!=="transform"||!c)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const du=40;class hu extends br{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:l,motionValue:c,element:d,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=be.now();const m={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:l,motionValue:c,element:d,...h},p=d?.KeyframeResolver||wr;this.keyframeResolver=new p(a,(v,w,T)=>this.onKeyframesResolved(v,w,m,!T),l,c,d),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:l,isHandoff:c,onUpdate:d}=s;this.resolvedAt=be.now(),au(t,o,i,a)||((Ge.instantAnimations||!l)&&d?.(xr(t,s,n)),t[0]=t[t.length-1],_s(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>du?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!c&&uu(m)?new iu({...m,element:m.motionValue.owner.current}):new vr(m);p.finished.then(()=>this.notifyFinished()).catch(Ne),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Gc()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const fu=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function mu(e){const t=fu.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const pu=4;function Ho(e,t,n=1){qe(n<=pu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=mu(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return yo(i)?parseFloat(i):i}return fr(r)?Ho(r,t,n+1):r}function Sr(e,t){return e?.[t]??e?.default??e}const Yo=new Set(["width","height","top","left","right","bottom",...zt]),gu={test:e=>e==="auto",parse:e=>e},Jo=e=>t=>t.test(e),Zo=[Ut,K,Be,et,oc,ic,gu],oi=e=>Zo.find(Jo(e));function yu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||bo(e):!0}const xu=new Set(["brightness","contrast","saturate","opacity"]);function bu(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(mr)||[];if(!s)return e;const r=n.replace(s,"");let o=xu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const vu=/\b([a-z-]*)\(.*?\)/gu,Xs={...nt,getAnimatableNone:e=>{const t=e.match(vu);return t?t.map(bu).join(" "):e}},ai={...Ut,transform:Math.round},wu={rotate:et,rotateX:et,rotateY:et,rotateZ:et,scale:On,scaleX:On,scaleY:On,scaleZ:On,skew:et,skewX:et,skewY:et,distance:K,translateX:K,translateY:K,translateZ:K,x:K,y:K,z:K,perspective:K,transformPerspective:K,opacity:gn,originX:Gr,originY:Gr,originZ:K},Tr={borderWidth:K,borderTopWidth:K,borderRightWidth:K,borderBottomWidth:K,borderLeftWidth:K,borderRadius:K,radius:K,borderTopLeftRadius:K,borderTopRightRadius:K,borderBottomRightRadius:K,borderBottomLeftRadius:K,width:K,maxWidth:K,height:K,maxHeight:K,top:K,right:K,bottom:K,left:K,padding:K,paddingTop:K,paddingRight:K,paddingBottom:K,paddingLeft:K,margin:K,marginTop:K,marginRight:K,marginBottom:K,marginLeft:K,backgroundPositionX:K,backgroundPositionY:K,...wu,zIndex:ai,fillOpacity:gn,strokeOpacity:gn,numOctaves:ai},Su={...Tr,color:ce,backgroundColor:ce,outlineColor:ce,fill:ce,stroke:ce,borderColor:ce,borderTopColor:ce,borderRightColor:ce,borderBottomColor:ce,borderLeftColor:ce,filter:Xs,WebkitFilter:Xs},Qo=e=>Su[e];function ea(e,t){let n=Qo(e);return n!==Xs&&(n=nt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Tu=new Set(["auto","none","0"]);function Cu(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!Tu.has(o)&&yn(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=ea(n,r)}class ju extends wr{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 c=t[l];if(typeof c=="string"&&(c=c.trim(),fr(c))){const d=Ho(c,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Yo.has(s)||t.length!==2)return;const[r,o]=t,i=oi(r),a=oi(o);if(i!==a)if(ni(i)&&ni(a))for(let l=0;l<t.length;l++){const c=t[l];typeof c=="string"&&(t[l]=parseFloat(c))}else xt[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||yu(t[r]))&&s.push(r);s.length&&Cu(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=xt[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]=xt[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,l])=>{t.getValue(a).set(l)}),this.resolveNoneKeyframes()}}function Pu(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const r=n?.[e]??s.querySelectorAll(e);return r?Array.from(r):[]}return Array.from(e)}const ta=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function na(e){return xo(e)&&"offsetHeight"in e}const li=30,Au=e=>!isNaN(parseFloat(e));class Eu{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=be.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=be.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Au(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&cr(!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 lr);const s=this.events[t].add(n);return t==="change"?()=>{s(),ne.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=be.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>li)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,li);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 Lt(e,t){return new Eu(e,t)}const{schedule:Cr}=No(queueMicrotask,!1),Ve={x:!1,y:!1};function sa(){return Ve.x||Ve.y}function Mu(e){return e==="x"||e==="y"?Ve[e]?null:(Ve[e]=!0,()=>{Ve[e]=!1}):Ve.x||Ve.y?null:(Ve.x=Ve.y=!0,()=>{Ve.x=Ve.y=!1})}function ra(e,t){const n=Pu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function ci(e){return!(e.pointerType==="touch"||sa())}function ku(e,t,n={}){const[s,r,o]=ra(e,n),i=a=>{if(!ci(a))return;const{target:l}=a,c=t(l,a);if(typeof c!="function"||!l)return;const d=h=>{ci(h)&&(c(h),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ia=(e,t)=>t?e===t?!0:ia(e,t.parentElement):!1,jr=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Nu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Ru(e){return Nu.has(e.tagName)||e.tabIndex!==-1}const _n=new WeakSet;function ui(e){return t=>{t.key==="Enter"&&e(t)}}function xs(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Du=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=ui(()=>{if(_n.has(n))return;xs(n,"down");const r=ui(()=>{xs(n,"up")}),o=()=>xs(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 di(e){return jr(e)&&!sa()}function Vu(e,t,n={}){const[s,r,o]=ra(e,n),i=a=>{const l=a.currentTarget;if(!di(a))return;_n.add(l);const c=t(l,a),d=(p,v)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),_n.has(l)&&_n.delete(l),di(p)&&typeof c=="function"&&c(p,{success:v})},h=p=>{d(p,l===window||l===document||n.useGlobalTarget||ia(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),na(a)&&(a.addEventListener("focus",c=>Du(c,r)),!Ru(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function oa(e){return xo(e)&&"ownerSVGElement"in e}function Iu(e){return oa(e)&&e.tagName==="svg"}const me=e=>!!(e&&e.getVelocity),Ou=[...Zo,ce,nt],$u=e=>Ou.find(Jo(e)),Pr=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function hi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Lu(...e){return t=>{let n=!1;const s=e.map(r=>{const o=hi(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():hi(e[r],null)}}}}function Fu(...e){return Ie.useCallback(Lu(...e),e)}class Bu extends Ie.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=na(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 Uu({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(Pr),l=Fu(o,e?.ref);return f.useInsertionEffect(()=>{const{width:c,height:d,top:h,left:m,right:p}=i.current;if(t||!o.current||!c||!d)return;const v=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const w=document.createElement("style");a&&(w.nonce=a);const T=s??document.head;return T.appendChild(w),w.sheet&&w.sheet.insertRule(`
1
+ "use strict";var rl=Object.create;var Br=Object.defineProperty;var il=Object.getOwnPropertyDescriptor;var ol=Object.getOwnPropertyNames;var al=Object.getPrototypeOf,ll=Object.prototype.hasOwnProperty;var cl=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ol(t))!ll.call(e,r)&&r!==n&&Br(e,r,{get:()=>t[r],enumerable:!(s=il(t,r))||s.enumerable});return e};var ul=(e,t,n)=>(n=e!=null?rl(al(e)):{},cl(t||!e||!e.__esModule?Br(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),f=require("react"),J=require("lucide-react"),dl=require("@ai-sdk/react"),Ur=require("ai"),ao=require("@radix-ui/react-slot"),lo=require("class-variance-authority"),hl=require("clsx"),fl=require("tailwind-merge"),ml=require("@radix-ui/react-tooltip"),zr=require("@radix-ui/react-use-controllable-state"),pl=require("@radix-ui/react-collapsible"),gl=require("react-dom"),yl=require("@radix-ui/react-dialog");function Jn(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 Oe=Jn(f),Dt=Jn(ml),er=Jn(pl),xt=Jn(yl),Me=Symbol.for("@arcteninc/core:originalName");function xl(e,t){return e[Me]=t,e}function bl(e,t,n,s){if(typeof e!="function")return null;const r=e[Me];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[Me]=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[Me]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(l=>!n.has(l.name)),i)return e[Me]=i.name,{fn:e,meta:i};return null}function tr(e,t){if(!t)return[];let n,s;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=bl(o,n,r,s);if(!i){const a=o.name,c=o[Me]||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 "${c}". This tool will be excluded.
2
+ To fix: Run "arcten-extract-types ." and ensure "${c}" 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)}const vl={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 on(e){for(const[t,n]of Object.entries(vl))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function wl(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 Sl(e,t,n){return t.length>0}function Tl(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 c=Cl(s[i]),d={name:i,type:jl(l||on(i)||"text"),label:co(i),placeholder:Pl(i,l),required:!0,value:c};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,c=a.name in n;return l===c?0:l?1:-1}),{shouldUseForm:Sl(e,t),fields:r,title:Al(e),description:El(e,r.length)}}function Cl(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function jl(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 co(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Pl(e,t){return t?wl(t,e).placeholder:`Enter ${co(e).toLowerCase()}...`}function Al(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function El(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 ln(e){if(typeof e=="string")try{const t=JSON.parse(e);return ln(t)}catch{return e}if(Array.isArray(e))return e.map(ln);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=ln(s);return t}return e}function Ml(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 kl(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return ln(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?ln(e):{}}const Fn="__secureOutput",Bn="[hidden for privacy]";function Nl(e,t){if(!e||e.length===0)return t;const n=new Map;t.forEach(o=>{const i=o[Me]||o.name;i&&n.set(i,o)});const s=new Map(e.map(o=>[o.name,o])),r=[];return e.forEach(o=>{const i=n.get(o.name);if(!i){console.log(`[useAgent] Skipping server-only tool: ${o.name}`);return}if(!o.isEnabled&&!o.isOverridable){console.log(`[useAgent] Blocking non-overridable disabled tool: ${o.name}`);return}if(!o.isEnabled&&o.isOverridable&&i){console.log(`[useAgent] Allowing overridable disabled tool with local implementation: ${o.name}`),r.push(i);return}o.isEnabled&&i&&r.push(i)}),t.forEach(o=>{const i=o[Me]||o.name;i&&!s.has(i)&&(console.log(`[useAgent] Allowing client-only tool (forward compatible): ${i}`),r.push(o))}),r}function Dl(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 Rl(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function Vl(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 Il(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 ks(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 uo(e,t=""){const n={};return e&&typeof e=="object"?Object.entries(e).forEach(([s,r])=>{const o=t?`${t}.${s}`:s;n[o]=ks(r),r&&typeof r=="object"&&Object.assign(n,uo(r,o))}):t&&(n[t]=ks(e)),n}function Ol(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:Bn,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:Bn,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??Bn,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function $l(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=Ol(s);r&&(t[n]=r)}return t}function ho(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=uo(t)),r.redactedFields=["*"];let l={};return n.preserve.length>0&&t&&typeof t=="object"&&n.preserve.forEach(c=>{c in t&&(l[c]=t[c])}),l[Fn]=r,l}if(n.fields.includes("*"))return ho(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[Fn]:{...r,redactedFields:n.fields}};const o=Dl(t),i=[],a={};return n.fields.forEach(l=>{const c=Rl(l);if(c.length===0)return;const d=Vl(o,c),h=ks(d);a[l]=h,Il(o,c,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[Fn]=r,o}function fo({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],safeToolNames:a,toolMetadata:l,sensitiveParams:c,sensitiveOutputs:d,autoDetectSensitive:h=!1,autoFormGeneration:m=!1,formMode:p="auto",systemPrompt:v="",agentId:w,agentName:C,projectId:S,enableRemoteConfig:M,remoteConfigUrl:A,initialMessages:U=[],conversationId:R,state:z,onToolCall:F,onFinish:E,sources:D,ragConfig:P,ragFilters:V,secureInputHandler:L}={}){const I=e.replace(/\/+$/,""),[B,H]=f.useState(null),[ee,q]=f.useState(!1),[Q,ce]=f.useState(null),be=f.useMemo(()=>{const g=D||[],y=B?.config?.sources||[];return[...new Set([...g,...y])]},[D,B]),re=f.useMemo(()=>P!==void 0?P:V?{enabled:!0,filters:V}:be&&be.length>0?{enabled:!0,organizationId:be[0],autoExecute:!0,filters:void 0}:{enabled:!1},[be,P,V]),rt=f.useMemo(()=>M===!1?!1:!!S,[S,M]);f.useEffect(()=>{if(!rt||!oe.current)return;(async()=>{q(!0),ce(null);try{const x=`${A||I.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,b=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${oe.current}`},body:JSON.stringify({path:"agents:getConfigForClient",args:{projectId:S,agentName:C,agentId:w},format:"json"})});if(!b.ok){if(b.status===404){console.warn("[useAgent] Remote config endpoint not found (404), using local tools only"),H(null);return}const N=await b.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch remote config: ${b.status} ${N}`)}const T=await b.json();H(T?.value||null),console.log("[useAgent] Remote config loaded successfully:",T?.value)}catch(y){console.error("[useAgent] Failed to fetch remote config:",y);const x=y instanceof Error?y:new Error(String(y));ce(x),H(null)}finally{q(!1)}})()},[rt,S,C,w,I,A]);const Y=f.useMemo(()=>{const g={};if(c)for(const[y,x]of Object.entries(c))if(g[y]={},Array.isArray(x))for(const b of x){const T=on(b);g[y][b]=T||"text"}else for(const[b,T]of Object.entries(x))g[y][b]=T;if(l){for(const[y,x]of Object.entries(l))if(x&&typeof x=="object"&&"sensitiveParams"in x){g[y]||(g[y]={});const b=x.sensitiveParams;if(Array.isArray(b))for(const T of b){const N=on(T);g[y][T]=N||"text"}else if(b&&typeof b=="object")for(const[T,N]of Object.entries(b))g[y][T]=N}}return g},[c,l,h]),bt=f.useMemo(()=>$l(d),[d]),Se=f.useCallback((g,y)=>{const x=bt[g];if(!x)return y;try{return ho(g,y,x)}catch(b){return console.error(`[useAgent] Failed to redact output for ${g}:`,b),{value:Bn,[Fn]:{tool:g,redacted:!0,error:String(b)}}}},[bt]),[Ce,pe]=f.useState(n||null),oe=f.useRef(n||null),[Cn,Ue]=f.useState(null),[Le,vt]=f.useState(null),ze=f.useRef(null),[jn,wt]=f.useState([]),[Ye,it]=f.useState(R||(typeof window<"u"?crypto.randomUUID():null)),[qt,ot]=f.useState(!1),St=f.useRef(new Set),Gt=f.useRef(new Set),at=f.useRef(new Set),[Tt,_e]=f.useState(new Map),[ns,Pn]=f.useState(new Map),[Xe,An]=f.useState(new Map),[En,Ct]=f.useState(new Map),Mn=f.useCallback(g=>L?L.showSecureModal(g):new Promise(y=>{_e(x=>new Map(x).set(g.id,g)),Pn(x=>new Map(x).set(g.id,y))}),[L]),Ht=f.useCallback((g,y)=>{if(L)return;const x=ns.get(g);x&&(x(y),_e(b=>{const T=new Map(b);return T.delete(g),T}),Pn(b=>{const T=new Map(b);return T.delete(g),T}))},[ns,L]),kn=f.useCallback(g=>L?L.showSecureForm(g):new Promise(y=>{An(x=>new Map(x).set(g.id,g)),Ct(x=>new Map(x).set(g.id,y))}),[L]),lt=f.useCallback((g,y)=>{if(L)return;const x=En.get(g);x&&(x(y),An(b=>{const T=new Map(b);return T.delete(g),T}),Ct(b=>{const T=new Map(b);return T.delete(g),T}))},[En,L]),ct=f.useCallback((g,y)=>{const x=Y[g]||{},b=Object.keys(x).length>0;if(h){const T=Object.keys(y).filter(N=>on(N)!==null);return b||T.length>0}return b},[Y,h]),De=f.useCallback((g,y)=>{const b={...Y[g]||{}};if(h){for(const N of Object.keys(y))if(!(N in b)){const O=on(N);O&&(b[N]=O)}}const T=Object.entries(b).filter(([N])=>Object.prototype.hasOwnProperty.call(y,N));return T.length>0?Object.fromEntries(T):b},[Y,h]),ue=f.useMemo(()=>re?.enabled?async function(y,x=20,b){const T={...re.filters,...b};if(D&&D.length>1){const O=D.map($=>fetch(`${I}/search`,{method:"POST",headers:{"Content-Type":"application/json",...oe.current?{Authorization:`Bearer ${oe.current}`}:{}},body:JSON.stringify({q:y,k:Math.min(x,100),organizationId:$,...Object.keys(T).length>0?{filters:T}:{}})}).then(W=>W.ok?W.json():null)),_=await Promise.all(O),k=[];for(const $ of _)$?.candidates&&k.push(...$.candidates);k.sort(($,W)=>{const K=$.scores?.rerank||$.scores?.dense||0;return(W.scores?.rerank||W.scores?.dense||0)-K});const G=k.slice(0,x).map(($,W)=>{const K=$.citation||$.url;return{rank:W+1,doc_id:$.doc_id,block_id:$.block_id,url:$.url,citation:K,title:$.title||"Untitled",snippet:$.snippet,score:$.scores?.rerank||$.scores?.dense||0,metadata:{site:$.metadata?.site,lang:$.metadata?.lang,contentType:$.metadata?.content_type}}});return{success:!0,query:y,total:k.length,results:G,summary:`Found ${k.length} relevant results across ${D.length} source(s) for "${y}". Top result: ${G[0]?.title||"N/A"}`}}const N=re.organizationId&&re.organizationId!=="default"?re.organizationId:D&&D.length>0?D[0]:void 0;try{const O={q:y,k:Math.min(x,100)};N&&(O.organizationId=N),Object.keys(T).length>0&&(O.filters=T);const _={"Content-Type":"application/json"};oe.current&&(_.Authorization=`Bearer ${oe.current}`);const k=await fetch(`${I}/search`,{method:"POST",headers:_,body:JSON.stringify(O)});if(!k.ok){const W=await k.text();return{success:!1,error:`Search failed: ${k.status} ${W}`}}const G=await k.json(),$=G.candidates.map((W,K)=>{const ge=W.citation||W.url;return{rank:K+1,doc_id:W.doc_id,block_id:W.block_id,url:W.url,citation:ge,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:G.query,total:G.total,results:$,summary:`Found ${G.total} relevant results for "${y}". Top result: ${$[0]?.title||"N/A"}`}}catch(O){return{success:!1,error:O instanceof Error?O.message:"Unknown error occurred"}}}:null,[re,I,oe]),Re=f.useMemo(()=>re?.enabled?async function(y,x){const b=re.organizationId&&re.organizationId!=="default"?re.organizationId:D&&D.length>0?D[0]:void 0;try{const T={"Content-Type":"application/json"};oe.current&&(T.Authorization=`Bearer ${oe.current}`);const N=await fetch(`${I}/fetch`,{method:"POST",headers:T,body:JSON.stringify({doc_id:y,block_ids:x,...b?{organizationId:b}:{}})});if(!N.ok){const _=await N.text();return{success:!1,error:`Fetch failed: ${N.status} ${_}`}}const O=await N.json();return{success:!0,blocks:O.blocks||[],fullContent:O.fullContent||"",pageUrl:O.pageUrl||"",pageTitle:O.pageTitle||"",summary:`Fetched ${O.blocks?.length||0} blocks from ${O.pageTitle||y}`}}catch(T){return{success:!1,error:T instanceof Error?T.message:"Unknown error occurred"}}}:null,[re,I,oe]),Fe=f.useMemo(()=>{if(B&&B.config?.tools){const g=Nl(B.config.tools,o);return console.log("[useAgent] Merged remote config:",{remoteToolCount:B.config.tools.length,localToolCount:o.length,mergedToolCount:g.length}),g}return o},[B,o]),Ve=B?.enableRagTools??re?.enabled??!1,ss=f.useMemo(()=>{const g=[...Fe,...i];return Ve&&(ue&&g.push(ue),Re&&g.push(Re)),g},[Fe,i,ue,Re,Ve]),je=f.useMemo(()=>[...Fe,...i],[Fe,i]),We=f.useMemo(()=>tr(je,l),[je,l]),de=f.useMemo(()=>{const g=new Map,y=new Map(We.map(x=>[x.name,x]));return re?.enabled&&(ue&&g.set("searchDocs",ue),Re&&g.set("fetchDocContent",Re)),ss.forEach(x=>{if(x===ue||x===Re)return;const b=x[Me];if(b){const N=y.get(b);if(N){g.set(N.name,x);return}}const T=We.find(N=>N.name===x.name);T&&g.set(T.name,x)}),g},[ss,We,ue,Re,re]),Yt=f.useMemo(()=>new Set(We.map(g=>g.name)),[We]),ut=f.useMemo(()=>{const g=[];Ve&&g.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"]}});const y=[];return B?.config?.workflows&&B.config.workflows.forEach(x=>{const b={},T=[];x.parameters&&x.parameters.forEach(N=>{b[N.name]={type:N.type||"string",description:N.description},N.required&&T.push(N.name)}),y.push({name:`workflow_${x.name.replace(/\s+/g,"_").toLowerCase()}`,description:x.description||`Execute the "${x.name}" workflow. ${x.contentPlaintext?.slice(0,200)||""}`,jsonSchema:{type:"object",properties:b,required:T},_workflow:x})}),[...We,...g,...y]},[We,Ve,B]),ve=f.useMemo(()=>ut.filter(g=>g.name==="searchDocs"||g.name==="fetchDocContent"?Ve:g.name.startsWith("workflow_")?!0:Yt.has(g.name)),[ut,Yt,Ve]),Jt=f.useMemo(()=>{const g=new Set;return Ve&&re?.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent")),B?.config?.tools?B.config.tools.forEach(y=>{y.isEnabled&&!y.requiresApproval&&g.add(y.name)}):(i.forEach(y=>{for(const[x,b]of de.entries())if(b===y){g.add(x);break}}),a&&Array.isArray(a)&&a.forEach(y=>{typeof y=="string"&&g.add(y)})),B?.config?.workflows&&B.config.workflows.forEach(y=>{const x=`workflow_${y.name.replace(/\s+/g,"_").toLowerCase()}`;y.requiresApproval||g.add(x)}),g},[B,i,a,de,Ve,re]);f.useEffect(()=>{if(s||n)return;let g=!1,y=null;const x=async(b=1,T=3)=>{if(!g)try{const N=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!N.ok)throw new Error("Failed to fetch token");const O=await N.json();g||(pe(O.clientToken),oe.current=O.clientToken,vt(O.expiresAt),Ue(null))}catch(N){if(console.error(`[useAgent] Token fetch failed (attempt ${b}/${T}):`,N),b<T&&!g){const O=Math.pow(2,b-1)*1e3;y=setTimeout(()=>x(b+1,T),O)}else g||Ue(N instanceof Error?N.message:"Failed to fetch token")}};return x(),()=>{g=!0,y&&clearTimeout(y),ze.current&&clearTimeout(ze.current)}},[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!Le||s||n)return;ze.current&&clearTimeout(ze.current);const g=async(N=1,O=3)=>{try{const _=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!_.ok)throw new Error("Failed to refresh token");const k=await _.json();pe(k.clientToken),oe.current=k.clientToken,vt(k.expiresAt),Ue(null)}catch(_){if(console.error(`[useAgent] Token refresh failed (attempt ${N}/${O}):`,_),N<O){const k=Math.pow(2,N-1)*1e3;setTimeout(()=>g(N+1,O),k)}else Ue(_ instanceof Error?_.message:"Failed to refresh token")}},y=Math.floor(Date.now()/1e3),x=Le-y,T=Math.max(0,x-5);return ze.current=setTimeout(()=>g(),T*1e3),()=>{ze.current&&clearTimeout(ze.current)}},[Le,t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(s||n)return;const g=async()=>{if(document.visibilityState!=="visible")return;const y=Math.floor(Date.now()/1e3);if(!Le||Le<=y+5){console.log("[useAgent] Tab visible, token expired - refreshing");try{const b=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(b.ok){const T=await b.json();pe(T.clientToken),oe.current=T.clientToken,vt(T.expiresAt),Ue(null)}}catch(b){console.error("[useAgent] Token refresh on visibility change failed:",b)}}};return document.addEventListener("visibilitychange",g),()=>document.removeEventListener("visibilitychange",g)},[t,JSON.stringify(r),Le,s,n]);const rs=async(g,y={})=>{const x=y.headers?new Headers(y.headers):new Headers;return x.delete("user-agent"),x.delete("User-Agent"),fetch(g,{...y,headers:x})},jt=f.useRef(null),Nn=`${I}/chat`,{messages:Ke,sendMessage:is,status:Zt,error:Qt,stop:os,addToolResult:en,setMessages:tn}=dl.useChat({id:Ye||void 0,messages:U,transport:new Ur.DefaultChatTransport({api:Nn,fetch:rs,headers:()=>{const g={};return oe.current&&(g.Authorization=`Bearer ${oe.current}`),g},body:()=>({tools:ve.map(y=>({name:y.name,description:y.description,inputSchema:y.jsonSchema})),...w&&{agentId:w},...C&&{agentName:C},...V&&{ragFilters:V},...z&&{state:z}})}),sendAutomaticallyWhen:g=>{const y=g.messages;if(y[y.length-1]?.role!=="assistant")return!1;const T=[...y].reverse().find(O=>O.role==="user")?.id;if(T&&jt.current===T)return!1;const N=Ur.lastAssistantMessageIsCompleteWithToolCalls(g);return N&&T&&(jt.current=T),N}}),Dn=is,Rn=f.useCallback(g=>(jt.current=null,at.current=new Set,Dn(g)),[Dn]),Te=f.useCallback((g,y,x)=>{const b=Se(g,x);en({toolCallId:y,tool:g,output:b})},[en,Se]);f.useEffect(()=>{Ke.forEach(g=>{g.role==="assistant"&&g.parts.forEach(y=>{if(!y.type?.startsWith("tool-")||y.state!=="input-available")return;const x=y.type.replace("tool-",""),b=y.toolCallId;if(St.current.has(b)||Gt.current.has(b)){console.log(`[useAgent] Skipping ${x} (${b}) - already processing or completed`);return}console.log(`[useAgent] Starting ${x} (${b})`),St.current.add(b);const T=_=>{console.log(`[useAgent] Completed ${x} (${_})`),Gt.current.add(_),St.current.delete(_)},N=kl(y.input),O=`${x}:${JSON.stringify(N)}`;if(at.current.has(O)){console.log(`[useAgent] Skipping duplicate tool call: ${O}`),Te(x,b,"This tool was already called successfully with the same arguments in this response. Using previous result."),T(b);return}if(ct(x,N)){const _=De(x,N),k=Object.entries(_).filter(([K])=>N[K]!==void 0),G=k.length>0?Object.fromEntries(k):_,$=Object.keys(N),W=Ml(N,G);(async()=>{try{const K=Tl(x,$,G,N),ge={id:`${b}-form`,toolName:x,toolCallId:b,title:K.title,description:K.description,fields:K.fields},ae=await kn(ge);if(ae===null){Te(x,b,"User cancelled secure input"),T(b);return}const ye={...W,...ae},Pe=de.get(x);if(!Pe)throw new Error(`Tool ${x} not found`);let us;const ds=ve.find(Fr=>Fr.name===x);if(ds&&ds.jsonSchema?.properties){const nl=Object.keys(ds.jsonSchema.properties).map(sl=>ye[sl]);us=await Pe(...nl)}else us=await Pe(...Object.values(ye));T(b),Te(x,b,us),at.current.add(O)}catch(K){console.error(`[useAgent] Error executing tool with secure input ${x}:`,K),T(b),Te(x,b,`Error: ${K}`)}})();return}if(x.startsWith("workflow_")&&Jt.has(x)){(async()=>{try{const k=ve.find($=>$.name===x)?._workflow;if(!k)throw new Error(`Workflow metadata not found for ${x}`);let G;if(k.webhook?.url){let $=N;if(k.webhook.bodyTemplate){let K=k.webhook.bodyTemplate;Object.entries(N).forEach(([ge,ae])=>{K=K.replace(new RegExp(`\\{\\{${ge}\\}\\}`,"g"),String(ae))}),$=JSON.parse(K)}const W=await fetch(k.webhook.url,{method:k.webhook.method||"POST",headers:{"Content-Type":"application/json",...k.webhook.headers||{}},body:JSON.stringify($)});if(W.ok)G={success:!0,data:await W.json().catch(()=>({success:!0}))};else{const K=await W.text();G={success:!1,error:`Webhook failed: ${W.status} ${K}`}}}else G={success:!0,message:`Workflow "${k.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:k.contentPlaintext};T(b),Te(x,b,G),at.current.add(O)}catch(_){console.error(`[useAgent] Error executing workflow ${x}:`,_),T(b),Te(x,b,`Error: ${_}`)}})();return}if(Jt.has(x)&&!ct(x,N)){const _=de.get(x);_?(async()=>{try{const k=ve.find($=>$.name===x);let G;if(k&&k.jsonSchema?.properties){const W=Object.keys(k.jsonSchema.properties).map(K=>N[K]);G=await _(...W)}else G=await _(...Object.values(N));T(b),Te(x,b,G),at.current.add(O)}catch(k){console.error(`[useAgent] Error executing tool ${x}:`,k),T(b),Te(x,b,`Error: ${k}`)}})():(console.warn(`[useAgent] Tool ${x} not found in toolsMap`),Te(x,b,`Error: Tool "${x}" not found. The tool may not be registered or available.`),T(b))}else x.startsWith("workflow_")&&F?F({toolCall:{toolCallId:b,toolName:x,args:N}}):F?F({toolCall:{toolCallId:b,toolName:x,args:N}}):(console.warn(`[useAgent] No handler for tool ${x} - tool is not safe and no onToolCall callback provided`),Te(x,b,`Error: Tool "${x}" cannot be executed. No handler is available for this tool.`),T(b))})})},[Ke,Jt,de,F,Te,ve,ct,De,Mn]),f.useEffect(()=>{if(Zt==="ready"&&Ke.length>0&&E){const g=Ke[Ke.length-1];g&&g.role==="assistant"&&E({message:g,messages:Ke,isAbort:!1,isDisconnect:!1,isError:!!Qt})}},[Zt,Ke,Qt,E]);async function as(){if(!(!r?.id||!Ce)){ot(!0);try{const y=await(await fetch(`${I}/conversations`,{headers:{Authorization:`Bearer ${Ce}`}})).json();wt(y.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{ot(!1)}}}f.useEffect(()=>{r?.id&&Ce&&as()},[JSON.stringify(r),Ce,I]);async function ls(g){it(g),ot(!0);try{const y=await fetch(`${I}/conversations/${g}/messages`,{headers:{Authorization:`Bearer ${oe.current}`}});if(!y.ok)throw new Error(`Failed to fetch messages: ${y.statusText}`);const b=(await y.json()).messages||[];tn(b)}catch(y){console.error("Failed to load conversation messages:",y)}finally{ot(!1)}}async function cs(g){if(Ce)try{await fetch(`${I}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${Ce}`}}),wt(jn.filter(y=>y._id!==g)),g===Ye&&nn()}catch(y){console.error("Failed to delete conversation:",y)}}function nn(){const g=crypto.randomUUID();it(g),tn([]),St.current=new Set,Gt.current=new Set}function sn(g){const y=g.tool||"unknown-tool",x=Se(y,g.output);en({toolCallId:g.toolCallId,tool:y,output:x})}async function j(g,y,x){if(!y.startsWith("workflow_"))throw new Error(`${y} is not a workflow tool`);try{const T=ve.find(O=>O.name===y)?._workflow;if(!T)throw new Error(`Workflow metadata not found for ${y}`);let N;if(T.webhook?.url){let O=x;if(T.webhook.bodyTemplate){let k=T.webhook.bodyTemplate;Object.entries(x).forEach(([G,$])=>{k=k.replace(new RegExp(`\\{\\{${G}\\}\\}`,"g"),String($))}),O=JSON.parse(k)}const _=await fetch(T.webhook.url,{method:T.webhook.method||"POST",headers:{"Content-Type":"application/json",...T.webhook.headers||{}},body:JSON.stringify(O)});if(_.ok)N={success:!0,data:await _.json().catch(()=>({success:!0}))};else{const k=await _.text();N={success:!1,error:`Webhook failed: ${_.status} ${k}`}}}else N={success:!0,message:`Workflow "${T.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:T.contentPlaintext};return sn({toolCallId:g,tool:y,output:N}),N}catch(b){const T={success:!1,error:String(b)};throw sn({toolCallId:g,tool:y,output:T}),b}}return{id:Ye,messages:Ke,status:Zt,error:Qt,sendMessage:Rn,stop:os,addToolOutput:sn,executeWorkflowTool:j,setMessages:tn,conversations:jn,loadConversation:ls,deleteConversation:cs,startNewConversation:nn,isLoadingConversations:qt,clientToken:Ce,tokenError:Cn,pendingSecureInputs:Array.from(Tt.values()),completeSecureInput:Ht,pendingSecureForms:Array.from(Xe.values()),completeSecureForm:lt,safeToolNames:Jt}}function Z(...e){return fl.twMerge(hl.clsx(e))}const ht=lo.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"}}),me=Oe.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?ao.Slot:"button";return u.jsx(i,{ref:o,"data-slot":"button",className:Z(ht({variant:t,size:n,className:e})),...r})});me.displayName="Button";const Ll=lo.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 hs({className:e,variant:t,asChild:n=!1,...s}){const r=n?ao.Slot:"span";return u.jsx(r,{"data-slot":"badge",className:Z(Ll({variant:t}),e),...s})}const Fl=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Oe.useState(!0);Oe.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=Oe.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Oe.useRef(null),[l,c]=Oe.useState("");return Fl({textAreaRef:a,triggerAutoSize:l,maxHeight:e,minHeight:t}),f.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),Oe.useEffect(()=>{c(r)},[o?.defaultValue,r]),u.jsx("textarea",{...o,value:r,ref:a,className:Z("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=>{c(d.target.value),s?.(d)}})});mo.displayName="AutosizeTextarea";function Bl({delayDuration:e=0,...t}){return u.jsx(Dt.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Je({...e}){return u.jsx(Bl,{children:u.jsx(Dt.Root,{"data-slot":"tooltip",...e})})}function Ze({...e}){return u.jsx(Dt.Trigger,{"data-slot":"tooltip-trigger",...e})}function Qe({className:e,sideOffset:t=0,children:n,...s}){return u.jsx(Dt.Portal,{children:u.jsxs(Dt.Content,{"data-slot":"tooltip-content",sideOffset:t,className:Z("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,u.jsx(Dt.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function _r({className:e,...t}){return u.jsx("kbd",{"data-slot":"kbd",className:Z("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 nr=f.createContext({});function sr(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const rr=typeof window<"u",po=rr?f.useLayoutEffect:f.useEffect,Zn=f.createContext(null);function ir(e,t){e.indexOf(t)===-1&&e.push(t)}function or(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const qe=(e,t,n)=>n>t?t:n<e?e:n;function Ns(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let Ot=()=>{},Ge=()=>{};process.env.NODE_ENV!=="production"&&(Ot=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(Ns(t,n))},Ge=(e,t,n)=>{if(!e)throw new Error(Ns(t,n))});const He={},go=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function yo(e){return typeof e=="object"&&e!==null}const xo=e=>/^0[^.\s]+$/u.test(e);function ar(e){let t;return()=>(t===void 0&&(t=e()),t)}const Ne=e=>e,Ul=(e,t)=>n=>t(e(n)),vn=(...e)=>e.reduce(Ul),mn=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class lr{constructor(){this.subscriptions=[]}add(t){return ir(this.subscriptions,t),()=>or(this.subscriptions,t)}notify(t,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](t,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const $e=e=>e*1e3,ke=e=>e/1e3;function bo(e,t){return t?e*(1e3/t):0}const Xr=new Set;function cr(e,t,n){e||Xr.has(t)||(console.warn(Ns(t,n)),Xr.add(t))}const vo=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,zl=1e-7,_l=12;function Xl(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=vo(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>zl&&++a<_l);return i}function wn(e,t,n,s){if(e===t&&n===s)return Ne;const r=o=>Xl(o,0,1,e,n);return o=>o===0||o===1?o:vo(r(o),t,s)}const wo=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,So=e=>t=>1-e(1-t),To=wn(.33,1.53,.69,.99),ur=So(To),Co=wo(ur),jo=e=>(e*=2)<1?.5*ur(e):.5*(2-Math.pow(2,-10*(e-1))),dr=e=>1-Math.sin(Math.acos(e)),Po=So(dr),Ao=wo(dr),Wl=wn(.42,0,1,1),Kl=wn(0,0,.58,1),Eo=wn(.42,0,.58,1),ql=e=>Array.isArray(e)&&typeof e[0]!="number",Mo=e=>Array.isArray(e)&&typeof e[0]=="number",Wr={linear:Ne,easeIn:Wl,easeInOut:Eo,easeOut:Kl,circIn:dr,circInOut:Ao,circOut:Po,backIn:ur,backInOut:Co,backOut:To,anticipate:jo},Gl=e=>typeof e=="string",Kr=e=>{if(Mo(e)){Ge(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return wn(t,n,s,r)}else if(Gl(e))return Ge(Wr[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),Wr[e];return e},Vn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Hl(e,t){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function l(d){i.has(d)&&(c.schedule(d),e()),d(a)}const c={schedule:(d,h=!1,m=!1)=>{const v=m&&r?n:s;return h&&i.add(d),v.has(d)||v.add(d),d},cancel:d=>{s.delete(d),i.delete(d)},process:d=>{if(a=d,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(l),n.clear(),r=!1,o&&(o=!1,c.process(d))}};return c}const Yl=40;function ko(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Vn.reduce((A,U)=>(A[U]=Hl(o),A),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:h,preRender:m,render:p,postRender:v}=i,w=()=>{const A=He.useManualTiming?r.timestamp:performance.now();n=!1,He.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(A-r.timestamp,Yl),1)),r.timestamp=A,r.isProcessing=!0,a.process(r),l.process(r),c.process(r),d.process(r),h.process(r),m.process(r),p.process(r),v.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(w))},C=()=>{n=!0,s=!0,r.isProcessing||e(w)};return{schedule:Vn.reduce((A,U)=>{const R=i[U];return A[U]=(z,F=!1,E=!1)=>(n||C(),R.schedule(z,F,E)),A},{}),cancel:A=>{for(let U=0;U<Vn.length;U++)i[Vn[U]].cancel(A)},state:r,steps:i}}const{schedule:te,cancel:tt,state:he,steps:fs}=ko(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ne,!0);let Un;function Jl(){Un=void 0}const we={now:()=>(Un===void 0&&we.set(he.isProcessing||He.useManualTiming?he.timestamp:performance.now()),Un),set:e=>{Un=e,queueMicrotask(Jl)}},No=e=>t=>typeof t=="string"&&t.startsWith(e),hr=No("--"),Zl=No("var(--"),fr=e=>Zl(e)?Ql.test(e.split("/*")[0].trim()):!1,Ql=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,$t={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},pn={...$t,transform:e=>qe(0,1,e)},In={...$t,default:1},cn=e=>Math.round(e*1e5)/1e5,mr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function ec(e){return e==null}const tc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,pr=(e,t)=>n=>!!(typeof n=="string"&&tc.test(n)&&n.startsWith(e)||t&&!ec(n)&&Object.prototype.hasOwnProperty.call(n,t)),Do=(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}},nc=e=>qe(0,255,e),ms={...$t,transform:e=>Math.round(nc(e))},mt={test:pr("rgb","red"),parse:Do("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+ms.transform(e)+", "+ms.transform(t)+", "+ms.transform(n)+", "+cn(pn.transform(s))+")"};function sc(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 Ds={test:pr("#"),parse:sc,transform:mt.transform},Sn=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),et=Sn("deg"),Be=Sn("%"),X=Sn("px"),rc=Sn("vh"),ic=Sn("vw"),qr={...Be,parse:e=>Be.parse(e)/100,transform:e=>Be.transform(e*100)},Pt={test:pr("hsl","hue"),parse:Do("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Be.transform(cn(t))+", "+Be.transform(cn(n))+", "+cn(pn.transform(s))+")"},le={test:e=>mt.test(e)||Ds.test(e)||Pt.test(e),parse:e=>mt.test(e)?mt.parse(e):Pt.test(e)?Pt.parse(e):Ds.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?mt.transform(e):Pt.transform(e),getAnimatableNone:e=>{const t=le.parse(e);return t.alpha=0,le.transform(t)}},oc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ac(e){return isNaN(e)&&typeof e=="string"&&(e.match(mr)?.length||0)+(e.match(oc)?.length||0)>0}const Ro="number",Vo="color",lc="var",cc="var(",Gr="${}",uc=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function gn(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(uc,l=>(le.test(l)?(s.color.push(o),r.push(Vo),n.push(le.parse(l))):l.startsWith(cc)?(s.var.push(o),r.push(lc),n.push(l)):(s.number.push(o),r.push(Ro),n.push(parseFloat(l))),++o,Gr)).split(Gr);return{values:n,split:a,indexes:s,types:r}}function Io(e){return gn(e).values}function Oo(e){const{split:t,types:n}=gn(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===Ro?o+=cn(r[i]):a===Vo?o+=le.transform(r[i]):o+=r[i]}return o}}const dc=e=>typeof e=="number"?0:le.test(e)?le.getAnimatableNone(e):e;function hc(e){const t=Io(e);return Oo(e)(t.map(dc))}const nt={test:ac,parse:Io,createTransformer:Oo,getAnimatableNone:hc};function ps(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 fc({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=ps(l,a,e+1/3),o=ps(l,a,e),i=ps(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function Kn(e,t){return n=>n>0?t:e}const se=(e,t,n)=>e+(t-e)*n,gs=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},mc=[Ds,mt,Pt],pc=e=>mc.find(t=>t.test(e));function Hr(e){const t=pc(e);if(Ot(!!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===Pt&&(n=fc(n)),n}const Yr=(e,t)=>{const n=Hr(e),s=Hr(t);if(!n||!s)return Kn(e,t);const r={...n};return o=>(r.red=gs(n.red,s.red,o),r.green=gs(n.green,s.green,o),r.blue=gs(n.blue,s.blue,o),r.alpha=se(n.alpha,s.alpha,o),mt.transform(r))},Rs=new Set(["none","hidden"]);function gc(e,t){return Rs.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function yc(e,t){return n=>se(e,t,n)}function gr(e){return typeof e=="number"?yc:typeof e=="string"?fr(e)?Kn:le.test(e)?Yr:vc:Array.isArray(e)?$o:typeof e=="object"?le.test(e)?Yr:xc:Kn}function $o(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>gr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function xc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=gr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function bc(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 vc=(e,t)=>{const n=nt.createTransformer(t),s=gn(e),r=gn(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?Rs.has(e)&&!r.values.length||Rs.has(t)&&!s.values.length?gc(e,t):vn($o(bc(s,r),r.values),n):(Ot(!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"),Kn(e,t))};function Lo(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?se(e,t,n):gr(e)(e,t)}const wc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>te.update(t,n),stop:()=>tt(t),now:()=>he.isProcessing?he.timestamp:we.now()}},Fo=(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)})`},qn=2e4;function yr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<qn;)t+=n,s=e.next(t);return t>=qn?1/0:t}function Sc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(yr(s),qn);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:ke(r)}}const Tc=5;function Bo(e,t,n){const s=Math.max(t-Tc,0);return bo(n-e(s),t-s)}const ne={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},ys=.001;function Cc({duration:e=ne.duration,bounce:t=ne.bounce,velocity:n=ne.velocity,mass:s=ne.mass}){let r,o;Ot(e<=$e(ne.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=qe(ne.minDamping,ne.maxDamping,i),e=qe(ne.minDuration,ne.maxDuration,ke(e)),i<1?(r=c=>{const d=c*i,h=d*e,m=d-n,p=Vs(c,i),v=Math.exp(-h);return ys-m/p*v},o=c=>{const h=c*i*e,m=h*n+n,p=Math.pow(i,2)*Math.pow(c,2)*e,v=Math.exp(-h),w=Vs(Math.pow(c,2),i);return(-r(c)+ys>0?-1:1)*((m-p)*v)/w}):(r=c=>{const d=Math.exp(-c*e),h=(c-n)*e+1;return-ys+d*h},o=c=>{const d=Math.exp(-c*e),h=(n-c)*(e*e);return d*h});const a=5/e,l=Pc(r,o,a);if(e=$e(e),isNaN(l))return{stiffness:ne.stiffness,damping:ne.damping,duration:e};{const c=Math.pow(l,2)*s;return{stiffness:c,damping:i*2*Math.sqrt(s*c),duration:e}}}const jc=12;function Pc(e,t,n){let s=n;for(let r=1;r<jc;r++)s=s-e(s)/t(s);return s}function Vs(e,t){return e*Math.sqrt(1-t*t)}const Ac=["duration","bounce"],Ec=["stiffness","damping","mass"];function Jr(e,t){return t.some(n=>e[n]!==void 0)}function Mc(e){let t={velocity:ne.velocity,stiffness:ne.stiffness,damping:ne.damping,mass:ne.mass,isResolvedFromDuration:!1,...e};if(!Jr(e,Ec)&&Jr(e,Ac))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*qe(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:ne.mass,stiffness:r,damping:o}}else{const n=Cc(e);t={...t,...n,mass:ne.mass},t.isResolvedFromDuration=!0}return t}function Gn(e=ne.visualDuration,t=ne.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:c,mass:d,duration:h,velocity:m,isResolvedFromDuration:p}=Mc({...n,velocity:-ke(n.velocity||0)}),v=m||0,w=c/(2*Math.sqrt(l*d)),C=i-o,S=ke(Math.sqrt(l/d)),M=Math.abs(C)<5;s||(s=M?ne.restSpeed.granular:ne.restSpeed.default),r||(r=M?ne.restDelta.granular:ne.restDelta.default);let A;if(w<1){const R=Vs(S,w);A=z=>{const F=Math.exp(-w*S*z);return i-F*((v+w*S*C)/R*Math.sin(R*z)+C*Math.cos(R*z))}}else if(w===1)A=R=>i-Math.exp(-S*R)*(C+(v+S*C)*R);else{const R=S*Math.sqrt(w*w-1);A=z=>{const F=Math.exp(-w*S*z),E=Math.min(R*z,300);return i-F*((v+w*S*C)*Math.sinh(E)+R*C*Math.cosh(E))/R}}const U={calculatedDuration:p&&h||null,next:R=>{const z=A(R);if(p)a.done=R>=h;else{let F=R===0?v:0;w<1&&(F=R===0?$e(v):Bo(A,R,z));const E=Math.abs(F)<=s,D=Math.abs(i-z)<=r;a.done=E&&D}return a.value=a.done?i:z,a},toString:()=>{const R=Math.min(yr(U),qn),z=Fo(F=>U.next(R*F).value,R,30);return R+"ms "+z},toTransition:()=>{}};return U}Gn.applyToOptions=e=>{const t=Sc(e,100,Gn);return e.ease=t.ease,e.duration=$e(t.duration),e.type="keyframes",e};function Is({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:l,restDelta:c=.5,restSpeed:d}){const h=e[0],m={done:!1,value:h},p=E=>a!==void 0&&E<a||l!==void 0&&E>l,v=E=>a===void 0?l:l===void 0||Math.abs(a-E)<Math.abs(l-E)?a:l;let w=n*t;const C=h+w,S=i===void 0?C:i(C);S!==C&&(w=S-h);const M=E=>-w*Math.exp(-E/s),A=E=>S+M(E),U=E=>{const D=M(E),P=A(E);m.done=Math.abs(D)<=c,m.value=m.done?S:P};let R,z;const F=E=>{p(m.value)&&(R=E,z=Gn({keyframes:[m.value,v(m.value)],velocity:Bo(A,E,m.value),damping:r,stiffness:o,restDelta:c,restSpeed:d}))};return F(0),{calculatedDuration:null,next:E=>{let D=!1;return!z&&R===void 0&&(D=!0,U(E),F(E)),R!==void 0&&E>=R?z.next(E-R):(!D&&U(E),m)}}}function kc(e,t,n){const s=[],r=n||He.mix||Lo,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]||Ne:t;a=vn(l,a)}s.push(a)}return s}function Nc(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(Ge(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=kc(t,s,r),l=a.length,c=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=mn(e[h],e[h+1],d);return a[h](m)};return n?d=>c(qe(e[0],e[o-1],d)):c}function Dc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=mn(0,t,s);e.push(se(n,1,r))}}function Rc(e){const t=[0];return Dc(t,e.length-1),t}function Vc(e,t){return e.map(n=>n*t)}function Ic(e,t){return e.map(()=>t||Eo).splice(0,e.length-1)}function At({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=ql(s)?s.map(Kr):Kr(s),o={done:!1,value:t[0]},i=Vc(n&&n.length===t.length?n:Rc(t),e),a=Nc(i,t,{ease:Array.isArray(r)?r:Ic(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const Oc=e=>e!==null;function xr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(Oc),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const $c={decay:Is,inertia:Is,tween:At,keyframes:At,spring:Gn};function Uo(e){typeof e.type=="string"&&(e.type=$c[e.type])}class br{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 Lc=e=>e/100;class vr extends br{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!==we.now()&&this.tick(we.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;Uo(t);const{type:n=At,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const l=n||At;process.env.NODE_ENV!=="production"&&l!==At&&Ge(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),l!==At&&typeof a[0]!="number"&&(this.mixKeyframes=vn(Lc,Lo(a[0],a[1])),a=[0,100]);const c=l({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...t,keyframes:[...a].reverse(),velocity:-i})),c.calculatedDuration===null&&(c.calculatedDuration=yr(c));const{calculatedDuration:d}=c;this.calculatedDuration=d,this.resolvedDuration=d+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=c}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:c=0,keyframes:d,repeat:h,repeatType:m,repeatDelay:p,type:v,onUpdate:w,finalKeyframe:C}=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 S=this.currentTime-c*(this.playbackSpeed>=0?1:-1),M=this.playbackSpeed>=0?S<0:S>r;this.currentTime=Math.max(S,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let A=this.currentTime,U=s;if(h){const E=Math.min(this.currentTime,r)/a;let D=Math.floor(E),P=E%1;!P&&E>=1&&(P=1),P===1&&D--,D=Math.min(D,h+1),!!(D%2)&&(m==="reverse"?(P=1-P,p&&(P-=p/a)):m==="mirror"&&(U=i)),A=qe(0,1,P)*a}const R=M?{done:!1,value:d[0]}:U.next(A);o&&(R.value=o(R.value));let{done:z}=R;!M&&l!==null&&(z=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const F=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&z);return F&&v!==Is&&(R.value=xr(d,this.options,C,this.speed)),w&&w(R.value),F&&this.finish(),R}then(t,n){return this.finished.then(t,n)}get duration(){return ke(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+ke(t)}get time(){return ke(this.currentTime)}set time(t){t=$e(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(we.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=ke(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=wc,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(we.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 Fc(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const pt=e=>e*180/Math.PI,Os=e=>{const t=pt(Math.atan2(e[1],e[0]));return $s(t)},Bc={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Os,rotateZ:Os,skewX:e=>pt(Math.atan(e[1])),skewY:e=>pt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},$s=e=>(e=e%360,e<0&&(e+=360),e),Zr=Os,Qr=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),ei=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),Uc={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Qr,scaleY:ei,scale:e=>(Qr(e)+ei(e))/2,rotateX:e=>$s(pt(Math.atan2(e[6],e[5]))),rotateY:e=>$s(pt(Math.atan2(-e[2],e[0]))),rotateZ:Zr,rotate:Zr,skewX:e=>pt(Math.atan(e[4])),skewY:e=>pt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Ls(e){return e.includes("scale")?1:0}function Fs(e,t){if(!e||e==="none")return Ls(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=Uc,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=Bc,r=a}if(!r)return Ls(t);const o=s[t],i=r[1].split(",").map(_c);return typeof o=="function"?o(i):i[o]}const zc=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Fs(n,t)};function _c(e){return parseFloat(e.trim())}const Lt=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ft=new Set(Lt),ti=e=>e===$t||e===X,Xc=new Set(["x","y","z"]),Wc=Lt.filter(e=>!Xc.has(e));function Kc(e){const t=[];return Wc.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const gt={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})=>Fs(t,"x"),y:(e,{transform:t})=>Fs(t,"y")};gt.translateX=gt.x;gt.translateY=gt.y;const yt=new Set;let Bs=!1,Us=!1,zs=!1;function zo(){if(Us){const e=Array.from(yt).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=Kc(s);r.length&&(n.set(s,r),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),e.forEach(s=>s.measureEndState()),e.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}Us=!1,Bs=!1,yt.forEach(e=>e.complete(zs)),yt.clear()}function _o(){yt.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Us=!0)})}function qc(){zs=!0,_o(),zo(),zs=!1}class wr{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?(yt.add(this),Bs||(Bs=!0,te.read(_o),te.resolveKeyframes(zo))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:r}=this;if(t[0]===null){const o=r?.get(),i=t[t.length-1];if(o!==void 0)t[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=i),r&&o===void 0&&r.set(t[0])}Fc(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),yt.delete(this)}cancel(){this.state==="scheduled"&&(yt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Gc=e=>e.startsWith("--");function Hc(e,t,n){Gc(t)?e.style.setProperty(t,n):e.style[t]=n}const Yc=ar(()=>window.ScrollTimeline!==void 0),Jc={};function Zc(e,t){const n=ar(e);return()=>Jc[t]??n()}const Xo=Zc(()=>{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})`,ni={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 Wo(e,t){if(e)return typeof e=="function"?Xo()?Fo(e,t):"ease-out":Mo(e)?an(e):Array.isArray(e)?e.map(n=>Wo(n,t)||ni.easeOut):ni[e]}function Qc(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:l}={},c=void 0){const d={[t]:n};l&&(d.offset=l);const h=Wo(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 c&&(m.pseudoElement=c),e.animate(d,m)}function Ko(e){return typeof e=="function"&&"applyToOptions"in e}function eu({type:e,...t}){return Ko(e)&&Xo()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class tu extends br{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,Ge(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const c=eu(t);this.animation=Qc(n,s,r,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=xr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Hc(n,s,d),this.animation.cancel()}l?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return ke(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+ke(t)}get time(){return ke(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=$e(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&Yc()?(this.animation.timeline=t,Ne):n(this)}}const qo={anticipate:jo,backInOut:Co,circInOut:Ao};function nu(e){return e in qo}function su(e){typeof e.ease=="string"&&nu(e.ease)&&(e.ease=qo[e.ease])}const si=10;class ru extends tu{constructor(t){su(t),Uo(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new vr({...i,autoplay:!1}),l=$e(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-si).value,a.sample(l).value,si),a.stop()}}const ri=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(nt.test(e)||e==="0")&&!e.startsWith("url("));function iu(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 ou(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=ri(r,t),a=ri(o,t);return Ot(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:iu(e)||(n==="spring"||Ko(n))&&s}function _s(e){e.duration=0,e.type="keyframes"}const au=new Set(["opacity","clipPath","filter","transform"]),lu=ar(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function cu(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:c}=t.owner.getProps();return lu()&&n&&au.has(n)&&(n!=="transform"||!c)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const uu=40;class du extends br{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:l,motionValue:c,element:d,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=we.now();const m={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:l,motionValue:c,element:d,...h},p=d?.KeyframeResolver||wr;this.keyframeResolver=new p(a,(v,w,C)=>this.onKeyframesResolved(v,w,m,!C),l,c,d),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:l,isHandoff:c,onUpdate:d}=s;this.resolvedAt=we.now(),ou(t,o,i,a)||((He.instantAnimations||!l)&&d?.(xr(t,s,n)),t[0]=t[t.length-1],_s(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>uu?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!c&&cu(m)?new ru({...m,element:m.motionValue.owner.current}):new vr(m);p.finished.then(()=>this.notifyFinished()).catch(Ne),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(),qc()),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 hu=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function fu(e){const t=hu.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const mu=4;function Go(e,t,n=1){Ge(n<=mu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=fu(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return go(i)?parseFloat(i):i}return fr(r)?Go(r,t,n+1):r}function Sr(e,t){return e?.[t]??e?.default??e}const Ho=new Set(["width","height","top","left","right","bottom",...Lt]),pu={test:e=>e==="auto",parse:e=>e},Yo=e=>t=>t.test(e),Jo=[$t,X,Be,et,ic,rc,pu],ii=e=>Jo.find(Yo(e));function gu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||xo(e):!0}const yu=new Set(["brightness","contrast","saturate","opacity"]);function xu(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=yu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const bu=/\b([a-z-]*)\(.*?\)/gu,Xs={...nt,getAnimatableNone:e=>{const t=e.match(bu);return t?t.map(xu).join(" "):e}},oi={...$t,transform:Math.round},vu={rotate:et,rotateX:et,rotateY:et,rotateZ:et,scale:In,scaleX:In,scaleY:In,scaleZ:In,skew:et,skewX:et,skewY:et,distance:X,translateX:X,translateY:X,translateZ:X,x:X,y:X,z:X,perspective:X,transformPerspective:X,opacity:pn,originX:qr,originY:qr,originZ:X},Tr={borderWidth:X,borderTopWidth:X,borderRightWidth:X,borderBottomWidth:X,borderLeftWidth:X,borderRadius:X,radius:X,borderTopLeftRadius:X,borderTopRightRadius:X,borderBottomRightRadius:X,borderBottomLeftRadius:X,width:X,maxWidth:X,height:X,maxHeight:X,top:X,right:X,bottom:X,left:X,padding:X,paddingTop:X,paddingRight:X,paddingBottom:X,paddingLeft:X,margin:X,marginTop:X,marginRight:X,marginBottom:X,marginLeft:X,backgroundPositionX:X,backgroundPositionY:X,...vu,zIndex:oi,fillOpacity:pn,strokeOpacity:pn,numOctaves:oi},wu={...Tr,color:le,backgroundColor:le,outlineColor:le,fill:le,stroke:le,borderColor:le,borderTopColor:le,borderRightColor:le,borderBottomColor:le,borderLeftColor:le,filter:Xs,WebkitFilter:Xs},Zo=e=>wu[e];function Qo(e,t){let n=Zo(e);return n!==Xs&&(n=nt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Su=new Set(["auto","none","0"]);function Tu(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!Su.has(o)&&gn(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=Qo(n,r)}class Cu extends wr{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 c=t[l];if(typeof c=="string"&&(c=c.trim(),fr(c))){const d=Go(c,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Ho.has(s)||t.length!==2)return;const[r,o]=t,i=ii(r),a=ii(o);if(i!==a)if(ti(i)&&ti(a))for(let l=0;l<t.length;l++){const c=t[l];typeof c=="string"&&(t[l]=parseFloat(c))}else gt[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||gu(t[r]))&&s.push(r);s.length&&Tu(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=gt[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]=gt[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 ju(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 ea=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function ta(e){return yo(e)&&"offsetHeight"in e}const ai=30,Pu=e=>!isNaN(parseFloat(e));class Au{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=we.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=we.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Pu(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&cr(!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 lr);const s=this.events[t].add(n);return t==="change"?()=>{s(),te.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=we.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>ai)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,ai);return bo(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 Vt(e,t){return new Au(e,t)}const{schedule:Cr}=ko(queueMicrotask,!1),Ie={x:!1,y:!1};function na(){return Ie.x||Ie.y}function Eu(e){return e==="x"||e==="y"?Ie[e]?null:(Ie[e]=!0,()=>{Ie[e]=!1}):Ie.x||Ie.y?null:(Ie.x=Ie.y=!0,()=>{Ie.x=Ie.y=!1})}function sa(e,t){const n=ju(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function li(e){return!(e.pointerType==="touch"||na())}function Mu(e,t,n={}){const[s,r,o]=sa(e,n),i=a=>{if(!li(a))return;const{target:l}=a,c=t(l,a);if(typeof c!="function"||!l)return;const d=h=>{li(h)&&(c(h),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ra=(e,t)=>t?e===t?!0:ra(e,t.parentElement):!1,jr=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,ku=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Nu(e){return ku.has(e.tagName)||e.tabIndex!==-1}const zn=new WeakSet;function ci(e){return t=>{t.key==="Enter"&&e(t)}}function xs(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Du=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=ci(()=>{if(zn.has(n))return;xs(n,"down");const r=ci(()=>{xs(n,"up")}),o=()=>xs(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 ui(e){return jr(e)&&!na()}function Ru(e,t,n={}){const[s,r,o]=sa(e,n),i=a=>{const l=a.currentTarget;if(!ui(a))return;zn.add(l);const c=t(l,a),d=(p,v)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),zn.has(l)&&zn.delete(l),ui(p)&&typeof c=="function"&&c(p,{success:v})},h=p=>{d(p,l===window||l===document||n.useGlobalTarget||ra(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),ta(a)&&(a.addEventListener("focus",c=>Du(c,r)),!Nu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function ia(e){return yo(e)&&"ownerSVGElement"in e}function Vu(e){return ia(e)&&e.tagName==="svg"}const fe=e=>!!(e&&e.getVelocity),Iu=[...Jo,le,nt],Ou=e=>Iu.find(Yo(e)),Pr=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function di(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function $u(...e){return t=>{let n=!1;const s=e.map(r=>{const o=di(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():di(e[r],null)}}}}function Lu(...e){return Oe.useCallback($u(...e),e)}class Fu extends Oe.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=ta(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 Bu({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(Pr),l=Lu(o,e?.ref);return f.useInsertionEffect(()=>{const{width:c,height:d,top:h,left:m,right:p}=i.current;if(t||!o.current||!c||!d)return;const v=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const w=document.createElement("style");a&&(w.nonce=a);const C=s??document.head;return C.appendChild(w),w.sheet&&w.sheet.insertRule(`
5
3
  [data-motion-pop-id="${r}"] {
6
4
  position: absolute !important;
7
5
  width: ${c}px !important;
@@ -9,10 +7,10 @@ ${JSON.stringify($,null,2)}`}]),At.current=$}},[$,ht]);const Qt=f.useCallback(g=
9
7
  ${v}px !important;
10
8
  top: ${h}px !important;
11
9
  }
12
- `),()=>{T.contains(w)&&T.removeChild(w)}},[t]),u.jsx(Bu,{isPresent:t,childRef:o,sizeRef:i,children:Ie.cloneElement(e,{ref:l})})}const zu=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const c=sr(_u),d=f.useId();let h=!0,m=f.useMemo(()=>(h=!1,{id:d,initial:t,isPresent:n,custom:r,onExitComplete:p=>{c.set(p,!0);for(const v of c.values())if(!v)return;s&&s()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[n,c,s]);return o&&h&&(m={...m}),f.useMemo(()=>{c.forEach((p,v)=>c.set(v,!1))},[n]),Ie.useEffect(()=>{!n&&!c.size&&s&&s()},[n]),i==="popLayout"&&(e=u.jsx(Uu,{isPresent:n,anchorX:a,root:l,children:e})),u.jsx(Qn.Provider,{value:m,children:e})};function _u(){return new Map}function aa(e=!0){const t=f.useContext(Qn);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 $n=e=>e.key||"";function fi(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const Xu=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:l})=>{const[c,d]=aa(i),h=f.useMemo(()=>fi(e),[e]),m=i&&!c?[]:h.map($n),p=f.useRef(!0),v=f.useRef(h),w=sr(()=>new Map),[T,S]=f.useState(h),[k,E]=f.useState(h);go(()=>{p.current=!1,v.current=h;for(let $=0;$<k.length;$++){const F=$n(k[$]);m.includes(F)?w.delete(F):w.get(F)!==!0&&w.set(F,!1)}},[k,m.length,m.join("-")]);const U=[];if(h!==T){let $=[...h];for(let F=0;F<k.length;F++){const M=k[F],R=$n(M);m.includes(R)||($.splice(F,0,M),U.push(M))}return o==="wait"&&U.length&&($=U),E(fi($)),S(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(nr);return u.jsx(u.Fragment,{children:k.map($=>{const F=$n($),M=i&&!c?!1:h===k||m.includes(F),R=()=>{if(w.has(F))w.set(F,!0);else return;let A=!0;w.forEach(V=>{V||(A=!1)}),A&&(D?.(),E(v.current),i&&d?.(),s&&s())};return u.jsx(zu,{isPresent:M,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:l,onExitComplete:M?void 0:R,anchorX:a,children:$},F)})})},Ar=f.createContext({strict:!1}),mi={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"]},Ft={};for(const e in mi)Ft[e]={isEnabled:t=>mi[e].some(n=>!!t[n])};function Ws(e){for(const t in e)Ft[t]={...Ft[t],...e[t]}}function Wu({children:e,features:t,strict:n=!1}){const[,s]=f.useState(!bs(t)),r=f.useRef(void 0);if(!bs(t)){const{renderer:o,...i}=t;r.current=o,Ws(i)}return f.useEffect(()=>{bs(t)&&t().then(({renderer:o,...i})=>{Ws(i),r.current=o,s(!0)})},[]),u.jsx(Ar.Provider,{value:{renderer:r.current,strict:n},children:e})}function bs(e){return typeof e=="function"}const Ku=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 Yn(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Ku.has(e)}let la=e=>!Yn(e);function qu(e){typeof e=="function"&&(la=t=>t.startsWith("on")?!Yn(t):e(t))}try{qu(require("@emotion/is-prop-valid").default)}catch{}function Gu(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(la(r)||n===!0&&Yn(r)||!t&&!Yn(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const es=f.createContext({});function ts(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function xn(e){return typeof e=="string"||Array.isArray(e)}const Er=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Mr=["initial",...Er];function ns(e){return ts(e.animate)||Mr.some(t=>xn(e[t]))}function ca(e){return!!(ns(e)||e.variants)}function Hu(e,t){if(ns(e)){const{initial:n,animate:s}=e;return{initial:n===!1||xn(n)?n:void 0,animate:xn(s)?s:void 0}}return e.inherit!==!1?t:{}}function Yu(e){const{initial:t,animate:n}=Hu(e,f.useContext(es));return f.useMemo(()=>({initial:t,animate:n}),[pi(t),pi(n)])}function pi(e){return Array.isArray(e)?e.join(" "):e}const bn={};function Ju(e){for(const t in e)bn[t]=e[t],hr(t)&&(bn[t].isCSSVariable=!0)}function ua(e,{layout:t,layoutId:n}){return _t.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!bn[e]||e==="opacity")}const Zu={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Qu=zt.length;function ed(e,t,n){let s="",r=!0;for(let o=0;o<Qu;o++){const i=zt[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 c=ta(a,Tr[i]);if(!l){r=!1;const d=Zu[i]||i;s+=`${d}(${c}) `}n&&(t[i]=c)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function kr(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const l in t){const c=t[l];if(_t.has(l)){i=!0;continue}else if(hr(l)){r[l]=c;continue}else{const d=ta(c,Tr[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=ed(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:d=0}=o;s.transformOrigin=`${l} ${c} ${d}`}}const Nr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function da(e,t,n){for(const s in t)!me(t[s])&&!ua(s,n)&&(e[s]=t[s])}function td({transformTemplate:e},t){return f.useMemo(()=>{const n=Nr();return kr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function nd(e,t){const n=e.style||{},s={};return da(s,n,e),Object.assign(s,td(e,t)),s}function sd(e,t){const n={},s=nd(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const rd={offset:"stroke-dashoffset",array:"stroke-dasharray"},id={offset:"strokeDashoffset",array:"strokeDasharray"};function od(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?rd:id;e[o.offset]=K.transform(-s);const i=K.transform(t),a=K.transform(n);e[o.array]=`${i} ${a}`}function ha(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,c,d){if(kr(e,a,c),l){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:h,style:m}=e;h.transform&&(m.transform=h.transform,delete h.transform),(m.transform||h.transformOrigin)&&(m.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),m.transform&&(m.transformBox=d?.transformBox??"fill-box",delete h.transformBox),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),r!==void 0&&od(h,r,o,i,!1)}const fa=()=>({...Nr(),attrs:{}}),ma=e=>typeof e=="string"&&e.toLowerCase()==="svg";function ad(e,t,n,s){const r=f.useMemo(()=>{const o=fa();return ha(o,t,ma(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};da(o,e.style,e),r.style={...o,...r.style}}return r}const ld=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Rr(e){return typeof e!="string"||e.includes("-")?!1:!!(ld.indexOf(e)>-1||/[A-Z]/u.test(e))}function cd(e,t,n,{latestValues:s},r,o=!1){const a=(Rr(e)?ad:sd)(t,s,r,e),l=Gu(t,typeof e=="string",o),c=e!==f.Fragment?{...l,...a,ref:n}:{},{children:d}=t,h=f.useMemo(()=>me(d)?d.get():d,[d]);return f.createElement(e,{...c,children:h})}function gi(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Dr(e,t,n,s){if(typeof t=="function"){const[r,o]=gi(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]=gi(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function Xn(e){return me(e)?e.get():e}function ud({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:dd(n,s,r,e),renderState:t()}}function dd(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=Xn(o[m]);let{initial:i,animate:a}=e;const l=ns(e),c=ca(e);t&&c&&!l&&e.inherit!==!1&&(i===void 0&&(i=t.initial),a===void 0&&(a=t.animate));let d=n?n.initial===!1:!1;d=d||i===!1;const h=d?a:i;if(h&&typeof h!="boolean"&&!ts(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p<m.length;p++){const v=Dr(e,m[p]);if(v){const{transitionEnd:w,transition:T,...S}=v;for(const k in S){let E=S[k];if(Array.isArray(E)){const U=d?E.length-1:0;E=E[U]}E!==null&&(r[k]=E)}for(const k in w)r[k]=w[k]}}}return r}const pa=e=>(t,n)=>{const s=f.useContext(es),r=f.useContext(Qn),o=()=>ud(e,t,s,r);return n?o():sr(o)};function Vr(e,t,n){const{style:s}=e,r={};for(const o in s)(me(s[o])||t.style&&me(t.style[o])||ua(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const hd=pa({scrapeMotionValuesFromProps:Vr,createRenderState:Nr});function ga(e,t,n){const s=Vr(e,t,n);for(const r in e)if(me(e[r])||me(t[r])){const o=zt.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const fd=pa({scrapeMotionValuesFromProps:ga,createRenderState:fa}),md=Symbol.for("motionComponentSymbol");function Rt(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function pd(e,t,n){return f.useCallback(s=>{s&&e.onMount&&e.onMount(s),t&&(s?t.mount(s):t.unmount()),n&&(typeof n=="function"?n(s):Rt(n)&&(n.current=s))},[t])}const Ir=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),gd="framerAppearId",ya="data-"+Ir(gd),xa=f.createContext({});function yd(e,t,n,s,r){const{visualElement:o}=f.useContext(es),i=f.useContext(Ar),a=f.useContext(Qn),l=f.useContext(Pr).reducedMotion,c=f.useRef(null);s=s||i.renderer,!c.current&&s&&(c.current=s(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const d=c.current,h=f.useContext(xa);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&xd(c.current,n,r,h);const m=f.useRef(!1);f.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[ya],v=f.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return go(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),v.current&&d.animationState&&d.animationState.animateChanges())}),f.useEffect(()=>{d&&(!v.current&&d.animationState&&d.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),v.current=!1),d.enteringChildren=void 0)}),d}function xd(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:ba(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Rt(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:l,layoutRoot:c})}function ba(e){if(e)return e.options.allowProjection!==!1?e.projection:ba(e.parent)}function Wn(e,{forwardMotionProps:t=!1}={},n,s){n&&Ws(n);const r=Rr(e)?fd:hd;function o(a,l){let c;const d={...f.useContext(Pr),...a,layoutId:bd(a)},{isStatic:h}=d,m=Yu(a),p=r(a,h);if(!h&&rr){vd(d,n);const v=wd(d);c=v.MeasureLayout,m.visualElement=yd(e,p,d,s,v.ProjectionNode)}return u.jsxs(es.Provider,{value:m,children:[c&&m.visualElement?u.jsx(c,{visualElement:m.visualElement,...d}):null,cd(e,a,pd(p,m.visualElement,l),p,h,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=f.forwardRef(o);return i[md]=e,i}function bd({layoutId:e}){const t=f.useContext(nr).id;return t&&e!==void 0?t+"-"+e:e}function vd(e,t){const n=f.useContext(Ar).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?Bt(!1,s,"lazy-strict-mode"):qe(!1,s,"lazy-strict-mode")}}function wd(e){const{drag:t,layout:n}=Ft;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Sd(e,t){if(typeof Proxy>"u")return Wn;const n=new Map,s=(o,i)=>Wn(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&cr(!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,Wn(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 Td({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Cd(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 vs(e){return e===void 0||e===1}function Ks({scale:e,scaleX:t,scaleY:n}){return!vs(e)||!vs(t)||!vs(n)}function pt(e){return Ks(e)||wa(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function wa(e){return yi(e.x)||yi(e.y)}function yi(e){return e&&e!=="0%"}function Jn(e,t,n){const s=e-n,r=t*s;return n+r}function xi(e,t,n,s,r){return r!==void 0&&(e=Jn(e,r,s)),Jn(e,n,s)+t}function qs(e,t=0,n=1,s,r){e.min=xi(e.min,t,n,s,r),e.max=xi(e.max,t,n,s,r)}function Sa(e,{x:t,y:n}){qs(e.x,t.translate,t.scale,t.originPoint),qs(e.y,n.translate,n.scale,n.originPoint)}const bi=.999999999999,vi=1.0000000000001;function jd(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&&Vt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,Sa(e,i)),s&&pt(o.latestValues)&&Vt(e,o.latestValues))}t.x<vi&&t.x>bi&&(t.x=1),t.y<vi&&t.y>bi&&(t.y=1)}function Dt(e,t){e.min=e.min+t,e.max=e.max+t}function wi(e,t,n,s,r=.5){const o=re(e.min,e.max,r);qs(e,t,n,o,s)}function Vt(e,t){wi(e.x,t.x,t.scaleX,t.scale,t.originX),wi(e.y,t.y,t.scaleY,t.scale,t.originY)}function Ta(e,t){return va(Cd(e.getBoundingClientRect(),t))}function Pd(e,t,n){const s=Ta(e,n),{scroll:r}=t;return r&&(Dt(s.x,r.offset.x),Dt(s.y,r.offset.y)),s}const Si=()=>({translate:0,scale:1,origin:0,originPoint:0}),It=()=>({x:Si(),y:Si()}),Ti=()=>({min:0,max:0}),ae=()=>({x:Ti(),y:Ti()}),Gs={current:null},Ca={current:!1};function Ad(){if(Ca.current=!0,!!rr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>Gs.current=e.matches;e.addEventListener("change",t),t()}else Gs.current=!1}const Ed=new WeakMap;function Md(e,t,n){for(const s in t){const r=t[s],o=n[s];if(me(r))e.addValue(s,r);else if(me(o))e.addValue(s,Lt(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,Lt(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Ci=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class kd{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=wr,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=be.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,ne.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=i;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,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=ns(n),this.isVariantNode=ca(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&&me(p)&&p.set(l[m])}}mount(t){this.current=t,Ed.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)),Ca.current||Ad(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Gs.current,process.env.NODE_ENV!=="production"&&cr(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(),tt(this.notifyUpdate),tt(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=_t.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&ne.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 Ft){const n=Ft[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):ae()}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<Ci.length;s++){const r=Ci[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=t[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=Md(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const s=this.values.get(t);n!==s&&(s&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let s=this.values.get(t);return s===void 0&&n!==void 0&&(s=Lt(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"&&(yo(s)||bo(s))?s=parseFloat(s):!$u(s)&&nt.test(n)&&(s=ea(t,n)),this.setBaseTarget(t,me(s)?s.get():s)),me(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=Dr(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&&!me(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 lr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Cr.render(this.render)}}class ja extends kd{constructor(){super(...arguments),this.KeyframeResolver=ju}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;me(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Pa(e,{style:t,vars:n},s,r){const o=e.style;let i;for(i in t)o[i]=t[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function Nd(e){return window.getComputedStyle(e)}class Rd extends ja{constructor(){super(...arguments),this.type="html",this.renderInstance=Pa}readValueFromInstance(t,n){if(_t.has(n))return this.projection?.isProjecting?Ls(n):_c(t,n);{const s=Nd(t),r=(hr(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Ta(t,n)}build(t,n,s){kr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Vr(t,n,s)}}const Aa=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 Dd(e,t,n,s){Pa(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(Aa.has(r)?r:Ir(r),t.attrs[r])}class Vd extends ja{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ae}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(_t.has(n)){const s=Qo(n);return s&&s.default||0}return n=Aa.has(n)?n:Ir(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return ga(t,n,s)}build(t,n,s){ha(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){Dd(t,n,s,r)}mount(t){this.isSVGTag=ma(t.tagName),super.mount(t)}}const Ea=(e,t)=>Rr(e)?new Vd(t):new Rd(t,{allowProjection:e!==f.Fragment});function $t(e,t,n){const s=e.getProps();return Dr(s,t,n!==void 0?n:s.custom,e)}const Hs=e=>Array.isArray(e);function Id(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Lt(n))}function Od(e){return Hs(e)?e[e.length-1]||0:e}function $d(e,t){const n=$t(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Od(o[i]);Id(e,i,a)}}function Ld(e){return!!(me(e)&&e.add)}function Ys(e,t){const n=e.getValue("willChange");if(Ld(n))return n.add(t);if(!n&&Ge.WillChange){const s=new Ge.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Ma(e){return e.props[ya]}const Fd=e=>e!==null;function Bd(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Fd),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const Ud={type:"spring",stiffness:500,damping:25,restSpeed:10},zd=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),_d={type:"keyframes",duration:.8},Xd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Wd=(e,{keyframes:t})=>t.length>2?_d:_t.has(e)?e.startsWith("scale")?zd(t[1]):Ud:Xd;function Kd({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:l,elapsed:c,...d}){return!!Object.keys(d).length}const Or=(e,t,n,s={},r,o)=>i=>{const a=Sr(s,e)||{},l=a.delay||s.delay||0;let{elapsed:c=0}=s;c=c-Oe(l);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-c,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};Kd(a)||Object.assign(d,Wd(e,d)),d.duration&&(d.duration=Oe(d.duration)),d.repeatDelay&&(d.repeatDelay=Oe(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let h=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(_s(d),d.delay===0&&(h=!0)),(Ge.instantAnimations||Ge.skipAnimations)&&(h=!0,_s(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const m=Bd(d.keyframes,a);if(m!==void 0){ne.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new vr(d):new hu(d)};function qd({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function ka(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const l=[],c=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||c&&qd(c,d))continue;const p={delay:n,...Sr(o||{},d)},v=h.get();if(v!==void 0&&!h.isAnimating&&!Array.isArray(m)&&m===v&&!p.velocity)continue;let w=!1;if(window.MotionHandoffAnimation){const S=Ma(e);if(S){const k=window.MotionHandoffAnimation(S,d,ne);k!==null&&(p.startTime=k,w=!0)}}Ys(e,d),h.start(Or(d,h,m,e.shouldReduceMotion&&Yo.has(d)?{type:!1}:p,e,w));const T=h.animation;T&&l.push(T)}return i&&Promise.all(l).then(()=>{ne.update(()=>{i&&$d(e,i)})}),l}function Na(e,t,n,s=0,r=1){const o=Array.from(e).sort((c,d)=>c.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 Js(e,t,n={}){const s=$t(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(ka(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:c=0,staggerChildren:d,staggerDirection:h}=r;return Gd(e,t,l,c,d,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[l,c]=a==="beforeChildren"?[o,i]:[i,o];return l().then(()=>c())}else return Promise.all([o(),i(n.delay)])}function Gd(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const l of e.variantChildren)l.notify("AnimationStart",t),a.push(Js(l,t,{...i,delay:n+(typeof s=="function"?0:s)+Na(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function Hd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>Js(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=Js(e,t,n);else{const r=typeof t=="function"?$t(e,t,n.custom):t;s=Promise.all(ka(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function Ra(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 Yd=Mr.length;function Da(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Da(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<Yd;n++){const s=Mr[n],r=e.props[s];(xn(r)||r===!1)&&(t[s]=r)}return t}const Jd=[...Er].reverse(),Zd=Er.length;function Qd(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Hd(e,n,s)))}function eh(e){let t=Qd(e),n=ji(),s=!0;const r=l=>(c,d)=>{const h=$t(e,d,l==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:m,transitionEnd:p,...v}=h;c={...c,...v,...p}}return c};function o(l){t=l(e)}function i(l){const{props:c}=e,d=Da(e.parent)||{},h=[],m=new Set;let p={},v=1/0;for(let T=0;T<Zd;T++){const S=Jd[T],k=n[S],E=c[S]!==void 0?c[S]:d[S],U=xn(E),D=S===l?k.isActive:null;D===!1&&(v=T);let $=E===d[S]&&E!==c[S]&&U;if($&&s&&e.manuallyAnimateOnMount&&($=!1),k.protectedKeys={...p},!k.isActive&&D===null||!E&&!k.prevProp||ts(E)||typeof E=="boolean")continue;const F=th(k.prevProp,E);let M=F||S===l&&k.isActive&&!$&&U||T>v&&U,R=!1;const A=Array.isArray(E)?E:[E];let V=A.reduce(r(S),{});D===!1&&(V={});const{prevResolvedValues:L={}}=k,I={...L,...V},B=G=>{M=!0,m.has(G)&&(R=!0,m.delete(G)),k.needsAnimating[G]=!0;const ee=e.getValue(G);ee&&(ee.liveStyle=!1)};for(const G in I){const ee=V[G],de=L[G];if(p.hasOwnProperty(G))continue;let xe=!1;Hs(ee)&&Hs(de)?xe=!Ra(ee,de):xe=ee!==de,xe?ee!=null?B(G):m.add(G):ee!==void 0&&m.has(G)?B(G):k.protectedKeys[G]=!0}k.prevProp=E,k.prevResolvedValues=V,k.isActive&&(p={...p,...V}),s&&e.blockInitialAnimation&&(M=!1);const H=$&&F;M&&(!H||R)&&h.push(...A.map(G=>{const ee={type:S};if(typeof G=="string"&&s&&!H&&e.manuallyAnimateOnMount&&e.parent){const{parent:de}=e,xe=$t(de,G);if(de.enteringChildren&&xe){const{delayChildren:oe}=xe.transition||{};ee.delay=Na(de.enteringChildren,e,oe)}}return{animation:G,options:ee}}))}if(m.size){const T={};if(typeof c.initial!="boolean"){const S=$t(e,Array.isArray(c.initial)?c.initial[0]:c.initial);S&&S.transition&&(T.transition=S.transition)}m.forEach(S=>{const k=e.getBaseTarget(S),E=e.getValue(S);E&&(E.liveStyle=!0),T[S]=k??null}),h.push({animation:T})}let w=!!h.length;return s&&(c.initial===!1||c.initial===c.animate)&&!e.manuallyAnimateOnMount&&(w=!1),s=!1,w?t(h):Promise.resolve()}function a(l,c){if(n[l].isActive===c)return Promise.resolve();e.variantChildren?.forEach(h=>h.animationState?.setActive(l,c)),n[l].isActive=c;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=ji()}}}function th(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!Ra(t,e):!1}function ft(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ji(){return{animate:ft(!0),whileInView:ft(),whileHover:ft(),whileTap:ft(),whileDrag:ft(),whileFocus:ft(),exit:ft()}}class st{constructor(t){this.isMounted=!1,this.node=t}update(){}}class nh extends st{constructor(t){super(t),t.animationState||(t.animationState=eh(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();ts(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let sh=0;class rh extends st{constructor(){super(...arguments),this.id=sh++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const Va={animation:{Feature:nh},exit:{Feature:rh}};function vn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function Cn(e){return{point:{x:e.pageX,y:e.pageY}}}const ih=e=>t=>jr(t)&&e(t,Cn(t));function dn(e,t,n,s){return vn(e,t,ih(n),s)}const Ia=1e-4,oh=1-Ia,ah=1+Ia,Oa=.01,lh=0-Oa,ch=0+Oa;function ye(e){return e.max-e.min}function uh(e,t,n){return Math.abs(e-t)<=n}function Pi(e,t,n,s=.5){e.origin=s,e.originPoint=re(t.min,t.max,e.origin),e.scale=ye(n)/ye(t),e.translate=re(n.min,n.max,e.origin)-e.originPoint,(e.scale>=oh&&e.scale<=ah||isNaN(e.scale))&&(e.scale=1),(e.translate>=lh&&e.translate<=ch||isNaN(e.translate))&&(e.translate=0)}function hn(e,t,n,s){Pi(e.x,t.x,n.x,s?s.originX:void 0),Pi(e.y,t.y,n.y,s?s.originY:void 0)}function Ai(e,t,n){e.min=n.min+t.min,e.max=e.min+ye(t)}function dh(e,t,n){Ai(e.x,t.x,n.x),Ai(e.y,t.y,n.y)}function Ei(e,t,n){e.min=t.min-n.min,e.max=e.min+ye(t)}function fn(e,t,n){Ei(e.x,t.x,n.x),Ei(e.y,t.y,n.y)}function Ee(e){return[e("x"),e("y")]}const $a=({current:e})=>e?e.ownerDocument.defaultView:null,Mi=(e,t)=>Math.abs(e-t);function hh(e,t){const n=Mi(e.x,t.x),s=Mi(e.y,t.y);return Math.sqrt(n**2+s**2)}class La{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=Ss(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,v=hh(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!v)return;const{point:w}=m,{timestamp:T}=fe;this.history.push({...w,timestamp:T});const{onStart:S,onMove:k}=this.handlers;p||(S&&S(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),k&&k(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=ws(p,this.transformPagePoint),ne.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:v,onSessionEnd:w,resumeAnimation:T}=this.handlers;if(this.dragSnapToOrigin&&T&&T(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=Ss(m.type==="pointercancel"?this.lastMoveEventInfo:ws(p,this.transformPagePoint),this.history);this.startEvent&&v&&v(m,S),w&&w(m,S)},!jr(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=Cn(t),l=ws(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=fe;this.history=[{...c,timestamp:d}];const{onSessionStart:h}=n;h&&h(t,Ss(l,this.history)),this.removeListeners=wn(dn(this.contextWindow,"pointermove",this.handlePointerMove),dn(this.contextWindow,"pointerup",this.handlePointerUp),dn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),tt(this.updatePoint)}}function ws(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 Ss({point:e},t){return{point:e,delta:ki(e,Fa(t)),offset:ki(e,fh(t)),velocity:mh(t,.1)}}function fh(e){return e[0]}function Fa(e){return e[e.length-1]}function mh(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Fa(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>Oe(t)));)n--;if(!s)return{x:0,y:0};const o=ke(r.timestamp-s.timestamp);if(o===0)return{x:0,y:0};const i={x:(r.x-s.x)/o,y:(r.y-s.y)/o};return i.x===1/0&&(i.x=0),i.y===1/0&&(i.y=0),i}function ph(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?re(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?re(n,e,s.max):Math.min(e,n)),e}function Ni(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function gh(e,{top:t,left:n,bottom:s,right:r}){return{x:Ni(e.x,n,r),y:Ni(e.y,t,s)}}function Ri(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function yh(e,t){return{x:Ri(e.x,t.x),y:Ri(e.y,t.y)}}function xh(e,t){let n=.5;const s=ye(e),r=ye(t);return r>s?n=pn(t.min,t.max-s,e.min):s>r&&(n=pn(e.min,e.max-r,t.min)),Ke(0,1,n)}function bh(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const Zs=.35;function vh(e=Zs){return e===!1?e=0:e===!0&&(e=Zs),{x:Di(e,"left","right"),y:Di(e,"top","bottom")}}function Di(e,t,n){return{min:Vi(e,t),max:Vi(e,n)}}function Vi(e,t){return typeof e=="number"?e:e[t]||0}const wh=new WeakMap;class Sh{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=ae(),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(Cn(h).point)},i=(h,m)=>{const{drag:p,dragPropagation:v,onDragStart:w}=this.getProps();if(p&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Mu(p),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ee(S=>{let k=this.getAxisMotionValue(S).get()||0;if(Be.test(k)){const{projection:E}=this.visualElement;if(E&&E.layout){const U=E.layout.layoutBox[S];U&&(k=ye(U)*(parseFloat(k)/100))}}this.originPoint[S]=k}),w&&ne.postRender(()=>w(h,m)),Ys(this.visualElement,"transform");const{animationState:T}=this.visualElement;T&&T.setActive("whileDrag",!0)},a=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:v,onDirectionLock:w,onDrag:T}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:S}=m;if(v&&this.currentDirection===null){this.currentDirection=Th(S),this.currentDirection!==null&&w&&w(this.currentDirection);return}this.updateAxis("x",m.point,S),this.updateAxis("y",m.point,S),this.visualElement.render(),T&&T(h,m)},l=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Ee(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:d}=this.getProps();this.panSession=new La(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:$a(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&&ne.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||!Ln(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=ph(i,this.constraints[t],this.elastic[t])),o.set(i)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&Rt(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=gh(s.layoutBox,t):this.constraints=!1,this.elastic=vh(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Ee(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=bh(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Rt(t))return!1;const s=t.current;qe(s!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const o=Pd(s,r.root,this.visualElement.getTransformPagePoint());let i=yh(r.layout.layoutBox,o);if(n){const a=n(Td(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||{},c=Ee(d=>{if(!Ln(d,n,this.currentDirection))return;let h=l&&l[d]||{};i&&(h={min:0,max:0});const m=r?200:1e6,p=r?40:1e7,v={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(d,v)});return Promise.all(c).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return Ys(this.visualElement,t),s.start(Or(t,s,0,n,this.visualElement,!1))}stopAnimation(){Ee(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Ee(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){Ee(n=>{const{drag:s}=this.getProps();if(!Ln(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]-re(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Rt(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Ee(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const l=a.get();r[i]=xh({min:l,max:l},this.constraints[i])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.resolveConstraints(),Ee(i=>{if(!Ln(i,t,null))return;const a=this.getAxisMotionValue(i),{min:l,max:c}=this.constraints[i];a.set(re(l,c,r[i]))})}addListeners(){if(!this.visualElement.current)return;wh.set(this.visualElement,this);const t=this.visualElement.current,n=dn(t,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),s=()=>{const{dragConstraints:l}=this.getProps();Rt(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()),ne.read(s);const i=vn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Ee(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=Zs,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function Ln(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Th(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Ch extends st{constructor(t){super(t),this.removeGroupControls=Ne,this.removeListeners=Ne,this.controls=new Sh(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ne}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ii=e=>(t,n)=>{e&&ne.postRender(()=>e(t,n))};class jh extends st{constructor(){super(...arguments),this.removePointerDownListener=Ne}onPointerDown(t){this.session=new La(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:$a(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ii(t),onStart:Ii(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&ne.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=dn(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 Kn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Oi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const on={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(K.test(e))e=parseFloat(e);else return e;const n=Oi(e,t.target.x),s=Oi(e,t.target.y);return`${n}% ${s}%`}},Ph={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=nt.parse(e);if(r.length>5)return s;const o=nt.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 c=re(a,l,.5);return typeof r[2+i]=="number"&&(r[2+i]/=c),typeof r[3+i]=="number"&&(r[3+i]/=c),o(r)}};let Ts=!1;class Ah extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;Ju(Eh),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),Ts&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Kn.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Ts=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||ne.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Cr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Ts=!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 Ba(e){const[t,n]=aa(),s=f.useContext(nr);return u.jsx(Ah,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(xa),isPresent:t,safeToRemove:n})}const Eh={borderRadius:{...on,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:on,borderTopRightRadius:on,borderBottomLeftRadius:on,borderBottomRightRadius:on,boxShadow:Ph};function Mh(e,t,n){const s=me(e)?e:Lt(e);return s.start(Or("",s,t,n)),s.animation}const kh=(e,t)=>e.depth-t.depth;class Nh{constructor(){this.children=[],this.isDirty=!1}add(t){ir(this.children,t),this.isDirty=!0}remove(t){or(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(kh),this.isDirty=!1,this.children.forEach(t)}}function Rh(e,t){const n=be.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(tt(s),e(o-t))};return ne.setup(s,!0),()=>tt(s)}const Ua=["TopLeft","TopRight","BottomLeft","BottomRight"],Dh=Ua.length,$i=e=>typeof e=="string"?parseFloat(e):e,Li=e=>typeof e=="number"||K.test(e);function Vh(e,t,n,s,r,o){r?(e.opacity=re(0,n.opacity??1,Ih(s)),e.opacityExit=re(t.opacity??1,0,Oh(s))):o&&(e.opacity=re(t.opacity??1,n.opacity??1,s));for(let i=0;i<Dh;i++){const a=`border${Ua[i]}Radius`;let l=Fi(t,a),c=Fi(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Li(l)===Li(c)?(e[a]=Math.max(re($i(l),$i(c),s),0),(Be.test(c)||Be.test(l))&&(e[a]+="%")):e[a]=c}(t.rotate||n.rotate)&&(e.rotate=re(t.rotate||0,n.rotate||0,s))}function Fi(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Ih=za(0,.5,Ao),Oh=za(.5,.95,Ne);function za(e,t,n){return s=>s<e?0:s>t?1:n(pn(e,t,s))}function Bi(e,t){e.min=t.min,e.max=t.max}function Ae(e,t){Bi(e.x,t.x),Bi(e.y,t.y)}function Ui(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function zi(e,t,n,s,r){return e-=t,e=Jn(e,1/n,s),r!==void 0&&(e=Jn(e,1/r,s)),e}function $h(e,t=0,n=1,s=.5,r,o=e,i=e){if(Be.test(t)&&(t=parseFloat(t),t=re(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=re(o.min,o.max,s);e===o&&(a-=t),e.min=zi(e.min,t,n,a,r),e.max=zi(e.max,t,n,a,r)}function _i(e,t,[n,s,r],o,i){$h(e,t[n],t[s],t[r],t.scale,o,i)}const Lh=["x","scaleX","originX"],Fh=["y","scaleY","originY"];function Xi(e,t,n,s){_i(e.x,t,Lh,n?n.x:void 0,s?s.x:void 0),_i(e.y,t,Fh,n?n.y:void 0,s?s.y:void 0)}function Wi(e){return e.translate===0&&e.scale===1}function _a(e){return Wi(e.x)&&Wi(e.y)}function Ki(e,t){return e.min===t.min&&e.max===t.max}function Bh(e,t){return Ki(e.x,t.x)&&Ki(e.y,t.y)}function qi(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Xa(e,t){return qi(e.x,t.x)&&qi(e.y,t.y)}function Gi(e){return ye(e.x)/ye(e.y)}function Hi(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class Uh{constructor(){this.members=[]}add(t){ir(this.members,t),t.scheduleRender()}remove(t){if(or(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 zh(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:c,rotate:d,rotateX:h,rotateY:m,skewX:p,skewY:v}=n;c&&(s=`perspective(${c}px) ${s}`),d&&(s+=`rotate(${d}deg) `),h&&(s+=`rotateX(${h}deg) `),m&&(s+=`rotateY(${m}deg) `),p&&(s+=`skewX(${p}deg) `),v&&(s+=`skewY(${v}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(s+=`scale(${a}, ${l})`),s||"none"}const Cs=["","X","Y","Z"],_h=1e3;let Xh=0;function js(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function Wa(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Ma(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",ne,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&Wa(s)}function Ka({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=Xh++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(qh),this.nodes.forEach(Jh),this.nodes.forEach(Zh),this.nodes.forEach(Gh)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=i,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new Nh)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new lr),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=oa(i)&&!Iu(i),this.instance=i;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.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;ne.read(()=>{h=window.innerWidth}),e(i,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,d&&d(),d=Rh(m,250),Kn.hasAnimatedSinceResize&&(Kn.hasAnimatedSinceResize=!1,this.nodes.forEach(Zi)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||c.getDefaultTransition()||sf,{onLayoutAnimationStart:w,onLayoutAnimationComplete:T}=c.getProps(),S=!this.targetLayout||!Xa(this.targetLayout,p),k=!h&&m;if(this.options.layoutRoot||this.resumeFrom||k||h&&(S||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const E={...Sr(v,"layout"),onPlay:w,onComplete:T};(c.shouldReduceMotion||this.options.layoutRoot)&&(E.delay=0,E.type=!1),this.startAnimation(E),this.setAnimationOrigin(d,k)}else h||Zi(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(),tt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Qh),this.animationId++)}getTransformTemplate(){const{visualElement:i}=this.options;return i&&i.getProps().transformTemplate}willUpdate(i=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Wa(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 c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Yi);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Ji);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Yh),this.nodes.forEach(Wh),this.nodes.forEach(Kh)):this.nodes.forEach(Ji),this.clearAllSnapshots();const a=be.now();fe.delta=Ke(0,1e3/60,a-fe.timestamp),fe.timestamp=a,fe.isProcessing=!0,fs.update.process(fe),fs.preRender.process(fe),fs.render.process(fe),fe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Cr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Hh),this.sharedNodes.forEach(ef)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ne.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ne.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!ye(this.snapshot.measuredBox.x)&&!ye(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=ae(),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&&!_a(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,d=c!==this.prevTransformTemplateValue;i&&this.instance&&(a||pt(this.latestValues)||d)&&(r(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return i&&(l=this.removeTransform(l)),rf(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ae();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(of))){const{scroll:c}=this.root;c&&(Dt(a.x,c.offset.x),Dt(a.y,c.offset.y))}return a}removeElementScroll(i){const a=ae();if(Ae(a,i),this.scroll?.wasRoot)return a;for(let l=0;l<this.path.length;l++){const c=this.path[l],{scroll:d,options:h}=c;c!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&Ae(a,i),Dt(a.x,d.offset.x),Dt(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const l=ae();Ae(l,i);for(let c=0;c<this.path.length;c++){const d=this.path[c];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&Vt(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),pt(d.latestValues)&&Vt(l,d.latestValues)}return pt(this.latestValues)&&Vt(l,this.latestValues),l}removeTransform(i){const a=ae();Ae(a,i);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!pt(c.latestValues))continue;Ks(c.latestValues)&&c.updateSnapshot();const d=ae(),h=c.measurePageBox();Ae(d,h),Xi(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return pt(this.latestValues)&&Xi(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!==fe.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=fe.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ae(),this.relativeTargetOrigin=ae(),fn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Ae(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ae(),this.targetWithTransforms=ae()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),dh(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Ae(this.target,this.layout.layoutBox),Sa(this.target,this.targetDelta)):Ae(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=ae(),this.relativeTargetOrigin=ae(),fn(this.relativeTargetOrigin,this.target,m.target),Ae(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ks(this.parent.latestValues)||wa(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===fe.timestamp&&(l=!1),l)return;const{layout:c,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||!(c||d))return;Ae(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,m=this.treeScale.y;jd(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=ae());const{target:p}=i;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Ui(this.prevProjectionDelta.x,this.projectionDelta.x),Ui(this.prevProjectionDelta.y,this.projectionDelta.y)),hn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==m||!Hi(this.projectionDelta.x,this.prevProjectionDelta.x)||!Hi(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=It(),this.projectionDelta=It(),this.projectionDeltaWithTransform=It()}setAnimationOrigin(i,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},h=It();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=ae(),p=l?l.source:void 0,v=this.layout?this.layout.source:void 0,w=p!==v,T=this.getStack(),S=!T||T.members.length<=1,k=!!(w&&!S&&this.options.crossfade===!0&&!this.path.some(nf));this.animationProgress=0;let E;this.mixTargetDelta=U=>{const D=U/1e3;Qi(h.x,i.x,D),Qi(h.y,i.y,D),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(fn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),tf(this.relativeTarget,this.relativeTargetOrigin,m,D),E&&Bh(this.relativeTarget,E)&&(this.isProjectionDirty=!1),E||(E=ae()),Ae(E,this.relativeTarget)),w&&(this.animationValues=d,Vh(d,c,this.latestValues,D,k,S)),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&&(tt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ne.update(()=>{Kn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Lt(0)),this.currentAnimation=Mh(this.motionValue,[0,1e3],{...i,velocity:0,isSync:!0,onUpdate:a=>{this.mixTargetDelta(a),i.onUpdate&&i.onUpdate(a)},onStop:()=>{},onComplete:()=>{i.onComplete&&i.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const i=this.getStack();i&&i.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(_h),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:d}=i;if(!(!a||!l||!c)){if(this!==i&&this.layout&&c&&qa(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ae();const h=ye(this.layout.layoutBox.x);l.x.min=i.target.x.min,l.x.max=l.x.min+h;const m=ye(this.layout.layoutBox.y);l.y.min=i.target.y.min,l.y.max=l.y.min+m}Ae(a,l),Vt(a,d),hn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new Uh),this.sharedNodes.get(i).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.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 c=this.getStack();c&&c.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 c={};l.z&&js("z",i,c,this.animationValues);for(let d=0;d<Cs.length;d++)js(`rotate${Cs[d]}`,i,c,this.animationValues),js(`skew${Cs[d]}`,i,c,this.animationValues);i.render();for(const d in c)i.setStaticValue(d,c[d]),this.animationValues&&(this.animationValues[d]=c[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=Xn(a?.pointerEvents)||"",i.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(i.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,i.pointerEvents=Xn(a?.pointerEvents)||""),this.hasProjected&&!pt(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let h=zh(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`,c.animationValues?i.opacity=c===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:i.opacity=c===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const v in bn){if(d[v]===void 0)continue;const{correct:w,applyTo:T,isCSSVariable:S}=bn[v],k=h==="none"?d[v]:w(d[v],c);if(T){const E=T.length;for(let U=0;U<E;U++)i[T[U]]=k}else S?this.options.visualElement.renderState.vars[v]=k:i[v]=k}this.options.layoutId&&(i.pointerEvents=c===this?Xn(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(Yi),this.root.sharedNodes.clear()}}}function Wh(e){e.updateLayout()}function Kh(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:r}=e.options,o=t.source!==e.layout.source;r==="size"?Ee(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=ye(h);h.min=n[d].min,h.max=h.min+m}):qa(r,t.layoutBox,n)&&Ee(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=ye(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=It();hn(i,n,t.layoutBox);const a=It();o?hn(a,e.applyTransform(s,!0),t.measuredBox):hn(a,n,t.layoutBox);const l=!_a(i);let c=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:m}=d;if(h&&m){const p=ae();fn(p,t.layoutBox,h.layoutBox);const v=ae();fn(v,n,m.layoutBox),Xa(p,v)||(c=!0),d.options.layoutRoot&&(e.relativeTarget=v,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:l,hasRelativeLayoutChanged:c})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function qh(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function Gh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Hh(e){e.clearSnapshot()}function Yi(e){e.clearMeasurements()}function Ji(e){e.isLayoutDirty=!1}function Yh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Zi(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Jh(e){e.resolveTargetDelta()}function Zh(e){e.calcProjection()}function Qh(e){e.resetSkewAndRotation()}function ef(e){e.removeLeadSnapshot()}function Qi(e,t,n){e.translate=re(t.translate,0,n),e.scale=re(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function eo(e,t,n,s){e.min=re(t.min,n.min,s),e.max=re(t.max,n.max,s)}function tf(e,t,n,s){eo(e.x,t.x,n.x,s),eo(e.y,t.y,n.y,s)}function nf(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const sf={duration:.45,ease:[.4,0,.1,1]},to=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),no=to("applewebkit/")&&!to("chrome/")?Math.round:Ne;function so(e){e.min=no(e.min),e.max=no(e.max)}function rf(e){so(e.x),so(e.y)}function qa(e,t,n){return e==="position"||e==="preserve-aspect"&&!uh(Gi(t),Gi(n),.2)}function of(e){return e!==e.root&&e.scroll?.wasRoot}const af=Ka({attachResizeListener:(e,t)=>vn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Ps={current:void 0},Ga=Ka({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Ps.current){const e=new af({});e.mount(window),e.setOptions({layoutScroll:!0}),Ps.current=e}return Ps.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),lf={pan:{Feature:jh},drag:{Feature:Ch,ProjectionNode:Ga,MeasureLayout:Ba}};function ro(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&&ne.postRender(()=>o(t,Cn(t)))}class cf extends st{mount(){const{current:t}=this.node;t&&(this.unmount=ku(t,(n,s)=>(ro(this.node,s,"Start"),r=>ro(this.node,r,"End"))))}unmount(){}}class uf 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=wn(vn(this.node.current,"focus",()=>this.onFocus()),vn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function io(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&&ne.postRender(()=>o(t,Cn(t)))}class df extends st{mount(){const{current:t}=this.node;t&&(this.unmount=Vu(t,(n,s)=>(io(this.node,s,"Start"),(r,{success:o})=>io(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Qs=new WeakMap,As=new WeakMap,hf=e=>{const t=Qs.get(e.target);t&&t(e)},ff=e=>{e.forEach(hf)};function mf({root:e,...t}){const n=e||document;As.has(n)||As.set(n,{});const s=As.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(ff,{root:e,...t})),s[r]}function pf(e,t,n){const s=mf(t);return Qs.set(e,n),s.observe(e),()=>{Qs.delete(e),s.unobserve(e)}}const gf={some:0,all:1};class yf 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:gf[r]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:d,onViewportLeave:h}=this.node.getProps(),m=c?d:h;m&&m(l)};return pf(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(xf(t,n))&&this.startObserver()}unmount(){}}function xf({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Ha={inView:{Feature:yf},tap:{Feature:df},focus:{Feature:uf},hover:{Feature:cf}},bf={layout:{ProjectionNode:Ga,MeasureLayout:Ba}},vf={...Va,...Ha,...lf,...bf},wf=Sd(vf,Ea),Sf={renderer:Ea,...Va,...Ha};function $r(e,t){return Wn(e,t)}const Tf=$r("button"),Fn=$r("div"),Cf=$r("p");function jf({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return u.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:u.jsxs("div",{className:"flex items-start gap-2",children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:u.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&u.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>u.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[u.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),u.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),u.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[u.jsxs(pe,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[u.jsx(Z.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),u.jsx(pe,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:u.jsx(Z.X,{className:"h-3 w-3"})})]})]})})}function Pf({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(([c])=>!i.includes(c))),l=Object.keys(a).length>0;return u.jsxs("div",{className:"my-1",children:[u.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&&u.jsx("span",{className:"transition-transform duration-200",children:r?u.jsx(Z.ChevronDown,{className:"h-3 w-3"}):u.jsx(Z.ChevronRight,{className:"h-3 w-3"})}),n?u.jsx(Z.X,{className:"h-3 w-3"}):s?u.jsx(Z.Zap,{className:"h-3 w-3"}):u.jsx(Z.Check,{className:"h-3 w-3"}),u.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&l&&u.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:u.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([c,d])=>u.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[u.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[c,":"]}),u.jsx("span",{className:"font-mono text-foreground",children:typeof d=="string"?d:JSON.stringify(d)})]},c))})})]})}function Af({...e}){return u.jsx(er.Root,{"data-slot":"collapsible",...e})}function Ef({...e}){return u.jsx(er.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function Mf({...e}){return u.jsx(er.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const kf=f.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Lr=f.memo(({className:e,...t})=>typeof window>"u"?null:u.jsx(f.Suspense,{fallback:null,children:u.jsx(kf,{className:Q("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Lr.displayName="Response";const Nf=Object.freeze(Object.defineProperty({__proto__:null,Response:Lr},Symbol.toStringTag,{value:"Module"})),Rf=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=wf.create(t),i=f.useMemo(()=>(e?.length??0)*r,[e,r]);return u.jsx(o,{animate:{backgroundPosition:"0% center"},className:Q("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:e})},Df=f.memo(Rf),Ya=f.createContext(null),Vf=()=>{const e=f.useContext(Ya);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},If=1e3,Of=1e3,Ja=f.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,c]=_r.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,h]=_r.useControllableState({prop:o,defaultProp:0}),[m,p]=f.useState(!1),[v,w]=f.useState(null);f.useEffect(()=>{t?v===null&&w(Date.now()):v!==null&&(h(Math.ceil((Date.now()-v)/Of)),w(null))},[t,v,h]),f.useEffect(()=>{if(s&&!t&&l&&!m){const S=setTimeout(()=>{c(!1),p(!0)},If);return()=>clearTimeout(S)}},[t,l,s,c,m]);const T=S=>{c(S)};return u.jsx(Ya.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:c,duration:d},children:u.jsx(Af,{className:Q("not-prose mb-4",e),onOpenChange:T,open:l,...a,children:i})})}),$f=(e,t)=>e||t===0?u.jsx(Df,{duration:1,children:"Thinking..."}):t===void 0?u.jsx("p",{children:"Thought for a few seconds"}):u.jsxs("p",{children:["Thought for ",t," seconds"]}),Za=f.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Vf();return u.jsx(Ef,{className:Q("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??u.jsxs(u.Fragment,{children:[u.jsx(Z.BrainIcon,{className:"size-4"}),$f(s,o),u.jsx(Z.ChevronDownIcon,{className:Q("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Qa=f.memo(({className:e,children:t,...n})=>u.jsx(Mf,{className:Q("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:u.jsx(Lr,{className:"grid gap-2",children:t})}));Ja.displayName="Reasoning";Za.displayName="ReasoningTrigger";Qa.displayName="ReasoningContent";function oo(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function Lf({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=oo(s.domain);return u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsxs("button",{className:Q("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:[u.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),u.jsx("span",{className:"leading-none",children:s.domain})]})}),u.jsx(Qe,{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:u.jsxs("div",{className:"space-y-1.5",children:[u.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 u.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:Q("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:[u.jsx("img",{src:oo(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const l=a.target;l.style.display="none"}}),u.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function Ff({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:l=!0}){const c=f.useRef(null),[d,h]=f.useState([]);f.useEffect(()=>{if(!a||!c.current||t.length===0||n.size===0){(n.size===0||!a)&&h([]);return}const T=c.current;let S,k=!1;const E=new WeakSet,U=()=>{if(!c.current||k)return;k=!0;const $=c.current,F=/\[(\d+)\]/g,M=document.createTreeWalker($,NodeFilter.SHOW_TEXT,null),R=[];let A;for(;A=M.nextNode();)if(A.nodeType===Node.TEXT_NODE&&!E.has(A)){const L=A,I=L.textContent||"";let B=L.parentElement,H=!1;for(;B&&B!==$;){if(B.tagName==="A"||B.tagName==="CODE"||B.tagName==="PRE"){H=!0;break}B=B.parentElement}if(!H){const G=Array.from(I.matchAll(F)).filter(ee=>{if(!ee[1])return!1;const de=parseInt(ee[1],10);return n.has(de)});G.length>0&&R.push({node:L,matches:G})}}if(R.length===0){k=!1;return}const V=[];R.forEach(({node:L,matches:I})=>{E.add(L);const B=L.textContent||"",H=document.createDocumentFragment();let te=0;I.forEach(G=>{if(!G[1])return;G.index!==void 0&&G.index>te&&H.appendChild(document.createTextNode(B.slice(te,G.index)));const ee=document.createElement("span");ee.className="inline-flex items-center citation-button-container";const de=parseInt(G[1],10);ee.setAttribute("data-citation",G[1]),H.appendChild(ee),V.push({element:ee,citationNum:de}),te=(G.index||0)+G[0].length}),te<B.length&&H.appendChild(document.createTextNode(B.slice(te))),L.parentNode&&L.parentNode.replaceChild(H,L)}),V.length>0&&h(L=>{const I=new Set(L.map(te=>te.element)),B=L.filter(te=>te.element.isConnected),H=V.filter(te=>!I.has(te.element));return[...B,...H]}),k=!1},D=new MutationObserver(()=>{clearTimeout(S),S=setTimeout(U,100)});return D.observe(T,{childList:!0,subtree:!0,characterData:!0}),S=setTimeout(U,200),()=>{D.disconnect(),clearTimeout(S)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(T){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(T)}&sz=16`}function v(T){try{return new URL(T).hostname.replace(/^www\./,"")}catch{return T}}const w=a&&l&&m?u.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[u.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),u.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((T,S)=>{const k=T.title||T.baseUrl,E=v(T.url),U=p(E);return u.jsxs("a",{href:T.url,target:"_blank",rel:"noopener noreferrer",className:Q("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:[u.jsx("img",{src:U,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:D=>{const $=D.target;$.style.display="none"}}),u.jsx("span",{className:"leading-none",children:k})]},`group-${S}`)}):Array.from(n.entries()).sort(([T],[S])=>T-S).map(([T,S])=>{const k=v(S),E=p(k);return u.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",className:Q("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:[u.jsx("img",{src:E,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:U=>{const D=U.target;D.style.display="none"}}),u.jsx("span",{className:"leading-none",children:S})]},T)})})]}):null;return u.jsxs("div",{className:i,children:[u.jsx("div",{ref:c,children:u.jsx(o,{children:e})}),a&&d.filter(({element:T})=>T.isConnected).map(({element:T,citationNum:S},k)=>{if(!t.find(D=>D.number===S))return null;const U=Array.from(new Map(t.map(D=>{const $=D.url.replace(/\/+$/,""),F=s?.find(M=>M.url.replace(/\/+$/,"")===$);return[$,{number:D.number,url:D.url,domain:v(D.url),title:F?.title}]})).values());return yl.createPortal(u.jsx(Lf,{sources:U,citationNumber:S},`citation-${S}-${T}`),T,`citation-${S}-${k}`)}),w]})}function Xt({...e}){return u.jsx(vt.Root,{"data-slot":"dialog",...e})}function Bf({...e}){return u.jsx(vt.Portal,{"data-slot":"dialog-portal",...e})}function Uf({className:e,...t}){return u.jsx(vt.Overlay,{"data-slot":"dialog-overlay",className:Q("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 Wt({className:e,children:t,showCloseButton:n=!0,...s}){return u.jsxs(Bf,{"data-slot":"dialog-portal",children:[u.jsx(Uf,{}),u.jsxs(vt.Content,{"data-slot":"dialog-content",className:Q("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&&u.jsxs(vt.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:[u.jsx(Z.XIcon,{}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Kt({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-header",className:Q("flex flex-col gap-2 text-center sm:text-left",e),...t})}function qt({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-footer",className:Q("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function Gt({className:e,...t}){return u.jsx(vt.Title,{"data-slot":"dialog-title",className:Q("text-lg leading-none font-semibold",e),...t})}function Ht({className:e,...t}){return u.jsx(vt.Description,{"data-slot":"dialog-description",className:Q("text-muted-foreground text-sm",e),...t})}function Yt({className:e,type:t,...n}){return u.jsx("input",{type:t,"data-slot":"input",className:Q("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 zf({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),[c,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 u.jsx(Xt,{open:e,children:u.jsx(Wt,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:h,children:[u.jsxs(Kt,{children:[u.jsx(Gt,{children:t}),u.jsx(Ht,{children:n})]}),u.jsx("div",{className:"py-4",children:u.jsxs("div",{className:"relative",children:[u.jsx(Yt,{type:a?"text":"password",value:o,onChange:p=>i(p.target.value),placeholder:s,className:"pr-10",autoFocus:!0,disabled:c}),u.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:c,children:a?u.jsx(Z.EyeOff,{className:"h-4 w-4"}):u.jsx(Z.Eye,{className:"h-4 w-4"})})]})}),u.jsxs(qt,{children:[u.jsx(pe,{type:"button",variant:"ghost",onClick:m,disabled:c,children:"Cancel"}),u.jsx(pe,{type:"submit",disabled:!o.trim()||c,children:c?"Submitting...":"Submit"})]})]})})})}function _f({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),[c,d]=f.useState(!1),h=w=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(w),m=w=>{i(w),w.trim()?l(h(w)):l(!0)},p=async w=>{if(w.preventDefault(),!o.trim()||!h(o)){l(!1);return}d(!0);try{r(o)}finally{d(!1)}},v=()=>{i(""),l(!0),r(null)};return u.jsx(Xt,{open:e,children:u.jsx(Wt,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:p,children:[u.jsxs(Kt,{children:[u.jsxs(Gt,{className:"flex items-center gap-2",children:[u.jsx(Z.Mail,{className:"h-5 w-5"}),t]}),u.jsx(Ht,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(Yt,{type:"email",value:o,onChange:w=>m(w.target.value),placeholder:s,className:a?"":"border-red-500",autoFocus:!0,disabled:c}),!a&&u.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid email address"})]}),u.jsxs(qt,{children:[u.jsx(pe,{type:"button",variant:"ghost",onClick:v,disabled:c,children:"Cancel"}),u.jsx(pe,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function Xf({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),[c,d]=f.useState(!1),h=T=>{const S=T.replace(/\D/g,"");return S.length<=3?S:S.length<=6?`(${S.slice(0,3)}) ${S.slice(3)}`:`(${S.slice(0,3)}) ${S.slice(3,6)}-${S.slice(6,10)}`},m=T=>T.replace(/\D/g,"").length===10,p=T=>{const S=h(T);i(S),S.trim()?l(m(S)):l(!0)},v=async T=>{if(T.preventDefault(),!o.trim()||!m(o)){l(!1);return}d(!0);try{const S=o.replace(/\D/g,"");r(S)}finally{d(!1)}},w=()=>{i(""),l(!0),r(null)};return u.jsx(Xt,{open:e,children:u.jsx(Wt,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:v,children:[u.jsxs(Kt,{children:[u.jsxs(Gt,{className:"flex items-center gap-2",children:[u.jsx(Z.Phone,{className:"h-5 w-5"}),t]}),u.jsx(Ht,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(Yt,{type:"tel",value:o,onChange:T=>p(T.target.value),placeholder:s,className:a?"":"border-red-500",maxLength:14,autoFocus:!0,disabled:c}),!a&&u.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid 10-digit phone number"})]}),u.jsxs(qt,{children:[u.jsx(pe,{type:"button",variant:"ghost",onClick:w,disabled:c,children:"Cancel"}),u.jsx(pe,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function Wf({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,c]=f.useState(!1),d=p=>{const v=p.replace(/\D/g,"");a(v.slice(0,r))},h=async p=>{if(p.preventDefault(),i.length===r){c(!0);try{o(i)}finally{c(!1)}}},m=()=>{a(""),o(null)};return u.jsx(Xt,{open:e,children:u.jsx(Wt,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:h,children:[u.jsxs(Kt,{children:[u.jsxs(Gt,{className:"flex items-center gap-2",children:[u.jsx(Z.Shield,{className:"h-5 w-5"}),t]}),u.jsx(Ht,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(Yt,{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}),u.jsxs("p",{className:"text-sm text-gray-500 mt-1 text-center",children:["Enter ",r,"-digit PIN"]})]}),u.jsxs(qt,{children:[u.jsx(pe,{type:"button",variant:"ghost",onClick:m,disabled:l,children:"Cancel"}),u.jsx(pe,{type:"submit",disabled:i.length!==r||l,children:l?"Submitting...":"Submit"})]})]})})})}function Es({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,c]=f.useState(!1),d=async m=>{if(m.preventDefault(),!!i.trim()){c(!0);try{o(i)}finally{c(!1)}}},h=()=>{a(""),o(null)};return u.jsx(Xt,{open:e,children:u.jsx(Wt,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:d,children:[u.jsxs(Kt,{children:[u.jsxs(Gt,{className:"flex items-center gap-2",children:[u.jsx(Z.Lock,{className:"h-5 w-5"}),t]}),u.jsx(Ht,{children:n})]}),u.jsx("div",{className:"py-4",children:u.jsx(Yt,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:l})}),u.jsxs(qt,{children:[u.jsx(pe,{type:"button",variant:"ghost",onClick:h,disabled:l,children:"Cancel"}),u.jsx(pe,{type:"submit",disabled:!i.trim()||l,children:l?"Submitting...":"Submit"})]})]})})})}function Kf({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(V=>{A[V.name]=V.value||""}),A}),[c,d]=f.useState({}),[h,m]=f.useState({}),[p,v]=f.useState(!1),w=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A)?null:"Please enter a valid email address",T=A=>A.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",S=(A,V=4)=>A.length===V?null:`PIN must be ${V} digits`,k=A=>{const V=A.replace(/\D/g,"");return V.length<=3?V:V.length<=6?`(${V.slice(0,3)}) ${V.slice(3)}`:`(${V.slice(0,3)}) ${V.slice(3,6)}-${V.slice(6,10)}`},E=(A,V,L)=>{let I=V,B=null;switch(L.type){case"phone":I=k(V),I.trim()&&(B=T(I));break;case"email":V.trim()&&(B=w(V));break;case"pin":I=V.replace(/\D/g,"").slice(0,6),I.trim()&&(B=S(I));break}!B&&L.validation&&I.trim()&&(B=L.validation(I)),l(H=>({...H,[A]:I})),d(H=>({...H,[A]:B||""}))},U=()=>{const A={};let V=!0;return s.forEach(L=>{const I=a[L.name]||"";let B=null;if(L.required&&!I.trim())B=`${L.label} is required`;else if(I.trim()){switch(L.type){case"email":B=w(I);break;case"phone":B=T(I);break;case"pin":B=S(I);break}!B&&L.validation&&(B=L.validation(I))}B&&(A[L.name]=B,V=!1)}),d(A),V},D=async A=>{if(A.preventDefault(),!!U()){v(!0);try{const V={};s.forEach(L=>{const I=a[L.name]?.trim();I&&(L.type==="phone"?V[L.name]=I.replace(/\D/g,""):V[L.name]=I)}),r(V)}finally{v(!1)}}},$=()=>{l({}),d({}),m({}),r(null)},F=A=>{m(V=>({...V,[A]:!V[A]}))},M=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"}},R=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 u.jsx(Xt,{open:e,children:u.jsx(Wt,{showCloseButton:!1,className:"max-w-md",children:u.jsxs("form",{onSubmit:D,children:[u.jsxs(Kt,{children:[u.jsx(Gt,{children:t}),n&&u.jsx(Ht,{children:n})]}),u.jsx("div",{className:"py-4 space-y-4",children:s.map(A=>u.jsxs("div",{children:[u.jsxs("label",{className:"block text-sm font-medium mb-1",children:[A.label,A.required&&u.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),u.jsxs("div",{className:"relative",children:[u.jsx(Yt,{type:M(A),value:a[A.name]||"",onChange:V=>E(A.name,V.target.value,A),placeholder:R(A),className:c[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"&&u.jsx("button",{type:"button",onClick:()=>F(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]?u.jsx(Z.EyeOff,{className:"h-4 w-4"}):u.jsx(Z.Eye,{className:"h-4 w-4"})})]}),c[A.name]&&u.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[u.jsx(Z.AlertCircle,{className:"h-3 w-3"}),c[A.name]]})]},A.name))}),u.jsxs(qt,{children:[u.jsx(pe,{type:"button",variant:"ghost",onClick:$,disabled:p,children:i}),u.jsx(pe,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const el=f.createContext(void 0);function tl(){const e=f.useContext(el);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function nl({children:e}){const[t,n]=f.useState(null),[s,r]=f.useState(null),o=f.useRef(null),i=f.useRef(null),a=f.useCallback(p=>new Promise(v=>{n(p),o.current=v}),[]),l=f.useCallback(p=>new Promise(v=>{r(p),i.current=v}),[]),c=f.useCallback(p=>{o.current&&(o.current(p),o.current=null),n(null)},[]),d=f.useCallback(p=>{i.current&&(i.current(p),i.current=null),r(null)},[]),h=()=>{if(s){const v=s.fields.map(w=>({name:w.name,type:w.type==="text"?"text":w.type==="password"?"password":w.type==="email"?"email":w.type==="phone"?"phone":w.type==="pin"?"pin":w.type==="ssn"?"ssn":w.type==="creditCard"?"creditCard":"text",label:w.label,placeholder:w.placeholder,required:w.required!==!1,value:w.value}));return u.jsx(Kf,{isOpen:!0,title:s.title,description:s.description,fields:v,onComplete:d})}if(!t)return null;const p={isOpen:!0,title:t.title,description:t.description,placeholder:t.placeholder,onComplete:c};switch(t.type){case"password":return u.jsx(zf,{...p});case"email":return u.jsx(_f,{...p});case"phone":return u.jsx(Xf,{...p});case"pin":return u.jsx(Wf,{...p});case"ssn":return u.jsx(Es,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return u.jsx(Es,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return u.jsx(Es,{...p})}},m=f.useMemo(()=>({showSecureModal:a,showSecureForm:l}),[a,l]);return u.jsxs(el.Provider,{value:m,children:[e,h()]})}function qf(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 Gf(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 ao(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,c=new Map;if(s&&s[1]){const M=s[1],R=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let A;for(;(A=R.exec(M))!==null;)if(A[1]&&A[2]){const V=parseInt(A[1],10),L=A[2].replace(/[.,;:!?]+$/,""),I=L.replace(/\/+$/,"");if(a.has(I)||a.set(I,L),i.has(I)||i.set(I,[]),i.get(I).push(V),!l.has(I))l.set(I,V);else{const B=l.get(I);V<B&&l.set(I,V)}}for(const[V,L]of i.entries()){const I=l.get(V);for(const B of L)B!==I&&c.set(B,I)}for(const[V,L]of l.entries()){const I=a.get(V)||V;r.set(L,I),o.push({number:L,url:I})}}let d,h=t;s&&s[0]&&(d=s[0],h=t.replace(n,""));const m=[];let p=0;const v=/```[\s\S]*?```|`[^`]+`/g;let w;for(;(w=v.exec(h))!==null;)w.index>p&&m.push({type:"text",content:h.slice(p,w.index),start:p,end:w.index}),m.push({type:"code",content:w[0],start:w.index,end:w.index+w[0].length}),p=w.index+w[0].length;p<h.length&&m.push({type:"text",content:h.slice(p),start:p,end:h.length});const T=m.map(M=>{if(M.type==="code")return M.content;let R=M.content;return R=R.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(V,L,I)=>{const B=parseInt(L,10),H=I.replace(/\/+$/,""),te=c.get(B)||B;return l.has(H)||(l.set(H,te),r.has(te)||(r.set(te,I),o.push({number:te,url:I}))),`[${te}]`}),R=R.replace(/\[(\d+)\]/g,(V,L)=>{const I=parseInt(L,10);return`[${c.get(I)||I}]`}),R}),S=[];for(const[M,R]of l.entries()){const A=a.get(M)||M,{baseUrl:V,anchor:L}=qf(A),I=Gf(A);S.push({url:A,baseUrl:V,numbers:[R],anchor:L,title:I})}S.sort((M,R)=>(M.numbers[0]||0)-(R.numbers[0]||0));const k=new Map;let E=1;for(const M of S){const R=M.numbers[0];k.set(R,E),M.numbers=[E],E++}const U=new Map;for(const[M,R]of r.entries()){const A=k.get(M);A&&U.set(A,R)}const D=o.map(M=>{const R=k.get(M.number);return R?{number:R,url:M.url}:M}).filter(M=>k.has(M.number)),$=Array.from(k.entries()).sort((M,R)=>R[0]-M[0]);let F=T.join("");for(const[M,R]of $){const A=new RegExp(`\\[${M}\\](?!\\d)`,"g");F=F.replace(A,`[${R}]`)}return{processedText:F,citations:D.sort((M,R)=>M.number-R.number),citationMap:U,groupedCitations:S,referencesText:d}}function mn(e){if(typeof e=="string")try{const t=JSON.parse(e);return mn(t)}catch{return e}if(Array.isArray(e))return e.map(mn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=mn(s);return t}return e}function Ms(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return mn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?mn(e):{}}function Hf({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:c=!1,tools:d=[],safeTools:h=[],safeToolNames:m,toolMetadata:p,systemPrompt:v="",agentId:w,agentName:T,tokenEndpoint:S="/api/arcten/token",apiBaseUrl:k="https://api.arcten.com",user:E,state:U,onStateChange:D,allowStateEdits:$=!0,sources:F,ragConfig:M,showCitations:R=!0,sensitiveParams:A,autoDetectSensitive:V=!1}){const L=k.replace(/\/+$/,""),{showSecureModal:I}=tl(),B=mo({apiBaseUrl:L,tokenEndpoint:S,user:E,tools:d,safeTools:h,toolMetadata:p,sensitiveParams:A,autoDetectSensitive:V,agentId:w,agentName:T,state:U,sources:F,ragConfig:M});f.useMemo(()=>M!==void 0?M:F&&F.length>0?{enabled:!0,organizationId:F[0],autoExecute:!0,filters:void 0}:{enabled:!1},[F,M]);const[H,te]=f.useState(c),[G,ee]=f.useState(i),[de,xe]=f.useState(600),[oe,rt]=f.useState(!1),[J,wt]=f.useState(!1),[ve,Te]=f.useState(!1),[ge,le]=f.useState({x:100,y:100}),[jn,Ue]=f.useState(!1),[$e,St]=f.useState({x:0,y:0}),[ze,Pn]=f.useState(!1),Tt=f.useRef(null),He=f.useRef(null),[it,Jt]=f.useState(""),[ot,Ct]=f.useState(null),[Zt,at]=f.useState("Thinking..."),[jt,_e]=f.useState(new Set),[ss,An]=f.useState(""),[Xe,En]=f.useState([]),Mn=f.useRef(new Map),Pt=f.useRef(!1),At=f.useRef(""),[Qt,kn]=f.useState(!1),[lt,en]=f.useState(!1),Ce=f.useMemo(()=>[...d,...h],[d,h]),je=f.useMemo(()=>tr(Ce,p),[Ce,p]),Re=f.useMemo(()=>{const C=new Map,q=new Map(je.map(g=>[g.name,g]));return Ce.forEach(g=>{const x=g[Me];if(x){const b=q.get(x);if(b){C.set(b.name,g);return}}const y=je.find(b=>b.name===g.name);y&&C.set(y.name,g)}),C},[Ce,je]),we=f.useMemo(()=>{const C=new Set,q=new Map(je.map(g=>[g.name,g]));return h.forEach(g=>{const x=g[Me];if(x&&q.has(x))C.add(x);else{const y=je.find(b=>b.name===g.name);y&&C.add(y.name)}}),m&&Array.isArray(m)&&m.forEach(g=>{typeof g=="string"&&C.add(g)}),C},[h,je,m]),ct=["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 C=localStorage.getItem("arcten-sidebar-expanded");C&&te(JSON.parse(C));const q=localStorage.getItem("arcten-sidebar-width");q&&ee(parseInt(q));const g=localStorage.getItem("arcten-sidebar-height");g&&xe(parseInt(g));const x=localStorage.getItem("arcten-sidebar-detached");x&&wt(JSON.parse(x));const y=localStorage.getItem("arcten-sidebar-position");if(y){const j=JSON.parse(y),P=50,z=Math.max(P-i,Math.min(j.x,window.innerWidth-P)),N=Math.max(0,Math.min(j.y,window.innerHeight-P));le({x:z,y:N})}const b=localStorage.getItem("arcten-sidebar-minimized");b&&Te(JSON.parse(b)),Pn(!0)}},[]),f.useMemo(()=>E,[E?.id]),f.useEffect(()=>{(async()=>{if(Ce.length===0)return;const q=Ce.map(g=>`${g.name}:${g.toString()}`).join("|");if(q!==At.current&&!Pt.current){Pt.current=!0,At.current=q;try{const g=Ce.map(y=>({name:y.name,code:y.toString()})),x=await fetch(`${L}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:g})});if(x.ok){const y=await x.json();y.tools&&y.tools.forEach(b=>{Mn.current.set(b.name,b)}),En(y.tools)}}catch(g){console.error("Failed to fetch tool descriptions:",g)}finally{Pt.current=!1}}})()},[Ce,L]),f.useEffect(()=>{Promise.resolve().then(()=>Nf).then(C=>{Ct(()=>C.Response)})},[]),f.useEffect(()=>{const C=()=>{An(window.location.pathname)};C(),window.addEventListener("popstate",C);const q=setInterval(C,500);return()=>{window.removeEventListener("popstate",C),clearInterval(q)}},[]);const{id:We,messages:Pe,sendMessage:Nn,status:ue,error:Ye,stop:ut,addToolOutput:Le,setMessages:dt,clientToken:Et,tokenError:Rn,conversations:Mt,isLoadingConversations:Fr,loadConversation:Fe,deleteConversation:rs,startNewConversation:tn}=B;f.useEffect(()=>{H&&He.current&&He.current.focus()},[H,Pe]),f.useEffect(()=>{const C=Pe[Pe.length-1];if(!C||C.role!=="assistant")return;const q=C.parts?.filter(g=>g.type?.startsWith("tool-")&&g.state==="input-available"&&typeof g.toolCallId=="string"&&g.input!==void 0)||[];for(const g of q){const x=g,y=x.type?.replace("tool-","")||"",b=x.toolCallId;if(we.has(y)){if(jt.has(b))continue;_e(P=>P.has(b)?P:new Set(P).add(b)),(async()=>{try{const P=Re.get(y);if(!P){console.warn(`[ArctenAgent] Tool ${y} not found in toolsMap`),Le({toolCallId:b,tool:y,output:`Error: Tool ${y} not found`}),_e(W=>{const X=new Set(W);return X.delete(b),X});return}const z=Ms(x.input),N=je.find(W=>W.name===y);let O;if(N&&N.jsonSchema?.properties){const X=Object.keys(N.jsonSchema.properties).map(_=>z[_]);O=await P(...X)}else O=await P(...Object.values(z));Le({toolCallId:b,tool:y,output:O}),_e(W=>{const X=new Set(W);return X.delete(b),X})}catch(P){console.error(`[ArctenAgent] Error executing safe tool ${y}:`,P),Le({toolCallId:b,tool:y,output:`Error: ${P instanceof Error?P.message:String(P)}`}),_e(z=>{const N=new Set(z);return N.delete(b),N})}})()}}},[Pe,we,Re,je,Le,jt]);function nn(){te(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function is(){te(!1),localStorage.setItem("arcten-sidebar-expanded","false")}f.useEffect(()=>{},[H]),f.useEffect(()=>{Tt.current&&Tt.current.scrollIntoView({behavior:"smooth"})},[Pe]),f.useEffect(()=>{function C(q){q.key==="Escape"&&(ue==="streaming"||ue==="submitted")&&(q.preventDefault(),ut())}return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[ue,ut]);function sn(C){const q=Math.floor((Date.now()-C)/1e3);return q<60?"now":q<3600?`${Math.floor(q/60)}m`:q<86400?`${Math.floor(q/3600)}h`:`${Math.floor(q/86400)}d`}function ht(){tn(),en(!1)}function rn(C){if(C.preventDefault(),!it.trim())return;(ue==="streaming"||ue==="submitted")&&ut();const q=ct[Math.floor(Math.random()*ct.length)]||"Thinking...";at(q),Nn({text:it}),Jt("")}function os(C){const q=C.target.value;Jt(q)}f.useEffect(()=>{if(!oe)return;function C(g){if(J){const x=g.clientX-ge.x,y=g.clientY-ge.y;x>=a&&x<=l&&ee(x),y>=400&&y<=1e3&&xe(y)}else{const x=window.innerWidth-g.clientX;x>=a&&x<=l&&ee(x)}}function q(){rt(!1),localStorage.setItem("arcten-sidebar-width",G.toString()),localStorage.setItem("arcten-sidebar-height",de.toString())}return window.addEventListener("mousemove",C),window.addEventListener("mouseup",q),()=>{window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",q)}},[oe,G,de,J,ge,a,l]);function Se(C){C.preventDefault(),rt(!0)}function as(){wt(!0),Te(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function ls(){wt(!1),Te(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Dn(){Te(!ve),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!ve))}function Vn(C){J&&(Ue(!0),St({x:C.clientX-ge.x,y:C.clientY-ge.y}))}return f.useEffect(()=>{if(!J)return;function C(){le(q=>{const x=window.innerWidth-50,y=window.innerHeight-50,b=50-G,j=0,P=Math.max(b,Math.min(q.x,x)),z=Math.max(j,Math.min(q.y,y));if(P!==q.x||z!==q.y){const N={x:P,y:z};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(N)),N}return q})}return window.addEventListener("resize",C),()=>window.removeEventListener("resize",C)},[J,G]),f.useEffect(()=>{if(!jn)return;function C(g){const x=g.clientX-$e.x,y=g.clientY-$e.y,b=50,j=window.innerWidth-b,P=window.innerHeight-b,z=b-G,N=0,O=Math.max(z,Math.min(x,j)),W=Math.max(N,Math.min(y,P));le({x:O,y:W})}function q(){Ue(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(ge))}return window.addEventListener("mousemove",C),window.addEventListener("mouseup",q),()=>{window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",q)}},[jn,$e,ge,G]),ze?Rn?u.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:u.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",Rn]})}):Et?u.jsx(Wu,{features:Sf,children:u.jsx(Fn,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:J?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:J?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
13
- ${J?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
10
+ `),()=>{C.contains(w)&&C.removeChild(w)}},[t]),u.jsx(Fu,{isPresent:t,childRef:o,sizeRef:i,children:Oe.cloneElement(e,{ref:l})})}const Uu=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const c=sr(zu),d=f.useId();let h=!0,m=f.useMemo(()=>(h=!1,{id:d,initial:t,isPresent:n,custom:r,onExitComplete:p=>{c.set(p,!0);for(const v of c.values())if(!v)return;s&&s()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[n,c,s]);return o&&h&&(m={...m}),f.useMemo(()=>{c.forEach((p,v)=>c.set(v,!1))},[n]),Oe.useEffect(()=>{!n&&!c.size&&s&&s()},[n]),i==="popLayout"&&(e=u.jsx(Bu,{isPresent:n,anchorX:a,root:l,children:e})),u.jsx(Zn.Provider,{value:m,children:e})};function zu(){return new Map}function oa(e=!0){const t=f.useContext(Zn);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 On=e=>e.key||"";function hi(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const _u=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:l})=>{const[c,d]=oa(i),h=f.useMemo(()=>hi(e),[e]),m=i&&!c?[]:h.map(On),p=f.useRef(!0),v=f.useRef(h),w=sr(()=>new Map),[C,S]=f.useState(h),[M,A]=f.useState(h);po(()=>{p.current=!1,v.current=h;for(let z=0;z<M.length;z++){const F=On(M[z]);m.includes(F)?w.delete(F):w.get(F)!==!0&&w.set(F,!1)}},[M,m.length,m.join("-")]);const U=[];if(h!==C){let z=[...h];for(let F=0;F<M.length;F++){const E=M[F],D=On(E);m.includes(D)||(z.splice(F,0,E),U.push(E))}return o==="wait"&&U.length&&(z=U),A(hi(z)),S(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&M.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:R}=f.useContext(nr);return u.jsx(u.Fragment,{children:M.map(z=>{const F=On(z),E=i&&!c?!1:h===M||m.includes(F),D=()=>{if(w.has(F))w.set(F,!0);else return;let P=!0;w.forEach(V=>{V||(P=!1)}),P&&(R?.(),A(v.current),i&&d?.(),s&&s())};return u.jsx(Uu,{isPresent:E,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:l,onExitComplete:E?void 0:D,anchorX:a,children:z},F)})})},Ar=f.createContext({strict:!1}),fi={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"]},It={};for(const e in fi)It[e]={isEnabled:t=>fi[e].some(n=>!!t[n])};function Ws(e){for(const t in e)It[t]={...It[t],...e[t]}}function Xu({children:e,features:t,strict:n=!1}){const[,s]=f.useState(!bs(t)),r=f.useRef(void 0);if(!bs(t)){const{renderer:o,...i}=t;r.current=o,Ws(i)}return f.useEffect(()=>{bs(t)&&t().then(({renderer:o,...i})=>{Ws(i),r.current=o,s(!0)})},[]),u.jsx(Ar.Provider,{value:{renderer:r.current,strict:n},children:e})}function bs(e){return typeof e=="function"}const Wu=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Hn(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Wu.has(e)}let aa=e=>!Hn(e);function Ku(e){typeof e=="function"&&(aa=t=>t.startsWith("on")?!Hn(t):e(t))}try{Ku(require("@emotion/is-prop-valid").default)}catch{}function qu(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(aa(r)||n===!0&&Hn(r)||!t&&!Hn(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const Qn=f.createContext({});function es(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function yn(e){return typeof e=="string"||Array.isArray(e)}const Er=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Mr=["initial",...Er];function ts(e){return es(e.animate)||Mr.some(t=>yn(e[t]))}function la(e){return!!(ts(e)||e.variants)}function Gu(e,t){if(ts(e)){const{initial:n,animate:s}=e;return{initial:n===!1||yn(n)?n:void 0,animate:yn(s)?s:void 0}}return e.inherit!==!1?t:{}}function Hu(e){const{initial:t,animate:n}=Gu(e,f.useContext(Qn));return f.useMemo(()=>({initial:t,animate:n}),[mi(t),mi(n)])}function mi(e){return Array.isArray(e)?e.join(" "):e}const xn={};function Yu(e){for(const t in e)xn[t]=e[t],hr(t)&&(xn[t].isCSSVariable=!0)}function ca(e,{layout:t,layoutId:n}){return Ft.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!xn[e]||e==="opacity")}const Ju={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Zu=Lt.length;function Qu(e,t,n){let s="",r=!0;for(let o=0;o<Zu;o++){const i=Lt[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 c=ea(a,Tr[i]);if(!l){r=!1;const d=Ju[i]||i;s+=`${d}(${c}) `}n&&(t[i]=c)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function kr(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const l in t){const c=t[l];if(Ft.has(l)){i=!0;continue}else if(hr(l)){r[l]=c;continue}else{const d=ea(c,Tr[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=Qu(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:d=0}=o;s.transformOrigin=`${l} ${c} ${d}`}}const Nr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function ua(e,t,n){for(const s in t)!fe(t[s])&&!ca(s,n)&&(e[s]=t[s])}function ed({transformTemplate:e},t){return f.useMemo(()=>{const n=Nr();return kr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function td(e,t){const n=e.style||{},s={};return ua(s,n,e),Object.assign(s,ed(e,t)),s}function nd(e,t){const n={},s=td(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 sd={offset:"stroke-dashoffset",array:"stroke-dasharray"},rd={offset:"strokeDashoffset",array:"strokeDasharray"};function id(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?sd:rd;e[o.offset]=X.transform(-s);const i=X.transform(t),a=X.transform(n);e[o.array]=`${i} ${a}`}function da(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,c,d){if(kr(e,a,c),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&&id(h,r,o,i,!1)}const ha=()=>({...Nr(),attrs:{}}),fa=e=>typeof e=="string"&&e.toLowerCase()==="svg";function od(e,t,n,s){const r=f.useMemo(()=>{const o=ha();return da(o,t,fa(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};ua(o,e.style,e),r.style={...o,...r.style}}return r}const ad=["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 Dr(e){return typeof e!="string"||e.includes("-")?!1:!!(ad.indexOf(e)>-1||/[A-Z]/u.test(e))}function ld(e,t,n,{latestValues:s},r,o=!1){const a=(Dr(e)?od:nd)(t,s,r,e),l=qu(t,typeof e=="string",o),c=e!==f.Fragment?{...l,...a,ref:n}:{},{children:d}=t,h=f.useMemo(()=>fe(d)?d.get():d,[d]);return f.createElement(e,{...c,children:h})}function pi(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Rr(e,t,n,s){if(typeof t=="function"){const[r,o]=pi(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]=pi(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function _n(e){return fe(e)?e.get():e}function cd({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:ud(n,s,r,e),renderState:t()}}function ud(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=_n(o[m]);let{initial:i,animate:a}=e;const l=ts(e),c=la(e);t&&c&&!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"&&!es(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p<m.length;p++){const v=Rr(e,m[p]);if(v){const{transitionEnd:w,transition:C,...S}=v;for(const M in S){let A=S[M];if(Array.isArray(A)){const U=d?A.length-1:0;A=A[U]}A!==null&&(r[M]=A)}for(const M in w)r[M]=w[M]}}}return r}const ma=e=>(t,n)=>{const s=f.useContext(Qn),r=f.useContext(Zn),o=()=>cd(e,t,s,r);return n?o():sr(o)};function Vr(e,t,n){const{style:s}=e,r={};for(const o in s)(fe(s[o])||t.style&&fe(t.style[o])||ca(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const dd=ma({scrapeMotionValuesFromProps:Vr,createRenderState:Nr});function pa(e,t,n){const s=Vr(e,t,n);for(const r in e)if(fe(e[r])||fe(t[r])){const o=Lt.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const hd=ma({scrapeMotionValuesFromProps:pa,createRenderState:ha}),fd=Symbol.for("motionComponentSymbol");function Et(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function md(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):Et(n)&&(n.current=s))},[t])}const Ir=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),pd="framerAppearId",ga="data-"+Ir(pd),ya=f.createContext({});function gd(e,t,n,s,r){const{visualElement:o}=f.useContext(Qn),i=f.useContext(Ar),a=f.useContext(Zn),l=f.useContext(Pr).reducedMotion,c=f.useRef(null);s=s||i.renderer,!c.current&&s&&(c.current=s(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const d=c.current,h=f.useContext(ya);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&yd(c.current,n,r,h);const m=f.useRef(!1);f.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[ga],v=f.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return po(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),v.current&&d.animationState&&d.animationState.animateChanges())}),f.useEffect(()=>{d&&(!v.current&&d.animationState&&d.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),v.current=!1),d.enteringChildren=void 0)}),d}function yd(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:xa(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Et(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:l,layoutRoot:c})}function xa(e){if(e)return e.options.allowProjection!==!1?e.projection:xa(e.parent)}function Xn(e,{forwardMotionProps:t=!1}={},n,s){n&&Ws(n);const r=Dr(e)?hd:dd;function o(a,l){let c;const d={...f.useContext(Pr),...a,layoutId:xd(a)},{isStatic:h}=d,m=Hu(a),p=r(a,h);if(!h&&rr){bd(d,n);const v=vd(d);c=v.MeasureLayout,m.visualElement=gd(e,p,d,s,v.ProjectionNode)}return u.jsxs(Qn.Provider,{value:m,children:[c&&m.visualElement?u.jsx(c,{visualElement:m.visualElement,...d}):null,ld(e,a,md(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[fd]=e,i}function xd({layoutId:e}){const t=f.useContext(nr).id;return t&&e!==void 0?t+"-"+e:e}function bd(e,t){const n=f.useContext(Ar).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?Ot(!1,s,"lazy-strict-mode"):Ge(!1,s,"lazy-strict-mode")}}function vd(e){const{drag:t,layout:n}=It;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function wd(e,t){if(typeof Proxy>"u")return Xn;const n=new Map,s=(o,i)=>Xn(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&cr(!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,Xn(i,void 0,e,t)),n.get(i))})}function ba({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function Sd({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Td(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),s=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function vs(e){return e===void 0||e===1}function Ks({scale:e,scaleX:t,scaleY:n}){return!vs(e)||!vs(t)||!vs(n)}function ft(e){return Ks(e)||va(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function va(e){return gi(e.x)||gi(e.y)}function gi(e){return e&&e!=="0%"}function Yn(e,t,n){const s=e-n,r=t*s;return n+r}function yi(e,t,n,s,r){return r!==void 0&&(e=Yn(e,r,s)),Yn(e,n,s)+t}function qs(e,t=0,n=1,s,r){e.min=yi(e.min,t,n,s,r),e.max=yi(e.max,t,n,s,r)}function wa(e,{x:t,y:n}){qs(e.x,t.translate,t.scale,t.originPoint),qs(e.y,n.translate,n.scale,n.originPoint)}const xi=.999999999999,bi=1.0000000000001;function Cd(e,t,n,s=!1){const r=n.length;if(!r)return;t.x=t.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&kt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,wa(e,i)),s&&ft(o.latestValues)&&kt(e,o.latestValues))}t.x<bi&&t.x>xi&&(t.x=1),t.y<bi&&t.y>xi&&(t.y=1)}function Mt(e,t){e.min=e.min+t,e.max=e.max+t}function vi(e,t,n,s,r=.5){const o=se(e.min,e.max,r);qs(e,t,n,o,s)}function kt(e,t){vi(e.x,t.x,t.scaleX,t.scale,t.originX),vi(e.y,t.y,t.scaleY,t.scale,t.originY)}function Sa(e,t){return ba(Td(e.getBoundingClientRect(),t))}function jd(e,t,n){const s=Sa(e,n),{scroll:r}=t;return r&&(Mt(s.x,r.offset.x),Mt(s.y,r.offset.y)),s}const wi=()=>({translate:0,scale:1,origin:0,originPoint:0}),Nt=()=>({x:wi(),y:wi()}),Si=()=>({min:0,max:0}),ie=()=>({x:Si(),y:Si()}),Gs={current:null},Ta={current:!1};function Pd(){if(Ta.current=!0,!!rr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>Gs.current=e.matches;e.addEventListener("change",t),t()}else Gs.current=!1}const Ad=new WeakMap;function Ed(e,t,n){for(const s in t){const r=t[s],o=n[s];if(fe(r))e.addValue(s,r);else if(fe(o))e.addValue(s,Vt(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,Vt(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Ti=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Md{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=wr,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=we.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,te.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=i;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,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=ts(n),this.isVariantNode=la(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&&fe(p)&&p.set(l[m])}}mount(t){this.current=t,Ad.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)),Ta.current||Pd(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Gs.current,process.env.NODE_ENV!=="production"&&cr(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(),tt(this.notifyUpdate),tt(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=Ft.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&te.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 It){const n=It[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):ie()}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<Ti.length;s++){const r=Ti[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=Ed(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=Vt(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"&&(go(s)||xo(s))?s=parseFloat(s):!Ou(s)&&nt.test(n)&&(s=Qo(t,n)),this.setBaseTarget(t,fe(s)?s.get():s)),fe(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=Rr(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&&!fe(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 lr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Cr.render(this.render)}}class Ca extends Md{constructor(){super(...arguments),this.KeyframeResolver=Cu}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:s}){delete n[t],delete s[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;fe(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function ja(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 kd(e){return window.getComputedStyle(e)}class Nd extends Ca{constructor(){super(...arguments),this.type="html",this.renderInstance=ja}readValueFromInstance(t,n){if(Ft.has(n))return this.projection?.isProjecting?Ls(n):zc(t,n);{const s=kd(t),r=(hr(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Sa(t,n)}build(t,n,s){kr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Vr(t,n,s)}}const Pa=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 Dd(e,t,n,s){ja(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(Pa.has(r)?r:Ir(r),t.attrs[r])}class Rd extends Ca{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ie}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Ft.has(n)){const s=Zo(n);return s&&s.default||0}return n=Pa.has(n)?n:Ir(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return pa(t,n,s)}build(t,n,s){da(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){Dd(t,n,s,r)}mount(t){this.isSVGTag=fa(t.tagName),super.mount(t)}}const Aa=(e,t)=>Dr(e)?new Rd(t):new Nd(t,{allowProjection:e!==f.Fragment});function Rt(e,t,n){const s=e.getProps();return Rr(s,t,n!==void 0?n:s.custom,e)}const Hs=e=>Array.isArray(e);function Vd(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Vt(n))}function Id(e){return Hs(e)?e[e.length-1]||0:e}function Od(e,t){const n=Rt(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Id(o[i]);Vd(e,i,a)}}function $d(e){return!!(fe(e)&&e.add)}function Ys(e,t){const n=e.getValue("willChange");if($d(n))return n.add(t);if(!n&&He.WillChange){const s=new He.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Ea(e){return e.props[ga]}const Ld=e=>e!==null;function Fd(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Ld),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const Bd={type:"spring",stiffness:500,damping:25,restSpeed:10},Ud=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),zd={type:"keyframes",duration:.8},_d={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Xd=(e,{keyframes:t})=>t.length>2?zd:Ft.has(e)?e.startsWith("scale")?Ud(t[1]):Bd:_d;function Wd({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:l,elapsed:c,...d}){return!!Object.keys(d).length}const Or=(e,t,n,s={},r,o)=>i=>{const a=Sr(s,e)||{},l=a.delay||s.delay||0;let{elapsed:c=0}=s;c=c-$e(l);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-c,onUpdate:m=>{t.set(m),a.onUpdate&&a.onUpdate(m)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:r};Wd(a)||Object.assign(d,Xd(e,d)),d.duration&&(d.duration=$e(d.duration)),d.repeatDelay&&(d.repeatDelay=$e(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let h=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(_s(d),d.delay===0&&(h=!0)),(He.instantAnimations||He.skipAnimations)&&(h=!0,_s(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const m=Fd(d.keyframes,a);if(m!==void 0){te.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new vr(d):new du(d)};function Kd({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function Ma(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const l=[],c=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||c&&Kd(c,d))continue;const p={delay:n,...Sr(o||{},d)},v=h.get();if(v!==void 0&&!h.isAnimating&&!Array.isArray(m)&&m===v&&!p.velocity)continue;let w=!1;if(window.MotionHandoffAnimation){const S=Ea(e);if(S){const M=window.MotionHandoffAnimation(S,d,te);M!==null&&(p.startTime=M,w=!0)}}Ys(e,d),h.start(Or(d,h,m,e.shouldReduceMotion&&Ho.has(d)?{type:!1}:p,e,w));const C=h.animation;C&&l.push(C)}return i&&Promise.all(l).then(()=>{te.update(()=>{i&&Od(e,i)})}),l}function ka(e,t,n,s=0,r=1){const o=Array.from(e).sort((c,d)=>c.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 Js(e,t,n={}){const s=Rt(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(Ma(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:c=0,staggerChildren:d,staggerDirection:h}=r;return qd(e,t,l,c,d,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[l,c]=a==="beforeChildren"?[o,i]:[i,o];return l().then(()=>c())}else return Promise.all([o(),i(n.delay)])}function qd(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(Js(l,t,{...i,delay:n+(typeof s=="function"?0:s)+ka(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function Gd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>Js(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=Js(e,t,n);else{const r=typeof t=="function"?Rt(e,t,n.custom):t;s=Promise.all(Ma(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function Na(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(t[s]!==e[s])return!1;return!0}const Hd=Mr.length;function Da(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Da(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<Hd;n++){const s=Mr[n],r=e.props[s];(yn(r)||r===!1)&&(t[s]=r)}return t}const Yd=[...Er].reverse(),Jd=Er.length;function Zd(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Gd(e,n,s)))}function Qd(e){let t=Zd(e),n=Ci(),s=!0;const r=l=>(c,d)=>{const h=Rt(e,d,l==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:m,transitionEnd:p,...v}=h;c={...c,...v,...p}}return c};function o(l){t=l(e)}function i(l){const{props:c}=e,d=Da(e.parent)||{},h=[],m=new Set;let p={},v=1/0;for(let C=0;C<Jd;C++){const S=Yd[C],M=n[S],A=c[S]!==void 0?c[S]:d[S],U=yn(A),R=S===l?M.isActive:null;R===!1&&(v=C);let z=A===d[S]&&A!==c[S]&&U;if(z&&s&&e.manuallyAnimateOnMount&&(z=!1),M.protectedKeys={...p},!M.isActive&&R===null||!A&&!M.prevProp||es(A)||typeof A=="boolean")continue;const F=eh(M.prevProp,A);let E=F||S===l&&M.isActive&&!z&&U||C>v&&U,D=!1;const P=Array.isArray(A)?A:[A];let V=P.reduce(r(S),{});R===!1&&(V={});const{prevResolvedValues:L={}}=M,I={...L,...V},B=q=>{E=!0,m.has(q)&&(D=!0,m.delete(q)),M.needsAnimating[q]=!0;const Q=e.getValue(q);Q&&(Q.liveStyle=!1)};for(const q in I){const Q=V[q],ce=L[q];if(p.hasOwnProperty(q))continue;let be=!1;Hs(Q)&&Hs(ce)?be=!Na(Q,ce):be=Q!==ce,be?Q!=null?B(q):m.add(q):Q!==void 0&&m.has(q)?B(q):M.protectedKeys[q]=!0}M.prevProp=A,M.prevResolvedValues=V,M.isActive&&(p={...p,...V}),s&&e.blockInitialAnimation&&(E=!1);const H=z&&F;E&&(!H||D)&&h.push(...P.map(q=>{const Q={type:S};if(typeof q=="string"&&s&&!H&&e.manuallyAnimateOnMount&&e.parent){const{parent:ce}=e,be=Rt(ce,q);if(ce.enteringChildren&&be){const{delayChildren:re}=be.transition||{};Q.delay=ka(ce.enteringChildren,e,re)}}return{animation:q,options:Q}}))}if(m.size){const C={};if(typeof c.initial!="boolean"){const S=Rt(e,Array.isArray(c.initial)?c.initial[0]:c.initial);S&&S.transition&&(C.transition=S.transition)}m.forEach(S=>{const M=e.getBaseTarget(S),A=e.getValue(S);A&&(A.liveStyle=!0),C[S]=M??null}),h.push({animation:C})}let w=!!h.length;return s&&(c.initial===!1||c.initial===c.animate)&&!e.manuallyAnimateOnMount&&(w=!1),s=!1,w?t(h):Promise.resolve()}function a(l,c){if(n[l].isActive===c)return Promise.resolve();e.variantChildren?.forEach(h=>h.animationState?.setActive(l,c)),n[l].isActive=c;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=Ci()}}}function eh(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!Na(t,e):!1}function dt(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Ci(){return{animate:dt(!0),whileInView:dt(),whileHover:dt(),whileTap:dt(),whileDrag:dt(),whileFocus:dt(),exit:dt()}}class st{constructor(t){this.isMounted=!1,this.node=t}update(){}}class th extends st{constructor(t){super(t),t.animationState||(t.animationState=Qd(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();es(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 nh=0;class sh extends st{constructor(){super(...arguments),this.id=nh++}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 Ra={animation:{Feature:th},exit:{Feature:sh}};function bn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function Tn(e){return{point:{x:e.pageX,y:e.pageY}}}const rh=e=>t=>jr(t)&&e(t,Tn(t));function un(e,t,n,s){return bn(e,t,rh(n),s)}const Va=1e-4,ih=1-Va,oh=1+Va,Ia=.01,ah=0-Ia,lh=0+Ia;function xe(e){return e.max-e.min}function ch(e,t,n){return Math.abs(e-t)<=n}function ji(e,t,n,s=.5){e.origin=s,e.originPoint=se(t.min,t.max,e.origin),e.scale=xe(n)/xe(t),e.translate=se(n.min,n.max,e.origin)-e.originPoint,(e.scale>=ih&&e.scale<=oh||isNaN(e.scale))&&(e.scale=1),(e.translate>=ah&&e.translate<=lh||isNaN(e.translate))&&(e.translate=0)}function dn(e,t,n,s){ji(e.x,t.x,n.x,s?s.originX:void 0),ji(e.y,t.y,n.y,s?s.originY:void 0)}function Pi(e,t,n){e.min=n.min+t.min,e.max=e.min+xe(t)}function uh(e,t,n){Pi(e.x,t.x,n.x),Pi(e.y,t.y,n.y)}function Ai(e,t,n){e.min=t.min-n.min,e.max=e.min+xe(t)}function hn(e,t,n){Ai(e.x,t.x,n.x),Ai(e.y,t.y,n.y)}function Ee(e){return[e("x"),e("y")]}const Oa=({current:e})=>e?e.ownerDocument.defaultView:null,Ei=(e,t)=>Math.abs(e-t);function dh(e,t){const n=Ei(e.x,t.x),s=Ei(e.y,t.y);return Math.sqrt(n**2+s**2)}class $a{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const m=Ss(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,v=dh(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!v)return;const{point:w}=m,{timestamp:C}=he;this.history.push({...w,timestamp:C});const{onStart:S,onMove:M}=this.handlers;p||(S&&S(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),M&&M(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=ws(p,this.transformPagePoint),te.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:v,onSessionEnd:w,resumeAnimation:C}=this.handlers;if(this.dragSnapToOrigin&&C&&C(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=Ss(m.type==="pointercancel"?this.lastMoveEventInfo:ws(p,this.transformPagePoint),this.history);this.startEvent&&v&&v(m,S),w&&w(m,S)},!jr(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=Tn(t),l=ws(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=he;this.history=[{...c,timestamp:d}];const{onSessionStart:h}=n;h&&h(t,Ss(l,this.history)),this.removeListeners=vn(un(this.contextWindow,"pointermove",this.handlePointerMove),un(this.contextWindow,"pointerup",this.handlePointerUp),un(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),tt(this.updatePoint)}}function ws(e,t){return t?{point:t(e.point)}:e}function Mi(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Ss({point:e},t){return{point:e,delta:Mi(e,La(t)),offset:Mi(e,hh(t)),velocity:fh(t,.1)}}function hh(e){return e[0]}function La(e){return e[e.length-1]}function fh(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=La(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>$e(t)));)n--;if(!s)return{x:0,y:0};const o=ke(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 mh(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?se(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?se(n,e,s.max):Math.min(e,n)),e}function ki(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 ph(e,{top:t,left:n,bottom:s,right:r}){return{x:ki(e.x,n,r),y:ki(e.y,t,s)}}function Ni(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 gh(e,t){return{x:Ni(e.x,t.x),y:Ni(e.y,t.y)}}function yh(e,t){let n=.5;const s=xe(e),r=xe(t);return r>s?n=mn(t.min,t.max-s,e.min):s>r&&(n=mn(e.min,e.max-r,t.min)),qe(0,1,n)}function xh(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 Zs=.35;function bh(e=Zs){return e===!1?e=0:e===!0&&(e=Zs),{x:Di(e,"left","right"),y:Di(e,"top","bottom")}}function Di(e,t,n){return{min:Ri(e,t),max:Ri(e,n)}}function Ri(e,t){return typeof e=="number"?e:e[t]||0}const vh=new WeakMap;class wh{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=ie(),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(Tn(h).point)},i=(h,m)=>{const{drag:p,dragPropagation:v,onDragStart:w}=this.getProps();if(p&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Eu(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),Ee(S=>{let M=this.getAxisMotionValue(S).get()||0;if(Be.test(M)){const{projection:A}=this.visualElement;if(A&&A.layout){const U=A.layout.layoutBox[S];U&&(M=xe(U)*(parseFloat(M)/100))}}this.originPoint[S]=M}),w&&te.postRender(()=>w(h,m)),Ys(this.visualElement,"transform");const{animationState:C}=this.visualElement;C&&C.setActive("whileDrag",!0)},a=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:v,onDirectionLock:w,onDrag:C}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:S}=m;if(v&&this.currentDirection===null){this.currentDirection=Sh(S),this.currentDirection!==null&&w&&w(this.currentDirection);return}this.updateAxis("x",m.point,S),this.updateAxis("y",m.point,S),this.visualElement.render(),C&&C(h,m)},l=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Ee(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:d}=this.getProps();this.panSession=new $a(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Oa(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&&te.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||!$n(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=mh(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&&Et(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=ph(s.layoutBox,t):this.constraints=!1,this.elastic=bh(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Ee(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=xh(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Et(t))return!1;const s=t.current;Ge(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=jd(s,r.root,this.visualElement.getTransformPagePoint());let i=gh(r.layout.layoutBox,o);if(n){const a=n(Sd(i));this.hasMutatedConstraints=!!a,a&&(i=ba(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Ee(d=>{if(!$n(d,n,this.currentDirection))return;let h=l&&l[d]||{};i&&(h={min:0,max:0});const m=r?200:1e6,p=r?40:1e7,v={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(d,v)});return Promise.all(c).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return Ys(this.visualElement,t),s.start(Or(t,s,0,n,this.visualElement,!1))}stopAnimation(){Ee(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Ee(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){Ee(n=>{const{drag:s}=this.getProps();if(!$n(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]-se(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Et(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Ee(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const l=a.get();r[i]=yh({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(),Ee(i=>{if(!$n(i,t,null))return;const a=this.getAxisMotionValue(i),{min:l,max:c}=this.constraints[i];a.set(se(l,c,r[i]))})}addListeners(){if(!this.visualElement.current)return;vh.set(this.visualElement,this);const t=this.visualElement.current,n=un(t,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),s=()=>{const{dragConstraints:l}=this.getProps();Et(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()),te.read(s);const i=bn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Ee(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=Zs,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function $n(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Sh(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Th extends st{constructor(t){super(t),this.removeGroupControls=Ne,this.removeListeners=Ne,this.controls=new wh(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ne}unmount(){this.removeGroupControls(),this.removeListeners()}}const Vi=e=>(t,n)=>{e&&te.postRender(()=>e(t,n))};class Ch extends st{constructor(){super(...arguments),this.removePointerDownListener=Ne}onPointerDown(t){this.session=new $a(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Oa(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Vi(t),onStart:Vi(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&te.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=un(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 Wn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ii(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const rn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(X.test(e))e=parseFloat(e);else return e;const n=Ii(e,t.target.x),s=Ii(e,t.target.y);return`${n}% ${s}%`}},jh={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=nt.parse(e);if(r.length>5)return s;const o=nt.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 c=se(a,l,.5);return typeof r[2+i]=="number"&&(r[2+i]/=c),typeof r[3+i]=="number"&&(r[3+i]/=c),o(r)}};let Ts=!1;class Ph extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;Yu(Ah),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),Ts&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Wn.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Ts=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||te.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Cr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Ts=!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 Fa(e){const[t,n]=oa(),s=f.useContext(nr);return u.jsx(Ph,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(ya),isPresent:t,safeToRemove:n})}const Ah={borderRadius:{...rn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:rn,borderTopRightRadius:rn,borderBottomLeftRadius:rn,borderBottomRightRadius:rn,boxShadow:jh};function Eh(e,t,n){const s=fe(e)?e:Vt(e);return s.start(Or("",s,t,n)),s.animation}const Mh=(e,t)=>e.depth-t.depth;class kh{constructor(){this.children=[],this.isDirty=!1}add(t){ir(this.children,t),this.isDirty=!0}remove(t){or(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Mh),this.isDirty=!1,this.children.forEach(t)}}function Nh(e,t){const n=we.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(tt(s),e(o-t))};return te.setup(s,!0),()=>tt(s)}const Ba=["TopLeft","TopRight","BottomLeft","BottomRight"],Dh=Ba.length,Oi=e=>typeof e=="string"?parseFloat(e):e,$i=e=>typeof e=="number"||X.test(e);function Rh(e,t,n,s,r,o){r?(e.opacity=se(0,n.opacity??1,Vh(s)),e.opacityExit=se(t.opacity??1,0,Ih(s))):o&&(e.opacity=se(t.opacity??1,n.opacity??1,s));for(let i=0;i<Dh;i++){const a=`border${Ba[i]}Radius`;let l=Li(t,a),c=Li(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||$i(l)===$i(c)?(e[a]=Math.max(se(Oi(l),Oi(c),s),0),(Be.test(c)||Be.test(l))&&(e[a]+="%")):e[a]=c}(t.rotate||n.rotate)&&(e.rotate=se(t.rotate||0,n.rotate||0,s))}function Li(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Vh=Ua(0,.5,Po),Ih=Ua(.5,.95,Ne);function Ua(e,t,n){return s=>s<e?0:s>t?1:n(mn(e,t,s))}function Fi(e,t){e.min=t.min,e.max=t.max}function Ae(e,t){Fi(e.x,t.x),Fi(e.y,t.y)}function Bi(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function Ui(e,t,n,s,r){return e-=t,e=Yn(e,1/n,s),r!==void 0&&(e=Yn(e,1/r,s)),e}function Oh(e,t=0,n=1,s=.5,r,o=e,i=e){if(Be.test(t)&&(t=parseFloat(t),t=se(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=se(o.min,o.max,s);e===o&&(a-=t),e.min=Ui(e.min,t,n,a,r),e.max=Ui(e.max,t,n,a,r)}function zi(e,t,[n,s,r],o,i){Oh(e,t[n],t[s],t[r],t.scale,o,i)}const $h=["x","scaleX","originX"],Lh=["y","scaleY","originY"];function _i(e,t,n,s){zi(e.x,t,$h,n?n.x:void 0,s?s.x:void 0),zi(e.y,t,Lh,n?n.y:void 0,s?s.y:void 0)}function Xi(e){return e.translate===0&&e.scale===1}function za(e){return Xi(e.x)&&Xi(e.y)}function Wi(e,t){return e.min===t.min&&e.max===t.max}function Fh(e,t){return Wi(e.x,t.x)&&Wi(e.y,t.y)}function Ki(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function _a(e,t){return Ki(e.x,t.x)&&Ki(e.y,t.y)}function qi(e){return xe(e.x)/xe(e.y)}function Gi(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class Bh{constructor(){this.members=[]}add(t){ir(this.members,t),t.scheduleRender()}remove(t){if(or(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(r=>t===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(t,n){const s=this.lead;if(t!==s&&(this.prevLead=s,this.lead=t,t.show(),s)){s.instance&&s.scheduleRender(),t.scheduleRender(),t.resumeFrom=s,n&&(t.resumeFrom.preserveOpacity=!0),s.snapshot&&(t.snapshot=s.snapshot,t.snapshot.latestValues=s.animationValues||s.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:r}=t.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:s}=t;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Uh(e,t,n){let s="";const r=e.x.translate/t.x,o=e.y.translate/t.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:c,rotate:d,rotateX:h,rotateY:m,skewX:p,skewY:v}=n;c&&(s=`perspective(${c}px) ${s}`),d&&(s+=`rotate(${d}deg) `),h&&(s+=`rotateX(${h}deg) `),m&&(s+=`rotateY(${m}deg) `),p&&(s+=`skewX(${p}deg) `),v&&(s+=`skewY(${v}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(s+=`scale(${a}, ${l})`),s||"none"}const Cs=["","X","Y","Z"],zh=1e3;let _h=0;function js(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function Xa(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Ea(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",te,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&Xa(s)}function Wa({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=_h++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(Kh),this.nodes.forEach(Yh),this.nodes.forEach(Jh),this.nodes.forEach(qh)},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 kh)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new lr),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=ia(i)&&!Vu(i),this.instance=i;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.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;te.read(()=>{h=window.innerWidth}),e(i,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,d&&d(),d=Nh(m,250),Wn.hasAnimatedSinceResize&&(Wn.hasAnimatedSinceResize=!1,this.nodes.forEach(Ji)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||c.getDefaultTransition()||nf,{onLayoutAnimationStart:w,onLayoutAnimationComplete:C}=c.getProps(),S=!this.targetLayout||!_a(this.targetLayout,p),M=!h&&m;if(this.options.layoutRoot||this.resumeFrom||M||h&&(S||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const A={...Sr(v,"layout"),onPlay:w,onComplete:C};(c.shouldReduceMotion||this.options.layoutRoot)&&(A.delay=0,A.type=!1),this.startAnimation(A),this.setAnimationOrigin(d,M)}else h||Ji(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(),tt(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(Zh),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&&Xa(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 c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Hi);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Yi);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Hh),this.nodes.forEach(Xh),this.nodes.forEach(Wh)):this.nodes.forEach(Yi),this.clearAllSnapshots();const a=we.now();he.delta=qe(0,1e3/60,a-he.timestamp),he.timestamp=a,he.isProcessing=!0,fs.update.process(he),fs.preRender.process(he),fs.render.process(he),he.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Cr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Gh),this.sharedNodes.forEach(Qh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,te.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){te.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!xe(this.snapshot.measuredBox.x)&&!xe(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=ie(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,i?i.layoutBox:void 0)}updateScroll(i="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===i&&(a=!1),a&&this.instance){const l=s(this.instance);this.scroll={animationId:this.root.animationId,phase:i,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!r)return;const i=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!za(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,d=c!==this.prevTransformTemplateValue;i&&this.instance&&(a||ft(this.latestValues)||d)&&(r(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return i&&(l=this.removeTransform(l)),sf(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ie();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(rf))){const{scroll:c}=this.root;c&&(Mt(a.x,c.offset.x),Mt(a.y,c.offset.y))}return a}removeElementScroll(i){const a=ie();if(Ae(a,i),this.scroll?.wasRoot)return a;for(let l=0;l<this.path.length;l++){const c=this.path[l],{scroll:d,options:h}=c;c!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&Ae(a,i),Mt(a.x,d.offset.x),Mt(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const l=ie();Ae(l,i);for(let c=0;c<this.path.length;c++){const d=this.path[c];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&kt(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),ft(d.latestValues)&&kt(l,d.latestValues)}return ft(this.latestValues)&&kt(l,this.latestValues),l}removeTransform(i){const a=ie();Ae(a,i);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!ft(c.latestValues))continue;Ks(c.latestValues)&&c.updateSnapshot();const d=ie(),h=c.measurePageBox();Ae(d,h),_i(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return ft(this.latestValues)&&_i(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!==he.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=he.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ie(),this.relativeTargetOrigin=ie(),hn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Ae(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ie(),this.targetWithTransforms=ie()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),uh(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Ae(this.target,this.layout.layoutBox),wa(this.target,this.targetDelta)):Ae(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=ie(),this.relativeTargetOrigin=ie(),hn(this.relativeTargetOrigin,this.target,m.target),Ae(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ks(this.parent.latestValues)||va(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===he.timestamp&&(l=!1),l)return;const{layout:c,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||!(c||d))return;Ae(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,m=this.treeScale.y;Cd(this.layoutCorrected,this.treeScale,this.path,a),i.layout&&!i.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(i.target=i.layout.layoutBox,i.targetWithTransforms=ie());const{target:p}=i;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Bi(this.prevProjectionDelta.x,this.projectionDelta.x),Bi(this.prevProjectionDelta.y,this.projectionDelta.y)),dn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==m||!Gi(this.projectionDelta.x,this.prevProjectionDelta.x)||!Gi(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=Nt(),this.projectionDelta=Nt(),this.projectionDeltaWithTransform=Nt()}setAnimationOrigin(i,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},h=Nt();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=ie(),p=l?l.source:void 0,v=this.layout?this.layout.source:void 0,w=p!==v,C=this.getStack(),S=!C||C.members.length<=1,M=!!(w&&!S&&this.options.crossfade===!0&&!this.path.some(tf));this.animationProgress=0;let A;this.mixTargetDelta=U=>{const R=U/1e3;Zi(h.x,i.x,R),Zi(h.y,i.y,R),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(hn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),ef(this.relativeTarget,this.relativeTargetOrigin,m,R),A&&Fh(this.relativeTarget,A)&&(this.isProjectionDirty=!1),A||(A=ie()),Ae(A,this.relativeTarget)),w&&(this.animationValues=d,Rh(d,c,this.latestValues,R,M,S)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(tt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=te.update(()=>{Wn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Vt(0)),this.currentAnimation=Eh(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(zh),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:d}=i;if(!(!a||!l||!c)){if(this!==i&&this.layout&&c&&Ka(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ie();const h=xe(this.layout.layoutBox.x);l.x.min=i.target.x.min,l.x.max=l.x.min+h;const m=xe(this.layout.layoutBox.y);l.y.min=i.target.y.min,l.y.max=l.y.min+m}Ae(a,l),kt(a,d),dn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new Bh),this.sharedNodes.get(i).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.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 c=this.getStack();c&&c.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 c={};l.z&&js("z",i,c,this.animationValues);for(let d=0;d<Cs.length;d++)js(`rotate${Cs[d]}`,i,c,this.animationValues),js(`skew${Cs[d]}`,i,c,this.animationValues);i.render();for(const d in c)i.setStaticValue(d,c[d]),this.animationValues&&(this.animationValues[d]=c[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=_n(a?.pointerEvents)||"",i.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(i.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,i.pointerEvents=_n(a?.pointerEvents)||""),this.hasProjected&&!ft(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let h=Uh(this.projectionDeltaWithTransform,this.treeScale,d);l&&(h=l(d,h)),i.transform=h;const{x:m,y:p}=this.projectionDelta;i.transformOrigin=`${m.origin*100}% ${p.origin*100}% 0`,c.animationValues?i.opacity=c===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:i.opacity=c===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const v in xn){if(d[v]===void 0)continue;const{correct:w,applyTo:C,isCSSVariable:S}=xn[v],M=h==="none"?d[v]:w(d[v],c);if(C){const A=C.length;for(let U=0;U<A;U++)i[C[U]]=M}else S?this.options.visualElement.renderState.vars[v]=M:i[v]=M}this.options.layoutId&&(i.pointerEvents=c===this?_n(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(Hi),this.root.sharedNodes.clear()}}}function Xh(e){e.updateLayout()}function Wh(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:r}=e.options,o=t.source!==e.layout.source;r==="size"?Ee(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=xe(h);h.min=n[d].min,h.max=h.min+m}):Ka(r,t.layoutBox,n)&&Ee(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=xe(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=Nt();dn(i,n,t.layoutBox);const a=Nt();o?dn(a,e.applyTransform(s,!0),t.measuredBox):dn(a,n,t.layoutBox);const l=!za(i);let c=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:m}=d;if(h&&m){const p=ie();hn(p,t.layoutBox,h.layoutBox);const v=ie();hn(v,n,m.layoutBox),_a(p,v)||(c=!0),d.options.layoutRoot&&(e.relativeTarget=v,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:l,hasRelativeLayoutChanged:c})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function Kh(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function qh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Gh(e){e.clearSnapshot()}function Hi(e){e.clearMeasurements()}function Yi(e){e.isLayoutDirty=!1}function Hh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Ji(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Yh(e){e.resolveTargetDelta()}function Jh(e){e.calcProjection()}function Zh(e){e.resetSkewAndRotation()}function Qh(e){e.removeLeadSnapshot()}function Zi(e,t,n){e.translate=se(t.translate,0,n),e.scale=se(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Qi(e,t,n,s){e.min=se(t.min,n.min,s),e.max=se(t.max,n.max,s)}function ef(e,t,n,s){Qi(e.x,t.x,n.x,s),Qi(e.y,t.y,n.y,s)}function tf(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const nf={duration:.45,ease:[.4,0,.1,1]},eo=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),to=eo("applewebkit/")&&!eo("chrome/")?Math.round:Ne;function no(e){e.min=to(e.min),e.max=to(e.max)}function sf(e){no(e.x),no(e.y)}function Ka(e,t,n){return e==="position"||e==="preserve-aspect"&&!ch(qi(t),qi(n),.2)}function rf(e){return e!==e.root&&e.scroll?.wasRoot}const of=Wa({attachResizeListener:(e,t)=>bn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Ps={current:void 0},qa=Wa({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Ps.current){const e=new of({});e.mount(window),e.setOptions({layoutScroll:!0}),Ps.current=e}return Ps.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),af={pan:{Feature:Ch},drag:{Feature:Th,ProjectionNode:qa,MeasureLayout:Fa}};function so(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&&te.postRender(()=>o(t,Tn(t)))}class lf extends st{mount(){const{current:t}=this.node;t&&(this.unmount=Mu(t,(n,s)=>(so(this.node,s,"Start"),r=>so(this.node,r,"End"))))}unmount(){}}class cf 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=vn(bn(this.node.current,"focus",()=>this.onFocus()),bn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function ro(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&&te.postRender(()=>o(t,Tn(t)))}class uf extends st{mount(){const{current:t}=this.node;t&&(this.unmount=Ru(t,(n,s)=>(ro(this.node,s,"Start"),(r,{success:o})=>ro(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Qs=new WeakMap,As=new WeakMap,df=e=>{const t=Qs.get(e.target);t&&t(e)},hf=e=>{e.forEach(df)};function ff({root:e,...t}){const n=e||document;As.has(n)||As.set(n,{});const s=As.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(hf,{root:e,...t})),s[r]}function mf(e,t,n){const s=ff(t);return Qs.set(e,n),s.observe(e),()=>{Qs.delete(e),s.unobserve(e)}}const pf={some:0,all:1};class gf 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:pf[r]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:d,onViewportLeave:h}=this.node.getProps(),m=c?d:h;m&&m(l)};return mf(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(yf(t,n))&&this.startObserver()}unmount(){}}function yf({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Ga={inView:{Feature:gf},tap:{Feature:uf},focus:{Feature:cf},hover:{Feature:lf}},xf={layout:{ProjectionNode:qa,MeasureLayout:Fa}},bf={...Ra,...Ga,...af,...xf},vf=wd(bf,Aa),wf={renderer:Aa,...Ra,...Ga};function $r(e,t){return Xn(e,t)}const Sf=$r("button"),Ln=$r("div"),Tf=$r("p");function Cf({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return u.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:u.jsxs("div",{className:"flex items-start gap-2",children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:u.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&u.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>u.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[u.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),u.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),u.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[u.jsxs(me,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[u.jsx(J.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),u.jsx(me,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:u.jsx(J.X,{className:"h-3 w-3"})})]})]})})}function jf({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(([c])=>!i.includes(c))),l=Object.keys(a).length>0;return u.jsxs("div",{className:"my-1",children:[u.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&&u.jsx("span",{className:"transition-transform duration-200",children:r?u.jsx(J.ChevronDown,{className:"h-3 w-3"}):u.jsx(J.ChevronRight,{className:"h-3 w-3"})}),n?u.jsx(J.X,{className:"h-3 w-3"}):s?u.jsx(J.Zap,{className:"h-3 w-3"}):u.jsx(J.Check,{className:"h-3 w-3"}),u.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&l&&u.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:u.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([c,d])=>u.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[u.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[c,":"]}),u.jsx("span",{className:"font-mono text-foreground",children:typeof d=="string"?d:JSON.stringify(d)})]},c))})})]})}function Pf({...e}){return u.jsx(er.Root,{"data-slot":"collapsible",...e})}function Af({...e}){return u.jsx(er.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function Ef({...e}){return u.jsx(er.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const Mf=f.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Lr=f.memo(({className:e,...t})=>typeof window>"u"?null:u.jsx(f.Suspense,{fallback:null,children:u.jsx(Mf,{className:Z("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Lr.displayName="Response";const kf=Object.freeze(Object.defineProperty({__proto__:null,Response:Lr},Symbol.toStringTag,{value:"Module"})),Nf=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=vf.create(t),i=f.useMemo(()=>(e?.length??0)*r,[e,r]);return u.jsx(o,{animate:{backgroundPosition:"0% center"},className:Z("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:e})},Df=f.memo(Nf),Ha=f.createContext(null),Rf=()=>{const e=f.useContext(Ha);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},Vf=1e3,If=1e3,Ya=f.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,c]=zr.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,h]=zr.useControllableState({prop:o,defaultProp:0}),[m,p]=f.useState(!1),[v,w]=f.useState(null);f.useEffect(()=>{t?v===null&&w(Date.now()):v!==null&&(h(Math.ceil((Date.now()-v)/If)),w(null))},[t,v,h]),f.useEffect(()=>{if(s&&!t&&l&&!m){const S=setTimeout(()=>{c(!1),p(!0)},Vf);return()=>clearTimeout(S)}},[t,l,s,c,m]);const C=S=>{c(S)};return u.jsx(Ha.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:c,duration:d},children:u.jsx(Pf,{className:Z("not-prose mb-4",e),onOpenChange:C,open:l,...a,children:i})})}),Of=(e,t)=>e||t===0?u.jsx(Df,{duration:1,children:"Thinking..."}):t===void 0?u.jsx("p",{children:"Thought for a few seconds"}):u.jsxs("p",{children:["Thought for ",t," seconds"]}),Ja=f.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Rf();return u.jsx(Af,{className:Z("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??u.jsxs(u.Fragment,{children:[u.jsx(J.BrainIcon,{className:"size-4"}),Of(s,o),u.jsx(J.ChevronDownIcon,{className:Z("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Za=f.memo(({className:e,children:t,...n})=>u.jsx(Ef,{className:Z("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:u.jsx(Lr,{className:"grid gap-2",children:t})}));Ya.displayName="Reasoning";Ja.displayName="ReasoningTrigger";Za.displayName="ReasoningContent";function io(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=io(s.domain);return u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsxs("button",{className:Z("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:[u.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),u.jsx("span",{className:"leading-none",children:s.domain})]})}),u.jsx(Qe,{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:u.jsxs("div",{className:"space-y-1.5",children:[u.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 u.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:Z("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:[u.jsx("img",{src:io(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const l=a.target;l.style.display="none"}}),u.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function Lf({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:l=!0}){const c=f.useRef(null),[d,h]=f.useState([]);f.useEffect(()=>{if(!a||!c.current||t.length===0||n.size===0){(n.size===0||!a)&&h([]);return}const C=c.current;let S,M=!1;const A=new WeakSet,U=()=>{if(!c.current||M)return;M=!0;const z=c.current,F=/\[(\d+)\]/g,E=document.createTreeWalker(z,NodeFilter.SHOW_TEXT,null),D=[];let P;for(;P=E.nextNode();)if(P.nodeType===Node.TEXT_NODE&&!A.has(P)){const L=P,I=L.textContent||"";let B=L.parentElement,H=!1;for(;B&&B!==z;){if(B.tagName==="A"||B.tagName==="CODE"||B.tagName==="PRE"){H=!0;break}B=B.parentElement}if(!H){const q=Array.from(I.matchAll(F)).filter(Q=>{if(!Q[1])return!1;const ce=parseInt(Q[1],10);return n.has(ce)});q.length>0&&D.push({node:L,matches:q})}}if(D.length===0){M=!1;return}const V=[];D.forEach(({node:L,matches:I})=>{A.add(L);const B=L.textContent||"",H=document.createDocumentFragment();let ee=0;I.forEach(q=>{if(!q[1])return;q.index!==void 0&&q.index>ee&&H.appendChild(document.createTextNode(B.slice(ee,q.index)));const Q=document.createElement("span");Q.className="inline-flex items-center citation-button-container";const ce=parseInt(q[1],10);Q.setAttribute("data-citation",q[1]),H.appendChild(Q),V.push({element:Q,citationNum:ce}),ee=(q.index||0)+q[0].length}),ee<B.length&&H.appendChild(document.createTextNode(B.slice(ee))),L.parentNode&&L.parentNode.replaceChild(H,L)}),V.length>0&&h(L=>{const I=new Set(L.map(ee=>ee.element)),B=L.filter(ee=>ee.element.isConnected),H=V.filter(ee=>!I.has(ee.element));return[...B,...H]}),M=!1},R=new MutationObserver(()=>{clearTimeout(S),S=setTimeout(U,100)});return R.observe(C,{childList:!0,subtree:!0,characterData:!0}),S=setTimeout(U,200),()=>{R.disconnect(),clearTimeout(S)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(C){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(C)}&sz=16`}function v(C){try{return new URL(C).hostname.replace(/^www\./,"")}catch{return C}}const w=a&&l&&m?u.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[u.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),u.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((C,S)=>{const M=C.title||C.baseUrl,A=v(C.url),U=p(A);return u.jsxs("a",{href:C.url,target:"_blank",rel:"noopener noreferrer",className:Z("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:[u.jsx("img",{src:U,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:R=>{const z=R.target;z.style.display="none"}}),u.jsx("span",{className:"leading-none",children:M})]},`group-${S}`)}):Array.from(n.entries()).sort(([C],[S])=>C-S).map(([C,S])=>{const M=v(S),A=p(M);return u.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",className:Z("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:[u.jsx("img",{src:A,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:U=>{const R=U.target;R.style.display="none"}}),u.jsx("span",{className:"leading-none",children:S})]},C)})})]}):null;return u.jsxs("div",{className:i,children:[u.jsx("div",{ref:c,children:u.jsx(o,{children:e})}),a&&d.filter(({element:C})=>C.isConnected).map(({element:C,citationNum:S},M)=>{if(!t.find(R=>R.number===S))return null;const U=Array.from(new Map(t.map(R=>{const z=R.url.replace(/\/+$/,""),F=s?.find(E=>E.url.replace(/\/+$/,"")===z);return[z,{number:R.number,url:R.url,domain:v(R.url),title:F?.title}]})).values());return gl.createPortal(u.jsx($f,{sources:U,citationNumber:S},`citation-${S}-${C}`),C,`citation-${S}-${M}`)}),w]})}function Bt({...e}){return u.jsx(xt.Root,{"data-slot":"dialog",...e})}function Ff({...e}){return u.jsx(xt.Portal,{"data-slot":"dialog-portal",...e})}function Bf({className:e,...t}){return u.jsx(xt.Overlay,{"data-slot":"dialog-overlay",className:Z("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 Ut({className:e,children:t,showCloseButton:n=!0,...s}){return u.jsxs(Ff,{"data-slot":"dialog-portal",children:[u.jsx(Bf,{}),u.jsxs(xt.Content,{"data-slot":"dialog-content",className:Z("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&&u.jsxs(xt.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:[u.jsx(J.XIcon,{}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function zt({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-header",className:Z("flex flex-col gap-2 text-center sm:text-left",e),...t})}function _t({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-footer",className:Z("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function Xt({className:e,...t}){return u.jsx(xt.Title,{"data-slot":"dialog-title",className:Z("text-lg leading-none font-semibold",e),...t})}function Wt({className:e,...t}){return u.jsx(xt.Description,{"data-slot":"dialog-description",className:Z("text-muted-foreground text-sm",e),...t})}function Kt({className:e,type:t,...n}){return u.jsx("input",{type:t,"data-slot":"input",className:Z("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 Uf({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),[c,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 u.jsx(Bt,{open:e,children:u.jsx(Ut,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:h,children:[u.jsxs(zt,{children:[u.jsx(Xt,{children:t}),u.jsx(Wt,{children:n})]}),u.jsx("div",{className:"py-4",children:u.jsxs("div",{className:"relative",children:[u.jsx(Kt,{type:a?"text":"password",value:o,onChange:p=>i(p.target.value),placeholder:s,className:"pr-10",autoFocus:!0,disabled:c}),u.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:c,children:a?u.jsx(J.EyeOff,{className:"h-4 w-4"}):u.jsx(J.Eye,{className:"h-4 w-4"})})]})}),u.jsxs(_t,{children:[u.jsx(me,{type:"button",variant:"ghost",onClick:m,disabled:c,children:"Cancel"}),u.jsx(me,{type:"submit",disabled:!o.trim()||c,children:c?"Submitting...":"Submit"})]})]})})})}function zf({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),[c,d]=f.useState(!1),h=w=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(w),m=w=>{i(w),w.trim()?l(h(w)):l(!0)},p=async w=>{if(w.preventDefault(),!o.trim()||!h(o)){l(!1);return}d(!0);try{r(o)}finally{d(!1)}},v=()=>{i(""),l(!0),r(null)};return u.jsx(Bt,{open:e,children:u.jsx(Ut,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:p,children:[u.jsxs(zt,{children:[u.jsxs(Xt,{className:"flex items-center gap-2",children:[u.jsx(J.Mail,{className:"h-5 w-5"}),t]}),u.jsx(Wt,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(Kt,{type:"email",value:o,onChange:w=>m(w.target.value),placeholder:s,className:a?"":"border-red-500",autoFocus:!0,disabled:c}),!a&&u.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid email address"})]}),u.jsxs(_t,{children:[u.jsx(me,{type:"button",variant:"ghost",onClick:v,disabled:c,children:"Cancel"}),u.jsx(me,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function _f({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),[c,d]=f.useState(!1),h=C=>{const S=C.replace(/\D/g,"");return S.length<=3?S:S.length<=6?`(${S.slice(0,3)}) ${S.slice(3)}`:`(${S.slice(0,3)}) ${S.slice(3,6)}-${S.slice(6,10)}`},m=C=>C.replace(/\D/g,"").length===10,p=C=>{const S=h(C);i(S),S.trim()?l(m(S)):l(!0)},v=async C=>{if(C.preventDefault(),!o.trim()||!m(o)){l(!1);return}d(!0);try{const S=o.replace(/\D/g,"");r(S)}finally{d(!1)}},w=()=>{i(""),l(!0),r(null)};return u.jsx(Bt,{open:e,children:u.jsx(Ut,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:v,children:[u.jsxs(zt,{children:[u.jsxs(Xt,{className:"flex items-center gap-2",children:[u.jsx(J.Phone,{className:"h-5 w-5"}),t]}),u.jsx(Wt,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(Kt,{type:"tel",value:o,onChange:C=>p(C.target.value),placeholder:s,className:a?"":"border-red-500",maxLength:14,autoFocus:!0,disabled:c}),!a&&u.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid 10-digit phone number"})]}),u.jsxs(_t,{children:[u.jsx(me,{type:"button",variant:"ghost",onClick:w,disabled:c,children:"Cancel"}),u.jsx(me,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function Xf({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,c]=f.useState(!1),d=p=>{const v=p.replace(/\D/g,"");a(v.slice(0,r))},h=async p=>{if(p.preventDefault(),i.length===r){c(!0);try{o(i)}finally{c(!1)}}},m=()=>{a(""),o(null)};return u.jsx(Bt,{open:e,children:u.jsx(Ut,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:h,children:[u.jsxs(zt,{children:[u.jsxs(Xt,{className:"flex items-center gap-2",children:[u.jsx(J.Shield,{className:"h-5 w-5"}),t]}),u.jsx(Wt,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(Kt,{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}),u.jsxs("p",{className:"text-sm text-gray-500 mt-1 text-center",children:["Enter ",r,"-digit PIN"]})]}),u.jsxs(_t,{children:[u.jsx(me,{type:"button",variant:"ghost",onClick:m,disabled:l,children:"Cancel"}),u.jsx(me,{type:"submit",disabled:i.length!==r||l,children:l?"Submitting...":"Submit"})]})]})})})}function Es({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,c]=f.useState(!1),d=async m=>{if(m.preventDefault(),!!i.trim()){c(!0);try{o(i)}finally{c(!1)}}},h=()=>{a(""),o(null)};return u.jsx(Bt,{open:e,children:u.jsx(Ut,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:d,children:[u.jsxs(zt,{children:[u.jsxs(Xt,{className:"flex items-center gap-2",children:[u.jsx(J.Lock,{className:"h-5 w-5"}),t]}),u.jsx(Wt,{children:n})]}),u.jsx("div",{className:"py-4",children:u.jsx(Kt,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:l})}),u.jsxs(_t,{children:[u.jsx(me,{type:"button",variant:"ghost",onClick:h,disabled:l,children:"Cancel"}),u.jsx(me,{type:"submit",disabled:!i.trim()||l,children:l?"Submitting...":"Submit"})]})]})})})}function Wf({isOpen:e,title:t,description:n,fields:s,onComplete:r,submitText:o="Submit",cancelText:i="Cancel"}){const[a,l]=f.useState(()=>{const P={};return s.forEach(V=>{P[V.name]=V.value||""}),P}),[c,d]=f.useState({}),[h,m]=f.useState({}),[p,v]=f.useState(!1),w=P=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(P)?null:"Please enter a valid email address",C=P=>P.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",S=(P,V=4)=>P.length===V?null:`PIN must be ${V} digits`,M=P=>{const V=P.replace(/\D/g,"");return V.length<=3?V:V.length<=6?`(${V.slice(0,3)}) ${V.slice(3)}`:`(${V.slice(0,3)}) ${V.slice(3,6)}-${V.slice(6,10)}`},A=(P,V,L)=>{let I=V,B=null;switch(L.type){case"phone":I=M(V),I.trim()&&(B=C(I));break;case"email":V.trim()&&(B=w(V));break;case"pin":I=V.replace(/\D/g,"").slice(0,6),I.trim()&&(B=S(I));break}!B&&L.validation&&I.trim()&&(B=L.validation(I)),l(H=>({...H,[P]:I})),d(H=>({...H,[P]:B||""}))},U=()=>{const P={};let V=!0;return s.forEach(L=>{const I=a[L.name]||"";let B=null;if(L.required&&!I.trim())B=`${L.label} is required`;else if(I.trim()){switch(L.type){case"email":B=w(I);break;case"phone":B=C(I);break;case"pin":B=S(I);break}!B&&L.validation&&(B=L.validation(I))}B&&(P[L.name]=B,V=!1)}),d(P),V},R=async P=>{if(P.preventDefault(),!!U()){v(!0);try{const V={};s.forEach(L=>{const I=a[L.name]?.trim();I&&(L.type==="phone"?V[L.name]=I.replace(/\D/g,""):V[L.name]=I)}),r(V)}finally{v(!1)}}},z=()=>{l({}),d({}),m({}),r(null)},F=P=>{m(V=>({...V,[P]:!V[P]}))},E=P=>{switch(P.type){case"password":return h[P.name]?"text":"password";case"email":return"email";case"phone":return"tel";case"pin":case"ssn":return"password";default:return"text"}},D=P=>{if(P.placeholder)return P.placeholder;switch(P.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 ${P.label.toLowerCase()}...`}};return u.jsx(Bt,{open:e,children:u.jsx(Ut,{showCloseButton:!1,className:"max-w-md",children:u.jsxs("form",{onSubmit:R,children:[u.jsxs(zt,{children:[u.jsx(Xt,{children:t}),n&&u.jsx(Wt,{children:n})]}),u.jsx("div",{className:"py-4 space-y-4",children:s.map(P=>u.jsxs("div",{children:[u.jsxs("label",{className:"block text-sm font-medium mb-1",children:[P.label,P.required&&u.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),u.jsxs("div",{className:"relative",children:[u.jsx(Kt,{type:E(P),value:a[P.name]||"",onChange:V=>A(P.name,V.target.value,P),placeholder:D(P),className:c[P.name]?"border-red-500":"",disabled:p,autoFocus:P===s[0],maxLength:P.type==="pin"?6:P.type==="phone"?14:void 0}),P.type==="password"&&u.jsx("button",{type:"button",onClick:()=>F(P.name),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:p,children:h[P.name]?u.jsx(J.EyeOff,{className:"h-4 w-4"}):u.jsx(J.Eye,{className:"h-4 w-4"})})]}),c[P.name]&&u.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[u.jsx(J.AlertCircle,{className:"h-3 w-3"}),c[P.name]]})]},P.name))}),u.jsxs(_t,{children:[u.jsx(me,{type:"button",variant:"ghost",onClick:z,disabled:p,children:i}),u.jsx(me,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const Qa=f.createContext(void 0);function el(){const e=f.useContext(Qa);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function tl({children:e}){const[t,n]=f.useState(null),[s,r]=f.useState(null),o=f.useRef(null),i=f.useRef(null),a=f.useCallback(p=>new Promise(v=>{n(p),o.current=v}),[]),l=f.useCallback(p=>new Promise(v=>{r(p),i.current=v}),[]),c=f.useCallback(p=>{o.current&&(o.current(p),o.current=null),n(null)},[]),d=f.useCallback(p=>{i.current&&(i.current(p),i.current=null),r(null)},[]),h=()=>{if(s){const v=s.fields.map(w=>({name:w.name,type:w.type==="text"?"text":w.type==="password"?"password":w.type==="email"?"email":w.type==="phone"?"phone":w.type==="pin"?"pin":w.type==="ssn"?"ssn":w.type==="creditCard"?"creditCard":"text",label:w.label,placeholder:w.placeholder,required:w.required!==!1,value:w.value}));return u.jsx(Wf,{isOpen:!0,title:s.title,description:s.description,fields:v,onComplete:d})}if(!t)return null;const p={isOpen:!0,title:t.title,description:t.description,placeholder:t.placeholder,onComplete:c};switch(t.type){case"password":return u.jsx(Uf,{...p});case"email":return u.jsx(zf,{...p});case"phone":return u.jsx(_f,{...p});case"pin":return u.jsx(Xf,{...p});case"ssn":return u.jsx(Es,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return u.jsx(Es,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return u.jsx(Es,{...p})}},m=f.useMemo(()=>({showSecureModal:a,showSecureForm:l}),[a,l]);return u.jsxs(Qa.Provider,{value:m,children:[e,h()]})}function Kf(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 oo(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,c=new Map;if(s&&s[1]){const E=s[1],D=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let P;for(;(P=D.exec(E))!==null;)if(P[1]&&P[2]){const V=parseInt(P[1],10),L=P[2].replace(/[.,;:!?]+$/,""),I=L.replace(/\/+$/,"");if(a.has(I)||a.set(I,L),i.has(I)||i.set(I,[]),i.get(I).push(V),!l.has(I))l.set(I,V);else{const B=l.get(I);V<B&&l.set(I,V)}}for(const[V,L]of i.entries()){const I=l.get(V);for(const B of L)B!==I&&c.set(B,I)}for(const[V,L]of l.entries()){const I=a.get(V)||V;r.set(L,I),o.push({number:L,url:I})}}let d,h=t;s&&s[0]&&(d=s[0],h=t.replace(n,""));const m=[];let p=0;const v=/```[\s\S]*?```|`[^`]+`/g;let w;for(;(w=v.exec(h))!==null;)w.index>p&&m.push({type:"text",content:h.slice(p,w.index),start:p,end:w.index}),m.push({type:"code",content:w[0],start:w.index,end:w.index+w[0].length}),p=w.index+w[0].length;p<h.length&&m.push({type:"text",content:h.slice(p),start:p,end:h.length});const C=m.map(E=>{if(E.type==="code")return E.content;let D=E.content;return D=D.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(V,L,I)=>{const B=parseInt(L,10),H=I.replace(/\/+$/,""),ee=c.get(B)||B;return l.has(H)||(l.set(H,ee),r.has(ee)||(r.set(ee,I),o.push({number:ee,url:I}))),`[${ee}]`}),D=D.replace(/\[(\d+)\]/g,(V,L)=>{const I=parseInt(L,10);return`[${c.get(I)||I}]`}),D}),S=[];for(const[E,D]of l.entries()){const P=a.get(E)||E,{baseUrl:V,anchor:L}=Kf(P),I=qf(P);S.push({url:P,baseUrl:V,numbers:[D],anchor:L,title:I})}S.sort((E,D)=>(E.numbers[0]||0)-(D.numbers[0]||0));const M=new Map;let A=1;for(const E of S){const D=E.numbers[0];M.set(D,A),E.numbers=[A],A++}const U=new Map;for(const[E,D]of r.entries()){const P=M.get(E);P&&U.set(P,D)}const R=o.map(E=>{const D=M.get(E.number);return D?{number:D,url:E.url}:E}).filter(E=>M.has(E.number)),z=Array.from(M.entries()).sort((E,D)=>D[0]-E[0]);let F=C.join("");for(const[E,D]of z){const P=new RegExp(`\\[${E}\\](?!\\d)`,"g");F=F.replace(P,`[${D}]`)}return{processedText:F,citations:R.sort((E,D)=>E.number-D.number),citationMap:U,groupedCitations:S,referencesText:d}}function fn(e){if(typeof e=="string")try{const t=JSON.parse(e);return fn(t)}catch{return e}if(Array.isArray(e))return e.map(fn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=fn(s);return t}return e}function Ms(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return fn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?fn(e):{}}function Gf({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:c=!1,tools:d=[],safeTools:h=[],safeToolNames:m,toolMetadata:p,systemPrompt:v="",agentId:w,agentName:C,tokenEndpoint:S="/api/arcten/token",apiBaseUrl:M="https://api.arcten.com",user:A,state:U,onStateChange:R,allowStateEdits:z=!0,sources:F,ragConfig:E,showCitations:D=!0,sensitiveParams:P,autoDetectSensitive:V=!1}){const L=M.replace(/\/+$/,""),{showSecureModal:I}=el(),B=fo({apiBaseUrl:L,tokenEndpoint:S,user:A,tools:d,safeTools:h,toolMetadata:p,sensitiveParams:P,autoDetectSensitive:V,agentId:w,agentName:C,state:U,sources:F,ragConfig:E});f.useMemo(()=>E!==void 0?E:F&&F.length>0?{enabled:!0,organizationId:F[0],autoExecute:!0,filters:void 0}:{enabled:!1},[F,E]);const[H,ee]=f.useState(c),[q,Q]=f.useState(i),[ce,be]=f.useState(600),[re,rt]=f.useState(!1),[Y,bt]=f.useState(!1),[Se,Ce]=f.useState(!1),[pe,oe]=f.useState({x:100,y:100}),[Cn,Ue]=f.useState(!1),[Le,vt]=f.useState({x:0,y:0}),[ze,jn]=f.useState(!1),wt=f.useRef(null),Ye=f.useRef(null),[it,qt]=f.useState(""),[ot,St]=f.useState(null),[Gt,at]=f.useState("Thinking..."),[Tt,_e]=f.useState(new Set),[ns,Pn]=f.useState(""),[Xe,An]=f.useState([]),En=f.useRef(new Map),Ct=f.useRef(!1),Mn=f.useRef(""),[Ht,kn]=f.useState(!1),[lt,ct]=f.useState(!1),De=f.useMemo(()=>[...d,...h],[d,h]),ue=f.useMemo(()=>tr(De,p),[De,p]),Re=f.useMemo(()=>{const j=new Map,g=new Map(ue.map(y=>[y.name,y]));return De.forEach(y=>{const x=y[Me];if(x){const T=g.get(x);if(T){j.set(T.name,y);return}}const b=ue.find(T=>T.name===y.name);b&&j.set(b.name,y)}),j},[De,ue]),Fe=f.useMemo(()=>{const j=new Set,g=new Map(ue.map(y=>[y.name,y]));return h.forEach(y=>{const x=y[Me];if(x&&g.has(x))j.add(x);else{const b=ue.find(T=>T.name===y.name);b&&j.add(b.name)}}),m&&Array.isArray(m)&&m.forEach(y=>{typeof y=="string"&&j.add(y)}),j},[h,ue,m]),Ve=["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 j=localStorage.getItem("arcten-sidebar-expanded");j&&ee(JSON.parse(j));const g=localStorage.getItem("arcten-sidebar-width");g&&Q(parseInt(g));const y=localStorage.getItem("arcten-sidebar-height");y&&be(parseInt(y));const x=localStorage.getItem("arcten-sidebar-detached");x&&bt(JSON.parse(x));const b=localStorage.getItem("arcten-sidebar-position");if(b){const N=JSON.parse(b),O=50,_=Math.max(O-i,Math.min(N.x,window.innerWidth-O)),k=Math.max(0,Math.min(N.y,window.innerHeight-O));oe({x:_,y:k})}const T=localStorage.getItem("arcten-sidebar-minimized");T&&Ce(JSON.parse(T)),jn(!0)}},[]),f.useMemo(()=>A,[A?.id]),f.useEffect(()=>{(async()=>{if(De.length===0)return;const g=De.map(y=>`${y.name}:${y.toString()}`).join("|");if(g!==Mn.current&&!Ct.current){Ct.current=!0,Mn.current=g;try{const y=De.map(b=>({name:b.name,code:b.toString()})),x=await fetch(`${L}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:y})});if(x.ok){const b=await x.json();b.tools&&b.tools.forEach(T=>{En.current.set(T.name,T)}),An(b.tools)}}catch(y){console.error("Failed to fetch tool descriptions:",y)}finally{Ct.current=!1}}})()},[De,L]),f.useEffect(()=>{Promise.resolve().then(()=>kf).then(j=>{St(()=>j.Response)})},[]),f.useEffect(()=>{const j=()=>{Pn(window.location.pathname)};j(),window.addEventListener("popstate",j);const g=setInterval(j,500);return()=>{window.removeEventListener("popstate",j),clearInterval(g)}},[]);const{id:ss,messages:je,sendMessage:We,status:de,error:Yt,stop:ut,addToolOutput:ve,setMessages:Jt,clientToken:rs,tokenError:jt,conversations:Nn,isLoadingConversations:Ke,loadConversation:is,deleteConversation:Zt,startNewConversation:Qt}=B;f.useEffect(()=>{H&&Ye.current&&Ye.current.focus()},[H,je]),f.useEffect(()=>{const j=je[je.length-1];if(!j||j.role!=="assistant")return;const g=j.parts?.filter(y=>y.type?.startsWith("tool-")&&y.state==="input-available"&&typeof y.toolCallId=="string"&&y.input!==void 0)||[];for(const y of g){const x=y,b=x.type?.replace("tool-","")||"",T=x.toolCallId;if(Fe.has(b)){if(Tt.has(T))continue;_e(O=>O.has(T)?O:new Set(O).add(T)),(async()=>{try{const O=Re.get(b);if(!O){console.warn(`[ArctenAgent] Tool ${b} not found in toolsMap`),ve({toolCallId:T,tool:b,output:`Error: Tool ${b} not found`}),_e($=>{const W=new Set($);return W.delete(T),W});return}const _=Ms(x.input),k=ue.find($=>$.name===b);let G;if(k&&k.jsonSchema?.properties){const W=Object.keys(k.jsonSchema.properties).map(K=>_[K]);G=await O(...W)}else G=await O(...Object.values(_));ve({toolCallId:T,tool:b,output:G}),_e($=>{const W=new Set($);return W.delete(T),W})}catch(O){console.error(`[ArctenAgent] Error executing safe tool ${b}:`,O),ve({toolCallId:T,tool:b,output:`Error: ${O instanceof Error?O.message:String(O)}`}),_e(_=>{const k=new Set(_);return k.delete(T),k})}})()}}},[je,Fe,Re,ue,ve,Tt]);function os(){ee(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function en(){ee(!1),localStorage.setItem("arcten-sidebar-expanded","false")}f.useEffect(()=>{},[H]),f.useEffect(()=>{wt.current&&wt.current.scrollIntoView({behavior:"smooth"})},[je]),f.useEffect(()=>{function j(g){g.key==="Escape"&&(de==="streaming"||de==="submitted")&&(g.preventDefault(),ut())}return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[de,ut]);function tn(j){const g=Math.floor((Date.now()-j)/1e3);return g<60?"now":g<3600?`${Math.floor(g/60)}m`:g<86400?`${Math.floor(g/3600)}h`:`${Math.floor(g/86400)}d`}function Dn(){Qt(),ct(!1)}function Rn(j){if(j.preventDefault(),!it.trim())return;(de==="streaming"||de==="submitted")&&ut();const g=Ve[Math.floor(Math.random()*Ve.length)]||"Thinking...";at(g),We({text:it}),qt("")}function Te(j){const g=j.target.value;qt(g)}f.useEffect(()=>{if(!re)return;function j(y){if(Y){const x=y.clientX-pe.x,b=y.clientY-pe.y;x>=a&&x<=l&&Q(x),b>=400&&b<=1e3&&be(b)}else{const x=window.innerWidth-y.clientX;x>=a&&x<=l&&Q(x)}}function g(){rt(!1),localStorage.setItem("arcten-sidebar-width",q.toString()),localStorage.setItem("arcten-sidebar-height",ce.toString())}return window.addEventListener("mousemove",j),window.addEventListener("mouseup",g),()=>{window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",g)}},[re,q,ce,Y,pe,a,l]);function as(j){j.preventDefault(),rt(!0)}function ls(){bt(!0),Ce(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function cs(){bt(!1),Ce(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function nn(){Ce(!Se),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Se))}function sn(j){Y&&(Ue(!0),vt({x:j.clientX-pe.x,y:j.clientY-pe.y}))}return f.useEffect(()=>{if(!Y)return;function j(){oe(g=>{const x=window.innerWidth-50,b=window.innerHeight-50,T=50-q,N=0,O=Math.max(T,Math.min(g.x,x)),_=Math.max(N,Math.min(g.y,b));if(O!==g.x||_!==g.y){const k={x:O,y:_};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(k)),k}return g})}return window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[Y,q]),f.useEffect(()=>{if(!Cn)return;function j(y){const x=y.clientX-Le.x,b=y.clientY-Le.y,T=50,N=window.innerWidth-T,O=window.innerHeight-T,_=T-q,k=0,G=Math.max(_,Math.min(x,N)),$=Math.max(k,Math.min(b,O));oe({x:G,y:$})}function g(){Ue(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(pe))}return window.addEventListener("mousemove",j),window.addEventListener("mouseup",g),()=>{window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",g)}},[Cn,Le,pe,q]),ze?jt?u.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:u.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",jt]})}):rs?u.jsx(Xu,{features:wf,children:u.jsx(Ln,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:Y?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:Y?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
11
+ ${Y?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
14
12
  ${H?"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"}
15
- ${J?"border border-border":"border-l border-border"}
13
+ ${Y?"border border-border":"border-l border-border"}
16
14
  ${H?"":"w-[30px]"}
17
- `,style:H?J?{width:`${G}px`,height:ve?"auto":`${de}px`,left:`${ge.x}px`,top:`${ge.y}px`}:{width:`${G}px`}:void 0,onClick:H?void 0:nn,children:H?u.jsxs(u.Fragment,{children:[!J&&u.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:Se,children:u.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),J&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:C=>{C.preventDefault(),rt(!0)}}),u.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:C=>{C.preventDefault(),C.stopPropagation(),Ue(!0),St({x:C.clientX-ge.x,y:C.clientY-ge.y})},children:u.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"})}),u.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:C=>{C.preventDefault(),rt(!0)}})]}),u.jsxs("div",{className:"flex flex-col h-full",children:[u.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${J?"cursor-move":""}`,onMouseDown:J?Vn:void 0,children:[u.jsx("h2",{className:`text-base font-semibold ${J&&ve?"cursor-pointer":""}`,onClick:J&&ve?C=>{C.stopPropagation(),Dn()}:void 0,children:r}),u.jsxs("div",{className:"flex items-center gap-1",onClick:C=>C.stopPropagation(),children:[u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx("button",{type:"button",className:Q(mt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ht,"aria-label":"New chat",children:u.jsx(Z.Plus,{className:"h-4 w-4"})})}),u.jsx(Qe,{children:"Start a new conversation"})]}),u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx("button",{type:"button",className:Q(mt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?ls:as,"aria-label":J?"Dock sidebar":"Float sidebar",children:J?u.jsx(Z.Dock,{className:"h-4 w-4"}):u.jsx(Z.PictureInPicture2,{className:"h-4 w-4"})})}),u.jsx(Qe,{children:J?"Dock to sidebar":"Undock to floating window"})]}),u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx("button",{type:"button",className:Q(mt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?Dn:is,"aria-label":J?ve?"Maximize":"Minimize":"Close sidebar",children:J?ve?u.jsx(Z.Maximize2,{className:"h-4 w-4"}):u.jsx(Z.Minimize2,{className:"h-4 w-4"}):u.jsx(Z.X,{className:"h-4 w-4"})})}),u.jsx(Qe,{children:J?ve?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!ve&&u.jsxs(u.Fragment,{children:[E&&Mt.length>0&&u.jsxs("div",{className:`border-b border-border ${lt?"flex flex-col flex-1":""}`,children:[u.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[u.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),u.jsx(pe,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{en(!lt)},children:lt?"Show less":"View all"})]}),u.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${lt?"flex-1 overflow-y-auto":""}`,children:Mt.slice(0,lt?void 0:3).map(C=>u.jsxs("div",{className:"group relative",children:[u.jsxs(Tf,{type:"button",className:Q(mt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>{Fe(C.chatId||C._id),en(!1)},children:[u.jsx("span",{className:"text-xs truncate",children:C.title}),u.jsx("div",{className:"ml-2 flex items-center",children:u.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:sn(C.updatedAt)})})]}),u.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:q=>{q.stopPropagation(),rs(C._id)},"aria-label":"Delete conversation",children:u.jsx(Z.X,{className:"h-3 w-3"})})]},C._id))})]}),u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[u.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Pe.length===0?u.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&u.jsx("div",{className:"mb-6",children:o}),u.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),Xe.length>0&&u.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:u.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(Qt?Xe:Xe.slice(0,10)).map(C=>u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx(hs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Jt(C.sampleUsage),He.current?.focus()},children:C.friendlyName})}),u.jsx(Qe,{children:u.jsxs("div",{className:"max-w-xs",children:[u.jsx("p",{className:"font-medium",children:C.description}),u.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[u.jsx("span",{className:"font-medium",children:"Example:"}),' "',C.sampleUsage,'"']}),C.paramCount>0&&u.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[u.jsx("span",{className:"font-medium",children:"Parameters:"})," ",C.params.join(", ")]})]})})]},C.name)),Xe.length>10&&!Qt&&u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsxs(hs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>kn(!0),children:["+",Xe.length-10," more"]})}),u.jsx(Qe,{children:u.jsxs("div",{className:"max-w-xs",children:[u.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),u.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:Xe.slice(10).map(C=>u.jsxs("div",{children:[u.jsxs("span",{className:"font-medium text-xs",children:[C.friendlyName,":"]}),u.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:C.description})]},C.name))}),u.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),Qt&&Xe.length>10&&u.jsx(hs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>kn(!1),children:"Show less"})]})})]}):u.jsxs(u.Fragment,{children:[Pe.map(C=>{const g=C.parts.filter(N=>N.type==="text").map(N=>N.text).join("");let x=C.parts;C.role==="assistant"&&C.parts.some(O=>O.timestamp)&&(x=[...C.parts].sort((O,W)=>{const X=O.timestamp||0,_=W.timestamp||0;return X-_}));let y=[],b=new Map,j=[],P,z=!0;if(C.role==="assistant"){const N=x.filter(_=>_.type==="text"&&_.text),O=[],W=[];N.forEach(_=>{const{citations:Y,citationMap:ie,groupedCitations:he,referencesText:De}=ao(_.text);y.push(...Y),O.push(ie),he&&W.push(...he),De&&(P=De)}),O.forEach(_=>{_.forEach((Y,ie)=>{b.has(ie)||b.set(ie,Y)})}),j=Array.from(new Map(W.map(_=>[_.url,_])).values()).sort((_,Y)=>(_.numbers[0]||0)-(Y.numbers[0]||0)),z=!(ue==="streaming"&&C.id===Pe.at(-1)?.id)}return u.jsx("div",{className:`${C.role==="user"?"flex justify-end":"w-full"}`,children:u.jsx("div",{className:`${C.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:C.role==="user"?u.jsx(Cf,{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:g}):u.jsx("div",{className:"space-y-2",children:x.map((N,O)=>{if(N.type?.startsWith("tool-")){const W=N.type?.replace("tool-","")||"",X=je.find(ie=>ie.name===W),_=N.state==="input-available",Y=N.state==="output-available";if(_&&we.has(W),_){if(we.has(W))return null;const ie=Ms(N.input);return u.jsx(Fn,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:u.jsx(jf,{toolName:W,description:X?.description||"",args:ie,onApprove:async()=>{if(jt.has(N.toolCallId))return;_e(De=>new Set(De).add(N.toolCallId));const he=Re.get(W);if(he)try{const De=await he(...Object.values(ie));Le({toolCallId:N.toolCallId,tool:W,output:De})}catch(De){Le({toolCallId:N.toolCallId,tool:W,output:`Error: ${De}`})}},onDeny:async()=>{jt.has(N.toolCallId)||(_e(he=>new Set(he).add(N.toolCallId)),Le({toolCallId:N.toolCallId,tool:W,output:"User denied tool execution"}))}})},`${N.toolCallId}-${O}`)}else if(Y){const ie=N.output==="User denied tool execution",he=Ms(N.input);return u.jsx(Pf,{toolName:W,args:he,isDenied:ie,isSafe:we.has(W)},`${N.toolCallId}-${O}`)}return null}if(N.type==="text"&&N.text&&ot){const{processedText:W}=ao(N.text),ie=!x.slice(O+1).some(he=>he.type==="text"&&he.text)&&z&&b.size>0;return u.jsx(Ff,{text:W,citations:y,citationMap:b,groupedCitations:ie?j:void 0,referencesText:ie?P:void 0,ResponseComponent:ot,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:R,showReferences:ie},`${C.id}-${O}`)}return N.type==="reasoning"&&N.text?u.jsxs(Ja,{className:"w-full",isStreaming:ue==="streaming"&&O===C.parts.length-1&&C.id===Pe.at(-1)?.id,children:[u.jsx(Za,{}),u.jsx(Qa,{children:N.text})]},`${C.id}-${O}`):null})})})},C.id)}),u.jsx("div",{ref:Tt})]})}),Ye&&u.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Ye.message]}),u.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[u.jsx(Xu,{mode:"wait",children:(ue==="streaming"||ue==="submitted")&&u.jsxs(Fn,{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:[u.jsx(Fn,{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]}}),u.jsx("p",{className:"text-xs text-muted-foreground",children:Zt})]})}),u.jsxs("form",{onSubmit:rn,className:"relative",children:[u.jsx(po,{ref:He,value:it,onChange:os,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),rn(C))}}),ue==="streaming"||ue==="submitted"?u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx("button",{type:"button",className:Q(mt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:ut,children:u.jsx(Z.Square,{className:"h-4 w-4"})})}),u.jsxs(Qe,{children:[u.jsx(Xr,{children:"Escape"})," to stop"]})]}):u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx("button",{type:"submit",className:Q(mt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!it.trim(),children:u.jsx(Z.ArrowRight,{className:"h-4 w-4"})})}),u.jsxs(Qe,{children:[u.jsx(Xr,{children:"Enter"})," to send"]})]})]})]})]}),u.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:[u.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),u.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),u.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):u.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[u.jsx(Z.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),u.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):u.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:u.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function Yf(e){return u.jsx(nl,{children:u.jsx(Hf,{...e})})}function Jf(e={}){const{apiBaseUrl:t="https://api.arcten.com",tokenEndpoint:n="/token",clientToken:s,skipTokenFetch:r=!1}=e,[o,i]=f.useState(!1),[a,l]=f.useState(null),c=f.useRef(s||null);f.useEffect(()=>{if(s){c.current=s;return}if(r)return;(async()=>{try{const p=await fetch(`${t}${n}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(p.ok){const v=await p.json();c.current=v.token}}catch(p){console.error("[useGenerate] Failed to fetch token:",p)}})()},[t,n,s,r]);const d=f.useCallback(async m=>{i(!0),l(null);try{const p={"Content-Type":"application/json"};c.current&&(p.Authorization=`Bearer ${c.current}`);const v=await fetch(`${t}/generate`,{method:"POST",headers:p,body:JSON.stringify(m)});if(!v.ok){const T=await v.json().catch(()=>({}));throw new Error(T.error||`HTTP ${v.status}`)}return await v.json()}catch(p){const v=p instanceof Error?p.message:String(p);throw l(v),p}finally{i(!1)}},[t]),h=f.useCallback(async(m,p)=>{i(!0),l(null);try{const v={"Content-Type":"application/json"};c.current&&(v.Authorization=`Bearer ${c.current}`);const w=await fetch(`${t}/generate/stream`,{method:"POST",headers:v,body:JSON.stringify(m)});if(!w.ok){const E=await w.json().catch(()=>({}));throw new Error(E.error||`HTTP ${w.status}`)}const T=w.body?.getReader();if(!T)throw new Error("No response body");const S=new TextDecoder;let k=null;for(;;){const{done:E,value:U}=await T.read();if(E)break;const $=S.decode(U,{stream:!0}).split(`
18
- `).filter(F=>F.startsWith("data: "));for(const F of $){const M=F.slice(6).trim();if(M)try{const R=JSON.parse(M);if(R.error)throw new Error(R.error);R.done&&R.object?k={object:R.object,usage:R.usage,finishReason:R.finishReason}:R.partial&&p&&p(R.partial)}catch{}}}if(!k)throw new Error("Stream ended without final result");return k}catch(v){const w=v instanceof Error?v.message:String(v);throw l(w),v}finally{i(!1)}},[t]);return{generate:d,streamGenerate:h,isLoading:o,error:a}}exports.ARCTEN_ORIGINAL_NAME=Me;exports.ArctenAgent=Yf;exports.SecureModalProvider=nl;exports.extractToolsMetadata=tr;exports.preserveToolName=bl;exports.useAgent=mo;exports.useGenerate=Jf;exports.useSecureModal=tl;
15
+ `,style:H?Y?{width:`${q}px`,height:Se?"auto":`${ce}px`,left:`${pe.x}px`,top:`${pe.y}px`}:{width:`${q}px`}:void 0,onClick:H?void 0:os,children:H?u.jsxs(u.Fragment,{children:[!Y&&u.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:as,children:u.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),Y&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:j=>{j.preventDefault(),rt(!0)}}),u.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:j=>{j.preventDefault(),j.stopPropagation(),Ue(!0),vt({x:j.clientX-pe.x,y:j.clientY-pe.y})},children:u.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"})}),u.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:j=>{j.preventDefault(),rt(!0)}})]}),u.jsxs("div",{className:"flex flex-col h-full",children:[u.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${Y?"cursor-move":""}`,onMouseDown:Y?sn:void 0,children:[u.jsx("h2",{className:`text-base font-semibold ${Y&&Se?"cursor-pointer":""}`,onClick:Y&&Se?j=>{j.stopPropagation(),nn()}:void 0,children:r}),u.jsxs("div",{className:"flex items-center gap-1",onClick:j=>j.stopPropagation(),children:[u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx("button",{type:"button",className:Z(ht({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Dn,"aria-label":"New chat",children:u.jsx(J.Plus,{className:"h-4 w-4"})})}),u.jsx(Qe,{children:"Start a new conversation"})]}),u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx("button",{type:"button",className:Z(ht({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Y?cs:ls,"aria-label":Y?"Dock sidebar":"Float sidebar",children:Y?u.jsx(J.Dock,{className:"h-4 w-4"}):u.jsx(J.PictureInPicture2,{className:"h-4 w-4"})})}),u.jsx(Qe,{children:Y?"Dock to sidebar":"Undock to floating window"})]}),u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx("button",{type:"button",className:Z(ht({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Y?nn:en,"aria-label":Y?Se?"Maximize":"Minimize":"Close sidebar",children:Y?Se?u.jsx(J.Maximize2,{className:"h-4 w-4"}):u.jsx(J.Minimize2,{className:"h-4 w-4"}):u.jsx(J.X,{className:"h-4 w-4"})})}),u.jsx(Qe,{children:Y?Se?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Se&&u.jsxs(u.Fragment,{children:[A&&Nn.length>0&&u.jsxs("div",{className:`border-b border-border ${lt?"flex flex-col flex-1":""}`,children:[u.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[u.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),u.jsx(me,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{ct(!lt)},children:lt?"Show less":"View all"})]}),u.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${lt?"flex-1 overflow-y-auto":""}`,children:Nn.slice(0,lt?void 0:3).map(j=>u.jsxs("div",{className:"group relative",children:[u.jsxs(Sf,{type:"button",className:Z(ht({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>{is(j.chatId||j._id),ct(!1)},children:[u.jsx("span",{className:"text-xs truncate",children:j.title}),u.jsx("div",{className:"ml-2 flex items-center",children:u.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:tn(j.updatedAt)})})]}),u.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:g=>{g.stopPropagation(),Zt(j._id)},"aria-label":"Delete conversation",children:u.jsx(J.X,{className:"h-3 w-3"})})]},j._id))})]}),u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[u.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:je.length===0?u.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&u.jsx("div",{className:"mb-6",children:o}),u.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),Xe.length>0&&u.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:u.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(Ht?Xe:Xe.slice(0,10)).map(j=>u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx(hs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{qt(j.sampleUsage),Ye.current?.focus()},children:j.friendlyName})}),u.jsx(Qe,{children:u.jsxs("div",{className:"max-w-xs",children:[u.jsx("p",{className:"font-medium",children:j.description}),u.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[u.jsx("span",{className:"font-medium",children:"Example:"}),' "',j.sampleUsage,'"']}),j.paramCount>0&&u.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[u.jsx("span",{className:"font-medium",children:"Parameters:"})," ",j.params.join(", ")]})]})})]},j.name)),Xe.length>10&&!Ht&&u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsxs(hs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>kn(!0),children:["+",Xe.length-10," more"]})}),u.jsx(Qe,{children:u.jsxs("div",{className:"max-w-xs",children:[u.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),u.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:Xe.slice(10).map(j=>u.jsxs("div",{children:[u.jsxs("span",{className:"font-medium text-xs",children:[j.friendlyName,":"]}),u.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:j.description})]},j.name))}),u.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),Ht&&Xe.length>10&&u.jsx(hs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>kn(!1),children:"Show less"})]})})]}):u.jsxs(u.Fragment,{children:[je.map(j=>{const y=j.parts.filter(k=>k.type==="text").map(k=>k.text).join("");let x=j.parts;j.role==="assistant"&&j.parts.some(G=>G.timestamp)&&(x=[...j.parts].sort((G,$)=>{const W=G.timestamp||0,K=$.timestamp||0;return W-K}));let b=[],T=new Map,N=[],O,_=!0;if(j.role==="assistant"){const k=x.filter(K=>K.type==="text"&&K.text),G=[],$=[];k.forEach(K=>{const{citations:ge,citationMap:ae,groupedCitations:ye,referencesText:Pe}=oo(K.text);b.push(...ge),G.push(ae),ye&&$.push(...ye),Pe&&(O=Pe)}),G.forEach(K=>{K.forEach((ge,ae)=>{T.has(ae)||T.set(ae,ge)})}),N=Array.from(new Map($.map(K=>[K.url,K])).values()).sort((K,ge)=>(K.numbers[0]||0)-(ge.numbers[0]||0)),_=!(de==="streaming"&&j.id===je.at(-1)?.id)}return u.jsx("div",{className:`${j.role==="user"?"flex justify-end":"w-full"}`,children:u.jsx("div",{className:`${j.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:j.role==="user"?u.jsx(Tf,{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:y}):u.jsx("div",{className:"space-y-2",children:x.map((k,G)=>{if(k.type?.startsWith("tool-")){const $=k.type?.replace("tool-","")||"",W=ue.find(ae=>ae.name===$),K=k.state==="input-available",ge=k.state==="output-available";if(K&&Fe.has($),K){if(Fe.has($))return null;const ae=Ms(k.input);return u.jsx(Ln,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:u.jsx(Cf,{toolName:$,description:W?.description||"",args:ae,onApprove:async()=>{if(Tt.has(k.toolCallId))return;_e(Pe=>new Set(Pe).add(k.toolCallId));const ye=Re.get($);if(ye)try{const Pe=await ye(...Object.values(ae));ve({toolCallId:k.toolCallId,tool:$,output:Pe})}catch(Pe){ve({toolCallId:k.toolCallId,tool:$,output:`Error: ${Pe}`})}},onDeny:async()=>{Tt.has(k.toolCallId)||(_e(ye=>new Set(ye).add(k.toolCallId)),ve({toolCallId:k.toolCallId,tool:$,output:"User denied tool execution"}))}})},`${k.toolCallId}-${G}`)}else if(ge){const ae=k.output==="User denied tool execution",ye=Ms(k.input);return u.jsx(jf,{toolName:$,args:ye,isDenied:ae,isSafe:Fe.has($)},`${k.toolCallId}-${G}`)}return null}if(k.type==="text"&&k.text&&ot){const{processedText:$}=oo(k.text),ae=!x.slice(G+1).some(ye=>ye.type==="text"&&ye.text)&&_&&T.size>0;return u.jsx(Lf,{text:$,citations:b,citationMap:T,groupedCitations:ae?N:void 0,referencesText:ae?O:void 0,ResponseComponent:ot,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:D,showReferences:ae},`${j.id}-${G}`)}return k.type==="reasoning"&&k.text?u.jsxs(Ya,{className:"w-full",isStreaming:de==="streaming"&&G===j.parts.length-1&&j.id===je.at(-1)?.id,children:[u.jsx(Ja,{}),u.jsx(Za,{children:k.text})]},`${j.id}-${G}`):null})})})},j.id)}),u.jsx("div",{ref:wt})]})}),Yt&&u.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Yt.message]}),u.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[u.jsx(_u,{mode:"wait",children:(de==="streaming"||de==="submitted")&&u.jsxs(Ln,{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:[u.jsx(Ln,{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]}}),u.jsx("p",{className:"text-xs text-muted-foreground",children:Gt})]})}),u.jsxs("form",{onSubmit:Rn,className:"relative",children:[u.jsx(mo,{ref:Ye,value:it,onChange:Te,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),Rn(j))}}),de==="streaming"||de==="submitted"?u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx("button",{type:"button",className:Z(ht({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:ut,children:u.jsx(J.Square,{className:"h-4 w-4"})})}),u.jsxs(Qe,{children:[u.jsx(_r,{children:"Escape"})," to stop"]})]}):u.jsxs(Je,{children:[u.jsx(Ze,{asChild:!0,children:u.jsx("button",{type:"submit",className:Z(ht({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!it.trim(),children:u.jsx(J.ArrowRight,{className:"h-4 w-4"})})}),u.jsxs(Qe,{children:[u.jsx(_r,{children:"Enter"})," to send"]})]})]})]})]}),u.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:[u.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),u.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),u.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):u.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[u.jsx(J.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),u.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):u.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:u.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function Hf(e){return u.jsx(tl,{children:u.jsx(Gf,{...e})})}function Yf(e={}){const{apiBaseUrl:t="https://api.arcten.com",tokenEndpoint:n="/token",clientToken:s,skipTokenFetch:r=!1}=e,[o,i]=f.useState(!1),[a,l]=f.useState(null),c=f.useRef(s||null);f.useEffect(()=>{if(s){c.current=s;return}if(r)return;(async()=>{try{const p=await fetch(`${t}${n}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(p.ok){const v=await p.json();c.current=v.token}}catch(p){console.error("[useGenerate] Failed to fetch token:",p)}})()},[t,n,s,r]);const d=f.useCallback(async m=>{i(!0),l(null);try{const p={"Content-Type":"application/json"};c.current&&(p.Authorization=`Bearer ${c.current}`);const v=await fetch(`${t}/generate`,{method:"POST",headers:p,body:JSON.stringify(m)});if(!v.ok){const C=await v.json().catch(()=>({}));throw new Error(C.error||`HTTP ${v.status}`)}return await v.json()}catch(p){const v=p instanceof Error?p.message:String(p);throw l(v),p}finally{i(!1)}},[t]),h=f.useCallback(async(m,p)=>{i(!0),l(null);try{const v={"Content-Type":"application/json"};c.current&&(v.Authorization=`Bearer ${c.current}`);const w=await fetch(`${t}/generate/stream`,{method:"POST",headers:v,body:JSON.stringify(m)});if(!w.ok){const A=await w.json().catch(()=>({}));throw new Error(A.error||`HTTP ${w.status}`)}const C=w.body?.getReader();if(!C)throw new Error("No response body");const S=new TextDecoder;let M=null;for(;;){const{done:A,value:U}=await C.read();if(A)break;const z=S.decode(U,{stream:!0}).split(`
16
+ `).filter(F=>F.startsWith("data: "));for(const F of z){const E=F.slice(6).trim();if(E)try{const D=JSON.parse(E);if(D.error)throw new Error(D.error);D.done&&D.object?M={object:D.object,usage:D.usage,finishReason:D.finishReason}:D.partial&&p&&p(D.partial)}catch{}}}if(!M)throw new Error("Stream ended without final result");return M}catch(v){const w=v instanceof Error?v.message:String(v);throw l(w),v}finally{i(!1)}},[t]);return{generate:d,streamGenerate:h,isLoading:o,error:a}}exports.ARCTEN_ORIGINAL_NAME=Me;exports.ArctenAgent=Hf;exports.SecureModalProvider=tl;exports.extractToolsMetadata=tr;exports.preserveToolName=xl;exports.useAgent=fo;exports.useGenerate=Yf;exports.useSecureModal=el;