function dg(e,t){for(var r=0;rn[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function r(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(s){if(s.ep)return;s.ep=!0;const i=r(s);fetch(s.href,i)}})();var Nr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function cd(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ls(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return e[n]}})}),r}var dd={exports:{}},Ki={},hd={exports:{}},B={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var us=Symbol.for("react.element"),hg=Symbol.for("react.portal"),fg=Symbol.for("react.fragment"),pg=Symbol.for("react.strict_mode"),gg=Symbol.for("react.profiler"),mg=Symbol.for("react.provider"),yg=Symbol.for("react.context"),vg=Symbol.for("react.forward_ref"),wg=Symbol.for("react.suspense"),bg=Symbol.for("react.memo"),_g=Symbol.for("react.lazy"),xu=Symbol.iterator;function xg(e){return e===null||typeof e!="object"?null:(e=xu&&e[xu]||e["@@iterator"],typeof e=="function"?e:null)}var fd={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},pd=Object.assign,gd={};function fn(e,t,r){this.props=e,this.context=t,this.refs=gd,this.updater=r||fd}fn.prototype.isReactComponent={};fn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};fn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function md(){}md.prototype=fn.prototype;function ml(e,t,r){this.props=e,this.context=t,this.refs=gd,this.updater=r||fd}var yl=ml.prototype=new md;yl.constructor=ml;pd(yl,fn.prototype);yl.isPureReactComponent=!0;var ku=Array.isArray,yd=Object.prototype.hasOwnProperty,vl={current:null},vd={key:!0,ref:!0,__self:!0,__source:!0};function wd(e,t,r){var n,s={},i=null,a=null;if(t!=null)for(n in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(i=""+t.key),t)yd.call(t,n)&&!vd.hasOwnProperty(n)&&(s[n]=t[n]);var o=arguments.length-2;if(o===1)s.children=r;else if(1>>1,re=A[q];if(0>>1;q<_t;){var tt=2*(q+1)-1,sr=A[tt],Me=tt+1,j=A[Me];if(0>s(sr,L))Mes(j,sr)?(A[q]=j,A[Me]=L,q=Me):(A[q]=sr,A[tt]=L,q=tt);else if(Mes(j,L))A[q]=j,A[Me]=L,q=Me;else break e}}return $}function s(A,$){var L=A.sortIndex-$.sortIndex;return L!==0?L:A.id-$.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,o=a.now();e.unstable_now=function(){return a.now()-o}}var l=[],c=[],d=1,h=null,f=3,g=!1,w=!1,v=!1,b=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,m=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function p(A){for(var $=r(c);$!==null;){if($.callback===null)n(c);else if($.startTime<=A)n(c),$.sortIndex=$.expirationTime,t(l,$);else break;$=r(c)}}function _(A){if(v=!1,p(A),!w)if(r(l)!==null)w=!0,Oe(x);else{var $=r(c);$!==null&&bt(_,$.startTime-A)}}function x(A,$){w=!1,v&&(v=!1,y(k),k=-1),g=!0;var L=f;try{for(p($),h=r(l);h!==null&&(!(h.expirationTime>$)||A&&!z());){var q=h.callback;if(typeof q=="function"){h.callback=null,f=h.priorityLevel;var re=q(h.expirationTime<=$);$=e.unstable_now(),typeof re=="function"?h.callback=re:h===r(l)&&n(l),p($)}else n(l);h=r(l)}if(h!==null)var _t=!0;else{var tt=r(c);tt!==null&&bt(_,tt.startTime-$),_t=!1}return _t}finally{h=null,f=L,g=!1}}var S=!1,E=null,k=-1,T=5,C=-1;function z(){return!(e.unstable_now()-CA||125q?(A.sortIndex=L,t(c,A),r(l)===null&&A===r(c)&&(v?(y(k),k=-1):v=!0,bt(_,L-q))):(A.sortIndex=re,t(l,A),w||g||(w=!0,Oe(x))),A},e.unstable_shouldYield=z,e.unstable_wrapCallback=function(A){var $=f;return function(){var L=f;f=$;try{return A.apply(this,arguments)}finally{f=L}}}})(Sd);kd.exports=Sd;var Ig=kd.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var $g=P,He=Ig;function N(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ro=Object.prototype.hasOwnProperty,Dg=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Eu={},ju={};function Lg(e){return ro.call(ju,e)?!0:ro.call(Eu,e)?!1:Dg.test(e)?ju[e]=!0:(Eu[e]=!0,!1)}function zg(e,t,r,n){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Ug(e,t,r,n){if(t===null||typeof t>"u"||zg(e,t,r,n))return!0;if(n)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Ae(e,t,r,n,s,i,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=n,this.attributeNamespace=s,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=a}var _e={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){_e[e]=new Ae(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];_e[t]=new Ae(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){_e[e]=new Ae(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){_e[e]=new Ae(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){_e[e]=new Ae(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){_e[e]=new Ae(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){_e[e]=new Ae(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){_e[e]=new Ae(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){_e[e]=new Ae(e,5,!1,e.toLowerCase(),null,!1,!1)});var bl=/[\-:]([a-z])/g;function _l(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(bl,_l);_e[t]=new Ae(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(bl,_l);_e[t]=new Ae(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(bl,_l);_e[t]=new Ae(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){_e[e]=new Ae(e,1,!1,e.toLowerCase(),null,!1,!1)});_e.xlinkHref=new Ae("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){_e[e]=new Ae(e,1,!1,e.toLowerCase(),null,!0,!0)});function xl(e,t,r,n){var s=_e.hasOwnProperty(t)?_e[t]:null;(s!==null?s.type!==0:n||!(2o||s[a]!==i[o]){var l=` `+s[a].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=a&&0<=o);break}}}finally{va=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?Nn(e):""}function Mg(e){switch(e.tag){case 5:return Nn(e.type);case 16:return Nn("Lazy");case 13:return Nn("Suspense");case 19:return Nn("SuspenseList");case 0:case 2:case 15:return e=wa(e.type,!1),e;case 11:return e=wa(e.type.render,!1),e;case 1:return e=wa(e.type,!0),e;default:return""}}function ao(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Dr:return"Fragment";case $r:return"Portal";case no:return"Profiler";case kl:return"StrictMode";case so:return"Suspense";case io:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Nd:return(e.displayName||"Context")+".Consumer";case jd:return(e._context.displayName||"Context")+".Provider";case Sl:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case El:return t=e.displayName||null,t!==null?t:ao(e.type)||"Memo";case Dt:t=e._payload,e=e._init;try{return ao(e(t))}catch{}}return null}function Bg(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ao(t);case 8:return t===kl?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Xt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Pd(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Fg(e){var t=Pd(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),n=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var s=r.get,i=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(a){n=""+a,i.call(this,a)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(a){n=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ws(e){e._valueTracker||(e._valueTracker=Fg(e))}function Cd(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return e&&(n=Pd(e)?e.checked?"true":"false":e.value),e=n,e!==r?(t.setValue(e),!0):!1}function ci(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function oo(e,t){var r=t.checked;return ie({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function Tu(e,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=Xt(t.value!=null?t.value:r),e._wrapperState={initialChecked:n,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Ad(e,t){t=t.checked,t!=null&&xl(e,"checked",t,!1)}function lo(e,t){Ad(e,t);var r=Xt(t.value),n=t.type;if(r!=null)n==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(n==="submit"||n==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?uo(e,t.type,r):t.hasOwnProperty("defaultValue")&&uo(e,t.type,Xt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Pu(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!(n!=="submit"&&n!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function uo(e,t,r){(t!=="number"||ci(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var Tn=Array.isArray;function Gr(e,t,r,n){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=bs.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Wn(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var Rn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Vg=["Webkit","ms","Moz","O"];Object.keys(Rn).forEach(function(e){Vg.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Rn[t]=Rn[e]})});function $d(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||Rn.hasOwnProperty(e)&&Rn[e]?(""+t).trim():t+"px"}function Dd(e,t){e=e.style;for(var r in t)if(t.hasOwnProperty(r)){var n=r.indexOf("--")===0,s=$d(r,t[r],n);r==="float"&&(r="cssFloat"),n?e.setProperty(r,s):e[r]=s}}var Wg=ie({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function fo(e,t){if(t){if(Wg[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(N(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(N(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(N(61))}if(t.style!=null&&typeof t.style!="object")throw Error(N(62))}}function po(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var go=null;function jl(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var mo=null,Jr=null,Qr=null;function Ou(e){if(e=hs(e)){if(typeof mo!="function")throw Error(N(280));var t=e.stateNode;t&&(t=Yi(t),mo(e.stateNode,e.type,t))}}function Ld(e){Jr?Qr?Qr.push(e):Qr=[e]:Jr=e}function zd(){if(Jr){var e=Jr,t=Qr;if(Qr=Jr=null,Ou(e),t)for(e=0;e>>=0,e===0?32:31-(t0(e)/r0|0)|0}var _s=64,xs=4194304;function Pn(e){switch(e&-e){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: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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function pi(e,t){var r=e.pendingLanes;if(r===0)return 0;var n=0,s=e.suspendedLanes,i=e.pingedLanes,a=r&268435455;if(a!==0){var o=a&~s;o!==0?n=Pn(o):(i&=a,i!==0&&(n=Pn(i)))}else a=r&~s,a!==0?n=Pn(a):i!==0&&(n=Pn(i));if(n===0)return 0;if(t!==0&&t!==n&&!(t&s)&&(s=n&-n,i=t&-t,s>=i||s===16&&(i&4194240)!==0))return t;if(n&4&&(n|=r&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=n;0r;r++)t.push(e);return t}function cs(e,t,r){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-dt(t),e[t]=r}function a0(e,t){var r=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var n=e.eventTimes;for(e=e.expirationTimes;0=$n),Bu=" ",Fu=!1;function sh(e,t){switch(e){case"keyup":return I0.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ih(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Lr=!1;function D0(e,t){switch(e){case"compositionend":return ih(t);case"keypress":return t.which!==32?null:(Fu=!0,Bu);case"textInput":return e=t.data,e===Bu&&Fu?null:e;default:return null}}function L0(e,t){if(Lr)return e==="compositionend"||!Il&&sh(e,t)?(e=rh(),Qs=Al=Ft=null,Lr=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Ku(r)}}function uh(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?uh(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ch(){for(var e=window,t=ci();t instanceof e.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)e=t.contentWindow;else break;t=ci(e.document)}return t}function $l(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function K0(e){var t=ch(),r=e.focusedElem,n=e.selectionRange;if(t!==r&&r&&r.ownerDocument&&uh(r.ownerDocument.documentElement,r)){if(n!==null&&$l(r)){if(t=n.start,e=n.end,e===void 0&&(e=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(e,r.value.length);else if(e=(t=r.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=r.textContent.length,i=Math.min(n.start,s);n=n.end===void 0?i:Math.min(n.end,s),!e.extend&&i>n&&(s=n,n=i,i=s),s=qu(r,i);var a=qu(r,n);s&&a&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>n?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=r;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,zr=null,xo=null,Ln=null,ko=!1;function Gu(e,t,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;ko||zr==null||zr!==ci(n)||(n=zr,"selectionStart"in n&&$l(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),Ln&&Qn(Ln,n)||(Ln=n,n=yi(xo,"onSelect"),0Br||(e.current=Po[Br],Po[Br]=null,Br--)}function Q(e,t){Br++,Po[Br]=e.current,e.current=t}var Zt={},je=tr(Zt),Le=tr(!1),br=Zt;function nn(e,t){var r=e.type.contextTypes;if(!r)return Zt;var n=e.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in r)s[i]=t[i];return n&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function ze(e){return e=e.childContextTypes,e!=null}function wi(){Z(Le),Z(je)}function tc(e,t,r){if(je.current!==Zt)throw Error(N(168));Q(je,t),Q(Le,r)}function wh(e,t,r){var n=e.stateNode;if(t=t.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var s in n)if(!(s in t))throw Error(N(108,Bg(e)||"Unknown",s));return ie({},r,n)}function bi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Zt,br=je.current,Q(je,e),Q(Le,Le.current),!0}function rc(e,t,r){var n=e.stateNode;if(!n)throw Error(N(169));r?(e=wh(e,t,br),n.__reactInternalMemoizedMergedChildContext=e,Z(Le),Z(je),Q(je,e)):Z(Le),Q(Le,r)}var St=null,Xi=!1,Ra=!1;function bh(e){St===null?St=[e]:St.push(e)}function sm(e){Xi=!0,bh(e)}function rr(){if(!Ra&&St!==null){Ra=!0;var e=0,t=H;try{var r=St;for(H=1;e>=a,s-=a,Et=1<<32-dt(t)+s|r<k?(T=E,E=null):T=E.sibling;var C=f(y,E,p[k],_);if(C===null){E===null&&(E=T);break}e&&E&&C.alternate===null&&t(y,E),m=i(C,m,k),S===null?x=C:S.sibling=C,S=C,E=T}if(k===p.length)return r(y,E),te&&or(y,k),x;if(E===null){for(;kk?(T=E,E=null):T=E.sibling;var z=f(y,E,C.value,_);if(z===null){E===null&&(E=T);break}e&&E&&z.alternate===null&&t(y,E),m=i(z,m,k),S===null?x=z:S.sibling=z,S=z,E=T}if(C.done)return r(y,E),te&&or(y,k),x;if(E===null){for(;!C.done;k++,C=p.next())C=h(y,C.value,_),C!==null&&(m=i(C,m,k),S===null?x=C:S.sibling=C,S=C);return te&&or(y,k),x}for(E=n(y,E);!C.done;k++,C=p.next())C=g(E,y,k,C.value,_),C!==null&&(e&&C.alternate!==null&&E.delete(C.key===null?k:C.key),m=i(C,m,k),S===null?x=C:S.sibling=C,S=C);return e&&E.forEach(function(K){return t(y,K)}),te&&or(y,k),x}function b(y,m,p,_){if(typeof p=="object"&&p!==null&&p.type===Dr&&p.key===null&&(p=p.props.children),typeof p=="object"&&p!==null){switch(p.$$typeof){case vs:e:{for(var x=p.key,S=m;S!==null;){if(S.key===x){if(x=p.type,x===Dr){if(S.tag===7){r(y,S.sibling),m=s(S,p.props.children),m.return=y,y=m;break e}}else if(S.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===Dt&&ic(x)===S.type){r(y,S.sibling),m=s(S,p.props),m.ref=Sn(y,S,p),m.return=y,y=m;break e}r(y,S);break}else t(y,S);S=S.sibling}p.type===Dr?(m=wr(p.props.children,y.mode,_,p.key),m.return=y,y=m):(_=si(p.type,p.key,p.props,null,y.mode,_),_.ref=Sn(y,m,p),_.return=y,y=_)}return a(y);case $r:e:{for(S=p.key;m!==null;){if(m.key===S)if(m.tag===4&&m.stateNode.containerInfo===p.containerInfo&&m.stateNode.implementation===p.implementation){r(y,m.sibling),m=s(m,p.children||[]),m.return=y,y=m;break e}else{r(y,m);break}else t(y,m);m=m.sibling}m=Ba(p,y.mode,_),m.return=y,y=m}return a(y);case Dt:return S=p._init,b(y,m,S(p._payload),_)}if(Tn(p))return w(y,m,p,_);if(wn(p))return v(y,m,p,_);Ps(y,p)}return typeof p=="string"&&p!==""||typeof p=="number"?(p=""+p,m!==null&&m.tag===6?(r(y,m.sibling),m=s(m,p),m.return=y,y=m):(r(y,m),m=Ma(p,y.mode,_),m.return=y,y=m),a(y)):r(y,m)}return b}var an=Sh(!0),Eh=Sh(!1),ki=tr(null),Si=null,Wr=null,Ul=null;function Ml(){Ul=Wr=Si=null}function Bl(e){var t=ki.current;Z(ki),e._currentValue=t}function Oo(e,t,r){for(;e!==null;){var n=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,n!==null&&(n.childLanes|=t)):n!==null&&(n.childLanes&t)!==t&&(n.childLanes|=t),e===r)break;e=e.return}}function Xr(e,t){Si=e,Ul=Wr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(De=!0),e.firstContext=null)}function Ze(e){var t=e._currentValue;if(Ul!==e)if(e={context:e,memoizedValue:t,next:null},Wr===null){if(Si===null)throw Error(N(308));Wr=e,Si.dependencies={lanes:0,firstContext:e}}else Wr=Wr.next=e;return t}var gr=null;function Fl(e){gr===null?gr=[e]:gr.push(e)}function jh(e,t,r,n){var s=t.interleaved;return s===null?(r.next=r,Fl(t)):(r.next=s.next,s.next=r),t.interleaved=r,Ct(e,n)}function Ct(e,t){e.lanes|=t;var r=e.alternate;for(r!==null&&(r.lanes|=t),r=e,e=e.return;e!==null;)e.childLanes|=t,r=e.alternate,r!==null&&(r.childLanes|=t),r=e,e=e.return;return r.tag===3?r.stateNode:null}var Lt=!1;function Vl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Nh(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Nt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Gt(e,t,r){var n=e.updateQueue;if(n===null)return null;if(n=n.shared,F&2){var s=n.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),n.pending=t,Ct(e,r)}return s=n.interleaved,s===null?(t.next=t,Fl(n)):(t.next=s.next,s.next=t),n.interleaved=t,Ct(e,r)}function Xs(e,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var n=t.lanes;n&=e.pendingLanes,r|=n,t.lanes=r,Tl(e,r)}}function ac(e,t){var r=e.updateQueue,n=e.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var s=null,i=null;if(r=r.firstBaseUpdate,r!==null){do{var a={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};i===null?s=i=a:i=i.next=a,r=r.next}while(r!==null);i===null?s=i=t:i=i.next=t}else s=i=t;r={baseState:n.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:n.shared,effects:n.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=t:e.next=t,r.lastBaseUpdate=t}function Ei(e,t,r,n){var s=e.updateQueue;Lt=!1;var i=s.firstBaseUpdate,a=s.lastBaseUpdate,o=s.shared.pending;if(o!==null){s.shared.pending=null;var l=o,c=l.next;l.next=null,a===null?i=c:a.next=c,a=l;var d=e.alternate;d!==null&&(d=d.updateQueue,o=d.lastBaseUpdate,o!==a&&(o===null?d.firstBaseUpdate=c:o.next=c,d.lastBaseUpdate=l))}if(i!==null){var h=s.baseState;a=0,d=c=l=null,o=i;do{var f=o.lane,g=o.eventTime;if((n&f)===f){d!==null&&(d=d.next={eventTime:g,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var w=e,v=o;switch(f=t,g=r,v.tag){case 1:if(w=v.payload,typeof w=="function"){h=w.call(g,h,f);break e}h=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=v.payload,f=typeof w=="function"?w.call(g,h,f):w,f==null)break e;h=ie({},h,f);break e;case 2:Lt=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,f=s.effects,f===null?s.effects=[o]:f.push(o))}else g={eventTime:g,lane:f,tag:o.tag,payload:o.payload,callback:o.callback,next:null},d===null?(c=d=g,l=h):d=d.next=g,a|=f;if(o=o.next,o===null){if(o=s.shared.pending,o===null)break;f=o,o=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);if(d===null&&(l=h),s.baseState=l,s.firstBaseUpdate=c,s.lastBaseUpdate=d,t=s.shared.interleaved,t!==null){s=t;do a|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);kr|=a,e.lanes=a,e.memoizedState=h}}function oc(e,t,r){if(e=t.effects,t.effects=null,e!==null)for(t=0;tr?r:4,e(!0);var n=$a.transition;$a.transition={};try{e(!1),t()}finally{H=r,$a.transition=n}}function Wh(){return et().memoizedState}function lm(e,t,r){var n=Qt(e);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},Hh(e))Kh(t,r);else if(r=jh(e,t,r,n),r!==null){var s=Pe();ht(r,e,n,s),qh(r,t,n)}}function um(e,t,r){var n=Qt(e),s={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(Hh(e))Kh(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var a=t.lastRenderedState,o=i(a,r);if(s.hasEagerState=!0,s.eagerState=o,ft(o,a)){var l=t.interleaved;l===null?(s.next=s,Fl(t)):(s.next=l.next,l.next=s),t.interleaved=s;return}}catch{}finally{}r=jh(e,t,s,n),r!==null&&(s=Pe(),ht(r,e,n,s),qh(r,t,n))}}function Hh(e){var t=e.alternate;return e===se||t!==null&&t===se}function Kh(e,t){zn=Ni=!0;var r=e.pending;r===null?t.next=t:(t.next=r.next,r.next=t),e.pending=t}function qh(e,t,r){if(r&4194240){var n=t.lanes;n&=e.pendingLanes,r|=n,t.lanes=r,Tl(e,r)}}var Ti={readContext:Ze,useCallback:xe,useContext:xe,useEffect:xe,useImperativeHandle:xe,useInsertionEffect:xe,useLayoutEffect:xe,useMemo:xe,useReducer:xe,useRef:xe,useState:xe,useDebugValue:xe,useDeferredValue:xe,useTransition:xe,useMutableSource:xe,useSyncExternalStore:xe,useId:xe,unstable_isNewReconciler:!1},cm={readContext:Ze,useCallback:function(e,t){return gt().memoizedState=[e,t===void 0?null:t],e},useContext:Ze,useEffect:uc,useImperativeHandle:function(e,t,r){return r=r!=null?r.concat([e]):null,ei(4194308,4,Uh.bind(null,t,e),r)},useLayoutEffect:function(e,t){return ei(4194308,4,e,t)},useInsertionEffect:function(e,t){return ei(4,2,e,t)},useMemo:function(e,t){var r=gt();return t=t===void 0?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var n=gt();return t=r!==void 0?r(t):t,n.memoizedState=n.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},n.queue=e,e=e.dispatch=lm.bind(null,se,e),[n.memoizedState,e]},useRef:function(e){var t=gt();return e={current:e},t.memoizedState=e},useState:lc,useDebugValue:Yl,useDeferredValue:function(e){return gt().memoizedState=e},useTransition:function(){var e=lc(!1),t=e[0];return e=om.bind(null,e[1]),gt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,r){var n=se,s=gt();if(te){if(r===void 0)throw Error(N(407));r=r()}else{if(r=t(),ge===null)throw Error(N(349));xr&30||Ah(n,t,r)}s.memoizedState=r;var i={value:r,getSnapshot:t};return s.queue=i,uc(Rh.bind(null,n,i,e),[e]),n.flags|=2048,ss(9,Oh.bind(null,n,i,r,t),void 0,null),r},useId:function(){var e=gt(),t=ge.identifierPrefix;if(te){var r=jt,n=Et;r=(n&~(1<<32-dt(n)-1)).toString(32)+r,t=":"+t+"R"+r,r=rs++,0<\/script>",e=e.removeChild(e.firstChild)):typeof n.is=="string"?e=a.createElement(r,{is:n.is}):(e=a.createElement(r),r==="select"&&(a=e,n.multiple?a.multiple=!0:n.size&&(a.size=n.size))):e=a.createElementNS(e,r),e[yt]=t,e[Zn]=n,nf(e,t,!1,!1),t.stateNode=e;e:{switch(a=po(r,n),r){case"dialog":X("cancel",e),X("close",e),s=n;break;case"iframe":case"object":case"embed":X("load",e),s=n;break;case"video":case"audio":for(s=0;sun&&(t.flags|=128,n=!0,En(i,!1),t.lanes=4194304)}else{if(!n)if(e=ji(a),e!==null){if(t.flags|=128,n=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),En(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!te)return ke(t),null}else 2*oe()-i.renderingStartTime>un&&r!==1073741824&&(t.flags|=128,n=!0,En(i,!1),t.lanes=4194304);i.isBackwards?(a.sibling=t.child,t.child=a):(r=i.last,r!==null?r.sibling=a:t.child=a,i.last=a)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=oe(),t.sibling=null,r=ne.current,Q(ne,n?r&1|2:r&1),t):(ke(t),null);case 22:case 23:return nu(),n=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==n&&(t.flags|=8192),n&&t.mode&1?Be&1073741824&&(ke(t),t.subtreeFlags&6&&(t.flags|=8192)):ke(t),null;case 24:return null;case 25:return null}throw Error(N(156,t.tag))}function vm(e,t){switch(Ll(t),t.tag){case 1:return ze(t.type)&&wi(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return on(),Z(Le),Z(je),Kl(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Hl(t),null;case 13:if(Z(ne),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(N(340));sn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Z(ne),null;case 4:return on(),null;case 10:return Bl(t.type._context),null;case 22:case 23:return nu(),null;case 24:return null;default:return null}}var As=!1,Se=!1,wm=typeof WeakSet=="function"?WeakSet:Set,O=null;function Hr(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){ae(e,t,n)}else r.current=null}function Bo(e,t,r){try{r()}catch(n){ae(e,t,n)}}var bc=!1;function bm(e,t){if(So=gi,e=ch(),$l(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var s=n.anchorOffset,i=n.focusNode;n=n.focusOffset;try{r.nodeType,i.nodeType}catch{r=null;break e}var a=0,o=-1,l=-1,c=0,d=0,h=e,f=null;t:for(;;){for(var g;h!==r||s!==0&&h.nodeType!==3||(o=a+s),h!==i||n!==0&&h.nodeType!==3||(l=a+n),h.nodeType===3&&(a+=h.nodeValue.length),(g=h.firstChild)!==null;)f=h,h=g;for(;;){if(h===e)break t;if(f===r&&++c===s&&(o=a),f===i&&++d===n&&(l=a),(g=h.nextSibling)!==null)break;h=f,f=h.parentNode}h=g}r=o===-1||l===-1?null:{start:o,end:l}}else r=null}r=r||{start:0,end:0}}else r=null;for(Eo={focusedElem:e,selectionRange:r},gi=!1,O=t;O!==null;)if(t=O,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,O=e;else for(;O!==null;){t=O;try{var w=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var v=w.memoizedProps,b=w.memoizedState,y=t.stateNode,m=y.getSnapshotBeforeUpdate(t.elementType===t.type?v:it(t.type,v),b);y.__reactInternalSnapshotBeforeUpdate=m}break;case 3:var p=t.stateNode.containerInfo;p.nodeType===1?p.textContent="":p.nodeType===9&&p.documentElement&&p.removeChild(p.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(N(163))}}catch(_){ae(t,t.return,_)}if(e=t.sibling,e!==null){e.return=t.return,O=e;break}O=t.return}return w=bc,bc=!1,w}function Un(e,t,r){var n=t.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var s=n=n.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&Bo(t,r,i)}s=s.next}while(s!==n)}}function ta(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var n=r.create;r.destroy=n()}r=r.next}while(r!==t)}}function Fo(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function of(e){var t=e.alternate;t!==null&&(e.alternate=null,of(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[yt],delete t[Zn],delete t[To],delete t[rm],delete t[nm])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function lf(e){return e.tag===5||e.tag===3||e.tag===4}function _c(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||lf(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Vo(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=vi));else if(n!==4&&(e=e.child,e!==null))for(Vo(e,t,r),e=e.sibling;e!==null;)Vo(e,t,r),e=e.sibling}function Wo(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(n!==4&&(e=e.child,e!==null))for(Wo(e,t,r),e=e.sibling;e!==null;)Wo(e,t,r),e=e.sibling}var ve=null,ot=!1;function $t(e,t,r){for(r=r.child;r!==null;)uf(e,t,r),r=r.sibling}function uf(e,t,r){if(vt&&typeof vt.onCommitFiberUnmount=="function")try{vt.onCommitFiberUnmount(qi,r)}catch{}switch(r.tag){case 5:Se||Hr(r,t);case 6:var n=ve,s=ot;ve=null,$t(e,t,r),ve=n,ot=s,ve!==null&&(ot?(e=ve,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):ve.removeChild(r.stateNode));break;case 18:ve!==null&&(ot?(e=ve,r=r.stateNode,e.nodeType===8?Oa(e.parentNode,r):e.nodeType===1&&Oa(e,r),Gn(e)):Oa(ve,r.stateNode));break;case 4:n=ve,s=ot,ve=r.stateNode.containerInfo,ot=!0,$t(e,t,r),ve=n,ot=s;break;case 0:case 11:case 14:case 15:if(!Se&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){s=n=n.next;do{var i=s,a=i.destroy;i=i.tag,a!==void 0&&(i&2||i&4)&&Bo(r,t,a),s=s.next}while(s!==n)}$t(e,t,r);break;case 1:if(!Se&&(Hr(r,t),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(o){ae(r,t,o)}$t(e,t,r);break;case 21:$t(e,t,r);break;case 22:r.mode&1?(Se=(n=Se)||r.memoizedState!==null,$t(e,t,r),Se=n):$t(e,t,r);break;default:$t(e,t,r)}}function xc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new wm),t.forEach(function(n){var s=Pm.bind(null,e,n);r.has(n)||(r.add(n),n.then(s,s))})}}function nt(e,t){var r=t.deletions;if(r!==null)for(var n=0;ns&&(s=a),n&=~i}if(n=s,n=oe()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*xm(n/1960))-n,10e?16:e,Vt===null)var n=!1;else{if(e=Vt,Vt=null,Ai=0,F&6)throw Error(N(331));var s=F;for(F|=4,O=e.current;O!==null;){var i=O,a=i.child;if(O.flags&16){var o=i.deletions;if(o!==null){for(var l=0;loe()-tu?vr(e,0):eu|=r),Ue(e,t)}function yf(e,t){t===0&&(e.mode&1?(t=xs,xs<<=1,!(xs&130023424)&&(xs=4194304)):t=1);var r=Pe();e=Ct(e,t),e!==null&&(cs(e,t,r),Ue(e,r))}function Tm(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),yf(e,r)}function Pm(e,t){var r=0;switch(e.tag){case 13:var n=e.stateNode,s=e.memoizedState;s!==null&&(r=s.retryLane);break;case 19:n=e.stateNode;break;default:throw Error(N(314))}n!==null&&n.delete(t),yf(e,r)}var vf;vf=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||Le.current)De=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return De=!1,mm(e,t,r);De=!!(e.flags&131072)}else De=!1,te&&t.flags&1048576&&_h(t,xi,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;ti(e,t),e=t.pendingProps;var s=nn(t,je.current);Xr(t,r),s=Gl(null,t,n,e,s,r);var i=Jl();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ze(n)?(i=!0,bi(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Vl(t),s.updater=ea,t.stateNode=s,s._reactInternals=t,Io(t,n,e,r),t=Lo(null,t,n,!0,i,r)):(t.tag=0,te&&i&&Dl(t),Te(null,t,s,r),t=t.child),t;case 16:n=t.elementType;e:{switch(ti(e,t),e=t.pendingProps,s=n._init,n=s(n._payload),t.type=n,s=t.tag=Am(n),e=it(n,e),s){case 0:t=Do(null,t,n,e,r);break e;case 1:t=yc(null,t,n,e,r);break e;case 11:t=gc(null,t,n,e,r);break e;case 14:t=mc(null,t,n,it(n.type,e),r);break e}throw Error(N(306,n,""))}return t;case 0:return n=t.type,s=t.pendingProps,s=t.elementType===n?s:it(n,s),Do(e,t,n,s,r);case 1:return n=t.type,s=t.pendingProps,s=t.elementType===n?s:it(n,s),yc(e,t,n,s,r);case 3:e:{if(ef(t),e===null)throw Error(N(387));n=t.pendingProps,i=t.memoizedState,s=i.element,Nh(e,t),Ei(t,n,null,r);var a=t.memoizedState;if(n=a.element,i.isDehydrated)if(i={element:n,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=ln(Error(N(423)),t),t=vc(e,t,n,r,s);break e}else if(n!==s){s=ln(Error(N(424)),t),t=vc(e,t,n,r,s);break e}else for(Ve=qt(t.stateNode.containerInfo.firstChild),We=t,te=!0,ut=null,r=Eh(t,null,n,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(sn(),n===s){t=At(e,t,r);break e}Te(e,t,n,r)}t=t.child}return t;case 5:return Th(t),e===null&&Ao(t),n=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,a=s.children,jo(n,s)?a=null:i!==null&&jo(n,i)&&(t.flags|=32),Zh(e,t),Te(e,t,a,r),t.child;case 6:return e===null&&Ao(t),null;case 13:return tf(e,t,r);case 4:return Wl(t,t.stateNode.containerInfo),n=t.pendingProps,e===null?t.child=an(t,null,n,r):Te(e,t,n,r),t.child;case 11:return n=t.type,s=t.pendingProps,s=t.elementType===n?s:it(n,s),gc(e,t,n,s,r);case 7:return Te(e,t,t.pendingProps,r),t.child;case 8:return Te(e,t,t.pendingProps.children,r),t.child;case 12:return Te(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(n=t.type._context,s=t.pendingProps,i=t.memoizedProps,a=s.value,Q(ki,n._currentValue),n._currentValue=a,i!==null)if(ft(i.value,a)){if(i.children===s.children&&!Le.current){t=At(e,t,r);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){a=i.child;for(var l=o.firstContext;l!==null;){if(l.context===n){if(i.tag===1){l=Nt(-1,r&-r),l.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var d=c.pending;d===null?l.next=l:(l.next=d.next,d.next=l),c.pending=l}}i.lanes|=r,l=i.alternate,l!==null&&(l.lanes|=r),Oo(i.return,r,t),o.lanes|=r;break}l=l.next}}else if(i.tag===10)a=i.type===t.type?null:i.child;else if(i.tag===18){if(a=i.return,a===null)throw Error(N(341));a.lanes|=r,o=a.alternate,o!==null&&(o.lanes|=r),Oo(a,r,t),a=i.sibling}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===t){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}Te(e,t,s.children,r),t=t.child}return t;case 9:return s=t.type,n=t.pendingProps.children,Xr(t,r),s=Ze(s),n=n(s),t.flags|=1,Te(e,t,n,r),t.child;case 14:return n=t.type,s=it(n,t.pendingProps),s=it(n.type,s),mc(e,t,n,s,r);case 15:return Yh(e,t,t.type,t.pendingProps,r);case 17:return n=t.type,s=t.pendingProps,s=t.elementType===n?s:it(n,s),ti(e,t),t.tag=1,ze(n)?(e=!0,bi(t)):e=!1,Xr(t,r),Gh(t,n,s),Io(t,n,s,r),Lo(null,t,n,!0,e,r);case 19:return rf(e,t,r);case 22:return Xh(e,t,r)}throw Error(N(156,t.tag))};function wf(e,t){return Hd(e,t)}function Cm(e,t,r,n){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ye(e,t,r,n){return new Cm(e,t,r,n)}function iu(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Am(e){if(typeof e=="function")return iu(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Sl)return 11;if(e===El)return 14}return 2}function Yt(e,t){var r=e.alternate;return r===null?(r=Ye(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function si(e,t,r,n,s,i){var a=2;if(n=e,typeof e=="function")iu(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case Dr:return wr(r.children,s,i,t);case kl:a=8,s|=8;break;case no:return e=Ye(12,r,t,s|2),e.elementType=no,e.lanes=i,e;case so:return e=Ye(13,r,t,s),e.elementType=so,e.lanes=i,e;case io:return e=Ye(19,r,t,s),e.elementType=io,e.lanes=i,e;case Td:return na(r,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case jd:a=10;break e;case Nd:a=9;break e;case Sl:a=11;break e;case El:a=14;break e;case Dt:a=16,n=null;break e}throw Error(N(130,e==null?e:typeof e,""))}return t=Ye(a,r,t,s),t.elementType=e,t.type=n,t.lanes=i,t}function wr(e,t,r,n){return e=Ye(7,e,n,t),e.lanes=r,e}function na(e,t,r,n){return e=Ye(22,e,n,t),e.elementType=Td,e.lanes=r,e.stateNode={isHidden:!1},e}function Ma(e,t,r){return e=Ye(6,e,null,t),e.lanes=r,e}function Ba(e,t,r){return t=Ye(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Om(e,t,r,n,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=_a(0),this.expirationTimes=_a(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=_a(0),this.identifierPrefix=n,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function au(e,t,r,n,s,i,a,o,l){return e=new Om(e,t,r,o,l),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ye(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},Vl(i),e}function Rm(e,t,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(kf)}catch(e){console.error(e)}}kf(),xd.exports=Ke;var zm=xd.exports,Cc=zm;to.createRoot=Cc.createRoot,to.hydrateRoot=Cc.hydrateRoot;var Um={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"};const Mm=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Bm=(e,t)=>{const r=P.forwardRef(({color:n="currentColor",size:s=24,strokeWidth:i=2,absoluteStrokeWidth:a,children:o,...l},c)=>P.createElement("svg",{ref:c,...Um,width:s,height:s,stroke:n,strokeWidth:a?Number(i)*24/Number(s):i,className:`lucide lucide-${Mm(e)}`,...l},[...t.map(([d,h])=>P.createElement(d,h)),...(Array.isArray(o)?o:[o])||[]]));return r.displayName=`${e}`,r};var V=Bm;const Sf=V("Activity",[["path",{d:"M22 12h-4l-3 9L9 3l-3 9H2",key:"d5dnw9"}]]),Fm=V("AlertTriangle",[["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-3Z",key:"c3ski4"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),Vm=V("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]),Ii=V("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]),Wm=V("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]),Hm=V("BarChart3",[["path",{d:"M3 3v18h18",key:"1s2lah"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]),Km=V("Brain",[["path",{d:"M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 1.98-3A2.5 2.5 0 0 1 9.5 2Z",key:"1mhkh5"}],["path",{d:"M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-1.98-3A2.5 2.5 0 0 0 14.5 2Z",key:"1d6s00"}]]),Ac=V("Calendar",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2",key:"eu3xkr"}],["line",{x1:"16",x2:"16",y1:"2",y2:"6",key:"m3sa8f"}],["line",{x1:"8",x2:"8",y1:"2",y2:"6",key:"18kwsl"}],["line",{x1:"3",x2:"21",y1:"10",y2:"10",key:"xt86sb"}]]),Jo=V("CheckCircle2",[["path",{d:"M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z",key:"14v8dr"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),qm=V("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),Gm=V("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),Jm=V("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),Qm=V("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]),Ym=V("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]),Ef=V("FileDown",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]),Xm=V("FileText",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["line",{x1:"16",x2:"8",y1:"13",y2:"13",key:"14keom"}],["line",{x1:"16",x2:"8",y1:"17",y2:"17",key:"17nazh"}],["line",{x1:"10",x2:"8",y1:"9",y2:"9",key:"1a5vjj"}]]),Zm=V("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]),ey=V("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]),ty=V("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]),ry=V("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),ny=V("Save",[["path",{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z",key:"1owoqh"}],["polyline",{points:"17 21 17 13 7 13 7 21",key:"1md35c"}],["polyline",{points:"7 3 7 8 15 8",key:"8nz8an"}]]),sy=V("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]),jf=V("ShieldCheck",[["path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",key:"3xmgem"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),iy=V("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]),Nf=V("Sparkles",[["path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z",key:"17u4zn"}],["path",{d:"M5 3v4",key:"bklmnn"}],["path",{d:"M19 17v4",key:"iiml17"}],["path",{d:"M3 5h4",key:"nem4j1"}],["path",{d:"M17 19h4",key:"lbex7p"}]]),ay=V("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]),Tf=V("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]),oy=V("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]),Pf=V("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]),ly=V("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]),uy=V("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]),cy=["M","D","M","D","F","S","S"],Qo=e=>{const t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${n}`},dy=e=>{if(!e||!e.includes("-"))return null;const[t,r,n]=e.split("-").map(Number);return new Date(t,r-1,n)},hy=e=>{const t=new Date(e.getFullYear(),e.getMonth(),1),r=(t.getDay()+6)%7,n=new Date(t.getFullYear(),t.getMonth(),1-r);return Array.from({length:42},(s,i)=>{const a=new Date(n.getFullYear(),n.getMonth(),n.getDate()+i);return{key:Qo(a),date:a,isoValue:Qo(a),isCurrentMonth:a.getMonth()===e.getMonth()}})},fy=({patTypes:e,assessments:t,overview:r,assessmentShareTokens:n={},onCreate:s,onEdit:i,onDelete:a,getPatTypeColor:o,getAchievement:l})=>{const c=P.useRef(null),[d,h]=P.useState(!1),[f,g]=P.useState(null),[w,v]=P.useState({key:"datum",direction:"desc"}),[b,y]=P.useState({name:"",datum:""}),[m,p]=P.useState(()=>{const j=new Date;return new Date(j.getFullYear(),j.getMonth(),1)}),_=Object.keys(e||{}),x=t.filter(j=>!j.isFinalized),S=t.filter(j=>j.isFinalized),E=j=>j.exercises.reduce((M,U)=>M+(U.points||0),0),k=j=>String(j||"").toLowerCase().trim(),T=j=>{if(!j||!j.includes("-"))return"";const[M,U,fe]=j.split("-");return`${fe}.${U}.${M}`},C=j=>{if(!j||!j.includes("-"))return j||"";const[M,U,fe]=j.split("-");return`${M}.${U}.${fe}`},z=P.useMemo(()=>new Intl.DateTimeFormat("de-DE",{month:"long",year:"numeric"}).format(m),[m]),K=P.useMemo(()=>hy(m),[m]);P.useEffect(()=>{if(!f)return;const j=U=>{c.current&&!c.current.contains(U.target)&&g(null)},M=U=>{U.key==="Escape"&&g(null)};return document.addEventListener("mousedown",j),document.addEventListener("keydown",M),()=>{document.removeEventListener("mousedown",j),document.removeEventListener("keydown",M)}},[f]);const Y=j=>{const M=!b.name||k(j.name).includes(k(b.name)),U=!b.datum||k(j.datum).includes(k(b.datum));return M&&U},Ne=(j,M)=>M==="name"?(j.name||"").toLowerCase():M==="datum"?j.datum||"":M==="result"?E(j):"",It=j=>[...j].sort((M,U)=>{const fe=Ne(M,w.key),Ge=Ne(U,w.key);return feGe?w.direction==="asc"?1:-1:0}),Oe=P.useMemo(()=>It(x.filter(Y)),[x,w,b]),bt=P.useMemo(()=>It(S.filter(Y)),[S,w,b]),A=j=>{v(M=>M.key===j?{key:j,direction:M.direction==="asc"?"desc":"asc"}:{key:j,direction:j==="datum"?"desc":"asc"})},$=j=>w.key!==j?u.jsx(Wm,{className:"w-4 h-4 text-gray-400 dark:text-gray-500","aria-hidden":"true"}):w.direction==="asc"?u.jsx(Qm,{className:"w-4 h-4","aria-hidden":"true"}):u.jsx(qm,{className:"w-4 h-4","aria-hidden":"true"}),L=(j,M)=>{y(U=>({...U,[j]:M}))},q=j=>{const U=dy(j)||new Date;p(new Date(U.getFullYear(),U.getMonth(),1))},re=j=>{g(M=>M!==j?(q(b.datum),j):null)},_t=j=>{L("datum",j),q(j),g(null)},tt=()=>{L("datum",""),q(""),g(null)},sr=()=>{_t(Qo(new Date))},Me=(j,M,U,fe,Ge)=>{const rt=f===j;return u.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-lg border border-gray-100 dark:border-gray-800 overflow-hidden",children:[u.jsxs("div",{className:"px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/70",children:[u.jsx("h2",{className:"text-lg font-bold text-gray-800 dark:text-gray-100",children:M}),u.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:["Anzahl: ",U.length,U.length!==fe?` von ${fe}`:""]})]}),fe===0?u.jsx("div",{className:"px-6 py-8 text-sm text-gray-500 dark:text-gray-400",children:Ge}):u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full",children:[u.jsx("thead",{className:"bg-gray-100 dark:bg-gray-800 text-left",children:u.jsxs("tr",{children:[u.jsx("th",{className:"px-6 py-3 text-sm font-semibold text-gray-700 dark:text-gray-200",children:u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("button",{type:"button",onClick:()=>A("name"),className:"inline-flex items-center gap-2 hover:text-gray-900 dark:hover:text-white transition",children:["Name",$("name")]}),u.jsx("input",{type:"text",value:b.name,onChange:G=>L("name",G.target.value),"aria-label":"Nach Name filtern",className:"w-40 rounded border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-950 px-3 py-2 text-sm font-normal text-gray-700 dark:text-gray-200"})]})}),u.jsx("th",{className:"px-6 py-3 text-sm font-semibold text-gray-700 dark:text-gray-200",children:u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("button",{type:"button",onClick:()=>A("datum"),className:"inline-flex items-center gap-2 hover:text-gray-900 dark:hover:text-white transition",children:["Datum",$("datum")]}),u.jsxs("div",{ref:rt?c:null,className:"relative",children:[u.jsxs("button",{type:"button",onClick:()=>re(j),"aria-label":"Nach Datum filtern","aria-expanded":rt,className:"flex w-36 items-center justify-between rounded border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-950 px-3 py-2 text-left text-sm font-normal text-gray-700 dark:text-gray-200",children:[u.jsx("span",{children:T(b.datum)||"tt.mm.jjjj"}),u.jsx(Ac,{className:"h-4 w-4 text-gray-500 dark:text-gray-400","aria-hidden":"true"})]}),rt&&u.jsxs("div",{className:"absolute left-0 top-full z-20 mt-2 w-80 rounded-xl border border-gray-200 bg-white p-3 shadow-2xl dark:border-gray-700 dark:bg-gray-900",children:[u.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[u.jsx("button",{type:"button",onClick:()=>p(G=>new Date(G.getFullYear(),G.getMonth()-1,1)),className:"rounded-lg p-2 text-gray-500 transition hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-white","aria-label":"Vorheriger Monat",children:u.jsx(Gm,{className:"h-4 w-4","aria-hidden":"true"})}),u.jsx("span",{className:"text-sm font-semibold capitalize text-gray-800 dark:text-gray-100",children:z}),u.jsx("button",{type:"button",onClick:()=>p(G=>new Date(G.getFullYear(),G.getMonth()+1,1)),className:"rounded-lg p-2 text-gray-500 transition hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-white","aria-label":"Nächster Monat",children:u.jsx(Jm,{className:"h-4 w-4","aria-hidden":"true"})})]}),u.jsx("div",{className:"grid grid-cols-7 gap-1 text-center text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400",children:cy.map((G,ms)=>u.jsx("span",{children:G},`${G}-${ms}`))}),u.jsx("div",{className:"mt-2 grid grid-cols-7 gap-1",children:K.map(G=>{const ms=G.isoValue===b.datum;return u.jsx("button",{type:"button",onClick:()=>_t(G.isoValue),className:`flex h-10 items-center justify-center rounded-lg text-sm transition ${ms?"bg-indigo-600 text-white":G.isCurrentMonth?"text-gray-800 hover:bg-gray-100 dark:text-gray-100 dark:hover:bg-gray-800":"text-gray-400 hover:bg-gray-100 dark:text-gray-600 dark:hover:bg-gray-800"}`,children:G.date.getDate()},G.key)})}),u.jsxs("div",{className:"mt-3 flex items-center justify-between border-t border-gray-200 pt-3 dark:border-gray-700",children:[u.jsx("button",{type:"button",onClick:sr,className:"rounded-lg bg-gray-100 px-3 py-2 text-sm font-medium text-gray-700 transition hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700",children:"Heute"}),u.jsx("button",{type:"button",onClick:tt,className:"rounded-lg bg-gray-100 px-3 py-2 text-sm font-medium text-gray-700 transition hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700",children:"Löschen"})]})]})]})]})}),u.jsx("th",{className:"px-6 py-3 text-sm font-semibold text-gray-700 dark:text-gray-200",children:u.jsx("div",{className:"flex items-center gap-3",children:u.jsxs("button",{type:"button",onClick:()=>A("result"),className:"inline-flex items-center gap-2 hover:text-gray-900 dark:hover:text-white transition",children:["Ergebnis",$("result")]})})}),u.jsx("th",{className:"px-6 py-3 text-sm font-semibold text-gray-700 dark:text-gray-200 text-right"})]})}),u.jsx("tbody",{children:U.length===0?u.jsx("tr",{className:"border-t border-gray-200 dark:border-gray-800",children:u.jsx("td",{colSpan:"4",className:"px-6 py-8 text-sm text-gray-500 dark:text-gray-400",children:Ge})}):U.map(G=>{const ug=!!n[G.id],_u=E(G),ga=l(G.patType,_u);return u.jsxs("tr",{className:"border-t border-gray-200 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/40",children:[u.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:u.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[u.jsx("span",{className:"font-semibold text-gray-900 dark:text-gray-100",children:G.name}),u.jsx("span",{className:`px-3 py-1 rounded-full text-xs font-semibold ${o(G.patType)}`,children:G.patType}),ug&&u.jsx("span",{className:"px-3 py-1 rounded-full text-xs font-semibold bg-sky-100 text-sky-800 dark:bg-sky-900/40 dark:text-sky-200",children:"Freigabe aktiv"}),G.isFinalized&&u.jsx("span",{className:"px-3 py-1 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-200",children:"Final abgeschlossen"})]})}),u.jsx("td",{className:"px-6 py-4 text-sm text-gray-600 dark:text-gray-300 whitespace-nowrap",children:u.jsxs("div",{className:"inline-flex items-center gap-2",children:[u.jsx(Ac,{className:"w-4 h-4","aria-hidden":"true"}),C(G.datum)]})}),u.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("span",{className:"text-xl font-bold text-green-600 dark:text-green-300",children:_u.toFixed(0)}),u.jsx("span",{className:`inline-flex px-2 py-1 rounded text-xs font-semibold ${ga.color} ${ga.text}`,children:ga.name})]})}),u.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx("button",{onClick:()=>i(G),className:"bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700 transition text-sm",children:"Öffnen"}),u.jsx("button",{onClick:cg=>{cg.stopPropagation(),a(G.id)},className:"text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 p-2",title:"Löschen",children:u.jsx(oy,{className:"w-5 h-5","aria-hidden":"true"})})]})})]},G.id)})})]})})]})};return u.jsx("div",{className:"min-h-screen bg-gradient-to-br from-green-50 to-blue-100 dark:from-gray-950 dark:to-gray-900 p-6 text-gray-900 dark:text-gray-100",children:u.jsxs("div",{className:"max-w-7xl mx-auto",children:[u.jsx("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-lg p-6 mb-6 border border-gray-100 dark:border-gray-800",children:u.jsxs("div",{className:"flex items-center justify-between mb-6",children:[u.jsx("h1",{className:"text-3xl font-bold text-gray-800 dark:text-gray-100",children:"PAT Test Manager"}),u.jsxs("div",{className:"relative",children:[u.jsxs("button",{onClick:()=>h(j=>!j),className:"bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition flex items-center justify-center gap-2",children:[u.jsx(ry,{className:"w-4 h-4"}),"Neue Bewertung"]}),d&&u.jsx("div",{className:"absolute right-0 top-full mt-2 w-48 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 shadow-lg z-10 overflow-hidden",children:_.map(j=>u.jsx("button",{type:"button",onClick:()=>{h(!1),s(j)},className:"w-full px-4 py-3 text-left text-sm font-medium text-gray-800 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-800 transition",children:j},j))})]})]})}),r&&u.jsx("div",{className:"mt-6",children:r}),t.length>0&&u.jsxs("div",{className:"space-y-6",children:[Me("open","Noch offene Bewertungen",Oe,x.length,"Keine offenen Bewertungen mit den aktuellen Suchfiltern gefunden"),Me("finalized","Abgeschlossene Bewertungen",bt,S.length,"Keine abgeschlossenen Bewertungen mit den aktuellen Suchfiltern gefunden")]}),t.length===0&&u.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-lg p-12 text-center border border-gray-100 dark:border-gray-800",children:[u.jsx(ly,{className:"w-16 h-16 mx-auto mb-4 text-gray-300 dark:text-gray-700","aria-hidden":"true"}),u.jsx("p",{className:"text-gray-600 dark:text-gray-300 mb-4",children:"Noch keine Bewertungen vorhanden"}),u.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Lege oben eine neue Bewertung an und wähle dabei PAT Start, PAT 1, PAT 2 oder PAT 3"})]})]})})},py=e=>String(e||"").replace(/\D/g,""),gy=(e,t=null)=>{var r;return t&&((r=e==null?void 0:e.subValueRanges)!=null&&r[t])?e.subValueRanges[t]:{minValue:e==null?void 0:e.minValue,maxValue:e==null?void 0:e.maxValue}},Cf=(e,t,r=null)=>{const n=py(t);if(!n)return"";const s=Number.parseInt(n,10),i=gy(e,r),a=Number.isFinite(i==null?void 0:i.minValue)?i.minValue:0,o=Number.isFinite(i==null?void 0:i.maxValue)?i.maxValue:null,l=o===null?Math.max(s,a):Math.min(Math.max(s,a),o);return String(l)},Fa=e=>`px-3 py-2 border border-gray-300 dark:border-gray-700 rounded text-center bg-white dark:bg-gray-900 ${e?"opacity-70 cursor-not-allowed bg-gray-100 dark:bg-gray-800":""}`,my=({exercise:e,exIndex:t,onChange:r,disabled:n=!1})=>{const s=(a,o=null)=>l=>{r(t,a,Cf(e,l.target.value,o),o)};if(e.subA&&e.subB){const[a="a)",o="b)"]=e.subLabels||[];return u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"grid grid-cols-5 gap-2 mb-2",children:[u.jsx("div",{}),u.jsx("div",{className:"font-semibold",children:a}),e.subA.map((l,c)=>u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",autoComplete:"off",value:l,onChange:s(c,"a"),disabled:n,className:Fa(n)},`a-${c}`))]}),u.jsxs("div",{className:"grid grid-cols-5 gap-2 mb-2",children:[u.jsx("div",{}),u.jsx("div",{className:"font-semibold",children:o}),e.subB.map((l,c)=>u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",autoComplete:"off",value:l,onChange:s(c,"b"),disabled:n,className:Fa(n)},`b-${c}`))]})]})}const i=e.values.length===4?"grid-cols-6":e.values.length===5?"grid-cols-7":"grid-cols-5";return u.jsxs("div",{className:`grid ${i} gap-2 mb-2`,children:[u.jsx("div",{}),u.jsx("div",{}),e.values.map((a,o)=>u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",autoComplete:"off",value:a,onChange:s(o),disabled:n,className:Fa(n)},o))]})},yy=({show:e,onSave:t,onDiscard:r,onCancel:n})=>e?u.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:u.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl p-6 max-w-md w-full mx-4 border border-gray-200 dark:border-gray-800",children:[u.jsx("h3",{className:"text-xl font-bold text-gray-800 dark:text-gray-100 mb-4",children:"Ungespeicherte Änderungen"}),u.jsx("p",{className:"text-gray-600 dark:text-gray-300 mb-6",children:"Sie haben ungespeicherte Änderungen. Möchten Sie diese speichern?"}),u.jsxs("div",{className:"flex gap-3",children:[u.jsx("button",{onClick:t,className:"flex-1 bg-green-600 text-white px-4 py-3 rounded-lg hover:bg-green-700 transition font-semibold",children:"Ja, speichern"}),u.jsx("button",{onClick:r,className:"flex-1 bg-red-600 text-white px-4 py-3 rounded-lg hover:bg-red-700 transition font-semibold",children:"Nein, verwerfen"}),u.jsx("button",{onClick:n,className:"flex-1 bg-gray-500 dark:bg-gray-700 text-white px-4 py-3 rounded-lg hover:bg-gray-600 dark:hover:bg-gray-600 transition font-semibold",children:"Abbrechen"})]})]})}):null,vy="modulepreload",wy=function(e){return"/"+e},Oc={},Rc=function(t,r,n){let s=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),o=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));s=Promise.allSettled(r.map(l=>{if(l=wy(l),l in Oc)return;Oc[l]=!0;const c=l.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${d}`))return;const h=document.createElement("link");if(h.rel=c?"stylesheet":vy,c||(h.as="script"),h.crossOrigin="",h.href=l,o&&h.setAttribute("nonce",o),document.head.appendChild(h),c)return new Promise((f,g)=>{h.addEventListener("load",f),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function i(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return s.then(a=>{for(const o of a||[])o.status==="rejected"&&i(o.reason);return t().catch(i)})},we=14,by=12,ii=22,ct=210-we*2,_y=we+10,Va=10.5,Ic=3,Af=e=>{if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}).format(t)},Wa=e=>(e||"pat-test").toLowerCase().replace(/[^a-z0-9-_]+/gi,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Fn=e=>e===""||e===null||typeof e>"u"?"—":String(e),Ha=(e,t=26)=>{const r=String(e||"—");return r.length>t?`${r.slice(0,t-1)}…`:r},$c="Versuch",xy=e=>18+(!!(e.subA&&e.subB)?30:21)+21,ky=e=>{var i;if(e.subA&&e.subB){const a=Math.max(e.subA.length,e.subB.length),o=[$c,...Array.from({length:a},(d,h)=>`${h+1}`)],l=32,c=(ct-l)/a;return{head:[o],body:[["a.)",...Array.from({length:a},(d,h)=>Fn(e.subA[h]))],["b.)",...Array.from({length:a},(d,h)=>Fn(e.subB[h]))]],columnStyles:{0:{cellWidth:l,halign:"center"},...Object.fromEntries(Array.from({length:a},(d,h)=>[h+1,{cellWidth:c,halign:"center"}]))}}}const t=((i=e.values)==null?void 0:i.length)||0,r=[$c,...Array.from({length:t},(a,o)=>`${o+1}`)],n=32,s=t>0?(ct-n)/t:ct-n;return{head:[r],body:[["Ist",...(e.values||[]).map(Fn)]],columnStyles:{0:{cellWidth:n,halign:"center"},...Object.fromEntries(Array.from({length:t},(a,o)=>[o+1,{cellWidth:s,halign:"center"}]))}}},Sy=e=>({head:[["Soll","Durchschnitt ist","Faktor","Punkte"]],body:[[Fn(e.soll),(e.durchschnitt||0).toFixed(2),Fn(e.faktor),(e.points||0).toFixed(0)]],columnStyles:{0:{cellWidth:ct/4,halign:"center"},1:{cellWidth:ct/4,halign:"center"},2:{cellWidth:ct/4,halign:"center"},3:{cellWidth:ct/4,halign:"center"}}}),Ey=({assessment:e,totalPoints:t,achievement:r})=>({head:[["Name","PAT Typ","Datum","Gesamtpunkte","Bewertung"]],body:[[e.name||"—",e.patType||"—",Af(e.datum),String(Math.round(t||0)),(r==null?void 0:r.name)||"—"]],columnStyles:{0:{cellWidth:42},1:{cellWidth:28},2:{cellWidth:34},3:{cellWidth:34,halign:"center"},4:{cellWidth:44}}}),jy=({assessment:e,achievement:t,pageNumber:r,pageCount:n})=>[`Name: ${Ha(e==null?void 0:e.name,20)}`,`PAT Typ: ${Ha(e==null?void 0:e.patType,14)}`,`Datum: ${Af(e==null?void 0:e.datum)}`,`Bewertung: ${Ha(t==null?void 0:t.name,18)}`,`Seite ${r}/${n}`],Ny=(e,t,r)=>{const n=e.internal.pageSize.getHeight();return t+r<=n-ii?t:(e.addPage(),_y)},Ty=(e,{assessment:t,achievement:r})=>{const n=e.getNumberOfPages(),s=e.internal.pageSize.getHeight(),i=e.internal.pageSize.getWidth(),a=s-8,o=[we,we+47,we+88,we+130,i-we];for(let l=1;l<=n;l+=1){const[c,d,h,f,g]=jy({assessment:t,achievement:r,pageNumber:l,pageCount:n});e.setPage(l),e.setDrawColor(226,232,240),e.setLineWidth(.3),e.line(we,a-4,i-we,a-4),e.setFont("helvetica","normal"),e.setFontSize(8.5),e.setTextColor(100,116,139),e.text(c,o[0],a),e.text(d,o[1],a),e.text(h,o[2],a),e.text(f,o[3],a),e.text(g,o[4],a,{align:"right"})}},Py=async({assessment:e,totalPoints:t,achievement:r})=>{if(!e)return;const[{jsPDF:n},{default:s}]=await Promise.all([Rc(()=>import("./jspdf.es.min-CzU92G48.js").then(o=>o.j),[]),Rc(()=>import("./jspdf.plugin.autotable-CyVc7Jkq.js"),[])]),i=new n({unit:"mm",format:"a4"});i.setFillColor(16,185,129),i.roundedRect(we,by,ct,18,4,4,"F"),i.setFont("helvetica","bold"),i.setFontSize(20),i.setTextColor(255,255,255),i.text("PAT Test Details",20,24),s(i,{startY:38,margin:{left:we,right:we,bottom:ii},theme:"grid",styles:{font:"helvetica",fontSize:Va,cellPadding:4,textColor:[31,41,55],lineColor:[226,232,240],lineWidth:.3},headStyles:{fillColor:[241,245,249],textColor:[71,85,105],fontStyle:"bold"},bodyStyles:{fillColor:[255,255,255]},tableWidth:ct,...Ey({assessment:e,totalPoints:t,achievement:r})}),(e.exercises||[]).forEach((o,l)=>{var d,h;const c=Ny(i,(((d=i.lastAutoTable)==null?void 0:d.finalY)||38)+8,xy(o));i.setFont("helvetica","bold"),i.setFontSize(14),i.setTextColor(17,24,39),i.text(o.name||`Übung ${l+1}`,we,c),s(i,{startY:c+4,margin:{left:we,right:we,bottom:ii},theme:"grid",styles:{font:"helvetica",fontSize:Va,cellPadding:Ic,halign:"center",textColor:[31,41,55],lineColor:[226,232,240],lineWidth:.3},headStyles:{fillColor:[239,246,255],textColor:[30,64,175],fontStyle:"bold",halign:"center"},bodyStyles:{fillColor:[255,255,255],halign:"center"},tableWidth:ct,pageBreak:"avoid",rowPageBreak:"avoid",...ky(o)}),s(i,{startY:(((h=i.lastAutoTable)==null?void 0:h.finalY)||c+4)+3,margin:{left:we,right:we,bottom:ii},theme:"grid",styles:{font:"helvetica",fontSize:Va,cellPadding:Ic,textColor:[31,41,55],lineColor:[226,232,240],lineWidth:.3},headStyles:{fillColor:[236,253,245],textColor:[6,95,70],fontStyle:"bold"},bodyStyles:{fillColor:[255,255,255],halign:"center"},didParseCell:({section:f,column:g,cell:w})=>{f==="body"&&g.index===3&&(w.styles.fillColor=[241,245,249])},tableWidth:ct,pageBreak:"avoid",rowPageBreak:"avoid",...Sy(o)})});const a=[Wa(e.name),Wa(e.patType),Wa(e.datum)].filter(Boolean).join("_");Ty(i,{assessment:e,achievement:r}),i.save(`${a||"pat-test"}.pdf`)},Cy=({currentAssessment:e,hasUnsavedChanges:t,onBack:r,onSave:n,onAssessmentChange:s,onUpdateExercise:i,onMarkDirty:a,showSaveDialog:o,onSaveAndExit:l,onDiscardAndExit:c,onCancelExit:d,getPatTypeColor:h,getAchievement:f,calculateTotal:g,isReadOnly:w=!1,canFinalize:v=!1,finalizeDisabledReason:b="",onFinalize:y,isShareActive:m=!1,canShare:p=!1,shareDisabledReason:_="",onShare:x,onRevokeShare:S})=>{if(!e)return null;const E=g(),k=f(e==null?void 0:e.patType,E),T=async()=>{await Py({assessment:e,totalPoints:E,achievement:k})};return u.jsx("div",{className:"min-h-screen bg-gray-100 dark:bg-gray-950 p-6 text-gray-900 dark:text-gray-100",children:u.jsxs("div",{className:"max-w-5xl mx-auto",children:[u.jsx(yy,{show:o,onSave:l,onDiscard:c,onCancel:d}),u.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-lg p-6 border border-gray-200 dark:border-gray-800",children:[u.jsxs("div",{className:"flex justify-between items-center mb-6",children:[u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx("button",{onClick:r,className:"text-gray-600 dark:text-gray-300 hover:text-gray-800 dark:hover:text-gray-100 font-medium",children:"← Zurück zur Übersicht"}),t&&u.jsx("span",{className:"text-orange-500 dark:text-orange-300 text-sm font-semibold",children:"● Ungespeicherte Änderungen"}),u.jsx("span",{className:`px-4 py-2 rounded-full text-sm font-semibold ${h(e==null?void 0:e.patType)}`,children:e==null?void 0:e.patType}),m&&u.jsx("span",{className:"px-4 py-2 rounded-full text-sm font-semibold bg-sky-100 text-sky-800 dark:bg-sky-900/40 dark:text-sky-200",children:"Freigabe aktiv"}),(e==null?void 0:e.isFinalized)&&u.jsx("span",{className:"px-4 py-2 rounded-full text-sm font-semibold bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-200",children:"Final abgeschlossen"})]}),u.jsxs("div",{className:"flex gap-2",children:[!w&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:n,className:"bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition flex items-center gap-2 text-sm",children:[u.jsx(ny,{className:"w-4 h-4","aria-hidden":"true"}),"Speichern"]}),u.jsxs("button",{onClick:y,disabled:!v,title:b||"Test final abschließen",className:`px-4 py-2 rounded-lg transition flex items-center gap-2 text-sm ${v?"bg-emerald-700 text-white hover:bg-emerald-800":"bg-gray-300 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed"}`,children:[u.jsx(Jo,{className:"w-4 h-4","aria-hidden":"true"}),"Final Abschließen"]})]}),u.jsxs("button",{onClick:T,className:"bg-amber-600 text-white px-4 py-2 rounded-lg hover:bg-amber-700 transition flex items-center gap-2 text-sm",children:[u.jsx(Ef,{className:"w-4 h-4","aria-hidden":"true"}),"PDF"]}),u.jsxs("button",{onClick:x,disabled:!p,title:_||"Test als Link teilen",className:`px-4 py-2 rounded-lg transition flex items-center gap-2 text-sm ${p?"bg-sky-600 text-white hover:bg-sky-700":"bg-gray-300 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed"}`,children:[u.jsx(sy,{className:"w-4 h-4","aria-hidden":"true"}),"Teilen"]}),m&&u.jsx("button",{onClick:S,className:"border border-rose-300 text-rose-700 dark:border-rose-700 dark:text-rose-300 px-4 py-2 rounded-lg hover:bg-rose-50 dark:hover:bg-rose-950/40 transition text-sm",children:"Freigabe aufheben"})]})]}),w&&u.jsxs("div",{className:"mb-6 rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/40 dark:text-emerald-200",children:[u.jsxs("div",{className:"flex items-center gap-2 font-semibold",children:[u.jsx(Zm,{className:"h-4 w-4","aria-hidden":"true"}),"Nur Lese-Modus"]}),u.jsx("p",{className:"mt-1 text-sm",children:"Diese Bewertung wurde final abgeschlossen und kann nicht mehr bearbeitet werden."})]}),u.jsxs("div",{className:"grid grid-cols-4 gap-2 mb-6 bg-gray-50 dark:bg-gray-800 p-4 rounded",children:[u.jsx("div",{className:"font-bold",children:"Datum / Name"}),u.jsx("div",{}),u.jsx("input",{type:"date",value:(e==null?void 0:e.datum)||"",disabled:w,onChange:C=>{s({...e,datum:C.target.value}),a()},className:`px-3 py-2 border border-gray-300 dark:border-gray-700 rounded bg-white dark:bg-gray-900 ${w?"opacity-70 cursor-not-allowed bg-gray-100 dark:bg-gray-800":""}`}),u.jsx("input",{type:"text",value:(e==null?void 0:e.name)||"",disabled:w,onChange:C=>{s({...e,name:C.target.value}),a()},placeholder:"Name",className:`px-3 py-2 border border-gray-300 dark:border-gray-700 rounded bg-white dark:bg-gray-900 ${w?"opacity-70 cursor-not-allowed bg-gray-100 dark:bg-gray-800":""}`})]}),e==null?void 0:e.exercises.map((C,z)=>u.jsxs("div",{className:"mb-6 border-b pb-4 border-gray-200 dark:border-gray-800",children:[u.jsx("div",{className:"font-bold text-lg mb-2 text-gray-700 dark:text-gray-200",children:C.name}),u.jsx(my,{exercise:C,exIndex:z,onChange:i,disabled:w}),u.jsxs("div",{className:"grid grid-cols-5 gap-2 mb-1 bg-blue-50 dark:bg-blue-900/30 p-2 rounded",children:[u.jsxs("div",{className:"font-semibold",children:["Durchschnitt Soll ",C.soll]}),u.jsx("div",{className:"font-semibold",children:"Ist"}),u.jsx("div",{className:"font-bold text-center",children:C.durchschnitt.toFixed(2)})]}),u.jsxs("div",{className:"grid grid-cols-5 gap-2 mb-1",children:[u.jsx("div",{children:"Faktor"}),u.jsx("div",{}),u.jsx("div",{className:"text-center font-semibold",children:C.faktor})]}),u.jsxs("div",{className:"grid grid-cols-5 gap-2 bg-green-50 dark:bg-green-900/30 p-2 rounded",children:[u.jsx("div",{className:"font-bold",children:"Points"}),u.jsx("div",{}),u.jsx("div",{className:"text-center font-bold text-green-600 dark:text-green-300",children:C.points.toFixed(0)})]})]},z)),u.jsxs("div",{className:"mt-6 bg-gradient-to-r from-green-100 to-blue-100 dark:from-gray-800 dark:to-gray-700 p-6 rounded-lg",children:[u.jsxs("div",{className:"flex justify-between items-center mb-4",children:[u.jsx("span",{className:"text-2xl font-bold text-gray-800 dark:text-gray-100",children:"Ergebnis"}),u.jsx("span",{className:"text-4xl font-bold text-green-600 dark:text-green-300",children:E.toFixed(0)})]}),u.jsxs("div",{className:`mt-4 px-6 py-4 rounded-lg ${k.color} ${k.text} text-center`,children:[u.jsx("p",{className:"text-2xl font-bold",children:k.name}),k.subtitle&&u.jsx("p",{className:"text-lg mt-2",children:k.subtitle})]})]})]})]})})},Of=e=>{let t=0,r=0;e.subA&&e.subB?[...e.subA,...e.subB].forEach(i=>{const a=parseFloat(i);isNaN(a)||(t+=a,r++)}):e.values.forEach(i=>{const a=parseFloat(i);isNaN(a)||(t+=a,r++)});const n=r>0?t/r:0,s=n*e.faktor;return{durchschnitt:n,points:s}},la=(e=[])=>e.reduce((t,r)=>t+(r.points||0),0),Yo=e=>({"PAT Start":"bg-green-100 text-green-800","PAT 1":"bg-blue-100 text-blue-800","PAT 2":"bg-purple-100 text-purple-800","PAT 3":"bg-orange-100 text-orange-800"})[e]||"bg-gray-100 text-gray-800",Xo=(e,t)=>{const r={"PAT Start":[{min:1e3,color:"bg-yellow-400",text:"text-black",name:"2. Schwarz-Weiss Sport WPA",subtitle:"Freizeit-Spieler"},{min:800,color:"bg-white",text:"text-black",name:"1. Weiss",subtitle:""},{min:600,color:"bg-gray-200",text:"text-gray-800",name:"PAT Start Teilnahme",subtitle:""},{min:0,color:"bg-gray-100",text:"text-gray-500",name:"Nicht bestanden",subtitle:""}],"PAT 1":[{min:1e3,color:"bg-green-700",text:"text-white",name:"4. Dunkelgrün",subtitle:"ca. Bezirksliga"},{min:800,color:"bg-green-300",text:"text-black",name:"3. Hellgrün",subtitle:"ca. Kreisliga"},{min:600,color:"bg-gray-200",text:"text-gray-800",name:"PAT 1 Teilnahme",subtitle:""},{min:0,color:"bg-gray-100",text:"text-gray-500",name:"Nicht bestanden",subtitle:""}],"PAT 2":[{min:1e3,color:"bg-blue-700",text:"text-white",name:"6. Dunkelblau",subtitle:"ca. Verbandsliga"},{min:800,color:"bg-blue-300",text:"text-black",name:"5. Hellblau",subtitle:"ca. Landesliga"},{min:600,color:"bg-gray-200",text:"text-gray-800",name:"PAT 2 Teilnahme",subtitle:""},{min:0,color:"bg-gray-100",text:"text-gray-500",name:"Nicht bestanden",subtitle:""}],"PAT 3":[{min:1e3,color:"bg-pink-400",text:"text-white",name:"10. Pink",subtitle:"Ein Weltstar!"},{min:850,color:"bg-yellow-400",text:"text-black",name:"9. Gold",subtitle:"internationaler Topsportler"},{min:700,color:"bg-red-600",text:"text-white",name:"8. Rot",subtitle:"ca. 1. Bundesliga"},{min:550,color:"bg-black",text:"text-white",name:"7. Schwarz",subtitle:"ca. 2. Bundesliga"},{min:0,color:"bg-gray-100",text:"text-gray-500",name:"Nicht bestanden",subtitle:""}]},n=r[e]||r["PAT Start"];return n.find(s=>t>=s.min)||n[n.length-1]},Is=(e,t=0)=>{const r=Number(e);return Number.isFinite(r)?r:t},xt=(e,t=4)=>{const r=10**t;return Math.round(e*r)/r},$i=e=>e.length?e.reduce((t,r)=>t+r,0)/e.length:0,Ay=e=>{if(e.length<=1)return 0;const t=$i(e),r=$i(e.map(n=>(n-t)**2));return Math.sqrt(r)},Oy=(e=[])=>[...e].sort((t,r)=>{const n=new Date((t==null?void 0:t.datum)||0).getTime(),s=new Date((r==null?void 0:r.datum)||0).getTime();if(n===s){const i=new Date((t==null?void 0:t.created_at)||0).getTime();return new Date((r==null?void 0:r.created_at)||0).getTime()-i}return s-n}),Ry=e=>!e||typeof e!="object"?[]:Array.isArray(e.subA)||Array.isArray(e.subB)?[...e.subA||[],...e.subB||[]].map(t=>Number(t)).filter(t=>Number.isFinite(t)):(e.values||[]).map(t=>Number(t)).filter(t=>Number.isFinite(t)),Iy=(e,t="zero")=>{if(!e)return t==="zero"?0:null;const r=Number(e.durchschnitt);if(Number.isFinite(r))return r;const n=Ry(e);return n.length?$i(n):t==="zero"?0:null},$y=e=>{if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}).format(t)},Rf=(e=[],t,r={})=>{const n=Is(r.windowSize,5),s=r.missingStrategy||"zero",a=Oy(e.filter(v=>(v==null?void 0:v.patType)===t)).slice(0,n);if(!a.length)return{windowedAssessments:[],exerciseMetrics:[],topWeaknesses:[],topStrengths:[],trendSeries:[],radarSeries:[],isLimitedData:!1,patType:t,windowSize:n};const o=a[0],l=(o==null?void 0:o.exercises)||[],c=Math.max(...l.map(v=>Is(v==null?void 0:v.faktor,0)),1),d=l.map((v,b)=>{const y=a.map(Oe=>{var $;const bt=($=Oe==null?void 0:Oe.exercises)==null?void 0:$[b],A=Iy(bt,s);return A===null?0:A}),m=$i(y),p=Is(v==null?void 0:v.soll,0),_=Is(v==null?void 0:v.faktor,0),x=p>0?p:1,S=Math.max(0,(p-m)/x),E=c>0?_/c:0,k=Math.min(1,Ay(y)/x),T=S*E*(1+k),C=Math.max(0,(m-p)/x),z=1-k,K=C*E*Math.max(z,.1),Y=y[0]||0,Ne=y[y.length-1]||0,It=Y-Ne;return{index:b,name:(v==null?void 0:v.name)||`Übung ${b+1}`,soll:p,factor:_,actualMean:xt(m,4),latestActual:xt(Y,4),trendDelta:xt(It,4),gapScore:xt(S,4),consistencyScore:xt(k,4),priorityScore:xt(T,4),strengthScore:xt(K,4),actualSeries:y.map(Oe=>xt(Oe,4))}}),h=[...d].sort((v,b)=>b.priorityScore-v.priorityScore).slice(0,3),f=[...d].sort((v,b)=>b.strengthScore-v.strengthScore).slice(0,3),g=[...a].reverse().map(v=>({assessmentId:v.id,datum:v.datum,label:$y(v.datum),totalPoints:Math.round(la(v.exercises||[]))})),w=[...d].sort((v,b)=>b.factor-v.factor).slice(0,6).map(v=>({name:v.name,soll:v.soll,actual:v.actualMean,ratio:v.soll>0?xt(Math.min(1.2,v.actualMean/v.soll),4):0,priorityScore:v.priorityScore}));return{windowedAssessments:a,exerciseMetrics:d,topWeaknesses:h,topStrengths:f,trendSeries:g,radarSeries:w,isLimitedData:a.length=0;o--)(a=e[o])&&(i=(s<3?a(i):s>3?a(t,r,i):a(t,r))||i);return s>3&&i&&Object.defineProperty(t,r,i),i}function Df(e,t){return function(r,n){t(r,n,e)}}function Lf(e,t,r,n,s,i){function a(y){if(y!==void 0&&typeof y!="function")throw new TypeError("Function expected");return y}for(var o=n.kind,l=o==="getter"?"get":o==="setter"?"set":"value",c=!t&&e?n.static?e:e.prototype:null,d=t||(c?Object.getOwnPropertyDescriptor(c,n.name):{}),h,f=!1,g=r.length-1;g>=0;g--){var w={};for(var v in n)w[v]=v==="access"?{}:n[v];for(var v in n.access)w.access[v]=n.access[v];w.addInitializer=function(y){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(a(y||null))};var b=(0,r[g])(o==="accessor"?{get:d.get,set:d.set}:d[l],w);if(o==="accessor"){if(b===void 0)continue;if(b===null||typeof b!="object")throw new TypeError("Object expected");(h=a(b.get))&&(d.get=h),(h=a(b.set))&&(d.set=h),(h=a(b.init))&&s.unshift(h)}else(h=a(b))&&(o==="field"?s.unshift(h):d[l]=h)}c&&Object.defineProperty(c,n.name,d),f=!0}function zf(e,t,r){for(var n=arguments.length>2,s=0;s0&&i[i.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function du(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,i=[],a;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)i.push(s.value)}catch(o){a={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i}function Wf(){for(var e=[],t=0;t1||l(g,v)})},w&&(s[g]=w(s[g])))}function l(g,w){try{c(n[g](w))}catch(v){f(i[0][3],v)}}function c(g){g.value instanceof cn?Promise.resolve(g.value.v).then(d,h):f(i[0][2],g)}function d(g){l("next",g)}function h(g){l("throw",g)}function f(g,w){g(w),i.shift(),i.length&&l(i[0][0],i[0][1])}}function Gf(e){var t,r;return t={},n("next"),n("throw",function(s){throw s}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(s,i){t[s]=e[s]?function(a){return(r=!r)?{value:cn(e[s](a)),done:!1}:i?i(a):a}:i}}function Jf(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof zi=="function"?zi(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(i){r[i]=e[i]&&function(a){return new Promise(function(o,l){a=e[i](a),s(o,l,a.done,a.value)})}}function s(i,a,o,l){Promise.resolve(l).then(function(c){i({value:c,done:o})},a)}}function Qf(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var Dy=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t},el=function(e){return el=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},el(e)};function Yf(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=el(e),n=0;ne?(...t)=>e(...t):(...t)=>fetch(...t);let ca=class extends Error{constructor(t,r="FunctionsError",n){super(t),this.name=r,this.context=n}},ip=class extends ca{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}},tl=class extends ca{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}},rl=class extends ca{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}};var Ui;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(Ui||(Ui={}));class By{constructor(t,{headers:r={},customFetch:n,region:s=Ui.Any}={}){this.url=t,this.headers=r,this.region=s,this.fetch=My(n)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t){return R(this,arguments,void 0,function*(r,n={}){var s;let i,a;try{const{headers:o,method:l,body:c,signal:d,timeout:h}=n;let f={},{region:g}=n;g||(g=this.region);const w=new URL(`${this.url}/${r}`);g&&g!=="any"&&(f["x-region"]=g,w.searchParams.set("forceFunctionRegion",g));let v;c&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",v=c):typeof c=="string"?(f["Content-Type"]="text/plain",v=c):typeof FormData<"u"&&c instanceof FormData?v=c:(f["Content-Type"]="application/json",v=JSON.stringify(c)):v=c;let b=d;h&&(a=new AbortController,i=setTimeout(()=>a.abort(),h),d?(b=a.signal,d.addEventListener("abort",()=>a.abort())):b=a.signal);const y=yield this.fetch(w.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),o),body:v,signal:b}).catch(x=>{throw new ip(x)}),m=y.headers.get("x-relay-error");if(m&&m==="true")throw new tl(y);if(!y.ok)throw new rl(y);let p=((s=y.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),_;return p==="application/json"?_=yield y.json():p==="application/octet-stream"||p==="application/pdf"?_=yield y.blob():p==="text/event-stream"?_=y:p==="multipart/form-data"?_=yield y.formData():_=yield y.text(),{data:_,error:null,response:y}}catch(o){return{data:null,error:o,response:o instanceof rl||o instanceof tl?o.context:void 0}}finally{i&&clearTimeout(i)}})}}const Fy=Object.freeze(Object.defineProperty({__proto__:null,get FunctionRegion(){return Ui},FunctionsClient:By,FunctionsError:ca,FunctionsFetchError:ip,FunctionsHttpError:rl,FunctionsRelayError:tl},Symbol.toStringTag,{value:"Module"})),ap=ls(Fy);var Ee={};const yn=ls(Uy);var $s={},Ds={},Ls={},zs={},Us={},Ms={},Dc;function op(){if(Dc)return Ms;Dc=1,Object.defineProperty(Ms,"__esModule",{value:!0});class e extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.code=r.code}}return Ms.default=e,Ms}var Lc;function lp(){if(Lc)return Us;Lc=1,Object.defineProperty(Us,"__esModule",{value:!0});const t=yn.__importDefault(op());let r=class{constructor(s){var i,a;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new Headers(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(i=s.shouldThrowOnError)!==null&&i!==void 0?i:!1,this.signal=s.signal,this.isMaybeSingle=(a=s.isMaybeSingle)!==null&&a!==void 0?a:!1,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,i){return this.headers=new Headers(this.headers),this.headers.set(s,i),this}then(s,i){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");const a=this.fetch;let o=a(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async l=>{var c,d,h,f;let g=null,w=null,v=null,b=l.status,y=l.statusText;if(l.ok){if(this.method!=="HEAD"){const x=await l.text();x===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((c=this.headers.get("Accept"))===null||c===void 0)&&c.includes("application/vnd.pgrst.plan+text"))?w=x:w=JSON.parse(x))}const p=(d=this.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),_=(h=l.headers.get("content-range"))===null||h===void 0?void 0:h.split("/");p&&_&&_.length>1&&(v=parseInt(_[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(w)&&(w.length>1?(g={code:"PGRST116",details:`Results contain ${w.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},w=null,v=null,b=406,y="Not Acceptable"):w.length===1?w=w[0]:w=null)}else{const p=await l.text();try{g=JSON.parse(p),Array.isArray(g)&&l.status===404&&(w=[],g=null,b=200,y="OK")}catch{l.status===404&&p===""?(b=204,y="No Content"):g={message:p}}if(g&&this.isMaybeSingle&&(!((f=g==null?void 0:g.details)===null||f===void 0)&&f.includes("0 rows"))&&(g=null,b=200,y="OK"),g&&this.shouldThrowOnError)throw new t.default(g)}return{error:g,data:w,count:v,status:b,statusText:y}});return this.shouldThrowOnError||(o=o.catch(l=>{var c,d,h,f,g,w;let v="";const b=l==null?void 0:l.cause;if(b){const y=(c=b==null?void 0:b.message)!==null&&c!==void 0?c:"",m=(d=b==null?void 0:b.code)!==null&&d!==void 0?d:"";v=`${(h=l==null?void 0:l.name)!==null&&h!==void 0?h:"FetchError"}: ${l==null?void 0:l.message}`,v+=` Caused by: ${(f=b==null?void 0:b.name)!==null&&f!==void 0?f:"Error"}: ${y}`,m&&(v+=` (${m})`),b!=null&&b.stack&&(v+=` ${b.stack}`)}else v=(g=l==null?void 0:l.stack)!==null&&g!==void 0?g:"";return{error:{message:`${(w=l==null?void 0:l.name)!==null&&w!==void 0?w:"FetchError"}: ${l==null?void 0:l.message}`,details:v,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),o.then(s,i)}returns(){return this}overrideTypes(){return this}};return Us.default=r,Us}var zc;function up(){if(zc)return zs;zc=1,Object.defineProperty(zs,"__esModule",{value:!0});const t=yn.__importDefault(lp());let r=class extends t.default{select(s){let i=!1;const a=(s??"*").split("").map(o=>/\s/.test(o)&&!i?"":(o==='"'&&(i=!i),o)).join("");return this.url.searchParams.set("select",a),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:i=!0,nullsFirst:a,foreignTable:o,referencedTable:l=o}={}){const c=l?`${l}.order`:"order",d=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${d?`${d},`:""}${s}.${i?"asc":"desc"}${a===void 0?"":a?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:i,referencedTable:a=i}={}){const o=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(o,`${s}`),this}range(s,i,{foreignTable:a,referencedTable:o=a}={}){const l=typeof o>"u"?"offset":`${o}.offset`,c=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(l,`${s}`),this.url.searchParams.set(c,`${i-s+1}`),this}abortSignal(s){return this.signal=s,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),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:s=!1,verbose:i=!1,settings:a=!1,buffers:o=!1,wal:l=!1,format:c="text"}={}){var d;const h=[s?"analyze":null,i?"verbose":null,a?"settings":null,o?"buffers":null,l?"wal":null].filter(Boolean).join("|"),f=(d=this.headers.get("Accept"))!==null&&d!==void 0?d:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${c}; for="${f}"; options=${h};`),c==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}};return zs.default=r,zs}var Uc;function hu(){if(Uc)return Ls;Uc=1,Object.defineProperty(Ls,"__esModule",{value:!0});const t=yn.__importDefault(up()),r=new RegExp("[,()]");let n=class extends t.default{eq(i,a){return this.url.searchParams.append(i,`eq.${a}`),this}neq(i,a){return this.url.searchParams.append(i,`neq.${a}`),this}gt(i,a){return this.url.searchParams.append(i,`gt.${a}`),this}gte(i,a){return this.url.searchParams.append(i,`gte.${a}`),this}lt(i,a){return this.url.searchParams.append(i,`lt.${a}`),this}lte(i,a){return this.url.searchParams.append(i,`lte.${a}`),this}like(i,a){return this.url.searchParams.append(i,`like.${a}`),this}likeAllOf(i,a){return this.url.searchParams.append(i,`like(all).{${a.join(",")}}`),this}likeAnyOf(i,a){return this.url.searchParams.append(i,`like(any).{${a.join(",")}}`),this}ilike(i,a){return this.url.searchParams.append(i,`ilike.${a}`),this}ilikeAllOf(i,a){return this.url.searchParams.append(i,`ilike(all).{${a.join(",")}}`),this}ilikeAnyOf(i,a){return this.url.searchParams.append(i,`ilike(any).{${a.join(",")}}`),this}regexMatch(i,a){return this.url.searchParams.append(i,`match.${a}`),this}regexIMatch(i,a){return this.url.searchParams.append(i,`imatch.${a}`),this}is(i,a){return this.url.searchParams.append(i,`is.${a}`),this}isDistinct(i,a){return this.url.searchParams.append(i,`isdistinct.${a}`),this}in(i,a){const o=Array.from(new Set(a)).map(l=>typeof l=="string"&&r.test(l)?`"${l}"`:`${l}`).join(",");return this.url.searchParams.append(i,`in.(${o})`),this}contains(i,a){return typeof a=="string"?this.url.searchParams.append(i,`cs.${a}`):Array.isArray(a)?this.url.searchParams.append(i,`cs.{${a.join(",")}}`):this.url.searchParams.append(i,`cs.${JSON.stringify(a)}`),this}containedBy(i,a){return typeof a=="string"?this.url.searchParams.append(i,`cd.${a}`):Array.isArray(a)?this.url.searchParams.append(i,`cd.{${a.join(",")}}`):this.url.searchParams.append(i,`cd.${JSON.stringify(a)}`),this}rangeGt(i,a){return this.url.searchParams.append(i,`sr.${a}`),this}rangeGte(i,a){return this.url.searchParams.append(i,`nxl.${a}`),this}rangeLt(i,a){return this.url.searchParams.append(i,`sl.${a}`),this}rangeLte(i,a){return this.url.searchParams.append(i,`nxr.${a}`),this}rangeAdjacent(i,a){return this.url.searchParams.append(i,`adj.${a}`),this}overlaps(i,a){return typeof a=="string"?this.url.searchParams.append(i,`ov.${a}`):this.url.searchParams.append(i,`ov.{${a.join(",")}}`),this}textSearch(i,a,{config:o,type:l}={}){let c="";l==="plain"?c="pl":l==="phrase"?c="ph":l==="websearch"&&(c="w");const d=o===void 0?"":`(${o})`;return this.url.searchParams.append(i,`${c}fts${d}.${a}`),this}match(i){return Object.entries(i).forEach(([a,o])=>{this.url.searchParams.append(a,`eq.${o}`)}),this}not(i,a,o){return this.url.searchParams.append(i,`not.${a}.${o}`),this}or(i,{foreignTable:a,referencedTable:o=a}={}){const l=o?`${o}.or`:"or";return this.url.searchParams.append(l,`(${i})`),this}filter(i,a,o){return this.url.searchParams.append(i,`${a}.${o}`),this}};return Ls.default=n,Ls}var Mc;function cp(){if(Mc)return Ds;Mc=1,Object.defineProperty(Ds,"__esModule",{value:!0});const t=yn.__importDefault(hu());let r=class{constructor(s,{headers:i={},schema:a,fetch:o}){this.url=s,this.headers=new Headers(i),this.schema=a,this.fetch=o}select(s,i){const{head:a=!1,count:o}=i??{},l=a?"HEAD":"GET";let c=!1;const d=(s??"*").split("").map(h=>/\s/.test(h)&&!c?"":(h==='"'&&(c=!c),h)).join("");return this.url.searchParams.set("select",d),o&&this.headers.append("Prefer",`count=${o}`),new t.default({method:l,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(s,{count:i,defaultToNull:a=!0}={}){var o;const l="POST";if(i&&this.headers.append("Prefer",`count=${i}`),a||this.headers.append("Prefer","missing=default"),Array.isArray(s)){const c=s.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(c.length>0){const d=[...new Set(c)].map(h=>`"${h}"`);this.url.searchParams.set("columns",d.join(","))}}return new t.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}upsert(s,{onConflict:i,ignoreDuplicates:a=!1,count:o,defaultToNull:l=!0}={}){var c;const d="POST";if(this.headers.append("Prefer",`resolution=${a?"ignore":"merge"}-duplicates`),i!==void 0&&this.url.searchParams.set("on_conflict",i),o&&this.headers.append("Prefer",`count=${o}`),l||this.headers.append("Prefer","missing=default"),Array.isArray(s)){const h=s.reduce((f,g)=>f.concat(Object.keys(g)),[]);if(h.length>0){const f=[...new Set(h)].map(g=>`"${g}"`);this.url.searchParams.set("columns",f.join(","))}}return new t.default({method:d,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(c=this.fetch)!==null&&c!==void 0?c:fetch})}update(s,{count:i}={}){var a;const o="PATCH";return i&&this.headers.append("Prefer",`count=${i}`),new t.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}delete({count:s}={}){var i;const a="DELETE";return s&&this.headers.append("Prefer",`count=${s}`),new t.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}};return Ds.default=r,Ds}var Bc;function Vy(){if(Bc)return $s;Bc=1,Object.defineProperty($s,"__esModule",{value:!0});const e=yn,t=e.__importDefault(cp()),r=e.__importDefault(hu());let n=class dp{constructor(i,{headers:a={},schema:o,fetch:l}={}){this.url=i,this.headers=new Headers(a),this.schemaName=o,this.fetch=l}from(i){if(!i||typeof i!="string"||i.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");const a=new URL(`${this.url}/${i}`);return new t.default(a,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(i){return new dp(this.url,{headers:this.headers,schema:i,fetch:this.fetch})}rpc(i,a={},{head:o=!1,get:l=!1,count:c}={}){var d;let h;const f=new URL(`${this.url}/rpc/${i}`);let g;o||l?(h=o?"HEAD":"GET",Object.entries(a).filter(([v,b])=>b!==void 0).map(([v,b])=>[v,Array.isArray(b)?`{${b.join(",")}}`:`${b}`]).forEach(([v,b])=>{f.searchParams.append(v,b)})):(h="POST",g=a);const w=new Headers(this.headers);return c&&w.set("Prefer",`count=${c}`),new r.default({method:h,url:f,headers:w,schema:this.schemaName,body:g,fetch:(d=this.fetch)!==null&&d!==void 0?d:fetch})}};return $s.default=n,$s}Object.defineProperty(Ee,"__esModule",{value:!0});Ee.PostgrestError=Ee.PostgrestBuilder=Ee.PostgrestTransformBuilder=Ee.PostgrestFilterBuilder=Ee.PostgrestQueryBuilder=Ee.PostgrestClient=void 0;const vn=yn,hp=vn.__importDefault(Vy());Ee.PostgrestClient=hp.default;const fp=vn.__importDefault(cp());Ee.PostgrestQueryBuilder=fp.default;const pp=vn.__importDefault(hu());Ee.PostgrestFilterBuilder=pp.default;const gp=vn.__importDefault(up());Ee.PostgrestTransformBuilder=gp.default;const mp=vn.__importDefault(lp());Ee.PostgrestBuilder=mp.default;const yp=vn.__importDefault(op());Ee.PostgrestError=yp.default;Ee.default={PostgrestClient:hp.default,PostgrestQueryBuilder:fp.default,PostgrestFilterBuilder:pp.default,PostgrestTransformBuilder:gp.default,PostgrestBuilder:mp.default,PostgrestError:yp.default};class vp{constructor(){}static detectEnvironment(){var t;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.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"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.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."};if(typeof process<"u"){const r=process.versions;if(r&&r.node){const n=r.node,s=parseInt(n.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: import ws from "ws" new RealtimeClient(url, { transport: ws })`}}}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 t=this.detectEnvironment();if(t.constructor)return t.constructor;let r=t.error||"WebSocket not supported in this environment.";throw t.workaround&&(r+=` Suggested solution: ${t.workaround}`),new Error(r)}static createWebSocket(t,r){const n=this.getWebSocketConstructor();return new n(t,r)}static isWebSocketSupported(){try{const t=this.detectEnvironment();return t.type==="native"||t.type==="ws"}catch{return!1}}}const Wy="2.86.2",Hy=`realtime-js/${Wy}`,wp="1.0.0",Ky="2.0.0",Fc=wp,nl=1e4,qy=1e3,Gy=100;var hr;(function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"})(hr||(hr={}));var le;(function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"})(le||(le={}));var lt;(function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"})(lt||(lt={}));var sl;(function(e){e.websocket="websocket"})(sl||(sl={}));var fr;(function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"})(fr||(fr={}));class Jy{constructor(t){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=t??[]}encode(t,r){if(t.event===this.BROADCAST_EVENT&&!(t.payload instanceof ArrayBuffer)&&typeof t.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(t));let n=[t.join_ref,t.ref,t.topic,t.event,t.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(t){var r;return this._isArrayBuffer((r=t.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(t):this._encodeJsonUserBroadcastPush(t)}_encodeBinaryUserBroadcastPush(t){var r,n;const s=(n=(r=t.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(t,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(t){var r,n;const s=(n=(r=t.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},a=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(t,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(t,r,n){var s,i;const a=t.topic,o=(s=t.ref)!==null&&s!==void 0?s:"",l=(i=t.join_ref)!==null&&i!==void 0?i:"",c=t.payload.event,d=this.allowedMetadataKeys?this._pick(t.payload,this.allowedMetadataKeys):{},h=Object.keys(d).length===0?"":JSON.stringify(d);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const f=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+o.length+a.length+c.length+h.length,g=new ArrayBuffer(this.HEADER_LENGTH+f);let w=new DataView(g),v=0;w.setUint8(v++,this.KINDS.userBroadcastPush),w.setUint8(v++,l.length),w.setUint8(v++,o.length),w.setUint8(v++,a.length),w.setUint8(v++,c.length),w.setUint8(v++,h.length),w.setUint8(v++,r),Array.from(l,y=>w.setUint8(v++,y.charCodeAt(0))),Array.from(o,y=>w.setUint8(v++,y.charCodeAt(0))),Array.from(a,y=>w.setUint8(v++,y.charCodeAt(0))),Array.from(c,y=>w.setUint8(v++,y.charCodeAt(0))),Array.from(h,y=>w.setUint8(v++,y.charCodeAt(0)));var b=new Uint8Array(g.byteLength+n.byteLength);return b.set(new Uint8Array(g),0),b.set(new Uint8Array(n),g.byteLength),b.buffer}decode(t,r){if(this._isArrayBuffer(t)){let n=this._binaryDecode(t);return r(n)}if(typeof t=="string"){const n=JSON.parse(t),[s,i,a,o,l]=n;return r({join_ref:s,ref:i,topic:a,event:o,payload:l})}return r({})}_binaryDecode(t){const r=new DataView(t),n=r.getUint8(0),s=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(t,r,s)}}_decodeUserBroadcast(t,r,n){const s=r.getUint8(1),i=r.getUint8(2),a=r.getUint8(3),o=r.getUint8(4);let l=this.HEADER_LENGTH+4;const c=n.decode(t.slice(l,l+s));l=l+s;const d=n.decode(t.slice(l,l+i));l=l+i;const h=n.decode(t.slice(l,l+a));l=l+a;const f=t.slice(l,t.byteLength),g=o===this.JSON_ENCODING?JSON.parse(n.decode(f)):f,w={type:this.BROADCAST_EVENT,event:d,payload:g};return a>0&&(w.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:w}}_isArrayBuffer(t){var r;return t instanceof ArrayBuffer||((r=t==null?void 0:t.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(t,r){return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(([n])=>r.includes(n)))}}class bp{constructor(t,r){this.callback=t,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var J;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(J||(J={}));const Vc=(e,t,r={})=>{var n;const s=(n=r.skipTypes)!==null&&n!==void 0?n:[];return t?Object.keys(t).reduce((i,a)=>(i[a]=Qy(a,e,t,s),i),{}):{}},Qy=(e,t,r,n)=>{const s=t.find(o=>o.name===e),i=s==null?void 0:s.type,a=r[e];return i&&!n.includes(i)?_p(i,a):il(a)},_p=(e,t)=>{if(e.charAt(0)==="_"){const r=e.slice(1,e.length);return ev(t,r)}switch(e){case J.bool:return Yy(t);case J.float4:case J.float8:case J.int2:case J.int4:case J.int8:case J.numeric:case J.oid:return Xy(t);case J.json:case J.jsonb:return Zy(t);case J.timestamp:return tv(t);case J.abstime:case J.date:case J.daterange:case J.int4range:case J.int8range:case J.money:case J.reltime:case J.text:case J.time:case J.timestamptz:case J.timetz:case J.tsrange:case J.tstzrange:return il(t);default:return il(t)}},il=e=>e,Yy=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Xy=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},Zy=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},ev=(e,t)=>{if(typeof e!="string")return e;const r=e.length-1,n=e[r];if(e[0]==="{"&&n==="}"){let i;const a=e.slice(1,r);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(o=>_p(t,o))}return e},tv=e=>typeof e=="string"?e.replace(" ","T"):e,xp=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),t.pathname===""||t.pathname==="/"?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class Ka{constructor(t,r,n={},s=nl){this.channel=t,this.event=r,this.payload=n,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,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()}))}updatePayload(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,r){var n;return this._hasReceived(t)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:t,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(r))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var al;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(al||(al={}));let kp=class ai{constructor(t,r){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},s=>{const{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ai.syncState(this.state,s,i,a),this.pendingDiffs.forEach(l=>{this.state=ai.syncDiff(this.state,l,i,a)}),this.pendingDiffs=[],o()}),this.channel._on(n.diff,{},s=>{const{onJoin:i,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=ai.syncDiff(this.state,s,i,a),o())}),this.onJoin((s,i,a)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:a})}),this.onLeave((s,i,a)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:a})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,r,n,s){const i=this.cloneDeep(t),a=this.transformState(r),o={},l={};return this.map(i,(c,d)=>{a[c]||(l[c]=d)}),this.map(a,(c,d)=>{const h=i[c];if(h){const f=d.map(b=>b.presence_ref),g=h.map(b=>b.presence_ref),w=d.filter(b=>g.indexOf(b.presence_ref)<0),v=h.filter(b=>f.indexOf(b.presence_ref)<0);w.length>0&&(o[c]=w),v.length>0&&(l[c]=v)}else o[c]=d}),this.syncDiff(i,{joins:o,leaves:l},n,s)}static syncDiff(t,r,n,s){const{joins:i,leaves:a}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),s||(s=()=>{}),this.map(i,(o,l)=>{var c;const d=(c=t[o])!==null&&c!==void 0?c:[];if(t[o]=this.cloneDeep(l),d.length>0){const h=t[o].map(g=>g.presence_ref),f=d.filter(g=>h.indexOf(g.presence_ref)<0);t[o].unshift(...f)}n(o,d,l)}),this.map(a,(o,l)=>{let c=t[o];if(!c)return;const d=l.map(h=>h.presence_ref);c=c.filter(h=>d.indexOf(h.presence_ref)<0),t[o]=c,s(o,c,l),c.length===0&&delete t[o]}),t}static map(t,r){return Object.getOwnPropertyNames(t).map(n=>r(n,t[n]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((r,n)=>{const s=t[n];return"metas"in s?r[n]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=s,r},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var ol;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(ol||(ol={}));var en;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(en||(en={}));var mt;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(mt||(mt={}));const rv=le;let Sp=class Ep{constructor(t,r={config:{}},n){var s,i;if(this.topic=t,this.params=r,this.socket=n,this.bindings={},this.state=le.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.timeout=this.socket.timeout,this.joinPush=new Ka(this,lt.join,this.params,this.timeout),this.rejoinTimer=new bp(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=le.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=le.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=le.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=le.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=le.errored,this.rejoinTimer.scheduleTimeout())}),this._on(lt.reply,{},(a,o)=>{this._trigger(this._replyEventName(o),a)}),this.presence=new kp(this),this.broadcastEndpointURL=xp(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(t,r=this.timeout){var n,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==le.closed){const{config:{broadcast:a,presence:o,private:l}}=this.params,c=(s=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(g=>g.filter))!==null&&s!==void 0?s:[],d=!!this.bindings[en.PRESENCE]&&this.bindings[en.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},f={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:d}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(g=>t==null?void 0:t(mt.CHANNEL_ERROR,g)),this._onClose(()=>t==null?void 0:t(mt.CLOSED)),this.updateJoinPayload(Object.assign({config:f},h)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:g})=>{var w;if(this.socket.setAuth(),g===void 0){t==null||t(mt.SUBSCRIBED);return}else{const v=this.bindings.postgres_changes,b=(w=v==null?void 0:v.length)!==null&&w!==void 0?w:0,y=[];for(let m=0;m{this.state=le.errored,t==null||t(mt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(g).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(mt.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,r={}){return await this.send({type:"presence",event:"track",payload:t},r.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,r,n){return this.state===le.joined&&t===en.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(t,r,n)}async httpSend(t,r,n={}){var s;const i=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(r==null)return Promise.reject("Payload is required for httpSend()");const a={method:"POST",headers:{Authorization:i,apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:t,payload:r,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=n.timeout)!==null&&s!==void 0?s:this.timeout);if(o.status===202)return{success:!0};let l=o.statusText;try{const c=await o.json();l=c.error||c.message||l}catch{}return Promise.reject(new Error(l))}async send(t,r={}){var n,s;if(!this._canPush()&&t.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:a}=t,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((s=c.body)===null||s===void 0?void 0:s.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,o,l;const c=this._push(t.type,t,r.timeout||this.timeout);t.type==="broadcast"&&!(!((l=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=le.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(lt.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(s=>{n=new Ka(this,lt.leave,{},t),n.receive("ok",()=>{r(),s("ok")}).receive("timeout",()=>{r(),s("timed out")}).receive("error",()=>{s("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{n==null||n.destroy()})}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=le.closed,this.bindings={}}async _fetchWithTimeout(t,r,n){const s=new AbortController,i=setTimeout(()=>s.abort(),n),a=await this.socket.fetch(t,Object.assign(Object.assign({},r),{signal:s.signal}));return clearTimeout(i),a}_push(t,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new Ka(this,t,r,n);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(t){if(t.startTimeout(),this.pushBuffer.push(t),this.pushBuffer.length>Gy){const r=this.pushBuffer.shift();r&&(r.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${r.event}`,r.payload))}}_onMessage(t,r,n){return r}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,r,n){var s,i;const a=t.toLocaleLowerCase(),{close:o,error:l,leave:c,join:d}=lt;if(n&&[o,l,c,d].indexOf(a)>=0&&n!==this._joinRef())return;let f=this._onMessage(a,r,n);if(r&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(g=>{var w,v,b;return((w=g.filter)===null||w===void 0?void 0:w.event)==="*"||((b=(v=g.filter)===null||v===void 0?void 0:v.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===a}).map(g=>g.callback(f,n)):(i=this.bindings[a])===null||i===void 0||i.filter(g=>{var w,v,b,y,m,p;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in g){const _=g.id,x=(w=g.filter)===null||w===void 0?void 0:w.event;return _&&((v=r.ids)===null||v===void 0?void 0:v.includes(_))&&(x==="*"||(x==null?void 0:x.toLocaleLowerCase())===((b=r.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{const _=(m=(y=g==null?void 0:g.filter)===null||y===void 0?void 0:y.event)===null||m===void 0?void 0:m.toLocaleLowerCase();return _==="*"||_===((p=r==null?void 0:r.event)===null||p===void 0?void 0:p.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===a}).map(g=>{if(typeof f=="object"&&"ids"in f){const w=f.data,{schema:v,table:b,commit_timestamp:y,type:m,errors:p}=w;f=Object.assign(Object.assign({},{schema:v,table:b,commit_timestamp:y,eventType:m,new:{},old:{},errors:p}),this._getPayloadRecords(w))}g.callback(f,n)})}_isClosed(){return this.state===le.closed}_isJoined(){return this.state===le.joined}_isJoining(){return this.state===le.joining}_isLeaving(){return this.state===le.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,r,n){const s=t.toLocaleLowerCase(),i={type:s,filter:r,callback:n};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(t,r){const n=t.toLocaleLowerCase();return this.bindings[n]&&(this.bindings[n]=this.bindings[n].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&Ep.isEqual(s.filter,r))})),this}static isEqual(t,r){if(Object.keys(t).length!==Object.keys(r).length)return!1;for(const n in t)if(t[n]!==r[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(lt.close,{},t)}_onError(t){this._on(lt.error,{},r=>t(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=le.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const r={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(r.new=Vc(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(r.old=Vc(t.columns,t.old_record)),r}};const qa=()=>{},Bs={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},nv=[1e3,2e3,5e3,1e4],sv=1e4,iv=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;let av=class{constructor(t,r){var n;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=nl,this.transport=null,this.heartbeatIntervalMs=Bs.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=qa,this.ref=0,this.reconnectTimer=null,this.vsn=Fc,this.logger=qa,this.conn=null,this.sendBuffer=[],this.serializer=new Jy,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((n=r==null?void 0:r.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey,this.endPoint=`${t}/${sl.websocket}`,this.httpEndpoint=xp(t),this._initializeOptions(r),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(r==null?void 0:r.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=vp.createWebSocket(this.endpointURL())}catch(t){this._setConnectionState("disconnected");const r=t.message;throw r.includes("Node.js")?new Error(`${r} To use Realtime in Node.js, you need to provide a WebSocket implementation: Option 1: Use Node.js 22+ which has native WebSocket support Option 2: Install and provide the "ws" package: npm install ws import ws from "ws" const client = new RealtimeClient(url, { ...options, transport: ws })`):new Error(`WebSocket not available: ${r}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(t,r){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const n=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(t?this.conn.close(t,r??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(t){const r=await t.unsubscribe();return this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const t=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,r,n){this.logger(t,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case hr.connecting:return fr.Connecting;case hr.open:return fr.Open;case hr.closing:return fr.Closing;default:return fr.Closed}}isConnected(){return this.connectionState()===fr.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(t,r={config:{}}){const n=`realtime:${t}`,s=this.getChannels().find(i=>i.topic===n);if(s)return s;{const i=new Sp(`realtime:${t}`,r,this);return this.channels.push(i),i}}push(t){const{topic:r,event:n,payload:s,ref:i}=t,a=()=>{this.encode(t,o=>{var l;(l=this.conn)===null||l===void 0||l.send(o)})};this.log("push",`${r} ${n} (${i})`,s),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(t=null){this._authPromise=this._performAuth(t);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var t;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(r){this.log("error","error in heartbeat callback",r)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(r){this.log("error","error in heartbeat callback",r)}this._wasManualDisconnect=!1,(t=this.conn)===null||t===void 0||t.close(qy,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},Bs.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(r){this.log("error","error in heartbeat callback",r)}this._setAuthSafely("heartbeat")}onHeartbeat(t){this.heartbeatCallback=t}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let r=this.channels.find(n=>n.topic===t&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${t}"`),r.unsubscribe())}_remove(t){this.channels=this.channels.filter(r=>r.topic!==t.topic)}_onConnMessage(t){this.decode(t.data,r=>{if(r.topic==="phoenix"&&r.event==="phx_reply")try{this.heartbeatCallback(r.payload.status==="ok"?"ok":"error")}catch(c){this.log("error","error in heartbeat callback",c)}r.ref&&r.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:n,event:s,payload:i,ref:a}=r,o=a?`(${a})`:"",l=i.status||"";this.log("receive",`${l} ${n} ${s} ${o}`.trim(),i),this.channels.filter(c=>c._isMember(n)).forEach(c=>c._trigger(s,i,a)),this._triggerStateCallbacks("message",r)})}_clearTimer(t){var r;t==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):t==="reconnect"&&((r=this.reconnectTimer)===null||r===void 0||r.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t))}_teardownConnection(){if(this.conn){if(this.conn.readyState===hr.open||this.conn.readyState===hr.connecting)try{this.conn.close()}catch(t){this.log("error","Error closing connection",t)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this.channels.forEach(t=>t.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(r=>{this.log("error","error waiting for auth on connect",r),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this.workerRef.terminate()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(t){var r;this._setConnectionState("disconnected"),this.log("transport","close",t),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout(),this._triggerStateCallbacks("close",t)}_onConnError(t){this._setConnectionState("disconnected"),this.log("transport",`${t}`),this._triggerChanError(),this._triggerStateCallbacks("error",t)}_triggerChanError(){this.channels.forEach(t=>t._trigger(lt.error))}_appendParams(t,r){if(Object.keys(r).length===0)return t;const n=t.match(/\?/)?"&":"?",s=new URLSearchParams(r);return`${t}${n}${s}`}_workerObjectUrl(t){let r;if(t)r=t;else{const n=new Blob([iv],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_setConnectionState(t,r=!1){this._connectionState=t,t==="connecting"?this._wasManualDisconnect=!1:t==="disconnecting"&&(this._wasManualDisconnect=r)}async _performAuth(t=null){let r;t?r=t:this.accessToken?r=await this.accessToken():r=this.accessTokenValue,this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{const s={access_token:r,version:Hy};r&&n.updateJoinPayload(s),n.joinedOnce&&n._isJoined()&&n._push(lt.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this.setAuth().catch(r=>{this.log("error",`error setting auth in ${t}`,r)})}_triggerStateCallbacks(t,r){try{this.stateChangeCallbacks[t].forEach(n=>{try{n(r)}catch(s){this.log("error",`error in ${t} callback`,s)}})}catch(n){this.log("error",`error triggering ${t} callbacks`,n)}}_setupReconnectionTimer(){this.reconnectTimer=new bp(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Bs.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(t){var r,n,s,i,a,o,l,c,d,h,f,g;switch(this.transport=(r=t==null?void 0:t.transport)!==null&&r!==void 0?r:null,this.timeout=(n=t==null?void 0:t.timeout)!==null&&n!==void 0?n:nl,this.heartbeatIntervalMs=(s=t==null?void 0:t.heartbeatIntervalMs)!==null&&s!==void 0?s:Bs.HEARTBEAT_INTERVAL,this.worker=(i=t==null?void 0:t.worker)!==null&&i!==void 0?i:!1,this.accessToken=(a=t==null?void 0:t.accessToken)!==null&&a!==void 0?a:null,this.heartbeatCallback=(o=t==null?void 0:t.heartbeatCallback)!==null&&o!==void 0?o:qa,this.vsn=(l=t==null?void 0:t.vsn)!==null&&l!==void 0?l:Fc,t!=null&&t.params&&(this.params=t.params),t!=null&&t.logger&&(this.logger=t.logger),(t!=null&&t.logLevel||t!=null&&t.log_level)&&(this.logLevel=t.logLevel||t.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(c=t==null?void 0:t.reconnectAfterMs)!==null&&c!==void 0?c:w=>nv[w-1]||sv,this.vsn){case wp:this.encode=(d=t==null?void 0:t.encode)!==null&&d!==void 0?d:(w,v)=>v(JSON.stringify(w)),this.decode=(h=t==null?void 0:t.decode)!==null&&h!==void 0?h:(w,v)=>v(JSON.parse(w));break;case Ky:this.encode=(f=t==null?void 0:t.encode)!==null&&f!==void 0?f:this.serializer.encode.bind(this.serializer),this.decode=(g=t==null?void 0:t.decode)!==null&&g!==void 0?g:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t==null?void 0:t.workerUrl}}};const ov=Object.freeze(Object.defineProperty({__proto__:null,REALTIME_CHANNEL_STATES:rv,get REALTIME_LISTEN_TYPES(){return en},get REALTIME_POSTGRES_CHANGES_LISTEN_EVENT(){return ol},get REALTIME_PRESENCE_LISTEN_EVENTS(){return al},get REALTIME_SUBSCRIBE_STATES(){return mt},RealtimeChannel:Sp,RealtimeClient:av,RealtimePresence:kp,WebSocketFactory:vp},Symbol.toStringTag,{value:"Module"})),jp=ls(ov);class ps extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function ee(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}class Np extends ps{constructor(t,r,n){super(t),this.name="StorageApiError",this.status=r,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Mi extends ps{constructor(t,r){super(t),this.name="StorageUnknownError",this.originalError=r}}const fu=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),lv=()=>Response,ll=e=>{if(Array.isArray(e))return e.map(r=>ll(r));if(typeof e=="function"||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([r,n])=>{const s=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[s]=ll(n)}),t},uv=e=>{if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},cv=e=>!e||typeof e!="string"||e.length===0||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e),Ga=e=>{var t;return e.msg||e.message||e.error_description||(typeof e.error=="string"?e.error:(t=e.error)===null||t===void 0?void 0:t.message)||JSON.stringify(e)},dv=(e,t,r)=>R(void 0,void 0,void 0,function*(){const n=yield lv();e instanceof n&&!(r!=null&&r.noResolveJson)?e.json().then(s=>{const i=e.status||500,a=(s==null?void 0:s.statusCode)||i+"";t(new Np(Ga(s),i,a))}).catch(s=>{t(new Mi(Ga(s),s))}):t(new Mi(Ga(e),e))}),hv=(e,t,r,n)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"||!n?s:(uv(n)?(s.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),s.body=JSON.stringify(n)):s.body=n,t!=null&&t.duplex&&(s.duplex=t.duplex),Object.assign(Object.assign({},s),r))};function gs(e,t,r,n,s,i){return R(this,void 0,void 0,function*(){return new Promise((a,o)=>{e(r,hv(t,n,s,i)).then(l=>{if(!l.ok)throw l;return n!=null&&n.noResolveJson?l:l.json()}).then(l=>a(l)).catch(l=>dv(l,o,n))})})}function as(e,t,r,n){return R(this,void 0,void 0,function*(){return gs(e,"GET",t,r,n)})}function at(e,t,r,n,s){return R(this,void 0,void 0,function*(){return gs(e,"POST",t,n,s,r)})}function ul(e,t,r,n,s){return R(this,void 0,void 0,function*(){return gs(e,"PUT",t,n,s,r)})}function fv(e,t,r,n){return R(this,void 0,void 0,function*(){return gs(e,"HEAD",t,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function pu(e,t,r,n,s){return R(this,void 0,void 0,function*(){return gs(e,"DELETE",t,n,s,r)})}class pv{constructor(t,r){this.downloadFn=t,this.shouldThrowOnError=r}then(t,r){return this.execute().then(t,r)}execute(){return R(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(ee(t))return{data:null,error:t};throw t}})}}var Tp;class gv{constructor(t,r){this.downloadFn=t,this.shouldThrowOnError=r,this[Tp]="BlobDownloadBuilder",this.promise=null}asStream(){return new pv(this.downloadFn,this.shouldThrowOnError)}then(t,r){return this.getPromise().then(t,r)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}execute(){return R(this,void 0,void 0,function*(){try{return{data:yield(yield this.downloadFn()).blob(),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(ee(t))return{data:null,error:t};throw t}})}}Tp=Symbol.toStringTag;const mv={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Wc={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class yv{constructor(t,r={},n,s){this.shouldThrowOnError=!1,this.url=t,this.headers=r,this.bucketId=n,this.fetch=fu(s)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(t,r,n,s){return R(this,void 0,void 0,function*(){try{let i;const a=Object.assign(Object.assign({},Wc),s);let o=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const l=a.metadata;typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),l&&i.append("metadata",this.encodeMetadata(l)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",this.encodeMetadata(l))):(i=n,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),s!=null&&s.headers&&(o=Object.assign(Object.assign({},o),s.headers));const c=this._removeEmptyFolders(r),d=this._getFinalPath(c),h=yield(t=="PUT"?ul:at)(this.fetch,`${this.url}/object/${d}`,i,Object.assign({headers:o},a!=null&&a.duplex?{duplex:a.duplex}:{}));return{data:{path:c,id:h.Id,fullPath:h.Key},error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(ee(i))return{data:null,error:i};throw i}})}upload(t,r,n){return R(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,r,n)})}uploadToSignedUrl(t,r,n,s){return R(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(t),a=this._getFinalPath(i),o=new URL(this.url+`/object/upload/sign/${a}`);o.searchParams.set("token",r);try{let l;const c=Object.assign({upsert:Wc.upsert},s),d=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&n instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",n)):typeof FormData<"u"&&n instanceof FormData?(l=n,l.append("cacheControl",c.cacheControl)):(l=n,d["cache-control"]=`max-age=${c.cacheControl}`,d["content-type"]=c.contentType);const h=yield ul(this.fetch,o.toString(),l,{headers:d});return{data:{path:i,fullPath:h.Key},error:null}}catch(l){if(this.shouldThrowOnError)throw l;if(ee(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(t,r){return R(this,void 0,void 0,function*(){try{let n=this._getFinalPath(t);const s=Object.assign({},this.headers);r!=null&&r.upsert&&(s["x-upsert"]="true");const i=yield at(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:s}),a=new URL(this.url+i.url),o=a.searchParams.get("token");if(!o)throw new ps("No token returned by API");return{data:{signedUrl:a.toString(),path:t,token:o},error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(ee(n))return{data:null,error:n};throw n}})}update(t,r,n){return R(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,r,n)})}move(t,r,n){return R(this,void 0,void 0,function*(){try{return{data:yield at(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(ee(s))return{data:null,error:s};throw s}})}copy(t,r,n){return R(this,void 0,void 0,function*(){try{return{data:{path:(yield at(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(ee(s))return{data:null,error:s};throw s}})}createSignedUrl(t,r,n){return R(this,void 0,void 0,function*(){try{let s=this._getFinalPath(t),i=yield at(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:r},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers});const a=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${a}`)},{data:i,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(ee(s))return{data:null,error:s};throw s}})}createSignedUrls(t,r,n){return R(this,void 0,void 0,function*(){try{const s=yield at(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:r,paths:t},{headers:this.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:s.map(a=>Object.assign(Object.assign({},a),{signedUrl:a.signedURL?encodeURI(`${this.url}${a.signedURL}${i}`):null})),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(ee(s))return{data:null,error:s};throw s}})}download(t,r){const s=typeof(r==null?void 0:r.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((r==null?void 0:r.transform)||{}),a=i?`?${i}`:"",o=this._getFinalPath(t),l=()=>as(this.fetch,`${this.url}/${s}/${o}${a}`,{headers:this.headers,noResolveJson:!0});return new gv(l,this.shouldThrowOnError)}info(t){return R(this,void 0,void 0,function*(){const r=this._getFinalPath(t);try{const n=yield as(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:ll(n),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(ee(n))return{data:null,error:n};throw n}})}exists(t){return R(this,void 0,void 0,function*(){const r=this._getFinalPath(t);try{return yield fv(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(ee(n)&&n instanceof Mi){const s=n.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:n}}throw n}})}getPublicUrl(t,r){const n=this._getFinalPath(t),s=[],i=r!=null&&r.download?`download=${r.download===!0?"":r.download}`:"";i!==""&&s.push(i);const o=typeof(r==null?void 0:r.transform)<"u"?"render/image":"object",l=this.transformOptsToQueryString((r==null?void 0:r.transform)||{});l!==""&&s.push(l);let c=s.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${n}${c}`)}}}remove(t){return R(this,void 0,void 0,function*(){try{return{data:yield pu(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(ee(r))return{data:null,error:r};throw r}})}list(t,r,n){return R(this,void 0,void 0,function*(){try{const s=Object.assign(Object.assign(Object.assign({},mv),r),{prefix:t||""});return{data:yield at(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},n),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(ee(s))return{data:null,error:s};throw s}})}listV2(t,r){return R(this,void 0,void 0,function*(){try{const n=Object.assign({},t);return{data:yield at(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,n,{headers:this.headers},r),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(ee(n))return{data:null,error:n};throw n}})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const r=[];return t.width&&r.push(`width=${t.width}`),t.height&&r.push(`height=${t.height}`),t.resize&&r.push(`resize=${t.resize}`),t.format&&r.push(`format=${t.format}`),t.quality&&r.push(`quality=${t.quality}`),r.join("&")}}const Pp="2.86.2",Cp={"X-Client-Info":`storage-js/${Pp}`};class vv{constructor(t,r={},n,s){this.shouldThrowOnError=!1;const i=new URL(t);s!=null&&s.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),this.url=i.href.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Cp),r),this.fetch=fu(n)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(t){return R(this,void 0,void 0,function*(){try{const r=this.listBucketOptionsToQueryString(t);return{data:yield as(this.fetch,`${this.url}/bucket${r}`,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(ee(r))return{data:null,error:r};throw r}})}getBucket(t){return R(this,void 0,void 0,function*(){try{return{data:yield as(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(ee(r))return{data:null,error:r};throw r}})}createBucket(t){return R(this,arguments,void 0,function*(r,n={public:!1}){try{return{data:yield at(this.fetch,`${this.url}/bucket`,{id:r,name:r,type:n.type,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(ee(s))return{data:null,error:s};throw s}})}updateBucket(t,r){return R(this,void 0,void 0,function*(){try{return{data:yield ul(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(ee(n))return{data:null,error:n};throw n}})}emptyBucket(t){return R(this,void 0,void 0,function*(){try{return{data:yield at(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(ee(r))return{data:null,error:r};throw r}})}deleteBucket(t){return R(this,void 0,void 0,function*(){try{return{data:yield pu(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(ee(r))return{data:null,error:r};throw r}})}listBucketOptionsToQueryString(t){const r={};return t&&("limit"in t&&(r.limit=String(t.limit)),"offset"in t&&(r.offset=String(t.offset)),t.search&&(r.search=t.search),t.sortColumn&&(r.sortColumn=t.sortColumn),t.sortOrder&&(r.sortOrder=t.sortOrder)),Object.keys(r).length>0?"?"+new URLSearchParams(r).toString():""}}var os=class extends Error{constructor(e,t){var r;super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType==="CommitStateUnknownException"||[500,502,504].includes(t.status)&&((r=t.icebergType)==null?void 0:r.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function wv(e,t,r){const n=new URL(t,e);if(r)for(const[s,i]of Object.entries(r))i!==void 0&&n.searchParams.set(s,i);return n.toString()}async function bv(e){return!e||e.type==="none"?{}:e.type==="bearer"?{Authorization:`Bearer ${e.token}`}:e.type==="header"?{[e.name]:e.value}:e.type==="custom"?await e.getHeaders():{}}function _v(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:s,body:i,headers:a}){const o=wv(e.baseUrl,n,s),l=await bv(e.auth),c=await t(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...a},body:i?JSON.stringify(i):void 0}),d=await c.text(),h=(c.headers.get("content-type")||"").includes("application/json"),f=h&&d?JSON.parse(d):d;if(!c.ok){const g=h?f:void 0,w=g==null?void 0:g.error;throw new os((w==null?void 0:w.message)??`Request failed with status ${c.status}`,{status:c.status,icebergType:w==null?void 0:w.type,icebergCode:w==null?void 0:w.code,details:g})}return{status:c.status,headers:c.headers,data:f}}}}function Fs(e){return e.join("")}var xv=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:Fs(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(e,t){const r={namespace:e.namespace,properties:t==null?void 0:t.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Fs(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Fs(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Fs(e.namespace)}`}),!0}catch(t){if(t instanceof os&&t.status===404)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(r){if(r instanceof os&&r.status===409)return;throw r}}};function Pr(e){return e.join("")}var kv=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Pr(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Pr(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Pr(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Pr(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String((t==null?void 0:t.purge)??!1)}})}async loadTable(e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Pr(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Pr(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(r){if(r instanceof os&&r.status===404)return!1;throw r}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof os&&r.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},Sv=class{constructor(e){var n;let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=_v({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=(n=e.accessDelegation)==null?void 0:n.join(","),this.namespaceOps=new xv(this.client,t),this.tableOps=new kv(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};class Ap{constructor(t,r={},n){this.shouldThrowOnError=!1,this.url=t.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Cp),r),this.fetch=fu(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(t){return R(this,void 0,void 0,function*(){try{return{data:yield at(this.fetch,`${this.url}/bucket`,{name:t},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(ee(r))return{data:null,error:r};throw r}})}listBuckets(t){return R(this,void 0,void 0,function*(){try{const r=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&r.set("limit",t.limit.toString()),(t==null?void 0:t.offset)!==void 0&&r.set("offset",t.offset.toString()),t!=null&&t.sortColumn&&r.set("sortColumn",t.sortColumn),t!=null&&t.sortOrder&&r.set("sortOrder",t.sortOrder),t!=null&&t.search&&r.set("search",t.search);const n=r.toString(),s=n?`${this.url}/bucket?${n}`:`${this.url}/bucket`;return{data:yield as(this.fetch,s,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(ee(r))return{data:null,error:r};throw r}})}deleteBucket(t){return R(this,void 0,void 0,function*(){try{return{data:yield pu(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(ee(r))return{data:null,error:r};throw r}})}from(t){if(!cv(t))throw new ps("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");return new Sv({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:()=>R(this,void 0,void 0,function*(){return this.headers})},fetch:this.fetch})}}const gu={"X-Client-Info":`storage-js/${Pp}`,"Content-Type":"application/json"};class mu extends Error{constructor(t){super(t),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function $e(e){return typeof e=="object"&&e!==null&&"__isStorageVectorsError"in e}class oi extends mu{constructor(t,r,n){super(t),this.name="StorageVectorsApiError",this.status=r,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Op extends mu{constructor(t,r){super(t),this.name="StorageVectorsUnknownError",this.originalError=r}}var cl;(function(e){e.InternalError="InternalError",e.S3VectorConflictException="S3VectorConflictException",e.S3VectorNotFoundException="S3VectorNotFoundException",e.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",e.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",e.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded"})(cl||(cl={}));const da=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),Ev=()=>Response,Rp=e=>{if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},jv=e=>Array.from(new Float32Array(e)),Nv=(e,t)=>{if(t!==void 0&&e.float32.length!==t)throw new Error(`Vector dimension mismatch: expected ${t}, got ${e.float32.length}`)},Hc=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Tv=(e,t,r)=>R(void 0,void 0,void 0,function*(){if(e&&typeof e=="object"&&"status"in e&&"ok"in e&&typeof e.status=="number"&&!(r!=null&&r.noResolveJson)){const s=e.status||500,i=e;if(typeof i.json=="function")i.json().then(a=>{const o=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||s+"";t(new oi(Hc(a),s,o))}).catch(()=>{const a=s+"",o=i.statusText||`HTTP ${s} error`;t(new oi(o,s,a))});else{const a=s+"",o=i.statusText||`HTTP ${s} error`;t(new oi(o,s,a))}}else t(new Op(Hc(e),e))}),Pv=(e,t,r,n)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};return n?(Rp(n)?(s.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),s.body=JSON.stringify(n)):s.body=n,Object.assign(Object.assign({},s),r)):s};function Cv(e,t,r,n,s,i){return R(this,void 0,void 0,function*(){return new Promise((a,o)=>{e(r,Pv(t,n,s,i)).then(l=>{if(!l.ok)throw l;if(n!=null&&n.noResolveJson)return l;const c=l.headers.get("content-type");return!c||!c.includes("application/json")?{}:l.json()}).then(l=>a(l)).catch(l=>Tv(l,o,n))})})}function Fe(e,t,r,n,s){return R(this,void 0,void 0,function*(){return Cv(e,"POST",t,n,s,r)})}class Ip{constructor(t,r={},n){this.shouldThrowOnError=!1,this.url=t.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},gu),r),this.fetch=da(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(t){return R(this,void 0,void 0,function*(){try{return{data:(yield Fe(this.fetch,`${this.url}/CreateIndex`,t,{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}getIndex(t,r){return R(this,void 0,void 0,function*(){try{return{data:yield Fe(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:t,indexName:r},{headers:this.headers}),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if($e(n))return{data:null,error:n};throw n}})}listIndexes(t){return R(this,void 0,void 0,function*(){try{return{data:yield Fe(this.fetch,`${this.url}/ListIndexes`,t,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}deleteIndex(t,r){return R(this,void 0,void 0,function*(){try{return{data:(yield Fe(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:t,indexName:r},{headers:this.headers}))||{},error:null}}catch(n){if(this.shouldThrowOnError)throw n;if($e(n))return{data:null,error:n};throw n}})}}class $p{constructor(t,r={},n){this.shouldThrowOnError=!1,this.url=t.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},gu),r),this.fetch=da(n)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(t){return R(this,void 0,void 0,function*(){try{if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:(yield Fe(this.fetch,`${this.url}/PutVectors`,t,{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}getVectors(t){return R(this,void 0,void 0,function*(){try{return{data:yield Fe(this.fetch,`${this.url}/GetVectors`,t,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}listVectors(t){return R(this,void 0,void 0,function*(){try{if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return{data:yield Fe(this.fetch,`${this.url}/ListVectors`,t,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}queryVectors(t){return R(this,void 0,void 0,function*(){try{return{data:yield Fe(this.fetch,`${this.url}/QueryVectors`,t,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}deleteVectors(t){return R(this,void 0,void 0,function*(){try{if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:(yield Fe(this.fetch,`${this.url}/DeleteVectors`,t,{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}}class Dp{constructor(t,r={},n){this.shouldThrowOnError=!1,this.url=t.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},gu),r),this.fetch=da(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(t){return R(this,void 0,void 0,function*(){try{return{data:(yield Fe(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}getBucket(t){return R(this,void 0,void 0,function*(){try{return{data:yield Fe(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:t},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}listBuckets(){return R(this,arguments,void 0,function*(t={}){try{return{data:yield Fe(this.fetch,`${this.url}/ListVectorBuckets`,t,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}deleteBucket(t){return R(this,void 0,void 0,function*(){try{return{data:(yield Fe(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($e(r))return{data:null,error:r};throw r}})}}class Lp extends Dp{constructor(t,r={}){super(t,r.headers||{},r.fetch)}from(t){return new zp(this.url,this.headers,t,this.fetch)}createBucket(t){const r=Object.create(null,{createBucket:{get:()=>super.createBucket}});return R(this,void 0,void 0,function*(){return r.createBucket.call(this,t)})}getBucket(t){const r=Object.create(null,{getBucket:{get:()=>super.getBucket}});return R(this,void 0,void 0,function*(){return r.getBucket.call(this,t)})}listBuckets(){const t=Object.create(null,{listBuckets:{get:()=>super.listBuckets}});return R(this,arguments,void 0,function*(r={}){return t.listBuckets.call(this,r)})}deleteBucket(t){const r=Object.create(null,{deleteBucket:{get:()=>super.deleteBucket}});return R(this,void 0,void 0,function*(){return r.deleteBucket.call(this,t)})}}class zp extends Ip{constructor(t,r,n,s){super(t,r,s),this.vectorBucketName=n}createIndex(t){const r=Object.create(null,{createIndex:{get:()=>super.createIndex}});return R(this,void 0,void 0,function*(){return r.createIndex.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName}))})}listIndexes(){const t=Object.create(null,{listIndexes:{get:()=>super.listIndexes}});return R(this,arguments,void 0,function*(r={}){return t.listIndexes.call(this,Object.assign(Object.assign({},r),{vectorBucketName:this.vectorBucketName}))})}getIndex(t){const r=Object.create(null,{getIndex:{get:()=>super.getIndex}});return R(this,void 0,void 0,function*(){return r.getIndex.call(this,this.vectorBucketName,t)})}deleteIndex(t){const r=Object.create(null,{deleteIndex:{get:()=>super.deleteIndex}});return R(this,void 0,void 0,function*(){return r.deleteIndex.call(this,this.vectorBucketName,t)})}index(t){return new Up(this.url,this.headers,this.vectorBucketName,t,this.fetch)}}class Up extends $p{constructor(t,r,n,s,i){super(t,r,i),this.vectorBucketName=n,this.indexName=s}putVectors(t){const r=Object.create(null,{putVectors:{get:()=>super.putVectors}});return R(this,void 0,void 0,function*(){return r.putVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}getVectors(t){const r=Object.create(null,{getVectors:{get:()=>super.getVectors}});return R(this,void 0,void 0,function*(){return r.getVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}listVectors(){const t=Object.create(null,{listVectors:{get:()=>super.listVectors}});return R(this,arguments,void 0,function*(r={}){return t.listVectors.call(this,Object.assign(Object.assign({},r),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}queryVectors(t){const r=Object.create(null,{queryVectors:{get:()=>super.queryVectors}});return R(this,void 0,void 0,function*(){return r.queryVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}deleteVectors(t){const r=Object.create(null,{deleteVectors:{get:()=>super.deleteVectors}});return R(this,void 0,void 0,function*(){return r.deleteVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class Av extends vv{constructor(t,r={},n,s){super(t,r,n,s)}from(t){return new yv(this.url,this.headers,t,this.fetch)}get vectors(){return new Lp(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Ap(this.url+"/iceberg",this.headers,this.fetch)}}const Ov=Object.freeze(Object.defineProperty({__proto__:null,StorageAnalyticsClient:Ap,StorageApiError:Np,StorageClient:Av,StorageError:ps,StorageUnknownError:Mi,StorageVectorsApiError:oi,StorageVectorsClient:Lp,StorageVectorsError:mu,get StorageVectorsErrorCode(){return cl},StorageVectorsUnknownError:Op,VectorBucketApi:Dp,VectorBucketScope:zp,VectorDataApi:$p,VectorIndexApi:Ip,VectorIndexScope:Up,isPlainObject:Rp,isStorageError:ee,isStorageVectorsError:$e,normalizeToFloat32:jv,resolveFetch:da,resolveResponse:Ev,validateVectorDimension:Nv},Symbol.toStringTag,{value:"Module"})),Rv=ls(Ov);var Mp={},ha={};Object.defineProperty(ha,"__esModule",{value:!0});ha.version=void 0;ha.version="2.86.2";(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_REALTIME_OPTIONS=e.DEFAULT_AUTH_OPTIONS=e.DEFAULT_DB_OPTIONS=e.DEFAULT_GLOBAL_OPTIONS=e.DEFAULT_HEADERS=void 0;const t=ha;let r="";typeof Deno<"u"?r="deno":typeof document<"u"?r="web":typeof navigator<"u"&&navigator.product==="ReactNative"?r="react-native":r="node",e.DEFAULT_HEADERS={"X-Client-Info":`supabase-js-${r}/${t.version}`},e.DEFAULT_GLOBAL_OPTIONS={headers:e.DEFAULT_HEADERS},e.DEFAULT_DB_OPTIONS={schema:"public"},e.DEFAULT_AUTH_OPTIONS={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},e.DEFAULT_REALTIME_OPTIONS={}})(Mp);var Bp={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.fetchWithAuth=e.resolveHeadersConstructor=e.resolveFetch=void 0;const t=s=>s?(...i)=>s(...i):(...i)=>fetch(...i);e.resolveFetch=t;const r=()=>Headers;e.resolveHeadersConstructor=r;const n=(s,i,a)=>{const o=(0,e.resolveFetch)(a),l=(0,e.resolveHeadersConstructor)();return async(c,d)=>{var h;const f=(h=await i())!==null&&h!==void 0?h:s;let g=new l(d==null?void 0:d.headers);return g.has("apikey")||g.set("apikey",s),g.has("Authorization")||g.set("Authorization",`Bearer ${f}`),o(c,Object.assign(Object.assign({},d),{headers:g}))}};e.fetchWithAuth=n})(Bp);var nr={};Object.defineProperty(nr,"__esModule",{value:!0});nr.isBrowser=void 0;nr.uuid=Iv;nr.ensureTrailingSlash=Fp;nr.applySettingDefaults=Dv;nr.validateSupabaseUrl=Lv;function Iv(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=Math.random()*16|0,r=e=="x"?t:t&3|8;return r.toString(16)})}function Fp(e){return e.endsWith("/")?e:e+"/"}const $v=()=>typeof window<"u";nr.isBrowser=$v;function Dv(e,t){var r,n;const{db:s,auth:i,realtime:a,global:o}=e,{db:l,auth:c,realtime:d,global:h}=t,f={db:Object.assign(Object.assign({},l),s),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},d),a),storage:{},global:Object.assign(Object.assign(Object.assign({},h),o),{headers:Object.assign(Object.assign({},(r=h==null?void 0:h.headers)!==null&&r!==void 0?r:{}),(n=o==null?void 0:o.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return e.accessToken?f.accessToken=e.accessToken:delete f.accessToken,f}function Lv(e){const t=e==null?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Fp(t))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var fa={};const Vp="2.86.2",Rr=30*1e3,dl=3,Ja=dl*Rr,zv="http://localhost:9999",Uv="supabase.auth.token",Mv={"X-Client-Info":`gotrue-js/${Vp}`},hl="X-Supabase-Api-Version",Wp={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Bv=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Fv=10*60*1e3;let dn=class extends Error{constructor(t,r,n){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}};function I(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}let Hp=class extends dn{constructor(t,r,n){super(t,r,n),this.name="AuthApiError",this.status=r,this.code=n}};function Kp(e){return I(e)&&e.name==="AuthApiError"}let Mt=class extends dn{constructor(t,r){super(t),this.name="AuthUnknownError",this.originalError=r}},Rt=class extends dn{constructor(t,r,n,s){super(t,n,s),this.name=r,this.status=n}},Re=class extends Rt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function qp(e){return I(e)&&e.name==="AuthSessionMissingError"}let ur=class extends Rt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},An=class extends Rt{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}},On=class extends Rt{constructor(t,r=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function Gp(e){return I(e)&&e.name==="AuthImplicitGrantRedirectError"}let fl=class extends Rt{constructor(t,r=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Bi=class extends Rt{constructor(t,r){super(t,"AuthRetryableFetchError",r,void 0)}};function li(e){return I(e)&&e.name==="AuthRetryableFetchError"}let pl=class extends Rt{constructor(t,r,n){super(t,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}};function Vv(e){return I(e)&&e.name==="AuthWeakPasswordError"}let Fi=class extends Rt{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}};const Vi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Kc=` \r=`.split(""),Wv=(()=>{const e=new Array(128);for(let t=0;t=6;){const n=t.queue>>t.queuedBits-6&63;r(Vi[n]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const n=t.queue>>t.queuedBits-6&63;r(Vi[n]),t.queuedBits-=6}}function Jp(e,t,r){const n=Wv[e];if(n>-1)for(t.queue=t.queue<<6|n,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}}function Gc(e){const t=[],r=a=>{t.push(String.fromCodePoint(a))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=a=>{qv(a,n,r)};for(let a=0;a>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function Kv(e,t){for(let r=0;r55295&&n<=56319){const s=(n-55296)*1024&65535;n=(e.charCodeAt(r+1)-56320&65535|s)+65536,r+=1}Hv(n,t)}}function qv(e,t,r){if(t.utf8seq===0){if(e<=127){r(e);return}for(let n=1;n<6;n+=1)if(!(e>>7-n&1)){t.utf8seq=n;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0&&r(t.codepoint)}}function tn(e){const t=[],r={queue:0,queuedBits:0},n=s=>{t.push(s)};for(let s=0;st.push(r)),new Uint8Array(t)}function yr(e){const t=[],r={queue:0,queuedBits:0},n=s=>{t.push(s)};return e.forEach(s=>qc(s,r,n)),qc(null,r,n),t.join("")}function Jv(e){return Math.round(Date.now()/1e3)+e}function Qv(){return Symbol("auth-callback")}const ye=()=>typeof window<"u"&&typeof document<"u",ir={tested:!1,writable:!1},Qp=()=>{if(!ye())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ir.tested)return ir.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),ir.tested=!0,ir.writable=!0}catch{ir.tested=!0,ir.writable=!1}return ir.writable};function Yv(e){const t={},r=new URL(e);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((s,i)=>{t[i]=s})}catch{}return r.searchParams.forEach((n,s)=>{t[s]=n}),t}const Yp=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),Xv=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",Ir=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},ar=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return r}},me=async(e,t)=>{await e.removeItem(t)};class pa{constructor(){this.promise=new pa.promiseConstructor((t,r)=>{this.resolve=t,this.reject=r})}}pa.promiseConstructor=Promise;function Qa(e){const t=e.split(".");if(t.length!==3)throw new Fi("Invalid JWT structure");for(let n=0;n{setTimeout(()=>t(null),e)})}function ew(e,t){return new Promise((n,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{const a=await e(i);if(!t(i,null,a)){n(a);return}}catch(a){if(!t(i,a)){s(a);return}}})()})}function tw(e){return("0"+e.toString(16)).substr(-2)}function rw(){const t=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let s="";for(let i=0;i<56;i++)s+=r.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(t),Array.from(t,tw).join("")}async function nw(e){const r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function sw(e){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."),e;const r=await nw(e);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Cr(e,t,r=!1){const n=rw();let s=n;r&&(s+="/PASSWORD_RECOVERY"),await Ir(e,`${t}-code-verifier`,s);const i=await sw(n);return[i,n===i?"plain":"s256"]}const iw=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function aw(e){const t=e.headers.get(hl);if(!t||!t.match(iw))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function ow(e){if(!e)throw new Error("Missing exp claim");const t=Math.floor(Date.now()/1e3);if(e<=t)throw new Error("JWT has expired")}function lw(e){switch(e){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 uw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Ar(e){if(!uw.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ya(){const e={};return new Proxy(e,{get:(t,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="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 "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(t,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(t,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function cw(e,t){return new Proxy(e,{get:(r,n,s)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){const i=n.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,s)}return!t.value&&typeof n=="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."),t.value=!0),Reflect.get(r,n,s)}})}function Jc(e){return JSON.parse(JSON.stringify(e))}const cr=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),dw=[502,503,504];async function Qc(e){var t;if(!Xv(e))throw new Bi(cr(e),0);if(dw.includes(e.status))throw new Bi(cr(e),e.status);let r;try{r=await e.json()}catch(i){throw new Mt(cr(i),i)}let n;const s=aw(e);if(s&&s.getTime()>=Wp["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new pl(cr(r),e.status,((t=r.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(n==="session_not_found")throw new Re}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0))throw new pl(cr(r),e.status,r.weak_password.reasons);throw new Hp(cr(r),e.status||500,n)}const hw=(e,t,r,n)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),r))};async function D(e,t,r,n){var s;const i=Object.assign({},n==null?void 0:n.headers);i[hl]||(i[hl]=Wp["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);const a=(s=n==null?void 0:n.query)!==null&&s!==void 0?s:{};n!=null&&n.redirectTo&&(a.redirect_to=n.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await fw(e,t,r+o,{headers:i,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(l):{data:Object.assign({},l),error:null}}async function fw(e,t,r,n,s,i){const a=hw(t,n,s,i);let o;try{o=await e(r,Object.assign({},a))}catch(l){throw console.error(l),new Bi(cr(l),0)}if(o.ok||await Qc(o),n!=null&&n.noResolveJson)return o;try{return await o.json()}catch(l){await Qc(l)}}function st(e){var t;let r=null;mw(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=Jv(e.expires_in)));const n=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:r,user:n},error:null}}function Yc(e){const t=st(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(t.data.weak_password=e.weak_password),t}function Bt(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function pw(e){return{data:e,error:null}}function gw(e){const{action_link:t,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i}=e,a=mn(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:t,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i},l=Object.assign({},a);return{data:{properties:o,user:l},error:null}}function Xc(e){return e}function mw(e){return e.access_token&&e.refresh_token&&e.expires_in}const ui=["global","local","others"];let yu=class{constructor({url:t="",headers:r={},fetch:n}){this.url=t,this.headers=r,this.fetch=Yp(n),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)}}async signOut(t,r=ui[0]){if(ui.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ui.join(", ")}`);try{return await D(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(n){if(I(n))return{data:null,error:n};throw n}}async inviteUserByEmail(t,r={}){try{return await D(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Bt})}catch(n){if(I(n))return{data:{user:null},error:n};throw n}}async generateLink(t){try{const{options:r}=t,n=mn(t,["options"]),s=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(s.new_email=n==null?void 0:n.newEmail,delete s.newEmail),await D(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:gw,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(I(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(t){try{return await D(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:Bt})}catch(r){if(I(r))return{data:{user:null},error:r};throw r}}async listUsers(t){var r,n,s,i,a,o,l;try{const c={nextPage:null,lastPage:0,total:0},d=await D(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=t==null?void 0:t.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Xc});if(d.error)throw d.error;const h=await d.json(),f=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,g=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return g.length>0&&(g.forEach(w=>{const v=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(w.split(";")[1].split("=")[1]);c[`${b}Page`]=v}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(I(c))return{data:{users:[]},error:c};throw c}}async getUserById(t){Ar(t);try{return await D(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:Bt})}catch(r){if(I(r))return{data:{user:null},error:r};throw r}}async updateUserById(t,r){Ar(t);try{return await D(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:r,headers:this.headers,xform:Bt})}catch(n){if(I(n))return{data:{user:null},error:n};throw n}}async deleteUser(t,r=!1){Ar(t);try{return await D(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:r},xform:Bt})}catch(n){if(I(n))return{data:{user:null},error:n};throw n}}async _listFactors(t){Ar(t.userId);try{const{data:r,error:n}=await D(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:r,error:n}}catch(r){if(I(r))return{data:null,error:r};throw r}}async _deleteFactor(t){Ar(t.userId),Ar(t.id);try{return{data:await D(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(r){if(I(r))return{data:null,error:r};throw r}}async _listOAuthClients(t){var r,n,s,i,a,o,l;try{const c={nextPage:null,lastPage:0,total:0},d=await D(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=t==null?void 0:t.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Xc});if(d.error)throw d.error;const h=await d.json(),f=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,g=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return g.length>0&&(g.forEach(w=>{const v=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(w.split(";")[1].split("=")[1]);c[`${b}Page`]=v}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(I(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(t){try{return await D(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(I(r))return{data:null,error:r};throw r}}async _getOAuthClient(t){try{return await D(this.fetch,"GET",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(I(r))return{data:null,error:r};throw r}}async _updateOAuthClient(t,r){try{return await D(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${t}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(I(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(t){try{return await D(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(I(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(t){try{return await D(this.fetch,"POST",`${this.url}/admin/oauth/clients/${t}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(I(r))return{data:null,error:r};throw r}}};function Zc(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}const dr={debug:!!(globalThis&&Qp()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class vu extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}let Xp=class extends vu{};class yw extends vu{}async function Zp(e,t,r){dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const n=new globalThis.AbortController;return t>0&&setTimeout(()=>{n.abort(),dr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}else{if(t===0)throw dr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new Xp(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(dr.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}}))}const ed={};async function vw(e,t,r){var n;const s=(n=ed[e])!==null&&n!==void 0?n:Promise.resolve(),i=Promise.race([s.catch(()=>null),t>=0?new Promise((a,o)=>{setTimeout(()=>{o(new yw(`Acquring process lock with name "${e}" timed out`))},t)}):null].filter(a=>a)).catch(a=>{if(a&&a.isAcquireTimeout)throw a;return null}).then(async()=>await r());return ed[e]=i.catch(async a=>{if(a&&a.isAcquireTimeout)return await s,null;throw a}),await i}function ww(){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 eg(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function bw(e){return parseInt(e,16)}function _w(e){const t=new TextEncoder().encode(e);return"0x"+Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function xw(e){var t;const{chainId:r,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:l,resources:c,scheme:d,uri:h,version:f}=e;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((t=e.statement)===null||t===void 0)&&t.includes(` `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}const g=eg(e.address),w=d?`${d}://${n}`:n,v=e.statement?`${e.statement} `:"",b=`${w} wants you to sign in with your Ethereum account: ${g} ${v}`;let y=`URI: ${h} Version: ${f} Chain ID: ${r}${a?` Nonce: ${a}`:""} Issued At: ${i.toISOString()}`;if(s&&(y+=` Expiration Time: ${s.toISOString()}`),o&&(y+=` Not Before: ${o.toISOString()}`),l&&(y+=` Request ID: ${l}`),c){let m=` Resources:`;for(const p of c){if(!p||typeof p!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${p}`);m+=` - ${p}`}y+=m}return`${b} ${y}`}class ue extends Error{constructor({message:t,code:r,cause:n,name:s}){var i;super(t,{cause:n}),this.__isWebAuthnError=!0,this.name=(i=s??(n instanceof Error?n.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}}class Wi extends ue{constructor(t,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:t}),this.name="WebAuthnUnknownError",this.originalError=r}}function kw({error:e,options:t}){var r,n,s;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new ue({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new ue({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new ue({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new ue({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new ue({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new ue({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new ue({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new ue({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){const a=window.location.hostname;if(tg(a)){if(i.rp.id!==a)return new ue({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new ue({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Sw({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new ue({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new ue({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){const n=window.location.hostname;if(tg(n)){if(r.rpId!==n)return new ue({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class Ew{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){const t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}}const jw=new Ew;function Nw(e){if(!e)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:r,excludeCredentials:n}=e,s=mn(e,["challenge","user","excludeCredentials"]),i=tn(t).buffer,a=Object.assign(Object.assign({},r),{id:tn(r.id).buffer}),o=Object.assign(Object.assign({},s),{challenge:i,user:a});if(n&&n.length>0){o.excludeCredentials=new Array(n.length);for(let l=0;l0){i.allowCredentials=new Array(r.length);for(let a=0;as!==null&&typeof s=="object"&&!Array.isArray(s),r=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),n={};for(const s of e)if(s)for(const i in s){const a=s[i];if(a!==void 0)if(Array.isArray(a))n[i]=a;else if(r(a))n[i]=a;else if(t(a)){const o=n[i];t(o)?n[i]=Hi(o,a):n[i]=Hi(a)}else n[i]=a}return n}function $w(e,t){return Hi(Rw,e,t||{})}function Dw(e,t){return Hi(Iw,e,t||{})}class Lw{constructor(t){this.client=t,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(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:r,friendlyName:n,signal:s},i){try{const{data:a,error:o}=await this.client.mfa.challenge({factorId:t,webauthn:r});if(!a)return{data:null,error:o};const l=s??jw.createNewAbortSignal();if(a.webauthn.type==="create"){const{user:c}=a.webauthn.credential_options.publicKey;c.name||(c.name=`${c.id}:${n}`),c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{const c=$w(a.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:d,error:h}=await Aw({publicKey:c,signal:l});return d?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:h}}case"request":{const c=Dw(a.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:d,error:h}=await Ow(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:l}));return d?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:h}}}}catch(a){return I(a)?{data:null,error:a}:{data:null,error:new Mt("Unexpected error in challenge",a)}}}async _verify({challengeId:t,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:t,webauthn:n})}async _authenticate({factorId:t,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!r)return{data:null,error:new dn("rpId is required for WebAuthn authentication")};try{if(!td())return{data:null,error:new Mt("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this.challenge({factorId:t,webauthn:{rpId:r,rpOrigins:n},signal:s},{request:i});if(!a)return{data:null,error:o};const{webauthn:l}=a;return this._verify({factorId:t,challengeId:a.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:n,credential_response:l.credential_response}})}catch(a){return I(a)?{data:null,error:a}:{data:null,error:new Mt("Unexpected error in authenticate",a)}}}async _register({friendlyName:t,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!r)return{data:null,error:new dn("rpId is required for WebAuthn registration")};try{if(!td())return{data:null,error:new Mt("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this._enroll({friendlyName:t});if(!a)return await this.client.mfa.listFactors().then(d=>{var h;return(h=d.data)===null||h===void 0?void 0:h.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===t&&f.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d==null?void 0:d.id}):void 0),{data:null,error:o};const{data:l,error:c}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:s},{create:i});return l?this._verify({factorId:a.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:n,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(a){return I(a)?{data:null,error:a}:{data:null,error:new Mt("Unexpected error in register",a)}}}}ww();const zw={url:zv,storageKey:Uv,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Mv,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1};async function rd(e,t,r){return await r()}const Or={};let wu=class gl{get jwks(){var t,r;return(r=(t=Or[this.storageKey])===null||t===void 0?void 0:t.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(t){Or[this.storageKey]=Object.assign(Object.assign({},Or[this.storageKey]),{jwks:t})}get jwks_cached_at(){var t,r;return(r=(t=Or[this.storageKey])===null||t===void 0?void 0:t.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(t){Or[this.storageKey]=Object.assign(Object.assign({},Or[this.storageKey]),{cachedAt:t})}constructor(t){var r,n,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},zw),t);if(this.storageKey=i.storageKey,this.instanceID=(r=gl.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,gl.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&ye()){const a=`${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(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new yu({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Yp(i.fetch),this.lock=i.lock||rd,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,i.lock?this.lock=i.lock:ye()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=Zp:this.lock=rd,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 Lw(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.persistSession?(i.storage?this.storage=i.storage:Qp()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Zc(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Zc(this.memoryStorage)),ye()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),await this._notifyAllSubscribers(a.data.event,a.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(t){if(this.throwOnError&&t&&t.error)throw t.error;return t}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Vp}) ${new Date().toISOString()}`}_debug(...t){return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var t;try{let r={},n="none";if(ye()&&(r=Yv(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),ye()&&this.detectSessionInUrl&&n!=="none"){const{data:s,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Gp(i)){const l=(t=i.details)===null||t===void 0?void 0:t.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:a,redirectType:o}=s;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return I(r)?this._returnResult({error:r}):this._returnResult({error:new Mt("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var r,n,s;try{const i=await D(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=t==null?void 0:t.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=t==null?void 0:t.options)===null||s===void 0?void 0:s.captchaToken}},xform:st}),{data:a,error:o}=i;if(o||!a)return this._returnResult({data:{user:null,session:null},error:o});const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(I(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(t){var r,n,s;try{let i;if("email"in t){const{email:d,password:h,options:f}=t;let g=null,w=null;this.flowType==="pkce"&&([g,w]=await Cr(this.storage,this.storageKey)),i=await D(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:d,password:h,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:g,code_challenge_method:w},xform:st})}else if("phone"in t){const{phone:d,password:h,options:f}=t;i=await D(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:h,data:(n=f==null?void 0:f.data)!==null&&n!==void 0?n:{},channel:(s=f==null?void 0:f.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:st})}else throw new An("You must provide either an email or phone number and a password");const{data:a,error:o}=i;if(o||!a)return await me(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(await me(this.storage,`${this.storageKey}-code-verifier`),I(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(t){try{let r;if("email"in t){const{email:i,password:a,options:o}=t;r=await D(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Yc})}else if("phone"in t){const{phone:i,password:a,options:o}=t;r=await D(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Yc})}else throw new An("You must provide either an email or phone number and a password");const{data:n,error:s}=r;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!n||!n.session||!n.user){const i=new ur;return this._returnResult({data:{user:null,session:null},error:i})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:s})}catch(r){if(I(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(t){var r,n,s,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(r=t.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=t.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=t.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(t))}async signInWithWeb3(t){const{chain:r}=t;switch(r){case"ethereum":return await this.signInWithEthereum(t);case"solana":return await this.signInWithSolana(t);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(t){var r,n,s,i,a,o,l,c,d,h,f;let g,w;if("message"in t)g=t.message,w=t.signature;else{const{chain:v,wallet:b,statement:y,options:m}=t;let p;if(ye())if(typeof b=="object")p=b;else{const T=window;if("ethereum"in T&&typeof T.ethereum=="object"&&"request"in T.ethereum&&typeof T.ethereum.request=="function")p=T.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 b!="object"||!(m!=null&&m.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");p=b}const _=new URL((r=m==null?void 0:m.url)!==null&&r!==void 0?r:window.location.href),x=await p.request({method:"eth_requestAccounts"}).then(T=>T).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!x||x.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const S=eg(x[0]);let E=(n=m==null?void 0:m.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!E){const T=await p.request({method:"eth_chainId"});E=bw(T)}const k={domain:_.host,address:S,statement:y,uri:_.href,version:"1",chainId:E,nonce:(s=m==null?void 0:m.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(a=(i=m==null?void 0:m.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=m==null?void 0:m.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=m==null?void 0:m.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=m==null?void 0:m.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(d=m==null?void 0:m.signInWithEthereum)===null||d===void 0?void 0:d.resources};g=xw(k),w=await p.request({method:"personal_sign",params:[_w(g),S]})}try{const{data:v,error:b}=await D(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:g,signature:w},!((h=t.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=t.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:st});if(b)throw b;if(!v||!v.session||!v.user){const y=new ur;return this._returnResult({data:{user:null,session:null},error:y})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:b})}catch(v){if(I(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(t){var r,n,s,i,a,o,l,c,d,h,f,g;let w,v;if("message"in t)w=t.message,v=t.signature;else{const{chain:b,wallet:y,statement:m,options:p}=t;let _;if(ye())if(typeof y=="object")_=y;else{const S=window;if("solana"in S&&typeof S.solana=="object"&&("signIn"in S.solana&&typeof S.solana.signIn=="function"||"signMessage"in S.solana&&typeof S.solana.signMessage=="function"))_=S.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 y!="object"||!(p!=null&&p.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=y}const x=new URL((r=p==null?void 0:p.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in _&&_.signIn){const S=await _.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},p==null?void 0:p.signInWithSolana),{version:"1",domain:x.host,uri:x.href}),m?{statement:m}:null));let E;if(Array.isArray(S)&&S[0]&&typeof S[0]=="object")E=S[0];else if(S&&typeof S=="object"&&"signedMessage"in S&&"signature"in S)E=S;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in E&&"signature"in E&&(typeof E.signedMessage=="string"||E.signedMessage instanceof Uint8Array)&&E.signature instanceof Uint8Array)w=typeof E.signedMessage=="string"?E.signedMessage:new TextDecoder().decode(E.signedMessage),v=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in _)||typeof _.signMessage!="function"||!("publicKey"in _)||typeof _!="object"||!_.publicKey||!("toBase58"in _.publicKey)||typeof _.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");w=[`${x.host} wants you to sign in with your Solana account:`,_.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${x.href}`,`Issued At: ${(s=(n=p==null?void 0:p.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=p==null?void 0:p.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${p.signInWithSolana.notBefore}`]:[],...!((a=p==null?void 0:p.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${p.signInWithSolana.expirationTime}`]:[],...!((o=p==null?void 0:p.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${p.signInWithSolana.chainId}`]:[],...!((l=p==null?void 0:p.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${p.signInWithSolana.nonce}`]:[],...!((c=p==null?void 0:p.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${p.signInWithSolana.requestId}`]:[],...!((h=(d=p==null?void 0:p.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...p.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(` `);const S=await _.signMessage(new TextEncoder().encode(w),"utf8");if(!S||!(S instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=S}}try{const{data:b,error:y}=await D(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:w,signature:yr(v)},!((f=t.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(g=t.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:st});if(y)throw y;if(!b||!b.session||!b.user){const m=new ur;return this._returnResult({data:{user:null,session:null},error:m})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:y})}catch(b){if(I(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(t){const r=await ar(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(r??"").split("/");try{const{data:i,error:a}=await D(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:n},xform:st});if(await me(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const o=new ur;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:a})}catch(i){if(await me(this.storage,`${this.storageKey}-code-verifier`),I(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(t){try{const{options:r,provider:n,token:s,access_token:i,nonce:a}=t,o=await D(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:st}),{data:l,error:c}=o;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){const d=new ur;return this._returnResult({data:{user:null,session:null},error:d})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(r){if(I(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(t){var r,n,s,i,a;try{if("email"in t){const{email:o,options:l}=t;let c=null,d=null;this.flowType==="pkce"&&([c,d]=await Cr(this.storage,this.storageKey));const{error:h}=await D(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=l==null?void 0:l.data)!==null&&r!==void 0?r:{},create_user:(n=l==null?void 0:l.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:d},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in t){const{phone:o,options:l}=t,{data:c,error:d}=await D(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(s=l==null?void 0:l.data)!==null&&s!==void 0?s:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(a=l==null?void 0:l.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:d})}throw new An("You must provide either an email or phone number.")}catch(o){if(await me(this.storage,`${this.storageKey}-code-verifier`),I(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(t){var r,n;try{let s,i;"options"in t&&(s=(r=t.options)===null||r===void 0?void 0:r.redirectTo,i=(n=t.options)===null||n===void 0?void 0:n.captchaToken);const{data:a,error:o}=await D(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:st});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,c=a.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if(I(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(t){var r,n,s,i,a;try{let o=null,l=null;this.flowType==="pkce"&&([o,l]=await Cr(this.storage,this.storageKey));const c=await D(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(n=(r=t.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=t==null?void 0:t.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:pw});return!((i=c.data)===null||i===void 0)&&i.url&&ye()&&!(!((a=t.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(o){if(await me(this.storage,`${this.storageKey}-code-verifier`),I(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;if(n)throw n;if(!r)throw new Re;const{error:s}=await D(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(t){if(I(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async resend(t){try{const r=`${this.url}/resend`;if("email"in t){const{email:n,type:s,options:i}=t,{error:a}=await D(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in t){const{phone:n,type:s,options:i}=t,{data:a,error:o}=await D(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o})}throw new An("You must provide either an email or phone number and a type")}catch(r){if(I(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async r=>r))}async _acquireLock(t,r){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await t(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const r=await ar(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const n=t.expires_at?t.expires_at*1e3-Date.now()await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(t){try{return t?await D(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:Bt}):await this._useSession(async r=>{var n,s,i;const{data:a,error:o}=r;if(o)throw o;return!(!((n=a.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Re}:await D(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:Bt})})}catch(r){if(I(r))return qp(r)&&(await this._removeSession(),await me(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(t,r={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,r))}async _updateUser(t,r={}){try{return await this._useSession(async n=>{const{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new Re;const a=s.session;let o=null,l=null;this.flowType==="pkce"&&t.email!=null&&([o,l]=await Cr(this.storage,this.storageKey));const{data:c,error:d}=await D(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:o,code_challenge_method:l}),jwt:a.access_token,xform:Bt});if(d)throw d;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(n){if(await me(this.storage,`${this.storageKey}-code-verifier`),I(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new Re;const r=Date.now()/1e3;let n=r,s=!0,i=null;const{payload:a}=Qa(t.access_token);if(a.exp&&(n=a.exp,s=n<=r),s){const{data:o,error:l}=await this._callRefreshToken(t.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:l}=await this._getUser(t.access_token);if(l)throw l;i={access_token:t.access_token,refresh_token:t.refresh_token,user:o.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(I(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async r=>{var n;if(!t){const{data:a,error:o}=r;if(o)throw o;t=(n=a.session)!==null&&n!==void 0?n:void 0}if(!(t!=null&&t.refresh_token))throw new Re;const{data:s,error:i}=await this._callRefreshToken(t.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(I(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(t,r){try{if(!ye())throw new On("No browser detected.");if(t.error||t.error_description||t.error_code)throw new On(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new fl("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new On("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new fl("No code detected.");const{data:m,error:p}=await this._exchangeCodeForSession(t.code);if(p)throw p;const _=new URL(window.location.href);return _.searchParams.delete("code"),window.history.replaceState(window.history.state,"",_.toString()),{data:{session:m.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:a,expires_in:o,expires_at:l,token_type:c}=t;if(!i||!o||!a||!c)throw new On("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(o);let f=d+h;l&&(f=parseInt(l));const g=f-d;g*1e3<=Rr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${h}s`);const w=f-h;d-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,f,d):d-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",w,f,d);const{data:v,error:b}=await this._getUser(i);if(b)throw b;const y={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:h,expires_at:f,refresh_token:a,token_type:c,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:t.type},error:null})}catch(n){if(I(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(t){return!!(t.access_token||t.error_description)}async _isPKCECallback(t){const r=await ar(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&r)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async r=>{var n;const{data:s,error:i}=r;if(i)return this._returnResult({error:i});const a=(n=s.session)===null||n===void 0?void 0:n.access_token;if(a){const{error:o}=await this.admin.signOut(a,t);if(o&&!(Kp(o)&&(o.status===404||o.status===401||o.status===403)))return this._returnResult({error:o})}return t!=="others"&&(await this._removeSession(),await me(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(t){const r=Qv(),n={id:r,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(t){return await this._useSession(async r=>{var n,s;try{const{data:{session:i},error:a}=r;if(a)throw a;await((n=this.stateChangeEmitters.get(t))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(t))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),console.error(i)}})}async resetPasswordForEmail(t,r={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await Cr(this.storage,this.storageKey,!0));try{return await D(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await me(this.storage,`${this.storageKey}-code-verifier`),I(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var t;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(t=r.user.identities)!==null&&t!==void 0?t:[]},error:null})}catch(r){if(I(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(t){return"token"in t?this.linkIdentityIdToken(t):this.linkIdentityOAuth(t)}async linkIdentityOAuth(t){var r;try{const{data:n,error:s}=await this._useSession(async i=>{var a,o,l,c,d;const{data:h,error:f}=i;if(f)throw f;const g=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(a=t.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=t.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=t.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await D(this.fetch,"GET",g,{headers:this.headers,jwt:(d=(c=h.session)===null||c===void 0?void 0:c.access_token)!==null&&d!==void 0?d:void 0})});if(s)throw s;return ye()&&!(!((r=t.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),this._returnResult({data:{provider:t.provider,url:n==null?void 0:n.url},error:null})}catch(n){if(I(n))return this._returnResult({data:{provider:t.provider,url:null},error:n});throw n}}async linkIdentityIdToken(t){return await this._useSession(async r=>{var n;try{const{error:s,data:{session:i}}=r;if(s)throw s;const{options:a,provider:o,token:l,access_token:c,nonce:d}=t,h=await D(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=i==null?void 0:i.access_token)!==null&&n!==void 0?n:void 0,body:{provider:o,id_token:l,access_token:c,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:st}),{data:f,error:g}=h;return g?this._returnResult({data:{user:null,session:null},error:g}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new ur}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:g}))}catch(s){if(await me(this.storage,`${this.storageKey}-code-verifier`),I(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(t){try{return await this._useSession(async r=>{var n,s;const{data:i,error:a}=r;if(a)throw a;return await D(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(r){if(I(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(t){const r=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await ew(async s=>(s>0&&await Zv(200*Math.pow(2,s-1)),this._debug(r,"refreshing attempt",s),await D(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:st})),(s,i)=>{const a=200*Math.pow(2,s);return i&&li(i)&&Date.now()+a-n{try{await o.callback(t,r)}catch(l){i.push(l)}});if(await Promise.all(a),i.length>0){for(let o=0;othis._autoRefreshTokenTick(),Rr);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((n.expires_at*1e3-t)/Rr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Rr}ms, refresh threshold is ${dl} ticks`),s<=dl&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof vu)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ye()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const r=`#_onVisibilityChanged(${t})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,r,n){const s=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[i,a]=await Cr(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});s.push(o.toString())}if(n!=null&&n.queryParams){const i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${t}?${s.join("&")}`}async _unenroll(t){try{return await this._useSession(async r=>{var n;const{data:s,error:i}=r;return i?this._returnResult({data:null,error:i}):await D(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(I(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(t){try{return await this._useSession(async r=>{var n,s;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:t.factorType==="totp"?{issuer:t.issuer}:{}),{data:l,error:c}=await D(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(t.factorType==="totp"&&l.type==="totp"&&(!((s=l==null?void 0:l.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(I(r))return this._returnResult({data:null,error:r});throw r}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=Object.assign({challenge_id:t.challengeId},"webauthn"in t?{webauthn:Object.assign(Object.assign({},t.webauthn),{credential_response:t.webauthn.type==="create"?Pw(t.webauthn.credential_response):Cw(t.webauthn.credential_response)})}:{code:t.code}),{data:o,error:l}=await D(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:a,headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:l}))})}catch(r){if(I(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=await D(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:t,headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});if(a.error)return a;const{data:o}=a;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Nw(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Tw(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(I(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(t){const{data:r,error:n}=await this._challenge({factorId:t.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:t.factorId,challengeId:r.id,code:t.code})}async _listFactors(){var t;const{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};const s={all:[],phone:[],totp:[],webauthn:[]};for(const i of(t=r==null?void 0:r.factors)!==null&&t!==void 0?t:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(){var t,r;const{data:{session:n},error:s}=await this.getSession();if(s)return this._returnResult({data:null,error:s});if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:i}=Qa(n.access_token);let a=null;i.aal&&(a=i.aal);let o=a;((r=(t=n.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(o="aal2");const c=i.amr||[];return{data:{currentLevel:a,nextLevel:o,currentAuthenticationMethods:c},error:null}}async _getAuthorizationDetails(t){try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?await D(this.fetch,"GET",`${this.url}/oauth/authorizations/${t}`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Re})})}catch(r){if(I(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(t,r){try{return await this._useSession(async n=>{const{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Re});const a=await D(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&ye()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(n){if(I(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(t,r){try{return await this._useSession(async n=>{const{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Re});const a=await D(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&ye()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(n){if(I(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;return n?this._returnResult({data:null,error:n}):r?await D(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Re})})}catch(t){if(I(t))return this._returnResult({data:null,error:t});throw t}}async _revokeOAuthGrant(t){try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?(await D(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:t.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Re})})}catch(r){if(I(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(t,r={keys:[]}){let n=r.keys.find(o=>o.kid===t);if(n)return n;const s=Date.now();if(n=this.jwks.keys.find(o=>o.kid===t),n&&this.jwks_cached_at+Fv>s)return n;const{data:i,error:a}=await D(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,n=i.keys.find(o=>o.kid===t),!n)?null:n}async getClaims(t,r={}){try{let n=t;if(!n){const{data:g,error:w}=await this.getSession();if(w||!g.session)return this._returnResult({data:null,error:w});n=g.session.access_token}const{header:s,payload:i,signature:a,raw:{header:o,payload:l}}=Qa(n);r!=null&&r.allowExpired||ow(i.exp);const c=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!c){const{error:g}=await this.getUser(n);if(g)throw g;return{data:{claims:i,header:s,signature:a},error:null}}const d=lw(s.alg),h=await crypto.subtle.importKey("jwk",c,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,Gv(`${o}.${l}`)))throw new Fi("Invalid JWT signature");return{data:{claims:i,header:s,signature:a},error:null}}catch(n){if(I(n))return this._returnResult({data:null,error:n});throw n}}};wu.nextInstanceID={};const Uw=yu,Mw=wu,Bw=Object.freeze(Object.defineProperty({__proto__:null,AuthAdminApi:Uw,AuthApiError:Hp,AuthClient:Mw,AuthError:dn,AuthImplicitGrantRedirectError:On,AuthInvalidCredentialsError:An,AuthInvalidJwtError:Fi,AuthInvalidTokenResponseError:ur,AuthPKCEGrantCodeExchangeError:fl,AuthRetryableFetchError:Bi,AuthSessionMissingError:Re,AuthUnknownError:Mt,AuthWeakPasswordError:pl,CustomAuthError:Rt,GoTrueAdminApi:yu,GoTrueClient:wu,NavigatorLockAcquireTimeoutError:Xp,SIGN_OUT_SCOPES:ui,isAuthApiError:Kp,isAuthError:I,isAuthImplicitGrantRedirectError:Gp,isAuthRetryableFetchError:li,isAuthSessionMissingError:qp,isAuthWeakPasswordError:Vv,lockInternals:dr,navigatorLock:Zp,processLock:vw},Symbol.toStringTag,{value:"Module"})),rg=ls(Bw);Object.defineProperty(fa,"__esModule",{value:!0});fa.SupabaseAuthClient=void 0;const Fw=rg;class Vw extends Fw.AuthClient{constructor(t){super(t)}}fa.SupabaseAuthClient=Vw;Object.defineProperty(Di,"__esModule",{value:!0});const Ww=ap,Hw=Ee,Kw=jp,qw=Rv,Vs=Mp,Gw=Bp,nd=nr,Jw=fa;let Qw=class{constructor(t,r,n){var s,i,a;this.supabaseUrl=t,this.supabaseKey=r;const o=(0,nd.validateSupabaseUrl)(t);if(!r)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",o),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",o),this.storageUrl=new URL("storage/v1",o),this.functionsUrl=new URL("functions/v1",o);const l=`sb-${o.hostname.split(".")[0]}-auth-token`,c={db:Vs.DEFAULT_DB_OPTIONS,realtime:Vs.DEFAULT_REALTIME_OPTIONS,auth:Object.assign(Object.assign({},Vs.DEFAULT_AUTH_OPTIONS),{storageKey:l}),global:Vs.DEFAULT_GLOBAL_OPTIONS},d=(0,nd.applySettingDefaults)(n??{},c);this.storageKey=(s=d.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=d.global.headers)!==null&&i!==void 0?i:{},d.accessToken?(this.accessToken=d.accessToken,this.auth=new Proxy({},{get:(h,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((a=d.auth)!==null&&a!==void 0?a:{},this.headers,d.global.fetch),this.fetch=(0,Gw.fetchWithAuth)(r,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},d.realtime)),this.accessToken&&this.accessToken().then(h=>this.realtime.setAuth(h)).catch(h=>console.warn("Failed to set initial Realtime auth token:",h)),this.rest=new Hw.PostgrestClient(new URL("rest/v1",o).href,{headers:this.headers,schema:d.db.schema,fetch:this.fetch}),this.storage=new qw.StorageClient(this.storageUrl.href,this.headers,this.fetch,n==null?void 0:n.storage),d.accessToken||this._listenForAuthEvents()}get functions(){return new Ww.FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,r={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,r,n)}channel(t,r={config:{}}){return this.realtime.channel(t,r)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t,r;if(this.accessToken)return await this.accessToken();const{data:n}=await this.auth.getSession();return(r=(t=n.session)===null||t===void 0?void 0:t.access_token)!==null&&r!==void 0?r:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:r,detectSessionInUrl:n,storage:s,userStorage:i,storageKey:a,flowType:o,lock:l,debug:c,throwOnError:d},h,f){const g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Jw.SupabaseAuthClient({url:this.authUrl.href,headers:Object.assign(Object.assign({},g),h),storageKey:a,autoRefreshToken:t,persistSession:r,detectSessionInUrl:n,storage:s,userStorage:i,flowType:o,lock:l,debug:c,throwOnError:d,fetch:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(w=>w.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Kw.RealtimeClient(this.realtimeUrl.href,Object.assign(Object.assign({},t),{params:Object.assign({apikey:this.supabaseKey},t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,n)=>{this._handleTokenChanged(r,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(t,r,n){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),r=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};Di.default=Qw;(function(e){var t=Nr&&Nr.__createBinding||(Object.create?function(d,h,f,g){g===void 0&&(g=f);var w=Object.getOwnPropertyDescriptor(h,f);(!w||("get"in w?!h.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return h[f]}}),Object.defineProperty(d,g,w)}:function(d,h,f,g){g===void 0&&(g=f),d[g]=h[f]}),r=Nr&&Nr.__exportStar||function(d,h){for(var f in d)f!=="default"&&!Object.prototype.hasOwnProperty.call(h,f)&&t(h,d,f)},n=Nr&&Nr.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(e,"__esModule",{value:!0}),e.createClient=e.SupabaseClient=e.FunctionRegion=e.FunctionsError=e.FunctionsRelayError=e.FunctionsFetchError=e.FunctionsHttpError=e.PostgrestError=void 0;const s=n(Di);r(rg,e);var i=Ee;Object.defineProperty(e,"PostgrestError",{enumerable:!0,get:function(){return i.PostgrestError}});var a=ap;Object.defineProperty(e,"FunctionsHttpError",{enumerable:!0,get:function(){return a.FunctionsHttpError}}),Object.defineProperty(e,"FunctionsFetchError",{enumerable:!0,get:function(){return a.FunctionsFetchError}}),Object.defineProperty(e,"FunctionsRelayError",{enumerable:!0,get:function(){return a.FunctionsRelayError}}),Object.defineProperty(e,"FunctionsError",{enumerable:!0,get:function(){return a.FunctionsError}}),Object.defineProperty(e,"FunctionRegion",{enumerable:!0,get:function(){return a.FunctionRegion}}),r(jp,e);var o=Di;Object.defineProperty(e,"SupabaseClient",{enumerable:!0,get:function(){return n(o).default}});const l=(d,h,f)=>new s.default(d,h,f);e.createClient=l;function c(){if(typeof window<"u"||typeof process>"u")return!1;const d=process.version;if(d==null)return!1;const h=d.match(/^v(\d+)\./);return h?parseInt(h[1],10)<=18:!1}c()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217")})(cu);const ng=cd(cu),Yw=dg({__proto__:null,default:ng},[cu]),{PostgrestError:S_,FunctionsHttpError:E_,FunctionsFetchError:j_,FunctionsRelayError:N_,FunctionsError:T_,FunctionRegion:P_,SupabaseClient:C_,createClient:Xw,GoTrueAdminApi:A_,GoTrueClient:O_,AuthAdminApi:R_,AuthClient:I_,navigatorLock:$_,NavigatorLockAcquireTimeoutError:D_,lockInternals:L_,processLock:z_,SIGN_OUT_SCOPES:U_,AuthError:M_,AuthApiError:B_,AuthUnknownError:F_,CustomAuthError:V_,AuthSessionMissingError:W_,AuthInvalidTokenResponseError:H_,AuthInvalidCredentialsError:K_,AuthImplicitGrantRedirectError:q_,AuthPKCEGrantCodeExchangeError:G_,AuthRetryableFetchError:J_,AuthWeakPasswordError:Q_,AuthInvalidJwtError:Y_,isAuthError:X_,isAuthApiError:Z_,isAuthSessionMissingError:ex,isAuthImplicitGrantRedirectError:tx,isAuthRetryableFetchError:rx,isAuthWeakPasswordError:nx,RealtimePresence:sx,RealtimeChannel:ix,RealtimeClient:ax,REALTIME_LISTEN_TYPES:ox,REALTIME_POSTGRES_CHANGES_LISTEN_EVENT:lx,REALTIME_PRESENCE_LISTEN_EVENTS:ux,REALTIME_SUBSCRIBE_STATES:cx,REALTIME_CHANNEL_STATES:dx}=ng||Yw,Zw="https://vzudjibddwcvfdnyvhhs.supabase.co",eb="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZ6dWRqaWJkZHdjdmZkbnl2aGhzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjUwMjk4MDksImV4cCI6MjA4MDYwNTgwOX0.wE8R1mpd2FY6m6d5-Hf3hlCG8OfeCkra6SjUvbt1mD0",W=Xw(Zw,eb),tb=e=>Array.isArray(e)?e.map(t=>({type:(t==null?void 0:t.type)||"task",title:(t==null?void 0:t.title)||"",durationMin:Number((t==null?void 0:t.durationMin)||0),repetitions:(t==null?void 0:t.repetitions)??null,intensity:(t==null?void 0:t.intensity)||null,instructions:(t==null?void 0:t.instructions)||""})):[],rb=e=>({weekNo:Number((e==null?void 0:e.weekNo)||(e==null?void 0:e.week_no)||1),sessionNo:Number((e==null?void 0:e.sessionNo)||(e==null?void 0:e.session_no)||1),mainExercise:(e==null?void 0:e.mainExercise)||(e==null?void 0:e.main_exercise)||"Basistechnik",secondaryExercises:Array.isArray(e==null?void 0:e.secondaryExercises)?e.secondaryExercises:Array.isArray(e==null?void 0:e.secondary_exercises)?e.secondary_exercises:[],tasks:tb(e==null?void 0:e.tasks),state:(e==null?void 0:e.state)||"open",notes:(e==null?void 0:e.notes)||""}),sg=async({patType:e,analysisSnapshot:t,durationWeeks:r,sessionsPerWeek:n,sessions:s})=>{if(!W)return{ok:!1,error:new Error("Supabase ist nicht konfiguriert.")};try{const i={p_pat_type:e,p_analysis_snapshot:t,p_duration_weeks:Number(r),p_sessions_per_week:Number(n),p_sessions:(s||[]).map(rb)},{data:a,error:o}=await W.rpc("create_training_plan_with_sessions",i);if(o)throw o;return{ok:!0,planId:a}}catch(i){return{ok:!1,error:i}}},sd=[0,1,0,2,0,1,0,1,2,0],id=(e,t,r)=>t.includes(e)?e:r,nb=e=>e>=.7?"hoch":e>=.4?"mittel":"leicht",sb=()=>({type:"warmup",title:"Warm-up",durationMin:10,instructions:"Lockere Stoßserie, Fokus auf saubere Ansprechposition und Rhythmus."}),ib=(e,t)=>{const r={hoch:24,mittel:18,leicht:12};return{type:"main",title:`Hauptblock: ${e}`,durationMin:t==="hoch"?35:28,repetitions:r[t],intensity:t,instructions:"Dokumentiere Trefferquote pro Serie und halte Pausen kurz (30-45 Sek.)."}},ad=(e,t)=>({type:"secondary",title:`Nebenblock ${t}: ${e}`,durationMin:18,repetitions:10,intensity:"mittel",instructions:"Konstanter Ablauf, Fokus auf Präzision statt Tempo."}),ab=()=>({type:"cooldown",title:"Cool-down",durationMin:8,instructions:"Kurze Reflexion: 2 Dinge die gut liefen, 1 Punkt für den nächsten Tag."}),ob=(e,t)=>{if(!t.length)return{name:"Generelle Basistechnik",gapScore:.3,priorityScore:.3};const n=sd[e%sd.length]%t.length;return t[n]},lb=(e,t,r)=>{const n=[...t.map(i=>i==null?void 0:i.name),...r.map(i=>i==null?void 0:i.name)].filter(Boolean),s=[...new Set(n)].filter(i=>i!==e);return s.length>=2?s.slice(0,2):s.length===1?[s[0],"Positionsspiel Basis"]:["Positionsspiel Basis","Stoßroutine Stabilisierung"]},bu=({topWeaknesses:e=[],topStrengths:t=[],durationWeeks:r=4,sessionsPerWeek:n=3,sessionMix:s="1-main-2-secondary"}={})=>{const i=id(Number(r),[2,4,6],4),a=id(Number(n),[2,3,4],3),o=i*a,l=Array.from({length:o},(c,d)=>{const h=Math.floor(d/a)+1,f=d%a+1,g=ob(d,e),w=nb(Number((g==null?void 0:g.gapScore)||0)),v=lb(g==null?void 0:g.name,e,t),b=[sb(),ib((g==null?void 0:g.name)||"Basistechnik",w),ad(v[0],1),ad(v[1],2),ab()];return{weekNo:h,sessionNo:f,mainExercise:(g==null?void 0:g.name)||"Basistechnik",secondaryExercises:v,sessionMix:s,intensity:w,state:"open",notes:"",tasks:b,meta:{gapScore:Number((g==null?void 0:g.gapScore)||0),priorityScore:Number((g==null?void 0:g.priorityScore)||0)}}});return{durationWeeks:i,sessionsPerWeek:a,sessions:l}},ub=e=>({id:e.id,patType:e.pat_type,status:e.status,analysisSnapshot:e.analysis_snapshot||{},durationWeeks:e.duration_weeks,sessionsPerWeek:e.sessions_per_week,generatedAt:e.generated_at,archivedAt:e.archived_at,createdAt:e.created_at,updatedAt:e.updated_at,sessions:[]}),cb=e=>({id:e.id,planId:e.plan_id,weekNo:e.week_no,sessionNo:e.session_no,mainExercise:e.main_exercise,secondaryExercises:e.secondary_exercises||[],tasks:e.tasks||[],state:e.state||"open",notes:e.notes||"",completedAt:e.completed_at,createdAt:e.created_at,updatedAt:e.updated_at}),Ws=(e,t,r)=>!e||!e.sessions.some(s=>s.id===t)?e:{...e,sessions:e.sessions.map(s=>s.id===t?{...s,...r}:s)},db=({user:e,patType:t})=>{const[r,n]=P.useState(null),[s,i]=P.useState([]),[a,o]=P.useState(!1),[l,c]=P.useState(!1),[d,h]=P.useState(""),f=P.useMemo(()=>!!(W&&(e!=null&&e.id)),[e]),g=P.useCallback(async()=>{if(!f||!t){n(null),i([]);return}o(!0),h("");try{const{data:y,error:m}=await W.from("training_plans").select("*").eq("user_id",e.id).eq("pat_type",t).order("generated_at",{ascending:!1});if(m)throw m;const p=(y||[]).map(ub),_=p.map(T=>T.id);let x=new Map;if(_.length){const{data:T,error:C}=await W.from("training_plan_sessions").select("*").in("plan_id",_).order("week_no",{ascending:!0}).order("session_no",{ascending:!0});if(C)throw C;x=(T||[]).reduce((z,K)=>{const Y=cb(K),Ne=z.get(Y.planId)||[];return Ne.push(Y),z.set(Y.planId,Ne),z},new Map)}const S=p.map(T=>({...T,sessions:x.get(T.id)||[]})),E=S.find(T=>T.status==="active")||S[0]||null,k=S.filter(T=>!E||T.id!==E.id);n(E),i(k)}catch(y){h(y.message||"Fehler beim Laden der Trainingspläne.")}finally{o(!1)}},[f,t,e==null?void 0:e.id]);P.useEffect(()=>{g()},[g]);const w=P.useCallback(async({analysis:y,durationWeeks:m=4,sessionsPerWeek:p=3,sessions:_=null})=>{if(!f||!t)return{ok:!1,error:new Error("Supabase oder PAT-Typ nicht verfügbar.")};c(!0),h("");try{const x=_||bu({topWeaknesses:(y==null?void 0:y.topWeaknesses)||[],topStrengths:(y==null?void 0:y.topStrengths)||[],durationWeeks:m,sessionsPerWeek:p}).sessions,S=await sg({patType:t,analysisSnapshot:y,durationWeeks:m,sessionsPerWeek:p,sessions:x});if(!S.ok)throw S.error;return await g(),{ok:!0,planId:S.planId}}catch(x){return h(x.message||"Fehler beim Speichern des Trainingsplans."),{ok:!1,error:x}}finally{c(!1)}},[f,g,t]),v=P.useCallback(async(y,m)=>{if(!f)return{ok:!1};const p=m==="done"?new Date().toISOString():null,_=r,x=s;n(E=>Ws(E,y,{state:m,completedAt:p})),i(E=>E.map(k=>Ws(k,y,{state:m,completedAt:p})));const{error:S}=await W.from("training_plan_sessions").update({state:m,completed_at:p}).eq("id",y);return S?(n(_),i(x),h(S.message||"Session-Status konnte nicht gespeichert werden."),{ok:!1,error:S}):{ok:!0}},[r,f,s]),b=P.useCallback(async(y,m)=>{if(!f)return{ok:!1};const p={...m},_=r,x=s;n(k=>Ws(k,y,p)),i(k=>k.map(T=>Ws(T,y,p)));const S={};Object.prototype.hasOwnProperty.call(p,"mainExercise")&&(S.main_exercise=p.mainExercise),Object.prototype.hasOwnProperty.call(p,"secondaryExercises")&&(S.secondary_exercises=p.secondaryExercises),Object.prototype.hasOwnProperty.call(p,"tasks")&&(S.tasks=p.tasks),Object.prototype.hasOwnProperty.call(p,"notes")&&(S.notes=p.notes);const{error:E}=await W.from("training_plan_sessions").update(S).eq("id",y);return E?(n(_),i(x),h(E.message||"Session-Änderung konnte nicht gespeichert werden."),{ok:!1,error:E}):{ok:!0}},[r,f,s]);return{activePlan:r,historyPlans:s,loading:a,saving:l,error:d,loadPlans:g,saveGeneratedPlan:w,updateSessionState:v,updateSessionPartial:b}},hb=(e,t=26)=>e.length>t?`${e.slice(0,t-1)}…`:e;function fb({metrics:e=[]}){const t=[...e].sort((h,f)=>f.priorityScore-h.priorityScore).slice(0,8);if(!t.length)return u.jsx("div",{className:"rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 bg-white/70 dark:bg-gray-900/70 p-4 text-sm text-gray-600 dark:text-gray-300",children:"Kein Gap-Chart verfügbar."});const r=760,n=220,s=24,i=38,a=20,l=a+24+i*t.length,c=Math.max(...t.map(h=>h.priorityScore),.01),d=r-n-s;return u.jsxs("div",{className:"rounded-2xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4 shadow-sm h-full flex flex-col",children:[u.jsx("h3",{className:"text-sm font-semibold text-gray-800 dark:text-gray-100 mb-3",children:"Gap-Bar-Chart (Priorität)"}),u.jsx("svg",{viewBox:`0 0 ${r} ${l}`,className:"w-full h-auto",role:"img","aria-label":"Gap-Balkendiagramm",children:t.map((h,f)=>{const g=a+f*i,w=h.priorityScore/c*d;return u.jsxs("g",{children:[u.jsx("text",{x:10,y:g+20,className:"fill-gray-700 dark:fill-gray-200",style:{fontSize:12,fontWeight:500},children:hb(h.name)}),u.jsx("rect",{x:n,y:g+8,width:d,height:16,rx:8,className:"fill-gray-200 dark:fill-gray-800"}),u.jsx("rect",{x:n,y:g+8,width:Math.max(3,w),height:16,rx:8,className:"fill-rose-500"}),u.jsx("text",{x:n+Math.max(8,w)+8,y:g+20,className:"fill-gray-700 dark:fill-gray-300",style:{fontSize:11,fontWeight:600},children:h.priorityScore.toFixed(2)})]},h.name)})})]})}const Hs=(e,t,r,n)=>({x:e+r*Math.cos(n),y:t+r*Math.sin(n)}),pb=(e,t=16)=>e.length>t?`${e.slice(0,t-1)}…`:e;function gb({radarSeries:e=[]}){const t=e.slice(0,6);if(!t.length)return u.jsx("div",{className:"rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 bg-white/70 dark:bg-gray-900/70 p-4 text-sm text-gray-600 dark:text-gray-300",children:"Kein Radarprofil verfügbar."});const r=420,n=320,s=r/2,i=n/2,a=105,o=Math.PI*2/t.length,l=(d,h)=>{const f=-Math.PI/2+h*o;return Hs(s,i,a*(Math.max(0,Math.min(1.2,d))/1.2),f)},c=t.map((d,h)=>{const f=l(d.ratio,h);return`${f.x},${f.y}`}).join(" ");return u.jsxs("div",{className:"rounded-2xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4 shadow-sm h-full flex flex-col",children:[u.jsx("h3",{className:"text-sm font-semibold text-gray-800 dark:text-gray-100 mb-3",children:"Radar-Profil (Ist/Soll)"}),u.jsxs("svg",{viewBox:`0 0 ${r} ${n}`,className:"w-full h-auto max-w-[420px] mx-auto",role:"img","aria-label":"Radarprofil",children:[[.25,.5,.75,1].map(d=>u.jsx("polygon",{points:t.map((h,f)=>{const g=-Math.PI/2+f*o,w=Hs(s,i,a*d,g);return`${w.x},${w.y}`}).join(" "),fill:"none",className:"stroke-gray-300 dark:stroke-gray-700",strokeWidth:"1"},d)),t.map((d,h)=>{const f=-Math.PI/2+h*o,g=Hs(s,i,a+16,f),w=Hs(s,i,a,f);return u.jsxs("g",{children:[u.jsx("line",{x1:s,y1:i,x2:w.x,y2:w.y,className:"stroke-gray-300 dark:stroke-gray-700",strokeWidth:"1"}),u.jsx("text",{x:g.x,y:g.y,textAnchor:"middle",className:"fill-gray-600 dark:fill-gray-300",style:{fontSize:10},children:pb(d.name)})]},d.name)}),u.jsx("polygon",{points:c,className:"fill-sky-300/40 dark:fill-sky-500/30 stroke-sky-600 dark:stroke-sky-400",strokeWidth:"2"})]})]})}const mb=e=>Math.round(Math.max(0,Math.min(1.5,e))*100);function yb({strengths:e=[]}){return e.length?u.jsxs("div",{className:"rounded-2xl border border-emerald-200 dark:border-emerald-900 bg-white dark:bg-gray-900 p-5 shadow-sm",children:[u.jsx("h3",{className:"text-lg font-semibold text-emerald-700 dark:text-emerald-300 mb-4",children:"Top-3 Stärken"}),u.jsx("div",{className:"space-y-3",children:e.map((t,r)=>u.jsxs("div",{className:"rounded-xl border border-emerald-100 dark:border-emerald-900/60 bg-emerald-50/60 dark:bg-emerald-950/20 p-3",children:[u.jsxs("div",{className:"flex items-center justify-between gap-3",children:[u.jsxs("p",{className:"font-semibold text-gray-900 dark:text-gray-100",children:[r+1,". ",t.name]}),u.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-emerald-200/70 dark:bg-emerald-800/60 text-emerald-800 dark:text-emerald-200 font-semibold",children:mb(t.strengthScore)})]}),u.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-xs text-gray-600 dark:text-gray-300",children:[u.jsxs("p",{children:["Ist: ",t.actualMean.toFixed(2)]}),u.jsxs("p",{children:["Soll: ",t.soll.toFixed(2)]}),u.jsxs("p",{children:["Trend: ",t.trendDelta.toFixed(2)]})]})]},t.name))})]}):u.jsx("div",{className:"rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 bg-white/70 dark:bg-gray-900/70 p-4 text-sm text-gray-600 dark:text-gray-300",children:"Keine Stärken-Daten verfügbar."})}const od=e=>{if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(t)},vb=(e,t)=>e.type!=="main"?e:{...e,intensity:t,repetitions:{hoch:24,mittel:18,leicht:12}[t]||18},wb=e=>e?"bg-indigo-600 text-white border-indigo-600":"bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-200 border-gray-300 dark:border-gray-700";function bb({patType:e,analysis:t,activePlan:r,historyPlans:n,loading:s,saving:i,error:a,onSavePlan:o,onUpdateSessionState:l,onUpdateSessionPartial:c,onReload:d}){const[h,f]=P.useState(4),[g,w]=P.useState(3),[v,b]=P.useState([]),[y,m]=P.useState(""),p=P.useMemo(()=>{const k=v.length,T=v.filter(K=>K.intensity==="hoch").length,C=v.filter(K=>K.intensity==="mittel").length,z=v.filter(K=>K.intensity==="leicht").length;return{total:k,high:T,medium:C,low:z}},[v]),_=()=>{const k=bu({topWeaknesses:(t==null?void 0:t.topWeaknesses)||[],topStrengths:(t==null?void 0:t.topStrengths)||[],durationWeeks:h,sessionsPerWeek:g,sessionMix:"1-main-2-secondary"});b(k.sessions),m("Neuer Entwurf erstellt. Du kannst jetzt Intensität und Übungen je Session anpassen.")},x=(k,T)=>{b(C=>C.map((z,K)=>{if(K!==k)return z;const Y={...z,...T};return Object.prototype.hasOwnProperty.call(T,"intensity")&&(Y.tasks=Y.tasks.map(Ne=>vb(Ne,T.intensity))),Y}))},S=async()=>{var T;if(!v.length){m("Erstelle zuerst einen Entwurf.");return}const k=await o({analysis:t,durationWeeks:h,sessionsPerWeek:g,sessions:v});if(!(k!=null&&k.ok)){m(((T=k==null?void 0:k.error)==null?void 0:T.message)||"Trainingsplan konnte nicht gespeichert werden.");return}m("Trainingsplan gespeichert. Der vorherige aktive Plan wurde archiviert."),b([])},E=(k,T)=>{const C=k.secondaryExercises.join(", ");return u.jsxs("div",{className:"rounded-xl border border-sky-100 dark:border-sky-900/60 bg-sky-50/60 dark:bg-sky-950/20 p-3",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsxs("p",{className:"text-sm font-semibold text-sky-800 dark:text-sky-200",children:["Woche ",k.weekNo," · Einheit ",k.sessionNo]}),u.jsx("span",{className:"text-xs text-sky-700 dark:text-sky-300",children:k.intensity})]}),u.jsxs("div",{className:"grid md:grid-cols-3 gap-2 text-sm",children:[u.jsx("input",{value:k.mainExercise,onChange:z=>x(T,{mainExercise:z.target.value}),className:"px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900",placeholder:"Hauptübung"}),u.jsx("input",{value:C,onChange:z=>{const K=z.target.value.split(",").map(Y=>Y.trim()).filter(Boolean).slice(0,2);x(T,{secondaryExercises:K.length===2?K:[...K,"Positionsspiel Basis"].slice(0,2)})},className:"px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900",placeholder:"Nebenübungen, getrennt mit Komma"}),u.jsxs("select",{value:k.intensity,onChange:z=>x(T,{intensity:z.target.value}),className:"px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900",children:[u.jsx("option",{value:"hoch",children:"hoch"}),u.jsx("option",{value:"mittel",children:"mittel"}),u.jsx("option",{value:"leicht",children:"leicht"})]})]})]},`draft-${T}`)};return u.jsxs("section",{className:"rounded-2xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm",children:[u.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-3 mb-4",children:[u.jsxs("div",{children:[u.jsxs("h3",{className:"text-xl font-semibold text-gray-900 dark:text-gray-100",children:["Trainingsplan (",e,")"]}),u.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"1 aktiver Plan + Historie, Session-Status: offen / erledigt / übersprungen."})]}),u.jsx("button",{onClick:d,type:"button",className:"px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800",children:"Neu laden"})]}),a&&u.jsx("div",{className:"mb-3 rounded-lg border border-red-300 dark:border-red-800 bg-red-50 dark:bg-red-900/30 p-3 text-sm text-red-700 dark:text-red-200",children:a}),u.jsxs("div",{className:"grid md:grid-cols-4 gap-3 mb-4",children:[u.jsxs("label",{className:"text-sm text-gray-700 dark:text-gray-200",children:["Dauer",u.jsxs("select",{value:h,onChange:k=>f(Number(k.target.value)),className:"mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900",children:[u.jsx("option",{value:2,children:"2 Wochen"}),u.jsx("option",{value:4,children:"4 Wochen"}),u.jsx("option",{value:6,children:"6 Wochen"})]})]}),u.jsxs("label",{className:"text-sm text-gray-700 dark:text-gray-200",children:["Einheiten/Woche",u.jsxs("select",{value:g,onChange:k=>w(Number(k.target.value)),className:"mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900",children:[u.jsx("option",{value:2,children:"2"}),u.jsx("option",{value:3,children:"3"}),u.jsx("option",{value:4,children:"4"})]})]}),u.jsx("button",{onClick:_,type:"button",className:"md:self-end px-4 py-2 rounded-lg bg-indigo-600 text-white hover:bg-indigo-700",children:"Plan (neu) generieren"}),u.jsx("button",{onClick:S,type:"button",disabled:i||!v.length,className:"md:self-end px-4 py-2 rounded-lg bg-emerald-600 text-white hover:bg-emerald-700 disabled:opacity-60",children:i?"Speichert…":"Entwurf speichern"})]}),y&&u.jsx("div",{className:"mb-4 rounded-lg border border-indigo-200 dark:border-indigo-800 bg-indigo-50 dark:bg-indigo-900/30 p-3 text-sm text-indigo-700 dark:text-indigo-200",children:y}),v.length>0&&u.jsxs("div",{className:"mb-6",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Entwurf (teilweise editierbar)"}),u.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:["Sessions: ",p.total," · hoch ",p.high," · mittel ",p.medium," · leicht ",p.low]})]}),u.jsx("div",{className:"max-h-80 overflow-y-auto space-y-2 pr-1",children:v.map(E)})]}),u.jsxs("div",{className:"grid lg:grid-cols-2 gap-4",children:[u.jsxs("div",{className:"rounded-xl border border-emerald-100 dark:border-emerald-900/60 p-3 bg-emerald-50/50 dark:bg-emerald-950/20",children:[u.jsx("h4",{className:"font-semibold text-emerald-800 dark:text-emerald-200 mb-2",children:"Aktiver Plan"}),s?u.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lädt…"}):r?u.jsxs(u.Fragment,{children:[u.jsxs("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2",children:["Generiert: ",od(r.generatedAt)," · ",r.durationWeeks," Wochen · ",r.sessionsPerWeek," Einheiten/Woche"]}),u.jsx("div",{className:"max-h-80 overflow-y-auto space-y-2 pr-1",children:r.sessions.map(k=>u.jsxs("div",{className:"rounded-lg border border-emerald-200/70 dark:border-emerald-800 bg-white dark:bg-gray-900 p-3",children:[u.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[u.jsxs("p",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:["W",k.weekNo," · E",k.sessionNo]}),u.jsx("div",{className:"flex gap-1",children:["open","done","skipped"].map(T=>u.jsx("button",{type:"button",onClick:()=>l(k.id,T),className:`text-xs px-2 py-1 border rounded ${wb(k.state===T)}`,children:T==="open"?"offen":T==="done"?"erledigt":"übersprungen"},T))})]}),u.jsx("input",{defaultValue:k.mainExercise,onBlur:T=>c(k.id,{mainExercise:T.target.value}),className:"w-full mb-2 px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900"}),u.jsx("input",{defaultValue:k.secondaryExercises.join(", "),onBlur:T=>c(k.id,{secondaryExercises:T.target.value.split(",").map(C=>C.trim()).filter(Boolean).slice(0,2)}),className:"w-full mb-2 px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900"}),u.jsx("textarea",{defaultValue:k.notes||"",onBlur:T=>c(k.id,{notes:T.target.value}),placeholder:"Notiz",className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900",rows:2})]},k.id))})]}):u.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Noch kein aktiver Trainingsplan vorhanden."})]}),u.jsxs("div",{className:"rounded-xl border border-gray-200 dark:border-gray-800 p-3 bg-gray-50 dark:bg-gray-950/40",children:[u.jsx("h4",{className:"font-semibold text-gray-900 dark:text-gray-100 mb-2",children:"Plan-Historie"}),n.length?u.jsx("div",{className:"space-y-2 max-h-80 overflow-y-auto pr-1",children:n.map(k=>u.jsxs("div",{className:"rounded-lg border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-3",children:[u.jsx("p",{className:"text-sm font-semibold text-gray-800 dark:text-gray-100",children:od(k.generatedAt)}),u.jsxs("p",{className:"text-xs text-gray-600 dark:text-gray-300",children:[k.durationWeeks," Wochen · ",k.sessionsPerWeek," Einheiten/Woche · ",k.sessions.length," Sessions"]})]},k.id))}):u.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine archivierten Pläne vorhanden."})]})]})]})}function _b({trendSeries:e=[]}){if(e.length<2)return u.jsx("div",{className:"rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 bg-white/70 dark:bg-gray-900/70 p-4 text-sm text-gray-600 dark:text-gray-300",children:"Für den Trend werden mindestens 2 Assessments benötigt."});const t=760,r=280,n=50,s=20,i=16,a=52,o=e.map(v=>v.totalPoints),l=Math.min(...o),d=Math.max(...o)-l||1,h=t-n-s,f=r-i-a,g=e.map((v,b)=>{const y=n+b/(e.length-1)*h,m=(v.totalPoints-l)/d,p=i+f-m*f;return{...v,x:y,y:p}}),w=g.map((v,b)=>`${b===0?"M":"L"}${v.x},${v.y}`).join(" ");return u.jsxs("div",{className:"rounded-2xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4 shadow-sm",children:[u.jsx("h3",{className:"text-sm font-semibold text-gray-800 dark:text-gray-100 mb-3",children:"Trend (Gesamtpunkte)"}),u.jsxs("svg",{viewBox:`0 0 ${t} ${r}`,className:"w-full h-auto",role:"img","aria-label":"Trenddiagramm",children:[u.jsx("line",{x1:n,y1:i,x2:n,y2:i+f,className:"stroke-gray-300 dark:stroke-gray-700",strokeWidth:"1"}),u.jsx("line",{x1:n,y1:i+f,x2:n+h,y2:i+f,className:"stroke-gray-300 dark:stroke-gray-700",strokeWidth:"1"}),u.jsx("path",{d:w,fill:"none",className:"stroke-indigo-500",strokeWidth:"3",strokeLinecap:"round"}),g.map(v=>u.jsxs("g",{children:[u.jsx("circle",{cx:v.x,cy:v.y,r:"4",className:"fill-indigo-500"}),u.jsx("text",{x:v.x,y:v.y-10,textAnchor:"middle",className:"fill-gray-700 dark:fill-gray-200",style:{fontSize:11,fontWeight:600},children:v.totalPoints}),u.jsx("text",{x:v.x,y:r-18,textAnchor:"middle",className:"fill-gray-500 dark:fill-gray-400",style:{fontSize:10},children:v.label})]},v.assessmentId))]})]})}const xb=e=>Math.round(Math.max(0,Math.min(1.5,e))*100);function kb({weaknesses:e=[]}){return e.length?u.jsxs("div",{className:"rounded-2xl border border-rose-200 dark:border-rose-900 bg-white dark:bg-gray-900 p-5 shadow-sm",children:[u.jsx("h3",{className:"text-lg font-semibold text-rose-700 dark:text-rose-300 mb-4",children:"Top-3 Schwächen"}),u.jsx("div",{className:"space-y-3",children:e.map((t,r)=>u.jsxs("div",{className:"rounded-xl border border-rose-100 dark:border-rose-900/60 bg-rose-50/60 dark:bg-rose-950/20 p-3",children:[u.jsxs("div",{className:"flex items-center justify-between gap-3",children:[u.jsxs("p",{className:"font-semibold text-gray-900 dark:text-gray-100",children:[r+1,". ",t.name]}),u.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-rose-200/70 dark:bg-rose-800/60 text-rose-800 dark:text-rose-200 font-semibold",children:xb(t.priorityScore)})]}),u.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-xs text-gray-600 dark:text-gray-300",children:[u.jsxs("p",{children:["Gap: ",t.gapScore.toFixed(2)]}),u.jsxs("p",{children:["Konstanz: ",t.consistencyScore.toFixed(2)]}),u.jsxs("p",{children:["Trend: ",t.trendDelta.toFixed(2)]})]})]},t.name))})]}):u.jsx("div",{className:"rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 bg-white/70 dark:bg-gray-900/70 p-4 text-sm text-gray-600 dark:text-gray-300",children:"Keine Schwächen-Daten verfügbar."})}function Sb({assessments:e,selectedPatType:t,onPatTypeChange:r,patTypes:n,user:s}){const i=Object.keys(n||{});P.useEffect(()=>{!t&&i.length&&r(i[0])},[r,i,t]);const a=P.useMemo(()=>Rf(e,t,{windowSize:5,missingStrategy:"zero"}),[e,t]),o=e.filter(p=>p.patType===t),l=e.length>0,{activePlan:c,historyPlans:d,loading:h,saving:f,error:g,saveGeneratedPlan:w,updateSessionState:v,updateSessionPartial:b,loadPlans:y}=db({user:s,patType:t}),m=({durationWeeks:p,sessionsPerWeek:_,sessions:x})=>w({analysis:a,durationWeeks:p,sessionsPerWeek:_,sessions:x});return u.jsx("div",{className:"min-h-screen bg-gradient-to-br from-cyan-50 via-white to-emerald-50 dark:from-gray-950 dark:via-gray-950 dark:to-gray-900 p-6 text-gray-900 dark:text-gray-100",children:u.jsxs("div",{className:"max-w-7xl mx-auto space-y-6",children:[u.jsxs("section",{className:"rounded-2xl border border-gray-200 dark:border-gray-800 bg-white/90 dark:bg-gray-900/80 backdrop-blur p-5 shadow-sm",children:[u.jsx("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:u.jsxs("div",{children:[u.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-cyan-700 dark:text-cyan-300",children:"Analyse"}),u.jsx("h1",{className:"text-2xl font-bold text-gray-900 dark:text-gray-100",children:"Wo solltest du besser werden?"}),u.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:"Priorisierung nach Gap × Faktor × Konstanz basierend auf den letzten 5 Assessments."})]})}),u.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:i.map(p=>{const _=p===t;return u.jsx("button",{type:"button",onClick:()=>r(p),className:`px-4 py-2 rounded-lg border text-sm font-semibold transition ${_?"bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900 border-gray-900 dark:border-gray-100":"bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-200 border-gray-300 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800"}`,children:p},p)})}),u.jsxs("div",{className:"mt-4 flex flex-wrap gap-2 text-xs",children:[u.jsxs("span",{className:"px-3 py-1 rounded-full border border-cyan-200 dark:border-cyan-800 bg-cyan-50 dark:bg-cyan-900/30 text-cyan-700 dark:text-cyan-200 font-semibold",children:[u.jsx(Sf,{className:"w-3 h-3 inline-block mr-1"}),"Assessments: ",o.length]}),u.jsxs("span",{className:"px-3 py-1 rounded-full border border-indigo-200 dark:border-indigo-800 bg-indigo-50 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-200 font-semibold",children:[u.jsx(Tf,{className:"w-3 h-3 inline-block mr-1"}),"Analysefenster: ",a.windowedAssessments.length,"/5"]}),a.isLimitedData&&u.jsxs("span",{className:"px-3 py-1 rounded-full border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-200 font-semibold",children:[u.jsx(Fm,{className:"w-3 h-3 inline-block mr-1"}),"Begrenzte Datenbasis"]})]})]}),l?o.length===0?u.jsxs("section",{className:"rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 bg-white/80 dark:bg-gray-900/70 p-6 text-center",children:[u.jsxs("h2",{className:"text-xl font-semibold text-gray-900 dark:text-gray-100 mb-1",children:["Keine Bewertungen für ",t]}),u.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Wähle einen anderen PAT-Typ oder erstelle eine neue Bewertung."})]}):u.jsxs(u.Fragment,{children:[u.jsxs("section",{className:"grid lg:grid-cols-2 gap-4",children:[u.jsx("div",{className:"h-full",children:u.jsx(fb,{metrics:a.exerciseMetrics})}),u.jsx("div",{className:"h-full",children:u.jsx(gb,{radarSeries:a.radarSeries})}),u.jsx("div",{className:"lg:col-span-2",children:u.jsx(_b,{trendSeries:a.trendSeries})})]}),u.jsxs("section",{className:"grid lg:grid-cols-2 gap-4",children:[u.jsx(kb,{weaknesses:a.topWeaknesses}),u.jsx(yb,{strengths:a.topStrengths})]}),u.jsx(bb,{patType:t,analysis:a,activePlan:c,historyPlans:d,loading:h,saving:f,error:g,onSavePlan:m,onUpdateSessionState:v,onUpdateSessionPartial:b,onReload:y})]}):u.jsxs("section",{className:"rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 bg-white/80 dark:bg-gray-900/70 p-6 text-center",children:[u.jsx(Km,{className:"w-10 h-10 mx-auto mb-3 text-gray-400 dark:text-gray-500"}),u.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-gray-100 mb-1",children:"Noch keine Daten für die Analyse"}),u.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:'Lege zuerst eine Bewertung im Bereich "Bewertungen" an.'})]})]})})}const Eb={"PAT Start":[{name:"1) Stoß-Geschwindigkeit",values:["","",""],soll:3,durchschnitt:0,faktor:33.33,points:0},{name:"2) Stoß-Gradlinigkeit",values:["","","",""],soll:2,durchschnitt:0,faktor:50,points:0},{name:"3) Winkelbälle",values:["","",""],soll:3,durchschnitt:0,faktor:33.33,points:0},{name:"4) Nachlauf Wirkung",values:["","",""],soll:9,durchschnitt:0,faktor:11.11,points:0},{name:"5) Rücklauf-Wirkung",values:["","",""],soll:7,durchschnitt:0,faktor:14.29,points:0},{name:"6) Kl. Positions-Spiel",subA:["","",""],subB:["","",""],soll:4,durchschnitt:0,faktor:25,points:0},{name:"7) Gr. Pos. Bereich",subA:["","",""],subB:["","",""],soll:5,durchschnitt:0,faktor:20,points:0},{name:"8) Press Bande",values:["","",""],soll:3,durchschnitt:0,faktor:33.33,points:0},{name:"9) Standardbälle",values:["","","","",""],soll:2,durchschnitt:0,faktor:50,points:0},{name:"10) 8-Ball Situation",values:["","",""],soll:3,durchschnitt:0,faktor:33.33,points:0}],"PAT 1":[{name:"1) Geschwindigkeit",values:["","",""],soll:3.33,durchschnitt:0,faktor:30,points:0,minValue:0,maxValue:4},{name:"2) Geradlinigkeit (Speed 2)",values:["","","",""],soll:2.5,durchschnitt:0,faktor:40,points:0,minValue:0,maxValue:3},{name:"3) Nachlauf",values:["","",""],soll:11,durchschnitt:0,faktor:9.1,points:0,minValue:0,maxValue:12},{name:"4) Rücklauf",values:["","",""],soll:10,durchschnitt:0,faktor:10,points:0,minValue:0,maxValue:12},{name:"5) Kl. Pos.-Bereich",subA:["","",""],subB:["","",""],subLabels:["1","2"],soll:3.33,durchschnitt:0,faktor:30,points:0,minValue:0,maxValue:5},{name:"6) Gr. Pos.-Bereich",subA:["","",""],subB:["","",""],subLabels:["1","2"],soll:3.33,durchschnitt:0,faktor:30,points:0,minValue:0,maxValue:6},{name:"7) Press Bande",subA:["","",""],subB:["","",""],subLabels:["1","2"],soll:4,durchschnitt:0,faktor:25,points:0,subValueRanges:{a:{minValue:0,maxValue:6},b:{minValue:0,maxValue:10}}},{name:"8) Endlos-Übung (Max: 9)",values:["","",""],soll:4.5,durchschnitt:0,faktor:22.22,points:0,minValue:0,maxValue:9},{name:"9) Standardbälle",values:["","","","",""],soll:2,durchschnitt:0,faktor:50,points:0,minValue:0,maxValue:3},{name:"10) 9-Ball Situation 5",values:["","",""],soll:4.5,durchschnitt:0,faktor:22.22,points:0,minValue:0,maxValue:9}],"PAT 2":[{name:"1) Übung PAT 2-1",values:["","",""],soll:3,durchschnitt:0,faktor:33.33,points:0},{name:"2) Übung PAT 2-2",values:["","",""],soll:3,durchschnitt:0,faktor:33.33,points:0},{name:"3) Übung PAT 2-3",values:["","",""],soll:3,durchschnitt:0,faktor:33.33,points:0}],"PAT 3":[{name:"1) Übung PAT 3-1",values:["","",""],soll:3,durchschnitt:0,faktor:33.33,points:0},{name:"2) Übung PAT 3-2",values:["","",""],soll:3,durchschnitt:0,faktor:33.33,points:0},{name:"3) Übung PAT 3-3",values:["","",""],soll:3,durchschnitt:0,faktor:33.33,points:0}]},qr=e=>e?JSON.parse(JSON.stringify(e)):null,hn=e=>e===null||typeof e>"u"?!1:typeof e=="string"?e.trim()!=="":!0,jb=(e={})=>e.subA&&e.subB?[...e.subA||[],...e.subB||[]].every(hn):(e.values||[]).every(hn),ig=e=>{if(!e||!hn(e.name)||!hn(e.datum))return!1;const t=e.exercises||[];return t.length?t.every(jb):!1},ag=e=>e?e.isFinalized?"Dieser Test wurde bereits final abgeschlossen":!hn(e.name)||!hn(e.datum)?"Bitte zuerst Name und Datum ausfüllen":ig(e)?"":"Bitte alle Übungsfelder ausfüllen, bevor du final abschließt":"Kein Test geöffnet",Nb=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(),Xa=e=>({id:e.id,patType:e.pat_type,datum:e.datum,name:e.name,exercises:qr(e.exercises||[]),isFinalized:!!e.is_finalized,finalizedAt:e.finalized_at||null,finalizationReminderSentAt:e.finalization_reminder_sent_at||null}),Tb=(e,t)=>({id:e.id,user_id:t,pat_type:e.patType,datum:e.datum,name:e.name,exercises:qr(e.exercises),is_finalized:!!e.isFinalized,finalized_at:e.finalizedAt||null,finalization_reminder_sent_at:e.finalizationReminderSentAt||null}),Pb=(e,t,r={})=>{const{onAfterSave:n}=r,[s,i]=P.useState([]),[a,o]=P.useState(null),[l,c]=P.useState(!1),d=P.useMemo(()=>!!W&&!!(t!=null&&t.id),[t]);P.useEffect(()=>{d&&h()},[d]);const h=async()=>{if(d)try{const{data:p,error:_}=await W.from("assessments").select("*").eq("user_id",t.id).order("created_at",{ascending:!1});if(_)throw _;i((p||[]).map(Xa))}catch(p){console.error("Fehler beim Laden:",p),alert("Fehler beim Laden der Daten aus Supabase: "+p.message)}},f=p=>{const _={id:Nb(),patType:p,datum:new Date().toISOString().split("T")[0],name:"",exercises:qr(e[p]),isFinalized:!1,finalizedAt:null,finalizationReminderSentAt:null};o(_),c(!1)},g=p=>{o(qr(p)),c(!1)},w=async({finalize:p=!1}={})=>{if(!(a!=null&&a.name)||!(a!=null&&a.datum))return alert("Bitte Name und Datum ausfüllen"),{ok:!1};if(a!=null&&a.isFinalized&&!p)return alert("Final abgeschlossene Bewertungen können nicht mehr geändert werden."),{ok:!1};if(p){const x=ag(a);if(x||!ig(a))return alert(x||"Bitte alle Felder ausfüllen, bevor du final abschließt."),{ok:!1}}if(!d)return alert("Supabase ist nicht konfiguriert. Bitte .env prüfen."),{ok:!1};const _=s.find(x=>x.id===a.id);try{const x=qr(a);x.name=x.name.trim(),p&&(x.isFinalized=!0,x.finalizedAt=new Date().toISOString(),x.finalizationReminderSentAt=null);const S=Tb(x,t.id);let E=null,k=[];if(_){const{data:T,error:C}=await W.from("assessments").update(S).eq("id",a.id).eq("user_id",t.id).select().single();if(C)throw C;E=Xa(T),k=s.map(z=>z.id===E.id?E:z),i(k),o(E)}else{const{data:T,error:C}=await W.from("assessments").insert(S).select().single();if(C)throw C;E=Xa(T),k=[E,...s.filter(z=>z.id!==E.id)],i(k),o(E)}if(typeof n=="function")try{await n({savedAssessment:E,assessments:k})}catch(T){console.warn("Post-save hook failed:",T)}return c(!1),{ok:!0,assessment:E,assessments:k}}catch(x){return alert("Fehler beim Speichern in Supabase: "+x.message),{ok:!1,error:x}}};return{assessments:s,currentAssessment:a,setCurrentAssessment:o,hasUnsavedChanges:l,setHasUnsavedChanges:c,createNewAssessment:f,openAssessment:g,handleSave:async()=>w(),finalizeAssessment:async()=>w({finalize:!0}),deleteAssessment:async p=>{if(!confirm("Möchten Sie diese Bewertung wirklich löschen?"))return;if(!d){alert("Supabase ist nicht konfiguriert. Bitte .env prüfen.");return}const{error:_}=await W.from("assessments").delete().eq("id",p).eq("user_id",t.id);if(_){alert("Fehler beim Löschen: "+_.message);return}i(x=>x.filter(S=>S.id!==p))},updateExerciseValue:(p,_,x,S=null)=>{if(!a||a.isFinalized)return;const E=qr(a),k=Cf(E.exercises[p],x,S);S==="a"?E.exercises[p].subA[_]=k:S==="b"?E.exercises[p].subB[_]=k:E.exercises[p].values[_]=k;const{durchschnitt:T,points:C}=Of(E.exercises[p]);E.exercises[p].durchschnitt=T,E.exercises[p].points=C,o(E),c(!0)},calculateTotal:()=>la((a==null?void 0:a.exercises)||[])}},Cb=e=>{if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}).format(t)};function Ab({assessments:e,loading:t=!1,error:r}){var s,i,a,o,l,c,d,h;const n=P.useMemo(()=>{if(t||!e)return{total:0,average:0,latest:null,best:null};if(!(e!=null&&e.length))return{total:0,average:0,latest:null,best:null};const f=e.map(b=>({...b,totalPoints:Math.round(la(b.exercises||[]))})),g=f.reduce((b,y)=>b+(y.totalPoints||0),0)/(f.length||1),w=f[0],v=f.reduce((b,y)=>!b||(y.totalPoints||0)>(b.totalPoints||0)?y:b,null);return{total:f.length,average:Math.round(g),latest:w,best:v}},[e]);return u.jsxs("div",{className:"bg-white/90 dark:bg-gray-900/80 border border-gray-100 dark:border-gray-800 rounded-2xl shadow-lg p-6 mb-6",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3 mb-4",children:[u.jsxs("div",{children:[u.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-emerald-600 dark:text-emerald-300",children:"Live Übersicht"}),u.jsx("h2",{className:"text-xl font-bold text-gray-900 dark:text-gray-100",children:"Aktuelle Statistik"}),u.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Basis: alle Bewertungen, geladen beim Seitenaufruf"})]}),u.jsx("span",{className:"rounded-full border border-emerald-200/70 dark:border-emerald-700 px-3 py-1 text-xs font-semibold text-emerald-700 dark:text-emerald-200 bg-emerald-50 dark:bg-emerald-900/40",children:t?"Lädt…":"Stand: jetzt"})]}),r&&u.jsx("div",{className:"mb-3 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/30 p-3 text-sm text-red-700 dark:text-red-200",children:r}),t?u.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[1,2,3,4].map(f=>u.jsx("div",{className:"h-28 rounded-2xl border border-gray-200/60 dark:border-gray-800 bg-gray-100 dark:bg-gray-800 animate-pulse"},f))}):n.total===0?u.jsx("div",{className:"rounded-xl border border-dashed border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/60 p-4 text-sm text-gray-600 dark:text-gray-300",children:"Noch keine Bewertungen vorhanden. Lege eine neue Bewertung an, um hier Live-Werte zu sehen."}):u.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[u.jsxs("div",{className:"rounded-2xl border border-emerald-200/70 dark:border-emerald-800 bg-gradient-to-br from-emerald-50 via-white to-emerald-50 dark:from-emerald-900/30 dark:via-gray-900 dark:to-emerald-900/20 p-4 shadow-sm",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("p",{className:"text-sm font-semibold text-emerald-700 dark:text-emerald-200",children:"Bewertungen"}),u.jsx(Sf,{className:"h-4 w-4 text-emerald-600 dark:text-emerald-300","aria-hidden":"true"})]}),u.jsx("p",{className:"mt-3 text-3xl font-bold text-emerald-800 dark:text-emerald-100",children:n.total}),u.jsx("p",{className:"text-xs text-emerald-700/80 dark:text-emerald-200/70",children:"In der PAT Datenbank hinterlegt"})]}),u.jsxs("div",{className:"rounded-2xl border border-sky-200/70 dark:border-sky-800 bg-gradient-to-br from-sky-50 via-white to-sky-50 dark:from-sky-900/30 dark:via-gray-900 dark:to-sky-900/20 p-4 shadow-sm",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("p",{className:"text-sm font-semibold text-sky-700 dark:text-sky-200",children:"Ø Gesamtpunkte"}),u.jsx(Pf,{className:"h-4 w-4 text-sky-600 dark:text-sky-300","aria-hidden":"true"})]}),u.jsx("p",{className:"mt-3 text-3xl font-bold text-sky-800 dark:text-sky-100",children:n.average}),u.jsx("p",{className:"text-xs text-sky-700/80 dark:text-sky-200/70",children:"Durchschnitt aller Assessments"})]}),u.jsxs("div",{className:"rounded-2xl border border-indigo-200/70 dark:border-indigo-800 bg-gradient-to-br from-indigo-50 via-white to-indigo-50 dark:from-indigo-900/30 dark:via-gray-900 dark:to-indigo-900/20 p-4 shadow-sm",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("p",{className:"text-sm font-semibold text-indigo-700 dark:text-indigo-200",children:"Letzte Bewertung"}),u.jsx(Ym,{className:"h-4 w-4 text-indigo-600 dark:text-indigo-300","aria-hidden":"true"})]}),u.jsx("p",{className:"mt-3 text-lg font-semibold text-indigo-900 dark:text-indigo-100",children:((s=n.latest)==null?void 0:s.name)||((i=n.latest)==null?void 0:i.patType)||"Unbenannt"}),u.jsxs("p",{className:"text-xs text-indigo-700/80 dark:text-indigo-200/70",children:[Cb((a=n.latest)==null?void 0:a.datum)," · ",((o=n.latest)==null?void 0:o.patType)||"PAT"]})]}),u.jsxs("div",{className:"rounded-2xl border border-amber-200/70 dark:border-amber-800 bg-gradient-to-br from-amber-50 via-white to-amber-50 dark:from-amber-900/30 dark:via-gray-900 dark:to-amber-900/20 p-4 shadow-sm",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("p",{className:"text-sm font-semibold text-amber-700 dark:text-amber-200",children:"Top Ergebnis"}),u.jsx(Hm,{className:"h-4 w-4 text-amber-600 dark:text-amber-300","aria-hidden":"true"})]}),u.jsx("p",{className:"mt-3 text-3xl font-bold text-amber-800 dark:text-amber-100",children:((l=n.best)==null?void 0:l.totalPoints)??0}),u.jsxs("p",{className:"text-xs text-amber-700/80 dark:text-amber-200/70",children:[((c=n.best)==null?void 0:c.name)||((d=n.best)==null?void 0:d.patType)||"—"," · ",((h=n.best)==null?void 0:h.patType)||"PAT"]})]})]})]})}const Ob=(e={})=>{const t={name:e.name||"",soll:e.soll??0,faktor:e.faktor??0};e.subA&&e.subB?(t.subA=e.subA,t.subB=e.subB,e.subLabels&&(t.subLabels=e.subLabels)):t.values=e.values||[];const{durchschnitt:r,points:n}=Of({...t,values:t.values||[]});return{...t,durchschnitt:r,points:n}},Rb=e=>({id:e.id,patType:e.pat_type,datum:e.datum,name:e.name,exercises:(e.exercises||[]).map(Ob)}),og=e=>Array.isArray(e)?e[0]||null:e||null,Ib=e=>{if(typeof window>"u")return`?share=${e}`;const t=new URL(window.location.origin+window.location.pathname);return t.searchParams.set("share",e),t.toString()},$b=async e=>{if(!e)throw new Error("Kein Test zum Teilen gefunden.");if(!W)throw new Error("Supabase ist nicht konfiguriert.");const{data:t,error:r}=await W.rpc("create_or_get_assessment_share",{p_assessment_id:e.id});if(r)throw r;const n=og(t);if(!(n!=null&&n.share_token))throw new Error("Kein Freigabetoken erhalten.");return{token:n.share_token,url:Ib(n.share_token)}},Db=async(e=[])=>{if(!W)throw new Error("Supabase ist nicht konfiguriert.");if(!e.length)return{};const{data:t,error:r}=await W.from("assessment_shares").select("assessment_id, share_token").in("assessment_id",e);if(r)throw r;return(t||[]).reduce((n,s)=>(n[s.assessment_id]=s.share_token,n),{})},Lb=async e=>{if(!W)throw new Error("Supabase ist nicht konfiguriert.");const{error:t}=await W.from("assessment_shares").delete().eq("assessment_id",e);if(t)throw t},zb=async e=>{if(!W)throw new Error("Supabase ist nicht konfiguriert.");const{data:t,error:r}=await W.rpc("get_shared_assessment",{p_share_token:e});if(r)throw r;const n=og(t);return n?Rb(n):null},Ub=async e=>{var t;return typeof navigator>"u"||!((t=navigator.clipboard)!=null&&t.writeText)?!1:(await navigator.clipboard.writeText(e),!0)},Mb=()=>typeof window<"u"&&["localhost","127.0.0.1"].includes(window.location.hostname);function Bb({user:e,activeTab:t="assessments",onEditingStateChange:r}){const n=P.useMemo(()=>Eb||{},[]),s=Object.keys(n),[i,a]=P.useState(!0),[o,l]=P.useState(()=>s[0]||""),[c,d]=P.useState(!1),[h,f]=P.useState({});P.useEffect(()=>{r==null||r(!i)},[r,i]),P.useEffect(()=>{s.length&&(!o||!s.includes(o))&&l(s[0])},[s,o]);const g=P.useCallback(async({savedAssessment:j,assessments:M})=>{var rt;if(!(j!=null&&j.patType)||!(M!=null&&M.length))return;const U=Rf(M,j.patType,{windowSize:5,missingStrategy:"zero"});if(!U.windowedAssessments.length)return;const fe=bu({topWeaknesses:U.topWeaknesses,topStrengths:U.topStrengths,durationWeeks:4,sessionsPerWeek:3,sessionMix:"1-main-2-secondary"}),Ge=await sg({patType:j.patType,analysisSnapshot:U,durationWeeks:4,sessionsPerWeek:3,sessions:fe.sessions});Ge.ok||console.warn("Automatische Plan-Neugenerierung fehlgeschlagen:",((rt=Ge.error)==null?void 0:rt.message)||Ge.error)},[]),{assessments:w,currentAssessment:v,setCurrentAssessment:b,hasUnsavedChanges:y,setHasUnsavedChanges:m,createNewAssessment:p,openAssessment:_,handleSave:x,finalizeAssessment:S,deleteAssessment:E,updateExerciseValue:k,calculateTotal:T}=Pb(n,e,{onAfterSave:g}),C=w,z=P.useMemo(()=>C.map(j=>j.id),[C]),K=P.useMemo(()=>w.some(j=>j.id===(v==null?void 0:v.id)),[w,v==null?void 0:v.id]),Y=!!(v!=null&&v.id&&h[v.id]),Ne=!!(v!=null&&v.isFinalized);P.useEffect(()=>{let j=!1;return(async()=>{if(!(e!=null&&e.id)||!z.length){f({});return}try{const U=await Db(z);j||f(U)}catch(U){console.warn("Freigaben konnten nicht geladen werden:",U),j||f({})}})(),()=>{j=!0}},[e==null?void 0:e.id,z]);const It=()=>{y&&!Ne?d(!0):a(!0)},Oe=async()=>{const j=await x();return j!=null&&j.ok&&alert("Erfolgreich gespeichert!"),j},bt=P.useCallback(async()=>{const j=await S();j!=null&&j.ok&&alert("Bewertung wurde final abgeschlossen und ist jetzt nur noch lesbar.")},[S]),A=async()=>{if(!(v!=null&&v.name)||!(v!=null&&v.datum)){alert("Bitte Name und Datum ausfüllen bevor Sie speichern");return}const j=await Oe();j!=null&&j.ok&&(d(!1),a(!0))},$=()=>{d(!1),m(!1),a(!0)},L=()=>{d(!1)},q=P.useCallback(async j=>{try{const{token:M,url:U}=await $b(j),fe=(j==null?void 0:j.name)||(j==null?void 0:j.patType)||"dieser Test",Ge=Mb()?` Hinweis: Der Link zeigt aktuell auf localhost und ist nur erreichbar, wenn die App von außen erreichbar ist.`:"";f(rt=>({...rt,[j.id]:M}));try{if(await Ub(U)){alert(`Freigabelink für "${fe}" wurde in die Zwischenablage kopiert.${Ge}`);return}}catch(rt){console.warn("Kopieren in die Zwischenablage fehlgeschlagen:",rt)}window.prompt(`Freigabelink für "${fe}"${Ge}`,U)}catch(M){alert(`Freigabelink konnte nicht erstellt werden: ${M.message||M}`)}},[]),re=P.useCallback(async j=>{const M=(j==null?void 0:j.name)||(j==null?void 0:j.patType)||"dieser Test";try{await Lb(j.id),f(U=>{const fe={...U};return delete fe[j.id],fe}),alert(`Freigabe für "${M}" wurde aufgehoben.`)}catch(U){alert(`Freigabe konnte nicht aufgehoben werden: ${U.message||U}`)}},[]),_t=P.useCallback(()=>{if(v){if(!K){alert("Bitte den Test zuerst speichern, bevor du ihn teilen kannst.");return}if(y){alert("Bitte erst speichern, damit der aktuelle Stand geteilt wird.");return}q(v)}},[v,q,y,K]),tt=P.useCallback(()=>{!v||!Y||re(v)},[v,re,Y]),sr=K?y?"Bitte erst speichern, damit der aktuelle Stand geteilt wird":"":"Bitte zuerst speichern",Me=ag(v);return i?t==="analysis"?u.jsx(Sb,{assessments:C,selectedPatType:o,onPatTypeChange:l,patTypes:n,user:e}):u.jsx(fy,{patTypes:n,assessments:C,overview:u.jsx(Ab,{assessments:C}),assessmentShareTokens:h,selectedPatType:o,onPatTypeChange:l,onCreate:j=>{p(j),a(!1)},onEdit:j=>{_(j),a(!1)},onDelete:E,getPatTypeColor:Yo,getAchievement:Xo}):u.jsx(Cy,{currentAssessment:v,hasUnsavedChanges:y,onBack:It,onSave:Oe,onAssessmentChange:b,onUpdateExercise:k,onMarkDirty:()=>m(!0),showSaveDialog:c,onSaveAndExit:A,onDiscardAndExit:$,onCancelExit:L,getPatTypeColor:Yo,getAchievement:Xo,calculateTotal:T,isReadOnly:Ne,canFinalize:!Me,finalizeDisabledReason:Me,onFinalize:bt,isShareActive:Y,canShare:K&&!y,shareDisabledReason:sr,onShare:_t,onRevokeShare:tt})}function Fb({onAuth:e,themeToggle:t,onBack:r}){const[n,s]=P.useState("login"),[i,a]=P.useState(""),[o,l]=P.useState(""),[c,d]=P.useState(""),[h,f]=P.useState(""),[g,w]=P.useState(!1),v=async b=>{if(b.preventDefault(),!!W){w(!0),f(""),d("");try{if(n==="login"){const{data:y,error:m}=await W.auth.signInWithPassword({email:i,password:o});m?f(m.message):(d("Erfolgreich angemeldet"),e==null||e(y.session))}else{const{data:y,error:m}=await W.auth.signUp({email:i,password:o});m?f(m.message):y.session?e==null||e(y.session):d("Registrierung abgeschlossen. Prüfe dein Postfach zur Bestätigung.")}}catch(y){f(y.message)}finally{w(!1)}}};return u.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-sky-100 via-blue-50 to-emerald-100 dark:from-gray-950 dark:via-gray-900 dark:to-gray-950 flex items-center justify-center p-6 text-gray-900 dark:text-gray-100",children:[u.jsx("div",{className:"absolute top-4 left-4 flex items-center gap-3",children:r&&u.jsxs("button",{type:"button",onClick:r,className:"inline-flex items-center gap-2 rounded-full border border-gray-200/70 bg-white/70 px-3 py-2 text-sm font-medium text-gray-800 shadow-sm backdrop-blur transition hover:-translate-y-[1px] hover:shadow-md dark:border-gray-800 dark:bg-gray-900/70 dark:text-gray-100",children:[u.jsx(Vm,{className:"h-4 w-4"}),"Zurück"]})}),u.jsx("div",{className:"absolute top-4 right-4",children:t}),u.jsxs("div",{className:"w-full max-w-lg bg-white/90 dark:bg-gray-900/80 backdrop-blur rounded-2xl shadow-xl border border-white/70 dark:border-gray-800",children:[u.jsxs("div",{className:"px-8 py-6 border-b border-gray-100 dark:border-gray-800",children:[u.jsx("p",{className:"text-sm uppercase tracking-wide text-indigo-600 dark:text-indigo-300 font-semibold",children:"PAT Stats"}),u.jsx("h1",{className:"text-3xl font-bold text-gray-900 dark:text-gray-100 mt-1",children:"Anmelden oder registrieren"}),u.jsx("p",{className:"text-gray-600 dark:text-gray-300 mt-2",children:"Melde dich mit deinem PAT-Test Konto an, um deine Bewertungen sicher zu verwalten."})]}),u.jsxs("form",{onSubmit:v,className:"px-8 py-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[u.jsx("button",{type:"button",onClick:()=>s("login"),className:`px-4 py-2 rounded-full transition ${n==="login"?"bg-indigo-600 text-white":"text-gray-600 dark:text-gray-300 hover:bg-indigo-50 dark:hover:bg-indigo-900/40"}`,children:"Login"}),u.jsx("button",{type:"button",onClick:()=>s("register"),className:`px-4 py-2 rounded-full transition ${n==="register"?"bg-emerald-600 text-white":"text-gray-600 dark:text-gray-300 hover:bg-emerald-50 dark:hover:bg-emerald-900/40"}`,children:"Registrieren"})]}),u.jsxs("label",{className:"block",children:[u.jsx("span",{className:"text-sm font-semibold text-gray-700 dark:text-gray-200",children:"E-Mail"}),u.jsx("input",{type:"email",value:i,onChange:b=>a(b.target.value),required:!0,className:"mt-1 w-full px-4 py-3 rounded-lg border border-gray-200 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white dark:bg-gray-800 dark:text-gray-100",placeholder:"you@example.com"})]}),u.jsxs("label",{className:"block",children:[u.jsx("span",{className:"text-sm font-semibold text-gray-700 dark:text-gray-200",children:"Passwort"}),u.jsx("input",{type:"password",value:o,onChange:b=>l(b.target.value),required:!0,className:"mt-1 w-full px-4 py-3 rounded-lg border border-gray-200 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white dark:bg-gray-800 dark:text-gray-100",placeholder:"••••••••"})]}),h&&u.jsx("div",{className:"p-3 rounded-lg bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-200 text-sm",children:h}),c&&u.jsx("div",{className:"p-3 rounded-lg bg-emerald-50 dark:bg-emerald-900/30 border border-emerald-200 dark:border-emerald-800 text-emerald-700 dark:text-emerald-200 text-sm",children:c}),u.jsx("button",{type:"submit",disabled:g,className:"w-full py-3 rounded-lg font-semibold text-white bg-gradient-to-r from-indigo-600 to-emerald-600 shadow-md hover:shadow-lg transition disabled:opacity-60 disabled:cursor-not-allowed",children:g?"Wird gesendet...":n==="login"?"Einloggen":"Konto erstellen"})]})]})]})}const Vb=[{label:"Datenschutz",path:"/datenschutz"},{label:"Impressum",path:"/impressum"},{label:"Kontakt",path:"/kontakt"}];function lg({children:e,themeToggle:t,onGetStarted:r,onNavigate:n,navLinks:s=[],currentPath:i="/"}){return u.jsxs("div",{className:"public-site",children:[u.jsx("div",{className:"public-site__backdrop"}),u.jsx("div",{className:"public-site__grid"}),u.jsxs("header",{className:"public-site__nav",children:[u.jsxs("button",{type:"button",className:"public-site__brand",onClick:()=>n("/"),children:[u.jsx("span",{className:"public-site__brand-mark",children:u.jsx(Tf,{className:"h-5 w-5","aria-hidden":"true"})}),u.jsxs("span",{className:"public-site__brand-copy",children:[u.jsx("span",{className:"public-site__brand-title",children:"PAT Manager"}),u.jsx("span",{className:"public-site__brand-subtitle",children:"Digitale Leistungsdiagnostik für Billard"})]})]}),u.jsx("nav",{className:"public-site__nav-links","aria-label":"Öffentliche Navigation",children:s.map(a=>u.jsx("button",{type:"button",className:`public-site__nav-link${a.active?" is-active":""}`,onClick:a.onClick,children:a.label},a.label))}),u.jsxs("div",{className:"public-site__nav-actions",children:[t&&u.jsx("div",{className:"public-site__theme-toggle",children:t}),u.jsxs("button",{type:"button",className:"public-site__cta public-site__cta--nav",onClick:r,children:["Anmelden",u.jsx(Ii,{className:"h-4 w-4","aria-hidden":"true"})]})]})]}),u.jsx("main",{className:"public-site__main",children:e}),u.jsx("footer",{className:"public-site__footer",children:u.jsxs("div",{className:"public-site__footer-inner",children:[u.jsxs("div",{className:"public-site__footer-links",children:[u.jsx("button",{type:"button",className:"public-site__footer-link",onClick:r,children:"Anmelden"}),Vb.map(a=>u.jsx("button",{type:"button",className:`public-site__footer-link${i===a.path?" is-active":""}`,onClick:()=>n(a.path),children:a.label},a.path))]}),u.jsx("p",{className:"public-site__footer-meta",children:"PAT Manager · Öffentliche Seiten"})]})})]})}const Wb=[{title:"Smarte Auswertungen",body:"Automatische Berechnungen für jede PAT-Kategorie mit klaren Kennzahlen, Trends und Fortschrittsbildern.",icon:Nf},{title:"Sichere Speicherung",body:"Nutzergebundene Datenhaltung, finale Abschlüsse und kontrollierte Freigaben für Trainer, Verein und Staff.",icon:jf},{title:"Team-ready",body:"Bewertungen erfassen, öffnen, teilen und wieder sperren, ohne Excel-Chaos oder doppelte Listen.",icon:uy},{title:"Performance-Insights",body:"Schwächen erkennen, Entwicklung verfolgen und Training gezielt auf die kritischen Übungen ausrichten.",icon:Pf},{title:"Mobile Erfassung",body:"Direkte Eingabe am Tisch mit klaren Grenzen pro Übung und sofortiger Berechnung der Punkte.",icon:iy},{title:"Export & Reports",body:"Saubere PDF-Ausgabe, öffentliche Freigabelinks und strukturierte Ergebnisansichten für Athleten und Staff.",icon:Ef}],Hb=[{title:"Vorlage wählen",body:"PAT Start, PAT 1, PAT 2 oder PAT 3 auswählen und die Bewertung sofort anlegen."},{title:"Werte erfassen",body:"Einzelwerte direkt eingeben, automatisch begrenzen lassen und live berechnen."},{title:"Abschließen & teilen",body:"Bewertung final abschließen, als PDF exportieren oder per Link freigeben."}],Kb=[{value:"100%",label:"Digitaler Ablauf"},{value:"0€",label:"Kostenlos starten"},{value:"SSL",label:"Verschlüsselte Übertragung"},{value:"24/7",label:"Jederzeit verfügbar"}],Ks=e=>{if(typeof document>"u")return;const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth",block:"start"})};function qb({onGetStarted:e,onNavigate:t,themeToggle:r}){return u.jsxs(lg,{themeToggle:r,onGetStarted:e,onNavigate:t,currentPath:"/",navLinks:[{label:"Features",onClick:()=>Ks("features")},{label:"So funktioniert es",onClick:()=>Ks("how-it-works")},{label:"Statistiken",onClick:()=>Ks("stats")}],children:[u.jsxs("section",{className:"public-hero",children:[u.jsxs("div",{children:[u.jsxs("span",{className:"public-hero__badge",children:[u.jsx(Nf,{className:"h-4 w-4","aria-hidden":"true"}),"Jetzt live verfügbar"]}),u.jsxs("h1",{className:"public-hero__title",children:["Professionelle",u.jsx("span",{className:"public-hero__title-accent",children:" PAT-Test Verwaltung"})]}),u.jsx("p",{className:"public-hero__copy",children:"Erfasse, analysiere und verfolge Pool Ability Tests digital. Von der Eingabe bis zum Report läuft alles in einer klaren Oberfläche für Trainer, Vereine und Spieler."}),u.jsxs("div",{className:"public-hero__actions",children:[u.jsxs("button",{type:"button",className:"public-site__button",onClick:e,children:["Kostenlos testen",u.jsx(Ii,{className:"h-4 w-4","aria-hidden":"true"})]}),u.jsx("button",{type:"button",className:"public-site__button--secondary",onClick:()=>Ks("features"),children:"Mehr erfahren"})]}),u.jsxs("div",{className:"public-hero__meta",children:[u.jsxs("span",{className:"public-chip",children:[u.jsx(Jo,{className:"h-4 w-4 text-blue-300","aria-hidden":"true"}),"PAT Start bis PAT 3"]}),u.jsxs("span",{className:"public-chip",children:[u.jsx(Jo,{className:"h-4 w-4 text-blue-300","aria-hidden":"true"}),"Teilen, PDF und Finalisierung"]})]})]}),u.jsxs("div",{className:"public-preview__panel",children:[u.jsxs("div",{className:"public-preview__head",children:[u.jsx("strong",{children:"Live Übersicht"}),u.jsx("span",{className:"public-preview__status",children:"Online"})]}),u.jsxs("div",{className:"public-preview__grid",children:[u.jsxs("div",{className:"public-preview__card",children:[u.jsx("div",{className:"public-preview__label",children:"PAT 1 · Übung 1"}),u.jsx("div",{className:"public-preview__value public-preview__value--accent",children:"4 / 4"}),u.jsx("div",{className:"public-progress",children:u.jsx("span",{style:{width:"100%"}})})]}),u.jsxs("div",{className:"public-preview__card",children:[u.jsx("div",{className:"public-preview__label",children:"Gesamtpunktzahl"}),u.jsx("div",{className:"public-preview__value public-preview__value--success",children:"87%"}),u.jsx("div",{className:"public-progress",children:u.jsx("span",{style:{width:"87%"}})})]})]}),u.jsxs("div",{className:"public-preview__meta",children:[u.jsxs("div",{className:"public-preview__meta-card",children:[u.jsx("div",{className:"public-preview__label",children:"Aktive Bewertung"}),u.jsx("strong",{children:"Stefan · PAT 1"})]}),u.jsxs("div",{className:"public-preview__meta-card",children:[u.jsx("div",{className:"public-preview__label",children:"Status"}),u.jsx("strong",{children:"Freigabe aktiv"})]}),u.jsxs("div",{className:"public-preview__meta-card",children:[u.jsx("div",{className:"public-preview__label",children:"Workflow"}),u.jsx("strong",{children:"Erfassen · Finalisieren"})]}),u.jsxs("div",{className:"public-preview__meta-card",children:[u.jsx("div",{className:"public-preview__label",children:"Auswertung"}),u.jsx("strong",{children:"PDF & Analyse"})]})]})]})]}),u.jsxs("section",{className:"public-section",id:"features",children:[u.jsxs("div",{className:"public-section__header",children:[u.jsx("span",{className:"public-section__tag",children:"Funktionen"}),u.jsx("h2",{className:"public-section__title",children:"Alles, was du für PAT-Tests brauchst"}),u.jsx("p",{className:"public-section__copy",children:"Von der digitalen Erfassung bis zur teamweiten Auswertung. Die neue Startseite orientiert sich an deiner Vorlage, sitzt aber sauber im bestehenden Produktstil."})]}),u.jsx("div",{className:"public-features",children:Wb.map(({title:n,body:s,icon:i})=>u.jsxs("article",{className:"public-card",children:[u.jsx("span",{className:"public-card__icon",children:u.jsx(i,{className:"h-5 w-5","aria-hidden":"true"})}),u.jsx("h3",{className:"public-card__title",children:n}),u.jsx("p",{className:"public-card__copy",children:s})]},n))})]}),u.jsxs("section",{className:"public-section",id:"how-it-works",children:[u.jsxs("div",{className:"public-section__header",children:[u.jsx("span",{className:"public-section__tag",children:"Prozess"}),u.jsx("h2",{className:"public-section__title",children:"So läuft PAT mit uns"}),u.jsx("p",{className:"public-section__copy",children:"Von der Testvorlage bis zum Report bleibt der Ablauf kurz, klar und sicher."})]}),u.jsx("div",{className:"public-steps",children:Hb.map((n,s)=>u.jsxs("article",{className:"public-card public-step",children:[u.jsx("span",{className:"public-step__number",children:s+1}),u.jsx("h3",{className:"public-step__title",children:n.title}),u.jsx("p",{className:"public-step__copy",children:n.body})]},n.title))})]}),u.jsxs("section",{className:"public-section",id:"stats",children:[u.jsxs("div",{className:"public-section__header",children:[u.jsx("span",{className:"public-section__tag",children:"Statistiken"}),u.jsx("h2",{className:"public-section__title",children:"Klare Vorteile für den Alltag am Tisch"}),u.jsx("p",{className:"public-section__copy",children:"Weniger Listenpflege, weniger Medienbrüche und deutlich schneller von der Eingabe zur Auswertung."})]}),u.jsx("div",{className:"public-stats",children:Kb.map(n=>u.jsxs("article",{className:"public-stats__card",children:[u.jsx("div",{className:"public-stats__value",children:n.value}),u.jsx("div",{className:"public-stats__label",children:n.label})]},n.label))})]}),u.jsx("section",{className:"public-section",children:u.jsxs("div",{className:"public-cta-panel",children:[u.jsxs("div",{children:[u.jsx("span",{className:"public-section__tag",children:"Bereit?"}),u.jsx("h2",{className:"public-cta-panel__title",children:"Starte deine nächste PAT-Bewertung ohne Tabellenchaos."}),u.jsx("p",{className:"public-cta-panel__copy",children:"Login öffnen, Bewertung anlegen, Werte eintragen und Ergebnisse direkt sauber speichern oder teilen."})]}),u.jsxs("div",{className:"public-cta-panel__actions",children:[u.jsxs("button",{type:"button",className:"public-site__button",onClick:e,children:["Jetzt kostenlos ausprobieren",u.jsx(Ii,{className:"h-4 w-4","aria-hidden":"true"})]}),u.jsx("button",{type:"button",className:"public-site__button--secondary",onClick:()=>t("/kontakt"),children:"Kontakt öffnen"})]})]})})]})}const Gb=e=>{if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}).format(t)},Jb=e=>e===""||e===null||typeof e>"u"?"—":e,Za=({label:e,values:t=[]})=>u.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[u.jsx("span",{className:"min-w-10 text-sm font-semibold text-gray-600 dark:text-gray-300",children:e}),t.map((r,n)=>u.jsx("span",{className:"min-w-12 rounded-md border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-3 py-2 text-center text-sm font-medium text-gray-800 dark:text-gray-100",children:Jb(r)},`${e}-${n}`))]});function Qb({assessment:e}){if(!e)return null;const t=la(e.exercises||[]),r=Xo(e.patType,t);return u.jsx("div",{className:"min-h-screen bg-gray-100 dark:bg-gray-950 p-6 text-gray-900 dark:text-gray-100",children:u.jsx("div",{className:"max-w-5xl mx-auto",children:u.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-lg p-6 border border-gray-200 dark:border-gray-800",children:[u.jsxs("div",{className:"flex justify-between items-start gap-4 mb-6 flex-wrap",children:[u.jsxs("div",{children:[u.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-sky-700 dark:text-sky-300",children:"Geteilter Test"}),u.jsx("h1",{className:"text-3xl font-bold text-gray-800 dark:text-gray-100 mt-2",children:e.name||"PAT Test"}),u.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 mt-2",children:"Dieser Link zeigt nur diesen einen Test im Nur-Lesen-Modus."})]}),u.jsx("span",{className:`px-4 py-2 rounded-full text-sm font-semibold ${Yo(e.patType)}`,children:e.patType})]}),u.jsxs("div",{className:"grid md:grid-cols-3 gap-3 mb-6 bg-gray-50 dark:bg-gray-800 p-4 rounded-lg",children:[u.jsxs("div",{children:[u.jsx("p",{className:"text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400",children:"Datum"}),u.jsx("p",{className:"mt-1 text-lg font-semibold",children:Gb(e.datum)})]}),u.jsxs("div",{children:[u.jsx("p",{className:"text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400",children:"Gesamtpunkte"}),u.jsx("p",{className:"mt-1 text-lg font-semibold text-green-600 dark:text-green-300",children:t.toFixed(0)})]}),u.jsxs("div",{children:[u.jsx("p",{className:"text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400",children:"Bewertung"}),u.jsx("p",{className:"mt-1 text-lg font-semibold",children:r.name})]})]}),(e.exercises||[]).map((n,s)=>{var i,a;return u.jsxs("div",{className:"mb-6 border-b pb-4 border-gray-200 dark:border-gray-800",children:[u.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3 flex-wrap",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"font-bold text-lg text-gray-700 dark:text-gray-200",children:n.name}),u.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:["Soll ",n.soll," · Faktor ",n.faktor]})]}),u.jsxs("div",{className:"rounded-lg bg-green-50 dark:bg-green-900/30 px-4 py-2",children:[u.jsx("p",{className:"text-xs uppercase tracking-wide text-green-700 dark:text-green-300",children:"Points"}),u.jsx("p",{className:"text-xl font-bold text-green-700 dark:text-green-200",children:(n.points||0).toFixed(0)})]})]}),u.jsx("div",{className:"space-y-3",children:n.subA&&n.subB?u.jsxs(u.Fragment,{children:[u.jsx(Za,{label:((i=n.subLabels)==null?void 0:i[0])||"a)",values:n.subA}),u.jsx(Za,{label:((a=n.subLabels)==null?void 0:a[1])||"b)",values:n.subB})]}):u.jsx(Za,{label:"Werte",values:n.values||[]})}),u.jsxs("div",{className:"grid md:grid-cols-3 gap-3 mt-4",children:[u.jsxs("div",{className:"rounded-lg bg-blue-50 dark:bg-blue-900/30 px-4 py-3",children:[u.jsx("p",{className:"text-xs uppercase tracking-wide text-blue-700 dark:text-blue-300",children:"Durchschnitt"}),u.jsx("p",{className:"text-lg font-semibold text-blue-700 dark:text-blue-200",children:(n.durchschnitt||0).toFixed(2)})]}),u.jsxs("div",{className:"rounded-lg bg-gray-50 dark:bg-gray-800 px-4 py-3",children:[u.jsx("p",{className:"text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400",children:"Soll"}),u.jsx("p",{className:"text-lg font-semibold",children:n.soll})]}),u.jsxs("div",{className:"rounded-lg bg-gray-50 dark:bg-gray-800 px-4 py-3",children:[u.jsx("p",{className:"text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400",children:"Faktor"}),u.jsx("p",{className:"text-lg font-semibold",children:n.faktor})]})]})]},`${n.name}-${s}`)}),u.jsxs("div",{className:"mt-6 bg-gradient-to-r from-green-100 to-blue-100 dark:from-gray-800 dark:to-gray-700 p-6 rounded-lg",children:[u.jsxs("div",{className:"flex justify-between items-center gap-4 flex-wrap mb-4",children:[u.jsx("span",{className:"text-2xl font-bold text-gray-800 dark:text-gray-100",children:"Ergebnis"}),u.jsx("span",{className:"text-4xl font-bold text-green-600 dark:text-green-300",children:t.toFixed(0)})]}),u.jsxs("div",{className:`mt-4 px-6 py-4 rounded-lg ${r.color} ${r.text} text-center`,children:[u.jsx("p",{className:"text-2xl font-bold",children:r.name}),r.subtitle&&u.jsx("p",{className:"text-lg mt-2",children:r.subtitle})]})]})]})})})}function Yb({shareToken:e,themeToggle:t}){const[r,n]=P.useState(null),[s,i]=P.useState(!0),[a,o]=P.useState("");return P.useEffect(()=>{let l=!1;return(async()=>{if(!e){o("Freigabelink fehlt."),i(!1);return}i(!0),o("");try{const d=await zb(e);if(l)return;if(!d){n(null),o("Dieser Freigabelink ist ungültig oder nicht mehr verfügbar.");return}n(d)}catch(d){if(l)return;n(null),o(d.message||"Geteilter Test konnte nicht geladen werden.")}finally{l||i(!1)}})(),()=>{l=!0}},[e]),u.jsxs("div",{className:"min-h-screen bg-gray-100 dark:bg-gray-950 text-gray-900 dark:text-gray-100",children:[u.jsx("div",{className:"absolute top-4 right-4 z-20",children:t}),s?u.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",children:u.jsx("div",{className:"bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 shadow-sm p-6",children:"Geteilter Test wird geladen..."})}):a?u.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",children:u.jsxs("div",{className:"max-w-xl w-full bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 shadow-sm p-6",children:[u.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-rose-600 dark:text-rose-300",children:"Freigabe"}),u.jsx("h1",{className:"text-2xl font-bold mt-2",children:"Geteilter Test nicht verfügbar"}),u.jsx("p",{className:"text-gray-600 dark:text-gray-300 mt-3",children:a})]})}):u.jsx(Qb,{assessment:r})]})}const ld={"/datenschutz":{tag:"Datenschutz",title:"Datenschutzhinweise für PAT Manager",intro:"Diese Seite ist als saubere öffentliche Datenschutzansicht angelegt. Inhaltlich solltest du sie vor dem Livegang noch mit deinen finalen Verantwortlichen, Kontaktdaten und juristisch geprüften Angaben vervollständigen.",cards:[{title:"Verantwortliche Stelle",body:"Trage hier den Vereinsnamen, die verantwortliche Person oder das Unternehmen ein, das PAT Manager betreibt. Ergänze außerdem Anschrift und eine echte Kontaktmöglichkeit."},{title:"Welche Daten verarbeitet werden",body:"Je nach Nutzung können Anmeldedaten, Bewertungsdaten, Freigaben, PDF-Exporte und technische Zugriffsdaten verarbeitet werden. Bei geteilten Bewertungen sehen anonyme Nutzer nur die explizit freigegebene Ansicht."},{title:"Zweck der Verarbeitung",body:"Die Verarbeitung dient der Durchführung von PAT-Bewertungen, der Auswertung von Leistungsdaten, der Teamorganisation sowie dem sicheren Speichern und Teilen einzelner Testergebnisse."},{title:"Speicherung und Dienstleister",body:"Die Anwendung nutzt Supabase als technische Datenbasis. Prüfe vor dem produktiven Einsatz die Auftragsverarbeitung, Speicherregion und die tatsächlich eingesetzten Zusatzdienste."},{title:"Rechte der betroffenen Personen",items:["Auskunft über gespeicherte Daten","Berichtigung unrichtiger Daten","Löschung oder Einschränkung der Verarbeitung","Widerspruch gegen einzelne Verarbeitungen","Beschwerde bei der zuständigen Aufsichtsbehörde"]},{title:"Wichtiger Hinweis",wide:!0,notice:"Diese Datenschutzseite ist eine strukturierte Vorlage. Vor der Veröffentlichung müssen echte Kontaktdaten, Rechtsgrundlagen, Speicherfristen und Dienstleisterangaben ergänzt und geprüft werden."}]},"/impressum":{tag:"Impressum",title:"Impressum für PAT Manager",intro:"Die Seite ist technisch fertig eingebunden, damit deine Footer- und Navigationslinks nicht mehr ins Leere laufen. Die konkreten Pflichtangaben musst du jetzt noch mit deinen echten Daten ergänzen.",cards:[{title:"Angaben gemäß § 5 TMG",body:"Ergänze hier Betreibername, Rechtsform, vertretungsberechtigte Person sowie die vollständige ladungsfähige Anschrift."},{title:"Kontakt",body:"Trage hier eine echte E-Mail-Adresse, optional Telefonnummer und weitere Kommunikationswege ein, unter denen Nutzer dich rechtssicher erreichen können."},{title:"Verantwortlich für den Inhalt",body:"Wenn erforderlich, ergänze die verantwortliche Person nach § 18 Abs. 2 MStV mit Name und Anschrift."},{title:"Haftungs- und Linkhinweise",body:"Wenn du externe Dienste, Inhalte oder Verlinkungen nutzt, prüfe bitte deine endgültigen Texte zu Haftung, Urheberrecht und externen Verweisen."},{title:"Wichtiger Hinweis",wide:!0,notice:"Dieses Impressum enthält absichtlich keine erfundenen Unternehmensdaten. Bitte ersetze die Platzhalter vor Veröffentlichung durch deine echten Pflichtangaben."}]},"/kontakt":{tag:"Kontakt",title:"Kontakt und Rückfragen",intro:"Hier ist eine öffentliche Kontaktseite im Stil der neuen Startseite eingebunden. Wenn du reale Ansprechpartner und Kanäle ergänzt, kannst du sie direkt produktiv nutzen.",cards:[{title:"Produkt & Demo",body:"Nutze diesen Bereich für Anfragen zu PAT Manager, Demos, Vereinsnutzung oder Einführung im Trainingsalltag."},{title:"Technischer Support",body:"Hier kannst du später Support-Zeiten, E-Mail-Adresse, Reaktionszeiten oder einen Helpdesk-Link ergänzen."},{title:"Kooperationen",body:"Platz für Kontakte zu Vereinen, Trainern, Leistungszentren oder Partnern, die das System einsetzen oder testen möchten."},{title:"Empfohlene nächste Ergänzungen",items:["Echte Support-E-Mail oder Kontaktformular verknüpfen","Antwortzeiten und Zuständigkeiten ergänzen","Optional Telefonnummer oder Vereinsanschrift angeben"]},{title:"Schnellzugriff",wide:!0,action:!0,body:"Wenn du direkt in die Anwendung wechseln willst, kannst du von hier aus sofort den Login öffnen und weiterarbeiten."}]}};function Xb({path:e,onGetStarted:t,onNavigate:r,themeToggle:n}){const s=ld[e]||ld["/kontakt"];return u.jsx(lg,{themeToggle:n,onGetStarted:t,onNavigate:r,currentPath:e,navLinks:[{label:"Startseite",onClick:()=>r("/")},{label:"Datenschutz",onClick:()=>r("/datenschutz"),active:e==="/datenschutz"},{label:"Impressum",onClick:()=>r("/impressum"),active:e==="/impressum"},{label:"Kontakt",onClick:()=>r("/kontakt"),active:e==="/kontakt"}],children:u.jsxs("section",{className:"public-page",children:[u.jsxs("div",{className:"public-page__hero",children:[u.jsxs("span",{className:"public-section__tag",children:[e==="/kontakt"?u.jsx(ey,{className:"h-4 w-4","aria-hidden":"true"}):u.jsx(Xm,{className:"h-4 w-4","aria-hidden":"true"}),s.tag]}),u.jsx("h1",{className:"public-page__title",children:s.title}),u.jsx("p",{className:"public-page__copy",children:s.intro})]}),u.jsx("div",{className:"public-page__grid",children:s.cards.map(i=>u.jsxs("article",{className:`public-page__card${i.wide?" public-page__card--wide":""}`,children:[u.jsx("h2",{className:"public-page__card-title",children:i.title}),i.body&&u.jsx("p",{className:"public-page__card-copy",children:i.body}),i.items&&u.jsx("ul",{className:"public-page__list",children:i.items.map(a=>u.jsx("li",{children:a},a))}),i.notice&&u.jsx("div",{className:"public-page__notice",children:i.notice}),i.action&&u.jsxs("div",{className:"public-hero__actions",children:[u.jsxs("button",{type:"button",className:"public-site__button",onClick:t,children:["Login öffnen",u.jsx(Ii,{className:"h-4 w-4","aria-hidden":"true"})]}),u.jsx("button",{type:"button",className:"public-site__button--secondary",onClick:()=>r("/"),children:"Zur Startseite"})]})]},i.title))}),u.jsx("section",{className:"public-section",children:u.jsxs("div",{className:"public-cta-panel",children:[u.jsxs("div",{children:[u.jsxs("span",{className:"public-section__tag",children:[u.jsx(jf,{className:"h-4 w-4","aria-hidden":"true"}),"Öffentliche Seiten fertig"]}),u.jsx("h2",{className:"public-cta-panel__title",children:"Die verlinkten Info-Seiten sind jetzt Bestandteil der App."}),u.jsx("p",{className:"public-cta-panel__copy",children:"Ergänze jetzt noch deine echten Vereins-, Kontakt- und Rechtstexte. Danach laufen Navigation und Footer sauber ohne Platzhalterlinks."})]}),u.jsxs("div",{className:"public-cta-panel__actions",children:[u.jsx("button",{type:"button",className:"public-site__button",onClick:()=>r("/"),children:"Zur Startseite"}),u.jsx("button",{type:"button",className:"public-site__button--secondary",onClick:t,children:"App öffnen"})]})]})})]})})}const eo=()=>typeof window>"u"?"":new URLSearchParams(window.location.search).get("share")||"",ud=()=>{if(typeof window>"u")return"/";const e=window.location.hash||"";return e.startsWith("#/")?e.slice(1):"/"};function Zb(){var _;const[e,t]=P.useState(null),[r,n]=P.useState(!0),[s,i]=P.useState(!1),[a,o]=P.useState("assessments"),[l,c]=P.useState(!1),[d,h]=P.useState(()=>eo()),[f,g]=P.useState(()=>ud()),[w,v]=P.useState(()=>{if(typeof window>"u")return"light";const x=localStorage.getItem("theme");return x==="light"||x==="dark"?x:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"});P.useEffect(()=>{const x=document.documentElement;w==="dark"?x.classList.add("dark"):x.classList.remove("dark"),localStorage.setItem("theme",w)},[w]),P.useEffect(()=>{const x=()=>{h(eo()),g(ud())};return window.addEventListener("popstate",x),window.addEventListener("hashchange",x),()=>{window.removeEventListener("popstate",x),window.removeEventListener("hashchange",x)}},[]),P.useEffect(()=>{if(d){n(!1);return}if(!W){n(!1);return}(async()=>{const{data:E,error:k}=await W.auth.getSession();k||t(E.session),n(!1)})();const{data:S}=W.auth.onAuthStateChange((E,k)=>{t(k)});return()=>{S==null||S.subscription.unsubscribe()}},[d]),P.useEffect(()=>{l&&a==="analysis"&&o("assessments")},[a,l]);const b=async()=>{W&&(await W.auth.signOut(),t(null),i(!1),o("assessments"),c(!1),m("/"))},y=()=>v(x=>x==="dark"?"light":"dark"),m=x=>{if(typeof window>"u")return;const S=x||"/",E=S==="/"?"":`#${S}`;if(window.location.hash===E){g(S),window.scrollTo({top:0,behavior:"smooth"});return}const k=`${window.location.pathname}${window.location.search}${E}`;window.history.pushState({},"",k),g(S),h(eo()),window.scrollTo({top:0,behavior:"smooth"})},p=()=>u.jsxs("button",{onClick:y,className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-100 shadow-sm hover:shadow transition","aria-label":"Darstellung wechseln",type:"button",children:[w==="dark"?u.jsx(ay,{className:"w-4 h-4"}):u.jsx(ty,{className:"w-4 h-4"}),u.jsx("span",{className:"text-sm font-medium",children:w==="dark"?"Light Mode":"Dark Mode"})]});return d?u.jsx(Yb,{shareToken:d,themeToggle:p()}):W?r?u.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950 text-gray-600 dark:text-gray-300",children:[u.jsx("div",{className:"absolute top-4 right-4",children:p()}),u.jsx("span",{children:"Auth wird geladen..."})]}):e?u.jsxs("div",{className:"min-h-screen bg-gray-50 dark:bg-gray-950 text-gray-900 dark:text-gray-100",children:[u.jsx("header",{className:"bg-white/80 dark:bg-gray-900/70 backdrop-blur border-b border-gray-200 dark:border-gray-800",children:u.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-3 flex items-center justify-between gap-3 flex-wrap",children:[u.jsxs("div",{children:[u.jsx("p",{className:"text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400",children:"Angemeldet"}),u.jsx("p",{className:"text-sm font-semibold text-gray-800 dark:text-gray-100",children:(_=e==null?void 0:e.user)==null?void 0:_.email})]}),u.jsxs("nav",{className:"flex items-center gap-2",children:[u.jsx("button",{type:"button",onClick:()=>o("assessments"),className:`px-4 py-2 rounded-lg border text-sm font-semibold transition ${a==="assessments"?"bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900 border-gray-900 dark:border-gray-100":"bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-200 border-gray-300 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800"}`,children:"Bewertungen"}),u.jsx("button",{type:"button",onClick:()=>o("analysis"),disabled:l,className:`px-4 py-2 rounded-lg border text-sm font-semibold transition ${a==="analysis"?"bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900 border-gray-900 dark:border-gray-100":"bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-200 border-gray-300 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800"} ${l?"opacity-50 cursor-not-allowed":""}`,title:l?"Analyse ist während der Bearbeitung deaktiviert":"Analyse öffnen",children:"Analyse"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[p(),u.jsx("button",{onClick:b,className:"px-4 py-2 bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900 rounded-lg hover:bg-gray-800 dark:hover:bg-gray-200 transition",children:"Abmelden"})]})]})}),u.jsx(Bb,{user:e==null?void 0:e.user,activeTab:a,onEditingStateChange:c})]}):s?u.jsx(Fb,{onAuth:t,themeToggle:p(),onBack:()=>i(!1)}):f==="/datenschutz"||f==="/impressum"||f==="/kontakt"?u.jsx(Xb,{path:f,onGetStarted:()=>i(!0),onNavigate:m,themeToggle:p()}):u.jsx(qb,{onGetStarted:()=>i(!0),onNavigate:m,themeToggle:p()}):u.jsxs("div",{className:"min-h-screen bg-gray-50 dark:bg-gray-950 text-gray-900 dark:text-gray-100 flex items-center justify-center p-6",children:[u.jsx("div",{className:"absolute top-4 right-4",children:p()}),u.jsxs("div",{className:"max-w-xl w-full bg-white/90 dark:bg-gray-900/80 border border-dashed border-gray-300 dark:border-gray-700 rounded-xl shadow-sm p-6",children:[u.jsx("h2",{className:"text-2xl font-bold text-gray-800 dark:text-gray-100 mb-2",children:"Supabase noch nicht konfiguriert"}),u.jsxs("p",{className:"text-gray-600 dark:text-gray-300",children:["Lege eine ",u.jsx("code",{children:".env"})," an (siehe ",u.jsx("code",{children:".env.example"}),") und trage",u.jsx("code",{children:" VITE_SUPABASE_URL "})," sowie ",u.jsx("code",{children:"VITE_SUPABASE_ANON_KEY"})," ein, um Login und Registrierung zu aktivieren."]}),u.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-3",children:"Anschließend Vite neu starten, damit die Variablen geladen werden."})]})]})}to.createRoot(document.getElementById("root")).render(u.jsx(Ng.StrictMode,{children:u.jsx(Zb,{})}));export{Rc as _,Nr as c,cd as g};