(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))a(l);new MutationObserver(l=>{for(const c of l)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&a(u)}).observe(document,{childList:!0,subtree:!0});function i(l){const c={};return l.integrity&&(c.integrity=l.integrity),l.referrerPolicy&&(c.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?c.credentials="include":l.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function a(l){if(l.ep)return;l.ep=!0;const c=i(l);fetch(l.href,c)}})();var Qh={exports:{}},Ur={};/** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Fy;function XS(){if(Fy)return Ur;Fy=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function i(a,l,c){var u=null;if(c!==void 0&&(u=""+c),l.key!==void 0&&(u=""+l.key),"key"in l){c={};for(var d in l)d!=="key"&&(c[d]=l[d])}else c=l;return l=c.ref,{$$typeof:n,type:a,key:u,ref:l!==void 0?l:null,props:c}}return Ur.Fragment=e,Ur.jsx=i,Ur.jsxs=i,Ur}var Gy;function JS(){return Gy||(Gy=1,Qh.exports=XS()),Qh.exports}var g=JS(),Zh={exports:{}},ye={};/** * @license React * react.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Ky;function QS(){if(Ky)return ye;Ky=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),l=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),u=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),v=Symbol.for("react.activity"),x=Symbol.iterator;function _(A){return A===null||typeof A!="object"?null:(A=x&&A[x]||A["@@iterator"],typeof A=="function"?A:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,R={};function N(A,H,J){this.props=A,this.context=H,this.refs=R,this.updater=J||S}N.prototype.isReactComponent={},N.prototype.setState=function(A,H){if(typeof A!="object"&&typeof A!="function"&&A!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,A,H,"setState")},N.prototype.forceUpdate=function(A){this.updater.enqueueForceUpdate(this,A,"forceUpdate")};function O(){}O.prototype=N.prototype;function C(A,H,J){this.props=A,this.context=H,this.refs=R,this.updater=J||S}var P=C.prototype=new O;P.constructor=C,E(P,N.prototype),P.isPureReactComponent=!0;var Y=Array.isArray;function X(){}var q={H:null,A:null,T:null,S:null},Z=Object.prototype.hasOwnProperty;function te(A,H,J){var W=J.ref;return{$$typeof:n,type:A,key:H,ref:W!==void 0?W:null,props:J}}function Q(A,H){return te(A.type,H,A.props)}function le(A){return typeof A=="object"&&A!==null&&A.$$typeof===n}function he(A){var H={"=":"=0",":":"=2"};return"$"+A.replace(/[=:]/g,function(J){return H[J]})}var Ge=/\/+/g;function Ne(A,H){return typeof A=="object"&&A!==null&&A.key!=null?he(""+A.key):H.toString(36)}function xe(A){switch(A.status){case"fulfilled":return A.value;case"rejected":throw A.reason;default:switch(typeof A.status=="string"?A.then(X,X):(A.status="pending",A.then(function(H){A.status==="pending"&&(A.status="fulfilled",A.value=H)},function(H){A.status==="pending"&&(A.status="rejected",A.reason=H)})),A.status){case"fulfilled":return A.value;case"rejected":throw A.reason}}throw A}function z(A,H,J,W,fe){var ge=typeof A;(ge==="undefined"||ge==="boolean")&&(A=null);var Ee=!1;if(A===null)Ee=!0;else switch(ge){case"bigint":case"string":case"number":Ee=!0;break;case"object":switch(A.$$typeof){case n:case e:Ee=!0;break;case y:return Ee=A._init,z(Ee(A._payload),H,J,W,fe)}}if(Ee)return fe=fe(A),Ee=W===""?"."+Ne(A,0):W,Y(fe)?(J="",Ee!=null&&(J=Ee.replace(Ge,"$&/")+"/"),z(fe,H,J,"",function(Pt){return Pt})):fe!=null&&(le(fe)&&(fe=Q(fe,J+(fe.key==null||A&&A.key===fe.key?"":(""+fe.key).replace(Ge,"$&/")+"/")+Ee)),H.push(fe)),1;Ee=0;var Ye=W===""?".":W+":";if(Y(A))for(var Le=0;Le>>1,ue=z[ie];if(0>>1;iel(J,K))Wl(fe,J)?(z[ie]=fe,z[W]=K,ie=W):(z[ie]=J,z[H]=K,ie=H);else if(Wl(fe,K))z[ie]=fe,z[W]=K,ie=W;else break e}}return G}function l(z,G){var K=z.sortIndex-G.sortIndex;return K!==0?K:z.id-G.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;n.unstable_now=function(){return c.now()}}else{var u=Date,d=u.now();n.unstable_now=function(){return u.now()-d}}var m=[],p=[],y=1,v=null,x=3,_=!1,S=!1,E=!1,R=!1,N=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,C=typeof setImmediate<"u"?setImmediate:null;function P(z){for(var G=i(p);G!==null;){if(G.callback===null)a(p);else if(G.startTime<=z)a(p),G.sortIndex=G.expirationTime,e(m,G);else break;G=i(p)}}function Y(z){if(E=!1,P(z),!S)if(i(m)!==null)S=!0,X||(X=!0,he());else{var G=i(p);G!==null&&xe(Y,G.startTime-z)}}var X=!1,q=-1,Z=5,te=-1;function Q(){return R?!0:!(n.unstable_now()-tez&&Q());){var ie=v.callback;if(typeof ie=="function"){v.callback=null,x=v.priorityLevel;var ue=ie(v.expirationTime<=z);if(z=n.unstable_now(),typeof ue=="function"){v.callback=ue,P(z),G=!0;break t}v===i(m)&&a(m),P(z)}else a(m);v=i(m)}if(v!==null)G=!0;else{var A=i(p);A!==null&&xe(Y,A.startTime-z),G=!1}}break e}finally{v=null,x=K,_=!1}G=void 0}}finally{G?he():X=!1}}}var he;if(typeof C=="function")he=function(){C(le)};else if(typeof MessageChannel<"u"){var Ge=new MessageChannel,Ne=Ge.port2;Ge.port1.onmessage=le,he=function(){Ne.postMessage(null)}}else he=function(){N(le,0)};function xe(z,G){q=N(function(){z(n.unstable_now())},G)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(z){z.callback=null},n.unstable_forceFrameRate=function(z){0>z||125ie?(z.sortIndex=K,e(p,z),i(m)===null&&z===i(p)&&(E?(O(q),q=-1):E=!0,xe(Y,K-ie))):(z.sortIndex=ue,e(m,z),S||_||(S=!0,X||(X=!0,he()))),z},n.unstable_shouldYield=Q,n.unstable_wrapCallback=function(z){var G=x;return function(){var K=x;x=G;try{return z.apply(this,arguments)}finally{x=K}}}})(td)),td}var Jy;function WS(){return Jy||(Jy=1,ed.exports=ZS()),ed.exports}var nd={exports:{}},Dt={};/** * @license React * react-dom.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Qy;function e1(){if(Qy)return Dt;Qy=1;var n=vf();function e(m){var p="https://react.dev/errors/"+m;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),nd.exports=e1(),nd.exports}/** * @license React * react-dom-client.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Wy;function n1(){if(Wy)return Lr;Wy=1;var n=WS(),e=vf(),i=t1();function a(t){var s="https://react.dev/errors/"+t;if(1ue||(t.current=ie[ue],ie[ue]=null,ue--)}function J(t,s){ue++,ie[ue]=t.current,t.current=s}var W=A(null),fe=A(null),ge=A(null),Ee=A(null);function Ye(t,s){switch(J(ge,s),J(fe,t),J(W,null),s.nodeType){case 9:case 11:t=(t=s.documentElement)&&(t=t.namespaceURI)?my(t):0;break;default:if(t=s.tagName,s=s.namespaceURI)s=my(s),t=py(s,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}H(W),J(W,t)}function Le(){H(W),H(fe),H(ge)}function Pt(t){t.memoizedState!==null&&J(Ee,t);var s=W.current,r=py(s,t.type);s!==r&&(J(fe,t),J(W,r))}function Qt(t){fe.current===t&&(H(W),H(fe)),Ee.current===t&&(H(Ee),Or._currentValue=K)}var ii,Zt;function ee(t){if(ii===void 0)try{throw Error()}catch(r){var s=r.stack.trim().match(/\n( *(at )?)/);ii=s&&s[1]||"",Zt=-1)":-1h||T[o]!==U[h]){var $=` `+T[o].replace(" at new "," at ");return t.displayName&&$.includes("")&&($=$.replace("",t.displayName)),$}while(1<=o&&0<=h);break}}}finally{Ce=!1,Error.prepareStackTrace=r}return(r=t?t.displayName||t.name:"")?ee(r):""}function Me(t,s){switch(t.tag){case 26:case 27:case 5:return ee(t.type);case 16:return ee("Lazy");case 13:return t.child!==s&&s!==null?ee("Suspense Fallback"):ee("Suspense");case 19:return ee("SuspenseList");case 0:case 15:return _e(t.type,!1);case 11:return _e(t.type.render,!1);case 1:return _e(t.type,!0);case 31:return ee("Activity");default:return""}}function st(t){try{var s="",r=null;do s+=Me(t,r),r=t,t=t.return;while(t);return s}catch(o){return` Error generating stack: `+o.message+` `+o.stack}}var Ht=Object.prototype.hasOwnProperty,qt=n.unstable_scheduleCallback,ct=n.unstable_cancelCallback,zn=n.unstable_shouldYield,Bt=n.unstable_requestPaint,ut=n.unstable_now,Di=n.unstable_getCurrentPriorityLevel,Xe=n.unstable_ImmediatePriority,dn=n.unstable_UserBlockingPriority,Wt=n.unstable_NormalPriority,An=n.unstable_LowPriority,Mi=n.unstable_IdlePriority,Bi=n.log,Ga=n.unstable_setDisableYieldValue,ai=null,Ot=null;function Vn(t){if(typeof Bi=="function"&&Ga(t),Ot&&typeof Ot.setStrictMode=="function")try{Ot.setStrictMode(ai,t)}catch{}}var Ut=Math.clz32?Math.clz32:Hc,_o=Math.log,Pc=Math.LN2;function Hc(t){return t>>>=0,t===0?32:31-(_o(t)/Pc|0)|0}var Ui=256,Li=262144,zi=4194304;function es(t){var s=t&42;if(s!==0)return s;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function D(t,s,r){var o=t.pendingLanes;if(o===0)return 0;var h=0,f=t.suspendedLanes,b=t.pingedLanes;t=t.warmLanes;var w=o&134217727;return w!==0?(o=w&~f,o!==0?h=es(o):(b&=w,b!==0?h=es(b):r||(r=w&~t,r!==0&&(h=es(r))))):(w=o&~f,w!==0?h=es(w):b!==0?h=es(b):r||(r=o&~t,r!==0&&(h=es(r)))),h===0?0:s!==0&&s!==h&&(s&f)===0&&(f=h&-h,r=s&-s,f>=r||f===32&&(r&4194048)!==0)?s:h}function ne(t,s){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&s)===0}function we(t,s){switch(t){case 1:case 2:case 4:case 8:case 64:return s+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return s+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ts(){var t=zi;return zi<<=1,(zi&62914560)===0&&(zi=4194304),t}function ns(t){for(var s=[],r=0;31>r;r++)s.push(t);return s}function bt(t,s){t.pendingLanes|=s,s!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function en(t,s,r,o,h,f){var b=t.pendingLanes;t.pendingLanes=r,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=r,t.entangledLanes&=r,t.errorRecoveryDisabledLanes&=r,t.shellSuspendCounter=0;var w=t.entanglements,T=t.expirationTimes,U=t.hiddenUpdates;for(r=b&~r;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var $w=/[\n"\\]/g;function mn(t){return t.replace($w,function(s){return"\\"+s.charCodeAt(0).toString(16)+" "})}function Fc(t,s,r,o,h,f,b,w){t.name="",b!=null&&typeof b!="function"&&typeof b!="symbol"&&typeof b!="boolean"?t.type=b:t.removeAttribute("type"),s!=null?b==="number"?(s===0&&t.value===""||t.value!=s)&&(t.value=""+fn(s)):t.value!==""+fn(s)&&(t.value=""+fn(s)):b!=="submit"&&b!=="reset"||t.removeAttribute("value"),s!=null?Gc(t,b,fn(s)):r!=null?Gc(t,b,fn(r)):o!=null&&t.removeAttribute("value"),h==null&&f!=null&&(t.defaultChecked=!!f),h!=null&&(t.checked=h&&typeof h!="function"&&typeof h!="symbol"),w!=null&&typeof w!="function"&&typeof w!="symbol"&&typeof w!="boolean"?t.name=""+fn(w):t.removeAttribute("name")}function lm(t,s,r,o,h,f,b,w){if(f!=null&&typeof f!="function"&&typeof f!="symbol"&&typeof f!="boolean"&&(t.type=f),s!=null||r!=null){if(!(f!=="submit"&&f!=="reset"||s!=null)){Ic(t);return}r=r!=null?""+fn(r):"",s=s!=null?""+fn(s):r,w||s===t.value||(t.value=s),t.defaultValue=s}o=o??h,o=typeof o!="function"&&typeof o!="symbol"&&!!o,t.checked=w?t.checked:!!o,t.defaultChecked=!!o,b!=null&&typeof b!="function"&&typeof b!="symbol"&&typeof b!="boolean"&&(t.name=b),Ic(t)}function Gc(t,s,r){s==="number"&&Ao(t.ownerDocument)===t||t.defaultValue===""+r||(t.defaultValue=""+r)}function Ii(t,s,r,o){if(t=t.options,s){s={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Qc=!1;if(as)try{var Ja={};Object.defineProperty(Ja,"passive",{get:function(){Qc=!0}}),window.addEventListener("test",Ja,Ja),window.removeEventListener("test",Ja,Ja)}catch{Qc=!1}var js=null,Zc=null,Co=null;function pm(){if(Co)return Co;var t,s=Zc,r=s.length,o,h="value"in js?js.value:js.textContent,f=h.length;for(t=0;t=Wa),wm=" ",_m=!1;function Sm(t,s){switch(t){case"keyup":return y_.indexOf(s.keyCode)!==-1;case"keydown":return s.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Tm(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Yi=!1;function v_(t,s){switch(t){case"compositionend":return Tm(s);case"keypress":return s.which!==32?null:(_m=!0,wm);case"textInput":return t=s.data,t===wm&&_m?null:t;default:return null}}function x_(t,s){if(Yi)return t==="compositionend"||!su&&Sm(t,s)?(t=pm(),Co=Zc=js=null,Yi=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(s.ctrlKey||s.altKey||s.metaKey)||s.ctrlKey&&s.altKey){if(s.char&&1=s)return{node:r,offset:s-t};t=o}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Om(r)}}function Mm(t,s){return t&&s?t===s?!0:t&&t.nodeType===3?!1:s&&s.nodeType===3?Mm(t,s.parentNode):"contains"in t?t.contains(s):t.compareDocumentPosition?!!(t.compareDocumentPosition(s)&16):!1:!1}function Bm(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var s=Ao(t.document);s instanceof t.HTMLIFrameElement;){try{var r=typeof s.contentWindow.location.href=="string"}catch{r=!1}if(r)t=s.contentWindow;else break;s=Ao(t.document)}return s}function ru(t){var s=t&&t.nodeName&&t.nodeName.toLowerCase();return s&&(s==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||s==="textarea"||t.contentEditable==="true")}var C_=as&&"documentMode"in document&&11>=document.documentMode,Xi=null,ou=null,sr=null,lu=!1;function Um(t,s,r){var o=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;lu||Xi==null||Xi!==Ao(o)||(o=Xi,"selectionStart"in o&&ru(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),sr&&nr(sr,o)||(sr=o,o=wl(ou,"onSelect"),0>=b,h-=b,Hn=1<<32-Ut(s)+h|r<ve?(je=ce,ce=null):je=ce.sibling;var De=L(k,ce,B[ve],I);if(De===null){ce===null&&(ce=je);break}t&&ce&&De.alternate===null&&s(k,ce),j=f(De,j,ve),Oe===null?de=De:Oe.sibling=De,Oe=De,ce=je}if(ve===B.length)return r(k,ce),Re&&os(k,ve),de;if(ce===null){for(;veve?(je=ce,ce=null):je=ce.sibling;var Xs=L(k,ce,De.value,I);if(Xs===null){ce===null&&(ce=je);break}t&&ce&&Xs.alternate===null&&s(k,ce),j=f(Xs,j,ve),Oe===null?de=Xs:Oe.sibling=Xs,Oe=Xs,ce=je}if(De.done)return r(k,ce),Re&&os(k,ve),de;if(ce===null){for(;!De.done;ve++,De=B.next())De=F(k,De.value,I),De!==null&&(j=f(De,j,ve),Oe===null?de=De:Oe.sibling=De,Oe=De);return Re&&os(k,ve),de}for(ce=o(ce);!De.done;ve++,De=B.next())De=V(ce,k,ve,De.value,I),De!==null&&(t&&De.alternate!==null&&ce.delete(De.key===null?ve:De.key),j=f(De,j,ve),Oe===null?de=De:Oe.sibling=De,Oe=De);return t&&ce.forEach(function(YS){return s(k,YS)}),Re&&os(k,ve),de}function qe(k,j,B,I){if(typeof B=="object"&&B!==null&&B.type===E&&B.key===null&&(B=B.props.children),typeof B=="object"&&B!==null){switch(B.$$typeof){case _:e:{for(var de=B.key;j!==null;){if(j.key===de){if(de=B.type,de===E){if(j.tag===7){r(k,j.sibling),I=h(j,B.props.children),I.return=k,k=I;break e}}else if(j.elementType===de||typeof de=="object"&&de!==null&&de.$$typeof===Z&&gi(de)===j.type){r(k,j.sibling),I=h(j,B.props),cr(I,B),I.return=k,k=I;break e}r(k,j);break}else s(k,j);j=j.sibling}B.type===E?(I=hi(B.props.children,k.mode,I,B.key),I.return=k,k=I):(I=zo(B.type,B.key,B.props,null,k.mode,I),cr(I,B),I.return=k,k=I)}return b(k);case S:e:{for(de=B.key;j!==null;){if(j.key===de)if(j.tag===4&&j.stateNode.containerInfo===B.containerInfo&&j.stateNode.implementation===B.implementation){r(k,j.sibling),I=h(j,B.children||[]),I.return=k,k=I;break e}else{r(k,j);break}else s(k,j);j=j.sibling}I=pu(B,k.mode,I),I.return=k,k=I}return b(k);case Z:return B=gi(B),qe(k,j,B,I)}if(xe(B))return ae(k,j,B,I);if(he(B)){if(de=he(B),typeof de!="function")throw Error(a(150));return B=de.call(B),pe(k,j,B,I)}if(typeof B.then=="function")return qe(k,j,Fo(B),I);if(B.$$typeof===C)return qe(k,j,Ho(k,B),I);Go(k,B)}return typeof B=="string"&&B!==""||typeof B=="number"||typeof B=="bigint"?(B=""+B,j!==null&&j.tag===6?(r(k,j.sibling),I=h(j,B),I.return=k,k=I):(r(k,j),I=mu(B,k.mode,I),I.return=k,k=I),b(k)):r(k,j)}return function(k,j,B,I){try{lr=0;var de=qe(k,j,B,I);return ra=null,de}catch(ce){if(ce===aa||ce===$o)throw ce;var Oe=nn(29,ce,null,k.mode);return Oe.lanes=I,Oe.return=k,Oe}finally{}}}var bi=ap(!0),rp=ap(!1),Os=!1;function ju(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Cu(t,s){t=t.updateQueue,s.updateQueue===t&&(s.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function Ds(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function Ms(t,s,r){var o=t.updateQueue;if(o===null)return null;if(o=o.shared,(Be&2)!==0){var h=o.pending;return h===null?s.next=s:(s.next=h.next,h.next=s),o.pending=s,s=Lo(t),$m(t,null,r),s}return Uo(t,o,s,r),Lo(t)}function ur(t,s,r){if(s=s.updateQueue,s!==null&&(s=s.shared,(r&4194048)!==0)){var o=s.lanes;o&=t.pendingLanes,r|=o,s.lanes=r,ht(t,r)}}function Ru(t,s){var r=t.updateQueue,o=t.alternate;if(o!==null&&(o=o.updateQueue,r===o)){var h=null,f=null;if(r=r.firstBaseUpdate,r!==null){do{var b={lane:r.lane,tag:r.tag,payload:r.payload,callback:null,next:null};f===null?h=f=b:f=f.next=b,r=r.next}while(r!==null);f===null?h=f=s:f=f.next=s}else h=f=s;r={baseState:o.baseState,firstBaseUpdate:h,lastBaseUpdate:f,shared:o.shared,callbacks:o.callbacks},t.updateQueue=r;return}t=r.lastBaseUpdate,t===null?r.firstBaseUpdate=s:t.next=s,r.lastBaseUpdate=s}var Nu=!1;function hr(){if(Nu){var t=ia;if(t!==null)throw t}}function dr(t,s,r,o){Nu=!1;var h=t.updateQueue;Os=!1;var f=h.firstBaseUpdate,b=h.lastBaseUpdate,w=h.shared.pending;if(w!==null){h.shared.pending=null;var T=w,U=T.next;T.next=null,b===null?f=U:b.next=U,b=T;var $=t.alternate;$!==null&&($=$.updateQueue,w=$.lastBaseUpdate,w!==b&&(w===null?$.firstBaseUpdate=U:w.next=U,$.lastBaseUpdate=T))}if(f!==null){var F=h.baseState;b=0,$=U=T=null,w=f;do{var L=w.lane&-536870913,V=L!==w.lane;if(V?(Ae&L)===L:(o&L)===L){L!==0&&L===sa&&(Nu=!0),$!==null&&($=$.next={lane:0,tag:w.tag,payload:w.payload,callback:null,next:null});e:{var ae=t,pe=w;L=s;var qe=r;switch(pe.tag){case 1:if(ae=pe.payload,typeof ae=="function"){F=ae.call(qe,F,L);break e}F=ae;break e;case 3:ae.flags=ae.flags&-65537|128;case 0:if(ae=pe.payload,L=typeof ae=="function"?ae.call(qe,F,L):ae,L==null)break e;F=v({},F,L);break e;case 2:Os=!0}}L=w.callback,L!==null&&(t.flags|=64,V&&(t.flags|=8192),V=h.callbacks,V===null?h.callbacks=[L]:V.push(L))}else V={lane:L,tag:w.tag,payload:w.payload,callback:w.callback,next:null},$===null?(U=$=V,T=F):$=$.next=V,b|=L;if(w=w.next,w===null){if(w=h.shared.pending,w===null)break;V=w,w=V.next,V.next=null,h.lastBaseUpdate=V,h.shared.pending=null}}while(!0);$===null&&(T=F),h.baseState=T,h.firstBaseUpdate=U,h.lastBaseUpdate=$,f===null&&(h.shared.lanes=0),Vs|=b,t.lanes=b,t.memoizedState=F}}function op(t,s){if(typeof t!="function")throw Error(a(191,t));t.call(s)}function lp(t,s){var r=t.callbacks;if(r!==null)for(t.callbacks=null,t=0;tf?f:8;var b=z.T,w={};z.T=w,Xu(t,!1,s,r);try{var T=h(),U=z.S;if(U!==null&&U(w,T),T!==null&&typeof T=="object"&&typeof T.then=="function"){var $=L_(T,o);pr(t,s,$,ln(t))}else pr(t,s,o,ln(t))}catch(F){pr(t,s,{then:function(){},status:"rejected",reason:F},ln())}finally{G.p=f,b!==null&&w.types!==null&&(b.types=w.types),z.T=b}}function $_(){}function Ku(t,s,r,o){if(t.tag!==5)throw Error(a(476));var h=Pp(t).queue;Vp(t,h,s,K,r===null?$_:function(){return Hp(t),r(o)})}function Pp(t){var s=t.memoizedState;if(s!==null)return s;s={memoizedState:K,baseState:K,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:hs,lastRenderedState:K},next:null};var r={};return s.next={memoizedState:r,baseState:r,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:hs,lastRenderedState:r},next:null},t.memoizedState=s,t=t.alternate,t!==null&&(t.memoizedState=s),s}function Hp(t){var s=Pp(t);s.next===null&&(s=t.alternate.memoizedState),pr(t,s.next.queue,{},ln())}function Yu(){return jt(Or)}function qp(){return rt().memoizedState}function $p(){return rt().memoizedState}function I_(t){for(var s=t.return;s!==null;){switch(s.tag){case 24:case 3:var r=ln();t=Ds(r);var o=Ms(s,t,r);o!==null&&(Xt(o,s,r),ur(o,s,r)),s={cache:Su()},t.payload=s;return}s=s.return}}function F_(t,s,r){var o=ln();r={lane:o,revertLane:0,gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},nl(t)?Fp(s,r):(r=du(t,s,r,o),r!==null&&(Xt(r,t,o),Gp(r,s,o)))}function Ip(t,s,r){var o=ln();pr(t,s,r,o)}function pr(t,s,r,o){var h={lane:o,revertLane:0,gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null};if(nl(t))Fp(s,h);else{var f=t.alternate;if(t.lanes===0&&(f===null||f.lanes===0)&&(f=s.lastRenderedReducer,f!==null))try{var b=s.lastRenderedState,w=f(b,r);if(h.hasEagerState=!0,h.eagerState=w,tn(w,b))return Uo(t,s,h,0),$e===null&&Bo(),!1}catch{}finally{}if(r=du(t,s,h,o),r!==null)return Xt(r,t,o),Gp(r,s,o),!0}return!1}function Xu(t,s,r,o){if(o={lane:2,revertLane:jh(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},nl(t)){if(s)throw Error(a(479))}else s=du(t,r,o,2),s!==null&&Xt(s,t,2)}function nl(t){var s=t.alternate;return t===be||s!==null&&s===be}function Fp(t,s){la=Xo=!0;var r=t.pending;r===null?s.next=s:(s.next=r.next,r.next=s),t.pending=s}function Gp(t,s,r){if((r&4194048)!==0){var o=s.lanes;o&=t.pendingLanes,r|=o,s.lanes=r,ht(t,r)}}var gr={readContext:jt,use:Zo,useCallback:We,useContext:We,useEffect:We,useImperativeHandle:We,useLayoutEffect:We,useInsertionEffect:We,useMemo:We,useReducer:We,useRef:We,useState:We,useDebugValue:We,useDeferredValue:We,useTransition:We,useSyncExternalStore:We,useId:We,useHostTransitionStatus:We,useFormState:We,useActionState:We,useOptimistic:We,useMemoCache:We,useCacheRefresh:We};gr.useEffectEvent=We;var Kp={readContext:jt,use:Zo,useCallback:function(t,s){return Lt().memoizedState=[t,s===void 0?null:s],t},useContext:jt,useEffect:Np,useImperativeHandle:function(t,s,r){r=r!=null?r.concat([t]):null,el(4194308,4,Mp.bind(null,s,t),r)},useLayoutEffect:function(t,s){return el(4194308,4,t,s)},useInsertionEffect:function(t,s){el(4,2,t,s)},useMemo:function(t,s){var r=Lt();s=s===void 0?null:s;var o=t();if(vi){Vn(!0);try{t()}finally{Vn(!1)}}return r.memoizedState=[o,s],o},useReducer:function(t,s,r){var o=Lt();if(r!==void 0){var h=r(s);if(vi){Vn(!0);try{r(s)}finally{Vn(!1)}}}else h=s;return o.memoizedState=o.baseState=h,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:h},o.queue=t,t=t.dispatch=F_.bind(null,be,t),[o.memoizedState,t]},useRef:function(t){var s=Lt();return t={current:t},s.memoizedState=t},useState:function(t){t=qu(t);var s=t.queue,r=Ip.bind(null,be,s);return s.dispatch=r,[t.memoizedState,r]},useDebugValue:Fu,useDeferredValue:function(t,s){var r=Lt();return Gu(r,t,s)},useTransition:function(){var t=qu(!1);return t=Vp.bind(null,be,t.queue,!0,!1),Lt().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,s,r){var o=be,h=Lt();if(Re){if(r===void 0)throw Error(a(407));r=r()}else{if(r=s(),$e===null)throw Error(a(349));(Ae&127)!==0||mp(o,s,r)}h.memoizedState=r;var f={value:r,getSnapshot:s};return h.queue=f,Np(gp.bind(null,o,f,t),[t]),o.flags|=2048,ua(9,{destroy:void 0},pp.bind(null,o,f,r,s),null),r},useId:function(){var t=Lt(),s=$e.identifierPrefix;if(Re){var r=qn,o=Hn;r=(o&~(1<<32-Ut(o)-1)).toString(32)+r,s="_"+s+"R_"+r,r=Jo++,0<\/script>",f=f.removeChild(f.firstChild);break;case"select":f=typeof o.is=="string"?b.createElement("select",{is:o.is}):b.createElement("select"),o.multiple?f.multiple=!0:o.size&&(f.size=o.size);break;default:f=typeof o.is=="string"?b.createElement(h,{is:o.is}):b.createElement(h)}}f[Et]=s,f[$t]=o;e:for(b=s.child;b!==null;){if(b.tag===5||b.tag===6)f.appendChild(b.stateNode);else if(b.tag!==4&&b.tag!==27&&b.child!==null){b.child.return=b,b=b.child;continue}if(b===s)break e;for(;b.sibling===null;){if(b.return===null||b.return===s)break e;b=b.return}b.sibling.return=b.return,b=b.sibling}s.stateNode=f;e:switch(Rt(f,h,o),h){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}o&&fs(s)}}return Qe(s),ch(s,s.type,t===null?null:t.memoizedProps,s.pendingProps,r),null;case 6:if(t&&s.stateNode!=null)t.memoizedProps!==o&&fs(s);else{if(typeof o!="string"&&s.stateNode===null)throw Error(a(166));if(t=ge.current,ta(s)){if(t=s.stateNode,r=s.memoizedProps,o=null,h=At,h!==null)switch(h.tag){case 27:case 5:o=h.memoizedProps}t[Et]=s,t=!!(t.nodeValue===r||o!==null&&o.suppressHydrationWarning===!0||dy(t.nodeValue,r)),t||Ns(s,!0)}else t=_l(t).createTextNode(o),t[Et]=s,s.stateNode=t}return Qe(s),null;case 31:if(r=s.memoizedState,t===null||t.memoizedState!==null){if(o=ta(s),r!==null){if(t===null){if(!o)throw Error(a(318));if(t=s.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(a(557));t[Et]=s}else di(),(s.flags&128)===0&&(s.memoizedState=null),s.flags|=4;Qe(s),t=!1}else r=vu(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=r),t=!0;if(!t)return s.flags&256?(an(s),s):(an(s),null);if((s.flags&128)!==0)throw Error(a(558))}return Qe(s),null;case 13:if(o=s.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(h=ta(s),o!==null&&o.dehydrated!==null){if(t===null){if(!h)throw Error(a(318));if(h=s.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(a(317));h[Et]=s}else di(),(s.flags&128)===0&&(s.memoizedState=null),s.flags|=4;Qe(s),h=!1}else h=vu(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=h),h=!0;if(!h)return s.flags&256?(an(s),s):(an(s),null)}return an(s),(s.flags&128)!==0?(s.lanes=r,s):(r=o!==null,t=t!==null&&t.memoizedState!==null,r&&(o=s.child,h=null,o.alternate!==null&&o.alternate.memoizedState!==null&&o.alternate.memoizedState.cachePool!==null&&(h=o.alternate.memoizedState.cachePool.pool),f=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(f=o.memoizedState.cachePool.pool),f!==h&&(o.flags|=2048)),r!==t&&r&&(s.child.flags|=8192),ol(s,s.updateQueue),Qe(s),null);case 4:return Le(),t===null&&kh(s.stateNode.containerInfo),Qe(s),null;case 10:return cs(s.type),Qe(s),null;case 19:if(H(at),o=s.memoizedState,o===null)return Qe(s),null;if(h=(s.flags&128)!==0,f=o.rendering,f===null)if(h)br(o,!1);else{if(et!==0||t!==null&&(t.flags&128)!==0)for(t=s.child;t!==null;){if(f=Yo(t),f!==null){for(s.flags|=128,br(o,!1),t=f.updateQueue,s.updateQueue=t,ol(s,t),s.subtreeFlags=0,t=r,r=s.child;r!==null;)Im(r,t),r=r.sibling;return J(at,at.current&1|2),Re&&os(s,o.treeForkCount),s.child}t=t.sibling}o.tail!==null&&ut()>dl&&(s.flags|=128,h=!0,br(o,!1),s.lanes=4194304)}else{if(!h)if(t=Yo(f),t!==null){if(s.flags|=128,h=!0,t=t.updateQueue,s.updateQueue=t,ol(s,t),br(o,!0),o.tail===null&&o.tailMode==="hidden"&&!f.alternate&&!Re)return Qe(s),null}else 2*ut()-o.renderingStartTime>dl&&r!==536870912&&(s.flags|=128,h=!0,br(o,!1),s.lanes=4194304);o.isBackwards?(f.sibling=s.child,s.child=f):(t=o.last,t!==null?t.sibling=f:s.child=f,o.last=f)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=ut(),t.sibling=null,r=at.current,J(at,h?r&1|2:r&1),Re&&os(s,o.treeForkCount),t):(Qe(s),null);case 22:case 23:return an(s),Ou(),o=s.memoizedState!==null,t!==null?t.memoizedState!==null!==o&&(s.flags|=8192):o&&(s.flags|=8192),o?(r&536870912)!==0&&(s.flags&128)===0&&(Qe(s),s.subtreeFlags&6&&(s.flags|=8192)):Qe(s),r=s.updateQueue,r!==null&&ol(s,r.retryQueue),r=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),o=null,s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(o=s.memoizedState.cachePool.pool),o!==r&&(s.flags|=2048),t!==null&&H(pi),null;case 24:return r=null,t!==null&&(r=t.memoizedState.cache),s.memoizedState.cache!==r&&(s.flags|=2048),cs(dt),Qe(s),null;case 25:return null;case 30:return null}throw Error(a(156,s.tag))}function J_(t,s){switch(yu(s),s.tag){case 1:return t=s.flags,t&65536?(s.flags=t&-65537|128,s):null;case 3:return cs(dt),Le(),t=s.flags,(t&65536)!==0&&(t&128)===0?(s.flags=t&-65537|128,s):null;case 26:case 27:case 5:return Qt(s),null;case 31:if(s.memoizedState!==null){if(an(s),s.alternate===null)throw Error(a(340));di()}return t=s.flags,t&65536?(s.flags=t&-65537|128,s):null;case 13:if(an(s),t=s.memoizedState,t!==null&&t.dehydrated!==null){if(s.alternate===null)throw Error(a(340));di()}return t=s.flags,t&65536?(s.flags=t&-65537|128,s):null;case 19:return H(at),null;case 4:return Le(),null;case 10:return cs(s.type),null;case 22:case 23:return an(s),Ou(),t!==null&&H(pi),t=s.flags,t&65536?(s.flags=t&-65537|128,s):null;case 24:return cs(dt),null;case 25:return null;default:return null}}function yg(t,s){switch(yu(s),s.tag){case 3:cs(dt),Le();break;case 26:case 27:case 5:Qt(s);break;case 4:Le();break;case 31:s.memoizedState!==null&&an(s);break;case 13:an(s);break;case 19:H(at);break;case 10:cs(s.type);break;case 22:case 23:an(s),Ou(),t!==null&&H(pi);break;case 24:cs(dt)}}function vr(t,s){try{var r=s.updateQueue,o=r!==null?r.lastEffect:null;if(o!==null){var h=o.next;r=h;do{if((r.tag&t)===t){o=void 0;var f=r.create,b=r.inst;o=f(),b.destroy=o}r=r.next}while(r!==h)}}catch(w){Ve(s,s.return,w)}}function Ls(t,s,r){try{var o=s.updateQueue,h=o!==null?o.lastEffect:null;if(h!==null){var f=h.next;o=f;do{if((o.tag&t)===t){var b=o.inst,w=b.destroy;if(w!==void 0){b.destroy=void 0,h=s;var T=r,U=w;try{U()}catch($){Ve(h,T,$)}}}o=o.next}while(o!==f)}}catch($){Ve(s,s.return,$)}}function bg(t){var s=t.updateQueue;if(s!==null){var r=t.stateNode;try{lp(s,r)}catch(o){Ve(t,t.return,o)}}}function vg(t,s,r){r.props=xi(t.type,t.memoizedProps),r.state=t.memoizedState;try{r.componentWillUnmount()}catch(o){Ve(t,s,o)}}function xr(t,s){try{var r=t.ref;if(r!==null){switch(t.tag){case 26:case 27:case 5:var o=t.stateNode;break;case 30:o=t.stateNode;break;default:o=t.stateNode}typeof r=="function"?t.refCleanup=r(o):r.current=o}}catch(h){Ve(t,s,h)}}function $n(t,s){var r=t.ref,o=t.refCleanup;if(r!==null)if(typeof o=="function")try{o()}catch(h){Ve(t,s,h)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof r=="function")try{r(null)}catch(h){Ve(t,s,h)}else r.current=null}function xg(t){var s=t.type,r=t.memoizedProps,o=t.stateNode;try{e:switch(s){case"button":case"input":case"select":case"textarea":r.autoFocus&&o.focus();break e;case"img":r.src?o.src=r.src:r.srcSet&&(o.srcset=r.srcSet)}}catch(h){Ve(t,t.return,h)}}function uh(t,s,r){try{var o=t.stateNode;bS(o,t.type,r,s),o[$t]=s}catch(h){Ve(t,t.return,h)}}function wg(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&Is(t.type)||t.tag===4}function hh(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||wg(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&Is(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function dh(t,s,r){var o=t.tag;if(o===5||o===6)t=t.stateNode,s?(r.nodeType===9?r.body:r.nodeName==="HTML"?r.ownerDocument.body:r).insertBefore(t,s):(s=r.nodeType===9?r.body:r.nodeName==="HTML"?r.ownerDocument.body:r,s.appendChild(t),r=r._reactRootContainer,r!=null||s.onclick!==null||(s.onclick=is));else if(o!==4&&(o===27&&Is(t.type)&&(r=t.stateNode,s=null),t=t.child,t!==null))for(dh(t,s,r),t=t.sibling;t!==null;)dh(t,s,r),t=t.sibling}function ll(t,s,r){var o=t.tag;if(o===5||o===6)t=t.stateNode,s?r.insertBefore(t,s):r.appendChild(t);else if(o!==4&&(o===27&&Is(t.type)&&(r=t.stateNode),t=t.child,t!==null))for(ll(t,s,r),t=t.sibling;t!==null;)ll(t,s,r),t=t.sibling}function _g(t){var s=t.stateNode,r=t.memoizedProps;try{for(var o=t.type,h=s.attributes;h.length;)s.removeAttributeNode(h[0]);Rt(s,o,r),s[Et]=t,s[$t]=r}catch(f){Ve(t,t.return,f)}}var ms=!1,pt=!1,fh=!1,Sg=typeof WeakSet=="function"?WeakSet:Set,St=null;function Q_(t,s){if(t=t.containerInfo,Mh=Rl,t=Bm(t),ru(t)){if("selectionStart"in t)var r={start:t.selectionStart,end:t.selectionEnd};else e:{r=(r=t.ownerDocument)&&r.defaultView||window;var o=r.getSelection&&r.getSelection();if(o&&o.rangeCount!==0){r=o.anchorNode;var h=o.anchorOffset,f=o.focusNode;o=o.focusOffset;try{r.nodeType,f.nodeType}catch{r=null;break e}var b=0,w=-1,T=-1,U=0,$=0,F=t,L=null;t:for(;;){for(var V;F!==r||h!==0&&F.nodeType!==3||(w=b+h),F!==f||o!==0&&F.nodeType!==3||(T=b+o),F.nodeType===3&&(b+=F.nodeValue.length),(V=F.firstChild)!==null;)L=F,F=V;for(;;){if(F===t)break t;if(L===r&&++U===h&&(w=b),L===f&&++$===o&&(T=b),(V=F.nextSibling)!==null)break;F=L,L=F.parentNode}F=V}r=w===-1||T===-1?null:{start:w,end:T}}else r=null}r=r||{start:0,end:0}}else r=null;for(Bh={focusedElem:t,selectionRange:r},Rl=!1,St=s;St!==null;)if(s=St,t=s.child,(s.subtreeFlags&1028)!==0&&t!==null)t.return=s,St=t;else for(;St!==null;){switch(s=St,f=s.alternate,t=s.flags,s.tag){case 0:if((t&4)!==0&&(t=s.updateQueue,t=t!==null?t.events:null,t!==null))for(r=0;r title"))),Rt(f,o,r),f[Et]=t,_t(f),o=f;break e;case"link":var b=Ry("link","href",h).get(o+(r.href||""));if(b){for(var w=0;wqe&&(b=qe,qe=pe,pe=b);var k=Dm(w,pe),j=Dm(w,qe);if(k&&j&&(V.rangeCount!==1||V.anchorNode!==k.node||V.anchorOffset!==k.offset||V.focusNode!==j.node||V.focusOffset!==j.offset)){var B=F.createRange();B.setStart(k.node,k.offset),V.removeAllRanges(),pe>qe?(V.addRange(B),V.extend(j.node,j.offset)):(B.setEnd(j.node,j.offset),V.addRange(B))}}}}for(F=[],V=w;V=V.parentNode;)V.nodeType===1&&F.push({element:V,left:V.scrollLeft,top:V.scrollTop});for(typeof w.focus=="function"&&w.focus(),w=0;wr?32:r,z.T=null,r=xh,xh=null;var f=Hs,b=vs;if(vt=0,pa=Hs=null,vs=0,(Be&6)!==0)throw Error(a(331));var w=Be;if(Be|=4,Mg(f.current),kg(f,f.current,b,r),Be=w,Ar(0,!1),Ot&&typeof Ot.onPostCommitFiberRoot=="function")try{Ot.onPostCommitFiberRoot(ai,f)}catch{}return!0}finally{G.p=h,z.T=o,Zg(t,s)}}function ey(t,s,r){s=gn(r,s),s=Wu(t.stateNode,s,2),t=Ms(t,s,2),t!==null&&(bt(t,2),In(t))}function Ve(t,s,r){if(t.tag===3)ey(t,t,r);else for(;s!==null;){if(s.tag===3){ey(s,t,r);break}else if(s.tag===1){var o=s.stateNode;if(typeof s.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(Ps===null||!Ps.has(o))){t=gn(r,t),r=tg(2),o=Ms(s,r,2),o!==null&&(ng(r,o,s,t),bt(o,2),In(o));break}}s=s.return}}function Th(t,s,r){var o=t.pingCache;if(o===null){o=t.pingCache=new eS;var h=new Set;o.set(s,h)}else h=o.get(s),h===void 0&&(h=new Set,o.set(s,h));h.has(r)||(gh=!0,h.add(r),t=aS.bind(null,t,s,r),s.then(t,t))}function aS(t,s,r){var o=t.pingCache;o!==null&&o.delete(s),t.pingedLanes|=t.suspendedLanes&r,t.warmLanes&=~r,$e===t&&(Ae&r)===r&&(et===4||et===3&&(Ae&62914560)===Ae&&300>ut()-hl?(Be&2)===0&&ga(t,0):yh|=r,ma===Ae&&(ma=0)),In(t)}function ty(t,s){s===0&&(s=ts()),t=ui(t,s),t!==null&&(bt(t,s),In(t))}function rS(t){var s=t.memoizedState,r=0;s!==null&&(r=s.retryLane),ty(t,r)}function oS(t,s){var r=0;switch(t.tag){case 31:case 13:var o=t.stateNode,h=t.memoizedState;h!==null&&(r=h.retryLane);break;case 19:o=t.stateNode;break;case 22:o=t.stateNode._retryCache;break;default:throw Error(a(314))}o!==null&&o.delete(s),ty(t,r)}function lS(t,s){return qt(t,s)}var bl=null,ba=null,Eh=!1,vl=!1,Ah=!1,$s=0;function In(t){t!==ba&&t.next===null&&(ba===null?bl=ba=t:ba=ba.next=t),vl=!0,Eh||(Eh=!0,uS())}function Ar(t,s){if(!Ah&&vl){Ah=!0;do for(var r=!1,o=bl;o!==null;){if(t!==0){var h=o.pendingLanes;if(h===0)var f=0;else{var b=o.suspendedLanes,w=o.pingedLanes;f=(1<<31-Ut(42|t)+1)-1,f&=h&~(b&~w),f=f&201326741?f&201326741|1:f?f|2:0}f!==0&&(r=!0,ay(o,f))}else f=Ae,f=D(o,o===$e?f:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(f&3)===0||ne(o,f)||(r=!0,ay(o,f));o=o.next}while(r);Ah=!1}}function cS(){ny()}function ny(){vl=Eh=!1;var t=0;$s!==0&&xS()&&(t=$s);for(var s=ut(),r=null,o=bl;o!==null;){var h=o.next,f=sy(o,s);f===0?(o.next=null,r===null?bl=h:r.next=h,h===null&&(ba=r)):(r=o,(t!==0||(f&3)!==0)&&(vl=!0)),o=h}vt!==0&&vt!==5||Ar(t),$s!==0&&($s=0)}function sy(t,s){for(var r=t.suspendedLanes,o=t.pingedLanes,h=t.expirationTimes,f=t.pendingLanes&-62914561;0w)break;var $=T.transferSize,F=T.initiatorType;$&&fy(F)&&(T=T.responseEnd,b+=$*(T"u"?null:document;function Ey(t,s,r){var o=va;if(o&&typeof s=="string"&&s){var h=mn(s);h='link[rel="'+t+'"][href="'+h+'"]',typeof r=="string"&&(h+='[crossorigin="'+r+'"]'),Ty.has(h)||(Ty.add(h),t={rel:t,crossOrigin:r,href:s},o.querySelector(h)===null&&(s=o.createElement("link"),Rt(s,"link",t),_t(s),o.head.appendChild(s)))}}function RS(t){xs.D(t),Ey("dns-prefetch",t,null)}function NS(t,s){xs.C(t,s),Ey("preconnect",t,s)}function kS(t,s,r){xs.L(t,s,r);var o=va;if(o&&t&&s){var h='link[rel="preload"][as="'+mn(s)+'"]';s==="image"&&r&&r.imageSrcSet?(h+='[imagesrcset="'+mn(r.imageSrcSet)+'"]',typeof r.imageSizes=="string"&&(h+='[imagesizes="'+mn(r.imageSizes)+'"]')):h+='[href="'+mn(t)+'"]';var f=h;switch(s){case"style":f=xa(t);break;case"script":f=wa(t)}_n.has(f)||(t=v({rel:"preload",href:s==="image"&&r&&r.imageSrcSet?void 0:t,as:s},r),_n.set(f,t),o.querySelector(h)!==null||s==="style"&&o.querySelector(Nr(f))||s==="script"&&o.querySelector(kr(f))||(s=o.createElement("link"),Rt(s,"link",t),_t(s),o.head.appendChild(s)))}}function OS(t,s){xs.m(t,s);var r=va;if(r&&t){var o=s&&typeof s.as=="string"?s.as:"script",h='link[rel="modulepreload"][as="'+mn(o)+'"][href="'+mn(t)+'"]',f=h;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":f=wa(t)}if(!_n.has(f)&&(t=v({rel:"modulepreload",href:t},s),_n.set(f,t),r.querySelector(h)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(r.querySelector(kr(f)))return}o=r.createElement("link"),Rt(o,"link",t),_t(o),r.head.appendChild(o)}}}function DS(t,s,r){xs.S(t,s,r);var o=va;if(o&&t){var h=qi(o).hoistableStyles,f=xa(t);s=s||"default";var b=h.get(f);if(!b){var w={loading:0,preload:null};if(b=o.querySelector(Nr(f)))w.loading=5;else{t=v({rel:"stylesheet",href:t,"data-precedence":s},r),(r=_n.get(f))&&qh(t,r);var T=b=o.createElement("link");_t(T),Rt(T,"link",t),T._p=new Promise(function(U,$){T.onload=U,T.onerror=$}),T.addEventListener("load",function(){w.loading|=1}),T.addEventListener("error",function(){w.loading|=2}),w.loading|=4,Tl(b,s,o)}b={type:"stylesheet",instance:b,count:1,state:w},h.set(f,b)}}}function MS(t,s){xs.X(t,s);var r=va;if(r&&t){var o=qi(r).hoistableScripts,h=wa(t),f=o.get(h);f||(f=r.querySelector(kr(h)),f||(t=v({src:t,async:!0},s),(s=_n.get(h))&&$h(t,s),f=r.createElement("script"),_t(f),Rt(f,"link",t),r.head.appendChild(f)),f={type:"script",instance:f,count:1,state:null},o.set(h,f))}}function BS(t,s){xs.M(t,s);var r=va;if(r&&t){var o=qi(r).hoistableScripts,h=wa(t),f=o.get(h);f||(f=r.querySelector(kr(h)),f||(t=v({src:t,async:!0,type:"module"},s),(s=_n.get(h))&&$h(t,s),f=r.createElement("script"),_t(f),Rt(f,"link",t),r.head.appendChild(f)),f={type:"script",instance:f,count:1,state:null},o.set(h,f))}}function Ay(t,s,r,o){var h=(h=ge.current)?Sl(h):null;if(!h)throw Error(a(446));switch(t){case"meta":case"title":return null;case"style":return typeof r.precedence=="string"&&typeof r.href=="string"?(s=xa(r.href),r=qi(h).hoistableStyles,o=r.get(s),o||(o={type:"style",instance:null,count:0,state:null},r.set(s,o)),o):{type:"void",instance:null,count:0,state:null};case"link":if(r.rel==="stylesheet"&&typeof r.href=="string"&&typeof r.precedence=="string"){t=xa(r.href);var f=qi(h).hoistableStyles,b=f.get(t);if(b||(h=h.ownerDocument||h,b={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},f.set(t,b),(f=h.querySelector(Nr(t)))&&!f._p&&(b.instance=f,b.state.loading=5),_n.has(t)||(r={rel:"preload",as:"style",href:r.href,crossOrigin:r.crossOrigin,integrity:r.integrity,media:r.media,hrefLang:r.hrefLang,referrerPolicy:r.referrerPolicy},_n.set(t,r),f||US(h,t,r,b.state))),s&&o===null)throw Error(a(528,""));return b}if(s&&o!==null)throw Error(a(529,""));return null;case"script":return s=r.async,r=r.src,typeof r=="string"&&s&&typeof s!="function"&&typeof s!="symbol"?(s=wa(r),r=qi(h).hoistableScripts,o=r.get(s),o||(o={type:"script",instance:null,count:0,state:null},r.set(s,o)),o):{type:"void",instance:null,count:0,state:null};default:throw Error(a(444,t))}}function xa(t){return'href="'+mn(t)+'"'}function Nr(t){return'link[rel="stylesheet"]['+t+"]"}function jy(t){return v({},t,{"data-precedence":t.precedence,precedence:null})}function US(t,s,r,o){t.querySelector('link[rel="preload"][as="style"]['+s+"]")?o.loading=1:(s=t.createElement("link"),o.preload=s,s.addEventListener("load",function(){return o.loading|=1}),s.addEventListener("error",function(){return o.loading|=2}),Rt(s,"link",r),_t(s),t.head.appendChild(s))}function wa(t){return'[src="'+mn(t)+'"]'}function kr(t){return"script[async]"+t}function Cy(t,s,r){if(s.count++,s.instance===null)switch(s.type){case"style":var o=t.querySelector('style[data-href~="'+mn(r.href)+'"]');if(o)return s.instance=o,_t(o),o;var h=v({},r,{"data-href":r.href,"data-precedence":r.precedence,href:null,precedence:null});return o=(t.ownerDocument||t).createElement("style"),_t(o),Rt(o,"style",h),Tl(o,r.precedence,t),s.instance=o;case"stylesheet":h=xa(r.href);var f=t.querySelector(Nr(h));if(f)return s.state.loading|=4,s.instance=f,_t(f),f;o=jy(r),(h=_n.get(h))&&qh(o,h),f=(t.ownerDocument||t).createElement("link"),_t(f);var b=f;return b._p=new Promise(function(w,T){b.onload=w,b.onerror=T}),Rt(f,"link",o),s.state.loading|=4,Tl(f,r.precedence,t),s.instance=f;case"script":return f=wa(r.src),(h=t.querySelector(kr(f)))?(s.instance=h,_t(h),h):(o=r,(h=_n.get(f))&&(o=v({},r),$h(o,h)),t=t.ownerDocument||t,h=t.createElement("script"),_t(h),Rt(h,"link",o),t.head.appendChild(h),s.instance=h);case"void":return null;default:throw Error(a(443,s.type))}else s.type==="stylesheet"&&(s.state.loading&4)===0&&(o=s.instance,s.state.loading|=4,Tl(o,r.precedence,t));return s.instance}function Tl(t,s,r){for(var o=r.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=o.length?o[o.length-1]:null,f=h,b=0;b title"):null)}function LS(t,s,r){if(r===1||s.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof s.precedence!="string"||typeof s.href!="string"||s.href==="")break;return!0;case"link":if(typeof s.rel!="string"||typeof s.href!="string"||s.href===""||s.onLoad||s.onError)break;switch(s.rel){case"stylesheet":return t=s.disabled,typeof s.precedence=="string"&&t==null;default:return!0}case"script":if(s.async&&typeof s.async!="function"&&typeof s.async!="symbol"&&!s.onLoad&&!s.onError&&s.src&&typeof s.src=="string")return!0}return!1}function ky(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function zS(t,s,r,o){if(r.type==="stylesheet"&&(typeof o.media!="string"||matchMedia(o.media).matches!==!1)&&(r.state.loading&4)===0){if(r.instance===null){var h=xa(o.href),f=s.querySelector(Nr(h));if(f){s=f._p,s!==null&&typeof s=="object"&&typeof s.then=="function"&&(t.count++,t=Al.bind(t),s.then(t,t)),r.state.loading|=4,r.instance=f,_t(f);return}f=s.ownerDocument||s,o=jy(o),(h=_n.get(h))&&qh(o,h),f=f.createElement("link"),_t(f);var b=f;b._p=new Promise(function(w,T){b.onload=w,b.onerror=T}),Rt(f,"link",o),r.instance=f}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(r,s),(s=r.state.preload)&&(r.state.loading&3)===0&&(t.count++,r=Al.bind(t),s.addEventListener("load",r),s.addEventListener("error",r))}}var Ih=0;function VS(t,s){return t.stylesheets&&t.count===0&&Cl(t,t.stylesheets),0Ih?50:800)+s);return t.unsuspend=r,function(){t.unsuspend=null,clearTimeout(o),clearTimeout(h)}}:null}function Al(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Cl(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var jl=null;function Cl(t,s){t.stylesheets=null,t.unsuspend!==null&&(t.count++,jl=new Map,s.forEach(PS,t),jl=null,Al.call(t))}function PS(t,s){if(!(s.state.loading&4)){var r=jl.get(t);if(r)var o=r.get(null);else{r=new Map,jl.set(t,r);for(var h=t.querySelectorAll("link[data-precedence],style[data-precedence]"),f=0;f"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),Wh.exports=n1(),Wh.exports}var i1=s1();const xf=M.createContext({});function wf(n){const e=M.useRef(null);return e.current===null&&(e.current=n()),e.current}const a1=typeof window<"u",_f=a1?M.useLayoutEffect:M.useEffect,Nc=M.createContext(null);function Sf(n,e){n.indexOf(e)===-1&&n.push(e)}function uc(n,e){const i=n.indexOf(e);i>-1&&n.splice(i,1)}const Qn=(n,e,i)=>i>e?e:i{};const ti={},_v=n=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(n),Sv=n=>typeof n=="object"&&n!==null,Tv=n=>/^0[^.\s]+$/u.test(n);function Ev(n){let e;return()=>(e===void 0&&(e=n()),e)}const En=n=>n,yo=(...n)=>n.reduce((e,i)=>a=>i(e(a))),to=(n,e,i)=>{const a=e-n;return a?(i-n)/a:1};class Ef{constructor(){this.subscriptions=[]}add(e){return Sf(this.subscriptions,e),()=>uc(this.subscriptions,e)}notify(e,i,a){const l=this.subscriptions.length;if(l)if(l===1)this.subscriptions[0](e,i,a);else for(let c=0;cn*1e3,Tn=n=>n/1e3,Av=(n,e)=>e?n*(1e3/e):0,jv=(n,e,i)=>(((1-3*i+3*e)*n+(3*i-6*e))*n+3*e)*n,r1=1e-7,o1=12;function l1(n,e,i,a,l){let c,u,d=0;do u=e+(i-e)/2,c=jv(u,a,l)-n,c>0?i=u:e=u;while(Math.abs(c)>r1&&++dl1(c,0,1,n,i);return c=>c===0||c===1?c:jv(l(c),e,a)}const Cv=n=>e=>e<=.5?n(2*e)/2:(2-n(2*(1-e)))/2,Rv=n=>e=>1-n(1-e),Nv=bo(.33,1.53,.69,.99),Af=Rv(Nv),kv=Cv(Af),Ov=n=>n>=1?1:(n*=2)<1?.5*Af(n):.5*(2-Math.pow(2,-10*(n-1))),jf=n=>1-Math.sin(Math.acos(n)),Dv=Rv(jf),Mv=Cv(jf),c1=bo(.42,0,1,1),u1=bo(0,0,.58,1),Bv=bo(.42,0,.58,1),h1=n=>Array.isArray(n)&&typeof n[0]!="number",Uv=n=>Array.isArray(n)&&typeof n[0]=="number",d1={linear:En,easeIn:c1,easeInOut:Bv,easeOut:u1,circIn:jf,circInOut:Mv,circOut:Dv,backIn:Af,backInOut:kv,backOut:Nv,anticipate:Ov},f1=n=>typeof n=="string",t0=n=>{if(Uv(n)){Tf(n.length===4);const[e,i,a,l]=n;return bo(e,i,a,l)}else if(f1(n))return d1[n];return n},Ul=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function m1(n){let e=new Set,i=new Set,a=!1,l=!1;const c=new WeakSet;let u={delta:0,timestamp:0,isProcessing:!1};function d(p){c.has(p)&&(m.schedule(p),n()),p(u)}const m={schedule:(p,y=!1,v=!1)=>{const _=v&&a?e:i;return y&&c.add(p),_.add(p),p},cancel:p=>{i.delete(p),c.delete(p)},process:p=>{if(u=p,a){l=!0;return}a=!0;const y=e;e=i,i=y,e.forEach(d),e.clear(),a=!1,l&&(l=!1,m.process(p))}};return m}const p1=40;function Lv(n,e){let i=!1,a=!0;const l={delta:0,timestamp:0,isProcessing:!1},c=()=>i=!0,u=Ul.reduce((C,P)=>(C[P]=m1(c),C),{}),{setup:d,read:m,resolveKeyframes:p,preUpdate:y,update:v,preRender:x,render:_,postRender:S}=u,E=()=>{const C=ti.useManualTiming,P=C?l.timestamp:performance.now();i=!1,C||(l.delta=a?1e3/60:Math.max(Math.min(P-l.timestamp,p1),1)),l.timestamp=P,l.isProcessing=!0,d.process(l),m.process(l),p.process(l),y.process(l),v.process(l),x.process(l),_.process(l),S.process(l),l.isProcessing=!1,i&&e&&(a=!1,n(E))},R=()=>{i=!0,a=!0,l.isProcessing||n(E)};return{schedule:Ul.reduce((C,P)=>{const Y=u[P];return C[P]=(X,q=!1,Z=!1)=>(i||R(),Y.schedule(X,q,Z)),C},{}),cancel:C=>{for(let P=0;P(tc===void 0&&zt.set(Nt.isProcessing||ti.useManualTiming?Nt.timestamp:performance.now()),tc),set:n=>{tc=n,queueMicrotask(g1)}},zv=n=>e=>typeof e=="string"&&e.startsWith(n),Vv=zv("--"),y1=zv("var(--"),Cf=n=>y1(n)?b1.test(n.split("/*")[0].trim()):!1,b1=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function n0(n){return typeof n!="string"?!1:n.split("/*")[0].includes("var(--")}const qa={test:n=>typeof n=="number",parse:parseFloat,transform:n=>n},no={...qa,transform:n=>Qn(0,1,n)},Ll={...qa,default:1},Gr=n=>Math.round(n*1e5)/1e5,Rf=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function v1(n){return n==null}const x1=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Nf=(n,e)=>i=>!!(typeof i=="string"&&x1.test(i)&&i.startsWith(n)||e&&!v1(i)&&Object.prototype.hasOwnProperty.call(i,e)),Pv=(n,e,i)=>a=>{if(typeof a!="string")return a;const[l,c,u,d]=a.match(Rf);return{[n]:parseFloat(l),[e]:parseFloat(c),[i]:parseFloat(u),alpha:d!==void 0?parseFloat(d):1}},w1=n=>Qn(0,255,n),id={...qa,transform:n=>Math.round(w1(n))},Ci={test:Nf("rgb","red"),parse:Pv("red","green","blue"),transform:({red:n,green:e,blue:i,alpha:a=1})=>"rgba("+id.transform(n)+", "+id.transform(e)+", "+id.transform(i)+", "+Gr(no.transform(a))+")"};function _1(n){let e="",i="",a="",l="";return n.length>5?(e=n.substring(1,3),i=n.substring(3,5),a=n.substring(5,7),l=n.substring(7,9)):(e=n.substring(1,2),i=n.substring(2,3),a=n.substring(3,4),l=n.substring(4,5),e+=e,i+=i,a+=a,l+=l),{red:parseInt(e,16),green:parseInt(i,16),blue:parseInt(a,16),alpha:l?parseInt(l,16)/255:1}}const kd={test:Nf("#"),parse:_1,transform:Ci.transform},vo=n=>({test:e=>typeof e=="string"&&e.endsWith(n)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${n}`}),_s=vo("deg"),Jn=vo("%"),re=vo("px"),S1=vo("vh"),T1=vo("vw"),s0={...Jn,parse:n=>Jn.parse(n)/100,transform:n=>Jn.transform(n*100)},Da={test:Nf("hsl","hue"),parse:Pv("hue","saturation","lightness"),transform:({hue:n,saturation:e,lightness:i,alpha:a=1})=>"hsla("+Math.round(n)+", "+Jn.transform(Gr(e))+", "+Jn.transform(Gr(i))+", "+Gr(no.transform(a))+")"},yt={test:n=>Ci.test(n)||kd.test(n)||Da.test(n),parse:n=>Ci.test(n)?Ci.parse(n):Da.test(n)?Da.parse(n):kd.parse(n),transform:n=>typeof n=="string"?n:n.hasOwnProperty("red")?Ci.transform(n):Da.transform(n),getAnimatableNone:n=>{const e=yt.parse(n);return e.alpha=0,yt.transform(e)}},E1=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function A1(n){var e,i;return isNaN(n)&&typeof n=="string"&&(((e=n.match(Rf))==null?void 0:e.length)||0)+(((i=n.match(E1))==null?void 0:i.length)||0)>0}const Hv="number",qv="color",j1="var",C1="var(",i0="${}",R1=/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 Pa(n){const e=n.toString(),i=[],a={color:[],number:[],var:[]},l=[];let c=0;const d=e.replace(R1,m=>(yt.test(m)?(a.color.push(c),l.push(qv),i.push(yt.parse(m))):m.startsWith(C1)?(a.var.push(c),l.push(j1),i.push(m)):(a.number.push(c),l.push(Hv),i.push(parseFloat(m))),++c,i0)).split(i0);return{values:i,split:d,indexes:a,types:l}}function N1(n){return Pa(n).values}function $v({split:n,types:e}){const i=n.length;return a=>{let l="";for(let c=0;ctypeof n=="number"?0:yt.test(n)?yt.getAnimatableNone(n):n,D1=(n,e)=>typeof n=="number"?e!=null&&e.trim().endsWith("/")?n:0:O1(n);function M1(n){const e=Pa(n);return $v(e)(e.values.map((a,l)=>D1(a,e.split[l])))}const Ln={test:A1,parse:N1,createTransformer:k1,getAnimatableNone:M1};function ad(n,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?n+(e-n)*6*i:i<1/2?e:i<2/3?n+(e-n)*(2/3-i)*6:n}function B1({hue:n,saturation:e,lightness:i,alpha:a}){n/=360,e/=100,i/=100;let l=0,c=0,u=0;if(!e)l=c=u=i;else{const d=i<.5?i*(1+e):i+e-i*e,m=2*i-d;l=ad(m,d,n+1/3),c=ad(m,d,n),u=ad(m,d,n-1/3)}return{red:Math.round(l*255),green:Math.round(c*255),blue:Math.round(u*255),alpha:a}}function hc(n,e){return i=>i>0?e:n}const Ie=(n,e,i)=>n+(e-n)*i,rd=(n,e,i)=>{const a=n*n,l=i*(e*e-a)+a;return l<0?0:Math.sqrt(l)},U1=[kd,Ci,Da],L1=n=>U1.find(e=>e.test(n));function a0(n){const e=L1(n);if(!e)return!1;let i=e.parse(n);return e===Da&&(i=B1(i)),i}const r0=(n,e)=>{const i=a0(n),a=a0(e);if(!i||!a)return hc(n,e);const l={...i};return c=>(l.red=rd(i.red,a.red,c),l.green=rd(i.green,a.green,c),l.blue=rd(i.blue,a.blue,c),l.alpha=Ie(i.alpha,a.alpha,c),Ci.transform(l))},Od=new Set(["none","hidden"]);function z1(n,e){return Od.has(n)?i=>i<=0?n:e:i=>i>=1?e:n}function V1(n,e){return i=>Ie(n,e,i)}function kf(n){return typeof n=="number"?V1:typeof n=="string"?Cf(n)?hc:yt.test(n)?r0:q1:Array.isArray(n)?Iv:typeof n=="object"?yt.test(n)?r0:P1:hc}function Iv(n,e){const i=[...n],a=i.length,l=n.map((c,u)=>kf(c)(c,e[u]));return c=>{for(let u=0;u{for(const c in a)i[c]=a[c](l);return i}}function H1(n,e){const i=[],a={color:0,var:0,number:0};for(let l=0;l{const i=Ln.createTransformer(e),a=Pa(n),l=Pa(e);return a.indexes.var.length===l.indexes.var.length&&a.indexes.color.length===l.indexes.color.length&&a.indexes.number.length>=l.indexes.number.length?Od.has(n)&&!l.values.length||Od.has(e)&&!a.values.length?z1(n,e):yo(Iv(H1(a,l),l.values),i):hc(n,e)};function Fv(n,e,i){return typeof n=="number"&&typeof e=="number"&&typeof i=="number"?Ie(n,e,i):kf(n)(n,e)}const $1=n=>{const e=({timestamp:i})=>n(i);return{start:(i=!0)=>Fe.update(e,i),stop:()=>ni(e),now:()=>Nt.isProcessing?Nt.timestamp:zt.now()}},Gv=(n,e,i=10)=>{let a="";const l=Math.max(Math.round(e/i),2);for(let c=0;c=dc?1/0:e}function I1(n,e=100,i){const a=i({...n,keyframes:[0,e]}),l=Math.min(Of(a),dc);return{type:"keyframes",ease:c=>a.next(l*c).value/e,duration:Tn(l)}}const nt={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};function Dd(n,e){return n*Math.sqrt(1-e*e)}const F1=12;function G1(n,e,i){let a=i;for(let l=1;l{const y=p*u,v=y*n,x=y-i,_=Dd(p,u),S=Math.exp(-v);return od-x/_*S},c=p=>{const v=p*u*n,x=v*i+i,_=Math.pow(u,2)*Math.pow(p,2)*n,S=Math.exp(-v),E=Dd(Math.pow(p,2),u);return(-l(p)+od>0?-1:1)*((x-_)*S)/E}):(l=p=>{const y=Math.exp(-p*n),v=(p-i)*n+1;return-od+y*v},c=p=>{const y=Math.exp(-p*n),v=(i-p)*(n*n);return y*v});const d=5/n,m=G1(l,c,d);if(n=hn(n),isNaN(m))return{stiffness:nt.stiffness,damping:nt.damping,duration:n};{const p=Math.pow(m,2)*a;return{stiffness:p,damping:u*2*Math.sqrt(a*p),duration:n}}}const Y1=["duration","bounce"],X1=["stiffness","damping","mass"];function o0(n,e){return e.some(i=>n[i]!==void 0)}function J1(n){let e={velocity:nt.velocity,stiffness:nt.stiffness,damping:nt.damping,mass:nt.mass,isResolvedFromDuration:!1,...n};if(!o0(n,X1)&&o0(n,Y1))if(e.velocity=0,n.visualDuration){const i=n.visualDuration,a=2*Math.PI/(i*1.2),l=a*a,c=2*Qn(.05,1,1-(n.bounce||0))*Math.sqrt(l);e={...e,mass:nt.mass,stiffness:l,damping:c}}else{const i=K1({...n,velocity:0});e={...e,...i,mass:nt.mass},e.isResolvedFromDuration=!0}return e}function fc(n=nt.visualDuration,e=nt.bounce){const i=typeof n!="object"?{visualDuration:n,keyframes:[0,1],bounce:e}:n;let{restSpeed:a,restDelta:l}=i;const c=i.keyframes[0],u=i.keyframes[i.keyframes.length-1],d={done:!1,value:c},{stiffness:m,damping:p,mass:y,duration:v,velocity:x,isResolvedFromDuration:_}=J1({...i,velocity:-Tn(i.velocity||0)}),S=x||0,E=p/(2*Math.sqrt(m*y)),R=u-c,N=Tn(Math.sqrt(m/y)),O=Math.abs(R)<5;a||(a=O?nt.restSpeed.granular:nt.restSpeed.default),l||(l=O?nt.restDelta.granular:nt.restDelta.default);let C,P,Y,X,q,Z;if(E<1)Y=Dd(N,E),X=(S+E*N*R)/Y,C=Q=>{const le=Math.exp(-E*N*Q);return u-le*(X*Math.sin(Y*Q)+R*Math.cos(Y*Q))},q=E*N*X+R*Y,Z=E*N*R-X*Y,P=Q=>Math.exp(-E*N*Q)*(q*Math.sin(Y*Q)+Z*Math.cos(Y*Q));else if(E===1){C=le=>u-Math.exp(-N*le)*(R+(S+N*R)*le);const Q=S+N*R;P=le=>Math.exp(-N*le)*(N*Q*le-S)}else{const Q=N*Math.sqrt(E*E-1);C=Ne=>{const xe=Math.exp(-E*N*Ne),z=Math.min(Q*Ne,300);return u-xe*((S+E*N*R)*Math.sinh(z)+Q*R*Math.cosh(z))/Q};const le=(S+E*N*R)/Q,he=E*N*le-R*Q,Ge=E*N*R-le*Q;P=Ne=>{const xe=Math.exp(-E*N*Ne),z=Math.min(Q*Ne,300);return xe*(he*Math.sinh(z)+Ge*Math.cosh(z))}}const te={calculatedDuration:_&&v||null,velocity:Q=>hn(P(Q)),next:Q=>{if(!_&&E<1){const he=Math.exp(-E*N*Q),Ge=Math.sin(Y*Q),Ne=Math.cos(Y*Q),xe=u-he*(X*Ge+R*Ne),z=hn(he*(q*Ge+Z*Ne));return d.done=Math.abs(z)<=a&&Math.abs(u-xe)<=l,d.value=d.done?u:xe,d}const le=C(Q);if(_)d.done=Q>=v;else{const he=hn(P(Q));d.done=Math.abs(he)<=a&&Math.abs(u-le)<=l}return d.value=d.done?u:le,d},toString:()=>{const Q=Math.min(Of(te),dc),le=Gv(he=>te.next(Q*he).value,Q,30);return Q+"ms "+le},toTransition:()=>{}};return te}fc.applyToOptions=n=>{const e=I1(n,100,fc);return n.ease=e.ease,n.duration=hn(e.duration),n.type="keyframes",n};const Q1=5;function Kv(n,e,i){const a=Math.max(e-Q1,0);return Av(i-n(a),e-a)}function Md({keyframes:n,velocity:e=0,power:i=.8,timeConstant:a=325,bounceDamping:l=10,bounceStiffness:c=500,modifyTarget:u,min:d,max:m,restDelta:p=.5,restSpeed:y}){const v=n[0],x={done:!1,value:v},_=Z=>d!==void 0&&Zm,S=Z=>d===void 0?m:m===void 0||Math.abs(d-Z)-E*Math.exp(-Z/a),C=Z=>N+O(Z),P=Z=>{const te=O(Z),Q=C(Z);x.done=Math.abs(te)<=p,x.value=x.done?N:Q};let Y,X;const q=Z=>{_(x.value)&&(Y=Z,X=fc({keyframes:[x.value,S(x.value)],velocity:Kv(C,Z,x.value),damping:l,stiffness:c,restDelta:p,restSpeed:y}))};return q(0),{calculatedDuration:null,next:Z=>{let te=!1;return!X&&Y===void 0&&(te=!0,P(Z),q(Z)),Y!==void 0&&Z>=Y?X.next(Z-Y):(!te&&P(Z),x)}}}function Z1(n,e,i){const a=[],l=i||ti.mix||Fv,c=n.length-1;for(let u=0;ue[0];if(c===2&&e[0]===e[1])return()=>e[1];const u=n[0]===n[1];n[0]>n[c-1]&&(n=[...n].reverse(),e=[...e].reverse());const d=Z1(e,a,l),m=d.length,p=y=>{if(u&&y1)for(;vp(Qn(n[0],n[c-1],y)):p}function eT(n,e){const i=n[n.length-1];for(let a=1;a<=e;a++){const l=to(0,e,a);n.push(Ie(i,1,l))}}function tT(n){const e=[0];return eT(e,n.length-1),e}function nT(n,e){return n.map(i=>i*e)}function sT(n,e){return n.map(()=>e||Bv).splice(0,n.length-1)}function Kr({duration:n=300,keyframes:e,times:i,ease:a="easeInOut"}){const l=h1(a)?a.map(t0):t0(a),c={done:!1,value:e[0]},u=nT(i&&i.length===e.length?i:tT(e),n),d=W1(u,e,{ease:Array.isArray(l)?l:sT(e,l)});return{calculatedDuration:n,next:m=>(c.value=d(m),c.done=m>=n,c)}}const iT=n=>n!==null;function kc(n,{repeat:e,repeatType:i="loop"},a,l=1){const c=n.filter(iT),d=l<0||e&&i!=="loop"&&e%2===1?0:c.length-1;return!d||a===void 0?c[d]:a}const aT={decay:Md,inertia:Md,tween:Kr,keyframes:Kr,spring:fc};function Yv(n){typeof n.type=="string"&&(n.type=aT[n.type])}class Df{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,i){return this.finished.then(e,i)}}const rT=n=>n/100;class mc extends Df{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{var a,l;const{motionValue:i}=this.options;i&&i.updatedAt!==zt.now()&&this.tick(zt.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(l=(a=this.options).onStop)==null||l.call(a))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;Yv(e);const{type:i=Kr,repeat:a=0,repeatDelay:l=0,repeatType:c,velocity:u=0}=e;let{keyframes:d}=e;const m=i||Kr;m!==Kr&&typeof d[0]!="number"&&(this.mixKeyframes=yo(rT,Fv(d[0],d[1])),d=[0,100]);const p=m({...e,keyframes:d});c==="mirror"&&(this.mirroredGenerator=m({...e,keyframes:[...d].reverse(),velocity:-u})),p.calculatedDuration===null&&(p.calculatedDuration=Of(p));const{calculatedDuration:y}=p;this.calculatedDuration=y,this.resolvedDuration=y+l,this.totalDuration=this.resolvedDuration*(a+1)-l,this.generator=p}updateTime(e){const i=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=i}tick(e,i=!1){const{generator:a,totalDuration:l,mixKeyframes:c,mirroredGenerator:u,resolvedDuration:d,calculatedDuration:m}=this;if(this.startTime===null)return a.next(0);const{delay:p=0,keyframes:y,repeat:v,repeatType:x,repeatDelay:_,type:S,onUpdate:E,finalKeyframe:R}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-l/this.speed,this.startTime)),i?this.currentTime=e:this.updateTime(e);const N=this.currentTime-p*(this.playbackSpeed>=0?1:-1),O=this.playbackSpeed>=0?N<0:N>l;this.currentTime=Math.max(N,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=l);let C=this.currentTime,P=a;if(v){const Z=Math.min(this.currentTime,l)/d;let te=Math.floor(Z),Q=Z%1;!Q&&Z>=1&&(Q=1),Q===1&&te--,te=Math.min(te,v+1),!!(te%2)&&(x==="reverse"?(Q=1-Q,_&&(Q-=_/d)):x==="mirror"&&(P=u)),C=Qn(0,1,Q)*d}let Y;O?(this.delayState.value=y[0],Y=this.delayState):Y=P.next(C),c&&!O&&(Y.value=c(Y.value));let{done:X}=Y;!O&&m!==null&&(X=this.playbackSpeed>=0?this.currentTime>=l:this.currentTime<=0);const q=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&X);return q&&S!==Md&&(Y.value=kc(y,this.options,R,this.speed)),E&&E(Y.value),q&&this.finish(),Y}then(e,i){return this.finished.then(e,i)}get duration(){return Tn(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Tn(e)}get time(){return Tn(this.currentTime)}set time(e){e=hn(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=e,this.tick(e))}getGeneratorVelocity(){const e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);const i=this.generator.next(e).value;return Kv(a=>this.generator.next(a).value,e,i)}get speed(){return this.playbackSpeed}set speed(e){const i=this.playbackSpeed!==e;i&&this.driver&&this.updateTime(zt.now()),this.playbackSpeed=e,i&&this.driver&&(this.time=Tn(this.currentTime))}play(){var l,c;if(this.isStopped)return;const{driver:e=$1,startTime:i}=this.options;this.driver||(this.driver=e(u=>this.tick(u))),(c=(l=this.options).onPlay)==null||c.call(l);const a=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=a):this.holdTime!==null?this.startTime=a-this.holdTime:this.startTime||(this.startTime=i??a),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(zt.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,i;this.notifyFinished(),this.teardown(),this.state="finished",(i=(e=this.options).onComplete)==null||i.call(e)}cancel(){var e,i;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(i=(e=this.options).onCancel)==null||i.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var i;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(i=this.driver)==null||i.stop(),e.observe(this)}}function oT(n){for(let e=1;en*180/Math.PI,Bd=n=>{const e=Ri(Math.atan2(n[1],n[0]));return Ud(e)},lT={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:n=>(Math.abs(n[0])+Math.abs(n[3]))/2,rotate:Bd,rotateZ:Bd,skewX:n=>Ri(Math.atan(n[1])),skewY:n=>Ri(Math.atan(n[2])),skew:n=>(Math.abs(n[1])+Math.abs(n[2]))/2},Ud=n=>(n=n%360,n<0&&(n+=360),n),l0=Bd,c0=n=>Math.sqrt(n[0]*n[0]+n[1]*n[1]),u0=n=>Math.sqrt(n[4]*n[4]+n[5]*n[5]),cT={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:c0,scaleY:u0,scale:n=>(c0(n)+u0(n))/2,rotateX:n=>Ud(Ri(Math.atan2(n[6],n[5]))),rotateY:n=>Ud(Ri(Math.atan2(-n[2],n[0]))),rotateZ:l0,rotate:l0,skewX:n=>Ri(Math.atan(n[4])),skewY:n=>Ri(Math.atan(n[1])),skew:n=>(Math.abs(n[1])+Math.abs(n[4]))/2};function Ld(n){return n.includes("scale")?1:0}function zd(n,e){if(!n||n==="none")return Ld(e);const i=n.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let a,l;if(i)a=cT,l=i;else{const d=n.match(/^matrix\(([-\d.e\s,]+)\)$/u);a=lT,l=d}if(!l)return Ld(e);const c=a[e],u=l[1].split(",").map(hT);return typeof c=="function"?c(u):u[c]}const uT=(n,e)=>{const{transform:i="none"}=getComputedStyle(n);return zd(i,e)};function hT(n){return parseFloat(n.trim())}const $a=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ia=new Set([...$a,"pathRotation"]),h0=n=>n===qa||n===re,dT=new Set(["x","y","z"]),fT=$a.filter(n=>!dT.has(n));function mT(n){const e=[];return fT.forEach(i=>{const a=n.getValue(i);a!==void 0&&(e.push([i,a.get()]),a.set(i.startsWith("scale")?1:0))}),e}const ei={width:({x:n},{paddingLeft:e="0",paddingRight:i="0",boxSizing:a})=>{const l=n.max-n.min;return a==="border-box"?l:l-parseFloat(e)-parseFloat(i)},height:({y:n},{paddingTop:e="0",paddingBottom:i="0",boxSizing:a})=>{const l=n.max-n.min;return a==="border-box"?l:l-parseFloat(e)-parseFloat(i)},top:(n,{top:e})=>parseFloat(e),left:(n,{left:e})=>parseFloat(e),bottom:({y:n},{top:e})=>parseFloat(e)+(n.max-n.min),right:({x:n},{left:e})=>parseFloat(e)+(n.max-n.min),x:(n,{transform:e})=>zd(e,"x"),y:(n,{transform:e})=>zd(e,"y")};ei.translateX=ei.x;ei.translateY=ei.y;const ki=new Set;let Vd=!1,Pd=!1,Hd=!1;function Xv(){if(Pd){const n=Array.from(ki).filter(a=>a.needsMeasurement),e=new Set(n.map(a=>a.element)),i=new Map;e.forEach(a=>{const l=mT(a);l.length&&(i.set(a,l),a.render())}),n.forEach(a=>a.measureInitialState()),e.forEach(a=>{a.render();const l=i.get(a);l&&l.forEach(([c,u])=>{var d;(d=a.getValue(c))==null||d.set(u)})}),n.forEach(a=>a.measureEndState()),n.forEach(a=>{a.suspendedScrollY!==void 0&&window.scrollTo(0,a.suspendedScrollY)})}Pd=!1,Vd=!1,ki.forEach(n=>n.complete(Hd)),ki.clear()}function Jv(){ki.forEach(n=>{n.readKeyframes(),n.needsMeasurement&&(Pd=!0)})}function pT(){Hd=!0,Jv(),Xv(),Hd=!1}class Mf{constructor(e,i,a,l,c,u=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=i,this.name=a,this.motionValue=l,this.element=c,this.isAsync=u}scheduleResolve(){this.state="scheduled",this.isAsync?(ki.add(this),Vd||(Vd=!0,Fe.read(Jv),Fe.resolveKeyframes(Xv))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:i,element:a,motionValue:l}=this;if(e[0]===null){const c=l==null?void 0:l.get(),u=e[e.length-1];if(c!==void 0)e[0]=c;else if(a&&i){const d=a.readValue(i,u);d!=null&&(e[0]=d)}e[0]===void 0&&(e[0]=u),l&&c===void 0&&l.set(e[0])}oT(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),ki.delete(this)}cancel(){this.state==="scheduled"&&(ki.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const gT=n=>n.startsWith("--");function Qv(n,e,i){gT(e)?n.style.setProperty(e,i):n.style[e]=i}const yT={};function Zv(n,e){const i=Ev(n);return()=>yT[e]??i()}const bT=Zv(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),Wv=Zv(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Pr=([n,e,i,a])=>`cubic-bezier(${n}, ${e}, ${i}, ${a})`,d0={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Pr([0,.65,.55,1]),circOut:Pr([.55,0,1,.45]),backIn:Pr([.31,.01,.66,-.59]),backOut:Pr([.33,1.53,.69,.99])};function ex(n,e){if(n)return typeof n=="function"?Wv()?Gv(n,e):"ease-out":Uv(n)?Pr(n):Array.isArray(n)?n.map(i=>ex(i,e)||d0.easeOut):d0[n]}function vT(n,e,i,{delay:a=0,duration:l=300,repeat:c=0,repeatType:u="loop",ease:d="easeOut",times:m}={},p=void 0){const y={[e]:i};m&&(y.offset=m);const v=ex(d,l);Array.isArray(v)&&(y.easing=v);const x={delay:a,duration:l,easing:Array.isArray(v)?"linear":v,fill:"both",iterations:c+1,direction:u==="reverse"?"alternate":"normal"};return p&&(x.pseudoElement=p),n.animate(y,x)}function tx(n){return typeof n=="function"&&"applyToOptions"in n}function xT({type:n,...e}){return tx(n)&&Wv()?n.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class nx extends Df{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;const{element:i,name:a,keyframes:l,pseudoElement:c,allowFlatten:u=!1,finalKeyframe:d,onComplete:m}=e;this.isPseudoElement=!!c,this.allowFlatten=u,this.options=e,Tf(typeof e.type!="string");const p=xT(e);this.animation=vT(i,a,l,p,c),p.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!c){const y=kc(l,this.options,d,this.speed);this.updateMotionValue&&this.updateMotionValue(y),Qv(i,a,y),this.animation.cancel()}m==null||m(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,i;(i=(e=this.animation).finish)==null||i.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var i,a,l;const e=(i=this.options)==null?void 0:i.element;!this.isPseudoElement&&(e!=null&&e.isConnected)&&((l=(a=this.animation).commitStyles)==null||l.call(a))}get duration(){var i,a;const e=((a=(i=this.animation.effect)==null?void 0:i.getComputedTiming)==null?void 0:a.call(i).duration)||0;return Tn(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Tn(e)}get time(){return Tn(Number(this.animation.currentTime)||0)}set time(e){const i=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=hn(e),i&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:i,rangeEnd:a,observe:l}){var c;return this.allowFlatten&&((c=this.animation.effect)==null||c.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&bT()?(this.animation.timeline=e,i&&(this.animation.rangeStart=i),a&&(this.animation.rangeEnd=a),En):l(this)}}const sx={anticipate:Ov,backInOut:kv,circInOut:Mv};function wT(n){return n in sx}function _T(n){typeof n.ease=="string"&&wT(n.ease)&&(n.ease=sx[n.ease])}const ld=10;class ST extends nx{constructor(e){_T(e),Yv(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:i,onUpdate:a,onComplete:l,element:c,...u}=this.options;if(!i)return;if(e!==void 0){i.set(e);return}const d=new mc({...u,autoplay:!1}),m=Math.max(ld,zt.now()-this.startTime),p=Qn(0,ld,m-ld),y=d.sample(m).value,{name:v}=this.options;c&&v&&Qv(c,v,y),i.setWithVelocity(d.sample(Math.max(0,m-p)).value,y,p),d.stop()}}const f0=(n,e)=>e==="zIndex"?!1:!!(typeof n=="number"||Array.isArray(n)||typeof n=="string"&&(Ln.test(n)||n==="0")&&!n.startsWith("url("));function TT(n){const e=n[0];if(n.length===1)return!0;for(let i=0;iObject.hasOwnProperty.call(Element.prototype,"animate"));function NT(n){var v;const{motionValue:e,name:i,repeatDelay:a,repeatType:l,damping:c,type:u,keyframes:d}=n;if(!(((v=e==null?void 0:e.owner)==null?void 0:v.current)instanceof HTMLElement))return!1;const{onUpdate:p,transformTemplate:y}=e.owner.getProps();return RT()&&i&&(ix.has(i)||CT.has(i)&&jT(d))&&(i!=="transform"||!y)&&!p&&!a&&l!=="mirror"&&c!==0&&u!=="inertia"}const kT=40;class OT extends Df{constructor({autoplay:e=!0,delay:i=0,type:a="keyframes",repeat:l=0,repeatDelay:c=0,repeatType:u="loop",keyframes:d,name:m,motionValue:p,element:y,...v}){var S;super(),this.stop=()=>{var E,R;this._animation&&(this._animation.stop(),(E=this.stopTimeline)==null||E.call(this)),(R=this.keyframeResolver)==null||R.cancel()},this.createdAt=zt.now();const x={autoplay:e,delay:i,type:a,repeat:l,repeatDelay:c,repeatType:u,name:m,motionValue:p,element:y,...v},_=(y==null?void 0:y.KeyframeResolver)||Mf;this.keyframeResolver=new _(d,(E,R,N)=>this.onKeyframesResolved(E,R,x,!N),m,p,y),(S=this.keyframeResolver)==null||S.scheduleResolve()}onKeyframesResolved(e,i,a,l){var N,O;this.keyframeResolver=void 0;const{name:c,type:u,velocity:d,delay:m,isHandoff:p,onUpdate:y}=a;this.resolvedAt=zt.now();let v=!0;ET(e,c,u,d)||(v=!1,(ti.instantAnimations||!m)&&(y==null||y(kc(e,a,i))),e[0]=e[e.length-1],qd(a),a.repeat=0);const _={startTime:l?this.resolvedAt?this.resolvedAt-this.createdAt>kT?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...a,keyframes:e},S=v&&!p&&NT(_),E=(O=(N=_.motionValue)==null?void 0:N.owner)==null?void 0:O.current;let R;if(S)try{R=new ST({..._,element:E})}catch{R=new mc(_)}else R=new mc(_);R.finished.then(()=>{this.notifyFinished()}).catch(En),this.pendingTimeline&&(this.stopTimeline=R.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=R}get finished(){return this._animation?this.animation.finished:this._finished}then(e,i){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),pT()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var e;this._animation&&this.animation.cancel(),(e=this.keyframeResolver)==null||e.cancel()}}function ax(n,e,i,a=0,l=1){const c=Array.from(n).sort((p,y)=>p.sortNodePosition(y)).indexOf(e),u=n.size,d=(u-1)*a;return typeof i=="function"?i(c,u):l===1?c*a:d-c*a}const m0=30,DT=n=>!isNaN(parseFloat(n));class MT{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=a=>{var c;const l=zt.now();if(this.updatedAt!==l&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(a),this.current!==this.prev&&((c=this.events.change)==null||c.notify(this.current),this.dependents))for(const u of this.dependents)u.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=i.owner}setCurrent(e){this.current=e,this.updatedAt=zt.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=DT(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,i){this.events[e]||(this.events[e]=new Ef);const a=this.events[e].add(i);return e==="change"?()=>{a(),Fe.read(()=>{this.events.change.getSize()||this.stop()})}:a}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,i){this.passiveEffect=e,this.stopPassiveEffect=i}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,i,a){this.set(i),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-a}jump(e,i=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,i&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=zt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>m0)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,m0);return Av(parseFloat(this.current)-parseFloat(this.prevFrameValue),i)}start(e){return this.stop(),new Promise(i=>{this.hasAnimated=!0,this.animation=e(i),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(){var e,i;(e=this.dependents)==null||e.clear(),(i=this.events.destroy)==null||i.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Ha(n,e){return new MT(n,e)}function rx(n,e){if(n!=null&&n.inherit&&e){const{inherit:i,...a}=n;return{...e,...a}}return n}function Bf(n,e){const i=(n==null?void 0:n[e])??(n==null?void 0:n.default)??n;return i!==n?rx(i,n):i}const BT={type:"spring",stiffness:500,damping:25,restSpeed:10},UT=n=>({type:"spring",stiffness:550,damping:n===0?2*Math.sqrt(550):30,restSpeed:10}),LT={type:"keyframes",duration:.8},zT={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},VT=(n,{keyframes:e})=>e.length>2?LT:Ia.has(n)?n.startsWith("scale")?UT(e[1]):BT:zT,PT=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function HT(n){for(const e in n)if(!PT.has(e))return!0;return!1}const Uf=(n,e,i,a={},l,c)=>u=>{const d=Bf(a,n)||{},m=d.delay||a.delay||0;let{elapsed:p=0}=a;p=p-hn(m);const y={keyframes:Array.isArray(i)?i:[null,i],ease:"easeOut",velocity:e.getVelocity(),...d,delay:-p,onUpdate:x=>{e.set(x),d.onUpdate&&d.onUpdate(x)},onComplete:()=>{u(),d.onComplete&&d.onComplete()},name:n,motionValue:e,element:c?void 0:l};HT(d)||Object.assign(y,VT(n,y)),y.duration&&(y.duration=hn(y.duration)),y.repeatDelay&&(y.repeatDelay=hn(y.repeatDelay)),y.from!==void 0&&(y.keyframes[0]=y.from);let v=!1;if((y.type===!1||y.duration===0&&!y.repeatDelay)&&(qd(y),y.delay===0&&(v=!0)),(ti.instantAnimations||ti.skipAnimations||l!=null&&l.shouldSkipAnimations||d.skipAnimations)&&(v=!0,qd(y),y.delay=0),y.allowFlatten=!d.type&&!d.ease,v&&!c&&e.get()!==void 0){const x=kc(y.keyframes,d);if(x!==void 0){Fe.update(()=>{y.onUpdate(x),y.onComplete()});return}}return d.isSync?new mc(y):new OT(y)},qT=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function $T(n){const e=qT.exec(n);if(!e)return[,];const[,i,a,l]=e;return[`--${i??a}`,l]}function ox(n,e,i=1){const[a,l]=$T(n);if(!a)return;const c=window.getComputedStyle(e).getPropertyValue(a);if(c){const u=c.trim();return _v(u)?parseFloat(u):u}return Cf(l)?ox(l,e,i+1):l}function p0(n){const e=[{},{}];return n==null||n.values.forEach((i,a)=>{e[0][a]=i.get(),e[1][a]=i.getVelocity()}),e}function Lf(n,e,i,a){if(typeof e=="function"){const[l,c]=p0(a);e=e(i!==void 0?i:n.custom,l,c)}if(typeof e=="string"&&(e=n.variants&&n.variants[e]),typeof e=="function"){const[l,c]=p0(a);e=e(i!==void 0?i:n.custom,l,c)}return e}function Oi(n,e,i){const a=n.getProps();return Lf(a,e,i!==void 0?i:a.custom,n)}const lx=new Set(["width","height","top","left","right","bottom",...$a]),$d=n=>Array.isArray(n);function IT(n,e,i){n.hasValue(e)?n.getValue(e).set(i):n.addValue(e,Ha(i))}function FT(n){return $d(n)?n[n.length-1]||0:n}function GT(n,e){const i=Oi(n,e);let{transitionEnd:a={},transition:l={},...c}=i||{};c={...c,...a};for(const u in c){const d=FT(c[u]);IT(n,u,d)}}const kt=n=>!!(n&&n.getVelocity);function KT(n){return!!(kt(n)&&n.add)}function Id(n,e){const i=n.getValue("willChange");if(KT(i))return i.add(e);if(!i&&ti.WillChange){const a=new ti.WillChange("auto");n.addValue("willChange",a),a.add(e)}}function zf(n){return n.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const YT="framerAppearId",cx="data-"+zf(YT);function ux(n){return n.props[cx]}function XT({protectedKeys:n,needsAnimating:e},i){const a=n.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,a}function hx(n,e,{delay:i=0,transitionOverride:a,type:l}={}){let{transition:c,transitionEnd:u,...d}=e;const m=n.getDefaultTransition();c=c?rx(c,m):m;const p=c==null?void 0:c.reduceMotion,y=c==null?void 0:c.skipAnimations;a&&(c=a);const v=[],x=l&&n.animationState&&n.animationState.getState()[l],_=c==null?void 0:c.path;_&&_.animateVisualElement(n,d,c,i,v);for(const S in d){const E=n.getValue(S,n.latestValues[S]??null),R=d[S];if(R===void 0||x&&XT(x,S))continue;const N={delay:i,...Bf(c||{},S)};y&&(N.skipAnimations=!0);const O=E.get();if(O!==void 0&&!E.isAnimating()&&!Array.isArray(R)&&R===O&&!N.velocity){Fe.update(()=>E.set(R));continue}let C=!1;if(window.MotionHandoffAnimation){const X=ux(n);if(X){const q=window.MotionHandoffAnimation(X,S,Fe);q!==null&&(N.startTime=q,C=!0)}}Id(n,S);const P=p??n.shouldReduceMotion;E.start(Uf(S,E,R,P&&lx.has(S)?{type:!1}:N,n,C));const Y=E.animation;Y&&v.push(Y)}if(u){const S=()=>Fe.update(()=>{u&>(n,u)});v.length?Promise.all(v).then(S):S()}return v}function Fd(n,e,i={}){var m;const a=Oi(n,e,i.type==="exit"?(m=n.presenceContext)==null?void 0:m.custom:void 0);let{transition:l=n.getDefaultTransition()||{}}=a||{};i.transitionOverride&&(l=i.transitionOverride);const c=a?()=>Promise.all(hx(n,a,i)):()=>Promise.resolve(),u=n.variantChildren&&n.variantChildren.size?(p=0)=>{const{delayChildren:y=0,staggerChildren:v,staggerDirection:x}=l;return JT(n,e,p,y,v,x,i)}:()=>Promise.resolve(),{when:d}=l;if(d){const[p,y]=d==="beforeChildren"?[c,u]:[u,c];return p().then(()=>y())}else return Promise.all([c(),u(i.delay)])}function JT(n,e,i=0,a=0,l=0,c=1,u){const d=[];for(const m of n.variantChildren)m.notify("AnimationStart",e),d.push(Fd(m,e,{...u,delay:i+(typeof a=="function"?0:a)+ax(n.variantChildren,m,a,l,c)}).then(()=>m.notify("AnimationComplete",e)));return Promise.all(d)}function QT(n,e,i={}){n.notify("AnimationStart",e);let a;if(Array.isArray(e)){const l=e.map(c=>Fd(n,c,i));a=Promise.all(l)}else if(typeof e=="string")a=Fd(n,e,i);else{const l=typeof e=="function"?Oi(n,e,i.custom):e;a=Promise.all(hx(n,l,i))}return a.then(()=>{n.notify("AnimationComplete",e)})}const ZT={test:n=>n==="auto",parse:n=>n},dx=n=>e=>e.test(n),fx=[qa,re,Jn,_s,T1,S1,ZT],g0=n=>fx.find(dx(n));function WT(n){return typeof n=="number"?n===0:n!==null?n==="none"||n==="0"||Tv(n):!0}const eE=new Set(["brightness","contrast","saturate","opacity"]);function tE(n){const[e,i]=n.slice(0,-1).split("(");if(e==="drop-shadow")return n;const[a]=i.match(Rf)||[];if(!a)return n;const l=i.replace(a,"");let c=eE.has(e)?1:0;return a!==i&&(c*=100),e+"("+c+l+")"}const nE=/\b([a-z-]*)\(.*?\)/gu,Gd={...Ln,getAnimatableNone:n=>{const e=n.match(nE);return e?e.map(tE).join(" "):n}},Kd={...Ln,getAnimatableNone:n=>{const e=Ln.parse(n);return Ln.createTransformer(n)(e.map(a=>typeof a=="number"?0:typeof a=="object"?{...a,alpha:1}:a))}},y0={...qa,transform:Math.round},sE={rotate:_s,pathRotation:_s,rotateX:_s,rotateY:_s,rotateZ:_s,scale:Ll,scaleX:Ll,scaleY:Ll,scaleZ:Ll,skew:_s,skewX:_s,skewY:_s,distance:re,translateX:re,translateY:re,translateZ:re,x:re,y:re,z:re,perspective:re,transformPerspective:re,opacity:no,originX:s0,originY:s0,originZ:re},pc={borderWidth:re,borderTopWidth:re,borderRightWidth:re,borderBottomWidth:re,borderLeftWidth:re,borderRadius:re,borderTopLeftRadius:re,borderTopRightRadius:re,borderBottomRightRadius:re,borderBottomLeftRadius:re,width:re,maxWidth:re,height:re,maxHeight:re,top:re,right:re,bottom:re,left:re,inset:re,insetBlock:re,insetBlockStart:re,insetBlockEnd:re,insetInline:re,insetInlineStart:re,insetInlineEnd:re,padding:re,paddingTop:re,paddingRight:re,paddingBottom:re,paddingLeft:re,paddingBlock:re,paddingBlockStart:re,paddingBlockEnd:re,paddingInline:re,paddingInlineStart:re,paddingInlineEnd:re,margin:re,marginTop:re,marginRight:re,marginBottom:re,marginLeft:re,marginBlock:re,marginBlockStart:re,marginBlockEnd:re,marginInline:re,marginInlineStart:re,marginInlineEnd:re,fontSize:re,backgroundPositionX:re,backgroundPositionY:re,...sE,zIndex:y0,fillOpacity:no,strokeOpacity:no,numOctaves:y0},iE={...pc,color:yt,backgroundColor:yt,outlineColor:yt,fill:yt,stroke:yt,borderColor:yt,borderTopColor:yt,borderRightColor:yt,borderBottomColor:yt,borderLeftColor:yt,filter:Gd,WebkitFilter:Gd,mask:Kd,WebkitMask:Kd},mx=n=>iE[n],aE=new Set([Gd,Kd]);function px(n,e){let i=mx(n);return aE.has(i)||(i=Ln),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const rE=new Set(["auto","none","0"]);function oE(n,e,i){let a=0,l;for(;a{e.getValue(m).set(p)}),this.resolveNoneKeyframes()}}const Vf=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function gx(n,e,i){if(n==null)return[];if(n instanceof EventTarget)return[n];if(typeof n=="string"){let a=document;const l=(i==null?void 0:i[n])??a.querySelectorAll(n);return l?Array.from(l):[]}return Array.from(n).filter(a=>a!=null)}const Yd=(n,e)=>e&&typeof n=="number"?e.transform(n):n;function nc(n){return Sv(n)&&"offsetHeight"in n&&!("ownerSVGElement"in n)}const{schedule:Pf}=Lv(queueMicrotask,!1),On={x:!1,y:!1};function yx(){return On.x||On.y}function cE(n){return n==="x"||n==="y"?On[n]?null:(On[n]=!0,()=>{On[n]=!1}):On.x||On.y?null:(On.x=On.y=!0,()=>{On.x=On.y=!1})}function bx(n,e){const i=gx(n),a=new AbortController,l={passive:!0,...e,signal:a.signal};return[i,l,()=>a.abort()]}function uE(n){return!(n.pointerType==="touch"||yx())}function hE(n,e,i={}){const[a,l,c]=bx(n,i);return a.forEach(u=>{let d=!1,m=!1,p;const y=()=>{u.removeEventListener("pointerleave",S)},v=R=>{p&&(p(R),p=void 0),y()},x=R=>{d=!1,window.removeEventListener("pointerup",x),window.removeEventListener("pointercancel",x),m&&(m=!1,v(R))},_=()=>{d=!0,window.addEventListener("pointerup",x,l),window.addEventListener("pointercancel",x,l)},S=R=>{if(R.pointerType!=="touch"){if(d){m=!0;return}v(R)}},E=R=>{if(!uE(R))return;m=!1;const N=e(u,R);typeof N=="function"&&(p=N,u.addEventListener("pointerleave",S,l))};u.addEventListener("pointerenter",E,l),u.addEventListener("pointerdown",_,l)}),c}const vx=(n,e)=>e?n===e?!0:vx(n,e.parentElement):!1,Hf=n=>n.pointerType==="mouse"?typeof n.button!="number"||n.button<=0:n.isPrimary!==!1,dE=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function fE(n){return dE.has(n.tagName)||n.isContentEditable===!0}const mE=new Set(["INPUT","SELECT","TEXTAREA"]);function pE(n){return mE.has(n.tagName)||n.isContentEditable===!0}const sc=new WeakSet;function b0(n){return e=>{e.key==="Enter"&&n(e)}}function cd(n,e){n.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const gE=(n,e)=>{const i=n.currentTarget;if(!i)return;const a=b0(()=>{if(sc.has(i))return;cd(i,"down");const l=b0(()=>{cd(i,"up")}),c=()=>cd(i,"cancel");i.addEventListener("keyup",l,e),i.addEventListener("blur",c,e)});i.addEventListener("keydown",a,e),i.addEventListener("blur",()=>i.removeEventListener("keydown",a),e)};function v0(n){return Hf(n)&&!yx()}const x0=new WeakSet;function yE(n,e,i={}){const[a,l,c]=bx(n,i),u=d=>{const m=d.currentTarget;if(!v0(d)||x0.has(d))return;sc.add(m),i.stopPropagation&&x0.add(d);const p=e(m,d),y={...l,capture:!0},v=(S,E)=>{window.removeEventListener("pointerup",x,y),window.removeEventListener("pointercancel",_,y),sc.has(m)&&sc.delete(m),v0(S)&&typeof p=="function"&&p(S,{success:E})},x=S=>{v(S,m===window||m===document||i.useGlobalTarget||vx(m,S.target))},_=S=>{v(S,!1)};window.addEventListener("pointerup",x,y),window.addEventListener("pointercancel",_,y)};return a.forEach(d=>{(i.useGlobalTarget?window:d).addEventListener("pointerdown",u,l),nc(d)&&(d.addEventListener("focus",p=>gE(p,l)),!fE(d)&&!d.hasAttribute("tabindex")&&(d.tabIndex=0))}),c}function qf(n){return Sv(n)&&"ownerSVGElement"in n}const ic=new WeakMap;let Js;const xx=(n,e,i)=>(a,l)=>l&&l[0]?l[0][n+"Size"]:qf(a)&&"getBBox"in a?a.getBBox()[e]:a[i],bE=xx("inline","width","offsetWidth"),vE=xx("block","height","offsetHeight");function xE({target:n,borderBoxSize:e}){var i;(i=ic.get(n))==null||i.forEach(a=>{a(n,{get width(){return bE(n,e)},get height(){return vE(n,e)}})})}function wE(n){n.forEach(xE)}function _E(){typeof ResizeObserver>"u"||(Js=new ResizeObserver(wE))}function SE(n,e){Js||_E();const i=gx(n);return i.forEach(a=>{let l=ic.get(a);l||(l=new Set,ic.set(a,l)),l.add(e),Js==null||Js.observe(a)}),()=>{i.forEach(a=>{const l=ic.get(a);l==null||l.delete(e),l!=null&&l.size||Js==null||Js.unobserve(a)})}}const ac=new Set;let Ma;function TE(){Ma=()=>{const n={get width(){return window.innerWidth},get height(){return window.innerHeight}};ac.forEach(e=>e(n))},window.addEventListener("resize",Ma)}function EE(n){return ac.add(n),Ma||TE(),()=>{ac.delete(n),!ac.size&&typeof Ma=="function"&&(window.removeEventListener("resize",Ma),Ma=void 0)}}function w0(n,e){return typeof n=="function"?EE(n):SE(n,e)}function AE(n){return qf(n)&&n.tagName==="svg"}const jE=[...fx,yt,Ln],CE=n=>jE.find(dx(n)),_0=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ba=()=>({x:_0(),y:_0()}),S0=()=>({min:0,max:0}),xt=()=>({x:S0(),y:S0()}),RE=new WeakMap;function Oc(n){return n!==null&&typeof n=="object"&&typeof n.start=="function"}function so(n){return typeof n=="string"||Array.isArray(n)}const $f=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],If=["initial",...$f];function Dc(n){return Oc(n.animate)||If.some(e=>so(n[e]))}function wx(n){return!!(Dc(n)||n.variants)}function NE(n,e,i){for(const a in e){const l=e[a],c=i[a];if(kt(l))n.addValue(a,l);else if(kt(c))n.addValue(a,Ha(l,{owner:n}));else if(c!==l)if(n.hasValue(a)){const u=n.getValue(a);u.liveStyle===!0?u.jump(l):u.hasAnimated||u.set(l)}else{const u=n.getStaticValue(a);n.addValue(a,Ha(u!==void 0?u:l,{owner:n}))}}for(const a in i)e[a]===void 0&&n.removeValue(a);return e}const Xd={current:null},_x={current:!1},kE=typeof window<"u";function OE(){if(_x.current=!0,!!kE)if(window.matchMedia){const n=window.matchMedia("(prefers-reduced-motion)"),e=()=>Xd.current=n.matches;n.addEventListener("change",e),e()}else Xd.current=!1}const T0=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let gc={};function Sx(n){gc=n}function DE(){return gc}class ME{scrapeMotionValuesFromProps(e,i,a){return{}}constructor({parent:e,props:i,presenceContext:a,reducedMotionConfig:l,skipAnimations:c,blockInitialAnimation:u,visualState:d},m={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=Mf,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,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 _=zt.now();this.renderScheduledAt<_&&(this.renderScheduledAt=_,Fe.render(this.render,!1,!0))};const{latestValues:p,renderState:y}=d;this.latestValues=p,this.baseTarget={...p},this.initialValues=i.initial?{...p}:{},this.renderState=y,this.parent=e,this.props=i,this.presenceContext=a,this.depth=e?e.depth+1:0,this.reducedMotionConfig=l,this.skipAnimationsConfig=c,this.options=m,this.blockInitialAnimation=!!u,this.isControllingVariants=Dc(i),this.isVariantNode=wx(i),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:v,...x}=this.scrapeMotionValuesFromProps(i,{},this);for(const _ in x){const S=x[_];p[_]!==void 0&&kt(S)&&S.set(p[_])}}mount(e){var i,a;if(this.hasBeenMounted)for(const l in this.initialValues)(i=this.values.get(l))==null||i.jump(this.initialValues[l]),this.latestValues[l]=this.initialValues[l];this.current=e,RE.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((l,c)=>this.bindToMotionValue(c,l)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(_x.current||OE(),this.shouldReduceMotion=Xd.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){var e;this.projection&&this.projection.unmount(),ni(this.notifyUpdate),ni(this.render),this.valueSubscriptions.forEach(i=>i()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(e=this.parent)==null||e.removeChild(this);for(const i in this.events)this.events[i].clear();for(const i in this.features){const a=this.features[i];a&&(a.unmount(),a.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,i){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),i.accelerate&&ix.has(e)&&this.current instanceof HTMLElement){const{factory:u,keyframes:d,times:m,ease:p,duration:y}=i.accelerate,v=new nx({element:this.current,name:e,keyframes:d,times:m,ease:p,duration:hn(y)}),x=u(v);this.valueSubscriptions.set(e,()=>{x(),v.cancel()});return}const a=Ia.has(e);a&&this.onBindTransform&&this.onBindTransform();const l=i.on("change",u=>{this.latestValues[e]=u,this.props.onUpdate&&Fe.preRender(this.notifyUpdate),a&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let c;typeof window<"u"&&window.MotionCheckAppearSync&&(c=window.MotionCheckAppearSync(this,e,i)),this.valueSubscriptions.set(e,()=>{l(),c&&c()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in gc){const i=gc[e];if(!i)continue;const{isEnabled:a,Feature:l}=i;if(!this.features[e]&&l&&a(this.props)&&(this.features[e]=new l(this)),this.features[e]){const c=this.features[e];c.isMounted?c.update():(c.mount(),c.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):xt()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,i){this.latestValues[e]=i}update(e,i){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=i;for(let a=0;ai.variantChildren.delete(e)}addValue(e,i){const a=this.values.get(e);i!==a&&(a&&this.removeValue(e),this.bindToMotionValue(e,i),this.values.set(e,i),this.latestValues[e]=i.get())}removeValue(e){this.values.delete(e);const i=this.valueSubscriptions.get(e);i&&(i(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,i){if(this.props.values&&this.props.values[e])return this.props.values[e];let a=this.values.get(e);return a===void 0&&i!==void 0&&(a=Ha(i===null?void 0:i,{owner:this}),this.addValue(e,a)),a}readValue(e,i){let a=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return a!=null&&(typeof a=="string"&&(_v(a)||Tv(a))?a=parseFloat(a):!CE(a)&&Ln.test(i)&&(a=px(e,i)),this.setBaseTarget(e,kt(a)?a.get():a)),kt(a)?a.get():a}setBaseTarget(e,i){this.baseTarget[e]=i}getBaseTarget(e){var c;const{initial:i}=this.props;let a;if(typeof i=="string"||typeof i=="object"){const u=Lf(this.props,i,(c=this.presenceContext)==null?void 0:c.custom);u&&(a=u[e])}if(i&&a!==void 0)return a;const l=this.getBaseTargetFromProps(this.props,e);return l!==void 0&&!kt(l)?l:this.initialValues[e]!==void 0&&a===void 0?void 0:this.baseTarget[e]}on(e,i){return this.events[e]||(this.events[e]=new Ef),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}scheduleRenderMicrotask(){Pf.render(this.render)}}class Tx extends ME{constructor(){super(...arguments),this.KeyframeResolver=lE}sortInstanceNodePosition(e,i){return e.compareDocumentPosition(i)&2?1:-1}getBaseTargetFromProps(e,i){const a=e.style;return a?a[i]:void 0}removeValueFromRenderState(e,{vars:i,style:a}){delete i[e],delete a[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;kt(e)&&(this.childSubscription=e.on("change",i=>{this.current&&(this.current.textContent=`${i}`)}))}}class si{constructor(e){this.isMounted=!1,this.node=e}update(){}}function Ex({top:n,left:e,right:i,bottom:a}){return{x:{min:e,max:i},y:{min:n,max:a}}}function BE({x:n,y:e}){return{top:e.min,right:n.max,bottom:e.max,left:n.min}}function UE(n,e){if(!e)return n;const i=e({x:n.left,y:n.top}),a=e({x:n.right,y:n.bottom});return{top:i.y,left:i.x,bottom:a.y,right:a.x}}function ud(n){return n===void 0||n===1}function Jd({scale:n,scaleX:e,scaleY:i}){return!ud(n)||!ud(e)||!ud(i)}function Ai(n){return Jd(n)||Ax(n)||n.z||n.rotate||n.rotateX||n.rotateY||n.skewX||n.skewY}function Ax(n){return E0(n.x)||E0(n.y)}function E0(n){return n&&n!=="0%"}function yc(n,e,i){const a=n-i,l=e*a;return i+l}function A0(n,e,i,a,l){return l!==void 0&&(n=yc(n,l,a)),yc(n,i,a)+e}function Qd(n,e=0,i=1,a,l){n.min=A0(n.min,e,i,a,l),n.max=A0(n.max,e,i,a,l)}function jx(n,{x:e,y:i}){Qd(n.x,e.translate,e.scale,e.originPoint),Qd(n.y,i.translate,i.scale,i.originPoint)}const j0=.999999999999,C0=1.0000000000001;function LE(n,e,i,a=!1){var d;const l=i.length;if(!l)return;e.x=e.y=1;let c,u;for(let m=0;mj0&&(e.x=1),e.yj0&&(e.y=1)}function Yn(n,e){n.min+=e,n.max+=e}function R0(n,e,i,a,l=.5){const c=Ie(n.min,n.max,l);Qd(n,e,i,c,a)}function N0(n,e){return typeof n=="string"?parseFloat(n)/100*(e.max-e.min):n}function rc(n,e,i){const a=i??n;R0(n.x,N0(e.x,a.x),e.scaleX,e.scale,e.originX),R0(n.y,N0(e.y,a.y),e.scaleY,e.scale,e.originY)}function Cx(n,e){return Ex(UE(n.getBoundingClientRect(),e))}function zE(n,e,i){const a=Cx(n,i),{scroll:l}=e;return l&&(Yn(a.x,l.offset.x),Yn(a.y,l.offset.y)),a}const VE={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},PE=$a.length;function HE(n,e,i){let a="",l=!0;for(let u=0;u{if(!e.target)return n;if(typeof n=="string")if(re.test(n))n=parseFloat(n);else return n;const i=k0(n,e.target.x),a=k0(n,e.target.y);return`${i}% ${a}%`}},qE={correct:(n,{treeScale:e,projectionDelta:i})=>{const a=n,l=Ln.parse(n);if(l.length>5)return a;const c=Ln.createTransformer(n),u=typeof l[0]!="number"?1:0,d=i.x.scale*e.x,m=i.y.scale*e.y;l[0+u]/=d,l[1+u]/=m;const p=Ie(d,m,.5);return typeof l[2+u]=="number"&&(l[2+u]/=p),typeof l[3+u]=="number"&&(l[3+u]/=p),c(l)}},Zd={borderRadius:{...zr,applyTo:[...Vf]},borderTopLeftRadius:zr,borderTopRightRadius:zr,borderBottomLeftRadius:zr,borderBottomRightRadius:zr,boxShadow:qE};function Nx(n,{layout:e,layoutId:i}){return Ia.has(n)||n.startsWith("origin")||(e||i!==void 0)&&(!!Zd[n]||n==="opacity")}function Gf(n,e,i){var u;const a=n.style,l=e==null?void 0:e.style,c={};if(!a)return c;for(const d in a)(kt(a[d])||l&&kt(l[d])||Nx(d,n)||((u=i==null?void 0:i.getValue(d))==null?void 0:u.liveStyle)!==void 0)&&(c[d]=a[d]);return c}function $E(n){return window.getComputedStyle(n)}class IE extends Tx{constructor(){super(...arguments),this.type="html",this.renderInstance=Rx}readValueFromInstance(e,i){var a;if(Ia.has(i))return(a=this.projection)!=null&&a.isProjecting?Ld(i):uT(e,i);{const l=$E(e),c=(Vv(i)?l.getPropertyValue(i):l[i])||0;return typeof c=="string"?c.trim():c}}measureInstanceViewportBox(e,{transformPagePoint:i}){return Cx(e,i)}build(e,i,a){Ff(e,i,a.transformTemplate)}scrapeMotionValuesFromProps(e,i,a){return Gf(e,i,a)}}const FE={offset:"stroke-dashoffset",array:"stroke-dasharray"},GE={offset:"strokeDashoffset",array:"strokeDasharray"};function KE(n,e,i=1,a=0,l=!0){n.pathLength=1;const c=l?FE:GE;n[c.offset]=`${-a}`,n[c.array]=`${e} ${i}`}const YE=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function kx(n,{attrX:e,attrY:i,attrScale:a,pathLength:l,pathSpacing:c=1,pathOffset:u=0,...d},m,p,y){if(Ff(n,d,p),m){n.style.viewBox&&(n.attrs.viewBox=n.style.viewBox);return}n.attrs=n.style,n.style={};const{attrs:v,style:x}=n;v.transform&&(x.transform=v.transform,delete v.transform),(x.transform||v.transformOrigin)&&(x.transformOrigin=v.transformOrigin??"50% 50%",delete v.transformOrigin),x.transform&&(x.transformBox=(y==null?void 0:y.transformBox)??"fill-box",delete v.transformBox);for(const _ of YE)v[_]!==void 0&&(x[_]=v[_],delete v[_]);e!==void 0&&(v.x=e),i!==void 0&&(v.y=i),a!==void 0&&(v.scale=a),l!==void 0&&KE(v,l,c,u,!1)}const Ox=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"]),Dx=n=>typeof n=="string"&&n.toLowerCase()==="svg";function XE(n,e,i,a){Rx(n,e,void 0,a);for(const l in e.attrs)n.setAttribute(Ox.has(l)?l:zf(l),e.attrs[l])}function Mx(n,e,i){const a=Gf(n,e,i);for(const l in n)if(kt(n[l])||kt(e[l])){const c=$a.indexOf(l)!==-1?"attr"+l.charAt(0).toUpperCase()+l.substring(1):l;a[c]=n[l]}return a}class JE extends Tx{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=xt}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(Ia.has(i)){const a=mx(i);return a&&a.default||0}return i=Ox.has(i)?i:zf(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,a){return Mx(e,i,a)}build(e,i,a){kx(e,i,this.isSVGTag,a.transformTemplate,a.style)}renderInstance(e,i,a,l){XE(e,i,a,l)}mount(e){this.isSVGTag=Dx(e.tagName),super.mount(e)}}const QE=If.length;function Bx(n){if(!n)return;if(!n.isControllingVariants){const i=n.parent?Bx(n.parent)||{}:{};return n.props.initial!==void 0&&(i.initial=n.props.initial),i}const e={};for(let i=0;iPromise.all(e.map(({animation:i,options:a})=>QT(n,i,a)))}function tA(n){let e=eA(n),i=O0(),a=!0,l=!1;const c=p=>(y,v)=>{var _;const x=Oi(n,v,p==="exit"?(_=n.presenceContext)==null?void 0:_.custom:void 0);if(x){const{transition:S,transitionEnd:E,...R}=x;y={...y,...R,...E}}return y};function u(p){e=p(n)}function d(p){const{props:y}=n,v=Bx(n.parent)||{},x=[],_=new Set;let S={},E=1/0;for(let N=0;NE&&Y,Q=!1;const le=Array.isArray(P)?P:[P];let he=le.reduce(c(O),{});X===!1&&(he={});const{prevResolvedValues:Ge={}}=C,Ne={...Ge,...he},xe=K=>{te=!0,_.has(K)&&(Q=!0,_.delete(K)),C.needsAnimating[K]=!0;const ie=n.getValue(K);ie&&(ie.liveStyle=!1)};for(const K in Ne){const ie=he[K],ue=Ge[K];if(S.hasOwnProperty(K))continue;let A=!1;$d(ie)&&$d(ue)?A=!Ux(ie,ue)||Z:A=ie!==ue,A?ie!=null?xe(K):_.add(K):ie!==void 0&&_.has(K)?xe(K):C.protectedKeys[K]=!0}C.prevProp=P,C.prevResolvedValues=he,C.isActive&&(S={...S,...he}),(a||l)&&n.blockInitialAnimation&&(te=!1);const z=q&&Z;te&&(!z||Q)&&x.push(...le.map(K=>{const ie={type:O};if(typeof K=="string"&&(a||l)&&!z&&n.manuallyAnimateOnMount&&n.parent){const{parent:ue}=n,A=Oi(ue,K);if(ue.enteringChildren&&A){const{delayChildren:H}=A.transition||{};ie.delay=ax(ue.enteringChildren,n,H)}}return{animation:K,options:ie}}))}if(_.size){const N={};if(typeof y.initial!="boolean"){const O=Oi(n,Array.isArray(y.initial)?y.initial[0]:y.initial);O&&O.transition&&(N.transition=O.transition)}_.forEach(O=>{const C=n.getBaseTarget(O),P=n.getValue(O);P&&(P.liveStyle=!0),N[O]=C??null}),x.push({animation:N})}let R=!!x.length;return a&&(y.initial===!1||y.initial===y.animate)&&!n.manuallyAnimateOnMount&&(R=!1),a=!1,l=!1,R?e(x):Promise.resolve()}function m(p,y){var x;if(i[p].isActive===y)return Promise.resolve();(x=n.variantChildren)==null||x.forEach(_=>{var S;return(S=_.animationState)==null?void 0:S.setActive(p,y)}),i[p].isActive=y;const v=d(p);for(const _ in i)i[_].protectedKeys={};return v}return{animateChanges:d,setActive:m,setAnimateFunction:u,getState:()=>i,reset:()=>{i=O0(),l=!0}}}function nA(n,e){return typeof e=="string"?e!==n:Array.isArray(e)?!Ux(e,n):!1}function Si(n=!1){return{isActive:n,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function O0(){return{animate:Si(!0),whileInView:Si(),whileHover:Si(),whileTap:Si(),whileDrag:Si(),whileFocus:Si(),exit:Si()}}function Wd(n,e){n.min=e.min,n.max=e.max}function Nn(n,e){Wd(n.x,e.x),Wd(n.y,e.y)}function D0(n,e){n.translate=e.translate,n.scale=e.scale,n.originPoint=e.originPoint,n.origin=e.origin}const Lx=1e-4,sA=1-Lx,iA=1+Lx,zx=.01,aA=0-zx,rA=0+zx;function Vt(n){return n.max-n.min}function oA(n,e,i){return Math.abs(n-e)<=i}function M0(n,e,i,a=.5){n.origin=a,n.originPoint=Ie(e.min,e.max,n.origin),n.scale=Vt(i)/Vt(e),n.translate=Ie(i.min,i.max,n.origin)-n.originPoint,(n.scale>=sA&&n.scale<=iA||isNaN(n.scale))&&(n.scale=1),(n.translate>=aA&&n.translate<=rA||isNaN(n.translate))&&(n.translate=0)}function Yr(n,e,i,a){M0(n.x,e.x,i.x,a?a.originX:void 0),M0(n.y,e.y,i.y,a?a.originY:void 0)}function B0(n,e,i,a=0){const l=a?Ie(i.min,i.max,a):i.min;n.min=l+e.min,n.max=n.min+Vt(e)}function lA(n,e,i,a){B0(n.x,e.x,i.x,a==null?void 0:a.x),B0(n.y,e.y,i.y,a==null?void 0:a.y)}function U0(n,e,i,a=0){const l=a?Ie(i.min,i.max,a):i.min;n.min=e.min-l,n.max=n.min+Vt(e)}function bc(n,e,i,a){U0(n.x,e.x,i.x,a==null?void 0:a.x),U0(n.y,e.y,i.y,a==null?void 0:a.y)}function L0(n,e,i,a,l){return n-=e,n=yc(n,1/i,a),l!==void 0&&(n=yc(n,1/l,a)),n}function cA(n,e=0,i=1,a=.5,l,c=n,u=n){if(Jn.test(e)&&(e=parseFloat(e),e=Ie(u.min,u.max,e/100)-u.min),typeof e!="number")return;let d=Ie(c.min,c.max,a);n===c&&(d-=e),n.min=L0(n.min,e,i,d,l),n.max=L0(n.max,e,i,d,l)}function z0(n,e,[i,a,l],c,u){cA(n,e[i],e[a],e[l],e.scale,c,u)}const uA=["x","scaleX","originX"],hA=["y","scaleY","originY"];function V0(n,e,i,a){z0(n.x,e,uA,i?i.x:void 0,a?a.x:void 0),z0(n.y,e,hA,i?i.y:void 0,a?a.y:void 0)}function P0(n){return n.translate===0&&n.scale===1}function Vx(n){return P0(n.x)&&P0(n.y)}function H0(n,e){return n.min===e.min&&n.max===e.max}function dA(n,e){return H0(n.x,e.x)&&H0(n.y,e.y)}function q0(n,e){return Math.round(n.min)===Math.round(e.min)&&Math.round(n.max)===Math.round(e.max)}function Px(n,e){return q0(n.x,e.x)&&q0(n.y,e.y)}function $0(n){return Vt(n.x)/Vt(n.y)}function I0(n,e){return n.translate===e.translate&&n.scale===e.scale&&n.originPoint===e.originPoint}function Gn(n){return[n("x"),n("y")]}function fA(n,e,i){let a="";const l=n.x.translate/e.x,c=n.y.translate/e.y,u=(i==null?void 0:i.z)||0;if((l||c||u)&&(a=`translate3d(${l}px, ${c}px, ${u}px) `),(e.x!==1||e.y!==1)&&(a+=`scale(${1/e.x}, ${1/e.y}) `),i){const{transformPerspective:p,rotate:y,pathRotation:v,rotateX:x,rotateY:_,skewX:S,skewY:E}=i;p&&(a=`perspective(${p}px) ${a}`),y&&(a+=`rotate(${y}deg) `),v&&(a+=`rotate(${v}deg) `),x&&(a+=`rotateX(${x}deg) `),_&&(a+=`rotateY(${_}deg) `),S&&(a+=`skewX(${S}deg) `),E&&(a+=`skewY(${E}deg) `)}const d=n.x.scale*e.x,m=n.y.scale*e.y;return(d!==1||m!==1)&&(a+=`scale(${d}, ${m})`),a||"none"}const mA=Vf.length,F0=n=>typeof n=="string"?parseFloat(n):n,G0=n=>typeof n=="number"||re.test(n);function pA(n,e,i,a,l,c){l?(n.opacity=Ie(0,i.opacity??1,gA(a)),n.opacityExit=Ie(e.opacity??1,0,yA(a))):c&&(n.opacity=Ie(e.opacity??1,i.opacity??1,a));for(let u=0;uae?1:i(to(n,e,a))}function bA(n,e,i){const a=kt(n)?n:Ha(n);return a.start(Uf("",a,e,i)),a.animation}function io(n,e,i,a={passive:!0}){return n.addEventListener(e,i,a),()=>n.removeEventListener(e,i,a)}const vA=(n,e)=>n.depth-e.depth;class xA{constructor(){this.children=[],this.isDirty=!1}add(e){Sf(this.children,e),this.isDirty=!0}remove(e){uc(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(vA),this.isDirty=!1,this.children.forEach(e)}}function wA(n,e){const i=zt.now(),a=({timestamp:l})=>{const c=l-i;c>=e&&(ni(a),n(c-e))};return Fe.setup(a,!0),()=>ni(a)}function oc(n){return kt(n)?n.get():n}class _A{constructor(){this.members=[]}add(e){Sf(this.members,e);for(let i=this.members.length-1;i>=0;i--){const a=this.members[i];if(a===e||a===this.lead||a===this.prevLead)continue;const l=a.instance;(!l||l.isConnected===!1)&&!a.snapshot&&(uc(this.members,a),a.unmount())}e.scheduleRender()}remove(e){if(uc(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const i=this.members[this.members.length-1];i&&this.promote(i)}}relegate(e){var i;for(let a=this.members.indexOf(e)-1;a>=0;a--){const l=this.members[a];if(l.isPresent!==!1&&((i=l.instance)==null?void 0:i.isConnected)!==!1)return this.promote(l),!0}return!1}promote(e,i){var l;const a=this.lead;if(e!==a&&(this.prevLead=a,this.lead=e,e.show(),a)){a.updateSnapshot(),e.scheduleRender();const{layoutDependency:c}=a.options,{layoutDependency:u}=e.options;(c===void 0||c!==u)&&(e.resumeFrom=a,i&&(a.preserveOpacity=!0),a.snapshot&&(e.snapshot=a.snapshot,e.snapshot.latestValues=a.animationValues||a.latestValues),(l=e.root)!=null&&l.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&a.hide()}}exitAnimationComplete(){this.members.forEach(e=>{var i,a,l,c,u;(a=(i=e.options).onExitComplete)==null||a.call(i),(u=(l=e.resumingFrom)==null?void 0:(c=l.options).onExitComplete)==null||u.call(c)})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){var e;(e=this.lead)!=null&&e.snapshot&&(this.lead.snapshot=void 0)}}const lc={hasAnimatedSinceResize:!0,hasEverUpdated:!1},hd=["","X","Y","Z"],SA=1e3;let TA=0;function dd(n,e,i,a){const{latestValues:l}=e;l[n]&&(i[n]=l[n],e.setStaticValue(n,0),a&&(a[n]=0))}function qx(n){if(n.hasCheckedOptimisedAppear=!0,n.root===n)return;const{visualElement:e}=n.options;if(!e)return;const i=ux(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:l,layoutId:c}=n.options;window.MotionCancelOptimisedAnimation(i,"transform",Fe,!(l||c))}const{parent:a}=n;a&&!a.hasCheckedOptimisedAppear&&qx(a)}function $x({attachResizeListener:n,defaultParent:e,measureScroll:i,checkIsScrollRoot:a,resetTransform:l}){return class{constructor(u={},d=e==null?void 0:e()){this.id=TA++,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.layoutVersion=0,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(jA),this.nodes.forEach(DA),this.nodes.forEach(MA),this.nodes.forEach(CA)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=u,this.root=d?d.root||d:this,this.path=d?[...d.path,d]:[],this.parent=d,this.depth=d?d.depth+1:0;for(let m=0;mthis.root.updateBlockedByResize=!1;Fe.read(()=>{v=window.innerWidth}),n(u,()=>{const _=window.innerWidth;_!==v&&(v=_,this.root.updateBlockedByResize=!0,y&&y(),y=wA(x,250),lc.hasAnimatedSinceResize&&(lc.hasAnimatedSinceResize=!1,this.nodes.forEach(J0)))})}d&&this.root.registerSharedNode(d,this),this.options.animate!==!1&&p&&(d||m)&&this.addEventListener("didUpdate",({delta:y,hasLayoutChanged:v,hasRelativeLayoutChanged:x,layout:_})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const S=this.options.transition||p.getDefaultTransition()||VA,{onLayoutAnimationStart:E,onLayoutAnimationComplete:R}=p.getProps(),N=!this.targetLayout||!Px(this.targetLayout,_),O=!v&&x;if(this.options.layoutRoot||this.resumeFrom||O||v&&(N||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const C={...Bf(S,"layout"),onPlay:E,onComplete:R};(p.shouldReduceMotion||this.options.layoutRoot)&&(C.delay=0,C.type=!1),this.startAnimation(C),this.setAnimationOrigin(y,O,C.path)}else v||J0(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=_})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const u=this.getStack();u&&u.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),ni(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(BA),this.animationId++)}getTransformTemplate(){const{visualElement:u}=this.options;return u&&u.getProps().transformTemplate}willUpdate(u=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&qx(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let y=0;y{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Vt(this.snapshot.measuredBox.x)&&!Vt(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 m=0;m{const q=X/1e3,Z=Y==null?void 0:Y(q);Z?(x.x.translate=Z.x,x.x.scale=Ie(u.x.scale,1,q),x.x.origin=u.x.origin,x.x.originPoint=u.x.originPoint,x.y.translate=Z.y,x.y.scale=Ie(u.y.scale,1,q),x.y.origin=u.y.origin,x.y.originPoint=u.y.originPoint):(Q0(x.x,u.x,q),Q0(x.y,u.y,q)),this.setTargetDelta(x),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(bc(_,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),LA(this.relativeTarget,this.relativeTargetOrigin,_,q),P&&dA(this.relativeTarget,P)&&(this.isProjectionDirty=!1),P||(P=xt()),Nn(P,this.relativeTarget)),R&&(this.animationValues=v,pA(v,y,this.latestValues,q,C,O)),Z&&Z.rotate!==void 0&&(this.animationValues||(this.animationValues=v),this.animationValues.pathRotation=Z.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=q},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(u){var d,m,p;this.notifyListeners("animationStart"),(d=this.currentAnimation)==null||d.stop(),(p=(m=this.resumingFrom)==null?void 0:m.currentAnimation)==null||p.stop(),this.pendingAnimation&&(ni(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Fe.update(()=>{lc.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Ha(0)),this.motionValue.jump(0,!1),this.currentAnimation=bA(this.motionValue,[0,1e3],{...u,velocity:0,isSync:!0,onUpdate:y=>{this.mixTargetDelta(y),u.onUpdate&&u.onUpdate(y)},onComplete:()=>{u.onComplete&&u.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 u=this.getStack();u&&u.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(SA),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const u=this.getLead();let{targetWithTransforms:d,target:m,layout:p,latestValues:y}=u;if(!(!d||!m||!p)){if(this!==u&&this.layout&&p&&Ix(this.options.animationType,this.layout.layoutBox,p.layoutBox)){m=this.target||xt();const v=Vt(this.layout.layoutBox.x);m.x.min=u.target.x.min,m.x.max=m.x.min+v;const x=Vt(this.layout.layoutBox.y);m.y.min=u.target.y.min,m.y.max=m.y.min+x}Nn(d,m),rc(d,y),Yr(this.projectionDeltaWithTransform,this.layoutCorrected,d,y)}}registerSharedNode(u,d){this.sharedNodes.has(u)||this.sharedNodes.set(u,new _A),this.sharedNodes.get(u).add(d);const p=d.options.initialPromotionConfig;d.promote({transition:p?p.transition:void 0,preserveFollowOpacity:p&&p.shouldPreserveFollowOpacity?p.shouldPreserveFollowOpacity(d):void 0})}isLead(){const u=this.getStack();return u?u.lead===this:!0}getLead(){var d;const{layoutId:u}=this.options;return u?((d=this.getStack())==null?void 0:d.lead)||this:this}getPrevLead(){var d;const{layoutId:u}=this.options;return u?(d=this.getStack())==null?void 0:d.prevLead:void 0}getStack(){const{layoutId:u}=this.options;if(u)return this.root.sharedNodes.get(u)}promote({needsReset:u,transition:d,preserveFollowOpacity:m}={}){const p=this.getStack();p&&p.promote(this,m),u&&(this.projectionDelta=void 0,this.needsReset=!0),d&&this.setOptions({transition:d})}relegate(){const u=this.getStack();return u?u.relegate(this):!1}resetSkewAndRotation(){const{visualElement:u}=this.options;if(!u)return;let d=!1;const{latestValues:m}=u;if((m.z||m.rotate||m.rotateX||m.rotateY||m.rotateZ||m.skewX||m.skewY)&&(d=!0),!d)return;const p={};m.z&&dd("z",u,p,this.animationValues);for(let y=0;y{var d;return(d=u.currentAnimation)==null?void 0:d.stop()}),this.root.nodes.forEach(Y0),this.root.sharedNodes.clear()}}}function EA(n){n.updateLayout()}function AA(n){var i;const e=((i=n.resumeFrom)==null?void 0:i.snapshot)||n.snapshot;if(n.isLead()&&n.layout&&e&&n.hasListeners("didUpdate")){const{layoutBox:a,measuredBox:l}=n.layout,{animationType:c}=n.options,u=e.source!==n.layout.source;if(c==="size")Gn(v=>{const x=u?e.measuredBox[v]:e.layoutBox[v],_=Vt(x);x.min=a[v].min,x.max=x.min+_});else if(c==="x"||c==="y"){const v=c==="x"?"y":"x";Wd(u?e.measuredBox[v]:e.layoutBox[v],a[v])}else Ix(c,e.layoutBox,a)&&Gn(v=>{const x=u?e.measuredBox[v]:e.layoutBox[v],_=Vt(a[v]);x.max=x.min+_,n.relativeTarget&&!n.currentAnimation&&(n.isProjectionDirty=!0,n.relativeTarget[v].max=n.relativeTarget[v].min+_)});const d=Ba();Yr(d,a,e.layoutBox);const m=Ba();u?Yr(m,n.applyTransform(l,!0),e.measuredBox):Yr(m,a,e.layoutBox);const p=!Vx(d);let y=!1;if(!n.resumeFrom){const v=n.getClosestProjectingParent();if(v&&!v.resumeFrom){const{snapshot:x,layout:_}=v;if(x&&_){const S=n.options.layoutAnchor||void 0,E=xt();bc(E,e.layoutBox,x.layoutBox,S);const R=xt();bc(R,a,_.layoutBox,S),Px(E,R)||(y=!0),v.options.layoutRoot&&(n.relativeTarget=R,n.relativeTargetOrigin=E,n.relativeParent=v)}}}n.notifyListeners("didUpdate",{layout:a,snapshot:e,delta:m,layoutDelta:d,hasLayoutChanged:p,hasRelativeLayoutChanged:y})}else if(n.isLead()){const{onExitComplete:a}=n.options;a&&a()}n.options.transition=void 0}function jA(n){n.parent&&(n.isProjecting()||(n.isProjectionDirty=n.parent.isProjectionDirty),n.isSharedProjectionDirty||(n.isSharedProjectionDirty=!!(n.isProjectionDirty||n.parent.isProjectionDirty||n.parent.isSharedProjectionDirty)),n.isTransformDirty||(n.isTransformDirty=n.parent.isTransformDirty))}function CA(n){n.isProjectionDirty=n.isSharedProjectionDirty=n.isTransformDirty=!1}function RA(n){n.clearSnapshot()}function Y0(n){n.clearMeasurements()}function NA(n){n.isLayoutDirty=!0,n.updateLayout()}function X0(n){n.isLayoutDirty=!1}function kA(n){n.isAnimationBlocked&&n.layout&&!n.isLayoutDirty&&(n.snapshot=n.layout,n.isLayoutDirty=!0)}function OA(n){const{visualElement:e}=n.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),n.resetTransform()}function J0(n){n.finishAnimation(),n.targetDelta=n.relativeTarget=n.target=void 0,n.isProjectionDirty=!0}function DA(n){n.resolveTargetDelta()}function MA(n){n.calcProjection()}function BA(n){n.resetSkewAndRotation()}function UA(n){n.removeLeadSnapshot()}function Q0(n,e,i){n.translate=Ie(e.translate,0,i),n.scale=Ie(e.scale,1,i),n.origin=e.origin,n.originPoint=e.originPoint}function Z0(n,e,i,a){n.min=Ie(e.min,i.min,a),n.max=Ie(e.max,i.max,a)}function LA(n,e,i,a){Z0(n.x,e.x,i.x,a),Z0(n.y,e.y,i.y,a)}function zA(n){return n.animationValues&&n.animationValues.opacityExit!==void 0}const VA={duration:.45,ease:[.4,0,.1,1]},W0=n=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(n),eb=W0("applewebkit/")&&!W0("chrome/")?Math.round:En;function tb(n){n.min=eb(n.min),n.max=eb(n.max)}function PA(n){tb(n.x),tb(n.y)}function Ix(n,e,i){return n==="position"||n==="preserve-aspect"&&!oA($0(e),$0(i),.2)}function HA(n){var e;return n!==n.root&&((e=n.scroll)==null?void 0:e.wasRoot)}const qA=$x({attachResizeListener:(n,e)=>io(n,"resize",e),measureScroll:()=>{var n,e;return{x:document.documentElement.scrollLeft||((n=document.body)==null?void 0:n.scrollLeft)||0,y:document.documentElement.scrollTop||((e=document.body)==null?void 0:e.scrollTop)||0}},checkIsScrollRoot:()=>!0}),fd={current:void 0},Fx=$x({measureScroll:n=>({x:n.scrollLeft,y:n.scrollTop}),defaultParent:()=>{if(!fd.current){const n=new qA({});n.mount(window),n.setOptions({layoutScroll:!0}),fd.current=n}return fd.current},resetTransform:(n,e)=>{n.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:n=>window.getComputedStyle(n).position==="fixed"}),Kf=M.createContext({transformPagePoint:n=>n,isStatic:!1,reducedMotion:"never"});function nb(n,e){if(typeof n=="function")return n(e);n!=null&&(n.current=e)}function $A(...n){return e=>{let i=!1;const a=n.map(l=>{const c=nb(l,e);return!i&&typeof c=="function"&&(i=!0),c});if(i)return()=>{for(let l=0;l{const{width:_,height:S,top:E,left:R,right:N,bottom:O,direction:C}=m.current;if(e||c===!1||!d.current||!_||!S)return;const P=C==="rtl",Y=i==="left"?P?`right: ${N}`:`left: ${R}`:P?`left: ${R}`:`right: ${N}`,X=a==="bottom"?`bottom: ${O}`:`top: ${E}`;d.current.dataset.motionPopId=u;const q=document.createElement("style");p&&(q.nonce=p);const Z=l??document.head;return Z.appendChild(q),q.sheet&&q.sheet.insertRule(` [data-motion-pop-id="${u}"] { position: absolute !important; width: ${_}px !important; height: ${S}px !important; ${Y}px !important; ${X}px !important; } `),()=>{var te;(te=d.current)==null||te.removeAttribute("data-motion-pop-id"),Z.contains(q)&&Z.removeChild(q)}},[e]),g.jsx(FA,{isPresent:e,childRef:d,sizeRef:m,pop:c,children:c===!1?n:M.cloneElement(n,{ref:v})})}const KA=({children:n,initial:e,isPresent:i,onExitComplete:a,custom:l,presenceAffectsLayout:c,mode:u,anchorX:d,anchorY:m,root:p})=>{const y=wf(YA),v=M.useId(),x=M.useRef(i),_=M.useRef(a);_f(()=>{x.current=i,_.current=a});let S=!0,E=M.useMemo(()=>(S=!1,{id:v,initial:e,isPresent:i,custom:l,onExitComplete:R=>{y.set(R,!0);for(const N of y.values())if(!N)return;a&&a()},register:R=>(y.set(R,!1),()=>{var N;y.delete(R),!x.current&&!y.size&&((N=_.current)==null||N.call(_))})}),[i,y,a]);return c&&S&&(E={...E}),M.useMemo(()=>{y.forEach((R,N)=>y.set(N,!1))},[i]),M.useEffect(()=>{!i&&!y.size&&a&&a()},[i]),n=g.jsx(GA,{pop:u==="popLayout",isPresent:i,anchorX:d,anchorY:m,root:p,children:n}),g.jsx(Nc.Provider,{value:E,children:n})};function YA(){return new Map}function Gx(n=!0){const e=M.useContext(Nc);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:a,register:l}=e,c=M.useId();M.useEffect(()=>{if(n)return l(c)},[n]);const u=M.useCallback(()=>n&&a&&a(c),[c,a,n]);return!i&&a?[!1,u]:[!0]}const zl=n=>n.key||"";function sb(n){const e=[];return M.Children.forEach(n,i=>{M.isValidElement(i)&&e.push(i)}),e}const Qs=({children:n,custom:e,initial:i=!0,onExitComplete:a,presenceAffectsLayout:l=!0,mode:c="sync",propagate:u=!1,anchorX:d="left",anchorY:m="top",root:p})=>{const[y,v]=Gx(u),x=M.useMemo(()=>sb(n),[n]),_=u&&!y?[]:x.map(zl),S=M.useRef(!0),E=M.useRef(x),R=wf(()=>new Map),N=M.useRef(new Set),[O,C]=M.useState(x),[P,Y]=M.useState(x);_f(()=>{S.current=!1,E.current=x;for(let Z=0;Z{const te=zl(Z),Q=u&&!y?!1:x===P||_.includes(te),le=()=>{if(N.current.has(te))return;if(R.has(te))N.current.add(te),R.set(te,!0);else return;let he=!0;R.forEach(Ge=>{Ge||(he=!1)}),he&&(q==null||q(),Y(E.current),u&&(v==null||v()),a&&a())};return g.jsx(KA,{isPresent:Q,initial:!S.current||i?void 0:!1,custom:e,presenceAffectsLayout:l,mode:c,root:p,onExitComplete:Q?void 0:le,anchorX:d,anchorY:m,children:Z},te)})})},Kx=M.createContext({strict:!1}),ib={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"]};let ab=!1;function XA(){if(ab)return;const n={};for(const e in ib)n[e]={isEnabled:i=>ib[e].some(a=>!!i[a])};Sx(n),ab=!0}function Yx(){return XA(),DE()}function JA(n){const e=Yx();for(const i in n)e[i]={...e[i],...n[i]};Sx(e)}const QA=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","propagate","ignoreStrict","viewport"]);function vc(n){return n.startsWith("while")||n.startsWith("drag")&&n!=="draggable"||n.startsWith("layout")||n.startsWith("onTap")||n.startsWith("onPan")||n.startsWith("onLayout")||QA.has(n)}let Xx=n=>!vc(n);function ZA(n){typeof n=="function"&&(Xx=e=>e.startsWith("on")?!vc(e):n(e))}try{ZA(require("@emotion/is-prop-valid").default)}catch{}function WA(n,e,i){const a={};for(const l in n)l==="values"&&typeof n.values=="object"||kt(n[l])||(Xx(l)||i===!0&&vc(l)||!e&&!vc(l)||n.draggable&&l.startsWith("onDrag"))&&(a[l]=n[l]);return a}const Mc=M.createContext({});function e2(n,e){if(Dc(n)){const{initial:i,animate:a}=n;return{initial:i===!1||so(i)?i:void 0,animate:so(a)?a:void 0}}return n.inherit!==!1?e:{}}function t2(n){const{initial:e,animate:i}=e2(n,M.useContext(Mc));return M.useMemo(()=>({initial:e,animate:i}),[rb(e),rb(i)])}function rb(n){return Array.isArray(n)?n.join(" "):n}const Yf=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Jx(n,e,i){for(const a in e)!kt(e[a])&&!Nx(a,i)&&(n[a]=e[a])}function n2({transformTemplate:n},e){return M.useMemo(()=>{const i=Yf();return Ff(i,e,n),Object.assign({},i.vars,i.style)},[e])}function s2(n,e){const i=n.style||{},a={};return Jx(a,i,n),Object.assign(a,n2(n,e)),a}function i2(n,e){const i={},a=s2(n,e);return n.drag&&n.dragListener!==!1&&(i.draggable=!1,a.userSelect=a.WebkitUserSelect=a.WebkitTouchCallout="none",a.touchAction=n.drag===!0?"none":`pan-${n.drag==="x"?"y":"x"}`),n.tabIndex===void 0&&(n.onTap||n.onTapStart||n.whileTap)&&(i.tabIndex=0),i.style=a,i}const Qx=()=>({...Yf(),attrs:{}});function a2(n,e,i,a){const l=M.useMemo(()=>{const c=Qx();return kx(c,e,Dx(a),n.transformTemplate,n.style),{...c.attrs,style:{...c.style}}},[e]);if(n.style){const c={};Jx(c,n.style,n),l.style={...c,...l.style}}return l}const r2=["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 Xf(n){return typeof n!="string"||n.includes("-")?!1:!!(r2.indexOf(n)>-1||/[A-Z]/u.test(n))}function o2(n,e,i,{latestValues:a},l,c=!1,u){const m=(u??Xf(n)?a2:i2)(e,a,l,n),p=WA(e,typeof n=="string",c),y=n!==M.Fragment?{...p,...m,ref:i}:{},{children:v}=e,x=M.useMemo(()=>kt(v)?v.get():v,[v]);return M.createElement(n,{...y,children:x})}function l2({scrapeMotionValuesFromProps:n,createRenderState:e},i,a,l){return{latestValues:c2(i,a,l,n),renderState:e()}}function c2(n,e,i,a){const l={},c=a(n,{});for(const x in c)l[x]=oc(c[x]);let{initial:u,animate:d}=n;const m=Dc(n),p=wx(n);e&&p&&!m&&n.inherit!==!1&&(u===void 0&&(u=e.initial),d===void 0&&(d=e.animate));let y=i?i.initial===!1:!1;y=y||u===!1;const v=y?d:u;if(v&&typeof v!="boolean"&&!Oc(v)){const x=Array.isArray(v)?v:[v];for(let _=0;_(e,i)=>{const a=M.useContext(Mc),l=M.useContext(Nc),c=()=>l2(n,e,a,l);return i?c():wf(c)},u2=Zx({scrapeMotionValuesFromProps:Gf,createRenderState:Yf}),h2=Zx({scrapeMotionValuesFromProps:Mx,createRenderState:Qx}),d2=Symbol.for("motionComponentSymbol");function f2(n,e,i){const a=M.useRef(i);M.useInsertionEffect(()=>{a.current=i});const l=M.useRef(null);return M.useCallback(c=>{var d;c&&((d=n.onMount)==null||d.call(n,c)),e&&(c?e.mount(c):e.unmount());const u=a.current;if(typeof u=="function")if(c){const m=u(c);typeof m=="function"&&(l.current=m)}else l.current?(l.current(),l.current=null):u(c);else u&&(u.current=c)},[e])}const Wx=M.createContext({});function Ca(n){return n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,"current")}function m2(n,e,i,a,l,c){var C,P;const{visualElement:u}=M.useContext(Mc),d=M.useContext(Kx),m=M.useContext(Nc),p=M.useContext(Kf),y=p.reducedMotion,v=p.skipAnimations,x=M.useRef(null),_=M.useRef(!1);a=a||d.renderer,!x.current&&a&&(x.current=a(n,{visualState:e,parent:u,props:i,presenceContext:m,blockInitialAnimation:m?m.initial===!1:!1,reducedMotionConfig:y,skipAnimations:v,isSVG:c}),_.current&&x.current&&(x.current.manuallyAnimateOnMount=!0));const S=x.current,E=M.useContext(Wx);S&&!S.projection&&l&&(S.type==="html"||S.type==="svg")&&p2(x.current,i,l,E);const R=M.useRef(!1);M.useInsertionEffect(()=>{S&&R.current&&S.update(i,m)});const N=i[cx],O=M.useRef(!!N&&typeof window<"u"&&!((C=window.MotionHandoffIsComplete)!=null&&C.call(window,N))&&((P=window.MotionHasOptimisedAnimation)==null?void 0:P.call(window,N)));return _f(()=>{_.current=!0,S&&(R.current=!0,window.MotionIsMounted=!0,S.updateFeatures(),S.scheduleRenderMicrotask(),O.current&&S.animationState&&S.animationState.animateChanges())}),M.useEffect(()=>{S&&(!O.current&&S.animationState&&S.animationState.animateChanges(),O.current&&(queueMicrotask(()=>{var Y;(Y=window.MotionHandoffMarkAsComplete)==null||Y.call(window,N)}),O.current=!1),S.enteringChildren=void 0)}),S}function p2(n,e,i,a){const{layoutId:l,layout:c,drag:u,dragConstraints:d,layoutScroll:m,layoutRoot:p,layoutAnchor:y,layoutCrossfade:v}=e;n.projection=new i(n.latestValues,e["data-framer-portal-id"]?void 0:ew(n.parent)),n.projection.setOptions({layoutId:l,layout:c,alwaysMeasureLayout:!!u||d&&Ca(d),visualElement:n,animationType:typeof c=="string"?c:"both",initialPromotionConfig:a,crossfade:v,layoutScroll:m,layoutRoot:p,layoutAnchor:y})}function ew(n){if(n)return n.options.allowProjection!==!1?n.projection:ew(n.parent)}function md(n,{forwardMotionProps:e=!1,type:i}={},a,l){a&&JA(a);const c=i?i==="svg":Xf(n),u=c?h2:u2;function d(p,y){let v;const x={...M.useContext(Kf),...p,layoutId:g2(p)},{isStatic:_}=x,S=t2(p),E=u(p,_);if(!_&&typeof window<"u"){y2();const R=b2(x);v=R.MeasureLayout,S.visualElement=m2(n,E,x,l,R.ProjectionNode,c)}return g.jsxs(Mc.Provider,{value:S,children:[v&&S.visualElement?g.jsx(v,{visualElement:S.visualElement,...x}):null,o2(n,p,f2(E,S.visualElement,y),E,_,e,c)]})}d.displayName=`motion.${typeof n=="string"?n:`create(${n.displayName??n.name??""})`}`;const m=M.forwardRef(d);return m[d2]=n,m}function g2({layoutId:n}){const e=M.useContext(xf).id;return e&&n!==void 0?e+"-"+n:n}function y2(n,e){M.useContext(Kx).strict}function b2(n){const e=Yx(),{drag:i,layout:a}=e;if(!i&&!a)return{};const l={...i,...a};return{MeasureLayout:i!=null&&i.isEnabled(n)||a!=null&&a.isEnabled(n)?l.MeasureLayout:void 0,ProjectionNode:l.ProjectionNode}}function v2(n,e){if(typeof Proxy>"u")return md;const i=new Map,a=(c,u)=>md(c,u,n,e),l=(c,u)=>a(c,u);return new Proxy(l,{get:(c,u)=>u==="create"?a:(i.has(u)||i.set(u,md(u,void 0,n,e)),i.get(u))})}const x2=(n,e)=>e.isSVG??Xf(n)?new JE(e):new IE(e,{allowProjection:n!==M.Fragment});class w2 extends si{constructor(e){super(e),e.animationState||(e.animationState=tA(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Oc(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:i}=this.node.prevProps||{};e!==i&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let _2=0;class S2 extends si{constructor(){super(...arguments),this.id=_2++,this.isExitComplete=!1}update(){var c;if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:i}=this.node.presenceContext,{isPresent:a}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===a)return;if(e&&a===!1){if(this.isExitComplete){const{initial:u,custom:d}=this.node.getProps();if(typeof u=="string"||typeof u=="object"&&u!==null&&!Array.isArray(u)){const m=Oi(this.node,u,d);if(m){const{transition:p,transitionEnd:y,...v}=m;for(const x in v)(c=this.node.getValue(x))==null||c.jump(v[x])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const l=this.node.animationState.setActive("exit",!e);i&&!e&&l.then(()=>{this.isExitComplete=!0,i(this.id)})}mount(){const{register:e,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const T2={animation:{Feature:w2},exit:{Feature:S2}};function xo(n){return{point:{x:n.pageX,y:n.pageY}}}const E2=n=>e=>Hf(e)&&n(e,xo(e));function Xr(n,e,i,a){return io(n,e,E2(i),a)}const tw=({current:n})=>n?n.ownerDocument.defaultView:null,ob=(n,e)=>Math.abs(n-e);function A2(n,e){const i=ob(n.x,e.x),a=ob(n.y,e.y);return Math.sqrt(i**2+a**2)}const lb=new Set(["auto","scroll"]);class nw{constructor(e,i,{transformPagePoint:a,contextWindow:l=window,dragSnapToOrigin:c=!1,distanceThreshold:u=3,element:d}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=S=>{this.handleScroll(S.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Vl(this.lastRawMoveEventInfo,this.transformPagePoint));const S=pd(this.lastMoveEventInfo,this.history),E=this.startEvent!==null,R=A2(S.offset,{x:0,y:0})>=this.distanceThreshold;if(!E&&!R)return;const{point:N}=S,{timestamp:O}=Nt;this.history.push({...N,timestamp:O});const{onStart:C,onMove:P}=this.handlers;E||(C&&C(this.lastMoveEvent,S),this.startEvent=this.lastMoveEvent),P&&P(this.lastMoveEvent,S)},this.handlePointerMove=(S,E)=>{this.lastMoveEvent=S,this.lastRawMoveEventInfo=E,this.lastMoveEventInfo=Vl(E,this.transformPagePoint),Fe.update(this.updatePoint,!0)},this.handlePointerUp=(S,E)=>{this.end();const{onEnd:R,onSessionEnd:N,resumeAnimation:O}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&O&&O(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const C=pd(S.type==="pointercancel"?this.lastMoveEventInfo:Vl(E,this.transformPagePoint),this.history);this.startEvent&&R&&R(S,C),N&&N(S,C)},!Hf(e))return;this.dragSnapToOrigin=c,this.handlers=i,this.transformPagePoint=a,this.distanceThreshold=u,this.contextWindow=l||window;const m=xo(e),p=Vl(m,this.transformPagePoint),{point:y}=p,{timestamp:v}=Nt;this.history=[{...y,timestamp:v}];const{onSessionStart:x}=i;x&&x(e,pd(p,this.history));const _={passive:!0,capture:!0};this.removeListeners=yo(Xr(this.contextWindow,"pointermove",this.handlePointerMove,_),Xr(this.contextWindow,"pointerup",this.handlePointerUp,_),Xr(this.contextWindow,"pointercancel",this.handlePointerUp,_)),d&&this.startScrollTracking(d)}startScrollTracking(e){let i=e.parentElement;for(;i;){const a=getComputedStyle(i);(lb.has(a.overflowX)||lb.has(a.overflowY))&&this.scrollPositions.set(i,{x:i.scrollLeft,y:i.scrollTop}),i=i.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(e){const i=this.scrollPositions.get(e);if(!i)return;const a=e===window,l=a?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},c={x:l.x-i.x,y:l.y-i.y};c.x===0&&c.y===0||(a?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=c.x,this.lastMoveEventInfo.point.y+=c.y):this.history.length>0&&(this.history[0].x-=c.x,this.history[0].y-=c.y),this.scrollPositions.set(e,l),Fe.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),ni(this.updatePoint)}}function Vl(n,e){return e?{point:e(n.point)}:n}function cb(n,e){return{x:n.x-e.x,y:n.y-e.y}}function pd({point:n},e){return{point:n,delta:cb(n,sw(e)),offset:cb(n,j2(e)),velocity:C2(e,.1)}}function j2(n){return n[0]}function sw(n){return n[n.length-1]}function C2(n,e){if(n.length<2)return{x:0,y:0};let i=n.length-1,a=null;const l=sw(n);for(;i>=0&&(a=n[i],!(l.timestamp-a.timestamp>hn(e)));)i--;if(!a)return{x:0,y:0};a===n[0]&&n.length>2&&l.timestamp-a.timestamp>hn(e)*2&&(a=n[1]);const c=Tn(l.timestamp-a.timestamp);if(c===0)return{x:0,y:0};const u={x:(l.x-a.x)/c,y:(l.y-a.y)/c};return u.x===1/0&&(u.x=0),u.y===1/0&&(u.y=0),u}function R2(n,{min:e,max:i},a){return e!==void 0&&ni&&(n=a?Ie(i,n,a.max):Math.min(n,i)),n}function ub(n,e,i){return{min:e!==void 0?n.min+e:void 0,max:i!==void 0?n.max+i-(n.max-n.min):void 0}}function N2(n,{top:e,left:i,bottom:a,right:l}){return{x:ub(n.x,i,l),y:ub(n.y,e,a)}}function hb(n,e){let i=e.min-n.min,a=e.max-n.max;return e.max-e.mina?i=to(e.min,e.max-a,n.min):a>l&&(i=to(n.min,n.max-l,e.min)),Qn(0,1,i)}function D2(n,e){const i={};return e.min!==void 0&&(i.min=e.min-n.min),e.max!==void 0&&(i.max=e.max-n.min),i}const ef=.35;function M2(n=ef){return n===!1?n=0:n===!0&&(n=ef),{x:db(n,"left","right"),y:db(n,"top","bottom")}}function db(n,e,i){return{min:fb(n,e),max:fb(n,i)}}function fb(n,e){return typeof n=="number"?n:n[e]||0}const B2=new WeakMap;class U2{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=xt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:i=!1,distanceThreshold:a}={}){const{presenceContext:l}=this.visualElement;if(l&&l.isPresent===!1)return;const c=v=>{i&&this.snapToCursor(xo(v).point),this.stopAnimation()},u=(v,x)=>{const{drag:_,dragPropagation:S,onDragStart:E}=this.getProps();if(_&&!S&&(this.openDragLock&&this.openDragLock(),this.openDragLock=cE(_),!this.openDragLock))return;this.latestPointerEvent=v,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Gn(N=>{let O=this.getAxisMotionValue(N).get()||0;if(Jn.test(O)){const{projection:C}=this.visualElement;if(C&&C.layout){const P=C.layout.layoutBox[N];P&&(O=Vt(P)*(parseFloat(O)/100))}}this.originPoint[N]=O}),E&&Fe.update(()=>E(v,x),!1,!0),Id(this.visualElement,"transform");const{animationState:R}=this.visualElement;R&&R.setActive("whileDrag",!0)},d=(v,x)=>{this.latestPointerEvent=v,this.latestPanInfo=x;const{dragPropagation:_,dragDirectionLock:S,onDirectionLock:E,onDrag:R}=this.getProps();if(!_&&!this.openDragLock)return;const{offset:N}=x;if(S&&this.currentDirection===null){this.currentDirection=z2(N),this.currentDirection!==null&&E&&E(this.currentDirection);return}this.updateAxis("x",x.point,N),this.updateAxis("y",x.point,N),this.visualElement.render(),R&&Fe.update(()=>R(v,x),!1,!0)},m=(v,x)=>{this.latestPointerEvent=v,this.latestPanInfo=x,this.stop(v,x),this.latestPointerEvent=null,this.latestPanInfo=null},p=()=>{const{dragSnapToOrigin:v}=this.getProps();(v||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:y}=this.getProps();this.panSession=new nw(e,{onSessionStart:c,onStart:u,onMove:d,onSessionEnd:m,resumeAnimation:p},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:y,distanceThreshold:a,contextWindow:tw(this.visualElement),element:this.visualElement.current})}stop(e,i){const a=e||this.latestPointerEvent,l=i||this.latestPanInfo,c=this.isDragging;if(this.cancel(),!c||!l||!a)return;const{velocity:u}=l;this.startAnimation(u);const{onDragEnd:d}=this.getProps();d&&Fe.postRender(()=>d(a,l))}cancel(){this.isDragging=!1;const{projection:e,animationState:i}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:a}=this.getProps();!a&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,i,a){const{drag:l}=this.getProps();if(!a||!Pl(e,l,this.currentDirection))return;const c=this.getAxisMotionValue(e);let u=this.originPoint[e]+a[e];this.constraints&&this.constraints[e]&&(u=R2(u,this.constraints[e],this.elastic[e])),c.set(u)}resolveConstraints(){var c;const{dragConstraints:e,dragElastic:i}=this.getProps(),a=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(c=this.visualElement.projection)==null?void 0:c.layout,l=this.constraints;e&&Ca(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&a?this.constraints=N2(a.layoutBox,e):this.constraints=!1,this.elastic=M2(i),l!==this.constraints&&!Ca(e)&&a&&this.constraints&&!this.hasMutatedConstraints&&Gn(u=>{this.constraints!==!1&&this.getAxisMotionValue(u)&&(this.constraints[u]=D2(a.layoutBox[u],this.constraints[u]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!Ca(e))return!1;const a=e.current,{projection:l}=this.visualElement;if(!l||!l.layout)return!1;l.root&&(l.root.scroll=void 0,l.root.updateScroll());const c=zE(a,l.root,this.visualElement.getTransformPagePoint());let u=k2(l.layout.layoutBox,c);if(i){const d=i(BE(u));this.hasMutatedConstraints=!!d,d&&(u=Ex(d))}return u}startAnimation(e){const{drag:i,dragMomentum:a,dragElastic:l,dragTransition:c,dragSnapToOrigin:u,onDragTransitionEnd:d}=this.getProps(),m=this.constraints||{},p=Gn(y=>{if(!Pl(y,i,this.currentDirection))return;let v=m&&m[y]||{};(u===!0||u===y)&&(v={min:0,max:0});const x=l?200:1e6,_=l?40:1e7,S={type:"inertia",velocity:a?e[y]:0,bounceStiffness:x,bounceDamping:_,timeConstant:750,restDelta:1,restSpeed:10,...c,...v};return this.startAxisValueAnimation(y,S)});return Promise.all(p).then(d)}startAxisValueAnimation(e,i){const a=this.getAxisMotionValue(e);return Id(this.visualElement,e),a.start(Uf(e,a,0,i,this.visualElement,!1))}stopAnimation(){Gn(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){const i=`_drag${e.toUpperCase()}`,l=this.visualElement.getProps()[i];return l||this.visualElement.getValue(e,this.visualElement.latestValues[e]??0)}snapToCursor(e){Gn(i=>{const{drag:a}=this.getProps();if(!Pl(i,a,this.currentDirection))return;const{projection:l}=this.visualElement,c=this.getAxisMotionValue(i);if(l&&l.layout){const{min:u,max:d}=l.layout.layoutBox[i],m=c.get()||0;c.set(e[i]-Ie(u,d,.5)+m)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:i}=this.getProps(),{projection:a}=this.visualElement;if(!Ca(i)||!a||!this.constraints)return;this.stopAnimation();const l={x:0,y:0};Gn(u=>{const d=this.getAxisMotionValue(u);if(d&&this.constraints!==!1){const m=d.get();l[u]=O2({min:m,max:m},this.constraints[u])}});const{transformTemplate:c}=this.visualElement.getProps();this.visualElement.current.style.transform=c?c({},""):"none",a.root&&a.root.updateScroll(),a.updateLayout(),this.constraints=!1,this.resolveConstraints(),Gn(u=>{if(!Pl(u,e,null))return;const d=this.getAxisMotionValue(u),{min:m,max:p}=this.constraints[u];d.set(Ie(m,p,l[u]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;B2.set(this.visualElement,this);const e=this.visualElement.current,i=Xr(e,"pointerdown",p=>{const{drag:y,dragListener:v=!0}=this.getProps(),x=p.target,_=x!==e&&pE(x);y&&v&&!_&&this.start(p)});let a;const l=()=>{const{dragConstraints:p}=this.getProps();Ca(p)&&p.current&&(this.constraints=this.resolveRefConstraints(),a||(a=L2(e,p.current,()=>this.scalePositionWithinConstraints())))},{projection:c}=this.visualElement,u=c.addEventListener("measure",l);c&&!c.layout&&(c.root&&c.root.updateScroll(),c.updateLayout()),Fe.read(l);const d=io(window,"resize",()=>this.scalePositionWithinConstraints()),m=c.addEventListener("didUpdate",(({delta:p,hasLayoutChanged:y})=>{this.isDragging&&y&&(Gn(v=>{const x=this.getAxisMotionValue(v);x&&(this.originPoint[v]+=p[v].translate,x.set(x.get()+p[v].translate))}),this.visualElement.render())}));return()=>{d(),i(),u(),m&&m(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:a=!1,dragPropagation:l=!1,dragConstraints:c=!1,dragElastic:u=ef,dragMomentum:d=!0}=e;return{...e,drag:i,dragDirectionLock:a,dragPropagation:l,dragConstraints:c,dragElastic:u,dragMomentum:d}}}function mb(n){let e=!0;return()=>{if(e){e=!1;return}n()}}function L2(n,e,i){const a=w0(n,mb(i)),l=w0(e,mb(i));return()=>{a(),l()}}function Pl(n,e,i){return(e===!0||e===n)&&(i===null||i===n)}function z2(n,e=10){let i=null;return Math.abs(n.y)>e?i="y":Math.abs(n.x)>e&&(i="x"),i}class V2 extends si{constructor(e){super(e),this.removeGroupControls=En,this.removeListeners=En,this.controls=new U2(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||En}update(){const{dragControls:e}=this.node.getProps(),{dragControls:i}=this.node.prevProps||{};e!==i&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const gd=n=>(e,i)=>{n&&Fe.update(()=>n(e,i),!1,!0)};class P2 extends si{constructor(){super(...arguments),this.removePointerDownListener=En}onPointerDown(e){this.session=new nw(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:tw(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:a,onPanEnd:l}=this.node.getProps();return{onSessionStart:gd(e),onStart:gd(i),onMove:gd(a),onEnd:(c,u)=>{delete this.session,l&&Fe.postRender(()=>l(c,u))}}}mount(){this.removePointerDownListener=Xr(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let yd=!1;class H2 extends M.Component{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:a,layoutId:l}=this.props,{projection:c}=e;c&&(i.group&&i.group.add(c),a&&a.register&&l&&a.register(c),yd&&c.root.didUpdate(),c.addEventListener("animationComplete",()=>{this.safeToRemove()}),c.setOptions({...c.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),lc.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:a,drag:l,isPresent:c}=this.props,{projection:u}=a;return u&&(u.isPresent=c,e.layoutDependency!==i&&u.setOptions({...u.options,layoutDependency:i}),yd=!0,l||e.layoutDependency!==i||i===void 0||e.isPresent!==c?u.willUpdate():this.safeToRemove(),e.isPresent!==c&&(c?u.promote():u.relegate()||Fe.postRender(()=>{const d=u.getStack();(!d||!d.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:e,layoutAnchor:i}=this.props,{projection:a}=e;a&&(a.options.layoutAnchor=i,a.root.didUpdate(),Pf.postRender(()=>{!a.currentAnimation&&a.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:a}=this.props,{projection:l}=e;yd=!0,l&&(l.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(l),a&&a.deregister&&a.deregister(l))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function iw(n){const[e,i]=Gx(),a=M.useContext(xf);return g.jsx(H2,{...n,layoutGroup:a,switchLayoutGroup:M.useContext(Wx),isPresent:e,safeToRemove:i})}const q2={pan:{Feature:P2},drag:{Feature:V2,ProjectionNode:Fx,MeasureLayout:iw}};function pb(n,e,i){const{props:a}=n;n.animationState&&a.whileHover&&n.animationState.setActive("whileHover",i==="Start");const l="onHover"+i,c=a[l];c&&Fe.postRender(()=>c(e,xo(e)))}class $2 extends si{mount(){const{current:e}=this.node;e&&(this.unmount=hE(e,(i,a)=>(pb(this.node,a,"Start"),l=>pb(this.node,l,"End"))))}unmount(){}}class I2 extends si{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=yo(io(this.node.current,"focus",()=>this.onFocus()),io(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function gb(n,e,i){const{props:a}=n;if(n.current instanceof HTMLButtonElement&&n.current.disabled)return;n.animationState&&a.whileTap&&n.animationState.setActive("whileTap",i==="Start");const l="onTap"+(i==="End"?"":i),c=a[l];c&&Fe.postRender(()=>c(e,xo(e)))}class F2 extends si{mount(){const{current:e}=this.node;if(!e)return;const{globalTapTarget:i,propagate:a}=this.node.props;this.unmount=yE(e,(l,c)=>(gb(this.node,c,"Start"),(u,{success:d})=>gb(this.node,u,d?"End":"Cancel")),{useGlobalTarget:i,stopPropagation:(a==null?void 0:a.tap)===!1})}unmount(){}}const tf=new WeakMap,bd=new WeakMap,G2=n=>{const e=tf.get(n.target);e&&e(n)},K2=n=>{n.forEach(G2)};function Y2({root:n,...e}){const i=n||document;bd.has(i)||bd.set(i,{});const a=bd.get(i),l=JSON.stringify(e);return a[l]||(a[l]=new IntersectionObserver(K2,{root:n,...e})),a[l]}function X2(n,e,i){const a=Y2(e);return tf.set(n,i),a.observe(n),()=>{tf.delete(n),a.unobserve(n)}}const J2={some:0,all:1};class Q2 extends si{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){var m;(m=this.stopObserver)==null||m.call(this);const{viewport:e={}}=this.node.getProps(),{root:i,margin:a,amount:l="some",once:c}=e,u={root:i?i.current:void 0,rootMargin:a,threshold:typeof l=="number"?l:J2[l]},d=p=>{const{isIntersecting:y}=p;if(this.isInView===y||(this.isInView=y,c&&!y&&this.hasEnteredView))return;y&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",y);const{onViewportEnter:v,onViewportLeave:x}=this.node.getProps(),_=y?v:x;_&&_(p)};this.stopObserver=X2(this.node.current,u,d)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:i}=this.node;["amount","margin","root"].some(Z2(e,i))&&this.startObserver()}unmount(){var e;(e=this.stopObserver)==null||e.call(this),this.hasEnteredView=!1,this.isInView=!1}}function Z2({viewport:n={}},{viewport:e={}}={}){return i=>n[i]!==e[i]}const W2={inView:{Feature:Q2},tap:{Feature:F2},focus:{Feature:I2},hover:{Feature:$2}},ej={layout:{ProjectionNode:Fx,MeasureLayout:iw}},tj={...T2,...W2,...q2,...ej},nj=v2(tj,x2),cn=nj;/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sj=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ij=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,a)=>a?a.toUpperCase():i.toLowerCase()),yb=n=>{const e=ij(n);return e.charAt(0).toUpperCase()+e.slice(1)},aw=(...n)=>n.filter((e,i,a)=>!!e&&e.trim()!==""&&a.indexOf(e)===i).join(" ").trim(),aj=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var rj={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oj=M.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:a,className:l="",children:c,iconNode:u,...d},m)=>M.createElement("svg",{ref:m,...rj,width:e,height:e,stroke:n,strokeWidth:a?Number(i)*24/Number(e):i,className:aw("lucide",l),...!c&&!aj(d)&&{"aria-hidden":"true"},...d},[...u.map(([p,y])=>M.createElement(p,y)),...Array.isArray(c)?c:[c]]));/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ue=(n,e)=>{const i=M.forwardRef(({className:a,...l},c)=>M.createElement(oj,{ref:c,iconNode:e,className:aw(`lucide-${sj(yb(n))}`,`lucide-${n}`,a),...l}));return i.displayName=yb(n),i};/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lj=[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]],cj=Ue("arrow-left-right",lj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uj=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],hj=Ue("arrow-right",uj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dj=[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M6 12h.01M18 12h.01",key:"113zkx"}]],bb=Ue("banknote",dj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fj=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]],mj=Ue("calendar-days",fj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pj=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],gj=Ue("calendar",pj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yj=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],bj=Ue("chevron-down",yj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vj=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],xj=Ue("circle-alert",vj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wj=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],xc=Ue("circle-check",wj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _j=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]],Sj=Ue("circle-user",_j);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tj=[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],rw=Ue("earth",Tj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ej=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Aj=Ue("external-link",Ej);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jj=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Cj=Ue("eye",jj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rj=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],Hr=Ue("file-spreadsheet",Rj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nj=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Hl=Ue("file-text",Nj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kj=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],Oj=Ue("funnel",kj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dj=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],vb=Ue("gift",Dj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mj=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Bj=Ue("history",Mj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uj=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],ow=Ue("info",Uj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lj=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Jr=Ue("loader-circle",Lj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zj=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],Vj=Ue("lock-keyhole",zj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pj=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],Hj=Ue("log-out",Pj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qj=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],lw=Ue("menu",qj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $j=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],Ij=Ue("play",$j);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fj=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Gj=Ue("plus",Fj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kj=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],Yj=Ue("refresh-cw",Kj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xj=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],qr=Ue("search",Xj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jj=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Qj=Ue("send",Jj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zj=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],ql=Ue("trash-2",Zj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wj=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],ao=Ue("triangle-alert",Wj);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eC=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],$l=Ue("upload",eC);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tC=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],ro=Ue("x",tC),oo=[{code:"GT",name:"Guatemala",flag:"/cruce-cuentas/gt-flag.png",currency:"GTQ",locale:"es-GT",enabled:!0},{code:"TT",name:"Trinidad y Tobago",flag:"/cruce-cuentas/tt-flag.png",currency:"TTD",locale:"en-TT",enabled:!0}];function xb(n){return oo.find(e=>e.code===n)??oo[0]}const nC="https://dbit.digitalcompass.agency/storage/v1/object/public/public-assets/GLM_completo.png";function sC({currentView:n,onViewChange:e,onNewCruce:i,isSidebarOpen:a=!1,onCloseSidebar:l,user:c,isAuthEnabled:u=!1,onLogout:d,country:m,onCountryChange:p,onChooseAnotherCountry:y}){const[v,x]=M.useState(!1),_=M.useRef(null);return M.useEffect(()=>{function S(E){_.current&&!_.current.contains(E.target)&&x(!1)}return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]),g.jsxs("aside",{className:`bg-neutral-100 h-screen w-64 fixed left-0 top-0 flex flex-col z-50 pb-6 min-h-screen font-sans transition-transform duration-300 md:translate-x-0 ${a?"translate-x-0":"-translate-x-full"}`,children:[g.jsx("div",{className:"absolute right-0 top-0 h-[80px] w-px bg-[#D0D0D0] pointer-events-none z-10 hidden md:block"}),g.jsx("div",{className:"absolute right-0 top-[84px] bottom-0 w-px bg-[#D0D0D0] pointer-events-none z-10 hidden md:block"}),g.jsxs("div",{className:"h-[84px] px-4 flex justify-between md:justify-center items-center bg-white border-b-4 border-[#6CC24A] relative",children:[g.jsx("img",{alt:"GomezLee Marketing logo",className:"h-10 object-contain selection:bg-transparent",src:nC}),g.jsx("button",{onClick:l,className:"md:hidden p-2 text-neutral-500 hover:text-neutral-800 transition-colors","aria-label":"Cerrar menú",children:g.jsx(ro,{className:"w-5 h-5"})})]}),g.jsxs("div",{className:"px-4 pt-5",children:[g.jsxs("label",{className:"block",children:[g.jsxs("span",{className:"text-[9px] uppercase tracking-wider font-black text-neutral-400 flex items-center gap-1.5 mb-1.5",children:[g.jsx(rw,{className:"w-3.5 h-3.5"}),"País"]}),g.jsxs("div",{className:"relative",ref:_,children:[g.jsxs("button",{type:"button",onClick:()=>x(!v),className:"w-full border border-neutral-300 bg-white px-3 py-2 text-xs font-bold text-[#4F758B] focus:outline-none focus:border-[#4F758B] flex items-center justify-between transition-colors hover:bg-neutral-50",children:[g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("img",{src:m.flag,alt:"",className:"w-5 h-3.5 object-cover shadow-sm border border-neutral-200"}),g.jsx("span",{children:m.name})]}),g.jsx(bj,{className:`w-4 h-4 text-[#4F758B] transition-transform ${v?"rotate-180":""}`})]}),v&&g.jsx("ul",{className:"absolute left-0 right-0 top-full mt-1 bg-white border border-neutral-300 shadow-lg z-50 py-1",children:oo.map(S=>g.jsx("li",{children:g.jsxs("button",{type:"button",disabled:!S.enabled,onClick:()=>{p(S.code),x(!1)},className:`w-full text-left px-3 py-2.5 text-xs font-bold flex items-center gap-2.5 transition-colors ${S.enabled?"hover:bg-neutral-100 text-[#4F758B]":"opacity-60 cursor-not-allowed text-neutral-500 bg-neutral-50"}`,children:[g.jsx("img",{src:S.flag,alt:"",className:"w-6 h-4 object-cover shadow-sm border border-neutral-200 bg-white flex-shrink-0"}),g.jsxs("span",{className:"min-w-0 text-left leading-tight",children:[g.jsx("span",{className:"block",children:S.name}),!S.enabled&&g.jsx("span",{className:"block mt-1 text-[10px] text-neutral-400 font-medium italic",children:"Próximamente"})]})]})},S.code))})]})]}),g.jsx("button",{type:"button",onClick:y,className:"mt-2 text-[9px] font-bold uppercase tracking-wider text-neutral-400 hover:text-[#4F758B]",children:"Ver países disponibles"})]}),g.jsx("nav",{className:"flex-1 flex flex-col mt-5",children:g.jsxs("ul",{className:"space-y-1",children:[g.jsx("li",{children:g.jsxs("button",{onClick:()=>e("cruce"),className:`w-full flex items-center gap-3 px-6 py-3.5 transition-all duration-150 text-left font-bold text-sm tracking-wide ${n==="cruce"?"bg-[#4F758B] text-white":"text-neutral-600 hover:bg-neutral-200 hover:text-neutral-800"}`,children:[g.jsx(cj,{className:`w-4 h-4 ${n==="cruce"?"text-[#6CC24A]":""}`}),g.jsx("span",{children:"Cruce de Cuentas"})]})}),g.jsx("li",{children:g.jsxs("button",{onClick:()=>e("historial"),className:`w-full flex items-center gap-3 px-6 py-3.5 transition-all duration-150 text-left font-bold text-sm tracking-wide ${n==="historial"?"bg-[#4F758B] text-white":"text-neutral-600 hover:bg-neutral-200 hover:text-neutral-800"}`,children:[g.jsx(Bj,{className:`w-4 h-4 ${n==="historial"?"text-[#6CC24A]":""}`}),g.jsx("span",{children:"Reportes Históricos"})]})})]})}),g.jsxs("div",{className:"px-4 space-y-3 pt-4 border-t border-[#D0D0D0] bg-neutral-100",children:[c&&g.jsxs("div",{className:"border border-neutral-200 bg-white px-3 py-3 flex items-center gap-2",children:[g.jsx(Sj,{className:"w-4 h-4 text-[#4F758B] flex-shrink-0"}),g.jsxs("div",{className:"min-w-0",children:[g.jsx("p",{className:"text-[11px] font-black text-neutral-700 truncate",title:c.name,children:c.name}),g.jsx("p",{className:"text-[9px] text-neutral-400 truncate",title:c.email,children:c.email})]})]}),g.jsxs("button",{onClick:i,className:"w-full bg-[#6CC24A] hover:bg-[#5bb03c] text-white py-3 px-4 font-bold text-xs uppercase tracking-wider flex items-center justify-center gap-2 transition-all duration-150 shadow-sm active:scale-98",children:[g.jsx(Gj,{className:"w-4 h-4"}),g.jsx("span",{children:"Nuevo Cruce"})]}),u&&d&&g.jsxs("button",{onClick:d,className:"w-full border border-neutral-300 bg-white hover:bg-neutral-50 text-neutral-600 py-2.5 px-4 font-bold text-[11px] uppercase tracking-wider flex items-center justify-center gap-2 transition-all duration-150",children:[g.jsx(Hj,{className:"w-4 h-4"}),g.jsx("span",{children:"Cerrar sesión"})]})]})]})}function Bc(n,e){var i={};for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&e.indexOf(a)<0&&(i[a]=n[a]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var l=0,a=Object.getOwnPropertySymbols(n);ln?(...e)=>n(...e):(...e)=>fetch(...e);class Jf extends Error{constructor(e,i="FunctionsError",a){super(e),this.name=i,this.context=a}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class rC extends Jf{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class wb extends Jf{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class _b extends Jf{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var nf;(function(n){n.Any="any",n.ApNortheast1="ap-northeast-1",n.ApNortheast2="ap-northeast-2",n.ApSouth1="ap-south-1",n.ApSoutheast1="ap-southeast-1",n.ApSoutheast2="ap-southeast-2",n.CaCentral1="ca-central-1",n.EuCentral1="eu-central-1",n.EuWest1="eu-west-1",n.EuWest2="eu-west-2",n.EuWest3="eu-west-3",n.SaEast1="sa-east-1",n.UsEast1="us-east-1",n.UsWest1="us-west-1",n.UsWest2="us-west-2"})(nf||(nf={}));class oC{constructor(e,{headers:i={},customFetch:a,region:l=nf.Any}={}){this.url=e,this.headers=i,this.region=l,this.fetch=aC(a)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return iC(this,arguments,void 0,function*(i,a={}){var l;let c,u;try{const{headers:d,method:m,body:p,signal:y,timeout:v}=a;let x={},{region:_}=a;_||(_=this.region);const S=new URL(`${this.url}/${i}`);_&&_!=="any"&&(x["x-region"]=_,S.searchParams.set("forceFunctionRegion",_));let E;const R=!!d&&Object.keys(d).some(X=>X.toLowerCase()==="content-type");p&&!R?typeof Blob<"u"&&p instanceof Blob||p instanceof ArrayBuffer?(x["Content-Type"]="application/octet-stream",E=p):typeof p=="string"?(x["Content-Type"]="text/plain",E=p):typeof FormData<"u"&&p instanceof FormData?E=p:(x["Content-Type"]="application/json",E=JSON.stringify(p)):p&&typeof p!="string"&&!(typeof Blob<"u"&&p instanceof Blob)&&!(p instanceof ArrayBuffer)&&!(typeof FormData<"u"&&p instanceof FormData)?E=JSON.stringify(p):E=p;let N=y;v&&(u=new AbortController,c=setTimeout(()=>u.abort(),v),y?(N=u.signal,y.addEventListener("abort",()=>u.abort())):N=u.signal);const O=yield this.fetch(S.toString(),{method:m||"POST",headers:Object.assign(Object.assign(Object.assign({},x),this.headers),d),body:E,signal:N}).catch(X=>{throw new rC(X)}),C=O.headers.get("x-relay-error");if(C&&C==="true")throw new wb(O);if(!O.ok)throw new _b(O);let P=((l=O.headers.get("Content-Type"))!==null&&l!==void 0?l:"text/plain").split(";")[0].trim(),Y;return P==="application/json"?Y=yield O.json():P==="application/octet-stream"||P==="application/pdf"?Y=yield O.blob():P==="text/event-stream"?Y=O:P==="multipart/form-data"?Y=yield O.formData():Y=yield O.text(),{data:Y,error:null,response:O}}catch(d){return{data:null,error:d,response:d instanceof _b||d instanceof wb?d.context:void 0}}finally{c&&clearTimeout(c)}})}}const cw=3,Sb=n=>Math.min(1e3*2**n,3e4),lC=[520,503],uw=["GET","HEAD","OPTIONS"];var Tb=class extends Error{constructor(n){super(n.message),this.name="PostgrestError",this.details=n.details,this.hint=n.hint,this.code=n.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function Eb(n,e){return new Promise(i=>{if(e!=null&&e.aborted){i();return}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",l),i()},n);function l(){clearTimeout(a),i()}e==null||e.addEventListener("abort",l)})}function cC(n,e,i,a){return!(!a||i>=cw||!uw.includes(n)||!lC.includes(e))}var uC=class{constructor(n){var e,i,a,l,c;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=n.method,this.url=n.url,this.headers=new Headers(n.headers),this.schema=n.schema,this.body=n.body,this.shouldThrowOnError=(e=n.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=n.signal,this.isMaybeSingle=(i=n.isMaybeSingle)!==null&&i!==void 0?i:!1,this.shouldStripNulls=(a=n.shouldStripNulls)!==null&&a!==void 0?a:!1,this.urlLengthLimit=(l=n.urlLengthLimit)!==null&&l!==void 0?l:8e3,this.retryEnabled=(c=n.retry)!==null&&c!==void 0?c:!0,n.fetch?this.fetch=n.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(n,e){return this.headers=new Headers(this.headers),this.headers.set(n,e),this}retry(n){return this.retryEnabled=n,this}then(n,e){var i=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const u=this.headers.get("Accept");u==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!u||u==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const a=this.fetch;let c=(async()=>{let u=0;for(;;){const p={};i.headers.forEach((v,x)=>{p[x]=v}),u>0&&(p["X-Retry-Count"]=String(u));let y;try{y=await a(i.url.toString(),{method:i.method,headers:p,body:JSON.stringify(i.body,(v,x)=>typeof x=="bigint"?x.toString():x),signal:i.signal})}catch(v){if((v==null?void 0:v.name)==="AbortError"||(v==null?void 0:v.code)==="ABORT_ERR"||!uw.includes(i.method))throw v;if(i.retryEnabled&&u{var d;let m="",p="",y="";const v=u==null?void 0:u.cause;if(v){var x,_,S,E;const O=(x=v==null?void 0:v.message)!==null&&x!==void 0?x:"",C=(_=v==null?void 0:v.code)!==null&&_!==void 0?_:"";m=`${(S=u==null?void 0:u.name)!==null&&S!==void 0?S:"FetchError"}: ${u==null?void 0:u.message}`,m+=` Caused by: ${(E=v==null?void 0:v.name)!==null&&E!==void 0?E:"Error"}: ${O}`,C&&(m+=` (${C})`),v!=null&&v.stack&&(m+=` ${v.stack}`)}else{var R;m=(R=u==null?void 0:u.stack)!==null&&R!==void 0?R:""}const N=this.url.toString().length;return(u==null?void 0:u.name)==="AbortError"||(u==null?void 0:u.code)==="ABORT_ERR"?(y="",p="Request was aborted (timeout or manual cancellation)",N>this.urlLengthLimit&&(p+=`. Note: Your request URL is ${N} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((v==null?void 0:v.name)==="HeadersOverflowError"||(v==null?void 0:v.code)==="UND_ERR_HEADERS_OVERFLOW")&&(y="",p="HTTP headers exceeded server limits (typically 16KB)",N>this.urlLengthLimit&&(p+=`. Your request URL is ${N} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(d=u==null?void 0:u.name)!==null&&d!==void 0?d:"FetchError"}: ${u==null?void 0:u.message}`,details:m,hint:p,code:y},data:null,count:null,status:0,statusText:""}})),c.then(n,e)}async processResponse(n){var e=this;let i=null,a=null,l=null,c=n.status,u=n.statusText;if(n.ok){var d,m;if(e.method!=="HEAD"){var p;const x=await n.text();if(x!=="")if(e.headers.get("Accept")==="text/csv")a=x;else if(e.headers.get("Accept")&&(!((p=e.headers.get("Accept"))===null||p===void 0)&&p.includes("application/vnd.pgrst.plan+text")))a=x;else try{a=JSON.parse(x)}catch{if(i={message:x},a=null,e.shouldThrowOnError)throw new Tb({message:x,details:"",hint:"",code:""})}}const y=(d=e.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),v=(m=n.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");y&&v&&v.length>1&&(l=parseInt(v[1])),e.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(i={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,c=406,u="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{const y=await n.text();try{i=JSON.parse(y),Array.isArray(i)&&n.status===404&&(a=[],i=null,c=200,u="OK")}catch{n.status===404&&y===""?(c=204,u="No Content"):i={message:y}}if(i&&e.shouldThrowOnError)throw new Tb(i)}return{success:i===null,error:i,data:a,count:l,status:c,statusText:u}}returns(){return this}overrideTypes(){return this}},hC=class extends uC{throwOnError(){return super.throwOnError()}select(n){let e=!1;const i=(n??"*").split("").map(a=>/\s/.test(a)&&!e?"":(a==='"'&&(e=!e),a)).join("");return this.url.searchParams.set("select",i),this.headers.append("Prefer","return=representation"),this}order(n,{ascending:e=!0,nullsFirst:i,foreignTable:a,referencedTable:l=a}={}){const c=l?`${l}.order`:"order",u=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${u?`${u},`:""}${n}.${e?"asc":"desc"}${i===void 0?"":i?".nullsfirst":".nullslast"}`),this}limit(n,{foreignTable:e,referencedTable:i=e}={}){const a=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(a,`${n}`),this}range(n,e,{foreignTable:i,referencedTable:a=i}={}){const l=typeof a>"u"?"offset":`${a}.offset`,c=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(l,`${n}`),this.url.searchParams.set(c,`${e-n+1}`),this}abortSignal(n){return this.signal=n,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:n=!1,verbose:e=!1,settings:i=!1,buffers:a=!1,wal:l=!1,format:c="text"}={}){var u;const d=[n?"analyze":null,e?"verbose":null,i?"settings":null,a?"buffers":null,l?"wal":null].filter(Boolean).join("|"),m=(u=this.headers.get("Accept"))!==null&&u!==void 0?u:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${c}; for="${m}"; options=${d};`),c==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(n){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${n}`),this}};const Ab=new RegExp("[,()]");var Ra=class extends hC{throwOnError(){return super.throwOnError()}eq(n,e){return this.url.searchParams.append(n,`eq.${e}`),this}neq(n,e){return this.url.searchParams.append(n,`neq.${e}`),this}gt(n,e){return this.url.searchParams.append(n,`gt.${e}`),this}gte(n,e){return this.url.searchParams.append(n,`gte.${e}`),this}lt(n,e){return this.url.searchParams.append(n,`lt.${e}`),this}lte(n,e){return this.url.searchParams.append(n,`lte.${e}`),this}like(n,e){return this.url.searchParams.append(n,`like.${e}`),this}likeAllOf(n,e){return this.url.searchParams.append(n,`like(all).{${e.join(",")}}`),this}likeAnyOf(n,e){return this.url.searchParams.append(n,`like(any).{${e.join(",")}}`),this}ilike(n,e){return this.url.searchParams.append(n,`ilike.${e}`),this}ilikeAllOf(n,e){return this.url.searchParams.append(n,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(n,e){return this.url.searchParams.append(n,`ilike(any).{${e.join(",")}}`),this}regexMatch(n,e){return this.url.searchParams.append(n,`match.${e}`),this}regexIMatch(n,e){return this.url.searchParams.append(n,`imatch.${e}`),this}is(n,e){return this.url.searchParams.append(n,`is.${e}`),this}isDistinct(n,e){return this.url.searchParams.append(n,`isdistinct.${e}`),this}in(n,e){const i=Array.from(new Set(e)).map(a=>typeof a=="string"&&Ab.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(n,`in.(${i})`),this}notIn(n,e){const i=Array.from(new Set(e)).map(a=>typeof a=="string"&&Ab.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(n,`not.in.(${i})`),this}contains(n,e){return typeof e=="string"?this.url.searchParams.append(n,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(n,`cs.{${e.join(",")}}`):this.url.searchParams.append(n,`cs.${JSON.stringify(e)}`),this}containedBy(n,e){return typeof e=="string"?this.url.searchParams.append(n,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(n,`cd.{${e.join(",")}}`):this.url.searchParams.append(n,`cd.${JSON.stringify(e)}`),this}rangeGt(n,e){return this.url.searchParams.append(n,`sr.${e}`),this}rangeGte(n,e){return this.url.searchParams.append(n,`nxl.${e}`),this}rangeLt(n,e){return this.url.searchParams.append(n,`sl.${e}`),this}rangeLte(n,e){return this.url.searchParams.append(n,`nxr.${e}`),this}rangeAdjacent(n,e){return this.url.searchParams.append(n,`adj.${e}`),this}overlaps(n,e){return typeof e=="string"?this.url.searchParams.append(n,`ov.${e}`):this.url.searchParams.append(n,`ov.{${e.join(",")}}`),this}textSearch(n,e,{config:i,type:a}={}){let l="";a==="plain"?l="pl":a==="phrase"?l="ph":a==="websearch"&&(l="w");const c=i===void 0?"":`(${i})`;return this.url.searchParams.append(n,`${l}fts${c}.${e}`),this}match(n){return Object.entries(n).filter(([e,i])=>i!==void 0).forEach(([e,i])=>{this.url.searchParams.append(e,`eq.${i}`)}),this}not(n,e,i){return this.url.searchParams.append(n,`not.${e}.${i}`),this}or(n,{foreignTable:e,referencedTable:i=e}={}){const a=i?`${i}.or`:"or";return this.url.searchParams.append(a,`(${n})`),this}filter(n,e,i){return this.url.searchParams.append(n,`${e}.${i}`),this}},dC=class{constructor(n,{headers:e={},schema:i,fetch:a,urlLengthLimit:l=8e3,retry:c}){this.url=n,this.headers=new Headers(e),this.schema=i,this.fetch=a,this.urlLengthLimit=l,this.retry=c}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(n,e){const{head:i=!1,count:a}=e??{},l=i?"HEAD":"GET";let c=!1;const u=(n??"*").split("").map(p=>/\s/.test(p)&&!c?"":(p==='"'&&(c=!c),p)).join(""),{url:d,headers:m}=this.cloneRequestState();return d.searchParams.set("select",u),a&&m.append("Prefer",`count=${a}`),new Ra({method:l,url:d,headers:m,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(n,{count:e,defaultToNull:i=!0}={}){var a;const l="POST",{url:c,headers:u}=this.cloneRequestState();if(e&&u.append("Prefer",`count=${e}`),i||u.append("Prefer","missing=default"),Array.isArray(n)){const d=n.reduce((m,p)=>m.concat(Object.keys(p)),[]);if(d.length>0){const m=[...new Set(d)].map(p=>`"${p}"`);c.searchParams.set("columns",m.join(","))}}return new Ra({method:l,url:c,headers:u,schema:this.schema,body:n,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(n,{onConflict:e,ignoreDuplicates:i=!1,count:a,defaultToNull:l=!0}={}){var c;const u="POST",{url:d,headers:m}=this.cloneRequestState();if(m.append("Prefer",`resolution=${i?"ignore":"merge"}-duplicates`),e!==void 0&&d.searchParams.set("on_conflict",e),a&&m.append("Prefer",`count=${a}`),l||m.append("Prefer","missing=default"),Array.isArray(n)){const p=n.reduce((y,v)=>y.concat(Object.keys(v)),[]);if(p.length>0){const y=[...new Set(p)].map(v=>`"${v}"`);d.searchParams.set("columns",y.join(","))}}return new Ra({method:u,url:d,headers:m,schema:this.schema,body:n,fetch:(c=this.fetch)!==null&&c!==void 0?c:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(n,{count:e}={}){var i;const a="PATCH",{url:l,headers:c}=this.cloneRequestState();return e&&c.append("Prefer",`count=${e}`),new Ra({method:a,url:l,headers:c,schema:this.schema,body:n,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:n}={}){var e;const i="DELETE",{url:a,headers:l}=this.cloneRequestState();return n&&l.append("Prefer",`count=${n}`),new Ra({method:i,url:a,headers:l,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function lo(n){"@babel/helpers - typeof";return lo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lo(n)}function fC(n,e){if(lo(n)!="object"||!n)return n;var i=n[Symbol.toPrimitive];if(i!==void 0){var a=i.call(n,e);if(lo(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function mC(n){var e=fC(n,"string");return lo(e)=="symbol"?e:e+""}function pC(n,e,i){return(e=mC(e))in n?Object.defineProperty(n,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):n[e]=i,n}function jb(n,e){var i=Object.keys(n);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(n);e&&(a=a.filter(function(l){return Object.getOwnPropertyDescriptor(n,l).enumerable})),i.push.apply(i,a)}return i}function Il(n){for(var e=1;e0?this.fetch=(p,y)=>{const v=new AbortController,x=setTimeout(()=>v.abort(),c),_=y==null?void 0:y.signal;if(_){if(_.aborted)return clearTimeout(x),m(p,y);const S=()=>{clearTimeout(x),v.abort()};return _.addEventListener("abort",S,{once:!0}),m(p,Il(Il({},y),{},{signal:v.signal})).finally(()=>{clearTimeout(x),_.removeEventListener("abort",S)})}return m(p,Il(Il({},y),{},{signal:v.signal})).finally(()=>clearTimeout(x))}:this.fetch=m,this.retry=d}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new dC(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new hw(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,i={},{head:a=!1,get:l=!1,count:c}={}){var u;let d;const m=new URL(`${this.url}/rpc/${e}`);let p;const y=_=>_!==null&&typeof _=="object"&&(!Array.isArray(_)||_.some(y)),v=a&&Object.values(i).some(y);v?(d="POST",p=i):a||l?(d=a?"HEAD":"GET",Object.entries(i).filter(([_,S])=>S!==void 0).map(([_,S])=>[_,Array.isArray(S)?`{${S.join(",")}}`:`${S}`]).forEach(([_,S])=>{m.searchParams.append(_,S)})):(d="POST",p=i);const x=new Headers(this.headers);return v?x.set("Prefer",c?`count=${c},return=minimal`:"return=minimal"):c&&x.set("Prefer",`count=${c}`),new Ra({method:d,url:m,headers:x,schema:this.schemaName,body:p,fetch:(u=this.fetch)!==null&&u!==void 0?u:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class yC{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const i=globalThis;if(typeof globalThis<"u"&&typeof i.WebSocket<"u")return{type:"native",wsConstructor:i.WebSocket};const a=typeof global<"u"?global:void 0;if(a&&typeof a.WebSocket<"u")return{type:"native",wsConstructor:a.WebSocket};if(typeof globalThis<"u"&&typeof i.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&i.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const l=globalThis.process;if(l){const c=l.versions;if(c&&c.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let i=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(i+=` Suggested solution: ${e.workaround}`),new Error(i)}static isWebSocketSupported(){try{return this.detectEnvironment().type==="native"}catch{return!1}}}const bC="2.110.2",vC=`realtime-js/${bC}`,xC="1.0.0",dw="2.0.0",wC=dw,_C=1e4,SC=100,Zs={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},fw={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},sf={connecting:"connecting",closing:"closing",closed:"closed"};class TC{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,i){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return i(this._binaryEncodeUserBroadcastPush(e));let a=[e.join_ref,e.ref,e.topic,e.event,e.payload];return i(JSON.stringify(a))}_binaryEncodeUserBroadcastPush(e){var i;return this._isArrayBuffer((i=e.payload)===null||i===void 0?void 0:i.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var i,a;const l=(a=(i=e.payload)===null||i===void 0?void 0:i.payload)!==null&&a!==void 0?a:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,l)}_encodeJsonUserBroadcastPush(e){var i,a;const l=(a=(i=e.payload)===null||i===void 0?void 0:i.payload)!==null&&a!==void 0?a:{},u=new TextEncoder().encode(JSON.stringify(l)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,u)}_encodeUserBroadcastPush(e,i,a){var l,c;const u=e.topic,d=(l=e.ref)!==null&&l!==void 0?l:"",m=(c=e.join_ref)!==null&&c!==void 0?c:"",p=e.payload.event,y=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},v=Object.keys(y).length===0?"":JSON.stringify(y);if(m.length>255)throw new Error(`joinRef length ${m.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`ref length ${d.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`topic length ${u.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`userEvent length ${p.length} exceeds maximum of 255`);if(v.length>255)throw new Error(`metadata length ${v.length} exceeds maximum of 255`);const x=this.USER_BROADCAST_PUSH_META_LENGTH+m.length+d.length+u.length+p.length+v.length,_=new ArrayBuffer(this.HEADER_LENGTH+x);let S=new DataView(_),E=0;S.setUint8(E++,this.KINDS.userBroadcastPush),S.setUint8(E++,m.length),S.setUint8(E++,d.length),S.setUint8(E++,u.length),S.setUint8(E++,p.length),S.setUint8(E++,v.length),S.setUint8(E++,i),Array.from(m,N=>S.setUint8(E++,N.charCodeAt(0))),Array.from(d,N=>S.setUint8(E++,N.charCodeAt(0))),Array.from(u,N=>S.setUint8(E++,N.charCodeAt(0))),Array.from(p,N=>S.setUint8(E++,N.charCodeAt(0))),Array.from(v,N=>S.setUint8(E++,N.charCodeAt(0)));var R=new Uint8Array(_.byteLength+a.byteLength);return R.set(new Uint8Array(_),0),R.set(new Uint8Array(a),_.byteLength),R.buffer}decode(e,i){if(this._isArrayBuffer(e)){let a=this._binaryDecode(e);return i(a)}if(typeof e=="string"){const a=JSON.parse(e),[l,c,u,d,m]=a;return i({join_ref:l,ref:c,topic:u,event:d,payload:m})}return i({})}_binaryDecode(e){const i=new DataView(e),a=i.getUint8(0),l=new TextDecoder;switch(a){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,i,l)}}_decodeUserBroadcast(e,i,a){const l=i.getUint8(1),c=i.getUint8(2),u=i.getUint8(3),d=i.getUint8(4);let m=this.HEADER_LENGTH+4;const p=a.decode(e.slice(m,m+l));m=m+l;const y=a.decode(e.slice(m,m+c));m=m+c;const v=a.decode(e.slice(m,m+u));m=m+u;const x=e.slice(m,e.byteLength),_=d===this.JSON_ENCODING?JSON.parse(a.decode(x)):x,S={type:this.BROADCAST_EVENT,event:y,payload:_};return u>0&&(S.meta=JSON.parse(v)),{join_ref:null,ref:null,topic:p,event:this.BROADCAST_EVENT,payload:S}}_isArrayBuffer(e){var i;return e instanceof ArrayBuffer||((i=e==null?void 0:e.constructor)===null||i===void 0?void 0:i.name)==="ArrayBuffer"}_pick(e,i){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([a])=>i.includes(a)))}}var Ke;(function(n){n.abstime="abstime",n.bool="bool",n.date="date",n.daterange="daterange",n.float4="float4",n.float8="float8",n.int2="int2",n.int4="int4",n.int4range="int4range",n.int8="int8",n.int8range="int8range",n.json="json",n.jsonb="jsonb",n.money="money",n.numeric="numeric",n.oid="oid",n.reltime="reltime",n.text="text",n.time="time",n.timestamp="timestamp",n.timestamptz="timestamptz",n.timetz="timetz",n.tsrange="tsrange",n.tstzrange="tstzrange"})(Ke||(Ke={}));const Cb=(n,e,i={})=>{var a;const l=(a=i.skipTypes)!==null&&a!==void 0?a:[];return e?Object.keys(e).reduce((c,u)=>(c[u]=EC(u,n,e,l),c),{}):{}},EC=(n,e,i,a)=>{const l=e.find(d=>d.name===n),c=l==null?void 0:l.type,u=i[n];return c&&!a.includes(c)?mw(c,u):af(u)},mw=(n,e)=>{if(n.charAt(0)==="_"){const i=n.slice(1,n.length);return RC(e,i)}switch(n){case Ke.bool:return AC(e);case Ke.float4:case Ke.float8:case Ke.int2:case Ke.int4:case Ke.int8:case Ke.numeric:case Ke.oid:return jC(e);case Ke.json:case Ke.jsonb:return CC(e);case Ke.timestamp:return NC(e);case Ke.abstime:case Ke.date:case Ke.daterange:case Ke.int4range:case Ke.int8range:case Ke.money:case Ke.reltime:case Ke.text:case Ke.time:case Ke.timestamptz:case Ke.timetz:case Ke.tsrange:case Ke.tstzrange:return af(e);default:return af(e)}},af=n=>n,AC=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},jC=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},CC=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n},RC=(n,e)=>{if(typeof n!="string")return n;const i=n.length-1,a=n[i];if(n[0]==="{"&&a==="}"){let c;const u=n.slice(1,i);try{c=JSON.parse("["+u+"]")}catch{c=u?u.split(","):[]}return c.map(d=>mw(e,d))}return n},NC=n=>typeof n=="string"?n.replace(" ","T"):n,pw=n=>{const e=new URL(n);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var Qr=n=>typeof n=="function"?n:function(){return n},kC=typeof self<"u"?self:null,Na=typeof window<"u"?window:null,Kn=kC||Na||globalThis,OC="2.0.0",DC=1e4,MC=1e3,Xn={connecting:0,open:1,closing:2,closed:3},Jt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ss={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},rf={longpoll:"longpoll",websocket:"websocket"},BC={complete:4},of="base64url.bearer.phx.",Fl=class{constructor(n,e,i,a){this.channel=n,this.event=e,this.payload=i||function(){return{}},this.receivedResp=null,this.timeout=a,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(n){this.timeout=n,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(n,e){return this.hasReceived(n)&&e(this.receivedResp.response),this.recHooks.push({status:n,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:n,response:e,_ref:i}){this.recHooks.filter(a=>a.status===n).forEach(a=>a.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,n=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=n,this.matchReceive(n)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(n){return this.receivedResp&&this.receivedResp.status===n}trigger(n,e){this.channel.trigger(this.refEvent,{status:n,response:e})}},gw=class{constructor(n,e){this.callback=n,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},UC=class{constructor(n,e,i){this.state=Jt.closed,this.topic=n,this.params=Qr(e||{}),this.socket=i,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Fl(this,Ss.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new gw(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Jt.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this.joinPush.receive("error",a=>{this.state=Jt.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Jt.closed,this.socket.remove(this)}),this.onError(a=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.isJoining()&&this.joinPush.reset(),this.state=Jt.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Fl(this,Ss.leave,Qr({}),this.timeout).send(),this.state=Jt.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Ss.reply,(a,l)=>{this.trigger(this.replyEventName(l),a)})}join(n=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=n,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(n=>n.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Jt.closed,this.bindings=[]}onClose(n){this.on(Ss.close,n)}onError(n){return this.on(Ss.error,e=>n(e))}on(n,e){let i=this.bindingRef++;return this.bindings.push({event:n,ref:i,callback:e}),i}off(n,e){this.bindings=this.bindings.filter(i=>!(i.event===n&&(typeof e>"u"||e===i.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(n,e,i=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${n}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let a=new Fl(this,n,function(){return e},i);return this.canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}leave(n=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Jt.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Ss.close,"leave")},i=new Fl(this,Ss.leave,Qr({}),n);return i.receive("ok",()=>e()).receive("timeout",()=>e()),i.send(),this.canPush()||i.trigger("ok",{}),i}onMessage(n,e,i){return e}filterBindings(n,e,i){return!0}isMember(n,e,i,a){return this.topic!==n?!1:a&&a!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:n,event:e,payload:i,joinRef:a}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(n=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Jt.joining,this.joinPush.resend(n))}trigger(n,e,i,a){let l=this.onMessage(n,e,i,a);if(e&&!l)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let c=this.bindings.filter(u=>u.event===n&&this.filterBindings(u,e,i));for(let u=0;um.abort(),l),d.signal=m.signal),Kn.fetch(e,d).then(p=>p.text()).then(p=>this.parseJSON(p)).then(p=>u&&u(p)).catch(p=>{p.name==="AbortError"&&c?c():u&&u(null)}),m}static xdomainRequest(n,e,i,a,l,c,u){return n.timeout=l,n.open(e,i),n.onload=()=>{let d=this.parseJSON(n.responseText);u&&u(d)},c&&(n.ontimeout=c),n.onprogress=()=>{},n.send(a),n}static xhrRequest(n,e,i,a,l,c,u,d){n.open(e,i,!0),n.timeout=c;for(let[m,p]of Object.entries(a))n.setRequestHeader(m,p);return n.onerror=()=>d&&d(null),n.onreadystatechange=()=>{if(n.readyState===BC.complete&&d){let m=this.parseJSON(n.responseText);d(m)}},u&&(n.ontimeout=u),n.send(l),n}static parseJSON(n){if(!n||n==="")return null;try{return JSON.parse(n)}catch{return console&&console.log("failed to parse JSON response",n),null}}static serialize(n,e){let i=[];for(var a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let l=e?`${e}[${a}]`:a,c=n[a];typeof c=="object"?i.push(this.serialize(c,l)):i.push(encodeURIComponent(l)+"="+encodeURIComponent(c))}return i.join("&")}static appendParams(n,e){if(Object.keys(e).length===0)return n;let i=n.match(/\?/)?"&":"?";return`${n}${i}${this.serialize(e)}`}},LC=n=>{let e="",i=new Uint8Array(n),a=i.byteLength;for(let l=0;lthis.poll(),0)}normalizeEndpoint(n){return n.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+rf.websocket),"$1/"+rf.longpoll)}endpointURL(){return wc.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(n,e,i){this.close(n,e,i),this.readyState=Xn.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Xn.open||this.readyState===Xn.connecting}poll(){const n={Accept:"application/json"};this.authToken&&(n["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",n,null,()=>this.ontimeout(),e=>{if(e){var{status:i,token:a,messages:l}=e;if(i===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=a}else i=0;switch(i){case 200:l.forEach(c=>{setTimeout(()=>this.onmessage({data:c}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Xn.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${i}`)}})}send(n){typeof n!="string"&&(n=LC(n)),this.currentBatch?this.currentBatch.push(n):this.awaitingBatchAck?this.batchBuffer.push(n):(this.currentBatch=[n],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(n){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},n.join(` `),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(n,e,i){for(let l of this.reqs)l.abort();this.readyState=Xn.closed;let a=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:n,reason:e,wasClean:i});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",a)):this.onclose(a)}ajax(n,e,i,a,l){let c,u=()=>{this.reqs.delete(c),a()};c=wc.request(n,this.endpointURL(),e,i,this.timeout,u,d=>{this.reqs.delete(c),this.isActive()&&l(d)}),this.reqs.add(c)}},zC=class $r{constructor(e,i={}){let a=i.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(a.state,l=>{let{onJoin:c,onLeave:u,onSync:d}=this.caller;this.joinRef=this.channel.joinRef(),this.state=$r.syncState(this.state,l,c,u),this.pendingDiffs.forEach(m=>{this.state=$r.syncDiff(this.state,m,c,u)}),this.pendingDiffs=[],d()}),this.channel.on(a.diff,l=>{let{onJoin:c,onLeave:u,onSync:d}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(l):(this.state=$r.syncDiff(this.state,l,c,u),d())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return $r.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,i,a,l){let c=this.clone(e),u={},d={};return this.map(c,(m,p)=>{i[m]||(d[m]=p)}),this.map(i,(m,p)=>{let y=c[m];if(y){let v=p.metas.map(E=>E.phx_ref),x=y.metas.map(E=>E.phx_ref),_=p.metas.filter(E=>x.indexOf(E.phx_ref)<0),S=y.metas.filter(E=>v.indexOf(E.phx_ref)<0);_.length>0&&(u[m]=p,u[m].metas=_),S.length>0&&(d[m]=this.clone(y),d[m].metas=S)}else u[m]=p}),this.syncDiff(c,{joins:u,leaves:d},a,l)}static syncDiff(e,i,a,l){let{joins:c,leaves:u}=this.clone(i);return a||(a=function(){}),l||(l=function(){}),this.map(c,(d,m)=>{let p=e[d];if(e[d]=this.clone(m),p){let y=e[d].metas.map(x=>x.phx_ref),v=p.metas.filter(x=>y.indexOf(x.phx_ref)<0);e[d].metas.unshift(...v)}a(d,p,m)}),this.map(u,(d,m)=>{let p=e[d];if(!p)return;let y=m.metas.map(v=>v.phx_ref);p.metas=p.metas.filter(v=>y.indexOf(v.phx_ref)<0),l(d,p,m),p.metas.length===0&&delete e[d]}),e}static list(e,i){return i||(i=function(a,l){return l}),this.map(e,(a,l)=>i(a,l))}static map(e,i){return Object.getOwnPropertyNames(e).map(a=>i(a,e[a]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Gl={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(n,e){if(n.payload.constructor===ArrayBuffer)return e(this.binaryEncode(n));{let i=[n.join_ref,n.ref,n.topic,n.event,n.payload];return e(JSON.stringify(i))}},decode(n,e){if(n.constructor===ArrayBuffer)return e(this.binaryDecode(n));{let[i,a,l,c,u]=JSON.parse(n);return e({join_ref:i,ref:a,topic:l,event:c,payload:u})}},binaryEncode(n){let{join_ref:e,ref:i,event:a,topic:l,payload:c}=n,u=this.META_LENGTH+e.length+i.length+l.length+a.length,d=new ArrayBuffer(this.HEADER_LENGTH+u),m=new DataView(d),p=0;m.setUint8(p++,this.KINDS.push),m.setUint8(p++,e.length),m.setUint8(p++,i.length),m.setUint8(p++,l.length),m.setUint8(p++,a.length),Array.from(e,v=>m.setUint8(p++,v.charCodeAt(0))),Array.from(i,v=>m.setUint8(p++,v.charCodeAt(0))),Array.from(l,v=>m.setUint8(p++,v.charCodeAt(0))),Array.from(a,v=>m.setUint8(p++,v.charCodeAt(0)));var y=new Uint8Array(d.byteLength+c.byteLength);return y.set(new Uint8Array(d),0),y.set(new Uint8Array(c),d.byteLength),y.buffer},binaryDecode(n){let e=new DataView(n),i=e.getUint8(0),a=new TextDecoder;switch(i){case this.KINDS.push:return this.decodePush(n,e,a);case this.KINDS.reply:return this.decodeReply(n,e,a);case this.KINDS.broadcast:return this.decodeBroadcast(n,e,a)}},decodePush(n,e,i){let a=e.getUint8(1),l=e.getUint8(2),c=e.getUint8(3),u=this.HEADER_LENGTH+this.META_LENGTH-1,d=i.decode(n.slice(u,u+a));u=u+a;let m=i.decode(n.slice(u,u+l));u=u+l;let p=i.decode(n.slice(u,u+c));u=u+c;let y=n.slice(u,n.byteLength);return{join_ref:d,ref:null,topic:m,event:p,payload:y}},decodeReply(n,e,i){let a=e.getUint8(1),l=e.getUint8(2),c=e.getUint8(3),u=e.getUint8(4),d=this.HEADER_LENGTH+this.META_LENGTH,m=i.decode(n.slice(d,d+a));d=d+a;let p=i.decode(n.slice(d,d+l));d=d+l;let y=i.decode(n.slice(d,d+c));d=d+c;let v=i.decode(n.slice(d,d+u));d=d+u;let x=n.slice(d,n.byteLength),_={status:v,response:x};return{join_ref:m,ref:p,topic:y,event:Ss.reply,payload:_}},decodeBroadcast(n,e,i){let a=e.getUint8(1),l=e.getUint8(2),c=this.HEADER_LENGTH+2,u=i.decode(n.slice(c,c+a));c=c+a;let d=i.decode(n.slice(c,c+l));c=c+l;let m=n.slice(c,n.byteLength);return{join_ref:null,ref:null,topic:u,event:d,payload:m}}},VC=class{constructor(n,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||DC,this.transport=e.transport||Kn.WebSocket||Sa,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let i=null;try{i=Kn&&Kn.sessionStorage}catch{}this.sessionStore=e.sessionStorage||i,this.establishedConnections=0,this.defaultEncoder=Gl.encode.bind(Gl),this.defaultDecoder=Gl.decode.bind(Gl),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Sa?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let a=null;Na&&Na.addEventListener&&(Na.addEventListener("pagehide",l=>{this.conn&&(this.disconnect(),a=this.connectClock)}),Na.addEventListener("pageshow",l=>{a===this.connectClock&&(a=null,this.connect())}),Na.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=l=>e.rejoinAfterMs?e.rejoinAfterMs(l):[1e3,2e3,5e3][l-1]||1e4,this.reconnectAfterMs=l=>e.reconnectAfterMs?e.reconnectAfterMs(l):[10,50,100,150,200,250,500,1e3,2e3][l-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(l,c,u)=>{console.log(`${l}: ${c}`,u)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Qr(e.params||{}),this.endPoint=`${n}/${rf.websocket}`,this.vsn=e.vsn||OC,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new gw(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return Sa}replaceTransport(n){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=n}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let n=wc.appendParams(wc.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return n.charAt(0)!=="/"?n:n.charAt(1)==="/"?`${this.protocol()}:${n}`:`${this.protocol()}://${location.host}${n}`}disconnect(n,e,i){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,n&&n()},e,i)}connect(n){n&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Qr(n)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Sa?this.connectWithFallback(Sa,this.longPollFallbackMs):this.transportConnect())}log(n,e,i){this.logger&&this.logger(n,e,i)}hasLogger(){return this.logger!==null}onOpen(n){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,n]),e}onClose(n){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,n]),e}onError(n){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,n]),e}onMessage(n){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,n]),e}onHeartbeat(n){this.heartbeatCallback=n}ping(n){if(!this.isConnected())return!1;let e=this.makeRef(),i=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let a=this.onMessage(l=>{l.ref===e&&(this.off([a]),n(Date.now()-i))});return!0}transportName(n){switch(n){case Sa:return"LongPoll";default:return n.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let n;this.authToken&&(n=["phoenix",`${of}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),n),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(n){return this.sessionStore&&this.sessionStore.getItem(n)}storeSession(n,e){this.sessionStore&&this.sessionStore.setItem(n,e)}connectWithFallback(n,e=2500){clearTimeout(this.fallbackTimer);let i=!1,a=!0,l,c,u=this.transportName(n),d=m=>{this.log("transport",`falling back to ${u}...`,m),this.off([l,c]),a=!1,this.replaceTransport(n),this.transportConnect()};if(this.getSession(`phx:fallback:${u}`))return d("memorized");this.fallbackTimer=setTimeout(d,e),c=this.onError(m=>{this.log("transport","error",m),a&&!i&&(clearTimeout(this.fallbackTimer),d(m))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(i=!0,!a){let m=this.transportName(n);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${m}`,"true"),this.log("transport",`established ${m} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(d,e),this.ping(m=>{this.log("transport","connected to primary after",m),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(n){this.log("error","error in heartbeat callback",n)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),MC,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(n,e,i){if(!this.conn)return n&&n();const a=this.conn;this.waitForBufferDone(a,()=>{e?a.close(e,i||""):a.close(),this.waitForSocketClosed(a,()=>{this.conn===a&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),n&&n()})})}waitForBufferDone(n,e,i=1){if(i===5||!n.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(n,e,i+1)},150*i)}waitForSocketClosed(n,e,i=1){if(i===5||n.readyState===Xn.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(n,e,i+1)},150*i)}onConnClose(n){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",n),this.triggerChanError(n),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",n)}onConnError(n){this.hasLogger()&&this.log("transport","error",n);let e=this.transport,i=this.establishedConnections;this.triggerStateCallbacks("error",n,e,i),(e===this.transport||i>0)&&this.triggerChanError(n)}triggerChanError(n){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(Ss.error,n)})}connectionState(){switch(this.conn&&this.conn.readyState){case Xn.connecting:return"connecting";case Xn.open:return"open";case Xn.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(n){this.off(n.stateChangeRefs),this.channels=this.channels.filter(e=>e!==n)}off(n){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([i])=>n.indexOf(i)===-1)}channel(n,e={}){let i=new UC(n,e,this);return this.channels.push(i),i}push(n){if(this.hasLogger()){let{topic:e,event:i,payload:a,ref:l,join_ref:c}=n;this.log("push",`${e} ${i} (${c}, ${l})`,a)}this.isConnected()?this.encode(n,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(n,e=>this.conn.send(e)))}makeRef(){let n=this.ref+1;return n===this.ref?this.ref=0:this.ref=n,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(n){this.log("error","error in heartbeat callback",n)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(n){this.log("error","error in heartbeat callback",n)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(n=>n()),this.sendBuffer=[])}onConnMessage(n){this.decode(n.data,e=>{let{topic:i,event:a,payload:l,ref:c,join_ref:u}=e;if(c&&c===this.pendingHeartbeatRef){const d=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(l.status==="ok"?"ok":"error",d)}catch(m){this.log("error","error in heartbeat callback",m)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${l.status||""} ${i} ${a} ${c&&"("+c+")"||""}`.trim(),l);for(let d=0;d{try{a(...e)}catch(l){this.log("error",`error in ${n} callback`,l)}})}catch(i){this.log("error",`error triggering ${n} callbacks`,i)}}leaveOpenTopic(n){let e=this.channels.find(i=>i.topic===n&&(i.isJoined()||i.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${n}"`),e.leave())}};class Zr{constructor(e,i){const a=HC(i);this.presence=new zC(e.getChannel(),a),this.presence.onJoin((l,c,u)=>{const d=Zr.onJoinPayload(l,c,u);e.getChannel().trigger("presence",d)}),this.presence.onLeave((l,c,u)=>{const d=Zr.onLeavePayload(l,c,u);e.getChannel().trigger("presence",d)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Zr.transformState(this.presence.state)}static transformState(e){return e=PC(e),Object.getOwnPropertyNames(e).reduce((i,a)=>{const l=e[a];return i[a]=cc(l),i},{})}static onJoinPayload(e,i,a){const l=Rb(i),c=cc(a);return{event:"join",key:e,currentPresences:l,newPresences:c}}static onLeavePayload(e,i,a){const l=Rb(i),c=cc(a);return{event:"leave",key:e,currentPresences:l,leftPresences:c}}}function cc(n){return n.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function PC(n){return JSON.parse(JSON.stringify(n))}function HC(n){return(n==null?void 0:n.events)&&{events:n.events}}function Rb(n){return n!=null&&n.metas?cc(n):[]}var Nb;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(Nb||(Nb={}));class qC{get state(){return this.presenceAdapter.state}constructor(e,i){this.channel=e,this.presenceAdapter=new Zr(this.channel.channelAdapter,i)}}function $C(n){if(n instanceof Error)return n;if(typeof n=="string")return new Error(n);if(n&&typeof n=="object"){const e=n;if(typeof e.code=="number"){const i=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${i}`,{cause:n})}return new Error("channel error: transport failure",{cause:n})}return new Error("channel error: connection lost")}class IC{constructor(e,i,a){const l=FC(a);this.channel=e.getSocket().channel(i,l),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,i){return this.channel.on(e,i)}off(e,i){this.channel.off(e,i)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,i,a){let l;try{l=this.channel.push(e,i,a)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>SC){const c=this.channel.pushBuffer.shift();c.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${c.event}`,c.payload())}return l}updateJoinPayload(e){const i=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},i),e)}canPush(){return this.socket.isConnected()&&this.state===Zs.joined}isJoined(){return this.state===Zs.joined}isJoining(){return this.state===Zs.joining}isClosed(){return this.state===Zs.closed}isLeaving(){return this.state===Zs.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function FC(n){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config)}}const GC=/[,()"\\]/,KC=n=>GC.test(n)||n!==n.trim(),YC=n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,kb=n=>{const e=n===null?"null":String(n);return KC(e)?YC(e):e},XC=n=>n===null?"null":String(n),JC=(n,e)=>{if(n==="in"){const i=Array.isArray(e)?e:[e];if(i.length===0)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(i)).map(l=>kb(l)).join(",")})`}return n==="is"?`is.${XC(e)}`:`${n}.${kb(e)}`};class QC{constructor(){this.filters=[]}add(e,i,a,l=!1){const c=l?"not.":"";return this.filters.push(`${e}=${c}${JC(i,a)}`),this}eq(e,i){return this.add(e,"eq",i)}neq(e,i){return this.add(e,"neq",i)}gt(e,i){return this.add(e,"gt",i)}gte(e,i){return this.add(e,"gte",i)}lt(e,i){return this.add(e,"lt",i)}lte(e,i){return this.add(e,"lte",i)}in(e,i){return this.add(e,"in",i)}like(e,i){return this.add(e,"like",i)}ilike(e,i){return this.add(e,"ilike",i)}match(e,i){return this.add(e,"match",i)}imatch(e,i){return this.add(e,"imatch",i)}is(e,i){return this.add(e,"is",i)}isDistinct(e,i){return this.add(e,"isdistinct",i)}not(e,i,a){return this.add(e,i,a,!0)}build(){return this.filters.join(",")}toString(){return this.build()}}var Ob;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(Ob||(Ob={}));var Ua;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes",n.SYSTEM="system"})(Ua||(Ua={}));var Ts;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(Ts||(Ts={}));class Wr{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,i={config:{}},a){var l,c;if(this.topic=e,this.params=i,this.socket=a,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},i.config),this.channelAdapter=new IC(this.socket.socketAdapter,e,this.params),this.presence=new qC(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=pw(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((c=(l=this.params.config)===null||l===void 0?void 0:l.broadcast)===null||c===void 0)&&c.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,i=this.timeout){var a,l,c;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:u,presence:d,private:m}}=this.params,p=(l=(a=this.bindings.postgres_changes)===null||a===void 0?void 0:a.map(_=>_.filter))!==null&&l!==void 0?l:[],y=!!this.bindings[Ua.PRESENCE]&&this.bindings[Ua.PRESENCE].length>0||((c=this.params.config.presence)===null||c===void 0?void 0:c.enabled)===!0,v={},x={broadcast:u,presence:Object.assign(Object.assign({},d),{enabled:y}),postgres_changes:p,private:m};this.socket.accessTokenValue&&(v.access_token=this.socket.accessTokenValue),this._onError(_=>{e==null||e(Ts.CHANNEL_ERROR,$C(_))}),this._onClose(()=>e==null?void 0:e(Ts.CLOSED)),this.updateJoinPayload(Object.assign({config:x},v)),this._updateFilterMessage(),this.channelAdapter.subscribe(i).receive("ok",async({postgres_changes:_})=>{if(this.socket._isManualToken()||this.socket.setAuth(),_===void 0){e==null||e(Ts.SUBSCRIBED);return}this._updatePostgresBindings(_,e)}).receive("error",_=>{this.state=Zs.errored;const S=Object.values(_).join(", ")||"error";e==null||e(Ts.CHANNEL_ERROR,new Error(S,{cause:_}))}).receive("timeout",()=>{e==null||e(Ts.TIMED_OUT)})}return this}_updatePostgresBindings(e,i){var a;const l=this.bindings.postgres_changes,c=(a=l==null?void 0:l.length)!==null&&a!==void 0?a:0,u=[];for(let d=0;d{var u,d,m;const p=this.channelAdapter.push(e.type,e,i.timeout||this.timeout);e.type==="broadcast"&&!(!((m=(d=(u=this.params)===null||u===void 0?void 0:u.config)===null||d===void 0?void 0:d.broadcast)===null||m===void 0)&&m.ack)&&c("ok"),p.receive("ok",()=>c("ok")),p.receive("error",()=>c("error")),p.receive("timeout",()=>c("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(i=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>i("ok")).receive("timeout",()=>i("timed out")).receive("error",()=>i("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,i,a){const l=new AbortController,c=setTimeout(()=>l.abort(),a),u=await this.socket.fetch(e,Object.assign(Object.assign({},i),{signal:l.signal}));return clearTimeout(c),u}_on(e,i,a){const l=e.toLocaleLowerCase(),c=i==null?void 0:i.filter;(c instanceof QC||typeof c=="object"&&c!==null&&typeof c.build=="function")&&(i=Object.assign(Object.assign({},i),{filter:c.build()}));const u=this.channelAdapter.on(e,a),d={type:l,filter:i,callback:a,ref:u};return this.bindings[l]?this.bindings[l].push(d):this.bindings[l]=[d],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,i,a)=>{var l,c,u,d,m,p,y;const v=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(v,a))return!1;const x=(l=this.bindings[v])===null||l===void 0?void 0:l.find(_=>_.ref===e.ref);if(!x)return!0;if(["broadcast","presence","postgres_changes"].includes(v))if("id"in x){const _=x.id,S=(c=x.filter)===null||c===void 0?void 0:c.event;return _&&((u=i.ids)===null||u===void 0?void 0:u.includes(_))&&(S==="*"||(S==null?void 0:S.toLocaleLowerCase())===((d=i.data)===null||d===void 0?void 0:d.type.toLocaleLowerCase()))}else{const _=(p=(m=x==null?void 0:x.filter)===null||m===void 0?void 0:m.event)===null||p===void 0?void 0:p.toLocaleLowerCase();return _==="*"||_===((y=i==null?void 0:i.event)===null||y===void 0?void 0:y.toLocaleLowerCase())}else return x.type.toLocaleLowerCase()===v})}_notThisChannelEvent(e,i){const{close:a,error:l,leave:c,join:u}=fw;return i&&[a,l,c,u].includes(e)&&i!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,i,a)=>{if(typeof i=="object"&&"ids"in i){const l=i.data,{schema:c,table:u,commit_timestamp:d,type:m,errors:p}=l;return Object.assign(Object.assign({},{schema:c,table:u,commit_timestamp:d,eventType:m,new:{},old:{},errors:p}),this._getPayloadRecords(l))}return i})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const i in e.bindings)for(const a of e.bindings[i])this._on(a.type,a.filter,a.callback)}static isFilterValueEqual(e,i){return(e??void 0)===(i??void 0)}_getPayloadRecords(e){const i={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(i.new=Cb(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(i.old=Cb(e.columns,e.old_record)),i}}class ZC{constructor(e,i){this.socket=new VC(e,i)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,i,a,l=1e4){return new Promise(c=>{setTimeout(()=>c("timeout"),l),this.socket.disconnect(()=>{e(),c("ok")},i,a)})}push(e){this.socket.push(e)}log(e,i,a){this.socket.log(e,i,a)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==sf.connecting}isDisconnecting(){return this.socket.connectionState()==sf.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const Db={HEARTBEAT_INTERVAL:25e3},WC=[1e3,2e3,5e3,1e4],eR=1e4;function tR(){const n=new Map;return{get length(){return n.size},clear(){n.clear()},getItem(e){return n.has(e)?n.get(e):null},key(e){var i;return(i=Array.from(n.keys())[e])!==null&&i!==void 0?i:null},removeItem(e){n.delete(e)},setItem(e,i){n.set(e,String(i))}}}function nR(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return tR()}const sR=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class iR{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,i){var a;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new TC,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=c=>c?(...u)=>c(...u):(...u)=>fetch(...u),!(!((a=i==null?void 0:i.params)===null||a===void 0)&&a.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=i.params.apikey;const l=this._initializeOptions(i);this.socketAdapter=new ZC(e,l),this.httpEndpoint=pw(e),this.fetch=this._resolveFetch(i==null?void 0:i.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const i=e.message;throw new Error(`WebSocket not available: ${i}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,i){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,i)}getChannels(){return this.channels}async removeChannel(e){const i=await e.unsubscribe();return i==="ok"&&e.teardown(),i}async removeAllChannels(){const e=this.channels.map(async a=>{const l=await a.unsubscribe();return a.teardown(),l}),i=await Promise.all(e);return await this.disconnect(),i}log(e,i,a){this.socketAdapter.log(e,i,a)}connectionState(){return this.socketAdapter.connectionState()||sf.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,i={config:{}}){const a=`realtime:${e}`,l=this.getChannels().find(c=>c.topic===a);if(l)return l;{const c=new Wr(`realtime:${e}`,i,this);return this._cancelPendingDisconnect(),this.channels.push(c),c}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(i=>i.topic!==e.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let i,a=!1;if(e)i=e,a=!0;else if(this.accessToken)try{i=await this.accessToken()}catch(l){this.log("error","Error fetching access token from callback",l),i=this.accessTokenValue}else i=this.accessTokenValue;a?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=i&&(this.accessTokenValue=i,this.channels.forEach(l=>{const c={access_token:i,version:vC};i&&l.updateJoinPayload(c),l.joinedOnce&&l.channelAdapter.isJoined()&&l.channelAdapter.push(fw.access_token,{access_token:i})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(i=>{this.log("error",`Error setting auth in ${e}`,i)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(i=>{this.log("error","error waiting for auth on connect",i)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(i,a)=>{i!=="disconnected"&&(i=="sent"&&this._setAuthSafely(),e&&e(i,a))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=i=>{this.log("worker","worker error",i.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=i=>{i.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let i;if(e)i=e;else{const a=new Blob([sR],{type:"application/javascript"});i=URL.createObjectURL(a)}return i}_initializeOptions(e){var i,a,l,c,u,d,m,p,y,v,x,_;this.worker=(i=e==null?void 0:e.worker)!==null&&i!==void 0?i:!1,this.accessToken=(a=e==null?void 0:e.accessToken)!==null&&a!==void 0?a:null;const S={};S.timeout=(l=e==null?void 0:e.timeout)!==null&&l!==void 0?l:_C,S.heartbeatIntervalMs=(c=e==null?void 0:e.heartbeatIntervalMs)!==null&&c!==void 0?c:Db.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(u=e==null?void 0:e.disconnectOnEmptyChannelsAfterMs)!==null&&u!==void 0?u:2*((d=e==null?void 0:e.heartbeatIntervalMs)!==null&&d!==void 0?d:Db.HEARTBEAT_INTERVAL),S.transport=(m=e==null?void 0:e.transport)!==null&&m!==void 0?m:yC.getWebSocketConstructor(),S.params=e==null?void 0:e.params,S.logger=e==null?void 0:e.logger,S.heartbeatCallback=this._wrapHeartbeatCallback(e==null?void 0:e.heartbeatCallback),S.sessionStorage=(p=e==null?void 0:e.sessionStorage)!==null&&p!==void 0?p:nR(),S.reconnectAfterMs=(y=e==null?void 0:e.reconnectAfterMs)!==null&&y!==void 0?y:(O=>WC[O-1]||eR);let E,R;const N=(v=e==null?void 0:e.vsn)!==null&&v!==void 0?v:wC;switch(N){case xC:E=(O,C)=>C(JSON.stringify(O)),R=(O,C)=>C(JSON.parse(O));break;case dw:E=this.serializer.encode.bind(this.serializer),R=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${S.vsn}`)}if(S.vsn=N,S.encode=(x=e==null?void 0:e.encode)!==null&&x!==void 0?x:E,S.decode=(_=e==null?void 0:e.decode)!==null&&_!==void 0?_:R,S.beforeReconnect=this._reconnectAuth.bind(this),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,S.params=Object.assign(Object.assign({},S.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl,S.autoSendHeartbeat=!this.worker}return S}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var co=class extends Error{constructor(n,e){var i;super(n),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((i=e.icebergType)==null?void 0:i.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function aR(n,e,i){const a=new URL(e,n);if(i)for(const[l,c]of Object.entries(i))c!==void 0&&a.searchParams.set(l,c);return a.toString()}async function rR(n){return!n||n.type==="none"?{}:n.type==="bearer"?{Authorization:`Bearer ${n.token}`}:n.type==="header"?{[n.name]:n.value}:n.type==="custom"?await n.getHeaders():{}}function oR(n){const e=n.fetchImpl??globalThis.fetch;return{async request({method:i,path:a,query:l,body:c,headers:u}){const d=aR(n.baseUrl,a,l),m=await rR(n.auth),p=await e(d,{method:i,headers:{...c?{"Content-Type":"application/json"}:{},...m,...u},body:c?JSON.stringify(c):void 0}),y=await p.text(),v=(p.headers.get("content-type")||"").includes("application/json"),x=v&&y?JSON.parse(y):y;if(!p.ok){const _=v?x:void 0,S=_==null?void 0:_.error;throw new co((S==null?void 0:S.message)??`Request failed with status ${p.status}`,{status:p.status,icebergType:S==null?void 0:S.type,icebergCode:S==null?void 0:S.code,details:_})}return{status:p.status,headers:p.headers,data:x}}}}function Kl(n){return n.join("")}var lR=class{constructor(n,e=""){this.client=n,this.prefix=e}async listNamespaces(n){const e=n?{parent:Kl(n.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(a=>({namespace:a}))}async createNamespace(n,e){const i={namespace:n.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:i})).data}async dropNamespace(n){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Kl(n.namespace)}`})}async loadNamespaceMetadata(n){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Kl(n.namespace)}`})).data.properties}}async namespaceExists(n){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Kl(n.namespace)}`}),!0}catch(e){if(e instanceof co&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(n,e){try{return await this.createNamespace(n,e)}catch(i){if(i instanceof co&&i.status===409)return;throw i}}};function Ta(n){return n.join("")}var cR=class{constructor(n,e="",i){this.client=n,this.prefix=e,this.accessDelegation=i}async listTables(n){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ta(n.namespace)}/tables`})).data.identifiers}async createTable(n,e){const i={};return this.accessDelegation&&(i["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ta(n.namespace)}/tables`,body:e,headers:i})).data.metadata}async updateTable(n,e){const i=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ta(n.namespace)}/tables/${n.name}`,body:e});return{"metadata-location":i.data["metadata-location"],metadata:i.data.metadata}}async dropTable(n,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ta(n.namespace)}/tables/${n.name}`,query:{purgeRequested:String((e==null?void 0:e.purge)??!1)}})}async loadTable(n){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ta(n.namespace)}/tables/${n.name}`,headers:e})).data.metadata}async tableExists(n){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ta(n.namespace)}/tables/${n.name}`,headers:e}),!0}catch(i){if(i instanceof co&&i.status===404)return!1;throw i}}async createTableIfNotExists(n,e){try{return await this.createTable(n,e)}catch(i){if(i instanceof co&&i.status===409)return await this.loadTable({namespace:n.namespace,name:e.name});throw i}}},uR=class{constructor(n){var a;let e="v1";n.catalogName&&(e+=`/${n.catalogName}`);const i=n.baseUrl.endsWith("/")?n.baseUrl:`${n.baseUrl}/`;this.client=oR({baseUrl:i,auth:n.auth,fetchImpl:n.fetch}),this.accessDelegation=(a=n.accessDelegation)==null?void 0:a.join(","),this.namespaceOps=new lR(this.client,e),this.tableOps=new cR(this.client,e,this.accessDelegation)}async listNamespaces(n){return this.namespaceOps.listNamespaces(n)}async createNamespace(n,e){return this.namespaceOps.createNamespace(n,e)}async dropNamespace(n){await this.namespaceOps.dropNamespace(n)}async loadNamespaceMetadata(n){return this.namespaceOps.loadNamespaceMetadata(n)}async listTables(n){return this.tableOps.listTables(n)}async createTable(n,e){return this.tableOps.createTable(n,e)}async updateTable(n,e){return this.tableOps.updateTable(n,e)}async dropTable(n,e){await this.tableOps.dropTable(n,e)}async loadTable(n){return this.tableOps.loadTable(n)}async namespaceExists(n){return this.namespaceOps.namespaceExists(n)}async tableExists(n){return this.tableOps.tableExists(n)}async createNamespaceIfNotExists(n,e){return this.namespaceOps.createNamespaceIfNotExists(n,e)}async createTableIfNotExists(n,e){return this.tableOps.createTableIfNotExists(n,e)}};function uo(n){"@babel/helpers - typeof";return uo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},uo(n)}function hR(n,e){if(uo(n)!="object"||!n)return n;var i=n[Symbol.toPrimitive];if(i!==void 0){var a=i.call(n,e);if(uo(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function dR(n){var e=hR(n,"string");return uo(e)=="symbol"?e:e+""}function fR(n,e,i){return(e=dR(e))in n?Object.defineProperty(n,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):n[e]=i,n}function Mb(n,e){var i=Object.keys(n);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(n);e&&(a=a.filter(function(l){return Object.getOwnPropertyDescriptor(n,l).enumerable})),i.push.apply(i,a)}return i}function me(n){for(var e=1;en?(...e)=>n(...e):(...e)=>fetch(...e),gR=n=>{if(typeof n!="object"||n===null)return!1;const e=Object.getPrototypeOf(n);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)},cf=n=>{if(Array.isArray(n))return n.map(i=>cf(i));if(typeof n=="function"||n!==Object(n))return n;const e={};return Object.entries(n).forEach(([i,a])=>{const l=i.replace(/([-_][a-z])/gi,c=>c.toUpperCase().replace(/[-_]/g,""));e[l]=cf(a)}),e},yR=n=>!n||typeof n!="string"||n.length===0||n.length>100||n.trim()!==n||n.includes("/")||n.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(n),Bb=n=>{if(typeof n=="object"&&n!==null){const e=n;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){const i=e.error;if(typeof i.message=="string")return i.message}}return JSON.stringify(n)},bR=async(n,e,i,a)=>{if(n!==null&&typeof n=="object"&&"json"in n&&typeof n.json=="function"){const l=n;let c=parseInt(String(l.status),10);Number.isFinite(c)||(c=500),l.json().then(u=>{const d=(u==null?void 0:u.statusCode)||(u==null?void 0:u.code)||c+"";e(new lf(Bb(u),c,d,a))}).catch(()=>{const u=c+"";e(new lf(l.statusText||`HTTP ${c} error`,c,u,a))})}else e(new yw(Bb(n),n,a))},vR=(n,e,i,a)=>{const l={method:n,headers:(e==null?void 0:e.headers)||{}};if(n==="GET"||n==="HEAD"||!a)return me(me({},l),i);if(gR(a)){var c;const u=(e==null?void 0:e.headers)||{};let d;for(const[m,p]of Object.entries(u))m.toLowerCase()==="content-type"&&(d=p);l.headers=_c(u,"Content-Type",(c=d)!==null&&c!==void 0?c:"application/json"),l.body=JSON.stringify(a)}else l.body=a;return e!=null&&e.duplex&&(l.duplex=e.duplex),me(me({},l),i)};async function Vr(n,e,i,a,l,c,u){return new Promise((d,m)=>{n(i,vR(e,a,l,c)).then(p=>{if(!p.ok)throw p;if(a!=null&&a.noResolveJson)return p;if(u==="vectors"){const y=p.headers.get("content-type");if(p.headers.get("content-length")==="0"||p.status===204)return{};if(!y||!y.includes("application/json"))return{}}return p.json()}).then(p=>d(p)).catch(p=>bR(p,m,a,u))})}function bw(n="storage"){return{get:async(e,i,a,l)=>Vr(e,"GET",i,a,l,void 0,n),post:async(e,i,a,l,c)=>Vr(e,"POST",i,l,c,a,n),put:async(e,i,a,l,c)=>Vr(e,"PUT",i,l,c,a,n),head:async(e,i,a,l)=>Vr(e,"HEAD",i,me(me({},a),{},{noResolveJson:!0}),l,void 0,n),remove:async(e,i,a,l,c)=>Vr(e,"DELETE",i,l,c,a,n)}}const xR=bw("storage"),{get:ho,post:Bn,put:uf,head:wR,remove:fo}=xR,un=bw("vectors");var Fa=class{constructor(n,e={},i,a="storage"){this.shouldThrowOnError=!1,this.url=n,this.headers=mR(e),this.fetch=pR(i),this.namespace=a}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(n,e){return this.headers=_c(this.headers,n,e),this}async handleOperation(n){var e=this;try{return{data:await n(),error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(Lc(i))return{data:null,error:i};throw i}}};let vw;vw=Symbol.toStringTag;var _R=class{constructor(n,e){this.downloadFn=n,this.shouldThrowOnError=e,this[vw]="StreamDownloadBuilder",this.promise=null}then(n,e){return this.getPromise().then(n,e)}catch(n){return this.getPromise().catch(n)}finally(n){return this.getPromise().finally(n)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var n=this;try{return{data:(await n.downloadFn()).body,error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(Lc(e))return{data:null,error:e};throw e}}};let xw;xw=Symbol.toStringTag;var SR=class{constructor(n,e){this.downloadFn=n,this.shouldThrowOnError=e,this[xw]="BlobDownloadBuilder",this.promise=null}asStream(){return new _R(this.downloadFn,this.shouldThrowOnError)}then(n,e){return this.getPromise().then(n,e)}catch(n){return this.getPromise().catch(n)}finally(n){return this.getPromise().finally(n)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var n=this;try{return{data:await(await n.downloadFn()).blob(),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(Lc(e))return{data:null,error:e};throw e}}};const vd={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ub={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var TR=class extends Fa{constructor(n,e={},i,a){super(n,e,a,"storage"),this.bucketId=i}async uploadOrUpdate(n,e,i,a){var l=this;return l.handleOperation(async()=>{let c;const u=me(me({},Ub),a);let d=me(me({},l.headers),n==="POST"&&{"x-upsert":String(u.upsert)});const m=u.metadata;if(typeof Blob<"u"&&i instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),m&&c.append("metadata",l.encodeMetadata(m)),c.append("",i)):typeof FormData<"u"&&i instanceof FormData?(c=i,c.has("cacheControl")||c.append("cacheControl",u.cacheControl),m&&!c.has("metadata")&&c.append("metadata",l.encodeMetadata(m))):(c=i,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType,m&&(d["x-metadata"]=l.toBase64(l.encodeMetadata(m))),(typeof ReadableStream<"u"&&c instanceof ReadableStream||c&&typeof c=="object"&&"pipe"in c&&typeof c.pipe=="function")&&!u.duplex&&(u.duplex="half")),a!=null&&a.headers)for(const[x,_]of Object.entries(a.headers))d=_c(d,x,_);const p=l._removeEmptyFolders(e),y=l._getFinalPath(p),v=await(n=="PUT"?uf:Bn)(l.fetch,`${l.url}/object/${y}`,c,me({headers:d},u!=null&&u.duplex?{duplex:u.duplex}:{}));return{path:p,id:v.Id,fullPath:v.Key}})}async upload(n,e,i){return this.uploadOrUpdate("POST",n,e,i)}async uploadToSignedUrl(n,e,i,a){var l=this;const c=l._removeEmptyFolders(n),u=l._getFinalPath(c),d=new URL(l.url+`/object/upload/sign/${u}`);return d.searchParams.set("token",e),l.handleOperation(async()=>{let m;const p=me(me({},Ub),a);let y=me(me({},l.headers),{"x-upsert":String(p.upsert)});const v=p.metadata;if(typeof Blob<"u"&&i instanceof Blob?(m=new FormData,m.append("cacheControl",p.cacheControl),v&&m.append("metadata",l.encodeMetadata(v)),m.append("",i)):typeof FormData<"u"&&i instanceof FormData?(m=i,m.has("cacheControl")||m.append("cacheControl",p.cacheControl),v&&!m.has("metadata")&&m.append("metadata",l.encodeMetadata(v))):(m=i,y["cache-control"]=`max-age=${p.cacheControl}`,y["content-type"]=p.contentType,v&&(y["x-metadata"]=l.toBase64(l.encodeMetadata(v))),(typeof ReadableStream<"u"&&m instanceof ReadableStream||m&&typeof m=="object"&&"pipe"in m&&typeof m.pipe=="function")&&!p.duplex&&(p.duplex="half")),a!=null&&a.headers)for(const[x,_]of Object.entries(a.headers))y=_c(y,x,_);return{path:c,fullPath:(await uf(l.fetch,d.toString(),m,me({headers:y},p!=null&&p.duplex?{duplex:p.duplex}:{}))).Key}})}async createSignedUploadUrl(n,e){var i=this;return i.handleOperation(async()=>{let a=i._getFinalPath(n);const l=me({},i.headers);e!=null&&e.upsert&&(l["x-upsert"]="true");const c=await Bn(i.fetch,`${i.url}/object/upload/sign/${a}`,{},{headers:l}),u=new URL(i.url+c.url),d=u.searchParams.get("token");if(!d)throw new Uc("No token returned by API");return{signedUrl:u.toString(),path:n,token:d}})}async update(n,e,i){return this.uploadOrUpdate("PUT",n,e,i)}async move(n,e,i){var a=this;return a.handleOperation(async()=>await Bn(a.fetch,`${a.url}/object/move`,{bucketId:a.bucketId,sourceKey:n,destinationKey:e,destinationBucket:i==null?void 0:i.destinationBucket},{headers:a.headers}))}async copy(n,e,i){var a=this;return a.handleOperation(async()=>({path:(await Bn(a.fetch,`${a.url}/object/copy`,{bucketId:a.bucketId,sourceKey:n,destinationKey:e,destinationBucket:i==null?void 0:i.destinationBucket},{headers:a.headers})).Key}))}async createSignedUrl(n,e,i){var a=this;return a.handleOperation(async()=>{let l=a._getFinalPath(n);const c=typeof(i==null?void 0:i.transform)=="object"&&i.transform!==null&&Object.keys(i.transform).length>0;let u=await Bn(a.fetch,`${a.url}/object/sign/${l}`,me({expiresIn:e},c?{transform:i.transform}:{}),{headers:a.headers});const d=new URLSearchParams;i!=null&&i.download&&d.set("download",i.download===!0?"":i.download),(i==null?void 0:i.cacheNonce)!=null&&d.set("cacheNonce",String(i.cacheNonce));const m=d.toString();return{signedUrl:encodeURI(`${a.url}${u.signedURL}${m?`&${m}`:""}`)}})}async createSignedUrls(n,e,i){var a=this;return a.handleOperation(async()=>{const l=await Bn(a.fetch,`${a.url}/object/sign/${a.bucketId}`,{expiresIn:e,paths:n},{headers:a.headers}),c=new URLSearchParams;i!=null&&i.download&&c.set("download",i.download===!0?"":i.download),(i==null?void 0:i.cacheNonce)!=null&&c.set("cacheNonce",String(i.cacheNonce));const u=c.toString();return l.map(d=>me(me({},d),{},{signedUrl:d.signedURL?encodeURI(`${a.url}${d.signedURL}${u?`&${u}`:""}`):null}))})}download(n,e,i){const a=typeof(e==null?void 0:e.transform)=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",l=new URLSearchParams;e!=null&&e.transform&&this.applyTransformOptsToQuery(l,e.transform),(e==null?void 0:e.cacheNonce)!=null&&l.set("cacheNonce",String(e.cacheNonce));const c=l.toString(),u=this._getFinalPath(n),d=()=>ho(this.fetch,`${this.url}/${a}/${u}${c?`?${c}`:""}`,{headers:this.headers,noResolveJson:!0},i);return new SR(d,this.shouldThrowOnError)}async info(n){var e=this;const i=e._getFinalPath(n);return e.handleOperation(async()=>cf(await ho(e.fetch,`${e.url}/object/info/${i}`,{headers:e.headers})))}async exists(n){var e=this;const i=e._getFinalPath(n);try{return await wR(e.fetch,`${e.url}/object/${i}`,{headers:e.headers}),{data:!0,error:null}}catch(l){if(e.shouldThrowOnError)throw l;if(Lc(l)){var a;const c=l instanceof lf?l.status:l instanceof yw?(a=l.originalError)===null||a===void 0?void 0:a.status:void 0;if(c!==void 0&&[400,404].includes(c))return{data:!1,error:l}}throw l}}getPublicUrl(n,e){const i=this._getFinalPath(n),a=new URLSearchParams;e!=null&&e.download&&a.set("download",e.download===!0?"":e.download),e!=null&&e.transform&&this.applyTransformOptsToQuery(a,e.transform),(e==null?void 0:e.cacheNonce)!=null&&a.set("cacheNonce",String(e.cacheNonce));const l=a.toString(),c=typeof(e==null?void 0:e.transform)=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${c}/public/${i}`)+(l?`?${l}`:"")}}}async remove(n){var e=this;return e.handleOperation(async()=>await fo(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:n},{headers:e.headers}))}async purgeCache(n,e,i){var a=this;return a.handleOperation(async()=>{const l=a._getFinalPath(n),c=new URLSearchParams;e!=null&&e.transformations&&c.set("transformations","true");const u=c.toString();return await fo(a.fetch,`${a.url}/cdn/${l}${u?`?${u}`:""}`,{},{headers:a.headers},i)})}async list(n,e,i){var a=this;return a.handleOperation(async()=>{const l=e!=null&&e.sortBy?me(me({},vd.sortBy),e.sortBy):vd.sortBy,c=me(me(me({},vd),e),{},{sortBy:l,prefix:n||""});return await Bn(a.fetch,`${a.url}/object/list/${a.bucketId}`,c,{headers:a.headers},i)})}async listV2(n,e){var i=this;return i.handleOperation(async()=>{const a=me({},n);return await Bn(i.fetch,`${i.url}/object/list-v2/${i.bucketId}`,a,{headers:i.headers},e)})}encodeMetadata(n){return JSON.stringify(n)}toBase64(n){return typeof Buffer<"u"?Buffer.from(n).toString("base64"):btoa(n)}_getFinalPath(n){return`${this.bucketId}/${n.replace(/^\/+/,"")}`}_removeEmptyFolders(n){return n.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(n,e){return e.width&&n.set("width",e.width.toString()),e.height&&n.set("height",e.height.toString()),e.resize&&n.set("resize",e.resize),e.format&&n.set("format",e.format),e.quality&&n.set("quality",e.quality.toString()),n}};const ER="2.110.2",wo={"X-Client-Info":`storage-js/${ER}`};var AR=class extends Fa{constructor(n,e={},i,a){const l=new URL(n);a!=null&&a.useNewHostname&&/supabase\.(co|in|red)$/.test(l.hostname)&&!l.hostname.includes("storage.supabase.")&&(l.hostname=l.hostname.replace("supabase.","storage.supabase."));const c=l.href.replace(/\/$/,""),u=me(me({},wo),e);super(c,u,i,"storage")}async listBuckets(n){var e=this;return e.handleOperation(async()=>{const i=e.listBucketOptionsToQueryString(n);return await ho(e.fetch,`${e.url}/bucket${i}`,{headers:e.headers})})}async getBucket(n){var e=this;return e.handleOperation(async()=>await ho(e.fetch,`${e.url}/bucket/${n}`,{headers:e.headers}))}async createBucket(n,e={public:!1}){var i=this;return i.handleOperation(async()=>await Bn(i.fetch,`${i.url}/bucket`,{id:n,name:n,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:i.headers}))}async updateBucket(n,e){var i=this;return i.handleOperation(async()=>await uf(i.fetch,`${i.url}/bucket/${n}`,{id:n,name:n,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:i.headers}))}async emptyBucket(n){var e=this;return e.handleOperation(async()=>await Bn(e.fetch,`${e.url}/bucket/${n}/empty`,{},{headers:e.headers}))}async deleteBucket(n){var e=this;return e.handleOperation(async()=>await fo(e.fetch,`${e.url}/bucket/${n}`,{},{headers:e.headers}))}async purgeBucketCache(n,e,i){var a=this;return a.handleOperation(async()=>{const l=new URLSearchParams;e!=null&&e.transformations&&l.set("transformations","true");const c=l.toString();return await fo(a.fetch,`${a.url}/cdn/${n}${c?`?${c}`:""}`,{},{headers:a.headers},i)})}listBucketOptionsToQueryString(n){const e={};return n&&("limit"in n&&(e.limit=String(n.limit)),"offset"in n&&(e.offset=String(n.offset)),n.search&&(e.search=n.search),n.sortColumn&&(e.sortColumn=n.sortColumn),n.sortOrder&&(e.sortOrder=n.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},jR=class extends Fa{constructor(n,e={},i){const a=n.replace(/\/$/,""),l=me(me({},wo),e);super(a,l,i,"storage")}async createBucket(n){var e=this;return e.handleOperation(async()=>await Bn(e.fetch,`${e.url}/bucket`,{name:n},{headers:e.headers}))}async listBuckets(n){var e=this;return e.handleOperation(async()=>{const i=new URLSearchParams;(n==null?void 0:n.limit)!==void 0&&i.set("limit",n.limit.toString()),(n==null?void 0:n.offset)!==void 0&&i.set("offset",n.offset.toString()),n!=null&&n.sortColumn&&i.set("sortColumn",n.sortColumn),n!=null&&n.sortOrder&&i.set("sortOrder",n.sortOrder),n!=null&&n.search&&i.set("search",n.search);const a=i.toString(),l=a?`${e.url}/bucket?${a}`:`${e.url}/bucket`;return await ho(e.fetch,l,{headers:e.headers})})}async deleteBucket(n){var e=this;return e.handleOperation(async()=>await fo(e.fetch,`${e.url}/bucket/${n}`,{},{headers:e.headers}))}from(n){var e=this;if(!yR(n))throw new Uc("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const i=new uR({baseUrl:this.url,catalogName:n,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),a=this.shouldThrowOnError;return new Proxy(i,{get(l,c){const u=l[c];return typeof u!="function"?u:async(...d)=>{try{return{data:await u.apply(l,d),error:null}}catch(m){if(a)throw m;return{data:null,error:m}}}}})}},CR=class extends Fa{constructor(n,e={},i){const a=n.replace(/\/$/,""),l=me(me({},wo),{},{"Content-Type":"application/json"},e);super(a,l,i,"vectors")}async createIndex(n){var e=this;return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/CreateIndex`,n,{headers:e.headers})||{})}async getIndex(n,e){var i=this;return i.handleOperation(async()=>await un.post(i.fetch,`${i.url}/GetIndex`,{vectorBucketName:n,indexName:e},{headers:i.headers}))}async listIndexes(n){var e=this;return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/ListIndexes`,n,{headers:e.headers}))}async deleteIndex(n,e){var i=this;return i.handleOperation(async()=>await un.post(i.fetch,`${i.url}/DeleteIndex`,{vectorBucketName:n,indexName:e},{headers:i.headers})||{})}},RR=class extends Fa{constructor(n,e={},i){const a=n.replace(/\/$/,""),l=me(me({},wo),{},{"Content-Type":"application/json"},e);super(a,l,i,"vectors")}async putVectors(n){var e=this;if(n.vectors.length<1||n.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/PutVectors`,n,{headers:e.headers})||{})}async getVectors(n){var e=this;return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/GetVectors`,n,{headers:e.headers}))}async listVectors(n){var e=this;if(n.segmentCount!==void 0){if(n.segmentCount<1||n.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(n.segmentIndex!==void 0&&(n.segmentIndex<0||n.segmentIndex>=n.segmentCount))throw new Error(`segmentIndex must be between 0 and ${n.segmentCount-1}`)}return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/ListVectors`,n,{headers:e.headers}))}async queryVectors(n){var e=this;return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/QueryVectors`,n,{headers:e.headers}))}async deleteVectors(n){var e=this;if(n.keys.length<1||n.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/DeleteVectors`,n,{headers:e.headers})||{})}},NR=class extends Fa{constructor(n,e={},i){const a=n.replace(/\/$/,""),l=me(me({},wo),{},{"Content-Type":"application/json"},e);super(a,l,i,"vectors")}async createBucket(n){var e=this;return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:n},{headers:e.headers})||{})}async getBucket(n){var e=this;return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:n},{headers:e.headers}))}async listBuckets(n={}){var e=this;return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/ListVectorBuckets`,n,{headers:e.headers}))}async deleteBucket(n){var e=this;return e.handleOperation(async()=>await un.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:n},{headers:e.headers})||{})}},kR=class extends NR{constructor(n,e={}){super(n,e.headers||{},e.fetch)}from(n){return new OR(this.url,this.headers,n,this.fetch)}async createBucket(n){var e=()=>super.createBucket,i=this;return e().call(i,n)}async getBucket(n){var e=()=>super.getBucket,i=this;return e().call(i,n)}async listBuckets(n={}){var e=()=>super.listBuckets,i=this;return e().call(i,n)}async deleteBucket(n){var e=()=>super.deleteBucket,i=this;return e().call(i,n)}},OR=class extends CR{constructor(n,e,i,a){super(n,e,a),this.vectorBucketName=i}async createIndex(n){var e=()=>super.createIndex,i=this;return e().call(i,me(me({},n),{},{vectorBucketName:i.vectorBucketName}))}async listIndexes(n={}){var e=()=>super.listIndexes,i=this;return e().call(i,me(me({},n),{},{vectorBucketName:i.vectorBucketName}))}async getIndex(n){var e=()=>super.getIndex,i=this;return e().call(i,i.vectorBucketName,n)}async deleteIndex(n){var e=()=>super.deleteIndex,i=this;return e().call(i,i.vectorBucketName,n)}index(n){return new DR(this.url,this.headers,this.vectorBucketName,n,this.fetch)}},DR=class extends RR{constructor(n,e,i,a,l){super(n,e,l),this.vectorBucketName=i,this.indexName=a}async putVectors(n){var e=()=>super.putVectors,i=this;return e().call(i,me(me({},n),{},{vectorBucketName:i.vectorBucketName,indexName:i.indexName}))}async getVectors(n){var e=()=>super.getVectors,i=this;return e().call(i,me(me({},n),{},{vectorBucketName:i.vectorBucketName,indexName:i.indexName}))}async listVectors(n={}){var e=()=>super.listVectors,i=this;return e().call(i,me(me({},n),{},{vectorBucketName:i.vectorBucketName,indexName:i.indexName}))}async queryVectors(n){var e=()=>super.queryVectors,i=this;return e().call(i,me(me({},n),{},{vectorBucketName:i.vectorBucketName,indexName:i.indexName}))}async deleteVectors(n){var e=()=>super.deleteVectors,i=this;return e().call(i,me(me({},n),{},{vectorBucketName:i.vectorBucketName,indexName:i.indexName}))}},MR=class extends AR{constructor(n,e={},i,a){super(n,e,i,a)}from(n){return new TR(this.url,this.headers,n,this.fetch)}get vectors(){return new kR(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new jR(this.url+"/iceberg",this.headers,this.fetch)}};const ww="2.110.2",Es=30*1e3,Ir=3,xd=Ir*Es,BR=2*Es,UR="http://localhost:9999",LR="supabase.auth.token",zR={"X-Client-Info":`gotrue-js/${ww}`},hf="X-Supabase-Api-Version",_w={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},VR=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,PR=600*1e3;class mo extends Error{constructor(e,i,a){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=i,this.code=a}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function se(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class HR extends mo{constructor(e,i,a){super(e,i,a),this.name="AuthApiError",this.status=i,this.code=a}}function qR(n){return se(n)&&n.name==="AuthApiError"}class Un extends mo{constructor(e,i){super(e),this.name="AuthUnknownError",this.originalError=i}}class Wn extends mo{constructor(e,i,a,l){super(e,a,l),this.name=i,this.status=a}}class Tt extends Wn{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Yl(n){return se(n)&&n.name==="AuthSessionMissingError"}class Ea extends Wn{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Xl extends Wn{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Jl extends Wn{constructor(e,i=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=i}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function $R(n){return se(n)&&n.name==="AuthImplicitGrantRedirectError"}class Lb extends Wn{constructor(e,i=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=i}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class IR extends Wn{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class df extends Wn{constructor(e,i){super(e,"AuthRetryableFetchError",i,void 0)}}function zb(n){return se(n)&&n.name==="AuthRetryableFetchError"}class Vb extends Wn{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}}function FR(n){return se(n)&&n.name==="AuthRefreshDiscardedError"}class Pb extends Wn{constructor(e,i,a){super(e,"AuthWeakPasswordError",i,"weak_password"),this.reasons=a}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class Sc extends Wn{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Tc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Hb=` \r=`.split(""),GR=(()=>{const n=new Array(128);for(let e=0;e=6;){const a=e.queue>>e.queuedBits-6&63;i(Tc[a]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const a=e.queue>>e.queuedBits-6&63;i(Tc[a]),e.queuedBits-=6}}function Sw(n,e,i){const a=GR[n];if(a>-1)for(e.queue=e.queue<<6|a,e.queuedBits+=6;e.queuedBits>=8;)i(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(a===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function $b(n){const e=[],i=u=>{e.push(String.fromCodePoint(u))},a={utf8seq:0,codepoint:0},l={queue:0,queuedBits:0},c=u=>{XR(u,a,i)};for(let u=0;u>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function YR(n,e){for(let i=0;i55295&&a<=56319){const l=(a-55296)*1024&65535;a=(n.charCodeAt(i+1)-56320&65535|l)+65536,i+=1}KR(a,e)}}function XR(n,e,i){if(e.utf8seq===0){if(n<=127){i(n);return}for(let a=1;a<6;a+=1)if((n>>7-a&1)===0){e.utf8seq=a;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&i(e.codepoint)}}function za(n){const e=[],i={queue:0,queuedBits:0},a=l=>{e.push(l)};for(let l=0;le.push(i)),new Uint8Array(e)}function Ni(n){const e=[],i={queue:0,queuedBits:0},a=l=>{e.push(l)};return n.forEach(l=>qb(l,i,a)),qb(null,i,a),e.join("")}function QR(n){return Math.round(Date.now()/1e3)+n}function ZR(){return Symbol("auth-callback")}const Mt=()=>typeof window<"u"&&typeof document<"u",Ti={tested:!1,writable:!1},Tw=()=>{if(!Mt())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ti.tested)return Ti.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),Ti.tested=!0,Ti.writable=!0}catch{Ti.tested=!0,Ti.writable=!1}return Ti.writable};function WR(n){const e={},i=new URL(n);if(i.hash&&i.hash[0]==="#")try{new URLSearchParams(i.hash.substring(1)).forEach((l,c)=>{e[c]=l})}catch{}return i.searchParams.forEach((a,l)=>{e[l]=a}),e}const Ew=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),eN=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",ka=async(n,e,i)=>{await n.setItem(e,JSON.stringify(i))},kn=async(n,e)=>{const i=await n.getItem(e);if(!i)return null;try{return JSON.parse(i)}catch{return null}},ot=async(n,e)=>{await n.removeItem(e)};class zc{constructor(){this.promise=new zc.promiseConstructor((e,i)=>{this.resolve=e,this.reject=i})}}zc.promiseConstructor=Promise;function Ql(n){const e=n.split(".");if(e.length!==3)throw new Sc("Invalid JWT structure");for(let a=0;a{setTimeout(()=>e(null),n)})}function nN(n,e){return new Promise((a,l)=>{(async()=>{for(let c=0;c<1/0;c++)try{const u=await n(c);if(!e(c,null,u)){a(u);return}}catch(u){if(!e(c,u)){l(u);return}}})()})}function sN(n){return("0"+n.toString(16)).substr(-2)}function iN(){const e=new Uint32Array(56);if(typeof crypto>"u"){const i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",a=i.length;let l="";for(let c=0;c<56;c++)l+=i.charAt(Math.floor(Math.random()*a));return l}return crypto.getRandomValues(e),Array.from(e,sN).join("")}async function aN(n){const i=new TextEncoder().encode(n),a=await crypto.subtle.digest("SHA-256",i),l=new Uint8Array(a);return Array.from(l).map(c=>String.fromCharCode(c)).join("")}async function rN(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),n;const i=await aN(n);return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ei(n,e,i=!1){const a=iN();let l=a;i&&(l+="/recovery"),await ka(n,`${e}-code-verifier`,l);const c=await rN(a);return[c,a===c?"plain":"s256"]}const oN=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function lN(n){const e=n.headers.get(hf);if(!e||!e.match(oN))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function cN(n){if(!n)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function uN(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const hN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ws(n){if(!hN.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Dn(n){if(!n.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function wd(){const n={};return new Proxy(n,{get:(e,i)=>{if(i==="__isUserNotAvailableProxy")return!0;if(typeof i=="symbol"){const a=i.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${i}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,i)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${i}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,i)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${i}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function dN(n,e){return new Proxy(n,{get:(i,a,l)=>{if(a==="__isInsecureUserWarningProxy")return!0;if(typeof a=="symbol"){const c=a.toString();if(c==="Symbol(Symbol.toPrimitive)"||c==="Symbol(Symbol.toStringTag)"||c==="Symbol(util.inspect.custom)"||c==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(i,a,l)}return!e.value&&typeof a=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(i,a,l)}})}function Ib(n){return JSON.parse(JSON.stringify(n))}const ji=n=>{if(typeof n=="object"&&n!==null){const e=n;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(n)},fN=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function Fb(n){var e;if(!eN(n))throw new df(ji(n),0);if(fN.includes(n.status))throw new df(ji(n),n.status);let i;try{i=await n.json()}catch(c){throw new Un(ji(c),c)}let a;const l=lN(n);if(l&&l.getTime()>=_w["2024-01-01"].timestamp&&typeof i=="object"&&i&&typeof i.code=="string"?a=i.code:typeof i=="object"&&i&&typeof i.error_code=="string"&&(a=i.error_code),a){if(a==="weak_password")throw new Pb(ji(i),n.status,((e=i.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(a==="session_not_found")throw new Tt}else if(typeof i=="object"&&i&&typeof i.weak_password=="object"&&i.weak_password&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.reasons.reduce((c,u)=>c&&typeof u=="string",!0))throw new Pb(ji(i),n.status,i.weak_password.reasons);throw new HR(ji(i),n.status||500,a)}const mN=(n,e,i,a)=>{const l={method:n,headers:(e==null?void 0:e.headers)||{}};return n==="GET"?l:(l.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),l.body=JSON.stringify(a),Object.assign(Object.assign({},l),i))};async function oe(n,e,i,a){var l;const c=Object.assign({},a==null?void 0:a.headers);c[hf]||(c[hf]=_w["2024-01-01"].name),a!=null&&a.jwt&&(c.Authorization=`Bearer ${a.jwt}`);const u=(l=a==null?void 0:a.query)!==null&&l!==void 0?l:{};a!=null&&a.redirectTo&&(u.redirect_to=a.redirectTo);const d=Object.keys(u).length?"?"+new URLSearchParams(u).toString():"",m=await pN(n,e,i+d,{headers:c,noResolveJson:a==null?void 0:a.noResolveJson},{},a==null?void 0:a.body);return a!=null&&a.xform?a==null?void 0:a.xform(m):{data:Object.assign({},m),error:null}}async function pN(n,e,i,a,l,c){const u=mN(e,a,l,c);let d;try{d=await n(i,Object.assign({},u))}catch(m){throw console.error(m),new df(ji(m),0)}if(d.ok||await Fb(d),a!=null&&a.noResolveJson)return d;try{return await d.json()}catch(m){await Fb(m)}}function Sn(n){var e;let i=null;bN(n)&&(i=Object.assign({},n),n.expires_at||(i.expires_at=QR(n.expires_in)));const a=(e=n.user)!==null&&e!==void 0?e:typeof(n==null?void 0:n.id)=="string"?n:null;return{data:{session:i,user:a},error:null}}function Gb(n){const e=Sn(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0)&&(e.data.weak_password=n.weak_password),e}function Ws(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function gN(n){return{data:n,error:null}}function yN(n){const{action_link:e,email_otp:i,hashed_token:a,redirect_to:l,verification_type:c}=n,u=Bc(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),d={action_link:e,email_otp:i,hashed_token:a,redirect_to:l,verification_type:c},m=Object.assign({},u);return{data:{properties:d,user:m},error:null}}function Kb(n){return n}function bN(n){return!!n.access_token&&!!n.refresh_token&&!!n.expires_in}const _d=["global","local","others"];class vN{constructor({url:e="",headers:i={},fetch:a,experimental:l}){this.url=e,this.headers=i,this.fetch=Ew(a),this.experimental=l??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,i=_d[0]){if(_d.indexOf(i)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${_d.join(", ")}`);try{return await oe(this.fetch,"POST",`${this.url}/logout?scope=${i}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(a){if(se(a))return{data:null,error:a};throw a}}async inviteUserByEmail(e,i={}){try{return await oe(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:i.data},headers:this.headers,redirectTo:i.redirectTo,xform:Ws})}catch(a){if(se(a))return{data:{user:null},error:a};throw a}}async generateLink(e){try{const{options:i}=e,a=Bc(e,["options"]),l=Object.assign(Object.assign({},a),i);return"newEmail"in a&&(l.new_email=a==null?void 0:a.newEmail,delete l.newEmail),await oe(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:l,headers:this.headers,xform:yN,redirectTo:i==null?void 0:i.redirectTo})}catch(i){if(se(i))return{data:{properties:null,user:null},error:i};throw i}}async createUser(e){try{return await oe(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Ws})}catch(i){if(se(i))return{data:{user:null},error:i};throw i}}async listUsers(e){var i,a,l,c,u,d,m;try{const p={nextPage:null,lastPage:0,total:0},y=await oe(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(a=(i=e==null?void 0:e.page)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:"",per_page:(c=(l=e==null?void 0:e.perPage)===null||l===void 0?void 0:l.toString())!==null&&c!==void 0?c:""},xform:Kb});if(y.error)throw y.error;const v=await y.json(),x=(u=y.headers.get("x-total-count"))!==null&&u!==void 0?u:0,_=(m=(d=y.headers.get("link"))===null||d===void 0?void 0:d.split(","))!==null&&m!==void 0?m:[];return _.length>0&&(_.forEach(S=>{const E=parseInt(S.split(";")[0].split("=")[1].substring(0,1)),R=JSON.parse(S.split(";")[1].split("=")[1]);p[`${R}Page`]=E}),p.total=parseInt(x)),{data:Object.assign(Object.assign({},v),p),error:null}}catch(p){if(se(p))return{data:{users:[]},error:p};throw p}}async getUserById(e){ws(e);try{return await oe(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ws})}catch(i){if(se(i))return{data:{user:null},error:i};throw i}}async updateUserById(e,i){ws(e);try{return await oe(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:i,headers:this.headers,xform:Ws})}catch(a){if(se(a))return{data:{user:null},error:a};throw a}}async deleteUser(e,i=!1){ws(e);try{return await oe(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:i},xform:Ws})}catch(a){if(se(a))return{data:{user:null},error:a};throw a}}async _listFactors(e){ws(e.userId);try{const{data:i,error:a}=await oe(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:l=>({data:{factors:l},error:null})});return{data:i,error:a}}catch(i){if(se(i))return{data:null,error:i};throw i}}async _deleteFactor(e){ws(e.userId),ws(e.id);try{return{data:await oe(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(i){if(se(i))return{data:null,error:i};throw i}}async _listOAuthClients(e){var i,a,l,c,u,d,m;try{const p={nextPage:null,lastPage:0,total:0},y=await oe(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(a=(i=e==null?void 0:e.page)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:"",per_page:(c=(l=e==null?void 0:e.perPage)===null||l===void 0?void 0:l.toString())!==null&&c!==void 0?c:""},xform:Kb});if(y.error)throw y.error;const v=await y.json(),x=(u=y.headers.get("x-total-count"))!==null&&u!==void 0?u:0,_=(m=(d=y.headers.get("link"))===null||d===void 0?void 0:d.split(","))!==null&&m!==void 0?m:[];return _.length>0&&(_.forEach(S=>{const E=parseInt(S.split(";")[0].split("=")[1].substring(0,1)),R=JSON.parse(S.split(";")[1].split("=")[1]);p[`${R}Page`]=E}),p.total=parseInt(x)),{data:Object.assign(Object.assign({},v),p),error:null}}catch(p){if(se(p))return{data:{clients:[]},error:p};throw p}}async _createOAuthClient(e){try{return await oe(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:i=>({data:i,error:null})})}catch(i){if(se(i))return{data:null,error:i};throw i}}async _getOAuthClient(e){try{return await oe(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:i=>({data:i,error:null})})}catch(i){if(se(i))return{data:null,error:i};throw i}}async _updateOAuthClient(e,i){try{return await oe(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:i,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(se(a))return{data:null,error:a};throw a}}async _deleteOAuthClient(e){try{return await oe(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(i){if(se(i))return{data:null,error:i};throw i}}async _regenerateOAuthClientSecret(e){try{return await oe(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:i=>({data:i,error:null})})}catch(i){if(se(i))return{data:null,error:i};throw i}}async _listCustomProviders(e){try{const i={};return e!=null&&e.type&&(i.type=e.type),await oe(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:i,xform:a=>{var l;return{data:{providers:(l=a==null?void 0:a.providers)!==null&&l!==void 0?l:[]},error:null}}})}catch(i){if(se(i))return{data:{providers:[]},error:i};throw i}}async _createCustomProvider(e){try{return await oe(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:i=>({data:i,error:null})})}catch(i){if(se(i))return{data:null,error:i};throw i}}async _getCustomProvider(e){try{return await oe(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:i=>({data:i,error:null})})}catch(i){if(se(i))return{data:null,error:i};throw i}}async _updateCustomProvider(e,i){try{return await oe(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:i,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(se(a))return{data:null,error:a};throw a}}async _deleteCustomProvider(e){try{return await oe(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(i){if(se(i))return{data:null,error:i};throw i}}async _adminListPasskeys(e){Dn(this.experimental),ws(e.userId);try{return await oe(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:i=>({data:i,error:null})})}catch(i){if(se(i))return{data:null,error:i};throw i}}async _adminDeletePasskey(e){Dn(this.experimental),ws(e.userId),ws(e.passkeyId);try{return await oe(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(i){if(se(i))return{data:null,error:i};throw i}}}function Yb(n={}){return{getItem:e=>n[e]||null,setItem:(e,i)=>{n[e]=i},removeItem:e=>{delete n[e]}}}globalThis&&Tw()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class xN extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}function wN(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function Aw(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))throw new Error(`@supabase/auth-js: Address "${n}" is invalid.`);return n.toLowerCase()}function _N(n){return parseInt(n,16)}function SN(n){const e=new TextEncoder().encode(n);return"0x"+Array.from(e,a=>a.toString(16).padStart(2,"0")).join("")}function TN(n){var e;const{chainId:i,domain:a,expirationTime:l,issuedAt:c=new Date,nonce:u,notBefore:d,requestId:m,resources:p,scheme:y,uri:v,version:x}=n;{if(!Number.isInteger(i))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${i}`);if(!a)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(u&&u.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${u}`);if(!v)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(x!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${x}`);if(!((e=n.statement)===null||e===void 0)&&e.includes(` `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${n.statement}`)}const _=Aw(n.address),S=y?`${y}://${a}`:a,E=n.statement?`${n.statement} `:"",R=`${S} wants you to sign in with your Ethereum account: ${_} ${E}`;let N=`URI: ${v} Version: ${x} Chain ID: ${i}${u?` Nonce: ${u}`:""} Issued At: ${c.toISOString()}`;if(l&&(N+=` Expiration Time: ${l.toISOString()}`),d&&(N+=` Not Before: ${d.toISOString()}`),m&&(N+=` Request ID: ${m}`),p){let O=` Resources:`;for(const C of p){if(!C||typeof C!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${C}`);O+=` - ${C}`}N+=O}return`${R} ${N}`}class gt extends Error{constructor({message:e,code:i,cause:a,name:l}){var c;super(e,{cause:a}),this.__isWebAuthnError=!0,this.name=(c=l??(a instanceof Error?a.name:void 0))!==null&&c!==void 0?c:"Unknown Error",this.code=i}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class Ec extends gt{constructor(e,i){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:i,message:e}),this.name="WebAuthnUnknownError",this.originalError=i}}function EN({error:n,options:e}){var i,a,l;const{publicKey:c}=e;if(!c)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new gt({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((i=c.authenticatorSelection)===null||i===void 0?void 0:i.requireResidentKey)===!0)return new gt({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((a=c.authenticatorSelection)===null||a===void 0?void 0:a.userVerification)==="required")return new gt({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((l=c.authenticatorSelection)===null||l===void 0?void 0:l.userVerification)==="required")return new gt({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new gt({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new gt({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return c.pubKeyCredParams.filter(d=>d.type==="public-key").length===0?new gt({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new gt({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){const u=window.location.hostname;if(jw(u)){if(c.rp.id!==u)return new gt({message:`The RP ID "${c.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new gt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(c.user.id.byteLength<1||c.user.id.byteLength>64)return new gt({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new gt({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new gt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function AN({error:n,options:e}){const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new gt({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new gt({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){const a=window.location.hostname;if(jw(a)){if(i.rpId!==a)return new gt({message:`The RP ID "${i.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new gt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new gt({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new gt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}class jN{createNewAbortSignal(){if(this.controller){const i=new Error("Cancelling existing WebAuthn API call for new one");i.name="AbortError",this.controller.abort(i)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const ff=new jN;function Xb(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);const{challenge:e,user:i,excludeCredentials:a}=n,l=Bc(n,["challenge","user","excludeCredentials"]),c=za(e).buffer,u=Object.assign(Object.assign({},i),{id:za(i.id).buffer}),d=Object.assign(Object.assign({},l),{challenge:c,user:u});if(a&&a.length>0){d.excludeCredentials=new Array(a.length);for(let m=0;m0){c.allowCredentials=new Array(i.length);for(let u=0;ul!==null&&typeof l=="object"&&!Array.isArray(l),i=l=>l instanceof ArrayBuffer||ArrayBuffer.isView(l),a={};for(const l of n)if(l)for(const c in l){const u=l[c];if(u!==void 0)if(Array.isArray(u))a[c]=u;else if(i(u))a[c]=u;else if(e(u)){const d=a[c];e(d)?a[c]=jc(d,u):a[c]=jc(u)}else a[c]=u}return a}function NN(n,e){return jc(CN,n,e||{})}function kN(n,e){return jc(RN,n,e||{})}class ON{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:i,friendlyName:a,signal:l},c){var u;try{const{data:d,error:m}=await this.client.mfa.challenge({factorId:e,webauthn:i});if(!d)return{data:null,error:m};const p=l??ff.createNewAbortSignal();if(d.webauthn.type==="create"){const{user:y}=d.webauthn.credential_options.publicKey;if(!y.name){const v=a;if(v)y.name=`${y.id}:${v}`;else{const _=(await this.client.getUser()).data.user,S=((u=_==null?void 0:_.user_metadata)===null||u===void 0?void 0:u.name)||(_==null?void 0:_.email)||(_==null?void 0:_.id)||"User";y.name=`${y.id}:${S}`}}y.displayName||(y.displayName=y.name)}switch(d.webauthn.type){case"create":{const y=NN(d.webauthn.credential_options.publicKey,c==null?void 0:c.create),{data:v,error:x}=await Cw({publicKey:y,signal:p});return v?{data:{factorId:e,challengeId:d.id,webauthn:{type:d.webauthn.type,credential_response:v}},error:null}:{data:null,error:x}}case"request":{const y=kN(d.webauthn.credential_options.publicKey,c==null?void 0:c.request),{data:v,error:x}=await Rw(Object.assign(Object.assign({},d.webauthn.credential_options),{publicKey:y,signal:p}));return v?{data:{factorId:e,challengeId:d.id,webauthn:{type:d.webauthn.type,credential_response:v}},error:null}:{data:null,error:x}}}}catch(d){return se(d)?{data:null,error:d}:{data:null,error:new Un("Unexpected error in challenge",d)}}}async _verify({challengeId:e,factorId:i,webauthn:a}){return this.client.mfa.verify({factorId:i,challengeId:e,webauthn:a})}async _authenticate({factorId:e,webauthn:{rpId:i=typeof window<"u"?window.location.hostname:void 0,rpOrigins:a=typeof window<"u"?[window.location.origin]:void 0,signal:l}={}},c){if(!i)return{data:null,error:new mo("rpId is required for WebAuthn authentication")};try{if(!Ac())return{data:null,error:new Un("Browser does not support WebAuthn",null)};const{data:u,error:d}=await this.challenge({factorId:e,webauthn:{rpId:i,rpOrigins:a},signal:l},{request:c});if(!u)return{data:null,error:d};const{webauthn:m}=u;return this._verify({factorId:e,challengeId:u.challengeId,webauthn:{type:m.type,rpId:i,rpOrigins:a,credential_response:m.credential_response}})}catch(u){return se(u)?{data:null,error:u}:{data:null,error:new Un("Unexpected error in authenticate",u)}}}async _register({friendlyName:e,webauthn:{rpId:i=typeof window<"u"?window.location.hostname:void 0,rpOrigins:a=typeof window<"u"?[window.location.origin]:void 0,signal:l}={}},c){if(!i)return{data:null,error:new mo("rpId is required for WebAuthn registration")};try{if(!Ac())return{data:null,error:new Un("Browser does not support WebAuthn",null)};const{data:u,error:d}=await this._enroll({friendlyName:e});if(!u)return await this.client.mfa.listFactors().then(y=>{var v;return(v=y.data)===null||v===void 0?void 0:v.all.find(x=>x.factor_type==="webauthn"&&x.friendly_name===e&&x.status!=="unverified")}).then(y=>y?this.client.mfa.unenroll({factorId:y==null?void 0:y.id}):void 0),{data:null,error:d};const{data:m,error:p}=await this._challenge({factorId:u.id,friendlyName:u.friendly_name,webauthn:{rpId:i,rpOrigins:a},signal:l},{create:c});return m?this._verify({factorId:u.id,challengeId:m.challengeId,webauthn:{rpId:i,rpOrigins:a,type:m.webauthn.type,credential_response:m.webauthn.credential_response}}):{data:null,error:p}}catch(u){return se(u)?{data:null,error:u}:{data:null,error:new Un("Unexpected error in register",u)}}}}wN();const DN={url:UR,storageKey:LR,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:zR,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},Aa={};class po{get jwks(){var e,i;return(i=(e=Aa[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&i!==void 0?i:{keys:[]}}set jwks(e){Aa[this.storageKey]=Object.assign(Object.assign({},Aa[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,i;return(i=(e=Aa[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&i!==void 0?i:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Aa[this.storageKey]=Object.assign(Object.assign({},Aa[this.storageKey]),{cachedAt:e})}constructor(e){var i,a,l;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const c=Object.assign(Object.assign({},DN),e);if(this.storageKey=c.storageKey,this.instanceID=(i=po.nextInstanceID[this.storageKey])!==null&&i!==void 0?i:0,po.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!c.debug,typeof c.debug=="function"&&(this.logger=c.debug),this.instanceID>0&&Mt()){const u=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(u),this.logDebugMessages&&console.trace(u)}if(this.persistSession=c.persistSession,this.autoRefreshToken=c.autoRefreshToken,this.experimental=(a=c.experimental)!==null&&a!==void 0?a:{},this.admin=new vN({url:c.url,headers:c.headers,fetch:c.fetch,experimental:this.experimental}),this.url=c.url,this.headers=c.headers,this.fetch=Ew(c.fetch),this.detectSessionInUrl=c.detectSessionInUrl,this.flowType=c.flowType,this.hasCustomAuthorizationHeader=c.hasCustomAuthorizationHeader,this.throwOnError=c.throwOnError,this.lockAcquireTimeout=c.lockAcquireTimeout,c.lock!=null&&(this.lock=c.lock),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new ON(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(c.storage?this.storage=c.storage:Tw()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Yb(this.memoryStorage)),c.userStorage&&(this.userStorage=c.userStorage)):(this.memoryStorage={},this.storage=Yb(this.memoryStorage)),Mt()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(u){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",u)}(l=this.broadcastChannel)===null||l===void 0||l.addEventListener("message",async u=>{this._debug("received broadcast notification from other tab or client",u),(u.data.event==="TOKEN_REFRESHED"||u.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(u.data.event,u.data.session,!1)}catch(d){this._debug("#broadcastChannel","error",d)}})}c.skipAutoInitialize||this.initialize().catch(u=>{this._debug("#initialize()","error",u)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ww}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();const i=await this.initializePromise,a=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(const l of a)await this._notifyAllSubscribers(l.event,l.session,l.broadcast);return i}async _initialize(){var e;try{let i={},a="none";if(Mt()&&(i=WR(window.location.href),this._isImplicitGrantCallback(i)?a="implicit":await this._isPKCECallback(i)&&(a="pkce")),Mt()&&this.detectSessionInUrl&&a!=="none"){const{data:l,error:c}=await this._getSessionFromURL(i,a);if(c){if(this._debug("#_initialize()","error detecting session from URL",c),$R(c)){const m=(e=c.details)===null||e===void 0?void 0:e.code;if(m==="identity_already_exists"||m==="identity_not_found"||m==="single_identity_not_deletable")return{error:c}}return{error:c}}const{session:u,redirectType:d}=l;return this._debug("#_initialize()","detected session in URL",u,"redirect type",d),await this._saveSession(u),setTimeout(async()=>{d==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",u):await this._notifyAllSubscribers("SIGNED_IN",u)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(i){return se(i)?this._returnResult({error:i}):this._returnResult({error:new Un("Unexpected error during initialization",i)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var i,a,l;try{const c=await oe(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(a=(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.data)!==null&&a!==void 0?a:{},gotrue_meta_security:{captcha_token:(l=e==null?void 0:e.options)===null||l===void 0?void 0:l.captchaToken}},xform:Sn}),{data:u,error:d}=c;if(d||!u)return this._returnResult({data:{user:null,session:null},error:d});const m=u.session,p=u.user;return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("SIGNED_IN",m)),this._returnResult({data:{user:p,session:m},error:null})}catch(c){if(se(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async signUp(e){var i,a,l;try{let c;if("email"in e){const{email:y,password:v,options:x}=e;let _=null,S=null;this.flowType==="pkce"&&([_,S]=await Ei(this.storage,this.storageKey)),c=await oe(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:x==null?void 0:x.emailRedirectTo,body:{email:y,password:v,data:(i=x==null?void 0:x.data)!==null&&i!==void 0?i:{},gotrue_meta_security:{captcha_token:x==null?void 0:x.captchaToken},code_challenge:_,code_challenge_method:S},xform:Sn})}else if("phone"in e){const{phone:y,password:v,options:x}=e;c=await oe(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:y,password:v,data:(a=x==null?void 0:x.data)!==null&&a!==void 0?a:{},channel:(l=x==null?void 0:x.channel)!==null&&l!==void 0?l:"sms",gotrue_meta_security:{captcha_token:x==null?void 0:x.captchaToken}},xform:Sn})}else throw new Xl("You must provide either an email or phone number and a password");const{data:u,error:d}=c;if(d||!u)return await ot(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:d});const m=u.session,p=u.user;return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("SIGNED_IN",m)),this._returnResult({data:{user:p,session:m},error:null})}catch(c){if(await ot(this.storage,`${this.storageKey}-code-verifier`),se(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async signInWithPassword(e){try{let i;if("email"in e){const{email:c,password:u,options:d}=e;i=await oe(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:c,password:u,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:Gb})}else if("phone"in e){const{phone:c,password:u,options:d}=e;i=await oe(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:c,password:u,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:Gb})}else throw new Xl("You must provide either an email or phone number and a password");const{data:a,error:l}=i;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a||!a.session||!a.user){const c=new Ea;return this._returnResult({data:{user:null,session:null},error:c})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:Object.assign({user:a.user,session:a.session},a.weak_password?{weakPassword:a.weak_password}:null),error:l})}catch(i){if(se(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithOAuth(e){var i,a,l,c;return await this._handleProviderSignIn(e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:(c=e.options)===null||c===void 0?void 0:c.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e)):this._exchangeCodeForSession(e)}async signInWithWeb3(e){const{chain:i}=e;switch(i){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${i}"`)}}async signInWithEthereum(e){var i,a,l,c,u,d,m,p,y,v,x;let _,S;if("message"in e)_=e.message,S=e.signature;else{const{chain:E,wallet:R,statement:N,options:O}=e;let C;if(Mt())if(typeof R=="object")C=R;else{const te=window;if("ethereum"in te&&typeof te.ethereum=="object"&&"request"in te.ethereum&&typeof te.ethereum.request=="function")C=te.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof R!="object"||!(O!=null&&O.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");C=R}const P=new URL((i=O==null?void 0:O.url)!==null&&i!==void 0?i:window.location.href),Y=await C.request({method:"eth_requestAccounts"}).then(te=>te).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Y||Y.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const X=Aw(Y[0]);let q=(a=O==null?void 0:O.signInWithEthereum)===null||a===void 0?void 0:a.chainId;if(!q){const te=await C.request({method:"eth_chainId"});q=_N(te)}const Z={domain:P.host,address:X,statement:N,uri:P.href,version:"1",chainId:q,nonce:(l=O==null?void 0:O.signInWithEthereum)===null||l===void 0?void 0:l.nonce,issuedAt:(u=(c=O==null?void 0:O.signInWithEthereum)===null||c===void 0?void 0:c.issuedAt)!==null&&u!==void 0?u:new Date,expirationTime:(d=O==null?void 0:O.signInWithEthereum)===null||d===void 0?void 0:d.expirationTime,notBefore:(m=O==null?void 0:O.signInWithEthereum)===null||m===void 0?void 0:m.notBefore,requestId:(p=O==null?void 0:O.signInWithEthereum)===null||p===void 0?void 0:p.requestId,resources:(y=O==null?void 0:O.signInWithEthereum)===null||y===void 0?void 0:y.resources};_=TN(Z),S=await C.request({method:"personal_sign",params:[SN(_),X]})}try{const{data:E,error:R}=await oe(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:_,signature:S},!((v=e.options)===null||v===void 0)&&v.captchaToken?{gotrue_meta_security:{captcha_token:(x=e.options)===null||x===void 0?void 0:x.captchaToken}}:null),xform:Sn});if(R)throw R;if(!E||!E.session||!E.user){const N=new Ea;return this._returnResult({data:{user:null,session:null},error:N})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:R})}catch(E){if(se(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var i,a,l,c,u,d,m,p,y,v,x,_;let S,E;if("message"in e)S=e.message,E=e.signature;else{const{chain:R,wallet:N,statement:O,options:C}=e;let P;if(Mt())if(typeof N=="object")P=N;else{const X=window;if("solana"in X&&typeof X.solana=="object"&&("signIn"in X.solana&&typeof X.solana.signIn=="function"||"signMessage"in X.solana&&typeof X.solana.signMessage=="function"))P=X.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof N!="object"||!(C!=null&&C.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");P=N}const Y=new URL((i=C==null?void 0:C.url)!==null&&i!==void 0?i:window.location.href);if("signIn"in P&&P.signIn){const X=await P.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},C==null?void 0:C.signInWithSolana),{version:"1",domain:Y.host,uri:Y.href}),O?{statement:O}:null));let q;if(Array.isArray(X)&&X[0]&&typeof X[0]=="object")q=X[0];else if(X&&typeof X=="object"&&"signedMessage"in X&&"signature"in X)q=X;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in q&&"signature"in q&&(typeof q.signedMessage=="string"||q.signedMessage instanceof Uint8Array)&&q.signature instanceof Uint8Array)S=typeof q.signedMessage=="string"?q.signedMessage:new TextDecoder().decode(q.signedMessage),E=q.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in P)||typeof P.signMessage!="function"||!("publicKey"in P)||typeof P!="object"||!P.publicKey||!("toBase58"in P.publicKey)||typeof P.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");S=[`${Y.host} wants you to sign in with your Solana account:`,P.publicKey.toBase58(),...O?["",O,""]:[""],"Version: 1",`URI: ${Y.href}`,`Issued At: ${(l=(a=C==null?void 0:C.signInWithSolana)===null||a===void 0?void 0:a.issuedAt)!==null&&l!==void 0?l:new Date().toISOString()}`,...!((c=C==null?void 0:C.signInWithSolana)===null||c===void 0)&&c.notBefore?[`Not Before: ${C.signInWithSolana.notBefore}`]:[],...!((u=C==null?void 0:C.signInWithSolana)===null||u===void 0)&&u.expirationTime?[`Expiration Time: ${C.signInWithSolana.expirationTime}`]:[],...!((d=C==null?void 0:C.signInWithSolana)===null||d===void 0)&&d.chainId?[`Chain ID: ${C.signInWithSolana.chainId}`]:[],...!((m=C==null?void 0:C.signInWithSolana)===null||m===void 0)&&m.nonce?[`Nonce: ${C.signInWithSolana.nonce}`]:[],...!((p=C==null?void 0:C.signInWithSolana)===null||p===void 0)&&p.requestId?[`Request ID: ${C.signInWithSolana.requestId}`]:[],...!((v=(y=C==null?void 0:C.signInWithSolana)===null||y===void 0?void 0:y.resources)===null||v===void 0)&&v.length?["Resources",...C.signInWithSolana.resources.map(q=>`- ${q}`)]:[]].join(` `);const X=await P.signMessage(new TextEncoder().encode(S),"utf8");if(!X||!(X instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=X}}try{const{data:R,error:N}=await oe(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:S,signature:Ni(E)},!((x=e.options)===null||x===void 0)&&x.captchaToken?{gotrue_meta_security:{captcha_token:(_=e.options)===null||_===void 0?void 0:_.captchaToken}}:null),xform:Sn});if(N)throw N;if(!R||!R.session||!R.user){const O=new Ea;return this._returnResult({data:{user:null,session:null},error:O})}return R.session&&(await this._saveSession(R.session),await this._notifyAllSubscribers("SIGNED_IN",R.session)),this._returnResult({data:Object.assign({},R),error:N})}catch(R){if(se(R))return this._returnResult({data:{user:null,session:null},error:R});throw R}}async _exchangeCodeForSession(e){const i=await kn(this.storage,`${this.storageKey}-code-verifier`),[a,l]=(i??"").split("/");try{if(!a&&this.flowType==="pkce")throw new IR;const{data:c,error:u}=await oe(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:a},xform:Sn});if(await ot(this.storage,`${this.storageKey}-code-verifier`),u)throw u;if(!c||!c.session||!c.user){const d=new Ea;return this._returnResult({data:{user:null,session:null,redirectType:null},error:d})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers(l==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c.session)),this._returnResult({data:Object.assign(Object.assign({},c),{redirectType:l??null}),error:u})}catch(c){if(await ot(this.storage,`${this.storageKey}-code-verifier`),se(c))return this._returnResult({data:{user:null,session:null,redirectType:null},error:c});throw c}}async signInWithIdToken(e){try{const{options:i,provider:a,token:l,access_token:c,nonce:u}=e,d=await oe(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:a,id_token:l,access_token:c,nonce:u,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},xform:Sn}),{data:m,error:p}=d;if(p)return this._returnResult({data:{user:null,session:null},error:p});if(!m||!m.session||!m.user){const y=new Ea;return this._returnResult({data:{user:null,session:null},error:y})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:m,error:p})}catch(i){if(se(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithOtp(e){var i,a,l,c,u;try{if("email"in e){const{email:d,options:m}=e;let p=null,y=null;this.flowType==="pkce"&&([p,y]=await Ei(this.storage,this.storageKey));const{error:v}=await oe(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:d,data:(i=m==null?void 0:m.data)!==null&&i!==void 0?i:{},create_user:(a=m==null?void 0:m.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:p,code_challenge_method:y},redirectTo:m==null?void 0:m.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:v})}if("phone"in e){const{phone:d,options:m}=e,{data:p,error:y}=await oe(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:d,data:(l=m==null?void 0:m.data)!==null&&l!==void 0?l:{},create_user:(c=m==null?void 0:m.shouldCreateUser)!==null&&c!==void 0?c:!0,gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},channel:(u=m==null?void 0:m.channel)!==null&&u!==void 0?u:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:p==null?void 0:p.message_id},error:y})}throw new Xl("You must provide either an email or phone number.")}catch(d){if(await ot(this.storage,`${this.storageKey}-code-verifier`),se(d))return this._returnResult({data:{user:null,session:null},error:d});throw d}}async verifyOtp(e){var i,a;try{let l,c;"options"in e&&(l=(i=e.options)===null||i===void 0?void 0:i.redirectTo,c=(a=e.options)===null||a===void 0?void 0:a.captchaToken);const{data:u,error:d}=await oe(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:c}}),redirectTo:l,xform:Sn});if(d)throw d;if(!u)throw new Error("An error occurred on token verification.");const m=u.session,p=u.user;return m!=null&&m.access_token&&(await this._saveSession(m),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",m)),this._returnResult({data:{user:p,session:m},error:null})}catch(l){if(se(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async signInWithSSO(e){var i,a,l,c,u;try{let d=null,m=null;this.flowType==="pkce"&&([d,m]=await Ei(this.storage,this.storageKey));const p=await oe(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(a=(i=e.options)===null||i===void 0?void 0:i.redirectTo)!==null&&a!==void 0?a:void 0}),!((l=e==null?void 0:e.options)===null||l===void 0)&&l.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:d,code_challenge_method:m}),headers:this.headers,xform:gN});return!((c=p.data)===null||c===void 0)&&c.url&&Mt()&&!(!((u=e.options)===null||u===void 0)&&u.skipBrowserRedirect)&&window.location.assign(p.data.url),this._returnResult(p)}catch(d){if(await ot(this.storage,`${this.storageKey}-code-verifier`),se(d))return this._returnResult({data:null,error:d});throw d}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:i},error:a}=e;if(a)throw a;if(!i)throw new Tt;const{error:l}=await oe(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:i.access_token});return this._returnResult({data:{user:null,session:null},error:l})})}catch(e){if(se(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const i=`${this.url}/resend`;if("email"in e){const{email:a,type:l,options:c}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await Ei(this.storage,this.storageKey));const{error:m}=await oe(this.fetch,"POST",i,{headers:this.headers,body:{email:a,type:l,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:c==null?void 0:c.emailRedirectTo});return m&&await ot(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:m})}else if("phone"in e){const{phone:a,type:l,options:c}=e,{data:u,error:d}=await oe(this.fetch,"POST",i,{headers:this.headers,body:{phone:a,type:l,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:d})}throw new Xl("You must provide either an email or phone number and a type")}catch(i){if(await ot(this.storage,`${this.storageKey}-code-verifier`),se(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,i){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const a=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),l=(async()=>(await a,await i()))();return this.pendingInLock.push((async()=>{try{await l}catch{}})()),l}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const a=i();for(this.pendingInLock.push((async()=>{try{await a}catch{}})()),await a;this.pendingInLock.length;){const l=[...this.pendingInLock];await Promise.all(l),this.pendingInLock.splice(0,l.length)}return await a}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const i=await this.__loadSession();return await e(i)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const i=await kn(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",i),i!==null&&(this._isValidSession(i)?e=i:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const a=e.expires_at?e.expires_at*1e3-Date.now()Date.now())){const d=await kn(this.storage,this.storageKey);if(d&&d.refresh_token===e.refresh_token)return this._returnResult({data:{session:e},error:null})}return this._returnResult({data:{session:null},error:c})}return this._returnResult({data:{session:l},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let i;return this.lock!=null?i=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):i=await this._getUser(),i.data.user&&(this.suppressGetSessionWarning=!0),i}async _getUser(e){try{return e?await oe(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ws}):await this._useSession(async i=>{var a,l,c;const{data:u,error:d}=i;if(d)throw d;return!(!((a=u.session)===null||a===void 0)&&a.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Tt}:await oe(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(c=(l=u.session)===null||l===void 0?void 0:l.access_token)!==null&&c!==void 0?c:void 0,xform:Ws})})}catch(i){if(se(i))return Yl(i)&&(await this._removeSession(),await ot(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:i});throw i}}async updateUser(e,i={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,i)):await this._updateUser(e,i)}async _updateUser(e,i={}){try{return await this._useSession(async a=>{const{data:l,error:c}=a;if(c)throw c;if(!l.session)throw new Tt;const u=l.session;let d=null,m=null;this.flowType==="pkce"&&e.email!=null&&([d,m]=await Ei(this.storage,this.storageKey));const{data:p,error:y}=await oe(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:i==null?void 0:i.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:d,code_challenge_method:m}),jwt:u.access_token,xform:Ws});if(y)throw y;return u.user=p.user,await this._saveSession(u),await this._notifyAllSubscribers("USER_UPDATED",u),this._returnResult({data:{user:u.user},error:null})})}catch(a){if(await ot(this.storage,`${this.storageKey}-code-verifier`),se(a))return this._returnResult({data:{user:null},error:a});throw a}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Tt;const i=Date.now()/1e3;let a=i,l=!0,c=null;const{payload:u}=Ql(e.access_token);if(u.exp&&(a=u.exp,l=a<=i),l){const{data:d,error:m}=await this._callRefreshToken(e.refresh_token);if(m)return this._returnResult({data:{user:null,session:null},error:m});if(!d)return{data:{user:null,session:null},error:null};c=d}else{const{data:d,error:m}=await this._getUser(e.access_token);if(m)return this._returnResult({data:{user:null,session:null},error:m});c={access_token:e.access_token,refresh_token:e.refresh_token,user:d.user,token_type:"bearer",expires_in:a-i,expires_at:a},await this._saveSession(c),await this._notifyAllSubscribers("SIGNED_IN",c)}return this._returnResult({data:{user:c.user,session:c},error:null})}catch(i){if(se(i))return this._returnResult({data:{session:null,user:null},error:i});throw i}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async i=>{var a;if(!e){const{data:u,error:d}=i;if(d)throw d;e=(a=u.session)!==null&&a!==void 0?a:void 0}if(!(e!=null&&e.refresh_token))throw new Tt;const{data:l,error:c}=await this._callRefreshToken(e.refresh_token);return c?this._returnResult({data:{user:null,session:null},error:c}):l?this._returnResult({data:{user:l.user,session:l},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(i){if(se(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async _getSessionFromURL(e,i){var a;try{if(!Mt())throw new Jl("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Jl(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(i){case"implicit":if(this.flowType==="pkce")throw new Lb("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Jl("Not a valid implicit grant flow url.");break;default:}if(i==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Lb("No code detected.");const{data:C,error:P}=await this._exchangeCodeForSession(e.code);if(P)throw P;const Y=new URL(window.location.href);return Y.searchParams.delete("code"),window.history.replaceState(window.history.state,"",Y.toString()),{data:{session:C.session,redirectType:(a=C.redirectType)!==null&&a!==void 0?a:null},error:null}}const{provider_token:l,provider_refresh_token:c,access_token:u,refresh_token:d,expires_in:m,expires_at:p,token_type:y}=e;if(!u||!m||!d||!y)throw new Jl("No session defined in URL");const v=Math.round(Date.now()/1e3),x=parseInt(m);let _=v+x;p&&(_=parseInt(p));const S=_-v;S*1e3<=Es&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${S}s, should have been closer to ${x}s`);const E=_-x;v-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,_,v):v-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,_,v);const{data:R,error:N}=await this._getUser(u);if(N)throw N;const O={provider_token:l,provider_refresh_token:c,access_token:u,expires_in:x,expires_at:_,refresh_token:d,token_type:y,user:R.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:O,redirectType:e.type},error:null})}catch(l){if(se(l))return this._returnResult({data:{session:null,redirectType:null},error:l});throw l}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){const i=await kn(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&i)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async i=>{var a;const l=async()=>{await this._removeSession(),await ot(this.storage,`${this.storageKey}-code-verifier`)},{data:c,error:u}=i;if(u&&!Yl(u))return this._returnResult({error:u});const d=(a=c.session)===null||a===void 0?void 0:a.access_token;if(d){const{error:m}=await this.admin.signOut(d,e);if(m&&!(qR(m)&&(m.status===404||m.status===401||m.status===403)||Yl(m)))return e!=="others"&&await l(),this._returnResult({error:m})}return e!=="others"&&await l(),this._returnResult({error:null})})}onAuthStateChange(e){const i=ZR(),a={id:i,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",i),this.stateChangeEmitters.delete(i)}};return this._debug("#onAuthStateChange()","registered callback with id",i),this.stateChangeEmitters.set(i,a),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(i)}):await this._emitInitialSession(i)))(),{data:{subscription:a}}}async _emitInitialSession(e){return await this._useSession(async i=>{var a,l;try{const{data:{session:c},error:u}=i;if(u)throw u;await((a=this.stateChangeEmitters.get(e))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",c)),this._debug("INITIAL_SESSION","callback id",e,"session",c)}catch(c){await((l=this.stateChangeEmitters.get(e))===null||l===void 0?void 0:l.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",c),Yl(c)?console.warn(c):console.error(c)}})}async resetPasswordForEmail(e,i={}){let a=null,l=null;this.flowType==="pkce"&&([a,l]=await Ei(this.storage,this.storageKey,!0));try{return await oe(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:a,code_challenge_method:l,gotrue_meta_security:{captcha_token:i.captchaToken}},headers:this.headers,redirectTo:i.redirectTo})}catch(c){if(await ot(this.storage,`${this.storageKey}-code-verifier`),se(c))return this._returnResult({data:null,error:c});throw c}}async getUserIdentities(){var e;try{const{data:i,error:a}=await this.getUser();if(a)throw a;return this._returnResult({data:{identities:(e=i.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(i){if(se(i))return this._returnResult({data:null,error:i});throw i}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var i;try{const{data:a,error:l}=await this._useSession(async c=>{var u,d,m,p,y;const{data:v,error:x}=c;if(x)throw x;const _=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(u=e.options)===null||u===void 0?void 0:u.redirectTo,scopes:(d=e.options)===null||d===void 0?void 0:d.scopes,queryParams:(m=e.options)===null||m===void 0?void 0:m.queryParams,skipBrowserRedirect:!0});return await oe(this.fetch,"GET",_,{headers:this.headers,jwt:(y=(p=v.session)===null||p===void 0?void 0:p.access_token)!==null&&y!==void 0?y:void 0})});if(l)throw l;return Mt()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(a==null?void 0:a.url),this._returnResult({data:{provider:e.provider,url:a==null?void 0:a.url},error:null})}catch(a){if(se(a))return this._returnResult({data:{provider:e.provider,url:null},error:a});throw a}}async linkIdentityIdToken(e){return await this._useSession(async i=>{var a;try{const{error:l,data:{session:c}}=i;if(l)throw l;const{options:u,provider:d,token:m,access_token:p,nonce:y}=e,v=await oe(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(a=c==null?void 0:c.access_token)!==null&&a!==void 0?a:void 0,body:{provider:d,id_token:m,access_token:p,nonce:y,link_identity:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Sn}),{data:x,error:_}=v;return _?this._returnResult({data:{user:null,session:null},error:_}):!x||!x.session||!x.user?this._returnResult({data:{user:null,session:null},error:new Ea}):(x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("USER_UPDATED",x.session)),this._returnResult({data:x,error:_}))}catch(l){if(await ot(this.storage,`${this.storageKey}-code-verifier`),se(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}})}async unlinkIdentity(e){try{return await this._useSession(async i=>{var a,l;const{data:c,error:u}=i;if(u)throw u;return await oe(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(l=(a=c.session)===null||a===void 0?void 0:a.access_token)!==null&&l!==void 0?l:void 0})})}catch(i){if(se(i))return this._returnResult({data:null,error:i});throw i}}async _refreshAccessToken(e){const i="#_refreshAccessToken()";this._debug(i,"begin");try{const a=Date.now();return await nN(async l=>(l>0&&await tN(200*Math.pow(2,l-1)),this._debug(i,"refreshing attempt",l),await oe(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Sn})),(l,c)=>{const u=200*Math.pow(2,l);return c&&zb(c)&&Date.now()+u-aDate.now())?this._debug(l,"proactive refresh failed, access token still valid — preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:u,expiresAt:Date.now()+BR},(i=this.refreshingDeferred)===null||i===void 0||i.resolve(u),u}throw(a=this.refreshingDeferred)===null||a===void 0||a.reject(c),c}finally{this.refreshingDeferred=null,this._debug(l,"end")}}async _notifyAllSubscribers(e,i,a=!0){if(this._pendingInitNotifications!==null&&a){this._pendingInitNotifications.push({event:e,session:i,broadcast:a});return}const l=`#_notifyAllSubscribers(${e})`;this._debug(l,"begin",i,`broadcast = ${a}`);try{this.broadcastChannel&&a&&this.broadcastChannel.postMessage({event:e,session:i});const c=[],u=Array.from(this.stateChangeEmitters.values()).map(async d=>{try{await d.callback(e,i)}catch(m){c.push(m)}});if(await Promise.all(u),c.length>0){for(let d=0;dthis._autoRefreshTokenTick(),Es);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const i=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=i,i&&typeof i=="object"&&typeof i.unref=="function"?i.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(i)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const i=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,i&&clearTimeout(i)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async i=>{const{data:{session:a}}=i;if(!a||!a.refresh_token||!a.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const l=Math.floor((a.expires_at*1e3-e)/Es);this._debug("#_autoRefreshTokenTick()",`access token expires in ${l} ticks, a tick lasts ${Es}ms, refresh threshold is ${Ir} ticks`),l<=Ir&&await this._callRefreshToken(a.refresh_token)})}catch(i){console.error("Auto refresh tick failed with error. This is likely a transient error.",i)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof xN)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{const e=Date.now();try{await this._useSession(async i=>{const{data:{session:a}}=i;if(!a||!a.refresh_token||!a.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const l=Math.floor((a.expires_at*1e3-e)/Es);this._debug("#_autoRefreshTokenTick()",`access token expires in ${l} ticks, a tick lasts ${Es}ms, refresh threshold is ${Ir} ticks`),l<=Ir&&await this._callRefreshToken(a.refresh_token)})}catch(i){console.error("Auto refresh tick failed with error. This is likely a transient error.",i)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Mt()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const i=`#_onVisibilityChanged(${e})`;if(this._debug(i,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(i,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(i,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,i,a){const l=[`provider=${encodeURIComponent(i)}`];if(a!=null&&a.redirectTo&&l.push(`redirect_to=${encodeURIComponent(a.redirectTo)}`),a!=null&&a.scopes&&l.push(`scopes=${encodeURIComponent(a.scopes)}`),this.flowType==="pkce"){const[c,u]=await Ei(this.storage,this.storageKey),d=new URLSearchParams({code_challenge:`${encodeURIComponent(c)}`,code_challenge_method:`${encodeURIComponent(u)}`});l.push(d.toString())}if(a!=null&&a.queryParams){const c=new URLSearchParams(a.queryParams);l.push(c.toString())}return a!=null&&a.skipBrowserRedirect&&l.push(`skip_http_redirect=${a.skipBrowserRedirect}`),`${e}?${l.join("&")}`}async _unenroll(e){try{return await this._useSession(async i=>{var a;const{data:l,error:c}=i;return c?this._returnResult({data:null,error:c}):await oe(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(a=l==null?void 0:l.session)===null||a===void 0?void 0:a.access_token})})}catch(i){if(se(i))return this._returnResult({data:null,error:i});throw i}}async _enroll(e){try{return await this._useSession(async i=>{var a,l;const{data:c,error:u}=i;if(u)return this._returnResult({data:null,error:u});const d=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:m,error:p}=await oe(this.fetch,"POST",`${this.url}/factors`,{body:d,headers:this.headers,jwt:(a=c==null?void 0:c.session)===null||a===void 0?void 0:a.access_token});return p?this._returnResult({data:null,error:p}):(e.factorType==="totp"&&m.type==="totp"&&(!((l=m==null?void 0:m.totp)===null||l===void 0)&&l.qr_code)&&(m.totp.qr_code=`data:image/svg+xml;utf-8,${m.totp.qr_code}`),this._returnResult({data:m,error:null}))})}catch(i){if(se(i))return this._returnResult({data:null,error:i});throw i}}async _verify(e){const i=async()=>{try{return await this._useSession(async a=>{var l;const{data:c,error:u}=a;if(u)return this._returnResult({data:null,error:u});const d=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Qb(e.webauthn.credential_response):Zb(e.webauthn.credential_response)})}:{code:e.code}),{data:m,error:p}=await oe(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:d,headers:this.headers,jwt:(l=c==null?void 0:c.session)===null||l===void 0?void 0:l.access_token});return p?this._returnResult({data:null,error:p}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+m.expires_in},m)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",m),this._returnResult({data:m,error:p}))})}catch(a){if(se(a))return this._returnResult({data:null,error:a});throw a}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,i):i()}async _challenge(e){const i=async()=>{try{return await this._useSession(async a=>{var l;const{data:c,error:u}=a;if(u)return this._returnResult({data:null,error:u});const d=await oe(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(l=c==null?void 0:c.session)===null||l===void 0?void 0:l.access_token});if(d.error)return d;const{data:m}=d;if(m.type!=="webauthn")return{data:m,error:null};switch(m.webauthn.type){case"create":return{data:Object.assign(Object.assign({},m),{webauthn:Object.assign(Object.assign({},m.webauthn),{credential_options:Object.assign(Object.assign({},m.webauthn.credential_options),{publicKey:Xb(m.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},m),{webauthn:Object.assign(Object.assign({},m.webauthn),{credential_options:Object.assign(Object.assign({},m.webauthn.credential_options),{publicKey:Jb(m.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(a){if(se(a))return this._returnResult({data:null,error:a});throw a}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,i):i()}async _challengeAndVerify(e){const{data:i,error:a}=await this._challenge({factorId:e.factorId});return a?this._returnResult({data:null,error:a}):await this._verify({factorId:e.factorId,challengeId:i.id,code:e.code})}async _listFactors(){var e;const{data:{user:i},error:a}=await this.getUser();if(a)return{data:null,error:a};const l={all:[],phone:[],totp:[],webauthn:[]};for(const c of(e=i==null?void 0:i.factors)!==null&&e!==void 0?e:[])l.all.push(c),c.status==="verified"&&l[c.factor_type].push(c);return{data:l,error:null}}async _getAuthenticatorAssuranceLevel(e){var i,a,l,c;if(e)try{const{payload:_}=Ql(e);let S=null;_.aal&&(S=_.aal);let E=S;const{data:{user:R},error:N}=await this.getUser(e);if(N)return this._returnResult({data:null,error:N});((a=(i=R==null?void 0:R.factors)===null||i===void 0?void 0:i.filter(P=>P.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(E="aal2");const C=_.amr||[];return{data:{currentLevel:S,nextLevel:E,currentAuthenticationMethods:C},error:null}}catch(_){if(se(_))return this._returnResult({data:null,error:_});throw _}const{data:{session:u},error:d}=await this.getSession();if(d)return this._returnResult({data:null,error:d});if(!u)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:m}=Ql(u.access_token);let p=null;m.aal&&(p=m.aal);let y=p;((c=(l=u.user.factors)===null||l===void 0?void 0:l.filter(_=>_.status==="verified"))!==null&&c!==void 0?c:[]).length>0&&(y="aal2");const x=m.amr||[];return{data:{currentLevel:p,nextLevel:y,currentAuthenticationMethods:x},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async i=>{const{data:{session:a},error:l}=i;return l?this._returnResult({data:null,error:l}):a?await oe(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:a.access_token,xform:c=>({data:c,error:null})}):this._returnResult({data:null,error:new Tt})})}catch(i){if(se(i))return this._returnResult({data:null,error:i});throw i}}async _approveAuthorization(e,i){try{return await this._useSession(async a=>{const{data:{session:l},error:c}=a;if(c)return this._returnResult({data:null,error:c});if(!l)return this._returnResult({data:null,error:new Tt});const u=await oe(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:l.access_token,body:{action:"approve"},xform:d=>({data:d,error:null})});return u.data&&u.data.redirect_url&&Mt()&&!(i!=null&&i.skipBrowserRedirect)&&window.location.assign(u.data.redirect_url),u})}catch(a){if(se(a))return this._returnResult({data:null,error:a});throw a}}async _denyAuthorization(e,i){try{return await this._useSession(async a=>{const{data:{session:l},error:c}=a;if(c)return this._returnResult({data:null,error:c});if(!l)return this._returnResult({data:null,error:new Tt});const u=await oe(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:l.access_token,body:{action:"deny"},xform:d=>({data:d,error:null})});return u.data&&u.data.redirect_url&&Mt()&&!(i!=null&&i.skipBrowserRedirect)&&window.location.assign(u.data.redirect_url),u})}catch(a){if(se(a))return this._returnResult({data:null,error:a});throw a}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:i},error:a}=e;return a?this._returnResult({data:null,error:a}):i?await oe(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:i.access_token,xform:l=>({data:l,error:null})}):this._returnResult({data:null,error:new Tt})})}catch(e){if(se(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async i=>{const{data:{session:a},error:l}=i;return l?this._returnResult({data:null,error:l}):a?(await oe(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:a.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Tt})})}catch(i){if(se(i))return this._returnResult({data:null,error:i});throw i}}async fetchJwk(e,i={keys:[]}){let a=i.keys.find(d=>d.kid===e);if(a)return a;const l=Date.now();if(a=this.jwks.keys.find(d=>d.kid===e),a&&this.jwks_cached_at+PR>l)return a;const{data:c,error:u}=await oe(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(u)throw u;return!c.keys||c.keys.length===0||(this.jwks=c,this.jwks_cached_at=l,a=c.keys.find(d=>d.kid===e),!a)?null:a}async getClaims(e,i={}){try{let a=e;if(!a){const{data:_,error:S}=await this.getSession();if(S||!_.session)return this._returnResult({data:null,error:S});a=_.session.access_token}const{header:l,payload:c,signature:u,raw:{header:d,payload:m}}=Ql(a);if(!(i!=null&&i.allowExpired))try{cN(c.exp)}catch(_){throw new Sc(_ instanceof Error?_.message:"JWT validation failed")}const p=!l.alg||l.alg.startsWith("HS")||!l.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(l.kid,i!=null&&i.keys?{keys:i.keys}:i==null?void 0:i.jwks);if(!p){const{error:_}=await this.getUser(a);if(_)throw _;return{data:{claims:c,header:l,signature:u},error:null}}const y=uN(l.alg),v=await crypto.subtle.importKey("jwk",p,y,!0,["verify"]);if(!await crypto.subtle.verify(y,v,u,JR(`${d}.${m}`)))throw new Sc("Invalid JWT signature");return{data:{claims:c,header:l,signature:u},error:null}}catch(a){if(se(a))return this._returnResult({data:null,error:a});throw a}}async signInWithPasskey(e){var i,a,l;Dn(this.experimental);try{if(!Ac())return this._returnResult({data:null,error:new Un("Browser does not support WebAuthn",null)});const{data:c,error:u}=await this._startPasskeyAuthentication({options:{captchaToken:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}});if(u||!c)return this._returnResult({data:null,error:u});const d=Jb(c.options),m=(l=(a=e==null?void 0:e.options)===null||a===void 0?void 0:a.signal)!==null&&l!==void 0?l:ff.createNewAbortSignal(),{data:p,error:y}=await Rw({publicKey:d,signal:m});if(y||!p)return this._returnResult({data:null,error:y??new Un("WebAuthn ceremony failed",null)});const v=Zb(p);return this._verifyPasskeyAuthentication({challengeId:c.challenge_id,credential:v})}catch(c){if(se(c))return this._returnResult({data:null,error:c});throw c}}async registerPasskey(e){var i,a;Dn(this.experimental);try{if(!Ac())return this._returnResult({data:null,error:new Un("Browser does not support WebAuthn",null)});const{data:l,error:c}=await this._startPasskeyRegistration();if(c||!l)return this._returnResult({data:null,error:c});const u=Xb(l.options),d=(a=(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.signal)!==null&&a!==void 0?a:ff.createNewAbortSignal(),{data:m,error:p}=await Cw({publicKey:u,signal:d});if(p||!m)return this._returnResult({data:null,error:p??new Un("WebAuthn ceremony failed",null)});const y=Qb(m);return this._verifyPasskeyRegistration({challengeId:l.challenge_id,credential:y})}catch(l){if(se(l))return this._returnResult({data:null,error:l});throw l}}async _startPasskeyRegistration(){Dn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:i},error:a}=e;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new Tt});const{data:l,error:c}=await oe(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:i.access_token,body:{}});return c?this._returnResult({data:null,error:c}):this._returnResult({data:l,error:null})})}catch(e){if(se(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){Dn(this.experimental);try{return await this._useSession(async i=>{const{data:{session:a},error:l}=i;if(l)return this._returnResult({data:null,error:l});if(!a)return this._returnResult({data:null,error:new Tt});const{data:c,error:u}=await oe(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:a.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return u?this._returnResult({data:null,error:u}):this._returnResult({data:c,error:null})})}catch(i){if(se(i))return this._returnResult({data:null,error:i});throw i}}async _startPasskeyAuthentication(e){var i;Dn(this.experimental);try{const{data:a,error:l}=await oe(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}}});return l?this._returnResult({data:null,error:l}):this._returnResult({data:a,error:null})}catch(a){if(se(a))return this._returnResult({data:null,error:a});throw a}}async _verifyPasskeyAuthentication(e){Dn(this.experimental);try{const{data:i,error:a}=await oe(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Sn});return a?this._returnResult({data:null,error:a}):(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:i,error:null}))}catch(i){if(se(i))return this._returnResult({data:null,error:i});throw i}}async _listPasskeys(){Dn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:i},error:a}=e;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new Tt});const{data:l,error:c}=await oe(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:i.access_token,xform:u=>({data:u,error:null})});return c?this._returnResult({data:null,error:c}):this._returnResult({data:l,error:null})})}catch(e){if(se(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){Dn(this.experimental);try{return await this._useSession(async i=>{const{data:{session:a},error:l}=i;if(l)return this._returnResult({data:null,error:l});if(!a)return this._returnResult({data:null,error:new Tt});const{data:c,error:u}=await oe(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:a.access_token,body:{friendly_name:e.friendlyName}});return u?this._returnResult({data:null,error:u}):this._returnResult({data:c,error:null})})}catch(i){if(se(i))return this._returnResult({data:null,error:i});throw i}}async _deletePasskey(e){Dn(this.experimental);try{return await this._useSession(async i=>{const{data:{session:a},error:l}=i;if(l)return this._returnResult({data:null,error:l});if(!a)return this._returnResult({data:null,error:new Tt});const{error:c}=await oe(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:a.access_token,noResolveJson:!0});return c?this._returnResult({data:null,error:c}):this._returnResult({data:null,error:null})})}catch(i){if(se(i))return this._returnResult({data:null,error:i});throw i}}}po.nextInstanceID={};const MN=po,BN="2.110.2";let Fr="",Cc;if(typeof Deno<"u"){var Sd;Fr="deno",Cc=(Sd=Deno.version)===null||Sd===void 0?void 0:Sd.deno}else if(typeof document<"u")Fr="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")Fr="react-native";else{var Td;Fr="node",Cc=typeof process<"u"?(Td=process.version)===null||Td===void 0?void 0:Td.replace(/^v/,""):void 0}const Nw=[`runtime=${Fr}`];Cc&&Nw.push(`runtime-version=${Cc}`);const UN={"X-Client-Info":`supabase-js/${BN}; ${Nw.join("; ")}`},LN={headers:UN},zN={schema:"public"},VN={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},PN={},HN={enabled:!1,respectSamplingDecision:!0};function qN(n,e,i,a){function l(c){return c instanceof i?c:new i(function(u){u(c)})}return new(i||(i=Promise))(function(c,u){function d(y){try{p(a.next(y))}catch(v){u(v)}}function m(y){try{p(a.throw(y))}catch(v){u(v)}}function p(y){y.done?c(y.value):l(y.value).then(d,m)}p((a=a.apply(n,[])).next())})}let Ed=null;const $N="@opentelemetry/api";function IN(){return Ed===null&&(Ed=import($N).catch(()=>null)),Ed}function FN(){return qN(this,void 0,void 0,function*(){try{const n=yield IN();if(!n||!n.propagation||!n.context)return null;const e={};n.propagation.inject(n.context.active(),e);const i=e.traceparent;return i?{traceparent:i,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function GN(n){if(!n||typeof n!="string")return null;const e=n.split("-");if(e.length!==4)return null;const[i,a,l,c]=e;if(i.length!==2||a.length!==32||l.length!==16||c.length!==2)return null;const u=/^[0-9a-f]+$/i;return!u.test(i)||!u.test(a)||!u.test(l)||!u.test(c)||a==="00000000000000000000000000000000"||l==="0000000000000000"?null:{version:i,traceId:a,parentId:l,traceFlags:c,isSampled:(parseInt(c,16)&1)===1}}function KN(n,e){if(!n||!e||e.length===0)return!1;let i;if(n instanceof URL)i=n;else try{i=new URL(n)}catch{return!1}for(const a of e)try{if(typeof a=="string"){if(YN(i.hostname,a))return!0}else if(a instanceof RegExp){if(a.test(i.hostname))return!0}else if(typeof a=="function"&&a(i))return!0}catch{continue}return!1}function YN(n,e){if(e===n)return!0;if(e.startsWith("*.")){const i=e.slice(2);if(n.endsWith(i)&&(n===i||n.endsWith("."+i)))return!0}return!1}function XN(n){const e=[];try{const i=new URL(n);e.push(i.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function go(n){"@babel/helpers - typeof";return go=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},go(n)}function JN(n,e){if(go(n)!="object"||!n)return n;var i=n[Symbol.toPrimitive];if(i!==void 0){var a=i.call(n,e);if(go(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function QN(n){var e=JN(n,"string");return go(e)=="symbol"?e:e+""}function ZN(n,e,i){return(e=QN(e))in n?Object.defineProperty(n,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):n[e]=i,n}function Wb(n,e){var i=Object.keys(n);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(n);e&&(a=a.filter(function(l){return Object.getOwnPropertyDescriptor(n,l).enumerable})),i.push.apply(i,a)}return i}function tt(n){for(var e=1;en?(...e)=>n(...e):(...e)=>fetch(...e),ek=()=>Headers,tk=(n,e,i,a,l)=>{const c=WN(a),u=ek(),d=(l==null?void 0:l.enabled)===!0,m=(l==null?void 0:l.respectSamplingDecision)!==!1,p=d?XN(e):null;return async(y,v)=>{var x;const _=(x=await i())!==null&&x!==void 0?x:n;let S=new u(v==null?void 0:v.headers);if(S.has("apikey")||S.set("apikey",n),S.has("Authorization")||S.set("Authorization",`Bearer ${_}`),p){const E=await nk(y,p,m);E&&(E.traceparent&&!S.has("traceparent")&&S.set("traceparent",E.traceparent),E.tracestate&&!S.has("tracestate")&&S.set("tracestate",E.tracestate),E.baggage&&!S.has("baggage")&&S.set("baggage",E.baggage))}return c(y,tt(tt({},v),{},{headers:S}))}};async function nk(n,e,i){if(!KN(typeof n=="string"||n instanceof URL?n:n.url,e))return null;const a=await FN();if(!a||!a.traceparent)return null;if(i){const l=GN(a.traceparent);if(l&&!l.isSampled)return null}return a}function ev(n){return typeof n=="boolean"?{enabled:n}:n}function sk(n){return n.endsWith("/")?n:n+"/"}function ik(n,e){var i,a,l,c,u,d;const{db:m,auth:p,realtime:y,global:v}=n,{db:x,auth:_,realtime:S,global:E}=e,R=ev(n.tracePropagation),N=ev(e.tracePropagation),O={db:tt(tt({},x),m),auth:tt(tt({},_),p),realtime:tt(tt({},S),y),storage:{},global:tt(tt(tt({},E),v),{},{headers:tt(tt({},(i=E==null?void 0:E.headers)!==null&&i!==void 0?i:{}),(a=v==null?void 0:v.headers)!==null&&a!==void 0?a:{})}),tracePropagation:{enabled:(l=(c=R==null?void 0:R.enabled)!==null&&c!==void 0?c:N==null?void 0:N.enabled)!==null&&l!==void 0?l:!1,respectSamplingDecision:(u=(d=R==null?void 0:R.respectSamplingDecision)!==null&&d!==void 0?d:N==null?void 0:N.respectSamplingDecision)!==null&&u!==void 0?u:!0},accessToken:async()=>""};return n.accessToken?O.accessToken=n.accessToken:delete O.accessToken,O}function ak(n){const e=n==null?void 0:n.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(sk(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var rk=class extends MN{constructor(n){super(n)}},ok=class{constructor(n,e,i){var a,l;this.supabaseUrl=n,this.supabaseKey=e;const c=ak(n);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",c),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",c),this.storageUrl=new URL("storage/v1",c),this.functionsUrl=new URL("functions/v1",c);const u=`sb-${c.hostname.split(".")[0]}-auth-token`,d={db:zN,realtime:PN,auth:tt(tt({},VN),{},{storageKey:u}),global:LN,tracePropagation:HN},m=ik(i??{},d);if(this.settings=m,this.storageKey=(a=m.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(l=m.global.headers)!==null&&l!==void 0?l:{},m.accessToken)this.accessToken=m.accessToken,this.auth=new Proxy({},{get:(y,v)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(v)} is not possible`)}});else{var p;this.auth=this._initSupabaseAuthClient((p=m.auth)!==null&&p!==void 0?p:{},this.headers,m.global.fetch)}this.fetch=tk(e,n,this._getAccessToken.bind(this),m.global.fetch,m.tracePropagation),this.realtime=this._initRealtimeClient(tt({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},m.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(y=>this.realtime.setAuth(y)).catch(y=>console.warn("Failed to set initial Realtime auth token:",y)),this.rest=new gC(new URL("rest/v1",c).href,{headers:this.headers,schema:m.db.schema,fetch:this.fetch,timeout:m.db.timeout,urlLengthLimit:m.db.urlLengthLimit}),this.storage=new MR(this.storageUrl.href,this.headers,this.fetch,i==null?void 0:i.storage),m.accessToken||this._listenForAuthEvents()}get functions(){return new oC(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(n){return this.rest.from(n)}schema(n){return this.rest.schema(n)}rpc(n,e={},i={head:!1,get:!1,count:void 0}){return this.rest.rpc(n,e,i)}channel(n,e={config:{}}){return this.realtime.channel(n,e)}getChannels(){return this.realtime.getChannels()}removeChannel(n){return this.realtime.removeChannel(n)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var n=this,e,i;if(n.accessToken)return await n.accessToken();const{data:a}=await n.auth.getSession();return(e=(i=a.session)===null||i===void 0?void 0:i.access_token)!==null&&e!==void 0?e:n.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:n,persistSession:e,detectSessionInUrl:i,storage:a,userStorage:l,storageKey:c,flowType:u,lock:d,debug:m,throwOnError:p,experimental:y,lockAcquireTimeout:v,skipAutoInitialize:x},_,S){const E={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new rk({url:this.authUrl.href,headers:tt(tt({},E),_),storageKey:c,autoRefreshToken:n,persistSession:e,detectSessionInUrl:i,storage:a,userStorage:l,flowType:u,lock:d,debug:m,throwOnError:p,experimental:y,fetch:S,lockAcquireTimeout:v,skipAutoInitialize:x,hasCustomAuthorizationHeader:Object.keys(this.headers).some(R=>R.toLowerCase()==="authorization")})}_initRealtimeClient(n){return new iR(this.realtimeUrl.href,tt(tt({},n),{},{params:tt(tt({},{apikey:this.supabaseKey}),n==null?void 0:n.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((n,e)=>{this._handleTokenChanged(n,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(n,e,i){(n==="TOKEN_REFRESHED"||n==="SIGNED_IN")&&this.changedAccessToken!==i?(this.changedAccessToken=i,this.realtime.setAuth(i)):n==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const lk=(n,e,i)=>new ok(n,e,i);function ck(){if(typeof window<"u")return!1;const n=globalThis.process;if(!n)return!1;const e=n.version;if(e==null)return!1;const i=e.match(/^v(\d+)\./);return i?parseInt(i[1],10)<=20:!1}ck()&&console.warn("⚠️ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");const uk="https://dbit.digitalcompass.agency",kw="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE",eo=!!kw,lt=eo?lk(uk,kw,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!0}}):null;function Ow(){return new URL("/cruce-cuentas/",window.location.origin).toString()}async function hk(){if(typeof window>"u"||typeof fetch>"u")return;const n=Ow(),e=new AbortController,i=window.setTimeout(()=>e.abort(),8e3);try{await(await fetch(n,{method:"GET",cache:"reload",credentials:"same-origin",redirect:"follow",headers:{Accept:"text/html,application/xhtml+xml"},signal:e.signal})).text()}catch(a){console.warn("No se pudo refrescar preventivamente la entrada de la app:",a)}finally{window.clearTimeout(i)}}const dk=180,fk=8e3;async function Rc(n=dk){if(!lt)return null;const{data:e,error:i}=await lt.auth.getSession();if(i)throw i;let a=e.session;if(!a)throw new Error("Tu sesión expiró. Inicia sesión nuevamente antes de continuar.");const l=Number(a.expires_at||0)*1e3;if(!l||l-Date.now()<=n*1e3){const u=await lt.auth.refreshSession();if(u.error)throw u.error;if(a=u.data.session,!a)throw new Error("Tu sesión expiró. Inicia sesión nuevamente antes de continuar.")}return a}async function tv(n){if(typeof window>"u"||typeof fetch>"u")return;if(typeof navigator<"u"&&navigator.onLine===!1)throw new Error("No hay conexión a Internet. Verifica tu conexión e intenta nuevamente.");let e;try{e=new URL(n,window.location.origin)}catch{return}if(e.origin===window.location.origin)return;const i=new URL("/favicon.ico",e.origin);i.searchParams.set("_glm_resume",String(Date.now()));const a=new AbortController,l=window.setTimeout(()=>a.abort(),fk);try{await fetch(i.toString(),{method:"GET",mode:"no-cors",cache:"no-store",credentials:"omit",signal:a.signal})}catch(c){if(typeof navigator<"u"&&navigator.onLine===!1)throw new Error("No hay conexión a Internet. Verifica tu conexión e intenta nuevamente.");console.warn("No se pudo precalentar la conexión con n8n:",c)}finally{window.clearTimeout(l)}}function nv(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`glm-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function sv(n,e){try{const i=new URL(n,window.location.origin);return i.searchParams.set("client_request_id",e),i.searchParams.set("_ts",String(Date.now())),i.toString()}catch{return n}}const mk="https://agenteit.digitalcompass.agency/webhook/cruce-cuentas-bamboo-correccion",Ad=["Nombre mal escrito en BambooHR","Apodo o nombre de uso","Nombre incompleto / nombres adicionales","Otro"];function pk(n){try{return n?JSON.parse(n):null}catch{return null}}function Dw({row:n,country:e,periodRange:i,operatorName:a,operatorEmail:l,executionId:c,reportUrl:u,onClose:d,onSuccess:m,onShowToast:p}){const y=n.bestBambooCandidate,[v,x]=M.useState((y==null?void 0:y.employeeName)||""),[_,S]=M.useState((y==null?void 0:y.employeeNumber)||""),[E,R]=M.useState(Ad[0]),[N,O]=M.useState(""),[C,P]=M.useState(!1),[Y,X]=M.useState(!1);M.useEffect(()=>{x((y==null?void 0:y.employeeName)||""),S((y==null?void 0:y.employeeNumber)||""),R(Ad[0]),O(""),P(!1)},[n.id,y==null?void 0:y.employeeName,y==null?void 0:y.employeeNumber]);const q=M.useMemo(()=>e.code==="TT"?"Laurele Nicome-Jack":"Pablo Gamboa Cú, Sara Meyer Lima y María Morales Adler",[e.code]),Z=M.useMemo(()=>Array.from(new Set([n.employee,n.bankNameFile,n.bankAccountHolder].map(Q=>String(Q||"").trim()).filter(Boolean))),[n.employee,n.bankNameFile,n.bankAccountHolder]),te=async()=>{var Q;if(!v.trim()){p("Escribe el nombre correcto del empleado en BambooHR.","error");return}if(!C){p("Confirma que se trata de la misma persona antes de enviar el caso.","error");return}if(!lt){p("Supabase no está configurado en esta aplicación.","error");return}X(!0);try{const le=await Rc(300),he=le==null?void 0:le.access_token;if(!he)throw new Error("Tu sesión expiró. Inicia sesión nuevamente antes de reportar el caso.");const Ge={country:e.code,country_name:e.name,source_name:n.employee,source_names:Z,bank_name_file:n.bankNameFile||"",bank_account_holder:n.bankAccountHolder||"",bank_account:n.account||"",bank_amount:n.amountBank,currency:e.currency,bamboo_name:v.trim(),bamboo_employee_number:_.trim(),reason:E,comment:N.trim(),confirmed_same_person:!0,execution_id:c||"",report_url:u||"",period_label:i.label,period_start:i.start,period_end:i.end,requested_by_name:a,requested_by_email:l},Ne=new FormData;Ne.append("payload",JSON.stringify(Ge)),Ne.append("access_token",he);const xe=await fetch(mk,{method:"POST",body:Ne}),z=await xe.text(),G=pk(z);if(!xe.ok||(G==null?void 0:G.ok)===!1){const K=(G==null?void 0:G.message)||(G==null?void 0:G.error)||((Q=G==null?void 0:G.errors)==null?void 0:Q[0])||z||"No se pudo enviar el caso a RRHH.";throw new Error(String(K))}m(n.id),p(`Caso enviado a RRHH de ${e.name}. La equivalencia quedó registrada para futuros cruces.`,"success"),d()}catch(le){const he=le instanceof Error?le.message:"No se pudo enviar el caso a RRHH.";p(he,"error")}finally{X(!1)}};return g.jsxs("div",{className:"fixed inset-0 z-[90] flex items-center justify-center px-4 py-6",children:[g.jsx("button",{type:"button",className:"absolute inset-0 bg-black/45",onClick:Y?void 0:d,"aria-label":"Cerrar"}),g.jsxs("div",{className:"relative w-full max-w-2xl bg-white border border-[#D0D0D0] shadow-2xl max-h-[92vh] overflow-y-auto",children:[g.jsx("div",{className:"h-1.5 bg-[#6CC24A]"}),g.jsxs("div",{className:"px-6 py-5 border-b border-neutral-200 flex items-start justify-between gap-4",children:[g.jsxs("div",{children:[g.jsx("p",{className:"text-[10px] uppercase tracking-[0.18em] font-black text-[#6B8FA3]",children:"Banco sin BambooHR"}),g.jsx("h2",{className:"text-xl font-black text-[#4F758B] mt-1",children:"Reportar corrección de identidad a RRHH"}),g.jsx("p",{className:"text-xs text-neutral-500 mt-2 leading-relaxed",children:"Esta validación crea una equivalencia permanente para que el mismo falso positivo no vuelva a aparecer mientras RRHH corrige BambooHR."})]}),g.jsx("button",{type:"button",onClick:d,disabled:Y,className:"p-2 text-neutral-400 hover:text-neutral-700 hover:bg-neutral-100 disabled:opacity-40","aria-label":"Cerrar modal",children:g.jsx(ro,{className:"w-5 h-5"})})]}),g.jsxs("div",{className:"px-6 py-5 space-y-5",children:[g.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 bg-[#F5F5F5] border border-neutral-200 p-4",children:[g.jsxs("div",{children:[g.jsx("p",{className:"text-[9px] uppercase tracking-wider font-black text-[#6B8FA3]",children:"Nombre detectado"}),g.jsx("p",{className:"text-sm font-black text-neutral-800 mt-1",children:n.employee})]}),g.jsxs("div",{children:[g.jsx("p",{className:"text-[9px] uppercase tracking-wider font-black text-[#6B8FA3]",children:"Cuenta bancaria"}),g.jsx("p",{className:"text-sm font-mono font-bold text-neutral-700 mt-1",children:n.account||"—"})]}),g.jsxs("div",{className:"sm:col-span-2",children:[g.jsx("p",{className:"text-[9px] uppercase tracking-wider font-black text-[#6B8FA3]",children:"Se notificará a"}),g.jsx("p",{className:"text-xs font-bold text-neutral-700 mt-1",children:q})]})]}),(y==null?void 0:y.employeeName)&&g.jsxs("div",{className:"border border-[#D6E8F4] bg-[#F7FBFD] p-4 flex items-start gap-3",children:[g.jsx(ao,{className:"w-4 h-4 text-[#4F758B] mt-0.5 flex-shrink-0"}),g.jsxs("div",{className:"text-xs text-neutral-600 leading-relaxed",children:[g.jsx("strong",{className:"text-[#4F758B]",children:"Candidato sugerido por el cruce:"})," ",y.employeeName,y.employeeNumber?` · Employee Number ${y.employeeNumber}`:"",". Verifícalo manualmente antes de confirmar."]})]}),g.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[g.jsxs("label",{className:"sm:col-span-2",children:[g.jsx("span",{className:"block text-[10px] uppercase tracking-wider font-black text-[#4F758B] mb-1.5",children:"Nombre correcto en BambooHR *"}),g.jsx("input",{type:"text",value:v,onChange:Q=>x(Q.target.value),placeholder:"Ej.: Jonathan Alexander Pérez",className:"w-full border border-[#D0D0D0] px-3 py-2.5 text-sm font-medium focus:outline-none focus:border-[#4F758B]"})]}),g.jsxs("label",{children:[g.jsx("span",{className:"block text-[10px] uppercase tracking-wider font-black text-[#4F758B] mb-1.5",children:"Employee Number"}),g.jsx("input",{type:"text",value:_,onChange:Q=>S(Q.target.value),placeholder:"Recomendado para mayor seguridad",className:"w-full border border-[#D0D0D0] px-3 py-2.5 text-sm font-medium focus:outline-none focus:border-[#4F758B]"})]}),g.jsxs("label",{children:[g.jsx("span",{className:"block text-[10px] uppercase tracking-wider font-black text-[#4F758B] mb-1.5",children:"Motivo *"}),g.jsx("select",{value:E,onChange:Q=>R(Q.target.value),className:"w-full border border-[#D0D0D0] px-3 py-2.5 text-sm font-medium focus:outline-none focus:border-[#4F758B] bg-white",children:Ad.map(Q=>g.jsx("option",{value:Q,children:Q},Q))})]}),g.jsxs("label",{className:"sm:col-span-2",children:[g.jsx("span",{className:"block text-[10px] uppercase tracking-wider font-black text-[#4F758B] mb-1.5",children:"Comentario para RRHH"}),g.jsx("textarea",{value:N,onChange:Q=>O(Q.target.value),rows:3,placeholder:"Detalle adicional que ayude a RRHH a corregir el registro.",className:"w-full border border-[#D0D0D0] px-3 py-2.5 text-sm font-medium focus:outline-none focus:border-[#4F758B] resize-y"})]})]}),g.jsxs("label",{className:"flex items-start gap-3 border border-[#D0D0D0] p-4 cursor-pointer",children:[g.jsx("input",{type:"checkbox",checked:C,onChange:Q=>P(Q.target.checked),className:"mt-0.5 accent-[#6CC24A]"}),g.jsxs("span",{className:"text-xs text-neutral-600 leading-relaxed",children:["Confirmo que revisé el caso manualmente y que ",g.jsx("strong",{children:n.employee})," corresponde a la misma persona indicada arriba en BambooHR."]})]})]}),g.jsxs("div",{className:"px-6 py-4 border-t border-neutral-200 bg-neutral-50 flex flex-col-reverse sm:flex-row sm:justify-end gap-2",children:[g.jsx("button",{type:"button",onClick:d,disabled:Y,className:"px-4 py-2.5 border border-neutral-300 bg-white text-neutral-600 text-xs font-black uppercase tracking-wider disabled:opacity-40",children:"Cancelar"}),g.jsx("button",{type:"button",onClick:te,disabled:Y||!C||!v.trim(),className:"px-5 py-2.5 bg-[#4F758B] text-white text-xs font-black uppercase tracking-wider inline-flex items-center justify-center gap-2 border-l-4 border-[#6CC24A] disabled:bg-neutral-300 disabled:border-neutral-300 disabled:cursor-not-allowed",children:Y?g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin"}),"Enviando..."]}):g.jsxs(g.Fragment,{children:[g.jsx(Qj,{className:"w-4 h-4"}),"Enviar a RRHH"]})})]})]})]})}const Mw=[{value:1,label:"Enero"},{value:2,label:"Febrero"},{value:3,label:"Marzo"},{value:4,label:"Abril"},{value:5,label:"Mayo"},{value:6,label:"Junio"},{value:7,label:"Julio"},{value:8,label:"Agosto"},{value:9,label:"Septiembre"},{value:10,label:"Octubre"},{value:11,label:"Noviembre"},{value:12,label:"Diciembre"}],iv=[{value:"quincena_15",label:"Quincena 15",description:"Del día 1 al 15 del mes."},{value:"quincena_30",label:"Quincena 30 / fin de mes",description:"Del día 16 al último día del mes."}],gk="https://agenteit.digitalcompass.agency/webhook/cruce-cuentas-analizar-nomina";function yk(n){return n==="TT"?"https://agenteit.digitalcompass.agency/webhook/nominatt-bamboo-test":"https://agenteit.digitalcompass.agency/webhook/nominagt-bamboo-test"}function bk(){return"https://agenteit.digitalcompass.agency/webhook/bono14gt-bamboo-test"}function vk(){const n=new Date().getFullYear(),e=n-5,i=n+10;return Array.from({length:i-e+1},(a,l)=>e+l)}function xk(){const n=new Date,e=n.getDate();let i=n.getFullYear(),a=n.getMonth()+1,l="quincena_15";return e<=15&&(a-=1,l="quincena_30",a===0&&(a=12,i-=1)),{year:i,month:a,periodType:l}}function mf(n){return n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(2)} MB`}function Zl(n){const e=n.name.toLowerCase();return e.endsWith(".xlsx")||e.endsWith(".xls")}function jd(n){return n.name.toLowerCase().endsWith(".csv")}function Cd(n){return Array.from(n).map(e=>({name:e.name,size:mf(e.size),type:"bank",rawFile:e}))}function La(n,e,i){return`${n}-${String(e).padStart(2,"0")}-${String(i).padStart(2,"0")}`}function av(n,e,i){var c;const a=new Date(n,e,0).getDate(),l=((c=Mw.find(u=>u.value===e))==null?void 0:c.label)??"Mes";return i==="quincena_15"?{start:La(n,e,1),end:La(n,e,15),label:`${l} ${n} · Quincena 15`}:{start:La(n,e,16),end:La(n,e,a),label:`${l} ${n} · Quincena 30 / fin de mes`}}function wk(n){const e=n-1;return{start:La(e,7,1),end:La(n,6,30),label:`Bono 14 ${n} · Julio ${e} a junio ${n}`}}function Rd(n,e,i){if(n==null||Number.isNaN(n))return"—";const a=i==="USD"||i==="GTQ"||i==="TTD"?i:e.currency,l=a==="USD"?"en-US":e.locale;return new Intl.NumberFormat(l,{style:"currency",currency:a,minimumFractionDigits:2}).format(n)}function Fn(n,e=0){const i=Number(n);return Number.isFinite(i)?i:e}function wt(n){return n.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function _k(n,e){const i=wt(String(n??e??""));return i.includes("coincid")?"Coincidencia":i.includes("resuelto")?"Resuelto":i.includes("no encontrado")?"No encontrado":i.includes("pendiente")?"Pendiente revisión":i.includes("riesgo")||i.includes("discrep")||i.includes("mal digitada")?"Riesgo":e==="coincidencia"?"Coincidencia":e==="posible_cuenta_mal_digitada"||e==="discrepancia"?"Riesgo":"Pendiente revisión"}function Wl(n,e){for(const i of e){if(typeof n[i]=="number")return n[i];if(typeof n[i]=="string"&&n[i]!==""){const a=n[i].replace(/[Q,$\s]/g,"").replace(/,/g,""),l=Number(a);if(Number.isFinite(l))return l}}return null}function rv(n){return Array.isArray(n)?n.map((e,i)=>{const a=e,l=String(a.category??a.categoria??a.tipo??a.source??a.fuente??""),c=Wl(a,["amountPayroll","monto_nomina","payroll_amount","amount_payroll","montoNomina"]),u=Wl(a,["amountBank","monto_banco","bank_amount","amount_bank","montoBanco"]),d=Wl(a,["difference","diferencia","diff"]);return{id:String(a.id??a.employeeNumber??a.employee_number??a.account??a.cuenta??`row-${i+1}`),employee:String(a.employee??a.empleado??a.name??a.nombre??a.employee_name??"Sin nombre"),employeeNumber:String(a.employeeNumber??a.employee_number??a.codigo??""),account:a.account||a.cuenta||a.bank_account?String(a.account??a.cuenta??a.bank_account):void 0,currency:String(a.currency??a.moneda??"").toUpperCase()||void 0,amountPayroll:c,amountBank:u,difference:d??(c!==null&&u!==null?c-u:null),status:_k(a.status??a.estado,l),category:l,observation:String(a.observation??a.observacion??a.note??a.nota??a.comentario??""),source:a.source??a.fuente??l,bankNameFile:String(a.bank_name_file??a.bankNameFile??""),bankAccountHolder:String(a.bank_account_holder??a.bankAccountHolder??""),bestBambooCandidate:a.best_bamboo_candidate&&typeof a.best_bamboo_candidate=="object"?{employeeNumber:String(a.best_bamboo_candidate.employee_number??""),employeeName:String(a.best_bamboo_candidate.employee_name??""),score:Wl(a.best_bamboo_candidate,["score"])}:null,ambiguousBambooMatch:!!a.ambiguous_bamboo_match}}):[]}function ov(n){const i=(Array.isArray(n)?n[0]:n)??{},a=i.originalResponse??i.original_response??i.response??i,l=a.summary??a.resumen??i.summary??i.resumen??{},c=rv(a.rows??i.rows??a.resultados??i.resultados??[]),u=rv(a.bankWithoutBamboo??i.bankWithoutBamboo??a.banco_sin_bamboo_rows??i.banco_sin_bamboo_rows??[]).map(C=>({...C,category:C.category||"banco_sin_bamboo",source:"banco_sin_bamboo",status:C.status==="Coincidencia"?"Pendiente revisión":C.status})),d=new Map;[...c,...u].forEach((C,P)=>{const Y=C.id||`${C.source??C.category??"row"}-${P}`;d.set(Y,C)});const m=Array.from(d.values()),p=Fn(l.matches??l.coincidencias,c.filter(C=>C.status==="Coincidencia").length),y=Fn(l.discrepancies??l.discrepancias,c.filter(C=>{const P=wt(String(C.category??C.source??""));return P.includes("discrepancia")||P.includes("posible_cuenta_mal_digitada")}).length),v=Fn(l.bankWithoutPayroll??l.bancoSinNomina??l.banco_sin_nomina,c.filter(C=>Oa(C,"banco_sin_nomina")).length),x=Fn(l.bankWithoutBamboo??l.bancoSinBamboo??l.banco_sin_bamboo,u.length),_=Fn(l.payrollWithoutAccount??l.nominaSinCuenta??l.nomina_sin_cuenta),S=Fn(l.nameDifferences??l.diferenciasNombreBanco??l.diferencias_nombre_banco,c.filter(C=>wt(String(C.category??"")).includes("diferencia_nombre_banco")).length),E=Fn(l.possibleWrongAccounts??l.posiblesCuentasMalDigitadas??l.posibles_cuentas_mal_digitadas,c.filter(C=>wt(String(C.category??"")).includes("posible_cuenta_mal_digitada")).length),R=y+v+x+_+S,N=a.metadata??i.metadata??{},O=String(N.period_type??N.periodType??"").toLowerCase();return{ok:!!(a.ok??i.ok??!0),reportKind:O==="bono14"?"bono14":"nomina",executionId:a.executionId||a.execution_id||i.executionId||i.execution_id?String(a.executionId??a.execution_id??i.executionId??i.execution_id):void 0,reportUrl:a.reportUrl||a.report_url||i.reportUrl||i.report_url||i.google_sheet_url?String(a.reportUrl??a.report_url??i.reportUrl??i.report_url??i.google_sheet_url):void 0,summary:{matches:p,discrepancies:y,bankWithoutPayroll:v,bankWithoutBamboo:x,payrollWithoutAccount:_,nameDifferences:S,possibleWrongAccounts:E,totalPending:R,totalRows:m.length,totalPayroll:Fn(l.totalNomina??l.total_nomina,void 0),totalBank:Fn(l.totalBanco??l.total_banco,void 0),totalDifference:Fn(l.diferenciaTotal??l.diferencia_total,void 0)},rows:m,message:a.message||i.message?String(a.message??i.message):void 0}}function Sk(n){return n==="Coincidencia"?"bg-emerald-50 text-emerald-800 border-emerald-200":n==="Resuelto"?"bg-blue-50 text-blue-800 border-blue-200":n==="No encontrado"?"bg-amber-50 text-amber-800 border-amber-200":n==="Pendiente revisión"?"bg-neutral-100 text-neutral-700 border-neutral-300":"bg-red-50 text-[#ba1a1a] border-red-200"}function lv(n){const e=wt(String(n.category??n.source??"")),i=wt(n.observation??"");return n.status==="Coincidencia"||e.includes("coincidencia")?90:e.includes("posible_cuenta_mal_digitada")||i.includes("mal digitada")?1:e.includes("discrepancia")||n.status==="Riesgo"?2:e.includes("banco_sin_bamboo")?3:e.includes("banco_sin_nomina")?4:e.includes("diferencia_nombre_banco")?5:e.includes("nomina_sin_cuenta")?6:n.status==="Pendiente revisión"?7:n.status==="No encontrado"?10:20}function Tk(n){return[...n].sort((e,i)=>{const a=lv(e)-lv(i);return a!==0?a:e.employee.localeCompare(i.employee,"es")})}function Ek(n){const e=wt(String(n.category??n.source??""));return e.includes("discrepancia")||e.includes("posible_cuenta_mal_digitada")}function Oa(n,e){return n.source===e||wt(String(n.category??"")).includes(e)}function Ak(n,e="nomina"){const i=wt(String(n??""));return i?i.includes("posible_cuenta_mal_digitada")?"Posible cuenta mal digitada":i.includes("banco_sin_bamboo")?"Banco sin Bamboo":i.includes("banco_sin_nomina")?e==="bono14"?"Banco sin Bono 14":"Banco sin nómina":i.includes("diferencia_nombre_banco")?"Diferencia nombre banco":i.includes("nomina_sin_cuenta")?e==="bono14"?"Bono 14 sin cuenta":"Nómina sin cuenta":i.includes("discrepancia")?"Discrepancia":i.includes("coincidencia")?"Coincidencia":String(n).replace(/_/g," "):"—"}function cv(n){const e=n instanceof Error?n.message:"";return e.includes("planillas del banco repetidas")||e.toLowerCase().includes("sesión expiró")||e.toLowerCase().includes("no hay conexión a internet")?e:"No se pudo procesar el cruce. Verifica los archivos e intenta nuevamente."}function jk(n){try{return new TextDecoder("windows-1252").decode(n)}catch{return new TextDecoder("utf-8").decode(n)}}function uv(n,e){let i=0,a=!1;for(let l=0;luv(n,a)>uv(n,i)?a:i)}function hv(n,e=Bw(n)){const i=[];let a="",l=!1;for(let c=0;cc.replace(/^\uFEFF/,"").trim())}function Ck(n){const e=String(n??"").replace(/\D/g,"");return/^\d{1,20}$/.test(e)?e:null}function Rk(n){const e=n.split(/\r?\n/).slice(0,120);for(const i of e.slice(0,25)){const l=wt(i).match(/(?:consulta\s+(?:del\s+)?)?detalle\s+(?:del\s+)?envio\s+(\d{1,20})/);if(l!=null&&l[1])return l[1]}for(let i=0;iwt(m).trim()).findIndex(m=>m==="numero de envio"||m.includes("numero de envio"));if(!(d<0))for(let m=i+1;mi.length>1).map(([i,a])=>({shipmentNumber:i,fileNames:a}))}const kk={1:["enero","january","jan"],2:["febrero","february","feb"],3:["marzo","march","mar"],4:["abril","april","apr"],5:["mayo","may"],6:["junio","june","jun"],7:["julio","july","jul"],8:["agosto","august","aug"],9:["septiembre","setiembre","september","sep"],10:["octubre","october","oct"],11:["noviembre","november","nov"],12:["diciembre","december","dec"]};function Ok(n){const e=wt(n).replace(/[_\-.()]+/g," ").replace(/\s+/g," ").trim(),i=e.match(/\b(20\d{2})\b/),a=i?Number(i[1]):void 0;let l;for(const[u,d]of Object.entries(kk))if(d.some(m=>new RegExp(`\\b${m}\\b`,"i").test(e))){l=Number(u);break}let c;return/\b(?:1q|q1|quincena\s*15|primera\s+quincena)\b/.test(e)?c="quincena_15":/\b(?:2q|q2|quincena\s*30|segunda\s+quincena|fin\s+de\s+mes)\b/.test(e)?c="quincena_30":/\b15\b/.test(e)?c="quincena_15":/\b(?:30|31)\b/.test(e)&&(c="quincena_30"),{year:a,month:l,periodType:c}}function fv(n){const e=xk();try{const i=window.localStorage.getItem(`glm_cruce_period_${n}`);if(!i)return e;const a=JSON.parse(i);if(Number.isInteger(a.year)&&Number.isInteger(a.month)&&a.month>=1&&a.month<=12&&(a.periodType==="quincena_15"||a.periodType==="quincena_30"))return a}catch{}return e}async function Dk(n,e){const i=Ok(n);try{const a=await fetch(gk,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify({fileName:n,country:e.code,countryName:e.name})});if(!a.ok)return i;const l=await a.json().catch(()=>null),c=(l==null?void 0:l.detected)??(l==null?void 0:l.result)??(l==null?void 0:l.analysis)??l??{},u=String(c.periodType??c.period_type??""),d=Number(c.year)||i.year,m=Number(c.month)||i.month,p=u==="quincena_15"||u==="quincena_30"?u:i.periodType;return{year:d,month:m,periodType:p,confidence:Number.isFinite(Number(c.confidence))?Number(c.confidence):void 0,requiresManualReview:!!(c.requiresManualReview??c.requires_manual_review??!1),source:String(c.source??"gemini")}}catch{return{...i,source:"local_fallback",requiresManualReview:!(Number.isInteger(i.year)&&Number.isInteger(i.month)&&(i.periodType==="quincena_15"||i.periodType==="quincena_30"))}}}function Mk({onShowToast:n,uploadedPayroll:e,setUploadedPayroll:i,uploadedBankFiles:a,setUploadedBankFiles:l,isCruceExecuted:c,setIsCruceExecuted:u,response:d,setResponse:m,onOpenSidebar:p,operatorName:y,operatorEmail:v,resetToken:x=0,country:_}){const S=M.useMemo(()=>fv(_.code),[_.code]),[E,R]=M.useState(!1),[N,O]=M.useState(""),[C,P]=M.useState("todos"),[Y,X]=M.useState(S.year),[q,Z]=M.useState(S.month),[te,Q]=M.useState(S.periodType),[le,he]=M.useState(1),[Ge,Ne]=M.useState(""),[xe,z]=M.useState(""),[G,K]=M.useState(null),[ie,ue]=M.useState([]),[A,H]=M.useState(""),[J,W]=M.useState(null),[fe,ge]=M.useState(()=>new Set),Ee=`glm_cruce_period_${_.code}`,Ye=M.useRef(null),Le=M.useRef(null),Pt=M.useRef(null),Qt=M.useRef(null),ii=M.useMemo(()=>vk(),[]),Zt=M.useMemo(()=>av(Y,q,te),[Y,q,te]),ee=_.code==="GT"&&q===7&&te==="quincena_15",Ce=M.useMemo(()=>wk(Y),[Y]),_e=(d==null?void 0:d.reportKind)==="bono14",Me=_e?Ce.label:Zt.label,st=M.useMemo(()=>Tk((d==null?void 0:d.rows)??[]),[d==null?void 0:d.rows]),Ht=M.useMemo(()=>{const D=wt(xe.trim());return a.map((ne,we)=>({file:ne,originalIndex:we})).filter(({file:ne})=>!D||wt(ne.name).includes(D))},[a,xe]),qt=M.useMemo(()=>{const D=wt(A.trim());return ie.map((ne,we)=>({file:ne,originalIndex:we})).filter(({file:ne})=>!D||wt(ne.name).includes(D))},[ie,A]),ct=st.filter(D=>{const ne=wt(Ge.trim());return wt(`${D.employee} ${D.employeeNumber} ${D.account??""} ${D.observation} ${D.category??""} ${D.source??""}`).includes(ne)?C==="discrepancias"?Ek(D):C==="coincidencias"?D.status==="Coincidencia":C==="banco_sin_nomina"?Oa(D,"banco_sin_nomina"):C==="banco_sin_bamboo"?Oa(D,"banco_sin_bamboo"):C==="diferencia_nombre_banco"?Oa(D,"diferencia_nombre_banco"):C==="nomina_sin_cuenta"?Oa(D,"nomina_sin_cuenta"):!0:!1}),zn=10,Bt=Math.max(1,Math.ceil(ct.length/zn)),ut=ct.slice((le-1)*zn,le*zn);M.useEffect(()=>{le>Bt&&he(Bt)},[le,Bt]);const Di=M.useMemo(()=>{var D;return((D=iv.find(ne=>ne.value===te))==null?void 0:D.description)??""},[te]);M.useEffect(()=>{const D=fv(_.code);X(D.year),Z(D.month),Q(D.periodType),he(1),Ne(""),z(""),H(""),K(null),ue([]),P("todos"),W(null),ge(new Set)},[_.code]),M.useEffect(()=>{window.localStorage.setItem(Ee,JSON.stringify({year:Y,month:q,periodType:te}))},[Ee,Y,q,te]),M.useEffect(()=>{Ne(""),z(""),H(""),K(null),ue([]),P("todos"),he(1),O(""),R(!1),W(null),ge(new Set),Ye.current&&(Ye.current.value=""),Le.current&&(Le.current.value=""),Pt.current&&(Pt.current.value=""),Qt.current&&(Qt.current.value="")},[x]),M.useEffect(()=>{a.length===0&&xe&&z("")},[a.length,xe]),M.useEffect(()=>{ie.length===0&&A&&H("")},[ie.length,A]);const Xe=()=>{u(!1),m(null),he(1),Ne(""),P("todos")},dn=async D=>{i({name:D.name,size:mf(D.size),type:"payroll",rawFile:D}),Xe();const ne=await Dk(D.name,_);if(Number.isInteger(ne.year)&&Number.isInteger(ne.month)&&(ne.periodType==="quincena_15"||ne.periodType==="quincena_30")){X(ne.year),Z(ne.month),Q(ne.periodType);const ts=av(ne.year,ne.month,ne.periodType);ne.requiresManualReview?n(`Nómina cargada. Período sugerido: ${ts.label}. Confirma los datos antes de ejecutar.`,"info"):n(`Nómina cargada. Período detectado: ${ts.label}.`,"success");return}n("Archivo de nómina cargado con éxito.","success")},Wt=D=>{D.preventDefault()},An=async D=>{D.preventDefault();const ne=D.dataTransfer.files[0];ne&&(Zl(ne)?await dn(ne):n("Formato inválido. Por favor carga un archivo Excel (.xlsx, .xls).","error"))},Mi=D=>{D.preventDefault();const we=Array.from(D.dataTransfer.files).filter(jd);if(we.length===0){n("Formato inválido. Por favor carga uno o varios archivos CSV (.csv).","error");return}l([...a,...Cd(we)]),Xe(),n(`${we.length} planilla(s) del banco cargada(s) con éxito.`,"success")},Bi=async D=>{var we;const ne=(we=D.target.files)==null?void 0:we[0];ne&&(Zl(ne)?await dn(ne):n("Formato inválido. Por favor carga un archivo Excel (.xlsx, .xls).","error"))},Ga=D=>{const ne=D.target.files;if(!ne||ne.length===0)return;const we=Array.from(ne).filter(jd);if(we.length===0){n("Formato inválido. Por favor carga uno o varios archivos CSV (.csv).","error");return}l([...a,...Cd(we)]),Xe(),n(`${we.length} planilla(s) del banco cargada(s) con éxito.`,"success")},ai=D=>{l(a.filter((ne,we)=>we!==D)),Le.current&&(Le.current.value=""),Xe(),n("Planilla de banco removida.","info")},Ot=D=>{K({name:D.name,size:mf(D.size),type:"payroll",rawFile:D}),Xe(),n("Archivo Excel de Bono 14 cargado con éxito.","success")},Vn=D=>{D.preventDefault();const ne=D.dataTransfer.files[0];if(ne){if(!Zl(ne)){n("Formato inválido. El Bono 14 requiere un archivo Excel (.xlsx, .xls).","error");return}Ot(ne)}},Ut=D=>{var we;const ne=(we=D.target.files)==null?void 0:we[0];if(ne){if(!Zl(ne)){n("Formato inválido. El Bono 14 requiere un archivo Excel (.xlsx, .xls).","error");return}Ot(ne)}},_o=D=>{const ne=D.filter(jd);if(ne.length===0){n("Formato inválido. Carga uno o varios archivos CSV del Bono 14.","error");return}ue([...ie,...Cd(ne)]),Xe(),n(`${ne.length} archivo(s) bancario(s) de Bono 14 cargado(s).`,"success")},Pc=D=>{D.preventDefault(),_o(Array.from(D.dataTransfer.files))},Hc=D=>{var ne;(ne=D.target.files)!=null&&ne.length&&_o(Array.from(D.target.files))},Ui=D=>{ue(ie.filter((ne,we)=>we!==D)),Qt.current&&(Qt.current.value=""),Xe(),n("Archivo bancario de Bono 14 removido.","info")},Li=async()=>{if(!E){if(!Y||!q||!te){n("Debes seleccionar año, mes y tipo de cruce antes de ejecutar.","error");return}if(!(e!=null&&e.rawFile)){n("Debes cargar la nómina antes de ejecutar el cruce.","error");return}if(a.length===0||a.some(D=>!D.rawFile)){n("Debes cargar al menos una planilla del banco antes de ejecutar el cruce.","error");return}R(!0),O("Validando archivos..."),he(1);try{const D=await dv(a);if(D.length>0){const ke=D.map(it=>`Número de envío ${it.shipmentNumber}: ${it.fileNames.join(", ")}`).join(` `);throw new Error(`Hay planillas del banco repetidas. Revisa los archivos cargados antes de continuar. ${ke}`)}const ne=yk(_.code);if(!ne)throw new Error("No se pudo procesar el cruce. El servicio de conciliación no está disponible.");const we=nv();O("Revalidando sesión..."),await Rc(300),O("Reactivando conexión segura..."),await tv(ne);const ts=sv(ne,we),ns={country:_.code,country_name:_.name,year:Y,month:q,period_type:te,period_label:Zt.label,period_start:Zt.start,period_end:Zt.end,payroll_file_name:e.name,bank_file_names:a.map(ke=>ke.name),requested_by_name:y,requested_by_email:v,auth_mode:"supabase_google",source_app:"portal-cruce-cuentas-glm",client_request_id:we};O("Procesando cruce de cuentas...");const bt=new FormData;bt.append("metadata",JSON.stringify(ns)),Object.entries(ns).forEach(([ke,it])=>{bt.append(ke,Array.isArray(it)?JSON.stringify(it):String(it))}),bt.append("payroll_file",e.rawFile,e.name),a.forEach((ke,it)=>{ke.rawFile&&(bt.append("bank_files",ke.rawFile,ke.name),bt.append(`bank_file_${it+1}`,ke.rawFile,ke.name))});const en=await fetch(ts,{method:"POST",body:bt,cache:"no-store",credentials:"omit"});O("Generando reporte...");const ht=(en.headers.get("content-type")??"").includes("application/json")?await en.json():{ok:en.ok,message:await en.text()};if(!en.ok||(ht==null?void 0:ht.ok)===!1)throw new Error(typeof(ht==null?void 0:ht.message)=="string"?ht.message:"No se pudo procesar el cruce. Verifica los archivos e intenta nuevamente.");const Pn=ov(ht);Pn.reportKind="nomina",m(Pn),u(!0),n(Pn.message||"Cruce procesado correctamente.","success"),setTimeout(()=>{const ke=document.getElementById("resultados-seccion");ke&&ke.scrollIntoView({behavior:"smooth",block:"start"})},150)}catch(D){const ne=cv(D);u(!1),m(null),n(ne,"error")}finally{R(!1),O("")}}},zi=async()=>{if(!E){if(!ee){n("El cruce de Bono 14 solo está disponible en Guatemala para julio · Quincena 15.","error");return}if(!(G!=null&&G.rawFile)){n("Debes cargar el Excel de Bono 14 antes de generar el reporte.","error");return}if(ie.length===0||ie.some(D=>!D.rawFile)){n("Debes cargar al menos un CSV bancario del Bono 14.","error");return}R(!0),O("Validando archivos de Bono 14..."),he(1);try{const D=await dv(ie);if(D.length>0){const ke=D.map(it=>`Número de envío ${it.shipmentNumber}: ${it.fileNames.join(", ")}`).join(` `);throw new Error(`Hay planillas del banco repetidas. Revisa los archivos cargados antes de continuar. ${ke}`)}const ne=bk(),we=nv();O("Revalidando sesión..."),await Rc(300),O("Reactivando conexión segura..."),await tv(ne);const ts=sv(ne,we),ns={country:"GT",country_name:"Guatemala",year:Y,month:7,period_type:"bono14",report_kind:"bono14",period_label:Ce.label,period_start:Ce.start,period_end:Ce.end,payroll_file_name:G.name,bank_file_names:ie.map(ke=>ke.name),requested_by_name:y,requested_by_email:v,auth_mode:"supabase_google",source_app:"portal-cruce-cuentas-glm-bono14",client_request_id:we},bt=new FormData;bt.append("metadata",JSON.stringify(ns)),Object.entries(ns).forEach(([ke,it])=>{bt.append(ke,Array.isArray(it)?JSON.stringify(it):String(it))}),bt.append("payroll_file",G.rawFile,G.name),ie.forEach((ke,it)=>{ke.rawFile&&(bt.append("bank_files",ke.rawFile,ke.name),bt.append(`bank_file_${it+1}`,ke.rawFile,ke.name))}),O("Procesando Bono 14...");const en=await fetch(ts,{method:"POST",body:bt,cache:"no-store",credentials:"omit"});O("Generando reporte independiente de Bono 14...");const ht=(en.headers.get("content-type")??"").includes("application/json")?await en.json():{ok:en.ok,message:await en.text()};if(!en.ok||(ht==null?void 0:ht.ok)===!1)throw new Error(typeof(ht==null?void 0:ht.message)=="string"?ht.message:"No se pudo procesar el Bono 14. Verifica los archivos e intenta nuevamente.");const Pn=ov(ht);Pn.reportKind="bono14",m(Pn),u(!0),n(Pn.message||"Bono 14 procesado correctamente.","success"),setTimeout(()=>{const ke=document.getElementById("resultados-seccion");ke&&ke.scrollIntoView({behavior:"smooth",block:"start"})},150)}catch(D){u(!1),m(null),n(cv(D),"error")}finally{R(!1),O("")}}},es=()=>{if(d!=null&&d.reportUrl){window.open(d.reportUrl,"_blank","noopener,noreferrer");return}n("El reporte aún no tiene un enlace disponible.","info")};return g.jsxs("div",{className:"flex-1 flex flex-col min-h-screen bg-neutral-50 text-neutral-800 font-sans",children:[g.jsxs("header",{className:"bg-white border-b-4 border-[#6CC24A] flex justify-between items-center w-full px-4 sm:px-8 h-[84px] sticky top-0 z-40 shadow-sm gap-x-4",children:[g.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0",children:[g.jsx("button",{onClick:p,className:"md:hidden p-2 -ml-2 text-neutral-600 hover:text-neutral-800 hover:bg-neutral-100 transition-colors flex-shrink-0","aria-label":"Abrir menú",children:g.jsx(lw,{className:"w-6 h-6"})}),g.jsx("h1",{className:"text-xs sm:text-sm md:text-lg lg:text-2xl font-black text-[#4F758B] tracking-tight uppercase flex items-center gap-1.5 sm:gap-2 min-w-0",children:g.jsxs("span",{className:"truncate",children:["Cruce de Cuentas GLM - ",_.name]})})]}),g.jsx("div",{className:"flex-shrink-0 flex items-center","aria-label":`Bandera de ${_.name}`,children:g.jsx("div",{className:"border border-neutral-200 bg-white px-2.5 py-2 shadow-sm",children:g.jsx("img",{src:_.flag,alt:`Bandera de ${_.name}`,className:"h-5 sm:h-6 w-auto object-contain"})})})]}),g.jsxs("main",{className:"flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 py-8 flex flex-col gap-8",children:[g.jsxs("section",{className:"bg-white border border-[#D0D0D0] p-5 shadow-sm",children:[g.jsx("div",{className:"flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-5",children:g.jsxs("div",{className:"flex items-center gap-3",children:[g.jsx("div",{className:"bg-[#4F758B]/10 p-2 rounded-full",children:g.jsx(ow,{className:"w-5 h-5 text-[#4F758B]"})}),g.jsx("div",{className:"pt-0.5",children:g.jsx("h2",{className:"text-sm font-black text-[#4F758B] uppercase tracking-wider leading-none",children:"Datos del cruce"})})]})}),g.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[g.jsxs("label",{className:"flex flex-col gap-1.5",children:[g.jsx("span",{className:"text-[10px] font-black uppercase tracking-wider text-neutral-500",children:"Año"}),g.jsx("select",{value:Y,onChange:D=>{X(Number(D.target.value)),Xe()},className:"border border-[#D0D0D0] bg-white px-3 py-2.5 text-sm font-bold text-neutral-700 focus:outline-none focus:border-[#4F758B]",children:ii.map(D=>g.jsx("option",{value:D,children:D},D))})]}),g.jsxs("label",{className:"flex flex-col gap-1.5",children:[g.jsx("span",{className:"text-[10px] font-black uppercase tracking-wider text-neutral-500",children:"Mes"}),g.jsx("select",{value:q,onChange:D=>{Z(Number(D.target.value)),Xe()},className:"border border-[#D0D0D0] bg-white px-3 py-2.5 text-sm font-bold text-neutral-700 focus:outline-none focus:border-[#4F758B]",children:Mw.map(D=>g.jsx("option",{value:D.value,children:D.label},D.value))})]}),g.jsxs("label",{className:"flex flex-col gap-1.5",children:[g.jsx("span",{className:"text-[10px] font-black uppercase tracking-wider text-neutral-500",children:"Tipo de cruce"}),g.jsx("select",{value:te,onChange:D=>{Q(D.target.value),Xe()},className:"border border-[#D0D0D0] bg-white px-3 py-2.5 text-sm font-bold text-neutral-700 focus:outline-none focus:border-[#4F758B]",children:iv.map(D=>g.jsx("option",{value:D.value,children:D.label},D.value))})]})]}),g.jsxs("div",{className:"mt-4 grid grid-cols-1 md:grid-cols-[1fr_auto] gap-3 items-center bg-[#4F758B]/5 border border-[#4F758B]/10 px-4 py-3",children:[g.jsxs("div",{className:"flex items-start gap-2 text-xs text-neutral-600",children:[g.jsx(mj,{className:"w-4 h-4 text-[#4F758B] mt-0.5 flex-shrink-0"}),g.jsxs("div",{children:[g.jsx("span",{className:"font-black text-[#4F758B]",children:"Período calculado:"})," ",Zt.start," al ",Zt.end,g.jsx("p",{className:"text-[10px] text-neutral-500 mt-0.5",children:Di})]})]}),g.jsx("div",{className:"text-[10px] font-bold text-neutral-500 uppercase tracking-wider",children:Zt.label})]})]}),g.jsxs("section",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[g.jsxs("div",{className:"bg-white border border-[#D0D0D0] p-6 flex flex-col justify-between relative shadow-sm hover:shadow-md transition-shadow",children:[g.jsx("div",{className:"absolute top-0 left-0 w-full h-1 bg-[#4F758B]"}),g.jsxs("div",{children:[g.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[g.jsx(Hr,{className:"w-5 h-5 text-[#4F758B]"}),g.jsx("h2",{className:"text-sm font-black text-neutral-800 uppercase tracking-wider",children:"1. Carga de Nómina"})]}),g.jsx("input",{type:"file",ref:Ye,onChange:Bi,accept:".xlsx,.xls",className:"hidden"}),e?g.jsxs("div",{className:"border border-[#6CC24A]/30 bg-[#6CC24A]/5 p-5 flex items-center justify-between gap-3",children:[g.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[g.jsx(Hr,{className:"w-8 h-8 text-[#6CC24A] flex-shrink-0"}),g.jsxs("div",{className:"overflow-hidden",children:[g.jsx("p",{className:"text-xs font-bold text-neutral-700 truncate max-w-[300px]",title:e.name,children:e.name}),g.jsxs("p",{className:"text-[10px] text-neutral-400 font-mono mt-0.5",children:[e.size," • Excel"]})]})]}),g.jsx("button",{onClick:()=>{i(null),Ye.current&&(Ye.current.value=""),Xe(),n("Nómina removida.","info")},className:"p-1.5 text-neutral-400 hover:text-red-500 hover:bg-neutral-100 transition-all rounded","aria-label":"Remover nómina",children:g.jsx(ql,{className:"w-4.5 h-4.5"})})]}):g.jsxs("div",{onDragOver:Wt,onDrop:An,onClick:()=>{var D;return(D=Ye.current)==null?void 0:D.click()},className:"border-2 border-dashed border-[#D0D0D0] bg-neutral-50 hover:bg-[#4F758B]/5 hover:border-[#4F758B]/40 transition-colors flex flex-col items-center justify-center py-10 px-4 text-center cursor-pointer min-h-[190px]",children:[g.jsx($l,{className:"w-8 h-8 text-neutral-300 mb-2"}),g.jsx("p",{className:"text-xs font-bold text-neutral-700",children:"Arrastre y suelte archivo Excel"}),g.jsx("p",{className:"text-[10px] text-neutral-400 mt-1 font-medium",children:"Formato .xlsx, .xls"}),g.jsx("button",{type:"button",className:"mt-4 border border-[#D0D0D0] bg-white px-4 py-1.5 text-[10px] font-bold text-neutral-600 hover:border-[#4F758B] hover:text-[#4F758B] transition-colors shadow-sm uppercase tracking-wide",children:"Seleccionar Archivo"})]})]})]}),g.jsxs("div",{className:"bg-white border border-[#D0D0D0] p-6 flex flex-col justify-between relative shadow-sm hover:shadow-md transition-shadow",children:[g.jsx("div",{className:"absolute top-0 left-0 w-full h-1 bg-[#4F758B]"}),g.jsxs("div",{children:[g.jsxs("div",{className:"flex items-center gap-2.5 mb-2",children:[g.jsx(Hl,{className:"w-5 h-5 text-[#4F758B]"}),g.jsx("h2",{className:"text-sm font-black text-neutral-800 uppercase tracking-wider",children:"2. Carga de Planillas del Banco"})]}),g.jsx("p",{className:"text-[11px] text-neutral-500 mb-4 leading-relaxed",children:"Puede subir múltiples archivos separados o un archivo consolidado del período."}),g.jsx("input",{type:"file",ref:Le,onChange:Ga,accept:".csv",multiple:!0,className:"hidden"}),g.jsxs("div",{onDragOver:Wt,onDrop:Mi,onClick:()=>{var D;return(D=Le.current)==null?void 0:D.click()},className:"border-2 border-dashed border-[#D0D0D0] bg-neutral-50 hover:bg-[#4F758B]/5 hover:border-[#4F758B]/40 transition-colors flex flex-col items-center justify-center py-8 px-4 text-center cursor-pointer min-h-[130px]",children:[g.jsx($l,{className:"w-7 h-7 text-neutral-300 mb-2"}),g.jsx("p",{className:"text-xs font-bold text-neutral-700",children:"Arrastre y suelte archivo CSV"}),g.jsx("p",{className:"text-[10px] text-neutral-400 mt-1 font-medium",children:"Formato .csv"}),g.jsx("button",{type:"button",className:"mt-4 border border-[#D0D0D0] bg-white px-4 py-1.5 text-[10px] font-bold text-neutral-600 hover:border-[#4F758B] hover:text-[#4F758B] transition-colors shadow-sm uppercase tracking-wide",children:"Seleccionar Archivos"})]}),a.length>0&&g.jsxs("div",{className:"mt-4 border border-neutral-200 bg-white",children:[g.jsxs("div",{className:"p-3 border-b border-neutral-200 bg-neutral-50",children:[g.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-2",children:[g.jsxs("div",{children:[g.jsxs("p",{className:"text-[11px] font-black text-neutral-700 uppercase tracking-wide",children:[a.length," ",a.length===1?"archivo cargado":"archivos cargados"]}),g.jsx("p",{className:"text-[9px] text-neutral-400 mt-0.5",children:"Busque por nombre para localizar y eliminar una planilla rápidamente."})]}),xe&&g.jsx("button",{type:"button",onClick:D=>{D.stopPropagation(),z("")},className:"self-start sm:self-auto text-[9px] font-bold uppercase tracking-wide text-[#4F758B] hover:underline",children:"Limpiar búsqueda"})]}),g.jsxs("div",{className:"relative",children:[g.jsx(qr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-neutral-400 pointer-events-none"}),g.jsx("input",{type:"search",value:xe,onChange:D=>z(D.target.value),onClick:D=>D.stopPropagation(),placeholder:"Buscar archivo CSV por nombre...",className:"w-full h-9 pl-9 pr-3 border border-[#D0D0D0] bg-white text-[11px] text-neutral-700 outline-none focus:border-[#4F758B] focus:ring-2 focus:ring-[#4F758B]/10 transition-all","aria-label":"Buscar archivos CSV cargados"})]}),xe&&g.jsxs("p",{className:"text-[9px] text-neutral-400 mt-2",children:["Mostrando ",Ht.length," de ",a.length," archivos."]})]}),g.jsx("div",{className:"max-h-[330px] overflow-y-auto overscroll-contain p-2 space-y-2",children:Ht.length>0?Ht.map(({file:D,originalIndex:ne})=>g.jsxs("div",{className:"border border-neutral-200 bg-white px-3 py-3 flex items-center justify-between gap-3 hover:border-[#4F758B]/40 hover:bg-[#4F758B]/[0.025] transition-colors",children:[g.jsxs("div",{className:"flex items-start gap-3 min-w-0 flex-1",children:[g.jsx("div",{className:"w-7 h-7 mt-0.5 border border-[#4F758B]/20 bg-[#4F758B]/5 flex items-center justify-center flex-shrink-0",children:g.jsx(Hl,{className:"w-4 h-4 text-[#4F758B]"})}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("p",{className:"text-[11px] leading-4 font-bold text-neutral-700 whitespace-normal break-words",title:D.name,children:D.name}),g.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[g.jsx("span",{className:"text-[9px] text-neutral-400 font-mono",children:D.size}),g.jsx("span",{className:"text-[8px] font-bold uppercase tracking-wide text-[#4F758B] bg-[#4F758B]/5 border border-[#4F758B]/10 px-1.5 py-0.5",children:"CSV"})]})]})]}),g.jsx("button",{type:"button",onClick:we=>{we.stopPropagation(),ai(ne)},className:"w-8 h-8 flex items-center justify-center flex-shrink-0 text-neutral-400 hover:text-red-600 hover:bg-red-50 border border-transparent hover:border-red-100 rounded transition-colors","aria-label":`Remover ${D.name}`,title:`Eliminar ${D.name}`,children:g.jsx(ql,{className:"w-4 h-4"})})]},`${D.name}-${ne}`)):g.jsxs("div",{className:"py-8 px-4 text-center",children:[g.jsx(qr,{className:"w-5 h-5 text-neutral-300 mx-auto mb-2"}),g.jsx("p",{className:"text-[11px] font-bold text-neutral-600",children:"No encontramos archivos con ese nombre."}),g.jsx("p",{className:"text-[9px] text-neutral-400 mt-1",children:"Pruebe con otra parte del nombre del CSV."})]})})]})]})]})]}),ee&&g.jsx("section",{className:"bg-white border border-[#D0D0D0] shadow-sm",children:g.jsxs("div",{className:"border-t-4 border-[#6CC24A] p-5 sm:p-6",children:[g.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4 mb-5",children:[g.jsxs("div",{className:"flex items-start gap-3",children:[g.jsx("div",{className:"bg-[#6CC24A]/10 p-2 rounded-full",children:g.jsx(vb,{className:"w-5 h-5 text-[#4F758B]"})}),g.jsxs("div",{children:[g.jsx("h2",{className:"text-sm font-black text-[#4F758B] uppercase tracking-wider",children:"Bono 14 · Reporte independiente"}),g.jsx("p",{className:"text-[11px] text-neutral-500 mt-1 max-w-3xl leading-relaxed",children:"Esta sección aparece únicamente para Guatemala · Julio · Quincena 15. El Bono 14 se procesa separado de la nómina quincenal y genera su propio Google Sheet e histórico."})]})]}),g.jsxs("div",{className:"text-left lg:text-right",children:[g.jsx("p",{className:"text-[9px] font-black uppercase tracking-wider text-neutral-400",children:"Período del Bono 14"}),g.jsxs("p",{className:"text-[11px] font-bold text-[#4F758B] mt-1",children:[Ce.start," al ",Ce.end]})]})]}),g.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-5",children:[g.jsxs("div",{className:"border border-neutral-200 p-4 bg-neutral-50/50",children:[g.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[g.jsx(Hr,{className:"w-4.5 h-4.5 text-[#4F758B]"}),g.jsx("h3",{className:"text-xs font-black uppercase tracking-wider text-neutral-700",children:"1. Excel de Bono 14"})]}),g.jsx("p",{className:"text-[10px] text-neutral-500 mb-3",children:"Archivo anual con los montos calculados de Bono 14."}),g.jsx("input",{type:"file",ref:Pt,onChange:Ut,accept:".xlsx,.xls",className:"hidden"}),G?g.jsxs("div",{className:"border border-neutral-200 bg-white px-3 py-3 flex items-center justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("p",{className:"text-[11px] font-bold text-neutral-700 break-words",title:G.name,children:G.name}),g.jsxs("p",{className:"text-[9px] text-neutral-400 font-mono mt-1",children:[G.size," · Excel"]})]}),g.jsx("button",{type:"button",onClick:()=>{K(null),Pt.current&&(Pt.current.value=""),Xe(),n("Excel de Bono 14 removido.","info")},className:"w-8 h-8 flex items-center justify-center text-neutral-400 hover:text-red-600 hover:bg-red-50 border border-transparent hover:border-red-100 rounded transition-colors","aria-label":"Remover Excel de Bono 14",children:g.jsx(ql,{className:"w-4 h-4"})})]}):g.jsxs("div",{onDragOver:Wt,onDrop:Vn,onClick:()=>{var D;return(D=Pt.current)==null?void 0:D.click()},className:"border-2 border-dashed border-[#D0D0D0] bg-white hover:bg-[#4F758B]/5 hover:border-[#4F758B]/40 transition-colors py-8 px-4 text-center cursor-pointer",children:[g.jsx($l,{className:"w-7 h-7 text-neutral-300 mx-auto mb-2"}),g.jsx("p",{className:"text-xs font-bold text-neutral-700",children:"Arrastre el Excel de Bono 14"}),g.jsx("p",{className:"text-[10px] text-neutral-400 mt-1",children:"Formato .xlsx, .xls"}),g.jsx("button",{type:"button",className:"mt-4 border border-[#D0D0D0] bg-white px-4 py-1.5 text-[10px] font-bold text-neutral-600 hover:border-[#4F758B] hover:text-[#4F758B] transition-colors shadow-sm uppercase tracking-wide",children:"Seleccionar Archivo"})]})]}),g.jsxs("div",{className:"border border-neutral-200 p-4 bg-neutral-50/50",children:[g.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[g.jsx(Hl,{className:"w-4.5 h-4.5 text-[#4F758B]"}),g.jsx("h3",{className:"text-xs font-black uppercase tracking-wider text-neutral-700",children:"2. CSV bancarios del Bono 14"})]}),g.jsx("p",{className:"text-[10px] text-neutral-500 mb-3",children:"Puede cargar todos los envíos bancarios correspondientes al Bono 14."}),g.jsx("input",{type:"file",ref:Qt,onChange:Hc,accept:".csv",multiple:!0,className:"hidden"}),g.jsxs("div",{onDragOver:Wt,onDrop:Pc,onClick:()=>{var D;return(D=Qt.current)==null?void 0:D.click()},className:"border-2 border-dashed border-[#D0D0D0] bg-white hover:bg-[#4F758B]/5 hover:border-[#4F758B]/40 transition-colors py-6 px-4 text-center cursor-pointer",children:[g.jsx($l,{className:"w-6 h-6 text-neutral-300 mx-auto mb-2"}),g.jsx("p",{className:"text-xs font-bold text-neutral-700",children:"Arrastre uno o varios CSV"}),g.jsx("p",{className:"text-[10px] text-neutral-400 mt-1",children:"Formato .csv"}),g.jsx("button",{type:"button",className:"mt-4 border border-[#D0D0D0] bg-white px-4 py-1.5 text-[10px] font-bold text-neutral-600 hover:border-[#4F758B] hover:text-[#4F758B] transition-colors shadow-sm uppercase tracking-wide",children:"Seleccionar Archivos"})]}),ie.length>0&&g.jsxs("div",{className:"mt-3 border border-neutral-200 bg-white",children:[g.jsxs("div",{className:"p-3 border-b border-neutral-200 bg-neutral-50",children:[g.jsxs("div",{className:"relative",children:[g.jsx(qr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-neutral-400 pointer-events-none"}),g.jsx("input",{type:"search",value:A,onChange:D=>H(D.target.value),onClick:D=>D.stopPropagation(),placeholder:"Buscar CSV de Bono 14...",className:"w-full h-9 pl-9 pr-3 border border-[#D0D0D0] bg-white text-[11px] text-neutral-700 outline-none focus:border-[#4F758B]"})]}),g.jsxs("p",{className:"text-[9px] text-neutral-400 mt-2",children:[ie.length," archivo(s) cargado(s)."]})]}),g.jsx("div",{className:"max-h-[250px] overflow-y-auto p-2 space-y-2",children:qt.map(({file:D,originalIndex:ne})=>g.jsxs("div",{className:"border border-neutral-200 px-3 py-2.5 flex items-start justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("p",{className:"text-[10px] leading-4 font-bold text-neutral-700 break-words",children:D.name}),g.jsx("p",{className:"text-[9px] text-neutral-400 font-mono mt-0.5",children:D.size})]}),g.jsx("button",{type:"button",onClick:we=>{we.stopPropagation(),Ui(ne)},className:"w-8 h-8 flex items-center justify-center flex-shrink-0 text-neutral-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors","aria-label":`Remover ${D.name}`,children:g.jsx(ql,{className:"w-4 h-4"})})]},`bonus14-${D.name}-${ne}`))})]})]})]}),g.jsxs("div",{className:"mt-5 flex flex-col items-center gap-2",children:[g.jsxs("button",{type:"button",onClick:zi,disabled:E||!(G!=null&&G.rawFile)||ie.length===0,className:"inline-flex items-center justify-center gap-2 bg-[#4F758B] hover:bg-[#3d6378] text-white px-7 py-3 text-xs font-black uppercase tracking-wider transition-colors disabled:opacity-45 disabled:cursor-not-allowed min-w-[280px]",children:[E?g.jsx(Jr,{className:"w-4 h-4 animate-spin"}):g.jsx(vb,{className:"w-4 h-4"}),"Generar reporte Bono 14"]}),g.jsxs("p",{className:"text-[9px] text-neutral-400 text-center",children:["Se guardará como un reporte separado: GT · ",Y," · Bono 14."]})]})]})}),g.jsx("section",{className:"flex flex-col items-center gap-3",children:g.jsx("button",{onClick:Li,disabled:E,className:"w-full sm:w-auto min-w-[280px] bg-[#4F758B] hover:bg-[#41677b] disabled:bg-neutral-300 disabled:cursor-not-allowed text-white px-8 py-4 font-black text-sm uppercase tracking-wider shadow-md flex items-center justify-center gap-3 transition-all duration-150 active:scale-[0.99] border-l-4 border-[#6CC24A]",children:E?g.jsxs(g.Fragment,{children:[g.jsx(Jr,{className:"w-5 h-5 animate-spin"}),g.jsx("span",{children:N||"Procesando cruce de cuentas..."})]}):g.jsxs(g.Fragment,{children:[g.jsx(Ij,{className:"w-5 h-5"}),g.jsx("span",{children:"Ejecutar Cruce de Cuentas"})]})})}),g.jsx(Qs,{children:c&&d&&g.jsxs(cn.section,{id:"resultados-seccion",initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:10},className:"flex flex-col gap-5 scroll-mt-28",children:[g.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4",children:[g.jsxs("div",{className:"bg-white border border-emerald-200 p-4 shadow-sm",children:[g.jsxs("div",{className:"flex items-center gap-2 text-emerald-700",children:[g.jsx(xc,{className:"w-5 h-5"}),g.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:"Coincidencias"})]}),g.jsx("p",{className:"text-3xl font-black text-emerald-800 mt-2",children:d.summary.matches})]}),g.jsxs("div",{className:"bg-white border border-red-200 p-4 shadow-sm",children:[g.jsxs("div",{className:"flex items-center gap-2 text-[#ba1a1a]",children:[g.jsx(ao,{className:"w-5 h-5"}),g.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:"Discrepancias"})]}),g.jsx("p",{className:"text-3xl font-black text-[#ba1a1a] mt-2",children:d.summary.discrepancies})]}),g.jsxs("div",{className:"bg-white border border-amber-200 p-4 shadow-sm",children:[g.jsxs("div",{className:"flex items-center gap-2 text-amber-800",children:[g.jsx(bb,{className:"w-5 h-5"}),g.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:_e?"Banco sin Bono 14":"Banco sin nómina"})]}),g.jsx("p",{className:"text-3xl font-black text-amber-800 mt-2",children:d.summary.bankWithoutPayroll})]}),g.jsxs("div",{className:"bg-white border border-orange-200 p-4 shadow-sm",children:[g.jsxs("div",{className:"flex items-center gap-2 text-orange-800",children:[g.jsx(bb,{className:"w-5 h-5"}),g.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:"Banco sin Bamboo"})]}),g.jsx("p",{className:"text-3xl font-black text-orange-800 mt-2",children:d.summary.bankWithoutBamboo})]}),g.jsxs("div",{className:"bg-white border border-violet-200 p-4 shadow-sm",children:[g.jsxs("div",{className:"flex items-center gap-2 text-violet-800",children:[g.jsx(Hl,{className:"w-5 h-5"}),g.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:"Diferencias nombre banco"})]}),g.jsx("p",{className:"text-3xl font-black text-violet-800 mt-2",children:d.summary.nameDifferences})]}),g.jsxs("div",{className:"bg-white border border-blue-200 p-4 shadow-sm",children:[g.jsxs("div",{className:"flex items-center gap-2 text-blue-800",children:[g.jsx(Hr,{className:"w-5 h-5"}),g.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:_e?"Bono 14 sin cuenta":"Nómina sin cuenta"})]}),g.jsx("p",{className:"text-3xl font-black text-blue-800 mt-2",children:d.summary.payrollWithoutAccount})]})]}),g.jsxs("div",{className:"bg-white border border-[#D0D0D0] shadow-sm overflow-hidden",children:[g.jsxs("div",{className:"p-5 border-b border-neutral-200 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4",children:[g.jsxs("div",{children:[g.jsx("h2",{className:"text-lg font-black text-[#4F758B] uppercase tracking-tight",children:_e?"Resultados del Bono 14":"Resultados del Cruce"}),g.jsx("p",{className:"text-[11px] text-neutral-500 mt-1",children:Me})]}),g.jsx("div",{className:"flex flex-col sm:flex-row gap-2",children:g.jsxs("button",{onClick:es,disabled:!d.reportUrl,className:"inline-flex items-center justify-center gap-2 border border-[#4F758B] text-[#4F758B] hover:bg-[#4F758B] hover:text-white px-4 py-2 text-xs font-bold transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[g.jsx(Aj,{className:"w-4 h-4"}),"Abrir Google Sheet"]})})]}),g.jsxs("div",{className:"p-4 border-b border-neutral-200 bg-neutral-50 flex flex-col lg:flex-row gap-3 lg:items-center lg:justify-between",children:[g.jsxs("div",{className:"relative w-full lg:max-w-sm",children:[g.jsx(qr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-neutral-400"}),g.jsx("input",{type:"text",value:Ge,onChange:D=>{Ne(D.target.value),he(1)},placeholder:"Buscar empleado, Employee Number o cuenta...",className:"w-full pl-9 pr-3 py-2 border border-[#D0D0D0] text-xs font-medium focus:outline-none focus:border-[#4F758B]"})]}),g.jsx("div",{className:"flex flex-wrap gap-2",children:[["todos","Todos"],["discrepancias","Discrepancias"],["coincidencias","Coincidencias"],["banco_sin_nomina",_e?"Banco sin Bono 14":"Banco sin nómina"],["banco_sin_bamboo","Banco sin Bamboo"],["diferencia_nombre_banco","Diferencias nombre banco"],["nomina_sin_cuenta",_e?"Bono 14 sin cuenta":"Nómina sin cuenta"]].map(([D,ne])=>g.jsx("button",{onClick:()=>{P(D),he(1)},className:`px-3 py-1.5 text-[10px] uppercase tracking-wider font-black border transition-colors ${C===D?"bg-[#4F758B] text-white border-[#4F758B]":"bg-white text-neutral-500 border-neutral-300 hover:border-[#4F758B] hover:text-[#4F758B]"}`,children:ne},D))})]}),g.jsx("div",{className:"overflow-x-auto",children:g.jsxs("table",{className:"w-full text-left border-collapse min-w-[960px] xl:min-w-full",children:[g.jsx("thead",{children:g.jsxs("tr",{className:"bg-[#4F758B] text-white text-xs font-bold uppercase tracking-wider",children:[g.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Empleado"}),g.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Employee Number"}),g.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Cuenta"}),g.jsx("th",{className:"py-3 px-3 xl:px-4 text-right",children:_e?"Monto Bono 14":"Monto Nómina"}),g.jsx("th",{className:"py-3 px-3 xl:px-4 text-right",children:"Monto Banco"}),g.jsx("th",{className:"py-3 px-3 xl:px-4 text-right",children:"Diferencia"}),g.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Estado"}),g.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Categoría"}),g.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Observación"}),g.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Acciones"})]})}),g.jsx("tbody",{className:"divide-y divide-neutral-200 text-xs",children:ut.length>0?ut.map(D=>g.jsxs("tr",{className:"hover:bg-neutral-50 transition-colors",children:[g.jsx("td",{className:"py-3 px-3 xl:px-4 font-bold text-neutral-800",children:D.employee}),g.jsx("td",{className:"py-3 px-3 xl:px-4 font-mono text-neutral-600",children:D.employeeNumber||"—"}),g.jsx("td",{className:"py-3 px-3 xl:px-4 font-mono text-neutral-500",children:D.account??"—"}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-right font-mono text-neutral-700",children:Rd(D.amountPayroll,_,D.currency)}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-right font-mono text-neutral-700",children:Rd(D.amountBank,_,D.currency)}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-right font-mono text-neutral-700",children:Rd(D.difference,_,D.currency)}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:g.jsx("span",{className:`inline-block px-2.5 py-1 text-[9px] font-black uppercase tracking-wider border ${Sk(D.status)}`,children:D.status})}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-neutral-600 max-w-[180px] capitalize",children:Ak(D.category??D.source,(d==null?void 0:d.reportKind)??"nomina")}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-neutral-600 max-w-[300px]",children:D.observation}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:Oa(D,"banco_sin_bamboo")?fe.has(D.id)?g.jsx("span",{className:"inline-flex items-center px-2.5 py-1 border border-emerald-200 bg-emerald-50 text-emerald-800 text-[9px] font-black uppercase tracking-wider",children:"Reportado a RRHH"}):g.jsx("button",{type:"button",onClick:()=>W(D),className:"inline-flex items-center justify-center px-3 py-2 border border-[#4F758B] text-[#4F758B] hover:bg-[#4F758B] hover:text-white text-[9px] font-black uppercase tracking-wider transition-colors whitespace-nowrap",children:"Reportar a RRHH"}):g.jsx("span",{className:"text-neutral-300",children:"—"})})]},D.id)):g.jsx("tr",{children:g.jsx("td",{colSpan:10,className:"py-12 text-center text-neutral-400 font-medium",children:"No hay resultados para el filtro seleccionado."})})})]})}),g.jsxs("div",{className:"p-4 border-t border-neutral-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 text-xs text-neutral-500",children:[g.jsxs("span",{children:["Mostrando ",ut.length," de ",ct.length," resultado(s)."]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("button",{onClick:()=>he(D=>Math.max(1,D-1)),disabled:le===1,className:"px-3 py-1.5 border border-neutral-300 bg-white disabled:opacity-40 disabled:cursor-not-allowed hover:border-[#4F758B] font-bold",children:"Anterior"}),g.jsxs("span",{className:"font-bold text-neutral-700",children:["Página ",le," de ",Bt]}),g.jsx("button",{onClick:()=>he(D=>Math.min(Bt,D+1)),disabled:le===Bt,className:"px-3 py-1.5 border border-neutral-300 bg-white disabled:opacity-40 disabled:cursor-not-allowed hover:border-[#4F758B] font-bold",children:"Siguiente"})]})]})]})]})})]}),J&&d&&g.jsx(Dw,{row:J,country:_,periodRange:_e?Ce:Zt,operatorName:y,operatorEmail:v,executionId:d.executionId,reportUrl:d.reportUrl,onClose:()=>W(null),onSuccess:D=>ge(ne=>{const we=new Set(ne);return we.add(D),we}),onShowToast:n})]})}const ec=10;function Bk(n){return n==="TT"?"https://agenteit.digitalcompass.agency/webhook/cruce-cuentas-tt-historicos":"https://agenteit.digitalcompass.agency/webhook/cruce-cuentas-gt-historicos"}function Uk(n){return n==="TT"?"https://agenteit.digitalcompass.agency/webhook/cruce-cuentas-tt-marcar-resuelto":"https://agenteit.digitalcompass.agency/webhook/cruce-cuentas-gt-marcar-resuelto"}function Mn(n){const e=Number(n);return Number.isFinite(e)?e:0}function Lk(n,e){if(!n)return"";const i=new Date(String(n));return Number.isNaN(i.getTime())?String(n).slice(0,10):i.toLocaleDateString(e,{year:"numeric",month:"2-digit",day:"2-digit"})}function pf(n,e){if(!n)return"";const i=new Date(String(n));return Number.isNaN(i.getTime())?String(n):i.toLocaleString(e,{dateStyle:"short",timeStyle:"short"})}function zk(n){return String(n??"").toLowerCase().includes("resuelto")?"Resuelto":"Pendiente revisión"}function mv(n,e){const i=n,a=!Array.isArray(i)&&i?i:{};return(Array.isArray(i)?i:Array.isArray(a.reports)?a.reports:[]).map((c,u)=>{const d=c,m=Mn(d.discrepancias??d.discrepancies),p=Mn(d.bancoSinNomina??d.banco_sin_nomina??d.bankWithoutPayroll),y=Mn(d.bancoSinBamboo??d.banco_sin_bamboo??d.bankWithoutBamboo),v=Mn(d.nominaSinCuenta??d.nomina_sin_cuenta??d.payrollWithoutAccount),x=Mn(d.diferenciasNombreBanco??d.diferencias_nombre_banco??d.nameDifferences),_=m+p+y+v+x,S=String(d.country??d.pais??d.country_code??e.code).toUpperCase(),E=Array.isArray(d.archivosBanco)?d.archivosBanco.map(String):Array.isArray(d.bank_file_names)?d.bank_file_names.map(String):[],R=d.updated_at??d.fechaEjecucion??d.ejecutado_en??d.created_at;return{id:String(d.id??`reporte-${u+1}`),country:S==="TT"?"TT":"GT",date:Lk(d.fecha??d.period_end??R,e.locale),executionDate:pf(R,e.locale),period:String(d.periodo??d.period_label??d.period??"Período no especificado"),periodStart:d.period_start?String(d.period_start):void 0,periodEnd:d.period_end?String(d.period_end):void 0,payrollFile:String(d.archivoNomina??d.payroll_file_name??d.payrollFile??""),bankFiles:E,matches:Mn(d.coincidencias??d.matches),discrepancies:m,bankWithoutPayroll:p,bankWithoutBamboo:y,payrollWithoutAccount:v,nameDifferences:x,totalPending:_,totalPayroll:Mn(d.totalNomina??d.total_nomina),totalBank:Mn(d.totalBanco??d.total_banco),totalDifference:Mn(d.diferenciaTotal??d.diferencia_total),status:zk(d.estado??d.status??d.estadoLabel),reportUrl:d.reportUrl||d.report_url?String(d.reportUrl??d.report_url):void 0,spreadsheetId:d.spreadsheetId||d.spreadsheet_id?String(d.spreadsheetId??d.spreadsheet_id):void 0,executedBy:d.ejecutadoPorNombre||d.ejecutado_por_nombre?String(d.ejecutadoPorNombre??d.ejecutado_por_nombre):void 0,executedByEmail:d.ejecutadoPorEmail||d.ejecutado_por_email?String(d.ejecutadoPorEmail??d.ejecutado_por_email):void 0,resolvedBy:d.resueltoPorNombre||d.resuelto_por_nombre?String(d.resueltoPorNombre??d.resuelto_por_nombre):void 0,resolvedByEmail:d.resueltoPorEmail||d.resuelto_por_email?String(d.resueltoPorEmail??d.resuelto_por_email):void 0,resolvedAt:pf(d.resueltoEn??d.resuelto_en,e.locale),resolutionComment:d.comentarioResolucion||d.comentario_resolucion?String(d.comentarioResolucion??d.comentario_resolucion):void 0,_sortTime:new Date(String(R??d.period_end??"")).getTime()||0}}).filter(c=>c.country===e.code).sort((c,u)=>u._sortTime-c._sortTime).map(({_sortTime:c,...u})=>u)}function gf(n){return String(n??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9 ]/g," ").replace(/\s+/g," ").trim()}function yf(n){return String(n??"").replace(/\.0$/g,"").replace(/\D/g,"").trim()}function pv(n,e){for(const i of e){const a=n[i];if(typeof a=="number"&&Number.isFinite(a))return a;if(typeof a=="string"&&a.trim()){const l=Number(a.replace(/[A-Za-z$Q,\s]/g,"").trim());if(Number.isFinite(l))return l}}return null}function Vk(n){return Array.isArray(n)?n.map((e,i)=>{const a=e??{},l=String(a.employee??a.employee_name??a.bank_name_file??a.bank_account_holder??"Sin nombre"),c=pv(a,["bankAmount","bank_amount","amount","monto_banco"]),u=a.best_bamboo_candidate&&typeof a.best_bamboo_candidate=="object"?a.best_bamboo_candidate:null;return{id:String(a.id??`historical-bamboo-${gf(l)}-${yf(a.account??a.bank_account)}-${i+1}`),employee:l,employeeNumber:"",account:String(a.account??a.bank_account??a.bankAccount??""),amountPayroll:0,amountBank:c,difference:c===null?null:0-c,status:"Pendiente revisión",category:"banco_sin_bamboo",source:"banco_sin_bamboo",observation:String(a.observation??a.observacion??"Pago bancario sin empleado identificado de forma confiable en BambooHR."),bankNameFile:String(a.bank_name_file??a.bankNameFile??""),bankAccountHolder:String(a.bank_account_holder??a.bankAccountHolder??""),bestBambooCandidate:u?{employeeNumber:String(u.employee_number??u.employeeNumber??""),employeeName:String(u.employee_name??u.employeeName??""),score:pv(u,["score"])}:null,ambiguousBambooMatch:!!a.ambiguous_bamboo_match}}):[]}function Pk(n){return Array.isArray(n)?n.map(e=>{const i=e??{};return{id:String(i.id??""),sourceName:String(i.nombre_origen_principal??i.source_name??""),sourceNames:Array.isArray(i.nombres_origen)?i.nombres_origen.map(String):[],bankAccount:String(i.cuenta_bancaria??i.bank_account??""),status:String(i.estado??""),emailSent:i.correo_enviado===!0}}):[]}function Hk(n,e){const i=n.status.toLowerCase();if(!(n.emailSent||i==="notificado_rrhh"||i==="corregido_bamboo"))return!1;const l=yf(n.bankAccount),c=yf(e.account);if(l&&c&&l!==c)return!1;const u=new Set([n.sourceName,...n.sourceNames].map(gf).filter(Boolean));return[e.employee,e.bankNameFile,e.bankAccountHolder].map(gf).filter(Boolean).some(m=>u.has(m))}function qk(n){return n==="Resuelto"?"bg-blue-50 text-blue-800 border-blue-200":"bg-amber-50 text-amber-800 border-amber-200"}function $k(n){return n==="Resuelto"?"RESUELTO":"PENDIENTE REVISIÓN"}function Ik({onShowToast:n,onOpenSidebar:e,operatorName:i,operatorEmail:a,country:l}){const[c,u]=M.useState(""),[d,m]=M.useState("todos"),[p,y]=M.useState([]),[v,x]=M.useState(1),[_,S]=M.useState(!1),[E,R]=M.useState(!1),[N,O]=M.useState(""),[C,P]=M.useState(null),[Y,X]=M.useState(""),[q,Z]=M.useState(null),[te,Q]=M.useState([]),[le,he]=M.useState(new Set),[Ge,Ne]=M.useState(!1),[xe,z]=M.useState(""),[G,K]=M.useState(null),[ie,ue]=M.useState(0),[A,H]=M.useState(0),J=M.useRef(0),W=M.useRef(null),fe=Math.max(1,Math.ceil(A/ec)),ge=p;M.useEffect(()=>{x(1)},[c,d,l.code]),M.useEffect(()=>{v>fe&&x(fe)},[v,fe]);const Ee=async()=>{var Me;const ee=++J.current;(Me=W.current)==null||Me.abort();const Ce=new AbortController;W.current=Ce;const _e=()=>J.current===ee&&!Ce.signal.aborted;S(!0),O("");try{if(lt){const Xe=d==="pendiente"?"pendiente_revision":d==="resuelto"?"resuelto":null,{data:dn,error:Wt}=await lt.rpc("cruce_cuentas_get_historicos",{p_country:l.code,p_page:v,p_page_size:ec,p_search:c.trim()||null,p_status:Xe});if(!_e())return;if(!Wt&&dn){const An=Array.isArray(dn)?dn[0]:dn,Mi=mv(An,l),Bi=Mn(An==null?void 0:An.total),Ga=Mn((An==null?void 0:An.filtered_total)??Bi);y(Mi),ue(Bi),H(Ga);return}}if(!_e())return;const st=Bk(l.code);if(!st)throw new Error(`No está configurado el origen histórico de ${l.name}.`);const Ht=new URL(st);Ht.searchParams.set("country",l.code);const qt=await fetch(Ht.toString(),{method:"GET",signal:Ce.signal}),ct=await qt.json().catch(()=>null);if(!_e())return;if(!qt.ok||(ct==null?void 0:ct.ok)===!1)throw new Error("No se pudieron cargar los reportes históricos.");const zn=mv(ct,l),Bt=c.trim().toLowerCase(),ut=zn.filter(Xe=>{const dn=d==="todos"||d==="pendiente"&&Xe.status==="Pendiente revisión"||d==="resuelto"&&Xe.status==="Resuelto",Wt=!Bt||Xe.period.toLowerCase().includes(Bt)||Xe.payrollFile.toLowerCase().includes(Bt)||Xe.id.toLowerCase().includes(Bt)||(Xe.resolvedBy??"").toLowerCase().includes(Bt)||(Xe.executedBy??"").toLowerCase().includes(Bt);return dn&&Wt});if(!_e())return;const Di=(v-1)*ec;y(ut.slice(Di,Di+ec)),ue(zn.length),H(ut.length)}catch(st){if(!_e()||st instanceof DOMException&&st.name==="AbortError")return;y([]),ue(0),H(0),O(st instanceof Error?st.message:"No se pudieron cargar los reportes históricos. Intenta nuevamente."),n("No se pudieron cargar los reportes históricos.","error")}finally{_e()&&(S(!1),W.current===Ce&&(W.current=null))}};M.useEffect(()=>{const ee=window.setTimeout(()=>{Ee()},c.trim()?300:0);return()=>{var Ce;window.clearTimeout(ee),J.current+=1,(Ce=W.current)==null||Ce.abort(),W.current=null}},[l.code,v,c,d]);const Ye=()=>{K(null),Z(null),Q([]),he(new Set),z("")},Le=async ee=>{if(ee.bankWithoutBamboo<=0){n("Este reporte no tiene casos de Banco sin Bamboo.","info");return}if(!lt){n("Supabase no está configurado en esta aplicación.","error");return}Z(ee),K(null),Q([]),he(new Set),z(""),Ne(!0);try{const{data:Ce,error:_e}=await lt.rpc("cruce_cuentas_get_banco_sin_bamboo_reporte",{p_report_id:ee.id,p_country:l.code});if(_e)throw _e;const Me=Array.isArray(Ce)?Ce[0]:Ce;if(!Me||Me.ok===!1)throw new Error(String((Me==null?void 0:Me.message)||"No se pudieron recuperar los casos de Banco sin Bamboo."));const st=Vk(Me.cases),Ht=Pk(Me.corrections),qt=new Set(st.filter(ct=>Ht.some(zn=>Hk(zn,ct))).map(ct=>ct.id));Q(st),he(qt),st.length===0&&z("Este reporte fue creado antes de que se guardara el detalle de Banco sin Bamboo. Los reportes nuevos conservarán los casos para revisarlos desde Históricos.")}catch(Ce){const _e=Ce instanceof Error?Ce.message:"No se pudieron recuperar los casos de Banco sin Bamboo.";z(_e),n(_e,"error")}finally{Ne(!1)}},Pt={label:(q==null?void 0:q.period)||"Período no especificado",start:(q==null?void 0:q.periodStart)||"",end:(q==null?void 0:q.periodEnd)||""},Qt=ee=>{if(ee.reportUrl){window.open(ee.reportUrl,"_blank","noopener,noreferrer");return}n("Este reporte aún no tiene un Google Sheet disponible.","info")},ii=ee=>{if(ee.status==="Resuelto"){n("Este reporte ya fue marcado como resuelto.","info");return}P(ee),X("")},Zt=async()=>{if(!C)return;const ee=Y.trim();if(ee.length<10){n("Debes escribir un comentario de resolución más descriptivo.","error");return}const Ce=Uk(l.code);if(!Ce){n(`La resolución de reportes para ${l.name} estará disponible próximamente.`,"info");return}R(!0);try{const _e=await fetch(Ce,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:C.id,comentarioResolucion:ee,resueltoPorNombre:i,resueltoPorEmail:a,country:l.code,countryName:l.name})}),Me=await _e.json().catch(()=>null);if(!_e.ok||(Me==null?void 0:Me.ok)===!1){const qt=Array.isArray(Me==null?void 0:Me.errors)?Me.errors.join(` `):(Me==null?void 0:Me.message)||"No se pudo marcar el reporte como resuelto.";throw new Error(qt)}const st=Me.report??{},Ht=pf(st.resueltoEn??new Date().toISOString(),l.locale);y(qt=>qt.map(ct=>ct.id===C.id?{...ct,status:"Resuelto",resolvedBy:String(st.resueltoPorNombre??i),resolvedByEmail:String(st.resueltoPorEmail??a),resolvedAt:Ht,resolutionComment:String(st.comentarioResolucion??ee)}:ct)),P(null),X(""),n("Reporte marcado como resuelto correctamente.","success")}catch(_e){const Me=_e instanceof Error?_e.message:"No se pudo marcar el reporte como resuelto.";n(Me,"error")}finally{R(!1)}};return g.jsxs("div",{className:"flex-1 flex flex-col min-h-screen bg-neutral-50 text-neutral-800 font-sans",children:[g.jsxs("header",{className:"bg-white border-b-4 border-[#6CC24A] flex justify-between items-center w-full px-4 sm:px-8 h-[84px] sticky top-0 z-40 shadow-sm gap-x-4",children:[g.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0",children:[g.jsx("button",{onClick:e,className:"md:hidden p-2 -ml-2 text-neutral-600 hover:text-neutral-800 hover:bg-neutral-100 transition-colors flex-shrink-0","aria-label":"Abrir menú",children:g.jsx(lw,{className:"w-6 h-6"})}),g.jsx("h1",{className:"text-xs sm:text-sm md:text-lg lg:text-2xl font-black text-[#4F758B] tracking-tight uppercase flex items-center gap-1.5 sm:gap-2 min-w-0",children:g.jsxs("span",{className:"truncate",children:["Reportes Históricos - ",l.name]})})]}),g.jsxs("div",{className:"flex items-center gap-3 flex-shrink-0",children:[g.jsx("div",{className:"hidden sm:flex items-center border border-neutral-200 bg-white px-2.5 py-2 shadow-sm","aria-label":`Bandera de ${l.name}`,children:g.jsx("img",{src:l.flag,alt:`Bandera de ${l.name}`,className:"h-5 sm:h-6 w-auto object-contain"})}),g.jsxs("button",{onClick:Ee,disabled:_,className:"hidden sm:inline-flex items-center gap-2 border border-[#4F758B]/20 text-[#4F758B] px-3 py-2 text-xs font-bold hover:border-[#4F758B]/50 disabled:opacity-50",children:[g.jsx(Yj,{className:`w-4 h-4 ${_?"animate-spin":""}`}),"Actualizar"]})]})]}),g.jsxs("main",{className:"flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 py-8 flex flex-col gap-6",children:[g.jsxs("div",{className:"bg-white border border-[#D0D0D0] p-4 flex flex-col lg:flex-row items-center justify-between gap-4 shadow-sm",children:[g.jsxs("div",{className:"relative w-full lg:max-w-md",children:[g.jsx(qr,{className:"absolute left-3.5 top-1/2 transform -translate-y-1/2 text-neutral-400 w-4 h-4"}),g.jsx("input",{type:"text",placeholder:"Buscar por período, reporte, archivo o resolutor...",value:c,onChange:ee=>u(ee.target.value),className:"w-full pl-10 pr-4 py-2 border border-[#D0D0D0] text-xs font-medium placeholder-neutral-400 focus:outline-none focus:border-[#4F758B] transition-colors"})]}),g.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3 w-full lg:w-auto",children:[g.jsx("div",{className:"flex flex-wrap gap-2",children:[["todos","Todos"],["pendiente","Pendiente revisión"],["resuelto","Resuelto"]].map(([ee,Ce])=>g.jsx("button",{onClick:()=>m(ee),className:`px-3 py-1.5 text-[10px] uppercase tracking-wider font-black border transition-colors ${d===ee?"bg-[#4F758B] text-white border-[#4F758B]":"bg-white text-neutral-500 border-neutral-300 hover:border-[#4F758B] hover:text-[#4F758B]"}`,children:Ce},ee))}),g.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold text-neutral-500",children:[g.jsx(Oj,{className:"w-4 h-4 text-neutral-400"}),g.jsxs("span",{children:["Mostrando: ",A," de ",ie," reportes"]})]})]})]}),N&&g.jsxs("div",{className:"border border-red-200 bg-red-50 text-[#ba1a1a] px-4 py-3 text-xs font-bold flex items-center gap-2",children:[g.jsx(ao,{className:"w-4 h-4"}),N]}),g.jsxs("div",{className:"bg-white border border-[#D0D0D0] shadow-sm overflow-hidden",children:[g.jsx("div",{className:"overflow-x-auto",children:g.jsxs("table",{className:"w-full text-left border-collapse min-w-[960px] xl:min-w-full",children:[g.jsx("thead",{children:g.jsxs("tr",{className:"bg-[#4F758B] text-white text-xs font-bold uppercase tracking-wider",children:[g.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Fecha"}),g.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Período"}),g.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Archivo de Nómina / Bono 14"}),g.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Coincidencias"}),g.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Banco sin Bamboo"}),g.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Pendientes"}),g.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Estado"}),g.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Resuelto por"}),g.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Acciones"})]})}),g.jsx("tbody",{className:"divide-y divide-neutral-200 text-xs",children:_?g.jsx("tr",{children:g.jsx("td",{colSpan:9,className:"py-12 text-center text-neutral-400 font-medium",children:g.jsxs("div",{className:"inline-flex items-center gap-2",children:[g.jsx(Jr,{className:"w-4 h-4 animate-spin"}),"Cargando reportes históricos..."]})})}):ge.length>0?ge.map(ee=>g.jsxs(cn.tr,{initial:{opacity:0},animate:{opacity:1},className:"hover:bg-neutral-50/70 transition-colors",children:[g.jsx("td",{className:"py-3 px-3 xl:px-4 font-medium text-neutral-700",children:g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx(gj,{className:"w-4 h-4 text-neutral-400"}),g.jsxs("div",{children:[g.jsx("span",{children:ee.date}),ee.executionDate&&g.jsx("p",{className:"text-[9px] text-neutral-400 mt-0.5",children:ee.executionDate})]})]})}),g.jsx("td",{className:"py-3 px-3 xl:px-4 font-bold text-[#4F758B]",children:ee.period}),g.jsx("td",{className:"py-3 px-3 xl:px-4 font-mono text-neutral-500 truncate max-w-[260px]",title:ee.payrollFile,children:g.jsxs("div",{className:"flex items-center gap-1.5",children:[g.jsx(Hr,{className:"w-4 h-4 text-neutral-400 flex-shrink-0"}),g.jsx("span",{className:"truncate",children:ee.payrollFile||"No especificado"})]})}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-center font-black text-emerald-800",children:ee.matches}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:ee.bankWithoutBamboo>0?g.jsxs("button",{type:"button",onClick:()=>void Le(ee),className:"inline-flex items-center gap-1.5 min-w-8 px-2.5 py-1 text-[10px] font-black border bg-orange-50 text-orange-800 border-orange-200 hover:bg-orange-100 hover:border-orange-300 transition-colors",title:"Revisar casos y reportar correcciones a RRHH",children:[g.jsx("span",{children:ee.bankWithoutBamboo}),g.jsx("span",{className:"hidden 2xl:inline",children:"Revisar"})]}):g.jsx("span",{className:"inline-block min-w-8 px-2.5 py-1 text-[10px] font-black border bg-neutral-50 text-neutral-400 border-neutral-200",children:"0"})}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:g.jsx("span",{className:`inline-block px-2.5 py-1 text-[10px] font-bold border ${ee.totalPending>0?"bg-red-50 text-[#ba1a1a] border-red-200":"bg-emerald-50 text-emerald-800 border-emerald-200"}`,children:ee.totalPending===0?"Sin pendientes":`${ee.totalPending} pendiente${ee.totalPending>1?"s":""}`})}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:g.jsx("span",{className:`inline-block px-2.5 py-1 text-[9px] uppercase font-black tracking-wider border ${qk(ee.status)}`,children:$k(ee.status)})}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-neutral-600 max-w-[220px]",children:ee.resolvedBy?g.jsxs("div",{title:ee.resolutionComment||"",children:[g.jsx("p",{className:"font-bold text-neutral-700 truncate",children:ee.resolvedBy}),g.jsx("p",{className:"text-[10px] text-neutral-400",children:ee.resolvedAt})]}):g.jsx("span",{className:"text-neutral-400",children:"Pendiente"})}),g.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:g.jsxs("div",{className:"flex justify-center gap-2",children:[g.jsxs("button",{onClick:()=>Qt(ee),className:"inline-flex items-center gap-1.5 text-[#4F758B] hover:text-[#3d6378] font-bold text-xs border border-[#4F758B]/20 hover:border-[#4F758B]/50 px-3 py-1.5 bg-white hover:bg-neutral-50 transition-colors",children:[g.jsx(Cj,{className:"w-3.5 h-3.5"}),g.jsx("span",{children:"Ver"})]}),g.jsxs("button",{onClick:()=>ii(ee),disabled:ee.status==="Resuelto",className:"inline-flex items-center gap-1.5 text-emerald-700 hover:text-emerald-800 font-bold text-xs border border-emerald-200 hover:border-emerald-400 px-3 py-1.5 bg-emerald-50 hover:bg-emerald-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[g.jsx(xc,{className:"w-3.5 h-3.5"}),g.jsx("span",{children:ee.status==="Resuelto"?"Resuelto":"Marcar resuelto"})]})]})})]},ee.id)):g.jsx("tr",{children:g.jsx("td",{colSpan:9,className:"py-12 text-center text-neutral-400 font-medium",children:"No se encontraron reportes históricos."})})})]})}),g.jsxs("div",{className:"p-4 border-t border-neutral-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 text-xs text-neutral-500",children:[g.jsxs("span",{children:["Mostrando ",ge.length," de ",A," reporte(s)."]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("button",{onClick:()=>x(ee=>Math.max(1,ee-1)),disabled:v===1,className:"px-3 py-1.5 border border-neutral-300 bg-white disabled:opacity-40 disabled:cursor-not-allowed hover:border-[#4F758B] font-bold",children:"Anterior"}),g.jsxs("span",{className:"font-bold text-neutral-700",children:["Página ",v," de ",fe]}),g.jsx("button",{onClick:()=>x(ee=>Math.min(fe,ee+1)),disabled:v===fe,className:"px-3 py-1.5 border border-neutral-300 bg-white disabled:opacity-40 disabled:cursor-not-allowed hover:border-[#4F758B] font-bold",children:"Siguiente"})]})]})]})]}),g.jsx(Qs,{children:q&&g.jsx(cn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/45 px-4 py-6",children:g.jsxs(cn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:12},className:"w-full max-w-5xl bg-white border border-[#D0D0D0] shadow-2xl max-h-[92vh] flex flex-col",children:[g.jsx("div",{className:"h-1.5 bg-[#6CC24A] flex-shrink-0"}),g.jsxs("div",{className:"border-b border-neutral-200 px-5 sm:px-6 py-4 flex items-start justify-between gap-4 flex-shrink-0",children:[g.jsxs("div",{children:[g.jsx("p",{className:"text-[10px] uppercase tracking-[0.18em] font-black text-[#6B8FA3]",children:"Histórico · Banco sin BambooHR"}),g.jsx("h2",{className:"text-lg sm:text-xl font-black text-[#4F758B] mt-1",children:q.period}),g.jsxs("p",{className:"text-xs text-neutral-500 mt-1",children:[l.name," · ",q.bankWithoutBamboo," caso",q.bankWithoutBamboo===1?"":"s"," guardado",q.bankWithoutBamboo===1?"":"s"," en este reporte"]})]}),g.jsx("button",{type:"button",onClick:Ye,className:"p-2 text-neutral-400 hover:text-neutral-700 hover:bg-neutral-100","aria-label":"Cerrar revisión de Banco sin Bamboo",children:g.jsx(ro,{className:"w-5 h-5"})})]}),g.jsxs("div",{className:"px-5 sm:px-6 py-4 overflow-y-auto",children:[g.jsxs("div",{className:"border border-[#D6E8F4] bg-[#F7FBFD] px-4 py-3 text-xs text-neutral-600 leading-relaxed mb-4",children:["Aquí puedes volver días después al reporte y enviar a RRHH únicamente los falsos positivos que ya verificaste manualmente. Los casos previamente enviados se muestran como ",g.jsx("strong",{children:"Reportado a RRHH"}),"."]}),Ge?g.jsxs("div",{className:"py-14 text-center text-neutral-500 text-sm",children:[g.jsx(Jr,{className:"w-5 h-5 animate-spin mx-auto mb-2 text-[#4F758B]"}),"Recuperando casos del reporte..."]}):xe?g.jsxs("div",{className:"border border-amber-200 bg-amber-50 text-amber-800 px-4 py-3 text-xs font-medium flex items-start gap-2",children:[g.jsx(ao,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),g.jsx("span",{children:xe})]}):te.length>0?g.jsx("div",{className:"overflow-x-auto border border-neutral-200",children:g.jsxs("table",{className:"w-full text-left border-collapse min-w-[760px]",children:[g.jsx("thead",{children:g.jsxs("tr",{className:"bg-[#4F758B] text-white text-[10px] font-black uppercase tracking-wider",children:[g.jsx("th",{className:"px-3 py-3",children:"Nombre detectado"}),g.jsx("th",{className:"px-3 py-3",children:"Cuenta"}),g.jsx("th",{className:"px-3 py-3 text-right",children:"Monto banco"}),g.jsx("th",{className:"px-3 py-3",children:"Candidato BambooHR"}),g.jsx("th",{className:"px-3 py-3 text-center",children:"Acción"})]})}),g.jsx("tbody",{className:"divide-y divide-neutral-200 text-xs",children:te.map(ee=>{var Me;const Ce=le.has(ee.id),_e=ee.amountBank;return g.jsxs("tr",{className:"hover:bg-neutral-50",children:[g.jsxs("td",{className:"px-3 py-3",children:[g.jsx("p",{className:"font-black text-neutral-800",children:ee.employee}),(ee.bankNameFile||ee.bankAccountHolder)&&g.jsx("p",{className:"text-[10px] text-neutral-400 mt-1",children:[ee.bankNameFile,ee.bankAccountHolder].filter(Boolean).join(" · ")})]}),g.jsx("td",{className:"px-3 py-3 font-mono font-bold text-neutral-600",children:ee.account||"—"}),g.jsx("td",{className:"px-3 py-3 text-right font-black text-neutral-700",children:_e===null?"—":new Intl.NumberFormat(l.locale,{style:"currency",currency:l.currency,maximumFractionDigits:2}).format(_e)}),g.jsx("td",{className:"px-3 py-3 text-neutral-600 max-w-[260px]",children:(Me=ee.bestBambooCandidate)!=null&&Me.employeeName?g.jsxs("div",{children:[g.jsx("p",{className:"font-bold text-[#4F758B]",children:ee.bestBambooCandidate.employeeName}),ee.bestBambooCandidate.employeeNumber&&g.jsxs("p",{className:"text-[10px] text-neutral-400 mt-0.5",children:["Employee Number ",ee.bestBambooCandidate.employeeNumber]})]}):g.jsx("span",{className:"text-neutral-400",children:"Sin candidato confiable"})}),g.jsx("td",{className:"px-3 py-3 text-center",children:Ce?g.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 border border-emerald-200 bg-emerald-50 text-emerald-800 text-[10px] font-black uppercase tracking-wider",children:[g.jsx(xc,{className:"w-3.5 h-3.5"}),"Reportado a RRHH"]}):g.jsx("button",{type:"button",onClick:()=>K(ee),className:"inline-flex items-center gap-1.5 px-3 py-1.5 bg-[#6CC24A] hover:bg-[#5aaa3f] text-white text-[10px] font-black uppercase tracking-wider transition-colors",children:"Reportar a RRHH"})})]},ee.id)})})]})}):g.jsx("div",{className:"py-12 text-center text-neutral-400 text-sm",children:"No hay casos guardados en este reporte."})]}),g.jsxs("div",{className:"border-t border-neutral-200 px-5 sm:px-6 py-4 flex items-center justify-between gap-3 flex-shrink-0",children:[g.jsxs("span",{className:"text-[10px] text-neutral-400",children:["ID del reporte: ",q.id]}),g.jsx("button",{type:"button",onClick:Ye,className:"border border-neutral-300 bg-white px-4 py-2 text-xs font-bold text-neutral-600 hover:bg-neutral-50",children:"Cerrar"})]})]})})}),G&&q&&g.jsx(Dw,{row:G,country:l,periodRange:Pt,operatorName:i,operatorEmail:a,executionId:q.id,reportUrl:q.reportUrl,onClose:()=>K(null),onSuccess:ee=>{he(Ce=>{const _e=new Set(Ce);return _e.add(ee),_e})},onShowToast:n}),g.jsx(Qs,{children:C&&g.jsx(cn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/45 px-4",children:g.jsxs(cn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:12},className:"w-full max-w-lg bg-white border border-[#D0D0D0] shadow-xl",children:[g.jsxs("div",{className:"border-b border-neutral-200 px-5 py-4 flex items-center justify-between",children:[g.jsxs("div",{children:[g.jsx("h2",{className:"text-base font-black text-[#4F758B] uppercase tracking-tight",children:"Marcar reporte como resuelto"}),g.jsx("p",{className:"text-xs text-neutral-500 mt-1",children:C.period})]}),g.jsx("button",{onClick:()=>P(null),disabled:E,className:"p-2 text-neutral-400 hover:text-neutral-700 disabled:opacity-50","aria-label":"Cerrar",children:g.jsx(ro,{className:"w-4 h-4"})})]}),g.jsxs("div",{className:"p-5 space-y-4",children:[g.jsx("div",{className:"bg-amber-50 border border-amber-200 text-amber-800 p-3 text-xs leading-relaxed",children:"Antes de resolver, confirma que las diferencias fueron revisadas y explica cómo se cerró el caso."}),g.jsxs("label",{className:"block",children:[g.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black text-neutral-500",children:"Comentario de resolución"}),g.jsx("textarea",{value:Y,onChange:ee=>X(ee.target.value),placeholder:"Ejemplo: Se corrigió la cuenta bancaria en nómina y se validó contra el banco.",className:"mt-2 w-full min-h-[130px] border border-[#D0D0D0] px-3 py-2 text-sm focus:outline-none focus:border-[#4F758B]"})]})]}),g.jsxs("div",{className:"border-t border-neutral-200 px-5 py-4 flex justify-end gap-3",children:[g.jsx("button",{onClick:()=>P(null),disabled:E,className:"border border-neutral-300 bg-white px-4 py-2 text-xs font-bold text-neutral-600 hover:bg-neutral-50 disabled:opacity-50",children:"Cancelar"}),g.jsxs("button",{onClick:Zt,disabled:E,className:"bg-[#4F758B] hover:bg-[#41677b] text-white px-4 py-2 text-xs font-black uppercase tracking-wider disabled:opacity-50 inline-flex items-center gap-2",children:[E&&g.jsx(Jr,{className:"w-4 h-4 animate-spin"}),"Confirmar resolución"]})]})]})})})]})}function Nd({message:n,type:e,onClose:i}){M.useEffect(()=>{const c=setTimeout(()=>{i()},2e3);return()=>clearTimeout(c)},[i]);const a={success:"bg-[#6CC24A] text-white border-l-4 border-emerald-700",error:"bg-[#ba1a1a] text-white border-l-4 border-red-800",info:"bg-[#4F758B] text-white border-l-4 border-slate-700"},l={success:xc,error:xj,info:ow}[e];return g.jsx("div",{className:"fixed bottom-6 right-6 z-50 max-w-sm w-full",children:g.jsxs(cn.div,{initial:{opacity:0,y:30,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:20,scale:.95},className:`flex items-center gap-3 p-4 shadow-lg rounded-md border border-neutral-200/10 ${a[e]}`,children:[g.jsx("span",{className:"flex-shrink-0",children:g.jsx(l,{className:"w-5 h-5"})}),g.jsx("div",{className:"flex-1 font-medium text-sm leading-tight pr-2",children:n}),g.jsx("button",{onClick:i,className:"flex-shrink-0 hover:bg-white/20 p-1 rounded transition-colors text-white",children:g.jsx(ro,{className:"w-4 h-4"})})]})})}function Fk({onShowToast:n}){const[e,i]=M.useState(!1),a=async()=>{if(!eo||!lt){n("El acceso con Google aún no está disponible. Contacta a IT.","error");return}i(!0),await hk();const{error:l}=await lt.auth.signInWithOAuth({provider:"google",options:{redirectTo:Ow(),queryParams:{access_type:"offline",prompt:"select_account"}}});l&&(i(!1),n("No se pudo iniciar sesión con Google. Intenta nuevamente.","error"))};return g.jsxs("div",{className:"min-h-screen w-full flex flex-col justify-between bg-[#F5F5F5] relative overflow-hidden font-sans",children:[g.jsx("div",{className:"h-1.5 w-full bg-[#4F758B]"}),g.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:g.jsxs(cn.div,{initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,ease:"easeOut"},className:"w-full max-w-md bg-white border border-[#D0D0D0] p-8 shadow-xl flex flex-col items-center gap-6",children:[g.jsx("div",{className:"w-full flex justify-center py-2",children:g.jsx("img",{alt:"Logo GOMEZLEE MARKETING",className:"h-14 object-contain",src:"https://dbit.digitalcompass.agency/storage/v1/object/public/public-assets/GLM_completo.png",referrerPolicy:"no-referrer"})}),g.jsx("div",{className:"text-center w-full",children:g.jsx("h1",{className:"text-2xl font-bold text-[#4F758B] tracking-tight",children:"Portal de Cruce de Cuentas GLM"})}),g.jsx("button",{onClick:a,disabled:e||!eo,className:"w-full relative overflow-hidden flex items-center justify-center gap-3 bg-[#6CC24A] hover:bg-[#5bb03c] disabled:bg-neutral-300 disabled:cursor-not-allowed text-white font-semibold py-3.5 px-6 transition-all duration-150 transform active:scale-[0.99] select-none text-sm tracking-wide",children:e?g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsxs("svg",{className:"animate-spin h-5 w-5 text-white",fill:"none",viewBox:"0 0 24 24",children:[g.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),g.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),g.jsx("span",{children:"Redirigiendo a Google..."})]}):g.jsxs(g.Fragment,{children:[g.jsxs("svg",{className:"w-5 h-5 flex-shrink-0 fill-current text-white",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[g.jsx("path",{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),g.jsx("path",{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),g.jsx("path",{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),g.jsx("path",{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),g.jsx("span",{children:"Continuar con Google"})]})}),!eo&&g.jsxs("div",{className:"w-full flex items-start gap-2 border border-amber-200 bg-amber-50 px-3 py-2 text-[11px] text-amber-800 leading-relaxed",children:[g.jsx(ao,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),g.jsx("span",{children:"El acceso con Google está pendiente de activación."})]})]})})]})}const Gk="https://dbit.digitalcompass.agency/storage/v1/object/public/public-assets/GLM_completo.png";function Kk({onSelect:n}){return g.jsxs("div",{className:"min-h-screen bg-[#F5F5F5] flex flex-col font-sans",children:[g.jsx("div",{className:"h-1.5 bg-[#6CC24A]"}),g.jsx("main",{className:"flex-1 flex items-center justify-center px-4 py-10",children:g.jsxs(cn.section,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},className:"w-full max-w-3xl bg-white border border-[#D0D0D0] shadow-xl p-6 sm:p-9",children:[g.jsx("img",{src:Gk,alt:"GomezLee Marketing",className:"h-14 object-contain mb-7"}),g.jsxs("div",{className:"flex items-start gap-3 mb-7",children:[g.jsx("div",{className:"bg-[#4F758B]/10 p-2.5 rounded-full",children:g.jsx(rw,{className:"w-5 h-5 text-[#4F758B]"})}),g.jsxs("div",{children:[g.jsx("h1",{className:"text-xl sm:text-2xl font-black text-[#4F758B] uppercase tracking-tight",children:"Selecciona el país"}),g.jsx("p",{className:"text-sm text-neutral-500 mt-1",children:"El portal cargará las reglas, la moneda y los reportes correspondientes."})]})]}),g.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:oo.map(e=>g.jsxs("button",{type:"button",disabled:!e.enabled,onClick:()=>e.enabled&&n(e.code),className:`text-left border p-5 transition-all min-h-[150px] flex flex-col justify-between ${e.enabled?"border-[#4F758B]/30 hover:border-[#4F758B] hover:shadow-md bg-white":"border-neutral-200 bg-neutral-50 cursor-not-allowed opacity-70"}`,children:[g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsx("img",{src:e.flag,alt:"",className:"w-12 h-8 sm:w-16 sm:h-10 object-cover shadow-sm border border-neutral-200","aria-hidden":"true"}),e.enabled?g.jsx(hj,{className:"w-5 h-5 text-[#6CC24A]"}):g.jsx(Vj,{className:"w-4 h-4 text-neutral-400"})]}),g.jsxs("div",{children:[g.jsx("p",{className:"font-black text-[#4F758B] uppercase tracking-wide",children:e.name}),g.jsx("p",{className:"text-xs text-neutral-500 mt-1",children:e.enabled?`Moneda ${e.currency}`:"Próximamente"})]})]},e.code))})]})})]})}const Yk="cruce_cuentas_mi_acceso",gv=2;function Uw(n){return(n??"").trim().toLowerCase()}function Xk(n){return Array.isArray(n)?Array.from(new Set(n.map(e=>String(e??"").trim().toUpperCase()).filter(Boolean))):[]}function Jk(n){const e=Array.isArray(n)?n[0]:n;if(!e||typeof e!="object")throw new Error("Supabase no devolvió una respuesta válida al comprobar el acceso.");return{ok:e.ok===!0,authenticated:e.autenticado===!0,authorized:e.autorizado===!0,email:Uw(typeof e.email=="string"?e.email:""),name:typeof e.nombre=="string"?e.nombre.trim():"",active:e.activo===!0,appAccess:e.acceso_app===!0,historyAccess:e.acceso_historicos===!0,receivesGeneratedReports:e.recibe_reportes_generados===!0,receivesResolvedEmails:e.recibe_correos_resuelto===!0,countries:Xk(e.paises),reason:typeof e.motivo=="string"?e.motivo.trim():""}}function Qk(n){return new Promise(e=>window.setTimeout(e,n))}async function Zk(){if(!lt)throw new Error("Supabase no está configurado.");let n=null;for(let i=1;i<=gv;i+=1){const{data:a,error:l}=await lt.rpc(Yk);if(!l)return Jk(a);n=l,i{if(typeof indexedDB>"u"){e(new Error("IndexedDB no está disponible en este navegador."));return}const i=indexedDB.open(Wk,eO);i.onupgradeneeded=()=>{const a=i.result;a.objectStoreNames.contains(Zn)||a.createObjectStore(Zn,{keyPath:"sessionId"})},i.onsuccess=()=>n(i.result),i.onerror=()=>e(i.error??new Error("No se pudo abrir IndexedDB.")),i.onblocked=()=>e(new Error("La base local está bloqueada por otra pestaña."))}),ja.catch(()=>{ja=null}),ja)}function nO(n){return new Promise((e,i)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>i(n.error??new Error("Falló una operación local."))})}function Vc(n){return new Promise((e,i)=>{n.oncomplete=()=>e(),n.onerror=()=>i(n.error??new Error("Falló la transacción local.")),n.onabort=()=>i(n.error??new Error("La transacción local fue cancelada."))})}function sO(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===Lw&&typeof e.sessionId=="string"&&typeof e.updatedAt=="number"&&(e.currentView==="cruce"||e.currentView==="historial")&&Array.isArray(e.uploadedBankFiles)&&typeof e.isCruceExecuted=="boolean"}async function iO(n,e){const i=Date.now()-tO,a=n.transaction(Zn,"readwrite"),l=Vc(a),u=a.objectStore(Zn).openCursor();await new Promise((d,m)=>{u.onsuccess=()=>{const p=u.result;if(!p){d();return}const y=p.value;y.sessionId!==e&&typeof y.updatedAt=="number"&&y.updatedAtm(u.error??new Error("No se pudieron limpiar borradores antiguos."))}),await l}async function aO(){const n=Qf();try{const e=await Zf(),i=e.transaction(Zn,"readonly"),a=Vc(i),l=await nO(i.objectStore(Zn).get(n));return await a,iO(e,n).catch(()=>{}),sO(l)?l:null}catch{return null}}function rO(n){const e=Qf(),i={...n,version:Lw,sessionId:e,updatedAt:Date.now()};return Va=Va.catch(()=>{}).then(async()=>{const l=(await Zf()).transaction(Zn,"readwrite"),c=Vc(l);l.objectStore(Zn).put(i),await c}).catch(()=>{}),Va}function xv(){const n=Qf();return Va=Va.catch(()=>{}).then(async()=>{const i=(await Zf()).transaction(Zn,"readwrite"),a=Vc(i);i.objectStore(Zn).delete(n),await a}).catch(()=>{}),Va}const wv=!0,bf="glm_cruce_selected_country",oO={name:"Isaac Aracena",email:"iaracena@gomezleemarketing.com"};function lO(n){const e=(n==null?void 0:n.user_metadata)??{},i=e.full_name||e.name||e.display_name;if(i)return String(i);const a=String((n==null?void 0:n.email)??"Usuario GLM");return a.includes("@")?a.split("@")[0]:a}function cO(){try{const n=window.localStorage.getItem(bf),e=oo.find(i=>i.code===n&&i.enabled);return(e==null?void 0:e.code)??null}catch{return null}}function uO(){const[n,e]=M.useState("cruce"),[i,a]=M.useState(!1),[l,c]=M.useState(null),[u,d]=M.useState([]),[m,p]=M.useState(!1),[y,v]=M.useState(null),[x,_]=M.useState(0),[S,E]=M.useState(()=>cO()),[R,N]=M.useState(null),[O,C]=M.useState(wv),[P,Y]=M.useState(!1),[X,q]=M.useState(null),Z=M.useRef(0),te=M.useMemo(()=>eo&<,[]),Q=S?xb(S):null,le=(K,ie)=>{q({message:K,type:ie})};M.useEffect(()=>{if(!te||!lt){C(!1);return}let K=!0;const ie=async H=>{const J=++Z.current;if(!(H!=null&&H.email)){K&&J===Z.current&&N(null);return}try{const W=await Zk();if(!K||J!==Z.current)return;const fe=Uw(H.email),ge=!!W.email&&W.email===fe;if(!W.ok||!W.authenticated||!W.authorized||!W.active||!W.appAccess||!ge){N(null),le(W.reason||"Tu usuario no tiene acceso autorizado a este módulo.","error"),lt.auth.signOut();return}N({name:W.name||lO(H),email:fe})}catch(W){if(!K||J!==Z.current)return;console.error("No se pudo validar el acceso en Supabase:",W),N(null),le("No se pudo validar tu acceso en Supabase. Intenta iniciar sesión nuevamente.","error"),lt.auth.signOut()}};(async()=>{var H;try{const{data:J,error:W}=await lt.auth.getSession();if(W)throw W;if(!K)return;await ie((H=J.session)==null?void 0:H.user)}catch(J){if(!K)return;console.error("No se pudo recuperar la sesión de Supabase:",J),N(null),le("No se pudo recuperar tu sesión. Intenta iniciar sesión nuevamente.","error")}finally{K&&C(!1)}})();const{data:A}=lt.auth.onAuthStateChange((H,J)=>{if(K){if(J!=null&&J.user){window.setTimeout(()=>{K&&ie(J.user)},0);return}H==="SIGNED_OUT"&&(Z.current+=1,N(null),C(!1))}});return()=>{K=!1,Z.current+=1,A.subscription.unsubscribe()}},[te]),M.useEffect(()=>{if(!te||!lt)return;let K=0;const ie=()=>{if(document.visibilityState!=="visible")return;const ue=Date.now();ue-K<5e3||(K=ue,Rc(300).catch(A=>{console.warn("No se pudo revalidar la sesión al reanudar la pestaña:",A)}))};return document.addEventListener("visibilitychange",ie),window.addEventListener("focus",ie),()=>{document.removeEventListener("visibilitychange",ie),window.removeEventListener("focus",ie)}},[te]),M.useEffect(()=>{let K=!0;return(async()=>{const ue=await aO();K&&(ue&&(!S||ue.countryCode===S?(ue.countryCode&&E(ue.countryCode),e(ue.currentView),c(ue.uploadedPayroll),d(ue.uploadedBankFiles),p(ue.isCruceExecuted),v(ue.cruceResponse)):await xv()),K&&Y(!0))})(),()=>{K=!1}},[]),M.useEffect(()=>{P&&rO({countryCode:S,currentView:n,uploadedPayroll:l,uploadedBankFiles:u,isCruceExecuted:m,cruceResponse:y})},[P,S,n,l,u,m,y]);const he=()=>{c(null),d([]),p(!1),v(null),_(K=>K+1)},Ge=async()=>{await xv(),lt&&await lt.auth.signOut(),N(null),E(null),window.localStorage.removeItem(bf),he(),e("cruce"),le("Sesión cerrada correctamente.","success")},Ne=()=>{he(),e("cruce"),le("Nuevo cruce iniciado.","success")},xe=K=>{const ie=xb(K);if(!ie.enabled){le(`${ie.name} estará disponible próximamente.`,"info");return}S&&S!==K&&he(),E(K),window.localStorage.setItem(bf,K),e("cruce"),a(!1)},z=()=>{E(null),a(!1)};if(O)return g.jsx("div",{className:"min-h-screen bg-[#F5F5F5] flex items-center justify-center text-[#4F758B] font-black uppercase tracking-wider",children:"Validando acceso..."});if(!R)return g.jsxs(g.Fragment,{children:[g.jsx(Fk,{onShowToast:le}),g.jsx(Qs,{children:X&&g.jsx(Nd,{message:X.message,type:X.type,onClose:()=>q(null)})})]});if(!Q)return g.jsxs(g.Fragment,{children:[g.jsx(Kk,{onSelect:xe}),g.jsx(Qs,{children:X&&g.jsx(Nd,{message:X.message,type:X.type,onClose:()=>q(null)})})]});const G=R??oO;return g.jsxs("div",{className:"min-h-screen bg-[#F5F5F5] selection:bg-[#6CC24A] selection:text-white antialiased font-sans flex flex-col",children:[g.jsxs(cn.div,{initial:{opacity:0},animate:{opacity:1},className:"min-h-screen flex w-full relative overflow-x-hidden",children:[g.jsx(Qs,{children:i&&g.jsx(cn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>a(!1),className:"fixed inset-0 bg-black/45 z-45 md:hidden"},"backdrop")}),g.jsx(sC,{currentView:n,onViewChange:K=>{e(K),a(!1)},onNewCruce:()=>{Ne(),a(!1)},isSidebarOpen:i,onCloseSidebar:()=>a(!1),user:G,isAuthEnabled:wv,onLogout:Ge,country:Q,onCountryChange:xe,onChooseAnotherCountry:z}),g.jsx("div",{className:"pl-0 md:pl-64 flex-1 flex flex-col w-full min-h-screen transition-all duration-300",children:g.jsx(Qs,{mode:"wait",children:n==="cruce"?g.jsx(cn.div,{initial:{opacity:0,x:10},animate:{opacity:1,x:0},exit:{opacity:0,x:-10},transition:{duration:.2},className:"flex-1 flex flex-col",children:g.jsx(Mk,{onShowToast:le,uploadedPayroll:l,setUploadedPayroll:c,uploadedBankFiles:u,setUploadedBankFiles:d,isCruceExecuted:m,setIsCruceExecuted:p,response:y,setResponse:v,onOpenSidebar:()=>a(!0),operatorName:G.name,operatorEmail:G.email,resetToken:x,country:Q})},`view-cruce-${Q.code}`):g.jsx(cn.div,{initial:{opacity:0,x:10},animate:{opacity:1,x:0},exit:{opacity:0,x:-10},transition:{duration:.2},className:"flex-1 flex flex-col",children:g.jsx(Ik,{onShowToast:le,onOpenSidebar:()=>a(!0),operatorName:G.name,operatorEmail:G.email,country:Q})},`view-history-${Q.code}`)})})]},`interface-${Q.code}`),g.jsx(Qs,{children:X&&g.jsx(Nd,{message:X.message,type:X.type,onClose:()=>q(null)})})]})}window.addEventListener("pageshow",n=>{n.persisted&&window.location.reload()});i1.createRoot(document.getElementById("root")).render(g.jsx(M.StrictMode,{children:g.jsx(uO,{})}));