const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/web-CCEu9YCM.js","assets/index-CkLBOkYv.js","assets/web-BaBzFDrr.js","assets/web-68rtgo36.js","assets/index.esm-Ct10TrAh.js","assets/index.esm2017-DuujyTn9.js","assets/index.esm-0EJQLKq6.js","assets/index.esm2017-B64x5eca.js","assets/web-Bv6HZ2S_.js","assets/index-DzdPQq_l.js","assets/InAppReviewService-Dr8bYv2x.js","assets/web-BMtXzcJx.js","assets/web-FhDKiIS1.js","assets/index-BKNHCE58.js","assets/TurretPreview-tL_lePQ9.js","assets/ShipPackPreview-C1SY9CLc.js","assets/ShipPackPreview-BeBfSYkD.css","assets/BroadcasterLive-BqXW-2JL.js","assets/BroadcasterLive-DDgCvhq9.css","assets/index.es-LUPp7F4V.js","assets/web-BC_xQ4dh.js","assets/index-Dj2TZsNT.js"])))=>i.map(i=>d[i]);
var v0A=Object.defineProperty;var J9=e=>{throw TypeError(e)};var K0A=(e,A,t)=>A in e?v0A(e,A,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[A]=t;var Oi=(e,A,t)=>K0A(e,typeof A!="symbol"?A+"":A,t),Iq=(e,A,t)=>A.has(e)||J9("Cannot "+t);var et=(e,A,t)=>(Iq(e,A,"read from private field"),t?t.call(e):A.get(e)),Hn=(e,A,t)=>A.has(e)?J9("Cannot add the same private member more than once"):A instanceof WeakSet?A.add(e):A.set(e,t),Pi=(e,A,t,i)=>(Iq(e,A,"write to private field"),i?i.call(e,t):A.set(e,t),t),Ha=(e,A,t)=>(Iq(e,A,"access private method"),t);var zG=(e,A,t,i)=>({set _(n){Pi(e,A,n,t)},get _(){return et(e,A,i)}});import{r as md,_ as Qi,C as Ui,S as ZG}from"./index-CkLBOkYv.js";var XRe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function nw(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function $Re(e){if(e.__esModule)return e;var A=e.default;if(typeof A=="function"){var t=function i(){return this instanceof i?Reflect.construct(A,arguments,this.constructor):A.apply(this,arguments)};t.prototype=A.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(e).forEach(function(i){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})}),t}var MaA={exports:{}},PJ={};/**
 * @license React
 * react-jsx-runtime.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var F0A=Symbol.for("react.transitional.element"),_0A=Symbol.for("react.fragment");function NaA(e,A,t){var i=null;if(t!==void 0&&(i=""+t),A.key!==void 0&&(i=""+A.key),"key"in A){t={};for(var n in A)n!=="key"&&(t[n]=A[n])}else t=A;return A=t.ref,{$$typeof:F0A,type:e,key:i,ref:A!==void 0?A:null,props:t}}PJ.Fragment=_0A;PJ.jsx=NaA;PJ.jsxs=NaA;MaA.exports=PJ;var C=MaA.exports,RaA={exports:{}},nn={};/**
 * @license React
 * react.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var z4=Symbol.for("react.transitional.element"),J0A=Symbol.for("react.portal"),L0A=Symbol.for("react.fragment"),x0A=Symbol.for("react.strict_mode"),T0A=Symbol.for("react.profiler"),q0A=Symbol.for("react.consumer"),Y0A=Symbol.for("react.context"),H0A=Symbol.for("react.forward_ref"),O0A=Symbol.for("react.suspense"),P0A=Symbol.for("react.memo"),GaA=Symbol.for("react.lazy"),j0A=Symbol.for("react.activity"),L9=Symbol.iterator;function z0A(e){return e===null||typeof e!="object"?null:(e=L9&&e[L9]||e["@@iterator"],typeof e=="function"?e:null)}var baA={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},UaA=Object.assign,vaA={};function gw(e,A,t){this.props=e,this.context=A,this.refs=vaA,this.updater=t||baA}gw.prototype.isReactComponent={};gw.prototype.setState=function(e,A){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,A,"setState")};gw.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function KaA(){}KaA.prototype=gw.prototype;function Z4(e,A,t){this.props=e,this.context=A,this.refs=vaA,this.updater=t||baA}var W4=Z4.prototype=new KaA;W4.constructor=Z4;UaA(W4,gw.prototype);W4.isPureReactComponent=!0;var x9=Array.isArray;function HO(){}var no={H:null,A:null,T:null,S:null},FaA=Object.prototype.hasOwnProperty;function V4(e,A,t){var i=t.ref;return{$$typeof:z4,type:e,key:A,ref:i!==void 0?i:null,props:t}}function Z0A(e,A){return V4(e.type,A,e.props)}function X4(e){return typeof e=="object"&&e!==null&&e.$$typeof===z4}function W0A(e){var A={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(t){return A[t]})}var T9=/\/+/g;function Cq(e,A){return typeof e=="object"&&e!==null&&e.key!=null?W0A(""+e.key):A.toString(36)}function V0A(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(HO,HO):(e.status="pending",e.then(function(A){e.status==="pending"&&(e.status="fulfilled",e.value=A)},function(A){e.status==="pending"&&(e.status="rejected",e.reason=A)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function MD(e,A,t,i,n){var g=typeof e;(g==="undefined"||g==="boolean")&&(e=null);var o=!1;if(e===null)o=!0;else switch(g){case"bigint":case"string":case"number":o=!0;break;case"object":switch(e.$$typeof){case z4:case J0A:o=!0;break;case GaA:return o=e._init,MD(o(e._payload),A,t,i,n)}}if(o)return n=n(e),o=i===""?"."+Cq(e,0):i,x9(n)?(t="",o!=null&&(t=o.replace(T9,"$&/")+"/"),MD(n,A,t,"",function(r){return r})):n!=null&&(X4(n)&&(n=Z0A(n,t+(n.key==null||e&&e.key===n.key?"":(""+n.key).replace(T9,"$&/")+"/")+o)),A.push(n)),1;o=0;var s=i===""?".":i+":";if(x9(e))for(var a=0;a<e.length;a++)i=e[a],g=s+Cq(i,a),o+=MD(i,A,t,g,n);else if(a=z0A(e),typeof a=="function")for(e=a.call(e),a=0;!(i=e.next()).done;)i=i.value,g=s+Cq(i,a++),o+=MD(i,A,t,g,n);else if(g==="object"){if(typeof e.then=="function")return MD(V0A(e),A,t,i,n);throw A=String(e),Error("Objects are not valid as a React child (found: "+(A==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":A)+"). If you meant to render a collection of children, use an array instead.")}return o}function WG(e,A,t){if(e==null)return e;var i=[],n=0;return MD(e,i,"","",function(g){return A.call(t,g,n++)}),i}function X0A(e){if(e._status===-1){var A=e._result;A=A(),A.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=A)}if(e._status===1)return e._result.default;throw e._result}var q9=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var A=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(A))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},$0A={map:WG,forEach:function(e,A,t){WG(e,function(){A.apply(this,arguments)},t)},count:function(e){var A=0;return WG(e,function(){A++}),A},toArray:function(e){return WG(e,function(A){return A})||[]},only:function(e){if(!X4(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};nn.Activity=j0A;nn.Children=$0A;nn.Component=gw;nn.Fragment=L0A;nn.Profiler=T0A;nn.PureComponent=Z4;nn.StrictMode=x0A;nn.Suspense=O0A;nn.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=no;nn.__COMPILER_RUNTIME={__proto__:null,c:function(e){return no.H.useMemoCache(e)}};nn.cache=function(e){return function(){return e.apply(null,arguments)}};nn.cacheSignal=function(){return null};nn.cloneElement=function(e,A,t){if(e==null)throw Error("The argument must be a React element, but you passed "+e+".");var i=UaA({},e.props),n=e.key;if(A!=null)for(g in A.key!==void 0&&(n=""+A.key),A)!FaA.call(A,g)||g==="key"||g==="__self"||g==="__source"||g==="ref"&&A.ref===void 0||(i[g]=A[g]);var g=arguments.length-2;if(g===1)i.children=t;else if(1<g){for(var o=Array(g),s=0;s<g;s++)o[s]=arguments[s+2];i.children=o}return V4(e.type,n,i)};nn.createContext=function(e){return e={$$typeof:Y0A,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:q0A,_context:e},e};nn.createElement=function(e,A,t){var i,n={},g=null;if(A!=null)for(i in A.key!==void 0&&(g=""+A.key),A)FaA.call(A,i)&&i!=="key"&&i!=="__self"&&i!=="__source"&&(n[i]=A[i]);var o=arguments.length-2;if(o===1)n.children=t;else if(1<o){for(var s=Array(o),a=0;a<o;a++)s[a]=arguments[a+2];n.children=s}if(e&&e.defaultProps)for(i in o=e.defaultProps,o)n[i]===void 0&&(n[i]=o[i]);return V4(e,g,n)};nn.createRef=function(){return{current:null}};nn.forwardRef=function(e){return{$$typeof:H0A,render:e}};nn.isValidElement=X4;nn.lazy=function(e){return{$$typeof:GaA,_payload:{_status:-1,_result:e},_init:X0A}};nn.memo=function(e,A){return{$$typeof:P0A,type:e,compare:A===void 0?null:A}};nn.startTransition=function(e){var A=no.T,t={};no.T=t;try{var i=e(),n=no.S;n!==null&&n(t,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(HO,q9)}catch(g){q9(g)}finally{A!==null&&t.types!==null&&(A.types=t.types),no.T=A}};nn.unstable_useCacheRefresh=function(){return no.H.useCacheRefresh()};nn.use=function(e){return no.H.use(e)};nn.useActionState=function(e,A,t){return no.H.useActionState(e,A,t)};nn.useCallback=function(e,A){return no.H.useCallback(e,A)};nn.useContext=function(e){return no.H.useContext(e)};nn.useDebugValue=function(){};nn.useDeferredValue=function(e,A){return no.H.useDeferredValue(e,A)};nn.useEffect=function(e,A){return no.H.useEffect(e,A)};nn.useEffectEvent=function(e){return no.H.useEffectEvent(e)};nn.useId=function(){return no.H.useId()};nn.useImperativeHandle=function(e,A,t){return no.H.useImperativeHandle(e,A,t)};nn.useInsertionEffect=function(e,A){return no.H.useInsertionEffect(e,A)};nn.useLayoutEffect=function(e,A){return no.H.useLayoutEffect(e,A)};nn.useMemo=function(e,A){return no.H.useMemo(e,A)};nn.useOptimistic=function(e,A){return no.H.useOptimistic(e,A)};nn.useReducer=function(e,A,t){return no.H.useReducer(e,A,t)};nn.useRef=function(e){return no.H.useRef(e)};nn.useState=function(e){return no.H.useState(e)};nn.useSyncExternalStore=function(e,A,t){return no.H.useSyncExternalStore(e,A,t)};nn.useTransition=function(){return no.H.useTransition()};nn.version="19.2.0";RaA.exports=nn;var E=RaA.exports;const ue=nw(E);var _aA={exports:{}},jJ={},JaA={exports:{}},LaA={};/**
 * @license React
 * scheduler.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */(function(e){function A(v,U){var x=v.length;v.push(U);A:for(;0<x;){var T=x-1>>>1,z=v[T];if(0<n(z,U))v[T]=U,v[x]=z,x=T;else break A}}function t(v){return v.length===0?null:v[0]}function i(v){if(v.length===0)return null;var U=v[0],x=v.pop();if(x!==U){v[0]=x;A:for(var T=0,z=v.length,Z=z>>>1;T<Z;){var eA=2*(T+1)-1,aA=v[eA],sA=eA+1,pA=v[sA];if(0>n(aA,x))sA<z&&0>n(pA,aA)?(v[T]=pA,v[sA]=x,T=sA):(v[T]=aA,v[eA]=x,T=eA);else if(sA<z&&0>n(pA,x))v[T]=pA,v[sA]=x,T=sA;else break A}}return U}function n(v,U){var x=v.sortIndex-U.sortIndex;return x!==0?x:v.id-U.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var g=performance;e.unstable_now=function(){return g.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var a=[],r=[],I=1,c=null,l=3,B=!1,Q=!1,h=!1,d=!1,p=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,m=typeof setImmediate<"u"?setImmediate:null;function D(v){for(var U=t(r);U!==null;){if(U.callback===null)i(r);else if(U.startTime<=v)i(r),U.sortIndex=U.expirationTime,A(a,U);else break;U=t(r)}}function S(v){if(h=!1,D(v),!Q)if(t(a)!==null)Q=!0,k||(k=!0,_());else{var U=t(r);U!==null&&q(S,U.startTime-v)}}var k=!1,N=-1,G=5,M=-1;function w(){return d?!0:!(e.unstable_now()-M<G)}function b(){if(d=!1,k){var v=e.unstable_now();M=v;var U=!0;try{A:{Q=!1,h&&(h=!1,y(N),N=-1),B=!0;var x=l;try{e:{for(D(v),c=t(a);c!==null&&!(c.expirationTime>v&&w());){var T=c.callback;if(typeof T=="function"){c.callback=null,l=c.priorityLevel;var z=T(c.expirationTime<=v);if(v=e.unstable_now(),typeof z=="function"){c.callback=z,D(v),U=!0;break e}c===t(a)&&i(a),D(v)}else i(a);c=t(a)}if(c!==null)U=!0;else{var Z=t(r);Z!==null&&q(S,Z.startTime-v),U=!1}}break A}finally{c=null,l=x,B=!1}U=void 0}}finally{U?_():k=!1}}}var _;if(typeof m=="function")_=function(){m(b)};else if(typeof MessageChannel<"u"){var K=new MessageChannel,J=K.port2;K.port1.onmessage=b,_=function(){J.postMessage(null)}}else _=function(){p(b,0)};function q(v,U){N=p(function(){v(e.unstable_now())},U)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(v){v.callback=null},e.unstable_forceFrameRate=function(v){0>v||125<v?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):G=0<v?Math.floor(1e3/v):5},e.unstable_getCurrentPriorityLevel=function(){return l},e.unstable_next=function(v){switch(l){case 1:case 2:case 3:var U=3;break;default:U=l}var x=l;l=U;try{return v()}finally{l=x}},e.unstable_requestPaint=function(){d=!0},e.unstable_runWithPriority=function(v,U){switch(v){case 1:case 2:case 3:case 4:case 5:break;default:v=3}var x=l;l=v;try{return U()}finally{l=x}},e.unstable_scheduleCallback=function(v,U,x){var T=e.unstable_now();switch(typeof x=="object"&&x!==null?(x=x.delay,x=typeof x=="number"&&0<x?T+x:T):x=T,v){case 1:var z=-1;break;case 2:z=250;break;case 5:z=1073741823;break;case 4:z=1e4;break;default:z=5e3}return z=x+z,v={id:I++,callback:U,priorityLevel:v,startTime:x,expirationTime:z,sortIndex:-1},x>T?(v.sortIndex=x,A(r,v),t(a)===null&&v===t(r)&&(h?(y(N),N=-1):h=!0,q(S,x-T))):(v.sortIndex=z,A(a,v),Q||B||(Q=!0,k||(k=!0,_()))),v},e.unstable_shouldYield=w,e.unstable_wrapCallback=function(v){var U=l;return function(){var x=l;l=U;try{return v.apply(this,arguments)}finally{l=x}}}})(LaA);JaA.exports=LaA;var AkA=JaA.exports,xaA={exports:{}},_r={};/**
 * @license React
 * react-dom.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var ekA=E;function TaA(e){var A="https://react.dev/errors/"+e;if(1<arguments.length){A+="?args[]="+encodeURIComponent(arguments[1]);for(var t=2;t<arguments.length;t++)A+="&args[]="+encodeURIComponent(arguments[t])}return"Minified React error #"+e+"; visit "+A+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function GQ(){}var kr={d:{f:GQ,r:function(){throw Error(TaA(522))},D:GQ,C:GQ,L:GQ,m:GQ,X:GQ,S:GQ,M:GQ},p:0,findDOMNode:null},tkA=Symbol.for("react.portal");function ikA(e,A,t){var i=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:tkA,key:i==null?null:""+i,children:e,containerInfo:A,implementation:t}}var Kk=ekA.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function zJ(e,A){if(e==="font")return"";if(typeof A=="string")return A==="use-credentials"?A:""}_r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=kr;_r.createPortal=function(e,A){var t=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!A||A.nodeType!==1&&A.nodeType!==9&&A.nodeType!==11)throw Error(TaA(299));return ikA(e,A,null,t)};_r.flushSync=function(e){var A=Kk.T,t=kr.p;try{if(Kk.T=null,kr.p=2,e)return e()}finally{Kk.T=A,kr.p=t,kr.d.f()}};_r.preconnect=function(e,A){typeof e=="string"&&(A?(A=A.crossOrigin,A=typeof A=="string"?A==="use-credentials"?A:"":void 0):A=null,kr.d.C(e,A))};_r.prefetchDNS=function(e){typeof e=="string"&&kr.d.D(e)};_r.preinit=function(e,A){if(typeof e=="string"&&A&&typeof A.as=="string"){var t=A.as,i=zJ(t,A.crossOrigin),n=typeof A.integrity=="string"?A.integrity:void 0,g=typeof A.fetchPriority=="string"?A.fetchPriority:void 0;t==="style"?kr.d.S(e,typeof A.precedence=="string"?A.precedence:void 0,{crossOrigin:i,integrity:n,fetchPriority:g}):t==="script"&&kr.d.X(e,{crossOrigin:i,integrity:n,fetchPriority:g,nonce:typeof A.nonce=="string"?A.nonce:void 0})}};_r.preinitModule=function(e,A){if(typeof e=="string")if(typeof A=="object"&&A!==null){if(A.as==null||A.as==="script"){var t=zJ(A.as,A.crossOrigin);kr.d.M(e,{crossOrigin:t,integrity:typeof A.integrity=="string"?A.integrity:void 0,nonce:typeof A.nonce=="string"?A.nonce:void 0})}}else A==null&&kr.d.M(e)};_r.preload=function(e,A){if(typeof e=="string"&&typeof A=="object"&&A!==null&&typeof A.as=="string"){var t=A.as,i=zJ(t,A.crossOrigin);kr.d.L(e,t,{crossOrigin:i,integrity:typeof A.integrity=="string"?A.integrity:void 0,nonce:typeof A.nonce=="string"?A.nonce:void 0,type:typeof A.type=="string"?A.type:void 0,fetchPriority:typeof A.fetchPriority=="string"?A.fetchPriority:void 0,referrerPolicy:typeof A.referrerPolicy=="string"?A.referrerPolicy:void 0,imageSrcSet:typeof A.imageSrcSet=="string"?A.imageSrcSet:void 0,imageSizes:typeof A.imageSizes=="string"?A.imageSizes:void 0,media:typeof A.media=="string"?A.media:void 0})}};_r.preloadModule=function(e,A){if(typeof e=="string")if(A){var t=zJ(A.as,A.crossOrigin);kr.d.m(e,{as:typeof A.as=="string"&&A.as!=="script"?A.as:void 0,crossOrigin:t,integrity:typeof A.integrity=="string"?A.integrity:void 0})}else kr.d.m(e)};_r.requestFormReset=function(e){kr.d.r(e)};_r.unstable_batchedUpdates=function(e,A){return e(A)};_r.useFormState=function(e,A,t){return Kk.H.useFormState(e,A,t)};_r.useFormStatus=function(){return Kk.H.useHostTransitionStatus()};_r.version="19.2.0";function qaA(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(qaA)}catch(e){console.error(e)}}qaA(),xaA.exports=_r;var er=xaA.exports;/**
 * @license React
 * react-dom-client.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var Ts=AkA,YaA=E,nkA=er;function It(e){var A="https://react.dev/errors/"+e;if(1<arguments.length){A+="?args[]="+encodeURIComponent(arguments[1]);for(var t=2;t<arguments.length;t++)A+="&args[]="+encodeURIComponent(arguments[t])}return"Minified React error #"+e+"; visit "+A+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function HaA(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function BR(e){var A=e,t=e;if(e.alternate)for(;A.return;)A=A.return;else{e=A;do A=e,A.flags&4098&&(t=A.return),e=A.return;while(e)}return A.tag===3?t:null}function OaA(e){if(e.tag===13){var A=e.memoizedState;if(A===null&&(e=e.alternate,e!==null&&(A=e.memoizedState)),A!==null)return A.dehydrated}return null}function PaA(e){if(e.tag===31){var A=e.memoizedState;if(A===null&&(e=e.alternate,e!==null&&(A=e.memoizedState)),A!==null)return A.dehydrated}return null}function Y9(e){if(BR(e)!==e)throw Error(It(188))}function gkA(e){var A=e.alternate;if(!A){if(A=BR(e),A===null)throw Error(It(188));return A!==e?null:e}for(var t=e,i=A;;){var n=t.return;if(n===null)break;var g=n.alternate;if(g===null){if(i=n.return,i!==null){t=i;continue}break}if(n.child===g.child){for(g=n.child;g;){if(g===t)return Y9(n),e;if(g===i)return Y9(n),A;g=g.sibling}throw Error(It(188))}if(t.return!==i.return)t=n,i=g;else{for(var o=!1,s=n.child;s;){if(s===t){o=!0,t=n,i=g;break}if(s===i){o=!0,i=n,t=g;break}s=s.sibling}if(!o){for(s=g.child;s;){if(s===t){o=!0,t=g,i=n;break}if(s===i){o=!0,i=g,t=n;break}s=s.sibling}if(!o)throw Error(It(189))}}if(t.alternate!==i)throw Error(It(190))}if(t.tag!==3)throw Error(It(188));return t.stateNode.current===t?e:A}function jaA(e){var A=e.tag;if(A===5||A===26||A===27||A===6)return e;for(e=e.child;e!==null;){if(A=jaA(e),A!==null)return A;e=e.sibling}return null}var so=Object.assign,okA=Symbol.for("react.element"),VG=Symbol.for("react.transitional.element"),gk=Symbol.for("react.portal"),_D=Symbol.for("react.fragment"),zaA=Symbol.for("react.strict_mode"),OO=Symbol.for("react.profiler"),ZaA=Symbol.for("react.consumer"),SE=Symbol.for("react.context"),$4=Symbol.for("react.forward_ref"),PO=Symbol.for("react.suspense"),jO=Symbol.for("react.suspense_list"),Aj=Symbol.for("react.memo"),VQ=Symbol.for("react.lazy"),zO=Symbol.for("react.activity"),skA=Symbol.for("react.memo_cache_sentinel"),H9=Symbol.iterator;function C0(e){return e===null||typeof e!="object"?null:(e=H9&&e[H9]||e["@@iterator"],typeof e=="function"?e:null)}var akA=Symbol.for("react.client.reference");function ZO(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===akA?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case _D:return"Fragment";case OO:return"Profiler";case zaA:return"StrictMode";case PO:return"Suspense";case jO:return"SuspenseList";case zO:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case gk:return"Portal";case SE:return e.displayName||"Context";case ZaA:return(e._context.displayName||"Context")+".Consumer";case $4:var A=e.render;return e=e.displayName,e||(e=A.displayName||A.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Aj:return A=e.displayName||null,A!==null?A:ZO(e.type)||"Memo";case VQ:A=e._payload,e=e._init;try{return ZO(e(A))}catch{}}return null}var ok=Array.isArray,Li=YaA.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Bg=nkA.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Np={pending:!1,data:null,method:null,action:null},WO=[],JD=-1;function SB(e){return{current:e}}function aa(e){0>JD||(e.current=WO[JD],WO[JD]=null,JD--)}function Zg(e,A){JD++,WO[JD]=e.current,e.current=A}var aB=SB(null),UM=SB(null),bu=SB(null),OK=SB(null);function PK(e,A){switch(Zg(bu,A),Zg(UM,e),Zg(aB,null),A.nodeType){case 9:case 11:e=(e=A.documentElement)&&(e=e.namespaceURI)?WX(e):0;break;default:if(e=A.tagName,A=A.namespaceURI)A=WX(A),e=ECA(A,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}aa(aB),Zg(aB,e)}function sS(){aa(aB),aa(UM),aa(bu)}function VO(e){e.memoizedState!==null&&Zg(OK,e);var A=aB.current,t=ECA(A,e.type);A!==t&&(Zg(UM,e),Zg(aB,t))}function jK(e){UM.current===e&&(aa(aB),aa(UM)),OK.current===e&&(aa(OK),HM._currentValue=Np)}var cq,O9;function _h(e){if(cq===void 0)try{throw Error()}catch(t){var A=t.stack.trim().match(/\n( *(at )?)/);cq=A&&A[1]||"",O9=-1<t.stack.indexOf(`
    at`)?" (<anonymous>)":-1<t.stack.indexOf("@")?"@unknown:0:0":""}return`
`+cq+e+O9}var lq=!1;function Bq(e,A){if(!e||lq)return"";lq=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var i={DetermineComponentFrameRoot:function(){try{if(A){var c=function(){throw Error()};if(Object.defineProperty(c.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(c,[])}catch(B){var l=B}Reflect.construct(e,[],c)}else{try{c.call()}catch(B){l=B}e.call(c.prototype)}}else{try{throw Error()}catch(B){l=B}(c=e())&&typeof c.catch=="function"&&c.catch(function(){})}}catch(B){if(B&&l&&typeof B.stack=="string")return[B.stack,l.stack]}return[null,null]}};i.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var n=Object.getOwnPropertyDescriptor(i.DetermineComponentFrameRoot,"name");n&&n.configurable&&Object.defineProperty(i.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var g=i.DetermineComponentFrameRoot(),o=g[0],s=g[1];if(o&&s){var a=o.split(`
`),r=s.split(`
`);for(n=i=0;i<a.length&&!a[i].includes("DetermineComponentFrameRoot");)i++;for(;n<r.length&&!r[n].includes("DetermineComponentFrameRoot");)n++;if(i===a.length||n===r.length)for(i=a.length-1,n=r.length-1;1<=i&&0<=n&&a[i]!==r[n];)n--;for(;1<=i&&0<=n;i--,n--)if(a[i]!==r[n]){if(i!==1||n!==1)do if(i--,n--,0>n||a[i]!==r[n]){var I=`
`+a[i].replace(" at new "," at ");return e.displayName&&I.includes("<anonymous>")&&(I=I.replace("<anonymous>",e.displayName)),I}while(1<=i&&0<=n);break}}}finally{lq=!1,Error.prepareStackTrace=t}return(t=e?e.displayName||e.name:"")?_h(t):""}function rkA(e,A){switch(e.tag){case 26:case 27:case 5:return _h(e.type);case 16:return _h("Lazy");case 13:return e.child!==A&&A!==null?_h("Suspense Fallback"):_h("Suspense");case 19:return _h("SuspenseList");case 0:case 15:return Bq(e.type,!1);case 11:return Bq(e.type.render,!1);case 1:return Bq(e.type,!0);case 31:return _h("Activity");default:return""}}function P9(e){try{var A="",t=null;do A+=rkA(e,t),t=e,e=e.return;while(e);return A}catch(i){return`
Error generating stack: `+i.message+`
`+i.stack}}var XO=Object.prototype.hasOwnProperty,ej=Ts.unstable_scheduleCallback,Eq=Ts.unstable_cancelCallback,IkA=Ts.unstable_shouldYield,CkA=Ts.unstable_requestPaint,zI=Ts.unstable_now,ckA=Ts.unstable_getCurrentPriorityLevel,WaA=Ts.unstable_ImmediatePriority,VaA=Ts.unstable_UserBlockingPriority,zK=Ts.unstable_NormalPriority,lkA=Ts.unstable_LowPriority,XaA=Ts.unstable_IdlePriority,BkA=Ts.log,EkA=Ts.unstable_setDisableYieldValue,ER=null,ZI=null;function uu(e){if(typeof BkA=="function"&&EkA(e),ZI&&typeof ZI.setStrictMode=="function")try{ZI.setStrictMode(ER,e)}catch{}}var WI=Math.clz32?Math.clz32:dkA,QkA=Math.log,ukA=Math.LN2;function dkA(e){return e>>>=0,e===0?32:31-(QkA(e)/ukA|0)|0}var XG=256,$G=262144,Ab=4194304;function Jh(e){var A=e&42;if(A!==0)return A;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:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function ZJ(e,A,t){var i=e.pendingLanes;if(i===0)return 0;var n=0,g=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=i&134217727;return s!==0?(i=s&~g,i!==0?n=Jh(i):(o&=s,o!==0?n=Jh(o):t||(t=s&~e,t!==0&&(n=Jh(t))))):(s=i&~g,s!==0?n=Jh(s):o!==0?n=Jh(o):t||(t=i&~e,t!==0&&(n=Jh(t)))),n===0?0:A!==0&&A!==n&&!(A&g)&&(g=n&-n,t=A&-A,g>=t||g===32&&(t&4194048)!==0)?A:n}function QR(e,A){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&A)===0}function hkA(e,A){switch(e){case 1:case 2:case 4:case 8:case 64:return A+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return A+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function $aA(){var e=Ab;return Ab<<=1,!(Ab&62914560)&&(Ab=4194304),e}function Qq(e){for(var A=[],t=0;31>t;t++)A.push(e);return A}function uR(e,A){e.pendingLanes|=A,A!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function pkA(e,A,t,i,n,g){var o=e.pendingLanes;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=t,e.entangledLanes&=t,e.errorRecoveryDisabledLanes&=t,e.shellSuspendCounter=0;var s=e.entanglements,a=e.expirationTimes,r=e.hiddenUpdates;for(t=o&~t;0<t;){var I=31-WI(t),c=1<<I;s[I]=0,a[I]=-1;var l=r[I];if(l!==null)for(r[I]=null,I=0;I<l.length;I++){var B=l[I];B!==null&&(B.lane&=-536870913)}t&=~c}i!==0&&ArA(e,i,0),g!==0&&n===0&&e.tag!==0&&(e.suspendedLanes|=g&~(o&~A))}function ArA(e,A,t){e.pendingLanes|=A,e.suspendedLanes&=~A;var i=31-WI(A);e.entangledLanes|=A,e.entanglements[i]=e.entanglements[i]|1073741824|t&261930}function erA(e,A){var t=e.entangledLanes|=A;for(e=e.entanglements;t;){var i=31-WI(t),n=1<<i;n&A|e[i]&A&&(e[i]|=A),t&=~n}}function trA(e,A){var t=A&-A;return t=t&42?1:tj(t),t&(e.suspendedLanes|A)?0:t}function tj(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;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:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function ij(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function irA(){var e=Bg.p;return e!==0?e:(e=window.event,e===void 0?32:wCA(e.type))}function j9(e,A){var t=Bg.p;try{return Bg.p=e,A()}finally{Bg.p=t}}var Sd=Math.random().toString(36).slice(2),wa="__reactFiber$"+Sd,II="__reactProps$"+Sd,ow="__reactContainer$"+Sd,$O="__reactEvents$"+Sd,fkA="__reactListeners$"+Sd,ykA="__reactHandles$"+Sd,z9="__reactResources$"+Sd,dR="__reactMarker$"+Sd;function nj(e){delete e[wa],delete e[II],delete e[$O],delete e[fkA],delete e[ykA]}function LD(e){var A=e[wa];if(A)return A;for(var t=e.parentNode;t;){if(A=t[ow]||t[wa]){if(t=A.alternate,A.child!==null||t!==null&&t.child!==null)for(e=e6(e);e!==null;){if(t=e[wa])return t;e=e6(e)}return A}e=t,t=e.parentNode}return null}function sw(e){if(e=e[wa]||e[ow]){var A=e.tag;if(A===5||A===6||A===13||A===31||A===26||A===27||A===3)return e}return null}function sk(e){var A=e.tag;if(A===5||A===26||A===27||A===6)return e.stateNode;throw Error(It(33))}function Bm(e){var A=e[z9];return A||(A=e[z9]={hoistableStyles:new Map,hoistableScripts:new Map}),A}function ga(e){e[dR]=!0}var nrA=new Set,grA={};function Mf(e,A){aS(e,A),aS(e+"Capture",A)}function aS(e,A){for(grA[e]=A,e=0;e<A.length;e++)nrA.add(A[e])}var DkA=RegExp("^[: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]*$"),Z9={},W9={};function mkA(e){return XO.call(W9,e)?!0:XO.call(Z9,e)?!1:DkA.test(e)?W9[e]=!0:(Z9[e]=!0,!1)}function _v(e,A,t){if(mkA(A))if(t===null)e.removeAttribute(A);else{switch(typeof t){case"undefined":case"function":case"symbol":e.removeAttribute(A);return;case"boolean":var i=A.toLowerCase().slice(0,5);if(i!=="data-"&&i!=="aria-"){e.removeAttribute(A);return}}e.setAttribute(A,""+t)}}function eb(e,A,t){if(t===null)e.removeAttribute(A);else{switch(typeof t){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(A);return}e.setAttribute(A,""+t)}}function PB(e,A,t,i){if(i===null)e.removeAttribute(t);else{switch(typeof i){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(t);return}e.setAttributeNS(A,t,""+i)}}function qC(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function orA(e){var A=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(A==="checkbox"||A==="radio")}function SkA(e,A,t){var i=Object.getOwnPropertyDescriptor(e.constructor.prototype,A);if(!e.hasOwnProperty(A)&&typeof i<"u"&&typeof i.get=="function"&&typeof i.set=="function"){var n=i.get,g=i.set;return Object.defineProperty(e,A,{configurable:!0,get:function(){return n.call(this)},set:function(o){t=""+o,g.call(this,o)}}),Object.defineProperty(e,A,{enumerable:i.enumerable}),{getValue:function(){return t},setValue:function(o){t=""+o},stopTracking:function(){e._valueTracker=null,delete e[A]}}}}function AP(e){if(!e._valueTracker){var A=orA(e)?"checked":"value";e._valueTracker=SkA(e,A,""+e[A])}}function srA(e){if(!e)return!1;var A=e._valueTracker;if(!A)return!0;var t=A.getValue(),i="";return e&&(i=orA(e)?e.checked?"true":"false":e.value),e=i,e!==t?(A.setValue(e),!0):!1}function ZK(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}}var wkA=/[\n"\\]/g;function PC(e){return e.replace(wkA,function(A){return"\\"+A.charCodeAt(0).toString(16)+" "})}function eP(e,A,t,i,n,g,o,s){e.name="",o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"?e.type=o:e.removeAttribute("type"),A!=null?o==="number"?(A===0&&e.value===""||e.value!=A)&&(e.value=""+qC(A)):e.value!==""+qC(A)&&(e.value=""+qC(A)):o!=="submit"&&o!=="reset"||e.removeAttribute("value"),A!=null?tP(e,o,qC(A)):t!=null?tP(e,o,qC(t)):i!=null&&e.removeAttribute("value"),n==null&&g!=null&&(e.defaultChecked=!!g),n!=null&&(e.checked=n&&typeof n!="function"&&typeof n!="symbol"),s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"?e.name=""+qC(s):e.removeAttribute("name")}function arA(e,A,t,i,n,g,o,s){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(e.type=g),A!=null||t!=null){if(!(g!=="submit"&&g!=="reset"||A!=null)){AP(e);return}t=t!=null?""+qC(t):"",A=A!=null?""+qC(A):t,s||A===e.value||(e.value=A),e.defaultValue=A}i=i??n,i=typeof i!="function"&&typeof i!="symbol"&&!!i,e.checked=s?e.checked:!!i,e.defaultChecked=!!i,o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"&&(e.name=o),AP(e)}function tP(e,A,t){A==="number"&&ZK(e.ownerDocument)===e||e.defaultValue===""+t||(e.defaultValue=""+t)}function Em(e,A,t,i){if(e=e.options,A){A={};for(var n=0;n<t.length;n++)A["$"+t[n]]=!0;for(t=0;t<e.length;t++)n=A.hasOwnProperty("$"+e[t].value),e[t].selected!==n&&(e[t].selected=n),n&&i&&(e[t].defaultSelected=!0)}else{for(t=""+qC(t),A=null,n=0;n<e.length;n++){if(e[n].value===t){e[n].selected=!0,i&&(e[n].defaultSelected=!0);return}A!==null||e[n].disabled||(A=e[n])}A!==null&&(A.selected=!0)}}function rrA(e,A,t){if(A!=null&&(A=""+qC(A),A!==e.value&&(e.value=A),t==null)){e.defaultValue!==A&&(e.defaultValue=A);return}e.defaultValue=t!=null?""+qC(t):""}function IrA(e,A,t,i){if(A==null){if(i!=null){if(t!=null)throw Error(It(92));if(ok(i)){if(1<i.length)throw Error(It(93));i=i[0]}t=i}t==null&&(t=""),A=t}t=qC(A),e.defaultValue=t,i=e.textContent,i===t&&i!==""&&i!==null&&(e.value=i),AP(e)}function rS(e,A){if(A){var t=e.firstChild;if(t&&t===e.lastChild&&t.nodeType===3){t.nodeValue=A;return}}e.textContent=A}var kkA=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function V9(e,A,t){var i=A.indexOf("--")===0;t==null||typeof t=="boolean"||t===""?i?e.setProperty(A,""):A==="float"?e.cssFloat="":e[A]="":i?e.setProperty(A,t):typeof t!="number"||t===0||kkA.has(A)?A==="float"?e.cssFloat=t:e[A]=(""+t).trim():e[A]=t+"px"}function CrA(e,A,t){if(A!=null&&typeof A!="object")throw Error(It(62));if(e=e.style,t!=null){for(var i in t)!t.hasOwnProperty(i)||A!=null&&A.hasOwnProperty(i)||(i.indexOf("--")===0?e.setProperty(i,""):i==="float"?e.cssFloat="":e[i]="");for(var n in A)i=A[n],A.hasOwnProperty(n)&&t[n]!==i&&V9(e,n,i)}else for(var g in A)A.hasOwnProperty(g)&&V9(e,g,A[g])}function gj(e){if(e.indexOf("-")===-1)return!1;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 MkA=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),NkA=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function Jv(e){return NkA.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function wE(){}var iP=null;function oj(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var xD=null,Qm=null;function X9(e){var A=sw(e);if(A&&(e=A.stateNode)){var t=e[II]||null;A:switch(e=A.stateNode,A.type){case"input":if(eP(e,t.value,t.defaultValue,t.defaultValue,t.checked,t.defaultChecked,t.type,t.name),A=t.name,t.type==="radio"&&A!=null){for(t=e;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll('input[name="'+PC(""+A)+'"][type="radio"]'),A=0;A<t.length;A++){var i=t[A];if(i!==e&&i.form===e.form){var n=i[II]||null;if(!n)throw Error(It(90));eP(i,n.value,n.defaultValue,n.defaultValue,n.checked,n.defaultChecked,n.type,n.name)}}for(A=0;A<t.length;A++)i=t[A],i.form===e.form&&srA(i)}break A;case"textarea":rrA(e,t.value,t.defaultValue);break A;case"select":A=t.value,A!=null&&Em(e,!!t.multiple,A,!1)}}}var uq=!1;function crA(e,A,t){if(uq)return e(A,t);uq=!0;try{var i=e(A);return i}finally{if(uq=!1,(xD!==null||Qm!==null)&&(sL(),xD&&(A=xD,e=Qm,Qm=xD=null,X9(A),e)))for(A=0;A<e.length;A++)X9(e[A])}}function vM(e,A){var t=e.stateNode;if(t===null)return null;var i=t[II]||null;if(i===null)return null;t=i[A];A:switch(A){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(i=!i.disabled)||(e=e.type,i=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!i;break A;default:e=!1}if(e)return null;if(t&&typeof t!="function")throw Error(It(231,A,typeof t));return t}var HE=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),nP=!1;if(HE)try{var c0={};Object.defineProperty(c0,"passive",{get:function(){nP=!0}}),window.addEventListener("test",c0,c0),window.removeEventListener("test",c0,c0)}catch{nP=!1}var du=null,sj=null,Lv=null;function lrA(){if(Lv)return Lv;var e,A=sj,t=A.length,i,n="value"in du?du.value:du.textContent,g=n.length;for(e=0;e<t&&A[e]===n[e];e++);var o=t-e;for(i=1;i<=o&&A[t-i]===n[g-i];i++);return Lv=n.slice(e,1<i?1-i:void 0)}function xv(e){var A=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&A===13&&(e=13)):e=A,e===10&&(e=13),32<=e||e===13?e:0}function tb(){return!0}function $9(){return!1}function QI(e){function A(t,i,n,g,o){this._reactName=t,this._targetInst=n,this.type=i,this.nativeEvent=g,this.target=o,this.currentTarget=null;for(var s in e)e.hasOwnProperty(s)&&(t=e[s],this[s]=t?t(g):g[s]);return this.isDefaultPrevented=(g.defaultPrevented!=null?g.defaultPrevented:g.returnValue===!1)?tb:$9,this.isPropagationStopped=$9,this}return so(A.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t&&(t.preventDefault?t.preventDefault():typeof t.returnValue!="unknown"&&(t.returnValue=!1),this.isDefaultPrevented=tb)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=tb)},persist:function(){},isPersistent:tb}),A}var Nf={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},WJ=QI(Nf),hR=so({},Nf,{view:0,detail:0}),RkA=QI(hR),dq,hq,l0,VJ=so({},hR,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:aj,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==l0&&(l0&&e.type==="mousemove"?(dq=e.screenX-l0.screenX,hq=e.screenY-l0.screenY):hq=dq=0,l0=e),dq)},movementY:function(e){return"movementY"in e?e.movementY:hq}}),AX=QI(VJ),GkA=so({},VJ,{dataTransfer:0}),bkA=QI(GkA),UkA=so({},hR,{relatedTarget:0}),pq=QI(UkA),vkA=so({},Nf,{animationName:0,elapsedTime:0,pseudoElement:0}),KkA=QI(vkA),FkA=so({},Nf,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),_kA=QI(FkA),JkA=so({},Nf,{data:0}),eX=QI(JkA),LkA={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},xkA={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},TkA={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function qkA(e){var A=this.nativeEvent;return A.getModifierState?A.getModifierState(e):(e=TkA[e])?!!A[e]:!1}function aj(){return qkA}var YkA=so({},hR,{key:function(e){if(e.key){var A=LkA[e.key]||e.key;if(A!=="Unidentified")return A}return e.type==="keypress"?(e=xv(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?xkA[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:aj,charCode:function(e){return e.type==="keypress"?xv(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?xv(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),HkA=QI(YkA),OkA=so({},VJ,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),tX=QI(OkA),PkA=so({},hR,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:aj}),jkA=QI(PkA),zkA=so({},Nf,{propertyName:0,elapsedTime:0,pseudoElement:0}),ZkA=QI(zkA),WkA=so({},VJ,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),VkA=QI(WkA),XkA=so({},Nf,{newState:0,oldState:0}),$kA=QI(XkA),AMA=[9,13,27,32],rj=HE&&"CompositionEvent"in window,Fk=null;HE&&"documentMode"in document&&(Fk=document.documentMode);var eMA=HE&&"TextEvent"in window&&!Fk,BrA=HE&&(!rj||Fk&&8<Fk&&11>=Fk),iX=" ",nX=!1;function ErA(e,A){switch(e){case"keyup":return AMA.indexOf(A.keyCode)!==-1;case"keydown":return A.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function QrA(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var TD=!1;function tMA(e,A){switch(e){case"compositionend":return QrA(A);case"keypress":return A.which!==32?null:(nX=!0,iX);case"textInput":return e=A.data,e===iX&&nX?null:e;default:return null}}function iMA(e,A){if(TD)return e==="compositionend"||!rj&&ErA(e,A)?(e=lrA(),Lv=sj=du=null,TD=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(A.ctrlKey||A.altKey||A.metaKey)||A.ctrlKey&&A.altKey){if(A.char&&1<A.char.length)return A.char;if(A.which)return String.fromCharCode(A.which)}return null;case"compositionend":return BrA&&A.locale!=="ko"?null:A.data;default:return null}}var nMA={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function gX(e){var A=e&&e.nodeName&&e.nodeName.toLowerCase();return A==="input"?!!nMA[e.type]:A==="textarea"}function urA(e,A,t,i){xD?Qm?Qm.push(i):Qm=[i]:xD=i,A=lF(A,"onChange"),0<A.length&&(t=new WJ("onChange","change",null,t,i),e.push({event:t,listeners:A}))}var _k=null,KM=null;function gMA(e){cCA(e,0)}function XJ(e){var A=sk(e);if(srA(A))return e}function oX(e,A){if(e==="change")return A}var drA=!1;if(HE){var fq;if(HE){var yq="oninput"in document;if(!yq){var sX=document.createElement("div");sX.setAttribute("oninput","return;"),yq=typeof sX.oninput=="function"}fq=yq}else fq=!1;drA=fq&&(!document.documentMode||9<document.documentMode)}function aX(){_k&&(_k.detachEvent("onpropertychange",hrA),KM=_k=null)}function hrA(e){if(e.propertyName==="value"&&XJ(KM)){var A=[];urA(A,KM,e,oj(e)),crA(gMA,A)}}function oMA(e,A,t){e==="focusin"?(aX(),_k=A,KM=t,_k.attachEvent("onpropertychange",hrA)):e==="focusout"&&aX()}function sMA(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return XJ(KM)}function aMA(e,A){if(e==="click")return XJ(A)}function rMA(e,A){if(e==="input"||e==="change")return XJ(A)}function IMA(e,A){return e===A&&(e!==0||1/e===1/A)||e!==e&&A!==A}var eC=typeof Object.is=="function"?Object.is:IMA;function FM(e,A){if(eC(e,A))return!0;if(typeof e!="object"||e===null||typeof A!="object"||A===null)return!1;var t=Object.keys(e),i=Object.keys(A);if(t.length!==i.length)return!1;for(i=0;i<t.length;i++){var n=t[i];if(!XO.call(A,n)||!eC(e[n],A[n]))return!1}return!0}function rX(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function IX(e,A){var t=rX(e);e=0;for(var i;t;){if(t.nodeType===3){if(i=e+t.textContent.length,e<=A&&i>=A)return{node:t,offset:A-e};e=i}A:{for(;t;){if(t.nextSibling){t=t.nextSibling;break A}t=t.parentNode}t=void 0}t=rX(t)}}function prA(e,A){return e&&A?e===A?!0:e&&e.nodeType===3?!1:A&&A.nodeType===3?prA(e,A.parentNode):"contains"in e?e.contains(A):e.compareDocumentPosition?!!(e.compareDocumentPosition(A)&16):!1:!1}function frA(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var A=ZK(e.document);A instanceof e.HTMLIFrameElement;){try{var t=typeof A.contentWindow.location.href=="string"}catch{t=!1}if(t)e=A.contentWindow;else break;A=ZK(e.document)}return A}function Ij(e){var A=e&&e.nodeName&&e.nodeName.toLowerCase();return A&&(A==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||A==="textarea"||e.contentEditable==="true")}var CMA=HE&&"documentMode"in document&&11>=document.documentMode,qD=null,gP=null,Jk=null,oP=!1;function CX(e,A,t){var i=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;oP||qD==null||qD!==ZK(i)||(i=qD,"selectionStart"in i&&Ij(i)?i={start:i.selectionStart,end:i.selectionEnd}:(i=(i.ownerDocument&&i.ownerDocument.defaultView||window).getSelection(),i={anchorNode:i.anchorNode,anchorOffset:i.anchorOffset,focusNode:i.focusNode,focusOffset:i.focusOffset}),Jk&&FM(Jk,i)||(Jk=i,i=lF(gP,"onSelect"),0<i.length&&(A=new WJ("onSelect","select",null,A,t),e.push({event:A,listeners:i}),A.target=qD)))}function Ch(e,A){var t={};return t[e.toLowerCase()]=A.toLowerCase(),t["Webkit"+e]="webkit"+A,t["Moz"+e]="moz"+A,t}var YD={animationend:Ch("Animation","AnimationEnd"),animationiteration:Ch("Animation","AnimationIteration"),animationstart:Ch("Animation","AnimationStart"),transitionrun:Ch("Transition","TransitionRun"),transitionstart:Ch("Transition","TransitionStart"),transitioncancel:Ch("Transition","TransitionCancel"),transitionend:Ch("Transition","TransitionEnd")},Dq={},yrA={};HE&&(yrA=document.createElement("div").style,"AnimationEvent"in window||(delete YD.animationend.animation,delete YD.animationiteration.animation,delete YD.animationstart.animation),"TransitionEvent"in window||delete YD.transitionend.transition);function Rf(e){if(Dq[e])return Dq[e];if(!YD[e])return e;var A=YD[e],t;for(t in A)if(A.hasOwnProperty(t)&&t in yrA)return Dq[e]=A[t];return e}var DrA=Rf("animationend"),mrA=Rf("animationiteration"),SrA=Rf("animationstart"),cMA=Rf("transitionrun"),lMA=Rf("transitionstart"),BMA=Rf("transitioncancel"),wrA=Rf("transitionend"),krA=new Map,sP="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");sP.push("scrollEnd");function nl(e,A){krA.set(e,A),Mf(A,[e])}var WK=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var A=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(A))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},KC=[],HD=0,Cj=0;function $J(){for(var e=HD,A=Cj=HD=0;A<e;){var t=KC[A];KC[A++]=null;var i=KC[A];KC[A++]=null;var n=KC[A];KC[A++]=null;var g=KC[A];if(KC[A++]=null,i!==null&&n!==null){var o=i.pending;o===null?n.next=n:(n.next=o.next,o.next=n),i.pending=n}g!==0&&MrA(t,n,g)}}function AL(e,A,t,i){KC[HD++]=e,KC[HD++]=A,KC[HD++]=t,KC[HD++]=i,Cj|=i,e.lanes|=i,e=e.alternate,e!==null&&(e.lanes|=i)}function cj(e,A,t,i){return AL(e,A,t,i),VK(e)}function Gf(e,A){return AL(e,null,null,A),VK(e)}function MrA(e,A,t){e.lanes|=t;var i=e.alternate;i!==null&&(i.lanes|=t);for(var n=!1,g=e.return;g!==null;)g.childLanes|=t,i=g.alternate,i!==null&&(i.childLanes|=t),g.tag===22&&(e=g.stateNode,e===null||e._visibility&1||(n=!0)),e=g,g=g.return;return e.tag===3?(g=e.stateNode,n&&A!==null&&(n=31-WI(t),e=g.hiddenUpdates,i=e[n],i===null?e[n]=[A]:i.push(A),A.lane=t|536870912),g):null}function VK(e){if(50<jk)throw jk=0,MP=null,Error(It(185));for(var A=e.return;A!==null;)e=A,A=e.return;return e.tag===3?e.stateNode:null}var OD={};function EMA(e,A,t,i){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=A,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=i,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function qI(e,A,t,i){return new EMA(e,A,t,i)}function lj(e){return e=e.prototype,!(!e||!e.isReactComponent)}function GE(e,A){var t=e.alternate;return t===null?(t=qI(e.tag,A,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=A,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&65011712,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,A=e.dependencies,t.dependencies=A===null?null:{lanes:A.lanes,firstContext:A.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t.refCleanup=e.refCleanup,t}function NrA(e,A){e.flags&=65011714;var t=e.alternate;return t===null?(e.childLanes=0,e.lanes=A,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=t.childLanes,e.lanes=t.lanes,e.child=t.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=t.memoizedProps,e.memoizedState=t.memoizedState,e.updateQueue=t.updateQueue,e.type=t.type,A=t.dependencies,e.dependencies=A===null?null:{lanes:A.lanes,firstContext:A.firstContext}),e}function Tv(e,A,t,i,n,g){var o=0;if(i=e,typeof e=="function")lj(e)&&(o=1);else if(typeof e=="string")o=pNA(e,t,aB.current)?26:e==="html"||e==="head"||e==="body"?27:5;else A:switch(e){case zO:return e=qI(31,t,A,n),e.elementType=zO,e.lanes=g,e;case _D:return Rp(t.children,n,g,A);case zaA:o=8,n|=24;break;case OO:return e=qI(12,t,A,n|2),e.elementType=OO,e.lanes=g,e;case PO:return e=qI(13,t,A,n),e.elementType=PO,e.lanes=g,e;case jO:return e=qI(19,t,A,n),e.elementType=jO,e.lanes=g,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case SE:o=10;break A;case ZaA:o=9;break A;case $4:o=11;break A;case Aj:o=14;break A;case VQ:o=16,i=null;break A}o=29,t=Error(It(130,e===null?"null":typeof e,"")),i=null}return A=qI(o,t,A,n),A.elementType=e,A.type=i,A.lanes=g,A}function Rp(e,A,t,i){return e=qI(7,e,i,A),e.lanes=t,e}function mq(e,A,t){return e=qI(6,e,null,A),e.lanes=t,e}function RrA(e){var A=qI(18,null,null,0);return A.stateNode=e,A}function Sq(e,A,t){return A=qI(4,e.children!==null?e.children:[],e.key,A),A.lanes=t,A.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},A}var cX=new WeakMap;function jC(e,A){if(typeof e=="object"&&e!==null){var t=cX.get(e);return t!==void 0?t:(A={value:e,source:A,stack:P9(A)},cX.set(e,A),A)}return{value:e,source:A,stack:P9(A)}}var PD=[],jD=0,XK=null,_M=0,YC=[],HC=0,Ad=null,$l=1,AB="";function CE(e,A){PD[jD++]=_M,PD[jD++]=XK,XK=e,_M=A}function GrA(e,A,t){YC[HC++]=$l,YC[HC++]=AB,YC[HC++]=Ad,Ad=e;var i=$l;e=AB;var n=32-WI(i)-1;i&=~(1<<n),t+=1;var g=32-WI(A)+n;if(30<g){var o=n-n%5;g=(i&(1<<o)-1).toString(32),i>>=o,n-=o,$l=1<<32-WI(A)+n|t<<n|i,AB=g+e}else $l=1<<g|t<<n|i,AB=e}function Bj(e){e.return!==null&&(CE(e,1),GrA(e,1,0))}function Ej(e){for(;e===XK;)XK=PD[--jD],PD[jD]=null,_M=PD[--jD],PD[jD]=null;for(;e===Ad;)Ad=YC[--HC],YC[HC]=null,AB=YC[--HC],YC[HC]=null,$l=YC[--HC],YC[HC]=null}function brA(e,A){YC[HC++]=$l,YC[HC++]=AB,YC[HC++]=Ad,$l=A.id,AB=A.overflow,Ad=e}var ka=null,to=null,Wn=!1,Uu=null,zC=!1,aP=Error(It(519));function ed(e){var A=Error(It(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw JM(jC(A,e)),aP}function lX(e){var A=e.stateNode,t=e.type,i=e.memoizedProps;switch(A[wa]=e,A[II]=i,t){case"dialog":bn("cancel",A),bn("close",A);break;case"iframe":case"object":case"embed":bn("load",A);break;case"video":case"audio":for(t=0;t<qM.length;t++)bn(qM[t],A);break;case"source":bn("error",A);break;case"img":case"image":case"link":bn("error",A),bn("load",A);break;case"details":bn("toggle",A);break;case"input":bn("invalid",A),arA(A,i.value,i.defaultValue,i.checked,i.defaultChecked,i.type,i.name,!0);break;case"select":bn("invalid",A);break;case"textarea":bn("invalid",A),IrA(A,i.value,i.defaultValue,i.children)}t=i.children,typeof t!="string"&&typeof t!="number"&&typeof t!="bigint"||A.textContent===""+t||i.suppressHydrationWarning===!0||BCA(A.textContent,t)?(i.popover!=null&&(bn("beforetoggle",A),bn("toggle",A)),i.onScroll!=null&&bn("scroll",A),i.onScrollEnd!=null&&bn("scrollend",A),i.onClick!=null&&(A.onclick=wE),A=!0):A=!1,A||ed(e,!0)}function BX(e){for(ka=e.return;ka;)switch(ka.tag){case 5:case 31:case 13:zC=!1;return;case 27:case 3:zC=!0;return;default:ka=ka.return}}function Uy(e){if(e!==ka)return!1;if(!Wn)return BX(e),Wn=!0,!1;var A=e.tag,t;if((t=A!==3&&A!==27)&&((t=A===5)&&(t=e.type,t=!(t!=="form"&&t!=="button")||UP(e.type,e.memoizedProps)),t=!t),t&&to&&ed(e),BX(e),A===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(It(317));to=A6(e)}else if(A===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(It(317));to=A6(e)}else A===27?(A=to,wd(e.type)?(e=_P,_P=null,to=e):to=A):to=ka?$C(e.stateNode.nextSibling):null;return!0}function Wp(){to=ka=null,Wn=!1}function wq(){var e=Uu;return e!==null&&(Vr===null?Vr=e:Vr.push.apply(Vr,e),Uu=null),e}function JM(e){Uu===null?Uu=[e]:Uu.push(e)}var rP=SB(null),bf=null,kE=null;function iu(e,A,t){Zg(rP,A._currentValue),A._currentValue=t}function bE(e){e._currentValue=rP.current,aa(rP)}function IP(e,A,t){for(;e!==null;){var i=e.alternate;if((e.childLanes&A)!==A?(e.childLanes|=A,i!==null&&(i.childLanes|=A)):i!==null&&(i.childLanes&A)!==A&&(i.childLanes|=A),e===t)break;e=e.return}}function CP(e,A,t,i){var n=e.child;for(n!==null&&(n.return=e);n!==null;){var g=n.dependencies;if(g!==null){var o=n.child;g=g.firstContext;A:for(;g!==null;){var s=g;g=n;for(var a=0;a<A.length;a++)if(s.context===A[a]){g.lanes|=t,s=g.alternate,s!==null&&(s.lanes|=t),IP(g.return,t,e),i||(o=null);break A}g=s.next}}else if(n.tag===18){if(o=n.return,o===null)throw Error(It(341));o.lanes|=t,g=o.alternate,g!==null&&(g.lanes|=t),IP(o,t,e),o=null}else o=n.child;if(o!==null)o.return=n;else for(o=n;o!==null;){if(o===e){o=null;break}if(n=o.sibling,n!==null){n.return=o.return,o=n;break}o=o.return}n=o}}function aw(e,A,t,i){e=null;for(var n=A,g=!1;n!==null;){if(!g){if(n.flags&524288)g=!0;else if(n.flags&262144)break}if(n.tag===10){var o=n.alternate;if(o===null)throw Error(It(387));if(o=o.memoizedProps,o!==null){var s=n.type;eC(n.pendingProps.value,o.value)||(e!==null?e.push(s):e=[s])}}else if(n===OK.current){if(o=n.alternate,o===null)throw Error(It(387));o.memoizedState.memoizedState!==n.memoizedState.memoizedState&&(e!==null?e.push(HM):e=[HM])}n=n.return}e!==null&&CP(A,e,t,i),A.flags|=262144}function $K(e){for(e=e.firstContext;e!==null;){if(!eC(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Vp(e){bf=e,kE=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function Na(e){return UrA(bf,e)}function ib(e,A){return bf===null&&Vp(e),UrA(e,A)}function UrA(e,A){var t=A._currentValue;if(A={context:A,memoizedValue:t,next:null},kE===null){if(e===null)throw Error(It(308));kE=A,e.dependencies={lanes:0,firstContext:A},e.flags|=524288}else kE=kE.next=A;return t}var QMA=typeof AbortController<"u"?AbortController:function(){var e=[],A=this.signal={aborted:!1,addEventListener:function(t,i){e.push(i)}};this.abort=function(){A.aborted=!0,e.forEach(function(t){return t()})}},uMA=Ts.unstable_scheduleCallback,dMA=Ts.unstable_NormalPriority,hs={$$typeof:SE,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Qj(){return{controller:new QMA,data:new Map,refCount:0}}function pR(e){e.refCount--,e.refCount===0&&uMA(dMA,function(){e.controller.abort()})}var Lk=null,cP=0,IS=0,um=null;function hMA(e,A){if(Lk===null){var t=Lk=[];cP=0,IS=Tj(),um={status:"pending",value:void 0,then:function(i){t.push(i)}}}return cP++,A.then(EX,EX),A}function EX(){if(--cP===0&&Lk!==null){um!==null&&(um.status="fulfilled");var e=Lk;Lk=null,IS=0,um=null;for(var A=0;A<e.length;A++)(0,e[A])()}}function pMA(e,A){var t=[],i={status:"pending",value:null,reason:null,then:function(n){t.push(n)}};return e.then(function(){i.status="fulfilled",i.value=A;for(var n=0;n<t.length;n++)(0,t[n])(A)},function(n){for(i.status="rejected",i.reason=n,n=0;n<t.length;n++)(0,t[n])(void 0)}),i}var QX=Li.S;Li.S=function(e,A){jIA=zI(),typeof A=="object"&&A!==null&&typeof A.then=="function"&&hMA(e,A),QX!==null&&QX(e,A)};var Gp=SB(null);function uj(){var e=Gp.current;return e!==null?e:Yg.pooledCache}function qv(e,A){A===null?Zg(Gp,Gp.current):Zg(Gp,A.pool)}function vrA(){var e=uj();return e===null?null:{parent:hs._currentValue,pool:e}}var rw=Error(It(460)),dj=Error(It(474)),eL=Error(It(542)),AF={then:function(){}};function uX(e){return e=e.status,e==="fulfilled"||e==="rejected"}function KrA(e,A,t){switch(t=e[t],t===void 0?e.push(A):t!==A&&(A.then(wE,wE),A=t),A.status){case"fulfilled":return A.value;case"rejected":throw e=A.reason,hX(e),e;default:if(typeof A.status=="string")A.then(wE,wE);else{if(e=Yg,e!==null&&100<e.shellSuspendCounter)throw Error(It(482));e=A,e.status="pending",e.then(function(i){if(A.status==="pending"){var n=A;n.status="fulfilled",n.value=i}},function(i){if(A.status==="pending"){var n=A;n.status="rejected",n.reason=i}})}switch(A.status){case"fulfilled":return A.value;case"rejected":throw e=A.reason,hX(e),e}throw bp=A,rw}}function Lh(e){try{var A=e._init;return A(e._payload)}catch(t){throw t!==null&&typeof t=="object"&&typeof t.then=="function"?(bp=t,rw):t}}var bp=null;function dX(){if(bp===null)throw Error(It(459));var e=bp;return bp=null,e}function hX(e){if(e===rw||e===eL)throw Error(It(483))}var dm=null,LM=0;function nb(e){var A=LM;return LM+=1,dm===null&&(dm=[]),KrA(dm,e,A)}function B0(e,A){A=A.props.ref,e.ref=A!==void 0?A:null}function gb(e,A){throw A.$$typeof===okA?Error(It(525)):(e=Object.prototype.toString.call(A),Error(It(31,e==="[object Object]"?"object with keys {"+Object.keys(A).join(", ")+"}":e)))}function FrA(e){function A(p,y){if(e){var m=p.deletions;m===null?(p.deletions=[y],p.flags|=16):m.push(y)}}function t(p,y){if(!e)return null;for(;y!==null;)A(p,y),y=y.sibling;return null}function i(p){for(var y=new Map;p!==null;)p.key!==null?y.set(p.key,p):y.set(p.index,p),p=p.sibling;return y}function n(p,y){return p=GE(p,y),p.index=0,p.sibling=null,p}function g(p,y,m){return p.index=m,e?(m=p.alternate,m!==null?(m=m.index,m<y?(p.flags|=67108866,y):m):(p.flags|=67108866,y)):(p.flags|=1048576,y)}function o(p){return e&&p.alternate===null&&(p.flags|=67108866),p}function s(p,y,m,D){return y===null||y.tag!==6?(y=mq(m,p.mode,D),y.return=p,y):(y=n(y,m),y.return=p,y)}function a(p,y,m,D){var S=m.type;return S===_D?I(p,y,m.props.children,D,m.key):y!==null&&(y.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===VQ&&Lh(S)===y.type)?(y=n(y,m.props),B0(y,m),y.return=p,y):(y=Tv(m.type,m.key,m.props,null,p.mode,D),B0(y,m),y.return=p,y)}function r(p,y,m,D){return y===null||y.tag!==4||y.stateNode.containerInfo!==m.containerInfo||y.stateNode.implementation!==m.implementation?(y=Sq(m,p.mode,D),y.return=p,y):(y=n(y,m.children||[]),y.return=p,y)}function I(p,y,m,D,S){return y===null||y.tag!==7?(y=Rp(m,p.mode,D,S),y.return=p,y):(y=n(y,m),y.return=p,y)}function c(p,y,m){if(typeof y=="string"&&y!==""||typeof y=="number"||typeof y=="bigint")return y=mq(""+y,p.mode,m),y.return=p,y;if(typeof y=="object"&&y!==null){switch(y.$$typeof){case VG:return m=Tv(y.type,y.key,y.props,null,p.mode,m),B0(m,y),m.return=p,m;case gk:return y=Sq(y,p.mode,m),y.return=p,y;case VQ:return y=Lh(y),c(p,y,m)}if(ok(y)||C0(y))return y=Rp(y,p.mode,m,null),y.return=p,y;if(typeof y.then=="function")return c(p,nb(y),m);if(y.$$typeof===SE)return c(p,ib(p,y),m);gb(p,y)}return null}function l(p,y,m,D){var S=y!==null?y.key:null;if(typeof m=="string"&&m!==""||typeof m=="number"||typeof m=="bigint")return S!==null?null:s(p,y,""+m,D);if(typeof m=="object"&&m!==null){switch(m.$$typeof){case VG:return m.key===S?a(p,y,m,D):null;case gk:return m.key===S?r(p,y,m,D):null;case VQ:return m=Lh(m),l(p,y,m,D)}if(ok(m)||C0(m))return S!==null?null:I(p,y,m,D,null);if(typeof m.then=="function")return l(p,y,nb(m),D);if(m.$$typeof===SE)return l(p,y,ib(p,m),D);gb(p,m)}return null}function B(p,y,m,D,S){if(typeof D=="string"&&D!==""||typeof D=="number"||typeof D=="bigint")return p=p.get(m)||null,s(y,p,""+D,S);if(typeof D=="object"&&D!==null){switch(D.$$typeof){case VG:return p=p.get(D.key===null?m:D.key)||null,a(y,p,D,S);case gk:return p=p.get(D.key===null?m:D.key)||null,r(y,p,D,S);case VQ:return D=Lh(D),B(p,y,m,D,S)}if(ok(D)||C0(D))return p=p.get(m)||null,I(y,p,D,S,null);if(typeof D.then=="function")return B(p,y,m,nb(D),S);if(D.$$typeof===SE)return B(p,y,m,ib(y,D),S);gb(y,D)}return null}function Q(p,y,m,D){for(var S=null,k=null,N=y,G=y=0,M=null;N!==null&&G<m.length;G++){N.index>G?(M=N,N=null):M=N.sibling;var w=l(p,N,m[G],D);if(w===null){N===null&&(N=M);break}e&&N&&w.alternate===null&&A(p,N),y=g(w,y,G),k===null?S=w:k.sibling=w,k=w,N=M}if(G===m.length)return t(p,N),Wn&&CE(p,G),S;if(N===null){for(;G<m.length;G++)N=c(p,m[G],D),N!==null&&(y=g(N,y,G),k===null?S=N:k.sibling=N,k=N);return Wn&&CE(p,G),S}for(N=i(N);G<m.length;G++)M=B(N,p,G,m[G],D),M!==null&&(e&&M.alternate!==null&&N.delete(M.key===null?G:M.key),y=g(M,y,G),k===null?S=M:k.sibling=M,k=M);return e&&N.forEach(function(b){return A(p,b)}),Wn&&CE(p,G),S}function h(p,y,m,D){if(m==null)throw Error(It(151));for(var S=null,k=null,N=y,G=y=0,M=null,w=m.next();N!==null&&!w.done;G++,w=m.next()){N.index>G?(M=N,N=null):M=N.sibling;var b=l(p,N,w.value,D);if(b===null){N===null&&(N=M);break}e&&N&&b.alternate===null&&A(p,N),y=g(b,y,G),k===null?S=b:k.sibling=b,k=b,N=M}if(w.done)return t(p,N),Wn&&CE(p,G),S;if(N===null){for(;!w.done;G++,w=m.next())w=c(p,w.value,D),w!==null&&(y=g(w,y,G),k===null?S=w:k.sibling=w,k=w);return Wn&&CE(p,G),S}for(N=i(N);!w.done;G++,w=m.next())w=B(N,p,G,w.value,D),w!==null&&(e&&w.alternate!==null&&N.delete(w.key===null?G:w.key),y=g(w,y,G),k===null?S=w:k.sibling=w,k=w);return e&&N.forEach(function(_){return A(p,_)}),Wn&&CE(p,G),S}function d(p,y,m,D){if(typeof m=="object"&&m!==null&&m.type===_D&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case VG:A:{for(var S=m.key;y!==null;){if(y.key===S){if(S=m.type,S===_D){if(y.tag===7){t(p,y.sibling),D=n(y,m.props.children),D.return=p,p=D;break A}}else if(y.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===VQ&&Lh(S)===y.type){t(p,y.sibling),D=n(y,m.props),B0(D,m),D.return=p,p=D;break A}t(p,y);break}else A(p,y);y=y.sibling}m.type===_D?(D=Rp(m.props.children,p.mode,D,m.key),D.return=p,p=D):(D=Tv(m.type,m.key,m.props,null,p.mode,D),B0(D,m),D.return=p,p=D)}return o(p);case gk:A:{for(S=m.key;y!==null;){if(y.key===S)if(y.tag===4&&y.stateNode.containerInfo===m.containerInfo&&y.stateNode.implementation===m.implementation){t(p,y.sibling),D=n(y,m.children||[]),D.return=p,p=D;break A}else{t(p,y);break}else A(p,y);y=y.sibling}D=Sq(m,p.mode,D),D.return=p,p=D}return o(p);case VQ:return m=Lh(m),d(p,y,m,D)}if(ok(m))return Q(p,y,m,D);if(C0(m)){if(S=C0(m),typeof S!="function")throw Error(It(150));return m=S.call(m),h(p,y,m,D)}if(typeof m.then=="function")return d(p,y,nb(m),D);if(m.$$typeof===SE)return d(p,y,ib(p,m),D);gb(p,m)}return typeof m=="string"&&m!==""||typeof m=="number"||typeof m=="bigint"?(m=""+m,y!==null&&y.tag===6?(t(p,y.sibling),D=n(y,m),D.return=p,p=D):(t(p,y),D=mq(m,p.mode,D),D.return=p,p=D),o(p)):t(p,y)}return function(p,y,m,D){try{LM=0;var S=d(p,y,m,D);return dm=null,S}catch(N){if(N===rw||N===eL)throw N;var k=qI(29,N,null,p.mode);return k.lanes=D,k.return=p,k}finally{}}}var Xp=FrA(!0),_rA=FrA(!1),XQ=!1;function hj(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function lP(e,A){e=e.updateQueue,A.updateQueue===e&&(A.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function vu(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ku(e,A,t){var i=e.updateQueue;if(i===null)return null;if(i=i.shared,lg&2){var n=i.pending;return n===null?A.next=A:(A.next=n.next,n.next=A),i.pending=A,A=VK(e),MrA(e,null,t),A}return AL(e,i,A,t),VK(e)}function xk(e,A,t){if(A=A.updateQueue,A!==null&&(A=A.shared,(t&4194048)!==0)){var i=A.lanes;i&=e.pendingLanes,t|=i,A.lanes=t,erA(e,t)}}function kq(e,A){var t=e.updateQueue,i=e.alternate;if(i!==null&&(i=i.updateQueue,t===i)){var n=null,g=null;if(t=t.firstBaseUpdate,t!==null){do{var o={lane:t.lane,tag:t.tag,payload:t.payload,callback:null,next:null};g===null?n=g=o:g=g.next=o,t=t.next}while(t!==null);g===null?n=g=A:g=g.next=A}else n=g=A;t={baseState:i.baseState,firstBaseUpdate:n,lastBaseUpdate:g,shared:i.shared,callbacks:i.callbacks},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=A:e.next=A,t.lastBaseUpdate=A}var BP=!1;function Tk(){if(BP){var e=um;if(e!==null)throw e}}function qk(e,A,t,i){BP=!1;var n=e.updateQueue;XQ=!1;var g=n.firstBaseUpdate,o=n.lastBaseUpdate,s=n.shared.pending;if(s!==null){n.shared.pending=null;var a=s,r=a.next;a.next=null,o===null?g=r:o.next=r,o=a;var I=e.alternate;I!==null&&(I=I.updateQueue,s=I.lastBaseUpdate,s!==o&&(s===null?I.firstBaseUpdate=r:s.next=r,I.lastBaseUpdate=a))}if(g!==null){var c=n.baseState;o=0,I=r=a=null,s=g;do{var l=s.lane&-536870913,B=l!==s.lane;if(B?(Ln&l)===l:(i&l)===l){l!==0&&l===IS&&(BP=!0),I!==null&&(I=I.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});A:{var Q=e,h=s;l=A;var d=t;switch(h.tag){case 1:if(Q=h.payload,typeof Q=="function"){c=Q.call(d,c,l);break A}c=Q;break A;case 3:Q.flags=Q.flags&-65537|128;case 0:if(Q=h.payload,l=typeof Q=="function"?Q.call(d,c,l):Q,l==null)break A;c=so({},c,l);break A;case 2:XQ=!0}}l=s.callback,l!==null&&(e.flags|=64,B&&(e.flags|=8192),B=n.callbacks,B===null?n.callbacks=[l]:B.push(l))}else B={lane:l,tag:s.tag,payload:s.payload,callback:s.callback,next:null},I===null?(r=I=B,a=c):I=I.next=B,o|=l;if(s=s.next,s===null){if(s=n.shared.pending,s===null)break;B=s,s=B.next,B.next=null,n.lastBaseUpdate=B,n.shared.pending=null}}while(!0);I===null&&(a=c),n.baseState=a,n.firstBaseUpdate=r,n.lastBaseUpdate=I,g===null&&(n.shared.lanes=0),id|=o,e.lanes=o,e.memoizedState=c}}function JrA(e,A){if(typeof e!="function")throw Error(It(191,e));e.call(A)}function LrA(e,A){var t=e.callbacks;if(t!==null)for(e.callbacks=null,e=0;e<t.length;e++)JrA(t[e],A)}var CS=SB(null),eF=SB(0);function pX(e,A){e=zE,Zg(eF,e),Zg(CS,A),zE=e|A.baseLanes}function EP(){Zg(eF,zE),Zg(CS,CS.current)}function pj(){zE=eF.current,aa(CS),aa(eF)}var tC=SB(null),XC=null;function nu(e){var A=e.alternate;Zg(Vo,Vo.current&1),Zg(tC,e),XC===null&&(A===null||CS.current!==null||A.memoizedState!==null)&&(XC=e)}function QP(e){Zg(Vo,Vo.current),Zg(tC,e),XC===null&&(XC=e)}function xrA(e){e.tag===22?(Zg(Vo,Vo.current),Zg(tC,e),XC===null&&(XC=e)):gu()}function gu(){Zg(Vo,Vo.current),Zg(tC,tC.current)}function TI(e){aa(tC),XC===e&&(XC=null),aa(Vo)}var Vo=SB(0);function tF(e){for(var A=e;A!==null;){if(A.tag===13){var t=A.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||KP(t)||FP(t)))return A}else if(A.tag===19&&(A.memoizedProps.revealOrder==="forwards"||A.memoizedProps.revealOrder==="backwards"||A.memoizedProps.revealOrder==="unstable_legacy-backwards"||A.memoizedProps.revealOrder==="together")){if(A.flags&128)return A}else if(A.child!==null){A.child.return=A,A=A.child;continue}if(A===e)break;for(;A.sibling===null;){if(A.return===null||A.return===e)return null;A=A.return}A.sibling.return=A.return,A=A.sibling}return null}var OE=0,In=null,vg=null,Qs=null,iF=!1,hm=!1,$p=!1,nF=0,xM=0,pm=null,fMA=0;function Uo(){throw Error(It(321))}function fj(e,A){if(A===null)return!1;for(var t=0;t<A.length&&t<e.length;t++)if(!eC(e[t],A[t]))return!1;return!0}function yj(e,A,t,i,n,g){return OE=g,In=A,A.memoizedState=null,A.updateQueue=null,A.lanes=0,Li.H=e===null||e.memoizedState===null?uIA:Uj,$p=!1,g=t(i,n),$p=!1,hm&&(g=qrA(A,t,i,n)),TrA(e),g}function TrA(e){Li.H=TM;var A=vg!==null&&vg.next!==null;if(OE=0,Qs=vg=In=null,iF=!1,xM=0,pm=null,A)throw Error(It(300));e===null||ps||(e=e.dependencies,e!==null&&$K(e)&&(ps=!0))}function qrA(e,A,t,i){In=e;var n=0;do{if(hm&&(pm=null),xM=0,hm=!1,25<=n)throw Error(It(301));if(n+=1,Qs=vg=null,e.updateQueue!=null){var g=e.updateQueue;g.lastEffect=null,g.events=null,g.stores=null,g.memoCache!=null&&(g.memoCache.index=0)}Li.H=dIA,g=A(t,i)}while(hm);return g}function yMA(){var e=Li.H,A=e.useState()[0];return A=typeof A.then=="function"?fR(A):A,e=e.useState()[0],(vg!==null?vg.memoizedState:null)!==e&&(In.flags|=1024),A}function Dj(){var e=nF!==0;return nF=0,e}function mj(e,A,t){A.updateQueue=e.updateQueue,A.flags&=-2053,e.lanes&=~t}function Sj(e){if(iF){for(e=e.memoizedState;e!==null;){var A=e.queue;A!==null&&(A.pending=null),e=e.next}iF=!1}OE=0,Qs=vg=In=null,hm=!1,xM=nF=0,pm=null}function ur(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Qs===null?In.memoizedState=Qs=e:Qs=Qs.next=e,Qs}function As(){if(vg===null){var e=In.alternate;e=e!==null?e.memoizedState:null}else e=vg.next;var A=Qs===null?In.memoizedState:Qs.next;if(A!==null)Qs=A,vg=e;else{if(e===null)throw In.alternate===null?Error(It(467)):Error(It(310));vg=e,e={memoizedState:vg.memoizedState,baseState:vg.baseState,baseQueue:vg.baseQueue,queue:vg.queue,next:null},Qs===null?In.memoizedState=Qs=e:Qs=Qs.next=e}return Qs}function tL(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function fR(e){var A=xM;return xM+=1,pm===null&&(pm=[]),e=KrA(pm,e,A),A=In,(Qs===null?A.memoizedState:Qs.next)===null&&(A=A.alternate,Li.H=A===null||A.memoizedState===null?uIA:Uj),e}function iL(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return fR(e);if(e.$$typeof===SE)return Na(e)}throw Error(It(438,String(e)))}function wj(e){var A=null,t=In.updateQueue;if(t!==null&&(A=t.memoCache),A==null){var i=In.alternate;i!==null&&(i=i.updateQueue,i!==null&&(i=i.memoCache,i!=null&&(A={data:i.data.map(function(n){return n.slice()}),index:0})))}if(A==null&&(A={data:[],index:0}),t===null&&(t=tL(),In.updateQueue=t),t.memoCache=A,t=A.data[A.index],t===void 0)for(t=A.data[A.index]=Array(e),i=0;i<e;i++)t[i]=skA;return A.index++,t}function PE(e,A){return typeof A=="function"?A(e):A}function Yv(e){var A=As();return kj(A,vg,e)}function kj(e,A,t){var i=e.queue;if(i===null)throw Error(It(311));i.lastRenderedReducer=t;var n=e.baseQueue,g=i.pending;if(g!==null){if(n!==null){var o=n.next;n.next=g.next,g.next=o}A.baseQueue=n=g,i.pending=null}if(g=e.baseState,n===null)e.memoizedState=g;else{A=n.next;var s=o=null,a=null,r=A,I=!1;do{var c=r.lane&-536870913;if(c!==r.lane?(Ln&c)===c:(OE&c)===c){var l=r.revertLane;if(l===0)a!==null&&(a=a.next={lane:0,revertLane:0,gesture:null,action:r.action,hasEagerState:r.hasEagerState,eagerState:r.eagerState,next:null}),c===IS&&(I=!0);else if((OE&l)===l){r=r.next,l===IS&&(I=!0);continue}else c={lane:0,revertLane:r.revertLane,gesture:null,action:r.action,hasEagerState:r.hasEagerState,eagerState:r.eagerState,next:null},a===null?(s=a=c,o=g):a=a.next=c,In.lanes|=l,id|=l;c=r.action,$p&&t(g,c),g=r.hasEagerState?r.eagerState:t(g,c)}else l={lane:c,revertLane:r.revertLane,gesture:r.gesture,action:r.action,hasEagerState:r.hasEagerState,eagerState:r.eagerState,next:null},a===null?(s=a=l,o=g):a=a.next=l,In.lanes|=c,id|=c;r=r.next}while(r!==null&&r!==A);if(a===null?o=g:a.next=s,!eC(g,e.memoizedState)&&(ps=!0,I&&(t=um,t!==null)))throw t;e.memoizedState=g,e.baseState=o,e.baseQueue=a,i.lastRenderedState=g}return n===null&&(i.lanes=0),[e.memoizedState,i.dispatch]}function Mq(e){var A=As(),t=A.queue;if(t===null)throw Error(It(311));t.lastRenderedReducer=e;var i=t.dispatch,n=t.pending,g=A.memoizedState;if(n!==null){t.pending=null;var o=n=n.next;do g=e(g,o.action),o=o.next;while(o!==n);eC(g,A.memoizedState)||(ps=!0),A.memoizedState=g,A.baseQueue===null&&(A.baseState=g),t.lastRenderedState=g}return[g,i]}function YrA(e,A,t){var i=In,n=As(),g=Wn;if(g){if(t===void 0)throw Error(It(407));t=t()}else t=A();var o=!eC((vg||n).memoizedState,t);if(o&&(n.memoizedState=t,ps=!0),n=n.queue,Mj(PrA.bind(null,i,n,e),[e]),n.getSnapshot!==A||o||Qs!==null&&Qs.memoizedState.tag&1){if(i.flags|=2048,cS(9,{destroy:void 0},OrA.bind(null,i,n,t,A),null),Yg===null)throw Error(It(349));g||OE&127||HrA(i,A,t)}return t}function HrA(e,A,t){e.flags|=16384,e={getSnapshot:A,value:t},A=In.updateQueue,A===null?(A=tL(),In.updateQueue=A,A.stores=[e]):(t=A.stores,t===null?A.stores=[e]:t.push(e))}function OrA(e,A,t,i){A.value=t,A.getSnapshot=i,jrA(A)&&zrA(e)}function PrA(e,A,t){return t(function(){jrA(A)&&zrA(e)})}function jrA(e){var A=e.getSnapshot;e=e.value;try{var t=A();return!eC(e,t)}catch{return!0}}function zrA(e){var A=Gf(e,2);A!==null&&aI(A,e,2)}function uP(e){var A=ur();if(typeof e=="function"){var t=e;if(e=t(),$p){uu(!0);try{t()}finally{uu(!1)}}}return A.memoizedState=A.baseState=e,A.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:PE,lastRenderedState:e},A}function ZrA(e,A,t,i){return e.baseState=t,kj(e,vg,typeof i=="function"?i:PE)}function DMA(e,A,t,i,n){if(gL(e))throw Error(It(485));if(e=A.action,e!==null){var g={payload:n,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(o){g.listeners.push(o)}};Li.T!==null?t(!0):g.isTransition=!1,i(g),t=A.pending,t===null?(g.next=A.pending=g,WrA(A,g)):(g.next=t.next,A.pending=t.next=g)}}function WrA(e,A){var t=A.action,i=A.payload,n=e.state;if(A.isTransition){var g=Li.T,o={};Li.T=o;try{var s=t(n,i),a=Li.S;a!==null&&a(o,s),fX(e,A,s)}catch(r){dP(e,A,r)}finally{g!==null&&o.types!==null&&(g.types=o.types),Li.T=g}}else try{g=t(n,i),fX(e,A,g)}catch(r){dP(e,A,r)}}function fX(e,A,t){t!==null&&typeof t=="object"&&typeof t.then=="function"?t.then(function(i){yX(e,A,i)},function(i){return dP(e,A,i)}):yX(e,A,t)}function yX(e,A,t){A.status="fulfilled",A.value=t,VrA(A),e.state=t,A=e.pending,A!==null&&(t=A.next,t===A?e.pending=null:(t=t.next,A.next=t,WrA(e,t)))}function dP(e,A,t){var i=e.pending;if(e.pending=null,i!==null){i=i.next;do A.status="rejected",A.reason=t,VrA(A),A=A.next;while(A!==i)}e.action=null}function VrA(e){e=e.listeners;for(var A=0;A<e.length;A++)(0,e[A])()}function XrA(e,A){return A}function DX(e,A){if(Wn){var t=Yg.formState;if(t!==null){A:{var i=In;if(Wn){if(to){e:{for(var n=to,g=zC;n.nodeType!==8;){if(!g){n=null;break e}if(n=$C(n.nextSibling),n===null){n=null;break e}}g=n.data,n=g==="F!"||g==="F"?n:null}if(n){to=$C(n.nextSibling),i=n.data==="F!";break A}}ed(i)}i=!1}i&&(A=t[0])}}return t=ur(),t.memoizedState=t.baseState=A,i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:XrA,lastRenderedState:A},t.queue=i,t=BIA.bind(null,In,i),i.dispatch=t,i=uP(!1),g=bj.bind(null,In,!1,i.queue),i=ur(),n={state:A,dispatch:null,action:e,pending:null},i.queue=n,t=DMA.bind(null,In,n,g,t),n.dispatch=t,i.memoizedState=e,[A,t,!1]}function mX(e){var A=As();return $rA(A,vg,e)}function $rA(e,A,t){if(A=kj(e,A,XrA)[0],e=Yv(PE)[0],typeof A=="object"&&A!==null&&typeof A.then=="function")try{var i=fR(A)}catch(o){throw o===rw?eL:o}else i=A;A=As();var n=A.queue,g=n.dispatch;return t!==A.memoizedState&&(In.flags|=2048,cS(9,{destroy:void 0},mMA.bind(null,n,t),null)),[i,g,e]}function mMA(e,A){e.action=A}function SX(e){var A=As(),t=vg;if(t!==null)return $rA(A,t,e);As(),A=A.memoizedState,t=As();var i=t.queue.dispatch;return t.memoizedState=e,[A,i,!1]}function cS(e,A,t,i){return e={tag:e,create:t,deps:i,inst:A,next:null},A=In.updateQueue,A===null&&(A=tL(),In.updateQueue=A),t=A.lastEffect,t===null?A.lastEffect=e.next=e:(i=t.next,t.next=e,e.next=i,A.lastEffect=e),e}function AIA(){return As().memoizedState}function Hv(e,A,t,i){var n=ur();In.flags|=e,n.memoizedState=cS(1|A,{destroy:void 0},t,i===void 0?null:i)}function nL(e,A,t,i){var n=As();i=i===void 0?null:i;var g=n.memoizedState.inst;vg!==null&&i!==null&&fj(i,vg.memoizedState.deps)?n.memoizedState=cS(A,g,t,i):(In.flags|=e,n.memoizedState=cS(1|A,g,t,i))}function wX(e,A){Hv(8390656,8,e,A)}function Mj(e,A){nL(2048,8,e,A)}function SMA(e){In.flags|=4;var A=In.updateQueue;if(A===null)A=tL(),In.updateQueue=A,A.events=[e];else{var t=A.events;t===null?A.events=[e]:t.push(e)}}function eIA(e){var A=As().memoizedState;return SMA({ref:A,nextImpl:e}),function(){if(lg&2)throw Error(It(440));return A.impl.apply(void 0,arguments)}}function tIA(e,A){return nL(4,2,e,A)}function iIA(e,A){return nL(4,4,e,A)}function nIA(e,A){if(typeof A=="function"){e=e();var t=A(e);return function(){typeof t=="function"?t():A(null)}}if(A!=null)return e=e(),A.current=e,function(){A.current=null}}function gIA(e,A,t){t=t!=null?t.concat([e]):null,nL(4,4,nIA.bind(null,A,e),t)}function Nj(){}function oIA(e,A){var t=As();A=A===void 0?null:A;var i=t.memoizedState;return A!==null&&fj(A,i[1])?i[0]:(t.memoizedState=[e,A],e)}function sIA(e,A){var t=As();A=A===void 0?null:A;var i=t.memoizedState;if(A!==null&&fj(A,i[1]))return i[0];if(i=e(),$p){uu(!0);try{e()}finally{uu(!1)}}return t.memoizedState=[i,A],i}function Rj(e,A,t){return t===void 0||OE&1073741824&&!(Ln&261930)?e.memoizedState=A:(e.memoizedState=t,e=ZIA(),In.lanes|=e,id|=e,t)}function aIA(e,A,t,i){return eC(t,A)?t:CS.current!==null?(e=Rj(e,t,i),eC(e,A)||(ps=!0),e):!(OE&42)||OE&1073741824&&!(Ln&261930)?(ps=!0,e.memoizedState=t):(e=ZIA(),In.lanes|=e,id|=e,A)}function rIA(e,A,t,i,n){var g=Bg.p;Bg.p=g!==0&&8>g?g:8;var o=Li.T,s={};Li.T=s,bj(e,!1,A,t);try{var a=n(),r=Li.S;if(r!==null&&r(s,a),a!==null&&typeof a=="object"&&typeof a.then=="function"){var I=pMA(a,i);Yk(e,A,I,VI(e))}else Yk(e,A,i,VI(e))}catch(c){Yk(e,A,{then:function(){},status:"rejected",reason:c},VI())}finally{Bg.p=g,o!==null&&s.types!==null&&(o.types=s.types),Li.T=o}}function wMA(){}function hP(e,A,t,i){if(e.tag!==5)throw Error(It(476));var n=IIA(e).queue;rIA(e,n,A,Np,t===null?wMA:function(){return CIA(e),t(i)})}function IIA(e){var A=e.memoizedState;if(A!==null)return A;A={memoizedState:Np,baseState:Np,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:PE,lastRenderedState:Np},next:null};var t={};return A.next={memoizedState:t,baseState:t,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:PE,lastRenderedState:t},next:null},e.memoizedState=A,e=e.alternate,e!==null&&(e.memoizedState=A),A}function CIA(e){var A=IIA(e);A.next===null&&(A=e.alternate.memoizedState),Yk(e,A.next.queue,{},VI())}function Gj(){return Na(HM)}function cIA(){return As().memoizedState}function lIA(){return As().memoizedState}function kMA(e){for(var A=e.return;A!==null;){switch(A.tag){case 24:case 3:var t=VI();e=vu(t);var i=Ku(A,e,t);i!==null&&(aI(i,A,t),xk(i,A,t)),A={cache:Qj()},e.payload=A;return}A=A.return}}function MMA(e,A,t){var i=VI();t={lane:i,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null},gL(e)?EIA(A,t):(t=cj(e,A,t,i),t!==null&&(aI(t,e,i),QIA(t,A,i)))}function BIA(e,A,t){var i=VI();Yk(e,A,t,i)}function Yk(e,A,t,i){var n={lane:i,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null};if(gL(e))EIA(A,n);else{var g=e.alternate;if(e.lanes===0&&(g===null||g.lanes===0)&&(g=A.lastRenderedReducer,g!==null))try{var o=A.lastRenderedState,s=g(o,t);if(n.hasEagerState=!0,n.eagerState=s,eC(s,o))return AL(e,A,n,0),Yg===null&&$J(),!1}catch{}finally{}if(t=cj(e,A,n,i),t!==null)return aI(t,e,i),QIA(t,A,i),!0}return!1}function bj(e,A,t,i){if(i={lane:2,revertLane:Tj(),gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},gL(e)){if(A)throw Error(It(479))}else A=cj(e,t,i,2),A!==null&&aI(A,e,2)}function gL(e){var A=e.alternate;return e===In||A!==null&&A===In}function EIA(e,A){hm=iF=!0;var t=e.pending;t===null?A.next=A:(A.next=t.next,t.next=A),e.pending=A}function QIA(e,A,t){if(t&4194048){var i=A.lanes;i&=e.pendingLanes,t|=i,A.lanes=t,erA(e,t)}}var TM={readContext:Na,use:iL,useCallback:Uo,useContext:Uo,useEffect:Uo,useImperativeHandle:Uo,useLayoutEffect:Uo,useInsertionEffect:Uo,useMemo:Uo,useReducer:Uo,useRef:Uo,useState:Uo,useDebugValue:Uo,useDeferredValue:Uo,useTransition:Uo,useSyncExternalStore:Uo,useId:Uo,useHostTransitionStatus:Uo,useFormState:Uo,useActionState:Uo,useOptimistic:Uo,useMemoCache:Uo,useCacheRefresh:Uo};TM.useEffectEvent=Uo;var uIA={readContext:Na,use:iL,useCallback:function(e,A){return ur().memoizedState=[e,A===void 0?null:A],e},useContext:Na,useEffect:wX,useImperativeHandle:function(e,A,t){t=t!=null?t.concat([e]):null,Hv(4194308,4,nIA.bind(null,A,e),t)},useLayoutEffect:function(e,A){return Hv(4194308,4,e,A)},useInsertionEffect:function(e,A){Hv(4,2,e,A)},useMemo:function(e,A){var t=ur();A=A===void 0?null:A;var i=e();if($p){uu(!0);try{e()}finally{uu(!1)}}return t.memoizedState=[i,A],i},useReducer:function(e,A,t){var i=ur();if(t!==void 0){var n=t(A);if($p){uu(!0);try{t(A)}finally{uu(!1)}}}else n=A;return i.memoizedState=i.baseState=n,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},i.queue=e,e=e.dispatch=MMA.bind(null,In,e),[i.memoizedState,e]},useRef:function(e){var A=ur();return e={current:e},A.memoizedState=e},useState:function(e){e=uP(e);var A=e.queue,t=BIA.bind(null,In,A);return A.dispatch=t,[e.memoizedState,t]},useDebugValue:Nj,useDeferredValue:function(e,A){var t=ur();return Rj(t,e,A)},useTransition:function(){var e=uP(!1);return e=rIA.bind(null,In,e.queue,!0,!1),ur().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,A,t){var i=In,n=ur();if(Wn){if(t===void 0)throw Error(It(407));t=t()}else{if(t=A(),Yg===null)throw Error(It(349));Ln&127||HrA(i,A,t)}n.memoizedState=t;var g={value:t,getSnapshot:A};return n.queue=g,wX(PrA.bind(null,i,g,e),[e]),i.flags|=2048,cS(9,{destroy:void 0},OrA.bind(null,i,g,t,A),null),t},useId:function(){var e=ur(),A=Yg.identifierPrefix;if(Wn){var t=AB,i=$l;t=(i&~(1<<32-WI(i)-1)).toString(32)+t,A="_"+A+"R_"+t,t=nF++,0<t&&(A+="H"+t.toString(32)),A+="_"}else t=fMA++,A="_"+A+"r_"+t.toString(32)+"_";return e.memoizedState=A},useHostTransitionStatus:Gj,useFormState:DX,useActionState:DX,useOptimistic:function(e){var A=ur();A.memoizedState=A.baseState=e;var t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return A.queue=t,A=bj.bind(null,In,!0,t),t.dispatch=A,[e,A]},useMemoCache:wj,useCacheRefresh:function(){return ur().memoizedState=kMA.bind(null,In)},useEffectEvent:function(e){var A=ur(),t={impl:e};return A.memoizedState=t,function(){if(lg&2)throw Error(It(440));return t.impl.apply(void 0,arguments)}}},Uj={readContext:Na,use:iL,useCallback:oIA,useContext:Na,useEffect:Mj,useImperativeHandle:gIA,useInsertionEffect:tIA,useLayoutEffect:iIA,useMemo:sIA,useReducer:Yv,useRef:AIA,useState:function(){return Yv(PE)},useDebugValue:Nj,useDeferredValue:function(e,A){var t=As();return aIA(t,vg.memoizedState,e,A)},useTransition:function(){var e=Yv(PE)[0],A=As().memoizedState;return[typeof e=="boolean"?e:fR(e),A]},useSyncExternalStore:YrA,useId:cIA,useHostTransitionStatus:Gj,useFormState:mX,useActionState:mX,useOptimistic:function(e,A){var t=As();return ZrA(t,vg,e,A)},useMemoCache:wj,useCacheRefresh:lIA};Uj.useEffectEvent=eIA;var dIA={readContext:Na,use:iL,useCallback:oIA,useContext:Na,useEffect:Mj,useImperativeHandle:gIA,useInsertionEffect:tIA,useLayoutEffect:iIA,useMemo:sIA,useReducer:Mq,useRef:AIA,useState:function(){return Mq(PE)},useDebugValue:Nj,useDeferredValue:function(e,A){var t=As();return vg===null?Rj(t,e,A):aIA(t,vg.memoizedState,e,A)},useTransition:function(){var e=Mq(PE)[0],A=As().memoizedState;return[typeof e=="boolean"?e:fR(e),A]},useSyncExternalStore:YrA,useId:cIA,useHostTransitionStatus:Gj,useFormState:SX,useActionState:SX,useOptimistic:function(e,A){var t=As();return vg!==null?ZrA(t,vg,e,A):(t.baseState=e,[e,t.queue.dispatch])},useMemoCache:wj,useCacheRefresh:lIA};dIA.useEffectEvent=eIA;function Nq(e,A,t,i){A=e.memoizedState,t=t(i,A),t=t==null?A:so({},A,t),e.memoizedState=t,e.lanes===0&&(e.updateQueue.baseState=t)}var pP={enqueueSetState:function(e,A,t){e=e._reactInternals;var i=VI(),n=vu(i);n.payload=A,t!=null&&(n.callback=t),A=Ku(e,n,i),A!==null&&(aI(A,e,i),xk(A,e,i))},enqueueReplaceState:function(e,A,t){e=e._reactInternals;var i=VI(),n=vu(i);n.tag=1,n.payload=A,t!=null&&(n.callback=t),A=Ku(e,n,i),A!==null&&(aI(A,e,i),xk(A,e,i))},enqueueForceUpdate:function(e,A){e=e._reactInternals;var t=VI(),i=vu(t);i.tag=2,A!=null&&(i.callback=A),A=Ku(e,i,t),A!==null&&(aI(A,e,t),xk(A,e,t))}};function kX(e,A,t,i,n,g,o){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(i,g,o):A.prototype&&A.prototype.isPureReactComponent?!FM(t,i)||!FM(n,g):!0}function MX(e,A,t,i){e=A.state,typeof A.componentWillReceiveProps=="function"&&A.componentWillReceiveProps(t,i),typeof A.UNSAFE_componentWillReceiveProps=="function"&&A.UNSAFE_componentWillReceiveProps(t,i),A.state!==e&&pP.enqueueReplaceState(A,A.state,null)}function Af(e,A){var t=A;if("ref"in A){t={};for(var i in A)i!=="ref"&&(t[i]=A[i])}if(e=e.defaultProps){t===A&&(t=so({},t));for(var n in e)t[n]===void 0&&(t[n]=e[n])}return t}function hIA(e){WK(e)}function pIA(e){console.error(e)}function fIA(e){WK(e)}function gF(e,A){try{var t=e.onUncaughtError;t(A.value,{componentStack:A.stack})}catch(i){setTimeout(function(){throw i})}}function NX(e,A,t){try{var i=e.onCaughtError;i(t.value,{componentStack:t.stack,errorBoundary:A.tag===1?A.stateNode:null})}catch(n){setTimeout(function(){throw n})}}function fP(e,A,t){return t=vu(t),t.tag=3,t.payload={element:null},t.callback=function(){gF(e,A)},t}function yIA(e){return e=vu(e),e.tag=3,e}function DIA(e,A,t,i){var n=t.type.getDerivedStateFromError;if(typeof n=="function"){var g=i.value;e.payload=function(){return n(g)},e.callback=function(){NX(A,t,i)}}var o=t.stateNode;o!==null&&typeof o.componentDidCatch=="function"&&(e.callback=function(){NX(A,t,i),typeof n!="function"&&(Fu===null?Fu=new Set([this]):Fu.add(this));var s=i.stack;this.componentDidCatch(i.value,{componentStack:s!==null?s:""})})}function NMA(e,A,t,i,n){if(t.flags|=32768,i!==null&&typeof i=="object"&&typeof i.then=="function"){if(A=t.alternate,A!==null&&aw(A,t,n,!0),t=tC.current,t!==null){switch(t.tag){case 31:case 13:return XC===null?IF():t.alternate===null&&Lo===0&&(Lo=3),t.flags&=-257,t.flags|=65536,t.lanes=n,i===AF?t.flags|=16384:(A=t.updateQueue,A===null?t.updateQueue=new Set([i]):A.add(i),xq(e,i,n)),!1;case 22:return t.flags|=65536,i===AF?t.flags|=16384:(A=t.updateQueue,A===null?(A={transitions:null,markerInstances:null,retryQueue:new Set([i])},t.updateQueue=A):(t=A.retryQueue,t===null?A.retryQueue=new Set([i]):t.add(i)),xq(e,i,n)),!1}throw Error(It(435,t.tag))}return xq(e,i,n),IF(),!1}if(Wn)return A=tC.current,A!==null?(!(A.flags&65536)&&(A.flags|=256),A.flags|=65536,A.lanes=n,i!==aP&&(e=Error(It(422),{cause:i}),JM(jC(e,t)))):(i!==aP&&(A=Error(It(423),{cause:i}),JM(jC(A,t))),e=e.current.alternate,e.flags|=65536,n&=-n,e.lanes|=n,i=jC(i,t),n=fP(e.stateNode,i,n),kq(e,n),Lo!==4&&(Lo=2)),!1;var g=Error(It(520),{cause:i});if(g=jC(g,t),Pk===null?Pk=[g]:Pk.push(g),Lo!==4&&(Lo=2),A===null)return!0;i=jC(i,t),t=A;do{switch(t.tag){case 3:return t.flags|=65536,e=n&-n,t.lanes|=e,e=fP(t.stateNode,i,e),kq(t,e),!1;case 1:if(A=t.type,g=t.stateNode,(t.flags&128)===0&&(typeof A.getDerivedStateFromError=="function"||g!==null&&typeof g.componentDidCatch=="function"&&(Fu===null||!Fu.has(g))))return t.flags|=65536,n&=-n,t.lanes|=n,n=yIA(n),DIA(n,e,t,i),kq(t,n),!1}t=t.return}while(t!==null);return!1}var vj=Error(It(461)),ps=!1;function ya(e,A,t,i){A.child=e===null?_rA(A,null,t,i):Xp(A,e.child,t,i)}function RX(e,A,t,i,n){t=t.render;var g=A.ref;if("ref"in i){var o={};for(var s in i)s!=="ref"&&(o[s]=i[s])}else o=i;return Vp(A),i=yj(e,A,t,o,g,n),s=Dj(),e!==null&&!ps?(mj(e,A,n),jE(e,A,n)):(Wn&&s&&Bj(A),A.flags|=1,ya(e,A,i,n),A.child)}function GX(e,A,t,i,n){if(e===null){var g=t.type;return typeof g=="function"&&!lj(g)&&g.defaultProps===void 0&&t.compare===null?(A.tag=15,A.type=g,mIA(e,A,g,i,n)):(e=Tv(t.type,null,i,A,A.mode,n),e.ref=A.ref,e.return=A,A.child=e)}if(g=e.child,!Kj(e,n)){var o=g.memoizedProps;if(t=t.compare,t=t!==null?t:FM,t(o,i)&&e.ref===A.ref)return jE(e,A,n)}return A.flags|=1,e=GE(g,i),e.ref=A.ref,e.return=A,A.child=e}function mIA(e,A,t,i,n){if(e!==null){var g=e.memoizedProps;if(FM(g,i)&&e.ref===A.ref)if(ps=!1,A.pendingProps=i=g,Kj(e,n))e.flags&131072&&(ps=!0);else return A.lanes=e.lanes,jE(e,A,n)}return yP(e,A,t,i,n)}function SIA(e,A,t,i){var n=i.children,g=e!==null?e.memoizedState:null;if(e===null&&A.stateNode===null&&(A.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),i.mode==="hidden"){if(A.flags&128){if(g=g!==null?g.baseLanes|t:t,e!==null){for(i=A.child=e.child,n=0;i!==null;)n=n|i.lanes|i.childLanes,i=i.sibling;i=n&~g}else i=0,A.child=null;return bX(e,A,g,t,i)}if(t&536870912)A.memoizedState={baseLanes:0,cachePool:null},e!==null&&qv(A,g!==null?g.cachePool:null),g!==null?pX(A,g):EP(),xrA(A);else return i=A.lanes=536870912,bX(e,A,g!==null?g.baseLanes|t:t,t,i)}else g!==null?(qv(A,g.cachePool),pX(A,g),gu(),A.memoizedState=null):(e!==null&&qv(A,null),EP(),gu());return ya(e,A,n,t),A.child}function ak(e,A){return e!==null&&e.tag===22||A.stateNode!==null||(A.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),A.sibling}function bX(e,A,t,i,n){var g=uj();return g=g===null?null:{parent:hs._currentValue,pool:g},A.memoizedState={baseLanes:t,cachePool:g},e!==null&&qv(A,null),EP(),xrA(A),e!==null&&aw(e,A,i,!0),A.childLanes=n,null}function Ov(e,A){return A=oF({mode:A.mode,children:A.children},e.mode),A.ref=e.ref,e.child=A,A.return=e,A}function UX(e,A,t){return Xp(A,e.child,null,t),e=Ov(A,A.pendingProps),e.flags|=2,TI(A),A.memoizedState=null,e}function RMA(e,A,t){var i=A.pendingProps,n=(A.flags&128)!==0;if(A.flags&=-129,e===null){if(Wn){if(i.mode==="hidden")return e=Ov(A,i),A.lanes=536870912,ak(null,e);if(QP(A),(e=to)?(e=uCA(e,zC),e=e!==null&&e.data==="&"?e:null,e!==null&&(A.memoizedState={dehydrated:e,treeContext:Ad!==null?{id:$l,overflow:AB}:null,retryLane:536870912,hydrationErrors:null},t=RrA(e),t.return=A,A.child=t,ka=A,to=null)):e=null,e===null)throw ed(A);return A.lanes=536870912,null}return Ov(A,i)}var g=e.memoizedState;if(g!==null){var o=g.dehydrated;if(QP(A),n)if(A.flags&256)A.flags&=-257,A=UX(e,A,t);else if(A.memoizedState!==null)A.child=e.child,A.flags|=128,A=null;else throw Error(It(558));else if(ps||aw(e,A,t,!1),n=(t&e.childLanes)!==0,ps||n){if(i=Yg,i!==null&&(o=trA(i,t),o!==0&&o!==g.retryLane))throw g.retryLane=o,Gf(e,o),aI(i,e,o),vj;IF(),A=UX(e,A,t)}else e=g.treeContext,to=$C(o.nextSibling),ka=A,Wn=!0,Uu=null,zC=!1,e!==null&&brA(A,e),A=Ov(A,i),A.flags|=4096;return A}return e=GE(e.child,{mode:i.mode,children:i.children}),e.ref=A.ref,A.child=e,e.return=A,e}function Pv(e,A){var t=A.ref;if(t===null)e!==null&&e.ref!==null&&(A.flags|=4194816);else{if(typeof t!="function"&&typeof t!="object")throw Error(It(284));(e===null||e.ref!==t)&&(A.flags|=4194816)}}function yP(e,A,t,i,n){return Vp(A),t=yj(e,A,t,i,void 0,n),i=Dj(),e!==null&&!ps?(mj(e,A,n),jE(e,A,n)):(Wn&&i&&Bj(A),A.flags|=1,ya(e,A,t,n),A.child)}function vX(e,A,t,i,n,g){return Vp(A),A.updateQueue=null,t=qrA(A,i,t,n),TrA(e),i=Dj(),e!==null&&!ps?(mj(e,A,g),jE(e,A,g)):(Wn&&i&&Bj(A),A.flags|=1,ya(e,A,t,g),A.child)}function KX(e,A,t,i,n){if(Vp(A),A.stateNode===null){var g=OD,o=t.contextType;typeof o=="object"&&o!==null&&(g=Na(o)),g=new t(i,g),A.memoizedState=g.state!==null&&g.state!==void 0?g.state:null,g.updater=pP,A.stateNode=g,g._reactInternals=A,g=A.stateNode,g.props=i,g.state=A.memoizedState,g.refs={},hj(A),o=t.contextType,g.context=typeof o=="object"&&o!==null?Na(o):OD,g.state=A.memoizedState,o=t.getDerivedStateFromProps,typeof o=="function"&&(Nq(A,t,o,i),g.state=A.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof g.getSnapshotBeforeUpdate=="function"||typeof g.UNSAFE_componentWillMount!="function"&&typeof g.componentWillMount!="function"||(o=g.state,typeof g.componentWillMount=="function"&&g.componentWillMount(),typeof g.UNSAFE_componentWillMount=="function"&&g.UNSAFE_componentWillMount(),o!==g.state&&pP.enqueueReplaceState(g,g.state,null),qk(A,i,g,n),Tk(),g.state=A.memoizedState),typeof g.componentDidMount=="function"&&(A.flags|=4194308),i=!0}else if(e===null){g=A.stateNode;var s=A.memoizedProps,a=Af(t,s);g.props=a;var r=g.context,I=t.contextType;o=OD,typeof I=="object"&&I!==null&&(o=Na(I));var c=t.getDerivedStateFromProps;I=typeof c=="function"||typeof g.getSnapshotBeforeUpdate=="function",s=A.pendingProps!==s,I||typeof g.UNSAFE_componentWillReceiveProps!="function"&&typeof g.componentWillReceiveProps!="function"||(s||r!==o)&&MX(A,g,i,o),XQ=!1;var l=A.memoizedState;g.state=l,qk(A,i,g,n),Tk(),r=A.memoizedState,s||l!==r||XQ?(typeof c=="function"&&(Nq(A,t,c,i),r=A.memoizedState),(a=XQ||kX(A,t,a,i,l,r,o))?(I||typeof g.UNSAFE_componentWillMount!="function"&&typeof g.componentWillMount!="function"||(typeof g.componentWillMount=="function"&&g.componentWillMount(),typeof g.UNSAFE_componentWillMount=="function"&&g.UNSAFE_componentWillMount()),typeof g.componentDidMount=="function"&&(A.flags|=4194308)):(typeof g.componentDidMount=="function"&&(A.flags|=4194308),A.memoizedProps=i,A.memoizedState=r),g.props=i,g.state=r,g.context=o,i=a):(typeof g.componentDidMount=="function"&&(A.flags|=4194308),i=!1)}else{g=A.stateNode,lP(e,A),o=A.memoizedProps,I=Af(t,o),g.props=I,c=A.pendingProps,l=g.context,r=t.contextType,a=OD,typeof r=="object"&&r!==null&&(a=Na(r)),s=t.getDerivedStateFromProps,(r=typeof s=="function"||typeof g.getSnapshotBeforeUpdate=="function")||typeof g.UNSAFE_componentWillReceiveProps!="function"&&typeof g.componentWillReceiveProps!="function"||(o!==c||l!==a)&&MX(A,g,i,a),XQ=!1,l=A.memoizedState,g.state=l,qk(A,i,g,n),Tk();var B=A.memoizedState;o!==c||l!==B||XQ||e!==null&&e.dependencies!==null&&$K(e.dependencies)?(typeof s=="function"&&(Nq(A,t,s,i),B=A.memoizedState),(I=XQ||kX(A,t,I,i,l,B,a)||e!==null&&e.dependencies!==null&&$K(e.dependencies))?(r||typeof g.UNSAFE_componentWillUpdate!="function"&&typeof g.componentWillUpdate!="function"||(typeof g.componentWillUpdate=="function"&&g.componentWillUpdate(i,B,a),typeof g.UNSAFE_componentWillUpdate=="function"&&g.UNSAFE_componentWillUpdate(i,B,a)),typeof g.componentDidUpdate=="function"&&(A.flags|=4),typeof g.getSnapshotBeforeUpdate=="function"&&(A.flags|=1024)):(typeof g.componentDidUpdate!="function"||o===e.memoizedProps&&l===e.memoizedState||(A.flags|=4),typeof g.getSnapshotBeforeUpdate!="function"||o===e.memoizedProps&&l===e.memoizedState||(A.flags|=1024),A.memoizedProps=i,A.memoizedState=B),g.props=i,g.state=B,g.context=a,i=I):(typeof g.componentDidUpdate!="function"||o===e.memoizedProps&&l===e.memoizedState||(A.flags|=4),typeof g.getSnapshotBeforeUpdate!="function"||o===e.memoizedProps&&l===e.memoizedState||(A.flags|=1024),i=!1)}return g=i,Pv(e,A),i=(A.flags&128)!==0,g||i?(g=A.stateNode,t=i&&typeof t.getDerivedStateFromError!="function"?null:g.render(),A.flags|=1,e!==null&&i?(A.child=Xp(A,e.child,null,n),A.child=Xp(A,null,t,n)):ya(e,A,t,n),A.memoizedState=g.state,e=A.child):e=jE(e,A,n),e}function FX(e,A,t,i){return Wp(),A.flags|=256,ya(e,A,t,i),A.child}var Rq={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Gq(e){return{baseLanes:e,cachePool:vrA()}}function bq(e,A,t){return e=e!==null?e.childLanes&~t:0,A&&(e|=YI),e}function wIA(e,A,t){var i=A.pendingProps,n=!1,g=(A.flags&128)!==0,o;if((o=g)||(o=e!==null&&e.memoizedState===null?!1:(Vo.current&2)!==0),o&&(n=!0,A.flags&=-129),o=(A.flags&32)!==0,A.flags&=-33,e===null){if(Wn){if(n?nu(A):gu(),(e=to)?(e=uCA(e,zC),e=e!==null&&e.data!=="&"?e:null,e!==null&&(A.memoizedState={dehydrated:e,treeContext:Ad!==null?{id:$l,overflow:AB}:null,retryLane:536870912,hydrationErrors:null},t=RrA(e),t.return=A,A.child=t,ka=A,to=null)):e=null,e===null)throw ed(A);return FP(e)?A.lanes=32:A.lanes=536870912,null}var s=i.children;return i=i.fallback,n?(gu(),n=A.mode,s=oF({mode:"hidden",children:s},n),i=Rp(i,n,t,null),s.return=A,i.return=A,s.sibling=i,A.child=s,i=A.child,i.memoizedState=Gq(t),i.childLanes=bq(e,o,t),A.memoizedState=Rq,ak(null,i)):(nu(A),DP(A,s))}var a=e.memoizedState;if(a!==null&&(s=a.dehydrated,s!==null)){if(g)A.flags&256?(nu(A),A.flags&=-257,A=Uq(e,A,t)):A.memoizedState!==null?(gu(),A.child=e.child,A.flags|=128,A=null):(gu(),s=i.fallback,n=A.mode,i=oF({mode:"visible",children:i.children},n),s=Rp(s,n,t,null),s.flags|=2,i.return=A,s.return=A,i.sibling=s,A.child=i,Xp(A,e.child,null,t),i=A.child,i.memoizedState=Gq(t),i.childLanes=bq(e,o,t),A.memoizedState=Rq,A=ak(null,i));else if(nu(A),FP(s)){if(o=s.nextSibling&&s.nextSibling.dataset,o)var r=o.dgst;o=r,i=Error(It(419)),i.stack="",i.digest=o,JM({value:i,source:null,stack:null}),A=Uq(e,A,t)}else if(ps||aw(e,A,t,!1),o=(t&e.childLanes)!==0,ps||o){if(o=Yg,o!==null&&(i=trA(o,t),i!==0&&i!==a.retryLane))throw a.retryLane=i,Gf(e,i),aI(o,e,i),vj;KP(s)||IF(),A=Uq(e,A,t)}else KP(s)?(A.flags|=192,A.child=e.child,A=null):(e=a.treeContext,to=$C(s.nextSibling),ka=A,Wn=!0,Uu=null,zC=!1,e!==null&&brA(A,e),A=DP(A,i.children),A.flags|=4096);return A}return n?(gu(),s=i.fallback,n=A.mode,a=e.child,r=a.sibling,i=GE(a,{mode:"hidden",children:i.children}),i.subtreeFlags=a.subtreeFlags&65011712,r!==null?s=GE(r,s):(s=Rp(s,n,t,null),s.flags|=2),s.return=A,i.return=A,i.sibling=s,A.child=i,ak(null,i),i=A.child,s=e.child.memoizedState,s===null?s=Gq(t):(n=s.cachePool,n!==null?(a=hs._currentValue,n=n.parent!==a?{parent:a,pool:a}:n):n=vrA(),s={baseLanes:s.baseLanes|t,cachePool:n}),i.memoizedState=s,i.childLanes=bq(e,o,t),A.memoizedState=Rq,ak(e.child,i)):(nu(A),t=e.child,e=t.sibling,t=GE(t,{mode:"visible",children:i.children}),t.return=A,t.sibling=null,e!==null&&(o=A.deletions,o===null?(A.deletions=[e],A.flags|=16):o.push(e)),A.child=t,A.memoizedState=null,t)}function DP(e,A){return A=oF({mode:"visible",children:A},e.mode),A.return=e,e.child=A}function oF(e,A){return e=qI(22,e,null,A),e.lanes=0,e}function Uq(e,A,t){return Xp(A,e.child,null,t),e=DP(A,A.pendingProps.children),e.flags|=2,A.memoizedState=null,e}function _X(e,A,t){e.lanes|=A;var i=e.alternate;i!==null&&(i.lanes|=A),IP(e.return,A,t)}function vq(e,A,t,i,n,g){var o=e.memoizedState;o===null?e.memoizedState={isBackwards:A,rendering:null,renderingStartTime:0,last:i,tail:t,tailMode:n,treeForkCount:g}:(o.isBackwards=A,o.rendering=null,o.renderingStartTime=0,o.last=i,o.tail=t,o.tailMode=n,o.treeForkCount=g)}function kIA(e,A,t){var i=A.pendingProps,n=i.revealOrder,g=i.tail;i=i.children;var o=Vo.current,s=(o&2)!==0;if(s?(o=o&1|2,A.flags|=128):o&=1,Zg(Vo,o),ya(e,A,i,t),i=Wn?_M:0,!s&&e!==null&&e.flags&128)A:for(e=A.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&_X(e,t,A);else if(e.tag===19)_X(e,t,A);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===A)break A;for(;e.sibling===null;){if(e.return===null||e.return===A)break A;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(n){case"forwards":for(t=A.child,n=null;t!==null;)e=t.alternate,e!==null&&tF(e)===null&&(n=t),t=t.sibling;t=n,t===null?(n=A.child,A.child=null):(n=t.sibling,t.sibling=null),vq(A,!1,n,t,g,i);break;case"backwards":case"unstable_legacy-backwards":for(t=null,n=A.child,A.child=null;n!==null;){if(e=n.alternate,e!==null&&tF(e)===null){A.child=n;break}e=n.sibling,n.sibling=t,t=n,n=e}vq(A,!0,t,null,g,i);break;case"together":vq(A,!1,null,null,void 0,i);break;default:A.memoizedState=null}return A.child}function jE(e,A,t){if(e!==null&&(A.dependencies=e.dependencies),id|=A.lanes,!(t&A.childLanes))if(e!==null){if(aw(e,A,t,!1),(t&A.childLanes)===0)return null}else return null;if(e!==null&&A.child!==e.child)throw Error(It(153));if(A.child!==null){for(e=A.child,t=GE(e,e.pendingProps),A.child=t,t.return=A;e.sibling!==null;)e=e.sibling,t=t.sibling=GE(e,e.pendingProps),t.return=A;t.sibling=null}return A.child}function Kj(e,A){return e.lanes&A?!0:(e=e.dependencies,!!(e!==null&&$K(e)))}function GMA(e,A,t){switch(A.tag){case 3:PK(A,A.stateNode.containerInfo),iu(A,hs,e.memoizedState.cache),Wp();break;case 27:case 5:VO(A);break;case 4:PK(A,A.stateNode.containerInfo);break;case 10:iu(A,A.type,A.memoizedProps.value);break;case 31:if(A.memoizedState!==null)return A.flags|=128,QP(A),null;break;case 13:var i=A.memoizedState;if(i!==null)return i.dehydrated!==null?(nu(A),A.flags|=128,null):t&A.child.childLanes?wIA(e,A,t):(nu(A),e=jE(e,A,t),e!==null?e.sibling:null);nu(A);break;case 19:var n=(e.flags&128)!==0;if(i=(t&A.childLanes)!==0,i||(aw(e,A,t,!1),i=(t&A.childLanes)!==0),n){if(i)return kIA(e,A,t);A.flags|=128}if(n=A.memoizedState,n!==null&&(n.rendering=null,n.tail=null,n.lastEffect=null),Zg(Vo,Vo.current),i)break;return null;case 22:return A.lanes=0,SIA(e,A,t,A.pendingProps);case 24:iu(A,hs,e.memoizedState.cache)}return jE(e,A,t)}function MIA(e,A,t){if(e!==null)if(e.memoizedProps!==A.pendingProps)ps=!0;else{if(!Kj(e,t)&&!(A.flags&128))return ps=!1,GMA(e,A,t);ps=!!(e.flags&131072)}else ps=!1,Wn&&A.flags&1048576&&GrA(A,_M,A.index);switch(A.lanes=0,A.tag){case 16:A:{var i=A.pendingProps;if(e=Lh(A.elementType),A.type=e,typeof e=="function")lj(e)?(i=Af(e,i),A.tag=1,A=KX(null,A,e,i,t)):(A.tag=0,A=yP(null,A,e,i,t));else{if(e!=null){var n=e.$$typeof;if(n===$4){A.tag=11,A=RX(null,A,e,i,t);break A}else if(n===Aj){A.tag=14,A=GX(null,A,e,i,t);break A}}throw A=ZO(e)||e,Error(It(306,A,""))}}return A;case 0:return yP(e,A,A.type,A.pendingProps,t);case 1:return i=A.type,n=Af(i,A.pendingProps),KX(e,A,i,n,t);case 3:A:{if(PK(A,A.stateNode.containerInfo),e===null)throw Error(It(387));i=A.pendingProps;var g=A.memoizedState;n=g.element,lP(e,A),qk(A,i,null,t);var o=A.memoizedState;if(i=o.cache,iu(A,hs,i),i!==g.cache&&CP(A,[hs],t,!0),Tk(),i=o.element,g.isDehydrated)if(g={element:i,isDehydrated:!1,cache:o.cache},A.updateQueue.baseState=g,A.memoizedState=g,A.flags&256){A=FX(e,A,i,t);break A}else if(i!==n){n=jC(Error(It(424)),A),JM(n),A=FX(e,A,i,t);break A}else{switch(e=A.stateNode.containerInfo,e.nodeType){case 9:e=e.body;break;default:e=e.nodeName==="HTML"?e.ownerDocument.body:e}for(to=$C(e.firstChild),ka=A,Wn=!0,Uu=null,zC=!0,t=_rA(A,null,i,t),A.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling}else{if(Wp(),i===n){A=jE(e,A,t);break A}ya(e,A,i,t)}A=A.child}return A;case 26:return Pv(e,A),e===null?(t=i6(A.type,null,A.pendingProps,null))?A.memoizedState=t:Wn||(t=A.type,e=A.pendingProps,i=BF(bu.current).createElement(t),i[wa]=A,i[II]=e,ba(i,t,e),ga(i),A.stateNode=i):A.memoizedState=i6(A.type,e.memoizedProps,A.pendingProps,e.memoizedState),null;case 27:return VO(A),e===null&&Wn&&(i=A.stateNode=dCA(A.type,A.pendingProps,bu.current),ka=A,zC=!0,n=to,wd(A.type)?(_P=n,to=$C(i.firstChild)):to=n),ya(e,A,A.pendingProps.children,t),Pv(e,A),e===null&&(A.flags|=4194304),A.child;case 5:return e===null&&Wn&&((n=i=to)&&(i=sNA(i,A.type,A.pendingProps,zC),i!==null?(A.stateNode=i,ka=A,to=$C(i.firstChild),zC=!1,n=!0):n=!1),n||ed(A)),VO(A),n=A.type,g=A.pendingProps,o=e!==null?e.memoizedProps:null,i=g.children,UP(n,g)?i=null:o!==null&&UP(n,o)&&(A.flags|=32),A.memoizedState!==null&&(n=yj(e,A,yMA,null,null,t),HM._currentValue=n),Pv(e,A),ya(e,A,i,t),A.child;case 6:return e===null&&Wn&&((e=t=to)&&(t=aNA(t,A.pendingProps,zC),t!==null?(A.stateNode=t,ka=A,to=null,e=!0):e=!1),e||ed(A)),null;case 13:return wIA(e,A,t);case 4:return PK(A,A.stateNode.containerInfo),i=A.pendingProps,e===null?A.child=Xp(A,null,i,t):ya(e,A,i,t),A.child;case 11:return RX(e,A,A.type,A.pendingProps,t);case 7:return ya(e,A,A.pendingProps,t),A.child;case 8:return ya(e,A,A.pendingProps.children,t),A.child;case 12:return ya(e,A,A.pendingProps.children,t),A.child;case 10:return i=A.pendingProps,iu(A,A.type,i.value),ya(e,A,i.children,t),A.child;case 9:return n=A.type._context,i=A.pendingProps.children,Vp(A),n=Na(n),i=i(n),A.flags|=1,ya(e,A,i,t),A.child;case 14:return GX(e,A,A.type,A.pendingProps,t);case 15:return mIA(e,A,A.type,A.pendingProps,t);case 19:return kIA(e,A,t);case 31:return RMA(e,A,t);case 22:return SIA(e,A,t,A.pendingProps);case 24:return Vp(A),i=Na(hs),e===null?(n=uj(),n===null&&(n=Yg,g=Qj(),n.pooledCache=g,g.refCount++,g!==null&&(n.pooledCacheLanes|=t),n=g),A.memoizedState={parent:i,cache:n},hj(A),iu(A,hs,n)):(e.lanes&t&&(lP(e,A),qk(A,null,null,t),Tk()),n=e.memoizedState,g=A.memoizedState,n.parent!==i?(n={parent:i,cache:i},A.memoizedState=n,A.lanes===0&&(A.memoizedState=A.updateQueue.baseState=n),iu(A,hs,i)):(i=g.cache,iu(A,hs,i),i!==n.cache&&CP(A,[hs],t,!0))),ya(e,A,A.pendingProps.children,t),A.child;case 29:throw A.pendingProps}throw Error(It(156,A.tag))}function jB(e){e.flags|=4}function Kq(e,A,t,i,n){if((A=(e.mode&32)!==0)&&(A=!1),A){if(e.flags|=16777216,(n&335544128)===n)if(e.stateNode.complete)e.flags|=8192;else if(XIA())e.flags|=8192;else throw bp=AF,dj}else e.flags&=-16777217}function JX(e,A){if(A.type!=="stylesheet"||A.state.loading&4)e.flags&=-16777217;else if(e.flags|=16777216,!fCA(A))if(XIA())e.flags|=8192;else throw bp=AF,dj}function ob(e,A){A!==null&&(e.flags|=4),e.flags&16384&&(A=e.tag!==22?$aA():536870912,e.lanes|=A,lS|=A)}function E0(e,A){if(!Wn)switch(e.tailMode){case"hidden":A=e.tail;for(var t=null;A!==null;)A.alternate!==null&&(t=A),A=A.sibling;t===null?e.tail=null:t.sibling=null;break;case"collapsed":t=e.tail;for(var i=null;t!==null;)t.alternate!==null&&(i=t),t=t.sibling;i===null?A||e.tail===null?e.tail=null:e.tail.sibling=null:i.sibling=null}}function Ao(e){var A=e.alternate!==null&&e.alternate.child===e.child,t=0,i=0;if(A)for(var n=e.child;n!==null;)t|=n.lanes|n.childLanes,i|=n.subtreeFlags&65011712,i|=n.flags&65011712,n.return=e,n=n.sibling;else for(n=e.child;n!==null;)t|=n.lanes|n.childLanes,i|=n.subtreeFlags,i|=n.flags,n.return=e,n=n.sibling;return e.subtreeFlags|=i,e.childLanes=t,A}function bMA(e,A,t){var i=A.pendingProps;switch(Ej(A),A.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Ao(A),null;case 1:return Ao(A),null;case 3:return t=A.stateNode,i=null,e!==null&&(i=e.memoizedState.cache),A.memoizedState.cache!==i&&(A.flags|=2048),bE(hs),sS(),t.pendingContext&&(t.context=t.pendingContext,t.pendingContext=null),(e===null||e.child===null)&&(Uy(A)?jB(A):e===null||e.memoizedState.isDehydrated&&!(A.flags&256)||(A.flags|=1024,wq())),Ao(A),null;case 26:var n=A.type,g=A.memoizedState;return e===null?(jB(A),g!==null?(Ao(A),JX(A,g)):(Ao(A),Kq(A,n,null,i,t))):g?g!==e.memoizedState?(jB(A),Ao(A),JX(A,g)):(Ao(A),A.flags&=-16777217):(e=e.memoizedProps,e!==i&&jB(A),Ao(A),Kq(A,n,e,i,t)),null;case 27:if(jK(A),t=bu.current,n=A.type,e!==null&&A.stateNode!=null)e.memoizedProps!==i&&jB(A);else{if(!i){if(A.stateNode===null)throw Error(It(166));return Ao(A),null}e=aB.current,Uy(A)?lX(A):(e=dCA(n,i,t),A.stateNode=e,jB(A))}return Ao(A),null;case 5:if(jK(A),n=A.type,e!==null&&A.stateNode!=null)e.memoizedProps!==i&&jB(A);else{if(!i){if(A.stateNode===null)throw Error(It(166));return Ao(A),null}if(g=aB.current,Uy(A))lX(A);else{var o=BF(bu.current);switch(g){case 1:g=o.createElementNS("http://www.w3.org/2000/svg",n);break;case 2:g=o.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;default:switch(n){case"svg":g=o.createElementNS("http://www.w3.org/2000/svg",n);break;case"math":g=o.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;case"script":g=o.createElement("div"),g.innerHTML="<script><\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof i.is=="string"?o.createElement("select",{is:i.is}):o.createElement("select"),i.multiple?g.multiple=!0:i.size&&(g.size=i.size);break;default:g=typeof i.is=="string"?o.createElement(n,{is:i.is}):o.createElement(n)}}g[wa]=A,g[II]=i;A:for(o=A.child;o!==null;){if(o.tag===5||o.tag===6)g.appendChild(o.stateNode);else if(o.tag!==4&&o.tag!==27&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===A)break A;for(;o.sibling===null;){if(o.return===null||o.return===A)break A;o=o.return}o.sibling.return=o.return,o=o.sibling}A.stateNode=g;A:switch(ba(g,n,i),n){case"button":case"input":case"select":case"textarea":i=!!i.autoFocus;break A;case"img":i=!0;break A;default:i=!1}i&&jB(A)}}return Ao(A),Kq(A,A.type,e===null?null:e.memoizedProps,A.pendingProps,t),null;case 6:if(e&&A.stateNode!=null)e.memoizedProps!==i&&jB(A);else{if(typeof i!="string"&&A.stateNode===null)throw Error(It(166));if(e=bu.current,Uy(A)){if(e=A.stateNode,t=A.memoizedProps,i=null,n=ka,n!==null)switch(n.tag){case 27:case 5:i=n.memoizedProps}e[wa]=A,e=!!(e.nodeValue===t||i!==null&&i.suppressHydrationWarning===!0||BCA(e.nodeValue,t)),e||ed(A,!0)}else e=BF(e).createTextNode(i),e[wa]=A,A.stateNode=e}return Ao(A),null;case 31:if(t=A.memoizedState,e===null||e.memoizedState!==null){if(i=Uy(A),t!==null){if(e===null){if(!i)throw Error(It(318));if(e=A.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(It(557));e[wa]=A}else Wp(),!(A.flags&128)&&(A.memoizedState=null),A.flags|=4;Ao(A),e=!1}else t=wq(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=t),e=!0;if(!e)return A.flags&256?(TI(A),A):(TI(A),null);if(A.flags&128)throw Error(It(558))}return Ao(A),null;case 13:if(i=A.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(n=Uy(A),i!==null&&i.dehydrated!==null){if(e===null){if(!n)throw Error(It(318));if(n=A.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(It(317));n[wa]=A}else Wp(),!(A.flags&128)&&(A.memoizedState=null),A.flags|=4;Ao(A),n=!1}else n=wq(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),n=!0;if(!n)return A.flags&256?(TI(A),A):(TI(A),null)}return TI(A),A.flags&128?(A.lanes=t,A):(t=i!==null,e=e!==null&&e.memoizedState!==null,t&&(i=A.child,n=null,i.alternate!==null&&i.alternate.memoizedState!==null&&i.alternate.memoizedState.cachePool!==null&&(n=i.alternate.memoizedState.cachePool.pool),g=null,i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(g=i.memoizedState.cachePool.pool),g!==n&&(i.flags|=2048)),t!==e&&t&&(A.child.flags|=8192),ob(A,A.updateQueue),Ao(A),null);case 4:return sS(),e===null&&qj(A.stateNode.containerInfo),Ao(A),null;case 10:return bE(A.type),Ao(A),null;case 19:if(aa(Vo),i=A.memoizedState,i===null)return Ao(A),null;if(n=(A.flags&128)!==0,g=i.rendering,g===null)if(n)E0(i,!1);else{if(Lo!==0||e!==null&&e.flags&128)for(e=A.child;e!==null;){if(g=tF(e),g!==null){for(A.flags|=128,E0(i,!1),e=g.updateQueue,A.updateQueue=e,ob(A,e),A.subtreeFlags=0,e=t,t=A.child;t!==null;)NrA(t,e),t=t.sibling;return Zg(Vo,Vo.current&1|2),Wn&&CE(A,i.treeForkCount),A.child}e=e.sibling}i.tail!==null&&zI()>aF&&(A.flags|=128,n=!0,E0(i,!1),A.lanes=4194304)}else{if(!n)if(e=tF(g),e!==null){if(A.flags|=128,n=!0,e=e.updateQueue,A.updateQueue=e,ob(A,e),E0(i,!0),i.tail===null&&i.tailMode==="hidden"&&!g.alternate&&!Wn)return Ao(A),null}else 2*zI()-i.renderingStartTime>aF&&t!==536870912&&(A.flags|=128,n=!0,E0(i,!1),A.lanes=4194304);i.isBackwards?(g.sibling=A.child,A.child=g):(e=i.last,e!==null?e.sibling=g:A.child=g,i.last=g)}return i.tail!==null?(e=i.tail,i.rendering=e,i.tail=e.sibling,i.renderingStartTime=zI(),e.sibling=null,t=Vo.current,Zg(Vo,n?t&1|2:t&1),Wn&&CE(A,i.treeForkCount),e):(Ao(A),null);case 22:case 23:return TI(A),pj(),i=A.memoizedState!==null,e!==null?e.memoizedState!==null!==i&&(A.flags|=8192):i&&(A.flags|=8192),i?t&536870912&&!(A.flags&128)&&(Ao(A),A.subtreeFlags&6&&(A.flags|=8192)):Ao(A),t=A.updateQueue,t!==null&&ob(A,t.retryQueue),t=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(t=e.memoizedState.cachePool.pool),i=null,A.memoizedState!==null&&A.memoizedState.cachePool!==null&&(i=A.memoizedState.cachePool.pool),i!==t&&(A.flags|=2048),e!==null&&aa(Gp),null;case 24:return t=null,e!==null&&(t=e.memoizedState.cache),A.memoizedState.cache!==t&&(A.flags|=2048),bE(hs),Ao(A),null;case 25:return null;case 30:return null}throw Error(It(156,A.tag))}function UMA(e,A){switch(Ej(A),A.tag){case 1:return e=A.flags,e&65536?(A.flags=e&-65537|128,A):null;case 3:return bE(hs),sS(),e=A.flags,e&65536&&!(e&128)?(A.flags=e&-65537|128,A):null;case 26:case 27:case 5:return jK(A),null;case 31:if(A.memoizedState!==null){if(TI(A),A.alternate===null)throw Error(It(340));Wp()}return e=A.flags,e&65536?(A.flags=e&-65537|128,A):null;case 13:if(TI(A),e=A.memoizedState,e!==null&&e.dehydrated!==null){if(A.alternate===null)throw Error(It(340));Wp()}return e=A.flags,e&65536?(A.flags=e&-65537|128,A):null;case 19:return aa(Vo),null;case 4:return sS(),null;case 10:return bE(A.type),null;case 22:case 23:return TI(A),pj(),e!==null&&aa(Gp),e=A.flags,e&65536?(A.flags=e&-65537|128,A):null;case 24:return bE(hs),null;case 25:return null;default:return null}}function NIA(e,A){switch(Ej(A),A.tag){case 3:bE(hs),sS();break;case 26:case 27:case 5:jK(A);break;case 4:sS();break;case 31:A.memoizedState!==null&&TI(A);break;case 13:TI(A);break;case 19:aa(Vo);break;case 10:bE(A.type);break;case 22:case 23:TI(A),pj(),e!==null&&aa(Gp);break;case 24:bE(hs)}}function yR(e,A){try{var t=A.updateQueue,i=t!==null?t.lastEffect:null;if(i!==null){var n=i.next;t=n;do{if((t.tag&e)===e){i=void 0;var g=t.create,o=t.inst;i=g(),o.destroy=i}t=t.next}while(t!==n)}}catch(s){wg(A,A.return,s)}}function td(e,A,t){try{var i=A.updateQueue,n=i!==null?i.lastEffect:null;if(n!==null){var g=n.next;i=g;do{if((i.tag&e)===e){var o=i.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,n=A;var a=t,r=s;try{r()}catch(I){wg(n,a,I)}}}i=i.next}while(i!==g)}}catch(I){wg(A,A.return,I)}}function RIA(e){var A=e.updateQueue;if(A!==null){var t=e.stateNode;try{LrA(A,t)}catch(i){wg(e,e.return,i)}}}function GIA(e,A,t){t.props=Af(e.type,e.memoizedProps),t.state=e.memoizedState;try{t.componentWillUnmount()}catch(i){wg(e,A,i)}}function Hk(e,A){try{var t=e.ref;if(t!==null){switch(e.tag){case 26:case 27:case 5:var i=e.stateNode;break;case 30:i=e.stateNode;break;default:i=e.stateNode}typeof t=="function"?e.refCleanup=t(i):t.current=i}}catch(n){wg(e,A,n)}}function eB(e,A){var t=e.ref,i=e.refCleanup;if(t!==null)if(typeof i=="function")try{i()}catch(n){wg(e,A,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof t=="function")try{t(null)}catch(n){wg(e,A,n)}else t.current=null}function bIA(e){var A=e.type,t=e.memoizedProps,i=e.stateNode;try{A:switch(A){case"button":case"input":case"select":case"textarea":t.autoFocus&&i.focus();break A;case"img":t.src?i.src=t.src:t.srcSet&&(i.srcset=t.srcSet)}}catch(n){wg(e,e.return,n)}}function Fq(e,A,t){try{var i=e.stateNode;eNA(i,e.type,t,A),i[II]=A}catch(n){wg(e,e.return,n)}}function UIA(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&wd(e.type)||e.tag===4}function _q(e){A:for(;;){for(;e.sibling===null;){if(e.return===null||UIA(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.tag===27&&wd(e.type)||e.flags&2||e.child===null||e.tag===4)continue A;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function mP(e,A,t){var i=e.tag;if(i===5||i===6)e=e.stateNode,A?(t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t).insertBefore(e,A):(A=t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t,A.appendChild(e),t=t._reactRootContainer,t!=null||A.onclick!==null||(A.onclick=wE));else if(i!==4&&(i===27&&wd(e.type)&&(t=e.stateNode,A=null),e=e.child,e!==null))for(mP(e,A,t),e=e.sibling;e!==null;)mP(e,A,t),e=e.sibling}function sF(e,A,t){var i=e.tag;if(i===5||i===6)e=e.stateNode,A?t.insertBefore(e,A):t.appendChild(e);else if(i!==4&&(i===27&&wd(e.type)&&(t=e.stateNode),e=e.child,e!==null))for(sF(e,A,t),e=e.sibling;e!==null;)sF(e,A,t),e=e.sibling}function vIA(e){var A=e.stateNode,t=e.memoizedProps;try{for(var i=e.type,n=A.attributes;n.length;)A.removeAttributeNode(n[0]);ba(A,i,t),A[wa]=e,A[II]=t}catch(g){wg(e,e.return,g)}}var uE=!1,us=!1,Jq=!1,LX=typeof WeakSet=="function"?WeakSet:Set,ea=null;function vMA(e,A){if(e=e.containerInfo,GP=dF,e=frA(e),Ij(e)){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else A:{t=(t=e.ownerDocument)&&t.defaultView||window;var i=t.getSelection&&t.getSelection();if(i&&i.rangeCount!==0){t=i.anchorNode;var n=i.anchorOffset,g=i.focusNode;i=i.focusOffset;try{t.nodeType,g.nodeType}catch{t=null;break A}var o=0,s=-1,a=-1,r=0,I=0,c=e,l=null;e:for(;;){for(var B;c!==t||n!==0&&c.nodeType!==3||(s=o+n),c!==g||i!==0&&c.nodeType!==3||(a=o+i),c.nodeType===3&&(o+=c.nodeValue.length),(B=c.firstChild)!==null;)l=c,c=B;for(;;){if(c===e)break e;if(l===t&&++r===n&&(s=o),l===g&&++I===i&&(a=o),(B=c.nextSibling)!==null)break;c=l,l=c.parentNode}c=B}t=s===-1||a===-1?null:{start:s,end:a}}else t=null}t=t||{start:0,end:0}}else t=null;for(bP={focusedElem:e,selectionRange:t},dF=!1,ea=A;ea!==null;)if(A=ea,e=A.child,(A.subtreeFlags&1028)!==0&&e!==null)e.return=A,ea=e;else for(;ea!==null;){switch(A=ea,g=A.alternate,e=A.flags,A.tag){case 0:if(e&4&&(e=A.updateQueue,e=e!==null?e.events:null,e!==null))for(t=0;t<e.length;t++)n=e[t],n.ref.impl=n.nextImpl;break;case 11:case 15:break;case 1:if(e&1024&&g!==null){e=void 0,t=A,n=g.memoizedProps,g=g.memoizedState,i=t.stateNode;try{var Q=Af(t.type,n);e=i.getSnapshotBeforeUpdate(Q,g),i.__reactInternalSnapshotBeforeUpdate=e}catch(h){wg(t,t.return,h)}}break;case 3:if(e&1024){if(e=A.stateNode.containerInfo,t=e.nodeType,t===9)vP(e);else if(t===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":vP(e);break;default:e.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if(e&1024)throw Error(It(163))}if(e=A.sibling,e!==null){e.return=A.return,ea=e;break}ea=A.return}}function KIA(e,A,t){var i=t.flags;switch(t.tag){case 0:case 11:case 15:ZB(e,t),i&4&&yR(5,t);break;case 1:if(ZB(e,t),i&4)if(e=t.stateNode,A===null)try{e.componentDidMount()}catch(o){wg(t,t.return,o)}else{var n=Af(t.type,A.memoizedProps);A=A.memoizedState;try{e.componentDidUpdate(n,A,e.__reactInternalSnapshotBeforeUpdate)}catch(o){wg(t,t.return,o)}}i&64&&RIA(t),i&512&&Hk(t,t.return);break;case 3:if(ZB(e,t),i&64&&(e=t.updateQueue,e!==null)){if(A=null,t.child!==null)switch(t.child.tag){case 27:case 5:A=t.child.stateNode;break;case 1:A=t.child.stateNode}try{LrA(e,A)}catch(o){wg(t,t.return,o)}}break;case 27:A===null&&i&4&&vIA(t);case 26:case 5:ZB(e,t),A===null&&i&4&&bIA(t),i&512&&Hk(t,t.return);break;case 12:ZB(e,t);break;case 31:ZB(e,t),i&4&&JIA(e,t);break;case 13:ZB(e,t),i&4&&LIA(e,t),i&64&&(e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(t=YMA.bind(null,t),rNA(e,t))));break;case 22:if(i=t.memoizedState!==null||uE,!i){A=A!==null&&A.memoizedState!==null||us,n=uE;var g=us;uE=i,(us=A)&&!g?sE(e,t,(t.subtreeFlags&8772)!==0):ZB(e,t),uE=n,us=g}break;case 30:break;default:ZB(e,t)}}function FIA(e){var A=e.alternate;A!==null&&(e.alternate=null,FIA(A)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(A=e.stateNode,A!==null&&nj(A)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}var Co=null,Zr=!1;function zB(e,A,t){for(t=t.child;t!==null;)_IA(e,A,t),t=t.sibling}function _IA(e,A,t){if(ZI&&typeof ZI.onCommitFiberUnmount=="function")try{ZI.onCommitFiberUnmount(ER,t)}catch{}switch(t.tag){case 26:us||eB(t,A),zB(e,A,t),t.memoizedState?t.memoizedState.count--:t.stateNode&&(t=t.stateNode,t.parentNode.removeChild(t));break;case 27:us||eB(t,A);var i=Co,n=Zr;wd(t.type)&&(Co=t.stateNode,Zr=!1),zB(e,A,t),zk(t.stateNode),Co=i,Zr=n;break;case 5:us||eB(t,A);case 6:if(i=Co,n=Zr,Co=null,zB(e,A,t),Co=i,Zr=n,Co!==null)if(Zr)try{(Co.nodeType===9?Co.body:Co.nodeName==="HTML"?Co.ownerDocument.body:Co).removeChild(t.stateNode)}catch(g){wg(t,A,g)}else try{Co.removeChild(t.stateNode)}catch(g){wg(t,A,g)}break;case 18:Co!==null&&(Zr?(e=Co,XX(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,t.stateNode),uS(e)):XX(Co,t.stateNode));break;case 4:i=Co,n=Zr,Co=t.stateNode.containerInfo,Zr=!0,zB(e,A,t),Co=i,Zr=n;break;case 0:case 11:case 14:case 15:td(2,t,A),us||td(4,t,A),zB(e,A,t);break;case 1:us||(eB(t,A),i=t.stateNode,typeof i.componentWillUnmount=="function"&&GIA(t,A,i)),zB(e,A,t);break;case 21:zB(e,A,t);break;case 22:us=(i=us)||t.memoizedState!==null,zB(e,A,t),us=i;break;default:zB(e,A,t)}}function JIA(e,A){if(A.memoizedState===null&&(e=A.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{uS(e)}catch(t){wg(A,A.return,t)}}}function LIA(e,A){if(A.memoizedState===null&&(e=A.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{uS(e)}catch(t){wg(A,A.return,t)}}function KMA(e){switch(e.tag){case 31:case 13:case 19:var A=e.stateNode;return A===null&&(A=e.stateNode=new LX),A;case 22:return e=e.stateNode,A=e._retryCache,A===null&&(A=e._retryCache=new LX),A;default:throw Error(It(435,e.tag))}}function sb(e,A){var t=KMA(e);A.forEach(function(i){if(!t.has(i)){t.add(i);var n=HMA.bind(null,e,i);i.then(n,n)}})}function Yr(e,A){var t=A.deletions;if(t!==null)for(var i=0;i<t.length;i++){var n=t[i],g=e,o=A,s=o;A:for(;s!==null;){switch(s.tag){case 27:if(wd(s.type)){Co=s.stateNode,Zr=!1;break A}break;case 5:Co=s.stateNode,Zr=!1;break A;case 3:case 4:Co=s.stateNode.containerInfo,Zr=!0;break A}s=s.return}if(Co===null)throw Error(It(160));_IA(g,o,n),Co=null,Zr=!1,g=n.alternate,g!==null&&(g.return=null),n.return=null}if(A.subtreeFlags&13886)for(A=A.child;A!==null;)xIA(A,e),A=A.sibling}var Kc=null;function xIA(e,A){var t=e.alternate,i=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Yr(A,e),Hr(e),i&4&&(td(3,e,e.return),yR(3,e),td(5,e,e.return));break;case 1:Yr(A,e),Hr(e),i&512&&(us||t===null||eB(t,t.return)),i&64&&uE&&(e=e.updateQueue,e!==null&&(i=e.callbacks,i!==null&&(t=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=t===null?i:t.concat(i))));break;case 26:var n=Kc;if(Yr(A,e),Hr(e),i&512&&(us||t===null||eB(t,t.return)),i&4){var g=t!==null?t.memoizedState:null;if(i=e.memoizedState,t===null)if(i===null)if(e.stateNode===null){A:{i=e.type,t=e.memoizedProps,n=n.ownerDocument||n;e:switch(i){case"title":g=n.getElementsByTagName("title")[0],(!g||g[dR]||g[wa]||g.namespaceURI==="http://www.w3.org/2000/svg"||g.hasAttribute("itemprop"))&&(g=n.createElement(i),n.head.insertBefore(g,n.querySelector("head > title"))),ba(g,i,t),g[wa]=e,ga(g),i=g;break A;case"link":var o=g6("link","href",n).get(i+(t.href||""));if(o){for(var s=0;s<o.length;s++)if(g=o[s],g.getAttribute("href")===(t.href==null||t.href===""?null:t.href)&&g.getAttribute("rel")===(t.rel==null?null:t.rel)&&g.getAttribute("title")===(t.title==null?null:t.title)&&g.getAttribute("crossorigin")===(t.crossOrigin==null?null:t.crossOrigin)){o.splice(s,1);break e}}g=n.createElement(i),ba(g,i,t),n.head.appendChild(g);break;case"meta":if(o=g6("meta","content",n).get(i+(t.content||""))){for(s=0;s<o.length;s++)if(g=o[s],g.getAttribute("content")===(t.content==null?null:""+t.content)&&g.getAttribute("name")===(t.name==null?null:t.name)&&g.getAttribute("property")===(t.property==null?null:t.property)&&g.getAttribute("http-equiv")===(t.httpEquiv==null?null:t.httpEquiv)&&g.getAttribute("charset")===(t.charSet==null?null:t.charSet)){o.splice(s,1);break e}}g=n.createElement(i),ba(g,i,t),n.head.appendChild(g);break;default:throw Error(It(468,i))}g[wa]=e,ga(g),i=g}e.stateNode=i}else o6(n,e.type,e.stateNode);else e.stateNode=n6(n,i,e.memoizedProps);else g!==i?(g===null?t.stateNode!==null&&(t=t.stateNode,t.parentNode.removeChild(t)):g.count--,i===null?o6(n,e.type,e.stateNode):n6(n,i,e.memoizedProps)):i===null&&e.stateNode!==null&&Fq(e,e.memoizedProps,t.memoizedProps)}break;case 27:Yr(A,e),Hr(e),i&512&&(us||t===null||eB(t,t.return)),t!==null&&i&4&&Fq(e,e.memoizedProps,t.memoizedProps);break;case 5:if(Yr(A,e),Hr(e),i&512&&(us||t===null||eB(t,t.return)),e.flags&32){n=e.stateNode;try{rS(n,"")}catch(Q){wg(e,e.return,Q)}}i&4&&e.stateNode!=null&&(n=e.memoizedProps,Fq(e,n,t!==null?t.memoizedProps:n)),i&1024&&(Jq=!0);break;case 6:if(Yr(A,e),Hr(e),i&4){if(e.stateNode===null)throw Error(It(162));i=e.memoizedProps,t=e.stateNode;try{t.nodeValue=i}catch(Q){wg(e,e.return,Q)}}break;case 3:if(Zv=null,n=Kc,Kc=EF(A.containerInfo),Yr(A,e),Kc=n,Hr(e),i&4&&t!==null&&t.memoizedState.isDehydrated)try{uS(A.containerInfo)}catch(Q){wg(e,e.return,Q)}Jq&&(Jq=!1,TIA(e));break;case 4:i=Kc,Kc=EF(e.stateNode.containerInfo),Yr(A,e),Hr(e),Kc=i;break;case 12:Yr(A,e),Hr(e);break;case 31:Yr(A,e),Hr(e),i&4&&(i=e.updateQueue,i!==null&&(e.updateQueue=null,sb(e,i)));break;case 13:Yr(A,e),Hr(e),e.child.flags&8192&&e.memoizedState!==null!=(t!==null&&t.memoizedState!==null)&&(oL=zI()),i&4&&(i=e.updateQueue,i!==null&&(e.updateQueue=null,sb(e,i)));break;case 22:n=e.memoizedState!==null;var a=t!==null&&t.memoizedState!==null,r=uE,I=us;if(uE=r||n,us=I||a,Yr(A,e),us=I,uE=r,Hr(e),i&8192)A:for(A=e.stateNode,A._visibility=n?A._visibility&-2:A._visibility|1,n&&(t===null||a||uE||us||xh(e)),t=null,A=e;;){if(A.tag===5||A.tag===26){if(t===null){a=t=A;try{if(g=a.stateNode,n)o=g.style,typeof o.setProperty=="function"?o.setProperty("display","none","important"):o.display="none";else{s=a.stateNode;var c=a.memoizedProps.style,l=c!=null&&c.hasOwnProperty("display")?c.display:null;s.style.display=l==null||typeof l=="boolean"?"":(""+l).trim()}}catch(Q){wg(a,a.return,Q)}}}else if(A.tag===6){if(t===null){a=A;try{a.stateNode.nodeValue=n?"":a.memoizedProps}catch(Q){wg(a,a.return,Q)}}}else if(A.tag===18){if(t===null){a=A;try{var B=a.stateNode;n?$X(B,!0):$X(a.stateNode,!1)}catch(Q){wg(a,a.return,Q)}}}else if((A.tag!==22&&A.tag!==23||A.memoizedState===null||A===e)&&A.child!==null){A.child.return=A,A=A.child;continue}if(A===e)break A;for(;A.sibling===null;){if(A.return===null||A.return===e)break A;t===A&&(t=null),A=A.return}t===A&&(t=null),A.sibling.return=A.return,A=A.sibling}i&4&&(i=e.updateQueue,i!==null&&(t=i.retryQueue,t!==null&&(i.retryQueue=null,sb(e,t))));break;case 19:Yr(A,e),Hr(e),i&4&&(i=e.updateQueue,i!==null&&(e.updateQueue=null,sb(e,i)));break;case 30:break;case 21:break;default:Yr(A,e),Hr(e)}}function Hr(e){var A=e.flags;if(A&2){try{for(var t,i=e.return;i!==null;){if(UIA(i)){t=i;break}i=i.return}if(t==null)throw Error(It(160));switch(t.tag){case 27:var n=t.stateNode,g=_q(e);sF(e,g,n);break;case 5:var o=t.stateNode;t.flags&32&&(rS(o,""),t.flags&=-33);var s=_q(e);sF(e,s,o);break;case 3:case 4:var a=t.stateNode.containerInfo,r=_q(e);mP(e,r,a);break;default:throw Error(It(161))}}catch(I){wg(e,e.return,I)}e.flags&=-3}A&4096&&(e.flags&=-4097)}function TIA(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var A=e;TIA(A),A.tag===5&&A.flags&1024&&A.stateNode.reset(),e=e.sibling}}function ZB(e,A){if(A.subtreeFlags&8772)for(A=A.child;A!==null;)KIA(e,A.alternate,A),A=A.sibling}function xh(e){for(e=e.child;e!==null;){var A=e;switch(A.tag){case 0:case 11:case 14:case 15:td(4,A,A.return),xh(A);break;case 1:eB(A,A.return);var t=A.stateNode;typeof t.componentWillUnmount=="function"&&GIA(A,A.return,t),xh(A);break;case 27:zk(A.stateNode);case 26:case 5:eB(A,A.return),xh(A);break;case 22:A.memoizedState===null&&xh(A);break;case 30:xh(A);break;default:xh(A)}e=e.sibling}}function sE(e,A,t){for(t=t&&(A.subtreeFlags&8772)!==0,A=A.child;A!==null;){var i=A.alternate,n=e,g=A,o=g.flags;switch(g.tag){case 0:case 11:case 15:sE(n,g,t),yR(4,g);break;case 1:if(sE(n,g,t),i=g,n=i.stateNode,typeof n.componentDidMount=="function")try{n.componentDidMount()}catch(r){wg(i,i.return,r)}if(i=g,n=i.updateQueue,n!==null){var s=i.stateNode;try{var a=n.shared.hiddenCallbacks;if(a!==null)for(n.shared.hiddenCallbacks=null,n=0;n<a.length;n++)JrA(a[n],s)}catch(r){wg(i,i.return,r)}}t&&o&64&&RIA(g),Hk(g,g.return);break;case 27:vIA(g);case 26:case 5:sE(n,g,t),t&&i===null&&o&4&&bIA(g),Hk(g,g.return);break;case 12:sE(n,g,t);break;case 31:sE(n,g,t),t&&o&4&&JIA(n,g);break;case 13:sE(n,g,t),t&&o&4&&LIA(n,g);break;case 22:g.memoizedState===null&&sE(n,g,t),Hk(g,g.return);break;case 30:break;default:sE(n,g,t)}A=A.sibling}}function Fj(e,A){var t=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(t=e.memoizedState.cachePool.pool),e=null,A.memoizedState!==null&&A.memoizedState.cachePool!==null&&(e=A.memoizedState.cachePool.pool),e!==t&&(e!=null&&e.refCount++,t!=null&&pR(t))}function _j(e,A){e=null,A.alternate!==null&&(e=A.alternate.memoizedState.cache),A=A.memoizedState.cache,A!==e&&(A.refCount++,e!=null&&pR(e))}function Dc(e,A,t,i){if(A.subtreeFlags&10256)for(A=A.child;A!==null;)qIA(e,A,t,i),A=A.sibling}function qIA(e,A,t,i){var n=A.flags;switch(A.tag){case 0:case 11:case 15:Dc(e,A,t,i),n&2048&&yR(9,A);break;case 1:Dc(e,A,t,i);break;case 3:Dc(e,A,t,i),n&2048&&(e=null,A.alternate!==null&&(e=A.alternate.memoizedState.cache),A=A.memoizedState.cache,A!==e&&(A.refCount++,e!=null&&pR(e)));break;case 12:if(n&2048){Dc(e,A,t,i),e=A.stateNode;try{var g=A.memoizedProps,o=g.id,s=g.onPostCommit;typeof s=="function"&&s(o,A.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(a){wg(A,A.return,a)}}else Dc(e,A,t,i);break;case 31:Dc(e,A,t,i);break;case 13:Dc(e,A,t,i);break;case 23:break;case 22:g=A.stateNode,o=A.alternate,A.memoizedState!==null?g._visibility&2?Dc(e,A,t,i):Ok(e,A):g._visibility&2?Dc(e,A,t,i):(g._visibility|=2,ND(e,A,t,i,(A.subtreeFlags&10256)!==0||!1)),n&2048&&Fj(o,A);break;case 24:Dc(e,A,t,i),n&2048&&_j(A.alternate,A);break;default:Dc(e,A,t,i)}}function ND(e,A,t,i,n){for(n=n&&((A.subtreeFlags&10256)!==0||!1),A=A.child;A!==null;){var g=e,o=A,s=t,a=i,r=o.flags;switch(o.tag){case 0:case 11:case 15:ND(g,o,s,a,n),yR(8,o);break;case 23:break;case 22:var I=o.stateNode;o.memoizedState!==null?I._visibility&2?ND(g,o,s,a,n):Ok(g,o):(I._visibility|=2,ND(g,o,s,a,n)),n&&r&2048&&Fj(o.alternate,o);break;case 24:ND(g,o,s,a,n),n&&r&2048&&_j(o.alternate,o);break;default:ND(g,o,s,a,n)}A=A.sibling}}function Ok(e,A){if(A.subtreeFlags&10256)for(A=A.child;A!==null;){var t=e,i=A,n=i.flags;switch(i.tag){case 22:Ok(t,i),n&2048&&Fj(i.alternate,i);break;case 24:Ok(t,i),n&2048&&_j(i.alternate,i);break;default:Ok(t,i)}A=A.sibling}}var rk=8192;function vy(e,A,t){if(e.subtreeFlags&rk)for(e=e.child;e!==null;)YIA(e,A,t),e=e.sibling}function YIA(e,A,t){switch(e.tag){case 26:vy(e,A,t),e.flags&rk&&e.memoizedState!==null&&fNA(t,Kc,e.memoizedState,e.memoizedProps);break;case 5:vy(e,A,t);break;case 3:case 4:var i=Kc;Kc=EF(e.stateNode.containerInfo),vy(e,A,t),Kc=i;break;case 22:e.memoizedState===null&&(i=e.alternate,i!==null&&i.memoizedState!==null?(i=rk,rk=16777216,vy(e,A,t),rk=i):vy(e,A,t));break;default:vy(e,A,t)}}function HIA(e){var A=e.alternate;if(A!==null&&(e=A.child,e!==null)){A.child=null;do A=e.sibling,e.sibling=null,e=A;while(e!==null)}}function Q0(e){var A=e.deletions;if(e.flags&16){if(A!==null)for(var t=0;t<A.length;t++){var i=A[t];ea=i,PIA(i,e)}HIA(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)OIA(e),e=e.sibling}function OIA(e){switch(e.tag){case 0:case 11:case 15:Q0(e),e.flags&2048&&td(9,e,e.return);break;case 3:Q0(e);break;case 12:Q0(e);break;case 22:var A=e.stateNode;e.memoizedState!==null&&A._visibility&2&&(e.return===null||e.return.tag!==13)?(A._visibility&=-3,jv(e)):Q0(e);break;default:Q0(e)}}function jv(e){var A=e.deletions;if(e.flags&16){if(A!==null)for(var t=0;t<A.length;t++){var i=A[t];ea=i,PIA(i,e)}HIA(e)}for(e=e.child;e!==null;){switch(A=e,A.tag){case 0:case 11:case 15:td(8,A,A.return),jv(A);break;case 22:t=A.stateNode,t._visibility&2&&(t._visibility&=-3,jv(A));break;default:jv(A)}e=e.sibling}}function PIA(e,A){for(;ea!==null;){var t=ea;switch(t.tag){case 0:case 11:case 15:td(8,t,A);break;case 23:case 22:if(t.memoizedState!==null&&t.memoizedState.cachePool!==null){var i=t.memoizedState.cachePool.pool;i!=null&&i.refCount++}break;case 24:pR(t.memoizedState.cache)}if(i=t.child,i!==null)i.return=t,ea=i;else A:for(t=e;ea!==null;){i=ea;var n=i.sibling,g=i.return;if(FIA(i),i===t){ea=null;break A}if(n!==null){n.return=g,ea=n;break A}ea=g}}}var FMA={getCacheForType:function(e){var A=Na(hs),t=A.data.get(e);return t===void 0&&(t=e(),A.data.set(e,t)),t},cacheSignal:function(){return Na(hs).controller.signal}},_MA=typeof WeakMap=="function"?WeakMap:Map,lg=0,Yg=null,vn=null,Ln=0,Sg=0,LI=null,hu=!1,Iw=!1,Jj=!1,zE=0,Lo=0,id=0,Up=0,Lj=0,YI=0,lS=0,Pk=null,Vr=null,SP=!1,oL=0,jIA=0,aF=1/0,rF=null,Fu=null,Ls=0,_u=null,BS=null,UE=0,wP=0,kP=null,zIA=null,jk=0,MP=null;function VI(){return lg&2&&Ln!==0?Ln&-Ln:Li.T!==null?Tj():irA()}function ZIA(){if(YI===0)if(!(Ln&536870912)||Wn){var e=$G;$G<<=1,!($G&3932160)&&($G=262144),YI=e}else YI=536870912;return e=tC.current,e!==null&&(e.flags|=32),YI}function aI(e,A,t){(e===Yg&&(Sg===2||Sg===9)||e.cancelPendingCommit!==null)&&(ES(e,0),pu(e,Ln,YI,!1)),uR(e,t),(!(lg&2)||e!==Yg)&&(e===Yg&&(!(lg&2)&&(Up|=t),Lo===4&&pu(e,Ln,YI,!1)),wB(e))}function WIA(e,A,t){if(lg&6)throw Error(It(327));var i=!t&&(A&127)===0&&(A&e.expiredLanes)===0||QR(e,A),n=i?xMA(e,A):Lq(e,A,!0),g=i;do{if(n===0){Iw&&!i&&pu(e,A,0,!1);break}else{if(t=e.current.alternate,g&&!JMA(t)){n=Lq(e,A,!1),g=!1;continue}if(n===2){if(g=A,e.errorRecoveryDisabledLanes&g)var o=0;else o=e.pendingLanes&-536870913,o=o!==0?o:o&536870912?536870912:0;if(o!==0){A=o;A:{var s=e;n=Pk;var a=s.current.memoizedState.isDehydrated;if(a&&(ES(s,o).flags|=256),o=Lq(s,o,!1),o!==2){if(Jj&&!a){s.errorRecoveryDisabledLanes|=g,Up|=g,n=4;break A}g=Vr,Vr=n,g!==null&&(Vr===null?Vr=g:Vr.push.apply(Vr,g))}n=o}if(g=!1,n!==2)continue}}if(n===1){ES(e,0),pu(e,A,0,!0);break}A:{switch(i=e,g=n,g){case 0:case 1:throw Error(It(345));case 4:if((A&4194048)!==A)break;case 6:pu(i,A,YI,!hu);break A;case 2:Vr=null;break;case 3:case 5:break;default:throw Error(It(329))}if((A&62914560)===A&&(n=oL+300-zI(),10<n)){if(pu(i,A,YI,!hu),ZJ(i,0,!0)!==0)break A;UE=A,i.timeoutHandle=QCA(xX.bind(null,i,t,Vr,rF,SP,A,YI,Up,lS,hu,g,"Throttled",-0,0),n);break A}xX(i,t,Vr,rF,SP,A,YI,Up,lS,hu,g,null,-0,0)}}break}while(!0);wB(e)}function xX(e,A,t,i,n,g,o,s,a,r,I,c,l,B){if(e.timeoutHandle=-1,c=A.subtreeFlags,c&8192||(c&16785408)===16785408){c={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:wE},YIA(A,g,c);var Q=(g&62914560)===g?oL-zI():(g&4194048)===g?jIA-zI():0;if(Q=yNA(c,Q),Q!==null){UE=g,e.cancelPendingCommit=Q(qX.bind(null,e,A,g,t,i,n,o,s,a,I,c,null,l,B)),pu(e,g,o,!r);return}}qX(e,A,g,t,i,n,o,s,a)}function JMA(e){for(var A=e;;){var t=A.tag;if((t===0||t===11||t===15)&&A.flags&16384&&(t=A.updateQueue,t!==null&&(t=t.stores,t!==null)))for(var i=0;i<t.length;i++){var n=t[i],g=n.getSnapshot;n=n.value;try{if(!eC(g(),n))return!1}catch{return!1}}if(t=A.child,A.subtreeFlags&16384&&t!==null)t.return=A,A=t;else{if(A===e)break;for(;A.sibling===null;){if(A.return===null||A.return===e)return!0;A=A.return}A.sibling.return=A.return,A=A.sibling}}return!0}function pu(e,A,t,i){A&=~Lj,A&=~Up,e.suspendedLanes|=A,e.pingedLanes&=~A,i&&(e.warmLanes|=A),i=e.expirationTimes;for(var n=A;0<n;){var g=31-WI(n),o=1<<g;i[g]=-1,n&=~o}t!==0&&ArA(e,t,A)}function sL(){return lg&6?!0:(DR(0),!1)}function xj(){if(vn!==null){if(Sg===0)var e=vn.return;else e=vn,kE=bf=null,Sj(e),dm=null,LM=0,e=vn;for(;e!==null;)NIA(e.alternate,e),e=e.return;vn=null}}function ES(e,A){var t=e.timeoutHandle;t!==-1&&(e.timeoutHandle=-1,nNA(t)),t=e.cancelPendingCommit,t!==null&&(e.cancelPendingCommit=null,t()),UE=0,xj(),Yg=e,vn=t=GE(e.current,null),Ln=A,Sg=0,LI=null,hu=!1,Iw=QR(e,A),Jj=!1,lS=YI=Lj=Up=id=Lo=0,Vr=Pk=null,SP=!1,A&8&&(A|=A&32);var i=e.entangledLanes;if(i!==0)for(e=e.entanglements,i&=A;0<i;){var n=31-WI(i),g=1<<n;A|=e[n],i&=~g}return zE=A,$J(),t}function VIA(e,A){In=null,Li.H=TM,A===rw||A===eL?(A=dX(),Sg=3):A===dj?(A=dX(),Sg=4):Sg=A===vj?8:A!==null&&typeof A=="object"&&typeof A.then=="function"?6:1,LI=A,vn===null&&(Lo=1,gF(e,jC(A,e.current)))}function XIA(){var e=tC.current;return e===null?!0:(Ln&4194048)===Ln?XC===null:(Ln&62914560)===Ln||Ln&536870912?e===XC:!1}function $IA(){var e=Li.H;return Li.H=TM,e===null?TM:e}function ACA(){var e=Li.A;return Li.A=FMA,e}function IF(){Lo=4,hu||(Ln&4194048)!==Ln&&tC.current!==null||(Iw=!0),!(id&134217727)&&!(Up&134217727)||Yg===null||pu(Yg,Ln,YI,!1)}function Lq(e,A,t){var i=lg;lg|=2;var n=$IA(),g=ACA();(Yg!==e||Ln!==A)&&(rF=null,ES(e,A)),A=!1;var o=Lo;A:do try{if(Sg!==0&&vn!==null){var s=vn,a=LI;switch(Sg){case 8:xj(),o=6;break A;case 3:case 2:case 9:case 6:tC.current===null&&(A=!0);var r=Sg;if(Sg=0,LI=null,zD(e,s,a,r),t&&Iw){o=0;break A}break;default:r=Sg,Sg=0,LI=null,zD(e,s,a,r)}}LMA(),o=Lo;break}catch(I){VIA(e,I)}while(!0);return A&&e.shellSuspendCounter++,kE=bf=null,lg=i,Li.H=n,Li.A=g,vn===null&&(Yg=null,Ln=0,$J()),o}function LMA(){for(;vn!==null;)eCA(vn)}function xMA(e,A){var t=lg;lg|=2;var i=$IA(),n=ACA();Yg!==e||Ln!==A?(rF=null,aF=zI()+500,ES(e,A)):Iw=QR(e,A);A:do try{if(Sg!==0&&vn!==null){A=vn;var g=LI;e:switch(Sg){case 1:Sg=0,LI=null,zD(e,A,g,1);break;case 2:case 9:if(uX(g)){Sg=0,LI=null,TX(A);break}A=function(){Sg!==2&&Sg!==9||Yg!==e||(Sg=7),wB(e)},g.then(A,A);break A;case 3:Sg=7;break A;case 4:Sg=5;break A;case 7:uX(g)?(Sg=0,LI=null,TX(A)):(Sg=0,LI=null,zD(e,A,g,7));break;case 5:var o=null;switch(vn.tag){case 26:o=vn.memoizedState;case 5:case 27:var s=vn;if(o?fCA(o):s.stateNode.complete){Sg=0,LI=null;var a=s.sibling;if(a!==null)vn=a;else{var r=s.return;r!==null?(vn=r,aL(r)):vn=null}break e}}Sg=0,LI=null,zD(e,A,g,5);break;case 6:Sg=0,LI=null,zD(e,A,g,6);break;case 8:xj(),Lo=6;break A;default:throw Error(It(462))}}TMA();break}catch(I){VIA(e,I)}while(!0);return kE=bf=null,Li.H=i,Li.A=n,lg=t,vn!==null?0:(Yg=null,Ln=0,$J(),Lo)}function TMA(){for(;vn!==null&&!IkA();)eCA(vn)}function eCA(e){var A=MIA(e.alternate,e,zE);e.memoizedProps=e.pendingProps,A===null?aL(e):vn=A}function TX(e){var A=e,t=A.alternate;switch(A.tag){case 15:case 0:A=vX(t,A,A.pendingProps,A.type,void 0,Ln);break;case 11:A=vX(t,A,A.pendingProps,A.type.render,A.ref,Ln);break;case 5:Sj(A);default:NIA(t,A),A=vn=NrA(A,zE),A=MIA(t,A,zE)}e.memoizedProps=e.pendingProps,A===null?aL(e):vn=A}function zD(e,A,t,i){kE=bf=null,Sj(A),dm=null,LM=0;var n=A.return;try{if(NMA(e,n,A,t,Ln)){Lo=1,gF(e,jC(t,e.current)),vn=null;return}}catch(g){if(n!==null)throw vn=n,g;Lo=1,gF(e,jC(t,e.current)),vn=null;return}A.flags&32768?(Wn||i===1?e=!0:Iw||Ln&536870912?e=!1:(hu=e=!0,(i===2||i===9||i===3||i===6)&&(i=tC.current,i!==null&&i.tag===13&&(i.flags|=16384))),tCA(A,e)):aL(A)}function aL(e){var A=e;do{if(A.flags&32768){tCA(A,hu);return}e=A.return;var t=bMA(A.alternate,A,zE);if(t!==null){vn=t;return}if(A=A.sibling,A!==null){vn=A;return}vn=A=e}while(A!==null);Lo===0&&(Lo=5)}function tCA(e,A){do{var t=UMA(e.alternate,e);if(t!==null){t.flags&=32767,vn=t;return}if(t=e.return,t!==null&&(t.flags|=32768,t.subtreeFlags=0,t.deletions=null),!A&&(e=e.sibling,e!==null)){vn=e;return}vn=e=t}while(e!==null);Lo=6,vn=null}function qX(e,A,t,i,n,g,o,s,a){e.cancelPendingCommit=null;do rL();while(Ls!==0);if(lg&6)throw Error(It(327));if(A!==null){if(A===e.current)throw Error(It(177));if(g=A.lanes|A.childLanes,g|=Cj,pkA(e,t,g,o,s,a),e===Yg&&(vn=Yg=null,Ln=0),BS=A,_u=e,UE=t,wP=g,kP=n,zIA=i,A.subtreeFlags&10256||A.flags&10256?(e.callbackNode=null,e.callbackPriority=0,OMA(zK,function(){return sCA(),null})):(e.callbackNode=null,e.callbackPriority=0),i=(A.flags&13878)!==0,A.subtreeFlags&13878||i){i=Li.T,Li.T=null,n=Bg.p,Bg.p=2,o=lg,lg|=4;try{vMA(e,A,t)}finally{lg=o,Bg.p=n,Li.T=i}}Ls=1,iCA(),nCA(),gCA()}}function iCA(){if(Ls===1){Ls=0;var e=_u,A=BS,t=(A.flags&13878)!==0;if(A.subtreeFlags&13878||t){t=Li.T,Li.T=null;var i=Bg.p;Bg.p=2;var n=lg;lg|=4;try{xIA(A,e);var g=bP,o=frA(e.containerInfo),s=g.focusedElem,a=g.selectionRange;if(o!==s&&s&&s.ownerDocument&&prA(s.ownerDocument.documentElement,s)){if(a!==null&&Ij(s)){var r=a.start,I=a.end;if(I===void 0&&(I=r),"selectionStart"in s)s.selectionStart=r,s.selectionEnd=Math.min(I,s.value.length);else{var c=s.ownerDocument||document,l=c&&c.defaultView||window;if(l.getSelection){var B=l.getSelection(),Q=s.textContent.length,h=Math.min(a.start,Q),d=a.end===void 0?h:Math.min(a.end,Q);!B.extend&&h>d&&(o=d,d=h,h=o);var p=IX(s,h),y=IX(s,d);if(p&&y&&(B.rangeCount!==1||B.anchorNode!==p.node||B.anchorOffset!==p.offset||B.focusNode!==y.node||B.focusOffset!==y.offset)){var m=c.createRange();m.setStart(p.node,p.offset),B.removeAllRanges(),h>d?(B.addRange(m),B.extend(y.node,y.offset)):(m.setEnd(y.node,y.offset),B.addRange(m))}}}}for(c=[],B=s;B=B.parentNode;)B.nodeType===1&&c.push({element:B,left:B.scrollLeft,top:B.scrollTop});for(typeof s.focus=="function"&&s.focus(),s=0;s<c.length;s++){var D=c[s];D.element.scrollLeft=D.left,D.element.scrollTop=D.top}}dF=!!GP,bP=GP=null}finally{lg=n,Bg.p=i,Li.T=t}}e.current=A,Ls=2}}function nCA(){if(Ls===2){Ls=0;var e=_u,A=BS,t=(A.flags&8772)!==0;if(A.subtreeFlags&8772||t){t=Li.T,Li.T=null;var i=Bg.p;Bg.p=2;var n=lg;lg|=4;try{KIA(e,A.alternate,A)}finally{lg=n,Bg.p=i,Li.T=t}}Ls=3}}function gCA(){if(Ls===4||Ls===3){Ls=0,CkA();var e=_u,A=BS,t=UE,i=zIA;A.subtreeFlags&10256||A.flags&10256?Ls=5:(Ls=0,BS=_u=null,oCA(e,e.pendingLanes));var n=e.pendingLanes;if(n===0&&(Fu=null),ij(t),A=A.stateNode,ZI&&typeof ZI.onCommitFiberRoot=="function")try{ZI.onCommitFiberRoot(ER,A,void 0,(A.current.flags&128)===128)}catch{}if(i!==null){A=Li.T,n=Bg.p,Bg.p=2,Li.T=null;try{for(var g=e.onRecoverableError,o=0;o<i.length;o++){var s=i[o];g(s.value,{componentStack:s.stack})}}finally{Li.T=A,Bg.p=n}}UE&3&&rL(),wB(e),n=e.pendingLanes,t&261930&&n&42?e===MP?jk++:(jk=0,MP=e):jk=0,DR(0)}}function oCA(e,A){(e.pooledCacheLanes&=A)===0&&(A=e.pooledCache,A!=null&&(e.pooledCache=null,pR(A)))}function rL(){return iCA(),nCA(),gCA(),sCA()}function sCA(){if(Ls!==5)return!1;var e=_u,A=wP;wP=0;var t=ij(UE),i=Li.T,n=Bg.p;try{Bg.p=32>t?32:t,Li.T=null,t=kP,kP=null;var g=_u,o=UE;if(Ls=0,BS=_u=null,UE=0,lg&6)throw Error(It(331));var s=lg;if(lg|=4,OIA(g.current),qIA(g,g.current,o,t),lg=s,DR(0,!1),ZI&&typeof ZI.onPostCommitFiberRoot=="function")try{ZI.onPostCommitFiberRoot(ER,g)}catch{}return!0}finally{Bg.p=n,Li.T=i,oCA(e,A)}}function YX(e,A,t){A=jC(t,A),A=fP(e.stateNode,A,2),e=Ku(e,A,2),e!==null&&(uR(e,2),wB(e))}function wg(e,A,t){if(e.tag===3)YX(e,e,t);else for(;A!==null;){if(A.tag===3){YX(A,e,t);break}else if(A.tag===1){var i=A.stateNode;if(typeof A.type.getDerivedStateFromError=="function"||typeof i.componentDidCatch=="function"&&(Fu===null||!Fu.has(i))){e=jC(t,e),t=yIA(2),i=Ku(A,t,2),i!==null&&(DIA(t,i,A,e),uR(i,2),wB(i));break}}A=A.return}}function xq(e,A,t){var i=e.pingCache;if(i===null){i=e.pingCache=new _MA;var n=new Set;i.set(A,n)}else n=i.get(A),n===void 0&&(n=new Set,i.set(A,n));n.has(t)||(Jj=!0,n.add(t),e=qMA.bind(null,e,A,t),A.then(e,e))}function qMA(e,A,t){var i=e.pingCache;i!==null&&i.delete(A),e.pingedLanes|=e.suspendedLanes&t,e.warmLanes&=~t,Yg===e&&(Ln&t)===t&&(Lo===4||Lo===3&&(Ln&62914560)===Ln&&300>zI()-oL?!(lg&2)&&ES(e,0):Lj|=t,lS===Ln&&(lS=0)),wB(e)}function aCA(e,A){A===0&&(A=$aA()),e=Gf(e,A),e!==null&&(uR(e,A),wB(e))}function YMA(e){var A=e.memoizedState,t=0;A!==null&&(t=A.retryLane),aCA(e,t)}function HMA(e,A){var t=0;switch(e.tag){case 31:case 13:var i=e.stateNode,n=e.memoizedState;n!==null&&(t=n.retryLane);break;case 19:i=e.stateNode;break;case 22:i=e.stateNode._retryCache;break;default:throw Error(It(314))}i!==null&&i.delete(A),aCA(e,t)}function OMA(e,A){return ej(e,A)}var CF=null,RD=null,NP=!1,cF=!1,Tq=!1,fu=0;function wB(e){e!==RD&&e.next===null&&(RD===null?CF=RD=e:RD=RD.next=e),cF=!0,NP||(NP=!0,jMA())}function DR(e,A){if(!Tq&&cF){Tq=!0;do for(var t=!1,i=CF;i!==null;){if(e!==0){var n=i.pendingLanes;if(n===0)var g=0;else{var o=i.suspendedLanes,s=i.pingedLanes;g=(1<<31-WI(42|e)+1)-1,g&=n&~(o&~s),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(t=!0,HX(i,g))}else g=Ln,g=ZJ(i,i===Yg?g:0,i.cancelPendingCommit!==null||i.timeoutHandle!==-1),!(g&3)||QR(i,g)||(t=!0,HX(i,g));i=i.next}while(t);Tq=!1}}function PMA(){rCA()}function rCA(){cF=NP=!1;var e=0;fu!==0&&iNA()&&(e=fu);for(var A=zI(),t=null,i=CF;i!==null;){var n=i.next,g=ICA(i,A);g===0?(i.next=null,t===null?CF=n:t.next=n,n===null&&(RD=t)):(t=i,(e!==0||g&3)&&(cF=!0)),i=n}Ls!==0&&Ls!==5||DR(e),fu!==0&&(fu=0)}function ICA(e,A){for(var t=e.suspendedLanes,i=e.pingedLanes,n=e.expirationTimes,g=e.pendingLanes&-62914561;0<g;){var o=31-WI(g),s=1<<o,a=n[o];a===-1?(!(s&t)||s&i)&&(n[o]=hkA(s,A)):a<=A&&(e.expiredLanes|=s),g&=~s}if(A=Yg,t=Ln,t=ZJ(e,e===A?t:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),i=e.callbackNode,t===0||e===A&&(Sg===2||Sg===9)||e.cancelPendingCommit!==null)return i!==null&&i!==null&&Eq(i),e.callbackNode=null,e.callbackPriority=0;if(!(t&3)||QR(e,t)){if(A=t&-t,A===e.callbackPriority)return A;switch(i!==null&&Eq(i),ij(t)){case 2:case 8:t=VaA;break;case 32:t=zK;break;case 268435456:t=XaA;break;default:t=zK}return i=CCA.bind(null,e),t=ej(t,i),e.callbackPriority=A,e.callbackNode=t,A}return i!==null&&i!==null&&Eq(i),e.callbackPriority=2,e.callbackNode=null,2}function CCA(e,A){if(Ls!==0&&Ls!==5)return e.callbackNode=null,e.callbackPriority=0,null;var t=e.callbackNode;if(rL()&&e.callbackNode!==t)return null;var i=Ln;return i=ZJ(e,e===Yg?i:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),i===0?null:(WIA(e,i,A),ICA(e,zI()),e.callbackNode!=null&&e.callbackNode===t?CCA.bind(null,e):null)}function HX(e,A){if(rL())return null;WIA(e,A,!0)}function jMA(){gNA(function(){lg&6?ej(WaA,PMA):rCA()})}function Tj(){if(fu===0){var e=IS;e===0&&(e=XG,XG<<=1,!(XG&261888)&&(XG=256)),fu=e}return fu}function OX(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Jv(""+e)}function PX(e,A){var t=A.ownerDocument.createElement("input");return t.name=A.name,t.value=A.value,e.id&&t.setAttribute("form",e.id),A.parentNode.insertBefore(t,A),e=new FormData(e),t.parentNode.removeChild(t),e}function zMA(e,A,t,i,n){if(A==="submit"&&t&&t.stateNode===n){var g=OX((n[II]||null).action),o=i.submitter;o&&(A=(A=o[II]||null)?OX(A.formAction):o.getAttribute("formAction"),A!==null&&(g=A,o=null));var s=new WJ("action","action",null,i,n);e.push({event:s,listeners:[{instance:null,listener:function(){if(i.defaultPrevented){if(fu!==0){var a=o?PX(n,o):new FormData(n);hP(t,{pending:!0,data:a,method:n.method,action:g},null,a)}}else typeof g=="function"&&(s.preventDefault(),a=o?PX(n,o):new FormData(n),hP(t,{pending:!0,data:a,method:n.method,action:g},g,a))},currentTarget:n}]})}}for(var qq=0;qq<sP.length;qq++){var Yq=sP[qq],ZMA=Yq.toLowerCase(),WMA=Yq[0].toUpperCase()+Yq.slice(1);nl(ZMA,"on"+WMA)}nl(DrA,"onAnimationEnd");nl(mrA,"onAnimationIteration");nl(SrA,"onAnimationStart");nl("dblclick","onDoubleClick");nl("focusin","onFocus");nl("focusout","onBlur");nl(cMA,"onTransitionRun");nl(lMA,"onTransitionStart");nl(BMA,"onTransitionCancel");nl(wrA,"onTransitionEnd");aS("onMouseEnter",["mouseout","mouseover"]);aS("onMouseLeave",["mouseout","mouseover"]);aS("onPointerEnter",["pointerout","pointerover"]);aS("onPointerLeave",["pointerout","pointerover"]);Mf("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Mf("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Mf("onBeforeInput",["compositionend","keypress","textInput","paste"]);Mf("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Mf("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Mf("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var qM="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),VMA=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(qM));function cCA(e,A){A=(A&4)!==0;for(var t=0;t<e.length;t++){var i=e[t],n=i.event;i=i.listeners;A:{var g=void 0;if(A)for(var o=i.length-1;0<=o;o--){var s=i[o],a=s.instance,r=s.currentTarget;if(s=s.listener,a!==g&&n.isPropagationStopped())break A;g=s,n.currentTarget=r;try{g(n)}catch(I){WK(I)}n.currentTarget=null,g=a}else for(o=0;o<i.length;o++){if(s=i[o],a=s.instance,r=s.currentTarget,s=s.listener,a!==g&&n.isPropagationStopped())break A;g=s,n.currentTarget=r;try{g(n)}catch(I){WK(I)}n.currentTarget=null,g=a}}}}function bn(e,A){var t=A[$O];t===void 0&&(t=A[$O]=new Set);var i=e+"__bubble";t.has(i)||(lCA(A,e,2,!1),t.add(i))}function Hq(e,A,t){var i=0;A&&(i|=4),lCA(t,e,i,A)}var ab="_reactListening"+Math.random().toString(36).slice(2);function qj(e){if(!e[ab]){e[ab]=!0,nrA.forEach(function(t){t!=="selectionchange"&&(VMA.has(t)||Hq(t,!1,e),Hq(t,!0,e))});var A=e.nodeType===9?e:e.ownerDocument;A===null||A[ab]||(A[ab]=!0,Hq("selectionchange",!1,A))}}function lCA(e,A,t,i){switch(wCA(A)){case 2:var n=SNA;break;case 8:n=wNA;break;default:n=Pj}t=n.bind(null,A,t,e),n=void 0,!nP||A!=="touchstart"&&A!=="touchmove"&&A!=="wheel"||(n=!0),i?n!==void 0?e.addEventListener(A,t,{capture:!0,passive:n}):e.addEventListener(A,t,!0):n!==void 0?e.addEventListener(A,t,{passive:n}):e.addEventListener(A,t,!1)}function Oq(e,A,t,i,n){var g=i;if(!(A&1)&&!(A&2)&&i!==null)A:for(;;){if(i===null)return;var o=i.tag;if(o===3||o===4){var s=i.stateNode.containerInfo;if(s===n)break;if(o===4)for(o=i.return;o!==null;){var a=o.tag;if((a===3||a===4)&&o.stateNode.containerInfo===n)return;o=o.return}for(;s!==null;){if(o=LD(s),o===null)return;if(a=o.tag,a===5||a===6||a===26||a===27){i=g=o;continue A}s=s.parentNode}}i=i.return}crA(function(){var r=g,I=oj(t),c=[];A:{var l=krA.get(e);if(l!==void 0){var B=WJ,Q=e;switch(e){case"keypress":if(xv(t)===0)break A;case"keydown":case"keyup":B=HkA;break;case"focusin":Q="focus",B=pq;break;case"focusout":Q="blur",B=pq;break;case"beforeblur":case"afterblur":B=pq;break;case"click":if(t.button===2)break A;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":B=AX;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":B=bkA;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":B=jkA;break;case DrA:case mrA:case SrA:B=KkA;break;case wrA:B=ZkA;break;case"scroll":case"scrollend":B=RkA;break;case"wheel":B=VkA;break;case"copy":case"cut":case"paste":B=_kA;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":B=tX;break;case"toggle":case"beforetoggle":B=$kA}var h=(A&4)!==0,d=!h&&(e==="scroll"||e==="scrollend"),p=h?l!==null?l+"Capture":null:l;h=[];for(var y=r,m;y!==null;){var D=y;if(m=D.stateNode,D=D.tag,D!==5&&D!==26&&D!==27||m===null||p===null||(D=vM(y,p),D!=null&&h.push(YM(y,D,m))),d)break;y=y.return}0<h.length&&(l=new B(l,Q,null,t,I),c.push({event:l,listeners:h}))}}if(!(A&7)){A:{if(l=e==="mouseover"||e==="pointerover",B=e==="mouseout"||e==="pointerout",l&&t!==iP&&(Q=t.relatedTarget||t.fromElement)&&(LD(Q)||Q[ow]))break A;if((B||l)&&(l=I.window===I?I:(l=I.ownerDocument)?l.defaultView||l.parentWindow:window,B?(Q=t.relatedTarget||t.toElement,B=r,Q=Q?LD(Q):null,Q!==null&&(d=BR(Q),h=Q.tag,Q!==d||h!==5&&h!==27&&h!==6)&&(Q=null)):(B=null,Q=r),B!==Q)){if(h=AX,D="onMouseLeave",p="onMouseEnter",y="mouse",(e==="pointerout"||e==="pointerover")&&(h=tX,D="onPointerLeave",p="onPointerEnter",y="pointer"),d=B==null?l:sk(B),m=Q==null?l:sk(Q),l=new h(D,y+"leave",B,t,I),l.target=d,l.relatedTarget=m,D=null,LD(I)===r&&(h=new h(p,y+"enter",Q,t,I),h.target=m,h.relatedTarget=d,D=h),d=D,B&&Q)e:{for(h=XMA,p=B,y=Q,m=0,D=p;D;D=h(D))m++;D=0;for(var S=y;S;S=h(S))D++;for(;0<m-D;)p=h(p),m--;for(;0<D-m;)y=h(y),D--;for(;m--;){if(p===y||y!==null&&p===y.alternate){h=p;break e}p=h(p),y=h(y)}h=null}else h=null;B!==null&&jX(c,l,B,h,!1),Q!==null&&d!==null&&jX(c,d,Q,h,!0)}}A:{if(l=r?sk(r):window,B=l.nodeName&&l.nodeName.toLowerCase(),B==="select"||B==="input"&&l.type==="file")var k=oX;else if(gX(l))if(drA)k=rMA;else{k=sMA;var N=oMA}else B=l.nodeName,!B||B.toLowerCase()!=="input"||l.type!=="checkbox"&&l.type!=="radio"?r&&gj(r.elementType)&&(k=oX):k=aMA;if(k&&(k=k(e,r))){urA(c,k,t,I);break A}N&&N(e,l,r),e==="focusout"&&r&&l.type==="number"&&r.memoizedProps.value!=null&&tP(l,"number",l.value)}switch(N=r?sk(r):window,e){case"focusin":(gX(N)||N.contentEditable==="true")&&(qD=N,gP=r,Jk=null);break;case"focusout":Jk=gP=qD=null;break;case"mousedown":oP=!0;break;case"contextmenu":case"mouseup":case"dragend":oP=!1,CX(c,t,I);break;case"selectionchange":if(CMA)break;case"keydown":case"keyup":CX(c,t,I)}var G;if(rj)A:{switch(e){case"compositionstart":var M="onCompositionStart";break A;case"compositionend":M="onCompositionEnd";break A;case"compositionupdate":M="onCompositionUpdate";break A}M=void 0}else TD?ErA(e,t)&&(M="onCompositionEnd"):e==="keydown"&&t.keyCode===229&&(M="onCompositionStart");M&&(BrA&&t.locale!=="ko"&&(TD||M!=="onCompositionStart"?M==="onCompositionEnd"&&TD&&(G=lrA()):(du=I,sj="value"in du?du.value:du.textContent,TD=!0)),N=lF(r,M),0<N.length&&(M=new eX(M,e,null,t,I),c.push({event:M,listeners:N}),G?M.data=G:(G=QrA(t),G!==null&&(M.data=G)))),(G=eMA?tMA(e,t):iMA(e,t))&&(M=lF(r,"onBeforeInput"),0<M.length&&(N=new eX("onBeforeInput","beforeinput",null,t,I),c.push({event:N,listeners:M}),N.data=G)),zMA(c,e,r,t,I)}cCA(c,A)})}function YM(e,A,t){return{instance:e,listener:A,currentTarget:t}}function lF(e,A){for(var t=A+"Capture",i=[];e!==null;){var n=e,g=n.stateNode;if(n=n.tag,n!==5&&n!==26&&n!==27||g===null||(n=vM(e,t),n!=null&&i.unshift(YM(e,n,g)),n=vM(e,A),n!=null&&i.push(YM(e,n,g))),e.tag===3)return i;e=e.return}return[]}function XMA(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function jX(e,A,t,i,n){for(var g=A._reactName,o=[];t!==null&&t!==i;){var s=t,a=s.alternate,r=s.stateNode;if(s=s.tag,a!==null&&a===i)break;s!==5&&s!==26&&s!==27||r===null||(a=r,n?(r=vM(t,g),r!=null&&o.unshift(YM(t,r,a))):n||(r=vM(t,g),r!=null&&o.push(YM(t,r,a)))),t=t.return}o.length!==0&&e.push({event:A,listeners:o})}var $MA=/\r\n?/g,ANA=/\u0000|\uFFFD/g;function zX(e){return(typeof e=="string"?e:""+e).replace($MA,`
`).replace(ANA,"")}function BCA(e,A){return A=zX(A),zX(e)===A}function bg(e,A,t,i,n,g){switch(t){case"children":typeof i=="string"?A==="body"||A==="textarea"&&i===""||rS(e,i):(typeof i=="number"||typeof i=="bigint")&&A!=="body"&&rS(e,""+i);break;case"className":eb(e,"class",i);break;case"tabIndex":eb(e,"tabindex",i);break;case"dir":case"role":case"viewBox":case"width":case"height":eb(e,t,i);break;case"style":CrA(e,i,g);break;case"data":if(A!=="object"){eb(e,"data",i);break}case"src":case"href":if(i===""&&(A!=="a"||t!=="href")){e.removeAttribute(t);break}if(i==null||typeof i=="function"||typeof i=="symbol"||typeof i=="boolean"){e.removeAttribute(t);break}i=Jv(""+i),e.setAttribute(t,i);break;case"action":case"formAction":if(typeof i=="function"){e.setAttribute(t,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof g=="function"&&(t==="formAction"?(A!=="input"&&bg(e,A,"name",n.name,n,null),bg(e,A,"formEncType",n.formEncType,n,null),bg(e,A,"formMethod",n.formMethod,n,null),bg(e,A,"formTarget",n.formTarget,n,null)):(bg(e,A,"encType",n.encType,n,null),bg(e,A,"method",n.method,n,null),bg(e,A,"target",n.target,n,null)));if(i==null||typeof i=="symbol"||typeof i=="boolean"){e.removeAttribute(t);break}i=Jv(""+i),e.setAttribute(t,i);break;case"onClick":i!=null&&(e.onclick=wE);break;case"onScroll":i!=null&&bn("scroll",e);break;case"onScrollEnd":i!=null&&bn("scrollend",e);break;case"dangerouslySetInnerHTML":if(i!=null){if(typeof i!="object"||!("__html"in i))throw Error(It(61));if(t=i.__html,t!=null){if(n.children!=null)throw Error(It(60));e.innerHTML=t}}break;case"multiple":e.multiple=i&&typeof i!="function"&&typeof i!="symbol";break;case"muted":e.muted=i&&typeof i!="function"&&typeof i!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(i==null||typeof i=="function"||typeof i=="boolean"||typeof i=="symbol"){e.removeAttribute("xlink:href");break}t=Jv(""+i),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":i!=null&&typeof i!="function"&&typeof i!="symbol"?e.setAttribute(t,""+i):e.removeAttribute(t);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":i&&typeof i!="function"&&typeof i!="symbol"?e.setAttribute(t,""):e.removeAttribute(t);break;case"capture":case"download":i===!0?e.setAttribute(t,""):i!==!1&&i!=null&&typeof i!="function"&&typeof i!="symbol"?e.setAttribute(t,i):e.removeAttribute(t);break;case"cols":case"rows":case"size":case"span":i!=null&&typeof i!="function"&&typeof i!="symbol"&&!isNaN(i)&&1<=i?e.setAttribute(t,i):e.removeAttribute(t);break;case"rowSpan":case"start":i==null||typeof i=="function"||typeof i=="symbol"||isNaN(i)?e.removeAttribute(t):e.setAttribute(t,i);break;case"popover":bn("beforetoggle",e),bn("toggle",e),_v(e,"popover",i);break;case"xlinkActuate":PB(e,"http://www.w3.org/1999/xlink","xlink:actuate",i);break;case"xlinkArcrole":PB(e,"http://www.w3.org/1999/xlink","xlink:arcrole",i);break;case"xlinkRole":PB(e,"http://www.w3.org/1999/xlink","xlink:role",i);break;case"xlinkShow":PB(e,"http://www.w3.org/1999/xlink","xlink:show",i);break;case"xlinkTitle":PB(e,"http://www.w3.org/1999/xlink","xlink:title",i);break;case"xlinkType":PB(e,"http://www.w3.org/1999/xlink","xlink:type",i);break;case"xmlBase":PB(e,"http://www.w3.org/XML/1998/namespace","xml:base",i);break;case"xmlLang":PB(e,"http://www.w3.org/XML/1998/namespace","xml:lang",i);break;case"xmlSpace":PB(e,"http://www.w3.org/XML/1998/namespace","xml:space",i);break;case"is":_v(e,"is",i);break;case"innerText":case"textContent":break;default:(!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(t=MkA.get(t)||t,_v(e,t,i))}}function RP(e,A,t,i,n,g){switch(t){case"style":CrA(e,i,g);break;case"dangerouslySetInnerHTML":if(i!=null){if(typeof i!="object"||!("__html"in i))throw Error(It(61));if(t=i.__html,t!=null){if(n.children!=null)throw Error(It(60));e.innerHTML=t}}break;case"children":typeof i=="string"?rS(e,i):(typeof i=="number"||typeof i=="bigint")&&rS(e,""+i);break;case"onScroll":i!=null&&bn("scroll",e);break;case"onScrollEnd":i!=null&&bn("scrollend",e);break;case"onClick":i!=null&&(e.onclick=wE);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!grA.hasOwnProperty(t))A:{if(t[0]==="o"&&t[1]==="n"&&(n=t.endsWith("Capture"),A=t.slice(2,n?t.length-7:void 0),g=e[II]||null,g=g!=null?g[t]:null,typeof g=="function"&&e.removeEventListener(A,g,n),typeof i=="function")){typeof g!="function"&&g!==null&&(t in e?e[t]=null:e.hasAttribute(t)&&e.removeAttribute(t)),e.addEventListener(A,i,n);break A}t in e?e[t]=i:i===!0?e.setAttribute(t,""):_v(e,t,i)}}}function ba(e,A,t){switch(A){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":bn("error",e),bn("load",e);var i=!1,n=!1,g;for(g in t)if(t.hasOwnProperty(g)){var o=t[g];if(o!=null)switch(g){case"src":i=!0;break;case"srcSet":n=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(It(137,A));default:bg(e,A,g,o,t,null)}}n&&bg(e,A,"srcSet",t.srcSet,t,null),i&&bg(e,A,"src",t.src,t,null);return;case"input":bn("invalid",e);var s=g=o=n=null,a=null,r=null;for(i in t)if(t.hasOwnProperty(i)){var I=t[i];if(I!=null)switch(i){case"name":n=I;break;case"type":o=I;break;case"checked":a=I;break;case"defaultChecked":r=I;break;case"value":g=I;break;case"defaultValue":s=I;break;case"children":case"dangerouslySetInnerHTML":if(I!=null)throw Error(It(137,A));break;default:bg(e,A,i,I,t,null)}}arA(e,g,s,a,r,o,n,!1);return;case"select":bn("invalid",e),i=o=g=null;for(n in t)if(t.hasOwnProperty(n)&&(s=t[n],s!=null))switch(n){case"value":g=s;break;case"defaultValue":o=s;break;case"multiple":i=s;default:bg(e,A,n,s,t,null)}A=g,t=o,e.multiple=!!i,A!=null?Em(e,!!i,A,!1):t!=null&&Em(e,!!i,t,!0);return;case"textarea":bn("invalid",e),g=n=i=null;for(o in t)if(t.hasOwnProperty(o)&&(s=t[o],s!=null))switch(o){case"value":i=s;break;case"defaultValue":n=s;break;case"children":g=s;break;case"dangerouslySetInnerHTML":if(s!=null)throw Error(It(91));break;default:bg(e,A,o,s,t,null)}IrA(e,i,n,g);return;case"option":for(a in t)if(t.hasOwnProperty(a)&&(i=t[a],i!=null))switch(a){case"selected":e.selected=i&&typeof i!="function"&&typeof i!="symbol";break;default:bg(e,A,a,i,t,null)}return;case"dialog":bn("beforetoggle",e),bn("toggle",e),bn("cancel",e),bn("close",e);break;case"iframe":case"object":bn("load",e);break;case"video":case"audio":for(i=0;i<qM.length;i++)bn(qM[i],e);break;case"image":bn("error",e),bn("load",e);break;case"details":bn("toggle",e);break;case"embed":case"source":case"link":bn("error",e),bn("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(r in t)if(t.hasOwnProperty(r)&&(i=t[r],i!=null))switch(r){case"children":case"dangerouslySetInnerHTML":throw Error(It(137,A));default:bg(e,A,r,i,t,null)}return;default:if(gj(A)){for(I in t)t.hasOwnProperty(I)&&(i=t[I],i!==void 0&&RP(e,A,I,i,t,void 0));return}}for(s in t)t.hasOwnProperty(s)&&(i=t[s],i!=null&&bg(e,A,s,i,t,null))}function eNA(e,A,t,i){switch(A){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var n=null,g=null,o=null,s=null,a=null,r=null,I=null;for(B in t){var c=t[B];if(t.hasOwnProperty(B)&&c!=null)switch(B){case"checked":break;case"value":break;case"defaultValue":a=c;default:i.hasOwnProperty(B)||bg(e,A,B,null,i,c)}}for(var l in i){var B=i[l];if(c=t[l],i.hasOwnProperty(l)&&(B!=null||c!=null))switch(l){case"type":g=B;break;case"name":n=B;break;case"checked":r=B;break;case"defaultChecked":I=B;break;case"value":o=B;break;case"defaultValue":s=B;break;case"children":case"dangerouslySetInnerHTML":if(B!=null)throw Error(It(137,A));break;default:B!==c&&bg(e,A,l,B,i,c)}}eP(e,o,s,a,r,I,g,n);return;case"select":B=o=s=l=null;for(g in t)if(a=t[g],t.hasOwnProperty(g)&&a!=null)switch(g){case"value":break;case"multiple":B=a;default:i.hasOwnProperty(g)||bg(e,A,g,null,i,a)}for(n in i)if(g=i[n],a=t[n],i.hasOwnProperty(n)&&(g!=null||a!=null))switch(n){case"value":l=g;break;case"defaultValue":s=g;break;case"multiple":o=g;default:g!==a&&bg(e,A,n,g,i,a)}A=s,t=o,i=B,l!=null?Em(e,!!t,l,!1):!!i!=!!t&&(A!=null?Em(e,!!t,A,!0):Em(e,!!t,t?[]:"",!1));return;case"textarea":B=l=null;for(s in t)if(n=t[s],t.hasOwnProperty(s)&&n!=null&&!i.hasOwnProperty(s))switch(s){case"value":break;case"children":break;default:bg(e,A,s,null,i,n)}for(o in i)if(n=i[o],g=t[o],i.hasOwnProperty(o)&&(n!=null||g!=null))switch(o){case"value":l=n;break;case"defaultValue":B=n;break;case"children":break;case"dangerouslySetInnerHTML":if(n!=null)throw Error(It(91));break;default:n!==g&&bg(e,A,o,n,i,g)}rrA(e,l,B);return;case"option":for(var Q in t)if(l=t[Q],t.hasOwnProperty(Q)&&l!=null&&!i.hasOwnProperty(Q))switch(Q){case"selected":e.selected=!1;break;default:bg(e,A,Q,null,i,l)}for(a in i)if(l=i[a],B=t[a],i.hasOwnProperty(a)&&l!==B&&(l!=null||B!=null))switch(a){case"selected":e.selected=l&&typeof l!="function"&&typeof l!="symbol";break;default:bg(e,A,a,l,i,B)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var h in t)l=t[h],t.hasOwnProperty(h)&&l!=null&&!i.hasOwnProperty(h)&&bg(e,A,h,null,i,l);for(r in i)if(l=i[r],B=t[r],i.hasOwnProperty(r)&&l!==B&&(l!=null||B!=null))switch(r){case"children":case"dangerouslySetInnerHTML":if(l!=null)throw Error(It(137,A));break;default:bg(e,A,r,l,i,B)}return;default:if(gj(A)){for(var d in t)l=t[d],t.hasOwnProperty(d)&&l!==void 0&&!i.hasOwnProperty(d)&&RP(e,A,d,void 0,i,l);for(I in i)l=i[I],B=t[I],!i.hasOwnProperty(I)||l===B||l===void 0&&B===void 0||RP(e,A,I,l,i,B);return}}for(var p in t)l=t[p],t.hasOwnProperty(p)&&l!=null&&!i.hasOwnProperty(p)&&bg(e,A,p,null,i,l);for(c in i)l=i[c],B=t[c],!i.hasOwnProperty(c)||l===B||l==null&&B==null||bg(e,A,c,l,i,B)}function ZX(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function tNA(){if(typeof performance.getEntriesByType=="function"){for(var e=0,A=0,t=performance.getEntriesByType("resource"),i=0;i<t.length;i++){var n=t[i],g=n.transferSize,o=n.initiatorType,s=n.duration;if(g&&s&&ZX(o)){for(o=0,s=n.responseEnd,i+=1;i<t.length;i++){var a=t[i],r=a.startTime;if(r>s)break;var I=a.transferSize,c=a.initiatorType;I&&ZX(c)&&(a=a.responseEnd,o+=I*(a<s?1:(s-r)/(a-r)))}if(--i,A+=8*(g+o)/(n.duration/1e3),e++,10<e)break}}if(0<e)return A/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var GP=null,bP=null;function BF(e){return e.nodeType===9?e:e.ownerDocument}function WX(e){switch(e){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function ECA(e,A){if(e===0)switch(A){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&A==="foreignObject"?0:e}function UP(e,A){return e==="textarea"||e==="noscript"||typeof A.children=="string"||typeof A.children=="number"||typeof A.children=="bigint"||typeof A.dangerouslySetInnerHTML=="object"&&A.dangerouslySetInnerHTML!==null&&A.dangerouslySetInnerHTML.__html!=null}var Pq=null;function iNA(){var e=window.event;return e&&e.type==="popstate"?e===Pq?!1:(Pq=e,!0):(Pq=null,!1)}var QCA=typeof setTimeout=="function"?setTimeout:void 0,nNA=typeof clearTimeout=="function"?clearTimeout:void 0,VX=typeof Promise=="function"?Promise:void 0,gNA=typeof queueMicrotask=="function"?queueMicrotask:typeof VX<"u"?function(e){return VX.resolve(null).then(e).catch(oNA)}:QCA;function oNA(e){setTimeout(function(){throw e})}function wd(e){return e==="head"}function XX(e,A){var t=A,i=0;do{var n=t.nextSibling;if(e.removeChild(t),n&&n.nodeType===8)if(t=n.data,t==="/$"||t==="/&"){if(i===0){e.removeChild(n),uS(A);return}i--}else if(t==="$"||t==="$?"||t==="$~"||t==="$!"||t==="&")i++;else if(t==="html")zk(e.ownerDocument.documentElement);else if(t==="head"){t=e.ownerDocument.head,zk(t);for(var g=t.firstChild;g;){var o=g.nextSibling,s=g.nodeName;g[dR]||s==="SCRIPT"||s==="STYLE"||s==="LINK"&&g.rel.toLowerCase()==="stylesheet"||t.removeChild(g),g=o}}else t==="body"&&zk(e.ownerDocument.body);t=n}while(t);uS(A)}function $X(e,A){var t=e;e=0;do{var i=t.nextSibling;if(t.nodeType===1?A?(t._stashedDisplay=t.style.display,t.style.display="none"):(t.style.display=t._stashedDisplay||"",t.getAttribute("style")===""&&t.removeAttribute("style")):t.nodeType===3&&(A?(t._stashedText=t.nodeValue,t.nodeValue=""):t.nodeValue=t._stashedText||""),i&&i.nodeType===8)if(t=i.data,t==="/$"){if(e===0)break;e--}else t!=="$"&&t!=="$?"&&t!=="$~"&&t!=="$!"||e++;t=i}while(t)}function vP(e){var A=e.firstChild;for(A&&A.nodeType===10&&(A=A.nextSibling);A;){var t=A;switch(A=A.nextSibling,t.nodeName){case"HTML":case"HEAD":case"BODY":vP(t),nj(t);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(t.rel.toLowerCase()==="stylesheet")continue}e.removeChild(t)}}function sNA(e,A,t,i){for(;e.nodeType===1;){var n=t;if(e.nodeName.toLowerCase()!==A.toLowerCase()){if(!i&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(i){if(!e[dR])switch(A){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(g=e.getAttribute("rel"),g==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(g!==n.rel||e.getAttribute("href")!==(n.href==null||n.href===""?null:n.href)||e.getAttribute("crossorigin")!==(n.crossOrigin==null?null:n.crossOrigin)||e.getAttribute("title")!==(n.title==null?null:n.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(g=e.getAttribute("src"),(g!==(n.src==null?null:n.src)||e.getAttribute("type")!==(n.type==null?null:n.type)||e.getAttribute("crossorigin")!==(n.crossOrigin==null?null:n.crossOrigin))&&g&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(A==="input"&&e.type==="hidden"){var g=n.name==null?null:""+n.name;if(n.type==="hidden"&&e.getAttribute("name")===g)return e}else return e;if(e=$C(e.nextSibling),e===null)break}return null}function aNA(e,A,t){if(A==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=$C(e.nextSibling),e===null))return null;return e}function uCA(e,A){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!A||(e=$C(e.nextSibling),e===null))return null;return e}function KP(e){return e.data==="$?"||e.data==="$~"}function FP(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function rNA(e,A){var t=e.ownerDocument;if(e.data==="$~")e._reactRetry=A;else if(e.data!=="$?"||t.readyState!=="loading")A();else{var i=function(){A(),t.removeEventListener("DOMContentLoaded",i)};t.addEventListener("DOMContentLoaded",i),e._reactRetry=i}}function $C(e){for(;e!=null;e=e.nextSibling){var A=e.nodeType;if(A===1||A===3)break;if(A===8){if(A=e.data,A==="$"||A==="$!"||A==="$?"||A==="$~"||A==="&"||A==="F!"||A==="F")break;if(A==="/$"||A==="/&")return null}}return e}var _P=null;function A6(e){e=e.nextSibling;for(var A=0;e;){if(e.nodeType===8){var t=e.data;if(t==="/$"||t==="/&"){if(A===0)return $C(e.nextSibling);A--}else t!=="$"&&t!=="$!"&&t!=="$?"&&t!=="$~"&&t!=="&"||A++}e=e.nextSibling}return null}function e6(e){e=e.previousSibling;for(var A=0;e;){if(e.nodeType===8){var t=e.data;if(t==="$"||t==="$!"||t==="$?"||t==="$~"||t==="&"){if(A===0)return e;A--}else t!=="/$"&&t!=="/&"||A++}e=e.previousSibling}return null}function dCA(e,A,t){switch(A=BF(t),e){case"html":if(e=A.documentElement,!e)throw Error(It(452));return e;case"head":if(e=A.head,!e)throw Error(It(453));return e;case"body":if(e=A.body,!e)throw Error(It(454));return e;default:throw Error(It(451))}}function zk(e){for(var A=e.attributes;A.length;)e.removeAttributeNode(A[0]);nj(e)}var nc=new Map,t6=new Set;function EF(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var lQ=Bg.d;Bg.d={f:INA,r:CNA,D:cNA,C:lNA,L:BNA,m:ENA,X:uNA,S:QNA,M:dNA};function INA(){var e=lQ.f(),A=sL();return e||A}function CNA(e){var A=sw(e);A!==null&&A.tag===5&&A.type==="form"?CIA(A):lQ.r(e)}var Cw=typeof document>"u"?null:document;function hCA(e,A,t){var i=Cw;if(i&&typeof A=="string"&&A){var n=PC(A);n='link[rel="'+e+'"][href="'+n+'"]',typeof t=="string"&&(n+='[crossorigin="'+t+'"]'),t6.has(n)||(t6.add(n),e={rel:e,crossOrigin:t,href:A},i.querySelector(n)===null&&(A=i.createElement("link"),ba(A,"link",e),ga(A),i.head.appendChild(A)))}}function cNA(e){lQ.D(e),hCA("dns-prefetch",e,null)}function lNA(e,A){lQ.C(e,A),hCA("preconnect",e,A)}function BNA(e,A,t){lQ.L(e,A,t);var i=Cw;if(i&&e&&A){var n='link[rel="preload"][as="'+PC(A)+'"]';A==="image"&&t&&t.imageSrcSet?(n+='[imagesrcset="'+PC(t.imageSrcSet)+'"]',typeof t.imageSizes=="string"&&(n+='[imagesizes="'+PC(t.imageSizes)+'"]')):n+='[href="'+PC(e)+'"]';var g=n;switch(A){case"style":g=QS(e);break;case"script":g=cw(e)}nc.has(g)||(e=so({rel:"preload",href:A==="image"&&t&&t.imageSrcSet?void 0:e,as:A},t),nc.set(g,e),i.querySelector(n)!==null||A==="style"&&i.querySelector(mR(g))||A==="script"&&i.querySelector(SR(g))||(A=i.createElement("link"),ba(A,"link",e),ga(A),i.head.appendChild(A)))}}function ENA(e,A){lQ.m(e,A);var t=Cw;if(t&&e){var i=A&&typeof A.as=="string"?A.as:"script",n='link[rel="modulepreload"][as="'+PC(i)+'"][href="'+PC(e)+'"]',g=n;switch(i){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=cw(e)}if(!nc.has(g)&&(e=so({rel:"modulepreload",href:e},A),nc.set(g,e),t.querySelector(n)===null)){switch(i){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(t.querySelector(SR(g)))return}i=t.createElement("link"),ba(i,"link",e),ga(i),t.head.appendChild(i)}}}function QNA(e,A,t){lQ.S(e,A,t);var i=Cw;if(i&&e){var n=Bm(i).hoistableStyles,g=QS(e);A=A||"default";var o=n.get(g);if(!o){var s={loading:0,preload:null};if(o=i.querySelector(mR(g)))s.loading=5;else{e=so({rel:"stylesheet",href:e,"data-precedence":A},t),(t=nc.get(g))&&Yj(e,t);var a=o=i.createElement("link");ga(a),ba(a,"link",e),a._p=new Promise(function(r,I){a.onload=r,a.onerror=I}),a.addEventListener("load",function(){s.loading|=1}),a.addEventListener("error",function(){s.loading|=2}),s.loading|=4,zv(o,A,i)}o={type:"stylesheet",instance:o,count:1,state:s},n.set(g,o)}}}function uNA(e,A){lQ.X(e,A);var t=Cw;if(t&&e){var i=Bm(t).hoistableScripts,n=cw(e),g=i.get(n);g||(g=t.querySelector(SR(n)),g||(e=so({src:e,async:!0},A),(A=nc.get(n))&&Hj(e,A),g=t.createElement("script"),ga(g),ba(g,"link",e),t.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},i.set(n,g))}}function dNA(e,A){lQ.M(e,A);var t=Cw;if(t&&e){var i=Bm(t).hoistableScripts,n=cw(e),g=i.get(n);g||(g=t.querySelector(SR(n)),g||(e=so({src:e,async:!0,type:"module"},A),(A=nc.get(n))&&Hj(e,A),g=t.createElement("script"),ga(g),ba(g,"link",e),t.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},i.set(n,g))}}function i6(e,A,t,i){var n=(n=bu.current)?EF(n):null;if(!n)throw Error(It(446));switch(e){case"meta":case"title":return null;case"style":return typeof t.precedence=="string"&&typeof t.href=="string"?(A=QS(t.href),t=Bm(n).hoistableStyles,i=t.get(A),i||(i={type:"style",instance:null,count:0,state:null},t.set(A,i)),i):{type:"void",instance:null,count:0,state:null};case"link":if(t.rel==="stylesheet"&&typeof t.href=="string"&&typeof t.precedence=="string"){e=QS(t.href);var g=Bm(n).hoistableStyles,o=g.get(e);if(o||(n=n.ownerDocument||n,o={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(e,o),(g=n.querySelector(mR(e)))&&!g._p&&(o.instance=g,o.state.loading=5),nc.has(e)||(t={rel:"preload",as:"style",href:t.href,crossOrigin:t.crossOrigin,integrity:t.integrity,media:t.media,hrefLang:t.hrefLang,referrerPolicy:t.referrerPolicy},nc.set(e,t),g||hNA(n,e,t,o.state))),A&&i===null)throw Error(It(528,""));return o}if(A&&i!==null)throw Error(It(529,""));return null;case"script":return A=t.async,t=t.src,typeof t=="string"&&A&&typeof A!="function"&&typeof A!="symbol"?(A=cw(t),t=Bm(n).hoistableScripts,i=t.get(A),i||(i={type:"script",instance:null,count:0,state:null},t.set(A,i)),i):{type:"void",instance:null,count:0,state:null};default:throw Error(It(444,e))}}function QS(e){return'href="'+PC(e)+'"'}function mR(e){return'link[rel="stylesheet"]['+e+"]"}function pCA(e){return so({},e,{"data-precedence":e.precedence,precedence:null})}function hNA(e,A,t,i){e.querySelector('link[rel="preload"][as="style"]['+A+"]")?i.loading=1:(A=e.createElement("link"),i.preload=A,A.addEventListener("load",function(){return i.loading|=1}),A.addEventListener("error",function(){return i.loading|=2}),ba(A,"link",t),ga(A),e.head.appendChild(A))}function cw(e){return'[src="'+PC(e)+'"]'}function SR(e){return"script[async]"+e}function n6(e,A,t){if(A.count++,A.instance===null)switch(A.type){case"style":var i=e.querySelector('style[data-href~="'+PC(t.href)+'"]');if(i)return A.instance=i,ga(i),i;var n=so({},t,{"data-href":t.href,"data-precedence":t.precedence,href:null,precedence:null});return i=(e.ownerDocument||e).createElement("style"),ga(i),ba(i,"style",n),zv(i,t.precedence,e),A.instance=i;case"stylesheet":n=QS(t.href);var g=e.querySelector(mR(n));if(g)return A.state.loading|=4,A.instance=g,ga(g),g;i=pCA(t),(n=nc.get(n))&&Yj(i,n),g=(e.ownerDocument||e).createElement("link"),ga(g);var o=g;return o._p=new Promise(function(s,a){o.onload=s,o.onerror=a}),ba(g,"link",i),A.state.loading|=4,zv(g,t.precedence,e),A.instance=g;case"script":return g=cw(t.src),(n=e.querySelector(SR(g)))?(A.instance=n,ga(n),n):(i=t,(n=nc.get(g))&&(i=so({},t),Hj(i,n)),e=e.ownerDocument||e,n=e.createElement("script"),ga(n),ba(n,"link",i),e.head.appendChild(n),A.instance=n);case"void":return null;default:throw Error(It(443,A.type))}else A.type==="stylesheet"&&!(A.state.loading&4)&&(i=A.instance,A.state.loading|=4,zv(i,t.precedence,e));return A.instance}function zv(e,A,t){for(var i=t.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),n=i.length?i[i.length-1]:null,g=n,o=0;o<i.length;o++){var s=i[o];if(s.dataset.precedence===A)g=s;else if(g!==n)break}g?g.parentNode.insertBefore(e,g.nextSibling):(A=t.nodeType===9?t.head:t,A.insertBefore(e,A.firstChild))}function Yj(e,A){e.crossOrigin==null&&(e.crossOrigin=A.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=A.referrerPolicy),e.title==null&&(e.title=A.title)}function Hj(e,A){e.crossOrigin==null&&(e.crossOrigin=A.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=A.referrerPolicy),e.integrity==null&&(e.integrity=A.integrity)}var Zv=null;function g6(e,A,t){if(Zv===null){var i=new Map,n=Zv=new Map;n.set(t,i)}else n=Zv,i=n.get(t),i||(i=new Map,n.set(t,i));if(i.has(e))return i;for(i.set(e,null),t=t.getElementsByTagName(e),n=0;n<t.length;n++){var g=t[n];if(!(g[dR]||g[wa]||e==="link"&&g.getAttribute("rel")==="stylesheet")&&g.namespaceURI!=="http://www.w3.org/2000/svg"){var o=g.getAttribute(A)||"";o=e+o;var s=i.get(o);s?s.push(g):i.set(o,[g])}}return i}function o6(e,A,t){e=e.ownerDocument||e,e.head.insertBefore(t,A==="title"?e.querySelector("head > title"):null)}function pNA(e,A,t){if(t===1||A.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof A.precedence!="string"||typeof A.href!="string"||A.href==="")break;return!0;case"link":if(typeof A.rel!="string"||typeof A.href!="string"||A.href===""||A.onLoad||A.onError)break;switch(A.rel){case"stylesheet":return e=A.disabled,typeof A.precedence=="string"&&e==null;default:return!0}case"script":if(A.async&&typeof A.async!="function"&&typeof A.async!="symbol"&&!A.onLoad&&!A.onError&&A.src&&typeof A.src=="string")return!0}return!1}function fCA(e){return!(e.type==="stylesheet"&&!(e.state.loading&3))}function fNA(e,A,t,i){if(t.type==="stylesheet"&&(typeof i.media!="string"||matchMedia(i.media).matches!==!1)&&!(t.state.loading&4)){if(t.instance===null){var n=QS(i.href),g=A.querySelector(mR(n));if(g){A=g._p,A!==null&&typeof A=="object"&&typeof A.then=="function"&&(e.count++,e=QF.bind(e),A.then(e,e)),t.state.loading|=4,t.instance=g,ga(g);return}g=A.ownerDocument||A,i=pCA(i),(n=nc.get(n))&&Yj(i,n),g=g.createElement("link"),ga(g);var o=g;o._p=new Promise(function(s,a){o.onload=s,o.onerror=a}),ba(g,"link",i),t.instance=g}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(t,A),(A=t.state.preload)&&!(t.state.loading&3)&&(e.count++,t=QF.bind(e),A.addEventListener("load",t),A.addEventListener("error",t))}}var jq=0;function yNA(e,A){return e.stylesheets&&e.count===0&&Wv(e,e.stylesheets),0<e.count||0<e.imgCount?function(t){var i=setTimeout(function(){if(e.stylesheets&&Wv(e,e.stylesheets),e.unsuspend){var g=e.unsuspend;e.unsuspend=null,g()}},6e4+A);0<e.imgBytes&&jq===0&&(jq=62500*tNA());var n=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Wv(e,e.stylesheets),e.unsuspend)){var g=e.unsuspend;e.unsuspend=null,g()}},(e.imgBytes>jq?50:800)+A);return e.unsuspend=t,function(){e.unsuspend=null,clearTimeout(i),clearTimeout(n)}}:null}function QF(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Wv(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var uF=null;function Wv(e,A){e.stylesheets=null,e.unsuspend!==null&&(e.count++,uF=new Map,A.forEach(DNA,e),uF=null,QF.call(e))}function DNA(e,A){if(!(A.state.loading&4)){var t=uF.get(e);if(t)var i=t.get(null);else{t=new Map,uF.set(e,t);for(var n=e.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g<n.length;g++){var o=n[g];(o.nodeName==="LINK"||o.getAttribute("media")!=="not all")&&(t.set(o.dataset.precedence,o),i=o)}i&&t.set(null,i)}n=A.instance,o=n.getAttribute("data-precedence"),g=t.get(o)||i,g===i&&t.set(null,n),t.set(o,n),this.count++,i=QF.bind(this),n.addEventListener("load",i),n.addEventListener("error",i),g?g.parentNode.insertBefore(n,g.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(n,e.firstChild)),A.state.loading|=4}}var HM={$$typeof:SE,Provider:null,Consumer:null,_currentValue:Np,_currentValue2:Np,_threadCount:0};function mNA(e,A,t,i,n,g,o,s,a){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=Qq(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Qq(0),this.hiddenUpdates=Qq(null),this.identifierPrefix=i,this.onUncaughtError=n,this.onCaughtError=g,this.onRecoverableError=o,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=a,this.incompleteTransitions=new Map}function yCA(e,A,t,i,n,g,o,s,a,r,I,c){return e=new mNA(e,A,t,o,a,r,I,c,s),A=1,g===!0&&(A|=24),g=qI(3,null,null,A),e.current=g,g.stateNode=e,A=Qj(),A.refCount++,e.pooledCache=A,A.refCount++,g.memoizedState={element:i,isDehydrated:t,cache:A},hj(g),e}function DCA(e){return e?(e=OD,e):OD}function mCA(e,A,t,i,n,g){n=DCA(n),i.context===null?i.context=n:i.pendingContext=n,i=vu(A),i.payload={element:t},g=g===void 0?null:g,g!==null&&(i.callback=g),t=Ku(e,i,A),t!==null&&(aI(t,e,A),xk(t,e,A))}function s6(e,A){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t<A?t:A}}function Oj(e,A){s6(e,A),(e=e.alternate)&&s6(e,A)}function SCA(e){if(e.tag===13||e.tag===31){var A=Gf(e,67108864);A!==null&&aI(A,e,67108864),Oj(e,67108864)}}function a6(e){if(e.tag===13||e.tag===31){var A=VI();A=tj(A);var t=Gf(e,A);t!==null&&aI(t,e,A),Oj(e,A)}}var dF=!0;function SNA(e,A,t,i){var n=Li.T;Li.T=null;var g=Bg.p;try{Bg.p=2,Pj(e,A,t,i)}finally{Bg.p=g,Li.T=n}}function wNA(e,A,t,i){var n=Li.T;Li.T=null;var g=Bg.p;try{Bg.p=8,Pj(e,A,t,i)}finally{Bg.p=g,Li.T=n}}function Pj(e,A,t,i){if(dF){var n=JP(i);if(n===null)Oq(e,A,i,hF,t),r6(e,i);else if(MNA(n,e,A,t,i))i.stopPropagation();else if(r6(e,i),A&4&&-1<kNA.indexOf(e)){for(;n!==null;){var g=sw(n);if(g!==null)switch(g.tag){case 3:if(g=g.stateNode,g.current.memoizedState.isDehydrated){var o=Jh(g.pendingLanes);if(o!==0){var s=g;for(s.pendingLanes|=2,s.entangledLanes|=2;o;){var a=1<<31-WI(o);s.entanglements[1]|=a,o&=~a}wB(g),!(lg&6)&&(aF=zI()+500,DR(0))}}break;case 31:case 13:s=Gf(g,2),s!==null&&aI(s,g,2),sL(),Oj(g,2)}if(g=JP(i),g===null&&Oq(e,A,i,hF,t),g===n)break;n=g}n!==null&&i.stopPropagation()}else Oq(e,A,i,null,t)}}function JP(e){return e=oj(e),jj(e)}var hF=null;function jj(e){if(hF=null,e=LD(e),e!==null){var A=BR(e);if(A===null)e=null;else{var t=A.tag;if(t===13){if(e=OaA(A),e!==null)return e;e=null}else if(t===31){if(e=PaA(A),e!==null)return e;e=null}else if(t===3){if(A.stateNode.current.memoizedState.isDehydrated)return A.tag===3?A.stateNode.containerInfo:null;e=null}else A!==e&&(e=null)}}return hF=e,null}function wCA(e){switch(e){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(ckA()){case WaA:return 2;case VaA:return 8;case zK:case lkA:return 32;case XaA:return 268435456;default:return 32}default:return 32}}var LP=!1,Ju=null,Lu=null,xu=null,OM=new Map,PM=new Map,ou=[],kNA="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function r6(e,A){switch(e){case"focusin":case"focusout":Ju=null;break;case"dragenter":case"dragleave":Lu=null;break;case"mouseover":case"mouseout":xu=null;break;case"pointerover":case"pointerout":OM.delete(A.pointerId);break;case"gotpointercapture":case"lostpointercapture":PM.delete(A.pointerId)}}function u0(e,A,t,i,n,g){return e===null||e.nativeEvent!==g?(e={blockedOn:A,domEventName:t,eventSystemFlags:i,nativeEvent:g,targetContainers:[n]},A!==null&&(A=sw(A),A!==null&&SCA(A)),e):(e.eventSystemFlags|=i,A=e.targetContainers,n!==null&&A.indexOf(n)===-1&&A.push(n),e)}function MNA(e,A,t,i,n){switch(A){case"focusin":return Ju=u0(Ju,e,A,t,i,n),!0;case"dragenter":return Lu=u0(Lu,e,A,t,i,n),!0;case"mouseover":return xu=u0(xu,e,A,t,i,n),!0;case"pointerover":var g=n.pointerId;return OM.set(g,u0(OM.get(g)||null,e,A,t,i,n)),!0;case"gotpointercapture":return g=n.pointerId,PM.set(g,u0(PM.get(g)||null,e,A,t,i,n)),!0}return!1}function kCA(e){var A=LD(e.target);if(A!==null){var t=BR(A);if(t!==null){if(A=t.tag,A===13){if(A=OaA(t),A!==null){e.blockedOn=A,j9(e.priority,function(){a6(t)});return}}else if(A===31){if(A=PaA(t),A!==null){e.blockedOn=A,j9(e.priority,function(){a6(t)});return}}else if(A===3&&t.stateNode.current.memoizedState.isDehydrated){e.blockedOn=t.tag===3?t.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Vv(e){if(e.blockedOn!==null)return!1;for(var A=e.targetContainers;0<A.length;){var t=JP(e.nativeEvent);if(t===null){t=e.nativeEvent;var i=new t.constructor(t.type,t);iP=i,t.target.dispatchEvent(i),iP=null}else return A=sw(t),A!==null&&SCA(A),e.blockedOn=t,!1;A.shift()}return!0}function I6(e,A,t){Vv(e)&&t.delete(A)}function NNA(){LP=!1,Ju!==null&&Vv(Ju)&&(Ju=null),Lu!==null&&Vv(Lu)&&(Lu=null),xu!==null&&Vv(xu)&&(xu=null),OM.forEach(I6),PM.forEach(I6)}function rb(e,A){e.blockedOn===A&&(e.blockedOn=null,LP||(LP=!0,Ts.unstable_scheduleCallback(Ts.unstable_NormalPriority,NNA)))}var Ib=null;function C6(e){Ib!==e&&(Ib=e,Ts.unstable_scheduleCallback(Ts.unstable_NormalPriority,function(){Ib===e&&(Ib=null);for(var A=0;A<e.length;A+=3){var t=e[A],i=e[A+1],n=e[A+2];if(typeof i!="function"){if(jj(i||t)===null)continue;break}var g=sw(t);g!==null&&(e.splice(A,3),A-=3,hP(g,{pending:!0,data:n,method:t.method,action:i},i,n))}}))}function uS(e){function A(a){return rb(a,e)}Ju!==null&&rb(Ju,e),Lu!==null&&rb(Lu,e),xu!==null&&rb(xu,e),OM.forEach(A),PM.forEach(A);for(var t=0;t<ou.length;t++){var i=ou[t];i.blockedOn===e&&(i.blockedOn=null)}for(;0<ou.length&&(t=ou[0],t.blockedOn===null);)kCA(t),t.blockedOn===null&&ou.shift();if(t=(e.ownerDocument||e).$$reactFormReplay,t!=null)for(i=0;i<t.length;i+=3){var n=t[i],g=t[i+1],o=n[II]||null;if(typeof g=="function")o||C6(t);else if(o){var s=null;if(g&&g.hasAttribute("formAction")){if(n=g,o=g[II]||null)s=o.formAction;else if(jj(n)!==null)continue}else s=o.action;typeof s=="function"?t[i+1]=s:(t.splice(i,3),i-=3),C6(t)}}}function MCA(){function e(g){g.canIntercept&&g.info==="react-transition"&&g.intercept({handler:function(){return new Promise(function(o){return n=o})},focusReset:"manual",scroll:"manual"})}function A(){n!==null&&(n(),n=null),i||setTimeout(t,20)}function t(){if(!i&&!navigation.transition){var g=navigation.currentEntry;g&&g.url!=null&&navigation.navigate(g.url,{state:g.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var i=!1,n=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",A),navigation.addEventListener("navigateerror",A),setTimeout(t,100),function(){i=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",A),navigation.removeEventListener("navigateerror",A),n!==null&&(n(),n=null)}}}function zj(e){this._internalRoot=e}IL.prototype.render=zj.prototype.render=function(e){var A=this._internalRoot;if(A===null)throw Error(It(409));var t=A.current,i=VI();mCA(t,i,e,A,null,null)};IL.prototype.unmount=zj.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var A=e.containerInfo;mCA(e.current,2,null,e,null,null),sL(),A[ow]=null}};function IL(e){this._internalRoot=e}IL.prototype.unstable_scheduleHydration=function(e){if(e){var A=irA();e={blockedOn:null,target:e,priority:A};for(var t=0;t<ou.length&&A!==0&&A<ou[t].priority;t++);ou.splice(t,0,e),t===0&&kCA(e)}};var c6=YaA.version;if(c6!=="19.2.0")throw Error(It(527,c6,"19.2.0"));Bg.findDOMNode=function(e){var A=e._reactInternals;if(A===void 0)throw typeof e.render=="function"?Error(It(188)):(e=Object.keys(e).join(","),Error(It(268,e)));return e=gkA(A),e=e!==null?jaA(e):null,e=e===null?null:e.stateNode,e};var RNA={bundleType:0,version:"19.2.0",rendererPackageName:"react-dom",currentDispatcherRef:Li,reconcilerVersion:"19.2.0"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Cb=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Cb.isDisabled&&Cb.supportsFiber)try{ER=Cb.inject(RNA),ZI=Cb}catch{}}jJ.createRoot=function(e,A){if(!HaA(e))throw Error(It(299));var t=!1,i="",n=hIA,g=pIA,o=fIA;return A!=null&&(A.unstable_strictMode===!0&&(t=!0),A.identifierPrefix!==void 0&&(i=A.identifierPrefix),A.onUncaughtError!==void 0&&(n=A.onUncaughtError),A.onCaughtError!==void 0&&(g=A.onCaughtError),A.onRecoverableError!==void 0&&(o=A.onRecoverableError)),A=yCA(e,1,!1,null,null,t,i,null,n,g,o,MCA),e[ow]=A.current,qj(e),new zj(A)};jJ.hydrateRoot=function(e,A,t){if(!HaA(e))throw Error(It(299));var i=!1,n="",g=hIA,o=pIA,s=fIA,a=null;return t!=null&&(t.unstable_strictMode===!0&&(i=!0),t.identifierPrefix!==void 0&&(n=t.identifierPrefix),t.onUncaughtError!==void 0&&(g=t.onUncaughtError),t.onCaughtError!==void 0&&(o=t.onCaughtError),t.onRecoverableError!==void 0&&(s=t.onRecoverableError),t.formState!==void 0&&(a=t.formState)),A=yCA(e,1,!0,A,t??null,i,n,a,g,o,s,MCA),A.context=DCA(null),t=A.current,i=VI(),i=tj(i),n=vu(i),n.callback=null,Ku(t,n,i),t=i,A.current.lanes=t,uR(A,t),wB(A),e[ow]=A.current,qj(e),new IL(A)};jJ.version="19.2.0";function NCA(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(NCA)}catch(e){console.error(e)}}NCA(),_aA.exports=jJ;var bQ=_aA.exports;/**
 * react-router v7.8.0
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */var l6="popstate";function GNA(e={}){function A(i,n){let{pathname:g,search:o,hash:s}=i.location;return xP("",{pathname:g,search:o,hash:s},n.state&&n.state.usr||null,n.state&&n.state.key||"default")}function t(i,n){return typeof n=="string"?n:jM(n)}return UNA(A,t,null,e)}function Qo(e,A){if(e===!1||e===null||typeof e>"u")throw new Error(A)}function gc(e,A){if(!e){typeof console<"u"&&console.warn(A);try{throw new Error(A)}catch{}}}function bNA(){return Math.random().toString(36).substring(2,10)}function B6(e,A){return{usr:e.state,key:e.key,idx:A}}function xP(e,A,t=null,i){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof A=="string"?lw(A):A,state:t,key:A&&A.key||i||bNA()}}function jM({pathname:e="/",search:A="",hash:t=""}){return A&&A!=="?"&&(e+=A.charAt(0)==="?"?A:"?"+A),t&&t!=="#"&&(e+=t.charAt(0)==="#"?t:"#"+t),e}function lw(e){let A={};if(e){let t=e.indexOf("#");t>=0&&(A.hash=e.substring(t),e=e.substring(0,t));let i=e.indexOf("?");i>=0&&(A.search=e.substring(i),e=e.substring(0,i)),e&&(A.pathname=e)}return A}function UNA(e,A,t,i={}){let{window:n=document.defaultView,v5Compat:g=!1}=i,o=n.history,s="POP",a=null,r=I();r==null&&(r=0,o.replaceState({...o.state,idx:r},""));function I(){return(o.state||{idx:null}).idx}function c(){s="POP";let d=I(),p=d==null?null:d-r;r=d,a&&a({action:s,location:h.location,delta:p})}function l(d,p){s="PUSH";let y=xP(h.location,d,p);r=I()+1;let m=B6(y,r),D=h.createHref(y);try{o.pushState(m,"",D)}catch(S){if(S instanceof DOMException&&S.name==="DataCloneError")throw S;n.location.assign(D)}g&&a&&a({action:s,location:h.location,delta:1})}function B(d,p){s="REPLACE";let y=xP(h.location,d,p);r=I();let m=B6(y,r),D=h.createHref(y);o.replaceState(m,"",D),g&&a&&a({action:s,location:h.location,delta:0})}function Q(d){return vNA(d)}let h={get action(){return s},get location(){return e(n,o)},listen(d){if(a)throw new Error("A history only accepts one active listener");return n.addEventListener(l6,c),a=d,()=>{n.removeEventListener(l6,c),a=null}},createHref(d){return A(n,d)},createURL:Q,encodeLocation(d){let p=Q(d);return{pathname:p.pathname,search:p.search,hash:p.hash}},push:l,replace:B,go(d){return o.go(d)}};return h}function vNA(e,A=!1){let t="http://localhost";typeof window<"u"&&(t=window.location.origin!=="null"?window.location.origin:window.location.href),Qo(t,"No window.location.(origin|href) available to create URL");let i=typeof e=="string"?e:jM(e);return i=i.replace(/ $/,"%20"),!A&&i.startsWith("//")&&(i=t+i),new URL(i,t)}function RCA(e,A,t="/"){return KNA(e,A,t,!1)}function KNA(e,A,t,i){let n=typeof A=="string"?lw(A):A,g=ZE(n.pathname||"/",t);if(g==null)return null;let o=GCA(e);FNA(o);let s=null;for(let a=0;s==null&&a<o.length;++a){let r=jNA(g);s=ONA(o[a],r,i)}return s}function GCA(e,A=[],t=[],i=""){let n=(g,o,s)=>{let a={relativePath:s===void 0?g.path||"":s,caseSensitive:g.caseSensitive===!0,childrenIndex:o,route:g};a.relativePath.startsWith("/")&&(Qo(a.relativePath.startsWith(i),`Absolute route path "${a.relativePath}" nested under path "${i}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),a.relativePath=a.relativePath.slice(i.length));let r=vE([i,a.relativePath]),I=t.concat(a);g.children&&g.children.length>0&&(Qo(g.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${r}".`),GCA(g.children,A,I,r)),!(g.path==null&&!g.index)&&A.push({path:r,score:YNA(r,g.index),routesMeta:I})};return e.forEach((g,o)=>{var s;if(g.path===""||!((s=g.path)!=null&&s.includes("?")))n(g,o);else for(let a of bCA(g.path))n(g,o,a)}),A}function bCA(e){let A=e.split("/");if(A.length===0)return[];let[t,...i]=A,n=t.endsWith("?"),g=t.replace(/\?$/,"");if(i.length===0)return n?[g,""]:[g];let o=bCA(i.join("/")),s=[];return s.push(...o.map(a=>a===""?g:[g,a].join("/"))),n&&s.push(...o),s.map(a=>e.startsWith("/")&&a===""?"/":a)}function FNA(e){e.sort((A,t)=>A.score!==t.score?t.score-A.score:HNA(A.routesMeta.map(i=>i.childrenIndex),t.routesMeta.map(i=>i.childrenIndex)))}var _NA=/^:[\w-]+$/,JNA=3,LNA=2,xNA=1,TNA=10,qNA=-2,E6=e=>e==="*";function YNA(e,A){let t=e.split("/"),i=t.length;return t.some(E6)&&(i+=qNA),A&&(i+=LNA),t.filter(n=>!E6(n)).reduce((n,g)=>n+(_NA.test(g)?JNA:g===""?xNA:TNA),i)}function HNA(e,A){return e.length===A.length&&e.slice(0,-1).every((i,n)=>i===A[n])?e[e.length-1]-A[A.length-1]:0}function ONA(e,A,t=!1){let{routesMeta:i}=e,n={},g="/",o=[];for(let s=0;s<i.length;++s){let a=i[s],r=s===i.length-1,I=g==="/"?A:A.slice(g.length)||"/",c=pF({path:a.relativePath,caseSensitive:a.caseSensitive,end:r},I),l=a.route;if(!c&&r&&t&&!i[i.length-1].route.index&&(c=pF({path:a.relativePath,caseSensitive:a.caseSensitive,end:!1},I)),!c)return null;Object.assign(n,c.params),o.push({params:n,pathname:vE([g,c.pathname]),pathnameBase:VNA(vE([g,c.pathnameBase])),route:l}),c.pathnameBase!=="/"&&(g=vE([g,c.pathnameBase]))}return o}function pF(e,A){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[t,i]=PNA(e.path,e.caseSensitive,e.end),n=A.match(t);if(!n)return null;let g=n[0],o=g.replace(/(.)\/+$/,"$1"),s=n.slice(1);return{params:i.reduce((r,{paramName:I,isOptional:c},l)=>{if(I==="*"){let Q=s[l]||"";o=g.slice(0,g.length-Q.length).replace(/(.)\/+$/,"$1")}const B=s[l];return c&&!B?r[I]=void 0:r[I]=(B||"").replace(/%2F/g,"/"),r},{}),pathname:g,pathnameBase:o,pattern:e}}function PNA(e,A=!1,t=!0){gc(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let i=[],n="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,s,a)=>(i.push({paramName:s,isOptional:a!=null}),a?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(i.push({paramName:"*"}),n+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?n+="\\/*$":e!==""&&e!=="/"&&(n+="(?:(?=\\/|$))"),[new RegExp(n,A?void 0:"i"),i]}function jNA(e){try{return e.split("/").map(A=>decodeURIComponent(A).replace(/\//g,"%2F")).join("/")}catch(A){return gc(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${A}).`),e}}function ZE(e,A){if(A==="/")return e;if(!e.toLowerCase().startsWith(A.toLowerCase()))return null;let t=A.endsWith("/")?A.length-1:A.length,i=e.charAt(t);return i&&i!=="/"?null:e.slice(t)||"/"}function zNA(e,A="/"){let{pathname:t,search:i="",hash:n=""}=typeof e=="string"?lw(e):e;return{pathname:t?t.startsWith("/")?t:ZNA(t,A):A,search:XNA(i),hash:$NA(n)}}function ZNA(e,A){let t=A.replace(/\/+$/,"").split("/");return e.split("/").forEach(n=>{n===".."?t.length>1&&t.pop():n!=="."&&t.push(n)}),t.length>1?t.join("/"):"/"}function zq(e,A,t,i){return`Cannot include a '${e}' character in a manually specified \`to.${A}\` field [${JSON.stringify(i)}].  Please separate it out to the \`to.${t}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function WNA(e){return e.filter((A,t)=>t===0||A.route.path&&A.route.path.length>0)}function Zj(e){let A=WNA(e);return A.map((t,i)=>i===A.length-1?t.pathname:t.pathnameBase)}function Wj(e,A,t,i=!1){let n;typeof e=="string"?n=lw(e):(n={...e},Qo(!n.pathname||!n.pathname.includes("?"),zq("?","pathname","search",n)),Qo(!n.pathname||!n.pathname.includes("#"),zq("#","pathname","hash",n)),Qo(!n.search||!n.search.includes("#"),zq("#","search","hash",n)));let g=e===""||n.pathname==="",o=g?"/":n.pathname,s;if(o==null)s=t;else{let c=A.length-1;if(!i&&o.startsWith("..")){let l=o.split("/");for(;l[0]==="..";)l.shift(),c-=1;n.pathname=l.join("/")}s=c>=0?A[c]:"/"}let a=zNA(n,s),r=o&&o!=="/"&&o.endsWith("/"),I=(g||o===".")&&t.endsWith("/");return!a.pathname.endsWith("/")&&(r||I)&&(a.pathname+="/"),a}var vE=e=>e.join("/").replace(/\/\/+/g,"/"),VNA=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),XNA=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,$NA=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function ARA(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}var UCA=["POST","PUT","PATCH","DELETE"];new Set(UCA);var eRA=["GET",...UCA];new Set(eRA);var Bw=E.createContext(null);Bw.displayName="DataRouter";var CL=E.createContext(null);CL.displayName="DataRouterState";E.createContext(!1);var vCA=E.createContext({isTransitioning:!1});vCA.displayName="ViewTransition";var tRA=E.createContext(new Map);tRA.displayName="Fetchers";var iRA=E.createContext(null);iRA.displayName="Await";var gl=E.createContext(null);gl.displayName="Navigation";var wR=E.createContext(null);wR.displayName="Location";var cc=E.createContext({outlet:null,matches:[],isDataRoute:!1});cc.displayName="Route";var Vj=E.createContext(null);Vj.displayName="RouteError";function nRA(e,{relative:A}={}){Qo(Ew(),"useHref() may be used only in the context of a <Router> component.");let{basename:t,navigator:i}=E.useContext(gl),{hash:n,pathname:g,search:o}=kR(e,{relative:A}),s=g;return t!=="/"&&(s=g==="/"?t:vE([t,g])),i.createHref({pathname:s,search:o,hash:n})}function Ew(){return E.useContext(wR)!=null}function ks(){return Qo(Ew(),"useLocation() may be used only in the context of a <Router> component."),E.useContext(wR).location}var KCA="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function FCA(e){E.useContext(gl).static||E.useLayoutEffect(e)}function qi(){let{isDataRoute:e}=E.useContext(cc);return e?hRA():gRA()}function gRA(){Qo(Ew(),"useNavigate() may be used only in the context of a <Router> component.");let e=E.useContext(Bw),{basename:A,navigator:t}=E.useContext(gl),{matches:i}=E.useContext(cc),{pathname:n}=ks(),g=JSON.stringify(Zj(i)),o=E.useRef(!1);return FCA(()=>{o.current=!0}),E.useCallback((a,r={})=>{if(gc(o.current,KCA),!o.current)return;if(typeof a=="number"){t.go(a);return}let I=Wj(a,JSON.parse(g),n,r.relative==="path");e==null&&A!=="/"&&(I.pathname=I.pathname==="/"?A:vE([A,I.pathname])),(r.replace?t.replace:t.push)(I,r.state,r)},[A,t,g,n,e])}var oRA=E.createContext(null);function sRA(e){let A=E.useContext(cc).outlet;return A&&E.createElement(oRA.Provider,{value:e},A)}function Qw(){let{matches:e}=E.useContext(cc),A=e[e.length-1];return A?A.params:{}}function kR(e,{relative:A}={}){let{matches:t}=E.useContext(cc),{pathname:i}=ks(),n=JSON.stringify(Zj(t));return E.useMemo(()=>Wj(e,JSON.parse(n),i,A==="path"),[e,n,i,A])}function aRA(e,A){return _CA(e,A)}function _CA(e,A,t,i){var p;Qo(Ew(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:n}=E.useContext(gl),{matches:g}=E.useContext(cc),o=g[g.length-1],s=o?o.params:{},a=o?o.pathname:"/",r=o?o.pathnameBase:"/",I=o&&o.route;{let y=I&&I.path||"";JCA(a,!I||y.endsWith("*")||y.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${a}" (under <Route path="${y}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.

Please change the parent <Route path="${y}"> to <Route path="${y==="/"?"*":`${y}/*`}">.`)}let c=ks(),l;if(A){let y=typeof A=="string"?lw(A):A;Qo(r==="/"||((p=y.pathname)==null?void 0:p.startsWith(r)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${r}" but pathname "${y.pathname}" was given in the \`location\` prop.`),l=y}else l=c;let B=l.pathname||"/",Q=B;if(r!=="/"){let y=r.replace(/^\//,"").split("/");Q="/"+B.replace(/^\//,"").split("/").slice(y.length).join("/")}let h=RCA(e,{pathname:Q});gc(I||h!=null,`No routes matched location "${l.pathname}${l.search}${l.hash}" `),gc(h==null||h[h.length-1].route.element!==void 0||h[h.length-1].route.Component!==void 0||h[h.length-1].route.lazy!==void 0,`Matched leaf route at location "${l.pathname}${l.search}${l.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let d=lRA(h&&h.map(y=>Object.assign({},y,{params:Object.assign({},s,y.params),pathname:vE([r,n.encodeLocation?n.encodeLocation(y.pathname).pathname:y.pathname]),pathnameBase:y.pathnameBase==="/"?r:vE([r,n.encodeLocation?n.encodeLocation(y.pathnameBase).pathname:y.pathnameBase])})),g,t,i);return A&&d?E.createElement(wR.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...l},navigationType:"POP"}},d):d}function rRA(){let e=dRA(),A=ARA(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),t=e instanceof Error?e.stack:null,i="rgba(200,200,200, 0.5)",n={padding:"0.5rem",backgroundColor:i},g={padding:"2px 4px",backgroundColor:i},o=null;return console.error("Error handled by React Router default ErrorBoundary:",e),o=E.createElement(E.Fragment,null,E.createElement("p",null,"💿 Hey developer 👋"),E.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",E.createElement("code",{style:g},"ErrorBoundary")," or"," ",E.createElement("code",{style:g},"errorElement")," prop on your route.")),E.createElement(E.Fragment,null,E.createElement("h2",null,"Unexpected Application Error!"),E.createElement("h3",{style:{fontStyle:"italic"}},A),t?E.createElement("pre",{style:n},t):null,o)}var IRA=E.createElement(rRA,null),CRA=class extends E.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,A){return A.location!==e.location||A.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:A.error,location:A.location,revalidation:e.revalidation||A.revalidation}}componentDidCatch(e,A){console.error("React Router caught the following error during render",e,A)}render(){return this.state.error!==void 0?E.createElement(cc.Provider,{value:this.props.routeContext},E.createElement(Vj.Provider,{value:this.state.error,children:this.props.component})):this.props.children}};function cRA({routeContext:e,match:A,children:t}){let i=E.useContext(Bw);return i&&i.static&&i.staticContext&&(A.route.errorElement||A.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=A.route.id),E.createElement(cc.Provider,{value:e},t)}function lRA(e,A=[],t=null,i=null){if(e==null){if(!t)return null;if(t.errors)e=t.matches;else if(A.length===0&&!t.initialized&&t.matches.length>0)e=t.matches;else return null}let n=e,g=t==null?void 0:t.errors;if(g!=null){let a=n.findIndex(r=>r.route.id&&(g==null?void 0:g[r.route.id])!==void 0);Qo(a>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(g).join(",")}`),n=n.slice(0,Math.min(n.length,a+1))}let o=!1,s=-1;if(t)for(let a=0;a<n.length;a++){let r=n[a];if((r.route.HydrateFallback||r.route.hydrateFallbackElement)&&(s=a),r.route.id){let{loaderData:I,errors:c}=t,l=r.route.loader&&!I.hasOwnProperty(r.route.id)&&(!c||c[r.route.id]===void 0);if(r.route.lazy||l){o=!0,s>=0?n=n.slice(0,s+1):n=[n[0]];break}}}return n.reduceRight((a,r,I)=>{let c,l=!1,B=null,Q=null;t&&(c=g&&r.route.id?g[r.route.id]:void 0,B=r.route.errorElement||IRA,o&&(s<0&&I===0?(JCA("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),l=!0,Q=null):s===I&&(l=!0,Q=r.route.hydrateFallbackElement||null)));let h=A.concat(n.slice(0,I+1)),d=()=>{let p;return c?p=B:l?p=Q:r.route.Component?p=E.createElement(r.route.Component,null):r.route.element?p=r.route.element:p=a,E.createElement(cRA,{match:r,routeContext:{outlet:a,matches:h,isDataRoute:t!=null},children:p})};return t&&(r.route.ErrorBoundary||r.route.errorElement||I===0)?E.createElement(CRA,{location:t.location,revalidation:t.revalidation,component:B,error:c,children:d(),routeContext:{outlet:null,matches:h,isDataRoute:!0}}):d()},null)}function Xj(e){return`${e} must be used within a data router.  See https://reactrouter.com/en/main/routers/picking-a-router.`}function BRA(e){let A=E.useContext(Bw);return Qo(A,Xj(e)),A}function ERA(e){let A=E.useContext(CL);return Qo(A,Xj(e)),A}function QRA(e){let A=E.useContext(cc);return Qo(A,Xj(e)),A}function $j(e){let A=QRA(e),t=A.matches[A.matches.length-1];return Qo(t.route.id,`${e} can only be used on routes that contain a unique "id"`),t.route.id}function uRA(){return $j("useRouteId")}function dRA(){var i;let e=E.useContext(Vj),A=ERA("useRouteError"),t=$j("useRouteError");return e!==void 0?e:(i=A.errors)==null?void 0:i[t]}function hRA(){let{router:e}=BRA("useNavigate"),A=$j("useNavigate"),t=E.useRef(!1);return FCA(()=>{t.current=!0}),E.useCallback(async(n,g={})=>{gc(t.current,KCA),t.current&&(typeof n=="number"?e.navigate(n):await e.navigate(n,{fromRouteId:A,...g}))},[e,A])}var Q6={};function JCA(e,A,t){!A&&!Q6[e]&&(Q6[e]=!0,gc(!1,t))}E.memo(pRA);function pRA({routes:e,future:A,state:t}){return _CA(e,void 0,t,A)}function Tg({to:e,replace:A,state:t,relative:i}){Qo(Ew(),"<Navigate> may be used only in the context of a <Router> component.");let{static:n}=E.useContext(gl);gc(!n,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:g}=E.useContext(cc),{pathname:o}=ks(),s=qi(),a=Wj(e,Zj(g),o,i==="path"),r=JSON.stringify(a);return E.useEffect(()=>{s(JSON.parse(r),{replace:A,state:t,relative:i})},[s,r,i,A,t]),null}function LCA(e){return sRA(e.context)}function fe(e){Qo(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function fRA({basename:e="/",children:A=null,location:t,navigationType:i="POP",navigator:n,static:g=!1}){Qo(!Ew(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let o=e.replace(/^\/*/,"/"),s=E.useMemo(()=>({basename:o,navigator:n,static:g,future:{}}),[o,n,g]);typeof t=="string"&&(t=lw(t));let{pathname:a="/",search:r="",hash:I="",state:c=null,key:l="default"}=t,B=E.useMemo(()=>{let Q=ZE(a,o);return Q==null?null:{location:{pathname:Q,search:r,hash:I,state:c,key:l},navigationType:i}},[o,a,r,I,c,l,i]);return gc(B!=null,`<Router basename="${o}"> is not able to match the URL "${a}${r}${I}" because it does not start with the basename, so the <Router> won't render anything.`),B==null?null:E.createElement(gl.Provider,{value:s},E.createElement(wR.Provider,{children:A,value:B}))}function Uf({children:e,location:A}){return aRA(TP(e),A)}function TP(e,A=[]){let t=[];return E.Children.forEach(e,(i,n)=>{if(!E.isValidElement(i))return;let g=[...A,n];if(i.type===E.Fragment){t.push.apply(t,TP(i.props.children,g));return}Qo(i.type===fe,`[${typeof i.type=="string"?i.type:i.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Qo(!i.props.index||!i.props.children,"An index route cannot have child routes.");let o={id:i.props.id||g.join("-"),caseSensitive:i.props.caseSensitive,element:i.props.element,Component:i.props.Component,index:i.props.index,path:i.props.path,loader:i.props.loader,action:i.props.action,hydrateFallbackElement:i.props.hydrateFallbackElement,HydrateFallback:i.props.HydrateFallback,errorElement:i.props.errorElement,ErrorBoundary:i.props.ErrorBoundary,hasErrorBoundary:i.props.hasErrorBoundary===!0||i.props.ErrorBoundary!=null||i.props.errorElement!=null,shouldRevalidate:i.props.shouldRevalidate,handle:i.props.handle,lazy:i.props.lazy};i.props.children&&(o.children=TP(i.props.children,g)),t.push(o)}),t}var Xv="get",$v="application/x-www-form-urlencoded";function cL(e){return e!=null&&typeof e.tagName=="string"}function yRA(e){return cL(e)&&e.tagName.toLowerCase()==="button"}function DRA(e){return cL(e)&&e.tagName.toLowerCase()==="form"}function mRA(e){return cL(e)&&e.tagName.toLowerCase()==="input"}function SRA(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function wRA(e,A){return e.button===0&&(!A||A==="_self")&&!SRA(e)}function qP(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((A,t)=>{let i=e[t];return A.concat(Array.isArray(i)?i.map(n=>[t,n]):[[t,i]])},[]))}function kRA(e,A){let t=qP(e);return A&&A.forEach((i,n)=>{t.has(n)||A.getAll(n).forEach(g=>{t.append(n,g)})}),t}var cb=null;function MRA(){if(cb===null)try{new FormData(document.createElement("form"),0),cb=!1}catch{cb=!0}return cb}var NRA=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Zq(e){return e!=null&&!NRA.has(e)?(gc(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${$v}"`),null):e}function RRA(e,A){let t,i,n,g,o;if(DRA(e)){let s=e.getAttribute("action");i=s?ZE(s,A):null,t=e.getAttribute("method")||Xv,n=Zq(e.getAttribute("enctype"))||$v,g=new FormData(e)}else if(yRA(e)||mRA(e)&&(e.type==="submit"||e.type==="image")){let s=e.form;if(s==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let a=e.getAttribute("formaction")||s.getAttribute("action");if(i=a?ZE(a,A):null,t=e.getAttribute("formmethod")||s.getAttribute("method")||Xv,n=Zq(e.getAttribute("formenctype"))||Zq(s.getAttribute("enctype"))||$v,g=new FormData(s,e),!MRA()){let{name:r,type:I,value:c}=e;if(I==="image"){let l=r?`${r}.`:"";g.append(`${l}x`,"0"),g.append(`${l}y`,"0")}else r&&g.append(r,c)}}else{if(cL(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');t=Xv,i=null,n=$v,o=e}return g&&n==="text/plain"&&(o=g,g=void 0),{action:i,method:t.toLowerCase(),encType:n,formData:g,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function A8(e,A){if(e===!1||e===null||typeof e>"u")throw new Error(A)}function GRA(e,A,t){let i=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return i.pathname==="/"?i.pathname=`_root.${t}`:A&&ZE(i.pathname,A)==="/"?i.pathname=`${A.replace(/\/$/,"")}/_root.${t}`:i.pathname=`${i.pathname.replace(/\/$/,"")}.${t}`,i}async function bRA(e,A){if(e.id in A)return A[e.id];try{let t=await import(e.module);return A[e.id]=t,t}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function URA(e){return e==null?!1:e.href==null?e.rel==="preload"&&typeof e.imageSrcSet=="string"&&typeof e.imageSizes=="string":typeof e.rel=="string"&&typeof e.href=="string"}async function vRA(e,A,t){let i=await Promise.all(e.map(async n=>{let g=A.routes[n.route.id];if(g){let o=await bRA(g,t);return o.links?o.links():[]}return[]}));return JRA(i.flat(1).filter(URA).filter(n=>n.rel==="stylesheet"||n.rel==="preload").map(n=>n.rel==="stylesheet"?{...n,rel:"prefetch",as:"style"}:{...n,rel:"prefetch"}))}function u6(e,A,t,i,n,g){let o=(a,r)=>t[r]?a.route.id!==t[r].route.id:!0,s=(a,r)=>{var I;return t[r].pathname!==a.pathname||((I=t[r].route.path)==null?void 0:I.endsWith("*"))&&t[r].params["*"]!==a.params["*"]};return g==="assets"?A.filter((a,r)=>o(a,r)||s(a,r)):g==="data"?A.filter((a,r)=>{var c;let I=i.routes[a.route.id];if(!I||!I.hasLoader)return!1;if(o(a,r)||s(a,r))return!0;if(a.route.shouldRevalidate){let l=a.route.shouldRevalidate({currentUrl:new URL(n.pathname+n.search+n.hash,window.origin),currentParams:((c=t[0])==null?void 0:c.params)||{},nextUrl:new URL(e,window.origin),nextParams:a.params,defaultShouldRevalidate:!0});if(typeof l=="boolean")return l}return!0}):[]}function KRA(e,A,{includeHydrateFallback:t}={}){return FRA(e.map(i=>{let n=A.routes[i.route.id];if(!n)return[];let g=[n.module];return n.clientActionModule&&(g=g.concat(n.clientActionModule)),n.clientLoaderModule&&(g=g.concat(n.clientLoaderModule)),t&&n.hydrateFallbackModule&&(g=g.concat(n.hydrateFallbackModule)),n.imports&&(g=g.concat(n.imports)),g}).flat(1))}function FRA(e){return[...new Set(e)]}function _RA(e){let A={},t=Object.keys(e).sort();for(let i of t)A[i]=e[i];return A}function JRA(e,A){let t=new Set;return new Set(A),e.reduce((i,n)=>{let g=JSON.stringify(_RA(n));return t.has(g)||(t.add(g),i.push({key:g,link:n})),i},[])}function xCA(){let e=E.useContext(Bw);return A8(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function LRA(){let e=E.useContext(CL);return A8(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}var e8=E.createContext(void 0);e8.displayName="FrameworkContext";function TCA(){let e=E.useContext(e8);return A8(e,"You must render this element inside a <HydratedRouter> element"),e}function xRA(e,A){let t=E.useContext(e8),[i,n]=E.useState(!1),[g,o]=E.useState(!1),{onFocus:s,onBlur:a,onMouseEnter:r,onMouseLeave:I,onTouchStart:c}=A,l=E.useRef(null);E.useEffect(()=>{if(e==="render"&&o(!0),e==="viewport"){let h=p=>{p.forEach(y=>{o(y.isIntersecting)})},d=new IntersectionObserver(h,{threshold:.5});return l.current&&d.observe(l.current),()=>{d.disconnect()}}},[e]),E.useEffect(()=>{if(i){let h=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(h)}}},[i]);let B=()=>{n(!0)},Q=()=>{n(!1),o(!1)};return t?e!=="intent"?[g,l,{}]:[g,l,{onFocus:d0(s,B),onBlur:d0(a,Q),onMouseEnter:d0(r,B),onMouseLeave:d0(I,Q),onTouchStart:d0(c,B)}]:[!1,l,{}]}function d0(e,A){return t=>{e&&e(t),t.defaultPrevented||A(t)}}function TRA({page:e,...A}){let{router:t}=xCA(),i=E.useMemo(()=>RCA(t.routes,e,t.basename),[t.routes,e,t.basename]);return i?E.createElement(YRA,{page:e,matches:i,...A}):null}function qRA(e){let{manifest:A,routeModules:t}=TCA(),[i,n]=E.useState([]);return E.useEffect(()=>{let g=!1;return vRA(e,A,t).then(o=>{g||n(o)}),()=>{g=!0}},[e,A,t]),i}function YRA({page:e,matches:A,...t}){let i=ks(),{manifest:n,routeModules:g}=TCA(),{basename:o}=xCA(),{loaderData:s,matches:a}=LRA(),r=E.useMemo(()=>u6(e,A,a,n,i,"data"),[e,A,a,n,i]),I=E.useMemo(()=>u6(e,A,a,n,i,"assets"),[e,A,a,n,i]),c=E.useMemo(()=>{if(e===i.pathname+i.search+i.hash)return[];let Q=new Set,h=!1;if(A.forEach(p=>{var m;let y=n.routes[p.route.id];!y||!y.hasLoader||(!r.some(D=>D.route.id===p.route.id)&&p.route.id in s&&((m=g[p.route.id])!=null&&m.shouldRevalidate)||y.hasClientLoader?h=!0:Q.add(p.route.id))}),Q.size===0)return[];let d=GRA(e,o,"data");return h&&Q.size>0&&d.searchParams.set("_routes",A.filter(p=>Q.has(p.route.id)).map(p=>p.route.id).join(",")),[d.pathname+d.search]},[o,s,i,n,r,A,e,g]),l=E.useMemo(()=>KRA(I,n),[I,n]),B=qRA(I);return E.createElement(E.Fragment,null,c.map(Q=>E.createElement("link",{key:Q,rel:"prefetch",as:"fetch",href:Q,...t})),l.map(Q=>E.createElement("link",{key:Q,rel:"modulepreload",href:Q,...t})),B.map(({key:Q,link:h})=>E.createElement("link",{key:Q,nonce:t.nonce,...h})))}function HRA(...e){return A=>{e.forEach(t=>{typeof t=="function"?t(A):t!=null&&(t.current=A)})}}var qCA=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{qCA&&(window.__reactRouterVersion="7.8.0")}catch{}function ORA({basename:e,children:A,window:t}){let i=E.useRef();i.current==null&&(i.current=GNA({window:t,v5Compat:!0}));let n=i.current,[g,o]=E.useState({action:n.action,location:n.location}),s=E.useCallback(a=>{E.startTransition(()=>o(a))},[o]);return E.useLayoutEffect(()=>n.listen(s),[n,s]),E.createElement(fRA,{basename:e,children:A,location:g.location,navigationType:g.action,navigator:n})}var YCA=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,HI=E.forwardRef(function({onClick:A,discover:t="render",prefetch:i="none",relative:n,reloadDocument:g,replace:o,state:s,target:a,to:r,preventScrollReset:I,viewTransition:c,...l},B){let{basename:Q}=E.useContext(gl),h=typeof r=="string"&&YCA.test(r),d,p=!1;if(typeof r=="string"&&h&&(d=r,qCA))try{let M=new URL(window.location.href),w=r.startsWith("//")?new URL(M.protocol+r):new URL(r),b=ZE(w.pathname,Q);w.origin===M.origin&&b!=null?r=b+w.search+w.hash:p=!0}catch{gc(!1,`<Link to="${r}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}let y=nRA(r,{relative:n}),[m,D,S]=xRA(i,l),k=ZRA(r,{replace:o,state:s,target:a,preventScrollReset:I,relative:n,viewTransition:c});function N(M){A&&A(M),M.defaultPrevented||k(M)}let G=E.createElement("a",{...l,...S,href:d||y,onClick:p||g?A:N,ref:HRA(B,D),target:a,"data-discover":!h&&t==="render"?"true":void 0});return m&&!h?E.createElement(E.Fragment,null,G,E.createElement(TRA,{page:y})):G});HI.displayName="Link";var PRA=E.forwardRef(function({"aria-current":A="page",caseSensitive:t=!1,className:i="",end:n=!1,style:g,to:o,viewTransition:s,children:a,...r},I){let c=kR(o,{relative:r.relative}),l=ks(),B=E.useContext(CL),{navigator:Q,basename:h}=E.useContext(gl),d=B!=null&&AGA(c)&&s===!0,p=Q.encodeLocation?Q.encodeLocation(c).pathname:c.pathname,y=l.pathname,m=B&&B.navigation&&B.navigation.location?B.navigation.location.pathname:null;t||(y=y.toLowerCase(),m=m?m.toLowerCase():null,p=p.toLowerCase()),m&&h&&(m=ZE(m,h)||m);const D=p!=="/"&&p.endsWith("/")?p.length-1:p.length;let S=y===p||!n&&y.startsWith(p)&&y.charAt(D)==="/",k=m!=null&&(m===p||!n&&m.startsWith(p)&&m.charAt(p.length)==="/"),N={isActive:S,isPending:k,isTransitioning:d},G=S?A:void 0,M;typeof i=="function"?M=i(N):M=[i,S?"active":null,k?"pending":null,d?"transitioning":null].filter(Boolean).join(" ");let w=typeof g=="function"?g(N):g;return E.createElement(HI,{...r,"aria-current":G,className:M,ref:I,style:w,to:o,viewTransition:s},typeof a=="function"?a(N):a)});PRA.displayName="NavLink";var jRA=E.forwardRef(({discover:e="render",fetcherKey:A,navigate:t,reloadDocument:i,replace:n,state:g,method:o=Xv,action:s,onSubmit:a,relative:r,preventScrollReset:I,viewTransition:c,...l},B)=>{let Q=XRA(),h=$RA(s,{relative:r}),d=o.toLowerCase()==="get"?"get":"post",p=typeof s=="string"&&YCA.test(s),y=m=>{if(a&&a(m),m.defaultPrevented)return;m.preventDefault();let D=m.nativeEvent.submitter,S=(D==null?void 0:D.getAttribute("formmethod"))||o;Q(D||m.currentTarget,{fetcherKey:A,method:S,navigate:t,replace:n,state:g,relative:r,preventScrollReset:I,viewTransition:c})};return E.createElement("form",{ref:B,method:d,action:h,onSubmit:i?a:y,...l,"data-discover":!p&&e==="render"?"true":void 0})});jRA.displayName="Form";function zRA(e){return`${e} must be used within a data router.  See https://reactrouter.com/en/main/routers/picking-a-router.`}function HCA(e){let A=E.useContext(Bw);return Qo(A,zRA(e)),A}function ZRA(e,{target:A,replace:t,state:i,preventScrollReset:n,relative:g,viewTransition:o}={}){let s=qi(),a=ks(),r=kR(e,{relative:g});return E.useCallback(I=>{if(wRA(I,A)){I.preventDefault();let c=t!==void 0?t:jM(a)===jM(r);s(e,{replace:c,state:i,preventScrollReset:n,relative:g,viewTransition:o})}},[a,s,r,t,i,A,e,n,g,o])}function uw(e){gc(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let A=E.useRef(qP(e)),t=E.useRef(!1),i=ks(),n=E.useMemo(()=>kRA(i.search,t.current?null:A.current),[i.search]),g=qi(),o=E.useCallback((s,a)=>{const r=qP(typeof s=="function"?s(new URLSearchParams(n)):s);t.current=!0,g("?"+r,a)},[g,n]);return[n,o]}var WRA=0,VRA=()=>`__${String(++WRA)}__`;function XRA(){let{router:e}=HCA("useSubmit"),{basename:A}=E.useContext(gl),t=uRA();return E.useCallback(async(i,n={})=>{let{action:g,method:o,encType:s,formData:a,body:r}=RRA(i,A);if(n.navigate===!1){let I=n.fetcherKey||VRA();await e.fetch(I,t,n.action||g,{preventScrollReset:n.preventScrollReset,formData:a,body:r,formMethod:n.method||o,formEncType:n.encType||s,flushSync:n.flushSync})}else await e.navigate(n.action||g,{preventScrollReset:n.preventScrollReset,formData:a,body:r,formMethod:n.method||o,formEncType:n.encType||s,replace:n.replace,state:n.state,fromRouteId:t,flushSync:n.flushSync,viewTransition:n.viewTransition})},[e,A,t])}function $RA(e,{relative:A}={}){let{basename:t}=E.useContext(gl),i=E.useContext(cc);Qo(i,"useFormAction must be used inside a RouteContext");let[n]=i.matches.slice(-1),g={...kR(e||".",{relative:A})},o=ks();if(e==null){g.search=o.search;let s=new URLSearchParams(g.search),a=s.getAll("index");if(a.some(I=>I==="")){s.delete("index"),a.filter(c=>c).forEach(c=>s.append("index",c));let I=s.toString();g.search=I?`?${I}`:""}}return(!e||e===".")&&n.route.index&&(g.search=g.search?g.search.replace(/^\?/,"?index&"):"?index"),t!=="/"&&(g.pathname=g.pathname==="/"?t:vE([t,g.pathname])),jM(g)}function AGA(e,{relative:A}={}){let t=E.useContext(vCA);Qo(t!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=HCA("useViewTransitionState"),n=kR(e,{relative:A});if(!t.isTransitioning)return!1;let g=ZE(t.currentLocation.pathname,i)||t.currentLocation.pathname,o=ZE(t.nextLocation.pathname,i)||t.nextLocation.pathname;return pF(n.pathname,o)!=null||pF(n.pathname,g)!=null}const zM=md("SocialLogin",{web:()=>Qi(()=>import("./web-CCEu9YCM.js"),__vite__mapDeps([0,1])).then(e=>new e.SocialLoginWeb)}),eGA={SOCKET:{NEEDS_PREMIUM:"premium_membership_required"}},tGA=(()=>{var e;try{if(typeof window>"u")return!1;const A=(((e=window.location)==null?void 0:e.protocol)||"").toLowerCase();return A==="capacitor:"||A==="ionic:"}catch{return!1}})(),iGA=(()=>{var e;try{if(typeof window>"u")return!1;const A=((e=window.location)==null?void 0:e.hostname)||"";return A==="localhost"||A==="127.0.0.1"}catch{return!1}})();function nGA(){var e,A;try{const t=((e=window.localStorage)==null?void 0:e.getItem("api:url"))||((A=window.sessionStorage)==null?void 0:A.getItem("api:url"));if(t&&/^https?:\/\//i.test(t))return t.replace(/\/$/,"")}catch{}return null}const ZM=(()=>{const e=nGA();return e||(tGA?"https://dicelounge.app":iGA?"http://localhost:4000":"https://dicelounge.app")})(),gGA=globalThis==null?void 0:globalThis.APP_TARGET;var oaA,saA;const oGA=(saA=(oaA=globalThis==null?void 0:globalThis.process)==null?void 0:oaA.env)==null?void 0:saA.APP_TARGET;let YP;var aaA,raA;try{YP=(raA=(aaA=import.meta)==null?void 0:aaA.env)==null?void 0:raA.VITE_APP_TARGET}catch{YP=void 0}const sGA=gGA??oGA??YP,qs=sGA??"unified",Wq=qs==="ceelo",vp=qs==="craps",Kp=qs==="poker",MR=qs==="skills",Lc=qs==="zentara",Th=qs==="unified",aGA="rcb_eaWheJLZtWHJDCzyjruqCITeZlrK",d6={ceelo:"goog_TshzudibKBufFkwSWOodGwQAzMI",craps:"goog_FJlwnXjmdmVYKAbOkaiNyICWjkd",poker:"goog_AwODgwTGrKmYPFStHgslgZENzyG",unified:"goog_TshzudibKBufFkwSWOodGwQAzMI",skills:"goog_iGrdhumdjhzgNbIWxdHFjChutDX",zentara:"goog_BNlqWfFLFTMPnLmGhHhcfdOsACj"},rGA=d6[qs]??d6.ceelo,h6={ceelo:"appl_YhZbXhNlphlrxochELLsdNJajdp",craps:"appl_uCBrYNXSOUzHdUNnkbfMaNxBxXI",poker:"appl_SKqhTdSJqfYQQGUjeFYzVZoSBqA",skills:"appl_OSFruGMgnsBocgEzWxpUyLYtskV",zentara:"appl_mpxyEsCoRtxMImTCLdZVnAUhtpJ",unified:"appl_YhZbXhNlphlrxochELLsdNJajdp"},IGA=h6[qs]??h6.ceelo,CGA="false",lL="default",cGA="com.zentaraone.ceeloLounge.chips",BL=cGA,lGA="com.zentaraone.ceeloLounge.chips1000",BGA="com.zentaraone.crapsLounge.chips_1000",EGA="com.zentaraone.pokerLounge.chips_1000",EL=vp?BGA:Kp?EGA:lGA,QGA="",t8="Premium",uGA="AIzaSyCmll0lLOqadkCyjlrM-bb5H4n1L8eMxkE",dGA="dice-lounge.firebaseapp.com",hGA="dice-lounge",pGA="1:423374558927:web:283377221554368e57c9ba",fGA="G-MYPNJQR9RN",yGA="dicelounge.app",DGA="PEcc15f3HTqKKafnvHp1yRrbxrS8ji1kzZ4dyS4R+fI=",mGA="193765381581-rucls0d90bmpkqaj0ginhp87chgjq70j.apps.googleusercontent.com",NR="193765381581-s0a3p66cb39cdfum20jrm0d2e87jmlu8.apps.googleusercontent.com",SGA=NR,wGA=NR,kGA=NR,MGA=NR,NGA=vp?SGA:Kp?wGA:MR?kGA:Lc?MGA:NR,RGA="com.zentaraone.ceeloLounge.service",GGA="com.zentaraone.crapsLounge.service",bGA="com.zentaraone.pokerLounge.service",UGA="com.zentaraone.skillslounge.service",vGA="com.zentaraone.zentara.service",KGA=vp?GGA:Kp?bGA:MR?UGA:Lc?vGA:RGA,FGA="https://dicelounge.app/api/auth/apple/callback",_GA="com.zentaraone.ceeloLounge",JGA="com.zentaraone.crapsLounge",LGA="com.zentaraone.pokerLounge",xGA="com.zentaraone.skillslounge",TGA="com.zentaraone.zentara",qGA=vp?JGA:Kp?LGA:MR?xGA:Lc?TGA:_GA,p6={ceelo:"ca-app-pub-4219446894372985/2712849620",craps:"ca-app-pub-4219446894372985/4123145978",poker:"ca-app-pub-4219446894372985/6524920361",skills:"ca-app-pub-4219446894372985/7770618032",zentara:"ca-app-pub-4219446894372985/7146732580",unified:"ca-app-pub-4219446894372985/2712849620"},f6={ceelo:"ca-app-pub-4219446894372985/9898216833",craps:"ca-app-pub-4219446894372985/2585675356",poker:"ca-app-pub-4219446894372985/5810604494",skills:"ca-app-pub-4219446894372985/2727665607",zentara:"ca-app-pub-4219446894372985/4221411683",unified:"ca-app-pub-4219446894372985/9898216833"},YGA=p6[qs]??p6.ceelo,y6=f6[qs]??f6.ceelo,D6={ceelo:"ca-app-pub-4219446894372985/3451216225",craps:"ca-app-pub-4219446894372985/9366706127",poker:"ca-app-pub-4219446894372985/4109691778",skills:"ca-app-pub-4219446894372985/6006474652",zentara:"ca-app-pub-4219446894372985/9288049883",unified:"ca-app-pub-4219446894372985/3451216225"},m6={ceelo:"ca-app-pub-4219446894372985/2394103660",craps:"ca-app-pub-4219446894372985/5020267007",poker:"ca-app-pub-4219446894372985/8389694041",skills:"ca-app-pub-4219446894372985/2073059481",zentara:"ca-app-pub-4219446894372985/1647101696",unified:"ca-app-pub-4219446894372985/2394103660"},HGA=D6[qs]??D6.ceelo,S6=m6[qs]??m6.ceelo,jQ=100,w6=30,OCA=3,PCA=3,jCA=40,qh=6e4,GD=800,OGA=!1,QL=md("SecureStoragePlugin",{web:()=>Qi(()=>import("./web-BaBzFDrr.js"),__vite__mapDeps([2,1])).then(e=>new e.SecureStoragePluginWeb)}),PGA=Object.freeze(Object.defineProperty({__proto__:null,SecureStoragePlugin:QL},Symbol.toStringTag,{value:"Module"})),Ia=md("Preferences",{web:()=>Qi(()=>import("./web-68rtgo36.js"),__vite__mapDeps([3,1])).then(e=>new e.PreferencesWeb)}),Oc=Object.freeze(Object.defineProperty({__proto__:null,Preferences:Ia},Symbol.toStringTag,{value:"Module"})),lb="sess:";async function k6(e){const{value:A}=await Ia.get({key:e});return A??null}async function M6(e,A){await Ia.set({key:e,value:A})}async function Vq(e){await Ia.remove({key:e})}const Wc={async get(e){return k6(e)},async set(e,A){await M6(e,A)},async remove(e){await Vq(e)},async setSession(e,A){await M6(lb+e,A)},async getSession(e){return k6(lb+e)},async removeSession(e){return Vq(lb+e)},async clearSessionKeys(){var e;try{const t=((e=(await Ia.keys()).keys)==null?void 0:e.filter(i=>i.startsWith(lb)))||[];await Promise.all(t.map(i=>Vq(i)))}catch{}}};async function dS(e){try{const A=await Wc.getSession(e);return A?JSON.parse(A):null}catch{return null}}async function uL(e,A){try{await Wc.setSession(e,JSON.stringify(A))}catch{}}async function hS(e){try{await Wc.removeSession(e)}catch{}}const pS="session_token",i8=Ui.isNativePlatform();async function ef(e){i8?await QL.set({key:pS,value:e}):await Wc.setSession(pS,e)}async function uo(){if(i8)try{const{value:A}=await QL.get({key:pS});return A||void 0}catch{return}return await Wc.getSession(pS)||void 0}async function kd(){if(i8)try{await QL.remove({key:pS})}catch{}else await Wc.removeSession(pS)}const jGA=Object.freeze(Object.defineProperty({__proto__:null,clearToken:kd,getToken:uo,setToken:ef},Symbol.toStringTag,{value:"Module"})),Ky={done:!1};function N6(e){if(!e)return"";const A=String(e);return A.length<=12?A:`${A.slice(0,6)}…${A.slice(-6)}`}function fr(e,A){try{console.log(`[NativeAuth] ${e}`,A??"")}catch{}}async function zGA(){const e=Ui.getPlatform(),A={mode:"online"},t=mGA,i=NGA;A.clientId=t,A.webClientId=t,A.mode="online",A.iOSClientId=i;const n={mode:"online"},g=e==="ios"?qGA:KGA,o=FGA;n.clientId=g,e!=="ios"&&o&&(n.redirectUrl=o),fr("initialize",{platform:e,hasIOS:!0,googleKeys:Object.keys(A),ids:{web:N6(t),iOS:N6(i)},apple:!0}),await zM.initialize({...Object.keys(A).length?{google:A}:{},...Object.keys(n).length?{apple:n}:{}})}async function fS(e=!1){if(!(!e&&Ky.done)){if(!e&&Ky.promise)return Ky.promise;Ky.promise=zGA().then(()=>{Ky.done=!0}).catch(A=>{throw Ky.promise=void 0,console.warn("[NativeAuth] SocialLogin initialize failed; will retry on next attempt",A),A})}}async function zCA(){try{await fS()}catch(e){fr("prewarm:err",String(e))}}function ZGA(){var e,A;try{const t=Ui.getPlatform();if(t==="ios"||t==="android")return!0;const i=typeof window<"u"?window:{};return(e=i.Capacitor)!=null&&e.isNativePlatform?!!i.Capacitor.isNativePlatform:!!((A=i.webkit)!=null&&A.messageHandlers)}catch{return!1}}async function WGA(){var r,I,c,l,B,Q,h;await fS(!0),fr("apple:login:start");const A=Ui.getPlatform()==="android"?{}:{scopes:["email","name"]},t=await zM.login({provider:"apple",options:A}),i=(r=t==null?void 0:t.result)==null?void 0:r.idToken,n=(I=t==null?void 0:t.result)==null?void 0:I.profile,g=(n==null?void 0:n.email)||void 0,o=(n==null?void 0:n.givenName)||((l=(c=n==null?void 0:n.name)==null?void 0:c.split(" "))==null?void 0:l[0]),s=(n==null?void 0:n.familyName)||((h=(Q=(B=n==null?void 0:n.name)==null?void 0:B.split(" "))==null?void 0:Q.slice(1))==null?void 0:h.join(" ")),a=[o,s].filter(Boolean).join(" ").trim()||(n==null?void 0:n.name)||void 0;if(fr("apple:login:result",{hasIdToken:!!i,hasEmail:!!g}),!i)throw new Error("Apple did not return an id token");return{provider:"apple",idToken:i,email:g,name:a}}async function VGA(){var e,A,t,i;await fS(!0);try{fr("google:login:start");const g=Ui.getPlatform()==="android"?{}:{scopes:["email","profile"]},o=await zM.login({provider:"google",options:g});fr("google:login:response",{hasResult:!!(o!=null&&o.result),keys:o&&typeof o=="object"?Object.keys(o):[],resultKeys:o!=null&&o.result?Object.keys(o.result):[]});const s=(e=o==null?void 0:o.result)==null?void 0:e.idToken,a=(A=o==null?void 0:o.result)==null?void 0:A.profile,r=(a==null?void 0:a.email)||void 0,I=(a==null?void 0:a.name)||[a==null?void 0:a.givenName,a==null?void 0:a.familyName].filter(Boolean).join(" ").trim()||void 0;if(fr("google:login:result",{hasIdToken:!!s,hasProfile:!!a,hasEmail:!!r}),!s)throw new Error("Google did not return an id token");return{provider:"google",idToken:s,email:r,name:I}}catch(n){const g=n,o={type:Object.prototype.toString.call(g),message:g==null?void 0:g.message,name:g==null?void 0:g.name,code:g==null?void 0:g.code,status:g==null?void 0:g.status,keys:g&&typeof g=="object"?Object.keys(g):[],raw:g};fr("google:login:err",o);const s=String((g==null?void 0:g.message)||"").toLowerCase();if(s.includes("developer console")||s.includes("config")||s.includes("clientid")||(g==null?void 0:g.code)===28444)try{fr("google:login:err:attempt-reinit"),await fS(!0);const a=Ui.getPlatform(),r=await zM.login({provider:"google",options:a==="android"?{}:{scopes:["email","profile"]}});fr("google:login:retry:response",{hasResult:!!(r!=null&&r.result)});const I=(t=r==null?void 0:r.result)==null?void 0:t.idToken,c=(i=r==null?void 0:r.result)==null?void 0:i.profile,l=(c==null?void 0:c.email)||void 0,B=(c==null?void 0:c.name)||[c==null?void 0:c.givenName,c==null?void 0:c.familyName].filter(Boolean).join(" ").trim()||void 0;if(!I)throw new Error("Google did not return an id token (retry)");return{provider:"google",idToken:I,email:l,name:B}}catch(a){fr("google:login:err:reinit-failed",String(a))}throw g}}async function XGA(e,A){try{await fS()}catch{}try{await zM.logout({provider:e}),fr("signOut",{provider:e,ok:!0})}catch(t){fr("signOut:err",String(t))}try{await new Promise(t=>setTimeout(t,120)),await fS(!0),fr("signOut:reinit:ok")}catch(t){fr("signOut:reinit:err",String(t))}if((A==null?void 0:A.clearLocal)!==!1)try{await kd()}catch{}}const fm={isNativePlatform:ZGA,signInWithAppleNative:WGA,signInWithGoogleNative:VGA,signOut:XGA,prewarmNativeAuth:zCA};let fl;function $GA(){var e,A;try{const t=(A=(e=Ui)==null?void 0:e.getPlatform)==null?void 0:A.call(e);if(t)return t==="android"}catch{}try{return typeof navigator<"u"&&/Android/i.test(navigator.userAgent)}catch{return!1}}function AbA(){var e,A;try{const t=(A=(e=Ui)==null?void 0:e.getPlatform)==null?void 0:A.call(e);if(t)return t==="ios"}catch{}try{return typeof navigator<"u"&&/iPhone|iPad|iPod/i.test(navigator.userAgent)}catch{return!1}}function ebA(){var e,A,t,i;try{const n=(A=(e=Ui)==null?void 0:e.getPlatform)==null?void 0:A.call(e);return n&&["ios","android"].includes(n)?!0:!!((i=(t=window.Capacitor)==null?void 0:t.isNativePlatform)!=null&&i.call(t))}catch{return!1}}function tbA(){var e,A;try{const t=((e=window.localStorage)==null?void 0:e.getItem("api:url"))||((A=window.sessionStorage)==null?void 0:A.getItem("api:url"));if(t&&/^https?:\/\//i.test(t))return t.replace(/\/+$/,"")}catch{}return null}function Ca(){var g;if(fl)return fl;const e=$GA(),A=AbA(),t=ebA();if(e||A&&t)return fl="https://dicelounge.app",fl;let i=null;if(!e&&!(A&&t)&&(i=tbA()),i)return fl=i,fl;let n=!1;try{const o=(g=window.location)==null?void 0:g.hostname;n=o==="localhost"||o==="127.0.0.1"}catch{}return n&&!(A&&t)?(fl="http://localhost:4000",fl):(fl="https://dicelounge.app",fl)}const Tu=Ca();let Yh=null,bD=0,UD=null;const ibA=1e4;async function dL(e){const A=(e==null?void 0:e.force)===!0,t=e==null?void 0:e.signal;return!A&&Yh&&Date.now()-bD<ibA?Yh:!A&&UD?UD:(UD=(async()=>{var g,o;try{let s=!1;try{s=!!((g=fm.isNativePlatform)!=null&&g.call(fm))}catch{s=!1}let a=null;try{a=await uo()??null}catch{a=null}if(!A&&!a&&s)return null;const r=!!a,I={Accept:"application/json"};r&&a&&(I.Authorization=`Bearer ${a}`);const c=await fetch(`${Tu}/api/auth/me`,{credentials:"include",headers:I,signal:t});if(c.ok){const l=await c.json();if(Yh=l,bD=Date.now(),(o=l==null?void 0:l.dailyGrant)!=null&&o.granted&&l.dailyGrant.amount)try{window.dispatchEvent(new CustomEvent("daily-grant",{detail:{amount:l.dailyGrant.amount}}))}catch{}return l}if(c.status===204)return Yh=null,bD=Date.now(),null;if(c.status===401){if(!r&&a){const l=await fetch(`${Tu}/api/auth/me`,{credentials:"include",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:t});if(l.ok){const B=await l.json();return Yh=B,bD=Date.now(),B}if(l.status===401)try{await kd()}catch{}}return Yh=null,bD=Date.now(),null}return null}catch(s){return(s==null?void 0:s.name)==="AbortError",null}})().finally(()=>{UD=null}),await UD)}async function ZCA(e){let A=null;try{A=await uo()??null}catch{A=null}try{await fetch(`${Tu}/api/auth/logout`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json",...A?{Authorization:`Bearer ${A}`}:{}},body:JSON.stringify({email:e})})}catch{}try{await kd()}catch{}try{Yh=null,bD=0,UD=null}catch{}}async function nbA(e){const t=await(await fetch(`${Tu}/api/auth/verify-app?token=${encodeURIComponent(e)}`,{method:"GET",credentials:"include"})).json().catch(()=>({}));try{if(t&&(t.success||t.ok||t.token)){const{clearInviter:i}=await Qi(async()=>{const{clearInviter:n}=await Promise.resolve().then(()=>Kke);return{clearInviter:n}},void 0);i()}}catch{}return t}async function gbA(e){try{if(fm.isNativePlatform())throw console.warn("[AuthServices] startOAuth called on native; blocking"),new Error("startOAuth is not allowed on native")}catch{}try{const A=await fetch(`${Tu}/api/auth/${e}`,{method:"POST",headers:{Accept:"application/json"},credentials:"include"});if(A.ok){const t=await A.json().catch(()=>({ok:!1}));if(t!=null&&t.ok&&(t!=null&&t.url))return window.location.assign(t.url),{ok:!0,url:t.url}}return window.location.assign(`${Tu}/api/auth/${e}`),{ok:!1}}catch{try{window.location.assign(`${Tu}/api/auth/${e}`)}catch{}return{ok:!1}}}async function obA(){try{const e=await fetch(`${Tu}/api/auth/guest`,{method:"POST",headers:{Accept:"application/json"},credentials:"include"});if(!e.ok)return{ok:!1};const A=await e.json().catch(()=>({ok:!1}));return{ok:!!(A!=null&&A.ok),token:A==null?void 0:A.token}}catch{return{ok:!1}}}var sbA={};let Xq=!1,yS=null,Fy=null;function abA(){return{apiKey:uGA,authDomain:dGA,projectId:hGA,appId:pGA,measurementId:fGA}}function Zk(){return typeof window<"u"&&typeof document<"u"}function WCA(){if(!Zk())return!1;if(Fy!==null)return Fy;try{const e=new URL(window.location.href);if(e.searchParams.has("debug_analytics")||e.searchParams.has("firebase_analytics_debug_mode")||window.localStorage.getItem("analytics:debug")==="1")return Fy=!0}catch{}return Fy=!1}function Wk(...e){WCA()&&console.info("[analytics]",...e)}async function n8(){if(Xq||!Zk())return;try{if(typeof navigator<"u"&&/jsdom|playwright/i.test(navigator.userAgent||"")||typeof window<"u"&&window.__E2E===!0||typeof process<"u"&&(sbA.VITEST||!1)){Xq=!0,Wk("skip:init (test env heuristic)");return}}catch{}const e=abA();try{const[{initializeApp:A},{getAnalytics:t}]=await Promise.all([Qi(()=>import("./index.esm-Ct10TrAh.js"),__vite__mapDeps([4,5])),Qi(()=>import("./index.esm-0EJQLKq6.js"),__vite__mapDeps([6,5,7]))]),i=A({apiKey:e.apiKey,authDomain:e.authDomain,projectId:e.projectId,appId:e.appId,measurementId:e.measurementId});yS=t(i),Wk("init:ok",{measurementId:e.measurementId})}catch(A){yS=null,Wk("init:fail",{error:(A==null?void 0:A.message)||String(A)})}finally{Xq=!0}}function tf(e,A){if(yS)try{Qi(async()=>{const{logEvent:t}=await import("./index.esm-0EJQLKq6.js");return{logEvent:t}},__vite__mapDeps([6,5,7])).then(({logEvent:t})=>{const i=A||{};WCA()&&(i.debug_mode=!0);try{t(yS,e,i),Wk("event",{eventName:e,params:i})}catch{}})}catch{}}function CI(e,A){const t=Zk()?window.location.href:void 0,i=e??(Zk()?window.location.pathname:void 0),n=Zk()?document.title:void 0;tf("page_view",{page_location:t,page_path:i,page_title:n})}function $q(e){!yS||!e||Qi(async()=>{const{setUserId:A}=await import("./index.esm-0EJQLKq6.js");return{setUserId:A}},__vite__mapDeps([6,5,7])).then(({setUserId:A})=>{try{A(yS,e)}catch{}Wk("userId:set",{userId:e})})}async function rbA(e){const A=new Set([]);try{await Ia.clear()}catch{}try{if(typeof window<"u"){try{const t={};if(A.size>0)for(let i=0;i<window.localStorage.length;i++){const n=window.localStorage.key(i);n&&A.has(n)&&(t[n]=window.localStorage.getItem(n))}if(window.localStorage.clear(),A.size>0)for(const i of Object.keys(t)){const n=t[i];n!=null&&window.localStorage.setItem(i,n)}}catch{}try{window.sessionStorage.clear()}catch{}}}catch{}}const dB=Object.create(null);dB.open="0";dB.close="1";dB.ping="2";dB.pong="3";dB.message="4";dB.upgrade="5";dB.noop="6";const AK=Object.create(null);Object.keys(dB).forEach(e=>{AK[dB[e]]=e});const HP={type:"error",data:"parser error"},VCA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",XCA=typeof ArrayBuffer=="function",$CA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,g8=({type:e,data:A},t,i)=>VCA&&A instanceof Blob?t?i(A):R6(A,i):XCA&&(A instanceof ArrayBuffer||$CA(A))?t?i(A):R6(new Blob([A]),i):i(dB[e]+(A||"")),R6=(e,A)=>{const t=new FileReader;return t.onload=function(){const i=t.result.split(",")[1];A("b"+(i||""))},t.readAsDataURL(e)};function G6(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let A2;function IbA(e,A){if(VCA&&e.data instanceof Blob)return e.data.arrayBuffer().then(G6).then(A);if(XCA&&(e.data instanceof ArrayBuffer||$CA(e.data)))return A(G6(e.data));g8(e,!1,t=>{A2||(A2=new TextEncoder),A(A2.encode(t))})}const b6="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ik=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<b6.length;e++)Ik[b6.charCodeAt(e)]=e;const CbA=e=>{let A=e.length*.75,t=e.length,i,n=0,g,o,s,a;e[e.length-1]==="="&&(A--,e[e.length-2]==="="&&A--);const r=new ArrayBuffer(A),I=new Uint8Array(r);for(i=0;i<t;i+=4)g=Ik[e.charCodeAt(i)],o=Ik[e.charCodeAt(i+1)],s=Ik[e.charCodeAt(i+2)],a=Ik[e.charCodeAt(i+3)],I[n++]=g<<2|o>>4,I[n++]=(o&15)<<4|s>>2,I[n++]=(s&3)<<6|a&63;return r},cbA=typeof ArrayBuffer=="function",o8=(e,A)=>{if(typeof e!="string")return{type:"message",data:AcA(e,A)};const t=e.charAt(0);return t==="b"?{type:"message",data:lbA(e.substring(1),A)}:AK[t]?e.length>1?{type:AK[t],data:e.substring(1)}:{type:AK[t]}:HP},lbA=(e,A)=>{if(cbA){const t=CbA(e);return AcA(t,A)}else return{base64:!0,data:e}},AcA=(e,A)=>{switch(A){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},ecA="",BbA=(e,A)=>{const t=e.length,i=new Array(t);let n=0;e.forEach((g,o)=>{g8(g,!1,s=>{i[o]=s,++n===t&&A(i.join(ecA))})})},EbA=(e,A)=>{const t=e.split(ecA),i=[];for(let n=0;n<t.length;n++){const g=o8(t[n],A);if(i.push(g),g.type==="error")break}return i};function QbA(){return new TransformStream({transform(e,A){IbA(e,t=>{const i=t.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const g=new DataView(n.buffer);g.setUint8(0,126),g.setUint16(1,i)}else{n=new Uint8Array(9);const g=new DataView(n.buffer);g.setUint8(0,127),g.setBigUint64(1,BigInt(i))}e.data&&typeof e.data!="string"&&(n[0]|=128),A.enqueue(n),A.enqueue(t)})}})}let e2;function Bb(e){return e.reduce((A,t)=>A+t.length,0)}function Eb(e,A){if(e[0].length===A)return e.shift();const t=new Uint8Array(A);let i=0;for(let n=0;n<A;n++)t[n]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),t}function ubA(e,A){e2||(e2=new TextDecoder);const t=[];let i=0,n=-1,g=!1;return new TransformStream({transform(o,s){for(t.push(o);;){if(i===0){if(Bb(t)<1)break;const a=Eb(t,1);g=(a[0]&128)===128,n=a[0]&127,n<126?i=3:n===126?i=1:i=2}else if(i===1){if(Bb(t)<2)break;const a=Eb(t,2);n=new DataView(a.buffer,a.byteOffset,a.length).getUint16(0),i=3}else if(i===2){if(Bb(t)<8)break;const a=Eb(t,8),r=new DataView(a.buffer,a.byteOffset,a.length),I=r.getUint32(0);if(I>Math.pow(2,21)-1){s.enqueue(HP);break}n=I*Math.pow(2,32)+r.getUint32(4),i=3}else{if(Bb(t)<n)break;const a=Eb(t,n);s.enqueue(o8(g?a:e2.decode(a),A)),i=0}if(n===0||n>e){s.enqueue(HP);break}}}})}const tcA=4;function fs(e){if(e)return dbA(e)}function dbA(e){for(var A in fs.prototype)e[A]=fs.prototype[A];return e}fs.prototype.on=fs.prototype.addEventListener=function(e,A){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(A),this};fs.prototype.once=function(e,A){function t(){this.off(e,t),A.apply(this,arguments)}return t.fn=A,this.on(e,t),this};fs.prototype.off=fs.prototype.removeListener=fs.prototype.removeAllListeners=fs.prototype.removeEventListener=function(e,A){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+e];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var i,n=0;n<t.length;n++)if(i=t[n],i===A||i.fn===A){t.splice(n,1);break}return t.length===0&&delete this._callbacks["$"+e],this};fs.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var A=new Array(arguments.length-1),t=this._callbacks["$"+e],i=1;i<arguments.length;i++)A[i-1]=arguments[i];if(t){t=t.slice(0);for(var i=0,n=t.length;i<n;++i)t[i].apply(this,A)}return this};fs.prototype.emitReserved=fs.prototype.emit;fs.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};fs.prototype.hasListeners=function(e){return!!this.listeners(e).length};const hL=typeof Promise=="function"&&typeof Promise.resolve=="function"?A=>Promise.resolve().then(A):(A,t)=>t(A,0),OC=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),hbA="arraybuffer";function icA(e,...A){return A.reduce((t,i)=>(e.hasOwnProperty(i)&&(t[i]=e[i]),t),{})}const pbA=OC.setTimeout,fbA=OC.clearTimeout;function pL(e,A){A.useNativeTimers?(e.setTimeoutFn=pbA.bind(OC),e.clearTimeoutFn=fbA.bind(OC)):(e.setTimeoutFn=OC.setTimeout.bind(OC),e.clearTimeoutFn=OC.clearTimeout.bind(OC))}const ybA=1.33;function DbA(e){return typeof e=="string"?mbA(e):Math.ceil((e.byteLength||e.size)*ybA)}function mbA(e){let A=0,t=0;for(let i=0,n=e.length;i<n;i++)A=e.charCodeAt(i),A<128?t+=1:A<2048?t+=2:A<55296||A>=57344?t+=3:(i++,t+=4);return t}function ncA(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function SbA(e){let A="";for(let t in e)e.hasOwnProperty(t)&&(A.length&&(A+="&"),A+=encodeURIComponent(t)+"="+encodeURIComponent(e[t]));return A}function wbA(e){let A={},t=e.split("&");for(let i=0,n=t.length;i<n;i++){let g=t[i].split("=");A[decodeURIComponent(g[0])]=decodeURIComponent(g[1])}return A}class kbA extends Error{constructor(A,t,i){super(A),this.description=t,this.context=i,this.type="TransportError"}}class s8 extends fs{constructor(A){super(),this.writable=!1,pL(this,A),this.opts=A,this.query=A.query,this.socket=A.socket,this.supportsBinary=!A.forceBase64}onError(A,t,i){return super.emitReserved("error",new kbA(A,t,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(A){this.readyState==="open"&&this.write(A)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(A){const t=o8(A,this.socket.binaryType);this.onPacket(t)}onPacket(A){super.emitReserved("packet",A)}onClose(A){this.readyState="closed",super.emitReserved("close",A)}pause(A){}createUri(A,t={}){return A+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const A=this.opts.hostname;return A.indexOf(":")===-1?A:"["+A+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(A){const t=SbA(A);return t.length?"?"+t:""}}class MbA extends s8{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(A){this.readyState="pausing";const t=()=>{this.readyState="paused",A()};if(this._polling||!this.writable){let i=0;this._polling&&(i++,this.once("pollComplete",function(){--i||t()})),this.writable||(i++,this.once("drain",function(){--i||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(A){const t=i=>{if(this.readyState==="opening"&&i.type==="open"&&this.onOpen(),i.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(i)};EbA(A,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const A=()=>{this.write([{type:"close"}])};this.readyState==="open"?A():this.once("open",A)}write(A){this.writable=!1,BbA(A,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const A=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=ncA()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(A,t)}}let gcA=!1;try{gcA=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const NbA=gcA;function RbA(){}class GbA extends MbA{constructor(A){if(super(A),typeof location<"u"){const t=location.protocol==="https:";let i=location.port;i||(i=t?"443":"80"),this.xd=typeof location<"u"&&A.hostname!==location.hostname||i!==A.port}}doWrite(A,t){const i=this.request({method:"POST",data:A});i.on("success",t),i.on("error",(n,g)=>{this.onError("xhr post error",n,g)})}doPoll(){const A=this.request();A.on("data",this.onData.bind(this)),A.on("error",(t,i)=>{this.onError("xhr poll error",t,i)}),this.pollXhr=A}}let ym=class eK extends fs{constructor(A,t,i){super(),this.createRequest=A,pL(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=i.data!==void 0?i.data:null,this._create()}_create(){var A;const t=icA(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const i=this._xhr=this.createRequest(t);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&i.setRequestHeader(n,this._opts.extraHeaders[n])}}catch{}if(this._method==="POST")try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{i.setRequestHeader("Accept","*/*")}catch{}(A=this._opts.cookieJar)===null||A===void 0||A.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var n;i.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.parseCookies(i.getResponseHeader("set-cookie"))),i.readyState===4&&(i.status===200||i.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof i.status=="number"?i.status:0)},0))},i.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=eK.requestsCount++,eK.requests[this._index]=this)}_onError(A){this.emitReserved("error",A,this._xhr),this._cleanup(!0)}_cleanup(A){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=RbA,A)try{this._xhr.abort()}catch{}typeof document<"u"&&delete eK.requests[this._index],this._xhr=null}}_onLoad(){const A=this._xhr.responseText;A!==null&&(this.emitReserved("data",A),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ym.requestsCount=0;ym.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",U6);else if(typeof addEventListener=="function"){const e="onpagehide"in OC?"pagehide":"unload";addEventListener(e,U6,!1)}}function U6(){for(let e in ym.requests)ym.requests.hasOwnProperty(e)&&ym.requests[e].abort()}const bbA=function(){const e=ocA({xdomain:!1});return e&&e.responseType!==null}();class UbA extends GbA{constructor(A){super(A);const t=A&&A.forceBase64;this.supportsBinary=bbA&&!t}request(A={}){return Object.assign(A,{xd:this.xd},this.opts),new ym(ocA,this.uri(),A)}}function ocA(e){const A=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!A||NbA))return new XMLHttpRequest}catch{}if(!A)try{return new OC[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const scA=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class vbA extends s8{get name(){return"websocket"}doOpen(){const A=this.uri(),t=this.opts.protocols,i=scA?{}:icA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(A,t,i)}catch(n){return this.emitReserved("error",n)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=A=>this.onClose({description:"websocket connection closed",context:A}),this.ws.onmessage=A=>this.onData(A.data),this.ws.onerror=A=>this.onError("websocket error",A)}write(A){this.writable=!1;for(let t=0;t<A.length;t++){const i=A[t],n=t===A.length-1;g8(i,this.supportsBinary,g=>{try{this.doWrite(i,g)}catch{}n&&hL(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const A=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ncA()),this.supportsBinary||(t.b64=1),this.createUri(A,t)}}const t2=OC.WebSocket||OC.MozWebSocket;class KbA extends vbA{createSocket(A,t,i){return scA?new t2(A,t,i):t?new t2(A,t):new t2(A)}doWrite(A,t){this.ws.send(t)}}class FbA extends s8{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(A){return this.emitReserved("error",A)}this._transport.closed.then(()=>{this.onClose()}).catch(A=>{this.onError("webtransport error",A)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(A=>{const t=ubA(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=A.readable.pipeThrough(t).getReader(),n=QbA();n.readable.pipeTo(A.writable),this._writer=n.writable.getWriter();const g=()=>{i.read().then(({done:s,value:a})=>{s||(this.onPacket(a),g())}).catch(s=>{})};g();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(A){this.writable=!1;for(let t=0;t<A.length;t++){const i=A[t],n=t===A.length-1;this._writer.write(i).then(()=>{n&&hL(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var A;(A=this._transport)===null||A===void 0||A.close()}}const _bA={websocket:KbA,webtransport:FbA,polling:UbA},JbA=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,LbA=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function OP(e){if(e.length>8e3)throw"URI too long";const A=e,t=e.indexOf("["),i=e.indexOf("]");t!=-1&&i!=-1&&(e=e.substring(0,t)+e.substring(t,i).replace(/:/g,";")+e.substring(i,e.length));let n=JbA.exec(e||""),g={},o=14;for(;o--;)g[LbA[o]]=n[o]||"";return t!=-1&&i!=-1&&(g.source=A,g.host=g.host.substring(1,g.host.length-1).replace(/;/g,":"),g.authority=g.authority.replace("[","").replace("]","").replace(/;/g,":"),g.ipv6uri=!0),g.pathNames=xbA(g,g.path),g.queryKey=TbA(g,g.query),g}function xbA(e,A){const t=/\/{2,9}/g,i=A.replace(t,"/").split("/");return(A.slice(0,1)=="/"||A.length===0)&&i.splice(0,1),A.slice(-1)=="/"&&i.splice(i.length-1,1),i}function TbA(e,A){const t={};return A.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,n,g){n&&(t[n]=g)}),t}const PP=typeof addEventListener=="function"&&typeof removeEventListener=="function",tK=[];PP&&addEventListener("offline",()=>{tK.forEach(e=>e())},!1);class qu extends fs{constructor(A,t){if(super(),this.binaryType=hbA,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,A&&typeof A=="object"&&(t=A,A=null),A){const i=OP(A);t.hostname=i.host,t.secure=i.protocol==="https"||i.protocol==="wss",t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=OP(t.host).host);pL(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(i=>{const n=i.prototype.name;this.transports.push(n),this._transportsByName[n]=i}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=wbA(this.opts.query)),PP&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},tK.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(A){const t=Object.assign({},this.opts.query);t.EIO=tcA,t.transport=A,this.id&&(t.sid=this.id);const i=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[A]);return new this._transportsByName[A](i)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const A=this.opts.rememberUpgrade&&qu.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(A);t.open(),this.setTransport(t)}setTransport(A){this.transport&&this.transport.removeAllListeners(),this.transport=A,A.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",qu.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(A){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",A),this.emitReserved("heartbeat"),A.type){case"open":this.onHandshake(JSON.parse(A.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=A.data,this._onError(t);break;case"message":this.emitReserved("data",A.data),this.emitReserved("message",A.data);break}}onHandshake(A){this.emitReserved("handshake",A),this.id=A.sid,this.transport.query.sid=A.sid,this._pingInterval=A.pingInterval,this._pingTimeout=A.pingTimeout,this._maxPayload=A.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const A=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+A,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},A),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const A=this._getWritablePackets();this.transport.send(A),this._prevBufferLen=A.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let i=0;i<this.writeBuffer.length;i++){const n=this.writeBuffer[i].data;if(n&&(t+=DbA(n)),i>0&&t>this._maxPayload)return this.writeBuffer.slice(0,i);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const A=Date.now()>this._pingTimeoutTime;return A&&(this._pingTimeoutTime=0,hL(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),A}write(A,t,i){return this._sendPacket("message",A,t,i),this}send(A,t,i){return this._sendPacket("message",A,t,i),this}_sendPacket(A,t,i,n){if(typeof t=="function"&&(n=t,t=void 0),typeof i=="function"&&(n=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;const g={type:A,data:t,options:i};this.emitReserved("packetCreate",g),this.writeBuffer.push(g),n&&this.once("flush",n),this.flush()}close(){const A=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),A()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():A()}):this.upgrading?i():A()),this}_onError(A){if(qu.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",A),this._onClose("transport error",A)}_onClose(A,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),PP&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const i=tK.indexOf(this._offlineEventListener);i!==-1&&tK.splice(i,1)}this.readyState="closed",this.id=null,this.emitReserved("close",A,t),this.writeBuffer=[],this._prevBufferLen=0}}}qu.protocol=tcA;class qbA extends qu{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let A=0;A<this._upgrades.length;A++)this._probe(this._upgrades[A])}_probe(A){let t=this.createTransport(A),i=!1;qu.priorWebsocketSuccess=!1;const n=()=>{i||(t.send([{type:"ping",data:"probe"}]),t.once("packet",c=>{if(!i)if(c.type==="pong"&&c.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;qu.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{i||this.readyState!=="closed"&&(I(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const l=new Error("probe error");l.transport=t.name,this.emitReserved("upgradeError",l)}}))};function g(){i||(i=!0,I(),t.close(),t=null)}const o=c=>{const l=new Error("probe error: "+c);l.transport=t.name,g(),this.emitReserved("upgradeError",l)};function s(){o("transport closed")}function a(){o("socket closed")}function r(c){t&&c.name!==t.name&&g()}const I=()=>{t.removeListener("open",n),t.removeListener("error",o),t.removeListener("close",s),this.off("close",a),this.off("upgrading",r)};t.once("open",n),t.once("error",o),t.once("close",s),this.once("close",a),this.once("upgrading",r),this._upgrades.indexOf("webtransport")!==-1&&A!=="webtransport"?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(A){this._upgrades=this._filterUpgrades(A.upgrades),super.onHandshake(A)}_filterUpgrades(A){const t=[];for(let i=0;i<A.length;i++)~this.transports.indexOf(A[i])&&t.push(A[i]);return t}}let YbA=class extends qbA{constructor(A,t={}){const i=typeof A=="object"?A:t;(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(n=>_bA[n]).filter(n=>!!n)),super(A,i)}};function HbA(e,A="",t){let i=e;t=t||typeof location<"u"&&location,e==null&&(e=t.protocol+"//"+t.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=t.protocol+e:e=t.host+e),/^(https?|wss?):\/\//.test(e)||(typeof t<"u"?e=t.protocol+"//"+e:e="https://"+e),i=OP(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const g=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+g+":"+i.port+A,i.href=i.protocol+"://"+g+(t&&t.port===i.port?"":":"+i.port),i}const ObA=typeof ArrayBuffer=="function",PbA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,acA=Object.prototype.toString,jbA=typeof Blob=="function"||typeof Blob<"u"&&acA.call(Blob)==="[object BlobConstructor]",zbA=typeof File=="function"||typeof File<"u"&&acA.call(File)==="[object FileConstructor]";function a8(e){return ObA&&(e instanceof ArrayBuffer||PbA(e))||jbA&&e instanceof Blob||zbA&&e instanceof File}function iK(e,A){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let t=0,i=e.length;t<i;t++)if(iK(e[t]))return!0;return!1}if(a8(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return iK(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&iK(e[t]))return!0;return!1}function ZbA(e){const A=[],t=e.data,i=e;return i.data=jP(t,A),i.attachments=A.length,{packet:i,buffers:A}}function jP(e,A){if(!e)return e;if(a8(e)){const t={_placeholder:!0,num:A.length};return A.push(e),t}else if(Array.isArray(e)){const t=new Array(e.length);for(let i=0;i<e.length;i++)t[i]=jP(e[i],A);return t}else if(typeof e=="object"&&!(e instanceof Date)){const t={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=jP(e[i],A));return t}return e}function WbA(e,A){return e.data=zP(e.data,A),delete e.attachments,e}function zP(e,A){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<A.length)return A[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let t=0;t<e.length;t++)e[t]=zP(e[t],A);else if(typeof e=="object")for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(e[t]=zP(e[t],A));return e}const VbA=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],XbA=5;var jn;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(jn||(jn={}));class $bA{constructor(A){this.replacer=A}encode(A){return(A.type===jn.EVENT||A.type===jn.ACK)&&iK(A)?this.encodeAsBinary({type:A.type===jn.EVENT?jn.BINARY_EVENT:jn.BINARY_ACK,nsp:A.nsp,data:A.data,id:A.id}):[this.encodeAsString(A)]}encodeAsString(A){let t=""+A.type;return(A.type===jn.BINARY_EVENT||A.type===jn.BINARY_ACK)&&(t+=A.attachments+"-"),A.nsp&&A.nsp!=="/"&&(t+=A.nsp+","),A.id!=null&&(t+=A.id),A.data!=null&&(t+=JSON.stringify(A.data,this.replacer)),t}encodeAsBinary(A){const t=ZbA(A),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}}function v6(e){return Object.prototype.toString.call(e)==="[object Object]"}class r8 extends fs{constructor(A){super(),this.reviver=A}add(A){let t;if(typeof A=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(A);const i=t.type===jn.BINARY_EVENT;i||t.type===jn.BINARY_ACK?(t.type=i?jn.EVENT:jn.ACK,this.reconstructor=new AUA(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(a8(A)||A.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(A),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+A)}decodeString(A){let t=0;const i={type:Number(A.charAt(0))};if(jn[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===jn.BINARY_EVENT||i.type===jn.BINARY_ACK){const g=t+1;for(;A.charAt(++t)!=="-"&&t!=A.length;);const o=A.substring(g,t);if(o!=Number(o)||A.charAt(t)!=="-")throw new Error("Illegal attachments");i.attachments=Number(o)}if(A.charAt(t+1)==="/"){const g=t+1;for(;++t&&!(A.charAt(t)===","||t===A.length););i.nsp=A.substring(g,t)}else i.nsp="/";const n=A.charAt(t+1);if(n!==""&&Number(n)==n){const g=t+1;for(;++t;){const o=A.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===A.length)break}i.id=Number(A.substring(g,t+1))}if(A.charAt(++t)){const g=this.tryParse(A.substr(t));if(r8.isPayloadValid(i.type,g))i.data=g;else throw new Error("invalid payload")}return i}tryParse(A){try{return JSON.parse(A,this.reviver)}catch{return!1}}static isPayloadValid(A,t){switch(A){case jn.CONNECT:return v6(t);case jn.DISCONNECT:return t===void 0;case jn.CONNECT_ERROR:return typeof t=="string"||v6(t);case jn.EVENT:case jn.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&VbA.indexOf(t[0])===-1);case jn.ACK:case jn.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class AUA{constructor(A){this.packet=A,this.buffers=[],this.reconPack=A}takeBinaryData(A){if(this.buffers.push(A),this.buffers.length===this.reconPack.attachments){const t=WbA(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const eUA=Object.freeze(Object.defineProperty({__proto__:null,Decoder:r8,Encoder:$bA,get PacketType(){return jn},protocol:XbA},Symbol.toStringTag,{value:"Module"}));function Fc(e,A,t){return e.on(A,t),function(){e.off(A,t)}}const tUA=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class rcA extends fs{constructor(A,t,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=A,this.nsp=t,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const A=this.io;this.subs=[Fc(A,"open",this.onopen.bind(this)),Fc(A,"packet",this.onpacket.bind(this)),Fc(A,"error",this.onerror.bind(this)),Fc(A,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...A){return A.unshift("message"),this.emit.apply(this,A),this}emit(A,...t){var i,n,g;if(tUA.hasOwnProperty(A))throw new Error('"'+A.toString()+'" is a reserved event name');if(t.unshift(A),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:jn.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const I=this.ids++,c=t.pop();this._registerAckCallback(I,c),o.id=I}const s=(n=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||n===void 0?void 0:n.writable,a=this.connected&&!(!((g=this.io.engine)===null||g===void 0)&&g._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(A,t){var i;const n=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(n===void 0){this.acks[A]=t;return}const g=this.io.setTimeoutFn(()=>{delete this.acks[A];for(let s=0;s<this.sendBuffer.length;s++)this.sendBuffer[s].id===A&&this.sendBuffer.splice(s,1);t.call(this,new Error("operation has timed out"))},n),o=(...s)=>{this.io.clearTimeoutFn(g),t.apply(this,s)};o.withError=!0,this.acks[A]=o}emitWithAck(A,...t){return new Promise((i,n)=>{const g=(o,s)=>o?n(o):i(s);g.withError=!0,t.push(g),this.emit(A,...t)})}_addToQueue(A){let t;typeof A[A.length-1]=="function"&&(t=A.pop());const i={id:this._queueSeq++,tryCount:0,pending:!1,args:A,flags:Object.assign({fromQueue:!0},this.flags)};A.push((n,...g)=>i!==this._queue[0]?void 0:(n!==null?i.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(n)):(this._queue.shift(),t&&t(null,...g)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(A=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!A||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(A){A.nsp=this.nsp,this.io._packet(A)}onopen(){typeof this.auth=="function"?this.auth(A=>{this._sendConnectPacket(A)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(A){this.packet({type:jn.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},A):A})}onerror(A){this.connected||this.emitReserved("connect_error",A)}onclose(A,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",A,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(A=>{if(!this.sendBuffer.some(i=>String(i.id)===A)){const i=this.acks[A];delete this.acks[A],i.withError&&i.call(this,new Error("socket has been disconnected"))}})}onpacket(A){if(A.nsp===this.nsp)switch(A.type){case jn.CONNECT:A.data&&A.data.sid?this.onconnect(A.data.sid,A.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case jn.EVENT:case jn.BINARY_EVENT:this.onevent(A);break;case jn.ACK:case jn.BINARY_ACK:this.onack(A);break;case jn.DISCONNECT:this.ondisconnect();break;case jn.CONNECT_ERROR:this.destroy();const i=new Error(A.data.message);i.data=A.data.data,this.emitReserved("connect_error",i);break}}onevent(A){const t=A.data||[];A.id!=null&&t.push(this.ack(A.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(A){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const i of t)i.apply(this,A)}super.emit.apply(this,A),this._pid&&A.length&&typeof A[A.length-1]=="string"&&(this._lastOffset=A[A.length-1])}ack(A){const t=this;let i=!1;return function(...n){i||(i=!0,t.packet({type:jn.ACK,id:A,data:n}))}}onack(A){const t=this.acks[A.id];typeof t=="function"&&(delete this.acks[A.id],t.withError&&A.data.unshift(null),t.apply(this,A.data))}onconnect(A,t){this.id=A,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(A=>this.emitEvent(A)),this.receiveBuffer=[],this.sendBuffer.forEach(A=>{this.notifyOutgoingListeners(A),this.packet(A)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(A=>A()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:jn.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(A){return this.flags.compress=A,this}get volatile(){return this.flags.volatile=!0,this}timeout(A){return this.flags.timeout=A,this}onAny(A){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(A),this}prependAny(A){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(A),this}offAny(A){if(!this._anyListeners)return this;if(A){const t=this._anyListeners;for(let i=0;i<t.length;i++)if(A===t[i])return t.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(A){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(A),this}prependAnyOutgoing(A){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(A),this}offAnyOutgoing(A){if(!this._anyOutgoingListeners)return this;if(A){const t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(A===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(A){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const i of t)i.apply(this,A.data)}}}function dw(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}dw.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var A=Math.random(),t=Math.floor(A*this.jitter*e);e=Math.floor(A*10)&1?e+t:e-t}return Math.min(e,this.max)|0};dw.prototype.reset=function(){this.attempts=0};dw.prototype.setMin=function(e){this.ms=e};dw.prototype.setMax=function(e){this.max=e};dw.prototype.setJitter=function(e){this.jitter=e};class ZP extends fs{constructor(A,t){var i;super(),this.nsps={},this.subs=[],A&&typeof A=="object"&&(t=A,A=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,pL(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((i=t.randomizationFactor)!==null&&i!==void 0?i:.5),this.backoff=new dw({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=A;const n=t.parser||eUA;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(A){return arguments.length?(this._reconnection=!!A,A||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(A){return A===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=A,this)}reconnectionDelay(A){var t;return A===void 0?this._reconnectionDelay:(this._reconnectionDelay=A,(t=this.backoff)===null||t===void 0||t.setMin(A),this)}randomizationFactor(A){var t;return A===void 0?this._randomizationFactor:(this._randomizationFactor=A,(t=this.backoff)===null||t===void 0||t.setJitter(A),this)}reconnectionDelayMax(A){var t;return A===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=A,(t=this.backoff)===null||t===void 0||t.setMax(A),this)}timeout(A){return arguments.length?(this._timeout=A,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(A){if(~this._readyState.indexOf("open"))return this;this.engine=new YbA(this.uri,this.opts);const t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const n=Fc(t,"open",function(){i.onopen(),A&&A()}),g=s=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",s),A?A(s):this.maybeReconnectOnOpen()},o=Fc(t,"error",g);if(this._timeout!==!1){const s=this._timeout,a=this.setTimeoutFn(()=>{n(),g(new Error("timeout")),t.close()},s);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}return this.subs.push(n),this.subs.push(o),this}connect(A){return this.open(A)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const A=this.engine;this.subs.push(Fc(A,"ping",this.onping.bind(this)),Fc(A,"data",this.ondata.bind(this)),Fc(A,"error",this.onerror.bind(this)),Fc(A,"close",this.onclose.bind(this)),Fc(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(A){try{this.decoder.add(A)}catch(t){this.onclose("parse error",t)}}ondecoded(A){hL(()=>{this.emitReserved("packet",A)},this.setTimeoutFn)}onerror(A){this.emitReserved("error",A)}socket(A,t){let i=this.nsps[A];return i?this._autoConnect&&!i.active&&i.connect():(i=new rcA(this,A,t),this.nsps[A]=i),i}_destroy(A){const t=Object.keys(this.nsps);for(const i of t)if(this.nsps[i].active)return;this._close()}_packet(A){const t=this.encoder.encode(A);for(let i=0;i<t.length;i++)this.engine.write(t[i],A.options)}cleanup(){this.subs.forEach(A=>A()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(A,t){var i;this.cleanup(),(i=this.engine)===null||i===void 0||i.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",A,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const A=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const i=this.setTimeoutFn(()=>{A.skipReconnect||(this.emitReserved("reconnect_attempt",A.backoff.attempts),!A.skipReconnect&&A.open(n=>{n?(A._reconnecting=!1,A.reconnect(),this.emitReserved("reconnect_error",n)):A.onreconnect()}))},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){const A=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",A)}}const h0={};function Vk(e,A){typeof e=="object"&&(A=e,e=void 0),A=A||{};const t=HbA(e,A.path||"/socket.io"),i=t.source,n=t.id,g=t.path,o=h0[n]&&g in h0[n].nsps,s=A.forceNew||A["force new connection"]||A.multiplex===!1||o;let a;return s?a=new ZP(i,A):(h0[n]||(h0[n]=new ZP(i,A)),a=h0[n]),t.query&&!A.query&&(A.query=t.queryKey),a.socket(t.path,A)}Object.assign(Vk,{Manager:ZP,Socket:rcA,io:Vk,connect:Vk});function Fp(e,A){try{if(!e){console.debug("[socket] disconnect skipped (no socket)",{tag:A});return}const t={tag:A,id:e.id,connected:e.connected,active:e.active};console.debug("[socket] disconnect invoked",t),e.disconnect()}catch(t){try{console.warn("[socket] disconnect error",{tag:A,err:t})}catch{}}}function IcA(e,A){var t;try{if(!e){console.debug("[socket] close skipped (no socket)",{tag:A});return}console.debug("[socket] close invoked",{tag:A,id:e.id}),(t=e.close)==null||t.call(e)}catch(i){try{console.warn("[socket] close error",{tag:A,err:i})}catch{}}}const CcA=E.createContext(void 0),iUA=({children:e})=>{const[A,t]=E.useState(!0),[i,n]=E.useState(0),g=E.useCallback(()=>t(!0),[]),o=E.useCallback(()=>n(I=>I+1),[]),s=E.useCallback(()=>n(0),[]),a=E.useCallback(I=>{t(!1),setTimeout(()=>t(!0),I)},[]),r=E.useCallback(()=>t(!1),[]);return E.useEffect(()=>{if(typeof window>"u"||!(typeof window.location<"u"&&window.location.search.includes("e2e=1")))return;const c={triggerSpin:o,scheduleReveal:a,resetReveal:r,resetSpin:s};try{window.__diceRevealTest=c}catch{}return()=>{try{delete window.__diceRevealTest}catch{}}},[o,a,r,s]),C.jsx(CcA.Provider,{value:{reveal:A,triggerReveal:g,scheduleReveal:a,resetReveal:r,triggerSpin:o,rollTrigger:i,resetSpin:s},children:e})},kB=()=>{const e=E.useContext(CcA);if(!e)throw new Error("useDiceReveal must be used within a DiceRevealProvider");return e},i2={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_TARGET:"zentara",VITE_OTA:"1"},WM=500,ccA=new Array(WM);let Xk=0,fF=0;const I8="fe:crashlog",nUA=80;function lcA(){try{const e=VM().slice(-nUA).map(A=>{var t;return{t:A.t,level:A.level,tag:A.tag,msg:A.msg,...A.data!==void 0?{data:typeof A.data=="string"?A.data:(t=JSON.stringify(A.data))==null?void 0:t.slice(0,200)}:{}}});localStorage.setItem(I8,JSON.stringify(e))}catch{}}function C8(){try{const e=localStorage.getItem(I8);return e?JSON.parse(e):[]}catch{return[]}}function gUA(){try{localStorage.removeItem(I8)}catch{}}let n2=null;function oUA(){n2||(n2=setTimeout(()=>{n2=null,lcA()},2e3))}function sUA(){var e;try{if(typeof window<"u"&&((e=window.localStorage)==null?void 0:e.getItem("logs:disable"))==="1"||typeof import.meta<"u"&&(i2==null?void 0:i2.VITE_LOGS_DISABLED)==="1")return!1}catch{}return!0}function aUA(e){ccA[Xk]=e,Xk=(Xk+1)%WM,fF=Math.min(fF+1,WM);try{window.dispatchEvent(new CustomEvent("fe:log",{detail:e}))}catch{}e.level==="error"||e.level==="warn"?lcA():oUA()}function VM(){const e=[],A=fF;for(let t=0;t<A;t++){const i=(Xk-A+t+WM)%WM,n=ccA[i];n&&e.push(n)}return e}function rUA(){Xk=0,fF=0}function ys(e,A,t,i){const n={t:Date.now(),tag:e,level:A,msg:t,data:i};if(sUA()){const g=`[${new Date(n.t).toISOString()}][${e}/${A}]`;try{const o=i===void 0?[]:[i];A==="error"?console.error(g,t,...o):A==="warn"?console.warn(g,t,...o):A==="debug"?console.debug(g,t,...o):console.log(g,t,...o)}catch{}aUA(n)}}const Ii={debug:(e,A)=>ys("RTC","debug",e,A),info:(e,A)=>ys("RTC","info",e,A),warn:(e,A)=>ys("RTC","warn",e,A),error:(e,A)=>ys("RTC","error",e,A)},Ks={debug:(e,A)=>ys("LIFE","debug",e,A),info:(e,A)=>ys("LIFE","info",e,A),warn:(e,A)=>ys("LIFE","warn",e,A),error:(e,A)=>ys("LIFE","error",e,A)},FC={debug:(e,A)=>ys("SOCK","debug",e,A),info:(e,A)=>ys("SOCK","info",e,A),warn:(e,A)=>ys("SOCK","warn",e,A),error:(e,A)=>ys("SOCK","error",e,A)},JI={debug:(e,A)=>ys("GL","debug",e,A),info:(e,A)=>ys("GL","info",e,A),warn:(e,A)=>ys("GL","warn",e,A),error:(e,A)=>ys("GL","error",e,A)},WP={debug:(e,A)=>ys("ERR","debug",e,A),info:(e,A)=>ys("ERR","info",e,A),warn:(e,A)=>ys("ERR","warn",e,A),error:(e,A)=>ys("ERR","error",e,A)};try{window.rtcLogs=VM,window.rtcLogsClear=rUA,window.feLogs=VM,window.feCrashLogs=C8}catch{}const c8=E.createContext(null);let Fs=null,K6="",Ck=0,Qb=0;const F6=1200;let l8=!1,ub=0;const BcA=2e3;function Za(e,A,t){var g,o,s,a;if(!e||e.connected||e.active)return!1;let i="";try{i=String(((g=e.auth)==null?void 0:g.token)||((a=(s=(o=e==null?void 0:e.io)==null?void 0:o.opts)==null?void 0:s.auth)==null?void 0:a.token)||"")}catch{i=""}if(!i&&!(t!=null&&t.allowCookieSession))return FC.debug("safeSocketConnect SKIPPED - no auth token",{source:A}),!1;if(l8)return FC.warn("safeSocketConnect SKIPPED - session superseded",{source:A}),console.log("[safeSocketConnect] SKIPPED - session superseded",{source:A}),!1;const n=Date.now();if(n<ub)return FC.debug("safeSocketConnect SKIPPED - debounce",{source:A,msRemaining:ub-n}),console.log("[safeSocketConnect] SKIPPED - connect already in progress",{source:A,msRemaining:ub-n}),!1;ub=n+BcA,FC.info("safeSocketConnect calling connect()",{source:A,socketId:e.id}),console.log("[safeSocketConnect] calling socket.connect()",{source:A,socketId:e.id});try{e.connect()}catch{}return!0}function IUA(){l8=!1}function EcA(){l8=!0,console.log("[SocketContext] Session superseded by another device/tab - auto-reconnect disabled")}function B8(e=2e3){try{Ck=Date.now()+Math.max(0,e|0)}catch{}}function hw(){return Fs}function CUA(e=2e3){try{B8(e)}catch{}try{Fs==null||Fs.removeAllListeners()}catch{}try{Fp(Fs,"SocketContext: hardDisconnectSocket")}catch{}}function cUA(){const e=Fs;if(e){try{e.auth={}}catch{}try{e.__authSig=""}catch{}try{Fp(e,"SocketContext: logout refresh")}catch{}}}function lUA(e){const A=(()=>{var s;try{return typeof window<"u"&&/^(capacitor:|ionic:)/i.test(((s=window.location)==null?void 0:s.protocol)||"")}catch{return!1}})(),t=(()=>{try{return typeof window<"u"?window.location.search:""}catch{return""}})(),n=/(?:[?&])wsOnly=1/.test(t)||(()=>{try{return localStorage.getItem("socket:wsOnly")==="1"}catch{return!1}})()?["websocket"]:["websocket","polling"],g=window.APP_TARGET||"ceelo",o=Vk(e,{path:"/socket.io",withCredentials:!0,transports:n,upgrade:n.length>1,timeout:25e3,autoConnect:!1,extraHeaders:A?{Origin:e}:void 0,auth:{appTarget:g}});return o.on("connect_error",s=>{try{o.__lastConnectErr={ts:Date.now(),reason:(s==null?void 0:s.message)||""}}catch{}}),o}function BUA(e){var A;if(Fs&&K6===e)return Fs;if(Fs){try{Fs.removeAllListeners()}catch{}try{IcA(Fs,"SocketContext: getSharedSocket replace")}catch{}Fs=null}Fs=lUA(e),K6=e;try{if(typeof window<"u"){(((A=window.location)==null?void 0:A.search)||"").includes("e2e=1")&&(window.__SOCKET=Fs,window.__sharedSocket=Fs,window.hardDisconnectSocket=CUA,window.suspendSocketAutoConnect=B8);try{if(!window.__clientErrMon){window.__clientErrMon=!0;const i=g=>{try{const o=window.__sharedSocket||Fs;if(!o)return;o.connected?o.emit("client_error",g):(o.__pendingClientErrors=o.__pendingClientErrors||[],o.__pendingClientErrors.push(g))}catch{}},n=()=>{let g="web";try{const o=navigator.userAgent||"";/iPhone|iPad|iPod/i.test(o)?g="ios":/Android/i.test(o)?g="android":g="web"}catch{}return{platform:g,userAgent:typeof navigator<"u"?navigator.userAgent:"",ts:Date.now()}};window.addEventListener("error",g=>{var o,s,a;try{if(!g.error&&!g.message)return;const r=g.message||"";if(r.includes("websocket error")||r.includes("WebSocket"))return;i({message:r||"error",stack:(a=(s=(o=g.error)==null?void 0:o.stack)==null?void 0:s.slice)==null?void 0:a.call(s,0,5e3),filename:g.filename,line:g.lineno,col:g.colno,...n()})}catch{}}),window.addEventListener("unhandledrejection",g=>{var o,s,a,r,I;try{const c=g.reason,l=typeof c=="string"?c:(c==null?void 0:c.message)||"unhandledrejection";if((c==null?void 0:c.name)==="AbortError"||(o=l==null?void 0:l.includes)!=null&&o.call(l,"aborted")||(s=l==null?void 0:l.includes)!=null&&s.call(l,"The operation was aborted"))return;i({message:((a=l==null?void 0:l.slice)==null?void 0:a.call(l,0,500))||"unhandledrejection",stack:(I=(r=(c==null?void 0:c.stack)||"").slice)==null?void 0:I.call(r,0,5e3),...n()})}catch{}}),Fs.on("connect",()=>{try{const g=Fs,o=g==null?void 0:g.__pendingClientErrors;Array.isArray(o)&&o.length&&o.splice(0,o.length).forEach(a=>{try{g.emit("client_error",a)}catch{}})}catch{}})}}catch{}}}catch{}return Fs}function EUA({children:e}){const{user:A,initialized:t}=tn(),i=Ca(),n=E.useMemo(()=>BUA(i),[i]),{resetSpin:g}=kB();return E.useEffect(()=>{if(!t)return;let o=!1;return(async()=>{const s=I=>{try{n.__authSig=I}catch{}},a=()=>{try{return String(n.__authSig||"")}catch{return""}},r=I=>{var B;const c=Math.max(0,Ck-Date.now());if(c<=0)return I();const l=setTimeout(()=>{o||I()},c);(B=l.unref)==null||B.call(l)};if(A){const I=await uo();if(o)return;if(I){const c=a(),l=`t:${I}`;n.auth={token:I};try{n.__allowCookieAuth=!1}catch{}if(s(l),n.disconnected)r(()=>{o||(Za(n,"SocketContext:auth-token-connect"),g())});else if(c!==l){const B=Date.now();B-Qb>=F6&&(Qb=B,r(()=>{if(!o){try{Fp(n,"SocketContext: auth change soft reconnect")}catch{}setTimeout(()=>{o||(Za(n,"SocketContext:auth-change-reconnect"),g())},100)}}))}}else{const c=a(),l="c:*";try{n.auth={}}catch{}try{n.__allowCookieAuth=!0}catch{}if(s(l),n.disconnected)r(()=>{o||(Za(n,"SocketContext:cookie-session-connect",{allowCookieSession:!0}),g())});else if(c!==l){const B=Date.now();B-Qb>=F6&&(Qb=B,r(()=>{if(!o){try{Fp(n,"SocketContext: cookie auth soft reconnect")}catch{}setTimeout(()=>{o||(Za(n,"SocketContext:cookie-auth-reconnect",{allowCookieSession:!0}),g())},100)}}))}}}else try{n.__allowCookieAuth=!1}catch{}})(),()=>{o=!0}},[t,A,n]),E.useEffect(()=>{const o=async()=>{if(Date.now()<Ck)return;const s=await uo();if(!s){if(A){try{n.auth={},n.__authSig="c:*",n.__allowCookieAuth=!0}catch{}g();return}try{n.auth={},n.__authSig="",n.__allowCookieAuth=!1}catch{}try{n.disconnected||Fp(n,"SocketContext: skip reconnect without token")}catch{}return}n.auth={token:s};try{n.__authSig=`t:${s}`,n.__allowCookieAuth=!1}catch{}g()};return n.on("reconnect_attempt",o),()=>{n.off("reconnect_attempt",o)}},[n,g,A]),E.useEffect(()=>{let o=!1,s=null;const a=async r=>{if(String((r==null?void 0:r.message)||"")==="INVALID_TOKEN"){try{n.disconnect()}catch{}try{await kd()}catch{}if(!o){try{n.auth={},n.__authSig="c:*",n.__allowCookieAuth=!!A}catch{}A&&(s=setTimeout(()=>{o||Za(n,"SocketContext:invalid-token-cookie-fallback",{allowCookieSession:!0})},BcA+100))}}};return n.on("connect_error",a),()=>{o=!0,s&&clearTimeout(s),n.off("connect_error",a)}},[n,A]),E.useEffect(()=>{const o=async s=>{try{await ef(s)}catch{}n.auth=s?{token:s}:{};try{n.__authSig=s?`t:${s}`:""}catch{}};return n.on("auth:rotate",o),()=>{n.off("auth:rotate",o)}},[n]),E.useEffect(()=>{let o=!1;const s=async()=>{if(!o&&!(Date.now()<Ck)&&n.disconnected){try{const l=await uo();if(o)return;if(l){n.auth={token:l};try{n.__authSig=`t:${l}`,n.__allowCookieAuth=!1}catch{}}else{if(!A)return;try{n.auth={},n.__authSig="c:*",n.__allowCookieAuth=!0}catch{}}}catch{}if(n.disconnected){const l=!!(n!=null&&n.__allowCookieAuth);Za(n,"SocketContext:refreshAuthAndConnect",{allowCookieSession:l}),g()}}},a=()=>{try{document.visibilityState==="visible"&&s()}catch{}},r=()=>s(),I=()=>s(),c=()=>s();return window.addEventListener("visibilitychange",a),window.addEventListener("focus",r),window.addEventListener("pageshow",I),window.addEventListener("online",c),()=>{o=!0,window.removeEventListener("visibilitychange",a),window.removeEventListener("focus",r),window.removeEventListener("pageshow",I),window.removeEventListener("online",c)}},[n,g,A]),E.useEffect(()=>{const o=()=>{try{n.removeAllListeners()}catch{}try{IcA(n,"SocketContext: beforeunload")}catch{}};return window.addEventListener("beforeunload",o),()=>{window.removeEventListener("beforeunload",o)}},[n]),E.useEffect(()=>{let o=!1;const s=5e3,a=15e3,r=2e3;let I=!1;const l=setInterval(()=>{var p;if(o)return;try{if(document.visibilityState==="hidden")return}catch{}if(Date.now()<Ck||!n||I)return;const B=n.connected,Q=(p=n==null?void 0:n.data)==null?void 0:p.lastAckAt;if(!B){try{const y=!!(n!=null&&n.__allowCookieAuth);Za(n,"SocketContext:health-poll-disconnected",{allowCookieSession:y})}catch{}return}if(Q&&Date.now()-Q<a)return;I=!0;let h=!1;const d=setTimeout(()=>{if(!h){h=!0,I=!1;try{n.disconnect()}catch{}setTimeout(()=>{if(!o)try{const y=!!(n!=null&&n.__allowCookieAuth);Za(n,"SocketContext:health-poll-timeout-reconnect",{allowCookieSession:y})}catch{}},100)}},r);try{n.emit("health:ping",{},y=>{if(!h){h=!0,clearTimeout(d),I=!1;try{n.data=n.data||{},n.data.lastAckAt=Date.now(),n.data.lastAckEvent="health:ping"}catch{}try{if(y&&typeof y.ts=="number"){const m=Date.now()-y.ts;n.__lastRttMs=m}y&&typeof y.lagMs=="number"&&(n.__lastServerLagMs=y.lagMs)}catch{}}})}catch{I=!1}},s);return()=>{o=!0,clearInterval(l)}},[n]),C.jsx(c8.Provider,{value:n,children:e})}function Ms(){const e=E.useContext(c8);if(!e)throw new Error("useSocket must be used within a SocketProvider");return e}const QcA=E.createContext({user:null,loading:!0,initialized:!1,refreshUser:async()=>{},logout:async()=>{},meId:"",updateBalance:()=>{}}),tn=()=>E.useContext(QcA);function QUA(e){if(!e)return null;if(typeof e=="object"&&"authenticated"in e){const A=e;return A.authenticated?A.user??null:null}return e}const uUA=({children:e})=>{const[A,t]=E.useState(null),[i,n]=E.useState(""),[g,o]=E.useState(!0),[s,a]=E.useState(!1),r=ks(),I=E.useRef(null),c=E.useRef(!0);E.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const l=E.useCallback(async d=>{var S;if(I.current){if(!(d!=null&&d.force))return I.current;try{await I.current}catch{}}const p=new URLSearchParams(r.search);if((()=>{var k,N;try{if(p.get("e2e")==="1"||typeof window<"u"&&(window.__E2E===!0||(N=(k=window.location)==null?void 0:k.search)!=null&&N.includes("e2e=1")||typeof window.sessionStorage<"u"&&window.sessionStorage.getItem("e2e")==="1"))return!0}catch{}return!1})()){let k=1e3;try{const N=(S=window.sessionStorage)==null?void 0:S.getItem("e2e_balance"),G=N?Number(N):NaN;Number.isFinite(G)&&(k=G)}catch{}t({id:"e2e-user",name:"E2E",email:"e2e@example.com",balance:k,botChatDisabled:!1,ceeloBotsPerRoom:null,crapsBotsPerRoom:null,pokerBotsPerRoom:null}),n("e2e-user"),o(!1),a(!0);return}const m=async()=>{t(null),n("");try{$q(null)}catch{}};o(!0);const D=(async()=>{try{const k=await dL(),N=QUA(k);if(N){IUA(),t(N),n((N==null?void 0:N.id)||"");try{$q(N.id||null)}catch{}}else await m()}catch{if(!c.current)return;await m()}finally{o(!1),a(!0),I.current=null}})();return I.current=D,D},[]);E.useEffect(()=>{l()},[l]);const B=E.useCallback(d=>{c.current&&t(p=>!p||p.balance===d?p:{...p,balance:d})},[]),Q=E.useCallback(async()=>{const d=A==null?void 0:A.email;try{try{B8(2500)}catch{}d&&await ZCA(d);try{await fetch("/api/auth/clear",{method:"POST",credentials:"include"})}catch{}}finally{if(!c.current)return;try{await kd()}catch{}try{await rbA()}catch{}t(null),n("");try{$q(null)}catch{}try{cUA()}catch{}try{(await Qi(()=>Promise.resolve().then(()=>Qke),void 0)).disconnectSocket()}catch{}}},[A==null?void 0:A.email]),h=E.useMemo(()=>({user:A,loading:g,initialized:s,refreshUser:l,logout:Q,meId:i,updateBalance:B}),[A,g,s,l,Q,i,B]);return C.jsx(QcA.Provider,{value:h,children:e})},dUA=(()=>{var e,A;try{return(A=(e=import.meta)==null?void 0:e.env)==null?void 0:A.VITE_APP_TARGET}catch{return}})();function hUA(){var e;try{const A=(e=window.localStorage)==null?void 0:e.getItem("app_target_lock");if(A==="ceelo"||A==="craps"||A==="poker"||A==="skills"||A==="zentara"||A==="unified")return A}catch{}}function pUA(e){var A;try{(A=window.localStorage)==null||A.setItem("app_target_lock",e)}catch{}}const _6=(()=>{try{return Ui.getPlatform()}catch{return"web"}})(),ucA=hUA()??dUA??qs;(_6==="ios"||_6==="android")&&pUA(ucA);const E8=ucA,Dm=E8==="zentara";function fUA(){return E8}if(typeof document<"u"){const A={zentara:"zentara-body"}[E8];if(A){const t=()=>{var i;(i=document.body)==null||i.classList.add(A)};document.body?t():document.addEventListener("DOMContentLoaded",t,{once:!0})}}function tr({className:e}){return E.useEffect(()=>(document.body.classList.add(e),()=>{document.body.classList.remove(e),window.scrollTo(0,0),document.body.scrollTop=0,document.documentElement.scrollTop=0}),[e]),null}function vf(){const{user:e,loading:A,initialized:t}=tn(),i=ks(),g=new URLSearchParams(i.search).get("e2e")==="1",o=i.pathname||"",s=/^\/poker\/room\//.test(o),a=/^\/room\//.test(o),r=/^\/(lobby|zentara\/)/.test(o);return!t||A?C.jsxs("div",{className:"HomeScreen theme-casino home-fixed-root",children:[C.jsx(tr,{className:"page-home-screen"}),C.jsx("div",{className:"home-preloader",children:C.jsx("div",{className:"home-preloader__spinner"})})]}):!e&&!g&&!(s||a||r)?C.jsx(Tg,{to:"/lobby",replace:!0,state:{from:i}}):C.jsx(LCA,{})}function Kf(){return C.jsxs("div",{style:{padding:24},children:[C.jsx("h2",{children:"Verification failed"}),C.jsx("p",{children:"Your login link is invalid or expired. Please request a new one."})]})}const dcA=E.createContext(null);function yUA({children:e}){const[A,t]=E.useState([]),i=E.useRef({}),n=E.useCallback(I=>{t(l=>l.filter(B=>B.id!==I));const c=i.current[I];c&&(window.clearTimeout(c),delete i.current[I])},[]),g=E.useCallback(I=>{const c=crypto.randomUUID(),l={id:c,duration:3500,...I};t(Q=>[...Q,l]);const B=l.duration??3500;return B>0&&(i.current[c]=window.setTimeout(()=>n(c),B)),c},[n]),o=E.useCallback((I,c={})=>g({message:I,variant:"success",...c}),[g]),s=E.useCallback((I,c={})=>g({message:I,variant:"error",...c}),[g]),a=E.useCallback((I,c={})=>g({message:I,variant:"info",...c}),[g]),r=E.useMemo(()=>({show:g,success:o,error:s,info:a,dismiss:n}),[g,o,s,a,n]);return C.jsxs(dcA.Provider,{value:r,children:[e,er.createPortal(C.jsx("div",{className:"toast-root","aria-live":"polite","aria-atomic":"true",children:A.map(I=>C.jsxs("div",{className:`toast-item toast-${I.variant}`,role:"status",onClick:()=>n(I.id),children:[I.title&&C.jsx("div",{className:"toast-title",children:I.title}),I.message&&C.jsx("div",{className:"toast-message",children:I.message}),C.jsx("button",{className:"toast-close","aria-label":"Dismiss",onClick:c=>{c.stopPropagation(),n(I.id)},children:"×"})]},I.id))}),document.body)]})}function MB(){const e=E.useContext(dcA);if(!e){const A=()=>"noop";return{show:()=>"noop",success:A,error:A,info:A,dismiss:()=>{}}}return e}const hcA={BOTS_NUDGE:"bots:nudge",ROOM_REFRESH_STATE:"room:refresh_state",USER_GET_BALANCE:"user:get_balance",SEND_FRIEND_REQUEST:"send_friend_request",CANCEL_FRIEND_REQUEST:"cancel_friend_request",RESPOND_FRIEND_REQUEST:"respond_friend_request",UNFRIEND:"unfriend",BLOCK_USER:"block_user",UNBLOCK_USER:"unblock_user",FAIRNESS_REVEAL:"fairness_reveal",CREATE_ROOM:"room_create",JOIN_ROOM:"join_room",LEAVE_ROOM:"leave_room",ROLL_DICE:"roll_dice",CONFIRM_BETS:"confirm_bets",GET_ROOMS_LIST:"get_rooms_list",BANKER_GIVE_UP:"banker_give_up",BANKER_CHANGED:"banker_changed",PLACE_MAIN_BET:"place_main_bet",CANCEL_MAIN_BET:"cancel_main_bet",CREATE_SIDE_BET:"create_side_bet",ACCEPT_SIDE_BET:"accept_side_bet",CANCEL_SIDE_BET:"cancel_side_bet",GET_WAGERS:"get_wagers",RTC_JOIN:"rtc_join",RTC_LEAVE:"rtc_leave",RTC_SIGNAL:"rtc_signal",RTC_SET_CAMERA_OWNER:"rtc_set_camera_owner",RTC_SET_VIDEO_ENABLED:"rtc_set_video_enabled",RTC_PEER_LEFT:"rtc_peer_left",RTC_CAMERA_OWNER_CHANGED:"rtc_camera_owner_changed",RTC_VIDEO_ENABLED:"rtc_video_enabled",ROOM_SEND_MESSAGE:"room_send_message",ROOM_FETCH_HISTORY:"room_fetch_history",ROOM_MESSAGE:"room_message",ROOM_HISTORY:"room_history",DM_SEND_MESSAGE:"dm_send_message",DM_FETCH_HISTORY:"dm_fetch_history",DIRECT_MESSAGE:"direct_message",DIRECT_HISTORY:"direct_history",LOBBY_JOIN:"lobby_join",LOBBY_LEAVE:"lobby_leave",LOBBY_LIST:"lobby_list",DELETE_ROOM:"room_delete",SOCIAL_GET_LIST:"social:get_list",SOCIAL_SEARCH_PLAYERS:"social:search_players",USER_UPDATE_PROFILE:"user:update_profile",TURN_ORDER_UPDATED:"turn_order_updated",SPECTATE_SET:"spectate_set",SPECTATORS_UPDATED:"spectators_updated",CRAPS_PLACE_PASS:"craps:place_pass",CRAPS_PLACE_DONT_PASS:"craps:place_dont_pass",CRAPS_PLACE_ODDS:"craps:place_odds",CRAPS_PLACE_PLACE:"craps:place_place",CRAPS_PLACE_FIELD:"craps:place_field",CRAPS_PLACE_BIG:"craps:place_big",CRAPS_PLACE_COME:"craps:place_come",CRAPS_PLACE_DONT_COME:"craps:place_dont_come",CRAPS_PLACE_COME_ODDS:"craps:place_come_odds",CRAPS_PLACE_DONT_COME_ODDS:"craps:place_dont_come_odds",CRAPS_TOGGLE_PLACE_WORKING:"craps:toggle_place_working",CRAPS_ROLL:"craps:roll",CRAPS_READY:"craps:ready",CRAPS_READY_UPDATE:"craps:ready_update",CRAPS_FETCH_HISTORY:"craps:fetch_history",POKER_ROOM_CREATE:"poker_room_create",POKER_ROOM_DELETE:"poker_room_delete",POKER_JOIN_ROOM:"poker_join_room",POKER_ACT:"poker:act",POKER_START_HAND:"poker:start_hand",POKER_ROOM_CREATED:"poker_room_created",POKER_ROOM_UPDATED:"poker_room_updated",POKER_ROOM_DELETED:"poker_room_deleted",POKER_JOINED_ROOM:"poker_joined_room",POKER_REJOINED_ROOM:"poker_rejoined_room",POKER_FETCH_HISTORY:"poker:fetch_history",POKER_START_READY_UPDATE:"poker:start_ready_update",GAME_INVITE_SEND:"game_invite:send",GAME_INVITE_RESPOND:"game_invite:respond",GAME_INVITE_RECEIVED:"game_invite:received",GAME_INVITE_CANCELLED:"game_invite:cancelled",POKER_AD_STARTED:"poker:ad_started",POKER_AD_COMPLETED:"poker:ad_completed",POKER_AD_FAILED:"poker:ad_failed",POKER_AD_REQUIRED:"poker:ad_required",POKER_AD_CLEARED:"poker:ad_cleared",POKER_PLAYER_AD_STATUS:"poker:player_ad_status",QUICK_MATCH_JOIN:"quick_match:join",QUICK_MATCH_LEAVE:"quick_match:leave",QUICK_MATCH_STATUS:"quick_match:status",QUICK_MATCH_FOUND:"quick_match:found",QUICK_MATCH_WAITING:"quick_match:waiting",SOCIAL_ONLINE_FRIENDS:"social:online_friends"};Object.freeze(hcA);const Lt=new Proxy(hcA,{set(){throw new TypeError("SocketEvents is read-only")},defineProperty(){throw new TypeError("SocketEvents is read-only")},deleteProperty(){throw new TypeError("SocketEvents is read-only")}}),DUA="data:audio/mp4;base64,AAAAHGZ0eXBNNEEgAAAAAE00QSBpc29tbXA0MgAAAAFtZGF0AAAAAAAACHkhIANAaBwhTuE5h+LsYiCvilbNXKcS0BitVYE9SNc0evNePa61+Z8fPn+j/f7bvwv1Hfs+vy2K8OXhDrVnwh7rcY/J7GoeN9vZoQqC4srBiAIptz6ALP25RIg4MSE6ZabZXAudF7C2F9WrVCtPjvCo2zgN65zbXJO2/YGjPc/gu8kKoUn0fRrvACx2qq4x6pvpYgEseZg9EuCYOKuLfO37xf82reT+1dw2OLir7jAeGeayVlQn9T+gQKKTQW1hVADPKJzu7J9kgIBhaLeiBk8aqUv40wAIwQxevFqQ246PdyYQft5CZAtrwC3+DAjRmX2+/C+4ObfObQ9We0ikCEg3ZrbGcqpMX4wAeQ/CRcEYnbQNSCYhFQyCCYng4Cqtme32Hnrx9v5/6a+zr1+/7+4+SHVrPgF1OMc0eupMA3Nxv1/QAKnXlMH0Gm58FQo2wbCv3hnH+gGPC2bz/LmBXLAaauTntyGGK7geDxR4IU6zQVmszRAqjKCyosXQGzGVQUQKIzVohIF9tzvXqmu9fHvnO7pu1P/n1/aWneQ/65+e+jvt8PCdOohAT/S/3dw1dm+8oWy68se0ux2Y4JoceYOXjtzXQD1KZyQccWgAU6RDlDi0XTKqJW2AsVBbkKmrE+nSaiz5Kjt6fPvHzOJfVg1htmqrUCQ92fC/gr1RuT9N7rfsYA7mEltF4s5hPr4ygEA0PejOqTnedYk8MWpMWoJgAj82gUeU94mhRFiEIIGt+rqkJUDGPyAYQoUMfm67hPhod3YcUmCcJ0ORraWn7eVZ6OMY8nAB4OIEANw/kdjzyEeS+UApmeQ2/TSiszfugCt8aSCDbWEdghf6QGejUaynpJgroIOVrpSYjU+O2eSFWnLjTVK4n3RlEoTwDjAe7xMLwXtfGmgTDOfwjf4tUdEMgAhmIfCQ7EghQeoQ+fb/j/u/CdOohABflVwyAFgWEschTpj////4PP/j//8PTaqYKISBqNyCpQmSIyhFgbbaGKrM7LIU/PPgu/f49+uf+/rvcrOsH+1f0XeO+F1+vn7eJ3J4++PD752wc/f3zk9TgRAIbiLK8s09S406sl1J+NWMxZboyQHlCnQisJ/xIFU7BnHz+1/Chy6vpEKAAihj7OnaXFW9iCdodbEqj4tX9MGh/AWGnmK2w9mESmG7fCRLpHbGSPPTOFOPGXyHjO9MyE4M0OKLYFehV0mGwfEN2yhFkUIzb/+giG9NXPCOZ3y1PnstBsWUmnJe8V9KpqTJDfg/dVm04DhNSe9eN2I57fb5pu8LyYrZfZZXPBukAfEP7KFEDyYz1ywOmv9ZjeuY+Xj2dPGWfKhBUc/BxfP4WREABmMm5McGRMmBigD0yQWLsr0yHP3IVOnUMKcx3JZY15jnpS+ODWRlm5ot9kPaM8FMDFO+YBKh+BoYSC+hPQkELC+wYcuggKCpPb4n5zfH6fD1OAkADBNNgeQAOEiszR569qr4IU5MgD/////gP4A/J3abQVSjlkJAw24RAqTZULAxWaQE+P4bur9UHs+c652wvv/2+v7zsnaP9OPXNGeuu5P8+3o5P4++Y9esgHwEAxDmwgx5CfgOqO/P1nNAhdZn8rtJmvMmmt4Lx7LP1VLZsL7PLV/emqmcoad0IzRugDn8XcipvozXIp6YVK2YTqfx6bLdTK7bFEmC6KaHHLZeK5xYiRLhZoNJpxTMoPhCAuTVN7ZGShCEkqZaLxIDIUApbW+Ql0vmAJSOn4iItJL3d0YJSvnQ98tLdYHXqmI5BRwX6M2M6kyZdLyOWss9BUysS8w90lxHGSjvGvD4ZdWDZTzzjTKPIrgaGYQerCg1NYcTSc3MayZHdOA6sa0e7E2z0VePfEqRfRMX3wu0xYIZTJr/p9dq2TwvAAx8ieh7GynXaN+akjY1bLV4F0bp7VuE7Z+NAQUnhCDPN/0xCB+IQ4N/Acf0FDWyP1v3U+zIEZdAevWQgACALGPUUmurBoAYKOAhbA4AAAAAAASNhqDHQ1hMSEIYhIIiAiZ7DA55Gxit2Dxq4bFzBJi+trFJKijFmr1nrMK9R0lXrebQmmrDhm7l949+jvDFVAlNl0SotM2MiulRpk6q6ZxJFdmsHloNhmqJ7z7scLAYjgJicjGU/NDgTs0SMdG4kckjIKBffTWaYN+Ks21c+RJvtndIwVDhRNQqmN/gelZoWFDzEeFQrjQABTrC7dw+Mf3qNExO+ZO79kDFBQcVJFNlpE7QX4KhtJVXPGu2SDbriZLP5oKFUvg1HxmAGS1jR/gACHP2+6dCK0w7j7lnJ9uR5hx/iAmRF/3vqUlFapS6oqARQqyhrdSgW4AhDA/4AAAAAASNOgqGIqiEwCEgEfjWLNr5QbzDdsYx3xcM1QuVm0UkiSSg6TM6fDUmJn8EmjufBhJ0StQNYX2qgNL08ZlXeayKUAKZDnSBmUddTAVVWGeAJ4mimJoPiMVVmvdt/3LBvFSpF4akTRHqOQGV/AnqG3af0h8AJSWfvPRwE73ycPn5vR1rOMRiRdMVqqgdPy7pj5/x/PojYAATflWCOztV19UfOurwT18P0c7ww4bZL+6tiVgQr4AR0wEoYmNemG+AlVNAj/pRSuO7qKgigSgSgRcrNopJEklwIQwP////wAAEHTBeQ2EISGDCPgBYKYg3pW8nWy5VxsSeHEAe2GkypPGiNh+g31iX2VZPLnmw4LQth0WdQ9lurM/vhqAS1/29Hu37ALfBVi8sTolPHq9Hl+H89joAlz5KE5l85I5tzzmWeDknKkWdnptWBQHvt55cPNulQCFAIQAAEy74oouY0+5zmabAdchD3KECDFgR+a9S+N2c8MknMla3M1MiLlXGxL48QB4HkyeHAPXj4AAAA1Jtb292AAAAbG12aGQAAAAA5RNTWeUTU1kAAKxEAAAUzAABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAB5HRyYWsAAABcdGtoZAAAAAHlE1NZ5RNTWQAAAAEAAAAAAAAUzAAAAAAAAAAAAAAAAAEAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAYBtZGlhAAAAIG1kaGQAAAAA5RNTWeUTU1kAAKxEAAAgAFXEAAAAAAAxaGRscgAAAAAAAAAAc291bgAAAAAAAAAAAAAAAENvcmUgTWVkaWEgQXVkaW8AAAABJ21pbmYAAAAQc21oZAAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAAA63N0YmwAAABnc3RzZAAAAAAAAAABAAAAV21wNGEAAAAAAAAAAQAAAAAAAAAAAAIAEAAAAACsRAAAAAAAM2VzZHMAAAAAA4CAgCIAAAAEgICAFEAUABgAAAH0AAAB9AAFgICAAhIQBoCAgAECAAAAGHN0dHMAAAAAAAAAAQAAAAgAAAQAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAAIAAAAAQAAADRzdHN6AAAAAAAAAAAAAAAIAAAABgAAAWYAAAFkAAABhAAAAX8AAAECAAAA3wAAALUAAAAUc3RjbwAAAAAAAAABAAAALAAAAPp1ZHRhAAAA8m1ldGEAAAAAAAAAImhkbHIAAAAAAAAAAG1kaXIAAAAAAAAAAAAAAAAAAAAAAMRpbHN0AAAAvC0tLS0AAAAcbWVhbgAAAABjb20uYXBwbGUuaVR1bmVzAAAAFG5hbWUAAAAAaVR1blNNUEIAAACEZGF0YQAAAAEAAAAAIDAwMDAwMDAwIDAwMDAwODQwIDAwMDAwMEUxIDAwMDAwMDAwMDAwMDE2REYgMDAwMDAwMDAgMDAwMDAwMDAgMDAwMDAwMDAgMDAwMDAwMDAgMDAwMDAwMDAgMDAwMDAwMDAgMDAwMDAwMDAgMDAwMDAwMDA=",J6="/assets/flash-1UjQ_pjl.m4a",L6="/assets/swoosh-DWLYYP2o.m4a",pcA="/assets/dice_whirr_merged-kYY8GDzo.m4a",mUA="/assets/loss-MbFJ6Xyb.m4a",SUA="/assets/winner-C_feQyA8.m4a",wUA="/assets/win-BofsSXdy.m4a",kUA="/assets/ante_up-BNJNkzdg.m4a",MUA="/assets/push-D8ciTeGD.m4a",NUA="/assets/your_turn-r-y-lDUH.m4a",RUA="/assets/point_set-BYYb2H7O.m4a",GUA="/assets/place_hit-B397CGff.m4a",bUA="/assets/yes-D6HNwLBK.m4a",UUA="/assets/smashing-CDhgl1WN.m4a",vUA="/assets/love_you-ClILzZiq.m4a",KUA="/assets/gangster-BuThOTHu.m4a",FUA="/assets/skills_win-B9044Qtf.m4a",_UA="/assets/skills_lose-C2hT1pjV.m4a",fcA="/assets/skills_lobby-Wq3LgbVY.m4a",JUA="/assets/zentara_theme-CMLmkTk1.m4a",LUA="/assets/zentara_explosion1-CjEhUDBF.mp3",xUA="/assets/zentara_explosion2-C8nIQN_s.mp3",TUA="/assets/zentara_explosion3-BTB3rcDN.mp3",qUA="/assets/zentara_fanfare-BovxnerY.mp3",YUA="data:audio/mpeg;base64, ",HUA="/assets/zentara_laser_burst-BEbiHJjZ.mp3",OUA="/assets/zentara_scan-DPmtrIPS.mp3",PUA="/assets/zentara_move-B9jZ_pmx.mp3",Ff=typeof navigator<"u"&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1),KE=typeof window<"u"?window.Capacitor:void 0,fL=!!KE&&typeof KE.isNativePlatform=="function"&&KE.isNativePlatform();var IaA;const _n=KE&&(((IaA=KE.Plugins)==null?void 0:IaA.NativeAudio)||KE.NativeAudio)||void 0,Md=fL&&!!_n,DS=fL&&Ff,jUA=fL&&!Ff;let va=!1,Kr=!0,XM=null;const Q8=500;function zUA(){return!!Kr}function x6(e){if(Kr=!!e,!Kr)try{SF(),tN()}catch{}}const ZUA=["vYes","vSmashing","vLove","vGangster"],Mr={click:DUA,flash:J6,chip:L6,win:SUA,winDing:wUA,lose:mUA,push:MUA,cardSwoosh:L6,placeBets:kUA,yourTurn:NUA,vYes:bUA,vSmashing:UUA,vLove:vUA,vGangster:KUA,pointSet:RUA,placeHit:GUA,betPlaced:J6,skillsWin:FUA,skillsLose:_UA,skillsLobby:fcA,zentaraExplosion1:LUA,zentaraExplosion2:xUA,zentaraExplosion3:TUA,zentaraFanfare:qUA,zentaraLaser:YUA,zentaraLaserBurst:HUA,zentaraScan:OUA,zentaraFuture:PUA},T6=["flash","win","winDing","lose","push","chip","cardSwoosh","placeBets","yourTurn","pointSet","vYes","vSmashing","vLove","vGangster","placeHit"],WUA=3,VUA=4,ycA=4,DcA=6,XUA=e=>e==="zentaraLaser"||e==="zentaraLaserBurst"?DcA:e.startsWith("zentaraExplosion")?ycA:1,mcA=DS?1:Ff?2:8;let g2=0,u8=!1;function ScA(){const e=performance.now();u8=g2>0&&e-g2>50,g2=e,requestAnimationFrame(ScA)}typeof requestAnimationFrame<"u"&&requestAnimationFrame(ScA);const wcA={flash:40,cardSwoosh:80,chip:60,click:25,win:25,winDing:25,lose:25,push:25,placeBets:250,yourTurn:250,pointSet:250,placeHit:250,vYes:2500,vSmashing:2500,vLove:2500,vGangster:2500},yF={},WE={};let nd=0,kcA=0;const o2=new WeakMap;let s2=!1;const q6=[];function $M(e){q6.push(e),!s2&&(s2=!0,requestAnimationFrame(()=>{s2=!1;const A=q6.splice(0);for(const t of A)t()}))}const OI=new Set,a2=new Map,AN=new Map;function gd(e){const A=Date.now(),t=AN.get(e)||{count:0,last:0};t.count=Math.min(5,t.count+1),t.last=A,AN.set(e,t)}function yL(e){e?AN.delete(e):AN.clear()}function DL(e){const A=AN.get(e);if(!A)return!0;const t=Date.now(),i=2e3*Math.min(3,A.count);return t-A.last>i}function $UA(e){try{const A=String(e||"");if(!A)return null;if(/^https?:\/\//i.test(A))return{path:A,isUrl:!0};if(/^data:/i.test(A))return null;if(/^file:\/\//i.test(A))return{path:A,isUrl:!0};if(/^capacitor:\/\//i.test(A)){const i=new URL(A).pathname||"";return i.startsWith("/assets/")?{path:`public${i}`,isUrl:!1}:i.startsWith("/public/")?{path:i.replace(/^\//,""),isUrl:!1}:{path:A,isUrl:!0}}return A.startsWith("./assets/")?{path:`public/${A.slice(2)}`,isUrl:!1}:A.startsWith("assets/")?{path:`public/${A}`,isUrl:!1}:A.startsWith("/assets/")?{path:`public${A}`,isUrl:!1}:A.startsWith("public/")?{path:A,isUrl:!1}:A.startsWith("/public/")?{path:A.slice(1),isUrl:!1}:{path:`public/${A.replace(/^\.\//,"")}`,isUrl:!1}}catch{return null}}const DF=new Map,Y6=DS?100:20;async function AvA(e){if(!(_n!=null&&_n.getDuration))return!0;try{const A=await _n.getDuration({assetId:e});return A&&typeof A.duration=="number"&&A.duration>0}catch{return!1}}async function eN(e,A){if(!Md||!_n)throw new Error("Native audio not available");if(OI.has(e))return;const t=a2.get(e);if(t){if(await t,!OI.has(e))throw new Error("Asset preload failed");return}try{const i=$UA(A);if(!i)throw gd(e),new Error("Failed to resolve asset path");const n=(async()=>{await _n.preload({assetId:e,assetPath:i.path,audioChannelNum:XUA(e)}),OI.add(e),DF.set(e,Date.now())})();a2.set(e,n),await n.finally(()=>{a2.delete(e)})}catch(i){throw gd(e),i}}async function evA(e,A,t){if(!Md||!_n)throw new Error("Native audio not available");if(!DL(e))throw new Error("Native audio cooldown active");try{if(await eN(e,A),!OI.has(e))throw new Error("Asset not loaded");const i=DF.get(e)||0,n=Date.now()-i;if(n<Y6&&await new Promise(g=>setTimeout(g,Y6-n)),DS&&!await AvA(e)){try{await _n.unload({assetId:e})}catch{}throw OI.delete(e),DF.delete(e),new Error("Asset verification failed - native player not ready")}if((t==null?void 0:t.volume)!=null&&_n.setVolume)try{await _n.setVolume({assetId:e,volume:ir(t.volume,0,1)})}catch{}try{await _n.play({assetId:e})}catch{await new Promise(o=>setTimeout(o,30)),await _n.play({assetId:e})}t!=null&&t.durationMs&&t.durationMs>0&&window.setTimeout(()=>{try{_n.stop({assetId:e})}catch{}},Math.max(10,Math.floor(t.durationMs)))}catch(i){throw gd(e),i}}function d8(e){const A=new Audio(Mr[e]);A.preload="auto";try{A.playsInline=!0}catch{}try{A.setAttribute("playsinline",""),A.setAttribute("webkit-playsinline","")}catch{}try{A.muted=!1}catch{}try{A.volume=1}catch{}return A.addEventListener("ended",()=>tB(e,A)),A}function Nd(e){let A=WE[e];if(!A){const t=McA(e);A={free:[],busy:new Set,size:0};for(let i=0;i<t;i++)A.free.push(d8(e)),A.size++;WE[e]=A}return A}function McA(e){return e==="flash"?VUA:e==="zentaraLaser"||e==="zentaraLaserBurst"?DcA:e.startsWith("zentaraExplosion")?ycA:WUA}function h8(e){const A=McA(e),t=Nd(e);if(t.free.length>0)return t.free.pop();if(t.size<A){const i=d8(e);return t.size++,i}return null}function tB(e,A){const t=WE[e];t&&t.busy.has(A)&&(t.busy.delete(A),t.free.push(A),nd=Math.max(0,nd-1))}function p8(){Object.keys(wcA).forEach(e=>delete yF[e])}function tvA(){try{OI.clear(),DF.clear(),yL()}catch{}}function mL(e,A=800){const t=o2.get(e);if(t)return t;const i=new Promise(n=>{try{if(e.readyState>=2){n(!0);return}let g=!1;const o=()=>{try{e.removeEventListener("canplaythrough",s)}catch{}try{e.removeEventListener("loadeddata",s)}catch{}try{e.removeEventListener("error",a)}catch{}},s=()=>{g||(g=!0,o(),n(!0))},a=()=>{g||(g=!0,o(),n(!1))};e.addEventListener("canplaythrough",s,{once:!0}),e.addEventListener("loadeddata",s,{once:!0}),e.addEventListener("error",a,{once:!0});try{e.load()}catch{}window.setTimeout(()=>{g||(g=!0,o(),n(e.readyState>=2))},Math.max(200,Math.min(4e3,A)))}catch{n(!1)}});return o2.set(e,i),i.finally(()=>{o2.delete(e)}),i}let db=null,rs=null,FE=null,mF=!1;function SF(){Object.keys(WE).forEach(e=>{const A=WE[e];A&&[...A.busy].forEach(t=>{try{t.pause(),t.currentTime=0}catch{}tB(e,t)})});try{db&&(db.pause(),db.currentTime=0)}catch{}try{rs&&(rs.pause(),rs.currentTime=0)}catch{}db=null,rs=null;try{}catch{}try{const e=Object.keys(Mr);for(const A of e){const t=yu==null?void 0:yu[A];if(t){try{t.pause(),t.currentTime=0}catch{}yu[A]=null}_E[A]&&(window.clearTimeout(_E[A]),delete _E[A])}if(Md&&_n){for(const A of Object.keys(Mr))if(OI.has(A)){try{ZD(_n.stop({assetId:A}))}catch{}try{_n.unload&&ZD(_n.unload({assetId:A}))}catch{}try{OI.delete(A)}catch{}}if(OI.has("loop_dice_whirr")){try{ZD(_n.stop({assetId:"loop_dice_whirr"}))}catch{}try{_n.unload&&ZD(_n.unload({assetId:"loop_dice_whirr"}))}catch{}try{OI.delete("loop_dice_whirr"),yL("loop_dice_whirr")}catch{}}mF=!1}}catch{}nd=0,p8()}let NcA=!1;function $k(e){NcA=!!e}let H6=0;const ivA=1500;async function nvA(e,A){if(!Kr||NcA)return!1;const t=Date.now();if(t-H6<ivA)return!1;if(H6=t,DS&&_n&&DL(e))try{return(async()=>{try{if(await eN(e,Mr[e]),OI.has(e)){if(_n.setVolume)try{await _n.setVolume({assetId:e,volume:ir(A,0,1)})}catch{}await _n.play({assetId:e})}}catch{gd(e)}})(),!0}catch{gd(e)}if(!va||Ff&&u8)return!1;try{const i=h8(e);if(!i){const g=new Audio(Mr[e]);return g.volume=ts(e,A),g.play().catch(()=>{}),!0}return Nd(e).busy.add(i),nd++,i.currentTime=0,i.volume=ts(e,A),i.play().catch(()=>tB(e,i)),!0}catch{return!1}}const gvA={3:"vGangster",4:"vLove",5:"vSmashing",6:"vYes",7:"vSmashing"};async function O6(e,A=.5){const t=gvA[e>=7?7:e];return t?nvA(t,A):!1}function SL(e,A){if(!Kr||!va||nd>=mcA)return;const t=h8(e);if(!t)return;Nd(e).busy.add(t),nd++;try{t.currentTime=0,(A==null?void 0:A.volume)!=null&&(t.volume=ts(e,A.volume)),(A==null?void 0:A.rate)!=null&&(t.playbackRate=ir(A.rate,.25,4));const n=A!=null&&A.durationMs&&A.durationMs>0?window.setTimeout(()=>{try{t.pause(),t.currentTime=0}catch{}tB(e,t)},Math.max(10,Math.floor(A.durationMs))):null;$M(()=>{t.play().catch(()=>{n&&window.clearTimeout(n),tB(e,t)})})}catch{tB(e,t)}}async function ws(e,A){if(!Kr)return;const t=Date.now();if(t<kcA||Ff&&u8&&e!=="win"&&e!=="lose"&&!(DS&&(e==="zentaraLaser"||e==="zentaraLaserBurst")))return;const i=wcA[e]??0;if(i>0){const o=yF[e]??0;if(t-o<i)return}if(yF[e]=t,DS&&_n&&DL(e)){(async()=>{try{await evA(e,Mr[e],{volume:A==null?void 0:A.volume,durationMs:A==null?void 0:A.durationMs})}catch{gd(e)}})();return}if(!va||XM&&t-XM<Q8)return;if(jUA){SL(e,A);return}if(nd>=mcA)return;const n=h8(e);if(!n)return;Nd(e).busy.add(n),nd++;try{n.currentTime=0,(A==null?void 0:A.volume)!=null&&(n.volume=ts(e,A.volume)),(A==null?void 0:A.rate)!=null&&(n.playbackRate=ir(A.rate,.25,4));const o=A!=null&&A.durationMs&&A.durationMs>0?window.setTimeout(()=>{try{n.pause(),n.currentTime=0}catch{}tB(e,n)},Math.max(10,Math.floor(A.durationMs))):null;if(!await mL(n,1e3)){$M(()=>{n.play().catch(()=>{o&&window.clearTimeout(o),tB(e,n)})});return}$M(()=>{n.play().catch(()=>{o&&window.clearTimeout(o),tB(e,n)})})}catch{tB(e,n)}}const ir=(e,A,t)=>Math.min(t,Math.max(A,e)),ovA={flash:.025,cardSwoosh:.02,chip:.25,win:.4,winDing:.025,lose:.1,push:.1,placeBets:.65,yourTurn:.5,pointSet:.12,placeHit:.12,vYes:.45,vSmashing:.45,vLove:.45,vGangster:.45,zentaraLaser:.14,zentaraLaserBurst:.12,lobbyMusic:.03};function ts(e,A){const t=ir(A,0,1);if(Ff){const i=ovA[e];if(typeof i=="number")return ir(Math.max(t,i),0,1)}return t}function VP(){Ff&&(Object.keys(WE).forEach(e=>{const A=e,t=WE[A];t&&t.free.forEach(i=>{try{i.pause(),i.src=Mr[A],i.load()}catch{}})}),p8())}function svA(){try{SF()}catch{}try{Yu()}catch{}try{tN()}catch{}}function avA(){tvA();try{VP()}catch{}p8()}var CaA;try{const e=KE&&(((CaA=KE.Plugins)==null?void 0:CaA.App)||KE.App)||void 0;fL&&(e!=null&&e.addListener)&&e.addListener("appStateChange",A=>{!!(A&&A.isActive)?avA():svA()})}catch{}let wF=null,np=!1,vD=0,RcA=0;function r2(){return!Md||np}function rvA(){return{loaded:vD,total:RcA}}async function IvA(e=5e3){if(!Md||np||!wF)return!0;try{return await Promise.race([wF,new Promise((A,t)=>setTimeout(()=>t(new Error("timeout")),e))]),!0}catch{return!1}}async function On(){if(!va){va=!0,XM=Date.now(),kcA=Date.now()+Q8,Object.keys(Mr).forEach(e=>{try{Nd(e)}catch{}});try{mS()}catch{}try{if(Md&&_n){const e=Object.keys(Mr);RcA=e.length,vD=0,np=!1,wF=(async()=>{for(const t of T6)try{await eN(t,Mr[t]),vD++,await new Promise(i=>setTimeout(i,15))}catch{vD++}const A=e.filter(t=>!T6.includes(t));for(const t of A)try{await eN(t,Mr[t]),vD++,await new Promise(i=>setTimeout(i,15))}catch{vD++}np=!0})(),wF.catch(()=>{np=!0})}else np=!0}catch{np=!0}}}function f8(){return!!va}function mS(e){const A=e&&e.length?e:Object.keys(Mr);for(const t of A)Nd(t).free.forEach(n=>{try{n.load()}catch{}})}async function kF(e,A=800){const t=e&&e.length?e:Object.keys(Mr),i=g=>new Promise(o=>{try{const a=Nd(g).free[0]||d8(g);mL(a,A).then(o)}catch{o(!1)}});return(await Promise.all(t.map(i))).every(Boolean)}if(typeof document<"u"){const e=()=>{document.visibilityState==="hidden"?(SF(),Yu(),tN()):VP()};document.addEventListener("visibilitychange",e),window.addEventListener("pagehide",()=>{SF(),Yu(),tN()}),window.addEventListener("pageshow",()=>VP())}function Vl(e){const t=ir((e==null?void 0:e.volume)??.01,0,1)*.5;ws("flash",{volume:ts("flash",t),rate:e==null?void 0:e.rate})}function CvA(e){ws("chip",{volume:ts("chip",(e==null?void 0:e.volume)??.25),durationMs:(e==null?void 0:e.durationMs)??500,rate:e==null?void 0:e.playbackRate})}function cvA(e){ws("cardSwoosh",{volume:ts("cardSwoosh",e==null?void 0:e.volume),rate:(e==null?void 0:e.playbackRate)??1})}function y8(e){ws("lose",{volume:ts("lose",(e==null?void 0:e.volume)??.1)})}function GcA(e){ws("push",{volume:ts("push",(e==null?void 0:e.volume)??.1)})}function lvA(e){const A=ir(e==null?void 0:e.volume,0,1),t=ts("win",A);ws("winDing",{volume:.025}),ws("win",{volume:ts("win",ir(t*.35,0,1))})}function XP(e){ws("winDing",{volume:ts("winDing",(e==null?void 0:e.volume)??.15),rate:e==null?void 0:e.rate})}function $P(e){ws("placeBets",{volume:ts("placeBets",(e==null?void 0:e.volume)??.65)})}function P6(e){ws("pointSet",{volume:ts("pointSet",(e==null?void 0:e.volume)??.15)})}function BvA(e){ws("betPlaced",{volume:ts("betPlaced",e==null?void 0:e.volume)})}function A1(e){ws("skillsWin",{volume:ts("skillsWin",(e==null?void 0:e.volume)??.5)}),ws("win",{volume:ts("win",.35)})}function e1(e){ws("skillsLose",{volume:ts("skillsLose",(e==null?void 0:e.volume)??.4)})}let cE=null,t1=!1;function wL(e){if(!(!Kr||!va)&&!(t1&&cE))try{cE||(cE=new Audio(fcA),cE.loop=!0),cE.volume=ts("lobbyMusic",(e==null?void 0:e.volume)??.075),cE.play().then(()=>{t1=!0}).catch(()=>{})}catch{}}function Yu(){if(cE)try{cE.pause(),cE.currentTime=0,t1=!1}catch{}}const EvA=.72,QvA={music:{defaultVolume:.1,trim:1},explosion:{defaultVolume:.24,trim:.9},fanfare:{defaultVolume:.2,trim:.45},laser:{defaultVolume:.26,trim:.62},scan:{defaultVolume:.18,trim:.78},move:{defaultVolume:.08,trim:.7}};function _f(e,A){const t=QvA[e];return ir((A??t.defaultVolume)*t.trim*EvA,0,1)}let lE=null,i1=!1;function uvA(e){if(!(!Kr||!va)&&!(i1&&lE))try{lE||(lE=new Audio(JUA),lE.loop=!0),lE.volume=ts("lobbyMusic",_f("music",e==null?void 0:e.volume)),lE.play().then(()=>{i1=!0}).catch(()=>{})}catch{}}function tN(){if(lE)try{lE.pause(),lE.currentTime=0,i1=!1}catch{}}const j6=["zentaraExplosion1","zentaraExplosion2","zentaraExplosion3"];let I2=0;function pa(e){if(!Kr||!va)return;const A=j6[I2%j6.length];I2++,SL(A,{volume:_f("explosion",e==null?void 0:e.volume),rate:.96+I2%3*.035})}function z6(e){!Kr||!va||SL("zentaraFanfare",{volume:_f("fanfare",e==null?void 0:e.volume)})}function Tc(e){!Kr||!va||ws("zentaraLaser",{volume:_f("laser",e==null?void 0:e.volume)})}function dvA(e){!Kr||!va||ws("zentaraLaserBurst",{volume:_f("laser",e==null?void 0:e.volume)})}function AM(e){!Kr||!va||SL("zentaraScan",{volume:_f("scan",e==null?void 0:e.volume)})}function hvA(e){ws("zentaraFuture",{volume:_f("move",e==null?void 0:e.volume)})}function Z6(e){const A=ir((e==null?void 0:e.sfxVolume)??.15,0,1);ws("winDing",{volume:ir(A*.25,0,1)}),window.setTimeout(()=>{ws("placeHit",{volume:ts("placeHit",A)})},90)}async function bcA(e,A=150){return new Promise(t=>{try{const n=Math.max(10,Math.floor(A/10));let g=0;const o=e.volume,s=window.setInterval(()=>{g++;const a=g/10;if(e.volume=Math.max(0,o*(1-a)),g>=10){window.clearInterval(s);try{e.pause(),e.currentTime=0}catch{}e.volume=o,t()}},n)}catch{try{e.pause(),e.currentTime=0}catch{}t()}})}function pvA(e){if(!Kr)return;const A=ir(e==null?void 0:e.volume,0,1),t=ir(e==null?void 0:e.playbackRate,.25,4);let i=!1;if(Md&&_n&&DL("loop_dice_whirr")){try{eN("loop_dice_whirr",pcA).then(async()=>{try{if(mF||(_n.loop?await _n.loop({assetId:"loop_dice_whirr"}):await _n.play({assetId:"loop_dice_whirr"}),mF=!0),_n.setVolume)try{await _n.setVolume({assetId:"loop_dice_whirr",volume:A})}catch{}}catch{gd("loop_dice_whirr"),C2(A,t)}}).catch(()=>{gd("loop_dice_whirr"),C2(A,t)}),i=!0}catch{}if(i){try{FE&&window.clearTimeout(FE),FE=window.setTimeout(()=>{try{RC()}catch{}},8e3)}catch{}return}}va&&C2(A,t)}function C2(e,A){if(va)try{if(!rs){rs=new Audio(pcA),rs.loop=!0,rs.preload="auto";try{rs.playsInline=!0}catch{}mL(rs,800)}if(!rs.paused){rs.volume=e,rs.playbackRate=A;return}rs.volume=e,rs.playbackRate=A,rs.currentTime=0,$M(()=>{rs&&rs.play().catch(()=>{})}),FE&&window.clearTimeout(FE),FE=window.setTimeout(()=>{try{RC()}catch{}},8e3)}catch{}}function RC(){if(FE&&(window.clearTimeout(FE),FE=null),Md&&_n)try{try{ZD(_n.stop({assetId:"loop_dice_whirr"}))}catch{}try{_n.unload&&ZD(_n.unload({assetId:"loop_dice_whirr"}))}catch{}try{OI.delete("loop_dice_whirr"),yL("loop_dice_whirr")}catch{}mF=!1}catch{}try{rs&&bcA(rs,120)}catch{}}function ZD(e){try{return e&&typeof e.then=="function"?e.catch(()=>{}):Promise.resolve()}catch{return Promise.resolve()}}const yu={},_E={};function UcA(e,A){ZUA.includes(e)||ws(e,{volume:A==null?void 0:A.volume,rate:A==null?void 0:A.rate,durationMs:A==null?void 0:A.durationMs})}function fvA(e,A){if(!(!Kr||!va)&&!(XM&&Date.now()-XM<Q8))try{let t=yu[e];if(!t){t=new Audio(Mr[e]),t.loop=!0,t.preload="auto";try{t.playsInline=!0}catch{}yu[e]=t,mL(t,800)}const i=ir((A==null?void 0:A.volume)??.1,0,1),n=ir((A==null?void 0:A.rate)??1,.25,4);if(!t.paused){t.volume=i,t.playbackRate=n;return}t.volume=i,t.playbackRate=n,t.currentTime=0,$M(()=>{t.play().catch(()=>{})}),_E[e]&&window.clearTimeout(_E[e]);const g=Math.max(5e3,Math.min(6e4,(A==null?void 0:A.maxMs)??15e3));_E[e]=window.setTimeout(()=>{try{vcA(e)}catch{}},g)}catch{}}async function vcA(e){try{_E[e]&&(window.clearTimeout(_E[e]),delete _E[e]);const A=yu[e];if(!A)return;await bcA(A,120),yu[e]=null}catch{}}function c2(){try{On()}catch{}}async function l2(e,A){try{if(e==="__probe__")return Promise.resolve(!!va);const t=e;return t in Mr?A!=null&&A.loop?(fvA(t,{volume:A.volume,rate:A.rate}),!0):(UcA(t,{volume:A==null?void 0:A.volume,rate:A==null?void 0:A.rate}),!0):!1}catch{return!1}}function B2(e){try{mS(e)}catch{}}function W6(e){try{const A=e;try{vcA(A)}catch{}const t=WE[A];if(t){try{[...t.busy].forEach(i=>{try{i.pause(),i.currentTime=0}catch{}})}catch{}delete WE[A]}try{delete yF[A]}catch{}try{OI.delete(A),yL(A)}catch{}try{Nd(A)}catch{}}catch{}}const yvA=(()=>{var e,A;try{return!!((A=(e=import.meta)==null?void 0:e.env)!=null&&A.DEV)}catch{return!1}})(),Du=[];function n1(e,A){try{Du.push({event:e,ts:Date.now(),mode:A}),Du.length>12&&Du.shift()}catch{}}function Kl(){return[...Du]}function eM(e,A=2e3){var n,g,o,s;if(e.connected)return Promise.resolve();const t=!!(e!=null&&e.__allowCookieAuth);return!String(((n=e==null?void 0:e.auth)==null?void 0:n.token)||((s=(o=(g=e==null?void 0:e.io)==null?void 0:g.opts)==null?void 0:o.auth)==null?void 0:s.token)||"")&&!t?Promise.reject(new Error("NO_AUTH_TOKEN")):(Za(e,"emit.ensureConnected",{allowCookieSession:t}),new Promise((a,r)=>{var d;let I=!1;const c=()=>{I||(I=!0,Q(),a())},l=p=>{I||(I=!0,Q(),r(p??new Error("socket connect error")))},B=()=>{I||(I=!0,Q(),r(new Error("socket connect timeout")))},Q=()=>{try{e.off("connect",c)}catch{}try{e.off("connect_error",l)}catch{}clearTimeout(h)},h=setTimeout(B,Math.max(300,A));(d=h.unref)==null||d.call(h),e.once("connect",c),e.once("connect_error",l)}))}async function g1(e,A,t,i){var o,s,a,r,I,c,l,B;try{FcA(A)}catch{}const n=(i==null?void 0:i.timeoutMs)??15e3;try{await eM(e)}catch(Q){const h=String((Q==null?void 0:Q.message)||Q||"");if(/socket has been disconnected|the socket is disconnected|connect_error|transport (?:close|error)|timeout/i.test(h)){try{const d=!!(e!=null&&e.__allowCookieAuth);Za(e,"emit.ts:emitAck-ensureConnected-fallback",{allowCookieSession:d})}catch{}await new Promise(d=>{const p=setTimeout(()=>d(),800);e.once("connect",()=>{clearTimeout(p),d()})})}else throw Q}n1(A,"ack");const g=()=>new Promise((Q,h)=>{e.timeout(n).emit(A,t,(d,p)=>d?h(d):p?Q(p):h(new Error("No ack payload received")))});try{return await g()}catch(Q){const h=String((Q==null?void 0:Q.message)||Q||"");try{if(/operation has timed out|timeout/i.test(h)){const d=(a=(s=(o=e==null?void 0:e.io)==null?void 0:o.engine)==null?void 0:s.transport)==null?void 0:a.name,p=(t==null?void 0:t.roomId)||null,y=((r=Du[Du.length-1])==null?void 0:r.event)||"unknown";tf("socket_ack_timeout",{event:String(A),scope:String(A).includes("craps")?"craps":String(A).includes("poker")?"poker":"other",roomId:p,lastEvent:y,timeoutMs:n,connected:!!e.connected,transport:d||"unknown",phase:"initial"}),console.warn("[client][timeout]",{event:String(A),roomId:p,lastEvent:y,timeoutMs:n,ts:Date.now()})}}catch{}if(/socket has been disconnected|the socket is disconnected/i.test(h)||/connect_error|transport close|transport error/i.test(h)){try{const d=!!(e!=null&&e.__allowCookieAuth);Za(e,"emit.ts:emitAck-disconnect-retry",{allowCookieSession:d})}catch{}try{await new Promise(d=>{const p=setTimeout(()=>d(),1e3);e.once("connect",()=>{clearTimeout(p),d()})})}catch{}try{return await g()}catch(d){const p=String((d==null?void 0:d.message)||d||"");try{if(/operation has timed out|timeout/i.test(p)){const y=(l=(c=(I=e==null?void 0:e.io)==null?void 0:I.engine)==null?void 0:c.transport)==null?void 0:l.name,m=(t==null?void 0:t.roomId)||null,D=((B=Du[Du.length-1])==null?void 0:B.event)||"unknown";tf("socket_ack_timeout",{event:String(A),scope:String(A).includes("craps")?"craps":String(A).includes("poker")?"poker":"other",roomId:m,lastEvent:D,timeoutMs:n,connected:!!e.connected,transport:y||"unknown",phase:"retry"}),console.warn("[client][timeout][retry]",{event:String(A),roomId:m,lastEvent:D,timeoutMs:n,ts:Date.now()})}}catch{}throw d}}throw Q}}async function KcA(e,A,t){try{FcA(A)}catch{}try{await eM(e),n1(A,"ff"),e.emit(A,t)}catch(i){const n=String((i==null?void 0:i.message)||i||"");if(/NO_AUTH_TOKEN|socket connect timeout|socket has been disconnected|the socket is disconnected|connect_error|transport (?:close|error)|timeout/i.test(n)){try{const g=!!(e!=null&&e.__allowCookieAuth);Za(e,"emit.ts:emitFF-fallback",{allowCookieSession:g})}catch{}if(await new Promise(g=>{const o=setTimeout(()=>g(),800);e.once("connect",()=>{clearTimeout(o),g()})}),!e.connected)return;n1(A,"ff"),e.emit(A,t);return}try{tf("socket_ff_emit_error",{event:String(A),message:n.slice(0,180),connected:!!e.connected})}catch{}if(yvA)try{console.warn("[emitFF] unexpected error",{event:String(A),message:n,connected:!!e.connected})}catch{}return}}function FcA(e){new Set([Lt.ROLL_DICE,Lt.PLACE_MAIN_BET,Lt.CREATE_SIDE_BET,Lt.ACCEPT_SIDE_BET,Lt.CANCEL_SIDE_BET,Lt.POKER_ACT,"poker:start_hand","craps:roll"]).has(e)&&On()}const _cA=Ca();async function DvA(e,A,t="usd"){return await(await fetch(`${_cA}/api/payment/chips`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({amount:e,userId:A,currency:t})})).json()}async function mvA(e,A){return await(await fetch(`${_cA}/api/payment/membership`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({planId:e,userId:A})})).json()}const V6={createChipsCheckout:DvA,createMembershipCheckout:mvA},JcA=E.createContext(void 0),SvA=({children:e})=>{const[A,t]=E.useState("idle"),[i,n]=E.useState(null),[g,o]=E.useState(!1),[s,a]=E.useState(!1),r=E.useCallback(async(c,l,B="usd")=>{t("loading"),n(null);try{const Q=await V6.createChipsCheckout(c,l,B);return Q.url?(t("success"),Q.url):(t("error"),n(Q.error||"Unable to start chips checkout"),null)}catch(Q){return t("error"),n(Q.message||"Unable to start chips checkout"),null}},[]),I=E.useCallback(async(c,l)=>{t("loading"),n(null);try{const B=await V6.createMembershipCheckout(c,l);return B.url?(t("success"),B.url):(t("error"),n(B.error||"Unable to start membership checkout"),null)}catch(B){return t("error"),n(B.message||"Unable to start membership checkout"),null}},[]);return C.jsx(JcA.Provider,{value:{status:A,error:i,startChipsCheckout:r,startMembershipCheckout:I,setStatus:t,setError:n,membershipModalOpen:g,setMembershipModalOpen:o,chipsModalOpen:s,setChipsModalOpen:a},children:e})};function RR(){const e=E.useContext(JcA);return e||{status:"idle",error:null,startChipsCheckout:async()=>null,startMembershipCheckout:async()=>null,setStatus:()=>{},setError:()=>{},membershipModalOpen:!1,setMembershipModalOpen:()=>{},chipsModalOpen:!1,setChipsModalOpen:()=>{}}}function vI(){const e=typeof globalThis<"u"?globalThis.crypto:void 0;try{if(e&&typeof e.randomUUID=="function")return e.randomUUID()}catch{}try{if(e&&typeof e.getRandomValues=="function"){const s=new Uint8Array(16);e.getRandomValues(s),s[6]=s[6]&15|64,s[8]=s[8]&63|128;const a=Array.from(s,r=>r.toString(16).padStart(2,"0")).join("");return`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`}}catch{}const A=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0"),t=A(),i=A().slice(0,4),n=("4"+A()).slice(0,4),g=((8+Math.floor(Math.random()*4)).toString(16)+A()).slice(0,4),o=(A()+A()).slice(0,12);return`${t}-${i}-${n}-${g}-${o}`}function wvA(e,A){const t=E.useCallback(async()=>{if(!e)throw new Error("Socket unavailable");if(e.connected)return e;try{!e.active&&e.disconnected&&Za(e,"useEmitter.ensureConnected"),await new Promise(g=>{const o=setTimeout(()=>g(),4e3);e.once("connect",()=>{clearTimeout(o),g()})})}catch{}return e},[e]),i=E.useCallback(async(g,o,s)=>{const a=await t();let r=o;if(o&&typeof o=="object"&&!o.eventId)try{r={...o,eventId:vI()}}catch{}const I={room_create:3e4,poker_room_create:3e4},c=(s==null?void 0:s.timeoutMs)||15e3,l=g in I?I[g]:c,B={...s,timeoutMs:l},Q=async()=>g1(a,g,r,B);let h,d=0;const p=2,y=async()=>{try{return await Q()}catch(m){const D=String((m==null?void 0:m.message)||m||"");if(/NO_AUTH_TOKEN/i.test(D))return{ok:!1,error:"NO_AUTH_TOKEN"};const S=/socket connect timeout/i.test(D)||/ETIMEDOUT/i.test(D)||/timeout/i.test(D),k=/socket has been disconnected/i.test(D)||/the socket is disconnected/i.test(D);if((S||k||/connect_error|transport close|transport error/i.test(D))&&d<p){d++;const w=(/create/i.test(g)?1500:800)*Math.pow(2,d-1);try{e&&e.disconnected&&Za(e,"useSocketEmitters:backoff-retry"),await new Promise(b=>{const _=setTimeout(()=>b(),w);e==null||e.once("connect",()=>{clearTimeout(_),b()})})}catch{}return y()}else throw m}};h=await y();try{if(h&&h.ok===!1&&(h.error==="rate_limited"||/rate[_-]?limited/i.test(h.error||""))){console.debug("[socket][rate_limited]",{event:String(g),ts:Date.now()});try{A&&A(String(g))}catch{}}}catch{}return h},[t,A]),n=E.useCallback(async(g,o)=>{const s=await t();return KcA(s,g,o)},[t]);return{ack:i,send:n}}function Mo(){const e=Ms(),{info:A}=MB(),t=E.useRef(0),i=E.useCallback(kA=>{const se=Date.now();if(!(se-t.current<1200)){t.current=se;try{A("Please wait a moment - you're doing that too quickly.",{duration:2500})}catch{}}},[A]),{ack:n,send:g}=wvA(e,i),{setMembershipModalOpen:o}=RR(),{user:s}=tn(),a=E.useCallback(kA=>{const se=(()=>{const VA={};try{if(VA.name=String(kA.name||"").trim().slice(0,60),(kA.isPrivate===!0||kA.isPrivate===!1)&&(VA.isPrivate=!!kA.isPrivate),(kA.singlePlayer===!0||kA.singlePlayer===!1)&&(VA.singlePlayer=!!kA.singlePlayer),typeof kA.botsPerRoom=="number"&&Number.isInteger(kA.botsPerRoom)&&(VA.botsPerRoom=kA.botsPerRoom),(kA.gameMode==="cee-lo"||kA.gameMode==="craps"||kA.gameMode==="zentara")&&(VA.gameMode=kA.gameMode),typeof kA.botLevel=="number"&&kA.botLevel>=1&&kA.botLevel<=9&&(VA.botLevel=kA.botLevel),kA.gameMode==="zentara"&&kA.gameRules&&typeof kA.gameRules=="object"){const nA={};kA.gameRules.disableRaid===!0&&(nA.disableRaid=!0),kA.gameRules.disableSpyStrike===!0&&(nA.disableSpyStrike=!0),Object.keys(nA).length>0&&(VA.gameRules=nA)}}catch{}return VA})(),Ce=Date.now();try{console.log("[socket][createRoom] emitting",{sanitized:se,timestamp:Ce})}catch{}return n(Lt.CREATE_ROOM,se).then(VA=>{var vA,KA;const nA=Date.now()-Ce;try{console.log("[socket][createRoom] response",{ok:VA==null?void 0:VA.ok,roomId:((vA=VA==null?void 0:VA.room)==null?void 0:vA.roomId)??((KA=VA==null?void 0:VA.room)==null?void 0:KA.id),duration:nA,error:VA==null?void 0:VA.error,res:VA}),VA&&VA.ok===!1&&console.warn("[socket][createRoom] ack error",VA.error)}catch{}return VA})},[n,o,s]),r=E.useCallback(async kA=>{const se=Date.now();console.log("[joinRoom] attempting join",{roomId:kA,timestamp:se,socketConnected:e==null?void 0:e.connected});const Ce=async()=>n(Lt.JOIN_ROOM,{roomId:kA});let VA=await Ce();const nA=Date.now()-se;if(console.log("[joinRoom] first attempt result",{roomId:kA,ok:VA==null?void 0:VA.ok,duration:nA,error:VA==null?void 0:VA.error}),VA&&VA.ok===!1&&/Room not found/i.test(String(VA.error||""))){console.warn("[useSocketEmitters] Room not found on first join attempt, retrying...",{roomId:kA,res:VA,firstAttemptDuration:nA});try{await new Promise(WA=>setTimeout(WA,120))}catch{}const vA=Date.now();VA=await Ce();const KA=Date.now()-vA;VA&&VA.ok===!1?console.error("[useSocketEmitters] Room not found after retry",{roomId:kA,res:VA,retryDuration:KA,totalDuration:Date.now()-se}):console.log("[useSocketEmitters] Retry successful",{roomId:kA,retryDuration:KA,totalDuration:Date.now()-se})}if(VA&&VA.ok===!1&&VA.error===eGA.SOCKET.NEEDS_PREMIUM)try{o(!0)}catch{}return VA},[n,o]),I=E.useCallback(kA=>n(Lt.LEAVE_ROOM,{roomId:kA}),[n]),c=E.useCallback(kA=>g(Lt.LEAVE_ROOM,{roomId:kA}),[g]),l=E.useCallback((kA,se,Ce,VA,nA)=>n("skills:submit",{roomId:kA,path:se,word:Ce,tsClient:VA,seq:nA}),[n]),B=E.useCallback((kA,se,Ce,VA,nA)=>n("skills:tap",{roomId:kA,r:se,c:Ce,tsClient:VA,seq:nA}),[n]),Q=E.useCallback((kA,se)=>n("anagrams:submit",{roomId:kA,word:se}),[n]),h=E.useCallback((kA,se,Ce)=>n("trivia:answer",{roomId:kA,questionIndex:se,answerIndex:Ce}),[n]),d=E.useCallback(kA=>n(Lt.ROLL_DICE,{roomId:kA}),[n]),p=E.useCallback(kA=>n(Lt.CONFIRM_BETS,{roomId:kA}),[n]),y=E.useCallback((kA,se)=>n(Lt.CRAPS_PLACE_PASS,{roomId:kA,amount:se}),[n]);E.useCallback((kA,se)=>n(Lt.CRAPS_PLACE_DONT_PASS,{roomId:kA,amount:se}),[n]);const m=E.useCallback((kA,se,Ce)=>n(Lt.CRAPS_PLACE_ODDS,{roomId:kA,amount:se,passType:Ce}),[n]),D=E.useCallback((kA,se,Ce)=>n(Lt.CRAPS_PLACE_PLACE,{roomId:kA,amount:se,point:Ce}),[n]),S=E.useCallback((kA,se)=>n(Lt.CRAPS_PLACE_FIELD,{roomId:kA,amount:se}),[n]),k=E.useCallback((kA,se,Ce)=>n(Lt.CRAPS_PLACE_BIG,{roomId:kA,amount:se,kind:Ce}),[n]),N=E.useCallback((kA,se)=>n(Lt.CRAPS_PLACE_COME,{roomId:kA,amount:se}),[n]),G=E.useCallback((kA,se)=>n(Lt.CRAPS_PLACE_DONT_COME,{roomId:kA,amount:se}),[n]),M=E.useCallback((kA,se,Ce)=>n(Lt.CRAPS_PLACE_COME_ODDS,{roomId:kA,point:se,amount:Ce}),[n]),w=E.useCallback((kA,se,Ce)=>n(Lt.CRAPS_PLACE_DONT_COME_ODDS,{roomId:kA,point:se,amount:Ce}),[n]),b=E.useCallback((kA,se)=>n(Lt.CRAPS_TOGGLE_PLACE_WORKING,{roomId:kA,working:se}),[n]),_=E.useCallback(async kA=>{try{const se=eA.current.get(kA)||[],Ce=aA.current.get(kA);if(Ce&&(clearTimeout(Ce),aA.current.delete(kA)),se.length>0)if(eA.current.delete(kA),se.length>1)await n("craps:add_bets_batch",{roomId:kA,bets:se,eventId:vI()});else{const{type:VA,amount:nA}=se[0];await n("craps:add_bet",{roomId:kA,type:VA,amount:nA,eventId:vI()})}}catch{}try{const se=pA.current.get(kA)||[],Ce=gA.current.get(kA);if(Ce&&(clearTimeout(Ce),gA.current.delete(kA)),se.length>0)if(pA.current.delete(kA),se.length>1)await n("craps:remove_bets_batch",{roomId:kA,bets:se,eventId:vI()});else{const{type:VA,amount:nA}=se[0];await n("craps:remove_bet",{roomId:kA,type:VA,amount:nA,eventId:vI()})}}catch{}},[n]),K=E.useCallback(async kA=>{try{if(!kA)return console.debug("[socket][crapsRoll] blocked: no roomId"),{ok:!1,error:"no_room"}}catch{}try{await _(kA)}catch{}return n(Lt.CRAPS_ROLL,{roomId:kA})},[n,_]),J=E.useCallback(kA=>n(Lt.CRAPS_READY,{roomId:kA}),[n]),q=E.useCallback((kA,se)=>n(Lt.CRAPS_FETCH_HISTORY,{roomId:kA,...se||{}}),[n]),v=E.useCallback(kA=>n("craps:get_state",{roomId:kA}),[n]),U=E.useCallback(kA=>n("craps:join_order",{roomId:kA}),[n]),x=E.useCallback(kA=>n("craps:leave_order",{roomId:kA}),[n]),T=E.useCallback(kA=>n("craps:pass_turn",{roomId:kA}),[n]),z=E.useCallback((kA,se)=>n("craps:set_order",{roomId:kA,order:se}),[n]),Z=E.useCallback(kA=>n("craps:reset_shooter",{roomId:kA}),[n]),eA=E.useRef(new Map),aA=E.useRef(new Map),sA=80,pA=E.useRef(new Map),gA=E.useRef(new Map),yA=80,fA=E.useCallback(kA=>n("craps:list_bets",{roomId:kA,eventId:vI()}),[n]),RA=E.useCallback((kA,se,Ce)=>{const VA=eA.current.get(kA)||[];VA.push({type:se,amount:Ce}),eA.current.set(kA,VA);const nA=aA.current.get(kA);nA&&clearTimeout(nA);const vA=setTimeout(()=>{const KA=eA.current.get(kA)||[];if(KA.length!==0)if(eA.current.delete(kA),aA.current.delete(kA),KA.length>1)n("craps:add_bets_batch",{roomId:kA,bets:KA,eventId:vI()});else{const{type:WA,amount:bA}=KA[0];n("craps:add_bet",{roomId:kA,type:WA,amount:bA,eventId:vI()})}},sA);return aA.current.set(kA,vA),Promise.resolve({ok:!0})},[n]),qA=E.useCallback((kA,se)=>n("craps:add_bets_batch",{roomId:kA,bets:se,eventId:vI()}),[n]),W=E.useCallback((kA,se)=>n("craps:remove_bets_batch",{roomId:kA,bets:se,eventId:vI()}),[n]),$=E.useCallback((kA,se,Ce)=>{const VA=pA.current.get(kA)||[];VA.push({type:se,amount:Ce}),pA.current.set(kA,VA);const nA=gA.current.get(kA);nA&&clearTimeout(nA);const vA=setTimeout(()=>{const KA=pA.current.get(kA)||[];if(KA.length!==0)if(pA.current.delete(kA),gA.current.delete(kA),KA.length>1)n("craps:remove_bets_batch",{roomId:kA,bets:KA,eventId:vI()});else{const{type:WA,amount:bA}=KA[0];n("craps:remove_bet",{roomId:kA,type:WA,amount:bA,eventId:vI()})}},yA);return gA.current.set(kA,vA),Promise.resolve({ok:!0})},[n]),L=E.useCallback(kA=>n("craps:clear_bets",{roomId:kA,eventId:vI()}),[n]),H=E.useCallback(kA=>n("craps:summarize",{roomId:kA}),[n]),P=E.useCallback(kA=>n(Lt.BANKER_GIVE_UP,{roomId:kA}),[n]),tA=E.useCallback(async()=>{const kA=async()=>n(Lt.GET_ROOMS_LIST,{});let se=await kA();return se&&se.ok===!1&&se.error==="invalid_payload"&&(await new Promise(Ce=>setTimeout(Ce,80)),se=await kA()),se},[n]),iA=E.useCallback((kA,se)=>n(Lt.SPECTATE_SET,{roomId:kA,spectate:se}),[n]),oA=E.useCallback(async(kA,se)=>{const Ce=await n(Lt.PLACE_MAIN_BET,{roomId:kA,amount:se});try{tf("bet_place",{game:"cee-lo",type:"MAIN",amount:se})}catch{}return Ce},[n]),IA=E.useCallback((kA,se)=>n(Lt.CANCEL_MAIN_BET,{roomId:kA,wagerId:se}),[n]),CA=E.useCallback((kA,se)=>n(Lt.CREATE_SIDE_BET,{roomId:kA,...se}),[n]),_A=E.useCallback((kA,se)=>n(Lt.ACCEPT_SIDE_BET,{roomId:kA,wagerId:se}),[n]),uA=E.useCallback((kA,se)=>n(Lt.CANCEL_SIDE_BET,{roomId:kA,wagerId:se}),[n]),X=E.useCallback(async kA=>{if(!kA)return{ok:!1,error:"no_room"};const se={roomId:kA};try{console.debug("[socket][getWagers] emit",se)}catch{}const Ce=await n(Lt.GET_WAGERS,se);if(Ce&&Ce.ok===!1)try{console.warn("[socket][getWagers] ack error",Ce.error)}catch{}return Ce},[n]),O=E.useCallback(kA=>n(Lt.RTC_JOIN,{roomId:kA}),[n]),cA=E.useCallback(kA=>{var se,Ce;try{(Ce=(se=e==null?void 0:e.volatile)==null?void 0:se.emit)==null||Ce.call(se,Lt.RTC_LEAVE,{roomId:kA})}catch{}},[e]),wA=E.useCallback(async(kA,se,Ce)=>{try{await g(Lt.RTC_SIGNAL,{roomId:kA,toPeerId:se,payload:Ce})}catch(VA){const nA=String((VA==null?void 0:VA.message)||VA||"");if(/disconnect|timeout|transport/i.test(nA)){await new Promise(vA=>setTimeout(vA,200));try{await g(Lt.RTC_SIGNAL,{roomId:kA,toPeerId:se,payload:Ce})}catch{}}}},[g]),xA=E.useCallback((kA,se)=>n(Lt.RTC_SET_CAMERA_OWNER,{roomId:kA,ownerId:se}),[n]),YA=E.useCallback(async(kA,se)=>{try{if(!kA)return{ok:!1,error:"no_room"};const Ce=await n(Lt.RTC_SET_VIDEO_ENABLED,{roomId:kA,enabled:se});return Ce.ok||console.error("Failed to set video enabled:",Ce.error),Ce}catch(Ce){console.error("Error setting video enabled:",Ce)}},[n,o]),jA=E.useCallback((kA,se)=>n(Lt.ROOM_SEND_MESSAGE,{roomId:kA,text:se}),[n]),ie=E.useCallback((kA,se)=>n(Lt.ROOM_FETCH_HISTORY,{roomId:kA,sinceTs:se}),[n]),he=E.useCallback((kA,se)=>n(Lt.DM_SEND_MESSAGE,{toUserId:kA,text:se}),[n]),le=E.useCallback((kA,se)=>n(Lt.DM_FETCH_HISTORY,{peerUserId:kA,sinceTs:se}),[n]),NA=E.useCallback(()=>n(Lt.LOBBY_JOIN,{}),[n]),EA=E.useCallback(()=>g(Lt.LOBBY_LEAVE,{}),[g]),PA=E.useCallback(()=>n(Lt.LOBBY_LIST,{}),[n]),ZA=E.useCallback(kA=>n(Lt.DELETE_ROOM,{roomId:kA}),[n]),FA=E.useCallback(()=>n(Lt.USER_GET_BALANCE,void 0),[n]),Ie=E.useCallback((kA,se)=>n(Lt.SEND_FRIEND_REQUEST,{toUserId:kA,message:se}),[n]),DA=E.useCallback(kA=>n(Lt.CANCEL_FRIEND_REQUEST,{requestId:kA}),[n]),rA=E.useCallback((kA,se)=>n(Lt.RESPOND_FRIEND_REQUEST,{requestId:kA,action:se}),[n]),BA=E.useCallback(kA=>n(Lt.UNFRIEND,{otherId:kA}),[n]),j=E.useCallback(kA=>n(Lt.BLOCK_USER,{blockedId:kA}),[n]),QA=E.useCallback(kA=>n(Lt.UNBLOCK_USER,{blockedId:kA}),[n]),dA=E.useCallback(()=>n(Lt.SOCIAL_GET_LIST,void 0),[n]),UA=E.useCallback((kA,se,Ce)=>n(Lt.GAME_INVITE_SEND,{roomId:kA,toUserId:se,gameMode:Ce}),[n]),TA=E.useCallback((kA,se)=>n(Lt.GAME_INVITE_RESPOND,{inviteId:kA,action:se}),[n]),oe=E.useCallback((kA,se)=>n(Lt.QUICK_MATCH_JOIN,{gameMode:kA,botsPerRoom:se}),[n]),me=E.useCallback(()=>n(Lt.QUICK_MATCH_LEAVE,void 0),[n]),be=E.useCallback(()=>n(Lt.QUICK_MATCH_STATUS,void 0),[n]),$e=E.useCallback(()=>n(Lt.SOCIAL_ONLINE_FRIENDS,void 0),[n]),ci=E.useCallback(kA=>n(Lt.USER_UPDATE_PROFILE,kA),[n]),ke=E.useCallback(kA=>n(Lt.BOTS_NUDGE,{roomId:kA??null}),[n]),nt=E.useCallback(kA=>n(Lt.ROOM_REFRESH_STATE,{roomId:kA??null}),[n]),Ut=E.useCallback((kA,se)=>g("player:visibility",{roomId:kA,visible:se}),[g]),dt=E.useCallback(async(kA,se,Ce,VA,nA)=>n("skills:single_start",{stake:kA,gameMode:se,duration:Ce,botLevel:VA,autoplay:nA}),[n]),Ht=E.useCallback(async(kA,se,Ce)=>n("skills:autoplay_start",{gameMode:kA,duration:se,botLevel:Ce}),[n]),Ft=E.useCallback(async kA=>n("skills:ready",{roomId:kA}),[n]),Jt=E.useCallback(async kA=>n("skills:room_create",kA),[n]),$A=E.useCallback(async kA=>n("skills:join_room",{roomId:kA}),[n]),He=E.useCallback(async kA=>n("skills:leave_room",{roomId:kA}),[n]),Xe=E.useCallback(async kA=>n("skills:spectator_join",{roomId:kA}),[n]),St=E.useCallback(async kA=>n("skills:spectator_leave",{roomId:kA}),[n]);return{createRoom:a,joinRoom:r,leaveRoom:I,leaveRoomTearDown:c,getRoomsList:tA,setSpectate:iA,bankerGiveUp:P,pokerCreateRoom:E.useCallback(kA=>{const se={...kA};let Ce=se.maxPlayers;if((typeof Ce!="number"||!Number.isInteger(Ce)||Ce<1||Ce>4)&&(Ce=se.singlePlayer?1:4),se.maxPlayers=Ce,typeof se.startingStack=="number"){const VA=Math.max(500,Math.min(1e6,Math.floor(se.startingStack)));se.startingStack=VA}se.eliminationMode?se.eliminationMode={enabled:!0}:delete se.eliminationMode,typeof se.botLevel=="number"&&se.botLevel>=1&&se.botLevel<=9||delete se.botLevel;try{console.debug("[socket][pokerCreateRoom] emitting",se)}catch{}return n(Lt.POKER_ROOM_CREATE,se)},[n,s,o]),pokerDeleteRoom:E.useCallback(kA=>n(Lt.POKER_ROOM_DELETE,{roomId:kA}),[n]),pokerJoinRoom:E.useCallback(async kA=>n(Lt.POKER_JOIN_ROOM,{roomId:kA}),[n]),pokerStartHand:E.useCallback(kA=>n(Lt.POKER_START_HAND,{roomId:kA}),[n]),pokerFold:E.useCallback(kA=>n(Lt.POKER_ACT,{roomId:kA,action:"fold"}),[n]),pokerCheck:E.useCallback(kA=>n(Lt.POKER_ACT,{roomId:kA,action:"check"}),[n]),pokerCall:E.useCallback(kA=>n(Lt.POKER_ACT,{roomId:kA,action:"call"}),[n]),pokerBet:E.useCallback((kA,se)=>n(Lt.POKER_ACT,{roomId:kA,action:"bet",amount:se}),[n]),pokerRaise:E.useCallback((kA,se)=>n(Lt.POKER_ACT,{roomId:kA,action:"raise",amount:se}),[n]),pokerFetchHistory:E.useCallback((kA,se,Ce)=>n(Lt.POKER_FETCH_HISTORY,{roomId:kA,limit:se,beforeSeq:Ce}),[n]),rollDice:d,confirmBets:p,crapsPlacePass:y,crapsRoll:K,crapsPlaceOdds:m,crapsPlacePlace:D,crapsPlaceField:S,crapsPlaceBig:k,crapsPlaceCome:N,crapsPlaceDontCome:G,crapsPlaceComeOdds:M,crapsPlaceDontComeOdds:w,crapsTogglePlaceWorking:b,crapsReady:J,crapsFetchHistory:q,crapsGetState:v,crapsJoinOrder:U,crapsLeaveOrder:x,crapsPassTurn:T,crapsSetOrder:z,crapsResetShooter:Z,crapsListBets:fA,crapsAddBet:RA,crapsBatchAddBets:qA,crapsRemoveBet:$,crapsBatchRemoveBets:W,crapsClearBets:L,crapsSummarizeBets:H,placeMainBet:oA,cancelMainBet:IA,createSideBet:CA,acceptSideBet:_A,cancelSideBet:uA,getWagers:X,rtcJoin:O,rtcLeave:cA,rtcSignal:wA,rtcSetCameraOwner:xA,rtcSetVideoEnabled:YA,roomSendMessage:jA,roomFetchHistory:ie,dmSendMessage:he,dmFetchHistory:le,lobbyJoin:NA,lobbyLeave:EA,lobbyList:PA,deleteRoom:ZA,getUserBalance:FA,sendFriendRequest:Ie,cancelFriendRequest:DA,respondFriendRequest:rA,unfriend:BA,blockUser:j,unblockUser:QA,getFriendsList:dA,sendGameInvite:UA,respondGameInvite:TA,quickMatchJoin:oe,quickMatchLeave:me,quickMatchStatus:be,getOnlineFriends:$e,updateProfile:ci,botsNudge:ke,refreshRoomState:nt,sendVisibilityChange:Ut,skillsSubmit:l,skillsTap:B,skillsSingleStart:dt,skillsAutoplayStart:Ht,skillsReady:Ft,skillsRoomCreate:Jt,skillsJoinRoom:$A,skillsLeaveRoom:He,skillsSpectatorJoin:Xe,skillsSpectatorLeave:St,anagramsSubmit:Q,triviaAnswer:h}}const ze={FAIRNESS_REVEAL:"fairness_reveal",GET_ROOMS_LIST:"get_rooms_list",LOBBY_ROOMS:"lobby_rooms",ROOM_CREATED:"room_created",ROOM_UPDATED:"room_updated",ROOM_DELETED:"room_deleted",JOINED_ROOM:"joined_room",REJOINED_ROOM:"rejoined_room",OTHER_JOINED:"other_player_joined_room",OTHER_LEFT:"other_player_left_room",BANKER_CHANGED:"banker_changed",DICE_ROLLED:"dice_rolled",NOT_YOUR_TURN:"not_your_turn",BETS_UPDATED:"bets_updated",GET_WAGERS:"get_wagers",PLAYER_BALANCE_UPDATED:"player_balance_updated",SIDE_BET_CREATED:"side_bet_created",SIDE_BET_ACCEPTED:"side_bet_accepted",SIDE_BET_CANCELED:"side_bet_canceled",FORCE_LOGOUT:"force_logout",ERROR:"error",RTC_SIGNAL:"rtc_signal",RTC_PEER_JOINED:"rtc_peer_joined",RTC_PEER_LEFT:"rtc_peer_left",RTC_CAMERA_OWNER_CHANGED:"rtc_camera_owner_changed",RTC_VIDEO_ENABLED:"rtc_video_enabled",ROOM_MESSAGE:"room_message",ROOM_HISTORY:"room_history",DM_MESSAGE:"dm_message",DM_HISTORY:"dm_history",FRIEND_REQUEST_RECEIVED:"friend_request_received",FRIEND_REQUEST_CANCELLED:"friend_request_cancelled",FRIEND_REQUEST_RESPONDED:"friend_request_responded",UNFRIENDED:"unfriended",USER_BLOCKED:"user_blocked",USER_UNBLOCKED:"user_unblocked",TURN_ORDER_UPDATED:"turn_order_updated",SPECTATORS_UPDATED:"spectators_updated",PLAYER_PROFILE_UPDATED:"player_profile_updated",CRAPS_ROLL:"craps:roll",CRAPS_READY_UPDATE:"craps:ready_update",CRAPS_BETS_UPDATE:"craps:bets_update",CRAPS_BET_DELTA:"craps:bet_delta",CRAPS_STATE:"craps:state",CRAPS_BET_RESULTS:"craps:bet_results",CRAPS_BET_ERROR:"craps:bet_error",CRAPS_POINT_SET:"craps:point_set",CRAPS_POINT_MADE:"craps:point_made",CRAPS_ATS_PROGRESS:"craps:ats_progress",CRAPS_ATS_SMALL_COMPLETE:"craps:ats_small_complete",CRAPS_ATS_TALL_COMPLETE:"craps:ats_tall_complete",CRAPS_ATS_ALL_COMPLETE:"craps:ats_all_complete",CRAPS_ATS_RESET:"craps:ats_reset",POKER_MY_HOLE:"poker:my_hole",POKER_WINNERS:"poker:winners",POKER_REVEAL_ALL:"poker:reveal_all",POKER_TIMED_OUT:"poker:timed_out",POKER_MY_BALANCE:"poker:my_balance",POKER_ROOM_CREATED:"poker_room_created",POKER_ROOM_UPDATED:"poker_room_updated",POKER_ROOM_DELETED:"poker_room_deleted",POKER_OTHER_JOINED:"poker_other_joined_room",POKER_JOINED_ROOM:"poker_joined_room",SKILLS_ROOM_CREATED:"skills_room_created",ROOM_UPDATE_STATE:"room:update_state",OTA_UPDATE_AVAILABLE:"ota:update_available",GAME_INVITE_RECEIVED:"game_invite:received",GAME_INVITE_CANCELLED:"game_invite:cancelled",PLAYER_PRESENCE_UPDATE:"player:presence_update",SKILLS_SUBMIT:"skills:submit",SKILLS_TAP:"skills:tap",SKILLS_SCORE_UPDATE:"skills:score_update",SKILLS_ROUND_START:"skills:round_start",SKILLS_ROUND_END:"skills:round_end"};function Os(e){const A=Ms(),t=E.useRef(e);E.useEffect(()=>{t.current=e},[e]),E.useEffect(()=>{var s,a;if(typeof window>"u"||!(((a=(s=window.location)==null?void 0:s.search)==null?void 0:a.includes("e2e=1"))||window.__E2E===!0||typeof window.sessionStorage<"u"&&window.sessionStorage.getItem("e2e")==="1"))return;const n=window;n.__crapsHandlersBus||(n.__crapsHandlersBus={onCrapsRollResult:new Set,onCrapsBetResults:new Set,onCrapsPointSet:new Set,onCrapsPointMade:new Set,_buffer:{onCrapsRollResult:[],onCrapsBetResults:[],onCrapsPointSet:[],onCrapsPointMade:[],push(r,I){const c=this[r];c.push(I),c.length>20&&c.shift()}}}),(()=>{const r=n.__crapsHandlers||{};r&&r.__wrappedByBus||(n.__crapsHandlers={onCrapsRollResult:I=>{var c,l;try{n.__crapsHandlersBus._buffer.push("onCrapsRollResult",I)}catch{}n.__crapsHandlersBus.onCrapsRollResult.forEach(B=>{try{B(I)}catch{}});try{const B=n.__flashTest;(n.__E2E===!0||((l=(c=n.location)==null?void 0:c.search)==null?void 0:l.includes("e2e=1"))||n.sessionStorage&&n.sessionStorage.getItem("e2e")==="1")&&B&&B.info}catch{}try{typeof r.onCrapsRollResult=="function"&&r.onCrapsRollResult(I)}catch{}},onCrapsBetResults:I=>{var c,l;try{n.__crapsHandlersBus._buffer.push("onCrapsBetResults",I)}catch{}n.__crapsHandlersBus.onCrapsBetResults.forEach(B=>{try{B(I)}catch{}});try{const B=n.__flashTest;if(!(!(n.__E2E===!0||((l=(c=n.location)==null?void 0:c.search)==null?void 0:l.includes("e2e=1"))||n.sessionStorage&&n.sessionStorage.getItem("e2e")==="1")||!B)){const h=Array.isArray(I==null?void 0:I.settlements)?I.settlements:[],d=h.filter(m=>typeof(m==null?void 0:m.betType)=="string"&&m.betType.startsWith("place")&&m.outcome==="WIN"),p=h.filter(m=>(m.betType==="pass"||m.betType==="dontPass")&&m.outcome==="WIN"),y=h.filter(m=>(m.betType==="pass"||m.betType==="dontPass")&&m.outcome==="LOSE");if(d.length>0&&typeof B.win=="function"){const m=d.reduce((D,S)=>D+(Number(S.payout)||0),0);B.win(d.length>1?"Place Wins":"Place Win",m?`+${m}`:void 0)}else if(p.length>0&&typeof B.win=="function"){const m=p.reduce((D,S)=>D+(Number(S.payout)||0)+(Number(S.amount)||0),0);B.win("Line Win",m?`+${m}`:void 0)}else if(y.length>0&&typeof B.lose=="function"){const m=y.reduce((D,S)=>D+(Number(S.amount)||0),0);B.lose("Line Lose",m?`-${m}`:void 0)}}}catch{}try{typeof r.onCrapsBetResults=="function"&&r.onCrapsBetResults(I)}catch{}},onCrapsPointSet:I=>{var c,l,B;try{n.__crapsHandlersBus._buffer.push("onCrapsPointSet",I)}catch{}n.__crapsHandlersBus.onCrapsPointSet.forEach(Q=>{try{Q(I)}catch{}});try{const Q=n.__flashTest;if((n.__E2E===!0||((l=(c=n.location)==null?void 0:c.search)==null?void 0:l.includes("e2e=1"))||n.sessionStorage&&n.sessionStorage.getItem("e2e")==="1")&&Q&&typeof Q.info=="function"){const d=I&&(I.point??((B=I==null?void 0:I.state)==null?void 0:B.point));Q.info("Point Set",d?`${d} is the point`:void 0)}}catch{}try{typeof r.onCrapsPointSet=="function"&&r.onCrapsPointSet(I)}catch{}},onCrapsPointMade:I=>{var c,l,B;try{n.__crapsHandlersBus._buffer.push("onCrapsPointMade",I)}catch{}n.__crapsHandlersBus.onCrapsPointMade.forEach(Q=>{try{Q(I)}catch{}});try{const Q=n.__flashTest;if((n.__E2E===!0||((l=(c=n.location)==null?void 0:c.search)==null?void 0:l.includes("e2e=1"))||n.sessionStorage&&n.sessionStorage.getItem("e2e")==="1")&&Q&&typeof Q.win=="function"){const d=I&&(I.point??((B=I==null?void 0:I.state)==null?void 0:B.point));Q.win("Point Made",d?`${d} hit`:void 0)}}catch{}try{typeof r.onCrapsPointMade=="function"&&r.onCrapsPointMade(I)}catch{}},__wrappedByBus:!0})})();const o={onCrapsRollResult:r=>{var I,c;return(c=(I=t.current).onCrapsRollResult)==null?void 0:c.call(I,r)},onCrapsBetResults:r=>{var I,c;return(c=(I=t.current).onCrapsBetResults)==null?void 0:c.call(I,r)},onCrapsPointSet:r=>{var I,c;return(c=(I=t.current).onCrapsPointSet)==null?void 0:c.call(I,r)},onCrapsPointMade:r=>{var I,c;return(c=(I=t.current).onCrapsPointMade)==null?void 0:c.call(I,r)}};n.__crapsHandlersBus.onCrapsRollResult.add(o.onCrapsRollResult),n.__crapsHandlersBus.onCrapsBetResults.add(o.onCrapsBetResults),n.__crapsHandlersBus.onCrapsPointSet.add(o.onCrapsPointSet),n.__crapsHandlersBus.onCrapsPointMade.add(o.onCrapsPointMade);try{const r=n.__crapsHandlersBus._buffer;if(r){for(const I of r.onCrapsRollResult)try{o.onCrapsRollResult(I)}catch{}for(const I of r.onCrapsBetResults)try{o.onCrapsBetResults(I)}catch{}for(const I of r.onCrapsPointSet)try{o.onCrapsPointSet(I)}catch{}for(const I of r.onCrapsPointMade)try{o.onCrapsPointMade(I)}catch{}}}catch{}return()=>{try{n.__crapsHandlersBus.onCrapsRollResult.delete(o.onCrapsRollResult),n.__crapsHandlersBus.onCrapsBetResults.delete(o.onCrapsBetResults),n.__crapsHandlersBus.onCrapsPointSet.delete(o.onCrapsPointSet),n.__crapsHandlersBus.onCrapsPointMade.delete(o.onCrapsPointMade)}catch{}}},[]),E.useEffect(()=>{if(!A)return;const i=rA=>{var BA,j;return(j=(BA=t.current).onLobbyRooms)==null?void 0:j.call(BA,rA)},n=rA=>{var BA,j;return(j=(BA=t.current).onRoomCreated)==null?void 0:j.call(BA,rA)},g=rA=>{var BA,j;return(j=(BA=t.current).onRoomUpdated)==null?void 0:j.call(BA,rA)},o=rA=>{var BA,j;return(j=(BA=t.current).onRoomDeleted)==null?void 0:j.call(BA,rA)},s=rA=>{var BA,j;return(j=(BA=t.current).onJoinedRoom)==null?void 0:j.call(BA,rA)},a=rA=>{var BA,j;return(j=(BA=t.current).onRejoinedRoom)==null?void 0:j.call(BA,rA)},r=rA=>{var BA,j,QA,dA,UA,TA,oe;console.log("[socket] received other_player_joined_room",{roomId:(BA=rA==null?void 0:rA.room)==null?void 0:BA.id,playersCount:(QA=(j=rA==null?void 0:rA.room)==null?void 0:j.players)==null?void 0:QA.length,playerIds:(UA=(dA=rA==null?void 0:rA.room)==null?void 0:dA.players)==null?void 0:UA.map(me=>me==null?void 0:me.id)}),(oe=(TA=t.current).onOtherPlayerJoined)==null||oe.call(TA,rA)},I=rA=>{var BA,j,QA,dA,UA,TA,oe;console.log("[socket] received other_player_left_room",{roomId:(BA=rA==null?void 0:rA.room)==null?void 0:BA.id,playersCount:(QA=(j=rA==null?void 0:rA.room)==null?void 0:j.players)==null?void 0:QA.length,playerIds:(UA=(dA=rA==null?void 0:rA.room)==null?void 0:dA.players)==null?void 0:UA.map(me=>me==null?void 0:me.id)}),(oe=(TA=t.current).onOtherLeft)==null||oe.call(TA,rA)},c=rA=>{var BA,j;return(j=(BA=t.current).onBankerChanged)==null?void 0:j.call(BA,rA)},l=rA=>{var BA,j;return(j=(BA=t.current).onDiceRolled)==null?void 0:j.call(BA,rA)},B=()=>{var rA,BA;return(BA=(rA=t.current).onNotYourTurn)==null?void 0:BA.call(rA)},Q=rA=>{var BA,j;return(j=(BA=t.current).onOtaUpdateAvailable)==null?void 0:j.call(BA,rA)},h=rA=>{var BA,j;return(j=(BA=t.current).onBetsUpdated)==null?void 0:j.call(BA,rA)},d=rA=>{var BA,j;return(j=(BA=t.current).onGetWagers)==null?void 0:j.call(BA,rA)},p=rA=>{var BA,j;return(j=(BA=t.current).onPlayerBalanceUpdated)==null?void 0:j.call(BA,rA)},y=rA=>{var BA,j;return(j=(BA=t.current).onSideBetCreated)==null?void 0:j.call(BA,rA)},m=rA=>{var BA,j;return(j=(BA=t.current).onSideBetAccepted)==null?void 0:j.call(BA,rA)},D=rA=>{var BA,j;return(j=(BA=t.current).onSideBetCanceled)==null?void 0:j.call(BA,rA)},S=rA=>{var BA,j;return(j=(BA=t.current).onForceLogout)==null?void 0:j.call(BA,rA)},k=rA=>{var BA,j;return(j=(BA=t.current).onError)==null?void 0:j.call(BA,rA)},N=rA=>{var BA,j;return(j=(BA=t.current).onRtcSignal)==null?void 0:j.call(BA,rA)},G=rA=>{var BA,j;return(j=(BA=t.current).onRtcPeerJoined)==null?void 0:j.call(BA,rA)},M=rA=>{var BA,j;return(j=(BA=t.current).onRtcPeerLeft)==null?void 0:j.call(BA,rA)},w=rA=>{var BA,j;return(j=(BA=t.current).onRtcCameraOwnerChanged)==null?void 0:j.call(BA,rA)},b=rA=>{var BA,j;return(j=(BA=t.current).onRtcVideoEnabled)==null?void 0:j.call(BA,rA)},_=rA=>{var BA,j;return(j=(BA=t.current).onRoomMessage)==null?void 0:j.call(BA,rA)},K=rA=>{var BA,j;return(j=(BA=t.current).onRoomHistory)==null?void 0:j.call(BA,rA)},J=rA=>{var BA,j;return(j=(BA=t.current).onDmMessage)==null?void 0:j.call(BA,rA)},q=rA=>{var BA,j;return(j=(BA=t.current).onDmHistory)==null?void 0:j.call(BA,rA)},v=rA=>{var BA,j;return(j=(BA=t.current).onFairnessReveal)==null?void 0:j.call(BA,rA)},U=rA=>{var BA,j;return(j=(BA=t.current).onFriendRequestReceived)==null?void 0:j.call(BA,rA)},x=rA=>{var BA,j;return(j=(BA=t.current).onFriendRequestCancelled)==null?void 0:j.call(BA,rA)},T=rA=>{var BA,j;return(j=(BA=t.current).onFriendRequestResponded)==null?void 0:j.call(BA,rA)},z=rA=>{var BA,j;return(j=(BA=t.current).onUnfriended)==null?void 0:j.call(BA,rA)},Z=rA=>{var BA,j;return(j=(BA=t.current).onUserBlocked)==null?void 0:j.call(BA,rA)},eA=rA=>{var BA,j;return(j=(BA=t.current).onUserUnblocked)==null?void 0:j.call(BA,rA)},aA=rA=>{var BA,j;return(j=(BA=t.current).onGameInviteReceived)==null?void 0:j.call(BA,rA)},sA=rA=>{var BA,j;return(j=(BA=t.current).onGameInviteCancelled)==null?void 0:j.call(BA,rA)},pA=rA=>{var BA,j;return(j=(BA=t.current).onTurnOrderUpdated)==null?void 0:j.call(BA,rA)},gA=rA=>{var BA,j;return(j=(BA=t.current).onSpectatorsUpdated)==null?void 0:j.call(BA,rA)},yA=rA=>{var BA,j;return(j=(BA=t.current).onPlayerProfileUpdated)==null?void 0:j.call(BA,rA)},fA=rA=>{var BA,j;return(j=(BA=t.current).onPlayerPresenceUpdate)==null?void 0:j.call(BA,rA)},RA=rA=>{var BA,j;return(j=(BA=t.current).onPokerMyHole)==null?void 0:j.call(BA,rA)},qA=rA=>{var BA,j;return(j=(BA=t.current).onPokerWinners)==null?void 0:j.call(BA,rA)},W=rA=>{var BA,j;return(j=(BA=t.current).onPokerRevealAll)==null?void 0:j.call(BA,rA)},$=rA=>{var BA,j;return(j=(BA=t.current).onPokerTimedOut)==null?void 0:j.call(BA,rA)},L=rA=>{var BA,j;return(j=(BA=t.current).onPokerMyBalance)==null?void 0:j.call(BA,rA)},H=rA=>{var BA,j;return(j=(BA=t.current).onRoomUpdateState)==null?void 0:j.call(BA,rA)},P=rA=>rA&&(!rA.dice&&typeof rA.d1=="number"&&typeof rA.d2=="number"&&(rA.dice=[rA.d1,rA.d2]),rA.dice&&(typeof rA.d1!="number"||typeof rA.d2!="number")&&(rA.d1=rA.dice[0],rA.d2=rA.dice[1]),rA.shooterId!==void 0&&rA.currentRollerId===void 0&&(rA.currentRollerId=rA.shooterId),rA.nextShooterId!==void 0&&rA.nextRollerId===void 0&&(rA.nextRollerId=rA.nextShooterId),rA),tA=rA=>{var BA,j;(j=(BA=t.current).onCrapsRollResult)==null||j.call(BA,P(rA))},iA=rA=>{var BA,j;(j=(BA=t.current).onCrapsReadyUpdate)==null||j.call(BA,rA)},oA=rA=>{var BA,j;(j=(BA=t.current).onCrapsBetsUpdate)==null||j.call(BA,rA)},IA=rA=>{var BA,j;(j=(BA=t.current).onCrapsBetDelta)==null||j.call(BA,rA)},CA=rA=>{var BA,j;(j=(BA=t.current).onCrapsBetResults)==null||j.call(BA,rA)},_A=rA=>{var BA,j;(j=(BA=t.current).onCrapsBetError)==null||j.call(BA,rA)},uA=rA=>{var BA,j;(j=(BA=t.current).onCrapsPointSet)==null||j.call(BA,rA)},X=rA=>{var BA,j;(j=(BA=t.current).onCrapsPointMade)==null||j.call(BA,rA)},O=rA=>{var BA,j;return(j=(BA=t.current).onSkillsRejoinedRoom)==null?void 0:j.call(BA,rA)},cA=rA=>{var BA,j;return(j=(BA=t.current).onSkillsScoreUpdate)==null?void 0:j.call(BA,rA)},wA=rA=>{var BA,j;return(j=(BA=t.current).onSkillsRoundStart)==null?void 0:j.call(BA,rA)},xA=rA=>{var BA,j;return(j=(BA=t.current).onSkillsRoundEnd)==null?void 0:j.call(BA,rA)},YA=rA=>{var BA,j;return(j=(BA=t.current).onSkillsSessionInfo)==null?void 0:j.call(BA,rA)},jA=rA=>{var BA,j;return(j=(BA=t.current).onAnagramsWordFound)==null?void 0:j.call(BA,rA)},ie=rA=>{var BA,j;return(j=(BA=t.current).onTriviaAnswer)==null?void 0:j.call(BA,rA)},he=rA=>{var BA,j;return(j=(BA=t.current).onTriviaNextQuestion)==null?void 0:j.call(BA,rA)},le=rA=>{var BA,j;return(j=(BA=t.current).onSkillsSpectatorState)==null?void 0:j.call(BA,rA)},NA=rA=>{var BA,j;return(j=(BA=t.current).onSkillsSpectatorUpdate)==null?void 0:j.call(BA,rA)},EA=rA=>{var BA,j;return(j=(BA=t.current).onSkillsSpectatorJoined)==null?void 0:j.call(BA,rA)},PA=rA=>{var BA,j;return(j=(BA=t.current).onSkillsSpectatorLeft)==null?void 0:j.call(BA,rA)},ZA=rA=>{var BA,j;return(j=(BA=t.current).onSkillsWordClaimed)==null?void 0:j.call(BA,rA)},FA=()=>{A.on(ze.LOBBY_ROOMS,i),A.on(ze.ROOM_CREATED,n);try{A.on(ze.POKER_ROOM_CREATED,n)}catch{}try{A.on(ze.SKILLS_ROOM_CREATED,n)}catch{}A.on(ze.ROOM_UPDATED,g);try{A.on(ze.POKER_ROOM_UPDATED,g)}catch{}A.on(ze.ROOM_DELETED,o);try{A.on(ze.POKER_ROOM_DELETED,o)}catch{}A.on(ze.JOINED_ROOM,s);try{A.on(ze.POKER_JOINED_ROOM,s)}catch{}A.on(ze.REJOINED_ROOM,a),A.on(ze.OTHER_JOINED,r),A.on(ze.POKER_OTHER_JOINED,r),A.on(ze.OTHER_LEFT,I),A.on(ze.BANKER_CHANGED,c),A.on(ze.DICE_ROLLED,l),A.on(ze.NOT_YOUR_TURN,B),A.on(ze.OTA_UPDATE_AVAILABLE,Q),A.on(ze.BETS_UPDATED,h),A.on(ze.GET_WAGERS,d),A.on(ze.PLAYER_BALANCE_UPDATED,p),A.on(ze.SIDE_BET_CREATED,y),A.on(ze.SIDE_BET_ACCEPTED,m),A.on(ze.SIDE_BET_CANCELED,D),A.on(ze.FORCE_LOGOUT,S),A.on(ze.ERROR,k),A.on(ze.RTC_SIGNAL,N),A.on(ze.RTC_PEER_JOINED,G),A.on(ze.RTC_PEER_LEFT,M),A.on(ze.RTC_CAMERA_OWNER_CHANGED,w),A.on(ze.RTC_VIDEO_ENABLED,b),A.on(ze.ROOM_MESSAGE,_),A.on(ze.ROOM_HISTORY,K),A.on(ze.DM_MESSAGE,J),A.on(ze.DM_HISTORY,q),A.on(ze.FAIRNESS_REVEAL,v),A.on(ze.FRIEND_REQUEST_RECEIVED,U),A.on(ze.FRIEND_REQUEST_CANCELLED,x),A.on(ze.FRIEND_REQUEST_RESPONDED,T),A.on(ze.UNFRIENDED,z),A.on(ze.USER_BLOCKED,Z),A.on(ze.USER_UNBLOCKED,eA),A.on(ze.GAME_INVITE_RECEIVED,aA),A.on(ze.GAME_INVITE_CANCELLED,sA),A.on(ze.TURN_ORDER_UPDATED,pA),A.on(ze.SPECTATORS_UPDATED,gA),A.on(ze.PLAYER_PROFILE_UPDATED,yA),A.on(ze.PLAYER_PRESENCE_UPDATE,fA),A.on(ze.CRAPS_ROLL,tA),A.on(ze.CRAPS_READY_UPDATE,iA),A.on(ze.CRAPS_BETS_UPDATE,oA),A.on(ze.CRAPS_BET_DELTA,IA),A.on(ze.CRAPS_BET_RESULTS,CA),A.on(ze.CRAPS_BET_ERROR,_A),A.on(ze.CRAPS_POINT_SET,uA),A.on(ze.CRAPS_POINT_MADE,X),A.on(ze.POKER_MY_HOLE,RA),A.on(ze.POKER_WINNERS,qA),A.on(ze.POKER_REVEAL_ALL,W),A.on(ze.POKER_TIMED_OUT,$),A.on(ze.POKER_MY_BALANCE,L),A.on(ze.ROOM_UPDATE_STATE,H);const rA=BA=>{var j,QA;return(QA=(j=t.current).onCrapsState)==null?void 0:QA.call(j,BA)};return A.on(ze.CRAPS_STATE,rA),A.on("skills:rejoined_room",O),A.on(ze.SKILLS_SCORE_UPDATE,cA),A.on(ze.SKILLS_ROUND_START,wA),A.on(ze.SKILLS_ROUND_END,xA),A.on("skills:session_info",YA),A.on("anagrams:word_found",jA),A.on("trivia:answer",ie),A.on("trivia:next_question",he),A.on("skills:spectator_state",le),A.on("skills:spectator_update",NA),A.on("skills:spectator_joined",EA),A.on("skills:spectator_left",PA),A.on("skills:word_claimed",ZA),()=>{A.off(ze.LOBBY_ROOMS,i),A.off(ze.ROOM_CREATED,n);try{A.off(ze.POKER_ROOM_CREATED,n)}catch{}try{A.off(ze.SKILLS_ROOM_CREATED,n)}catch{}A.off(ze.ROOM_UPDATED,g);try{A.off(ze.POKER_ROOM_UPDATED,g)}catch{}A.off(ze.ROOM_DELETED,o);try{A.off(ze.POKER_ROOM_DELETED,o)}catch{}A.off(ze.JOINED_ROOM,s);try{A.off(ze.POKER_JOINED_ROOM,s)}catch{}A.off(ze.REJOINED_ROOM,a),A.off(ze.OTHER_JOINED,r);try{A.off(ze.POKER_OTHER_JOINED,r)}catch{}A.off(ze.OTHER_LEFT,I),A.off(ze.BANKER_CHANGED,c),A.off(ze.DICE_ROLLED,l),A.off(ze.NOT_YOUR_TURN,B),A.off(ze.OTA_UPDATE_AVAILABLE,Q),A.off(ze.BETS_UPDATED,h),A.off(ze.GET_WAGERS,d),A.off(ze.PLAYER_BALANCE_UPDATED,p),A.off(ze.SIDE_BET_CREATED,y),A.off(ze.SIDE_BET_ACCEPTED,m),A.off(ze.SIDE_BET_CANCELED,D),A.off(ze.FORCE_LOGOUT,S),A.off(ze.ERROR,k),A.off(ze.RTC_SIGNAL,N),A.off(ze.RTC_PEER_JOINED,G),A.off(ze.RTC_PEER_LEFT,M),A.off(ze.RTC_CAMERA_OWNER_CHANGED,w),A.off(ze.RTC_VIDEO_ENABLED,b),A.off(ze.ROOM_MESSAGE,_),A.off(ze.ROOM_HISTORY,K),A.off(ze.DM_MESSAGE,J),A.off(ze.DM_HISTORY,q),A.off(ze.FAIRNESS_REVEAL,v),A.off(ze.FRIEND_REQUEST_RECEIVED,U),A.off(ze.FRIEND_REQUEST_CANCELLED,x),A.off(ze.FRIEND_REQUEST_RESPONDED,T),A.off(ze.UNFRIENDED,z),A.off(ze.USER_BLOCKED,Z),A.off(ze.USER_UNBLOCKED,eA),A.off(ze.GAME_INVITE_RECEIVED,aA),A.off(ze.GAME_INVITE_CANCELLED,sA),A.off(ze.TURN_ORDER_UPDATED,pA),A.off(ze.SPECTATORS_UPDATED,gA),A.off(ze.PLAYER_PROFILE_UPDATED,yA),A.off(ze.PLAYER_PRESENCE_UPDATE,fA),A.off(ze.CRAPS_ROLL,tA),A.off(ze.CRAPS_READY_UPDATE,iA),A.off(ze.CRAPS_BETS_UPDATE,oA),A.off(ze.CRAPS_BET_DELTA,IA),A.off(ze.CRAPS_BET_RESULTS,CA),A.off(ze.CRAPS_BET_ERROR,_A),A.off(ze.CRAPS_POINT_SET,uA),A.off(ze.CRAPS_POINT_MADE,X),A.off(ze.POKER_MY_HOLE,RA),A.off(ze.POKER_WINNERS,qA),A.off(ze.POKER_REVEAL_ALL,W),A.off(ze.POKER_TIMED_OUT,$),A.off(ze.POKER_MY_BALANCE,L),A.off(ze.ROOM_UPDATE_STATE,H),A.off(ze.CRAPS_STATE,rA),A.off("skills:rejoined_room",O),A.off(ze.SKILLS_SCORE_UPDATE,cA),A.off(ze.SKILLS_ROUND_START,wA),A.off(ze.SKILLS_ROUND_END,xA),A.off("skills:session_info",YA),A.off("anagrams:word_found",jA),A.off("trivia:answer",ie),A.off("trivia:next_question",he),A.off("skills:spectator_state",le),A.off("skills:spectator_update",NA),A.off("skills:spectator_joined",EA),A.off("skills:spectator_left",PA),A.off("skills:word_claimed",ZA)}};let Ie=FA();const DA=()=>{try{Ie&&Ie()}catch{}Ie=FA();try{Qi(async()=>{const{reRegisterPushToken:rA}=await Promise.resolve().then(()=>$Ne);return{reRegisterPushToken:rA}},void 0).then(({reRegisterPushToken:rA})=>{rA()}).catch(()=>{})}catch{}};return A.on("connect",DA),A.on("reconnect",DA),()=>{A.off("connect",DA),A.off("reconnect",DA);try{Ie&&Ie()}catch{}}},[A])}function D8(){const{getRoomsList:e,createRoom:A,lobbyJoin:t,lobbyLeave:i}=Mo(),[n,g]=E.useState({public:[],private:[]}),[o,s]=E.useState(!0),[a,r]=E.useState(null),{setMembershipModalOpen:I}=RR(),{resetSpin:c}=kB(),l=globalThis.__lastRoomsFetchAt||(globalThis.__lastRoomsFetchAt={}),B=600,Q=(N,G)=>{switch(N){case"skills":return`/skills/play?roomId=${G}`;case"zentara":return`/zentara/room/${G}`;case"cee-lo":return`/room/${G}`;case"craps":return`/room/${G}`;case"poker":return`/poker/room/${G}`;default:return`/room/${G}`}},h=E.useCallback(async()=>{const N=Date.now(),G=l.t||0;if(!(N-G<B)){l.t=N,s(!0),r(null);try{const M=await e();if(M!=null&&M.ok){const w=M.public&&M.private?{public:M.public,private:M.private}:null,b=M.data||M.roomsList||{},_=b.public&&b.private?{public:b.public,private:b.private}:null,K=w||_||{public:[],private:[]};g({public:Array.isArray(K.public)?K.public:[],private:Array.isArray(K.private)?K.private:[]})}else throw new Error((M==null?void 0:M.error)??"Failed to load rooms.")}catch(M){r((M==null?void 0:M.message)??"Failed to load rooms.")}finally{s(!1)}}},[e]),d=globalThis.__lobbyState||(globalThis.__lobbyState={refCount:0,joined:!1}),p=E.useCallback(async(N=!1)=>{d.refCount++,(!d.joined||N)&&(d.joined=!0,await t())},[t]),y=E.useCallback(async()=>{d.refCount=Math.max(0,d.refCount-1),d.refCount===0&&d.joined&&(d.joined=!1,await i())},[i]),m=globalThis.__createRoomGuard||(globalThis.__createRoomGuard={}),D=800,S=E.useCallback(async N=>{var _,K,J,q;const G=Date.now(),M=m.lastAt||0;if(G-M<D&&m.inFlight)try{return await m.inFlight}catch{}const w=async()=>{let U=0;if(G-M<D){const x=D-(G-M);await new Promise(T=>setTimeout(T,Math.max(50,x)))}for(;U<3;){U++;const x=await A({name:N.name,isPrivate:N.isPrivate,singlePlayer:N.singlePlayer,gameMode:N.gameMode,botLevel:N.botLevel,gameRules:N.gameRules});if(!x||x.ok===!0||(x==null?void 0:x.ok)===!1&&x.error!=="rate_limited"&&!/rate[_-]?limited/i.test(x.error||""))return x;const T=180*U,z=Math.floor(Math.random()*140);await new Promise(Z=>setTimeout(Z,T+z))}return A({name:N.name,isPrivate:N.isPrivate,singlePlayer:N.singlePlayer,gameMode:N.gameMode,botLevel:N.botLevel,gameRules:N.gameRules})};s(!0),r(null),m.lastAt=Date.now();const b=w();m.inFlight=b;try{const v=await b;if(!(v!=null&&v.ok))return v;const U=v.room||((_=v.roomsList)==null?void 0:_.room)||null;if(U){const x={roomId:U.roomId,name:U.name,createdAt:U.createdAt,maxPlayers:U.maxPlayers,currentPlayers:((K=U.players)==null?void 0:K.length)??1,phase:((J=U.gameState)==null?void 0:J.phase)??"waiting",private:!!U.private,gameMode:U.gameMode||((q=U.gameState)==null?void 0:q.gameMode)||"cee-lo"};g(T=>T.public.some(z=>z.roomId===x.roomId)||T.private.some(z=>z.roomId===x.roomId)?T:x.private?{...T,private:[x,...T.private]}:{...T,public:[x,...T.public]})}else await h();return c(),v}catch(v){const U=(v==null?void 0:v.message)??"Failed to create room.";throw r(U),v}finally{s(!1),m.inFlight=null}},[A,h,I,c]),k=Ms();return E.useEffect(()=>(p(),()=>{y()}),[]),E.useEffect(()=>{if(!k)return;let N=!0;const G=async()=>{if(N){N=!1;return}console.log("[useLobbyRooms] socket reconnected, re-joining lobby and refreshing rooms"),await p(!0),await h()},M=()=>{d.joined=!1,console.log("[useLobbyRooms] socket disconnected, reset lobby joined state")};return k.on("connect",G),k.on("disconnect",M),()=>{k.off("connect",G),k.off("disconnect",M)}},[k,p,h]),E.useEffect(()=>{h()},[h]),Os({onRoomCreated:N=>{g(G=>N.private?{...G,private:[N,...G.private.filter(M=>M.roomId!==N.roomId)]}:{...G,public:[N,...G.public.filter(M=>M.roomId!==N.roomId)]})},onRoomDeleted:({roomId:N})=>{g(G=>({public:G.public.filter(M=>M.roomId!==N),private:G.private.filter(M=>M.roomId!==N)}))},onRoomUpdated:N=>{g(G=>({public:G.public.map(M=>M.roomId===N.roomId?{...M,currentPlayers:N.currentPlayers??M.currentPlayers,phase:N.phase??M.phase}:M),private:G.private.map(M=>M.roomId===N.roomId?{...M,currentPlayers:N.currentPlayers??M.currentPlayers,phase:N.phase??M.phase}:M)}))}}),{roomsList:n,loading:o,error:a,refreshRooms:h,createRoom:S,getGameRoute:Q}}const kvA=[0,100,250,500,1e3,2500,5e3],MvA=[15,30,45,60,90,120],NvA=[{value:"wordsearch",label:"🔤 Word Search"},{value:"anagrams",label:"🔀 Anagrams"},{value:"trivia",label:"❓ Trivia"}];function RvA({gameMode:e}){const[A,t]=E.useState(""),[i,n]=E.useState(2),[g,o]=E.useState(!1),[s,a]=E.useState(!1),[r,I]=E.useState(!1),[c,l]=E.useState(1e3),[B,Q]=E.useState(100),[h,d]=E.useState(30),[p,y]=E.useState("wordsearch"),[m,D]=E.useState(!1),[S,k]=E.useState(!1),[N,G]=E.useState(!1),[M,w]=E.useState(null),[b,_]=E.useState(null),K=qi(),{createRoom:J}=D8(),{pokerCreateRoom:q,skillsRoomCreate:v}=Mo(),U=e==="skills",x=async T=>{var z,Z,eA;T.preventDefault(),w(null),G(!0);try{const aA=e||"cee-lo";let sA;if(aA==="zentara"?sA=await J({name:A,maxPlayers:i,isPrivate:g,singlePlayer:s,gameMode:"zentara",gameRules:m||S?{disableRaid:m,disableSpyStrike:S}:void 0}):aA==="poker"?sA=await q({name:A,maxPlayers:i,isPrivate:g,singlePlayer:s,eliminationMode:r,startingStack:c}):aA==="skills"?sA=await v({name:A,maxPlayers:i,isPrivate:g,stake:B,duration:h,gameMode:p}):sA=await J({name:A,maxPlayers:i,isPrivate:g,singlePlayer:s,gameMode:aA}),!(sA!=null&&sA.ok))w((sA==null?void 0:sA.error)||"Failed to create room");else{const pA=(sA==null?void 0:sA.room)??((z=sA==null?void 0:sA.roomsList)==null?void 0:z.room)??((Z=sA==null?void 0:sA.data)==null?void 0:Z.room)??null,gA=(pA==null?void 0:pA.roomId)??(pA==null?void 0:pA.id)??(sA==null?void 0:sA.roomId)??((eA=sA==null?void 0:sA.data)==null?void 0:eA.roomId);K(gA?aA==="poker"?`/poker/room/${gA}`:aA==="skills"?`/skills/room/${gA}`:aA==="zentara"?`/zentara/room/${gA}`:`/room/${gA}`:aA==="poker"?"/poker":aA==="skills"?"/skills/play":aA==="zentara"?"/zentara":"/")}}catch(aA){console.error(aA),w("Unexpected error")}finally{G(!1)}};return b?C.jsxs("div",{className:"create-room-success",children:[C.jsx("h2",{children:"Room Created!"}),C.jsxs("p",{children:["Your room ",C.jsx("strong",{children:b.name})," (ID: ",C.jsx("code",{children:b.roomId}),") has been created."]})]}):C.jsxs("form",{className:"create-room-form",onSubmit:x,children:[C.jsx("h2",{children:"Create a New Room"}),C.jsxs("label",{children:["Room Name",C.jsx("input",{type:"text",value:A,onChange:T=>t(T.target.value),required:!0,disabled:N,className:"create-room-input",placeholder:"Enter room name"})]}),C.jsxs("label",{children:["Max Players",C.jsx("input",{type:"number",value:i,min:2,max:U?4:10,className:"create-room-input",onChange:T=>n(Number(T.target.value)),required:!0,disabled:N})]}),U&&C.jsxs(C.Fragment,{children:[C.jsxs("label",{children:["Game Mode",C.jsx("select",{value:p,onChange:T=>y(T.target.value),className:"create-room-input",disabled:N,children:NvA.map(T=>C.jsx("option",{value:T.value,children:T.label},T.value))})]}),C.jsxs("label",{children:["Bet Amount",C.jsx("select",{value:B,onChange:T=>Q(Number(T.target.value)),className:"create-room-input",disabled:N,children:kvA.map(T=>C.jsx("option",{value:T,children:T===0?"Free Play":`${T.toLocaleString()} Credits`},T))})]}),C.jsxs("label",{children:["Game Duration",C.jsx("select",{value:h,onChange:T=>d(Number(T.target.value)),className:"create-room-input",disabled:N,children:MvA.map(T=>C.jsxs("option",{value:T,children:[T," seconds"]},T))})]})]}),e==="poker"&&C.jsxs("label",{children:["Buy-In Amount",C.jsx("input",{type:"number",value:c,min:500,max:25e3,step:100,className:"create-room-input",onChange:T=>l(Math.max(500,Math.min(25e3,Number(T.target.value)))),required:!0,disabled:N})]}),e==="poker"&&!s&&C.jsxs("label",{className:"create-room-elim-toggle",children:[C.jsx("input",{type:"checkbox",className:"create-room-checkbox",checked:r,onChange:T=>I(T.target.checked),disabled:N}),"Elimination Mode",C.jsx("span",{className:"create-room-elim-hint",children:"Players lose shields on losses & get knocked out"})]}),e==="zentara"&&C.jsxs(C.Fragment,{children:[C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",className:"create-room-checkbox",checked:m,onChange:T=>D(T.target.checked),disabled:N}),"Disable Resource Raid"]}),C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",className:"create-room-checkbox",checked:S,onChange:T=>k(T.target.checked),disabled:N}),"Disable Spy Strike"]})]}),C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",className:"create-room-checkbox",checked:g,onChange:T=>o(T.target.checked),disabled:N}),"Private room (invite only)"]}),M&&C.jsx("p",{className:"error",children:M}),C.jsx("button",{className:"felt-btn",type:"submit",disabled:N,children:N?"Creating...":"Create Room"})]})}function LcA(e){E.useEffect(()=>{if(!(typeof document>"u")){if(e){try{$k(!0)}catch{}try{RC()}catch{}try{document.body.classList.add("modal-open")}catch{}}else{try{$k(!1)}catch{}try{document.body.classList.remove("modal-open")}catch{}}return()=>{try{$k(!1)}catch{}try{document.body.classList.remove("modal-open")}catch{}}}},[e])}function GvA({open:e,onClose:A,gameMode:t}){const[i,n]=E.useState(t||"cee-lo");LcA(!!e),E.useEffect(()=>{const o=s=>{s.key==="Escape"&&A()};return e&&document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,A]),E.useEffect(()=>{t&&n(t)},[t]);const g=i==="craps"?"Craps":i==="poker"?"Poker":i==="skills"?"Skills":i==="zentara"?"Zentara":"Cee‑Lo";return e?C.jsx("div",{className:"modal-backdrop",role:"presentation",onClick:A,children:C.jsxs("div",{className:"modal-panel",role:"dialog","aria-modal":"true","aria-label":"Create a room",onClick:o=>o.stopPropagation(),children:[C.jsx("button",{className:"modal-close",onClick:A,"aria-label":"Close",children:"×"}),C.jsx("h3",{className:"modal-title",children:"Create a Room"}),C.jsxs("p",{"aria-live":"polite",className:"modal-subtitle",children:["Game mode: ",C.jsx("strong",{children:g})]}),C.jsx(RvA,{gameMode:i})]})}):null}function X6({rooms:e,title:A,onJoinClick:t,spectateMode:i}){const n=qi(),[g,o]=E.useState(null);if(e.length===0)return C.jsx("div",{className:"room-list",children:"No rooms available."});const s=async(a,r)=>{if(!g){o(a);try{if(t&&await t(),i&&r==="skills")return n(`/skills/spectate/${a}`);if(r==="poker")return n(`/poker/room/${a}`);if(r==="skills")return n(`/skills/room/${a}`);if(r==="zentara")return n(`/zentara/room/${a}`);n(`/room/${a}`)}catch(I){console.error("[RoomList] join failed:",I),o(null)}}};return C.jsxs("div",{className:"room-list",children:[C.jsx("h3",{children:A}),C.jsx("ul",{children:[...new Set(e)].filter(a=>!a.singlePlayer&&!a.quickMatch).map(a=>C.jsxs("li",{className:"room-list__item",children:[C.jsxs("div",{className:"room-list__info",children:[C.jsx("span",{className:"room-list__name",children:a.name}),a.private&&C.jsx("span",{className:"room-list__private",children:"🔒"}),C.jsxs("span",{className:"room-list__players",children:[a.currentPlayers,"/",a.maxPlayers]}),C.jsx("span",{className:"room-list__phase",children:a.phase??"waiting"}),a.gameMode&&C.jsx("span",{className:"room-list__mode",title:"Game Mode",children:a.gameMode}),a.gameMode==="skills"&&C.jsxs(C.Fragment,{children:[typeof a.stake=="number"&&C.jsxs("span",{className:"room-list__stake",title:"Bet Amount",children:["💰 ",a.stake===0?"Free":a.stake.toLocaleString()]}),typeof a.duration=="number"&&C.jsxs("span",{className:"room-list__duration",title:"Game Duration",children:["⏱️ ",a.duration,"s"]})]}),C.jsx("span",{className:"room-list__created",children:new Date(a.createdAt).toLocaleTimeString()})]}),C.jsx("button",{className:`btn btn--join ${i&&a.gameMode==="skills"?"btn--spectate":""} ${g===a.roomId?"btn--loading":""}`,"data-game-mode":a.gameMode,onClick:()=>s(a.roomId,a.gameMode),disabled:g!==null,children:g===a.roomId?C.jsx("span",{className:"btn-spinner"}):i&&a.gameMode==="skills"?"👁️ Spectate":"Join"})]},a.roomId))})]})}function bvA({open:e,onClose:A,isPrivate:t,setIsPrivate:i,roomsList:n,onJoinClick:g,loading:o}){const s=E.useRef(null),[a,r]=E.useState(!1);return E.useEffect(()=>{if(!e)return;const I=l=>{l.key==="Escape"&&A()},c=l=>{s.current&&!s.current.contains(l.target)&&A()};return document.addEventListener("keydown",I),document.addEventListener("mousedown",c),()=>{document.removeEventListener("keydown",I),document.removeEventListener("mousedown",c)}},[e,A]),e?C.jsx("div",{className:"modal-backdrop",role:"presentation",children:C.jsxs("div",{className:"modal-panel",role:"dialog","aria-modal":"true","aria-label":"Browse Rooms",ref:s,children:[C.jsx("button",{className:"modal-close",onClick:A,"aria-label":"Close",children:"×"}),C.jsx("h3",{className:"modal-title",children:"Browse Rooms"}),C.jsxs("div",{style:{display:"flex",gap:16,marginBottom:12,flexWrap:"wrap"},children:[C.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[C.jsx("input",{type:"checkbox",className:"create-room-checkbox",checked:t,onChange:I=>i(I.target.checked)}),C.jsxs("span",{children:[t?"Private":"Public"," Rooms"]})]}),C.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[C.jsx("input",{type:"checkbox",className:"create-room-checkbox",checked:a,onChange:I=>r(I.target.checked)}),C.jsx("span",{children:"👁️ Spectate Mode"})]})]}),o?C.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"32px 0"},children:C.jsx("div",{className:"home-preloader__spinner",style:{width:32,height:32}})}):t?n.private.length?C.jsx(X6,{title:"Private Rooms",rooms:n.private,onJoinClick:g,spectateMode:a}):C.jsx("p",{children:"No private rooms available."}):n.public.length?C.jsx(X6,{title:"Public Rooms",rooms:n.public,onJoinClick:g,spectateMode:a}):C.jsx("p",{children:"No public rooms available."})]})}):null}function UvA({anchorRef:e,open:A,onClose:t,items:i}){const n=E.useRef(null);return E.useEffect(()=>{if(!A)return;const g=s=>{var c,l;const a=s.target,r=!!((c=n.current)!=null&&c.contains(a)),I=!!((l=e.current)!=null&&l.contains(a));!r&&!I&&t()},o=s=>{s.key==="Escape"&&t()};return document.addEventListener("mousedown",g,!0),document.addEventListener("keydown",o),()=>{document.removeEventListener("mousedown",g,!0),document.removeEventListener("keydown",o)}},[A,t,e]),A?C.jsx("div",{ref:n,className:"settings-menu",role:"menu","aria-orientation":"vertical",children:i.map(g=>C.jsxs("button",{className:"settings-menu__item",role:"menuitem",onClick:()=>{var o;(o=g.onClick)==null||o.call(g),t()},children:[g.label,(g.badge??0)>0&&C.jsx("span",{className:"settings-menu__badge",children:g.badge>99?"99+":g.badge})]},g.key))}):null}const ds={diceAudio:!0,backgroundMusic:!0,chatAudio:!1,video:!1,showAnimations:!0,showCelebrationImages:!0,lastGameMode:"cee-lo",diceColorTheme:"dice_white_black",theme:"dark",zentaraBotCount:3},xcA="app:settings:v1";async function Xo(){try{const{value:e}=await Ia.get({key:xcA});if(!e)return{...ds};const A=JSON.parse(e);return{...ds,...A}}catch{return{...ds}}}async function JE(e){await Ia.set({key:xcA,value:JSON.stringify(e)});try{window.dispatchEvent(new CustomEvent("app:settings",{detail:e}))}catch{}}const TcA=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_SETTINGS:ds,loadSettings:Xo,saveSettings:JE},Symbol.toStringTag,{value:"Module"})),Nr=md("App",{web:()=>Qi(()=>import("./web-Bv6HZ2S_.js"),__vite__mapDeps([8,1])).then(e=>new e.AppWeb)}),GR=Object.freeze(Object.defineProperty({__proto__:null,App:Nr},Symbol.toStringTag,{value:"Module"}));var vvA=Object.create,qcA=Object.defineProperty,KvA=Object.getOwnPropertyDescriptor,FvA=(e,A)=>(A=Symbol[e])?A:Symbol.for("Symbol."+e),YcA=e=>{throw TypeError(e)},HcA=(e,A,t)=>A in e?qcA(e,A,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[A]=t,_vA=e=>[,,,vvA(null)],OcA=["class","method","getter","setter","accessor","field","value","get","set"],PcA=e=>e!==void 0&&typeof e!="function"?YcA("Function expected"):e,JvA=(e,A,t,i,n)=>({kind:OcA[e],name:A,metadata:i,addInitializer:g=>t._?YcA("Already initialized"):n.push(PcA(g||null))}),LvA=(e,A)=>HcA(A,FvA("metadata"),e[3]),xvA=(e,A,t,i)=>{for(var n=0,g=e[A>>1],o=g&&g.length;n<o;n++)g[n].call(t);return i},TvA=(e,A,t,i,n,g)=>{for(var o,s,a,r,I=A&7,c=!1,l=!1,B=2,Q=OcA[I+5],h=e[B]||(e[B]=[]),d=(n=n.prototype,KvA(n,t)),p=i.length-1;p>=0;p--)a=JvA(I,t,s={},e[3],h),a.static=c,a.private=l,r=a.access={has:y=>t in y},r.get=y=>y[t],I>2,o=(0,i[p])(d[Q],a),s._=1,PcA(o)&&(d[Q]=o);return d&&qcA(n,t,d),n},Yt=(e,A,t)=>HcA(e,typeof A!="symbol"?A+"":A,t);const qvA="5";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(qvA);const m8=1,S8=2,jcA=4,YvA=8,HvA=16,OvA=1,PvA=2,jvA=4,zvA=8,ZvA=16,WvA=1,VvA=2,XvA=4,$vA=1,AKA=2,Pr=Symbol(),iN="http://www.w3.org/2000/svg";function eKA(e){return e.endsWith("capture")&&e!=="gotpointercapture"&&e!=="lostpointercapture"}const tKA=["beforeinput","click","change","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"];function iKA(e){return tKA.includes(e)}const nKA={formnovalidate:"formNoValidate",ismap:"isMap",nomodule:"noModule",playsinline:"playsInline",readonly:"readOnly",defaultvalue:"defaultValue",defaultchecked:"defaultChecked",srcobject:"srcObject"};function gKA(e){return e=e.toLowerCase(),nKA[e]??e}const oKA=["touchstart","touchmove"];function sKA(e){return oKA.includes(e)}const aKA=!1;var kL=Array.isArray,rKA=Array.prototype.indexOf,w8=Array.from,IKA=Object.defineProperty,Hu=Object.getOwnPropertyDescriptor,zcA=Object.getOwnPropertyDescriptors,CKA=Object.prototype,cKA=Array.prototype,k8=Object.getPrototypeOf;function KD(e){return typeof e=="function"}const cg=()=>{};function lKA(e){return e()}function o1(e){for(var A=0;A<e.length;A++)e[A]()}const $c=2,ZcA=4,bR=8,ML=16,ol=32,UR=64,MF=128,Jf=256,NF=512,cI=1024,od=2048,vR=4096,rB=8192,pw=16384,WcA=32768,Rd=65536,BKA=1<<17,EKA=1<<19,VcA=1<<20,Ou=Symbol("$state"),XcA=Symbol("legacy props"),QKA=Symbol("");function $cA(e){return e===this.v}function AlA(e,A){return e!=e?A==A:e!==A||e!==null&&typeof e=="object"||typeof e=="function"}function M8(e){return!AlA(e,this.v)}function uKA(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function dKA(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function hKA(e){throw new Error("https://svelte.dev/e/effect_orphan")}function pKA(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function fKA(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function yKA(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function DKA(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function mKA(){throw new Error("https://svelte.dev/e/state_unsafe_local_read")}function SKA(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}let fw=!1,wKA=!1;function kKA(){fw=!0}function xI(e,A){var t={f:0,v:e,reactions:null,equals:$cA,rv:0,wv:0};return t}function sn(e){return elA(xI(e))}function NL(e,A=!1){var t;const i=xI(e);return A||(i.equals=M8),fw&&ng!==null&&ng.l!==null&&((t=ng.l).s??(t.s=[])).push(i),i}function Nc(e,A=!1){return elA(NL(e,A))}function elA(e){return pg!==null&&pg.f&$c&&(IB===null?_KA([e]):IB.push(e)),e}function Kt(e,A){return pg!==null&&v8()&&pg.f&($c|ML)&&(IB===null||!IB.includes(e))&&SKA(),s1(e,A)}function s1(e,A){return e.equals(A)||(e.v,e.v=A,e.wv=ulA(),tlA(e,od),v8()&&fn!==null&&fn.f&cI&&!(fn.f&ol)&&(Wa!==null&&Wa.includes(e)?(sl(fn,od),UL(fn)):Pu===null?JKA([e]):Pu.push(e))),A}function tlA(e,A){var t=e.reactions;if(t!==null)for(var i=v8(),n=t.length,g=0;g<n;g++){var o=t[g],s=o.f;!(s&od)&&(!i&&o===fn||(sl(o,A),s&(cI|Jf)&&(s&$c?tlA(o,vR):UL(o))))}}let N8=!1;function pi(e,A=null,t){if(typeof e!="object"||e===null||Ou in e)return e;const i=k8(e);if(i!==CKA&&i!==cKA)return e;var n=new Map,g=kL(e),o=xI(0);g&&n.set("length",xI(e.length));var s;return new Proxy(e,{defineProperty(a,r,I){(!("value"in I)||I.configurable===!1||I.enumerable===!1||I.writable===!1)&&yKA();var c=n.get(r);return c===void 0?(c=xI(I.value),n.set(r,c)):Kt(c,pi(I.value,s)),!0},deleteProperty(a,r){var I=n.get(r);if(I===void 0)r in a&&n.set(r,xI(Pr));else{if(g&&typeof r=="string"){var c=n.get("length"),l=Number(r);Number.isInteger(l)&&l<c.v&&Kt(c,l)}Kt(I,Pr),$6(o)}return!0},get(a,r,I){var c;if(r===Ou)return e;var l=n.get(r),B=r in a;if(l===void 0&&(!B||(c=Hu(a,r))!=null&&c.writable)&&(l=xI(pi(B?a[r]:Pr,s)),n.set(r,l)),l!==void 0){var Q=MA(l);return Q===Pr?void 0:Q}return Reflect.get(a,r,I)},getOwnPropertyDescriptor(a,r){var I=Reflect.getOwnPropertyDescriptor(a,r);if(I&&"value"in I){var c=n.get(r);c&&(I.value=MA(c))}else if(I===void 0){var l=n.get(r),B=l==null?void 0:l.v;if(l!==void 0&&B!==Pr)return{enumerable:!0,configurable:!0,value:B,writable:!0}}return I},has(a,r){var I;if(r===Ou)return!0;var c=n.get(r),l=c!==void 0&&c.v!==Pr||Reflect.has(a,r);if(c!==void 0||fn!==null&&(!l||(I=Hu(a,r))!=null&&I.writable)){c===void 0&&(c=xI(l?pi(a[r],s):Pr),n.set(r,c));var B=MA(c);if(B===Pr)return!1}return l},set(a,r,I,c){var l,B=n.get(r),Q=r in a;if(g&&r==="length")for(var h=I;h<B.v;h+=1){var d=n.get(h+"");d!==void 0?Kt(d,Pr):h in a&&(d=xI(Pr),n.set(h+"",d))}B===void 0?(!Q||(l=Hu(a,r))!=null&&l.writable)&&(B=xI(void 0),Kt(B,pi(I,s)),n.set(r,B)):(Q=B.v!==Pr,Kt(B,pi(I,s)));var p=Reflect.getOwnPropertyDescriptor(a,r);if(p!=null&&p.set&&p.set.call(c,I),!Q){if(g&&typeof r=="string"){var y=n.get("length"),m=Number(r);Number.isInteger(m)&&m>=y.v&&Kt(y,m+1)}$6(o)}return!0},ownKeys(a){MA(o);var r=Reflect.ownKeys(a).filter(l=>{var B=n.get(l);return B===void 0||B.v!==Pr});for(var[I,c]of n)c.v!==Pr&&!(I in a)&&r.push(I);return r},setPrototypeOf(){DKA()}})}function $6(e,A=1){Kt(e,e.v+A)}var A7,ilA,nlA;function MKA(){if(A7===void 0){A7=window;var e=Element.prototype,A=Node.prototype;ilA=Hu(A,"firstChild").get,nlA=Hu(A,"nextSibling").get,e.__click=void 0,e.__className="",e.__attributes=null,e.__styles=null,e.__e=void 0,Text.prototype.__t=void 0}}function KR(e=""){return document.createTextNode(e)}function nf(e){return ilA.call(e)}function RL(e){return nlA.call(e)}function Ve(e,A){return nf(e)}function _i(e,A){{var t=nf(e);return t instanceof Comment&&t.data===""?RL(t):t}}function Ot(e,A=1,t=!1){let i=e;for(;A--;)i=RL(i);return i}function NKA(e){e.textContent=""}function Bt(e){var A=$c|od;fn===null?A|=Jf:fn.f|=VcA;var t=pg!==null&&pg.f&$c?pg:null;const i={children:null,ctx:ng,deps:null,equals:$cA,f:A,fn:e,reactions:null,rv:0,v:null,wv:0,parent:t??fn};return t!==null&&(t.children??(t.children=[])).push(i),i}function mm(e){const A=Bt(e);return A.equals=M8,A}function glA(e){var A=e.children;if(A!==null){e.children=null;for(var t=0;t<A.length;t+=1){var i=A[t];i.f&$c?R8(i):oc(i)}}}function RKA(e){for(var A=e.parent;A!==null;){if(!(A.f&$c))return A;A=A.parent}return null}function olA(e){var A,t=fn;lI(RKA(e));try{glA(e),A=dlA(e)}finally{lI(t)}return A}function slA(e){var A=olA(e),t=(rp||e.f&Jf)&&e.deps!==null?vR:cI;sl(e,t),e.equals(A)||(e.v=A,e.wv=ulA())}function R8(e){glA(e),gN(e,0),sl(e,pw),e.v=e.children=e.deps=e.ctx=e.reactions=null}function alA(e){fn===null&&pg===null&&hKA(),pg!==null&&pg.f&Jf&&dKA(),U8&&uKA()}function GKA(e,A){var t=A.last;t===null?A.last=A.first=e:(t.next=e,e.prev=t,A.last=e)}function yw(e,A,t,i=!0){var n=(e&UR)!==0,g=fn,o={ctx:ng,deps:null,deriveds:null,nodes_start:null,nodes_end:null,f:e|od,first:null,fn:A,last:null,next:null,parent:n?null:g,prev:null,teardown:null,transitions:null,wv:0};if(t){var s=Sm;try{e7(!0),_R(o),o.f|=WcA}catch(I){throw oc(o),I}finally{e7(s)}}else A!==null&&UL(o);var a=t&&o.deps===null&&o.first===null&&o.nodes_start===null&&o.teardown===null&&(o.f&VcA)===0;if(!a&&!n&&i&&(g!==null&&GKA(o,g),pg!==null&&(pg.f&$c)!==0)){var r=pg;(r.children??(r.children=[])).push(o)}return o}function rlA(e){const A=yw(bR,null,!1);return sl(A,cI),A.teardown=e,A}function SS(e){alA();var A=fn!==null&&(fn.f&ol)!==0&&ng!==null&&!ng.m;if(A){var t=ng;(t.e??(t.e=[])).push({fn:e,effect:fn,reaction:pg})}else{var i=GL(e);return i}}function bKA(e){return alA(),bL(e)}function UKA(e){const A=yw(UR,e,!0);return(t={})=>new Promise(i=>{t.outro?gf(A,()=>{oc(A),i(void 0)}):(oc(A),i(void 0))})}function GL(e){return yw(ZcA,e,!1)}function yl(e,A){var t=ng,i={effect:null,ran:!1};t.l.r1.push(i),i.effect=bL(()=>{e(),!i.ran&&(i.ran=!0,Kt(t.l.r2,!0),VE(A))})}function vKA(){var e=ng;bL(()=>{if(MA(e.l.r2)){for(var A of e.l.r1){var t=A.effect;t.f&cI&&sl(t,vR),Dw(t)&&_R(t),A.ran=!1}e.l.r2.v=!1}})}function bL(e){return yw(bR,e,!0)}function xt(e){return Gd(e)}function Gd(e,A=0){return yw(bR|ML|A,e,!0)}function Ac(e,A=!0){return yw(bR|ol,e,!0,A)}function IlA(e){var A=e.teardown;if(A!==null){const t=U8,i=pg;t7(!0),sc(null);try{A.call(null)}finally{t7(t),sc(i)}}}function ClA(e){var A=e.deriveds;if(A!==null){e.deriveds=null;for(var t=0;t<A.length;t+=1)R8(A[t])}}function clA(e,A=!1){var t=e.first;for(e.first=e.last=null;t!==null;){var i=t.next;oc(t,A),t=i}}function KKA(e){for(var A=e.first;A!==null;){var t=A.next;!(A.f&ol)&&oc(A),A=t}}function oc(e,A=!0){var t=!1;if((A||e.f&EKA)&&e.nodes_start!==null){for(var i=e.nodes_start,n=e.nodes_end;i!==null;){var g=i===n?null:RL(i);i.remove(),i=g}t=!0}clA(e,A&&!t),ClA(e),gN(e,0),sl(e,pw);var o=e.transitions;if(o!==null)for(const a of o)a.stop();IlA(e);var s=e.parent;s!==null&&s.first!==null&&llA(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes_start=e.nodes_end=null}function llA(e){var A=e.parent,t=e.prev,i=e.next;t!==null&&(t.next=i),i!==null&&(i.prev=t),A!==null&&(A.first===e&&(A.first=i),A.last===e&&(A.last=t))}function gf(e,A){var t=[];G8(e,t,!0),BlA(t,()=>{oc(e),A&&A()})}function BlA(e,A){var t=e.length;if(t>0){var i=()=>--t||A();for(var n of e)n.out(i)}else A()}function G8(e,A,t){if(!(e.f&rB)){if(e.f^=rB,e.transitions!==null)for(const o of e.transitions)(o.is_global||t)&&A.push(o);for(var i=e.first;i!==null;){var n=i.next,g=(i.f&Rd)!==0||(i.f&ol)!==0;G8(i,A,g?t:!1),i=n}}}function nN(e){ElA(e,!0)}function ElA(e,A){if(e.f&rB){Dw(e)&&_R(e),e.f^=rB;for(var t=e.first;t!==null;){var i=t.next,n=(t.f&Rd)!==0||(t.f&ol)!==0;ElA(t,n?A:!1),t=i}if(e.transitions!==null)for(const g of e.transitions)(g.is_global||A)&&g.in()}}let a1=!1,r1=[];function FKA(){a1=!1;const e=r1.slice();r1=[],o1(e)}function Lf(e){a1||(a1=!0,queueMicrotask(FKA)),r1.push(e)}function b8(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}let tM=!1,RF=!1,GF=null,Sm=!1,U8=!1;function e7(e){Sm=e}function t7(e){U8=e}let I1=[],iM=0,pg=null;function sc(e){pg=e}let fn=null;function lI(e){fn=e}let IB=null;function _KA(e){IB=e}let Wa=null,KI=0,Pu=null;function JKA(e){Pu=e}let QlA=1,C1=0,rp=!1,ng=null;function i7(e){ng=e}function ulA(){return++QlA}function v8(){return!fw||ng!==null&&ng.l===null}function Dw(e){var A,t=e.f;if(t&od)return!0;if(t&vR){var i=e.deps,n=(t&Jf)!==0;if(i!==null){var g,o,s=(t&NF)!==0,a=n&&fn!==null&&!rp,r=i.length;if(s||a){for(g=0;g<r;g++)o=i[g],(s||!((A=o==null?void 0:o.reactions)!=null&&A.includes(e)))&&(o.reactions??(o.reactions=[])).push(e);s&&(e.f^=NF)}for(g=0;g<r;g++)if(o=i[g],Dw(o)&&slA(o),o.wv>e.wv)return!0}(!n||fn!==null&&!rp)&&sl(e,cI)}return!1}function LKA(e,A){for(var t=A;t!==null;){if(t.f&MF)try{t.fn(e);return}catch{t.f^=MF}t=t.parent}throw tM=!1,e}function xKA(e){return(e.f&pw)===0&&(e.parent===null||(e.parent.f&MF)===0)}function E2(){tM=!1}function FR(e,A,t,i){if(tM){if(t===null&&(tM=!1),xKA(A))throw e;return}t!==null&&(tM=!0);{LKA(e,A);return}}function dlA(e){var A,t=Wa,i=KI,n=Pu,g=pg,o=rp,s=IB,a=ng,r=e.f;Wa=null,KI=0,Pu=null,pg=r&(ol|UR)?null:e,rp=!Sm&&(r&Jf)!==0,IB=null,ng=e.ctx,C1++;try{var I=(0,e.fn)(),c=e.deps;if(Wa!==null){var l;if(gN(e,KI),c!==null&&KI>0)for(c.length=KI+Wa.length,l=0;l<Wa.length;l++)c[KI+l]=Wa[l];else e.deps=c=Wa;if(!rp)for(l=KI;l<c.length;l++)((A=c[l]).reactions??(A.reactions=[])).push(e)}else c!==null&&KI<c.length&&(gN(e,KI),c.length=KI);return I}finally{Wa=t,KI=i,Pu=n,pg=g,rp=o,IB=s,ng=a}}function TKA(e,A){let t=A.reactions;if(t!==null){var i=rKA.call(t,e);if(i!==-1){var n=t.length-1;n===0?t=A.reactions=null:(t[i]=t[n],t.pop())}}t===null&&A.f&$c&&(Wa===null||!Wa.includes(A))&&(sl(A,vR),!(A.f&(Jf|NF))&&(A.f^=NF),gN(A,0))}function gN(e,A){var t=e.deps;if(t!==null)for(var i=A;i<t.length;i++)TKA(e,t[i])}function _R(e){var A=e.f;if(!(A&pw)){sl(e,cI);var t=fn,i=ng;fn=e;try{A&ML?KKA(e):clA(e),ClA(e),IlA(e);var n=dlA(e);e.teardown=typeof n=="function"?n:null,e.wv=QlA;var g=e.deps,o;aKA&&wKA&&e.f&od}catch(s){FR(s,e,t,i||e.ctx)}finally{fn=t}}}function qKA(){if(iM>1e3){iM=0;try{pKA()}catch(e){if(GF!==null)FR(e,GF,null);else throw e}}iM++}function YKA(e){var A=e.length;if(A!==0){qKA();var t=Sm;Sm=!0;try{for(var i=0;i<A;i++){var n=e[i];!(n.f&cI)&&(n.f^=cI);var g=[];hlA(n,g),HKA(g)}}finally{Sm=t}}}function HKA(e){var A=e.length;if(A!==0)for(var t=0;t<A;t++){var i=e[t];if(!(i.f&(pw|rB)))try{Dw(i)&&(_R(i),i.deps===null&&i.first===null&&i.nodes_start===null&&(i.teardown===null?llA(i):i.fn=null))}catch(n){FR(n,i,null,i.ctx)}}}function OKA(){if(RF=!1,iM>1001)return;const e=I1;I1=[],YKA(e),RF||(iM=0,GF=null)}function UL(e){RF||(RF=!0,queueMicrotask(OKA)),GF=e;for(var A=e;A.parent!==null;){A=A.parent;var t=A.f;if(t&(UR|ol)){if(!(t&cI))return;A.f^=cI}}I1.push(A)}function hlA(e,A){var t=e.first,i=[];A:for(;t!==null;){var n=t.f,g=(n&ol)!==0,o=g&&(n&cI)!==0,s=t.next;if(!o&&!(n&rB))if(n&bR){if(g)t.f^=cI;else try{Dw(t)&&_R(t)}catch(c){FR(c,t,null,t.ctx)}var a=t.first;if(a!==null){t=a;continue}}else n&ZcA&&i.push(t);if(s===null){let c=t.parent;for(;c!==null;){if(e===c)break A;var r=c.next;if(r!==null){t=r;continue A}c=c.parent}}t=s}for(var I=0;I<i.length;I++)a=i[I],A.push(a),hlA(a,A)}function MA(e){var A,t=e.f,i=(t&$c)!==0;if(i&&t&pw){var n=olA(e);return R8(e),n}if(pg!==null){IB!==null&&IB.includes(e)&&mKA();var g=pg.deps;e.rv<C1&&(e.rv=C1,Wa===null&&g!==null&&g[KI]===e?KI++:Wa===null?Wa=[e]:Wa.push(e),Pu!==null&&fn!==null&&fn.f&cI&&!(fn.f&ol)&&Pu.includes(e)&&(sl(fn,od),UL(fn)))}else if(i&&e.deps===null)for(var o=e,s=o.parent,a=o;s!==null;)if(s.f&$c){var r=s;a=r,s=r.parent}else{var I=s;(A=I.deriveds)!=null&&A.includes(a)||(I.deriveds??(I.deriveds=[])).push(a);break}return i&&(o=e,Dw(o)&&slA(o)),e.v}function VE(e){const A=pg;try{return pg=null,e()}finally{pg=A}}const PKA=-7169;function sl(e,A){e.f=e.f&PKA|A}function nr(e){return plA().get(e)}function Q2(e,A){return plA().set(e,A),A}function plA(e){return ng===null&&b8(),ng.c??(ng.c=new Map(jKA(ng)||void 0))}function jKA(e){let A=e.p;for(;A!==null;){const t=A.c;if(t!==null)return t;A=A.p}return null}function Ri(e,A=!1,t){ng={p:ng,c:null,e:null,m:!1,s:e,x:null,l:null},fw&&!A&&(ng.l={s:null,u:null,r1:[],r2:xI(!1)})}function Gi(e){const A=ng;if(A!==null){e!==void 0&&(A.x=e);const o=A.e;if(o!==null){var t=fn,i=pg;A.e=null;try{for(var n=0;n<o.length;n++){var g=o[n];lI(g.effect),sc(g.reaction),GL(g.fn)}}finally{lI(t),sc(i)}}ng=A.p,A.m=!0}return e||{}}function nK(e){if(!(typeof e!="object"||!e||e instanceof EventTarget)){if(Ou in e)c1(e);else if(!Array.isArray(e))for(let A in e){const t=e[A];typeof t=="object"&&t&&Ou in t&&c1(t)}}}function c1(e,A=new Set){if(typeof e=="object"&&e!==null&&!(e instanceof EventTarget)&&!A.has(e)){A.add(e),e instanceof Date&&e.getTime();for(let i in e)try{c1(e[i],A)}catch{}const t=k8(e);if(t!==Object.prototype&&t!==Array.prototype&&t!==Map.prototype&&t!==Set.prototype&&t!==Date.prototype){const i=zcA(t);for(let n in i){const g=i[n].get;if(g)try{g.call(e)}catch{}}}}}function zKA(e,A){if(A){const t=document.body;e.autofocus=!0,Lf(()=>{document.activeElement===t&&e.focus()})}}function ZKA(e){var A=pg,t=fn;sc(null),lI(null);try{return e()}finally{sc(A),lI(t)}}const flA=new Set,l1=new Set;function ylA(e,A,t,i){function n(g){if(i.capture||ck.call(A,g),!g.cancelBubble)return ZKA(()=>t.call(this,g))}return e.startsWith("pointer")||e.startsWith("touch")||e==="wheel"?Lf(()=>{A.addEventListener(e,n,i)}):A.addEventListener(e,n,i),n}function iB(e,A,t,i,n){var g={capture:i,passive:n},o=ylA(e,A,t,g);(A===document.body||A===window||A===document)&&rlA(()=>{A.removeEventListener(e,o,g)})}function vL(e){for(var A=0;A<e.length;A++)flA.add(e[A]);for(var t of l1)t(e)}function ck(e){var A,t=this,i=t.ownerDocument,n=e.type,g=((A=e.composedPath)==null?void 0:A.call(e))||[],o=g[0]||e.target,s=0,a=e.__root;if(a){var r=g.indexOf(a);if(r!==-1&&(t===document||t===window)){e.__root=t;return}var I=g.indexOf(t);if(I===-1)return;r<=I&&(s=r)}if(o=g[s]||e.target,o!==t){IKA(e,"currentTarget",{configurable:!0,get(){return o||i}});var c=pg,l=fn;sc(null),lI(null);try{for(var B,Q=[];o!==null;){var h=o.assignedSlot||o.parentNode||o.host||null;try{var d=o["__"+n];if(d!==void 0&&!o.disabled)if(kL(d)){var[p,...y]=d;p.apply(o,[e,...y])}else d.call(o,e)}catch(m){B?Q.push(m):B=m}if(e.cancelBubble||h===t||h===null)break;o=h}if(B){for(let m of Q)queueMicrotask(()=>{throw m});throw B}}finally{e.__root=t,delete e.currentTarget,sc(c),lI(l)}}}function K8(e){var A=document.createElement("template");return A.innerHTML=e,A.content}function of(e,A){var t=fn;t.nodes_start===null&&(t.nodes_start=e,t.nodes_end=A)}function Nt(e,A){var t=(A&$vA)!==0,i=(A&AKA)!==0,n,g=!e.startsWith("<!>");return()=>{n===void 0&&(n=K8(g?e:"<!>"+e),t||(n=nf(n)));var o=i?document.importNode(n,!0):n.cloneNode(!0);if(t){var s=nf(o),a=o.lastChild;of(s,a)}else of(o,o);return o}}function NB(e,A,t="svg"){var i=!e.startsWith("<!>"),n=`<${t}>${i?e:"<!>"+e}</${t}>`,g;return()=>{if(!g){var o=K8(n),s=nf(o);g=nf(s)}var a=g.cloneNode(!0);return of(a,a),a}}function Cg(e=""){{var A=KR(e+"");return of(A,A),A}}function xn(){var e=document.createDocumentFragment(),A=document.createComment(""),t=KR();return e.append(A,t),of(A,t),e}function Ne(e,A){e!==null&&e.before(A)}let bF=!0;function n7(e){bF=e}function Sn(e,A){var t=A==null?"":typeof A=="object"?A+"":A;t!==(e.__t??(e.__t=e.nodeValue))&&(e.__t=t,e.nodeValue=t==null?"":t+"")}function B1(e,A){return WKA(e,A)}const _y=new Map;function WKA(e,{target:A,anchor:t,props:i={},events:n,context:g,intro:o=!0}){MKA();var s=new Set,a=c=>{for(var l=0;l<c.length;l++){var B=c[l];if(!s.has(B)){s.add(B);var Q=sKA(B);A.addEventListener(B,ck,{passive:Q});var h=_y.get(B);h===void 0?(document.addEventListener(B,ck,{passive:Q}),_y.set(B,1)):_y.set(B,h+1)}}};a(w8(flA)),l1.add(a);var r=void 0,I=UKA(()=>{var c=t??A.appendChild(KR());return Ac(()=>{if(g){Ri({});var l=ng;l.c=g}n&&(i.$$events=n),bF=o,r=e(c,i)||{},bF=!0,g&&Gi()}),()=>{var l;for(var B of s){A.removeEventListener(B,ck);var Q=_y.get(B);--Q===0?(document.removeEventListener(B,ck),_y.delete(B)):_y.set(B,Q)}l1.delete(a),c!==t&&((l=c.parentNode)==null||l.removeChild(c))}});return E1.set(r,I),r}let E1=new WeakMap;function gK(e,A){const t=E1.get(e);return t?(E1.delete(e),t(A)):Promise.resolve()}function ii(e,A,t=!1){var i=e,n=null,g=null,o=Pr,s=t?Rd:0,a=!1;const r=(c,l=!0)=>{a=!0,I(l,c)},I=(c,l)=>{o!==(o=c)&&(o?(n?nN(n):l&&(n=Ac(()=>l(i))),g&&gf(g,()=>{g=null})):(g?nN(g):l&&(g=Ac(()=>l(i))),n&&gf(n,()=>{n=null})))};Gd(()=>{a=!1,A(r),a||I(null,null)},s)}function wS(e,A){return A}function VKA(e,A,t,i){for(var n=[],g=A.length,o=0;o<g;o++)G8(A[o].e,n,!0);var s=g>0&&n.length===0&&t!==null;if(s){var a=t.parentNode;NKA(a),a.append(t),i.clear(),$Q(e,A[0].prev,A[g-1].next)}BlA(n,()=>{for(var r=0;r<g;r++){var I=A[r];s||(i.delete(I.k),$Q(e,I.prev,I.next)),oc(I.e,!s)}})}function kS(e,A,t,i,n,g=null){var o=e,s={flags:A,items:new Map,first:null},a=(A&jcA)!==0;if(a){var r=e;o=r.appendChild(KR())}var I=null,c=!1;Gd(()=>{var l=t(),B=kL(l)?l:l==null?[]:w8(l),Q=B.length;if(!(c&&Q===0)){c=Q===0;{var h=pg;XKA(B,s,o,n,A,(h.f&rB)!==0,i)}g!==null&&(Q===0?I?nN(I):I=Ac(()=>g(o)):I!==null&&gf(I,()=>{I=null})),t()}})}function XKA(e,A,t,i,n,g,o,s){var a,r,I,c,l=(n&YvA)!==0,B=(n&(m8|S8))!==0,Q=e.length,h=A.items,d=A.first,p=d,y,m=null,D,S=[],k=[],N,G,M,w;if(l)for(w=0;w<Q;w+=1)N=e[w],G=o(N,w),M=h.get(G),M!==void 0&&((a=M.a)==null||a.measure(),(D??(D=new Set)).add(M));for(w=0;w<Q;w+=1){if(N=e[w],G=o(N,w),M=h.get(G),M===void 0){var b=p?p.e.nodes_start:t;m=AFA(b,A,m,m===null?A.first:m.next,N,G,w,i,n),h.set(G,m),S=[],k=[],p=m.next;continue}if(B&&$KA(M,N,w,n),M.e.f&rB&&(nN(M.e),l&&((r=M.a)==null||r.unfix(),(D??(D=new Set)).delete(M))),M!==p){if(y!==void 0&&y.has(M)){if(S.length<k.length){var _=k[0],K;m=_.prev;var J=S[0],q=S[S.length-1];for(K=0;K<S.length;K+=1)g7(S[K],_,t);for(K=0;K<k.length;K+=1)y.delete(k[K]);$Q(A,J.prev,q.next),$Q(A,m,J),$Q(A,q,_),p=_,m=q,w-=1,S=[],k=[]}else y.delete(M),g7(M,p,t),$Q(A,M.prev,M.next),$Q(A,M,m===null?A.first:m.next),$Q(A,m,M),m=M;continue}for(S=[],k=[];p!==null&&p.k!==G;)(g||!(p.e.f&rB))&&(y??(y=new Set)).add(p),k.push(p),p=p.next;if(p===null)continue;M=p}S.push(M),m=M,p=M.next}if(p!==null||y!==void 0){for(var v=y===void 0?[]:w8(y);p!==null;)(g||!(p.e.f&rB))&&v.push(p),p=p.next;var U=v.length;if(U>0){var x=n&jcA&&Q===0?t:null;if(l){for(w=0;w<U;w+=1)(I=v[w].a)==null||I.measure();for(w=0;w<U;w+=1)(c=v[w].a)==null||c.fix()}VKA(A,v,x,h)}}l&&Lf(()=>{var T;if(D!==void 0)for(M of D)(T=M.a)==null||T.apply()}),fn.first=A.first&&A.first.e,fn.last=m&&m.e}function $KA(e,A,t,i){i&m8&&s1(e.v,A),i&S8?s1(e.i,t):e.i=t}function AFA(e,A,t,i,n,g,o,s,a,r){var I=(a&m8)!==0,c=(a&HvA)===0,l=I?c?NL(n):xI(n):n,B=a&S8?xI(o):o,Q={i:B,v:l,k:g,a:null,e:null,prev:t,next:i};try{return Q.e=Ac(()=>s(e,l,B),N8),Q.e.prev=t&&t.e,Q.e.next=i&&i.e,t===null?A.first=Q:(t.next=Q,t.e.next=Q.e),i!==null&&(i.prev=Q,i.e.prev=Q.e),Q}finally{}}function g7(e,A,t){for(var i=e.next?e.next.e.nodes_start:t,n=A?A.e.nodes_start:t,g=e.e.nodes_start;g!==i;){var o=RL(g);n.before(g),g=o}}function $Q(e,A,t){A===null?e.first=t:(A.next=t,A.e.next=t&&t.e),t!==null&&(t.prev=A,t.e.prev=A&&A.e)}function bd(e,A,t,i,n){var g=e,o="",s;Gd(()=>{o!==(o=A()??"")&&(s!==void 0&&(oc(s),s=void 0),o!==""&&(s=Ac(()=>{var a=o+"",r=K8(a);of(nf(r),r.lastChild),g.before(r)})))})}function eFA(e,A,t,i,n){var g,o=(g=A.$$slots)==null?void 0:g[t],s=!1;o===!0&&(o=A.children,s=!0),o===void 0||o(e,s?()=>i:i)}function is(e,A,...t){var i=e,n=cg,g;Gd(()=>{n!==(n=A())&&(g&&(oc(g),g=null),g=Ac(()=>n(i,...t)))},Rd)}function tFA(e,A,t){var i=e,n,g;Gd(()=>{n!==(n=A())&&(g&&(gf(g),g=null),n&&(g=Ac(()=>t(i,n))))},Rd)}function UF(e,A,t,i,n,g){var o,s,a=null,r=e,I;Gd(()=>{const c=A()||null;var l=c==="svg"?iN:null;c!==o&&(I&&(c===null?gf(I,()=>{I=null,s=null}):c===s?nN(I):(oc(I),n7(!1))),c&&c!==s&&(I=Ac(()=>{if(a=l?document.createElementNS(l,c):document.createElement(c),of(a,a),i){var B=a.appendChild(KR());i(a,B)}fn.nodes_end=a,r.before(a)})),o=c,o&&(s=o),n7(!0))},Rd)}function hi(e,A){Lf(()=>{var t=e.getRootNode(),i=t.host?t:t.head??t.ownerDocument.head;if(!i.querySelector("#"+A.hash)){const n=document.createElement("style");n.id=A.hash,n.textContent=A.code,i.appendChild(n)}})}function DlA(e){var A,t,i="";if(typeof e=="string"||typeof e=="number")i+=e;else if(typeof e=="object")if(Array.isArray(e)){var n=e.length;for(A=0;A<n;A++)e[A]&&(t=DlA(e[A]))&&(i&&(i+=" "),i+=t)}else for(t in e)e[t]&&(i&&(i+=" "),i+=t);return i}function iFA(){for(var e,A,t=0,i="",n=arguments.length;t<n;t++)(e=arguments[t])&&(A=DlA(e))&&(i&&(i+=" "),i+=A);return i}function mlA(e){return typeof e=="object"?iFA(e):e??""}function nFA(e,A){A?e.hasAttribute("selected")||e.setAttribute("selected",""):e.removeAttribute("selected")}function Ci(e,A,t,i){var n=e.__attributes??(e.__attributes={});n[A]!==(n[A]=t)&&(A==="style"&&"__styles"in e&&(e.__styles={}),A==="loading"&&(e[QKA]=t),t==null?e.removeAttribute(A):typeof t!="string"&&SlA(e).includes(A)?e[A]=t:e.setAttribute(A,t))}function vF(e,A,t,i,n=!1,g=!1,o=!1){var s=A||{},a=e.tagName==="OPTION";for(var r in A)r in t||(t[r]=null);t.class&&(t.class=mlA(t.class)),i!==void 0&&(t.class=t.class?t.class+" "+i:i);var I=SlA(e),c=e.__attributes??(e.__attributes={});for(const p in t){let y=t[p];if(a&&p==="value"&&y==null){e.value=e.__value="",s[p]=y;continue}var l=s[p];if(y!==l){s[p]=y;var B=p[0]+p[1];if(B!=="$$"){if(B==="on"){const m={},D="$$"+p;let S=p.slice(2);var Q=iKA(S);if(eKA(S)&&(S=S.slice(0,-7),m.capture=!0),!Q&&l){if(y!=null)continue;e.removeEventListener(S,s[D],m),s[D]=null}if(y!=null)if(Q)e[`__${S}`]=y,vL([S]);else{let k=function(N){s[p].call(this,N)};s[D]=ylA(S,e,k,m)}else Q&&(e[`__${S}`]=void 0)}else if(p==="style"&&y!=null)e.style.cssText=y+"";else if(p==="autofocus")zKA(e,!!y);else if(p==="__value"||p==="value"&&y!=null)e.value=e[p]=e.__value=y;else if(p==="selected"&&a)nFA(e,y);else{var h=p;n||(h=gKA(h));var d=h==="defaultValue"||h==="defaultChecked";if(y==null&&!g&&!d)if(c[p]=null,h==="value"||h==="checked"){let m=e;if(h==="value"){let D=m.defaultValue;m.removeAttribute(h),m.defaultValue=D}else{let D=m.defaultChecked;m.removeAttribute(h),m.defaultChecked=D}}else e.removeAttribute(p);else d||I.includes(h)&&(g||typeof y!="string")?e[h]=y:typeof y!="function"&&Ci(e,h,y)}p==="style"&&"__styles"in e&&(e.__styles={})}}}return s}var o7=new Map;function SlA(e){var A=o7.get(e.nodeName);if(A)return A;o7.set(e.nodeName,A=[]);for(var t,i=e,n=Element.prototype;n!==i;){t=zcA(i);for(var g in t)t[g].set&&A.push(g);i=k8(i)}return A}function gFA(e,A,t){var i=e.__className,n=wlA(A,t);(i!==n||N8)&&(n===""?e.removeAttribute("class"):e.setAttribute("class",n),e.__className=n)}function sd(e,A,t){var i=e.__className,n=wlA(A,t);(i!==n||N8)&&(A==null&&!t?e.removeAttribute("class"):e.className=n,e.__className=n)}function wlA(e,A){return(e??"")+(A?" "+A:"")}function LE(e,A,t){if(t){if(e.classList.contains(A))return;e.classList.add(A)}else{if(!e.classList.contains(A))return;e.classList.remove(A)}}const oFA=()=>performance.now(),dE={tick:e=>requestAnimationFrame(e),now:()=>oFA(),tasks:new Set};function klA(){const e=dE.now();dE.tasks.forEach(A=>{A.c(e)||(dE.tasks.delete(A),A.f())}),dE.tasks.size!==0&&dE.tick(klA)}function sFA(e){let A;return dE.tasks.size===0&&dE.tick(klA),{promise:new Promise(t=>{dE.tasks.add(A={c:e,f:t})}),abort(){dE.tasks.delete(A)}}}function hb(e,A){e.dispatchEvent(new CustomEvent(A))}function aFA(e){if(e==="float")return"cssFloat";if(e==="offset")return"cssOffset";if(e.startsWith("--"))return e;const A=e.split("-");return A.length===1?A[0]:A[0]+A.slice(1).map(t=>t[0].toUpperCase()+t.slice(1)).join("")}function s7(e){const A={},t=e.split(";");for(const i of t){const[n,g]=i.split(":");if(!n||g===void 0)break;const o=aFA(n.trim());A[o]=g.trim()}return A}const rFA=e=>e;function MlA(e,A,t,i){var n=(e&WvA)!==0,g=(e&VvA)!==0,o=n&&g,s=(e&XvA)!==0,a=o?"both":n?"in":"out",r,I=A.inert,c,l;function B(){var y=pg,m=fn;sc(null),lI(null);try{return r??(r=t()(A,(i==null?void 0:i())??{},{direction:a}))}finally{sc(y),lI(m)}}var Q={is_global:s,in(){var y;if(A.inert=I,!n){l==null||l.abort(),(y=l==null?void 0:l.reset)==null||y.call(l);return}g||c==null||c.abort(),hb(A,"introstart"),c=Q1(A,B(),l,1,()=>{hb(A,"introend"),c==null||c.abort(),c=r=void 0})},out(y){if(!g){y==null||y(),r=void 0;return}A.inert=!0,hb(A,"outrostart"),l=Q1(A,B(),c,0,()=>{hb(A,"outroend"),y==null||y()})},stop:()=>{c==null||c.abort(),l==null||l.abort()}},h=fn;if((h.transitions??(h.transitions=[])).push(Q),n&&bF){var d=s;if(!d){for(var p=h.parent;p&&p.f&Rd;)for(;(p=p.parent)&&!(p.f&ML););d=!p||(p.f&WcA)!==0}d&&GL(()=>{VE(()=>Q.in())})}}function Q1(e,A,t,i,n){var g=i===1;if(KD(A)){var o,s=!1;return Lf(()=>{if(!s){var d=A({direction:g?"in":"out"});o=Q1(e,d,t,i,n)}}),{abort:()=>{s=!0,o==null||o.abort()},deactivate:()=>o.deactivate(),reset:()=>o.reset(),t:()=>o.t()}}if(t==null||t.deactivate(),!(A!=null&&A.duration))return n(),{abort:cg,deactivate:cg,reset:cg,t:()=>i};const{delay:a=0,css:r,tick:I,easing:c=rFA}=A;var l=[];if(g&&t===void 0&&(I&&I(0,1),r)){var B=s7(r(0,1));l.push(B,B)}var Q=()=>1-i,h=e.animate(l,{duration:a});return h.onfinish=()=>{var d=(t==null?void 0:t.t())??1-i;t==null||t.abort();var p=i-d,y=A.duration*Math.abs(p),m=[];if(y>0){if(r)for(var D=Math.ceil(y/16.666666666666668),S=0;S<=D;S+=1){var k=d+p*c(S/D),N=r(k,1-k);m.push(s7(N))}Q=()=>{var G=h.currentTime;return d+p*c(G/y)},I&&sFA(()=>{if(h.playState!=="running")return!1;var G=Q();return I(G,1-G),!0})}h=e.animate(m,{duration:y,fill:"forwards"}),h.onfinish=()=>{Q=()=>i,I==null||I(i,1-i),n()}},{abort:()=>{h&&(h.cancel(),h.effect=null,h.onfinish=cg)},deactivate:()=>{n=cg},reset:()=>{i===0&&(I==null||I(1,0))},t:()=>Q()}}function a7(e,A){return e===A||(e==null?void 0:e[Ou])===A}function NlA(e={},A,t,i){return GL(()=>{var n,g;return bL(()=>{n=g,g=[],VE(()=>{e!==t(...g)&&(A(e,...g),n&&a7(t(...n),e)&&A(null,...n))})}),()=>{Lf(()=>{g&&a7(t(...g),e)&&A(null,...g)})}}),e}function lc(e=!1){const A=ng,t=A.l.u;if(!t)return;let i=()=>nK(A.s);if(e){let n=0,g={};const o=Bt(()=>{let s=!1;const a=A.s;for(const r in a)a[r]!==g[r]&&(g[r]=a[r],s=!0);return s&&n++,n});i=()=>MA(o)}t.b.length&&bKA(()=>{r7(A,i),o1(t.b)}),SS(()=>{const n=VE(()=>t.m.map(lKA));return()=>{for(const g of n)typeof g=="function"&&g()}}),t.a.length&&SS(()=>{r7(A,i),o1(t.a)})}function r7(e,A){if(e.l.s)for(const t of e.l.s)MA(t);A()}function RlA(e,A){var t,i=(t=e.$$events)==null?void 0:t[A.type],n=kL(i)?i.slice():i==null?[]:[i];for(var g of n)g.call(this,A)}function ac(e){ng===null&&b8(),fw&&ng.l!==null?IFA(ng).m.push(e):SS(()=>{const A=VE(e);if(typeof A=="function")return A})}function JR(e){ng===null&&b8(),ac(()=>()=>VE(e))}function IFA(e){var A=e.l;return A.u??(A.u={a:[],b:[],m:[]})}function CFA(e,A,t){if(e==null)return A(void 0),cg;const i=VE(()=>e.subscribe(A,t));return i.unsubscribe?()=>i.unsubscribe():i}let pb=!1;function uI(e,A,t){const i=t[A]??(t[A]={store:null,source:NL(void 0),unsubscribe:cg});if(i.store!==e)if(i.unsubscribe(),i.store=e??null,e==null)i.source.v=void 0,i.unsubscribe=cg;else{var n=!0;i.unsubscribe=CFA(e,g=>{n?i.source.v=g:Kt(i.source,g)}),n=!1}return MA(i.source)}function dI(){const e={};return rlA(()=>{for(var A in e)e[A].unsubscribe()}),e}function cFA(e){var A=pb;try{return pb=!1,[e(),pb]}finally{pb=A}}const lFA={get(e,A){if(!e.exclude.includes(A))return e.props[A]},set(e,A){return!1},getOwnPropertyDescriptor(e,A){if(!e.exclude.includes(A)&&A in e.props)return{enumerable:!0,configurable:!0,value:e.props[A]}},has(e,A){return e.exclude.includes(A)?!1:A in e.props},ownKeys(e){return Reflect.ownKeys(e.props).filter(A=>!e.exclude.includes(A))}};function Ud(e,A,t){return new Proxy({props:e,exclude:A},lFA)}const BFA={get(e,A){let t=e.props.length;for(;t--;){let i=e.props[t];if(KD(i)&&(i=i()),typeof i=="object"&&i!==null&&A in i)return i[A]}},set(e,A,t){let i=e.props.length;for(;i--;){let n=e.props[i];KD(n)&&(n=n());const g=Hu(n,A);if(g&&g.set)return g.set(t),!0}return!1},getOwnPropertyDescriptor(e,A){let t=e.props.length;for(;t--;){let i=e.props[t];if(KD(i)&&(i=i()),typeof i=="object"&&i!==null&&A in i){const n=Hu(i,A);return n&&!n.configurable&&(n.configurable=!0),n}}},has(e,A){if(A===Ou||A===XcA)return!1;for(let t of e.props)if(KD(t)&&(t=t()),t!=null&&A in t)return!0;return!1},ownKeys(e){const A=[];for(let t of e.props){KD(t)&&(t=t());for(const i in t)A.includes(i)||A.push(i)}return A}};function XE(...e){return new Proxy({props:e},BFA)}function I7(e){for(var A=fn,t=fn;A!==null&&!(A.f&(ol|UR));)A=A.parent;try{return lI(A),e()}finally{lI(t)}}function ri(e,A,t,i){var n,g=(t&OvA)!==0,o=!fw||(t&PvA)!==0,s=(t&zvA)!==0,a=(t&ZvA)!==0,r=!1,I;s?[I,r]=cFA(()=>e[A]):I=e[A];var c=Ou in e||XcA in e,l=((n=Hu(e,A))==null?void 0:n.set)??(c&&s&&A in e?G=>e[A]=G:void 0),B=i,Q=!0,h=!1,d=()=>(h=!0,Q&&(Q=!1,a?B=VE(i):B=i),B);I===void 0&&i!==void 0&&(l&&o&&fKA(),I=d(),l&&l(I));var p;if(o)p=()=>{var G=e[A];return G===void 0?d():(Q=!0,h=!1,G)};else{var y=I7(()=>(g?Bt:mm)(()=>e[A]));y.f|=BKA,p=()=>{var G=MA(y);return G!==void 0&&(B=void 0),G===void 0?B:G}}if(!(t&jvA))return p;if(l){var m=e.$$legacy;return function(G,M){return arguments.length>0?((!o||!M||m||r)&&l(M?p():G),G):p()}}var D=!1,S=!1,k=NL(I),N=I7(()=>Bt(()=>{var G=p(),M=MA(k);return D?(D=!1,S=!0,M):(S=!1,k.v=G)}));return g||(N.equals=M8),function(G,M){if(arguments.length>0){const w=M?MA(N):o&&s?pi(G):G;return N.equals(w)||(D=!0,Kt(k,w),h&&B!==void 0&&(B=w),VE(()=>MA(N))),G}return MA(N)}}function C7(e,A){var t=fn,i=pg,n=ng;lI(e),sc(e),i7(e.ctx);try{A()}finally{lI(t),sc(i),i7(n)}}function EFA(e,A,t){var i=e,n;Gd(()=>{var g=fn,o=!1;g.fn=s=>{var a=A.onerror;let r=A.failed;if(!a&&!r||o)throw s;var I=()=>{gf(n),C7(g,()=>{o=!1,n=Ac(()=>t(i)),E2()})};a==null||a(s,I),n&&oc(n),r&&Lf(()=>{C7(g,()=>{o=!0;try{n=Ac(()=>{r(i,()=>s,()=>I)})}catch(c){FR(c,g,null,g.ctx)}E2(),o=!1})})},n=Ac(()=>t(i)),E2()},Rd|MF)}var Ds=(e=>(e[e.UnknownError=0]="UnknownError",e[e.UserCancelledError=1]="UserCancelledError",e[e.StoreProblemError=2]="StoreProblemError",e[e.PurchaseNotAllowedError=3]="PurchaseNotAllowedError",e[e.PurchaseInvalidError=4]="PurchaseInvalidError",e[e.ProductNotAvailableForPurchaseError=5]="ProductNotAvailableForPurchaseError",e[e.ProductAlreadyPurchasedError=6]="ProductAlreadyPurchasedError",e[e.ReceiptAlreadyInUseError=7]="ReceiptAlreadyInUseError",e[e.InvalidReceiptError=8]="InvalidReceiptError",e[e.MissingReceiptFileError=9]="MissingReceiptFileError",e[e.NetworkError=10]="NetworkError",e[e.InvalidCredentialsError=11]="InvalidCredentialsError",e[e.UnexpectedBackendResponseError=12]="UnexpectedBackendResponseError",e[e.InvalidAppUserIdError=14]="InvalidAppUserIdError",e[e.OperationAlreadyInProgressError=15]="OperationAlreadyInProgressError",e[e.UnknownBackendError=16]="UnknownBackendError",e[e.InvalidAppleSubscriptionKeyError=17]="InvalidAppleSubscriptionKeyError",e[e.IneligibleError=18]="IneligibleError",e[e.InsufficientPermissionsError=19]="InsufficientPermissionsError",e[e.PaymentPendingError=20]="PaymentPendingError",e[e.InvalidSubscriberAttributesError=21]="InvalidSubscriberAttributesError",e[e.LogOutWithAnonymousUserError=22]="LogOutWithAnonymousUserError",e[e.ConfigurationError=23]="ConfigurationError",e[e.UnsupportedError=24]="UnsupportedError",e[e.EmptySubscriberAttributesError=25]="EmptySubscriberAttributesError",e[e.CustomerInfoError=28]="CustomerInfoError",e[e.SignatureVerificationError=36]="SignatureVerificationError",e[e.InvalidEmailError=38]="InvalidEmailError",e))(Ds||{});class nM{static getPublicMessage(A){switch(A){case 0:return"Unknown error.";case 1:return"Purchase was cancelled.";case 2:return"There was a problem with the store.";case 3:return"The device or user is not allowed to make the purchase.";case 4:return"One or more of the arguments provided are invalid.";case 5:return"The product is not available for purchase.";case 6:return"This product is already active for the user.";case 7:return"There is already another active subscriber using the same receipt.";case 8:return"The receipt is not valid.";case 9:return"The receipt is missing.";case 10:return"Error performing request. Please check your network connection and try again.";case 11:return"There was a credentials issue. Check the underlying error for more details.";case 12:return"Received unexpected response from the backend.";case 14:return"The app user id is not valid.";case 15:return"The operation is already in progress.";case 16:return"There was an unknown backend error.";case 17:return"Apple Subscription Key is invalid or not present. In order to provide subscription offers, you must first generate a subscription key. Please see https://docs.revenuecat.com/docs/ios-subscription-offers for more info.";case 18:return"The User is ineligible for that action.";case 19:return"App does not have sufficient permissions to make purchases.";case 20:return"The payment is pending.";case 21:return"One or more of the attributes sent could not be saved.";case 22:return"Called logOut but the current user is anonymous.";case 23:return"There is an issue with your configuration. Check the underlying error for more details.";case 24:return"There was a problem with the operation. Looks like we doesn't support that yet. Check the underlying error for more details.";case 25:return"A request for subscriber attributes returned none.";case 28:return"There was a problem related to the customer info.";case 36:return"Request failed signature verification. Please see https://rev.cat/trusted-entitlements for more info.";case 38:return"Email is not valid. Please provide a valid email address."}}static getErrorCodeForBackendErrorCode(A){switch(A){case 7101:case 7773:case 7898:case 7899:case 7900:case 7901:return 2;case 7102:return 7;case 7103:return 8;case 7107:case 7224:case 7225:return 11;case 7105:case 7106:case 7814:case 7877:case 7878:return 4;case 7772:return 6;case 7220:return 14;case 7259:return 28;case 7229:return 2;case 7230:case 7e3:return 23;case 7231:return 2;case 7232:return 18;case 7263:case 7264:return 21;case 7104:case 7234:case 7226:case 7110:return 12;case 7662:return 24;case 7012:case 7834:case 7879:return 38}}static convertCodeToBackendErrorCode(A){return A in gM?A:null}static convertPurchaseFlowErrorCodeToErrorCode(A){switch(A){case dg.ErrorSettingUpPurchase:return 2;case dg.ErrorChargingPayment:return 20;case dg.NetworkError:return 10;case dg.MissingEmailError:return 4;case dg.AlreadyPurchasedError:return 6;default:return 0}}}var gM=(e=>(e[e.BackendInvalidPlatform=7e3]="BackendInvalidPlatform",e[e.BackendInvalidEmail=7012]="BackendInvalidEmail",e[e.BackendStoreProblem=7101]="BackendStoreProblem",e[e.BackendCannotTransferPurchase=7102]="BackendCannotTransferPurchase",e[e.BackendInvalidReceiptToken=7103]="BackendInvalidReceiptToken",e[e.BackendInvalidAppStoreSharedSecret=7104]="BackendInvalidAppStoreSharedSecret",e[e.BackendInvalidPaymentModeOrIntroPriceNotProvided=7105]="BackendInvalidPaymentModeOrIntroPriceNotProvided",e[e.BackendProductIdForGoogleReceiptNotProvided=7106]="BackendProductIdForGoogleReceiptNotProvided",e[e.BackendInvalidPlayStoreCredentials=7107]="BackendInvalidPlayStoreCredentials",e[e.BackendInternalServerError=7110]="BackendInternalServerError",e[e.BackendEmptyAppUserId=7220]="BackendEmptyAppUserId",e[e.BackendInvalidAuthToken=7224]="BackendInvalidAuthToken",e[e.BackendInvalidAPIKey=7225]="BackendInvalidAPIKey",e[e.BackendBadRequest=7226]="BackendBadRequest",e[e.BackendPlayStoreQuotaExceeded=7229]="BackendPlayStoreQuotaExceeded",e[e.BackendPlayStoreInvalidPackageName=7230]="BackendPlayStoreInvalidPackageName",e[e.BackendPlayStoreGenericError=7231]="BackendPlayStoreGenericError",e[e.BackendUserIneligibleForPromoOffer=7232]="BackendUserIneligibleForPromoOffer",e[e.BackendInvalidAppleSubscriptionKey=7234]="BackendInvalidAppleSubscriptionKey",e[e.BackendSubscriberNotFound=7259]="BackendSubscriberNotFound",e[e.BackendInvalidSubscriberAttributes=7263]="BackendInvalidSubscriberAttributes",e[e.BackendInvalidSubscriberAttributesBody=7264]="BackendInvalidSubscriberAttributesBody",e[e.BackendProductIDsMalformed=7662]="BackendProductIDsMalformed",e[e.BackendAlreadySubscribedError=7772]="BackendAlreadySubscribedError",e[e.BackendPaymentGatewayGenericError=7773]="BackendPaymentGatewayGenericError",e[e.BackendOfferNotFound=7814]="BackendOfferNotFound",e[e.BackendNoMXRecordsFound=7834]="BackendNoMXRecordsFound",e[e.BackendInvalidOperationSession=7877]="BackendInvalidOperationSession",e[e.BackendPurchaseCannotBeCompleted=7878]="BackendPurchaseCannotBeCompleted",e[e.BackendEmailIsRequired=7879]="BackendEmailIsRequired",e[e.BackendGatewaySetupErrorStripeTaxNotActive=7898]="BackendGatewaySetupErrorStripeTaxNotActive",e[e.BackendGatewaySetupErrorInvalidTaxOriginAddress=7899]="BackendGatewaySetupErrorInvalidTaxOriginAddress",e[e.BackendGatewaySetupErrorMissingRequiredPermission=7900]="BackendGatewaySetupErrorMissingRequiredPermission",e[e.BackendGatewaySetupErrorSandboxModeOnly=7901]="BackendGatewaySetupErrorSandboxModeOnly",e))(gM||{});class mo extends Error{constructor(A,t,i,n){super(t),Yt(this,"toString",()=>`PurchasesError(code: ${Ds[this.errorCode]}, message: ${this.message})`),this.errorCode=A,this.underlyingErrorMessage=i,this.extra=n}static getForBackendError(A,t){const i=nM.getErrorCodeForBackendErrorCode(A);return new mo(i,nM.getPublicMessage(i),t,{backendErrorCode:A})}static getForPurchasesFlowError(A){return new mo(nM.convertPurchaseFlowErrorCodeToErrorCode(A.errorCode),A.message,A.underlyingErrorMessage)}}class QFA extends Error{constructor(){super("Purchases must be configured before calling getInstance")}}var lk=(e=>(e.Started="started",e.InProgress="in_progress",e.Succeeded="succeeded",e.Failed="failed",e))(lk||{}),FD=(e=>(e[e.SetupIntentCreationFailed=1]="SetupIntentCreationFailed",e[e.PaymentMethodCreationFailed=2]="PaymentMethodCreationFailed",e[e.PaymentChargeFailed=3]="PaymentChargeFailed",e[e.SetupIntentCompletionFailed=4]="SetupIntentCompletionFailed",e[e.AlreadyPurchased=5]="AlreadyPurchased",e))(FD||{}),FI=(e=>(e[e.Silent=0]="Silent",e[e.Error=1]="Error",e[e.Warn=2]="Warn",e[e.Info=3]="Info",e[e.Debug=4]="Debug",e[e.Verbose=5]="Verbose",e))(FI||{});let $i=class{static setLogLevel(A){this.logLevel=A}static log(A,t=this.logLevel){const i=`[Purchases] ${A}`;if(!(this.logLevel<t||t===FI.Silent))switch(t){case FI.Error:console.error(i);break;case FI.Warn:console.warn(i);break;case FI.Info:console.info(i);break;case FI.Debug:console.debug(i);break;case FI.Verbose:console.debug(i);break}}static errorLog(A){this.log(A,FI.Error)}static warnLog(A){this.log(A,FI.Warn)}static infoLog(A){this.log(A,FI.Info)}static debugLog(A){this.log(A,FI.Debug)}static verboseLog(A){this.log(A,FI.Verbose)}};Yt($i,"logLevel",FI.Silent);function uFA(e){var A;return e.operation.redemption_info?{redeemUrl:((A=e.operation.redemption_info)==null?void 0:A.redeem_url)??null}:null}var dg=(e=>(e[e.ErrorSettingUpPurchase=0]="ErrorSettingUpPurchase",e[e.ErrorChargingPayment=1]="ErrorChargingPayment",e[e.UnknownError=2]="UnknownError",e[e.NetworkError=3]="NetworkError",e[e.MissingEmailError=4]="MissingEmailError",e[e.AlreadyPurchasedError=5]="AlreadyPurchasedError",e[e.StripeTaxNotActive=6]="StripeTaxNotActive",e[e.StripeInvalidTaxOriginAddress=7]="StripeInvalidTaxOriginAddress",e[e.StripeMissingRequiredPermission=8]="StripeMissingRequiredPermission",e))(dg||{});class Fg extends Error{constructor(A,t,i,n,g){super(t),this.errorCode=A,this.underlyingErrorMessage=i,this.purchasesErrorCode=n,this.extra=g}getErrorCode(){var A;return((A=this.extra)==null?void 0:A.backendErrorCode)??this.purchasesErrorCode??this.errorCode}static fromPurchasesError(A,t){var i;let n;return A.errorCode===Ds.ProductAlreadyPurchasedError?n=5:A.errorCode===Ds.InvalidEmailError?n=4:A.errorCode===Ds.NetworkError?n=3:n=Fg.fromBackendErrorCode((i=A.extra)==null?void 0:i.backendErrorCode)??t,new Fg(n,A.message,A.underlyingErrorMessage,A.errorCode,A.extra)}static fromBackendErrorCode(A){switch(A){case gM.BackendGatewaySetupErrorStripeTaxNotActive:return 6;case gM.BackendGatewaySetupErrorInvalidTaxOriginAddress:return 7;case gM.BackendGatewaySetupErrorMissingRequiredPermission:return 8;default:return null}}}class dFA{constructor(A,t,i=10){Yt(this,"operationSessionId",null),Yt(this,"backend"),Yt(this,"eventsTracker"),Yt(this,"maxNumberAttempts"),Yt(this,"waitMSBetweenAttempts",1e3),this.backend=A,this.eventsTracker=t,this.maxNumberAttempts=i}async checkoutStart(A,t,i,n,g,o){try{const s=this.eventsTracker.getTraceId(),a=await this.backend.postCheckoutStart(A,t,n,i,s,g,o);return this.operationSessionId=a.operation_session_id,a}catch(s){if(s instanceof mo)throw Fg.fromPurchasesError(s,0);{const a="Unknown error starting purchase: "+String(s);throw $i.errorLog(a),new Fg(2,a)}}}async checkoutCalculateTax(A,t,i){const n=this.operationSessionId;if(!n)throw new Fg(0,"No purchase started");try{return await this.backend.postCheckoutCalculateTax(n,A,t,i)}catch(g){if(g instanceof mo)throw Fg.fromPurchasesError(g,0);{const o="Unknown error calculating tax: "+String(g);throw $i.errorLog(o),new Fg(2,o)}}}async checkoutComplete(A){const t=this.operationSessionId;if(!t)throw new Fg(0,"No purchase started");try{return await this.backend.postCheckoutComplete(t,A)}catch(i){if(i instanceof mo)throw Fg.fromPurchasesError(i,0);{const n="Unknown error starting purchase: "+String(i);throw $i.errorLog(n),new Fg(2,n)}}}async pollCurrentPurchaseForCompletion(){const A=this.operationSessionId;if(!A)throw new Fg(0,"No purchase in progress");return new Promise((t,i)=>{const n=(g=1)=>{if(g>this.maxNumberAttempts){this.clearPurchaseInProgress(),i(new Fg(2,"Max attempts reached trying to get successful purchase status"));return}this.backend.getCheckoutStatus(A).then(o=>{const s=o.operation.store_transaction_identifier,a=o.operation.product_identifier,r=o.operation.purchase_date?isNaN(Date.parse(o.operation.purchase_date))?null:new Date(o.operation.purchase_date):null;switch(o.operation.status){case lk.Started:case lk.InProgress:setTimeout(()=>n(g+1),this.waitMSBetweenAttempts);break;case lk.Succeeded:if(this.clearPurchaseInProgress(),!s||!a||!r){i(new Fg(2,"Missing required fields in operation response."));return}t({redemptionInfo:uFA(o),operationSessionId:A,storeTransactionIdentifier:s,productIdentifier:a,purchaseDate:r});return;case lk.Failed:this.clearPurchaseInProgress(),this.handlePaymentError(o.operation.error,i)}}).catch(o=>{const s=Fg.fromPurchasesError(o,3);i(s)})};n()})}clearPurchaseInProgress(){this.operationSessionId=null}handlePaymentError(A,t){if(A==null){t(new Fg(2,"Got an error status but error field is empty."));return}switch(A.code){case FD.SetupIntentCreationFailed:t(new Fg(0,"Setup intent creation failed"));return;case FD.PaymentMethodCreationFailed:t(new Fg(0,"Payment method creation failed"));return;case FD.PaymentChargeFailed:t(new Fg(1,"Payment charge failed"));return;case FD.SetupIntentCompletionFailed:t(new Fg(0,"Setup intent completion failed"));return;case FD.AlreadyPurchased:t(new Fg(5,"Purchased was already completed"));return;default:t(new Fg(2,"Unknown error code received"));return}}}const iC="rcb-ui-translator",wm="en",hFA={"periods.week":"{{amount}} week","periods.month":"{{amount}} month","periods.year":"{{amount}} year","periods.day":"{{amount}} day","periods.weekShort":"{{amount}}wk","periods.monthShort":"{{amount}}mo","periods.yearShort":"{{amount}}yr","periods.dayShort":"{{amount}}d","periods.lifetime":"lifetime","periods.weekPlural":"{{amount}} weeks","periods.monthPlural":"{{amount}} months","periods.yearPlural":"{{amount}} years","periods.dayPlural":"{{amount}} days","periods.weekFrequency":"weekly","periods.monthFrequency":"monthly","periods.yearFrequency":"yearly","periods.dayFrequency":"daily","periods.perWeekFrequency":"per week","periods.perMonthFrequency":"per month","periods.perYearFrequency":"per year","periods.perDayFrequency":"per day","periods.unknownFrequency":"unknown","periods.weekFrequencyPlural":"every {{amount}} weeks","periods.monthFrequencyPlural":"every {{amount}} months","periods.yearFrequencyPlural":"every {{amount}} years","periods.dayFrequencyPlural":"every {{amount}} days","product_info.subscribe_to":"Subscribe to","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"Try free for {{trialDuration}}","product_info.price_after_free_trial":"After trial ends, on {{renewalDate}}","product_info.intro_price_phase_after_trial":"Then {{introPriceDuration}} for {{introPrice}}","product_info.intro_price_phase":"First {{introPriceDuration}} for {{introPrice}}","product_info.intro_price_phase_paid_once":"paid once","product_info.price_after_intro_price":"After {{introPriceDuration}}, on {{renewalDate}}","product_info.after_trial":"after trial","product_info.after":"after","product_info.total_due_today":"Total due today","product_info.renewal_frequency":"Renews {{frequency}}","product_info.continues_until_cancelled":"Continues until cancelled","product_info.cancel_anytime":"Cancel anytime","payment_entry_page.payment_step_title":"Secure checkout by RevenueCat","payment_entry_page.trial_subscription_terms_info":"After your trial ends, you will be charged {{price}} {{perFrequency}} starting {{renewalDate}}. You can cancel any time before this date.","payment_entry_page.subscription_terms_info":"By subscribing, you agree to allow {{appName}} to charge you according to their terms until you cancel.","payment_entry_page.otp_terms_info":"By purchasing, you agree to allow {{appName}} to charge you according to their terms.","payment_entry_page.subscription_info":"Subscription renews automatically. Cancel anytime.","payment_entry_page.button_pay":"Pay now","payment_entry_page.button_start_trial":"Start trial","payment_entry_page.button_with_price":"Pay {{formattedPrice}}","payment_entry_page.button_payment_method":"Pay {{formattedPrice}} with {{paymentMethod}}","payment_entry_page.express_checkout_divider":"OR PAY BY CARD","success_page.purchase_successful":"Payment complete","success_page.button_close":"Continue","error_page.close_button_title":"Go to {{appName}}","error_page.if_error_persists":"If it persists, please contact ","error_page.trouble_accessing":"If you're having trouble accessing your purchase, reach out to support on ","error_page.error_title_already_subscribed":"You already subscribed to {{productTitle}}","error_page.error_title_already_purchased":"You already purchased {{productTitle}}","error_page.error_title_other_errors":"Something went wrong","error_page.error_message_already_subscribed":"You can't subscribe to this product again.","error_page.error_message_already_purchased":"You can't purchase this product again.","error_page.error_title_stripe_tax_not_active":"Stripe Tax not active","error_page.error_title_stripe_invalid_tax_origin_address":"Invalid tax origin address","error_page.error_title_stripe_missing_required_permission":"Missing Stripe permission","error_page.error_message_missing_email_error":"Email is required to complete the purchase.","error_page.error_message_invalid_email_error":"The email address {{email}} couldn't be verified. Please provide a valid email address.","error_page.error_message_network_error":"Network error. Please check your internet connection.","error_page.error_message_error_charging_payment":"Payment failed.","error_page.error_message_error_setting_up_purchase":"Purchase not started due to an error (error code: {{errorCode}}).","error_page.error_message_invalid_tax_location":"We couldn't verify your billing address. Please double-check that the postal code and country are correct.","error_page.error_message_unknown_error":"An unknown error occurred (error code: {{errorCode}}).","error_page.error_message_stripe_tax_not_active":"The purchase failed because Stripe Tax isn’t enabled. In production, purchases will work without taxes applied.","error_page.error_message_stripe_invalid_tax_origin_address":"The purchase failed because the tax origin address is invalid. In production, purchases will work without taxes applied.","error_page.error_message_stripe_missing_required_permission":"The purchase failed because the Stripe app lacks a required permission. In production, purchases will work without taxes applied.","error_page.error_only_in_sandbox":"This message appears only in sandbox.","error_page.button_try_again":"Try again","error_page.button_close":"Close","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% off","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","pricing_dropdown.show_details":"Show details","pricing_dropdown.hide_details":"Hide details","pricing_table.trial_ends":"After trial ends, on {{formattedTrialEndDate}}","pricing_table.total_excluding_tax":"Total excluding tax","pricing_table.total_due_today":"Total due today","pricing_table.tax":"Tax","pricing_table.enter_billing_address_to_calculate":"Enter billing address to calculate","pricing_table.enter_postal_code_to_calculate":"Enter zip code to calculate","pricing_table.enter_state_or_postal_code_to_calculate":"Enter state or postal code to calculate","navbar_header.details":"Details","navbar_header.back_button":"Back","price_update.title":"Price update","price_update.base_message":"The total price was updated with tax based on your billing address. Please review and try again. Your card will only be charged once.","price_update.trial_message":"The subscription price was updated to include tax based on your billing address. Free trial still applies. Review and try again.","apple_pay.free_trial":"Free Trial"},pFA={"periods.week":"{{amount}} semana","periods.month":"{{amount}} mes","periods.year":"{{amount}} año","periods.day":"{{amount}} día","periods.weekShort":"{{amount}} sem","periods.monthShort":"{{amount}}mes","periods.yearShort":"{{amount}}año","periods.dayShort":"{{amount}}d","periods.lifetime":"de por vida","periods.weekPlural":"{{amount}} semanas","periods.monthPlural":"{{amount}} meses","periods.yearPlural":"{{amount}} años","periods.dayPlural":"{{amount}} días","periods.weekFrequency":"semanal","periods.monthFrequency":"mensual","periods.yearFrequency":"anual","periods.dayFrequency":"diaria","periods.perWeekFrequency":"por semana","periods.perMonthFrequency":"por mes","periods.perYearFrequency":"por año","periods.perDayFrequency":"por día","periods.unknownFrequency":"desconocida","periods.weekFrequencyPlural":"cada {{amount}} semanas","periods.monthFrequencyPlural":"cada {{amount}} meses","periods.yearFrequencyPlural":"cada {{amount}} años","periods.dayFrequencyPlural":"cada {{amount}} días","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} prueba gratuita","product_info.price_after_free_trial":"Después de que termine el periodo de prueba, el {{renewalDate}}","product_info.renewal_frequency":"Se renueva {{frequency}}","product_info.continues_until_cancelled":"Continua hasta que se cancele","product_info.cancel_anytime":"Cancelar en cualquier momento","payment_entry_page.payment_step_title":"Pago seguro mediante RevenueCat","payment_entry_page.button_pay":"Pagar ahora","payment_entry_page.button_start_trial":"Comenzar prueba","success_page.purchase_successful":"Pago completado","success_page.button_close":"Continuar","error_page.if_error_persists":"Si el error persiste, contacta con ","error_page.error_title_already_subscribed":"Ya te has suscrito a {{productTitle}}","error_page.error_title_already_purchased":"Ya has comprado {{productTitle}}","error_page.error_title_other_errors":"Algo salió mal","error_page.error_message_already_subscribed":"No puedes suscribirte a este producto de nuevo.","error_page.error_message_already_purchased":"No puedes comprar este producto de nuevo.","error_page.error_message_missing_email_error":"Se requiere un correo electrónico para completar la compra.","error_page.error_message_network_error":"Error de red. Por favor, comprueba tu conexión a internet.","error_page.error_message_error_charging_payment":"Pago fallido.","error_page.error_message_error_setting_up_purchase":"No se pudo iniciar la compra debido a un error (código de error: {{errorCode}}).","error_page.error_message_invalid_tax_location":"No pudimos verificar tu dirección de facturación. Por favor, verifica que el código postal y el país sean correctos.","error_page.error_message_unknown_error":"Ocurrió un error desconocido (código de error: {{errorCode}}).","error_page.button_try_again":"Intentar de nuevo","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% de descuento","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Total a pagar hoy","product_info.subscribe_to":"Suscribirse a","navbar_header.details":"Detalles","navbar_header.back_button":"Atrás","pricing_dropdown.show_details":"Mostrar detalles","pricing_dropdown.hide_details":"Ocultar detalles","pricing_table.tax":"Impuestos","pricing_table.trial_ends":"Después de que finalice la prueba, el {{formattedTrialEndDate}}","pricing_table.total_due_today":"Total a pagar hoy","pricing_table.total_excluding_tax":"Total sin impuestos","pricing_table.enter_billing_address_to_calculate":"Introduce la dirección de facturación para calcular","pricing_table.enter_state_or_postal_code_to_calculate":"Introduce el estado o el código postal para calcular","pricing_table.enter_postal_code_to_calculate":"Introduce el código postal para calcular","error_page.error_message_invalid_email_error":"La dirección de correo electrónico {{email}} no se pudo verificar. Por favor, proporciona una dirección de correo electrónico válida.","payment_entry_page.button_payment_method":"Pagar {{formattedPrice}} con {{paymentMethod}}","payment_entry_page.button_with_price":"Pagar {{formattedPrice}}","price_update.title":"Actualización de precio","price_update.base_message":"El precio total se actualizó con impuestos según su dirección de facturación. Revise e intente nuevamente. Solo se efectuará un cobro en su tarjeta.","price_update.trial_message":"El precio de la suscripción se actualizó para incluir impuestos según su dirección de facturación. La prueba gratuita sigue aplicándose. Revise e intente nuevamente.","payment_entry_page.express_checkout_divider":"O PAGA CON TARJETA","error_page.trouble_accessing":"Si tiene problemas para acceder a su compra, póngase en contacto con el servicio de asistencia en ","error_page.close_button_title":"Ir a {{appName}}","error_page.error_title_stripe_missing_required_permission":"Falta permiso de Stripe","error_page.button_close":"Cerrar","error_page.error_message_stripe_invalid_tax_origin_address":"La compra falló porque la dirección de origen fiscal no es válida. En producción, las compras funcionarán sin impuestos aplicados.","error_page.error_message_stripe_tax_not_active":"La compra falló porque Stripe Tax no está habilitado. En producción, las compras funcionarán sin impuestos aplicados.","error_page.error_only_in_sandbox":"Este mensaje aparece solo en el entorno de pruebas.","error_page.error_message_stripe_missing_required_permission":"La compra falló porque la aplicación Stripe carece de un permiso necesario. En producción, las compras funcionarán sin impuestos aplicados.","error_page.error_title_stripe_tax_not_active":"Stripe Tax no está activo","error_page.error_title_stripe_invalid_tax_origin_address":"Dirección de origen fiscal no válida","apple_pay.free_trial":"Prueba gratuita","product_info.price_after_intro_price":"Después de {{introPriceDuration}}, el {{renewalDate}}","product_info.after_trial":"después del período de prueba","product_info.after":"después de","product_info.intro_price_phase_after_trial":"Luego, {{introPriceDuration}} por {{introPrice}}","product_info.intro_price_phase":"Primero, {{introPriceDuration}} por {{introPrice}}","product_info.intro_price_phase_paid_once":"pago único","payment_entry_page.trial_subscription_terms_info":"Una vez finalizado el período de prueba, se te cobrarán {{price}} {{perFrequency}} a partir del {{renewalDate}}. Puedes cancelar en cualquier momento antes de esta fecha.","payment_entry_page.subscription_info":"La suscripción se renueva automáticamente. Cancela en cualquier momento.","payment_entry_page.otp_terms_info":"Al comprar, aceptas que {{appName}} te cobre de acuerdo con sus términos.","payment_entry_page.subscription_terms_info":"Al suscribirte, aceptas que {{appName}} te cobre de acuerdo con sus términos hasta que canceles."},fFA={"periods.week":"{{amount}} settimana","periods.month":"{{amount}} mese","periods.year":"{{amount}} anno","periods.day":"{{amount}} giorno","periods.weekShort":"{{amount}}sett","periods.monthShort":"{{amount}}mese","periods.yearShort":"{{amount}}anno","periods.dayShort":"{{amount}}g","periods.lifetime":"a vita","periods.weekPlural":"{{amount}} settimane","periods.monthPlural":"{{amount}} mesi","periods.yearPlural":"{{amount}} anni","periods.dayPlural":"{{amount}} giorni","periods.weekFrequency":"settimanale","periods.monthFrequency":"mensile","periods.yearFrequency":"annuale","periods.dayFrequency":"giornaliero","periods.perWeekFrequency":"a settimana","periods.perMonthFrequency":"al mese","periods.perYearFrequency":"all'anno","periods.perDayFrequency":"al giorno","periods.unknownFrequency":"sconosciuto","periods.weekFrequencyPlural":"ogni {{amount}} settimane","periods.monthFrequencyPlural":"ogni {{amount}} mesi","periods.yearFrequencyPlural":"ogni {{amount}} anni","periods.dayFrequencyPlural":"ogni {{amount}} giorni","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} prova gratuita","product_info.price_after_free_trial":"Dopo la fine della prova, il {{renewalDate}}","product_info.renewal_frequency":"Si rinnova {{frequency}}","product_info.continues_until_cancelled":"Continua fino a disdetta","product_info.cancel_anytime":"Disdici in qualsiasi momento","payment_entry_page.payment_step_title":"Pagamento sicuro tramite RevenueCat","payment_entry_page.button_pay":"Paga ora","payment_entry_page.button_start_trial":"Inizia la prova","success_page.purchase_successful":"Pagamento completato","success_page.button_close":"Continua","error_page.if_error_persists":"Se l'errore persiste, contatta ","error_page.error_title_already_subscribed":"Hai già un abbonamento a {{productTitle}}","error_page.error_title_already_purchased":"Hai già acquistato {{productTitle}}","error_page.error_title_other_errors":"Qualcosa è andato storto","error_page.error_message_already_subscribed":"Non puoi abbonarti di nuovo a questo prodotto.","error_page.error_message_already_purchased":"Non puoi acquistare di nuovo questo prodotto.","error_page.error_message_missing_email_error":"L'email è necessaria per completare l'acquisto.","error_page.error_message_network_error":"Errore di rete. Verifica la connessione internet.","error_page.error_message_error_charging_payment":"Pagamento fallito.","error_page.error_message_error_setting_up_purchase":"Acquisto non avviato a causa di un errore (codice errore: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Non siamo riusciti a verificare il tuo indirizzo di fatturazione. Per favore, controlla che il codice postale e il paese siano corretti.","error_page.error_message_unknown_error":"Si è verificato un errore sconosciuto (codice errore: {{errorCode}}).","error_page.button_try_again":"Riprova","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% di sconto","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Totale dovuto oggi","product_info.subscribe_to":"Abbonati a","navbar_header.details":"Dettagli","navbar_header.back_button":"Indietro","pricing_dropdown.show_details":"Mostra dettagli","pricing_dropdown.hide_details":"Nascondi dettagli","pricing_table.tax":"Tasse","pricing_table.trial_ends":"Al termine del periodo di prova, il {{formattedTrialEndDate}}","pricing_table.total_due_today":"Totale dovuto oggi","pricing_table.total_excluding_tax":"Totale tasse escluse","pricing_table.enter_billing_address_to_calculate":"Inserisci l'indirizzo di fatturazione per calcolare","pricing_table.enter_state_or_postal_code_to_calculate":"Inserisci la regione o il codice postale per calcolare","pricing_table.enter_postal_code_to_calculate":"Inserisci il codice postale per calcolare","error_page.error_message_invalid_email_error":"L'indirizzo email {{email}} non può essere verificato. Si prega di fornire un indirizzo email valido.","payment_entry_page.button_payment_method":"Paga {{formattedPrice}} con {{paymentMethod}}","payment_entry_page.button_with_price":"Paga {{formattedPrice}}","price_update.title":"Aggiornamento prezzo","price_update.base_message":"Il prezzo totale è stato aggiornato con le tasse in base al tuo indirizzo di fatturazione. Rivedi e riprova. L'addebito sulla tua carta avverrà solo una volta.","price_update.trial_message":"Il prezzo dell'abbonamento è stato aggiornato per includere le tasse in base al tuo indirizzo di fatturazione. La prova gratuita è ancora valida. Controlla e riprova.","payment_entry_page.express_checkout_divider":"OPPURE PAGA CON CARTA","error_page.trouble_accessing":"Se hai problemi ad accedere al tuo acquisto, contatta l'assistenza all'indirizzo ","error_page.close_button_title":"Vai a {{appName}}","error_page.error_title_stripe_missing_required_permission":"Autorizzazione Stripe mancante","error_page.button_close":"Chiudi","error_page.error_message_stripe_invalid_tax_origin_address":"L'acquisto non è andato a buon fine perché l'indirizzo di origine fiscale non è valido. In produzione, gli acquisti verranno effettuati senza l'applicazione delle imposte e questo errore non sarà visibile.","error_page.error_message_stripe_tax_not_active":"L'acquisto non è andato a buon fine perché Stripe Tax non è abilitato. In produzione, gli acquisti verranno effettuati senza l'applicazione delle imposte e questo errore non sarà visibile.","error_page.error_only_in_sandbox":"Questo messaggio viene visualizzato solo in sandbox.","error_page.error_message_stripe_missing_required_permission":"L'acquisto non è andato a buon fine perché l'app Stripe non dispone dell'autorizzazione necessaria. In produzione, gli acquisti verranno effettuati senza l'applicazione delle imposte e questo errore non sarà visibile.","error_page.error_title_stripe_tax_not_active":"Stripe Tax non attivo","error_page.error_title_stripe_invalid_tax_origin_address":"Indirizzo di origine fiscale non valido","apple_pay.free_trial":"Prova gratuita","product_info.price_after_intro_price":"Dopo {{introPriceDuration}}, il {{renewalDate}}","product_info.after_trial":"dopo il periodo di prova","product_info.after":"dopo","product_info.intro_price_phase_after_trial":"Poi {{introPriceDuration}} a {{introPrice}}","product_info.intro_price_phase":"Prima {{introPriceDuration}} a {{introPrice}}","product_info.intro_price_phase_paid_once":"pagato una volta","payment_entry_page.trial_subscription_terms_info":"Al termine del periodo di prova, ti verranno addebitati {{price}} {{perFrequency}} a partire dal {{renewalDate}}. Puoi annullare in qualsiasi momento prima di questa data.","payment_entry_page.subscription_info":"L'abbonamento si rinnova automaticamente. Annulla in qualsiasi momento.","payment_entry_page.otp_terms_info":"Acquistando, accetti che {{appName}} ti addebiti l'importo in base ai suoi termini.","payment_entry_page.subscription_terms_info":"Abbonandoti, accetti che {{appName}} ti addebiti l'importo secondo i suoi termini fino all'annullamento."},yFA={"periods.week":"{{amount}} أسبوع","periods.month":"{{amount}} شهر","periods.year":"{{amount}} سنة","periods.day":"{{amount}} يوم","periods.weekShort":"{{amount}}أسبوع","periods.monthShort":"{{amount}}شهر","periods.yearShort":"{{amount}}سنة","periods.dayShort":"{{amount}}يوم","periods.lifetime":"مدى الحياة","periods.weekPlural":"{{amount}} أسابيع","periods.monthPlural":"{{amount}} أشهر","periods.yearPlural":"{{amount}} سنوات","periods.dayPlural":"{{amount}} أيام","periods.weekFrequency":"أسبوعيًا","periods.monthFrequency":"شهريًا","periods.yearFrequency":"سنويًا","periods.dayFrequency":"يوميًا","periods.perWeekFrequency":"في الأسبوع","periods.perMonthFrequency":"في الشهر","periods.perYearFrequency":"في السنة","periods.perDayFrequency":"في اليوم","periods.unknownFrequency":"غير معروف","periods.weekFrequencyPlural":"كل {{amount}} أسابيع","periods.monthFrequencyPlural":"كل {{amount}} أشهر","periods.yearFrequencyPlural":"كل {{amount}} سنوات","periods.dayFrequencyPlural":"كل {{amount}} أيام","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} تجربة مجانية","product_info.price_after_free_trial":"بعد انتهاء التجربة، في {{renewalDate}}","product_info.renewal_frequency":"يتم التجديد {{frequency}}","product_info.continues_until_cancelled":"يستمر حتى يتم إلغاؤه","product_info.cancel_anytime":"يمكن الإلغاء في أي وقت","payment_entry_page.payment_step_title":"الدفع الآمن عبر RevenueCat","payment_entry_page.button_pay":"ادفع الآن","payment_entry_page.button_start_trial":"ابدأ التجربة","success_page.purchase_successful":"تم الدفع بنجاح","success_page.button_close":"متابعة","error_page.if_error_persists":"إذا استمرت المشكلة، يرجى الاتصال بـ ","error_page.error_title_already_subscribed":"أنت مشترك بالفعل في {{productTitle}}","error_page.error_title_already_purchased":"لقد اشتريت {{productTitle}} بالفعل","error_page.error_title_other_errors":"حدث خطأ ما","error_page.error_message_already_subscribed":"لا يمكنك الاشتراك في هذا المنتج مرة أخرى.","error_page.error_message_already_purchased":"لا يمكنك شراء هذا المنتج مرة أخرى.","error_page.error_message_missing_email_error":"يُطلب البريد الإلكتروني لإتمام عملية الشراء.","error_page.error_message_network_error":"خطأ في الشبكة. يرجى التحقق من اتصال الإنترنت.","error_page.error_message_error_charging_payment":"فشل الدفع.","error_page.error_message_error_setting_up_purchase":"لم تبدأ عملية الشراء بسبب خطأ (رمز الخطأ: {{errorCode}}).","error_page.error_message_invalid_tax_location":"لم نتمكن من التحقق من عنوان الفوترة الخاص بك. يرجى التحقق مرة أخرى من الرمز البريدي والبلد للتأكد من صحتهما.","error_page.error_message_unknown_error":"حدث خطأ غير معروف (رمز الخطأ: {{errorCode}}).","error_page.button_try_again":"حاول مرة أخرى","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% خصم","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"إجمالي المبلغ المستحق اليوم","product_info.subscribe_to":"اشترك في","navbar_header.details":"تفاصيل","navbar_header.back_button":"عودة","pricing_dropdown.show_details":"إظهار التفاصيل","pricing_dropdown.hide_details":"إخفاء التفاصيل","pricing_table.tax":"الضريبة","pricing_table.trial_ends":"بعد انتهاء الفترة التجريبية، في {{formattedTrialEndDate}}","pricing_table.total_due_today":"الإجمالي المستحق اليوم","pricing_table.total_excluding_tax":"الإجمالي باستثناء الضريبة","pricing_table.enter_billing_address_to_calculate":"أدخل عنوان إرسال الفواتير لحسابها","pricing_table.enter_state_or_postal_code_to_calculate":"أدخل الولاية أو الرمز البريدي للحساب","pricing_table.enter_postal_code_to_calculate":"أدخل الرمز البريدي للحساب","error_page.error_message_invalid_email_error":"تعذر التحقق من عنوان البريد الإلكتروني {{email}}. يرجى تقديم عنوان بريد إلكتروني صالح.","payment_entry_page.button_payment_method":"ادفع {{formattedPrice}} باستخدام {{paymentMethod}}","payment_entry_page.button_with_price":"ادفع {{formattedPrice}}","price_update.title":"تحديث السعر","price_update.base_message":"تم تحديث السعر الإجمالي مع الضريبة بناءً على عنوان إرسال الفواتير الخاص بك. يرجى المراجعة والمحاولة مرة أخرى. لن يتم تحصيل رسوم من بطاقتك إلا مرة واحدة.","price_update.trial_message":"تم تحديث سعر الاشتراك ليشمل الضرائب بناءً على عنوان الفوترة الخاص بك. فترة التجربة المجانية لا تزال سارية. يرجى التحقق والمحاولة مرة أخرى.","payment_entry_page.express_checkout_divider":"أو ادفع بواسطة البطاقة","error_page.trouble_accessing":"إذا كنت تواجه مشكلة في الوصول إلى عملية الشراء، فتواصل مع الدعم على ","error_page.close_button_title":"اذهب إلى {{appName}}","error_page.error_title_stripe_missing_required_permission":"إذن Stripe مفقود","error_page.button_close":"إغلاق","error_page.error_message_stripe_invalid_tax_origin_address":"فشلت عملية الشراء لأن عنوان المنشأ الضريبي غير صالح. في مرحلة الإنتاج، ستعمل عمليات الشراء بدون تطبيق الضرائب.","error_page.error_message_stripe_tax_not_active":"فشلت عملية الشراء لأن ضريبة Stripe غير مفعلة. في مرحلة الإنتاج، ستعمل عمليات الشراء بدون تطبيق الضرائب.","error_page.error_only_in_sandbox":"تظهر هذه الرسالة فقط في البيئة التجريبية.","error_page.error_message_stripe_missing_required_permission":"فشلت عملية الشراء لأن تطبيق Stripe يفتقر إلى إذن مطلوب. في مرحلة الإنتاج، ستعمل عمليات الشراء بدون تطبيق الضرائب.","error_page.error_title_stripe_tax_not_active":"ضريبة Stripe غير نشطة","error_page.error_title_stripe_invalid_tax_origin_address":"عنوان منشأ ضريبي غير صالح","apple_pay.free_trial":"تجربة مجانية","product_info.price_after_intro_price":"بعد {{introPriceDuration}}، في {{renewalDate}}","product_info.after_trial":"بعد الفترة التجريبية","product_info.after":"بعد","product_info.intro_price_phase_after_trial":"ثم {{introPriceDuration}} مقابل {{introPrice}}","product_info.intro_price_phase":"أولاً {{introPriceDuration}} مقابل {{introPrice}}","product_info.intro_price_phase_paid_once":"تدفع مرة واحدة","payment_entry_page.trial_subscription_terms_info":"بعد انتهاء الفترة التجريبية، سيتم محاسبتك بمبلغ {{price}} {{perFrequency}} بدءًا من {{renewalDate}}. يمكنك الإلغاء في أي وقت قبل هذا التاريخ.","payment_entry_page.subscription_info":"يتم تجديد الاشتراك تلقائيًا. يمكنك الإلغاء في أي وقت.","payment_entry_page.otp_terms_info":"بالشراء، أنت توافق على السماح لتطبيق {{appName}} بتحصيل الرسوم منك وفقًا لشروطه.","payment_entry_page.subscription_terms_info":"بالاشتراك، فإنك توافق على السماح لـ {{appName}} بتحصيل رسوم منك وفقًا لشروطها حتى تقوم بالإلغاء."},DFA={"periods.week":"{{amount}} setmana","periods.month":"{{amount}} mes","periods.year":"{{amount}} any","periods.day":"{{amount}} dia","periods.weekShort":"{{amount}}set","periods.monthShort":"{{amount}}mes","periods.yearShort":"{{amount}}any","periods.dayShort":"{{amount}}d","periods.lifetime":"de per vida","periods.weekPlural":"{{amount}} setmanes","periods.monthPlural":"{{amount}} mesos","periods.yearPlural":"{{amount}} anys","periods.dayPlural":"{{amount}} dies","periods.weekFrequency":"setmanal","periods.monthFrequency":"mensual","periods.yearFrequency":"anual","periods.dayFrequency":"diari","periods.perWeekFrequency":"per setmana","periods.perMonthFrequency":"per mes","periods.perYearFrequency":"per any","periods.perDayFrequency":"per dia","periods.unknownFrequency":"desconeguda","periods.weekFrequencyPlural":"cada {{amount}} setmanes","periods.monthFrequencyPlural":"cada {{amount}} mesos","periods.yearFrequencyPlural":"cada {{amount}} anys","periods.dayFrequencyPlural":"cada {{amount}} dies","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} de prova gratuïta","product_info.price_after_free_trial":"Després del període de prova, el {{renewalDate}}","product_info.renewal_frequency":"Es renova {{frequency}}","product_info.continues_until_cancelled":"Continua fins que es cancel·li","product_info.cancel_anytime":"Cancel·la en qualsevol moment","payment_entry_page.payment_step_title":"Pagament segur amb RevenueCat","payment_entry_page.button_pay":"Paga ara","payment_entry_page.button_start_trial":"Comença la prova","success_page.purchase_successful":"Pagament complet","success_page.button_close":"Continua","error_page.if_error_persists":"Si l'error persisteix, contacta amb ","error_page.error_title_already_subscribed":"Ja us heu subscrit a {{productTitle}}","error_page.error_title_already_purchased":"Ja heu comprat {{productTitle}}","error_page.error_title_other_errors":"Alguna cosa ha anat malament","error_page.error_message_already_subscribed":"No us podeu subscriure a aquest producte de nou.","error_page.error_message_already_purchased":"No podeu comprar aquest producte de nou.","error_page.error_message_missing_email_error":"Es necessita un correu electrònic per completar la compra.","error_page.error_message_network_error":"Error de xarxa. Comprova la teva connexió a internet.","error_page.error_message_error_charging_payment":"El pagament ha fallat.","error_page.error_message_error_setting_up_purchase":"No s'ha iniciat la compra a causa d'un error (codi d'error: {{errorCode}}).","error_page.error_message_invalid_tax_location":"No hem pogut verificar la vostra adreça de facturació. Si us plau, verifiqueu de nou el codi postal i el país per assegurar-vos que són correctes.","error_page.error_message_unknown_error":"S'ha produït un error desconegut (codi d'error: {{errorCode}}).","error_page.button_try_again":"Torna a intentar-ho","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% de descompte","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Total a pagar avui","product_info.subscribe_to":"Subscriu-te a","navbar_header.details":"Detalls","navbar_header.back_button":"Enrere","pricing_dropdown.show_details":"Mostra detalls","pricing_dropdown.hide_details":"Amaga detalls","pricing_table.tax":"Impostos","pricing_table.trial_ends":"Després que finalitzi la prova, el {{formattedTrialEndDate}}","pricing_table.total_due_today":"Total a pagar avui","pricing_table.total_excluding_tax":"Total sense impostos","pricing_table.enter_billing_address_to_calculate":"Introduïu l'adreça de facturació per calcular","pricing_table.enter_state_or_postal_code_to_calculate":"Introduïu la província o el codi postal per calcular","pricing_table.enter_postal_code_to_calculate":"Introduïu el codi postal per calcular","error_page.error_message_invalid_email_error":"No s'ha pogut verificar l'adreça de correu electrònic {{email}}. Si us plau, proporcioneu una adreça de correu electrònic vàlida.","payment_entry_page.button_payment_method":"Paga {{formattedPrice}} amb {{paymentMethod}}","payment_entry_page.button_with_price":"Paga {{formattedPrice}}","price_update.title":"Actualització de preu","price_update.base_message":"El preu total s'ha actualitzat amb els impostos segons la vostra adreça de facturació. Reviseu-ho i torneu-ho a provar. Només es carregarà la vostra targeta una vegada.","price_update.trial_message":"El preu de la subscripció s'ha actualitzat per incloure els impostos segons la seva adreça de facturació. El període de prova gratuït segueix vigent. Si us plau, comprovi-ho i torni-ho a provar.","payment_entry_page.express_checkout_divider":"O PAGUEU AMB TARGETA","error_page.trouble_accessing":"Si teniu problemes per accedir a la vostra compra, poseu-vos en contacte amb el servei d'assistència a ","error_page.close_button_title":"Vés a {{appName}}","error_page.error_title_stripe_missing_required_permission":"Falta el permís de Stripe","error_page.button_close":"Tanca","error_page.error_message_stripe_invalid_tax_origin_address":"La compra ha fallat perquè l'adreça d'origen fiscal no és vàlida. En producció, les compres funcionaran sense impostos aplicats.","error_page.error_message_stripe_tax_not_active":"La compra ha fallat perquè Stripe Tax no està activat. En producció, les compres funcionaran sense impostos aplicats.","error_page.error_only_in_sandbox":"Aquest missatge apareix només a l'entorn de proves.","error_page.error_message_stripe_missing_required_permission":"La compra ha fallat perquè l'aplicació Stripe no té un permís necessari. En producció, les compres funcionaran sense impostos aplicats.","error_page.error_title_stripe_tax_not_active":"Stripe Tax no està actiu","error_page.error_title_stripe_invalid_tax_origin_address":"Adreça d'origen fiscal no vàlida","apple_pay.free_trial":"Prova gratuïta","product_info.price_after_intro_price":"Després de {{introPriceDuration}}, el {{renewalDate}}","product_info.after_trial":"després del període de prova","product_info.after":"després de","product_info.intro_price_phase_after_trial":"Després {{introPriceDuration}} per {{introPrice}}","product_info.intro_price_phase":"Primer {{introPriceDuration}} per {{introPrice}}","product_info.intro_price_phase_paid_once":"pagat un cop","payment_entry_page.trial_subscription_terms_info":"Un cop finalitzat el període de prova, se us cobrarà {{price}} {{perFrequency}} a partir del {{renewalDate}}. Podeu cancel·lar-ho en qualsevol moment abans d'aquesta data.","payment_entry_page.subscription_info":"La subscripció es renova automàticament. Cancel·leu-la quan vulgueu.","payment_entry_page.otp_terms_info":"En comprar, accepteu que {{appName}} us cobri d'acord amb les seves condicions.","payment_entry_page.subscription_terms_info":"En subscriure-us, accepteu que {{appName}} us cobri d'acord amb les seves condicions fins que ho cancel·leu."},mFA={"periods.week":"{{amount}} 周","periods.month":"{{amount}} 月","periods.year":"{{amount}} 年","periods.day":"{{amount}} 天","periods.weekShort":"{{amount}}周","periods.monthShort":"{{amount}}月","periods.yearShort":"{{amount}}年","periods.dayShort":"{{amount}}天","periods.lifetime":"终身","periods.weekPlural":"{{amount}} 周","periods.monthPlural":"{{amount}} 个月","periods.yearPlural":"{{amount}} 年","periods.dayPlural":"{{amount}} 天","periods.weekFrequency":"每周","periods.monthFrequency":"每月","periods.yearFrequency":"每年","periods.dayFrequency":"每天","periods.perWeekFrequency":"每周","periods.perMonthFrequency":"每月","periods.perYearFrequency":"每年","periods.perDayFrequency":"每天","periods.unknownFrequency":"未知","periods.weekFrequencyPlural":"每 {{amount}} 周","periods.monthFrequencyPlural":"每 {{amount}} 个月","periods.yearFrequencyPlural":"每 {{amount}} 年","periods.dayFrequencyPlural":"每 {{amount}} 天","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} 天免费试用","product_info.price_after_free_trial":"试用期结束后，于 {{renewalDate}}","product_info.renewal_frequency":"续订 {{frequency}}","product_info.continues_until_cancelled":"持续到取消","product_info.cancel_anytime":"随时取消","payment_entry_page.payment_step_title":"RevenueCat 安全结账","payment_entry_page.button_pay":"立即支付","payment_entry_page.button_start_trial":"开始试用","success_page.purchase_successful":"支付完成","success_page.button_close":"继续","error_page.if_error_persists":"如果错误仍然存在，请联系 ","error_page.error_title_already_subscribed":"您已订阅 {{productTitle}}","error_page.error_title_already_purchased":"您已购买 {{productTitle}}","error_page.error_title_other_errors":"出现错误","error_page.error_message_already_subscribed":"您不能再次订阅此产品。","error_page.error_message_already_purchased":"您不能再次购买此产品。","error_page.error_message_missing_email_error":"完成购买需要邮箱地址。","error_page.error_message_network_error":"网络错误。请检查您的互联网连接。","error_page.error_message_error_charging_payment":"支付失败。","error_page.error_message_error_setting_up_purchase":"由于错误，购买未启动（错误代码：{{errorCode}}）。","error_page.error_message_invalid_tax_location":"我们无法验证您的账单地址。请仔细检查邮政编码和国家是否正确。","error_page.error_message_unknown_error":"发生未知错误（错误代码：{{errorCode}}）。","error_page.button_try_again":"重试","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% 折扣","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"今天应付总额","product_info.subscribe_to":"订阅","navbar_header.details":"详情","navbar_header.back_button":"返回","pricing_dropdown.show_details":"显示详情","pricing_dropdown.hide_details":"隐藏详情","pricing_table.tax":"税","pricing_table.trial_ends":"试用期结束后，于{{formattedTrialEndDate}}","pricing_table.total_due_today":"今日应付总额","pricing_table.total_excluding_tax":"总计（不含税）","pricing_table.enter_billing_address_to_calculate":"输入账单地址以计算","pricing_table.enter_state_or_postal_code_to_calculate":"输入州或邮政编码以计算","pricing_table.enter_postal_code_to_calculate":"输入邮政编码以计算","error_page.error_message_invalid_email_error":"无法验证电子邮件地址{{email}}。请提供有效的电子邮件地址。","payment_entry_page.button_payment_method":"使用{{paymentMethod}}支付{{formattedPrice}}","payment_entry_page.button_with_price":"支付{{formattedPrice}}","price_update.title":"价格更新","price_update.base_message":"总价已根据您的账单地址更新了税费。请查看并重试。您的银行卡只会扣款一次。","price_update.trial_message":"根据您的账单地址，订阅价格已更新为含税价格。免费试用仍然有效。请查看并重试。","payment_entry_page.express_checkout_divider":"或使用银行卡支付","error_page.trouble_accessing":"如果您在访问购买项目时遇到问题，请通过以下方式联系支持：","error_page.close_button_title":"前往{{appName}}","error_page.error_title_stripe_missing_required_permission":"缺少Stripe权限","error_page.button_close":"关闭","error_page.error_message_stripe_invalid_tax_origin_address":"购买失败，因为税务起始地址无效。在生产环境中，购买将在不应用税款的情况下进行。","error_page.error_message_stripe_tax_not_active":"购买失败，因为Stripe Tax未启用。在生产环境中，购买将在不应用税款的情况下进行。","error_page.error_only_in_sandbox":"此消息仅在沙盒中显示。","error_page.error_message_stripe_missing_required_permission":"购买失败，因为Stripe应用程序缺少必需的权限。在生产环境中，购买将在不应用税款的情况下进行。","error_page.error_title_stripe_tax_not_active":"Stripe Tax未激活","error_page.error_title_stripe_invalid_tax_origin_address":"税务起始地址无效","apple_pay.free_trial":"免费试用","product_info.price_after_intro_price":"在{{introPriceDuration}}之后，于{{renewalDate}}开始","product_info.after_trial":"试用后","product_info.after":"之后","product_info.intro_price_phase_after_trial":"然后{{introPriceDuration}}，价格为{{introPrice}}","product_info.intro_price_phase":"首先{{introPriceDuration}}，价格为{{introPrice}}","product_info.intro_price_phase_paid_once":"一次性支付","payment_entry_page.trial_subscription_terms_info":"试用期结束后，您将被收取 {{price}} {{perFrequency}}，从 {{renewalDate}} 开始。您可以在此日期之前的任何时间取消。","payment_entry_page.subscription_info":"订阅自动续订。随时取消。","payment_entry_page.otp_terms_info":"购买即表示您同意允许{{appName}}根据其条款向您收费。","payment_entry_page.subscription_terms_info":"订阅即表示您同意允许 {{appName}} 按照其条款向您收费，直到您取消订阅。"},SFA={"periods.week":"{{amount}} 週","periods.month":"{{amount}} 個月","periods.year":"{{amount}} 年","periods.day":"{{amount}} 天","periods.weekShort":"{{amount}}週","periods.monthShort":"{{amount}}月","periods.yearShort":"{{amount}}年","periods.dayShort":"{{amount}}天","periods.lifetime":"終身","periods.weekPlural":"{{amount}} 週","periods.monthPlural":"{{amount}} 個月","periods.yearPlural":"{{amount}} 年","periods.dayPlural":"{{amount}} 天","periods.weekFrequency":"每週","periods.monthFrequency":"每月","periods.yearFrequency":"每年","periods.dayFrequency":"每天","periods.perWeekFrequency":"每週","periods.perMonthFrequency":"每月","periods.perYearFrequency":"每年","periods.perDayFrequency":"每天","periods.unknownFrequency":"未知","periods.weekFrequencyPlural":"每 {{amount}} 週","periods.monthFrequencyPlural":"每 {{amount}} 個月","periods.yearFrequencyPlural":"每 {{amount}} 年","periods.dayFrequencyPlural":"每 {{amount}} 天","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} 天免費試用","product_info.price_after_free_trial":"試用期結束後，於 {{renewalDate}}","product_info.renewal_frequency":"每 {{frequency}} 續約","product_info.continues_until_cancelled":"持續到取消","product_info.cancel_anytime":"隨時取消","payment_entry_page.payment_step_title":"RevenueCat 安全結帳","payment_entry_page.button_pay":"立即付款","payment_entry_page.button_start_trial":"開始試用","success_page.purchase_successful":"付款完成","success_page.button_close":"繼續","error_page.if_error_persists":"如果錯誤持續存在，請聯絡 ","error_page.error_title_already_subscribed":"您已經訂閱 {{productTitle}}","error_page.error_title_already_purchased":"您已經購買 {{productTitle}}","error_page.error_title_other_errors":"發生錯誤","error_page.error_message_already_subscribed":"您無法再次訂閱此產品。","error_page.error_message_already_purchased":"您無法再次購買此產品。","error_page.error_message_missing_email_error":"完成購買需要電子郵件地址。","error_page.error_message_network_error":"網路錯誤。請檢查您的網路連線。","error_page.error_message_error_charging_payment":"付款失敗。","error_page.error_message_error_setting_up_purchase":"由於發生錯誤，購買未啟動（錯誤代碼：{{errorCode}}）。","error_page.error_message_invalid_tax_location":"我們無法驗證您的帳單地址。請仔細檢查郵遞區號和國家是否正確。","error_page.error_message_unknown_error":"發生不明錯誤（錯誤代碼：{{errorCode}}）。","error_page.button_try_again":"再試一次","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% 折扣","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}} ({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"今日應付總額","product_info.subscribe_to":"訂閱","navbar_header.details":"詳細資訊","navbar_header.back_button":"返回","pricing_dropdown.show_details":"顯示詳細資訊","pricing_dropdown.hide_details":"隱藏詳細資訊","pricing_table.tax":"稅金","pricing_table.trial_ends":"試用期結束後，於 {{formattedTrialEndDate}}","pricing_table.total_due_today":"今日應付總額","pricing_table.total_excluding_tax":"總計（不含稅）","pricing_table.enter_billing_address_to_calculate":"輸入帳單地址以計算","pricing_table.enter_state_or_postal_code_to_calculate":"輸入州或郵政編碼以計算","pricing_table.enter_postal_code_to_calculate":"輸入郵政編碼以計算","error_page.error_message_invalid_email_error":"無法驗證電子郵件地址 {{email}}。請提供有效的電子郵件地址。","payment_entry_page.button_payment_method":"使用 {{paymentMethod}} 支付 {{formattedPrice}}","payment_entry_page.button_with_price":"支付 {{formattedPrice}}","price_update.title":"價格更新","price_update.base_message":"總價已根據您的帳單地址更新稅金。請檢查後重試。您的信用卡只會被收取一次費用。","price_update.trial_message":"根據您的帳單地址，訂閱價格已更新為含稅價格。免費試用仍然有效。請查看並重試。","payment_entry_page.express_checkout_divider":"或以信用卡付款","error_page.trouble_accessing":"如果您在存取購買項目時遇到問題，請透過以下方式聯絡支援人員：","error_page.close_button_title":"前往{{appName}}","error_page.error_title_stripe_missing_required_permission":"缺少 Stripe 權限","error_page.button_close":"關閉","error_page.error_message_stripe_invalid_tax_origin_address":"購買失敗，因為稅務起始地址無效。在正式環境中，購買將在不套用稅金的情況下運作。","error_page.error_message_stripe_tax_not_active":"購買失敗，因為 Stripe Tax 未啟用。在正式環境中，購買將在不套用稅金的情況下運作。","error_page.error_only_in_sandbox":"此訊息僅在沙盒中顯示。","error_page.error_message_stripe_missing_required_permission":"購買失敗，因為 Stripe 應用程式缺少必要的權限。在正式環境中，購買將在不套用稅金的情況下運作。","error_page.error_title_stripe_tax_not_active":"Stripe Tax 未啟用","error_page.error_title_stripe_invalid_tax_origin_address":"無效的稅務起始地址","apple_pay.free_trial":"免費試用","product_info.price_after_intro_price":"在 {{introPriceDuration}} 之後，於 {{renewalDate}}","product_info.after_trial":"試用期後","product_info.after":"之後","product_info.intro_price_phase_after_trial":"然後 {{introPriceDuration}}，價格為 {{introPrice}}","product_info.intro_price_phase":"首先 {{introPriceDuration}}，價格為 {{introPrice}}","product_info.intro_price_phase_paid_once":"一次性支付","payment_entry_page.trial_subscription_terms_info":"在您的試用期結束後，您將被收取 {{price}} {{perFrequency}}，從 {{renewalDate}} 開始。您可以隨時在此日期之前取消。","payment_entry_page.subscription_info":"訂閱會自動續訂。隨時取消。","payment_entry_page.otp_terms_info":"購買即表示您同意授權 {{appName}} 根據其條款向您收費。","payment_entry_page.subscription_terms_info":"訂閱即表示您同意允許 {{appName}} 根據其條款向您收費，直到您取消為止。"},wFA={"periods.week":"{{amount}} tjedan","periods.month":"{{amount}} mjesec","periods.year":"{{amount}} godina","periods.day":"{{amount}} dan","periods.weekShort":"{{amount}}tj","periods.monthShort":"{{amount}}mj","periods.yearShort":"{{amount}}g","periods.dayShort":"{{amount}}d","periods.lifetime":"doživotno","periods.weekPlural":"{{amount}} tjedana","periods.monthPlural":"{{amount}} mjeseci","periods.yearPlural":"{{amount}} godina","periods.dayPlural":"{{amount}} dana","periods.weekFrequency":"tjedno","periods.monthFrequency":"mjesečno","periods.yearFrequency":"godišnje","periods.dayFrequency":"dnevno","periods.perWeekFrequency":"tjedno","periods.perMonthFrequency":"mjesečno","periods.perYearFrequency":"godišnje","periods.perDayFrequency":"dnevno","periods.unknownFrequency":"nepoznato","periods.weekFrequencyPlural":"svakih {{amount}} tjedana","periods.monthFrequencyPlural":"svakih {{amount}} mjeseci","periods.yearFrequencyPlural":"svakih {{amount}} godina","periods.dayFrequencyPlural":"svakih {{amount}} dana","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} besplatno probno razdoblje","product_info.price_after_free_trial":"Nakon isteka probnog razdoblja, {{renewalDate}}","product_info.renewal_frequency":"Obnavlja se {{frequency}}","product_info.continues_until_cancelled":"Nastavlja se dok se ne otkaže","product_info.cancel_anytime":"Otkažite u bilo kojem trenutku","payment_entry_page.payment_step_title":"Sigurna naplata putem RevenueCat","payment_entry_page.button_pay":"Plati sada","payment_entry_page.button_start_trial":"Počni probno razdoblje","success_page.purchase_successful":"Uplata je uspješna","success_page.button_close":"Nastavi","error_page.if_error_persists":"Ako se pogreška nastavi, obratite se ","error_page.error_title_already_subscribed":"Već ste pretplaćeni na {{productTitle}}","error_page.error_title_already_purchased":"Već ste kupili {{productTitle}}","error_page.error_title_other_errors":"Nešto je pošlo po zlu","error_page.error_message_already_subscribed":"Ne možete se ponovno pretplatiti na ovaj proizvod.","error_page.error_message_already_purchased":"Ne možete ponovno kupiti ovaj proizvod.","error_page.error_message_missing_email_error":"E-pošta je potrebna za dovršetak kupnje.","error_page.error_message_network_error":"Mrežna pogreška. Provjerite internetsku vezu.","error_page.error_message_error_charging_payment":"Plaćanje nije uspjelo.","error_page.error_message_error_setting_up_purchase":"Kupnja nije započela zbog pogreške (kod pogreške: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Nismo mogli potvrditi vašu adresu za naplatu. Molimo provjerite poštanski broj i državu kako biste bili sigurni da su točni.","error_page.error_message_unknown_error":"Došlo je do nepoznate pogreške (kod pogreške: {{errorCode}}).","error_page.button_try_again":"Pokušaj ponovno","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% popusta","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Ukupno dospijeće danas","product_info.subscribe_to":"Pretplatite se","navbar_header.details":"Detalji","navbar_header.back_button":"Natrag","pricing_dropdown.show_details":"Prikaži detalje","pricing_dropdown.hide_details":"Sakrij detalje","pricing_table.tax":"Porez","pricing_table.trial_ends":"Nakon isteka probnog razdoblja, {{formattedTrialEndDate}}","pricing_table.total_due_today":"Ukupan iznos dospijeća danas","pricing_table.total_excluding_tax":"Ukupno bez poreza","pricing_table.enter_billing_address_to_calculate":"Unesite adresu za naplatu za izračun","pricing_table.enter_state_or_postal_code_to_calculate":"Unesite državu ili poštanski broj za izračun","pricing_table.enter_postal_code_to_calculate":"Unesite poštanski broj za izračun","error_page.error_message_invalid_email_error":"Adresa e-pošte {{email}} nije se mogla potvrditi. Molimo unesite valjanu adresu e-pošte.","payment_entry_page.button_payment_method":"Plati {{formattedPrice}} putem {{paymentMethod}}","payment_entry_page.button_with_price":"Plati {{formattedPrice}}","price_update.title":"Ažuriranje cijene","price_update.base_message":"Ukupna cijena je ažurirana s porezom na temelju vaše adrese za naplatu. Pregledajte i pokušajte ponovo. Vaša kartica bit će naplaćena samo jednom.","price_update.trial_message":"Cijena pretplate je ažurirana da uključi poreze na temelju vaše adrese za naplatu. Besplatno probno razdoblje i dalje vrijedi. Molimo provjerite i pokušajte ponovno.","payment_entry_page.express_checkout_divider":"ILI PLATITE KARTICOM","error_page.trouble_accessing":"Ako imate problema s pristupom kupnji, obratite se podršci na ","error_page.close_button_title":"Idi na {{appName}}","error_page.error_title_stripe_missing_required_permission":"Nedostaje Stripe dopuštenje","error_page.button_close":"Zatvori","error_page.error_message_stripe_invalid_tax_origin_address":"Kupnja nije uspjela jer je adresa poreznog podrijetla nevažeća. U produkciji će kupnje funkcionirati bez primijenjenih poreza.","error_page.error_message_stripe_tax_not_active":"Kupnja nije uspjela jer Stripe Tax nije omogućen. U produkciji će kupnje funkcionirati bez primijenjenih poreza.","error_page.error_only_in_sandbox":"Ova se poruka pojavljuje samo u sandboxu.","error_page.error_message_stripe_missing_required_permission":"Kupnja nije uspjela jer Stripe aplikaciji nedostaje potrebno dopuštenje. U produkciji će kupnje funkcionirati bez primijenjenih poreza.","error_page.error_title_stripe_tax_not_active":"Stripe Tax nije aktivan","error_page.error_title_stripe_invalid_tax_origin_address":"Nevažeća adresa poreznog podrijetla","apple_pay.free_trial":"Besplatna proba","product_info.price_after_intro_price":"Nakon {{introPriceDuration}}, na {{renewalDate}}","product_info.after_trial":"nakon probnog perioda","product_info.after":"nakon","product_info.intro_price_phase_after_trial":"Zatim {{introPriceDuration}} za {{introPrice}}","product_info.intro_price_phase":"Prvo {{introPriceDuration}} za {{introPrice}}","product_info.intro_price_phase_paid_once":"plaća se jednokratno","payment_entry_page.trial_subscription_terms_info":"Nakon isteka probnog razdoblja, bit će vam naplaćeno {{price}} {{perFrequency}} počevši od {{renewalDate}}. Možete otkazati bilo kada prije tog datuma.","payment_entry_page.subscription_info":"Pretplata se automatski obnavlja. Otkažite bilo kada.","payment_entry_page.otp_terms_info":"Kupnjom pristajete dopustiti aplikaciji {{appName}} da vam naplati u skladu s njihovim uvjetima.","payment_entry_page.subscription_terms_info":"Pretplatom se slažete da ćete dopustiti {{appName}} da vam naplaćuje u skladu s njihovim uvjetima dok ne otkažete."},kFA={"periods.week":"{{amount}} týden","periods.month":"{{amount}} měsíc","periods.year":"{{amount}} rok","periods.day":"{{amount}} den","periods.weekShort":"{{amount}}týd","periods.monthShort":"{{amount}}měs","periods.yearShort":"{{amount}}rok","periods.dayShort":"{{amount}}d","periods.lifetime":"doživotně","periods.weekPlural":"{{amount}} týdnů","periods.monthPlural":"{{amount}} měsíců","periods.yearPlural":"{{amount}} let","periods.dayPlural":"{{amount}} dnů","periods.weekFrequency":"týdně","periods.monthFrequency":"měsíčně","periods.yearFrequency":"ročně","periods.dayFrequency":"denně","periods.perWeekFrequency":"týdně","periods.perMonthFrequency":"měsíčně","periods.perYearFrequency":"ročně","periods.perDayFrequency":"denně","periods.unknownFrequency":"neznámé","periods.weekFrequencyPlural":"každých {{amount}} týdnů","periods.monthFrequencyPlural":"každých {{amount}} měsíců","periods.yearFrequencyPlural":"každých {{amount}} let","periods.dayFrequencyPlural":"každých {{amount}} dnů","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} zkušební verze zdarma","product_info.price_after_free_trial":"Po skončení zkušební verze, {{renewalDate}}","product_info.renewal_frequency":"Obnovuje se {{frequency}}","product_info.continues_until_cancelled":"Pokračuje, dokud není zrušeno","product_info.cancel_anytime":"Zrušit kdykoli","payment_entry_page.payment_step_title":"Bezpečné placení přes RevenueCat","payment_entry_page.button_pay":"Platit nyní","payment_entry_page.button_start_trial":"Spustit zkušební verzi","success_page.purchase_successful":"Platba dokončena","success_page.button_close":"Pokračovat","error_page.if_error_persists":"Pokud chyba přetrvává, kontaktujte ","error_page.error_title_already_subscribed":"Již máte předplatné pro {{productTitle}}","error_page.error_title_already_purchased":"Již jste zakoupili {{productTitle}}","error_page.error_title_other_errors":"Něco se pokazilo","error_page.error_message_already_subscribed":"Nemůžete si znovu předplatit tento produkt.","error_page.error_message_already_purchased":"Tento produkt si nemůžete znovu zakoupit.","error_page.error_message_missing_email_error":"Pro dokončení nákupu je vyžadován e-mail.","error_page.error_message_network_error":"Síťová chyba. Zkontrolujte prosím své internetové připojení.","error_page.error_message_error_charging_payment":"Platba selhala.","error_page.error_message_error_setting_up_purchase":"Nákup nebyl zahájen z důvodu chyby (kód chyby: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Nemohli jsme ověřit vaši fakturační adresu. Zkontrolujte prosím, zda je poštovní směrovací číslo a země správné.","error_page.error_message_unknown_error":"Došlo k neznámé chybě (kód chyby: {{errorCode}}).","error_page.button_try_again":"Zkusit znovu","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% sleva","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Celkem dnes k zaplacení","product_info.subscribe_to":"Předplatit","navbar_header.details":"Podrobnosti","navbar_header.back_button":"Zpět","pricing_dropdown.show_details":"Zobrazit podrobnosti","pricing_dropdown.hide_details":"Skrýt podrobnosti","pricing_table.tax":"Daň","pricing_table.trial_ends":"Po skončení zkušební doby, dne {{formattedTrialEndDate}}","pricing_table.total_due_today":"Celkem splatné dnes","pricing_table.total_excluding_tax":"Celkem bez daně","pricing_table.enter_billing_address_to_calculate":"Zadejte fakturační adresu pro výpočet","pricing_table.enter_state_or_postal_code_to_calculate":"Zadejte stát nebo PSČ pro výpočet","pricing_table.enter_postal_code_to_calculate":"Zadejte PSČ pro výpočet","error_page.error_message_invalid_email_error":"E-mailová adresa {{email}} nemohla být ověřena. Zadejte prosím platnou e-mailovou adresu.","payment_entry_page.button_payment_method":"Zaplatit {{formattedPrice}} pomocí {{paymentMethod}}","payment_entry_page.button_with_price":"Zaplatit {{formattedPrice}}","price_update.title":"Aktualizace ceny","price_update.base_message":"Celková cena byla aktualizována o daň na základě vaší fakturační adresy. Zkontrolujte ji a zkuste to znovu. Vaše karta bude stržena pouze jednou.","price_update.trial_message":"Cena předplatného byla aktualizována včetně daní na základě vaší fakturační adresy. Bezplatná zkušební doba stále platí. Prosím, zkontrolujte a zkuste to znovu.","payment_entry_page.express_checkout_divider":"NEBO ZAPLATIT KARTOU","error_page.trouble_accessing":"Pokud máte potíže s přístupem k zakoupenému obsahu, kontaktujte podporu na ","error_page.close_button_title":"Přejít na {{appName}}","error_page.error_title_stripe_missing_required_permission":"Chybí oprávnění Stripe","error_page.button_close":"Zavřít","error_page.error_message_stripe_invalid_tax_origin_address":"Nákup se nezdařil, protože adresa původu daně je neplatná. V produkčním prostředí budou nákupy fungovat bez uplatnění daní.","error_page.error_message_stripe_tax_not_active":"Nákup se nezdařil, protože Stripe Tax není aktivní. V produkčním prostředí budou nákupy fungovat bez uplatnění daní.","error_page.error_only_in_sandbox":"Tato zpráva se zobrazuje pouze v sandboxu.","error_page.error_message_stripe_missing_required_permission":"Nákup se nezdařil, protože aplikaci Stripe chybí požadované oprávnění. V produkčním prostředí budou nákupy fungovat bez uplatnění daní.","error_page.error_title_stripe_tax_not_active":"Stripe Tax není aktivní","error_page.error_title_stripe_invalid_tax_origin_address":"Neplatná adresa původu daně","apple_pay.free_trial":"Zkušební verze zdarma","product_info.price_after_intro_price":"Po {{introPriceDuration}}, dne {{renewalDate}}","product_info.after_trial":"po zkušební době","product_info.after":"po","product_info.intro_price_phase_after_trial":"Poté {{introPriceDuration}} za {{introPrice}}","product_info.intro_price_phase":"Nejprve {{introPriceDuration}} za {{introPrice}}","product_info.intro_price_phase_paid_once":"placeno jednorázově","payment_entry_page.trial_subscription_terms_info":"Po skončení zkušebního období vám bude účtováno {{price}} {{perFrequency}} počínaje {{renewalDate}}. Před tímto datem můžete kdykoli zrušit.","payment_entry_page.subscription_info":"Předplatné se automaticky obnovuje. Zrušit můžete kdykoli.","payment_entry_page.otp_terms_info":"Zakoupením souhlasíte s tím, že umožníte aplikaci {{appName}} účtovat vám poplatky v souladu s jejími podmínkami.","payment_entry_page.subscription_terms_info":"Přihlášením k odběru souhlasíte s tím, že společnost {{appName}} vám bude účtovat poplatky v souladu s jejími podmínkami, dokud odběr nezrušíte."},MFA={"periods.week":"{{amount}} uge","periods.month":"{{amount}} måned","periods.year":"{{amount}} år","periods.day":"{{amount}} dag","periods.weekShort":"{{amount}}ug","periods.monthShort":"{{amount}}md","periods.yearShort":"{{amount}}år","periods.dayShort":"{{amount}}d","periods.lifetime":"livstid","periods.weekPlural":"{{amount}} uger","periods.monthPlural":"{{amount}} måneder","periods.yearPlural":"{{amount}} år","periods.dayPlural":"{{amount}} dage","periods.weekFrequency":"ugentligt","periods.monthFrequency":"månedligt","periods.yearFrequency":"årligt","periods.dayFrequency":"dagligt","periods.perWeekFrequency":"pr. uge","periods.perMonthFrequency":"pr. måned","periods.perYearFrequency":"pr. år","periods.perDayFrequency":"pr. dag","periods.unknownFrequency":"ukendt","periods.weekFrequencyPlural":"hver {{amount}} uger","periods.monthFrequencyPlural":"hver {{amount}} måneder","periods.yearFrequencyPlural":"hver {{amount}} år","periods.dayFrequencyPlural":"hver {{amount}} dage","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} gratis prøveperiode","product_info.price_after_free_trial":"Efter prøveperioden slutter, den {{renewalDate}}","product_info.renewal_frequency":"Fornyes {{frequency}}","product_info.continues_until_cancelled":"Fortsætter indtil annulleret","product_info.cancel_anytime":"Annuller når som helst","payment_entry_page.payment_step_title":"Sikker betaling via RevenueCat","payment_entry_page.button_pay":"Betal nu","payment_entry_page.button_start_trial":"Start prøveperiode","success_page.purchase_successful":"Betaling gennemført","success_page.button_close":"Fortsæt","error_page.if_error_persists":"Hvis fejlen fortsætter, kontakt venligst ","error_page.error_title_already_subscribed":"Du abonnerer allerede på {{productTitle}}","error_page.error_title_already_purchased":"Du har allerede købt {{productTitle}}","error_page.error_title_other_errors":"Noget gik galt","error_page.error_message_already_subscribed":"Du kan ikke abonnere på dette produkt igen.","error_page.error_message_already_purchased":"Du kan ikke købe dette produkt igen.","error_page.error_message_missing_email_error":"Email er påkrævet for at gennemføre købet.","error_page.error_message_network_error":"Netværksfejl. Kontroller din internetforbindelse.","error_page.error_message_error_charging_payment":"Betalingen mislykkedes.","error_page.error_message_error_setting_up_purchase":"Køb ikke startet på grund af en fejl (fejlkode: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Vi kunne ikke bekræfte din faktureringsadresse. Kontroller venligst, at postnummeret og landet er korrekte.","error_page.error_message_unknown_error":"Der opstod en ukendt fejl (fejlkode: {{errorCode}}).","error_page.button_try_again":"Prøv igen","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% rabat","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Samlet beløb for i dag","product_info.subscribe_to":"Abonner på","navbar_header.details":"Detaljer","navbar_header.back_button":"Tilbage","pricing_dropdown.show_details":"Vis detaljer","pricing_dropdown.hide_details":"Skjul detaljer","pricing_table.tax":"Moms","pricing_table.trial_ends":"Efter prøveperioden slutter, den {{formattedTrialEndDate}}","pricing_table.total_due_today":"Samlet beløb forfalden i dag","pricing_table.total_excluding_tax":"Samlet beløb eksklusive moms","pricing_table.enter_billing_address_to_calculate":"Indtast faktureringsadresse for at beregne","pricing_table.enter_state_or_postal_code_to_calculate":"Indtast stat eller postnummer for at beregne","pricing_table.enter_postal_code_to_calculate":"Indtast postnummer for at beregne","error_page.error_message_invalid_email_error":"E-mailadressen {{email}} kunne ikke bekræftes. Angiv en gyldig e-mailadresse.","payment_entry_page.button_payment_method":"Betal {{formattedPrice}} med {{paymentMethod}}","payment_entry_page.button_with_price":"Betal {{formattedPrice}}","price_update.title":"Prisopdatering","price_update.base_message":"Den samlede pris er blevet opdateret med moms baseret på din faktureringsadresse. Gennemgå og prøv igen. Dit kort vil kun blive debiteret én gang.","price_update.trial_message":"Abonnementsprisen er opdateret for at inkludere skatter baseret på din faktureringsadresse. Den gratis prøveperiode gælder stadig. Kontroller venligst og prøv igen.","payment_entry_page.express_checkout_divider":"ELLER BETAL MED KORT","error_page.trouble_accessing":"Hvis du har problemer med at få adgang til dit køb, kan du kontakte support på ","error_page.close_button_title":"Gå til {{appName}}","error_page.error_title_stripe_missing_required_permission":"Manglende Stripe-tilladelse","error_page.button_close":"Luk","error_page.error_message_stripe_invalid_tax_origin_address":"Købet mislykkedes, fordi skatteoprindelsesadressen er ugyldig. I produktion vil køb fungere uden påførte skatter.","error_page.error_message_stripe_tax_not_active":"Købet mislykkedes, fordi Stripe Tax ikke er aktiveret. I produktion vil køb fungere uden påførte skatter.","error_page.error_only_in_sandbox":"Denne meddelelse vises kun i sandkassen.","error_page.error_message_stripe_missing_required_permission":"Købet mislykkedes, fordi Stripe-appen mangler en påkrævet tilladelse. I produktion vil køb fungere uden påførte skatter.","error_page.error_title_stripe_tax_not_active":"Stripe Tax er ikke aktiv","error_page.error_title_stripe_invalid_tax_origin_address":"Ugyldig skatteoprindelsesadresse","apple_pay.free_trial":"Gratis prøveperiode","product_info.price_after_intro_price":"Efter {{introPriceDuration}}, den {{renewalDate}}","product_info.after_trial":"efter prøveperiode","product_info.after":"efter","product_info.intro_price_phase_after_trial":"Derefter {{introPriceDuration}} for {{introPrice}}","product_info.intro_price_phase":"Først {{introPriceDuration}} for {{introPrice}}","product_info.intro_price_phase_paid_once":"betales én gang","payment_entry_page.trial_subscription_terms_info":"Efter din prøveperiode slutter, vil du blive opkrævet {{price}} {{perFrequency}} fra og med {{renewalDate}}. Du kan opsige når som helst før denne dato.","payment_entry_page.subscription_info":"Abonnementet fornys automatisk. Opsig når som helst.","payment_entry_page.otp_terms_info":"Ved at købe accepterer du, at {{appName}} kan debitere dig i overensstemmelse med deres vilkår.","payment_entry_page.subscription_terms_info":"Ved at abonnere accepterer du, at {{appName}} kan opkræve dig i henhold til deres vilkår, indtil du opsiger."},NFA={"periods.week":"{{amount}} week","periods.month":"{{amount}} maand","periods.year":"{{amount}} jaar","periods.day":"{{amount}} dag","periods.weekShort":"{{amount}}wk","periods.monthShort":"{{amount}}maand","periods.yearShort":"{{amount}}jr","periods.dayShort":"{{amount}}d","periods.lifetime":"levenslang","periods.weekPlural":"{{amount}} weken","periods.monthPlural":"{{amount}} maanden","periods.yearPlural":"{{amount}} jaren","periods.dayPlural":"{{amount}} dagen","periods.weekFrequency":"wekelijks","periods.monthFrequency":"maandelijks","periods.yearFrequency":"jaarlijks","periods.dayFrequency":"dagelijks","periods.perWeekFrequency":"per week","periods.perMonthFrequency":"per maand","periods.perYearFrequency":"per jaar","periods.perDayFrequency":"per dag","periods.unknownFrequency":"onbekend","periods.weekFrequencyPlural":"elke {{amount}} weken","periods.monthFrequencyPlural":"elke {{amount}} maanden","periods.yearFrequencyPlural":"elke {{amount}} jaren","periods.dayFrequencyPlural":"elke {{amount}} dagen","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} gratis proefperiode","product_info.price_after_free_trial":"Na afloop van de proefperiode, op {{renewalDate}}","product_info.renewal_frequency":"Wordt verlengd {{frequency}}","product_info.continues_until_cancelled":"Wordt voortgezet tot annulering","product_info.cancel_anytime":"Annuleer op elk gewenst moment","payment_entry_page.payment_step_title":"Veilige afrekening via RevenueCat","payment_entry_page.button_pay":"Nu betalen","payment_entry_page.button_start_trial":"Start proefperiode","success_page.purchase_successful":"Betaling voltooid","success_page.button_close":"Doorgaan","error_page.if_error_persists":"Neem contact op met  als de fout aanhoudt","error_page.error_title_already_subscribed":"Je bent al geabonneerd op {{productTitle}}","error_page.error_title_already_purchased":"Je hebt {{productTitle}} al gekocht","error_page.error_title_other_errors":"Er is iets misgegaan","error_page.error_message_already_subscribed":"Je kunt je niet opnieuw abonneren op dit product.","error_page.error_message_already_purchased":"Je kunt dit product niet opnieuw kopen.","error_page.error_message_missing_email_error":"Een e-mailadres is vereist om de aankoop te voltooien.","error_page.error_message_network_error":"Netwerkfout. Controleer uw internetverbinding.","error_page.error_message_error_charging_payment":"Betaling mislukt.","error_page.error_message_error_setting_up_purchase":"Aankoop niet gestart vanwege een fout (foutcode: {{errorCode}}).","error_page.error_message_invalid_tax_location":"We konden uw factuuradres niet verifiëren. Controleer of de postcode en het land correct zijn.","error_page.error_message_unknown_error":"Er is een onbekende fout opgetreden (foutcode: {{errorCode}}).","error_page.button_try_again":"Opnieuw proberen","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% korting","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Totaal te betalen vandaag","product_info.subscribe_to":"Abonneren op","navbar_header.details":"Details","navbar_header.back_button":"Terug","pricing_dropdown.show_details":"Toon details","pricing_dropdown.hide_details":"Verberg details","pricing_table.tax":"Btw","pricing_table.trial_ends":"Na afloop van de proefperiode, op {{formattedTrialEndDate}}","pricing_table.total_due_today":"Totaal vandaag te betalen","pricing_table.total_excluding_tax":"Totaal exclusief btw","pricing_table.enter_billing_address_to_calculate":"Voer het factuuradres in om te berekenen","pricing_table.enter_state_or_postal_code_to_calculate":"Voer provincie of postcode in om te berekenen","pricing_table.enter_postal_code_to_calculate":"Voer postcode in om te berekenen","error_page.error_message_invalid_email_error":"Het e-mailadres {{email}} kon niet worden geverifieerd. Geef een geldig e-mailadres op.","payment_entry_page.button_payment_method":"Betaal {{formattedPrice}} met {{paymentMethod}}","payment_entry_page.button_with_price":"Betaal {{formattedPrice}}","price_update.title":"Prijsupdate","price_update.base_message":"De totale prijs is bijgewerkt met belasting op basis van uw factuuradres. Controleer en probeer het opnieuw. Uw kaart wordt slechts één keer belast.","price_update.trial_message":"De abonnementsprijs is bijgewerkt om belastingen op te nemen op basis van uw factuuradres. De gratis proefperiode blijft van toepassing. Controleer en probeer het opnieuw.","payment_entry_page.express_checkout_divider":"OF BETAAL MET EEN KAART","error_page.trouble_accessing":"Als je problemen hebt met het verkrijgen van toegang tot je aankoop, neem dan contact op met de ondersteuning via ","error_page.close_button_title":"Ga naar {{appName}}","error_page.error_title_stripe_missing_required_permission":"Ontbrekende Stripe-toestemming","error_page.button_close":"Sluiten","error_page.error_message_stripe_invalid_tax_origin_address":"De aankoop is mislukt omdat het belastingoorsprongadres ongeldig is. In productie werken aankopen zonder toegepaste belastingen.","error_page.error_message_stripe_tax_not_active":"De aankoop is mislukt omdat Stripe Tax niet is ingeschakeld. In productie werken aankopen zonder toegepaste belastingen.","error_page.error_only_in_sandbox":"Dit bericht verschijnt alleen in de sandbox.","error_page.error_message_stripe_missing_required_permission":"De aankoop is mislukt omdat de Stripe-app een vereiste toestemming mist. In productie werken aankopen zonder toegepaste belastingen.","error_page.error_title_stripe_tax_not_active":"Stripe Tax niet actief","error_page.error_title_stripe_invalid_tax_origin_address":"Ongeldig belastingoorsprongadres","apple_pay.free_trial":"Gratis proefperiode","product_info.price_after_intro_price":"Na {{introPriceDuration}}, op {{renewalDate}}","product_info.after_trial":"na proefperiode","product_info.after":"na","product_info.intro_price_phase_after_trial":"Daarna {{introPriceDuration}} voor {{introPrice}}","product_info.intro_price_phase":"Eerst {{introPriceDuration}} voor {{introPrice}}","product_info.intro_price_phase_paid_once":"eenmalig betaald","payment_entry_page.trial_subscription_terms_info":"Na afloop van uw proefperiode wordt {{price}} {{perFrequency}} in rekening gebracht, beginnend op {{renewalDate}}. U kunt op elk moment vóór deze datum annuleren.","payment_entry_page.subscription_info":"Abonnement wordt automatisch verlengd. Annuleer op elk moment.","payment_entry_page.otp_terms_info":"Door de aankoop ga je ermee akkoord dat {{appName}} kosten in rekening brengt volgens hun voorwaarden.","payment_entry_page.subscription_terms_info":"Door u te abonneren, stemt u ermee in dat {{appName}} u kosten in rekening brengt volgens hun voorwaarden totdat u annuleert."},RFA={"periods.week":"{{amount}} viikko","periods.month":"{{amount}} kuukausi","periods.year":"{{amount}} vuosi","periods.day":"{{amount}} päivä","periods.weekShort":"{{amount}}vk","periods.monthShort":"{{amount}}kk","periods.yearShort":"{{amount}}v","periods.dayShort":"{{amount}}p","periods.lifetime":"elämäaika","periods.weekPlural":"{{amount}} viikkoa","periods.monthPlural":"{{amount}} kuukautta","periods.yearPlural":"{{amount}} vuotta","periods.dayPlural":"{{amount}} päivää","periods.weekFrequency":"viikoittain","periods.monthFrequency":"kuukausittain","periods.yearFrequency":"vuosittain","periods.dayFrequency":"päivittäin","periods.perWeekFrequency":"viikossa","periods.perMonthFrequency":"kuukaudessa","periods.perYearFrequency":"vuodessa","periods.perDayFrequency":"päivässä","periods.unknownFrequency":"tuntematon","periods.weekFrequencyPlural":"joka {{amount}} viikko","periods.monthFrequencyPlural":"joka {{amount}} kuukausi","periods.yearFrequencyPlural":"joka {{amount}} vuosi","periods.dayFrequencyPlural":"joka {{amount}} päivä","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} ilmainen kokeilujakso","product_info.price_after_free_trial":"Kokeilujakson päätyttyä, {{renewalDate}}","product_info.renewal_frequency":"Uusiutuu {{frequency}}","product_info.continues_until_cancelled":"Jatkuu, kunnes peruutetaan","product_info.cancel_anytime":"Peruuta milloin tahansa","payment_entry_page.payment_step_title":"Suojautunut kassatoiminto RevenueCatin kautta","payment_entry_page.button_pay":"Maksa nyt","payment_entry_page.button_start_trial":"Aloita kokeilujakso","success_page.purchase_successful":"Maksaminen onnistui","success_page.button_close":"Jatka","error_page.if_error_persists":"Jos virhe jatkuu, ota yhteyttä ","error_page.error_title_already_subscribed":"Olet jo tilannut tuotteen {{productTitle}}","error_page.error_title_already_purchased":"Olet jo ostanut tuotteen {{productTitle}}","error_page.error_title_other_errors":"Jokin meni pieleen","error_page.error_message_already_subscribed":"Et voi tilata tätä tuotetta uudelleen.","error_page.error_message_already_purchased":"Et voi ostaa tätä tuotetta uudelleen.","error_page.error_message_missing_email_error":"Sähköpostiosoite tarvitaan ostoksen loppuun saattamiseksi.","error_page.error_message_network_error":"Verkkovirhe. Tarkista internet-yhteytesi.","error_page.error_message_error_charging_payment":"Maksaminen epäonnistui.","error_page.error_message_error_setting_up_purchase":"Ostoa ei aloitettu virheen vuoksi (virhekoodi: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Emme voineet vahvistaa laskutusosoitettasi. Tarkista, että postinumero ja maa ovat oikein.","error_page.error_message_unknown_error":"Tapahtui tuntematon virhe (virhekoodi: {{errorCode}}).","error_page.button_try_again":"Yritä uudelleen","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% alennus","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}} ({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Maksettava summa tänään","product_info.subscribe_to":"Tilaa","navbar_header.details":"Yksityiskohdat","navbar_header.back_button":"Takaisin","pricing_dropdown.show_details":"Näytä tiedot","pricing_dropdown.hide_details":"Piilota tiedot","pricing_table.tax":"Vero","pricing_table.trial_ends":"Kokeilujakson päätyttyä, {{formattedTrialEndDate}}","pricing_table.total_due_today":"Maksettava summa tänään","pricing_table.total_excluding_tax":"Veroton kokonaissumma","pricing_table.enter_billing_address_to_calculate":"Syötä laskutusosoite laskeaksesi","pricing_table.enter_state_or_postal_code_to_calculate":"Syötä osavaltio tai postinumero laskeaksesi","pricing_table.enter_postal_code_to_calculate":"Syötä postinumero laskeaksesi","error_page.error_message_invalid_email_error":"Sähköpostiosoitetta {{email}} ei voitu vahvistaa. Anna kelvollinen sähköpostiosoite.","payment_entry_page.button_payment_method":"Maksa {{formattedPrice}} käyttämällä {{paymentMethod}}","payment_entry_page.button_with_price":"Maksa {{formattedPrice}}","price_update.title":"Hinnan päivitys","price_update.base_message":"Kokonaishinta on päivitetty verolla laskutusosoitteesi perusteella. Tarkista ja yritä uudelleen. Korttiasi veloitetaan vain kerran.","price_update.trial_message":"Tilauksen hinta on päivitetty sisältämään verot laskutusosoitteesi perusteella. Ilmainen kokeilujakso on edelleen voimassa. Tarkista ja yritä uudelleen.","payment_entry_page.express_checkout_divider":"TAI MAKSA KORTILLA","error_page.trouble_accessing":"Jos sinulla on ongelmia ostoksesi käyttämisessä, ota yhteyttä tukeen osoitteessa ","error_page.close_button_title":"Siirry sovellukseen {{appName}}","error_page.error_title_stripe_missing_required_permission":"Puuttuva Stripe-käyttöoikeus","error_page.button_close":"Sulje","error_page.error_message_stripe_invalid_tax_origin_address":"Osto epäonnistui, koska veron alkuperäosoite on virheellinen. Tuotantoympäristössä ostot toimivat ilman veroja.","error_page.error_message_stripe_tax_not_active":"Osto epäonnistui, koska Stripe Tax ei ole käytössä. Tuotantoympäristössä ostot toimivat ilman veroja.","error_page.error_only_in_sandbox":"Tämä viesti näkyy vain hiekkalaatikossa.","error_page.error_message_stripe_missing_required_permission":"Osto epäonnistui, koska Stripe-sovellukselta puuttuu vaadittu käyttöoikeus. Tuotantoympäristössä ostot toimivat ilman veroja.","error_page.error_title_stripe_tax_not_active":"Stripe Tax ei ole aktiivinen","error_page.error_title_stripe_invalid_tax_origin_address":"Virheellinen veron alkuperäosoite","apple_pay.free_trial":"Ilmainen kokeilu","product_info.price_after_intro_price":"{{introPriceDuration}} jälkeen, {{renewalDate}}","product_info.after_trial":"kokeilujakson jälkeen","product_info.after":"jälkeen","product_info.intro_price_phase_after_trial":"Sitten {{introPriceDuration}} hintaan {{introPrice}}","product_info.intro_price_phase":"Ensimmäiset {{introPriceDuration}} hintaan {{introPrice}}","product_info.intro_price_phase_paid_once":"maksetaan kerran","payment_entry_page.trial_subscription_terms_info":"Kokeilujakson päätyttyä sinulta veloitetaan {{price}} {{perFrequency}} alkaen {{renewalDate}}. Voit peruuttaa milloin tahansa ennen tätä päivämäärää.","payment_entry_page.subscription_info":"Tilaus uusiutuu automaattisesti. Peruuta milloin tahansa.","payment_entry_page.otp_terms_info":"Ostamalla hyväksyt, että {{appName}} veloittaa sinua heidän ehtojensa mukaisesti.","payment_entry_page.subscription_terms_info":"Tilaamalla hyväksyt, että {{appName}} veloittaa sinulta ehtojensa mukaisesti, kunnes peruutat tilauksen."},GFA={"periods.week":"{{amount}} semaine","periods.month":"{{amount}} mois","periods.year":"{{amount}} an","periods.day":"{{amount}} jour","periods.weekShort":"{{amount}}sem","periods.monthShort":"{{amount}}mois","periods.yearShort":"{{amount}}an","periods.dayShort":"{{amount}}j","periods.lifetime":"à vie","periods.weekPlural":"{{amount}} semaines","periods.monthPlural":"{{amount}} mois","periods.yearPlural":"{{amount}} ans","periods.dayPlural":"{{amount}} jours","periods.weekFrequency":"hebdomadaire","periods.monthFrequency":"mensuel","periods.yearFrequency":"annuel","periods.dayFrequency":"quotidien","periods.perWeekFrequency":"par semaine","periods.perMonthFrequency":"par mois","periods.perYearFrequency":"par an","periods.perDayFrequency":"par jour","periods.unknownFrequency":"inconnu","periods.weekFrequencyPlural":"toutes les {{amount}} semaines","periods.monthFrequencyPlural":"tous les {{amount}} mois","periods.yearFrequencyPlural":"tous les {{amount}} ans","periods.dayFrequencyPlural":"tous les {{amount}} jours","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} essai gratuit","product_info.price_after_free_trial":"Après la fin de l'essai, le {{renewalDate}}","product_info.renewal_frequency":"Renouvellement {{frequency}}","product_info.continues_until_cancelled":"Continue jusqu'à annulation","product_info.cancel_anytime":"Annulez à tout moment","payment_entry_page.payment_step_title":"Paiement sécurisé par RevenueCat","payment_entry_page.button_pay":"Payer maintenant","payment_entry_page.button_start_trial":"Commencer l'essai","success_page.purchase_successful":"Paiement effectué","success_page.button_close":"Continuer","error_page.if_error_persists":"Si l'erreur persiste, veuillez contacter ","error_page.error_title_already_subscribed":"Vous êtes déjà abonné à {{productTitle}}","error_page.error_title_already_purchased":"Vous avez déjà acheté {{productTitle}}","error_page.error_title_other_errors":"Une erreur s'est produite","error_page.error_message_already_subscribed":"Vous ne pouvez pas vous abonner à nouveau à ce produit.","error_page.error_message_already_purchased":"Vous ne pouvez pas acheter ce produit à nouveau.","error_page.error_message_missing_email_error":"L'adresse e-mail est requise pour effectuer l'achat.","error_page.error_message_network_error":"Erreur réseau. Veuillez vérifier votre connexion Internet.","error_page.error_message_error_charging_payment":"Échec du paiement.","error_page.error_message_error_setting_up_purchase":"L'achat n'a pas pu démarrer en raison d'une erreur (code d'erreur : {{errorCode}}).","error_page.error_message_invalid_tax_location":"Nous n'avons pas pu vérifier votre adresse de facturation. Veuillez vérifier que le code postal et le pays sont corrects.","error_page.error_message_unknown_error":"Une erreur inconnue s'est produite (code d'erreur : {{errorCode}}).","error_page.button_try_again":"Réessayer","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% de réduction","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}} ({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Total dû aujourd'hui","product_info.subscribe_to":"S'abonner à","navbar_header.details":"Détails","navbar_header.back_button":"Retour","pricing_dropdown.show_details":"Afficher les détails","pricing_dropdown.hide_details":"Masquer les détails","pricing_table.tax":"Taxe","pricing_table.trial_ends":"Après la fin de l'essai, le {{formattedTrialEndDate}}","pricing_table.total_due_today":"Total dû aujourd'hui","pricing_table.total_excluding_tax":"Total hors taxes","pricing_table.enter_billing_address_to_calculate":"Saisir l'adresse de facturation pour calculer","pricing_table.enter_state_or_postal_code_to_calculate":"Entrez l'état ou le code postal pour calculer","pricing_table.enter_postal_code_to_calculate":"Entrez le code postal pour calculer","error_page.error_message_invalid_email_error":"L'adresse e-mail {{email}} n'a pas pu être vérifiée. Veuillez fournir une adresse e-mail valide.","payment_entry_page.button_payment_method":"Payer {{formattedPrice}} avec {{paymentMethod}}","payment_entry_page.button_with_price":"Payer {{formattedPrice}}","price_update.title":"Mise à jour du prix","price_update.base_message":"Le prix total a été mis à jour avec la taxe en fonction de votre adresse de facturation. Veuillez vérifier et réessayer. Votre carte ne sera débitée qu'une seule fois.","price_update.trial_message":"Le prix de l'abonnement a été mis à jour pour inclure les taxes en fonction de votre adresse de facturation. La période d'essai gratuit reste applicable. Veuillez vérifier et réessayer.","payment_entry_page.express_checkout_divider":"OU PAYER PAR CARTE","error_page.trouble_accessing":"Si vous avez des difficultés à accéder à votre achat, contactez le support à l'adresse suivante : ","error_page.close_button_title":"Aller sur {{appName}}","error_page.error_title_stripe_missing_required_permission":"Autorisation Stripe manquante","error_page.button_close":"Fermer","error_page.error_message_stripe_invalid_tax_origin_address":"L'achat a échoué car l'adresse d'origine de la taxe n'est pas valide. En production, les achats fonctionneront sans taxes appliquées.","error_page.error_message_stripe_tax_not_active":"L'achat a échoué car Stripe Tax n'est pas activé. En production, les achats fonctionneront sans taxes appliquées.","error_page.error_only_in_sandbox":"Ce message apparaît uniquement dans l'environnement de test.","error_page.error_message_stripe_missing_required_permission":"L'achat a échoué car l'application Stripe ne dispose pas d'une autorisation requise. En production, les achats fonctionneront sans taxes appliquées.","error_page.error_title_stripe_tax_not_active":"Stripe Tax non actif","error_page.error_title_stripe_invalid_tax_origin_address":"Adresse d'origine de la taxe non valide","apple_pay.free_trial":"Essai gratuit","product_info.price_after_intro_price":"Après {{introPriceDuration}}, le {{renewalDate}}","product_info.after_trial":"après l'essai","product_info.after":"après","product_info.intro_price_phase_after_trial":"Puis {{introPriceDuration}} pour {{introPrice}}","product_info.intro_price_phase":"{{introPriceDuration}} pour {{introPrice}} au départ","product_info.intro_price_phase_paid_once":"payé une fois","payment_entry_page.trial_subscription_terms_info":"Après la fin de votre essai, vous serez facturé {{price}} {{perFrequency}} à partir du {{renewalDate}}. Vous pouvez annuler à tout moment avant cette date.","payment_entry_page.subscription_info":"L'abonnement est renouvelé automatiquement. Annulez à tout moment.","payment_entry_page.otp_terms_info":"En achetant, vous acceptez d'autoriser {{appName}} à vous facturer conformément à ses conditions.","payment_entry_page.subscription_terms_info":"En vous abonnant, vous acceptez d'autoriser {{appName}} à vous facturer conformément à ses conditions jusqu'à ce que vous annuliez."},bFA={"periods.week":"{{amount}} Woche","periods.month":"{{amount}} Monat","periods.year":"{{amount}} Jahr","periods.day":"{{amount}} Tag","periods.weekShort":"{{amount}}Wo","periods.monthShort":"{{amount}}Mo","periods.yearShort":"{{amount}}J","periods.dayShort":"{{amount}}T","periods.lifetime":"lebenslang","periods.weekPlural":"{{amount}} Wochen","periods.monthPlural":"{{amount}} Monate","periods.yearPlural":"{{amount}} Jahre","periods.dayPlural":"{{amount}} Tage","periods.weekFrequency":"wöchentlich","periods.monthFrequency":"monatlich","periods.yearFrequency":"jährlich","periods.dayFrequency":"täglich","periods.perWeekFrequency":"pro Woche","periods.perMonthFrequency":"pro Monat","periods.perYearFrequency":"pro Jahr","periods.perDayFrequency":"pro Tag","periods.unknownFrequency":"unbekannt","periods.weekFrequencyPlural":"alle {{amount}} Wochen","periods.monthFrequencyPlural":"alle {{amount}} Monate","periods.yearFrequencyPlural":"alle {{amount}} Jahre","periods.dayFrequencyPlural":"alle {{amount}} Tage","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} kostenlose Testversion","product_info.price_after_free_trial":"Nach Ablauf der Testversion, am {{renewalDate}}","product_info.renewal_frequency":"Verlängert sich {{frequency}}","product_info.continues_until_cancelled":"Läuft bis zur Kündigung","product_info.cancel_anytime":"Jederzeit kündbar","payment_entry_page.payment_step_title":"Sicherer Checkout über RevenueCat","payment_entry_page.button_pay":"Jetzt bezahlen","payment_entry_page.button_start_trial":"Testversion starten","success_page.purchase_successful":"Zahlung abgeschlossen","success_page.button_close":"Weiter","error_page.if_error_persists":"Wenn der Fehler weiterhin besteht, wenden Sie sich bitte an ","error_page.error_title_already_subscribed":"Du hast {{productTitle}} bereits abonniert","error_page.error_title_already_purchased":"Du hast {{productTitle}} bereits gekauft","error_page.error_title_other_errors":"Etwas ist schief gelaufen","error_page.error_message_already_subscribed":"Du kannst dieses Produkt nicht erneut abonnieren.","error_page.error_message_already_purchased":"Du kannst dieses Produkt nicht erneut kaufen.","error_page.error_message_missing_email_error":"Für den Kauf ist eine E-Mail-Adresse erforderlich.","error_page.error_message_network_error":"Netzwerkfehler. Bitte überprüfen Sie Ihre Internetverbindung.","error_page.error_message_error_charging_payment":"Zahlung fehlgeschlagen.","error_page.error_message_error_setting_up_purchase":"Der Kauf wurde aufgrund eines Fehlers nicht gestartet (Fehlercode: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Wir konnten Ihre Rechnungsadresse nicht überprüfen. Bitte überprüfen Sie, ob die Postleitzahl und das Land korrekt sind.","error_page.error_message_unknown_error":"Ein unbekannter Fehler ist aufgetreten (Fehlercode: {{errorCode}}).","error_page.button_try_again":"Erneut versuchen","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% Rabatt","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}} ({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Heute fälliger Gesamtbetrag","product_info.subscribe_to":"Abonnieren","navbar_header.details":"Details","navbar_header.back_button":"Zurück","pricing_dropdown.show_details":"Details anzeigen","pricing_dropdown.hide_details":"Details ausblenden","pricing_table.tax":"Steuer","pricing_table.trial_ends":"Nach Ablauf der Testphase, am {{formattedTrialEndDate}}","pricing_table.total_due_today":"Heute fälliger Gesamtbetrag","pricing_table.total_excluding_tax":"Gesamtbetrag ohne Steuer","pricing_table.enter_billing_address_to_calculate":"Rechnungsadresse eingeben, um zu berechnen","pricing_table.enter_state_or_postal_code_to_calculate":"Bundesland oder Postleitzahl zur Berechnung eingeben","pricing_table.enter_postal_code_to_calculate":"Postleitzahl zur Berechnung eingeben","error_page.error_message_invalid_email_error":"Die E-Mail-Adresse {{email}} konnte nicht verifiziert werden. Bitte gib eine gültige E-Mail-Adresse an.","payment_entry_page.button_payment_method":"Mit {{paymentMethod}} für {{formattedPrice}} bezahlen","payment_entry_page.button_with_price":"{{formattedPrice}} bezahlen","price_update.title":"Preisaktualisierung","price_update.base_message":"Der Gesamtpreis wurde basierend auf Ihrer Rechnungsadresse mit Steuern aktualisiert. Bitte überprüfen Sie ihn und versuchen Sie es erneut. Ihre Karte wird erst belastet, wenn alles korrekt ist.","price_update.trial_message":"Der Abonnementpreis wurde aktualisiert, um Steuern basierend auf Ihrer Rechnungsadresse einzuschließen. Die kostenlose Testphase gilt weiterhin. Bitte überprüfen Sie und versuchen Sie es erneut.","payment_entry_page.express_checkout_divider":"ODER MIT KARTE ZAHLEN","error_page.trouble_accessing":"Wenn Sie Probleme beim Zugriff auf Ihren Kauf haben, wenden Sie sich an den Support unter ","error_page.close_button_title":"Zu {{appName}} gehen","error_page.error_title_stripe_missing_required_permission":"Fehlende Stripe-Berechtigung","error_page.button_close":"Schließen","error_page.error_message_stripe_invalid_tax_origin_address":"Der Kauf ist fehlgeschlagen, da die Steuerursprungsadresse ungültig ist. In der Produktion funktionieren Käufe ohne angewendete Steuern.","error_page.error_message_stripe_tax_not_active":"Der Kauf ist fehlgeschlagen, da Stripe Tax nicht aktiviert ist. In der Produktion funktionieren Käufe ohne angewendete Steuern.","error_page.error_only_in_sandbox":"Diese Meldung wird nur in der Sandbox angezeigt.","error_page.error_message_stripe_missing_required_permission":"Der Kauf ist fehlgeschlagen, da der Stripe-App eine erforderliche Berechtigung fehlt. In der Produktion funktionieren Käufe ohne angewendete Steuern.","error_page.error_title_stripe_tax_not_active":"Stripe Tax ist nicht aktiv","error_page.error_title_stripe_invalid_tax_origin_address":"Ungültige Steuerursprungsadresse","apple_pay.free_trial":"Kostenlose Testversion","product_info.price_after_intro_price":"Nach {{introPriceDuration}}, am {{renewalDate}}","product_info.after_trial":"nach Testphase","product_info.after":"nach","product_info.intro_price_phase_after_trial":"Danach {{introPriceDuration}} für {{introPrice}}","product_info.intro_price_phase":"Zuerst {{introPriceDuration}} für {{introPrice}}","product_info.intro_price_phase_paid_once":"einmalig bezahlt","payment_entry_page.trial_subscription_terms_info":"Nach Ablauf Ihres Testzeitraums werden Ihnen {{price}} {{perFrequency}} ab dem {{renewalDate}} berechnet. Sie können jederzeit vor diesem Datum kündigen.","payment_entry_page.subscription_info":"Das Abonnement verlängert sich automatisch. Jederzeit kündbar.","payment_entry_page.otp_terms_info":"Mit dem Kauf erklären Sie sich einverstanden, dass {{appName}} Ihnen Gebühren gemäß ihren Bedingungen berechnet.","payment_entry_page.subscription_terms_info":"Mit dem Abonnieren erklären Sie sich damit einverstanden, dass {{appName}} Ihnen gemäß ihren Bedingungen Gebühren berechnet, bis Sie kündigen."},UFA={"periods.week":"{{amount}} εβδομάδα","periods.month":"{{amount}} μήνας","periods.year":"{{amount}} χρόνος","periods.day":"{{amount}} ημέρα","periods.weekShort":"{{amount}} εβδ.","periods.monthShort":"{{amount}} μήν.","periods.yearShort":"{{amount}} έτ.","periods.dayShort":"{{amount}} ημ.","periods.lifetime":"διάρκεια ζωής","periods.weekPlural":"{{amount}} εβδομάδες","periods.monthPlural":"{{amount}} μήνες","periods.yearPlural":"{{amount}} χρόνια","periods.dayPlural":"{{amount}} ημέρες","periods.weekFrequency":"εβδομαδιαία","periods.monthFrequency":"μηνιαία","periods.yearFrequency":"ετήσια","periods.dayFrequency":"καθημερινά","periods.perWeekFrequency":"ανά εβδομάδα","periods.perMonthFrequency":"ανά μήνα","periods.perYearFrequency":"ανά έτος","periods.perDayFrequency":"ανά ημέρα","periods.unknownFrequency":"άγνωστο","periods.weekFrequencyPlural":"κάθε {{amount}} εβδομάδες","periods.monthFrequencyPlural":"κάθε {{amount}} μήνες","periods.yearFrequencyPlural":"κάθε {{amount}} χρόνια","periods.dayFrequencyPlural":"κάθε {{amount}} ημέρες","product_info.subscribe_to":"Εγγραφείτε στο","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"Δωρεάν για {{trialDuration}}","product_info.price_after_free_trial":"Μετά τη λήξη της δοκιμής, στις {{renewalDate}}","product_info.total_due_today":"Σύνολο πληρωτέο σήμερα","product_info.renewal_frequency":"Ανανεώνεται {{frequency}}","product_info.continues_until_cancelled":"Συνεχίζεται μέχρι την ακύρωση","product_info.cancel_anytime":"Ακύρωση ανά πάσα στιγμή","payment_entry_page.payment_step_title":"Ασφαλής ολοκλήρωση αγοράς από την RevenueCat","payment_entry_page.button_pay":"Πληρωμή τώρα","payment_entry_page.button_start_trial":"Έναρξη δοκιμής","success_page.purchase_successful":"Η πληρωμή ολοκληρώθηκε","success_page.button_close":"Συνέχεια","error_page.if_error_persists":"Εάν το σφάλμα παραμένει, επικοινωνήστε με ","error_page.error_title_already_subscribed":"Έχετε ήδη εγγραφεί στο {{productTitle}}","error_page.error_title_already_purchased":"Έχετε ήδη αγοράσει το {{productTitle}}","error_page.error_title_other_errors":"Κάτι πήγε στραβά","error_page.error_message_already_subscribed":"Δεν μπορείτε να εγγραφείτε ξανά σε αυτό το προϊόν.","error_page.error_message_already_purchased":"Δεν μπορείτε να αγοράσετε ξανά αυτό το προϊόν.","error_page.error_message_missing_email_error":"Απαιτείται email για την ολοκλήρωση της αγοράς.","error_page.error_message_network_error":"Σφάλμα δικτύου. Ελέγξτε τη σύνδεσή σας στο διαδίκτυο.","error_page.error_message_error_charging_payment":"Η πληρωμή απέτυχε.","error_page.error_message_error_setting_up_purchase":"Η αγορά δεν ξεκίνησε λόγω σφάλματος (κωδικός σφάλματος: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Δεν μπορέσαμε να επαληθεύσουμε τη διεύθυνση χρέωσής σας. Παρακαλούμε ελέγξτε ξανά τον ταχυδρομικό κώδικα και τη χώρα για να βεβαιωθείτε ότι είναι σωστά.","error_page.error_message_unknown_error":"Παρουσιάστηκε ένα άγνωστο σφάλμα (κωδικός σφάλματος: {{errorCode}}).","error_page.button_try_again":"Προσπαθήστε ξανά","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% έκπτωση","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","navbar_header.details":"Λεπτομέρειες","navbar_header.back_button":"Πίσω","pricing_dropdown.show_details":"Εμφάνιση λεπτομερειών","pricing_dropdown.hide_details":"Απόκρυψη λεπτομερειών","pricing_table.tax":"Φόρος","pricing_table.trial_ends":"Μετά τη λήξη της δοκιμαστικής περιόδου, στις {{formattedTrialEndDate}}","pricing_table.total_due_today":"Σύνολο πληρωτέο σήμερα","pricing_table.total_excluding_tax":"Σύνολο χωρίς φόρο","pricing_table.enter_billing_address_to_calculate":"Εισαγάγετε τη διεύθυνση χρέωσης για να υπολογιστεί","pricing_table.enter_state_or_postal_code_to_calculate":"Εισαγάγετε την πολιτεία ή τον ταχυδρομικό κώδικα για να υπολογιστεί","pricing_table.enter_postal_code_to_calculate":"Εισαγάγετε τον ταχυδρομικό κώδικα για να υπολογιστεί","error_page.error_message_invalid_email_error":"Η διεύθυνση email {{email}} δεν μπόρεσε να επαληθευτεί. Παρακαλώ δώστε μια έγκυρη διεύθυνση email.","payment_entry_page.button_payment_method":"Πληρωμή {{formattedPrice}} με {{paymentMethod}}","payment_entry_page.button_with_price":"Πληρωμή {{formattedPrice}}","price_update.title":"Ενημέρωση τιμής","price_update.base_message":"Η συνολική τιμή ενημερώθηκε με τον φόρο βάσει της διεύθυνσης χρέωσής σας. Ελέγξτε και δοκιμάστε ξανά. Η κάρτα σας θα χρεωθεί μόνο μία φορά.","price_update.trial_message":"Η τιμή της συνδρομής ενημερώθηκε για να συμπεριλάβει τους φόρους βάσει της διεύθυνσης χρέωσής σας. Η δωρεάν δοκιμαστική περίοδος εξακολουθεί να ισχύει. Παρακαλώ ελέγξτε και δοκιμάστε ξανά.","payment_entry_page.express_checkout_divider":"Ή ΠΛΗΡΩΣΤΕ ΜΕ ΚΑΡΤΑ","error_page.trouble_accessing":"Εάν αντιμετωπίζετε προβλήματα πρόσβασης στην αγορά σας, επικοινωνήστε με την υποστήριξη στο ","error_page.close_button_title":"Μετάβαση στο {{appName}}","error_page.error_title_stripe_missing_required_permission":"Λείπει άδεια Stripe","error_page.button_close":"Κλείσιμο","error_page.error_message_stripe_invalid_tax_origin_address":"Η αγορά απέτυχε επειδή η διεύθυνση προέλευσης φόρου δεν είναι έγκυρη. Στην παραγωγή, οι αγορές θα λειτουργούν χωρίς να εφαρμόζονται φόροι.","error_page.error_message_stripe_tax_not_active":"Η αγορά απέτυχε επειδή το Stripe Tax δεν είναι ενεργοποιημένο. Στην παραγωγή, οι αγορές θα λειτουργούν χωρίς να εφαρμόζονται φόροι.","error_page.error_only_in_sandbox":"Αυτό το μήνυμα εμφανίζεται μόνο στο sandbox.","error_page.error_message_stripe_missing_required_permission":"Η αγορά απέτυχε επειδή η εφαρμογή Stripe δεν διαθέτει την απαιτούμενη άδεια. Στην παραγωγή, οι αγορές θα λειτουργούν χωρίς να εφαρμόζονται φόροι.","error_page.error_title_stripe_tax_not_active":"Το Stripe Tax δεν είναι ενεργό","error_page.error_title_stripe_invalid_tax_origin_address":"Μη έγκυρη διεύθυνση προέλευσης φόρου","apple_pay.free_trial":"Δωρεάν δοκιμή","product_info.price_after_intro_price":"Μετά από {{introPriceDuration}}, στις {{renewalDate}}","product_info.after_trial":"μετά τη δοκιμή","product_info.after":"μετά","product_info.intro_price_phase_after_trial":"Έπειτα {{introPriceDuration}} για {{introPrice}}","product_info.intro_price_phase":"Αρχικά {{introPriceDuration}} για {{introPrice}}","product_info.intro_price_phase_paid_once":"πληρωμένο εφάπαξ","payment_entry_page.trial_subscription_terms_info":"Μετά τη λήξη της δοκιμαστικής περιόδου, θα χρεωθείτε {{price}} {{perFrequency}} ξεκινώντας από {{renewalDate}}. Μπορείτε να ακυρώσετε ανά πάσα στιγμή πριν από αυτήν την ημερομηνία.","payment_entry_page.subscription_info":"Η συνδρομή ανανεώνεται αυτόματα. Ακυρώστε ανά πάσα στιγμή.","payment_entry_page.otp_terms_info":"Με την αγορά, συμφωνείτε να επιτρέψετε στην {{appName}} να σας χρεώσει σύμφωνα με τους όρους της.","payment_entry_page.subscription_terms_info":"Με την εγγραφή σας, συμφωνείτε να επιτρέψετε στην εφαρμογή {{appName}} να σας χρεώνει σύμφωνα με τους όρους της έως ότου ακυρώσετε."},vFA={"periods.week":"{{amount}} שבוע","periods.month":"{{amount}} חודש","periods.year":"{{amount}} שנה","periods.day":"{{amount}} יום","periods.weekShort":"{{amount}}wk","periods.monthShort":"{{amount}}mo","periods.yearShort":"{{amount}}yr","periods.dayShort":"{{amount}}d","periods.lifetime":"למשך כל החיים","periods.weekPlural":"{{amount}} שבועות","periods.monthPlural":"{{amount}} חודשים","periods.yearPlural":"{{amount}} שנים","periods.dayPlural":"{{amount}} ימים","periods.weekFrequency":"שבועי","periods.monthFrequency":"חודשי","periods.yearFrequency":"שנתי","periods.dayFrequency":"יומי","periods.perWeekFrequency":"לשבוע","periods.perMonthFrequency":"לחודש","periods.perYearFrequency":"לשנה","periods.perDayFrequency":"ליום","periods.unknownFrequency":"לא ידוע","periods.weekFrequencyPlural":"כל {{amount}} שבועות","periods.monthFrequencyPlural":"כל {{amount}} חודשים","periods.yearFrequencyPlural":"כל {{amount}} שנים","periods.dayFrequencyPlural":"כל {{amount}} ימים","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} ניסיון חינם","product_info.price_after_free_trial":"לאחר סיום הניסיון, ב-{{renewalDate}}","product_info.renewal_frequency":"מתחדש {{frequency}}","product_info.continues_until_cancelled":"נמשך עד ביטול","product_info.cancel_anytime":"ניתן לבטל בכל עת","payment_entry_page.payment_step_title":"קופה מאובטחת באמצעות RevenueCat","payment_entry_page.button_pay":"שלם עכשיו","payment_entry_page.button_start_trial":"התחל ניסיון","success_page.purchase_successful":"התשלום הושלם","success_page.button_close":"המשך","error_page.if_error_persists":"אם השגיאה נמשכת, אנא פנה אל ","error_page.error_title_already_subscribed":"כבר נרשמת כמנוי ל-{{productTitle}}","error_page.error_title_already_purchased":"כבר רכשת את {{productTitle}}","error_page.error_title_other_errors":"משהו השתבש","error_page.error_message_already_subscribed":"אינך יכול להירשם כמנוי למוצר זה שוב.","error_page.error_message_already_purchased":"אינך יכול לרכוש מוצר זה שוב.","error_page.error_message_missing_email_error":'דוא"ל נדרש כדי להשלים את הרכישה.',"error_page.error_message_network_error":"שגיאת רשת. אנא בדוק את חיבור האינטרנט שלך.","error_page.error_message_error_charging_payment":"התשלום נכשל.","error_page.error_message_error_setting_up_purchase":"הרכישה לא הופעלה עקב שגיאה (קוד שגיאה: {{errorCode}}).","error_page.error_message_invalid_tax_location":"לא הצלחנו לאמת את כתובת החיוב שלך. אנא בדוק שוב את המיקוד והמדינה כדי לוודא שהם נכונים.","error_page.error_message_unknown_error":"אירעה שגיאה לא ידועה (קוד שגיאה: {{errorCode}}).","error_page.button_try_again":"נסה שוב","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% הנחה","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":'סה"כ לתשלום היום',"product_info.subscribe_to":"הירשם כמנוי ל-","navbar_header.details":"פרטים","navbar_header.back_button":"חזרה","pricing_dropdown.show_details":"הצג פרטים","pricing_dropdown.hide_details":"הסתר פרטים","pricing_table.tax":"מס","pricing_table.trial_ends":"לאחר סיום תקופת הניסיון, בתאריך {{formattedTrialEndDate}}","pricing_table.total_due_today":"סך הכל לתשלום היום","pricing_table.total_excluding_tax":"סך הכל לא כולל מס","pricing_table.enter_billing_address_to_calculate":"הזן כתובת לחיוב כדי לחשב","pricing_table.enter_state_or_postal_code_to_calculate":"הזן מדינה או מיקוד לחישוב","pricing_table.enter_postal_code_to_calculate":"הזן מיקוד לחישוב","error_page.error_message_invalid_email_error":"לא ניתן לאמת את כתובת האימייל {{email}}. אנא ספק כתובת אימייל חוקית.","payment_entry_page.button_payment_method":"שלם {{formattedPrice}} באמצעות {{paymentMethod}}","payment_entry_page.button_with_price":"שלם {{formattedPrice}}","price_update.title":"עדכון מחיר","price_update.base_message":"המחיר הכולל עודכן עם מס בהתבסס על כתובת החיוב שלך. אנא בדוק שוב ונסה שוב. החיוב יתבצע רק פעם אחת.","price_update.trial_message":"מחיר המנוי עודכן כדי לכלול מיסים בהתבסס על כתובת החיוב שלך. תקופת הניסיון החינמית עדיין תקפה. אנא בדוק ונסה שוב.","payment_entry_page.express_checkout_divider":"או שלם באמצעות כרטיס","error_page.trouble_accessing":"אם אתה מתקשה לגשת לרכישה שלך, פנה לתמיכה בכתובת ","error_page.close_button_title":"עבור אל {{appName}}","error_page.error_title_stripe_missing_required_permission":"חסרה הרשאה של Stripe","error_page.button_close":"סגור","error_page.error_message_stripe_invalid_tax_origin_address":"הרכישה נכשלה מכיוון שכתובת מקור המס אינה חוקית. בייצור, רכישות יעבדו ללא מסים.","error_page.error_message_stripe_tax_not_active":"הרכישה נכשלה מכיוון שמס Stripe אינו מופעל. בייצור, רכישות יעבדו ללא מסים.","error_page.error_only_in_sandbox":"הודעה זו מופיעה רק בארגז חול.","error_page.error_message_stripe_missing_required_permission":"הרכישה נכשלה מכיוון שלאפליקציית Stripe חסרה הרשאה נדרשת. בייצור, רכישות יעבדו ללא מסים.","error_page.error_title_stripe_tax_not_active":"מס Stripe לא פעיל","error_page.error_title_stripe_invalid_tax_origin_address":"כתובת מקור מס לא חוקית","apple_pay.free_trial":"תקופת ניסיון בחינם","product_info.price_after_intro_price":"לאחר {{introPriceDuration}}, בתאריך {{renewalDate}}","product_info.after_trial":"אחרי תקופת ניסיון","product_info.after":"אחרי","product_info.intro_price_phase_after_trial":"אחר כך {{introPriceDuration}} עבור {{introPrice}}","product_info.intro_price_phase":"תחילה {{introPriceDuration}} עבור {{introPrice}}","product_info.intro_price_phase_paid_once":"משולם פעם אחת","payment_entry_page.trial_subscription_terms_info":"לאחר סיום תקופת הניסיון שלך, תחויב בסך {{price}} {{perFrequency}} החל מ-{{renewalDate}}. באפשרותך לבטל בכל עת לפני תאריך זה.","payment_entry_page.subscription_info":"המנוי מתחדש אוטומטית. ניתן לבטל בכל עת.","payment_entry_page.otp_terms_info":"ברכישה, אתה מסכים לאפשר ל-{{appName}} לחייב אותך בהתאם לתנאים שלהם.","payment_entry_page.subscription_terms_info":"על ידי הרשמה כמנוי, אתה מסכים לאפשר ל-{{appName}} לחייב אותך בהתאם לתנאים שלהם עד שתבטל."},KFA={"periods.week":"{{amount}} सप्ताह","periods.month":"{{amount}} महीना","periods.year":"{{amount}} वर्ष","periods.day":"{{amount}} दिन","periods.weekShort":"{{amount}}सप्ताह","periods.monthShort":"{{amount}}महीना","periods.yearShort":"{{amount}}वर्ष","periods.dayShort":"{{amount}}दिन","periods.lifetime":"लाइफ़टाइम","periods.weekPlural":"{{amount}} सप्ताह","periods.monthPlural":"{{amount}} महीने","periods.yearPlural":"{{amount}} वर्ष","periods.dayPlural":"{{amount}} दिन","periods.weekFrequency":"साप्ताहिक","periods.monthFrequency":"मासिक","periods.yearFrequency":"वार्षिक","periods.dayFrequency":"दैनिक","periods.perWeekFrequency":"प्रति सप्ताह","periods.perMonthFrequency":"प्रति माह","periods.perYearFrequency":"प्रति वर्ष","periods.perDayFrequency":"प्रति दिन","periods.unknownFrequency":"अज्ञात","periods.weekFrequencyPlural":"प्रत्येक {{amount}} सप्ताह","periods.monthFrequencyPlural":"प्रत्येक {{amount}} महीने","periods.yearFrequencyPlural":"प्रत्येक {{amount}} वर्ष","periods.dayFrequencyPlural":"प्रत्येक {{amount}} दिन","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} निःशुल्क परीक्षण","product_info.price_after_free_trial":"परीक्षण समाप्त होने के बाद, {{renewalDate}} को","product_info.renewal_frequency":"{{frequency}} पर नवीनीकृत होता है","product_info.continues_until_cancelled":"रद्द होने तक जारी रहता है","product_info.cancel_anytime":"किसी भी समय रद्द करें","payment_entry_page.payment_step_title":"RevenueCat द्वारा सुरक्षित चेकआउट","payment_entry_page.button_pay":"अभी भुगतान करें","payment_entry_page.button_start_trial":"परीक्षण प्रारंभ करें","success_page.purchase_successful":"भुगतान पूर्ण","success_page.button_close":"जारी रखें","error_page.if_error_persists":"यदि त्रुटि बनी रहती है, तो कृपया संपर्क करें ","error_page.error_title_already_subscribed":"आपने पहले ही {{productTitle}} की सदस्यता ले ली है","error_page.error_title_already_purchased":"आपने पहले ही {{productTitle}} खरीद लिया है","error_page.error_title_other_errors":"कुछ गलत हो गया","error_page.error_message_already_subscribed":"आप इस उत्पाद की सदस्यता फिर से नहीं ले सकते.","error_page.error_message_already_purchased":"आप इस उत्पाद को फिर से नहीं खरीद सकते.","error_page.error_message_missing_email_error":"खरीद को पूरा करने के लिए ईमेल आवश्यक है।","error_page.error_message_network_error":"नेटवर्क त्रुटि। कृपया अपना इंटरनेट कनेक्शन जांचें।","error_page.error_message_error_charging_payment":"भुगतान विफल।","error_page.error_message_error_setting_up_purchase":"किसी त्रुटि के कारण खरीदारी शुरू नहीं हुई (त्रुटि कोड: {{errorCode}})।","error_page.error_message_invalid_tax_location":"हम आपके बिलिंग पते को सत्यापित नहीं कर सके। कृपया सुनिश्चित करें कि पिन कोड और देश सही हैं।","error_page.error_message_unknown_error":"एक अज्ञात त्रुटि हुई (त्रुटि कोड: {{errorCode}})।","error_page.button_try_again":"फिर से कोशिश करें","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% छूट","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"आज देय कुल राशि","product_info.subscribe_to":"सदस्यता लें","navbar_header.details":"विवरण","navbar_header.back_button":"वापस","pricing_dropdown.show_details":"विवरण दिखाएँ","pricing_dropdown.hide_details":"विवरण छिपाएँ","pricing_table.tax":"कर","pricing_table.trial_ends":"{{formattedTrialEndDate}} पर परीक्षण समाप्त होने के बाद","pricing_table.total_due_today":"आज देय कुल","pricing_table.total_excluding_tax":"कर को छोड़कर कुल","pricing_table.enter_billing_address_to_calculate":"गणना करने के लिए बिलिंग पता दर्ज करें","pricing_table.enter_state_or_postal_code_to_calculate":"गणना करने के लिए राज्य या ज़िप कोड दर्ज करें","pricing_table.enter_postal_code_to_calculate":"गणना करने के लिए ज़िप कोड दर्ज करें","error_page.error_message_invalid_email_error":"ईमेल पता {{email}} सत्यापित नहीं किया जा सका. कृपया एक मान्य ईमेल पता प्रदान करें.","payment_entry_page.button_payment_method":"{{paymentMethod}} के साथ {{formattedPrice}} का भुगतान करें","payment_entry_page.button_with_price":"{{formattedPrice}} का भुगतान करें","price_update.title":"मूल्य अपडेट","price_update.base_message":"आप के बिलिंग पते के आधार पर कुल कीमत कर के साथ अपडेट की गई थी। कृपया समीक्षा करें और फिर से प्रयास करें। आपके कार्ड से केवल एक बार शुल्क लिया जाएगा।","price_update.trial_message":"सदस्यता मूल्य आपके बिलिंग पते के आधार पर करों को शामिल करने के लिए अपडेट किया गया है। निःशुल्क परीक्षण अवधि अभी भी लागू है। कृपया जांचें और पुनः प्रयास करें।","payment_entry_page.express_checkout_divider":"या कार्ड से भुगतान करें","error_page.trouble_accessing":"यदि आपको अपनी खरीदारी तक पहुंचने में परेशानी हो रही है, तो पर समर्थन के लिए संपर्क करें","error_page.close_button_title":"{{appName}} पर जाएं","error_page.error_title_stripe_missing_required_permission":"स्ट्राइप अनुमति गुम है","error_page.button_close":"बंद करें","error_page.error_message_stripe_invalid_tax_origin_address":"खरीदारी विफल रही क्योंकि कर उत्पत्ति पता अमान्य है. उत्पादन में, खरीदारी बिना करों के लागू किए काम करेगी.","error_page.error_message_stripe_tax_not_active":"खरीदारी विफल रही क्योंकि स्ट्राइप टैक्स सक्षम नहीं है. उत्पादन में, खरीदारी बिना करों के लागू किए काम करेगी.","error_page.error_only_in_sandbox":"यह संदेश केवल सैंडबॉक्स में दिखाई देता है.","error_page.error_message_stripe_missing_required_permission":"खरीदारी विफल रही क्योंकि स्ट्राइप ऐप में आवश्यक अनुमति नहीं है. उत्पादन में, खरीदारी बिना करों के लागू किए काम करेगी.","error_page.error_title_stripe_tax_not_active":"स्ट्राइप टैक्स सक्रिय नहीं है","error_page.error_title_stripe_invalid_tax_origin_address":"अमान्य कर उत्पत्ति पता","apple_pay.free_trial":"मुफ़्त ट्रायल","product_info.price_after_intro_price":"{{introPriceDuration}} के बाद, {{renewalDate}} पर","product_info.after_trial":"ट्रायल के बाद","product_info.after":"के बाद","product_info.intro_price_phase_after_trial":"फिर {{introPriceDuration}} के लिए {{introPrice}}","product_info.intro_price_phase":"पहले {{introPriceDuration}} के लिए {{introPrice}}","product_info.intro_price_phase_paid_once":"एक बार भुगतान किया गया","payment_entry_page.trial_subscription_terms_info":"आपकी परीक्षण अवधि समाप्त होने के बाद, आपसे {{renewalDate}} से शुरू होकर {{price}} {{perFrequency}} शुल्क लिया जाएगा. आप इस तिथि से पहले कभी भी रद्द कर सकते हैं.","payment_entry_page.subscription_info":"सदस्यता स्वतः नवीनीकृत हो जाती है. कभी भी रद्द करें.","payment_entry_page.otp_terms_info":"खरीदकर, आप {{appName}} को उनकी शर्तों के अनुसार आपसे शुल्क लेने की अनुमति देने के लिए सहमत हैं.","payment_entry_page.subscription_terms_info":"सदस्यता लेकर, आप {{appName}} को रद्द करने तक उनकी शर्तों के अनुसार आपसे शुल्क लेने की अनुमति देने के लिए सहमत हैं."},FFA={"periods.week":"{{amount}} hét","periods.month":"{{amount}} hónap","periods.year":"{{amount}} év","periods.day":"{{amount}} nap","periods.weekShort":"{{amount}}hét","periods.monthShort":"{{amount}}hó","periods.yearShort":"{{amount}}év","periods.dayShort":"{{amount}}n","periods.lifetime":"életre szóló","periods.weekPlural":"{{amount}} hét","periods.monthPlural":"{{amount}} hónap","periods.yearPlural":"{{amount}} év","periods.dayPlural":"{{amount}} nap","periods.weekFrequency":"heti","periods.monthFrequency":"havi","periods.yearFrequency":"éves","periods.dayFrequency":"napi","periods.perWeekFrequency":"hetente","periods.perMonthFrequency":"havonta","periods.perYearFrequency":"évente","periods.perDayFrequency":"naponta","periods.unknownFrequency":"ismeretlen","periods.weekFrequencyPlural":"minden {{amount}} hétben","periods.monthFrequencyPlural":"minden {{amount}} hónapban","periods.yearFrequencyPlural":"minden {{amount}} évben","periods.dayFrequencyPlural":"minden {{amount}} napban","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} próbaidőszak","product_info.price_after_free_trial":"A próbaidőszak vége után, {{renewalDate}}-kor","product_info.renewal_frequency":"{{frequency}} gyakorisággal megújul","product_info.continues_until_cancelled":"Folytatódik, amíg le nem mondják","product_info.cancel_anytime":"Bármikor lemondható","payment_entry_page.payment_step_title":"Biztonságos fizetés a RevenueCat-en keresztül","payment_entry_page.button_pay":"Fizetés most","payment_entry_page.button_start_trial":"Próbaidőszak indítása","success_page.purchase_successful":"Fizetés sikeres","success_page.button_close":"Tovább","error_page.if_error_persists":"Ha a hiba továbbra is fennáll, kérjük, vedd fel a kapcsolatot ","error_page.error_title_already_subscribed":"Már előfizettél a(z) {{productTitle}} termékre","error_page.error_title_already_purchased":"Már megvásároltad a(z) {{productTitle}} terméket","error_page.error_title_other_errors":"Valami hiba történt","error_page.error_message_already_subscribed":"Nem fizethetsz elő újra erre a termékre.","error_page.error_message_already_purchased":"Nem vásárolhatod meg újra ezt a terméket.","error_page.error_message_missing_email_error":"Az email cím szükséges a vásárlás befejezéséhez.","error_page.error_message_network_error":"Hálózati hiba. Kérjük, ellenőrizd az internetkapcsolatodat.","error_page.error_message_error_charging_payment":"A fizetés sikertelen volt.","error_page.error_message_error_setting_up_purchase":"Hiba miatt nem indult el a vásárlás (hibakód: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Nem tudtuk ellenőrizni a számlázási címét. Kérjük, ellenőrizze, hogy az irányítószám és az ország helyes-e.","error_page.error_message_unknown_error":"Ismeretlen hiba történt (hibakód: {{errorCode}}).","error_page.button_try_again":"Újrapróbálkozás","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% kedvezmény","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Ma fizetendő összesen","product_info.subscribe_to":"Feliratkozás erre:","navbar_header.details":"Részletek","navbar_header.back_button":"Vissza","pricing_dropdown.show_details":"Részletek mutatása","pricing_dropdown.hide_details":"Részletek elrejtése","pricing_table.tax":"Adó","pricing_table.trial_ends":"A próbaidőszak vége: {{formattedTrialEndDate}}","pricing_table.total_due_today":"Ma fizetendő összeg","pricing_table.total_excluding_tax":"Összesen adó nélkül","pricing_table.enter_billing_address_to_calculate":"Adja meg a számlázási címet a számításhoz","pricing_table.enter_state_or_postal_code_to_calculate":"Adja meg az államot vagy az irányítószámot a számításhoz","pricing_table.enter_postal_code_to_calculate":"Adja meg az irányítószámot a számításhoz","error_page.error_message_invalid_email_error":"A(z) {{email}} e-mail címet nem sikerült ellenőrizni. Kérjük, adj meg egy érvényes e-mail címet.","payment_entry_page.button_payment_method":"Fizetés {{formattedPrice}} összeggel a következővel: {{paymentMethod}}","payment_entry_page.button_with_price":"Fizetés {{formattedPrice}}","price_update.title":"Ár frissítése","price_update.base_message":"A teljes ár frissítve lett az adóval a számlázási címed alapján. Kérjük, tekintsd át és próbáld újra. A kártyádat csak egyszer terheljük meg.","price_update.trial_message":"Az előfizetés ára adókkal együtt frissítésre került a számlázási címének megfelelően. Az ingyenes próbaidőszak továbbra is érvényes. Kérjük, ellenőrizze és próbálja újra.","payment_entry_page.express_checkout_divider":"VAGY FIZESSEN KÁRTYÁVAL","error_page.trouble_accessing":"Ha problémái vannak a vásárláshoz való hozzáféréssel, forduljon az ügyfélszolgálathoz a következő címen: ","error_page.close_button_title":"Ugrás a(z) {{appName}} alkalmazáshoz","error_page.error_title_stripe_missing_required_permission":"Hiányzó Stripe engedély","error_page.button_close":"Bezárás","error_page.error_message_stripe_invalid_tax_origin_address":"A vásárlás sikertelen volt, mert az adókiindulási cím érvénytelen. Éles környezetben a vásárlások adók alkalmazása nélkül fognak működni.","error_page.error_message_stripe_tax_not_active":"A vásárlás sikertelen volt, mert a Stripe adó nincs engedélyezve. Éles környezetben a vásárlások adók alkalmazása nélkül fognak működni.","error_page.error_only_in_sandbox":"Ez az üzenet csak a tesztkörnyezetben jelenik meg.","error_page.error_message_stripe_missing_required_permission":"A vásárlás sikertelen volt, mert a Stripe alkalmazásból hiányzik egy szükséges engedély. Éles környezetben a vásárlások adók alkalmazása nélkül fognak működni.","error_page.error_title_stripe_tax_not_active":"A Stripe adó nincs aktiválva","error_page.error_title_stripe_invalid_tax_origin_address":"Érvénytelen adókiindulási cím","apple_pay.free_trial":"Ingyenes próbaidőszak","product_info.price_after_intro_price":"{{introPriceDuration}} után, {{renewalDate}} napján","product_info.after_trial":"próbaidőszak után","product_info.after":"utána","product_info.intro_price_phase_after_trial":"Ezután {{introPriceDuration}} ideig {{introPrice}} áron","product_info.intro_price_phase":"Először {{introPriceDuration}} ideig {{introPrice}} áron","product_info.intro_price_phase_paid_once":"egyszeri fizetéssel","payment_entry_page.trial_subscription_terms_info":"A próbaidőszak vége után {{price}} összeget számítunk fel {{perFrequency}} gyakorisággal, kezdve {{renewalDate}} dátummal. Ezt a dátumot megelőzően bármikor lemondhatod.","payment_entry_page.subscription_info":"Az előfizetés automatikusan megújul. Bármikor lemondhatod.","payment_entry_page.otp_terms_info":"A vásárlással elfogadod, hogy a {{appName}} az általa meghatározott feltételek szerint terheljen.","payment_entry_page.subscription_terms_info":"A feliratkozással elfogadod, hogy a {{appName}} az általa meghatározott feltételek szerint terheljen, amíg le nem mondod."},_FA={"periods.week":"{{amount}} minggu","periods.month":"{{amount}} bulan","periods.year":"{{amount}} tahun","periods.day":"{{amount}} hari","periods.weekShort":"{{amount}}mg","periods.monthShort":"{{amount}}bl","periods.yearShort":"{{amount}}th","periods.dayShort":"{{amount}}h","periods.lifetime":"seumur hidup","periods.weekPlural":"{{amount}} minggu","periods.monthPlural":"{{amount}} bulan","periods.yearPlural":"{{amount}} tahun","periods.dayPlural":"{{amount}} hari","periods.weekFrequency":"mingguan","periods.monthFrequency":"bulanan","periods.yearFrequency":"tahunan","periods.dayFrequency":"harian","periods.perWeekFrequency":"per minggu","periods.perMonthFrequency":"per bulan","periods.perYearFrequency":"per tahun","periods.perDayFrequency":"per hari","periods.unknownFrequency":"tidak diketahui","periods.weekFrequencyPlural":"setiap {{amount}} minggu","periods.monthFrequencyPlural":"setiap {{amount}} bulan","periods.yearFrequencyPlural":"setiap {{amount}} tahun","periods.dayFrequencyPlural":"setiap {{amount}} hari","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} uji coba gratis","product_info.price_after_free_trial":"Setelah uji coba berakhir, pada {{renewalDate}}","product_info.renewal_frequency":"Diperbarui {{frequency}}","product_info.continues_until_cancelled":"Berlanjut hingga dibatalkan","product_info.cancel_anytime":"Batalkan kapan saja","payment_entry_page.payment_step_title":"Pembayaran aman oleh RevenueCat","payment_entry_page.button_pay":"Bayar sekarang","payment_entry_page.button_start_trial":"Mulai Uji Coba","success_page.purchase_successful":"Pembayaran selesai","success_page.button_close":"Lanjutkan","error_page.if_error_persists":"Jika kesalahan berlanjut, silakan hubungi ","error_page.error_title_already_subscribed":"Anda sudah berlangganan ke {{productTitle}}","error_page.error_title_already_purchased":"Anda sudah membeli {{productTitle}}","error_page.error_title_other_errors":"Terjadi kesalahan","error_page.error_message_already_subscribed":"Anda tidak dapat berlangganan produk ini lagi.","error_page.error_message_already_purchased":"Anda tidak dapat membeli produk ini lagi.","error_page.error_message_missing_email_error":"Email diperlukan untuk menyelesaikan pembelian.","error_page.error_message_network_error":"Kesalahan jaringan. Periksa koneksi internet Anda.","error_page.error_message_error_charging_payment":"Pembayaran gagal.","error_page.error_message_error_setting_up_purchase":"Pembelian tidak dimulai karena kesalahan (kode kesalahan: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Kami tidak dapat memverifikasi alamat penagihan Anda. Harap periksa kembali kode pos dan negara untuk memastikan keduanya benar.","error_page.error_message_unknown_error":"Terjadi kesalahan yang tidak diketahui (kode kesalahan: {{errorCode}}).","error_page.button_try_again":"Coba lagi","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% diskon","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Total yang harus dibayar hari ini","product_info.subscribe_to":"Berlangganan ke","navbar_header.details":"Detail","navbar_header.back_button":"Kembali","pricing_dropdown.show_details":"Tampilkan detail","pricing_dropdown.hide_details":"Sembunyikan detail","pricing_table.tax":"Pajak","pricing_table.trial_ends":"Setelah masa percobaan berakhir, pada {{formattedTrialEndDate}}","pricing_table.total_due_today":"Total yang harus dibayar hari ini","pricing_table.total_excluding_tax":"Total belum termasuk pajak","pricing_table.enter_billing_address_to_calculate":"Masukkan alamat penagihan untuk menghitung","pricing_table.enter_state_or_postal_code_to_calculate":"Masukkan negara bagian atau kode pos untuk menghitung","pricing_table.enter_postal_code_to_calculate":"Masukkan kode pos untuk menghitung","error_page.error_message_invalid_email_error":"Alamat email {{email}} tidak dapat diverifikasi. Harap berikan alamat email yang valid.","payment_entry_page.button_payment_method":"Bayar {{formattedPrice}} dengan {{paymentMethod}}","payment_entry_page.button_with_price":"Bayar {{formattedPrice}}","price_update.title":"Pembaruan harga","price_update.base_message":"Total harga telah diperbarui dengan pajak berdasarkan alamat penagihan Anda. Harap tinjau dan coba lagi. Kartu Anda hanya akan dikenakan biaya sekali.","price_update.trial_message":"Harga langganan telah diperbarui untuk menyertakan pajak berdasarkan alamat penagihan Anda. Masa percobaan gratis masih berlaku. Silakan periksa dan coba lagi.","payment_entry_page.express_checkout_divider":"ATAU BAYAR DENGAN KARTU","error_page.trouble_accessing":"Jika Anda mengalami masalah dalam mengakses pembelian, hubungi dukungan di ","error_page.close_button_title":"Pergi ke {{appName}}","error_page.error_title_stripe_missing_required_permission":"Izin Stripe tidak ada","error_page.button_close":"Tutup","error_page.error_message_stripe_invalid_tax_origin_address":"Pembelian gagal karena alamat asal pajak tidak valid. Dalam produksi, pembelian akan berfungsi tanpa pajak yang diterapkan.","error_page.error_message_stripe_tax_not_active":"Pembelian gagal karena Stripe Tax tidak diaktifkan. Dalam produksi, pembelian akan berfungsi tanpa pajak yang diterapkan.","error_page.error_only_in_sandbox":"Pesan ini hanya muncul di sandbox.","error_page.error_message_stripe_missing_required_permission":"Pembelian gagal karena aplikasi Stripe tidak memiliki izin yang diperlukan. Dalam produksi, pembelian akan berfungsi tanpa pajak yang diterapkan.","error_page.error_title_stripe_tax_not_active":"Stripe Tax tidak aktif","error_page.error_title_stripe_invalid_tax_origin_address":"Alamat asal pajak tidak valid","apple_pay.free_trial":"Uji Coba Gratis","product_info.price_after_intro_price":"Setelah {{introPriceDuration}}, pada {{renewalDate}}","product_info.after_trial":"setelah uji coba","product_info.after":"setelah","product_info.intro_price_phase_after_trial":"Kemudian {{introPriceDuration}} dengan harga {{introPrice}}","product_info.intro_price_phase":"Pertama {{introPriceDuration}} dengan harga {{introPrice}}","product_info.intro_price_phase_paid_once":"dibayar sekali","payment_entry_page.trial_subscription_terms_info":"Setelah masa percobaan Anda berakhir, Anda akan dikenakan biaya sebesar {{price}} {{perFrequency}} mulai {{renewalDate}}. Anda dapat membatalkan kapan saja sebelum tanggal ini.","payment_entry_page.subscription_info":"Langganan diperpanjang secara otomatis. Batalkan kapan saja.","payment_entry_page.otp_terms_info":"Dengan membeli, Anda setuju untuk mengizinkan {{appName}} menagih Anda sesuai dengan ketentuan mereka.","payment_entry_page.subscription_terms_info":"Dengan berlangganan, Anda setuju untuk mengizinkan {{appName}} mengenakan biaya sesuai dengan ketentuan mereka hingga Anda membatalkan."},JFA={"periods.week":"{{amount}}週間","periods.month":"{{amount}}ヶ月","periods.year":"{{amount}}年","periods.day":"{{amount}}日","periods.weekShort":"{{amount}}週","periods.monthShort":"{{amount}}ヶ月","periods.yearShort":"{{amount}}年","periods.dayShort":"{{amount}}日","periods.lifetime":"生涯","periods.weekPlural":"{{amount}}週間","periods.monthPlural":"{{amount}}ヶ月","periods.yearPlural":"{{amount}}年","periods.dayPlural":"{{amount}}日","periods.weekFrequency":"毎週","periods.monthFrequency":"毎月","periods.yearFrequency":"毎年","periods.dayFrequency":"毎日","periods.perWeekFrequency":"週ごと","periods.perMonthFrequency":"月ごと","periods.perYearFrequency":"年ごと","periods.perDayFrequency":"日ごと","periods.unknownFrequency":"不明","periods.weekFrequencyPlural":"{{amount}}週間ごと","periods.monthFrequencyPlural":"{{amount}}ヶ月ごと","periods.yearFrequencyPlural":"{{amount}}年ごと","periods.dayFrequencyPlural":"{{amount}}日ごと","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}}日間無料トライアル","product_info.price_after_free_trial":"トライアル終了後、{{renewalDate}}に","product_info.renewal_frequency":"{{frequency}}で更新","product_info.continues_until_cancelled":"キャンセルされるまで継続されます","product_info.cancel_anytime":"いつでもキャンセルできます","payment_entry_page.payment_step_title":"RevenueCatによる安全なチェックアウト","payment_entry_page.button_pay":"今すぐ支払う","payment_entry_page.button_start_trial":"トライアルを開始","success_page.purchase_successful":"支払いが完了しました","success_page.button_close":"続行","error_page.if_error_persists":"エラーが続く場合は、ご連絡ください。","error_page.error_title_already_subscribed":"すでに{{productTitle}}を購読しています","error_page.error_title_already_purchased":"すでに{{productTitle}}を購入しています","error_page.error_title_other_errors":"エラーが発生しました","error_page.error_message_already_subscribed":"この商品を再度購読することはできません。","error_page.error_message_already_purchased":"この商品を再度購入することはできません。","error_page.error_message_missing_email_error":"購入を完了するにはメールアドレスが必要です。","error_page.error_message_network_error":"ネットワークエラーです。インターネット接続を確認してください。","error_page.error_message_error_charging_payment":"支払いに失敗しました。","error_page.error_message_error_setting_up_purchase":"エラーが発生したため、購入を開始できませんでした（エラーコード：{{errorCode}}）。","error_page.error_message_invalid_tax_location":"請求先住所を確認できませんでした。郵便番号と国が正しいかご確認ください。","error_page.error_message_unknown_error":"不明なエラーが発生しました（エラーコード：{{errorCode}}）。","error_page.button_try_again":"再試行","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}%オフ","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"本日のお支払い合計","product_info.subscribe_to":"購読する","navbar_header.details":"詳細","navbar_header.back_button":"戻る","pricing_dropdown.show_details":"詳細を表示","pricing_dropdown.hide_details":"詳細を隠す","pricing_table.tax":"税金","pricing_table.trial_ends":"トライアル終了後、{{formattedTrialEndDate}}","pricing_table.total_due_today":"本日お支払いいただく合計金額","pricing_table.total_excluding_tax":"税抜き合計","pricing_table.enter_billing_address_to_calculate":"請求先住所を入力して計算","pricing_table.enter_state_or_postal_code_to_calculate":"計算するには州または郵便番号を入力してください","pricing_table.enter_postal_code_to_calculate":"計算するには郵便番号を入力してください","error_page.error_message_invalid_email_error":"メールアドレス{{email}}を確認できませんでした。有効なメールアドレスを入力してください。","payment_entry_page.button_payment_method":"{{paymentMethod}}で{{formattedPrice}}を支払う","payment_entry_page.button_with_price":"{{formattedPrice}}を支払う","price_update.title":"価格の更新","price_update.base_message":"合計金額が、お客様の請求先住所に基づいて税金とともに更新されました。再度ご確認ください。カードへの請求は1回のみです。","price_update.trial_message":"請求先住所に基づいて税金を含むサブスクリプション料金が更新されました。無料トライアルは引き続き適用されます。確認して再度お試しください。","payment_entry_page.express_checkout_divider":"カードで支払う","error_page.trouble_accessing":"購入へのアクセスに問題がある場合は、サポートにお問い合わせください: ","error_page.close_button_title":"{{appName}} に移動","error_page.error_title_stripe_missing_required_permission":"必要なStripeの権限がありません","error_page.button_close":"閉じる","error_page.error_message_stripe_invalid_tax_origin_address":"税の原産地住所が無効なため、購入に失敗しました。 本番環境では、税金が適用されなくても購入は可能です。","error_page.error_message_stripe_tax_not_active":"Stripe Taxが有効になっていないため、購入に失敗しました。 本番環境では、税金が適用されなくても購入は可能です。","error_page.error_only_in_sandbox":"このメッセージはサンドボックスでのみ表示されます。","error_page.error_message_stripe_missing_required_permission":"Stripeアプリに必要な権限がないため、購入に失敗しました。 本番環境では、税金が適用されなくても購入は可能です。","error_page.error_title_stripe_tax_not_active":"Stripe Taxが有効ではありません","error_page.error_title_stripe_invalid_tax_origin_address":"税の原産地住所が無効です","apple_pay.free_trial":"無料トライアル","product_info.price_after_intro_price":"{{introPriceDuration}}の後、{{renewalDate}}に","product_info.after_trial":"トライアル後","product_info.after":"後","product_info.intro_price_phase_after_trial":"その後、{{introPriceDuration}}間は{{introPrice}}","product_info.intro_price_phase":"最初の{{introPriceDuration}}間は{{introPrice}}","product_info.intro_price_phase_paid_once":"一回払い","payment_entry_page.trial_subscription_terms_info":"トライアル期間が終了すると、{{renewalDate}}から{{price}} {{perFrequency}}が課金されます。この日より前にいつでもキャンセルできます。","payment_entry_page.subscription_info":"サブスクリプションは自動的に更新されます。いつでもキャンセルできます。","payment_entry_page.otp_terms_info":"購入することにより、{{appName}}が利用規約に基づいて料金を請求することに同意したことになります。","payment_entry_page.subscription_terms_info":"サブスクリプションに登録すると、キャンセルするまで{{appName}}が利用規約に従って課金することを許可することに同意したことになります。"},LFA={"periods.week":"{{amount}}주","periods.month":"{{amount}}개월","periods.year":"{{amount}}년","periods.day":"{{amount}}일","periods.weekShort":"{{amount}}주","periods.monthShort":"{{amount}}개월","periods.yearShort":"{{amount}}년","periods.dayShort":"{{amount}}일","periods.lifetime":"평생","periods.weekPlural":"{{amount}}주","periods.monthPlural":"{{amount}}개월","periods.yearPlural":"{{amount}}년","periods.dayPlural":"{{amount}}일","periods.weekFrequency":"매주","periods.monthFrequency":"매달","periods.yearFrequency":"매년","periods.dayFrequency":"매일","periods.perWeekFrequency":"주당","periods.perMonthFrequency":"월별","periods.perYearFrequency":"연간","periods.perDayFrequency":"매일","periods.unknownFrequency":"알 수 없음","periods.weekFrequencyPlural":"{{amount}}주마다","periods.monthFrequencyPlural":"{{amount}}개월마다","periods.yearFrequencyPlural":"{{amount}}년마다","periods.dayFrequencyPlural":"{{amount}}일마다","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}}일 무료 체험","product_info.price_after_free_trial":"체험 종료 후, {{renewalDate}}에","product_info.renewal_frequency":"{{frequency}}마다 갱신","product_info.continues_until_cancelled":"취소될 때까지 계속됩니다.","product_info.cancel_anytime":"언제든지 취소 가능","payment_entry_page.payment_step_title":"RevenueCat을 통한 안전한 결제","payment_entry_page.button_pay":"지금 결제","payment_entry_page.button_start_trial":"체험 시작","success_page.purchase_successful":"결제가 완료되었습니다.","success_page.button_close":"계속","error_page.if_error_persists":"오류가 지속되면 다음으로 문의하십시오.","error_page.error_title_already_subscribed":"이미 {{productTitle}}을 구독하셨습니다","error_page.error_title_already_purchased":"이미 {{productTitle}}을 구매하셨습니다","error_page.error_title_other_errors":"문제가 발생했습니다.","error_page.error_message_already_subscribed":"이 제품을 다시 구독할 수 없습니다.","error_page.error_message_already_purchased":"이 제품을 다시 구매할 수 없습니다.","error_page.error_message_missing_email_error":"구매를 완료하려면 이메일이 필요합니다.","error_page.error_message_network_error":"네트워크 오류입니다. 인터넷 연결을 확인하십시오.","error_page.error_message_error_charging_payment":"결제에 실패했습니다.","error_page.error_message_error_setting_up_purchase":"오류로 인해 구매가 시작되지 않았습니다(오류 코드: {{errorCode}}).","error_page.error_message_invalid_tax_location":"청구 주소를 확인할 수 없습니다. 우편번호와 국가가 정확한지 다시 한번 확인해 주세요.","error_page.error_message_unknown_error":"알 수 없는 오류가 발생했습니다(오류 코드: {{errorCode}}).","error_page.button_try_again":"다시 시도","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% 할인","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"오늘 총 결제 금액","product_info.subscribe_to":"구독하기","navbar_header.details":"세부 정보","navbar_header.back_button":"뒤로","pricing_dropdown.show_details":"세부 정보 표시","pricing_dropdown.hide_details":"세부 정보 숨기기","pricing_table.tax":"세금","pricing_table.trial_ends":"체험판 종료 후, {{formattedTrialEndDate}}","pricing_table.total_due_today":"오늘 지불해야 할 총액","pricing_table.total_excluding_tax":"세금 제외 총액","pricing_table.enter_billing_address_to_calculate":"계산을 위해 청구지 주소를 입력하세요","pricing_table.enter_state_or_postal_code_to_calculate":"주 또는 우편 번호를 입력하여 계산","pricing_table.enter_postal_code_to_calculate":"우편 번호를 입력하여 계산","error_page.error_message_invalid_email_error":"이메일 주소 {{email}}을(를) 확인할 수 없습니다. 유효한 이메일 주소를 제공해 주세요.","payment_entry_page.button_payment_method":"{{paymentMethod}}으로 {{formattedPrice}} 결제","payment_entry_page.button_with_price":"{{formattedPrice}} 결제","price_update.title":"가격 업데이트","price_update.base_message":"청구지 주소를 기준으로 세금이 포함된 총 가격이 업데이트되었습니다. 다시 확인하고 시도해 주세요. 카드는 한 번만 청구됩니다.","price_update.trial_message":"청구 주소에 따라 세금이 포함된 구독 가격이 업데이트되었습니다. 무료 체험은 계속 적용됩니다. 확인하고 다시 시도해 주세요.","payment_entry_page.express_checkout_divider":"또는 카드 결제","error_page.trouble_accessing":"구매에 문제가 있는 경우 다음 주소로 지원팀에 문의하세요. ","error_page.close_button_title":"{{appName}}으로 이동","error_page.error_title_stripe_missing_required_permission":"필수 Stripe 권한 누락","error_page.button_close":"닫기","error_page.error_message_stripe_invalid_tax_origin_address":"세금 원산지 주소가 잘못되어 구매에 실패했습니다. 프로덕션 환경에서는 세금이 적용되지 않은 상태로 구매가 진행됩니다.","error_page.error_message_stripe_tax_not_active":"Stripe Tax가 활성화되지 않아 구매에 실패했습니다. 프로덕션 환경에서는 세금이 적용되지 않은 상태로 구매가 진행됩니다.","error_page.error_only_in_sandbox":"이 메시지는 샌드박스에서만 표시됩니다.","error_page.error_message_stripe_missing_required_permission":"Stripe 앱에 필요한 권한이 없어 구매에 실패했습니다. 프로덕션 환경에서는 세금이 적용되지 않은 상태로 구매가 진행됩니다.","error_page.error_title_stripe_tax_not_active":"Stripe Tax가 활성화되지 않음","error_page.error_title_stripe_invalid_tax_origin_address":"잘못된 세금 원산지 주소","apple_pay.free_trial":"무료 체험","product_info.price_after_intro_price":"{{introPriceDuration}} 후 {{renewalDate}}에","product_info.after_trial":"체험 후","product_info.after":"후","product_info.intro_price_phase_after_trial":"다음 {{introPriceDuration}} 동안 {{introPrice}}","product_info.intro_price_phase":"처음 {{introPriceDuration}} 동안 {{introPrice}}","product_info.intro_price_phase_paid_once":"1회 결제","payment_entry_page.trial_subscription_terms_info":"체험 기간이 종료되면 {{renewalDate}}부터 {{price}} {{perFrequency}}가 청구됩니다. 이 날짜 전에는 언제든지 취소할 수 있습니다.","payment_entry_page.subscription_info":"구독은 자동으로 갱신됩니다. 언제든지 취소할 수 있습니다.","payment_entry_page.otp_terms_info":"구매하시면 {{appName}}의 약관에 따라 요금이 청구되는 것에 동의하는 것입니다.","payment_entry_page.subscription_terms_info":"구독하면 취소할 때까지 {{appName}}이 약관에 따라 요금을 청구하는 데 동의하는 것입니다."},xFA={"periods.week":"{{amount}} minggu","periods.month":"{{amount}} bulan","periods.year":"{{amount}} tahun","periods.day":"{{amount}} hari","periods.weekShort":"{{amount}}mg","periods.monthShort":"{{amount}}bl","periods.yearShort":"{{amount}}th","periods.dayShort":"{{amount}}h","periods.lifetime":"seumur hidup","periods.weekPlural":"{{amount}} minggu","periods.monthPlural":"{{amount}} bulan","periods.yearPlural":"{{amount}} tahun","periods.dayPlural":"{{amount}} hari","periods.weekFrequency":"mingguan","periods.monthFrequency":"bulanan","periods.yearFrequency":"tahunan","periods.dayFrequency":"harian","periods.perWeekFrequency":"setiap minggu","periods.perMonthFrequency":"setiap bulan","periods.perYearFrequency":"setiap tahun","periods.perDayFrequency":"setiap hari","periods.unknownFrequency":"tidak diketahui","periods.weekFrequencyPlural":"setiap {{amount}} minggu","periods.monthFrequencyPlural":"setiap {{amount}} bulan","periods.yearFrequencyPlural":"setiap {{amount}} tahun","periods.dayFrequencyPlural":"setiap {{amount}} hari","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} percubaan percuma","product_info.price_after_free_trial":"Selepas tamat percubaan, pada {{renewalDate}}","product_info.renewal_frequency":"Diperbaharui {{frequency}}","product_info.continues_until_cancelled":"Berterusan sehingga dibatalkan","product_info.cancel_anytime":"Batal bila-bila masa","payment_entry_page.payment_step_title":"Pembayaran selamat oleh RevenueCat","payment_entry_page.button_pay":"Bayar sekarang","payment_entry_page.button_start_trial":"Mula Percubaan","success_page.purchase_successful":"Pembayaran selesai","success_page.button_close":"Teruskan","error_page.if_error_persists":"Jika ralat berterusan, sila hubungi ","error_page.error_title_already_subscribed":"Anda sudah melanggan {{productTitle}}","error_page.error_title_already_purchased":"Anda sudah membeli {{productTitle}}","error_page.error_title_other_errors":"Ada sesuatu yang tidak kena","error_page.error_message_already_subscribed":"Anda tidak boleh melanggan produk ini lagi.","error_page.error_message_already_purchased":"Anda tidak boleh membeli produk ini lagi.","error_page.error_message_missing_email_error":"Emel diperlukan untuk menyelesaikan pembelian.","error_page.error_message_network_error":"Ralat rangkaian. Sila semak sambungan internet anda.","error_page.error_message_error_charging_payment":"Pembayaran gagal.","error_page.error_message_error_setting_up_purchase":"Pembelian tidak dimulakan disebabkan ralat (kod ralat: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Kami tidak dapat mengesahkan alamat bil anda. Sila semak sama ada poskod dan negara adalah betul.","error_page.error_message_unknown_error":"Ralat yang tidak diketahui telah berlaku (kod ralat: {{errorCode}}).","error_page.button_try_again":"Cuba lagi","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% diskaun","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Jumlah yang perlu dibayar hari ini","product_info.subscribe_to":"Langgan","navbar_header.details":"Butiran","navbar_header.back_button":"Kembali","pricing_dropdown.show_details":"Tunjukkan butiran","pricing_dropdown.hide_details":"Sembunyikan butiran","pricing_table.tax":"Cukai","pricing_table.trial_ends":"Selepas tempoh percubaan tamat, pada {{formattedTrialEndDate}}","pricing_table.total_due_today":"Jumlah yang perlu dibayar hari ini","pricing_table.total_excluding_tax":"Jumlah tidak termasuk cukai","pricing_table.enter_billing_address_to_calculate":"Masukkan alamat pengebilan untuk mengira","pricing_table.enter_state_or_postal_code_to_calculate":"Masukkan negeri atau poskod untuk mengira","pricing_table.enter_postal_code_to_calculate":"Masukkan poskod untuk mengira","error_page.error_message_invalid_email_error":"Alamat e-mel {{email}} tidak dapat disahkan. Sila berikan alamat e-mel yang sah.","payment_entry_page.button_payment_method":"Bayar {{formattedPrice}} dengan {{paymentMethod}}","payment_entry_page.button_with_price":"Bayar {{formattedPrice}}","price_update.title":"Kemaskini harga","price_update.base_message":"Jumlah harga telah dikemas kini dengan cukai berdasarkan alamat pengebilan anda. Sila semak dan cuba lagi. Kad anda hanya akan dicaj sekali.","price_update.trial_message":"Harga langganan telah dikemas kini untuk memasukkan cukai berdasarkan alamat bil anda. Tempoh percubaan percuma masih terpakai. Sila semak dan cuba lagi.","payment_entry_page.express_checkout_divider":"ATAU BAYAR DENGAN KAD","error_page.trouble_accessing":"Jika anda menghadapi masalah untuk mengakses pembelian anda, hubungi sokongan di ","error_page.close_button_title":"Pergi ke {{appName}}","error_page.error_title_stripe_missing_required_permission":"Kebenaran Stripe hilang","error_page.button_close":"Tutup","error_page.error_message_stripe_invalid_tax_origin_address":"Pembelian gagal kerana alamat asal cukai tidak sah. Dalam pengeluaran, pembelian akan berfungsi tanpa cukai dikenakan.","error_page.error_message_stripe_tax_not_active":"Pembelian gagal kerana Cukai Stripe tidak didayakan. Dalam pengeluaran, pembelian akan berfungsi tanpa cukai dikenakan.","error_page.error_only_in_sandbox":"Mesej ini hanya muncul dalam kotak pasir.","error_page.error_message_stripe_missing_required_permission":"Pembelian gagal kerana aplikasi Stripe kekurangan kebenaran yang diperlukan. Dalam pengeluaran, pembelian akan berfungsi tanpa cukai dikenakan.","error_page.error_title_stripe_tax_not_active":"Cukai Stripe tidak aktif","error_page.error_title_stripe_invalid_tax_origin_address":"Alamat asal cukai Stripe tidak sah","apple_pay.free_trial":"Percubaan Percuma","product_info.price_after_intro_price":"Selepas {{introPriceDuration}}, pada {{renewalDate}}","product_info.after_trial":"selepas percubaan","product_info.after":"selepas","product_info.intro_price_phase_after_trial":"Kemudian {{introPriceDuration}} untuk {{introPrice}}","product_info.intro_price_phase":"Pertama {{introPriceDuration}} untuk {{introPrice}}","product_info.intro_price_phase_paid_once":"dibayar sekali","payment_entry_page.trial_subscription_terms_info":"Selepas tempoh percubaan anda tamat, anda akan dikenakan bayaran sebanyak {{price}} {{perFrequency}} bermula {{renewalDate}}. Anda boleh membatalkan pada bila-bila masa sebelum tarikh ini.","payment_entry_page.subscription_info":"Langganan diperbaharui secara automatik. Batalkan bila-bila masa.","payment_entry_page.otp_terms_info":"Dengan membuat pembelian, anda bersetuju untuk membenarkan {{appName}} mengenakan bayaran kepada anda mengikut terma mereka.","payment_entry_page.subscription_terms_info":"Dengan melanggan, anda bersetuju untuk membenarkan {{appName}} mengenakan bayaran kepada anda mengikut terma mereka sehingga anda membatalkan."},TFA={"periods.week":"{{amount}} uke","periods.month":"{{amount}} måned","periods.year":"{{amount}} år","periods.day":"{{amount}} dag","periods.weekShort":"{{amount}}uk","periods.monthShort":"{{amount}}md","periods.yearShort":"{{amount}}år","periods.dayShort":"{{amount}}d","periods.lifetime":"livstid","periods.weekPlural":"{{amount}} uker","periods.monthPlural":"{{amount}} måneder","periods.yearPlural":"{{amount}} år","periods.dayPlural":"{{amount}} dager","periods.weekFrequency":"ukentlig","periods.monthFrequency":"månedlig","periods.yearFrequency":"årlig","periods.dayFrequency":"daglig","periods.perWeekFrequency":"per uke","periods.perMonthFrequency":"per måned","periods.perYearFrequency":"per år","periods.perDayFrequency":"per dag","periods.unknownFrequency":"ukjent","periods.weekFrequencyPlural":"hver {{amount}} uker","periods.monthFrequencyPlural":"hver {{amount}} måneder","periods.yearFrequencyPlural":"hver {{amount}} år","periods.dayFrequencyPlural":"hver {{amount}} dager","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} gratis prøveperiode","product_info.price_after_free_trial":"Etter prøveperioden slutter, den {{renewalDate}}","product_info.renewal_frequency":"Fornyes {{frequency}}","product_info.continues_until_cancelled":"Varer til den avbestilles","product_info.cancel_anytime":"Avbestille når som helst","payment_entry_page.payment_step_title":"Sikker betaling via RevenueCat","payment_entry_page.button_pay":"Betal nå","payment_entry_page.button_start_trial":"Start prøveperiode","success_page.purchase_successful":"Betalingen er fullført","success_page.button_close":"Fortsett","error_page.if_error_persists":"Hvis feilen vedvarer, vennligst kontakt ","error_page.error_title_already_subscribed":"Du abonnerer allerede på {{productTitle}}","error_page.error_title_already_purchased":"Du har allerede kjøpt {{productTitle}}","error_page.error_title_other_errors":"Noe gikk galt","error_page.error_message_already_subscribed":"Du kan ikke abonnere på dette produktet igjen.","error_page.error_message_already_purchased":"Du kan ikke kjøpe dette produktet igjen.","error_page.error_message_missing_email_error":"E-post er nødvendig for å fullføre kjøpet.","error_page.error_message_network_error":"Nettverksfeil. Vennligst sjekk internettforbindelsen din.","error_page.error_message_error_charging_payment":"Betalingen mislyktes.","error_page.error_message_error_setting_up_purchase":"Kjøpet ble ikke startet på grunn av en feil (feilkode: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Vi kunne ikke bekrefte faktureringsadressen din. Vennligst sjekk at postnummeret og landet er korrekte.","error_page.error_message_unknown_error":"En ukjent feil oppstod (feilkode: {{errorCode}}).","error_page.button_try_again":"Prøv igjen","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% rabatt","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}} ({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Totalt forfaller i dag","product_info.subscribe_to":"Abonner på","navbar_header.details":"Detaljer","navbar_header.back_button":"Tilbake","pricing_dropdown.show_details":"Vis detaljer","pricing_dropdown.hide_details":"Skjul detaljer","pricing_table.tax":"Skatt","pricing_table.trial_ends":"Etter prøveperioden slutter, den {{formattedTrialEndDate}}","pricing_table.total_due_today":"Totalt forfaller i dag","pricing_table.total_excluding_tax":"Total eksklusive skatt","pricing_table.enter_billing_address_to_calculate":"Oppgi faktureringsadresse for å beregne","pricing_table.enter_state_or_postal_code_to_calculate":"Skriv inn stat eller postnummer for å beregne","pricing_table.enter_postal_code_to_calculate":"Skriv inn postnummer for å beregne","error_page.error_message_invalid_email_error":"E-postadressen {{email}} kunne ikke bekreftes. Vennligst oppgi en gyldig e-postadresse.","payment_entry_page.button_payment_method":"Betal {{formattedPrice}} med {{paymentMethod}}","payment_entry_page.button_with_price":"Betal {{formattedPrice}}","price_update.title":"Prisoppdatering","price_update.base_message":"Totalprisen er oppdatert med skatt basert på fakturaadressen din. Vennligst se gjennom og prøv igjen. Kortet ditt vil kun bli belastet én gang.","price_update.trial_message":"Abonnementsprisen er oppdatert for å inkludere skatter basert på din fakturaadresse. Den gratis prøveperioden gjelder fortsatt. Vennligst sjekk og prøv igjen.","payment_entry_page.express_checkout_divider":"ELLER BETAL MED KORT","error_page.trouble_accessing":"Hvis du har problemer med å få tilgang til kjøpet ditt, kan du kontakte support på ","error_page.close_button_title":"Gå til {{appName}}","error_page.error_title_stripe_missing_required_permission":"Mangler Stripe-tillatelse","error_page.button_close":"Lukk","error_page.error_message_stripe_invalid_tax_origin_address":"Kjøpet mislyktes fordi skatteopprinnelsesadressen er ugyldig. I produksjon vil kjøp fungere uten at skatter brukes.","error_page.error_message_stripe_tax_not_active":"Kjøpet mislyktes fordi Stripe Tax ikke er aktivert. I produksjon vil kjøp fungere uten at skatter brukes.","error_page.error_only_in_sandbox":"Denne meldingen vises bare i sandkassen.","error_page.error_message_stripe_missing_required_permission":"Kjøpet mislyktes fordi Stripe-appen mangler en nødvendig tillatelse. I produksjon vil kjøp fungere uten at skatter brukes.","error_page.error_title_stripe_tax_not_active":"Stripe Tax er ikke aktivt","error_page.error_title_stripe_invalid_tax_origin_address":"Ugyldig skatteopprinnelsesadresse","apple_pay.free_trial":"Gratis prøveperiode","product_info.price_after_intro_price":"Etter {{introPriceDuration}}, den {{renewalDate}}","product_info.after_trial":"etter prøveperiode","product_info.after":"etter","product_info.intro_price_phase_after_trial":"Deretter {{introPriceDuration}} for {{introPrice}}","product_info.intro_price_phase":"Først {{introPriceDuration}} for {{introPrice}}","product_info.intro_price_phase_paid_once":"betales én gang","payment_entry_page.trial_subscription_terms_info":"Etter at prøveperioden din er over, blir du belastet {{price}} {{perFrequency}} fra og med {{renewalDate}}. Du kan kansellere når som helst før denne datoen.","payment_entry_page.subscription_info":"Abonnementet fornyes automatisk. Avbryt når som helst.","payment_entry_page.otp_terms_info":"Ved å kjøpe godtar du at {{appName}} belaster deg i henhold til deres vilkår.","payment_entry_page.subscription_terms_info":"Ved å abonnere godtar du at {{appName}} belaster deg i henhold til deres vilkår til du kansellerer."},qFA={"periods.week":"{{amount}} tydzień","periods.month":"{{amount}} miesiąc","periods.year":"{{amount}} rok","periods.day":"{{amount}} dzień","periods.weekShort":"{{amount}}tydz","periods.monthShort":"{{amount}}mies","periods.yearShort":"{{amount}}rok","periods.dayShort":"{{amount}}d","periods.lifetime":"dożywotnio","periods.weekPlural":"{{amount}} tygodni","periods.monthPlural":"{{amount}} miesięcy","periods.yearPlural":"{{amount}} lat","periods.dayPlural":"{{amount}} dni","periods.weekFrequency":"tygodniowo","periods.monthFrequency":"miesięcznie","periods.yearFrequency":"rocznie","periods.dayFrequency":"dziennie","periods.perWeekFrequency":"na tydzień","periods.perMonthFrequency":"na miesiąc","periods.perYearFrequency":"na rok","periods.perDayFrequency":"na dzień","periods.unknownFrequency":"nieznany","periods.weekFrequencyPlural":"co {{amount}} tygodni","periods.monthFrequencyPlural":"co {{amount}} miesięcy","periods.yearFrequencyPlural":"co {{amount}} lat","periods.dayFrequencyPlural":"co {{amount}} dni","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} dni próbnych","product_info.price_after_free_trial":"Po zakończeniu okresu próbnego, dnia {{renewalDate}}","product_info.renewal_frequency":"Odnawialny co {{frequency}}","product_info.continues_until_cancelled":"Kontynuowane do momentu anulowania","product_info.cancel_anytime":"Możesz anulować w dowolnym momencie","payment_entry_page.payment_step_title":"Bezpieczna płatność przez RevenueCat","payment_entry_page.button_pay":"Zapłać teraz","payment_entry_page.button_start_trial":"Rozpocznij okres próbny","success_page.purchase_successful":"Płatność zakończona","success_page.button_close":"Kontynuuj","error_page.if_error_persists":"Jeśli błąd będzie się powtarzał, skontaktuj się z ","error_page.error_title_already_subscribed":"Już subskrybujesz {{productTitle}}","error_page.error_title_already_purchased":"Już zakupiłeś/aś {{productTitle}}","error_page.error_title_other_errors":"Coś poszło nie tak","error_page.error_message_already_subscribed":"Nie możesz ponownie subskrybować tego produktu.","error_page.error_message_already_purchased":"Nie możesz ponownie zakupić tego produktu.","error_page.error_message_missing_email_error":"Adres e-mail jest wymagany do dokonania zakupu.","error_page.error_message_network_error":"Błąd sieci. Sprawdź połączenie internetowe.","error_page.error_message_error_charging_payment":"Płatność nieudana.","error_page.error_message_error_setting_up_purchase":"Zakup nie został rozpoczęty z powodu błędu (kod błędu: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Nie mogliśmy zweryfikować Twojego adresu rozliczeniowego. Sprawdź, czy kod pocztowy i kraj są poprawne.","error_page.error_message_unknown_error":"Wystąpił nieznany błąd (kod błędu: {{errorCode}}).","error_page.button_try_again":"Spróbuj ponownie","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% zniżki","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Do zapłaty dzisiaj","product_info.subscribe_to":"Subskrybuj","navbar_header.details":"Szczegóły","navbar_header.back_button":"Wstecz","pricing_dropdown.show_details":"Pokaż szczegóły","pricing_dropdown.hide_details":"Ukryj szczegóły","pricing_table.tax":"Podatek","pricing_table.trial_ends":"Po zakończeniu okresu próbnego, {{formattedTrialEndDate}}","pricing_table.total_due_today":"Suma należna dzisiaj","pricing_table.total_excluding_tax":"Suma bez podatku","pricing_table.enter_billing_address_to_calculate":"Wprowadź adres rozliczeniowy, aby obliczyć","pricing_table.enter_state_or_postal_code_to_calculate":"Wprowadź stan lub kod pocztowy, aby obliczyć","pricing_table.enter_postal_code_to_calculate":"Wprowadź kod pocztowy, aby obliczyć","error_page.error_message_invalid_email_error":"Nie można zweryfikować adresu e-mail {{email}}. Proszę podać prawidłowy adres e-mail.","payment_entry_page.button_payment_method":"Zapłać {{formattedPrice}} przez {{paymentMethod}}","payment_entry_page.button_with_price":"Zapłać {{formattedPrice}}","price_update.title":"Aktualizacja ceny","price_update.base_message":"Cena całkowita została zaktualizowana o podatek na podstawie Twojego adresu rozliczeniowego. Sprawdź i spróbuj ponownie. Twoja karta zostanie obciążona tylko raz.","price_update.trial_message":"Cena subskrypcji została zaktualizowana o podatki na podstawie Twojego adresu rozliczeniowego. Okres próbny nadal obowiązuje. Sprawdź i spróbuj ponownie.","payment_entry_page.express_checkout_divider":"LUB ZAPŁAĆ KARTĄ","error_page.trouble_accessing":"Jeśli masz problemy z dostępem do zakupu, skontaktuj się z działem pomocy pod adresem ","error_page.close_button_title":"Przejdź do {{appName}}","error_page.error_title_stripe_missing_required_permission":"Brakujące uprawnienie Stripe","error_page.button_close":"Zamknij","error_page.error_message_stripe_invalid_tax_origin_address":"Zakup nie powiódł się, ponieważ adres pochodzenia podatku jest nieprawidłowy. W środowisku produkcyjnym zakupy będą działać bez naliczania podatków.","error_page.error_message_stripe_tax_not_active":"Zakup nie powiódł się, ponieważ Stripe Tax nie jest włączony. W środowisku produkcyjnym zakupy będą działać bez naliczania podatków.","error_page.error_only_in_sandbox":"Ta wiadomość pojawia się tylko w środowisku testowym.","error_page.error_message_stripe_missing_required_permission":"Zakup nie powiódł się, ponieważ aplikacja Stripe nie ma wymaganego uprawnienia. W środowisku produkcyjnym zakupy będą działać bez naliczania podatków.","error_page.error_title_stripe_tax_not_active":"Stripe Tax nieaktywny","error_page.error_title_stripe_invalid_tax_origin_address":"Nieprawidłowy adres pochodzenia podatku","apple_pay.free_trial":"Okres próbny","product_info.price_after_intro_price":"Po {{introPriceDuration}}, od {{renewalDate}}","product_info.after_trial":"po okresie próbnym","product_info.after":"po","product_info.intro_price_phase_after_trial":"Następnie {{introPriceDuration}} za {{introPrice}}","product_info.intro_price_phase":"Najpierw {{introPriceDuration}} za {{introPrice}}","product_info.intro_price_phase_paid_once":"płatne jednorazowo","payment_entry_page.trial_subscription_terms_info":"Po zakończeniu okresu próbnego zostanie pobrana opłata w wysokości {{price}} {{perFrequency}} począwszy od {{renewalDate}}. Możesz anulować subskrypcję w dowolnym momencie przed tą datą.","payment_entry_page.subscription_info":"Subskrypcja odnawia się automatycznie. Anuluj w dowolnym momencie.","payment_entry_page.otp_terms_info":"Dokonując zakupu, zgadzasz się na obciążenie przez {{appName}} zgodnie z ich warunkami.","payment_entry_page.subscription_terms_info":"Subskrybując, zgadzasz się na obciążanie przez {{appName}} zgodnie z ich warunkami do momentu anulowania."},YFA={"periods.week":"{{amount}} semana","periods.month":"{{amount}} mês","periods.year":"{{amount}} ano","periods.day":"{{amount}} dia","periods.weekShort":"{{amount}}sem","periods.monthShort":"{{amount}}mês","periods.yearShort":"{{amount}}ano","periods.dayShort":"{{amount}}d","periods.lifetime":"vitalício","periods.weekPlural":"{{amount}} semanas","periods.monthPlural":"{{amount}} meses","periods.yearPlural":"{{amount}} anos","periods.dayPlural":"{{amount}} dias","periods.weekFrequency":"semanal","periods.monthFrequency":"mensal","periods.yearFrequency":"anual","periods.dayFrequency":"diário","periods.perWeekFrequency":"por semana","periods.perMonthFrequency":"por mês","periods.perYearFrequency":"por ano","periods.perDayFrequency":"por dia","periods.unknownFrequency":"desconhecido","periods.weekFrequencyPlural":"a cada {{amount}} semanas","periods.monthFrequencyPlural":"a cada {{amount}} meses","periods.yearFrequencyPlural":"a cada {{amount}} anos","periods.dayFrequencyPlural":"a cada {{amount}} dias","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} teste grátis","product_info.price_after_free_trial":"Após o término do teste, em {{renewalDate}}","product_info.renewal_frequency":"Renova {{frequency}}","product_info.continues_until_cancelled":"Continua até ser cancelado","product_info.cancel_anytime":"Cancelar a qualquer momento","payment_entry_page.payment_step_title":"Pagamento seguro pela RevenueCat","payment_entry_page.button_pay":"Pagar agora","payment_entry_page.button_start_trial":"Iniciar Teste","success_page.purchase_successful":"Pagamento concluído","success_page.button_close":"Continuar","error_page.if_error_persists":"Se o erro persistir, entre em contato com ","error_page.error_title_already_subscribed":"Você já se inscreveu em {{productTitle}}","error_page.error_title_already_purchased":"Você já comprou {{productTitle}}","error_page.error_title_other_errors":"Algo deu errado","error_page.error_message_already_subscribed":"Você não pode se inscrever neste produto novamente.","error_page.error_message_already_purchased":"Você não pode comprar este produto novamente.","error_page.error_message_missing_email_error":"Email é necessário para concluir a compra.","error_page.error_message_network_error":"Erro de rede. Verifique sua conexão com a internet.","error_page.error_message_error_charging_payment":"Pagamento falhou.","error_page.error_message_error_setting_up_purchase":"Compra não iniciada devido a um erro (código de erro: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Não conseguimos verificar seu endereço de cobrança. Por favor, verifique se o código postal e o país estão corretos.","error_page.error_message_unknown_error":"Ocorreu um erro desconhecido (código de erro: {{errorCode}}).","error_page.button_try_again":"Tentar novamente","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% de desconto","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Total a pagar hoje","product_info.subscribe_to":"Subscrever","navbar_header.details":"Detalhes","navbar_header.back_button":"Voltar","pricing_dropdown.show_details":"Mostrar detalhes","pricing_dropdown.hide_details":"Ocultar detalhes","pricing_table.tax":"Imposto","pricing_table.trial_ends":"Após o término do período de avaliação, em {{formattedTrialEndDate}}","pricing_table.total_due_today":"Total a pagar hoje","pricing_table.total_excluding_tax":"Total sem impostos","pricing_table.enter_billing_address_to_calculate":"Insira o endereço de cobrança para calcular","pricing_table.enter_state_or_postal_code_to_calculate":"Insira o estado ou o CEP para calcular","pricing_table.enter_postal_code_to_calculate":"Insira o CEP para calcular","error_page.error_message_invalid_email_error":"O endereço de e-mail {{email}} não pôde ser verificado. Por favor, forneça um endereço de e-mail válido.","payment_entry_page.button_payment_method":"Pagar {{formattedPrice}} com {{paymentMethod}}","payment_entry_page.button_with_price":"Pagar {{formattedPrice}}","price_update.title":"Atualização de preço","price_update.base_message":"O preço total foi atualizado com impostos com base no seu endereço de cobrança. Por favor, revise e tente novamente. Seu cartão só será cobrado uma vez.","price_update.trial_message":"O preço da assinatura foi atualizado para incluir impostos com base no seu endereço de faturação. O período de teste gratuito continua válido. Por favor, verifique e tente novamente.","payment_entry_page.express_checkout_divider":"OU PAGUE COM CARTÃO","error_page.trouble_accessing":"Se estiver com problemas para acessar sua compra, entre em contato com o suporte em ","error_page.close_button_title":"Ir para {{appName}}","error_page.error_title_stripe_missing_required_permission":"Permissão do Stripe em falta","error_page.button_close":"Fechar","error_page.error_message_stripe_invalid_tax_origin_address":"A compra falhou porque o endereço de origem fiscal é inválido. Em produção, as compras funcionarão sem impostos aplicados.","error_page.error_message_stripe_tax_not_active":"A compra falhou porque o Stripe Tax não está ativado. Em produção, as compras funcionarão sem impostos aplicados.","error_page.error_only_in_sandbox":"Esta mensagem aparece apenas na sandbox.","error_page.error_message_stripe_missing_required_permission":"A compra falhou porque o aplicativo Stripe não tem uma permissão necessária. Em produção, as compras funcionarão sem impostos aplicados.","error_page.error_title_stripe_tax_not_active":"Stripe Tax não está ativo","error_page.error_title_stripe_invalid_tax_origin_address":"Endereço de origem fiscal inválido","apple_pay.free_trial":"Teste Gratuito","product_info.price_after_intro_price":"Após {{introPriceDuration}}, em {{renewalDate}}","product_info.after_trial":"após o período de teste","product_info.after":"após","product_info.intro_price_phase_after_trial":"Depois, {{introPriceDuration}} por {{introPrice}}","product_info.intro_price_phase":"Primeiro, {{introPriceDuration}} por {{introPrice}}","product_info.intro_price_phase_paid_once":"pago uma vez","payment_entry_page.trial_subscription_terms_info":"Após o término do período de avaliação, será cobrado o valor de {{price}} {{perFrequency}} a partir de {{renewalDate}}. Pode cancelar a qualquer momento antes desta data.","payment_entry_page.subscription_info":"A subscrição é renovada automaticamente. Cancele a qualquer momento.","payment_entry_page.otp_terms_info":"Ao comprar, você concorda em permitir que o {{appName}} cobre de acordo com os termos deles.","payment_entry_page.subscription_terms_info":"Ao subscrever, concorda em permitir que a {{appName}} lhe cobre de acordo com os seus termos até cancelar."},HFA={"periods.week":"{{amount}} săptămână","periods.month":"{{amount}} lună","periods.year":"{{amount}} an","periods.day":"{{amount}} zi","periods.weekShort":"{{amount}}săpt","periods.monthShort":"{{amount}}lun","periods.yearShort":"{{amount}}an","periods.dayShort":"{{amount}}z","periods.lifetime":"pe viață","periods.weekPlural":"{{amount}} săptămâni","periods.monthPlural":"{{amount}} luni","periods.yearPlural":"{{amount}} ani","periods.dayPlural":"{{amount}} zile","periods.weekFrequency":"săptămânal","periods.monthFrequency":"lunar","periods.yearFrequency":"anual","periods.dayFrequency":"zilnic","periods.perWeekFrequency":"pe săptămână","periods.perMonthFrequency":"pe lună","periods.perYearFrequency":"pe an","periods.perDayFrequency":"pe zi","periods.unknownFrequency":"necunoscut","periods.weekFrequencyPlural":"la fiecare {{amount}} săptămâni","periods.monthFrequencyPlural":"la fiecare {{amount}} luni","periods.yearFrequencyPlural":"la fiecare {{amount}} ani","periods.dayFrequencyPlural":"la fiecare {{amount}} zile","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} perioadă de probă gratuită","product_info.price_after_free_trial":"După terminarea perioadei de probă, pe {{renewalDate}}","product_info.renewal_frequency":"Se reînnoiește {{frequency}}","product_info.continues_until_cancelled":"Continuă până la anulare","product_info.cancel_anytime":"Anulare oricând","payment_entry_page.payment_step_title":"Plata securizată prin RevenueCat","payment_entry_page.button_pay":"Plătește acum","payment_entry_page.button_start_trial":"Începe perioada de probă","success_page.purchase_successful":"Plata efectuată","success_page.button_close":"Continuă","error_page.if_error_persists":"Dacă eroarea persistă, vă rugăm să contactați ","error_page.error_title_already_subscribed":"Sunteți deja abonat la {{productTitle}}","error_page.error_title_already_purchased":"Ați achiziționat deja {{productTitle}}","error_page.error_title_other_errors":"A apărut o eroare","error_page.error_message_already_subscribed":"Nu vă puteți abona din nou la acest produs.","error_page.error_message_already_purchased":"Nu puteți achiziționa din nou acest produs.","error_page.error_message_missing_email_error":"Adresa de e-mail este necesară pentru a finaliza achiziția.","error_page.error_message_network_error":"Eroare de rețea. Verificați conexiunea la internet.","error_page.error_message_error_charging_payment":"Plata a eșuat.","error_page.error_message_error_setting_up_purchase":"Achiziția nu a putut fi inițiată din cauza unei erori (cod de eroare: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Nu am putut verifica adresa de facturare. Vă rugăm să verificați dacă codul poștal și țara sunt corecte.","error_page.error_message_unknown_error":"A apărut o eroare necunoscută (cod de eroare: {{errorCode}}).","error_page.button_try_again":"Încearcă din nou","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% reducere","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Total de plată astăzi","product_info.subscribe_to":"Abonare la","navbar_header.details":"Detalii","navbar_header.back_button":"Înapoi","pricing_dropdown.show_details":"Arată detalii","pricing_dropdown.hide_details":"Ascunde detalii","pricing_table.tax":"Taxă","pricing_table.trial_ends":"După ce perioada de probă se termină, pe {{formattedTrialEndDate}}","pricing_table.total_due_today":"Total de plătit astăzi","pricing_table.total_excluding_tax":"Total fără taxe","pricing_table.enter_billing_address_to_calculate":"Introduceți adresa de facturare pentru a calcula","pricing_table.enter_state_or_postal_code_to_calculate":"Introduceți statul sau codul poștal pentru a calcula","pricing_table.enter_postal_code_to_calculate":"Introduceți codul poștal pentru a calcula","error_page.error_message_invalid_email_error":"Adresa de e-mail {{email}} nu a putut fi verificată. Vă rugăm să furnizați o adresă de e-mail validă.","payment_entry_page.button_payment_method":"Plătește {{formattedPrice}} cu {{paymentMethod}}","payment_entry_page.button_with_price":"Plătește {{formattedPrice}}","price_update.title":"Actualizare preț","price_update.base_message":"Prețul total a fost actualizat cu taxe, în funcție de adresa dumneavoastră de facturare. Vă rugăm să revizuiți și să încercați din nou. Cardul dumneavoastră va fi debitat o singură dată.","price_update.trial_message":"Prețul abonamentului a fost actualizat pentru a include taxele bazate pe adresa dvs. de facturare. Perioada de probă gratuită rămâne valabilă. Vă rugăm să verificați și să încercați din nou.","payment_entry_page.express_checkout_divider":"SAU PLĂTEȘTE CU CARDUL","error_page.trouble_accessing":"Dacă întâmpini probleme în accesarea achiziției tale, contactează serviciul de asistență la ","error_page.close_button_title":"Mergi la {{appName}}","error_page.error_title_stripe_missing_required_permission":"Permisiune Stripe lipsă","error_page.button_close":"Închide","error_page.error_message_stripe_invalid_tax_origin_address":"Achiziția a eșuat deoarece adresa de origine fiscală este nevalidă. În producție, achizițiile vor funcționa fără taxe aplicate.","error_page.error_message_stripe_tax_not_active":"Achiziția a eșuat deoarece Stripe Tax nu este activat. În producție, achizițiile vor funcționa fără taxe aplicate.","error_page.error_only_in_sandbox":"Acest mesaj apare doar în sandbox.","error_page.error_message_stripe_missing_required_permission":"Achiziția a eșuat deoarece aplicației Stripe îi lipsește o permisiune necesară. În producție, achizițiile vor funcționa fără taxe aplicate.","error_page.error_title_stripe_tax_not_active":"Stripe Tax nu este activ","error_page.error_title_stripe_invalid_tax_origin_address":"Adresă de origine fiscală Stripe nevalidă","apple_pay.free_trial":"Perioadă de probă gratuită","product_info.price_after_intro_price":"După {{introPriceDuration}}, pe {{renewalDate}}","product_info.after_trial":"după perioada de probă","product_info.after":"după","product_info.intro_price_phase_after_trial":"Apoi {{introPriceDuration}} pentru {{introPrice}}","product_info.intro_price_phase":"Mai întâi {{introPriceDuration}} pentru {{introPrice}}","product_info.intro_price_phase_paid_once":"plătit o singură dată","payment_entry_page.trial_subscription_terms_info":"După ce perioada de probă se termină, veți fi taxat cu {{price}} {{perFrequency}} începând cu {{renewalDate}}. Puteți anula oricând înainte de această dată.","payment_entry_page.subscription_info":"Abonamentul se reînnoiește automat. Anulați oricând.","payment_entry_page.otp_terms_info":"Prin achiziționarea, sunteți de acord să permiteți {{appName}} să vă taxeze conform termenilor săi.","payment_entry_page.subscription_terms_info":"Prin abonare, sunteți de acord să permiteți {{appName}} să vă taxeze conform termenilor săi până la anulare."},OFA={"periods.week":"{{amount}} неделя","periods.month":"{{amount}} месяц","periods.year":"{{amount}} год","periods.day":"{{amount}} день","periods.weekShort":"{{amount}}нед","periods.monthShort":"{{amount}}мес","periods.yearShort":"{{amount}}г","periods.dayShort":"{{amount}}д","periods.lifetime":"пожизненно","periods.weekPlural":"{{amount}} недель","periods.monthPlural":"{{amount}} месяцев","periods.yearPlural":"{{amount}} лет","periods.dayPlural":"{{amount}} дней","periods.weekFrequency":"еженедельно","periods.monthFrequency":"ежемесячно","periods.yearFrequency":"ежегодно","periods.dayFrequency":"ежедневно","periods.perWeekFrequency":"в неделю","periods.perMonthFrequency":"в месяц","periods.perYearFrequency":"в год","periods.perDayFrequency":"в день","periods.unknownFrequency":"неизвестно","periods.weekFrequencyPlural":"каждые {{amount}} недель","periods.monthFrequencyPlural":"каждые {{amount}} месяцев","periods.yearFrequencyPlural":"каждые {{amount}} лет","periods.dayFrequencyPlural":"каждые {{amount}} дней","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} бесплатная пробная версия","product_info.price_after_free_trial":"После окончания пробного периода, {{renewalDate}}","product_info.renewal_frequency":"Продлевается {{frequency}}","product_info.continues_until_cancelled":"Продолжается до отмены","product_info.cancel_anytime":"Отменить в любое время","payment_entry_page.payment_step_title":"Безопасная оплата через RevenueCat","payment_entry_page.button_pay":"Оплатить сейчас","payment_entry_page.button_start_trial":"Начать пробный период","success_page.purchase_successful":"Оплата завершена","success_page.button_close":"Продолжить","error_page.if_error_persists":"Если ошибка сохраняется, пожалуйста, свяжитесь с ","error_page.error_title_already_subscribed":"Вы уже подписаны на {{productTitle}}","error_page.error_title_already_purchased":"Вы уже приобрели {{productTitle}}","error_page.error_title_other_errors":"Что-то пошло не так","error_page.error_message_already_subscribed":"Вы не можете подписаться на этот продукт повторно.","error_page.error_message_already_purchased":"Вы не можете приобрести этот продукт повторно.","error_page.error_message_missing_email_error":"Для завершения покупки необходим адрес электронной почты.","error_page.error_message_network_error":"Ошибка сети. Проверьте ваше интернет-соединение.","error_page.error_message_error_charging_payment":"Оплата не прошла.","error_page.error_message_error_setting_up_purchase":"Покупка не была начата из-за ошибки (код ошибки: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Мы не смогли проверить ваш платежный адрес. Пожалуйста, проверьте, что почтовый индекс и страна указаны правильно.","error_page.error_message_unknown_error":"Произошла неизвестная ошибка (код ошибки: {{errorCode}}).","error_page.button_try_again":"Повторить попытку","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% скидки","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Всего к оплате сегодня","product_info.subscribe_to":"Подписаться","navbar_header.details":"Детали","navbar_header.back_button":"Назад","pricing_dropdown.show_details":"Показать детали","pricing_dropdown.hide_details":"Скрыть детали","pricing_table.tax":"Налог","pricing_table.trial_ends":"После окончания пробного периода, {{formattedTrialEndDate}}","pricing_table.total_due_today":"Итого к оплате сегодня","pricing_table.total_excluding_tax":"Итого без учета налога","pricing_table.enter_billing_address_to_calculate":"Введите платежный адрес для расчета","pricing_table.enter_state_or_postal_code_to_calculate":"Введите штат или почтовый индекс для расчета","pricing_table.enter_postal_code_to_calculate":"Введите почтовый индекс для расчета","error_page.error_message_invalid_email_error":"Не удалось проверить адрес электронной почты {{email}}. Пожалуйста, укажите действительный адрес электронной почты.","payment_entry_page.button_payment_method":"Оплатить {{formattedPrice}} через {{paymentMethod}}","payment_entry_page.button_with_price":"Оплатить {{formattedPrice}}","price_update.title":"Обновление цены","price_update.base_message":"Общая цена была обновлена с учетом налога на основе вашего платежного адреса. Пожалуйста, проверьте и повторите попытку. С вашей карты будет списано только один раз.","price_update.trial_message":"Цена подписки была обновлена с учетом налогов на основе вашего платежного адреса. Пробный период остается бесплатным. Пожалуйста, проверьте и попробуйте снова.","payment_entry_page.express_checkout_divider":"ИЛИ ОПЛАТИТЕ КАРТОЙ","error_page.trouble_accessing":"Если у вас возникли проблемы с доступом к вашей покупке, обратитесь в службу поддержки по адресу ","error_page.close_button_title":"Перейти в {{appName}}","error_page.error_title_stripe_missing_required_permission":"Отсутствует разрешение Stripe","error_page.button_close":"Закрыть","error_page.error_message_stripe_invalid_tax_origin_address":"Покупка не удалась, так как адрес отправления налога недействителен. В рабочей среде покупки будут работать без применения налогов.","error_page.error_message_stripe_tax_not_active":"Покупка не удалась, так как Stripe Tax не включен. В рабочей среде покупки будут работать без применения налогов.","error_page.error_only_in_sandbox":"Это сообщение появляется только в песочнице.","error_page.error_message_stripe_missing_required_permission":"Покупка не удалась, так как у приложения Stripe отсутствует необходимое разрешение. В рабочей среде покупки будут работать без применения налогов.","error_page.error_title_stripe_tax_not_active":"Stripe Tax не активен","error_page.error_title_stripe_invalid_tax_origin_address":"Недействительный адрес отправления налога","apple_pay.free_trial":"Бесплатная пробная версия","product_info.price_after_intro_price":"После {{introPriceDuration}}, {{renewalDate}}","product_info.after_trial":"после пробного периода","product_info.after":"после","product_info.intro_price_phase_after_trial":"Затем {{introPriceDuration}} за {{introPrice}}","product_info.intro_price_phase":"Сначала {{introPriceDuration}} за {{introPrice}}","product_info.intro_price_phase_paid_once":"единоразовый платеж","payment_entry_page.trial_subscription_terms_info":"По окончании пробного периода с вас будет взиматься плата в размере {{price}} {{perFrequency}}, начиная с {{renewalDate}}. Вы можете отменить подписку в любое время до этой даты.","payment_entry_page.subscription_info":"Подписка продлевается автоматически. Отменить можно в любое время.","payment_entry_page.otp_terms_info":"Совершая покупку, вы соглашаетесь с тем, что {{appName}} будет взимать с вас плату в соответствии со своими условиями.","payment_entry_page.subscription_terms_info":"Подписываясь, вы соглашаетесь с тем, что {{appName}} будет взимать с вас плату в соответствии с их условиями до тех пор, пока вы не отмените подписку."},PFA={"periods.week":"{{amount}} týždeň","periods.month":"{{amount}} mesiac","periods.year":"{{amount}} rok","periods.day":"{{amount}} deň","periods.weekShort":"{{amount}}týž","periods.monthShort":"{{amount}}mes","periods.yearShort":"{{amount}}rok","periods.dayShort":"{{amount}}d","periods.lifetime":"doživotne","periods.weekPlural":"{{amount}} týždňov","periods.monthPlural":"{{amount}} mesiacov","periods.yearPlural":"{{amount}} rokov","periods.dayPlural":"{{amount}} dní","periods.weekFrequency":"týždenne","periods.monthFrequency":"mesačne","periods.yearFrequency":"ročne","periods.dayFrequency":"denne","periods.perWeekFrequency":"týždenne","periods.perMonthFrequency":"mesačne","periods.perYearFrequency":"ročne","periods.perDayFrequency":"denne","periods.unknownFrequency":"neznáme","periods.weekFrequencyPlural":"každých {{amount}} týždňov","periods.monthFrequencyPlural":"každých {{amount}} mesiacov","periods.yearFrequencyPlural":"každých {{amount}} rokov","periods.dayFrequencyPlural":"každých {{amount}} dní","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} bezplatné skúšobné obdobie","product_info.price_after_free_trial":"Po skončení skúšobného obdobia, dňa {{renewalDate}}","product_info.renewal_frequency":"Obnovuje sa {{frequency}}","product_info.continues_until_cancelled":"Pokračuje, kým sa nezruší","product_info.cancel_anytime":"Kedykoľvek zrušiť","payment_entry_page.payment_step_title":"Bezpečný nákup prostredníctvom RevenueCat","payment_entry_page.button_pay":"Zaplatiť teraz","payment_entry_page.button_start_trial":"Spustiť skúšobné obdobie","success_page.purchase_successful":"Platba dokončená","success_page.button_close":"Pokračovať","error_page.if_error_persists":"Ak chyba pretrváva, kontaktujte ","error_page.error_title_already_subscribed":"Už ste si predplatili {{productTitle}}","error_page.error_title_already_purchased":"Už ste si zakúpili {{productTitle}}","error_page.error_title_other_errors":"Niečo sa pokazilo","error_page.error_message_already_subscribed":"Na tento produkt sa nemôžete znova prihlásiť na odber.","error_page.error_message_already_purchased":"Tento produkt si nemôžete znova zakúpiť.","error_page.error_message_missing_email_error":"Na dokončenie nákupu je potrebný e-mail.","error_page.error_message_network_error":"Chyba siete. Skontrolujte svoje internetové pripojenie.","error_page.error_message_error_charging_payment":"Platba zlyhala.","error_page.error_message_error_setting_up_purchase":"Nákup sa nespustil kvôli chybe (kód chyby: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Nepodarilo sa nám overiť vašu fakturačnú adresu. Skontrolujte, prosím, či je PSČ a krajina správne.","error_page.error_message_unknown_error":"Vyskytla sa neznáma chyba (kód chyby: {{errorCode}}).","error_page.button_try_again":"Skúsiť znova","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% zľava","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Celková suma splatná dnes","product_info.subscribe_to":"Prihlásiť sa na odber","navbar_header.details":"Podrobnosti","navbar_header.back_button":"Späť","pricing_dropdown.show_details":"Zobraziť podrobnosti","pricing_dropdown.hide_details":"Skryť podrobnosti","pricing_table.tax":"Daň","pricing_table.trial_ends":"Po skončení skúšobnej verzie, dňa {{formattedTrialEndDate}}","pricing_table.total_due_today":"Celková suma splatná dnes","pricing_table.total_excluding_tax":"Celkom bez dane","pricing_table.enter_billing_address_to_calculate":"Zadajte fakturačnú adresu pre výpočet","pricing_table.enter_state_or_postal_code_to_calculate":"Zadajte štát alebo PSČ pre výpočet","pricing_table.enter_postal_code_to_calculate":"Zadajte PSČ pre výpočet","error_page.error_message_invalid_email_error":"E-mailová adresa {{email}} sa nedala overiť. Zadajte platnú e-mailovú adresu.","payment_entry_page.button_payment_method":"Zaplatiť sumu {{formattedPrice}} pomocou {{paymentMethod}}","payment_entry_page.button_with_price":"Zaplatiť {{formattedPrice}}","price_update.title":"Aktualizácia ceny","price_update.base_message":"Celková cena bola aktualizovaná o daň na základe vašej fakturačnej adresy. Skontrolujte to a skúste znova. Vaša karta bude zaťažená iba raz.","price_update.trial_message":"Cena predplatného bola aktualizovaná o daňe na základe vašej fakturačnej adresy. Bezplatná skúšobná doba stále platí. Prosím, skontrolujte a skúste znova.","payment_entry_page.express_checkout_divider":"ALEBO ZAPLATIŤ KARTOU","error_page.trouble_accessing":"Ak máte problémy s prístupom k svojmu nákupu, kontaktujte podporu na ","error_page.close_button_title":"Prejsť na {{appName}}","error_page.error_title_stripe_missing_required_permission":"Chýbajúce povolenie Stripe","error_page.button_close":"Zavrieť","error_page.error_message_stripe_invalid_tax_origin_address":"Nákup sa nepodaril, pretože adresa pôvodu dane je neplatná. V produkčnom prostredí budú nákupy fungovať bez uplatnenia daní.","error_page.error_message_stripe_tax_not_active":"Nákup sa nepodaril, pretože Stripe Tax nie je povolený. V produkčnom prostredí budú nákupy fungovať bez uplatnenia daní.","error_page.error_only_in_sandbox":"Táto správa sa zobrazuje iba v testovacom prostredí (sandbox).","error_page.error_message_stripe_missing_required_permission":"Nákup sa nepodaril, pretože aplikácii Stripe chýba požadované povolenie. V produkčnom prostredí budú nákupy fungovať bez uplatnenia daní.","error_page.error_title_stripe_tax_not_active":"Stripe Tax nie je aktívny","error_page.error_title_stripe_invalid_tax_origin_address":"Neplatná adresa pôvodu dane","apple_pay.free_trial":"Skúšobná verzia zdarma","product_info.price_after_intro_price":"Po {{introPriceDuration}}, dňa {{renewalDate}}","product_info.after_trial":"po skúšobnej dobe","product_info.after":"po","product_info.intro_price_phase_after_trial":"Potom {{introPriceDuration}} za {{introPrice}}","product_info.intro_price_phase":"Najprv {{introPriceDuration}} za {{introPrice}}","product_info.intro_price_phase_paid_once":"zaplatené jednorazovo","payment_entry_page.trial_subscription_terms_info":"Po skončení skúšobného obdobia vám bude účtovaná suma {{price}} {{perFrequency}} počnúc dňom {{renewalDate}}. Pred týmto dátumom môžete kedykoľvek zrušiť.","payment_entry_page.subscription_info":"Predplatné sa automaticky obnovuje. Zrušiť môžete kedykoľvek.","payment_entry_page.otp_terms_info":"Zakúpením súhlasíte s tým, že spoločnosti {{appName}} umožníte účtovať vám poplatky v súlade s jej podmienkami.","payment_entry_page.subscription_terms_info":"Prihlásením na odber súhlasíte s tým, že spoločnosť {{appName}} vám bude účtovať poplatky podľa svojich podmienok, až kým odber nezrušíte."},jFA={"periods.week":"{{amount}} vecka","periods.month":"{{amount}} månad","periods.year":"{{amount}} år","periods.day":"{{amount}} dag","periods.weekShort":"{{amount}}v","periods.monthShort":"{{amount}}mån","periods.yearShort":"{{amount}}år","periods.dayShort":"{{amount}}d","periods.lifetime":"livstid","periods.weekPlural":"{{amount}} veckor","periods.monthPlural":"{{amount}} månader","periods.yearPlural":"{{amount}} år","periods.dayPlural":"{{amount}} dagar","periods.weekFrequency":"veckovis","periods.monthFrequency":"månadsvis","periods.yearFrequency":"årligen","periods.dayFrequency":"dagligen","periods.perWeekFrequency":"per vecka","periods.perMonthFrequency":"per månad","periods.perYearFrequency":"per år","periods.perDayFrequency":"per dag","periods.unknownFrequency":"okänd","periods.weekFrequencyPlural":"varje {{amount}} veckor","periods.monthFrequencyPlural":"varje {{amount}} månader","periods.yearFrequencyPlural":"varje {{amount}} år","periods.dayFrequencyPlural":"varje {{amount}} dagar","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} gratis provperiod","product_info.price_after_free_trial":"Efter provperioden slutar, den {{renewalDate}}","product_info.renewal_frequency":"Förnyas {{frequency}}","product_info.continues_until_cancelled":"Gäller tills avbokad","product_info.cancel_anytime":"Avboka när som helst","payment_entry_page.payment_step_title":"Säker betalning via RevenueCat","payment_entry_page.button_pay":"Betala nu","payment_entry_page.button_start_trial":"Starta provperiod","success_page.purchase_successful":"Betalningen är klar","success_page.button_close":"Fortsätt","error_page.if_error_persists":"Om felet kvarstår, vänligen kontakta ","error_page.error_title_already_subscribed":"Du prenumererar redan på {{productTitle}}","error_page.error_title_already_purchased":"Du har redan köpt {{productTitle}}","error_page.error_title_other_errors":"Något gick fel","error_page.error_message_already_subscribed":"Du kan inte prenumerera på den här produkten igen.","error_page.error_message_already_purchased":"Du kan inte köpa den här produkten igen.","error_page.error_message_missing_email_error":"E-post krävs för att slutföra köpet.","error_page.error_message_network_error":"Nätverksfel. Kontrollera din internetanslutning.","error_page.error_message_error_charging_payment":"Betalningen misslyckades.","error_page.error_message_error_setting_up_purchase":"Köp kunde inte startas på grund av ett fel (felkod: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Vi kunde inte verifiera din faktureringsadress. Kontrollera att postnummer och land är korrekta.","error_page.error_message_unknown_error":"Ett okänt fel inträffade (felkod: {{errorCode}}).","error_page.button_try_again":"Försök igen","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% rabatt","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}} ({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Totalt att betala idag","product_info.subscribe_to":"Prenumerera på","navbar_header.details":"Detaljer","navbar_header.back_button":"Tillbaka","pricing_dropdown.show_details":"Visa detaljer","pricing_dropdown.hide_details":"Dölj detaljer","pricing_table.tax":"Moms","pricing_table.trial_ends":"Efter provperiodens slut, den {{formattedTrialEndDate}}","pricing_table.total_due_today":"Total summa att betala idag","pricing_table.total_excluding_tax":"Totalt exklusive moms","pricing_table.enter_billing_address_to_calculate":"Ange faktureringsadress för att beräkna","pricing_table.enter_state_or_postal_code_to_calculate":"Ange delstat eller postnummer för att beräkna","pricing_table.enter_postal_code_to_calculate":"Ange postnummer för att beräkna","error_page.error_message_invalid_email_error":"E-postadressen {{email}} kunde inte verifieras. Ange en giltig e-postadress.","payment_entry_page.button_payment_method":"Betala {{formattedPrice}} med {{paymentMethod}}","payment_entry_page.button_with_price":"Betala {{formattedPrice}}","price_update.title":"Prisuppdatering","price_update.base_message":"Det totala priset har uppdaterats med moms baserat på din faktureringsadress. Granska och försök igen. Ditt kort kommer endast att debiteras en gång.","price_update.trial_message":"Prenumerationspriset har uppdaterats för att inkludera skatter baserat på din fakturaadress. Den kostnadsfria provperioden gäller fortfarande. Kontrollera och försök igen.","payment_entry_page.express_checkout_divider":"ELLER BETALA MED KORT","error_page.trouble_accessing":"Om du har problem med att komma åt ditt köp, kontakta support på ","error_page.close_button_title":"Gå till {{appName}}","error_page.error_title_stripe_missing_required_permission":"Saknar Stripe-behörighet","error_page.button_close":"Stäng","error_page.error_message_stripe_invalid_tax_origin_address":"Köpet misslyckades eftersom skatteursprungsadressen är ogiltig. I produktion kommer köp att fungera utan att skatter tillämpas.","error_page.error_message_stripe_tax_not_active":"Köpet misslyckades eftersom Stripe Tax inte är aktiverat. I produktion kommer köp att fungera utan att skatter tillämpas.","error_page.error_only_in_sandbox":"Det här meddelandet visas bara i sandlådan.","error_page.error_message_stripe_missing_required_permission":"Köpet misslyckades eftersom Stripe-appen saknar en nödvändig behörighet. I produktion kommer köp att fungera utan att skatter tillämpas.","error_page.error_title_stripe_tax_not_active":"Stripe Tax är inte aktivt","error_page.error_title_stripe_invalid_tax_origin_address":"Ogiltig skatteursprungsadress","apple_pay.free_trial":"Gratis provperiod","product_info.price_after_intro_price":"Efter {{introPriceDuration}}, den {{renewalDate}}","product_info.after_trial":"efter provperioden","product_info.after":"efter","product_info.intro_price_phase_after_trial":"Sedan {{introPriceDuration}} för {{introPrice}}","product_info.intro_price_phase":"Först {{introPriceDuration}} för {{introPrice}}","product_info.intro_price_phase_paid_once":"betalas en gång","payment_entry_page.trial_subscription_terms_info":"Efter att din provperiod slutar debiteras du {{price}} {{perFrequency}} från och med {{renewalDate}}. Du kan avbryta när som helst före detta datum.","payment_entry_page.subscription_info":"Prenumerationen förnyas automatiskt. Avbryt när som helst.","payment_entry_page.otp_terms_info":"Genom att köpa godkänner du att {{appName}} debiterar dig i enlighet med deras villkor.","payment_entry_page.subscription_terms_info":"Genom att prenumerera godkänner du att {{appName}} debiterar dig i enlighet med deras villkor tills du avbryter."},zFA={"periods.week":"{{amount}} สัปดาห์","periods.month":"{{amount}} เดือน","periods.year":"{{amount}} ปี","periods.day":"{{amount}} วัน","periods.weekShort":"{{amount}} สัปดาห์","periods.monthShort":"{{amount}} เดือน","periods.yearShort":"{{amount}} ปี","periods.dayShort":"{{amount}} วัน","periods.lifetime":"ตลอดชีพ","periods.weekPlural":"{{amount}} สัปดาห์","periods.monthPlural":"{{amount}} เดือน","periods.yearPlural":"{{amount}} ปี","periods.dayPlural":"{{amount}} วัน","periods.weekFrequency":"รายสัปดาห์","periods.monthFrequency":"รายเดือน","periods.yearFrequency":"รายปี","periods.dayFrequency":"รายวัน","periods.perWeekFrequency":"ต่อสัปดาห์","periods.perMonthFrequency":"ต่อเดือน","periods.perYearFrequency":"ต่อปี","periods.perDayFrequency":"ต่อวัน","periods.unknownFrequency":"ไม่รู้จัก","periods.weekFrequencyPlural":"ทุกๆ {{amount}} สัปดาห์","periods.monthFrequencyPlural":"ทุกๆ {{amount}} เดือน","periods.yearFrequencyPlural":"ทุกๆ {{amount}} ปี","periods.dayFrequencyPlural":"ทุกๆ {{amount}} วัน","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} ทดลองใช้ฟรี","product_info.price_after_free_trial":"หลังจากสิ้นสุดการทดลองใช้ ในวันที่ {{renewalDate}}","product_info.renewal_frequency":"ต่ออายุ {{frequency}}","product_info.continues_until_cancelled":"ต่อเนื่องจนกว่าจะยกเลิก","product_info.cancel_anytime":"ยกเลิกได้ตลอดเวลา","payment_entry_page.payment_step_title":"การชำระเงินอย่างปลอดภัยโดย RevenueCat","payment_entry_page.button_pay":"ชำระเงินตอนนี้","payment_entry_page.button_start_trial":"เริ่มทดลองใช้","success_page.purchase_successful":"การชำระเงินเสร็จสมบูรณ์","success_page.button_close":"ดำเนินการต่อ","error_page.if_error_persists":"หากข้อผิดพลาดยังคงอยู่ โปรดติดต่อ ","error_page.error_title_already_subscribed":"คุณได้สมัครสมาชิก {{productTitle}} แล้ว","error_page.error_title_already_purchased":"คุณได้ซื้อ {{productTitle}} แล้ว","error_page.error_title_other_errors":"มีบางอย่างผิดพลาด","error_page.error_message_already_subscribed":"คุณไม่สามารถสมัครสมาชิกผลิตภัณฑ์นี้ได้อีก","error_page.error_message_already_purchased":"คุณไม่สามารถซื้อผลิตภัณฑ์นี้ได้อีก","error_page.error_message_missing_email_error":"ต้องใช้อีเมลเพื่อทำการซื้อให้เสร็จสมบูรณ์","error_page.error_message_network_error":"ข้อผิดพลาดของเครือข่าย โปรดตรวจสอบการเชื่อมต่ออินเทอร์เน็ตของคุณ","error_page.error_message_error_charging_payment":"การชำระเงินล้มเหลว","error_page.error_message_error_setting_up_purchase":"ไม่สามารถเริ่มการซื้อได้เนื่องจากข้อผิดพลาด (รหัสข้อผิดพลาด: {{errorCode}})","error_page.error_message_invalid_tax_location":"เราไม่สามารถยืนยันที่อยู่สำหรับออกใบแจ้งหนี้ของคุณได้ กรุณาตรวจสอบรหัสไปรษณีย์และประเทศให้ถูกต้อง","error_page.error_message_unknown_error":"เกิดข้อผิดพลาดที่ไม่รู้จัก (รหัสข้อผิดพลาด: {{errorCode}})","error_page.button_try_again":"ลองอีกครั้ง","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% ลด","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"ยอดรวมที่ต้องชำระวันนี้","product_info.subscribe_to":"สมัครสมาชิก","navbar_header.details":"รายละเอียด","navbar_header.back_button":"ย้อนกลับ","pricing_dropdown.show_details":"แสดงรายละเอียด","pricing_dropdown.hide_details":"ซ่อนรายละเอียด","pricing_table.tax":"ภาษี","pricing_table.trial_ends":"หลังจากช่วงทดลองใช้สิ้นสุด ในวันที่ {{formattedTrialEndDate}}","pricing_table.total_due_today":"ยอดรวมที่ต้องชำระวันนี้","pricing_table.total_excluding_tax":"ราคารวมก่อนภาษี","pricing_table.enter_billing_address_to_calculate":"กรุณากรอกที่อยู่สำหรับเรียกเก็บเงินเพื่อคำนวณ","pricing_table.enter_state_or_postal_code_to_calculate":"ใส่รัฐหรือรหัสไปรษณีย์เพื่อคำนวณ","pricing_table.enter_postal_code_to_calculate":"ใส่รหัสไปรษณีย์เพื่อคำนวณ","error_page.error_message_invalid_email_error":"ไม่สามารถยืนยันที่อยู่อีเมล {{email}} ได้ โปรดระบุที่อยู่อีเมลที่ถูกต้อง","payment_entry_page.button_payment_method":"ชำระเงิน {{formattedPrice}} ด้วย {{paymentMethod}}","payment_entry_page.button_with_price":"ชำระเงิน {{formattedPrice}}","price_update.title":"อัปเดตราคา","price_update.base_message":"ราคารวมได้รับการอัปเดตพร้อมภาษีตามที่อยู่สำหรับการเรียกเก็บเงินของคุณ โปรดตรวจสอบและลองอีกครั้ง บัตรของคุณจะถูกเรียกเก็บเงินเพียงครั้งเดียวเท่านั้น","price_update.trial_message":"ราคาการสมัครสมาชิกได้รับการอัปเดตเพื่อรวมภาษีตามที่อยู่สำหรับการเรียกเก็บเงินของคุณ ระยะเวลาทดลองใช้ฟรียังคงมีผล โปรดตรวจสอบและลองอีกครั้ง","payment_entry_page.express_checkout_divider":"หรือชำระด้วยบัตร","error_page.trouble_accessing":"หากคุณมีปัญหาในการเข้าถึงการซื้อ โปรดติดต่อฝ่ายสนับสนุนที่ ","error_page.close_button_title":"ไปที่ {{appName}}","error_page.error_title_stripe_missing_required_permission":"ขาดสิทธิ์ Stripe ที่จำเป็น","error_page.button_close":"ปิด","error_page.error_message_stripe_invalid_tax_origin_address":"การซื้อล้มเหลวเนื่องจากที่อยู่ต้นทางภาษีไม่ถูกต้อง ในสภาพแวดล้อมจริง การซื้อจะทำงานได้โดยไม่มีการเรียกเก็บภาษี","error_page.error_message_stripe_tax_not_active":"การซื้อล้มเหลวเนื่องจากไม่ได้เปิดใช้งาน Stripe Tax ในสภาพแวดล้อมจริง การซื้อจะทำงานได้โดยไม่มีการเรียกเก็บภาษี","error_page.error_only_in_sandbox":"ข้อความนี้จะปรากฏเฉพาะใน sandbox เท่านั้น","error_page.error_message_stripe_missing_required_permission":"การซื้อล้มเหลวเนื่องจากแอป Stripe ขาดสิทธิ์ที่จำเป็น ในสภาพแวดล้อมจริง การซื้อจะทำงานได้โดยไม่มีการเรียกเก็บภาษี","error_page.error_title_stripe_tax_not_active":"Stripe Tax ไม่เปิดใช้งาน","error_page.error_title_stripe_invalid_tax_origin_address":"ที่อยู่ต้นทางภาษีไม่ถูกต้อง","apple_pay.free_trial":"ทดลองใช้ฟรี","product_info.price_after_intro_price":"หลังจาก {{introPriceDuration}} ในวันที่ {{renewalDate}}","product_info.after_trial":"หลังช่วงทดลองใช้","product_info.after":"หลังจาก","product_info.intro_price_phase_after_trial":"จากนั้น {{introPriceDuration}} ในราคา {{introPrice}}","product_info.intro_price_phase":"ช่วงแรก {{introPriceDuration}} ในราคา {{introPrice}}","product_info.intro_price_phase_paid_once":"ชำระครั้งเดียว","payment_entry_page.trial_subscription_terms_info":"หลังจากช่วงทดลองใช้ของคุณสิ้นสุดลง คุณจะถูกเรียกเก็บเงิน {{price}} {{perFrequency}} เริ่มตั้งแต่วันที่ {{renewalDate}} คุณสามารถยกเลิกได้ตลอดเวลาก่อนวันดังกล่าว","payment_entry_page.subscription_info":"การสมัครรับข้อมูลจะต่ออายุโดยอัตโนมัติ ยกเลิกได้ตลอดเวลา","payment_entry_page.otp_terms_info":"เมื่อทำการซื้อ คุณตกลงที่จะอนุญาตให้ {{appName}} เรียกเก็บเงินจากคุณตามข้อกำหนดของพวกเขา","payment_entry_page.subscription_terms_info":"เมื่อสมัครรับข้อมูล แสดงว่าคุณยินยอมให้ {{appName}} เรียกเก็บเงินจากคุณตามข้อกำหนดจนกว่าคุณจะยกเลิก"},ZFA={"periods.week":"{{amount}} hafta","periods.month":"{{amount}} ay","periods.year":"{{amount}} yıl","periods.day":"{{amount}} gün","periods.weekShort":"{{amount}}hf","periods.monthShort":"{{amount}}ay","periods.yearShort":"{{amount}}yl","periods.dayShort":"{{amount}}g","periods.lifetime":"ömür boyu","periods.weekPlural":"{{amount}} hafta","periods.monthPlural":"{{amount}} ay","periods.yearPlural":"{{amount}} yıl","periods.dayPlural":"{{amount}} gün","periods.weekFrequency":"haftalık","periods.monthFrequency":"aylık","periods.yearFrequency":"yıllık","periods.dayFrequency":"günlük","periods.perWeekFrequency":"haftada","periods.perMonthFrequency":"ayda","periods.perYearFrequency":"yılda","periods.perDayFrequency":"günde","periods.unknownFrequency":"bilinmiyor","periods.weekFrequencyPlural":"her {{amount}} haftada","periods.monthFrequencyPlural":"her {{amount}} ayda","periods.yearFrequencyPlural":"her {{amount}} yılda","periods.dayFrequencyPlural":"her {{amount}} günde","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} ücretsiz deneme","product_info.price_after_free_trial":"Deneme süresi sona erdiğinde, {{renewalDate}} tarihinde","product_info.renewal_frequency":"{{frequency}} sıklığında yenilenir","product_info.continues_until_cancelled":"İptal edilene kadar devam eder","product_info.cancel_anytime":"İstediğiniz zaman iptal edebilirsiniz","payment_entry_page.payment_step_title":"RevenueCat ile güvenli ödeme","payment_entry_page.button_pay":"Şimdi öde","payment_entry_page.button_start_trial":"Denemeyi başlat","success_page.purchase_successful":"Ödeme tamamlandı","success_page.button_close":"Devam et","error_page.if_error_persists":"Hata devam ederse lütfen iletişime geçin ","error_page.error_title_already_subscribed":"{{productTitle}} ürününe zaten abone oldunuz","error_page.error_title_already_purchased":"{{productTitle}} ürününü zaten satın aldınız","error_page.error_title_other_errors":"Bir şeyler ters gitti","error_page.error_message_already_subscribed":"Bu ürüne tekrar abone olamazsınız.","error_page.error_message_already_purchased":"Bu ürünü tekrar satın alamazsınız.","error_page.error_message_missing_email_error":"Satın almayı tamamlamak için e-posta gereklidir.","error_page.error_message_network_error":"Ağ hatası. Lütfen internet bağlantınızı kontrol edin.","error_page.error_message_error_charging_payment":"Ödeme başarısız oldu.","error_page.error_message_error_setting_up_purchase":"Bir hata nedeniyle satın alma başlatılamadı (hata kodu: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Fatura adresinizi doğrulayamadık. Lütfen posta kodu ve ülkenin doğru olduğunu kontrol edin.","error_page.error_message_unknown_error":"Bilinmeyen bir hata oluştu (hata kodu: {{errorCode}}).","error_page.button_try_again":"Tekrar dene","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% indirim","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Bugün ödenecek toplam tutar","product_info.subscribe_to":"Abone Ol","navbar_header.details":"Detaylar","navbar_header.back_button":"Geri","pricing_dropdown.show_details":"Detayları göster","pricing_dropdown.hide_details":"Detayları gizle","pricing_table.tax":"Vergi","pricing_table.trial_ends":"Deneme süresi sona erdikten sonra, {{formattedTrialEndDate}} tarihinde","pricing_table.total_due_today":"Bugün ödenecek toplam","pricing_table.total_excluding_tax":"Vergi hariç toplam","pricing_table.enter_billing_address_to_calculate":"Hesaplamak için fatura adresini girin","pricing_table.enter_state_or_postal_code_to_calculate":"Hesaplamak için eyalet veya posta kodunu girin","pricing_table.enter_postal_code_to_calculate":"Hesaplamak için posta kodunu girin","error_page.error_message_invalid_email_error":"{{email}} e-posta adresi doğrulanamadı. Lütfen geçerli bir e-posta adresi girin.","payment_entry_page.button_payment_method":"{{paymentMethod}} ile {{formattedPrice}} öde","payment_entry_page.button_with_price":"{{formattedPrice}} öde","price_update.title":"Fiyat güncellemesi","price_update.base_message":"Toplam fiyat, fatura adresinize göre vergi dahil olacak şekilde güncellendi. Lütfen inceleyip tekrar deneyin. Kartınızdan yalnızca bir kez ücret alınacaktır.","price_update.trial_message":"Abonelik fiyatı, fatura adresinize göre vergileri içerecek şekilde güncellendi. Ücretsiz deneme süresi hala geçerli. Lütfen kontrol edin ve tekrar deneyin.","payment_entry_page.express_checkout_divider":"VEYA KARTLA ÖDEYİN","error_page.trouble_accessing":"Satın alımınıza erişmekte sorun yaşıyorsanız, şu adresten destek ekibine ulaşın: ","error_page.close_button_title":"{{appName}}'e Git","error_page.error_title_stripe_missing_required_permission":"Eksik Stripe izni","error_page.button_close":"Kapat","error_page.error_message_stripe_invalid_tax_origin_address":"Vergi başlangıç adresi geçersiz olduğu için satın alma başarısız oldu. Üretimde, satın alımlar vergi uygulanmadan çalışacaktır.","error_page.error_message_stripe_tax_not_active":"Stripe Vergi etkinleştirilmediği için satın alma başarısız oldu. Üretimde, satın alımlar vergi uygulanmadan çalışacaktır.","error_page.error_only_in_sandbox":"Bu mesaj yalnızca sanal ortamda görünür.","error_page.error_message_stripe_missing_required_permission":"Stripe uygulamasında gerekli bir izin eksik olduğu için satın alma başarısız oldu. Üretimde, satın alımlar vergi uygulanmadan çalışacaktır.","error_page.error_title_stripe_tax_not_active":"Stripe Vergi aktif değil","error_page.error_title_stripe_invalid_tax_origin_address":"Geçersiz vergi başlangıç adresi","apple_pay.free_trial":"Ücretsiz Deneme","product_info.price_after_intro_price":"{{introPriceDuration}} sonra, {{renewalDate}} tarihinde","product_info.after_trial":"deneme süresinden sonra","product_info.after":"sonra","product_info.intro_price_phase_after_trial":"Sonra {{introPriceDuration}} boyunca {{introPrice}}","product_info.intro_price_phase":"İlk {{introPriceDuration}} boyunca {{introPrice}}","product_info.intro_price_phase_paid_once":"bir defaya mahsus ödenir","payment_entry_page.trial_subscription_terms_info":"Deneme süreniz sona erdikten sonra, {{renewalDate}} tarihinden itibaren {{price}} {{perFrequency}} ücretlendirileceksiniz. Bu tarihten önce istediğiniz zaman iptal edebilirsiniz.","payment_entry_page.subscription_info":"Abonelik otomatik olarak yenilenir. İstediğiniz zaman iptal edin.","payment_entry_page.otp_terms_info":"Satın alarak, {{appName}}'in sizi şartlarına göre ücretlendirmesine izin vermeyi kabul edersiniz.","payment_entry_page.subscription_terms_info":"Abone olarak, iptal edene kadar {{appName}}'in sizi şartlarına göre ücretlendirmesine izin vermeyi kabul edersiniz."},WFA={"periods.week":"{{amount}} тиждень","periods.month":"{{amount}} місяць","periods.year":"{{amount}} рік","periods.day":"{{amount}} день","periods.weekShort":"{{amount}}тиж","periods.monthShort":"{{amount}}міс","periods.yearShort":"{{amount}}рік","periods.dayShort":"{{amount}}дн","periods.lifetime":"пожиттєво","periods.weekPlural":"{{amount}} тижнів","periods.monthPlural":"{{amount}} місяців","periods.yearPlural":"{{amount}} років","periods.dayPlural":"{{amount}} днів","periods.weekFrequency":"щотижня","periods.monthFrequency":"щомісяця","periods.yearFrequency":"щороку","periods.dayFrequency":"щодня","periods.perWeekFrequency":"на тиждень","periods.perMonthFrequency":"на місяць","periods.perYearFrequency":"на рік","periods.perDayFrequency":"на день","periods.unknownFrequency":"невідомо","periods.weekFrequencyPlural":"кожні {{amount}} тижнів","periods.monthFrequencyPlural":"кожні {{amount}} місяців","periods.yearFrequencyPlural":"кожні {{amount}} років","periods.dayFrequencyPlural":"кожні {{amount}} днів","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} безкоштовний пробний період","product_info.price_after_free_trial":"Після закінчення пробного періоду, {{renewalDate}}","product_info.renewal_frequency":"Продовжується {{frequency}}","product_info.continues_until_cancelled":"Триває до скасування","product_info.cancel_anytime":"Можна скасувати в будь-який час","payment_entry_page.payment_step_title":"Безпечна оплата через RevenueCat","payment_entry_page.button_pay":"Оплатити зараз","payment_entry_page.button_start_trial":"Розпочати пробний період","success_page.purchase_successful":"Оплата завершена","success_page.button_close":"Продовжити","error_page.if_error_persists":"Якщо помилка повторюється, зверніться до ","error_page.error_title_already_subscribed":"Ви вже підписалися на {{productTitle}}","error_page.error_title_already_purchased":"Ви вже придбали {{productTitle}}","error_page.error_title_other_errors":"Щось пішло не так","error_page.error_message_already_subscribed":"Ви не можете підписатися на цей продукт знову.","error_page.error_message_already_purchased":"Ви не можете придбати цей продукт знову.","error_page.error_message_missing_email_error":"Для завершення покупки потрібна електронна пошта.","error_page.error_message_network_error":"Помилка мережі. Перевірте підключення до інтернету.","error_page.error_message_error_charging_payment":"Оплата не пройшла.","error_page.error_message_error_setting_up_purchase":"Помилка при ініціалізації покупки (код помилки: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Ми не змогли перевірити вашу платіжну адресу. Будь ласка, перевірте, чи правильні поштовий індекс та країна.","error_page.error_message_unknown_error":"Сталася невідома помилка (код помилки: {{errorCode}}).","error_page.button_try_again":"Спробувати ще раз","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% знижки","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Всього до сплати сьогодні","product_info.subscribe_to":"Підписатися на","navbar_header.details":"Деталі","navbar_header.back_button":"Назад","pricing_dropdown.show_details":"Показати деталі","pricing_dropdown.hide_details":"Приховати деталі","pricing_table.tax":"Податок","pricing_table.trial_ends":"Після закінчення пробного періоду, {{formattedTrialEndDate}}","pricing_table.total_due_today":"Загальна сума до сплати сьогодні","pricing_table.total_excluding_tax":"Загальна сума без урахування податку","pricing_table.enter_billing_address_to_calculate":"Введіть адресу виставлення рахунку для розрахунку","pricing_table.enter_state_or_postal_code_to_calculate":"Введіть штат або поштовий індекс для розрахунку","pricing_table.enter_postal_code_to_calculate":"Введіть поштовий індекс для розрахунку","error_page.error_message_invalid_email_error":"Електронну адресу {{email}} не вдалося підтвердити. Будь ласка, вкажіть дійсну електронну адресу.","payment_entry_page.button_payment_method":"Сплатити {{formattedPrice}} за допомогою {{paymentMethod}}","payment_entry_page.button_with_price":"Сплатити {{formattedPrice}}","price_update.title":"Оновлення ціни","price_update.base_message":"Загальну ціну було оновлено з урахуванням податку на основі вашої платіжної адреси. Перегляньте та спробуйте ще раз. З вашої картки буде списано кошти лише один раз.","price_update.trial_message":"Ціна підписки була оновлена для включення податків на основі вашої платіжної адреси. Безкоштовний пробний період все ще діє. Будь ласка, перевірте та спробуйте ще раз.","payment_entry_page.express_checkout_divider":"АБО СПЛАТІТЬ КАРТКОЮ","error_page.trouble_accessing":"Якщо у вас виникли проблеми з доступом до вашої покупки, зверніться до служби підтримки за адресою ","error_page.close_button_title":"Перейти до {{appName}}","error_page.error_title_stripe_missing_required_permission":"Відсутній дозвіл Stripe","error_page.button_close":"Закрити","error_page.error_message_stripe_invalid_tax_origin_address":"Покупка не вдалася, оскільки адреса походження податку недійсна. У виробництві покупки працюватимуть без застосування податків.","error_page.error_message_stripe_tax_not_active":"Покупка не вдалася, оскільки Stripe Tax не ввімкнено. У виробництві покупки працюватимуть без застосування податків.","error_page.error_only_in_sandbox":"Це повідомлення з’являється лише в пісочниці.","error_page.error_message_stripe_missing_required_permission":"Покупка не вдалася, оскільки програмі Stripe не вистачає необхідного дозволу. У виробництві покупки працюватимуть без застосування податків.","error_page.error_title_stripe_tax_not_active":"Stripe Tax не активовано","error_page.error_title_stripe_invalid_tax_origin_address":"Недійсна адреса походження податку","apple_pay.free_trial":"Безкоштовна пробна версія","product_info.price_after_intro_price":"Після {{introPriceDuration}}, {{renewalDate}}","product_info.after_trial":"після пробного періоду","product_info.after":"після","product_info.intro_price_phase_after_trial":"Потім {{introPriceDuration}} за {{introPrice}}","product_info.intro_price_phase":"Спочатку {{introPriceDuration}} за {{introPrice}}","product_info.intro_price_phase_paid_once":"сплачено один раз","payment_entry_page.trial_subscription_terms_info":"Після закінчення пробного періоду з вас буде стягуватися плата в розмірі {{price}} {{perFrequency}} починаючи з {{renewalDate}}. Ви можете скасувати підписку в будь-який час до цієї дати.","payment_entry_page.subscription_info":"Підписка поновлюється автоматично. Скасувати можна в будь-який час.","payment_entry_page.otp_terms_info":"Купуючи, ви погоджуєтеся дозволити {{appName}} стягувати з вас плату відповідно до їхніх умов.","payment_entry_page.subscription_terms_info":"Підписуючись, ви погоджуєтеся дозволити {{appName}} стягувати з вас плату відповідно до їхніх умов, поки ви не скасуєте підписку."},VFA={"periods.week":"{{amount}} tuần","periods.month":"{{amount}} tháng","periods.year":"{{amount}} năm","periods.day":"{{amount}} ngày","periods.weekShort":"{{amount}}tuần","periods.monthShort":"{{amount}}tháng","periods.yearShort":"{{amount}}năm","periods.dayShort":"{{amount}}ngày","periods.lifetime":"trọn đời","periods.weekPlural":"{{amount}} tuần","periods.monthPlural":"{{amount}} tháng","periods.yearPlural":"{{amount}} năm","periods.dayPlural":"{{amount}} ngày","periods.weekFrequency":"hàng tuần","periods.monthFrequency":"hàng tháng","periods.yearFrequency":"hàng năm","periods.dayFrequency":"hàng ngày","periods.perWeekFrequency":"mỗi tuần","periods.perMonthFrequency":"mỗi tháng","periods.perYearFrequency":"mỗi năm","periods.perDayFrequency":"mỗi ngày","periods.unknownFrequency":"không xác định","periods.weekFrequencyPlural":"cứ {{amount}} tuần","periods.monthFrequencyPlural":"cứ {{amount}} tháng","periods.yearFrequencyPlural":"cứ {{amount}} năm","periods.dayFrequencyPlural":"cứ {{amount}} ngày","product_info.product_title":"{{productTitle}}","product_info.product_description":"{{productDescription}}","product_info.product_price":"{{productPrice}}","product_info.free_trial_duration":"{{trialDuration}} dùng thử miễn phí","product_info.price_after_free_trial":"Sau khi dùng thử kết thúc, vào {{renewalDate}}","product_info.renewal_frequency":"Gia hạn {{frequency}}","product_info.continues_until_cancelled":"Tiếp tục cho đến khi hủy","product_info.cancel_anytime":"Hủy bất cứ lúc nào","payment_entry_page.payment_step_title":"Thanh toán an toàn bởi RevenueCat","payment_entry_page.button_pay":"Thanh toán ngay","payment_entry_page.button_start_trial":"Bắt đầu dùng thử","success_page.purchase_successful":"Thanh toán hoàn tất","success_page.button_close":"Tiếp tục","error_page.if_error_persists":"Nếu lỗi vẫn tiếp diễn, vui lòng liên hệ ","error_page.error_title_already_subscribed":"Bạn đã đăng ký {{productTitle}} rồi","error_page.error_title_already_purchased":"Bạn đã mua {{productTitle}} rồi","error_page.error_title_other_errors":"Có lỗi xảy ra","error_page.error_message_already_subscribed":"Bạn không thể đăng ký sản phẩm này lần nữa.","error_page.error_message_already_purchased":"Bạn không thể mua sản phẩm này lần nữa.","error_page.error_message_missing_email_error":"Email bắt buộc để hoàn tất việc mua hàng.","error_page.error_message_network_error":"Lỗi mạng. Vui lòng kiểm tra kết nối internet của bạn.","error_page.error_message_error_charging_payment":"Thanh toán thất bại.","error_page.error_message_error_setting_up_purchase":"Không thể bắt đầu mua do lỗi (mã lỗi: {{errorCode}}).","error_page.error_message_invalid_tax_location":"Chúng tôi không thể xác minh địa chỉ thanh toán của bạn. Vui lòng kiểm tra lại mã bưu điện và quốc gia.","error_page.error_message_unknown_error":"Đã xảy ra lỗi không xác định (mã lỗi: {{errorCode}}).","error_page.button_try_again":"Thử lại","paywall_variables.price_per_period":"{{formattedPrice}}/{{period}}","paywall_variables.sub_relative_discount":"{{discount}}% giảm","paywall_variables.total_price_and_per_month":"{{formattedPrice}}/{{period}}({{formattedPricePerMonth}}/{{monthPeriod}})","product_info.total_due_today":"Tổng số tiền phải trả hôm nay","product_info.subscribe_to":"Đăng ký","navbar_header.details":"Chi tiết","navbar_header.back_button":"Quay lại","pricing_dropdown.show_details":"Xem chi tiết","pricing_dropdown.hide_details":"Ẩn chi tiết","pricing_table.tax":"Thuế","pricing_table.trial_ends":"Sau khi thời gian dùng thử kết thúc, vào {{formattedTrialEndDate}}","pricing_table.total_due_today":"Tổng số tiền phải trả hôm nay","pricing_table.total_excluding_tax":"Tổng cộng chưa bao gồm thuế","pricing_table.enter_billing_address_to_calculate":"Nhập địa chỉ thanh toán để tính toán","pricing_table.enter_state_or_postal_code_to_calculate":"Nhập tiểu bang hoặc mã bưu điện để tính toán","pricing_table.enter_postal_code_to_calculate":"Nhập mã bưu điện để tính toán","error_page.error_message_invalid_email_error":"Không thể xác minh địa chỉ email {{email}}. Vui lòng cung cấp một địa chỉ email hợp lệ.","payment_entry_page.button_payment_method":"Thanh toán {{formattedPrice}} bằng {{paymentMethod}}","payment_entry_page.button_with_price":"Thanh toán {{formattedPrice}}","price_update.title":"Cập nhật giá","price_update.base_message":"Tổng giá đã được cập nhật với thuế dựa trên địa chỉ thanh toán của bạn. Vui lòng xem lại và thử lại. Thẻ của bạn sẽ chỉ bị tính phí một lần.","price_update.trial_message":"Giá đăng ký đã được cập nhật để bao gồm thuế dựa trên địa chỉ thanh toán của bạn. Thời gian dùng thử miễn phí vẫn được áp dụng. Vui lòng kiểm tra và thử lại.","payment_entry_page.express_checkout_divider":"HOẶC THANH TOÁN BẰNG THẺ","error_page.trouble_accessing":"Nếu bạn gặp sự cố khi truy cập giao dịch mua của mình, hãy liên hệ với bộ phận hỗ trợ theo địa chỉ ","error_page.close_button_title":"Đi đến {{appName}}","error_page.error_title_stripe_missing_required_permission":"Thiếu quyền Stripe","error_page.button_close":"Đóng","error_page.error_message_stripe_invalid_tax_origin_address":"Giao dịch mua không thành công vì địa chỉ gốc thuế không hợp lệ. Trong môi trường thực tế, giao dịch mua sẽ hoạt động mà không áp dụng thuế.","error_page.error_message_stripe_tax_not_active":"Giao dịch mua không thành công vì Thuế Stripe chưa được bật. Trong môi trường thực tế, giao dịch mua sẽ hoạt động mà không áp dụng thuế.","error_page.error_only_in_sandbox":"Thông báo này chỉ xuất hiện trong môi trường thử nghiệm.","error_page.error_message_stripe_missing_required_permission":"Giao dịch mua không thành công vì ứng dụng Stripe thiếu một quyền cần thiết. Trong môi trường thực tế, giao dịch mua sẽ hoạt động mà không áp dụng thuế.","error_page.error_title_stripe_tax_not_active":"Thuế Stripe chưa hoạt động","error_page.error_title_stripe_invalid_tax_origin_address":"Địa chỉ gốc thuế không hợp lệ","apple_pay.free_trial":"Dùng thử miễn phí","product_info.price_after_intro_price":"Sau {{introPriceDuration}}, vào {{renewalDate}}","product_info.after_trial":"sau khi dùng thử","product_info.after":"sau","product_info.intro_price_phase_after_trial":"Sau đó {{introPriceDuration}} với giá {{introPrice}}","product_info.intro_price_phase":"{{introPriceDuration}} đầu tiên với giá {{introPrice}}","product_info.intro_price_phase_paid_once":"trả một lần","payment_entry_page.trial_subscription_terms_info":"Sau khi thời gian dùng thử của bạn kết thúc, bạn sẽ bị tính phí {{price}} {{perFrequency}} bắt đầu từ {{renewalDate}}. Bạn có thể hủy bất cứ lúc nào trước ngày này.","payment_entry_page.subscription_info":"Gói đăng ký tự động gia hạn. Hủy bất cứ lúc nào.","payment_entry_page.otp_terms_info":"Bằng cách mua, bạn đồng ý cho phép {{appName}} tính phí bạn theo các điều khoản của họ.","payment_entry_page.subscription_terms_info":"Bằng cách đăng ký, bạn đồng ý cho phép {{appName}} tính phí bạn theo các điều khoản của họ cho đến khi bạn hủy."};var oi=(e=>(e.PeriodsWeek="periods.week",e.PeriodsMonth="periods.month",e.PeriodsYear="periods.year",e.PeriodsDay="periods.day",e.PeriodsWeekShort="periods.weekShort",e.PeriodsMonthShort="periods.monthShort",e.PeriodsYearShort="periods.yearShort",e.PeriodsDayShort="periods.dayShort",e.PeriodsLifetime="periods.lifetime",e.PeriodsWeekPlural="periods.weekPlural",e.PeriodsMonthPlural="periods.monthPlural",e.PeriodsYearPlural="periods.yearPlural",e.PeriodsDayPlural="periods.dayPlural",e.PeriodsWeekFrequency="periods.weekFrequency",e.PeriodsMonthFrequency="periods.monthFrequency",e.PeriodsYearFrequency="periods.yearFrequency",e.PeriodsDayFrequency="periods.dayFrequency",e.PeriodsPerWeekFrequency="periods.perWeekFrequency",e.PeriodsPerMonthFrequency="periods.perMonthFrequency",e.PeriodsPerYearFrequency="periods.perYearFrequency",e.PeriodsPerDayFrequency="periods.perDayFrequency",e.PeriodsUnknownFrequency="periods.unknownFrequency",e.PeriodsWeekFrequencyPlural="periods.weekFrequencyPlural",e.PeriodsMonthFrequencyPlural="periods.monthFrequencyPlural",e.PeriodsYearFrequencyPlural="periods.yearFrequencyPlural",e.PeriodsDayFrequencyPlural="periods.dayFrequencyPlural",e.ProductInfoProductTitle="product_info.product_title",e.ProductInfoProductDescription="product_info.product_description",e.ProductInfoProductPrice="product_info.product_price",e.ProductInfoFreeTrialDuration="product_info.free_trial_duration",e.ProductInfoPriceAfterFreeTrial="product_info.price_after_free_trial",e.ProductInfoIntroPricePhaseAfterTrial="product_info.intro_price_phase_after_trial",e.ProductInfoIntroPricePhasePaidOnce="product_info.intro_price_phase_paid_once",e.ProductInfoIntroPricePhase="product_info.intro_price_phase",e.ProductInfoPriceAfterIntroPrice="product_info.price_after_intro_price",e.ProductInfoAfterTrial="product_info.after_trial",e.ProductInfoAfter="product_info.after",e.ProductInfoPriceTotalDueToday="product_info.total_due_today",e.ProductInfoSubscribeTo="product_info.subscribe_to",e.ProductInfoRenewalFrequency="product_info.renewal_frequency",e.ProductInfoContinuesUntilCancelled="product_info.continues_until_cancelled",e.ProductInfoCancelAnytime="product_info.cancel_anytime",e.PaymentEntryPagePaymentStepTitle="payment_entry_page.payment_step_title",e.PaymentEntryPageTrialSubscriptionTermsInfo="payment_entry_page.trial_subscription_terms_info",e.PaymentEntryPageSubscriptionTermsInfo="payment_entry_page.subscription_terms_info",e.PaymentEntryPageOtpTermsInfo="payment_entry_page.otp_terms_info",e.PaymentEntryPageSubscriptionInfo="payment_entry_page.subscription_info",e.PaymentEntryPageButtonPay="payment_entry_page.button_pay",e.PaymentEntryPageButtonStartTrial="payment_entry_page.button_start_trial",e.PaymentEntryPageButtonWithPrice="payment_entry_page.button_with_price",e.PaymentEntryPageButtonPaymentMethod="payment_entry_page.button_payment_method",e.PaymentEntryPageExpressCheckoutDivider="payment_entry_page.express_checkout_divider",e.SuccessPagePurchaseSuccessful="success_page.purchase_successful",e.SuccessPageButtonClose="success_page.button_close",e.ErrorPageCloseButtonTitle="error_page.close_button_title",e.ErrorPageIfErrorPersists="error_page.if_error_persists",e.ErrorPageTroubleAccessing="error_page.trouble_accessing",e.ErrorPageErrorTitleAlreadySubscribed="error_page.error_title_already_subscribed",e.ErrorPageErrorTitleAlreadyPurchased="error_page.error_title_already_purchased",e.ErrorPageErrorTitleOtherErrors="error_page.error_title_other_errors",e.ErrorPageErrorTitleStripeTaxNotActive="error_page.error_title_stripe_tax_not_active",e.ErrorPageErrorTitleStripeInvalidTaxOriginAddress="error_page.error_title_stripe_invalid_tax_origin_address",e.ErrorPageErrorTitleStripeMissingRequiredPermission="error_page.error_title_stripe_missing_required_permission",e.ErrorPageErrorMessageAlreadySubscribed="error_page.error_message_already_subscribed",e.ErrorPageErrorMessageAlreadyPurchased="error_page.error_message_already_purchased",e.ErrorPageErrorMessageMissingEmailError="error_page.error_message_missing_email_error",e.ErrorPageErrorMessageInvalidEmailError="error_page.error_message_invalid_email_error",e.ErrorPageErrorMessageNetworkError="error_page.error_message_network_error",e.ErrorPageErrorMessageErrorChargingPayment="error_page.error_message_error_charging_payment",e.ErrorPageErrorMessageErrorSettingUpPurchase="error_page.error_message_error_setting_up_purchase",e.ErrorPageErrorMessageUnknownError="error_page.error_message_unknown_error",e.ErrorPageErrorMessageInvalidTaxLocation="error_page.error_message_invalid_tax_location",e.ErrorPageErrorMessageStripeTaxNotActive="error_page.error_message_stripe_tax_not_active",e.ErrorPageErrorMessageStripeInvalidTaxOriginAddress="error_page.error_message_stripe_invalid_tax_origin_address",e.ErrorPageErrorMessageStripeMissingRequiredPermission="error_page.error_message_stripe_missing_required_permission",e.ErrorPageErrorMessageOnlyInSandbox="error_page.error_only_in_sandbox",e.ErrorButtonTryAgain="error_page.button_try_again",e.ErrorButtonClose="error_page.button_close",e.PaywallVariablesPricePerPeriod="paywall_variables.price_per_period",e.PaywallVariablesSubRelativeDiscount="paywall_variables.sub_relative_discount",e.PaywallVariablesTotalPriceAndPerMonth="paywall_variables.total_price_and_per_month",e.PricingDropdownShowDetails="pricing_dropdown.show_details",e.PricingDropdownHideDetails="pricing_dropdown.hide_details",e.PricingTotalExcludingTax="pricing_table.total_excluding_tax",e.PricingTableTrialEnds="pricing_table.trial_ends",e.PricingTableTotalDueToday="pricing_table.total_due_today",e.PricingTableTax="pricing_table.tax",e.PricingTableEnterBillingAddressToCalculate="pricing_table.enter_billing_address_to_calculate",e.PricingTableEnterStateOrPostalCodeToCalculate="pricing_table.enter_state_or_postal_code_to_calculate",e.PricingTableEnterPostalCodeToCalculate="pricing_table.enter_postal_code_to_calculate",e.NavbarHeaderDetails="navbar_header.details",e.NavbarBackButton="navbar_header.back_button",e.PriceUpdateTitle="price_update.title",e.PriceUpdateBaseMessage="price_update.base_message",e.PriceUpdateTrialMessage="price_update.trial_message",e.ApplePayFreeTrial="apple_pay.free_trial",e))(oi||{});const XFA={en:hFA,es:pFA,it:fFA,ar:yFA,ca:DFA,zh_Hans:mFA,zh_Hant:SFA,hr:wFA,cs:kFA,da:MFA,nl:NFA,fi:RFA,fr:GFA,de:bFA,el:UFA,he:vFA,hi:KFA,hu:FFA,id:_FA,ja:JFA,ko:LFA,ms:xFA,no:TFA,pl:qFA,pt:YFA,ro:HFA,ru:OFA,sk:PFA,sv:jFA,th:zFA,tr:ZFA,uk:WFA,vi:VFA};var Sa=(e=>(e.Year="year",e.Month="month",e.Week="week",e.Day="day",e))(Sa||{});function GlA(e){const A=e.match(/^PT?([0-9]+)([MDYW])$/);if(!A||A.length<3)return $i.errorLog(`Invalid ISO 8601 duration format: ${e}`),null;const t=parseInt(A[1]);switch(A[2]){case"Y":return{number:t,unit:"year"};case"M":return{number:t,unit:"month"};case"W":return{number:t,unit:"week"};case"D":return{number:t,unit:"day"};default:return $i.errorLog(`Invalid ISO 8601 unit duration format: ${e}`),null}}function u1(e,A,t){if(!t)return null;let i=new Date(e);switch(A.unit){case"year":i.getDate()===29&&i.getMonth()===1&&A.number!==4?i.setFullYear(i.getFullYear()+A.number,i.getMonth(),28):i.setFullYear(i.getFullYear()+A.number,i.getMonth(),i.getDate());break;case"month":i.setMonth(i.getMonth()+A.number,i.getDate()),i.getDate()!==e.getDate()&&(i=new Date(e),i.setMonth(i.getMonth()+A.number+1,0));break;case"week":i.setDate(i.getDate()+A.number*7);break;case"day":i.setDate(i.getDate()+A.number);break}return i}const $FA=e=>e/1e6,ju=(e,A,t,i={})=>{const n=$FA(e),g={style:"currency",currency:A,currencyDisplay:"symbol",...i,minimumFractionDigits:i.maximumFractionDigits};return new Intl.NumberFormat(t,g).format(n).replace("US$","$")},A_A=(e,A)=>{const t=GlA(e);return t?A.translatePeriod(t.number,t.unit)||`${t.number} ${t.unit}s`:e},e_A=e=>{try{return e.charAt(0).toUpperCase()+e.slice(1)}catch{return e}},WD={noWhitespace:!1,short:!1},blA={useMultipleWords:!1};class KL{constructor(A={},t=wm,i=wm){Yt(this,"locales",{}),this.selectedLocale=t,this.defaultLocale=i;const n={};Object.entries(XFA).forEach(([g,o])=>{n[g]=new c7(o,g)}),this.locales=n,A&&this.override(A)}static fallback(){return new KL}override(A){Object.entries(A).forEach(([t,i])=>{this.locales[t]=new c7({...this.locales[t].labels||{},...i},this.getLanguageCodeString(t))})}formatPrice(A,t){const i={currencyDisplay:"narrowSymbol"};A===0&&(i.maximumFractionDigits=0);try{return ju(A,t,this.locale,i)}catch{$i.errorLog(`Failed to create a price formatter for locale: ${this.locale}`)}try{return ju(A,t,this.fallbackLocale,i)}catch{$i.errorLog(`Failed to create a price formatter for locale: ${this.fallbackLocale}`)}return ju(A,t,wm,i)}get locale(){var A;return((A=this.getLocaleInstance(this.selectedLocale))==null?void 0:A.localeKey)||this.getLanguageCodeString(this.selectedLocale)}get fallbackLocale(){var A;return((A=this.getLocaleInstance(this.defaultLocale))==null?void 0:A.localeKey)||this.getLanguageCodeString(this.defaultLocale)}getLanguageCodeString(A){return A.split("_")[0].split("-")[0]}getLocaleInstance(A){const t=this.getLanguageCodeString(A);return this.locales[A]||this.locales[t]}translate(A,t){const i=this.getLocaleInstance(this.selectedLocale),n=this.getLocaleInstance(this.defaultLocale);return(i==null?void 0:i.translate(A,t))||(n==null?void 0:n.translate(A,t))||""}formatCountry(A){return new Intl.DisplayNames([this.locale],{type:"region"}).of(A)||A}translatePeriod(A,t,i=WD){const n=this.getLocaleInstance(this.selectedLocale),g=this.getLocaleInstance(this.defaultLocale);return(n==null?void 0:n.translatePeriod(A,t,i))||(g==null?void 0:g.translatePeriod(A,t,i))}translatePeriodUnit(A,t=WD){const i=this.getLocaleInstance(this.selectedLocale),n=this.getLocaleInstance(this.defaultLocale);return(i==null?void 0:i.translatePeriodUnit(A,t))||(n==null?void 0:n.translatePeriodUnit(A,t))}translatePeriodFrequency(A,t,i=blA){const n=this.getLocaleInstance(this.selectedLocale),g=this.getLocaleInstance(this.defaultLocale);return(n==null?void 0:n.translatePeriodFrequency(A,t,i))||(g==null?void 0:g.translatePeriodFrequency(A,t,i))}translateDate(A,t={}){const i=this.getLocaleInstance(this.selectedLocale),n=this.getLocaleInstance(this.defaultLocale);return(i==null?void 0:i.translateDate(A,t))||(n==null?void 0:n.translateDate(A,t))}}class c7{constructor(A={},t){this.labels=A,this.localeKey=t}replaceVariables(A,t){return Object.entries(t).reduce((i,[n,g])=>i.replace(`{{${n}}}`,`${g??""}`),A)}translate(A,t){const i=this.labels[A];if(i)return this.replaceVariables(i,t||{})}translatePeriod(A,t,i=WD){var n;const{noWhitespace:g,short:o}={...WD,...i},s=o?`periods.${t}Short`:Math.abs(A)===1?`periods.${t}`:`periods.${t}Plural`;return(n=this.translate(s,{amount:A.toString()}))==null?void 0:n.replace(" ",g?"":" ")}translatePeriodUnit(A,t=WD){var i;const{noWhitespace:n,short:g}={...WD,...t},o=`periods.${A}${g?"Short":""}`;return(i=this.translate(o,{amount:""}))==null?void 0:i.replace(" ",n?"":" ")}translatePeriodFrequency(A,t,i=blA){const n=i==null?void 0:i.useMultipleWords,g=Math.abs(A)===1?`periods.${n===!0?"per":""}${n?e_A(t.toString()):t}Frequency`:`periods.${t}FrequencyPlural`;return this.translate(g,{amount:A.toString()})}translateDate(A,t={}){return A.toLocaleDateString(this.localeKey,t)}}kKA();const t_A=`<svg viewBox="0 0 124 124" fill="var(--rc-color-grey-text-dark)" xmlns="http://www.w3.org/2000/svg">
    <circle cx="62" cy="62" r="62" fill="var(--rc-color-grey-text-dark)" opacity="0.2"/>
    <path d="M87.6668 41.504L82.4968 36.334L62.0002 56.8307L41.5035 36.334L36.3335 41.504L56.8302 62.0006L36.3335 82.4973L41.5035 87.6673L62.0002 67.1706L82.4968 87.6673L87.6668 82.4973L67.1702 62.0006L87.6668 41.504Z"
          />
</svg>
`;var i_A=Nt('<div style="color:var(--rc-color-primary);"><!></div>');function UlA(e){var A=i_A(),t=Ve(A);bd(t,()=>t_A),Ne(e,A)}var d1;(function(e){e.body_s="p",e.body_m="p",e.body_l="p",e.body_xl="p",e.heading_xs="h6",e.heading_s="h5",e.heading_m="h4",e.heading_l="h3",e.heading_xl="h2",e.heading_xxl="h1"})(d1||(d1={}));var KF;(function(e){e[e.extra_light=100]="extra_light",e[e.thin=200]="thin",e[e.light=300]="light",e[e.regular=400]="regular",e[e.medium=500]="medium",e[e.semibold=600]="semibold",e[e.bold=700]="bold",e[e.extra_bold=800]="extra_bold",e[e.black=900]="black"})(KF||(KF={}));var FF;(function(e){e.body_s="13px",e.body_m="14px",e.body_l="15px",e.body_xl="16px",e.heading_xs="14px",e.heading_s="16px",e.heading_m="18px",e.heading_l="20px",e.heading_xl="26px",e.heading_xxl="32px"})(FF||(FF={}));var _F;(function(e){e.leading="start",e.center="center",e.trailing="end"})(_F||(_F={}));var h1;(function(e){e.vertical="column",e.horizontal="row",e.zlayer="zstack"})(h1||(h1={}));var p1;(function(e){e.top="flex-start",e.leading="flex-start",e.center="center",e.bottom="flex-end",e.trailing="flex-end"})(p1||(p1={}));var f1;(function(e){e.space_between="space-between",e.space_around="space-around",e.space_evenly="space-evenly",e.start="flex-start",e.center="center",e.end="flex-end"})(f1||(f1={}));const n_A=["product_name","price","price_per_period","price_per_period_full","total_price_and_per_month","total_price_and_per_month_full","sub_price_per_month","sub_price_per_week","sub_duration","sub_duration_in_months","sub_period","sub_period_length","sub_period_abbreviated","sub_offer_duration","sub_offer_duration_2","sub_offer_price","sub_offer_price_2","sub_relative_discount"],g_A=({value:e="",variableDictionary:A})=>A?n_A.reduce((t,i)=>{var n;return t.replaceAll(`{{ ${i} }}`,((n=A[i])==null?void 0:n.toString())||"N/A")},e):e;function vlA(e,A,t,i){var n;if(!e)return"";const g=(n=i[t])==null?void 0:n[e];return(i[A]||{})[e]?i[A][e]:g}function F8({text_lid:e,locale:A,defaultLocale:t,labels:i,variableDictionary:n}){if(!e)return"";const g=vlA(e,A,t,i);return g_A({value:g,variableDictionary:n})}const Jy=[];function o_A(e,A){return{subscribe:KlA(e,A).subscribe}}function KlA(e,A=cg){let t=null;const i=new Set;function n(s){if(AlA(e,s)&&(e=s,t)){const a=!Jy.length;for(const r of i)r[1](),Jy.push(r,e);if(a){for(let r=0;r<Jy.length;r+=2)Jy[r][0](Jy[r+1]);Jy.length=0}}}function g(s){n(s(e))}function o(s,a=cg){const r=[s,a];return i.add(r),i.size===1&&(t=A(n,g)||cg),s(e),()=>{i.delete(r),i.size===0&&t&&(t(),t=null)}}return{set:n,update:g,subscribe:o}}const FlA=o_A(!1,e=>{if(typeof window<"u"){const A=window.matchMedia("(prefers-color-scheme: dark)");e(A.matches);const t=i=>e(i.matches);return A.addEventListener("change",t),()=>A.removeEventListener("change",t)}return()=>{}}),ZC="light",y1="#000000",s_A="#FFFFFF";function l7(e,A){const t={[`--${A}-block-start`]:"0px",[`--${A}-inline-end`]:"0px",[`--${A}-block-end`]:"0px",[`--${A}-inline-start`]:"0px"};return!e||!A||Object.assign(t,{[`--${A}-block-start`]:`${e.top??0}px`,[`--${A}-inline-end`]:`${e.trailing??0}px`,[`--${A}-block-end`]:`${e.bottom??0}px`,[`--${A}-inline-start`]:`${e.leading??0}px`}),t}function a_A(e){return d1[e]}function xE({colorMap:e,colorMode:A=ZC,fallback:t="FFFFFF"}){if(!e)return t;const i=e[A]||e[ZC];let n="";switch(i.type){case"hex":case"alias":return i.value??t;case"linear":return n=(i.points||[]).map(g=>`${g.color} ${g.percent}%`).join(", "),`linear-gradient(${i.degrees}deg, ${n})`;case"radial":return n=(i.points||[]).map(g=>`${g.color} ${g.percent}%`).join(", "),`radial-gradient(${n})`;default:return t}}function _lA(e,A=ZC){if(!e)return"";const t=xE({colorMap:e.color,colorMode:A});return`${e.width}px solid ${t}`}function JF(e){return{"--border-start-start-radius":`${e.top_leading}px`,"--border-start-end-radius":`${e.top_trailing}px`,"--border-end-start-radius":`${e.bottom_leading}px`,"--border-end-end-radius":`${e.bottom_trailing}px`}}function FL({background_color:e,border:A,margin:t,padding:i,color:n,colorMode:g=ZC,shape:o,shadow:s}){const a={"--margin-block-start":"0px","--margin-inline-end":"0px","--margin-block-end":"0px","--margin-inline-start":"0px","--padding-block-start":"0px","--padding-inline-end":"0px","--padding-block-end":"0px","--padding-inline-start":"0px","--background":"initial","--text-color":"initial","--border":"none","--border-end-start-radius":"0px","--border-end-end-radius":"0px","--border-start-start-radius":"0px","--border-start-end-radius":"0px","--shadow":"none"};return i&&Object.assign(a,l7(i,"padding")),t&&Object.assign(a,l7(t,"margin")),e&&(a["--background"]=xE({colorMap:e,colorMode:g,fallback:"transparent"})),n&&(a["--text-color"]=xE({colorMap:n,colorMode:g,fallback:y1})),A&&(a["--border"]=_lA(A,g)),(o==null?void 0:o.type)==="rectangle"&&o.corners&&Object.assign(a,JF(o.corners)),(o==null?void 0:o.type)==="pill"&&Object.assign(a,JF({bottom_leading:9999,bottom_trailing:9999,top_leading:9999,top_trailing:9999})),s&&(a["--shadow"]=`${s.x}px ${s.y}px ${s.radius}px 
      ${xE({colorMap:s.color,colorMode:g,fallback:y1})}`),a}function B7(e){return e.type==="fixed"?`${e.value}px`:e.type==="fit"?"fit-content":e.type==="fill"?navigator.userAgent.match(/firefox|fxios/i)?"-moz-available":"-webkit-fill-available":"initial"}function LR(e){const A={"--width":"initial","--height":"initial","--flex":"initial"},t=B7(e.width),i=B7(e.height),n=e.width.type==="fill"||e.height.type==="fill";return Object.assign(A,{"--width":t,"--height":i,"--flex":n?"initial":"0 1 auto"}),A}function JlA(e){const A={"--inset":"initial","--transform":"initial"};switch(e.alignment){case"top_leading":A["--inset"]="0 auto auto 0";break;case"top":A["--inset"]="auto auto auto 50%",A["--transform"]="translate(-50%, 0)";break;case"top_trailing":A["--inset"]="0 0 auto auto";break;case"leading":A["--inset"]="50% 0 50% 0",A["--transform"]="translate(0, -50%)";break;case"center":A["--inset"]="50% auto auto 50%",A["--transform"]="translate(-50%, -50%)";break;case"trailing":A["--inset"]="50% 0 50% auto",A["--transform"]="translate(0, -50%)";break;case"bottom_leading":A["--inset"]="auto auto 0 0";break;case"bottom":A["--inset"]="auto 50% 0 auto",A["--transform"]="translate(50%, 0)";break;case"bottom_trailing":A["--inset"]="auto 0 0 auto";break}return A}function r_A(e){const A={"--direction":"initial","--alignment":"initial","--distribution":"initial","--position":"relative","--inset":"initial","--transform":"initial"};return e.type!=="zlayer"&&(Object.assign(A,{"--direction":h1[e.type],"--alignment":p1[e.alignment]}),e.distribution&&Object.assign(A,{"--distribution":f1[e.distribution]})),A}function I_A(e,A=ZC){var t,i;const{font_size:n,horizontal_alignment:g,font_weight:o,font_name:s,color:a}=e,r={"--text-align":"initial","--font-weight":"initial","--font-size":"initial","--font-family":"sans-serif","--background-clip":"none","--text-fill-color":"none","--background":"unset"};return Object.assign(r,{"--text-align":_F[g]||_F.leading,"--font-weight":KF[o]||KF.regular,"--font-size":FF[n]||FF.body_m,"--font-family":s||"sans-serif"}),a&&(((t=a[A])==null?void 0:t.type)==="linear"||((i=a[A])==null?void 0:i.type)==="radial")&&Object.assign(r,{"--background-clip":"text","--text-fill-color":"transparent","--background":xE({colorMap:a,colorMode:A})}),r}function nC(e){return Object.entries(e).map(([A,t])=>`${A}: ${t}`).join("; ")}function C_A(e){const A=i=>{if(i.type==="package"&&i.is_selected_by_default)return i;if(i.components&&Array.isArray(i.components))for(const n of i.components){const g=A(n);if(g)return g}if(i.stack!==void 0){const n=A(i.stack);if(n)return n}},t=A(e.components_config.base.stack);if(t!==void 0)return t.package_id}const _8=(e,A)=>A?c_A(A).reduce((t,i)=>{var n;if(e){const g=((n=e==null?void 0:e.states)==null?void 0:n[i])||{};return{...t,...g}}return t},{}):{},c_A=e=>e?Object.entries(e).reduce((A,[t,i])=>(i&&A.push(t),A),[]):[];function Bc(e,A){return e?A?Object.entries(e).reduce((t,[i,n])=>{const g=i.replace(/^--/,`${A}-`);return t[`--${g}`]=n,t},{}):e:{}}function l_A(e){const{mask_shape:A,imageAspectRatio:t}=e;let i="";return(A==null?void 0:A.type)==="concave"?i=`M 0 0 
              H 100 
              V ${t*100} 
              Q 50 ${t*80} 0 ${t*100} 
              Z`:(A==null?void 0:A.type)==="convex"?i=`M 0 0 
              H 100 
              V ${t*80} 
              Q 50 ${t*120} 0 ${t*80} 
              Z`:i=`M 0 0 H 100 V ${t*100} H 0 Z`,i}const B_A=e=>{const A={"--border-end-start-radius":"0px","--border-end-end-radius":"0px","--border-start-start-radius":"0px","--border-start-end-radius":"0px"};return e!=null&&e.corners&&Object.assign(A,JF(e.corners)),A};function E_A(e){var A,t,i;if(((t=(A=e.color_overlay)==null?void 0:A[e.purchaseState.colorMode])==null?void 0:t.type)!=="linear")return{x1:"0%",y1:"0%",x2:"0%",y2:"0%"};const{color_overlay:n}=e,g=((i=n==null?void 0:n[ZC])==null?void 0:i.degrees)||0,o="50%",s="0%",a=`${Math.round(50+Math.sin((g+90)*Math.PI/90)*50)}%`,r=`${Math.round(50-Math.cos((g+90)*Math.PI/90)*50)}%`;return{x1:o,y1:s,x2:a,y2:r}}const LlA={light:{type:"hex",value:y1}},Q_A={light:{type:"hex",value:s_A}},J8=e=>{const{font_size:A="body_m",color:t=LlA,background_color:i=Q_A,padding:n,margin:g,size:o,purchaseState:s}=e,a={"--width":"unset","--height":"unset","--text-align":"initial","--font-weight":"initial","--font-size":"initial","--font-family":"sans-serif","--background-clip":"unset","--text-fill-color":"unset","--margin-block-start":"0px","--margin-inline-end":"0px","--margin-block-end":"0px","--margin-inline-start":"0px","--padding-block-start":"0px","--padding-inline-end":"0px","--padding-block-end":"0px","--padding-inline-start":"0px","--background":"transparent","--text-color":"inherit","--border":"none","--border-end-start-radius":"0px","--border-end-end-radius":"0px","--border-start-start-radius":"0px","--border-start-end-radius":"0px","--shadow":"none","--flex":"0 1 auto"},r=_8(e.overrides,e.componentState),I=a_A(A),c=I_A({...e,...r},s.colorMode),l=FL({background_color:i,color:t,margin:g,padding:n,colorMode:s.colorMode,...r}),B=LR({...o,...r}),Q={...a,...l,...c,...B};return{textStyles:Bc(Q,"text"),tagToRender:I}};function u_A(e,A,t){const i={"--width":"unset","--height":"unset","--flex":"0 1 auto","--margin-block-start":"0px","--margin-inline-end":"0px","--margin-block-end":"0px","--margin-inline-start":"0px","--padding-block-start":"0px","--padding-inline-end":"0px","--padding-block-end":"0px","--padding-inline-start":"0px","--background":"transparent","--text-color":"inherit","--border":"none","--border-end-start-radius":"0px","--border-end-end-radius":"0px","--border-start-start-radius":"0px","--border-start-end-radius":"0px","--shadow":"none","--position":"relative","--inset":"0","--transform":"initial"};Object.assign(i,FL({background_color:t,...e}),LR(A)),Object.assign(i,e.zStackChildStyles);const n=Bc(i,"text");return nC(n)}function d_A(e){const A={"--text-margin-block-start":"0px","--text-margin-inline-end":"0px","--text-margin-block-end":"0px","--text-margin-inline-start":"0px","--text-padding-block-start":"0px","--text-padding-inline-end":"0px","--text-padding-block-end":"0px","--text-padding-inline-start":"0px","--text-background":"transparent","--text-text-color":"inherit","--text-border":"none","--text-border-end-start-radius":"0px","--text-border-end-end-radius":"0px","--text-border-start-start-radius":"0px","--text-border-start-end-radius":"0px","--text-shadow":"none","--text-text-align":"initial","--text-font-weight":"initial","--text-font-size":"initial","--text-font-family":"sans-serif","--text-background-clip":"initial","--text-text-fill-color":"initial","--text-width":"unset","--text-height":"unset","--text-flex":"0 1 auto"},{tagToRender:t,textStyles:i}=J8(e);return Object.assign(A,i),{tagToRender:t,textStyles:nC(A)}}function h_A(e){return e?Object.values({newLine:{regexp:/\\\n/g,output:"<br/>"},bold:{regexp:/\*\*(.*?)\*\*/g,output:"<b>$1</b>"},italic:{regexp:/\*(.*?)\*/g,output:"<i>$1</i>"},strikethrough:{regexp:/~(.*?)~/g,output:"<s>$1</s>"},code:{regexp:/`(.*?)`/g,output:"<span style='font-family: monospace'>$1</span>"},link:{regexp:/\[(.*?)\]\((.*?)\)/g,output:"<a href=$2 target='_blank' rel='noopener noreferrer'>$1</a>"}}).reduce((A,{regexp:t,output:i})=>A.replaceAll(t,i),e):""}const p_A={hash:"svelte-1wz4si8",code:".rc-pw-text-block.svelte-1wz4si8 {display:block;padding-block-start:var(--text-padding-block-start, initial);padding-inline-end:var(--text-padding-inline-end, initial);padding-block-end:var(--text-padding-block-end, initial);padding-inline-start:var(--text-padding-inline-start, initial);margin-block-start:var(--text-margin-block-start, initial);margin-inline-end:var(--text-margin-inline-end, initial);margin-block-end:var(--text-margin-block-end, initial);margin-inline-start:var(--text-margin-inline-start, initial);color:var(--text-text-color, #ffffff);background:var(--text-background, none);font-size:var(--text-font-size, 1rem);font-weight:var(--text-font-weight, normal);text-align:var(--text-text-align, center);font-family:var(--text-font-family, sans-serif);-webkit-background-clip:var(--text-background-clip, initial);background-clip:var(--text-background-clip, initial);-webkit-text-fill-color:var(--text-text-fill-color, initial);}"};function xlA(e,A){Ri(A,!0),hi(e,p_A);const t=ri(A,"styleVariables",3,""),i=ri(A,"component",3,"p");var n=xn(),g=_i(n);UF(g,i,!1,(o,s)=>{let a;xt(()=>a=vF(o,a,{id:A.id,style:t(),class:"rc-pw-text-block"},"svelte-1wz4si8",o.namespaceURI===iN,o.nodeName.includes("-")));var r=xn(),I=_i(r);is(I,()=>A.children??cg),Ne(s,r)}),Ne(e,n),Gi()}var f_A=Nt('<span class="rc-pw-text-wrapper svelte-11gzifq"><!></span>');const y_A={hash:"svelte-11gzifq",code:".rc-pw-text-wrapper.svelte-11gzifq {display:block;height:var(--text-height, initial);width:var(--text-width, initial);background:var(--text-background, none);position:var(--text-position, relative);inset:var(--text-inset, 0);transform:var(--text-transform, initial);}"};function D_A(e,A){Ri(A,!0),hi(e,y_A);const t=Ud(A,["$$slots","$$events","$$legacy","id","labels","text_lid","purchaseState","variableDictionary","background_color","size"]),i=Bt(()=>d_A({id:A.id,labels:A.labels,text_lid:A.text_lid,purchaseState:A.purchaseState,background_color:A.background_color,size:A.size,...t})),n=Bt(()=>MA(i).tagToRender),g=Bt(()=>MA(i).textStyles),o=Bt(()=>u_A(t,A.size,A.background_color)),s=Bt(()=>F8({text_lid:A.text_lid,locale:A.purchaseState.locale,defaultLocale:A.purchaseState.defaultLocale,labels:A.labels,variableDictionary:A.variableDictionary})),a=Bt(()=>h_A(MA(s)));var r=f_A(),I=Ve(r);xlA(I,{get styleVariables(){return MA(g)},get component(){return MA(n)},get id(){return A.id},children:(c,l)=>{var B=xn(),Q=_i(B);bd(Q,()=>MA(a)),Ne(c,B)},$$slots:{default:!0}}),xt(()=>Ci(r,"style",MA(o))),Ne(e,r),Gi()}const m_A=e=>{const{background_color:A,margin:t,padding:i,spacing:n,size:g,border:o,shape:s,shadow:a,dimension:r,componentState:I,overrides:c,purchaseState:l,zStackChildStyles:B}=e,Q={"--flex":"0 1 auto","--height":"initial","--width":"initial","--spacing":`${n||0}px`,"--direction":"unset","--alignment":"unset","--distribution":"flex-start","--margin-block-start":"0px","--margin-inline-end":"0px","--margin-block-end":"0px","--margin-inline-start":"0px","--padding-block-start":"0px","--padding-inline-end":"0px","--padding-block-end":"0px","--padding-inline-start":"0px","--background":"unset","--text-color":"inherit","--border":"none","--border-end-start-radius":"0px","--border-end-end-radius":"0px","--border-start-start-radius":"0px","--border-start-end-radius":"0px","--shadow":"none","--position":"relative","--transform":"initial","--inset":"initial"},h=_8(c,I);Object.assign(Q,FL({background_color:A,margin:t,padding:i,border:o,colorMode:l.colorMode,shape:s,shadow:a,...h}),r_A({...r,...h}),LR({...g,...h})),Object.assign(Q,B);const d=Bc(Q,"stack");return nC(d)};function S_A(e){var A,t,i,n,g,o;const{badge:s}=e;if(!s)return"";const a={"--inset":"unset","--transform":"unset","--margin-block-start":"0px","--margin-inline-end":"0px","--margin-block-end":"0px","--margin-inline-start":"0px","--padding-block-start":"0px","--padding-inline-end":"0px","--padding-block-end":"0px","--padding-inline-start":"0px","--background":"unset","--text-color":"inherit","--border":"none","--border-end-start-radius":"0px","--border-end-end-radius":"0px","--border-start-start-radius":"0px","--border-start-end-radius":"0px","--shadow":"none","--badge-width":"unset","--z-index":"unset"};if(Object.assign(a,JlA({alignment:s.alignment}),FL({...s,background_color:s.background_color,color:s.color,colorMode:e.purchaseState.colorMode})),s.style==="overlay"&&(a["--margin-block-start"]="0px",a["--margin-block-end"]="0px",a["--transform"]=fb(s,0,-(((A=e.border)==null?void 0:A.width)||0))),s.style==="edge_to_edge")if(a["--margin-block-start"]="0px",a["--margin-block-end"]="0px",a["--margin-inline-start"]="0px",a["--margin-inline-end"]="0px",s.alignment==="top"||s.alignment==="bottom"){a["--badge-width"]=`calc(100% + ${(((t=e.border)==null?void 0:t.width)||0)*2}px)`,a["--z-index"]="-1";const I=Math.max(((n=(i=e.shape)==null?void 0:i.corners)==null?void 0:n.top_leading)||0,((o=(g=e.shape)==null?void 0:g.corners)==null?void 0:o.top_trailing)||0);s.alignment==="top"&&(a["--padding-block-end"]=`${I+s.padding.bottom}px`,a["--transform"]=fb(s,I)),s.alignment==="bottom"&&(a["--padding-block-start"]=`${I+s.padding.top}px`,a["--transform"]=fb(s,-I))}else a["--transform"]=fb(s),Object.assign(a,w_A(e));const r=Bc(a,"stack-badge");return nC(r)}const E7={top_leading:"bottom_trailing",top_trailing:"bottom_leading",bottom_leading:"top_trailing",bottom_trailing:"top_leading"},Q7={top_leading:"--border-start-start-radius",top_trailing:"--border-start-end-radius",bottom_leading:"--border-end-start-radius",bottom_trailing:"--border-end-end-radius"};function w_A(e){var A,t,i;const n={"--border-end-start-radius":"0px","--border-end-end-radius":"0px","--border-start-start-radius":"0px","--border-start-end-radius":"0px"},{badge:g}=e;if(!g)return n;const o=((A=e.border)==null?void 0:A.width)||0,s=g.alignment;return n[Q7[E7[s]]]=`${(t=g.shape)==null?void 0:t.corners[E7[s]]}px`,n[Q7[s]]=`${((i=e.shape)==null?void 0:i.corners[s])-o}px`,n}function fb(e,A=0,t=0){if(!e)return"";if(e.style==="overlay"){if(e.alignment==="top_leading")return`translate(${t}px, calc(-50% + ${A}px))`;if(e.alignment==="top_trailing")return`translate(calc(0% - ${t}px), calc(-50% + ${A}px))`;if(e.alignment==="bottom_leading")return`translate(${t}px, calc(50% + ${A}px))`;if(e.alignment==="bottom_trailing")return`translate(calc(0% - ${t}px), calc(50% + ${A}px))`;if(e.alignment==="top")return`translate(calc(-50% + ${t}px), calc(-50% + ${A}px))`;if(e.alignment==="bottom")return`translate(calc(50% + ${t}px), calc(50% + ${A}px))`}if(e.style==="edge_to_edge"){if(e.alignment==="top")return`translate(calc(-50% + ${t}px), calc(-100% - ${A}px + 16px))`;if(e.alignment==="bottom")return`translate(calc(50% + ${t}px), calc(100% + ${A}px))`}return""}function k_A(e){const{badge:A}=e;if(!A)return{tagToRender:"",textStyles:""};const{tagToRender:t,textStyles:i}=J8({id:e.id,labels:e.labels,purchaseState:e.purchaseState,...A,components:[],type:"text",size:{width:{type:"fit"},height:{type:"fit"}},color:A==null?void 0:A.color,name:e.name}),n={...i,"--text-margin-block-start":"0px","--text-margin-inline-end":"0px","--text-margin-block-end":"0px","--text-margin-inline-start":"0px","--text-padding-block-start":"0px","--text-padding-inline-end":"0px","--text-padding-block-end":"0px","--text-padding-inline-start":"0px"},g=nC(n);return{tagToRender:t,textStyles:g}}function M_A(e){const{dimension:A}=e,t={"--inset":"initial","--transform":"initial","--position":"relative"};if(A.type!=="zlayer")return;const i=JlA({...A});return Object.assign(t,{...i,"--position":"absolute"}),t}var N_A=Nt('<span class="rc-pw-badge svelte-1b5bst5"><!></span>'),R_A=Nt('<div class="rc-pw-stack-wrapper svelte-1b5bst5"><!> <div class="rc-pw-stack svelte-1b5bst5"></div></div>');const G_A={hash:"svelte-1b5bst5",code:`.rc-pw-stack-wrapper.svelte-1b5bst5 {display:block;box-sizing:border-box;width:var(--stack-width, unset);height:var(--stack-height, unset);box-shadow:var(--stack-shadow, none);background:var(--stack-background, unset);position:var(--stack-position, relative);transform:var(--stack-transform, initial);inset:var(--stack-inset, initial);margin-block-start:var(--stack-margin-block-start, 0);margin-inline-end:var(--stack-margin-inline-end, 0);margin-block-end:var(--stack-margin-block-end, 0);margin-inline-start:var(--stack-margin-inline-start, 0);border:var(--stack-border, none);border-end-start-radius:var(--stack-border-end-start-radius, 0px);border-end-end-radius:var(--stack-border-end-end-radius, 0px);border-start-start-radius:var(--stack-border-start-start-radius, 0px);border-start-end-radius:var(--stack-border-start-end-radius, 0px);}.rc-pw-stack.svelte-1b5bst5 {background:none;overflow:hidden;box-sizing:border-box;width:100%;height:100%;display:flex;gap:var(--stack-spacing, 0);flex:var(--stack-flex, 0 1 auto);flex-direction:var(--stack-direction, unset);justify-content:var(--stack-distribution, flex-start);align-items:var(--stack-alignment, flex-start);padding-block-start:var(--stack-padding-block-start, 0);padding-inline-end:var(--stack-padding-inline-end, 0);padding-block-end:var(--stack-padding-block-end, 0);padding-inline-start:var(--stack-padding-inline-start, 0);}.rc-pw-badge.svelte-1b5bst5 {box-sizing:border-box;font-family:var(--stack-badge-font-family, sans-serif);position:absolute;inset:var(--stack-badge-inset, unset);transform:var(--stack-badge-transform, initial);margin-block-start:var(--stack-badge-margin-block-start, 0px);margin-inline-end:var(--stack-badge-margin-inline-end, 0px);margin-block-end:var(--stack-badge-margin-block-end, 0px);margin-inline-start:var(--stack-badge-margin-inline-start, 0px);padding-block-start:var(--stack-badge-padding-block-start, 0px);padding-inline-end:var(--stack-badge-padding-inline-end, 0px);padding-block-end:var(--stack-badge-padding-block-end, 0px);padding-inline-start:var(--stack-badge-padding-inline-start, 0px);background:var(--stack-badge-background, initial);color:var(--stack-badge-text-color, inherit);border:var(--stack-badge-border, none);border-end-start-radius:var(--stack-badge-border-end-start-radius, 0px);border-end-end-radius:var(--stack-badge-border-end-end-radius, 0px);border-start-start-radius:var(
      --stack-badge-border-start-start-radius,
      0px
    );border-start-end-radius:var(--stack-badge-border-start-end-radius, 0px);box-shadow:var(--stack-badge-shadow, none);display:flex;align-items:center;justify-content:center;width:var(--stack-badge-badge-width, max-content);height:var(--stack-badge-badge-height, max-content);z-index:var(--stack-badge-z-index, 1);}`};function xR(e,A){Ri(A,!0),hi(e,G_A);const t=Ud(A,["$$slots","$$events","$$legacy","id","components","labels","onAction","purchaseState","variableDictionary","badge","zStackChildStyles"]),i=Bt(()=>m_A({id:A.id,components:A.components,labels:A.labels,onAction:A.onAction,purchaseState:A.purchaseState,zStackChildStyles:A.zStackChildStyles,...t})),n=Bt(()=>S_A({id:A.id,components:A.components,labels:A.labels,onAction:A.onAction,purchaseState:A.purchaseState,badge:A.badge,...t})),g=Bt(()=>M_A({id:A.id,components:A.components,labels:A.labels,onAction:A.onAction,purchaseState:A.purchaseState,...t})),o=Bt(()=>{var Q;return F8({defaultLocale:A.purchaseState.defaultLocale,locale:A.purchaseState.locale,labels:A.labels,variableDictionary:A.variableDictionary,text_lid:(Q=A.badge)==null?void 0:Q.text_lid})}),s=Bt(()=>k_A({id:A.id,components:A.components,labels:A.labels,onAction:A.onAction,purchaseState:A.purchaseState,variableDictionary:A.variableDictionary,badge:A.badge,...t})),a=Bt(()=>MA(s).tagToRender),r=Bt(()=>MA(s).textStyles);var I=R_A(),c=Ve(I);{var l=Q=>{var h=N_A(),d=Ve(h);xlA(d,{get styleVariables(){return MA(r)},get component(){return MA(a)},children:(p,y)=>{var m=Cg();xt(()=>Sn(m,MA(o))),Ne(p,m)},$$slots:{default:!0}}),xt(()=>Ci(h,"style",MA(n))),Ne(Q,h)};ii(c,Q=>{A.badge&&Q(l)})}var B=Ot(c,2);kS(B,21,()=>A.components,wS,(Q,h,d)=>{var p=xn(),y=_i(p);{var m=S=>{var k=Bt(()=>d>0?MA(g):void 0);LF(S,{get nodeData(){return MA(h)},get labels(){return A.labels},get onAction(){return A.onAction},get purchaseState(){return A.purchaseState},get variableDictionary(){return A.variableDictionary},get componentState(){return A.componentState},get zStackChildStyles(){return MA(k)}})},D=S=>{LF(S,{get nodeData(){return MA(h)},get labels(){return A.labels},get onAction(){return A.onAction},get purchaseState(){return A.purchaseState},get variableDictionary(){return A.variableDictionary},get componentState(){return A.componentState}})};ii(y,S=>{MA(g)?S(m):S(D,!1)})}Ne(Q,p)}),xt(()=>{Ci(I,"id",A.id),Ci(I,"style",MA(i))}),Ne(e,I),Gi()}function b_A({stack:e,zStackChildStyles:A}){var t,i;const n=((i=(t=e==null?void 0:e.size)==null?void 0:t.width)==null?void 0:i.type)==="fill"?"100%":"fit-content",g=Bc(A||{},"button");return nC({...g,position:"var(--button-position, relative)",inset:"var(--button-inset, 0)",transform:"var(--button-transform, initial)",width:n})}const U_A={hash:"svelte-mx8s0a",code:""};function v_A(e,A){Ri(A,!0),hi(e,U_A);const t=Ud(A,["$$slots","$$events","$$legacy","stack","action","onAction","labels","purchaseState","variableDictionary"]),i=()=>{A.onAction&&A.onAction(A.action)},n=Bt(()=>b_A({stack:A.stack,action:A.action,onAction:A.onAction,labels:A.labels,purchaseState:A.purchaseState,variableDictionary:A.variableDictionary,...t}));qlA(e,{onclick:i,get style(){return MA(n)},class:"rc-pw-button",children:(g,o)=>{xR(g,XE(()=>A.stack,{get labels(){return A.labels},get purchaseState(){return A.purchaseState},get variableDictionary(){return A.variableDictionary}}))},$$slots:{default:!0}}),Gi()}function LF(e,A){Ri(A,!0);const t=dI(),i=()=>uI(FlA,"$prefersDarkMode",t),n={stack:xR,text:D_A,image:GJA,button:v_A,purchase_button:vJA,package:JJA,footer:TlA,timeline:PJA},g=l=>{if(n[l.type])return[n[l.type],l];const{fallback:B}=l;if(B&&n[B==null?void 0:B.type])return[n[B.type],B];throw new Error(`Invalid component type: ${l.type}`)},o=Ud(A,["$$slots","$$events","$$legacy","nodeData","labels","onAction","purchaseState","variableDictionary","zStackChildStyles"]),s=Bt(()=>g(A.nodeData)),a=Bt(()=>MA(s)[0]),r=Bt(()=>MA(s)[1]);var I=xn(),c=_i(I);return tFA(c,()=>MA(a),(l,B)=>{B(l,XE(()=>MA(r)||{},{get labels(){return A.labels},get prefersDarkMode(){return i()},get onAction(){return A.onAction},get purchaseState(){return A.purchaseState},get variableDictionary(){return A.variableDictionary},get zStackChildStyles(){return A.zStackChildStyles}},()=>o,{children:(Q,h)=>{var d=xn(),p=_i(d);kS(p,17,()=>A.nodeData.components,wS,(y,m)=>{LF(y,XE({get nodeData(){return MA(m)},get labels(){return A.labels},get onAction(){return A.onAction},get purchaseState(){return A.purchaseState},get variableDictionary(){return A.variableDictionary}},()=>o))}),Ne(Q,d)},$$slots:{default:!0}}))}),Ne(e,I),Gi({getComponentClass:g})}function K_A({background:e,colorMode:A}){const t={"--background":"initial"};(e==null?void 0:e.type)==="color"&&Object.assign(t,{"--background":xE({colorMap:e.value,colorMode:A,fallback:"transparent"})});const i=Bc(t,"paywall");return nC(i)}function F_A(e,A){var t,i,n,g;if(((i=(t=e.components_config.base)==null?void 0:t.background)==null?void 0:i.type)!=="image")return"";const o=e.components_config.base.background;return((n=o.value[A])==null?void 0:n.original)||((g=o.value[ZC])==null?void 0:g.original)}var __A=Nt('<div class="rc-pw-footer svelte-pg5jlz"><!></div>');const J_A={hash:"svelte-pg5jlz",code:".rc-pw-footer.svelte-pg5jlz {position:sticky;bottom:0;transform:translateY(50%);width:100%;}"};function TlA(e,A){hi(e,J_A);var t=__A(),i=Ve(t);xR(i,XE(()=>A.stack,{get labels(){return A.labels},get purchaseState(){return A.purchaseState},get variableDictionary(){return A.variableDictionary},get onAction(){return A.onAction}})),xt(()=>Ci(t,"id",A.id)),Ne(e,t)}var L_A=Nt('<div class="rc-pw-paywall-background svelte-14bszwq"></div>'),x_A=Nt('<div class="rc-pw-paywall-background rc-pw-image-container svelte-14bszwq"><img class="rc-pw-image svelte-14bszwq" alt=""></div>'),T_A=Nt('<div class="rc-pw-paywall svelte-14bszwq"><!> <!> <!></div>');const q_A={hash:"svelte-14bszwq",code:`.rc-pw-paywall.svelte-14bszwq {position:relative;display:block;max-height:100%;}.rc-pw-paywall-background.svelte-14bszwq {position:absolute;top:0;left:0;width:100%;height:100%;background:var(--paywall-background, none);z-index:-1;}.rc-pw-image-container.svelte-14bszwq {overflow:hidden;background:none;}.rc-pw-image.svelte-14bszwq {width:100%;height:100%;object-fit:cover;display:block;}*,
    *::before,
    *::after {box-sizing:border-box;margin:0;padding:0;font-family:sans-serif;}body {line-height:1.5;-webkit-font-smoothing:antialiased;}img,
    picture,
    video,
    canvas,
    svg {display:block;max-width:100%;}input,
    button,
    textarea,
    select {font:inherit;}p,
    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {overflow-wrap:break-word;}p {text-wrap:pretty;}h1,
    h2,
    h3,
    h4,
    h5,
    h6 {text-wrap:balance;}#root,
    #__next {isolation:isolate;}`};function Y_A(e,A){Ri(A,!0),hi(e,q_A);const t=dI(),i=()=>uI(FlA,"$prefersDarkMode",t),n=ri(A,"variablesPerPackage",19,()=>({}));let g=pi({selectedPackageId:C_A(A.paywallData),locale:A.selectedLocale||A.paywallData.default_locale,defaultLocale:A.paywallData.default_locale,variablesPerPackage:n(),colorMode:A.preferredColorMode||(i()?"dark":ZC)}),o=sn(pi(n()[g.selectedPackageId||""]));const s=(p,y)=>{var m;(m=A.onRestorePurchasesClicked)==null||m.call(A)},a=(p,y)=>{var m;(m=A.onBackClicked)==null||m.call(A)},r=(p,y)=>{var m,D;if(p.destination==="customer_center"&&((m=A.onVisitCustomerCenterClicked)==null||m.call(A)),!p.url)return;const S=vlA(p.url.url_lid,g.locale,g.defaultLocale,A.paywallData.components_localizations);S&&((D=A.onNavigateToUrlClicked)==null||D.call(A,S))},I=(p,y)=>{g.selectedPackageId=y==null?void 0:y.packageId,y!=null&&y.packageId&&Kt(o,pi(n()[y.packageId]))},c=(p,y)=>{var m;g.selectedPackageId!==void 0&&((m=A.onPurchaseClicked)==null||m.call(A,g.selectedPackageId))},l=(p,y)=>{switch(p.type){case"select_package":I(p,y);break;case"navigate_to":r(p);break;case"navigate_back":a();break;case"restore_purchases":s();break;case"purchase":c();break}},B=Bt(()=>{var p;return K_A({background:(p=A.paywallData.components_config.base)==null?void 0:p.background,colorMode:g.colorMode})}),Q=Bt(()=>F_A(A.paywallData,g.colorMode));var h=xn(),d=_i(h);EFA(d,{get onerror(){return A.onError}},p=>{var y=T_A(),m=Ve(y);LF(m,{onAction:l,get nodeData(){return A.paywallData.components_config.base.stack},get labels(){return A.paywallData.components_localizations},get purchaseState(){return g},get variableDictionary(){return MA(o)}});var D=Ot(m,2);{var S=M=>{TlA(M,XE(()=>A.paywallData.components_config.base.sticky_footer,{get stack(){return A.paywallData.components_config.base.sticky_footer.stack},get labels(){return A.paywallData.components_localizations},get purchaseState(){return g},get variableDictionary(){return MA(o)},onAction:l}))};ii(D,M=>{A.paywallData.components_config.base.sticky_footer&&M(S)})}var k=Ot(D,2);{var N=M=>{var w=L_A();xt(()=>Ci(w,"style",MA(B))),Ne(M,w)},G=M=>{var w=xn(),b=_i(w);{var _=K=>{var J=x_A(),q=Ve(J);xt(()=>Ci(q,"src",MA(Q))),Ne(K,J)};ii(b,K=>{var J;((J=A.paywallData.components_config.base.background)==null?void 0:J.type)==="image"&&K(_)},!0)}Ne(M,w)};ii(k,M=>{var w;((w=A.paywallData.components_config.base.background)==null?void 0:w.type)==="color"?M(N):M(G,!1)})}Ne(p,y)}),Ne(e,h),Gi()}const H_A=(e,A)=>{var t;(t=A.onclick)==null||t.call(A)};var O_A=Nt("<button><!></button>");const P_A={hash:"svelte-1wpam0z",code:"button.svelte-1wpam0z {border:none;cursor:pointer;background:transparent;width:fit-content;}"};function qlA(e,A){Ri(A,!0),hi(e,P_A);var t=O_A();t.__click=[H_A,A];var i=Ve(t);is(i,()=>A.children??cg),xt(()=>{sd(t,mlA(A.class),"svelte-1wpam0z"),t.disabled=!A.onclick,Ci(t,"style",A.style)}),Ne(e,t),Gi()}vL(["click"]);var j_A=Nt('<div class="rcb-processing svelte-2j2b59"></div>');const z_A={hash:"svelte-2j2b59",code:`.rcb-processing.svelte-2j2b59 {width:var(--width, 12px);aspect-ratio:1;border-radius:50%;
    animation: svelte-2j2b59-l5 1.5s infinite linear;}

  @keyframes svelte-2j2b59-l5 {
    0% {
      box-shadow:
        var(--shadow-offset) 0 #fff2,
        calc(-1 * var(--shadow-offset)) 0 #fff2;
      background: #fff2;
    }
    25% {
      box-shadow:
        var(--shadow-offset) 0 #fff2,
        calc(-1 * var(--shadow-offset)) 0 #ffff;
      background: #fff2;
    }
    50% {
      box-shadow:
        var(--shadow-offset) 0 #fff2,
        calc(-1 * var(--shadow-offset)) 0 #fff2;
      background: #ffff;
    }
    75% {
      box-shadow:
        var(--shadow-offset) 0 #ffff,
        calc(-1 * var(--shadow-offset)) 0 #fff2;
      background: #fff2;
    }
    100% {
      box-shadow:
        var(--shadow-offset) 0 #fff2,
        calc(-1 * var(--shadow-offset)) 0 #fff2;
      background: #fff2;
    }
  }`};function Z_A(e,A){hi(e,z_A);let t=ri(A,"size",8,"medium");const i={small:{width:"8px",offset:"10px"},medium:{width:"12px",offset:"20px"},large:{width:"16px",offset:"30px"}};var n=j_A();xt(()=>Ci(n,"style",`--shadow-offset: ${i[t()].offset??""}; --width: ${i[t()].width??""};`)),Ne(e,n)}var W_A=Nt("<span><!></span>");const V_A={hash:"svelte-byrjto",code:`
  /* svelte-ignore css-unused-selector */.rcb-typography-heading-2xl.svelte-byrjto {font:var(--rc-text-heading2xl-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-heading-xl.svelte-byrjto {font:var(--rc-text-headingXl-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-heading-lg.svelte-byrjto {font:var(--rc-text-headingLg-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-heading-md.svelte-byrjto {font:var(--rc-text-headingMd-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-body-base.svelte-byrjto {font:var(--rc-text-bodyBase-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-body-small.svelte-byrjto {font:var(--rc-text-bodySmall-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-label-button.svelte-byrjto {font:var(--rc-text-labelButton-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-label-default.svelte-byrjto {font:var(--rc-text-labelDefault-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-caption-default.svelte-byrjto {font:var(--rc-text-captionDefault-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-caption-link.svelte-byrjto {font:var(--rc-text-captionLink-mobile);}

  @container layout-query-container (width >= 768px) {
    /* svelte-ignore css-unused-selector */.rcb-typography-heading-2xl.svelte-byrjto {font:var(--rc-text-heading2xl-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-heading-xl.svelte-byrjto {font:var(--rc-text-headingXl-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-heading-lg.svelte-byrjto {font:var(--rc-text-headingLg-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-heading-md.svelte-byrjto {font:var(--rc-text-headingMd-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-body-base.svelte-byrjto {font:var(--rc-text-bodyBase-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-body-small.svelte-byrjto {font:var(--rc-text-bodySmall-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-label-button.svelte-byrjto {font:var(--rc-text-labelButton-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-label-default.svelte-byrjto {font:var(--rc-text-labelDefault-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-caption-default.svelte-byrjto {font:var(--rc-text-captionDefault-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-caption-link.svelte-byrjto {font:var(--rc-text-captionLink-desktop);}
  }`};function X_A(e,A){Ri(A,!0),hi(e,V_A);const t=ri(A,"size",3,"body-base");var i=W_A(),n=Ve(i);is(n,()=>A.children??cg),xt(()=>sd(i,`rcb-typography rcb-typography-${t()??""} svelte-byrjto`)),Ne(e,i),Gi()}const $_A={error:"#B0171F",warning:"#f4e971",focus:"#1148B8",accent:"#767676",primary:"#576CDB","primary-hover":"rgba(87, 108, 219, .8)","primary-pressed":"rgba(87, 108, 219, .9)","primary-text":"#ffffff",white:"#ffffff","grey-text-dark":"rgba(0,0,0,1)","grey-text-light":"rgba(0,0,0,0.7)","grey-ui-dark":"rgba(0,0,0,0.3)","grey-ui-light":"rgba(0,0,0,0.1)","input-background":"white",background:"white"},AJA={error:"#B0171F",warning:"#f4e971",focus:"#1148B8",accent:"#767676",primary:"#576CDB","primary-hover":"rgba(87, 108, 219, .8)","primary-pressed":"rgba(87, 108, 219, .9)","primary-text":"#ffffff",white:"#ffffff","grey-text-dark":"rgba(0,0,0,1)","grey-text-light":"rgba(0,0,0,0.7)","grey-ui-dark":"rgba(0,0,0,0.3)","grey-ui-light":"rgba(0,0,0,0.1)","input-background":"white",background:"#EFF3FA"},YlA={error:"color_error",focus:"color_accent",accent:"color_accent",primary:"color_buttons_primary"},eJA={...YlA,"input-background":"color_form_bg",background:"color_form_bg"},tJA={...YlA,"input-background":"color_product_info_bg",background:"color_product_info_bg"},HlA={"input-border-radius":"4px","input-button-border-radius":"8px"},iJA={"input-border-radius":"0px","input-button-border-radius":"0px"},nJA={"input-border-radius":"12px","input-button-border-radius":"9999px"},u7=HlA,d7="-apple-system, BlinkMacSystemFont, avenir next, avenir, segoe ui, helvetica neue, helvetica, Cantarell, Ubuntu, roboto, noto, arial, sans-serif",Dl={regular:"400",medium:"500",semibold:"600"},_C={12:"12px",14:"14px",16:"16px",18:"18px",24:"24px",28:"28px",32:"32px",36:"36px"},ml={120:"120%",130:"130%",140:"140%"},Sl={tight:"0.20%",regular:"0"},Cs={heading2xl:{fontSize:_C[28],lineHeight:ml[120],fontWeight:Dl.semibold,letterSpacing:Sl.tight},headingXl:{fontSize:_C[24],lineHeight:ml[130],fontWeight:Dl.semibold,letterSpacing:Sl.regular},headingLg:{fontSize:"20px",lineHeight:ml[130],fontWeight:Dl.semibold,letterSpacing:Sl.regular},headingMd:{fontSize:"16px",lineHeight:ml[140],fontWeight:Dl.medium,letterSpacing:Sl.regular},bodyBase:{fontSize:_C[16],lineHeight:ml[140],fontWeight:Dl.regular,letterSpacing:Sl.regular},bodySmall:{fontSize:_C[14],lineHeight:ml[140],fontWeight:Dl.regular,letterSpacing:Sl.regular},labelButton:{fontSize:_C[16],lineHeight:ml[140],fontWeight:Dl.regular,letterSpacing:Sl.tight},labelDefault:{fontSize:_C[14],lineHeight:ml[140],fontWeight:Dl.regular,letterSpacing:Sl.tight},captionDefault:{fontSize:_C[12],lineHeight:ml[140],fontWeight:Dl.regular,letterSpacing:Sl.regular},captionLink:{fontSize:_C[12],lineHeight:ml[140],fontWeight:Dl.regular,letterSpacing:Sl.regular}},wl={heading2xl:{...Cs.heading2xl,fontSize:_C[36]},headingXl:{...Cs.headingXl,fontSize:_C[32]},headingLg:{...Cs.headingLg,fontSize:_C[24]},headingMd:{...Cs.headingMd,fontSize:_C[18]},bodyBase:{...Cs.bodyBase},bodySmall:{...Cs.bodySmall},labelButton:{...Cs.labelButton},labelDefault:{...Cs.labelDefault},captionDefault:{...Cs.captionDefault},captionLink:{...Cs.captionLink}},gJA={heading2xl:{mobile:Cs.heading2xl,desktop:wl.heading2xl},headingXl:{desktop:wl.headingXl,mobile:Cs.headingXl},headingLg:{desktop:wl.headingLg,mobile:Cs.headingLg},headingMd:{desktop:wl.headingMd,mobile:Cs.headingMd},bodyBase:{desktop:wl.bodyBase,mobile:Cs.bodyBase},bodySmall:{desktop:wl.bodySmall,mobile:Cs.bodySmall},labelButton:{desktop:wl.labelButton,mobile:Cs.labelButton},labelDefault:{desktop:wl.labelDefault,mobile:Cs.labelDefault},captionDefault:{desktop:wl.captionDefault,mobile:Cs.captionDefault},captionLink:{desktop:wl.captionLink,mobile:Cs.captionLink}},oN=e=>e.length==7?{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}:e.length==4?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:null,L8=({r:e,g:A,b:t,luminanceThreshold:i})=>{const n=g=>(g=g/255,g<=.03928?g/12.92:Math.pow((g+.055)/1.055,2.4));return .2126*n(e)+.7152*n(A)+.0722*n(t)>i},x8=.37,oJA=(e,A=x8)=>{const t=L8({...e,luminanceThreshold:A})?"0,0,0":"255,255,255";return{"grey-text-dark":`rgb(${t})`,"grey-text-light":`rgba(${t},0.70)`,"grey-ui-dark":`rgba(${t},0.3)`,"grey-ui-light":`rgba(${t},0.1)`}};function sJA(e,A,t){const i=oN(e)||{r:0,g:0,b:0},n=oN(A)||{r:255,g:255,b:255},g=Math.round(n.r*t+i.r*(1-t)),o=Math.round(n.g*t+i.g*(1-t)),s=Math.round(n.b*t+i.b*(1-t));return`#${u2(g)}${u2(o)}${u2(s)}`}function h7(e,A){const t={r:255,g:255,b:255},i=Math.max(0,Math.min(1,A));let n=e,g=oN(e)||t;(isNaN(g.r)||isNaN(g.g)||isNaN(g.b))&&(g=t,n="#FFFFFF");const o=L8({...g,luminanceThreshold:x8})?"#000000":"#FFFFFF";return sJA(n,o,i)}function u2(e){return e.toString(16).padStart(2,"0").toUpperCase()}const aJA=(e,A,t,i=x8)=>{const n={"grey-text-dark":t["grey-text-dark"],"grey-text-light":t["grey-text-light"],"grey-ui-dark":t["grey-ui-dark"],"grey-ui-light":t["grey-ui-light"],"primary-text":t["primary-text"]};if(e!=null&&e.startsWith("#")){const g=oN(e);g!==null&&Object.assign(n,oJA(g))}if(A!=null&&A.startsWith("#")){const g=oN(A);g!==null&&(n["primary-text"]=L8({...g,luminanceThreshold:i})?"black":"white")}return n},rJA=e=>({"primary-hover":h7(e,.1),"primary-pressed":h7(e,.15)}),IJA=(e,A)=>e||A,CJA=(e,A,t)=>{const i=Object.entries(e).map(([n,g])=>[n,IJA(t?t[g]:null,A[n])]);return Object.fromEntries(i)},OlA=(e,A,t)=>{const i=CJA(e,A,t);return t?{...A,...i,...aJA(i.background,i.primary,A),...rJA(i.primary)}:{...A}},cJA=e=>OlA(tJA,AJA,e),PlA=e=>OlA(eJA,$_A,e),T8=e=>{if(!e)return u7;switch(e.shapes){case"rounded":return HlA;case"rectangle":return iJA;case"pill":return nJA;default:return u7}},xF=(e="",A)=>A.map(([t,i])=>`--rc-${e}-${t}: ${i}`).join("; "),lJA=e=>{const A=xF("color",Object.entries(cJA(e))),t=xF("shape",Object.entries(T8(e)));return[A,t].join("; ")},BJA=e=>{const A=xF("color",Object.entries(PlA(e))),t=xF("shape",Object.entries(T8(e)));return[A,t].join("; ")},EJA=(e="",A)=>Object.entries(A).flatMap(([t,{desktop:i,mobile:n}])=>[`--rc-${e}-${t}-desktop: normal normal ${i.fontWeight} ${i.fontSize}/${i.lineHeight} ${d7}`,`--rc-${e}-${t}-mobile: normal normal ${n.fontWeight} ${n.fontSize}/${n.lineHeight} ${d7}`,`--rc-${e}-${t}-desktop-font-size: ${i.fontSize}`,`--rc-${e}-${t}-mobile-font-size: ${n.fontSize}`]).join("; "),QJA=(e="",A)=>Object.entries(A).map(([t,{mobile:i,desktop:n}])=>`--rc-${e}-${t}-mobile: ${i};  --rc-${e}-${t}-desktop: ${n};`).join(" "),uJA={outerPadding:{mobile:"clamp(1.3125rem, 5.6vw, 1.5rem)",desktop:"clamp(1.5rem, 9.44vw, 5rem)"},outerPaddingSmall:{mobile:"clamp(0.75rem, 4.2vw, 1rem)",desktop:"clamp(1.5rem, 9.44vw, 5rem)"},gapSmall:{mobile:"0.25rem",desktop:"0.375rem"},gapMedium:{mobile:"0.5rem",desktop:"0.75rem"},gapLarge:{mobile:"0.75rem",desktop:"0.75rem"},gapXLarge:{mobile:"1rem",desktop:"1.5rem"},gapXXLarge:{mobile:"1.25rem",desktop:"2.25rem"},gapXXXLarge:{mobile:"2.25rem",desktop:"4.5rem"},inputHeight:{mobile:"3rem",desktop:"3rem"},gapStripeElement:{mobile:"0.70rem",desktop:"1rem"}};let dJA=class{constructor(e){Yt(this,"brandingAppearance"),e?this.brandingAppearance=e:this.brandingAppearance=void 0}get shape(){return T8(this.brandingAppearance)}get formColors(){return PlA(this.brandingAppearance)}get formStyleVars(){return BJA(this.brandingAppearance)}get productInfoStyleVars(){return lJA(this.brandingAppearance)}get spacing(){return uJA}get textStyles(){return gJA}get textStyleVars(){return EJA("text",this.textStyles)}get spacingStyleVars(){return QJA("spacing",this.spacing)}};var hJA=Nt("<button><!></button>");const pJA={hash:"svelte-td7xvm",code:`button.svelte-td7xvm {border:none;border-radius:var(--rc-shape-input-button-border-radius);cursor:pointer;height:var(--rc-spacing-inputHeight-mobile);color:var(--rc-color-grey-text-dark);background-color:var(--rc-color-grey-ui-dark);display:flex;align-items:center;justify-content:center;-webkit-tap-highlight-color:rgba(0, 0, 0, 0);-webkit-tap-highlight-color:transparent;transition:background-color 0.15s ease-in-out;user-select:none;}

  @container layout-query-container (width >= 768px) {button.svelte-td7xvm {height:var(--rc-spacing-inputHeight-desktop);}
  }

  /* focus-visible is triggered only when focused with keyboard/reader */button.svelte-td7xvm:focus-visible {outline:2px solid var(--rc-color-focus);}button.intent-primary.svelte-td7xvm {background-color:var(--rc-color-primary);color:var(--rc-color-primary-text);}button.svelte-td7xvm:disabled {color:var(--rc-color-grey-text-light);background-color:var(--rc-color-grey-ui-dark);outline:none;}button.intent-primary.svelte-td7xvm:not(:disabled):hover {background-color:var(--rc-color-primary-hover);}button.intent-primary.svelte-td7xvm:not(:disabled):active,
  button.svelte-td7xvm:active {background-color:var(--rc-color-primary-pressed);outline:none;}button.intent-primary.svelte-td7xvm:disabled {color:var(--rc-color-grey-text-light);background-color:var(--rc-color-grey-ui-dark);}`};function jlA(e,A){Ri(A,!0),hi(e,pJA);const t=ri(A,"intent",3,"primary"),i=ri(A,"disabled",3,!1),n=ri(A,"loading",3,!1),g=Bt(()=>new dJA(A.brandingAppearance)),o=Bt(()=>MA(g).textStyleVars),s=Bt(()=>MA(g).spacingStyleVars),a=Bt(()=>MA(g).productInfoStyleVars),r=Bt(()=>MA(g).formStyleVars),I=Bt(()=>[A.styleOverrides,MA(o),MA(s),MA(a),MA(r)].join("; "));var c=hJA();c.__click=function(...h){var d;(d=A.onclick)==null||d.apply(this,h)};var l=Ve(c);{var B=h=>{Z_A(h,{size:"small"})},Q=h=>{X_A(h,{size:"body-base",children:(d,p)=>{var y=xn(),m=_i(y);eFA(m,A,"default",{}),Ne(d,y)},$$slots:{default:!0}})};ii(l,h=>{n()?h(B):h(Q,!1)})}xt(()=>{sd(c,`${`intent-${t()}`??""} svelte-td7xvm`),c.disabled=i(),Ci(c,"data-testid",A.testId),Ci(c,"type",A.type),Ci(c,"style",MA(I))}),Ne(e,c),Gi()}vL(["click"]);const fJA=e=>{const{size:A,overrides:t,componentState:i,zStackChildStyles:n}=e,g={"--height":"unset","--width":"unset","--clip-path":"none","--border-end-start-radius":"unset","--border-end-end-radius":"unset","--border-start-start-radius":"unset","--border-start-end-radius":"unset","--position":"relative","--inset":"0","--transform":"initial"},o=_8(t,i);Object.assign(g,n),Object.assign(g,LR({...A,...o})),Object.assign(g,B_A(e.mask_shape));const s=Bc(g,"image"),a=l_A(e),r=E_A(e);return{imageStyles:nC(s),maskPath:a,linearGradientAngle:r}};var yJA=NB('<ellipse cx="50" rx="50"></ellipse>'),DJA=NB("<path></path>"),mJA=NB("<stop></stop>"),SJA=NB("<linearGradient></linearGradient>"),wJA=NB("<stop></stop>"),kJA=NB('<radialGradient cx="50%" cy="50%" r="50%" fx="50%" fy="50%"></radialGradient>'),MJA=NB('<linearGradient><stop offset="0%"></stop></linearGradient>'),NJA=Nt('<img style="display: none;" alt=""> <svg class="rc-pw-image-container svelte-1esrvxg" preserveAspectRatio="xMidYMid slice"><defs><clipPath><!></clipPath><!></defs><image class="rc-pw-image svelte-1esrvxg" x="0" y="0" width="100" preserveAspectRatio="xMidYMid slice"></image><rect class="rc-pw-image-overlay svelte-1esrvxg" x="0" y="0" width="100"></rect></svg>',1);const RJA={hash:"svelte-1esrvxg",code:".rc-pw-image-container.svelte-1esrvxg {border-end-start-radius:var(--image-border-end-start-radius, 0px);border-end-end-radius:var(--image-border-end-end-radius, 0px);border-start-start-radius:var(--image-border-start-start-radius, 0px);border-start-end-radius:var(--image-border-start-end-radius, 0px);position:relative;overflow:hidden;display:flex;flex:var(--image-flex, 1 1 auto);position:var(--image-position, relative);inset:var(--image-inset, 0);transform:var(--image-transform, initial);height:var(--image-height, initial);width:var(--image-width, initial);}.rc-pw-image.svelte-1esrvxg {width:100%;height:100%;object-fit:cover;display:block;}.rc-pw-image-overlay.svelte-1esrvxg {position:absolute;inset:0;}"};function GJA(e,A){Ri(A,!0),hi(e,RJA);const t=Ud(A,["$$slots","$$events","$$legacy","id","source","purchaseState"]);let i=sn(0),n;function g(){n&&Kt(i,n.naturalHeight/n.naturalWidth)}const o=Bt(()=>fJA({id:A.id,colorMode:A.purchaseState.colorMode,source:A.source,purchaseState:A.purchaseState,...t,imageAspectRatio:MA(i)})),s=Bt(()=>MA(o).imageStyles),a=Bt(()=>MA(o).maskPath),r=Bt(()=>MA(o).linearGradientAngle),I=Bt(()=>{var G,M;const w=A.purchaseState.colorMode;return(G=A.source[w])!=null&&G.original?A.source[w].original:(M=A.source[ZC])==null?void 0:M.original});var c=NJA(),l=_i(c);NlA(l,G=>n=G,()=>n);var B=Ot(l,2),Q=Ve(B),h=Ve(Q),d=Ve(h);{var p=G=>{var M=yJA();xt(()=>{Ci(M,"cy",MA(i)*50),Ci(M,"ry",MA(i)*50)}),Ne(G,M)},y=G=>{var M=DJA();xt(()=>Ci(M,"d",MA(a))),Ne(G,M)};ii(d,G=>{var M;((M=A.mask_shape)==null?void 0:M.type)==="circle"?G(p):G(y,!1)})}var m=Ot(h);{var D=G=>{var M=SJA();kS(M,21,()=>{var w,b,_,K;return((b=(w=A.color_overlay)==null?void 0:w[A.purchaseState.colorMode])==null?void 0:b.points)||((K=(_=A.color_overlay)==null?void 0:_[ZC])==null?void 0:K.points)||[]},wS,(w,b)=>{var _=mJA();xt(()=>{Ci(_,"offset",`${MA(b).percent}%`),Ci(_,"style",`stop-color: ${MA(b).color}`)}),Ne(w,_)}),xt(()=>{Ci(M,"id",`gradient-${A.id}`),Ci(M,"x1",MA(r).x1),Ci(M,"y1",MA(r).y1),Ci(M,"x2",MA(r).x2),Ci(M,"y2",MA(r).y2)}),Ne(G,M)},S=G=>{var M=xn(),w=_i(M);{var b=K=>{var J=kJA();kS(J,21,()=>{var q,v,U,x;return((v=(q=A.color_overlay)==null?void 0:q[A.purchaseState.colorMode])==null?void 0:v.points)||((x=(U=A.color_overlay)==null?void 0:U[ZC])==null?void 0:x.points)||[]},wS,(q,v)=>{var U=wJA();xt(()=>{Ci(U,"offset",`${MA(v).percent}%`),Ci(U,"style",`stop-color: ${MA(v).color}`)}),Ne(q,U)}),xt(()=>Ci(J,"id",`gradient-${A.id}`)),Ne(K,J)},_=K=>{var J=xn(),q=_i(J);{var v=U=>{var x=MJA(),T=Ve(x);xt(()=>{var z,Z,eA;Ci(x,"id",`gradient-${A.id}`),Ci(T,"style",`stop-color: ${((z=A.color_overlay[A.purchaseState.colorMode])==null?void 0:z.value)||((eA=(Z=A.color_overlay)==null?void 0:Z[ZC])==null?void 0:eA.value)}`)}),Ne(U,x)};ii(q,U=>{var x,T;((T=(x=A.color_overlay)==null?void 0:x[A.purchaseState.colorMode])==null?void 0:T.type)==="hex"&&U(v)},!0)}Ne(K,J)};ii(w,K=>{var J,q;((q=(J=A.color_overlay)==null?void 0:J[A.purchaseState.colorMode])==null?void 0:q.type)==="radial"?K(b):K(_,!1)},!0)}Ne(G,M)};ii(m,G=>{var M,w;((w=(M=A.color_overlay)==null?void 0:M[A.purchaseState.colorMode])==null?void 0:w.type)==="linear"?G(D):G(S,!1)})}var k=Ot(Q),N=Ot(k);xt(()=>{Ci(l,"src",MA(I)),Ci(B,"id",`rc-pw-image-container-${A.id}`),Ci(B,"style",MA(s)),Ci(B,"viewBox",`0 0 100 ${MA(i)*100}`),Ci(h,"id",`clip-path-${A.id}`),Ci(k,"href",MA(I)),Ci(k,"height",MA(i)*100),Ci(k,"clip-path",`url(#clip-path-${A.id})`),Ci(k,"id",A.id),Ci(N,"height",MA(i)*100),Ci(N,"clip-path",`url(#clip-path-${A.id})`),Ci(N,"fill",`url(#gradient-${A.id})`)}),iB("load",l,g),Ne(e,c),Gi()}function bJA({stack:e,zStackChildStyles:A}){const t=e.size.width.type==="fill"?"100%":"fit-content",i=Bc(A||{},"purchase-button");return nC({...i,position:"var(--purchase-button-position, relative)",inset:"var(--purchase-button-inset, 0)",transform:"var(--purchase-button-transform, initial)",width:t})}const UJA={hash:"svelte-1x8zwdp",code:""};function vJA(e,A){Ri(A,!0),hi(e,UJA);const t=Ud(A,["$$slots","$$events","$$legacy","stack","labels","onAction","purchaseState","variableDictionary","zStackChildStyles"]),i=()=>{A.onAction&&A.onAction({type:"purchase"})},n=Bt(()=>bJA({stack:A.stack,labels:A.labels,onAction:A.onAction,purchaseState:A.purchaseState,variableDictionary:A.variableDictionary,zStackChildStyles:A.zStackChildStyles,...t}));qlA(e,{onclick:i,class:"rc-pw-purchase-button",get style(){return MA(n)},children:(g,o)=>{xR(g,XE(()=>A.stack,{get labels(){return A.labels},get purchaseState(){return A.purchaseState},get variableDictionary(){return A.variableDictionary}}))},$$slots:{default:!0}}),Gi()}const KJA=(e,A)=>{e.preventDefault(),e.stopPropagation(),A.onAction&&A.onAction({type:"select_package"},{packageId:A.package_id})};var FJA=Nt('<button class="rc-pw-package svelte-123kamd"><!></button>');const _JA={hash:"svelte-123kamd",code:".rc-pw-package.svelte-123kamd {width:100%;display:flex;margin:0;padding:0;background:initial;border:initial;text-align:initial;position:var(--package-position, relative);inset:var(--package-inset, 0);transform:var(--package-transform, initial);}"};function JJA(e,A){Ri(A,!0),hi(e,_JA);const t=Bt(()=>{var s;return((s=A.purchaseState.variablesPerPackage)==null?void 0:s[A.package_id])||A.variableDictionary}),i=Bt(()=>{var s;return{selected:((s=A.purchaseState)==null?void 0:s.selectedPackageId)===A.package_id}}),n=Bt(()=>nC(Bc(A.zStackChildStyles,"package")));var g=FJA();g.__click=[KJA,A];var o=Ve(g);xR(o,XE(()=>A.stack,{get labels(){return A.labels},get onAction(){return A.onAction},get purchaseState(){return A.purchaseState},get componentState(){return MA(i)},get variableDictionary(){return MA(t)}})),xt(()=>{Ci(g,"id",A.id),Ci(g,"style",MA(n)),LE(g,"selected",MA(i).selected)}),Ne(e,g),Gi()}vL(["click"]);function LJA(e){const A={"--item-spacing":`${e.item_spacing}px`,"--width":"initial","--height":"initial","--flex":"0 1 auto","--position":"relative","--inset":"0","--transform":"initial"};Object.assign(A,LR(e.size)),Object.assign(A,e.zStackChildStyles);const t=Bc(A,"timeline");return nC(t)}function xJA(e){var A,t,i,n,g,o,s,a,r,I;const c={"--icon-size":`${e.icon.width_and_height}px`,"--icon-padding":`${e.icon.padding}px`,"--icon-color":xE({colorMap:e.icon.color,colorMode:(A=e.purchaseState)==null?void 0:A.colorMode}),"--icon-background-color":xE({colorMap:(t=e.icon_background)==null?void 0:t.color,colorMode:e.purchaseState.colorMode}),"--icon-border":_lA((i=e.icon_background)==null?void 0:i.border,(n=e.purchaseState)==null?void 0:n.colorMode),"--text-spacing":`${e.text_spacing}px`,"--border-start-start-radius":"0px","--border-start-end-radius":"0px","--border-end-start-radius":"0px","--border-end-end-radius":"0px","--connector-color":xE({colorMap:(g=e.connector)==null?void 0:g.color,colorMode:e.purchaseState.colorMode}),"--connector-width":`${((o=e.connector)==null?void 0:o.width)||0}px`,"--connector-top":"0px","--connector-height":`${e.item_spacing}px`};if(Object.assign(c,((a=(s=e.icon_background)==null?void 0:s.shape)==null?void 0:a.type)==="rectangle"?JF((I=(r=e.icon_background)==null?void 0:r.shape)==null?void 0:I.corners):{"--border-start-start-radius":"50%","--border-start-end-radius":"50%","--border-end-start-radius":"50%","--border-end-end-radius":"50%"}),e.connector){const B=e.connector.margin.top!==0,Q=e.connector.margin.bottom!==0,h=e.icon.padding+e.icon.width_and_height/2;!B&&!Q&&(c["--connector-height"]=`${e.item_spacing+h*2}px`,c["--connector-top"]="50%"),B&&Q&&(c["--connector-height"]=`${e.item_spacing-e.connector.margin.top-e.connector.margin.bottom}px`,c["--connector-top"]=`calc(100% + ${e.connector.margin.top}px)`),!B&&Q&&(c["--connector-height"]=`${e.item_spacing-e.connector.margin.bottom+h}px`,c["--connector-top"]="50%"),B&&!Q&&(c["--connector-height"]=`${e.item_spacing+h}px`,c["--connector-top"]=`calc(100% + ${e.connector.margin.top}px)`)}const l=Bc(c,"timeline-item");return nC(l)}function p7(e,A="title"){var t,i,n,g,o;const s={"--text-color":"inherit","--text-font-size":"initial","--text-font-weight":"initial","--text-horizontal-alignment":"initial","--text-margin-block-start":"0px","--text-margin-inline-end":"0px","--text-margin-block-end":"0px","--text-margin-inline-start":"0px","--text-padding-block-start":"0px","--text-padding-inline-end":"0px","--text-padding-block-end":"0px","--text-padding-inline-start":"0px"},a={color:((t=e[A])==null?void 0:t.color)||LlA,font_size:((i=e[A])==null?void 0:i.font_size)||"body_m",font_weight:((n=e[A])==null?void 0:n.font_weight)||"regular",horizontal_alignment:((g=e[A])==null?void 0:g.horizontal_alignment)||"leading"},{tagToRender:r,textStyles:I}=J8({...e,components:[],...a,size:{width:{type:"fit"},height:{type:"fit"}},type:"text",margin:{top:0,bottom:0,leading:0,trailing:0},padding:{top:0,bottom:0,leading:0,trailing:0},text_lid:""});Object.assign(s,I);const c=nC(Bc(s,"timeline-item")),l=F8({text_lid:(o=e[A])==null?void 0:o.text_lid,locale:e.purchaseState.locale,defaultLocale:e.purchaseState.defaultLocale,labels:e.labels,variableDictionary:e.variableDictionary});return{textStyles:c,tagToRender:r,textLabel:l}}var TJA=Nt('<div class="rc-pw-timeline-item svelte-gjmo4g"><div class="rc-pw-timeline-item-icon-container svelte-gjmo4g"><div class="rc-pw-timeline-item-icon svelte-gjmo4g"></div></div> <div class="rc-pw-timeline-item-content svelte-gjmo4g"><!> <!></div></div>');const qJA={hash:"svelte-gjmo4g",code:`.rc-pw-timeline-item.svelte-gjmo4g {display:flex;align-items:center;gap:var(--timeline-item-spacing, 0px);}.rc-pw-timeline-item-icon-container.svelte-gjmo4g {position:relative;border-end-start-radius:var(--timeline-item-border-end-start-radius, 0px);border-end-end-radius:var(--timeline-item-border-end-end-radius, 0px);border-start-start-radius:var(
      --timeline-item-border-start-start-radius,
      0px
    );border-start-end-radius:var(--timeline-item-border-start-end-radius, 0px);width:var(--timeline-item-icon-size, 16px);height:var(--timeline-item-icon-size, 16px);flex-shrink:0;background-color:var(--timeline-item-icon-background-color, #ffffff);border:var(--timeline-item-icon-border, initial);display:flex;align-items:center;justify-content:center;padding:var(--timeline-item-icon-padding, 0px);box-sizing:content-box;}.rc-pw-timeline-item-icon-container.svelte-gjmo4g::before {position:absolute;content:"";z-index:-1;top:var(--timeline-item-connector-top, 0px);height:var(--timeline-item-connector-height, 0px);width:var(--timeline-item-connector-width, 0px);background:var(--timeline-item-connector-color, transparent);}.rc-pw-timeline-item-icon.svelte-gjmo4g {width:var(--timeline-item-icon-size, 10px);height:var(--timeline-item-icon-size, 10px);color:var(--timeline-item-icon-color, #ffffff);display:flex;align-items:center;justify-content:center;}.rc-pw-timeline-item-content.svelte-gjmo4g {display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start;gap:var(--timeline-item-text-spacing, 0px);height:fit-content;}.rc-pw-timeline-item-content-title.svelte-gjmo4g,
  .rc-pw-timeline-item-content-description.svelte-gjmo4g {margin-block-start:var(--timeline-item-text-margin-block-start, 0px);margin-inline-end:var(--timeline-item-text-margin-inline-end, 0px);margin-block-end:var(--timeline-item-text-margin-block-end, 0px);margin-inline-start:var(--timeline-item-text-margin-inline-start, 0px);padding-block-start:var(--timeline-item-text-padding-block-start, 0);padding-inline-end:var(--timeline-item-text-padding-inline-end, 0);padding-block-end:var(--timeline-item-text-padding-block-end, 0);padding-inline-start:var(--timeline-item-text-padding-inline-start, 0);font-family:var(--timeline-item-text-font-family, sans-serif);}`};function YJA(e,A){Ri(A,!0),hi(e,qJA);const t=Ud(A,["$$slots","$$events","$$legacy"]),i=Bt(()=>xJA(t)),n=Bt(()=>p7(t,"title")),g=Bt(()=>MA(n).tagToRender),o=Bt(()=>MA(n).textStyles),s=Bt(()=>MA(n).textLabel),a=Bt(()=>p7(t,"description")),r=Bt(()=>MA(a).tagToRender),I=Bt(()=>MA(a).textStyles),c=Bt(()=>MA(a).textLabel);var l=TJA(),B=Ot(Ve(l),2),Q=Ve(B);UF(Q,()=>MA(g),!1,(p,y)=>{let m;xt(()=>m=vF(p,m,{class:"rc-pw-timeline-item-content-title",style:MA(o)},"svelte-gjmo4g",p.namespaceURI===iN,p.nodeName.includes("-")));var D=Cg();xt(()=>Sn(D,MA(s))),Ne(y,D)});var h=Ot(Q,2);{var d=p=>{var y=xn(),m=_i(y);UF(m,()=>MA(r),!1,(D,S)=>{let k;xt(()=>k=vF(D,k,{class:"rc-pw-timeline-item-content-description",style:MA(I)},"svelte-gjmo4g",D.namespaceURI===iN,D.nodeName.includes("-")));var N=Cg();xt(()=>Sn(N,MA(c))),Ne(S,N)}),Ne(p,y)};ii(h,p=>{MA(c)&&p(d)})}xt(()=>Ci(l,"style",MA(i))),Ne(e,l),Gi()}var HJA=Nt('<div class="rc-pw-timeline-container svelte-12g27vu"></div>');const OJA={hash:"svelte-12g27vu",code:".rc-pw-timeline-container.svelte-12g27vu {display:flex;flex:var(--timeline-flex, 0 1 auto);flex-direction:column;gap:var(--timeline-item-spacing, 0);width:var(--timeline-width, initial);height:var(--timeline-height, initial);position:var(--timeline-position, relative);inset:var(--timeline-inset, 0);transform:var(--timeline-transform, initial);}"};function PJA(e,A){Ri(A,!0),hi(e,OJA);const t=Ud(A,["$$slots","$$events","$$legacy","items"]),i=Bt(()=>LJA({items:A.items,...t}));var n=xn(),g=_i(n);{var o=s=>{var a=HJA();kS(a,21,()=>A.items,wS,(r,I,c)=>{var l=Bt(()=>`${A.id}-${c}`),B=Bt(()=>`${A.name}-${c}`);YJA(r,XE(()=>MA(I),{get labels(){return A.labels},get id(){return MA(l)},get name(){return MA(B)},type:"timeline",get purchaseState(){return A.purchaseState},get text_spacing(){return A.text_spacing},get item_spacing(){return A.item_spacing}}))}),xt(()=>Ci(a,"style",MA(i))),Ne(s,a)};ii(g,s=>{A.items.length&&s(o)})}Ne(e,n),Gi()}var jJA=Nt('<footer class="rcb-modal-footer svelte-1f9z0o8"><!></footer>');const zJA={hash:"svelte-1f9z0o8",code:"footer.svelte-1f9z0o8 {display:flex;flex-direction:column;}"};function ZJA(e,A){Ri(A,!1),hi(e,zJA);let t=ri(A,"children",8);lc();var i=jJA(),n=Ve(i);is(n,()=>t()??cg),Ne(e,i),Gi()}const WJA={hash:"svelte-1bzqb13",code:".rcb-modal-section.svelte-1bzqb13 {padding:8px 0px;display:flex;}section.rcb-modal-section.svelte-1bzqb13 {flex-grow:1;}.rcb-modal-section.svelte-1bzqb13:last-of-type {padding:0;}"};function VJA(e,A){Ri(A,!1),hi(e,WJA);let t=ri(A,"as",8,"section"),i=ri(A,"children",8);lc();var n=xn(),g=_i(n);UF(g,t,!1,(o,s)=>{vF(o,null,{class:"rcb-modal-section"},"svelte-1bzqb13",o.namespaceURI===iN,o.nodeName.includes("-"));var a=xn(),r=_i(a);is(r,()=>i()??cg),Ne(s,a)}),Ne(e,n),Gi()}var XJA=Nt("<div><!></div>");const $JA={hash:"svelte-b5dygi",code:`.rcb-column.svelte-b5dygi {display:flex;flex-direction:column;justify-content:flex-start;flex-grow:1;min-width:100%;}.rcb-column.align-center.svelte-b5dygi {justify-content:center;}.rcb-column.align-end.svelte-b5dygi {justify-content:flex-end;}.rcb-column.gap-small.svelte-b5dygi {gap:var(--rc-spacing-gapSmall-mobile);}.rcb-column.gap-medium.svelte-b5dygi {gap:var(--rc-spacing-gapXLarge-mobile);}.rcb-column.gap-large.svelte-b5dygi {gap:var(--rc-spacing-gapXXLarge-mobile);}

  @container layout-query-container (width >= 768px) {.rcb-column.gap-small.svelte-b5dygi {gap:var(--rc-spacing-gapSmall-desktop);}.rcb-column.gap-medium.svelte-b5dygi {gap:var(--rc-spacing-gapLarge-desktop);}.rcb-column.gap-large.svelte-b5dygi {gap:var(--rc-spacing-gapXXLarge-desktop);}
  }`};function zlA(e,A){Ri(A,!1),hi(e,$JA);let t=ri(A,"gap",8,"small"),i=ri(A,"align",8,"start"),n=ri(A,"children",8);lc();var g=XJA(),o=Ve(g);is(o,()=>n()??cg),xt(()=>sd(g,`rcb-column gap-${t()??""} align-${i()??""} svelte-b5dygi`)),Ne(e,g),Gi()}var ALA=Nt('<div class="rcb-row svelte-1seeuxq"><!></div>');const eLA={hash:"svelte-1seeuxq",code:".rcb-row.svelte-1seeuxq {display:flex;flex-direction:row;justify-content:flex-start;}"};function tLA(e,A){Ri(A,!1),hi(e,eLA);let t=ri(A,"children",8);lc();var i=ALA(),n=Ve(i);is(n,()=>t()??cg),Ne(e,i),Gi()}var iLA=Nt("<span><!></span>");const nLA={hash:"svelte-orw2sj",code:`.rcb-typography.svelte-orw2sj {display:inline-block;line-height:normal;}

  /* svelte-ignore css-unused-selector */.rcb-typography-heading-2xl.svelte-orw2sj {font:var(--rc-text-heading2xl-mobile);}.rcb-typography-heading-2xl.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-heading2xl-branded-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-heading-xl.svelte-orw2sj {font:var(--rc-text-headingXl-mobile);}.rcb-typography-heading-xl.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-headingXl-branded-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-heading-lg.svelte-orw2sj {font:var(--rc-text-headingLg-mobile);}.rcb-typography-heading-lg.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-headingLg-branded-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-heading-md.svelte-orw2sj {font:var(--rc-text-headingMd-mobile);}.rcb-typography-heading-md.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-headingMd-branded-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-body-base.svelte-orw2sj {font:var(--rc-text-bodyBase-mobile);}.rcb-typography-body-base.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-bodyBase-branded-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-body-small.svelte-orw2sj {font:var(--rc-text-bodySmall-mobile);}.rcb-typography-body-small.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-bodySmall-branded-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-label-button.svelte-orw2sj {font:var(--rc-text-labelButton-mobile);}.rcb-typography-label-button.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-labelButton-branded-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-label-default.svelte-orw2sj {font:var(--rc-text-labelDefault-mobile);}.rcb-typography-label-default.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-labelDefault-branded-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-caption-default.svelte-orw2sj {font:var(--rc-text-captionDefault-mobile);}.rcb-typography-caption-default.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-captionDefault-branded-mobile);}

  /* svelte-ignore css-unused-selector */.rcb-typography-caption-link.svelte-orw2sj {font:var(--rc-text-captionLink-mobile);}.rcb-typography-caption-link.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-captionLink-branded-mobile);}

  @container layout-query-container (width >= 768px) {span.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-brandedText-font-style-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-heading-2xl.svelte-orw2sj {font:var(--rc-text-heading2xl-desktop);}.rcb-typography-heading-2xl.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-heading2xl-branded-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-heading-xl.svelte-orw2sj {font:var(--rc-text-headingXl-desktop);}.rcb-typography-heading-xl.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-headingXl-branded-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-heading-lg.svelte-orw2sj {font:var(--rc-text-headingLg-desktop);}.rcb-typography-heading-lg.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-headingLg-branded-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-heading-md.svelte-orw2sj {font:var(--rc-text-headingMd-desktop);}.rcb-typography-heading-md.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-headingMd-branded-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-body-base.svelte-orw2sj {font:var(--rc-text-bodyBase-desktop);}.rcb-typography-body-base.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-bodyBase-branded-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-body-small.svelte-orw2sj {font:var(--rc-text-bodySmall-desktop);}.rcb-typography-body-small.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-bodySmall-branded-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-label-button.svelte-orw2sj {font:var(--rc-text-labelButton-desktop);}.rcb-typography-label-button.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-labelButton-branded-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-label-default.svelte-orw2sj {font:var(--rc-text-labelDefault-desktop);}.rcb-typography-label-default.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-labelDefault-branded-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-caption-default.svelte-orw2sj {font:var(--rc-text-captionDefault-desktop);}.rcb-typography-caption-default.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-captionDefault-branded-desktop);}

    /* svelte-ignore css-unused-selector */.rcb-typography-caption-link.svelte-orw2sj {font:var(--rc-text-captionLink-desktop);}.rcb-typography-caption-link.rcb-typography-branded.svelte-orw2sj {font:var(--rc-text-captionLink-branded-desktop);}
  }`};function Zn(e,A){Ri(A,!0),hi(e,nLA);const t=ri(A,"size",3,"body-base"),i=ri(A,"branded",3,!1);var n=iLA(),g=Ve(n);is(g,()=>A.children??cg),xt(()=>sd(n,`rcb-typography rcb-typography-${t()??""} ${(i()?"rcb-typography-branded":"")??""} svelte-orw2sj`)),Ne(e,n),Gi()}var gLA=Nt("<div><!></div>"),oLA=Nt('<span style="display: block;"><!></span>'),sLA=Nt("<!> <!>",1),aLA=Nt("<!> <!>",1),rLA=Nt('<div class="rcb-modal-message svelte-w46z5s" data-type="error"><!></div>');const ILA={hash:"svelte-w46z5s",code:`.rcb-modal-message-icon.svelte-w46z5s {flex-shrink:0;align-self:center;margin-right:16px;}.rcb-modal-message.svelte-w46z5s {width:100%;min-height:160px;display:flex;justify-content:center;align-items:center;flex-direction:column;text-align:left;margin-top:4px;}.rcb-modal-message[data-has-title="false"].svelte-w46z5s {margin-top:var(--rc-spacing-gapXXLarge-mobile);}.rcb-modal-message-icon.small.svelte-w46z5s {height:var(--rc-text-headingLg-mobile-font-size);width:var(--rc-text-headingLg-mobile-font-size);}.rcb-modal-message-icon.large.svelte-w46z5s {height:calc(2 * var(--rc-text-headingMd-mobile-font-size));width:calc(2 * var(--rc-text-headingMd-mobile-font-size));}

  @container layout-query-container (width >= 768px) {.rcb-modal-message-icon.small.svelte-w46z5s {height:var(--rc-text-headingLg-desktop-font-size);width:var(--rc-text-headingLg-desktop-font-size);}.rcb-modal-message-icon.large.svelte-w46z5s {height:calc(2 * var(--rc-text-headingMd-desktop-font-size));width:calc(2 * var(--rc-text-headingMd-desktop-font-size));}.rcb-modal-message[data-has-title="false"].svelte-w46z5s {margin-top:var(--rc-spacing-gapXXLarge-desktop);}
  }`};function CLA(e,A){Ri(A,!0),hi(e,ILA);const t=ri(A,"title",3,null),i=ri(A,"icon",3,null),n=32;let g=sn(null),o=sn(!1),s;ac(()=>(MA(g)&&(s=new ResizeObserver(()=>{var I;Kt(o,(((I=MA(g))==null?void 0:I.offsetHeight)??0)>n)}),s.observe(MA(g))),()=>{s==null||s.disconnect()}));var a=rLA(),r=Ve(a);zlA(r,{gap:"medium",align:"start",children:(I,c)=>{var l=aLA(),B=_i(l);tLA(B,{children:(d,p)=>{var y=sLA(),m=_i(y);{var D=N=>{var G=gLA(),M=Ve(G);is(M,i),xt(()=>sd(G,`rcb-modal-message-icon ${(MA(o)?"large":"small")??""} svelte-w46z5s`)),Ne(N,G)};ii(m,N=>{i()&&N(D)})}var S=Ot(m,2);{var k=N=>{var G=oLA(),M=Ve(G);Zn(M,{size:"heading-md",children:(w,b)=>{var _=Cg();xt(()=>Sn(_,t())),Ne(w,_)},$$slots:{default:!0}}),NlA(G,w=>Kt(g,w),()=>MA(g)),Ne(N,G)};ii(S,N=>{t()&&N(k)})}Ne(d,y)},$$slots:{default:!0}});var Q=Ot(B,2);{var h=d=>{Zn(d,{size:"body-small",children:(p,y)=>{var m=xn(),D=_i(m);is(D,()=>A.message??cg),Ne(p,m)},$$slots:{default:!0}})};ii(Q,d=>{A.message&&d(h)})}Ne(I,l)},$$slots:{default:!0}}),xt(()=>Ci(a,"data-has-title",!!t())),Ne(e,a),Gi()}var cLA=Nt('<div class="rcb-modal-message-icon svelte-c8cuu5"><!></div>'),lLA=Nt("<!> <!>",1),BLA=Nt('<div class="rcb-modal-message svelte-c8cuu5" data-type="success"><!></div>');const ELA={hash:"svelte-c8cuu5",code:`.rcb-modal-message-icon.svelte-c8cuu5 {height:54px;width:54px;margin:0 auto;}.rcb-modal-message[data-has-title="false"].svelte-c8cuu5 {margin-top:var(--rc-spacing-gapXXLarge-mobile);}.rcb-modal-message.svelte-c8cuu5 {width:100%;min-height:160px;display:flex;justify-content:center;align-items:center;flex-direction:column;text-align:center;}

  @container layout-query-container (width >= 768px) {.rcb-modal-message[data-has-title="false"].svelte-c8cuu5 {margin-top:var(--rc-spacing-gapXXLarge-desktop);}
  }`};function QLA(e,A){Ri(A,!0),hi(e,ELA);const t=ri(A,"title",3,null),i=ri(A,"icon",3,null);var n=BLA(),g=Ve(n);zlA(g,{gap:"large",align:"center",children:(o,s)=>{var a=lLA(),r=_i(a);{var I=B=>{var Q=cLA(),h=Ve(Q);is(h,i),Ne(B,Q)};ii(r,B=>{i()&&B(I)})}var c=Ot(r,2);{var l=B=>{Zn(B,{size:"heading-md",children:(Q,h)=>{var d=Cg();xt(()=>Sn(d,t())),Ne(Q,d)},$$slots:{default:!0}})};ii(c,B=>{t()&&B(l)})}Ne(o,a)},$$slots:{default:!0}}),xt(()=>Ci(n,"data-has-title",!!t())),Ne(e,n),Gi()}const q8="rcb-ui-events-tracker",Y8="branding";var uLA=Nt('<div class="message-layout svelte-qavr33"><div class="message-layout-content svelte-qavr33"><!></div> <div class="message-layout-footer"><!></div></div>');const dLA={hash:"svelte-qavr33",code:`.message-layout.svelte-qavr33 {display:flex;flex-direction:column;}.message-layout-content.svelte-qavr33 {flex-grow:1;display:flex;flex-direction:column;justify-content:center;}

  @container layout-query-container (width < 768px) {.message-layout.svelte-qavr33 {flex-grow:1;gap:var(--rc-spacing-gapXXLarge-mobile);}
  }

  @container layout-query-container (width >= 768px) {.message-layout.svelte-qavr33 {min-height:354px;gap:var(--rc-spacing-gapXXLarge-desktop);}.message-layout-content.svelte-qavr33 {justify-content:flex-start;flex-grow:1;}
  }`};function H8(e,A){Ri(A,!0),hi(e,dLA);let t=ri(A,"title",3,null),i=ri(A,"closeButtonTitle",3,"Go back to app"),n=ri(A,"icon",3,null),g=ri(A,"message",3,null);const o=nr(Y8);function s(){A.onDismiss()}var a=uLA(),r=Ve(a),I=Ve(r);VJA(I,{children:(B,Q)=>{var h=xn(),d=_i(h);{var p=m=>{QLA(m,{get title(){return t()},get icon(){return n()}})},y=m=>{CLA(m,{get title(){return t()},get icon(){return n()},get message(){return g()}})};ii(d,m=>{A.type==="success"?m(p):m(y,!1)})}Ne(B,h)},$$slots:{default:!0}});var c=Ot(r,2),l=Ve(c);ZJA(l,{children:(B,Q)=>{jlA(B,{onclick:s,type:"submit",brandingAppearance:o,children:(h,d)=>{var p=Cg();xt(()=>Sn(p,i())),Ne(h,p)},$$slots:{default:!0}})},$$slots:{default:!0}}),Ne(e,a),Gi()}function $r(e,A){Ri(A,!0);const t=dI(),i=()=>uI(g,"$translator",t),n=ri(A,"key",3,""),g=nr(iC),o=Bt(()=>n()?i().translate(n()||"",A.variables):void 0);var s=xn(),a=_i(s);{var r=c=>{var l=Cg();xt(()=>Sn(l,MA(o))),Ne(c,l)},I=c=>{var l=xn(),B=_i(l);is(B,()=>A.children??cg),Ne(c,l)};ii(a,c=>{MA(o)?c(r):c(I,!1)})}Ne(e,s),Gi()}var hLA=Nt('<p class="footer-caption svelte-1hbk6xu"><!></p>'),pLA=Nt('<p class="footer-caption svelte-1hbk6xu"><!></p>'),fLA=Nt('<div class="footer-caption-container svelte-1hbk6xu"><!> <!> <p class="footer-caption svelte-1hbk6xu"><!></p></div>');const yLA={hash:"svelte-1hbk6xu",code:`.footer-caption-container.svelte-1hbk6xu {display:flex;flex-direction:column;gap:var(--rc-spacing-gapLarge-mobile);}.footer-caption.svelte-1hbk6xu {color:var(--rc-color-grey-text-light);text-align:center;margin:0;}

  @container layout-query-container (width >= 768px) {.footer-caption-container.svelte-1hbk6xu {gap:var(--rc-spacing-gapLarge-desktop);}
  }`};function DLA(e,A){Ri(A,!1),hi(e,yLA);const t=dI(),i=()=>uI(d,"$translator",t),n=Nc(),g=Nc(),o=Nc(),s=Nc(),a=Nc(),r=Nc(),I=Nc(),c=Nc(),l=Nc(),B=Nc();let Q=ri(A,"brandingInfo",8,null),h=ri(A,"purchaseOption",8,null);const d=nr(iC);function p(b){return b!=null&&"base"in b}function y(b){return b!=null&&"basePrice"in b}function m(b){return b?b.trial?oi.PaymentEntryPageTrialSubscriptionTermsInfo:oi.PaymentEntryPageSubscriptionTermsInfo:oi.PaymentEntryPageOtpTermsInfo}yl(()=>nK(h()),()=>{Kt(n,p(h())?h():null)}),yl(()=>nK(h()),()=>{Kt(g,y(h())?h():null)}),yl(()=>MA(n),()=>{Kt(o,m(MA(n)))}),yl(()=>MA(n),()=>{var b,_;Kt(s,((b=MA(n))==null?void 0:b.introPrice)||((_=MA(n))==null?void 0:_.base))}),yl(()=>(MA(g),MA(s)),()=>{var b,_;Kt(a,((b=MA(g))==null?void 0:b.basePrice)||((_=MA(s))==null?void 0:_.price))}),yl(()=>(MA(a),i()),()=>{Kt(r,MA(a)?ju(MA(a).amountMicros,MA(a).currency,i().locale||i().fallbackLocale):null)}),yl(()=>(MA(s),i()),()=>{var b,_,K,J,q;Kt(I,(b=MA(s))!=null&&b.period?i().translatePeriodFrequency(((K=(_=MA(s))==null?void 0:_.period)==null?void 0:K.number)||1,(q=(J=MA(s))==null?void 0:J.period)==null?void 0:q.unit,{useMultipleWords:!0}):null)}),yl(()=>(MA(n),i(),u1),()=>{var b,_;Kt(c,(_=(b=MA(n))==null?void 0:b.trial)!=null&&_.period?i().translateDate(u1(new Date,MA(n).trial.period,!0),{year:"numeric",month:"long",day:"numeric"}):null)}),yl(()=>(nK(Q()),MA(a),i(),MA(o),MA(r),MA(I),MA(c)),()=>{var b;Kt(l,Q()&&MA(a)?i().translate(MA(o),{appName:(b=Q())==null?void 0:b.app_name,price:MA(r),perFrequency:MA(I),renewalDate:MA(c)}):null)}),yl(()=>(MA(n),i(),oi),()=>{Kt(B,MA(n)?i().translate(oi.PaymentEntryPageSubscriptionInfo):null)}),vKA(),lc();var D=fLA(),S=Ve(D);{var k=b=>{var _=hLA(),K=Ve(_);Zn(K,{size:"caption-default",children:(J,q)=>{var v=Cg();xt(()=>Sn(v,MA(l))),Ne(J,v)},$$slots:{default:!0}}),Ne(b,_)};ii(S,b=>{MA(l)&&b(k)})}var N=Ot(S,2);{var G=b=>{var _=pLA(),K=Ve(_);Zn(K,{size:"caption-default",children:(J,q)=>{var v=Cg();xt(()=>Sn(v,MA(B))),Ne(J,v)},$$slots:{default:!0}}),Ne(b,_)};ii(N,b=>{MA(B)&&b(G)})}var M=Ot(N,2),w=Ve(M);Zn(w,{size:"caption-default",children:(b,_)=>{$r(b,{get key(){return oi.PaymentEntryPagePaymentStepTitle}})},$$slots:{default:!0}}),Ne(e,D),Gi()}var BI=(e=>(e.SDKInitialized="sdk_initialized",e.CheckoutSessionStart="checkout_session_start",e.CheckoutSessionEnd="checkout_session_end",e.CheckoutFlowError="checkout_flow_error",e.CheckoutPaymentTaxCalculation="checkout_payment_tax_calculation",e.CheckoutPaymentFormImpression="checkout_payment_form_impression",e.CheckoutPaymentFormError="checkout_payment_form_error",e.CheckoutPaymentFormDismiss="checkout_payment_form_dismiss",e.CheckoutPaymentFormSubmit="checkout_payment_form_submit",e.CheckoutPaymentFormGatewayError="checkout_payment_form_gateway_error",e.CheckoutPurchaseSuccessfulImpression="checkout_purchase_successful_impression",e.CheckoutPurchaseSuccessfulDismiss="checkout_purchase_successful_dismiss",e))(BI||{}),O8=(e=>(e.tax_collection_disabled="tax_collection_disabled",e.invalid_tax_location="invalid_tax_location",e.rate_limit_exceeded="rate_limit_exceeded",e.missing_required_permission="missing_required_permission",e.invalid_origin_address="invalid_origin_address",e.taxes_not_active="taxes_not_active",e.unexpected_gateway_error="unexpected_gateway_error",e))(O8||{});function mLA({errorCode:e,errorMessage:A}){return{eventName:BI.CheckoutFlowError,properties:{errorCode:e,errorMessage:A}}}function SLA({errorCode:e,errorMessage:A}){return{eventName:BI.CheckoutPaymentFormError,properties:{errorCode:e,errorMessage:A}}}function wLA({appearance:e,rcPackage:A,purchaseOptionToUse:t,customerEmail:i}){return{eventName:BI.CheckoutSessionStart,properties:{customizationColorButtonsPrimary:(e==null?void 0:e.color_buttons_primary)??null,customizationColorAccent:(e==null?void 0:e.color_accent)??null,customizationColorError:(e==null?void 0:e.color_error)??null,customizationColorProductInfoBg:(e==null?void 0:e.color_product_info_bg)??null,customizationColorFormBg:(e==null?void 0:e.color_form_bg)??null,customizationColorPageBg:(e==null?void 0:e.color_page_bg)??null,customizationFont:(e==null?void 0:e.font)??null,customizationShapes:(e==null?void 0:e.shapes)??null,customizationShowProductDescription:(e==null?void 0:e.show_product_description)??null,productInterval:A.webBillingProduct.normalPeriodDuration,productPrice:A.webBillingProduct.price.amountMicros,productCurrency:A.webBillingProduct.price.currency,selectedProductId:A.webBillingProduct.identifier,selectedPackageId:A.identifier,selectedPurchaseOption:t.id,customerEmailProvidedByDeveloper:!!i}}}function kLA({redemptionInfo:e}){return{eventName:BI.CheckoutSessionEnd,properties:{outcome:"finished",withRedemptionInfo:!!e}}}function MLA(){return{eventName:BI.CheckoutSessionEnd,properties:{outcome:"closed"}}}function NLA({errorCode:e,errorMessage:A}){return{eventName:BI.CheckoutSessionEnd,properties:{outcome:"errored",errorCode:e,errorMessage:A}}}function RLA({taxCalculation:e,taxCustomerDetails:A}){const t=e.failed_reason===O8.tax_collection_disabled?"disabled":e.failed_reason?"failed":e.tax_amount_in_micros===0?"not-taxed":"taxed",i=A===null?"auto":"form";return{eventName:BI.CheckoutPaymentTaxCalculation,properties:{outcome:t,ui_element:i,tax_inclusive:e.tax_inclusive,error_code:e.failed_reason??null}}}function GLA({selectedPaymentMethod:e}){return{eventName:BI.CheckoutPaymentFormSubmit,properties:{selectedPaymentMethod:e??null}}}function bLA({errorCode:e,errorMessage:A}){return{eventName:BI.CheckoutPaymentFormGatewayError,properties:{errorCode:e,errorMessage:A}}}const ULA=`<svg width="80" height="80" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
  <g transform="scale(0.5)" transform-origin="center">
  <path d="M12 3.5C7.30558 3.5 3.5 7.30558 3.5 12C3.5 16.6944 7.30558 20.5 12 20.5C16.6944 20.5 20.5 16.6944 20.5 12C20.5 11.5858 20.8358 11.25 21.25 11.25C21.6642 11.25 22 11.5858 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C12.4142 2 12.75 2.33579 12.75 2.75C12.75 3.16421 12.4142 3.5 12 3.5Z" fill="currentColor"/>
  </g>
</svg>`;var vLA=Nt('<div style="color:var(--rc-color-accent);" class="rcb-ui-asset-icon svelte-1sxpw7o"><!></div>');const KLA={hash:"svelte-1sxpw7o",code:`
  @-webkit-keyframes svelte-1sxpw7o-rotating /* Safari and Chrome */ {
    from {
      -webkit-transform: rotate(0deg);
      -o-transform: rotate(0deg);
      transform: rotate(0deg);
    }
    to {
      -webkit-transform: rotate(360deg);
      -o-transform: rotate(360deg);
      transform: rotate(360deg);
    }
  }
  @keyframes svelte-1sxpw7o-rotating {
    from {
      -ms-transform: rotate(0deg);
      -moz-transform: rotate(0deg);
      -webkit-transform: rotate(0deg);
      -o-transform: rotate(0deg);
      transform: rotate(0deg);
    }
    to {
      -ms-transform: rotate(360deg);
      -moz-transform: rotate(360deg);
      -webkit-transform: rotate(360deg);
      -o-transform: rotate(360deg);
      transform: rotate(360deg);
    }
  }div.svelte-1sxpw7o {width:80px;height:80px;
    -webkit-animation: svelte-1sxpw7o-rotating 2s ease-in-out infinite;
    -moz-animation: svelte-1sxpw7o-rotating 2s ease-in-out infinite;
    -ms-animation: svelte-1sxpw7o-rotating 2s ease-in-out infinite;
    -o-animation: svelte-1sxpw7o-rotating 2s ease-in-out infinite;
    animation: svelte-1sxpw7o-rotating 2s ease-in-out infinite;}`};function FLA(e){hi(e,KLA);var A=vLA(),t=Ve(A);bd(t,()=>ULA),Ne(e,A)}var _LA=Nt('<div class="rcb-modal-loader svelte-102edf4"><!></div>');const JLA={hash:"svelte-102edf4",code:`.rcb-modal-loader.svelte-102edf4 {width:100%;flex-grow:1;display:flex;justify-content:center;align-items:center;}

  @container layout-query-container (width >= 768px) {.rcb-modal-loader.svelte-102edf4 {align-items:flex-start;margin-top:calc(var(--rc-spacing-gapXXLarge-desktop) * 6);}
  }`};function ZlA(e){hi(e,JLA);var A=_LA(),t=Ve(A);FLA(t),Ne(e,A)}function LLA(e,A){var t,i;Ri(A,!0);const n=dI(),g=()=>uI(o,"$translator",n),o=nr(iC),s=nr(Y8),a=Bt(()=>A.priceBreakdown?g().formatPrice(A.priceBreakdown.totalAmountInMicros,A.priceBreakdown.currency):null),r=(i=(t=A.subscriptionOption)==null?void 0:t.trial)==null?void 0:i.period,I=Bt(()=>r?g().translatePeriod(r.number,r.unit):null);jlA(e,{get disabled(){return A.disabled},testId:"PayButton",brandingAppearance:s,children:(c,l)=>{var B=xn(),Q=_i(B);{var h=p=>{var y=Bt(()=>({trialPeriodLabel:MA(I)}));$r(p,{get key(){return oi.PaymentEntryPageButtonStartTrial},get variables(){return MA(y)}})},d=p=>{var y=xn(),m=_i(y);{var D=k=>{var N=Bt(()=>({formattedPrice:MA(a)}));$r(k,{get key(){return oi.PaymentEntryPageButtonWithPrice},get variables(){return MA(N)}})},S=k=>{$r(k,{get key(){return oi.PaymentEntryPageButtonPay}})};ii(m,k=>{MA(a)?k(D):k(S,!1)},!0)}Ne(p,y)};ii(Q,p=>{var y;(y=A.subscriptionOption)!=null&&y.trial?p(h):p(d,!1)})}Ne(c,B)},$$slots:{default:!0}}),Gi()}const xLA={error:"#B0171F",warning:"#f4e971",focus:"#1148B8",accent:"#767676",primary:"#576CDB","primary-hover":"rgba(87, 108, 219, .8)","primary-pressed":"rgba(87, 108, 219, .9)","primary-text":"#ffffff",white:"#ffffff","grey-text-dark":"rgba(0,0,0,1)","grey-text-light":"rgba(0,0,0,0.7)","grey-ui-dark":"rgba(0,0,0,0.3)","grey-ui-light":"rgba(0,0,0,0.1)","input-background":"white",background:"white"},TLA={error:"#B0171F",warning:"#f4e971",focus:"#1148B8",accent:"#767676",primary:"#576CDB","primary-hover":"rgba(87, 108, 219, .8)","primary-pressed":"rgba(87, 108, 219, .9)","primary-text":"#ffffff",white:"#ffffff","grey-text-dark":"rgba(0,0,0,1)","grey-text-light":"rgba(0,0,0,0.7)","grey-ui-dark":"rgba(0,0,0,0.3)","grey-ui-light":"rgba(0,0,0,0.1)","input-background":"white",background:"#EFF3FA"},WlA={error:"color_error",focus:"color_accent",accent:"color_accent",primary:"color_buttons_primary"},qLA={...WlA,"input-background":"color_form_bg",background:"color_form_bg"},YLA={...WlA,"input-background":"color_product_info_bg",background:"color_product_info_bg"},VlA={"input-border-radius":"4px","input-button-border-radius":"8px"},HLA={"input-border-radius":"0px","input-button-border-radius":"0px"},OLA={"input-border-radius":"12px","input-button-border-radius":"9999px"},f7=VlA,TF="-apple-system, BlinkMacSystemFont, avenir next, avenir, segoe ui, helvetica neue, helvetica, Cantarell, Ubuntu, roboto, noto, arial, sans-serif",XlA="BrandCustomFont",y7=`${XlA}, ${TF}`,kl={regular:"400",medium:"500",semibold:"600"},JC={12:"12px",14:"14px",16:"16px",18:"18px",24:"24px",28:"28px",32:"32px",36:"36px"},Ml={130:"130%",140:"140%"},Nl={tight:"0.20%",regular:"0",loose:"0.20%"},cs={heading2xl:{fontSize:JC[28],lineHeight:Ml[130],fontWeight:kl.semibold,letterSpacing:Nl.loose},headingXl:{fontSize:JC[24],lineHeight:Ml[130],fontWeight:kl.semibold,letterSpacing:Nl.loose},headingLg:{fontSize:"20px",lineHeight:Ml[130],fontWeight:kl.semibold,letterSpacing:Nl.loose},headingMd:{fontSize:"16px",lineHeight:Ml[140],fontWeight:kl.medium,letterSpacing:Nl.regular},bodyBase:{fontSize:JC[16],lineHeight:Ml[140],fontWeight:kl.regular,letterSpacing:Nl.regular},bodySmall:{fontSize:JC[14],lineHeight:Ml[140],fontWeight:kl.regular,letterSpacing:Nl.regular},labelButton:{fontSize:JC[16],lineHeight:Ml[140],fontWeight:kl.semibold,letterSpacing:Nl.tight},labelDefault:{fontSize:JC[14],lineHeight:Ml[140],fontWeight:kl.regular,letterSpacing:Nl.tight},captionDefault:{fontSize:JC[12],lineHeight:Ml[140],fontWeight:kl.regular,letterSpacing:Nl.regular},captionLink:{fontSize:JC[12],lineHeight:Ml[140],fontWeight:kl.regular,letterSpacing:Nl.regular}},Rl={heading2xl:{...cs.heading2xl,fontSize:JC[36]},headingXl:{...cs.headingXl,fontSize:JC[32]},headingLg:{...cs.headingLg,fontSize:JC[24]},headingMd:{...cs.headingMd,fontSize:JC[18]},bodyBase:{...cs.bodyBase},bodySmall:{...cs.bodySmall},labelButton:{...cs.labelButton},labelDefault:{...cs.labelDefault},captionDefault:{...cs.captionDefault},captionLink:{...cs.captionLink}},D1={heading2xl:{mobile:cs.heading2xl,desktop:Rl.heading2xl},headingXl:{desktop:Rl.headingXl,mobile:cs.headingXl},headingLg:{desktop:Rl.headingLg,mobile:cs.headingLg},headingMd:{desktop:Rl.headingMd,mobile:cs.headingMd},bodyBase:{desktop:Rl.bodyBase,mobile:cs.bodyBase},bodySmall:{desktop:Rl.bodySmall,mobile:cs.bodySmall},labelButton:{desktop:Rl.labelButton,mobile:cs.labelButton},labelDefault:{desktop:Rl.labelDefault,mobile:cs.labelDefault},captionDefault:{desktop:Rl.captionDefault,mobile:cs.captionDefault},captionLink:{desktop:Rl.captionLink,mobile:cs.captionLink}},sN=e=>e.length==7?{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}:e.length==4?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:null,P8=({r:e,g:A,b:t,luminanceThreshold:i})=>{const n=g=>(g=g/255,g<=.03928?g/12.92:Math.pow((g+.055)/1.055,2.4));return .2126*n(e)+.7152*n(A)+.0722*n(t)>i},j8=.37,PLA=(e,A=j8)=>{const t=P8({...e,luminanceThreshold:A})?"0,0,0":"255,255,255";return{"grey-text-dark":`rgb(${t})`,"grey-text-light":`rgba(${t},0.70)`,"grey-ui-dark":`rgba(${t},0.3)`,"grey-ui-light":`rgba(${t},0.1)`}};function jLA(e,A,t){const i=sN(e)||{r:0,g:0,b:0},n=sN(A)||{r:255,g:255,b:255},g=Math.round(n.r*t+i.r*(1-t)),o=Math.round(n.g*t+i.g*(1-t)),s=Math.round(n.b*t+i.b*(1-t));return`#${d2(g)}${d2(o)}${d2(s)}`}function D7(e,A){const t={r:255,g:255,b:255},i=Math.max(0,Math.min(1,A));let n=e,g=sN(e)||t;(isNaN(g.r)||isNaN(g.g)||isNaN(g.b))&&(g=t,n="#FFFFFF");const o=P8({...g,luminanceThreshold:j8})?"#000000":"#FFFFFF";return jLA(n,o,i)}function d2(e){return e.toString(16).padStart(2,"0").toUpperCase()}const zLA=(e,A,t,i=j8)=>{const n={"grey-text-dark":t["grey-text-dark"],"grey-text-light":t["grey-text-light"],"grey-ui-dark":t["grey-ui-dark"],"grey-ui-light":t["grey-ui-light"],"primary-text":t["primary-text"]};if(e!=null&&e.startsWith("#")){const g=sN(e);g!==null&&Object.assign(n,PLA(g))}if(A!=null&&A.startsWith("#")){const g=sN(A);g!==null&&(n["primary-text"]=P8({...g,luminanceThreshold:i})?"black":"white")}return n},ZLA=e=>({"primary-hover":D7(e,.1),"primary-pressed":D7(e,.15)}),WLA=(e,A)=>e||A,VLA=(e,A,t)=>{const i=Object.entries(e).map(([n,g])=>[n,WLA(t?t[g]:null,A[n])]);return Object.fromEntries(i)},$lA=(e,A,t)=>{const i=VLA(e,A,t);return t?{...A,...i,...zLA(i.background,i.primary,A),...ZLA(i.primary)}:{...A}},XLA=e=>$lA(YLA,TLA,e),ABA=e=>$lA(qLA,xLA,e),z8=e=>{if(!e)return f7;switch(e.shapes){case"rounded":return VlA;case"rectangle":return HLA;case"pill":return OLA;default:return f7}},qF=(e="",A)=>A.map(([t,i])=>`--rc-${e}-${t}: ${i}`).join("; "),eBA=e=>{const A=qF("color",Object.entries(XLA(e))),t=qF("shape",Object.entries(z8(e)));return[A,t].join("; ")},$LA=e=>{const A=qF("color",Object.entries(ABA(e))),t=qF("shape",Object.entries(z8(e)));return[A,t].join("; ")},AxA=(e="",A,t)=>Object.entries(A).flatMap(([i,{desktop:n,mobile:g}])=>{const o=`normal normal ${n.fontWeight} ${n.fontSize}/${n.lineHeight} ${TF}`,s=`normal normal ${g.fontWeight} ${g.fontSize}/${g.lineHeight} ${TF}`,a=`normal normal ${t==null?void 0:t.desktop.font_weight} ${t==null?void 0:t.desktop.font_size} ${y7}`,r=`normal normal ${t==null?void 0:t.mobile.font_weight} ${t==null?void 0:t.mobile.font_size} ${y7}`;return[`--rc-${e}-${i}-desktop: ${o}`,`--rc-${e}-${i}-mobile: ${s}`,`--rc-${e}-${i}-branded-desktop: ${t?a:o}`,`--rc-${e}-${i}-branded-mobile: ${t?r:s}`,`--rc-${e}-${i}-desktop-font-size: ${n.fontSize}`,`--rc-${e}-${i}-mobile-font-size: ${g.fontSize}`]}).join("; "),exA=(e="",A)=>Object.entries(A).map(([t,{mobile:i,desktop:n}])=>`--rc-${e}-${t}-mobile: ${i};  --rc-${e}-${t}-desktop: ${n};`).join(" "),txA={outerPaddingTop:{mobile:"0.25rem",desktop:"clamp(1rem, 8.44vw, 7.5rem)"},outerPadding:{mobile:"clamp(1.3125rem, 5.6vw, 1.5rem)",desktop:"clamp(3rem, 6.44vw, 4.5rem)"},gapSmall:{mobile:"0.25rem",desktop:"0.5rem"},gapMedium:{mobile:"0.5rem",desktop:"0.75rem"},gapLarge:{mobile:"0.75rem",desktop:"1rem"},gapXLarge:{mobile:"1rem",desktop:"2rem"},gapXXLarge:{mobile:"1.25rem",desktop:"2.25rem"},gapXXXLarge:{mobile:"2.25rem",desktop:"5rem"},inputHeight:{mobile:"3rem",desktop:"3rem"}};class aN{constructor(A){Yt(this,"brandingAppearance"),A?this.brandingAppearance=A:this.brandingAppearance=void 0}get shape(){return z8(this.brandingAppearance)}get formColors(){return ABA(this.brandingAppearance)}get formStyleVars(){return $LA(this.brandingAppearance)}get productInfoStyleVars(){return eBA(this.brandingAppearance)}get spacing(){return txA}get textStyles(){return D1}getTextStyleVars(A){return AxA("text",this.textStyles,A)}get spacingStyleVars(){return exA("spacing",this.spacing)}}var tBA="basil",ixA=function(e){return e===3?"v3":e},iBA="https://js.stripe.com",nxA="".concat(iBA,"/").concat(tBA,"/stripe.js"),gxA=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/,oxA=/^https:\/\/js\.stripe\.com\/(v3|[a-z]+)\/stripe\.js(\?.*)?$/,sxA=function(e){return gxA.test(e)||oxA.test(e)},axA=function(){for(var e=document.querySelectorAll('script[src^="'.concat(iBA,'"]')),A=0;A<e.length;A++){var t=e[A];if(sxA(t.src))return t}return null},m7=function(e){var A="",t=document.createElement("script");t.src="".concat(nxA).concat(A);var i=document.head||document.body;if(!i)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return i.appendChild(t),t},rxA=function(e,A){!e||!e._registerWrapper||e._registerWrapper({name:"stripe-js",version:"7.3.1",startTime:A})},p0=null,yb=null,Db=null,IxA=function(e){return function(A){e(new Error("Failed to load Stripe.js",{cause:A}))}},CxA=function(e,A){return function(){window.Stripe?e(window.Stripe):A(new Error("Stripe.js not available"))}},cxA=function(e){return p0!==null?p0:(p0=new Promise(function(A,t){if(typeof window>"u"||typeof document>"u"){A(null);return}if(window.Stripe){A(window.Stripe);return}try{var i=axA();if(!(i&&e)){if(!i)i=m7(e);else if(i&&Db!==null&&yb!==null){var n;i.removeEventListener("load",Db),i.removeEventListener("error",yb),(n=i.parentNode)===null||n===void 0||n.removeChild(i),i=m7(e)}}Db=CxA(A,t),yb=IxA(t),i.addEventListener("load",Db),i.addEventListener("error",yb)}catch(g){t(g);return}}),p0.catch(function(A){return p0=null,Promise.reject(A)}))},lxA=function(e,A,t){if(e===null)return null;var i=A[0],n=i.match(/^pk_test/),g=ixA(e.version),o=tBA;n&&g!==o&&console.warn("Stripe.js@".concat(g," was loaded on the page, but @stripe/stripe-js@").concat("7.3.1"," expected Stripe.js@").concat(o,". This may result in unexpected behavior. For more information, see https://docs.stripe.com/sdks/stripejs-versioning"));var s=e.apply(void 0,A);return rxA(s,t),s},mb,nBA=!1,gBA=function(){return mb||(mb=cxA(null).catch(function(e){return mb=null,Promise.reject(e)}),mb)};Promise.resolve().then(function(){return gBA()}).catch(function(e){nBA||console.warn(e)});var BxA=function(){for(var e=arguments.length,A=new Array(e),t=0;t<e;t++)A[t]=arguments[t];nBA=!0;var i=Date.now();return gBA().then(function(n){return lxA(n,A,i)})},m1=(e=>(e[e.ErrorLoadingStripe=0]="ErrorLoadingStripe",e[e.HandledFormError=1]="HandledFormError",e[e.UnhandledFormError=2]="UnhandledFormError",e))(m1||{});class oK{constructor(A,t,i){this.code=A,this.gatewayErrorCode=t,this.message=i}}const oBA=class sK{static getStripeLocale(A){if(["ca","hi","uk"].includes(A))return"auto";const t={zh_Hans:"zh",zh_Hant:"zh"};return Object.keys(t).includes(A)?t[A]:A}static async initializeStripe(A,t,i,n,g,o,s){if(!t||!A||!i)throw{code:0,gatewayErrorCode:void 0,message:"Stripe configuration is missing"};const a=await BxA(t,{stripeAccount:A}).catch(h=>{throw this.mapInitializationError(h)});if(!a)throw{code:0,gatewayErrorCode:void 0,message:"Stripe client not found"};const r=new aN(n==null?void 0:n.appearance),I=r.shape,c=r.formColors,l=r.textStyles,B=D1.bodyBase[s].fontSize||D1.bodyBase.mobile.fontSize;let Q;try{Q=a.elements({mode:i.mode,paymentMethodTypes:i.payment_method_types,setupFutureUsage:i.setup_future_usage,amount:i.amount,currency:i.currency,loader:"always",locale:g,appearance:{theme:"stripe",labels:"floating",variables:{borderRadius:I["input-border-radius"],focusBoxShadow:"none",colorDanger:c.error,colorTextPlaceholder:c["grey-text-light"],colorText:c["grey-text-dark"],colorTextSecondary:c["grey-text-light"],fontSizeBase:B,...o},rules:{".Input":{boxShadow:"none",paddingTop:"6px",paddingBottom:"6px",fontSize:B,border:`1px solid ${c["grey-ui-dark"]}`,backgroundColor:c["input-background"],color:c["grey-text-dark"]},".Input:focus":{border:`1px solid ${c.focus}`,outline:"none"},".Label":{fontWeight:l.labelDefault[s].fontWeight,lineHeight:"22px",color:c["grey-text-dark"]},".Label--floating":{opacity:"1"},".Input--invalid":{boxShadow:"none"}}}})}catch(h){throw this.mapInitializationError(h)}return{stripe:a,elements:Q}}static async updateElementsConfiguration(A,t){A.update({mode:t.mode,paymentMethodTypes:t.payment_method_types,setupFutureUsage:t.setup_future_usage,amount:t.amount,currency:t.currency})}static isStripeHandledFormError(A){const t=A.type==="validation_error",i=A.type==="card_error"&&A.code&&this.FORM_VALIDATED_CARD_ERROR_CODES.includes(A.code);return t||i}static createPaymentElement(A,t){return A.create("payment",{business:t?{name:t}:void 0,layout:{type:"tabs"},terms:{applePay:"never",auBecsDebit:"never",bancontact:"never",card:"never",cashapp:"never",googlePay:"never",ideal:"never",paypal:"never",sepaDebit:"never",sofort:"never",usBankAccount:"never"}})}static createExpressCheckoutElement(A,t,i){const n={billingAddressRequired:t,emailRequired:!0,...i||{}};return A.create("expressCheckout",n)}static createLinkAuthenticationElement(A,t){return A.create("linkAuthentication",{defaultValues:{email:t??""}})}static async submitElements(A){const{error:t}=await A.submit();if(t)throw this.mapError(t)}static mapInitializationError(A){return new oK(0,A.code,A.message)}static mapError(A){return this.isStripeHandledFormError(A)?new oK(1,A.code,A.message):new oK(2,A.code,A.message)}static async confirmElements(A,t,i,n){const g={clientSecret:i,redirect:"if_required"},o=n?{...g,confirmParams:{confirmation_token:n}}:{...g,elements:t},s=i.startsWith("seti_");let a;if(s?a=await A.confirmSetup(o):a=await A.confirmPayment(o),a!=null&&a.error)throw this.mapError(a.error)}static async extractTaxCustomerDetails(A,t){var i,n;const{error:g,confirmationToken:o}=await t.createConfirmationToken({elements:A});if(g)throw this.mapError(g);const s=(n=(i=o.payment_method_preview)==null?void 0:i.billing_details)==null?void 0:n.address;return{customerDetails:{countryCode:(s==null?void 0:s.country)??void 0,postalCode:(s==null?void 0:s.postal_code)??void 0},confirmationTokenId:o.id}}static nextDateForPeriod(A,t){return A.unit===Sa.Year?(t.setFullYear(t.getFullYear()+A.number),t):A.unit===Sa.Month?(t.setMonth(t.getMonth()+A.number),t):A.unit===Sa.Week?(t.setDate(t.getDate()+A.number*7),t):(A.unit===Sa.Day&&t.setDate(t.getDate()+A.number),t)}static applePayPeriod(A){return A.unit===Sa.Week?{recurringPaymentIntervalUnit:"day",recurringPaymentIntervalCount:A.number*7}:{recurringPaymentIntervalUnit:A.unit,recurringPaymentIntervalCount:A.number}}static microsToMinimumAmountPrice(A,t){return["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"].includes(t)?Math.floor(A/1e6):Math.floor(A/1e4)}static buildStripeExpressCheckoutOptionsForSubscription(A,t,i,n,g){var o;const s=sK.microsToMinimumAmountPrice(t.totalAmountInMicros,t.currency),a=i.trial,r=(o=i.trial)==null?void 0:o.period,I=i.base.period,c=a&&r?sK.nextDateForPeriod(r,new Date):void 0,l=I?sK.applePayPeriod(I):{};return{applePay:{recurringPaymentRequest:{paymentDescription:A.title,managementURL:g,trialBilling:a?{label:n.translate(oi.ApplePayFreeTrial),amount:0}:void 0,regularBilling:{label:A.title,amount:s,recurringPaymentStartDate:c,...l}}}}}};Yt(oBA,"FORM_VALIDATED_CARD_ERROR_CODES",["card_declined","expired_card","incorrect_cvc","incorrect_number"]);let Xa=oBA;var ExA=Nt("<div></div>");function QxA(e,A){Ri(A,!0);let t=null;const i="payment-element",n=async o=>{await A.onError(Xa.mapInitializationError(o.error))};ac(()=>{var o;try{t=Xa.createPaymentElement(A.elements,(o=A.brandingInfo)==null?void 0:o.app_name),t.mount(`#${i}`),t.on("ready",A.onReady),t.on("change",A.onChange),t.on("loaderror",n)}catch(s){A.onError(Xa.mapInitializationError(s))}}),JR(()=>{t==null||t.destroy(),t=null});var g=ExA();Ci(g,"id",i),Ne(e,g),Gi()}var uxA=Nt("<div></div>");function dxA(e,A){Ri(A,!0);let t=null;const i="link-authentication-element",n=async o=>{await A.onError(Xa.mapInitializationError(o.error))};ac(()=>{try{t=Xa.createLinkAuthenticationElement(A.elements,A.email),t.mount(`#${i}`),t.on("ready",A.onReady),t.on("change",A.onChange),t.on("loaderror",n)}catch(o){A.onError(Xa.mapInitializationError(o))}}),JR(()=>{t==null||t.destroy(),t=null});var g=uxA();Ci(g,"id",i),Ne(e,g),Gi()}var hxA=Nt('<div class="text-separator svelte-ch0h61"><hr class="line svelte-ch0h61"> <span class="text svelte-ch0h61"><!></span> <hr class="line svelte-ch0h61"></div>');const pxA={hash:"svelte-ch0h61",code:`.text-separator.svelte-ch0h61 {display:flex;align-items:center;justify-content:center;gap:var(--rc-spacing-gapSmall-mobile);}

  @container layout-query-container (width >= 768px) {.text-separator.svelte-ch0h61 {gap:var(--rc-spacing-gapSmall-desktop);}
  }.line.svelte-ch0h61 {flex:1;height:1px;background-color:var(--rc-color-grey-ui-dark);border:none;}.text.svelte-ch0h61 {color:var(--rc-color-grey-text-light);text-transform:uppercase;white-space:nowrap;}`};function fxA(e,A){hi(e,pxA);let t=ri(A,"text",8);var i=hxA(),n=Ot(Ve(i),2),g=Ve(n);Zn(g,{size:"caption-default",children:(o,s)=>{var a=Cg();xt(()=>Sn(a,t())),Ne(o,a)},$$slots:{default:!0}}),Ne(e,i)}var yxA=Nt("<div></div> <!>",1);function DxA(e,A){Ri(A,!0);const t=dI(),i=()=>uI(n,"$translator",t),n=nr(iC);let g=null,o=sn(!1);const s="express-checkout-element",a=async h=>{const d={...A.expressCheckoutOptions?A.expressCheckoutOptions:{}};h.resolve(d)},r=async h=>{await A.onError(Xa.mapInitializationError(h.error))},I=async h=>{var d;A.onSubmit(h.expressPaymentType,((d=h.billingDetails)==null?void 0:d.email)??"")},c=async h=>{Kt(o,!h.availablePaymentMethods),A.onReady()};ac(()=>{try{g=Xa.createExpressCheckoutElement(A.elements,A.billingAddressRequired,A.expressCheckoutOptions),g.mount(`#${s}`),g.on("ready",c),g.on("confirm",I),g.on("loaderror",r),g.on("click",a)}catch(h){A.onError(Xa.mapInitializationError(h))}}),JR(()=>{g==null||g.destroy(),g=null});var l=xn(),B=_i(l);{var Q=h=>{var d=yxA(),p=_i(d);Ci(p,"id",s);var y=Ot(p,2),m=Bt(()=>i().translate(oi.PaymentEntryPageExpressCheckoutDivider));fxA(y,{get text(){return MA(m)}}),Ne(h,d)};ii(B,h=>{MA(o)||h(Q)})}Ne(e,l),Gi()}var mxA=Nt('<div class="rc-elements svelte-6qa1vy"><!> <!> <!></div>');const SxA={hash:"svelte-6qa1vy",code:`.rc-elements.svelte-6qa1vy {display:flex;flex-direction:column;gap:var(--rc-spacing-gapXLarge-mobile);}

  @container layout-query-container (width >= 768px) {.rc-elements.svelte-6qa1vy {gap:var(--rc-spacing-gapLarge-desktop);}
  }`};function wxA(e,A){Ri(A,!0),hi(e,SxA);const t=dI(),i=()=>uI(o,"$translator",t);let n=ri(A,"stripe",15,null),g=ri(A,"elements",15,null);const o=nr(iC),s=Xa.getStripeLocale(i().locale||i().fallbackLocale);let a=sn(!1),r=sn(pi(A.skipEmail)),I=sn(!1),c=sn(void 0),l=sn("mobile"),B=sn(void 0);function Q(){window.matchMedia&&window.matchMedia("(max-width: 767px)").matches?Kt(l,"mobile"):Kt(l,"desktop"),Kt(c,pi({fontSizeBase:"14px",fontFamily:TF,spacingGridRow:"16px"}))}function h(){clearTimeout(MA(B)),Kt(B,pi(setTimeout(()=>{Q()},150)))}const d=M=>{A.onError(M),A.onLoadingComplete()},p=async()=>{MA(r)||(Kt(r,!0),MA(r)&&MA(a)&&MA(I)&&A.onLoadingComplete())},y=async()=>{MA(I)||(Kt(I,!0),MA(r)&&MA(a)&&MA(I)&&A.onLoadingComplete())},m=async()=>{MA(a)||(Kt(a,!0),MA(r)&&MA(a)&&MA(I)&&A.onLoadingComplete())},D=async M=>{A.onPaymentInfoChange({complete:M.complete,paymentMethod:M.complete?M.value.type:void 0})},S=async M=>{A.onEmailChange(M.complete,M.value.email)};ac(()=>(window.addEventListener("resize",h),()=>{window.removeEventListener("resize",h)})),ac(async()=>{Q(),!n()&&(g()||!A.stripeAccountId||!A.publishableApiKey||!A.elementsConfiguration||await Xa.initializeStripe(A.stripeAccountId,A.publishableApiKey,A.elementsConfiguration,A.brandingInfo,s,MA(c),MA(l)).then(({stripe:M,elements:w})=>{n(M),g(w)}).catch(M=>{A.onError(M)}))}),SS(()=>{A.elementsConfiguration&&g()&&Xa.updateElementsConfiguration(g(),A.elementsConfiguration)});var k=xn(),N=_i(k);{var G=M=>{var w=mxA(),b=Ve(w);DxA(b,{get elements(){return g()},onError:d,onReady:y,get onSubmit(){return A.onExpressCheckoutElementSubmit},get expressCheckoutOptions(){return A.expressCheckoutOptions},get billingAddressRequired(){return A.billingAddressRequired}});var _=Ot(b,2);{var K=q=>{dxA(q,{get elements(){return g()},onReady:p,onChange:S,onError:d})};ii(_,q=>{A.skipEmail||q(K)})}var J=Ot(_,2);QxA(J,{get elements(){return g()},get brandingInfo(){return A.brandingInfo},onReady:m,onChange:D,onError:d}),Ne(M,w)};ii(N,M=>{g()&&M(G)})}Ne(e,k),Gi()}const kxA=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
  <path fill-rule="evenodd" d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm0 6.5a1.25 1.25 0 100-2.5 1.25 1.25 0 000 2.5zm1.25 4.5a1.25 1.25 0 10-2.5 0v4.5a1.25 1.25 0 102.5 0v-4.5z" clip-rule="evenodd" />
</svg> `;var MxA=Nt('<div class="rcb-ui-asset-icon svelte-1rk57mx"><!></div>');const NxA={hash:"svelte-1rk57mx",code:".rcb-ui-asset-icon.svelte-1rk57mx {display:inline-block;width:1em;height:1em;}"};function sBA(e){hi(e,NxA);var A=MxA(),t=Ve(A);bd(t,()=>kxA),Ne(e,A)}var RxA=Nt('<div class="rcb-info svelte-1czikbr"><div class="rcb-info-icon-wrapper svelte-1czikbr"><!></div> <div class="rcb-info-content svelte-1czikbr"><div class="rcb-info-title svelte-1czikbr"><!></div> <div class="rcb-info-message svelte-1czikbr"><!></div></div></div>');const GxA={hash:"svelte-1czikbr",code:`.rcb-info.svelte-1czikbr {display:flex;align-items:flex-start;background-color:var(--rc-color-grey-ui-light);border-radius:var(--rc-shape-input-border-radius);gap:var(--rc-spacing-gapLarge-mobile);padding:var(--rc-spacing-gapLarge-mobile);}.rcb-info-content.svelte-1czikbr {flex:1;}.rcb-info-icon-wrapper.svelte-1czikbr {flex-shrink:0;color:var(--rc-color-accent-primary);}.rcb-info-title.svelte-1czikbr {color:var(--rc-color-grey-text-dark);margin-bottom:var(--rc-spacing-gapSmall-mobile);display:flex;}.rcb-info-message.svelte-1czikbr {color:var(--rc-color-grey-text-light);}

  @container layout-query-container (width >= 768px) {.rcb-info.svelte-1czikbr {gap:var(--rc-spacing-gapLarge-desktop);padding:var(--rc-spacing-gapLarge-desktop);}.rcb-info-title.svelte-1czikbr {margin-bottom:var(--rc-spacing-gapSmall-desktop);}
  }`};function bxA(e,A){hi(e,GxA);var t=RxA(),i=Ve(t),n=Ve(i);sBA(n);var g=Ot(i,2),o=Ve(g),s=Ve(o);Zn(s,{size:"body-small",children:(I,c)=>{var l=Cg();xt(()=>Sn(l,A.title)),Ne(I,l)},$$slots:{default:!0}});var a=Ot(o,2),r=Ve(a);Zn(r,{size:"body-small",children:(I,c)=>{var l=Cg();xt(()=>Sn(l,A.message)),Ne(I,l)},$$slots:{default:!0}}),Ne(e,t)}function UxA(e,A){Ri(A,!0);const t=dI(),i=()=>uI(n,"$translator",t),n=nr(iC);var g=Bt(()=>i().translate(oi.PriceUpdateTitle)),o=Bt(()=>{var s;return i().translate((s=A.subscriptionOption)!=null&&s.trial?oi.PriceUpdateTrialMessage:oi.PriceUpdateBaseMessage)});bxA(e,{get title(){return MA(g)},get message(){return MA(o)}}),Gi()}function aBA(e,A){if(e.productType==="subscription"){const t=A,i=t.introPrice?t.introPrice.price:t.base.price;if(i)return i}else return A.basePrice;return e.price}class S7 extends Error{}var vxA=Nt('<div class="rc-loading svelte-dg9m6p"><!></div>'),KxA=Nt('<div class="rc-checkout-container svelte-dg9m6p"><!> <!> <form data-testid="payment-form" class="rc-checkout-form svelte-dg9m6p"><div class="rc-checkout-form-container svelte-dg9m6p"><div class="rc-elements-container svelte-dg9m6p"><!></div> <div class="rc-checkout-price-update-info-container svelte-dg9m6p"><!></div> <div class="rc-checkout-pay-container svelte-dg9m6p"><!> <div class="rc-checkout-secure-container svelte-dg9m6p"><!></div></div></div></form></div>');const FxA={hash:"svelte-dg9m6p",code:`.rc-checkout-secure-container.svelte-dg9m6p {margin-top:var(--rc-spacing-gapXLarge-mobile);}.rc-checkout-container.svelte-dg9m6p {display:flex;flex-direction:column;gap:var(--rc-spacing-gapXLarge-mobile);user-select:none;position:relative;}.rc-checkout-price-update-info-container.svelte-dg9m6p {margin-top:var(--rc-spacing-gapXLarge-mobile);}.fully-hidden.svelte-dg9m6p {display:none;height:0;}.rc-checkout-pay-container.svelte-dg9m6p {display:flex;flex-direction:column;margin-top:var(--rc-spacing-gapXLarge-mobile);}.rc-checkout-pay-container.fully-hidden.svelte-dg9m6p {display:none;}.rc-checkout-form-container.svelte-dg9m6p {width:100%;}.rc-elements-container.svelte-dg9m6p {
    /* The standard height of the payment form from Stripe */
    /* Added to avoid the card getting smaller while loading */min-height:210px;}.rc-checkout-form-container.invisible.svelte-dg9m6p {visibility:hidden;}.rc-loading.svelte-dg9m6p {width:100%;height:100%;display:flex;justify-content:center;align-items:center;}

  @container layout-query-container (width <= 767px) {.rc-checkout-pay-container.svelte-dg9m6p {flex-grow:1;justify-content:flex-end;}.rc-checkout-form.svelte-dg9m6p {flex-grow:1;}.rc-checkout-form-container.svelte-dg9m6p {height:100%;display:flex;flex-direction:column;}.rc-checkout-container.svelte-dg9m6p {flex-grow:1;}.rc-loading.svelte-dg9m6p {position:absolute;top:0;left:0;}
  }

  @container layout-query-container (width >= 768px) {.rc-checkout-secure-container.svelte-dg9m6p {margin-top:var(--rc-spacing-gapXLarge-desktop);}.rc-checkout-container.svelte-dg9m6p {gap:var(--rc-spacing-gapXLarge-desktop);}.rc-checkout-pay-container.svelte-dg9m6p {margin-top:var(--rc-spacing-gapXLarge-desktop);}.rc-checkout-price-update-info-container.svelte-dg9m6p {margin-top:var(--rc-spacing-gapXLarge-desktop);}
  }form.svelte-dg9m6p {display:flex;flex-direction:column;flex-grow:1;}`};function _xA(e,A){var t,i,n;Ri(A,!0),hi(e,FxA);const g=dI(),o=()=>uI(a,"$translator",g),s=nr(q8),a=nr(iC),r=(t=A.productDetails.subscriptionOptions)==null?void 0:t[A.purchaseOption.id],I=aBA(A.productDetails,A.purchaseOption);let c=sn(pi(((i=A.defaultPriceBreakdown)==null?void 0:i.taxCalculationStatus)??((n=A.brandingInfo)!=null&&n.gateway_tax_collection_enabled?"unavailable":"disabled"))),l=sn(null),B=sn(null),Q=sn(pi(I.amountMicros)),h=sn(pi(I.amountMicros)),d=Bt(()=>A.defaultPriceBreakdown??{currency:I.currency,totalAmountInMicros:MA(h),totalExcludingTaxInMicros:MA(Q),taxCalculationStatus:MA(c),taxAmountInMicros:MA(l),taxBreakdown:MA(B)}),p=sn(pi(A.gatewayParams.elements_configuration)),y=sn(null),m=sn(null),D=sn(null),S=sn(pi(A.customerEmail??void 0)),k=sn(pi(!!A.customerEmail)),N=sn(!0),G=sn(!1),M=sn(void 0),w=sn(void 0),b=sn(void 0),_=sn(!1),K=sn(null),J=Bt(()=>MA(N)||MA(_)?"loading":MA(w)?"error":"form"),q=sn("unavailable"),v=Bt(()=>!MA(_)&&MA(G)&&MA(k)&&(MA(c)==="disabled"||MA(c)==="calculated"||MA(c)==="miss-match")),U=Bt(()=>r&&A.managementUrl&&MA(d)?Xa.buildStripeExpressCheckoutOptionsForSubscription(A.productDetails,MA(d),r,o(),A.managementUrl):void 0);SS(()=>{A.onPriceBreakdownUpdated(MA(d))}),ac(async()=>{MA(c)==="unavailable"&&await x(null).catch($)}),JR(()=>{MA(K)&&(MA(K).abort(),Kt(K,null))});async function x(EA,PA){await A.purchaseOperationHelper.checkoutCalculateTax(EA==null?void 0:EA.countryCode,EA==null?void 0:EA.postalCode,PA).then(ZA=>{const FA=RLA({taxCalculation:ZA,taxCustomerDetails:EA});s.trackSDKEvent(FA),PA==null||PA.throwIfAborted(),ZA.failed_reason?!EA&&ZA.failed_reason===O8.invalid_tax_location?Kt(c,"pending"):Kt(c,"disabled"):Kt(c,"calculated"),Kt(l,pi(ZA.tax_amount_in_micros)),Kt(Q,pi(ZA.total_excluding_tax_in_micros)),Kt(h,pi(ZA.total_amount_in_micros)),Kt(B,pi(ZA.tax_breakdown)),Kt(p,pi(ZA.gateway_params.elements_configuration)),Kt(y,pi(EA))})}function T(){s.trackSDKEvent({eventName:BI.CheckoutPaymentFormImpression}),Kt(N,!1)}async function z(EA,PA){Kt(S,pi(PA)),Kt(k,pi(EA)),await sA()}async function Z({complete:EA,paymentMethod:PA}){Kt(M,pi(PA)),Kt(G,pi(EA)),await sA()}async function eA(EA){if(EA==null||EA.preventDefault(),MA(_))return;const PA=GLA({selectedPaymentMethod:MA(M)??null});s.trackSDKEvent(PA),Kt(_,!0),await pA()?A.onContinue():Kt(_,!1)}async function aA(EA,PA){Kt(M,pi(EA)),Kt(S,pi(A.customerEmail??PA)),await eA()}async function sA(){MA(M)!=="card"||!MA(k)||!MA(G)||MA(_)||MA(c)==="disabled"||(MA(c)!=="loading"&&(Kt(q,pi(MA(c))),Kt(c,"loading")),await gA(async EA=>{await yA().then(()=>EA.throwIfAborted()).then(()=>fA(EA)).then(()=>EA.throwIfAborted()).catch(PA=>{EA.aborted||$(PA)}).finally(()=>{MA(c)==="loading"&&!EA.aborted&&Kt(c,pi(MA(q)))})}))}async function pA(){return await gA(async EA=>{const PA=MA(h);let ZA;return await yA().then(()=>EA.throwIfAborted()).then(()=>fA(EA)).then(FA=>{ZA=FA}).then(()=>EA.throwIfAborted()).then(RA(PA)).then(()=>EA.throwIfAborted()).then(qA).then(()=>EA.throwIfAborted()).then(()=>W(ZA)).then(()=>EA.throwIfAborted()).then(()=>!0).catch(FA=>(EA.aborted||$(FA),!1))})}async function gA(EA){MA(K)&&MA(K).abort(),Kt(K,pi(new AbortController));const PA=MA(K).signal;try{return await EA(PA)}catch(ZA){if(ZA instanceof DOMException&&ZA.name==="AbortError")return Promise.resolve(void 0);throw ZA}}async function yA(){MA(D)&&await Xa.submitElements(MA(D))}async function fA(EA){var PA,ZA;if(MA(c)==="unavailable"||MA(c)==="disabled"||!MA(D)||!MA(m))return;const{customerDetails:FA,confirmationTokenId:Ie}=await Xa.extractTaxCustomerDetails(MA(D),MA(m));return EA==null||EA.throwIfAborted(),FA.postalCode===((PA=MA(y))==null?void 0:PA.postalCode)&&FA.countryCode===((ZA=MA(y))==null?void 0:ZA.countryCode)||await x(FA,EA),Ie&&MA(M)!=="card"?Ie:void 0}function RA(EA){return()=>{if(MA(h)!==EA)throw new S7}}async function qA(){var EA;const PA=await A.purchaseOperationHelper.checkoutComplete(MA(S)),ZA=(EA=PA==null?void 0:PA.gateway_params)==null?void 0:EA.client_secret;ZA&&Kt(b,pi(ZA))}async function W(EA){!MA(m)||!MA(D)||!MA(b)||await Xa.confirmElements(MA(m),MA(D),MA(b),EA)}async function $(EA){if(EA instanceof S7)Kt(c,"miss-match");else if(EA instanceof Fg){const PA=SLA({errorCode:EA.errorCode.toString(),errorMessage:EA.message});s.trackSDKEvent(PA),EA.errorCode===dg.MissingEmailError?Kt(w,pi(o().translate(oi.ErrorPageErrorMessageInvalidEmailError,{email:MA(S)}))):A.onError(EA)}else if(EA instanceof oK)await L(EA);else throw EA}async function L(EA){const PA=bLA({errorCode:EA.gatewayErrorCode??"",errorMessage:EA.message??""});s.trackSDKEvent(PA),EA.code===m1.HandledFormError||(EA.code===m1.UnhandledFormError?Kt(w,pi(EA.message)):A.onError(new Fg(dg.ErrorSettingUpPurchase,"Failed to initialize payment form",EA.message)))}const H=()=>{Kt(w,void 0)};var P=KxA(),tA=Ve(P);{var iA=EA=>{var PA=vxA(),ZA=Ve(PA);ZlA(ZA),Ne(EA,PA)};ii(tA,EA=>{MA(J)==="loading"&&EA(iA)})}var oA=Ot(tA,2);{var IA=EA=>{var PA=Bt(()=>o().translate(oi.ErrorButtonTryAgain));H8(EA,{title:null,type:"error",get closeButtonTitle(){return MA(PA)},onDismiss:H,icon:ZA=>{UlA(ZA)},message:ZA=>{var FA=Cg();xt(()=>Sn(FA,MA(w))),Ne(ZA,FA)},$$slots:{icon:!0,message:!0}})};ii(oA,EA=>{MA(J)==="error"&&EA(IA)})}var CA=Ot(oA,2),_A=Ve(CA),uA=Ve(_A),X=Ve(uA),O=Bt(()=>!!A.customerEmail),cA=Bt(()=>MA(c)!=="disabled");wxA(X,{get stripeAccountId(){return A.gatewayParams.stripe_account_id},get publishableApiKey(){return A.gatewayParams.publishable_api_key},get elementsConfiguration(){return MA(p)},get brandingInfo(){return A.brandingInfo},get skipEmail(){return MA(O)},get billingAddressRequired(){return MA(cA)},onLoadingComplete:T,onError:L,onEmailChange:z,onPaymentInfoChange:Z,onExpressCheckoutElementSubmit:aA,get expressCheckoutOptions(){return MA(U)},get stripe(){return MA(m)},set stripe(EA){Kt(m,pi(EA))},get elements(){return MA(D)},set elements(EA){Kt(D,pi(EA))}});var wA=Ot(uA,2),xA=Ve(wA);UxA(xA,{subscriptionOption:r});var YA=Ot(wA,2),jA=Ve(YA),ie=Bt(()=>!MA(v)),he=Bt(()=>{var EA;return(EA=A.brandingInfo)!=null&&EA.gateway_tax_collection_enabled?MA(d):void 0});LLA(jA,{get disabled(){return MA(ie)},subscriptionOption:r,get priceBreakdown(){return MA(he)}});var le=Ot(jA,2),NA=Ve(le);DLA(NA,{get brandingInfo(){return A.brandingInfo},get purchaseOption(){return A.purchaseOption}}),xt(()=>{LE(_A,"invisible",MA(J)!=="form"),LE(wA,"fully-hidden",MA(c)!=="miss-match"||MA(J)!=="form"),LE(YA,"fully-hidden",MA(J)!=="form")}),iB("submit",CA,eA),Ne(e,P),Gi()}function JxA(e){return e!=null}var _p=(e=>(e.Subscription="subscription",e.Consumable="consumable",e.NonConsumable="non_consumable",e))(_p||{});const rBA=e=>({amount:e.amount_micros/1e4,amountMicros:e.amount_micros,currency:e.currency,formattedPrice:ju(e.amount_micros,e.currency)}),h2=e=>{const A=e.period_duration,t=e.price?rBA(e.price):null,i=A?GlA(A):null;let n=null,g=null,o=null;if(t!==null&&i!==null){const s=LxA(i),a=1e4,r=Math.round(t.amountMicros*s.toWeek);n={amount:r/a,amountMicros:r,currency:t.currency,formattedPrice:ju(r,t.currency)};const I=Math.round(t.amountMicros*s.toMonth);g={amount:I/a,amountMicros:I,currency:t.currency,formattedPrice:ju(I,t.currency)};const c=Math.round(t.amountMicros*s.toYear);o={amount:c/a,amountMicros:c,currency:t.currency,formattedPrice:ju(c,t.currency)}}return{periodDuration:A,period:i,cycleCount:e.cycle_count,price:t,pricePerWeek:n,pricePerMonth:g,pricePerYear:o}};function LxA(e){const{number:A,unit:t}=e,i=7,n=30,g=365;let o;switch(t){case Sa.Day:o=A;break;case Sa.Week:o=A*i;break;case Sa.Month:o=A*n;break;case Sa.Year:o=A*g;break;default:o=0,$i.errorLog(`Unknown period unit: ${t}`)}const s=o>0?i/o:0,a=o>0?n/o:0,r=o>0?g/o:0;return{toWeek:s,toMonth:a,toYear:r}}const xxA=e=>e.base==null?($i.debugLog("Missing base phase for subscription option. Ignoring."),null):{id:e.id,priceId:e.price_id,base:h2(e.base),trial:e.trial?h2(e.trial):null,introPrice:e.intro_price?h2(e.intro_price):null},TxA=e=>e.base_price==null?($i.debugLog("Missing base price for non-subscription option. Ignoring."),null):{id:e.id,priceId:e.price_id,basePrice:rBA(e.base_price)},qxA=(e,A)=>{const t=e.product_type;return t==="subscription"?HxA(e,A,t):YxA(e,A,t)},YxA=(e,A,t)=>{const i={};if(Object.entries(e.purchase_options).forEach(([o,s])=>{const a=TxA(s);a!=null&&(i[o]=a)}),Object.keys(i).length===0)return $i.debugLog(`Product ${e.identifier} has no purchase options. Ignoring.`),null;const n=e.default_purchase_option_id,g=n&&n in e.purchase_options?i[n]:null;return g==null?($i.debugLog(`Product ${e.identifier} has no default purchase option. Ignoring.`),null):{identifier:e.identifier,displayName:e.title,title:e.title,description:e.description,productType:t,currentPrice:g.basePrice,normalPeriodDuration:null,presentedOfferingIdentifier:A.offeringIdentifier,presentedOfferingContext:A,defaultPurchaseOption:g,defaultSubscriptionOption:null,subscriptionOptions:{},defaultNonSubscriptionOption:g,price:g.basePrice,period:null,freeTrialPhase:null,introPricePhase:null}},HxA=(e,A,t)=>{const i={};if(Object.entries(e.purchase_options).forEach(([s,a])=>{const r=xxA(a);r!=null&&(i[s]=r)}),Object.keys(i).length===0)return $i.debugLog(`Product ${e.identifier} has no subscription options. Ignoring.`),null;const n=e.default_purchase_option_id,g=n&&n in i?i[n]:null;if(g==null)return $i.debugLog(`Product ${e.identifier} has no default subscription option. Ignoring.`),null;const o=g.base.price;return o==null?($i.debugLog(`Product ${e.identifier} default option has no base price. Ignoring.`),null):{identifier:e.identifier,displayName:e.title,title:e.title,description:e.description,productType:t,currentPrice:o,normalPeriodDuration:g.base.periodDuration,presentedOfferingIdentifier:A.offeringIdentifier,presentedOfferingContext:A,defaultPurchaseOption:g,defaultSubscriptionOption:g,subscriptionOptions:i,defaultNonSubscriptionOption:null,price:o,period:g.base.period,freeTrialPhase:g.trial,introPricePhase:g.introPrice}},OxA=(e,A,t)=>{const i=t[A.platform_product_identifier];if(i===void 0)return null;const n=qxA(i,e);return n===null?null:{identifier:A.identifier,rcBillingProduct:n,webBillingProduct:n,packageType:jxA(A.identifier)}},PxA=(e,A,t,i)=>{const n={offeringIdentifier:A.identifier,targetingContext:e&&i?{ruleId:i.rule_id,revision:i.revision}:null,placementIdentifier:null},g=A.packages.map(s=>OxA(n,s,t)).filter(JxA),o={};for(const s of g)s!=null&&(o[s.identifier]=s);return g.length==0?null:{identifier:A.identifier,serverDescription:A.description,metadata:A.metadata,packagesById:o,availablePackages:g,lifetime:o.$rc_lifetime??null,annual:o.$rc_annual??null,sixMonth:o.$rc_six_month??null,threeMonth:o.$rc_three_month??null,twoMonth:o.$rc_two_month??null,monthly:o.$rc_monthly??null,weekly:o.$rc_weekly??null,paywall_components:A.paywall_components?A.paywall_components:null}};function jxA(e){switch(e){case"$rc_lifetime":return"$rc_lifetime";case"$rc_annual":return"$rc_annual";case"$rc_six_month":return"$rc_six_month";case"$rc_three_month":return"$rc_three_month";case"$rc_two_month":return"$rc_two_month";case"$rc_monthly":return"$rc_monthly";case"$rc_weekly":return"$rc_weekly";default:return e.startsWith("$rc_")?"unknown":"custom"}}var zxA=NB('<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4.94 5.72656L8 8.7799L11.06 5.72656L12 6.66656L8 10.6666L4 6.66656L4.94 5.72656Z" class="arrow-fill svelte-1qexsu3" fill-opacity="0.7"></path></svg>');const ZxA={hash:"svelte-1qexsu3",code:".arrow.svelte-1qexsu3 {transition:transform 0.3s ease;}.arrow-fill.svelte-1qexsu3 {fill:var(--rc-color-grey-text-dark);}.arrow.left.svelte-1qexsu3 {transform:rotate(90deg);}.arrow.up.svelte-1qexsu3 {transform:rotate(180deg);}.arrow.right.svelte-1qexsu3 {transform:rotate(-90deg);}.arrow.down.svelte-1qexsu3 {transform:rotate(0deg);}"};function Sb(e,A){hi(e,ZxA);let t=ri(A,"direction",8);var i=zxA();xt(()=>gFA(i,`arrow ${t()??""} svelte-1qexsu3`)),Ne(e,i)}var WxA=NB('<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="arrow"><path d="M15.41 7.41L14 6L8 12L14 18L15.41 16.59L10.83 12L15.41 7.41Z" class="arrow-fill svelte-r0zny8" fill-opacity="0.7"></path></svg>');const VxA={hash:"svelte-r0zny8",code:".arrow-fill.svelte-r0zny8 {fill:var(--rc-color-grey-text-dark);}"};function XxA(e){hi(e,VxA);var A=WxA();Ne(e,A)}const $xA=`<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"
     xmlns="http://www.w3.org/2000/svg">
    <g opacity="0.5" clip-path="url(#clip0_344_3390)">
        <path d="M7 18C5.9 18 5.01 18.9 5.01 20C5.01 21.1 5.9 22 7 22C8.1 22 9 21.1 9 20C9 18.9 8.1 18 7 18ZM1 2V4H3L6.6 11.59L5.25 14.04C5.09 14.32 5 14.65 5 15C5 16.1 5.9 17 7 17H19V15H7.42C7.28 15 7.17 14.89 7.17 14.75L7.2 14.63L8.1 13H15.55C16.3 13 16.96 12.59 17.3 11.97L20.88 5.48C20.96 5.34 21 5.17 21 5C21 4.45 20.55 4 20 4H5.21L4.27 2H1ZM17 18C15.9 18 15.01 18.9 15.01 20C15.01 21.1 15.9 22 17 22C18.1 22 19 21.1 19 20C19 18.9 18.1 18 17 18Z"
              fill="currentColor"/>
    </g>
    <defs>
        <clipPath id="clip0_344_3390">
            <rect width="24" height="24" fill="currentColor"/>
        </clipPath>
    </defs>
</svg>
`;var ATA=Nt('<div style="color:var(--rc-color-gray-text-dark);"><!></div>');function eTA(e){var A=ATA(),t=Ve(A);bd(t,()=>$xA),Ne(e,A)}const tTA=`<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"
     xmlns="http://www.w3.org/2000/svg">
    <path d="M18 8H17V6C17 3.24 14.76 1 12 1C9.24 1 7 3.24 7 6V8H6C4.9 8 4 8.9 4 10V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V10C20 8.9 19.1 8 18 8ZM12 17C10.9 17 10 16.1 10 15C10 13.9 10.9 13 12 13C13.1 13 14 13.9 14 15C14 16.1 13.1 17 12 17ZM15.1 8H8.9V6C8.9 4.29 10.29 2.9 12 2.9C13.71 2.9 15.1 4.29 15.1 6V8Z"
          fill="currentColor"/>
</svg>
`;var iTA=Nt('<div style="color:var(--rc-color-accent);" class="rcb-ui-asset-icon svelte-wgufvv"><!></div>');const nTA={hash:"svelte-wgufvv",code:"div.svelte-wgufvv {height:24px;width:24px;}"};function gTA(e){hi(e,nTA);var A=iTA(),t=Ve(A);bd(t,()=>tTA),Ne(e,A)}const oTA=`<svg viewBox="0 0 124 124" fill="var(--rc-color-grey-text-dark)" xmlns="http://www.w3.org/2000/svg">
    <circle cx="62" cy="62" r="62" fill="var(--rc-color-grey-text-dark)" opacity="0.2"/>
    <rect x="44.1116" y="56" width="27.5" height="11" transform="rotate(45 44.1116 56)" fill="var(--rc-color-grey-text-dark)"/>
    <rect x="79.1133" y="44.334" width="11" height="44" transform="rotate(45 79.1133 44.334)" fill="var(--rc-color-grey-text-dark)"/>
</svg>
`;var sTA=Nt('<div style="color:var(--rc-color-primary)"><!></div>');function IBA(e){var A=sTA(),t=Ve(A);bd(t,()=>oTA),Ne(e,A)}var aTA=NB('<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12L19 6.41Z" class="arrow-fill svelte-1jpfelf" fill-opacity="0.7"></path></svg>');const rTA={hash:"svelte-1jpfelf",code:".arrow-fill.svelte-1jpfelf {fill:var(--arrow-fill-color, var(--rc-color-grey-text-dark));}"};function ITA(e){hi(e,rTA);var A=aTA();Ne(e,A)}const CTA={cart:eTA,error:UlA,lock:gTA,success:IBA,back:XxA,info:sBA,close:ITA,"chevron-left":Sb,"chevron-right":Sb,"chevron-up":Sb,"chevron-down":Sb};function rN(e,A){Ri(A,!0);const t=CTA[A.name];let i=sn(pi({}));if(A.name.startsWith("chevron")){const n=A.name.split("-")[1];Kt(i,pi({direction:n}))}t(e,XE(()=>MA(i))),Gi()}var cTA=Nt('<span class="rc-sandbox-only-error svelte-1d8gf9n"><!></span> <br> <br>',1),lTA=Nt('<!> <a class="svelte-1d8gf9n"> </a>.',1),BTA=Nt("<!> <!>",1);const ETA={hash:"svelte-1d8gf9n",code:"a.svelte-1d8gf9n {color:var(--rc-color-grey-text-dark);}.rc-sandbox-only-error.svelte-1d8gf9n {font-weight:bold;}"};function QTA(e,A){Ri(A,!0),hi(e,ETA);const t=dI(),i=()=>uI(g,"$translator",t),n=Bt(()=>A.lastError??new Fg(dg.UnknownError,"Unknown error without state set.")),g=nr(iC),o=Bt(()=>MA(n).errorCode===dg.StripeTaxNotActive||MA(n).errorCode===dg.StripeInvalidTaxOriginAddress||MA(n).errorCode===dg.StripeMissingRequiredPermission);ac(()=>{$i.errorLog(`Displayed error: ${dg[MA(n).errorCode]}. Message: ${MA(n).message??"None"}. Underlying error: ${MA(n).underlyingErrorMessage??"None"}`)});function s(){return MA(n).errorCode===dg.AlreadyPurchasedError?i().translate(oi.ErrorPageCloseButtonTitle,{appName:A.appName??"App"}):MA(o)?i().translate(oi.ErrorButtonClose):i().translate(oi.ErrorButtonTryAgain)}function a(){switch(MA(n).errorCode){case dg.AlreadyPurchasedError:return A.productDetails.productType===_p.Subscription?i().translate(oi.ErrorPageErrorTitleAlreadySubscribed,{productTitle:A.productDetails.title}):i().translate(oi.ErrorPageErrorTitleAlreadyPurchased,{productTitle:A.productDetails.title});case dg.StripeTaxNotActive:return i().translate(oi.ErrorPageErrorTitleStripeTaxNotActive);case dg.StripeInvalidTaxOriginAddress:return i().translate(oi.ErrorPageErrorTitleStripeInvalidTaxOriginAddress);case dg.StripeMissingRequiredPermission:return i().translate(oi.ErrorPageErrorTitleStripeMissingRequiredPermission);default:return i().translate(oi.ErrorPageErrorTitleOtherErrors)}}function r(){const Q=MA(n).getErrorCode();switch(MA(n).errorCode){case dg.ErrorSettingUpPurchase:return i().translate(oi.ErrorPageErrorMessageErrorSettingUpPurchase,{errorCode:Q});case dg.ErrorChargingPayment:return i().translate(oi.ErrorPageErrorMessageErrorChargingPayment,{errorCode:Q});case dg.AlreadyPurchasedError:return A.productDetails.productType===_p.Subscription?i().translate(oi.ErrorPageErrorMessageAlreadySubscribed,{errorCode:Q}):i().translate(oi.ErrorPageErrorMessageAlreadyPurchased,{errorCode:Q});case dg.StripeTaxNotActive:return i().translate(oi.ErrorPageErrorMessageStripeTaxNotActive,{errorCode:Q});case dg.StripeInvalidTaxOriginAddress:return i().translate(oi.ErrorPageErrorMessageStripeInvalidTaxOriginAddress,{errorCode:Q});case dg.StripeMissingRequiredPermission:return i().translate(oi.ErrorPageErrorMessageStripeMissingRequiredPermission,{errorCode:Q});case dg.NetworkError:return i().translate(oi.ErrorPageErrorMessageNetworkError,{errorCode:Q});default:return i().translate(oi.ErrorPageErrorMessageUnknownError,{errorCode:Q})}}function I(){return MA(n).errorCode===dg.AlreadyPurchasedError?oi.ErrorPageTroubleAccessing:oi.ErrorPageIfErrorPersists}function c(){return MA(n).errorCode===dg.AlreadyPurchasedError?"success":"error"}var l=Bt(a),B=Bt(s);H8(e,{get title(){return MA(l)},get onDismiss(){return A.onDismiss},type:"error",get closeButtonTitle(){return MA(B)},icon:Q=>{var h=Bt(c);rN(Q,{get name(){return MA(h)}})},message:Q=>{var h=BTA(),d=_i(h);{var p=S=>{var k=cTA(),N=_i(k),G=Ve(N);$r(G,{get key(){return oi.ErrorPageErrorMessageOnlyInSandbox}}),Ne(S,k)};ii(d,S=>{MA(o)&&S(p)})}var y=Ot(d);xt(()=>Sn(y,` ${r()??""} `));var m=Ot(y);{var D=S=>{var k=lTA(),N=_i(k),G=Bt(I);$r(N,{get key(){return MA(G)}});var M=Ot(N,2),w=Ve(M);xt(()=>{Ci(M,"href",`mailto:${A.supportEmail??""}`),Sn(w,A.supportEmail)}),Ne(S,k)};ii(m,S=>{!MA(o)&&A.supportEmail&&S(D)})}Ne(Q,h)},$$slots:{icon:!0,message:!0}}),Gi()}function uTA(e,A){Ri(A,!1);const t=dI(),i=()=>uI(g,"$translator",t);let n=ri(A,"onContinue",8);const g=nr(iC),o=nr(q8);function s(){o.trackSDKEvent({eventName:BI.CheckoutPurchaseSuccessfulDismiss,properties:{ui_element:"go_back_to_app"}}),n()()}ac(()=>{o.trackSDKEvent({eventName:BI.CheckoutPurchaseSuccessfulImpression})}),lc();var a=mm(()=>i().translate(oi.SuccessPagePurchaseSuccessful)),r=mm(()=>i().translate(oi.SuccessPageButtonClose));H8(e,{type:"success",get title(){return MA(a)},onDismiss:s,get closeButtonTitle(){return MA(r)},icon:I=>{IBA(I)},$$slots:{icon:!0}}),Gi()}function dTA(e){ZlA(e)}var hTA=Nt('<div class="rcb-pricing-dropdown svelte-fgrbnh"><div class="rcb-pricing-dropdown-header svelte-fgrbnh" tabindex="0" role="button"><!> <span class="rcb-pricing-dropdown-toggle svelte-fgrbnh"><!></span></div> <div class="rcb-pricing-dropdown-content svelte-fgrbnh"><div class="rcb-pricing-dropdown-content-inner svelte-fgrbnh"><!></div></div></div>');const pTA={hash:"svelte-fgrbnh",code:`.rcb-pricing-dropdown.svelte-fgrbnh {width:100%;overflow:hidden;display:flex;flex-direction:column;}.rcb-pricing-dropdown-header.svelte-fgrbnh {padding-top:var(--rc-spacing-gapSmall-mobile);padding-bottom:var(--rc-spacing-gapSmall-mobile);padding-left:var(--rc-spacing-gapLarge-mobile);padding-right:var(--rc-spacing-gapMedium-mobile);color:var(--rc-color-grey-text-light);border-radius:var(--rc-shape-input-button-border-radius);cursor:pointer;display:inline-flex;align-items:center;background-color:var(--rc-color-grey-ui-light);width:fit-content;user-select:none;}.rcb-pricing-dropdown-toggle.svelte-fgrbnh {display:flex;align-items:center;margin-left:var(--rc-spacing-gapSmall-mobile);}.rcb-pricing-dropdown-content.svelte-fgrbnh {display:flex;flex-direction:column;overflow:hidden;}

  @container layout-query-container (width < 768px) {.rcb-pricing-dropdown-content.svelte-fgrbnh {max-height:1000px; /* Set a large max-height for animation */transition:max-height 0.2s ease-in-out;}.rcb-pricing-dropdown-content.collapsed.svelte-fgrbnh {max-height:0;}.rcb-pricing-dropdown-content-inner.svelte-fgrbnh {padding-top:var(--rc-spacing-gapMedium-mobile);}
  }

  @container layout-query-container (width >= 768px) {.rcb-pricing-dropdown-header.svelte-fgrbnh {display:none;}
  }`};function fTA(e,A){Ri(A,!1),hi(e,pTA);const t=dI(),i=()=>uI(o,"$translator",t);let n=ri(A,"isExpanded",12,!0),g=ri(A,"children",8);const o=nr(iC);function s(){n(!n())}lc();var a=hTA(),r=Ve(a),I=Ve(r);Zn(I,{size:"label-default",children:(y,m)=>{var D=xn(),S=_i(D);{var k=G=>{var M=Cg();xt(()=>Sn(M,i().translate(oi.PricingDropdownHideDetails))),Ne(G,M)},N=G=>{var M=Cg();xt(()=>Sn(M,i().translate(oi.PricingDropdownShowDetails))),Ne(G,M)};ii(S,G=>{n()?G(k):G(N,!1)})}Ne(y,D)},$$slots:{default:!0}});var c=Ot(I,2),l=Ve(c);{var B=y=>{rN(y,{name:"chevron-up"})},Q=y=>{rN(y,{name:"chevron-down"})};ii(l,y=>{n()?y(B):y(Q,!1)})}var h=Ot(r,2),d=Ve(h),p=Ve(d);is(p,()=>g()??cg),xt(()=>{Ci(r,"aria-expanded",n()),LE(h,"collapsed",!n())}),iB("click",r,s),iB("keydown",r,y=>y.key==="Enter"||y.key===" "?s():null),Ne(e,a),Gi()}var yTA=Nt('<div class="rcb-pricing-table-value-loading svelte-erv89n"><!></div>');const DTA={hash:"svelte-erv89n",code:`.rcb-pricing-table-value-loading.svelte-erv89n {color:transparent;
    animation: svelte-erv89n-rcb-pricing-table-value-loading 1.5s ease-in-out 0s infinite
      normal none running;cursor:progress;background-color:var(--rc-color-grey-text-dark);user-select:none;border-radius:var(--rc-shape-input-border-radius);}

  @keyframes svelte-erv89n-rcb-pricing-table-value-loading {
    0%,
    100% {
      opacity: 0.5;
    }
    50% {
      opacity: 0.3;
    }
  }`};function mTA(e,A){Ri(A,!1),hi(e,DTA);let t=ri(A,"children",8);lc();var i=yTA(),n=Ve(i);is(n,()=>t()??cg),Ne(e,i),Gi()}var STA=Nt('<div class="rcb-pricing-table-row svelte-i12130" data-testid="tax-loading-skeleton"><div class="rcb-pricing-table-header svelte-i12130"><!></div> <div class="rcb-pricing-table-value svelte-i12130"><!></div></div>'),wTA=Nt('<div class="rcb-pricing-table-row svelte-i12130"><div class="rcb-pricing-table-header svelte-i12130"> </div> <div class="rcb-pricing-table-value svelte-i12130"><!></div></div>'),kTA=Nt('<div class="rcb-pricing-table-row svelte-i12130"><div class="rcb-pricing-table-header svelte-i12130"><!></div> <div class="rcb-pricing-table-value svelte-i12130"><!></div></div>'),MTA=Nt('<div class="rcb-pricing-table-row svelte-i12130"><div class="rcb-pricing-table-header svelte-i12130"><!></div> <div class="rcb-pricing-table-value svelte-i12130"><!></div></div> <!> <div class="rcb-pricing-table-separator svelte-i12130"></div>',1),NTA=Nt('<div class="rcb-pricing-table-row svelte-i12130"><div class="rcb-pricing-table-header svelte-i12130"><!></div> <div class="rcb-pricing-table-value svelte-i12130"><!></div></div>'),RTA=Nt('<div class="rcb-pricing-table svelte-i12130"><!> <!> <div class="rcb-pricing-table-row rcb-header svelte-i12130"><div class="rcb-pricing-table-header svelte-i12130"><!></div> <div class="rcb-pricing-table-value svelte-i12130"><!></div></div></div>');const GTA={hash:"svelte-i12130",code:`.rcb-pricing-table.svelte-i12130 {display:flex;flex-direction:column;gap:var(--rc-spacing-gapSmall-mobile);}.rcb-pricing-table-row.svelte-i12130 {display:flex;flex-direction:row;align-items:center;justify-content:space-between;}.rcb-pricing-table-separator.svelte-i12130 {height:1px;background-color:var(--rc-color-grey-ui-dark);}.rcb-pricing-table-row.svelte-i12130 > .rcb-pricing-table-header:where(.svelte-i12130) {color:var(--rc-color-grey-text-light);}.rcb-pricing-table-row.svelte-i12130 > .rcb-pricing-table-value:where(.svelte-i12130) {color:var(--rc-color-grey-text-dark);}.rcb-pricing-table-row.svelte-i12130:last-child > .rcb-pricing-table-header:where(.svelte-i12130),
  .rcb-pricing-table-row.svelte-i12130:last-child > .rcb-pricing-table-value:where(.svelte-i12130) {color:var(--rc-color-grey-text-dark);}

  @container layout-query-container (width >= 768px) {.rcb-pricing-table-separator.svelte-i12130 {display:none;}.rcb-pricing-table.svelte-i12130 {gap:var(--rc-spacing-gapSmall-desktop);}.rcb-pricing-table-row.svelte-i12130 > .rcb-pricing-table-header:where(.svelte-i12130),
    .rcb-pricing-table-row.svelte-i12130 > .rcb-pricing-table-value:where(.svelte-i12130) {color:var(--rc-color-grey-text-light);}
  }`};function bTA(e,A){var t;Ri(A,!0),hi(e,GTA);const i=dI(),n=()=>uI(s,"$translator",i),g=B=>{var Q=RTA(),h=Ve(Q);{var d=G=>{var M=MTA(),w=_i(M),b=Ve(w),_=Ve(b);Zn(_,{size:"body-small",children:(x,T)=>{var z=Cg();xt(()=>Sn(z,n().translate(oi.PricingTotalExcludingTax))),Ne(x,z)},$$slots:{default:!0}});var K=Ot(b,2),J=Ve(K);Zn(J,{size:"body-small",children:(x,T)=>{var z=Cg();xt(()=>Sn(z,n().formatPrice(A.priceBreakdown.totalExcludingTaxInMicros,A.priceBreakdown.currency))),Ne(x,z)},$$slots:{default:!0}});var q=Ot(w,2);{var v=x=>{var T=STA(),z=Ve(T),Z=Ve(z);Zn(Z,{size:"body-small",children:(sA,pA)=>{var gA=Cg();xt(()=>Sn(gA,n().translate(oi.PricingTableTax))),Ne(sA,gA)},$$slots:{default:!0}});var eA=Ot(z,2),aA=Ve(eA);Zn(aA,{size:"body-small",children:(sA,pA)=>{mTA(sA,{children:(gA,yA)=>{var fA=Cg();xt(()=>Sn(fA,n().formatPrice(1234e4,A.priceBreakdown.currency))),Ne(gA,fA)},$$slots:{default:!0}})},$$slots:{default:!0}}),Ne(x,T)},U=x=>{var T=xn(),z=_i(T);{var Z=aA=>{var sA=wTA(),pA=Ve(sA),gA=Ve(pA);xt(()=>Sn(gA,n().translate(oi.PricingTableTax)));var yA=Ot(pA,2),fA=Ve(yA);Zn(fA,{size:"body-small",children:(RA,qA)=>{var W=Cg();xt(()=>Sn(W,n().translate(oi.PricingTableEnterBillingAddressToCalculate))),Ne(RA,W)},$$slots:{default:!0}}),Ne(aA,sA)},eA=aA=>{var sA=xn(),pA=_i(sA);{var gA=yA=>{var fA=xn(),RA=_i(fA);kS(RA,17,()=>A.priceBreakdown.taxBreakdown,wS,(qA,W)=>{var $=kTA(),L=Ve($),H=Ve(L);Zn(H,{size:"body-small",children:(iA,oA)=>{var IA=Cg();xt(()=>Sn(IA,MA(W).display_name)),Ne(iA,IA)},$$slots:{default:!0}});var P=Ot(L,2),tA=Ve(P);Zn(tA,{size:"body-small",children:(iA,oA)=>{var IA=Cg();xt(()=>Sn(IA,n().formatPrice(MA(W).tax_amount_in_micros,A.priceBreakdown.currency))),Ne(iA,IA)},$$slots:{default:!0}}),Ne(qA,$)}),Ne(yA,fA)};ii(pA,yA=>{A.priceBreakdown.taxBreakdown!==null&&yA(gA)},!0)}Ne(aA,sA)};ii(z,aA=>{A.priceBreakdown.taxCalculationStatus==="pending"?aA(Z):aA(eA,!1)},!0)}Ne(x,T)};ii(q,x=>{A.priceBreakdown.taxCalculationStatus==="loading"?x(v):x(U,!1)})}Ne(G,M)};ii(h,G=>{MA(a)&&G(d)})}var p=Ot(h,2);{var y=G=>{var M=NTA(),w=Ve(M),b=Ve(w);Zn(b,{size:"body-small",children:(J,q)=>{var v=Cg();xt(()=>Sn(v,n().translate(oi.PricingTableTrialEnds,{formattedTrialEndDate:n().translateDate(MA(o),{dateStyle:"medium"})}))),Ne(J,v)},$$slots:{default:!0}});var _=Ot(w,2),K=Ve(_);Zn(K,{size:"body-small",children:(J,q)=>{var v=Cg();xt(()=>Sn(v,n().formatPrice(A.priceBreakdown.totalAmountInMicros,A.priceBreakdown.currency))),Ne(J,v)},$$slots:{default:!0}}),Ne(G,M)};ii(p,G=>{MA(o)&&G(y)})}var m=Ot(p,2),D=Ve(m),S=Ve(D);Zn(S,{size:"body-small",children:(G,M)=>{var w=Cg();xt(()=>Sn(w,n().translate(oi.PricingTableTotalDueToday))),Ne(G,w)},$$slots:{default:!0}});var k=Ot(D,2),N=Ve(k);Zn(N,{size:"body-small",children:(G,M)=>{var w=xn(),b=_i(w);{var _=J=>{var q=Cg();xt(()=>Sn(q,n().formatPrice(0,A.priceBreakdown.currency))),Ne(J,q)},K=J=>{var q=Cg();xt(()=>Sn(q,n().formatPrice(A.priceBreakdown.totalAmountInMicros,A.priceBreakdown.currency))),Ne(J,q)};ii(b,J=>{MA(o)?J(_):J(K,!1)})}Ne(G,w)},$$slots:{default:!0}}),Ne(B,Q)};let o=sn(null);(t=A.trialPhase)!=null&&t.period&&Kt(o,pi(u1(new Date,A.trialPhase.period,!0)));const s=nr(iC),a=Bt(()=>A.priceBreakdown.taxCalculationStatus!=="unavailable"&&A.priceBreakdown.taxCalculationStatus!=="disabled"&&A.priceBreakdown.taxBreakdown&&A.priceBreakdown.taxBreakdown.length>0);var r=xn(),I=_i(r);{var c=B=>{fTA(B,{children:(Q,h)=>{g(Q)},$$slots:{default:!0}})},l=B=>{g(B)};ii(I,B=>{MA(a)?B(c):B(l,!1)})}Ne(e,r),Gi()}var UTA=Nt('<div class="rcb-subscribe-to svelte-4fnm8t"><!></div>'),vTA=Nt('<span class="rcb-product-description svelte-4fnm8t"><!></span>'),KTA=Nt('<div class="rcb-pricing-info-header svelte-4fnm8t"><!> <div class="rcb-product-title svelte-4fnm8t"><!></div> <!></div>');const FTA={hash:"svelte-4fnm8t",code:`.rcb-pricing-info-header.svelte-4fnm8t {display:flex;flex-direction:column;gap:var(--rc-spacing-gapMedium-mobile);}.rcb-product-title.svelte-4fnm8t {color:var(--rc-color-grey-text-dark);}.rcb-product-description.svelte-4fnm8t {color:var(--rc-color-grey-text-light);}.rcb-subscribe-to.svelte-4fnm8t {display:none;}

  @container layout-query-container (width >= 768px) {.rcb-subscribe-to.svelte-4fnm8t {display:block;}.rcb-pricing-info-header.svelte-4fnm8t {display:flex;flex-direction:column;gap:var(--rc-spacing-gapMedium-desktop);}
  }`};function _TA(e,A){Ri(A,!1),hi(e,FTA);let t=ri(A,"productDetails",8),i=ri(A,"showProductDescription",8);const n=t().productType===_p.Subscription;lc();var g=KTA(),o=Ve(g);{var s=l=>{var B=UTA(),Q=Ve(B);Zn(Q,{size:"body-base",children:(h,d)=>{var p=mm(()=>({productTitle:t().title}));$r(h,{get key(){return oi.ProductInfoSubscribeTo},get variables(){return MA(p)}})},$$slots:{default:!0}}),Ne(l,B)};ii(o,l=>{n&&l(s)})}var a=Ot(o,2),r=Ve(a);Zn(r,{size:"heading-lg",branded:!0,children:(l,B)=>{var Q=mm(()=>({productTitle:t().title}));$r(l,{get key(){return oi.ProductInfoProductTitle},get variables(){return MA(Q)}})},$$slots:{default:!0}});var I=Ot(a,2);{var c=l=>{var B=vTA(),Q=Ve(B);Zn(Q,{size:"body-small",children:(h,d)=>{var p=mm(()=>({productDescription:t().description}));$r(h,{get key(){return oi.ProductInfoProductDescription},get variables(){return MA(p)}})},$$slots:{default:!0}}),Ne(l,B)};ii(I,l=>{i()&&t().description&&l(c)})}Ne(e,g),Gi()}var JTA=Nt("<div><!></div>"),LTA=Nt("<div><!> <!></div>"),xTA=Nt('<div class="rcb-product-price-container svelte-509gz3"><!> <!> <div><!> <!> <!></div></div>');const TTA={hash:"svelte-509gz3",code:".rcb-product-price-container.svelte-509gz3 {display:flex;flex-direction:column;justify-content:space-between;gap:var(--rc-spacing-gapMedium-mobile);color:var(--rc-color-grey-text-dark);}"};function qTA(e,A){Ri(A,!0),hi(e,TTA);const t=dI(),i=()=>uI(n,"$translator",t),n=nr(iC),g=Bt(()=>{var w;return(w=A.introPricePhase)!=null&&w.period&&i().translatePeriod(A.introPricePhase.period.number*A.introPricePhase.cycleCount,A.introPricePhase.period.unit)||""}),o=Bt(()=>"heading-lg"),s=Bt(()=>{var w;return(w=A.trialPhase)!=null&&w.periodDuration?"heading-md":"heading-lg"}),a=Bt(()=>{var w,b;return(w=A.trialPhase)!=null&&w.periodDuration||(b=A.introPricePhase)!=null&&b.periodDuration?"heading-md":"heading-lg"}),r=Bt(()=>{var w;return(w=A.trialPhase)==null?void 0:w.periodDuration}),I=Bt(()=>{var w;return(w=A.introPricePhase)==null?void 0:w.periodDuration}),c=Bt(()=>{var w;return((w=A.introPricePhase)==null?void 0:w.cycleCount)==1}),l=Bt(()=>{var w,b;return i().formatPrice(MA(I)?((b=(w=A.basePhase)==null?void 0:w.price)==null?void 0:b.amountMicros)??0:A.priceBreakdown.totalAmountInMicros,A.priceBreakdown.currency)}),B=Bt(()=>i().formatPrice(A.priceBreakdown.totalAmountInMicros,A.priceBreakdown.currency));var Q=xTA(),h=Ve(Q);{var d=w=>{var b=JTA(),_=Ve(b);Zn(_,{get size(){return MA(o)},children:(K,J)=>{var q=Bt(()=>({trialDuration:A_A(A.trialPhase.periodDuration,i())}));$r(K,{get key(){return oi.ProductInfoFreeTrialDuration},get variables(){return MA(q)}})},$$slots:{default:!0}}),Ne(w,b)};ii(h,w=>{var b;(b=A.trialPhase)!=null&&b.periodDuration&&w(d)})}var p=Ot(h,2);{var y=w=>{var b=LTA(),_=Ve(b);Zn(_,{get size(){return MA(s)},children:(v,U)=>{var x=Bt(()=>MA(r)?oi.ProductInfoIntroPricePhaseAfterTrial:oi.ProductInfoIntroPricePhase),T=Bt(()=>({introPriceDuration:MA(g),introPrice:MA(B)}));$r(v,{get key(){return MA(x)},get variables(){return MA(T)}})},$$slots:{default:!0}});var K=Ot(_,2);{var J=v=>{Zn(v,{size:"body-small",children:(U,x)=>{$r(U,{get key(){return oi.ProductInfoIntroPricePhasePaidOnce}})},$$slots:{default:!0}})},q=v=>{var U=xn(),x=_i(U);{var T=z=>{Zn(z,{size:"body-small",children:(Z,eA)=>{var aA=Cg();xt(()=>Sn(aA,i().translatePeriodFrequency(A.introPricePhase.period.number,A.introPricePhase.period.unit,{useMultipleWords:!0}))),Ne(Z,aA)},$$slots:{default:!0}})};ii(x,z=>{A.introPricePhase.period&&z(T)},!0)}Ne(v,U)};ii(K,v=>{MA(c)?v(J):v(q,!1)})}Ne(w,b)};ii(p,w=>{var b;(b=A.introPricePhase)!=null&&b.periodDuration&&w(y)})}var m=Ot(p,2),D=Ve(m);Zn(D,{get size(){return MA(a)},children:(w,b)=>{var _=Cg();xt(()=>Sn(_,MA(l))),Ne(w,_)},$$slots:{default:!0}});var S=Ot(D,2);{var k=w=>{Zn(w,{size:"body-small",children:(b,_)=>{var K=Cg();xt(()=>Sn(K,i().translatePeriodFrequency(A.basePhase.period.number,A.basePhase.period.unit,{useMultipleWords:!0}))),Ne(b,K)},$$slots:{default:!0}})};ii(S,w=>{var b;(b=A.basePhase)!=null&&b.period&&w(k)})}var N=Ot(S,2);{var G=w=>{Zn(w,{size:"body-small",children:(b,_)=>{$r(b,{get key(){return oi.ProductInfoAfter}})},$$slots:{default:!0}})},M=w=>{var b=xn(),_=_i(b);{var K=J=>{Zn(J,{size:"body-small",children:(q,v)=>{$r(q,{get key(){return oi.ProductInfoAfterTrial}})},$$slots:{default:!0}})};ii(_,J=>{MA(r)&&J(K)},!0)}Ne(w,b)};ii(N,w=>{MA(I)?w(G):w(M,!1)})}Ne(e,Q),Gi()}var YTA=Nt('<div class="rcb-pricing-info svelte-18guro7"><div class="rcb-pricing-info-header svelte-18guro7"><!> <!></div> <!></div>');const HTA={hash:"svelte-18guro7",code:`.rcb-pricing-info.svelte-18guro7 {display:flex;flex-direction:column;user-select:none;gap:var(--rc-spacing-gapXXLarge-mobile);}.rcb-pricing-info-header.svelte-18guro7 {display:flex;flex-direction:column;gap:var(--rc-spacing-gapLarge-mobile);}

  @container layout-query-container (width >= 768px) {.rcb-pricing-info.svelte-18guro7 {gap:var(--rc-spacing-gapXXXLarge-desktop);}.rcb-pricing-info-header.svelte-18guro7 {gap:var(--rc-spacing-gapLarge-desktop);}
  }`};function OTA(e,A){hi(e,HTA);let t=ri(A,"productDetails",8),i=ri(A,"purchaseOption",8),n=ri(A,"showProductDescription",8),g=ri(A,"priceBreakdown",8);const o=i(),s=o==null?void 0:o.base,a=o==null?void 0:o.trial,r=o==null?void 0:o.introPrice;var I=YTA(),c=Ve(I),l=Ve(c);_TA(l,{get productDetails(){return t()},get showProductDescription(){return n()}});var B=Ot(l,2);qTA(B,{get priceBreakdown(){return g()},basePhase:s,trialPhase:a,introPricePhase:r});var Q=Ot(c,2);bTA(Q,{get priceBreakdown(){return g()},trialPhase:a}),Ne(e,I)}const Bk=e=>`https://da08ctfrofx1b.cloudfront.net/${e}`;var PTA=Nt('<div class="rcb-ui-container svelte-1h6xr8z"><!></div>');const jTA={hash:"svelte-1h6xr8z",code:`.rcb-ui-container.svelte-1h6xr8z {display:flex;flex-direction:column;inset:0;color-scheme:none;line-height:1.5em;font-family:-apple-system,
      BlinkMacSystemFont,
      avenir next,
      avenir,
      segoe ui,
      helvetica neue,
      helvetica,
      Cantarell,
      Ubuntu,
      roboto,
      noto,
      arial,
      sans-serif;overflow-x:hidden;overflow-y:auto;}.rcb-ui-container.fullscreen.svelte-1h6xr8z {position:fixed;top:0;left:0;right:0;bottom:0;overscroll-behavior:none;z-index:1000001;}.rcb-ui-container.inside.svelte-1h6xr8z {position:relative;width:100%;z-index:unset;height:100%;top:0;left:0;}`};function zTA(e,A){Ri(A,!0),hi(e,jTA);const t=ri(A,"brandingAppearance",3,void 0),i=ri(A,"brandFontConfig",3,void 0),n=ri(A,"isInElement",3,!1),g=Bt(()=>new aN(t()).getTextStyleVars(i())),o=Bt(()=>new aN(t()).spacingStyleVars),s=Bt(()=>[MA(g),MA(o)].join("; ")),a=Bt(()=>{var l;return(l=i())!=null&&l.font_url?Bk(i().font_url):null}),r=async l=>{try{const B=new FontFace(XlA,`url(${l})`);await B.load(),document.fonts.add(B)}catch(B){console.error("Failed to set brand font:",B)}};SS(()=>{MA(a)&&r(MA(a))});var I=PTA(),c=Ve(I);is(c,()=>A.children??cg),xt(()=>{Ci(I,"style",MA(s)),LE(I,"fullscreen",!n()),LE(I,"inside",n())}),Ne(e,I),Gi()}var ZTA=Nt('<div id="layout-query-container" class="svelte-1x4ow5d"><div class="rcb-ui-layout svelte-1x4ow5d"><!></div></div>');const WTA={hash:"svelte-1x4ow5d",code:`#layout-query-container.svelte-1x4ow5d {width:100%;height:100%;container-type:size;container-name:layout-query-container;overflow-y:auto;overscroll-behavior:none;}.rcb-ui-layout.svelte-1x4ow5d {width:100%;min-height:100%;display:flex;box-sizing:border-box;flex-direction:column;overflow-y:auto;overscroll-behavior:none;}

  @container layout-query-container (width < 768px) {.rcb-ui-layout.svelte-1x4ow5d {flex-grow:1;}
  }

  @container layout-query-container (width >= 768px) {.rcb-ui-layout.svelte-1x4ow5d {flex-direction:row;}
  }`};function VTA(e,A){Ri(A,!1),hi(e,WTA);let t=ri(A,"style",8,""),i=ri(A,"children",8);lc();var n=ZTA(),g=Ve(n),o=Ve(g);is(o,()=>i()??cg),xt(()=>Ci(g,"style",t())),Ne(e,n),Gi()}const XTA=e=>e;function $TA(e){const A=e-1;return A*A*A+1}function w7(e){const A=typeof e=="string"&&e.match(/^\s*(-?[\d.]+)([^\s]*)\s*$/);return A?[parseFloat(A[1]),A[2]||"px"]:[e,"px"]}function AqA(e,{delay:A=0,duration:t=400,easing:i=XTA}={}){const n=+getComputedStyle(e).opacity;return{delay:A,duration:t,easing:i,css:g=>`opacity: ${g*n}`}}function eqA(e,{delay:A=0,duration:t=400,easing:i=$TA,x:n=0,y:g=0,opacity:o=0}={}){const s=getComputedStyle(e),a=+s.opacity,r=s.transform==="none"?"":s.transform,I=a*(1-o),[c,l]=w7(n),[B,Q]=w7(g);return{delay:A,duration:t,easing:i,css:(h,d)=>`
			transform: ${r} translate(${(1-h)*c}${l}, ${(1-h)*B}${Q});
			opacity: ${a-I*d}`}}var tqA=Nt('<div><div class="layout-wrapper svelte-1w6qvx7"><div><!></div></div></div>');const iqA={hash:"svelte-1w6qvx7",code:`.layout-wrapper-outer.svelte-1w6qvx7 {flex:1;display:flex;background-color:var(--rc-color-background);}.layout-wrapper-outer.rcb-navbar.svelte-1w6qvx7 {justify-content:flex-end;}.layout-wrapper.svelte-1w6qvx7 {width:100%;}.layout-content.svelte-1w6qvx7 {box-sizing:border-box;background-color:var(--rc-color-background);color:var(--rc-color-grey-text-dark);display:flex;flex-direction:column;}.layout-content.rcb-navbar.svelte-1w6qvx7 {display:flex;flex-direction:column;gap:var(--rc-spacing-gapXLarge-mobile);}

  @container layout-query-container (width < 768px) {.layout-wrapper.svelte-1w6qvx7 {width:100%;min-width:300px;display:flex;flex-grow:1;}.layout-content.svelte-1w6qvx7 {flex-grow:1;height:100%;}.layout-content.rcb-navbar.svelte-1w6qvx7 {padding-bottom:var(--rc-spacing-outerPadding-mobile);}.layout-content.rcb-main-block.svelte-1w6qvx7 {padding:var(--rc-spacing-outerPadding-mobile);}
  }

  @container layout-query-container (width >= 768px) {.layout-wrapper.svelte-1w6qvx7 {flex-basis:544px;}.layout-content.rcb-main-block.svelte-1w6qvx7 {padding-left:var(--rc-spacing-outerPadding-desktop);padding-right:var(--rc-spacing-outerPadding-desktop);}.layout-content.rcb-navbar.svelte-1w6qvx7 {gap:var(--rc-spacing-gapXXLarge-desktop);}.layout-wrapper-outer.svelte-1w6qvx7 {padding-top:var(--rc-spacing-outerPaddingTop-desktop);padding-bottom:var(--rc-spacing-outerPadding-desktop);}
  }`};function CBA(e,A){Ri(A,!0),hi(e,iqA);const t=`rcb-${A.location}`;var i=tqA();sd(i,`layout-wrapper-outer ${t??""} svelte-1w6qvx7`);var n=Ve(i),g=Ve(n);sd(g,`layout-content ${t??""} svelte-1w6qvx7`);var o=Ve(g);is(o,()=>A.children??cg),MlA(3,g,()=>AqA,()=>({duration:500,delay:50})),Ne(e,i),Gi()}var nqA=Nt('<div class="navbar-body svelte-jz90ay"><!></div>'),gqA=Nt('<div class="navbar-header svelte-jz90ay"><!></div> <!>',1),oqA=Nt('<div class="rcb-ui-navbar svelte-jz90ay"><!></div>');const sqA={hash:"svelte-jz90ay",code:`.rcb-ui-navbar.svelte-jz90ay {width:100%;max-width:none;flex-shrink:0;background-color:var(--rc-color-background);}

  @container layout-query-container (width < 768px) {.navbar-body.svelte-jz90ay {padding-left:var(--rc-spacing-outerPadding-mobile);padding-right:var(--rc-spacing-outerPadding-mobile);}
  }

  @container layout-query-container (width >= 768px) {.rcb-ui-navbar.svelte-jz90ay {width:50vw;display:flex;justify-content:flex-end;}.navbar-header.svelte-jz90ay {padding-left:var(--rc-spacing-outerPadding-desktop);padding-right:var(--rc-spacing-outerPadding-desktop);}.navbar-body.svelte-jz90ay {padding-left:var(--rc-spacing-outerPadding-desktop);padding-right:var(--rc-spacing-outerPadding-desktop);}
  }`};function aqA(e,A){Ri(A,!0),hi(e,sqA);const t=ri(A,"brandingAppearance",3,void 0),i=Bt(()=>new aN(t()).productInfoStyleVars);var n=oqA(),g=Ve(n);CBA(g,{location:"navbar",children:(o,s)=>{var a=gqA(),r=_i(a),I=Ve(r);is(I,()=>A.headerContent??cg);var c=Ot(r,2);{var l=B=>{var Q=nqA(),h=Ve(Q);is(h,()=>A.bodyContent??cg),Ne(B,Q)};ii(c,B=>{A.bodyContent&&B(l)})}Ne(o,a)},$$slots:{default:!0}}),xt(()=>Ci(n,"style",MA(i))),Ne(e,n),Gi()}var rqA=Nt('<button class="rcb-close-button svelte-nssttr" data-testid="close-button"><!></button>');const IqA={hash:"svelte-nssttr",code:".rcb-close-button.svelte-nssttr {padding:10px;border:none;cursor:pointer;background-color:transparent;border-radius:50%;color:var(--rc-color-grey-text-dark);display:inline-flex;align-items:center;justify-content:center;width:fit-content;height:fit-content;}.rcb-close-button.svelte-nssttr:active {transition:outline 0.1s ease-in-out;outline:2px solid var(--rc-color-focus);}.rcb-close-button.svelte-nssttr:hover {color:var(--rc-color-grey-text-dark);}"};function cBA(e,A){hi(e,IqA);var t=rqA(),i=Ve(t);rN(i,{name:"close"}),iB("click",t,function(n){RlA.call(this,A,n)}),Ne(e,t)}const CqA=`<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none">
    <g clip-path="url(#clip0_6333_13826)">
    <rect opacity="0.2" width="12" height="12" rx="2.25" fill="black"/>
    <path fill-rule="evenodd" clip-rule="evenodd" d="M8.53206 2.06972C9.28201 2.17252 9.88339 2.78615 9.96146 3.52824L10.2298 6.07852C10.2893 6.64453 9.87503 7.12287 9.30441 7.14692C8.73379 7.17097 8.22294 6.73163 8.16339 6.16562L8.08036 5.37641L6.00414 7.35193C5.6039 7.73275 4.94623 7.70146 4.53518 7.28205C4.12413 6.86263 4.11537 6.2139 4.51561 5.83307L6.59182 3.85756L5.79425 3.74823C5.22225 3.66982 4.79448 3.15142 4.83881 2.59036C4.88313 2.02929 5.38276 1.63802 5.95476 1.71643L8.53206 2.06972Z" fill="black"/>
    </g>
    <defs>
    <clipPath id="clip0_6333_13826">
    <rect width="12" height="12" fill="white"/>
    </clipPath>
    </defs>
    </svg>
`;var cqA=Nt('<div style="color:var(--rc-color-accent);" class="rcb-ui-asset-icon svelte-5vi85d"><!></div>');const lqA={hash:"svelte-5vi85d",code:"div.svelte-5vi85d {height:12px;width:12px;}"};function BqA(e){hi(e,lqA);var A=cqA(),t=Ve(A);bd(t,()=>CqA),Ne(e,A)}var EqA=Nt('<span class="rcb-sandbox-text svelte-18xxdea">SANDBOX</span>'),QqA=Nt('<span class="rcb-sandbox-text svelte-18xxdea">Share feedback</span>'),uqA=Nt('<a class="rcb-ui-sandbox-banner-link svelte-18xxdea" target="_blank"><!> <!></a>'),dqA=Nt('<div class="rcb-ui-sandbox-banner svelte-18xxdea"><div class="rcb-sandbox-banner-spacer svelte-18xxdea"></div> <div class="rcb-sandbox-banner-title-wrapper svelte-18xxdea"><!></div> <div class="rcb-sandbox-banner-actions-wrapper svelte-18xxdea" style="--arrow-fill-color: black"><!> <!></div></div>');const hqA={hash:"svelte-18xxdea",code:`.rcb-ui-sandbox-banner.svelte-18xxdea {position:static;background-color:var(--rc-color-warning);color:black;padding:var(--rc-spacing-gapMedium-mobile) 0;display:flex;justify-content:space-between;align-items:center;height:24px;}.rcb-sandbox-text.svelte-18xxdea {font-weight:bold;color:black;line-height:2;}.rcb-sandbox-banner-spacer.svelte-18xxdea {flex:1;}.rcb-sandbox-banner-title-wrapper.svelte-18xxdea {flex:0;text-align:center;}

  @media (max-width: 768px) {.rcb-sandbox-banner-spacer.svelte-18xxdea {flex:0;}.rcb-sandbox-banner-title-wrapper.svelte-18xxdea {padding-left:var(--rc-spacing-gapXXLarge-mobile);}
  }.rcb-sandbox-banner-actions-wrapper.svelte-18xxdea {flex:1;display:flex;justify-content:flex-end;align-items:center;}.rcb-ui-sandbox-banner-link.svelte-18xxdea {display:flex;align-items:center;gap:var(--rc-spacing-gapSmall-mobile);line-height:12px;}`};function pqA(e,A){Ri(A,!1),hi(e,hqA);let t=ri(A,"style",8,""),i=ri(A,"isInElement",8,!1),n=ri(A,"brandingInfo",8,null),g=Nc(!0);function o(){$i.debugLog("closeBanner"),Kt(g,!1)}lc();var s=xn(),a=_i(s);{var r=I=>{var c=dqA(),l=Ot(Ve(c),2),B=Ve(l);Zn(B,{size:"caption-default",children:(y,m)=>{var D=EqA();Ne(y,D)},$$slots:{default:!0}});var Q=Ot(l,2),h=Ve(Q);{var d=y=>{var m=uqA(),D=Ve(m);BqA(D);var S=Ot(D,2);Zn(S,{size:"caption-link",children:(k,N)=>{var G=QqA();Ne(k,G)},$$slots:{default:!0}}),xt(()=>Ci(m,"href",n().sandbox_configuration.checkout_feedback_form_url)),Ne(y,m)};ii(h,y=>{var m;(m=n())!=null&&m.sandbox_configuration&&y(d)})}var p=Ot(h,2);cBA(p,{$$events:{click:o}}),xt(()=>{Ci(c,"style",t()),LE(c,"isInElement",i())}),MlA(2,c,()=>eqA,()=>({y:-100,duration:300})),Ne(I,c)};ii(a,I=>{MA(g)&&I(r)})}Ne(e,s),Gi()}var fqA=Nt('<div class="rcb-ui-main svelte-nr408n"><!></div>');const yqA={hash:"svelte-nr408n",code:".rcb-ui-main.svelte-nr408n {flex:1;display:flex;background-color:var(--rc-color-background);}"};function DqA(e,A){Ri(A,!0),hi(e,yqA);const t=Bt(()=>new aN(A.brandingAppearance).formStyleVars);var i=fqA(),n=Ve(i);CBA(n,{location:"main-block",children:(g,o)=>{var s=xn(),a=_i(s);is(a,()=>A.children??cg),Ne(g,s)},$$slots:{default:!0}}),xt(()=>Ci(i,"style",MA(t))),Ne(e,i),Gi()}var mqA=Nt("<!> <!>",1),SqA=Nt("<!> <!>",1);function wqA(e,A){Ri(A,!0);const t=Bt(()=>{var g;return eBA((g=A.brandingInfo)==null?void 0:g.appearance)??""});var i=Bt(()=>{var g;return(g=A.brandingInfo)==null?void 0:g.appearance}),n=Bt(()=>{var g;return(g=A.brandingInfo)==null?void 0:g.brand_font_config});zTA(e,{get brandingAppearance(){return MA(i)},get brandFontConfig(){return MA(n)},get isInElement(){return A.isInElement},children:(g,o)=>{var s=SqA(),a=_i(s);{var r=c=>{pqA(c,{get style(){return MA(t)},get isInElement(){return A.isInElement},get brandingInfo(){return A.brandingInfo}})};ii(a,c=>{A.isSandbox&&c(r)})}var I=Ot(a,2);VTA(I,{get style(){return MA(t)},children:(c,l)=>{var B=mqA(),Q=_i(B);{var h=y=>{var m=Bt(()=>{var D;return(D=A.brandingInfo)==null?void 0:D.appearance});aqA(y,{get brandingAppearance(){return MA(m)},get headerContent(){return A.navbarHeaderContent},get bodyContent(){return A.navbarBodyContent}})};ii(Q,y=>{(A.navbarHeaderContent||A.navbarBodyContent)&&y(h)})}var d=Ot(Q,2),p=Bt(()=>{var y;return(y=A.brandingInfo)==null?void 0:y.appearance});DqA(d,{get brandingAppearance(){return MA(p)},children:(y,m)=>{var D=xn(),S=_i(D);is(S,()=>A.mainContent??cg),Ne(y,D)},$$slots:{default:!0}}),Ne(c,B)},$$slots:{default:!0}}),Ne(g,s)},$$slots:{default:!0}}),Gi()}var kqA=Nt('<source type="image/webp">'),MqA=Nt('<picture class="rcb-app-icon-picture-container svelte-el1u77"><!> <img class="rcb-app-icon svelte-el1u77" alt="App icon"></picture>'),NqA=Nt('<div class="rcb-app-icon loading svelte-el1u77"></div>');const RqA={hash:"svelte-el1u77",code:".rcb-app-icon.svelte-el1u77 {width:32px;height:32px;border-radius:12px;box-shadow:0px 1px 10px 0px rgba(0, 0, 0, 0.1);}.rcb-app-icon-picture-container.svelte-el1u77 {height:32px;}.rcb-app-icon.loading.svelte-el1u77 {background-color:gray;}"};function GqA(e,A){hi(e,RqA);var t=xn(),i=_i(t);{var n=o=>{var s=MqA(),a=Ve(s);{var r=c=>{var l=kqA();xt(()=>Ci(l,"srcset",A.srcWebp)),Ne(c,l)};ii(a,c=>{A.srcWebp&&c(r)})}var I=Ot(a,2);xt(()=>Ci(I,"src",A.src)),Ne(o,s)},g=o=>{var s=NqA();Ne(o,s)};ii(i,o=>{A.src?o(n):o(g,!1)})}Ne(e,t)}var bqA=Nt('<button class="rcb-back-button svelte-9xjbko" data-testid="close-button"><!></button>');const UqA={hash:"svelte-9xjbko",code:".rcb-back-button.svelte-9xjbko {padding:8px;border:none;cursor:pointer;background-color:transparent;border-radius:50%;color:var(--rc-color-grey-text-dark);display:inline-flex;align-items:center;justify-content:center;width:fit-content;height:fit-content;}"};function vqA(e,A){hi(e,UqA);var t=bqA(),i=Ve(t);rN(i,{name:"back"}),iB("click",t,function(n){RlA.call(this,A,n)}),Ne(e,t)}var KqA=Nt('<source type="image/webp" class="rcb-app-icon svelte-19gv4gf">'),FqA=Nt('<picture class="rcb-app-icon svelte-19gv4gf"><!> <img class="rcb-app-icon svelte-19gv4gf" alt="App icon"></picture>');const _qA={hash:"svelte-19gv4gf",code:".rcb-app-icon.svelte-19gv4gf {height:32px;}"};function JqA(e,A){hi(e,_qA);var t=FqA(),i=Ve(t);{var n=o=>{var s=KqA();xt(()=>Ci(s,"srcset",A.srcWebp)),Ne(o,s)};ii(i,o=>{A.srcWebp&&o(n)})}var g=Ot(i,2);xt(()=>Ci(g,"src",A.src)),Ne(e,t)}var LqA=Nt('<div class="rcb-back-wrapper svelte-11zapuq"><!></div>'),xqA=Nt('<div class="rcb-close-wrapper svelte-11zapuq"><!></div>'),TqA=Nt('<div class="rcb-header-wrapper svelte-11zapuq"><!> <div class="rcb-header svelte-11zapuq"><div class="rcb-title svelte-11zapuq"><!> <!></div></div> <!></div>');const qqA={hash:"svelte-11zapuq",code:`.rcb-header-wrapper.svelte-11zapuq {display:flex;position:relative;justify-content:space-between;align-items:center;}.rcb-header.svelte-11zapuq {display:flex;flex-direction:row;align-items:center;padding-top:var(--rc-spacing-gapSmall-mobile);padding-bottom:var(--rc-spacing-gapSmall-mobile);height:40px;justify-content:space-between;}.rcb-title.svelte-11zapuq {display:flex;align-items:center;position:relative;gap:var(--rc-spacing-gapMedium-mobile);}.rcb-close-wrapper.svelte-11zapuq,
  .rcb-back-wrapper.svelte-11zapuq {padding:var(--rc-spacing-gapSmall-mobile);}

  @container layout-query-container (width < 768px) {.rcb-header.svelte-11zapuq {padding-top:var(--rc-spacing-gapMedium-mobile);}.rcb-close-wrapper.svelte-11zapuq {padding-top:var(--rc-spacing-gapMedium-mobile);}.rcb-header-wrapper.svelte-11zapuq {padding-top:var(--rc-spacing-gapSmall-mobile);padding-bottom:var(--rc-spacing-gapSmall-mobile);padding-left:var(--rc-spacing-outerPadding-mobile);padding-right:var(--rc-spacing-outerPadding-mobile);}.rcb-header-wrapper.rcb-with-close-button.svelte-11zapuq {padding-right:var(--rc-spacing-gapSmall-mobile);}.rcb-back-wrapper.svelte-11zapuq {display:none;}.rcb-header-wrapper.svelte-11zapuq {padding-left:var(--rc-spacing-outerPadding-mobile);padding-right:var(--rc-spacing-outerPadding-mobile);}
  }

  @container layout-query-container (width >= 768px) {.rcb-close-wrapper.svelte-11zapuq {display:none;}.rcb-back-wrapper.svelte-11zapuq {position:absolute;left:-48px;margin-left:0;}
  }`};function YqA(e,A){Ri(A,!0),hi(e,qqA);const t=G=>G==null||G==null||G==""?null:G,i=Bt(()=>{var G;return t((G=A.brandingInfo)==null?void 0:G.app_icon)}),n=Bt(()=>{var G;return t((G=A.brandingInfo)==null?void 0:G.app_icon_webp)}),g=Bt(()=>{var G;return t((G=A.brandingInfo)==null?void 0:G.app_wordmark)}),o=Bt(()=>{var G;return t((G=A.brandingInfo)==null?void 0:G.app_wordmark_webp)}),s=Bt(()=>MA(i)?Bk(MA(i)):null),a=Bt(()=>MA(n)?Bk(MA(n)):null),r=Bt(()=>MA(g)?Bk(MA(g)):null),I=Bt(()=>MA(o)?Bk(MA(o)):null),c=()=>{A.onClose&&A.onClose()};var l=TqA(),B=Ve(l);{var Q=G=>{var M=LqA(),w=Ve(M);vqA(w,{$$events:{click:c}}),Ne(G,M)};ii(B,G=>{A.showCloseButton&&G(Q)})}var h=Ot(B,2),d=Ve(h),p=Ve(d);{var y=G=>{JqA(G,{get src(){return MA(r)},get srcWebp(){return MA(I)}})},m=G=>{var M=xn(),w=_i(M);{var b=_=>{GqA(_,{get src(){return MA(s)},get srcWebp(){return MA(a)}})};ii(w,_=>{MA(s)!==null&&MA(a)!==null&&_(b)},!0)}Ne(G,M)};ii(p,G=>{MA(r)!==null?G(y):G(m,!1)})}var D=Ot(p,2);{var S=G=>{Zn(G,{size:"body-base",children:(M,w)=>{var b=Cg();xt(()=>{var _;return Sn(b,(_=A.brandingInfo)==null?void 0:_.app_name)}),Ne(M,b)},$$slots:{default:!0}})};ii(D,G=>{MA(r)===null&&G(S)})}var k=Ot(h,2);{var N=G=>{var M=xqA(),w=Ve(M);cBA(w,{$$events:{click:c}}),Ne(G,M)};ii(k,G=>{A.showCloseButton&&G(N)})}xt(()=>LE(l,"rcb-with-close-button",A.showCloseButton)),Ne(e,l),Gi()}var HqA=Nt("<!> <!> <!> <!>",1);function OqA(e,A){Ri(A,!0);const t=ri(A,"onClose",3,void 0),i=aBA(A.productDetails,A.purchaseOptionToUse);let n=sn(pi(A.defaultPriceBreakdown??{currency:i.currency,totalAmountInMicros:i.amountMicros,totalExcludingTaxInMicros:i.amountMicros,taxCalculationStatus:"unavailable",taxAmountInMicros:null,taxBreakdown:null}));const g=o=>{Kt(n,pi(o))};wqA(e,{get brandingInfo(){return A.brandingInfo},get isInElement(){return A.isInElement},get isSandbox(){return A.isSandbox},get onClose(){return t()},navbarHeaderContent:o=>{var s=Bt(()=>!A.isInElement&&!!t());YqA(o,{get brandingInfo(){return A.brandingInfo},get onClose(){return t()},get showCloseButton(){return MA(s)}})},navbarBodyContent:o=>{var s=Bt(()=>{var a,r;return((r=(a=A.brandingInfo)==null?void 0:a.appearance)==null?void 0:r.show_product_description)??!1});OTA(o,{get productDetails(){return A.productDetails},get purchaseOption(){return A.purchaseOptionToUse},get showProductDescription(){return MA(s)},get priceBreakdown(){return MA(n)}})},mainContent:o=>{var s=HqA(),a=_i(s);{var r=d=>{dTA(d)};ii(a,d=>{A.currentPage==="payment-entry-loading"&&d(r)})}var I=Ot(a,2);{var c=d=>{_xA(d,{get productDetails(){return A.productDetails},get purchaseOption(){return A.purchaseOptionToUse},get brandingInfo(){return A.brandingInfo},get purchaseOperationHelper(){return A.purchaseOperationHelper},get gatewayParams(){return A.gatewayParams},get managementUrl(){return A.managementUrl},get customerEmail(){return A.customerEmail},get defaultPriceBreakdown(){return A.defaultPriceBreakdown},get onContinue(){return A.onContinue},get onError(){return A.onError},onPriceBreakdownUpdated:g})};ii(I,d=>{A.currentPage==="payment-entry"&&d(c)})}var l=Ot(I,2);{var B=d=>{var p=Bt(()=>{var m;return((m=A.brandingInfo)==null?void 0:m.support_email)??null}),y=Bt(()=>{var m;return((m=A.brandingInfo)==null?void 0:m.app_name)??null});QTA(d,{get lastError(){return A.lastError},get productDetails(){return A.productDetails},get supportEmail(){return MA(p)},get onDismiss(){return A.closeWithError},get appName(){return MA(y)}})};ii(l,d=>{A.currentPage==="error"&&d(B)})}var Q=Ot(l,2);{var h=d=>{uTA(d,{get onContinue(){return A.onContinue}})};ii(Q,d=>{A.currentPage==="success"&&d(h)})}Ne(o,s)},$$slots:{navbarHeaderContent:!0,navbarBodyContent:!0,mainContent:!0}}),Gi()}function PqA(e){return e.trim()===""?"You need to provide your email address to continue.":e.match(/^[^@]+@[^@]+\.[^@]+$/)?null:"Email is not valid. Please provide a valid email address."}function jqA(e){if(e&&!e.match(/^[A-Z]{3}$/)){const A=`Currency code ${e} is not valid. Please provide a valid ISO 4217 currency code.`;throw $i.errorLog(A),new mo(Ds.ConfigurationError,A)}}function zqA(e,A){var t;Ri(A,!0);const i=ri(A,"customTranslations",19,()=>({})),n=ri(A,"skipSuccessPage",3,!1),g=A.customerEmail?PqA(A.customerEmail):null;let o=sn(pi(g?void 0:A.customerEmail)),s=A.rcPackage.webBillingProduct,a=sn(null);const r=A.rcPackage.webBillingProduct.identifier??null;let I=sn("payment-entry-loading"),c=sn(null),l=sn(pi({})),B=sn(null),Q=sn(null),h=sn(null),d=sn(null),p=new KL(i(),A.selectedLocale,A.defaultLocale),y=KlA(p);Q2(iC,y),Q2(Y8,(t=A.brandingInfo)==null?void 0:t.appearance),ac(()=>{A.isInElement||(Kt(Q,pi(document.documentElement.style.height)),Kt(h,pi(document.documentElement.style.overflow)),Kt(d,pi(document.body.style.height)),document.documentElement.style.height="100%",document.body.style.height="100%",document.documentElement.style.overflow="hidden")}),JR(()=>{if(!A.isInElement){const G=(M,w,b)=>{b===""?M.style.removeProperty(w):M.style.setProperty(w,b)};G(document.documentElement,"height",MA(Q)),G(document.body,"height",MA(d)),G(document.documentElement,"overflow",MA(h))}}),Q2(q8,A.eventsTracker),ac(async()=>{if(r===null){D(new Fg(dg.ErrorSettingUpPurchase,"Product ID was not set before purchase."));return}A.purchaseOperationHelper.checkoutStart(A.appUserId,r,A.purchaseOption,A.rcPackage.webBillingProduct.presentedOfferingContext,MA(o),A.metadata).then(G=>{Kt(a,null),Kt(I,"payment-entry"),Kt(l,pi(G.gateway_params)),Kt(B,pi(G.management_url))}).catch(G=>{if(G.errorCode===dg.MissingEmailError)return Kt(o,void 0),A.purchaseOperationHelper.checkoutStart(A.appUserId,r,A.purchaseOption,A.rcPackage.webBillingProduct.presentedOfferingContext,MA(o),A.metadata).then(M=>{Kt(a,null),Kt(I,"payment-entry"),Kt(l,pi(M.gateway_params)),Kt(B,pi(M.management_url))}).catch(M=>{D(M)});D(G)})});const m=()=>{if(MA(I)==="payment-entry"){A.purchaseOperationHelper.pollCurrentPurchaseForCompletion().then(G=>{Kt(c,pi(G)),n()?A.onFinished(G):Kt(I,"success")}).catch(G=>{D(G)});return}if(MA(I)==="success"||MA(I)==="error"){A.onFinished(MA(c));return}Kt(I,"success")},D=G=>{const M=mLA({errorCode:G.getErrorCode().toString(),errorMessage:G.message});A.eventsTracker.trackSDKEvent(M),Kt(a,pi(G)),Kt(I,"error")},S=()=>{A.onError(MA(a)??new Fg(dg.UnknownError,"Unknown error without state set."))};var k=Bt(()=>A.purchases.isSandbox()),N=Bt(()=>MA(o)??null);OqA(e,{get isSandbox(){return MA(k)},get currentPage(){return MA(I)},get brandingInfo(){return A.brandingInfo},productDetails:s,get purchaseOptionToUse(){return A.purchaseOption},get lastError(){return MA(a)},get gatewayParams(){return MA(l)},get managementUrl(){return MA(B)},get purchaseOperationHelper(){return A.purchaseOperationHelper},get isInElement(){return A.isInElement},get customerEmail(){return MA(N)},closeWithError:S,onContinue:m,onError:D,get onClose(){return A.onClose}}),Gi()}function lBA(e){return e==null?!0:new Date(e)>new Date}function ZqA(e,A,t,i){const n=A.product_identifier;if(n in t)return WqA(e,A,t[n]);if(n in i)return VqA(e,A,i[n]);throw new mo(Ds.CustomerInfoError,"Could not find entitlement product in subscriptions or non-subscriptions.")}function WqA(e,A,t){return{identifier:e,isActive:lBA(A.expires_date),willRenew:EBA(A.expires_date,t),store:(t==null?void 0:t.store)??"unknown",latestPurchaseDate:new Date(A.purchase_date),originalPurchaseDate:new Date(A.purchase_date),expirationDate:ql(A.expires_date),productIdentifier:A.product_identifier,productPlanIdentifier:A.product_plan_identifier??null,unsubscribeDetectedAt:ql(t==null?void 0:t.unsubscribe_detected_at),billingIssueDetectedAt:ql(t==null?void 0:t.billing_issues_detected_at),isSandbox:(t==null?void 0:t.is_sandbox)??!1,periodType:(t==null?void 0:t.period_type)??"normal",ownershipType:(t==null?void 0:t.ownership_type)??"UNKNOWN"}}function VqA(e,A,t){return{identifier:e,isActive:!0,willRenew:!1,store:t.store,latestPurchaseDate:new Date(A.purchase_date),originalPurchaseDate:new Date(t.original_purchase_date),expirationDate:null,productIdentifier:A.product_identifier,productPlanIdentifier:null,unsubscribeDetectedAt:null,billingIssueDetectedAt:null,isSandbox:t.is_sandbox,periodType:"normal",ownershipType:"UNKNOWN"}}function XqA(e,A,t){const i={},n={};for(const g in e){const o=ZqA(g,e[g],A,t);i[g]=o,o.isActive&&(n[g]=o)}return{all:i,active:n}}function ql(e){return e==null?null:new Date(e)}function BBA(e){const A=A2A(e),t=e.subscriber,i=t2A(t.non_subscriptions),n=Object.entries(e.subscriber.non_subscriptions).flatMap(([s,a])=>a.map(r=>({transactionIdentifier:r.id,productIdentifier:s,purchaseDate:new Date(r.purchase_date||r.original_purchase_date),storeTransactionId:r.store_transaction_id||null,store:r.store}))),g=new Date(e.request_date),o=Object.fromEntries(Object.entries(e.subscriber.subscriptions).map(([s,a])=>[s,{productIdentifier:s,purchaseDate:new Date(a.purchase_date),originalPurchaseDate:ql(a.original_purchase_date),expiresDate:ql(a.expires_date),store:a.store,unsubscribeDetectedAt:ql(a.unsubscribe_detected_at),isSandbox:a.is_sandbox,billingIssuesDetectedAt:ql(a.billing_issues_detected_at),gracePeriodExpiresDate:ql(a.grace_period_expires_date),ownershipType:a.ownership_type??"UNKNOWN",periodType:a.period_type,refundedAt:ql(a.refunded_at),storeTransactionId:a.store_transaction_id||null,isActive:lBA(a.expires_date),willRenew:EBA(a.expires_date,a)}]));return{entitlements:XqA(t.entitlements,t.subscriptions,i),allExpirationDatesByProduct:A,allPurchaseDatesByProduct:$qA(e,i),activeSubscriptions:e2A(A),managementURL:t.management_url,requestDate:g,firstSeenDate:new Date(t.first_seen),originalPurchaseDate:ql(t.original_purchase_date),originalAppUserId:e.subscriber.original_app_user_id,nonSubscriptionTransactions:n,subscriptionsByProductIdentifier:o}}function EBA(e,A){if(A==null)return!1;const t=A.store=="promotional",i=e==null,n=A.unsubscribe_detected_at!=null,g=A.billing_issues_detected_at!=null;return!(t||i||n||g)}function $qA(e,A){const t={};for(const i in e.subscriber.subscriptions){const n=e.subscriber.subscriptions[i];t[i]=new Date(n.purchase_date)}for(const i in A){const n=A[i].purchase_date;n==null?t[i]=null:t[i]=new Date(n)}return t}function A2A(e){const A={};for(const t in e.subscriber.subscriptions){const i=e.subscriber.subscriptions[t];i.expires_date==null?A[t]=null:A[t]=new Date(i.expires_date)}return A}function e2A(e){const A=new Set,t=new Date;for(const i in e){const n=e[i];(n==null||n>t)&&A.add(i)}return A}function t2A(e){const A={};for(const t in e){if(e[t].length===0)continue;const i=e[t].length;A[t]=e[t][i-1]}return A}const QBA="1.13.1",i2A="https://api.revenuecat.com",n2A="https://e.revenue.cat";var YF;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(YF||(YF={}));const g2A=/^rcb_[a-zA-Z0-9_.-]+$/,o2A=/^pdl_[a-zA-Z0-9_.-]+$/,s2A=/^test_[a-zA-Z0-9_.-]+$/;function HF(e){return e?e.startsWith("rcb_sb_"):!1}function a2A(e){return e?g2A.test(e):!1}function r2A(e){return e?o2A.test(e):!1}function Ek(e){return e?s2A.test(e):!1}async function mc(e,A,t){const{apiKey:i,body:n,headers:g,httpConfig:o}=A,s=`${(o==null?void 0:o.proxyURL)??i2A}${e.urlPath()}`;try{const a=await fetch(s,{method:e.method,headers:SBA(i,g,o==null?void 0:o.additionalHeaders),body:C2A(n),signal:t});return await I2A(a,e),await a.json()}catch(a){throw a instanceof TypeError?new mo(Ds.NetworkError,nM.getPublicMessage(Ds.NetworkError),a.message):a}}async function I2A(e,A){const t=e.status;if(t>=YF.INTERNAL_SERVER_ERROR)p2(A,t,await e.text());else if(t>=YF.BAD_REQUEST){const i=await e.json(),n=i?JSON.stringify(i):null,g=i==null?void 0:i.code,o=i==null?void 0:i.message;if(g!=null){const s=nM.convertCodeToBackendErrorCode(g);if(s==null)p2(A,t,n,g);else throw mo.getForBackendError(s,o)}else p2(A,t,n)}}function p2(e,A,t,i){throw new mo(Ds.UnknownBackendError,"Unknown backend error.",`Request: ${e.name}. Status code: ${A}. Body: ${t}.`,{backendErrorCode:i})}function C2A(e){return e==null?null:JSON.stringify(e)}const uBA="Authorization",dBA="Content-Type",hBA="Accept",pBA="X-Platform",fBA="X-Version",yBA="X-Platform-Flavor",DBA="X-Platform-Flavor-Version",mBA="X-Is-Sandbox",c2A=new Set([uBA,dBA,hBA,pBA,fBA,mBA,yBA,DBA]);function SBA(e,A,t){let i={[uBA]:`Bearer ${e}`,[dBA]:"application/json",[hBA]:"application/json",[pBA]:"web",[fBA]:QBA,[mBA]:`${HF(e)}`};const n=gp.getPlatformInfo();if(n){const g={[yBA]:n.flavor,[DBA]:n.version};i={...i,...g}}return A&&(i={...i,...A}),t&&(i={...t,...i}),i}const _L="/v1/subscribers",mw="/rcbilling/v1";class l2A{constructor(A){Yt(this,"appUserId"),Yt(this,"method","GET"),Yt(this,"name","getOfferings"),this.appUserId=A}urlPath(){const A=encodeURIComponent(this.appUserId);return`${_L}/${A}/offerings`}}class B2A{constructor(A,t,i){Yt(this,"method","GET"),Yt(this,"name","getProducts"),Yt(this,"appUserId"),Yt(this,"productIds"),Yt(this,"currency"),this.appUserId=A,this.productIds=t,this.currency=i}urlPath(){const A=encodeURIComponent(this.appUserId),t=this.productIds.map(encodeURIComponent).join("&id="),i=this.currency?`&currency=${this.currency}`:"";return`${mw}/subscribers/${A}/products?id=${t}${i}`}}class E2A{constructor(A){Yt(this,"method","GET"),Yt(this,"name","getCustomerInfo"),Yt(this,"appUserId"),this.appUserId=A}urlPath(){const A=encodeURIComponent(this.appUserId);return`${_L}/${A}`}}class Q2A{constructor(){Yt(this,"method","GET"),Yt(this,"name","getBrandingInfo")}urlPath(){return`${mw}/branding`}}class u2A{constructor(){Yt(this,"method","POST"),Yt(this,"name","postCheckoutStart")}urlPath(){return`${mw}/checkout/start`}}class d2A{constructor(A){Yt(this,"method","POST"),Yt(this,"name","postCheckoutCalculateTax"),Yt(this,"operationSessionId"),this.operationSessionId=A}urlPath(){return`${mw}/checkout/${this.operationSessionId}/calculate_taxes`}}class h2A{constructor(A){Yt(this,"method","POST"),Yt(this,"name","postCheckoutComplete"),Yt(this,"operationSessionId"),this.operationSessionId=A}urlPath(){return`${mw}/checkout/${this.operationSessionId}/complete`}}class p2A{constructor(A){Yt(this,"method","GET"),Yt(this,"name","getCheckoutStatus"),Yt(this,"operationSessionId"),this.operationSessionId=A}urlPath(){return`${mw}/checkout/${this.operationSessionId}`}}class f2A{constructor(A){Yt(this,"method","POST"),Yt(this,"name","setAttributes"),Yt(this,"appUserId"),this.appUserId=A}urlPath(){const A=encodeURIComponent(this.appUserId);return`${_L}/${A}/attributes`}}class y2A{constructor(){Yt(this,"method","POST"),Yt(this,"name","postReceipt")}urlPath(){return"/v1/receipts"}}class D2A{constructor(A){Yt(this,"method","GET"),Yt(this,"name","getVirtualCurrencies"),Yt(this,"appUserId"),this.appUserId=A}urlPath(){const A=encodeURIComponent(this.appUserId);return`${_L}/${A}/virtual_currencies`}}const S1={};class m2A{constructor(A,t=S1){Yt(this,"API_KEY"),Yt(this,"httpConfig"),Yt(this,"isSandbox"),this.API_KEY=A,this.httpConfig=t,this.isSandbox=HF(A)}getIsSandbox(){return this.isSandbox}async getOfferings(A){return await mc(new l2A(A),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getCustomerInfo(A){return await mc(new E2A(A),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getProducts(A,t,i){return await mc(new B2A(A,t,i),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getBrandingInfo(){return await mc(new Q2A,{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async postCheckoutStart(A,t,i,n,g,o,s=void 0){const a={app_user_id:A,product_id:t,email:o,price_id:n.priceId,presented_offering_identifier:i.offeringIdentifier,trace_id:g};return s&&(a.metadata=s),n.id!=="base_option"&&(a.offer_id=n.id),i.targetingContext&&(a.applied_targeting_rule={rule_id:i.targetingContext.ruleId,revision:i.targetingContext.revision}),i.placementIdentifier&&(a.presented_placement_identifier=i.placementIdentifier),await mc(new u2A,{apiKey:this.API_KEY,body:a,httpConfig:this.httpConfig})}async postCheckoutCalculateTax(A,t,i,n){const g={country_code:t,postal_code:i};return await mc(new d2A(A),{apiKey:this.API_KEY,body:g,httpConfig:this.httpConfig},n)}async postCheckoutComplete(A,t){const i={email:t};return await mc(new h2A(A),{apiKey:this.API_KEY,body:i,httpConfig:this.httpConfig})}async getCheckoutStatus(A){return await mc(new p2A(A),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async setAttributes(A,t){const i=Date.now(),n={};for(const[o,s]of Object.entries(t))n[o]={value:s,updated_at_ms:i};const g={attributes:n};return await mc(new f2A(A),{apiKey:this.API_KEY,body:g,httpConfig:this.httpConfig})}async postReceipt(A,t,i,n,g){let o=null;n.targetingContext&&(o={rule_id:n.targetingContext.ruleId,revision:n.targetingContext.revision});const s={fetch_token:i,product_id:t,app_user_id:A,presented_offering_identifier:n.offeringIdentifier,presented_placement_identifier:n.placementIdentifier,applied_targeting_rule:o,initiation_source:g};return await mc(new y2A,{apiKey:this.API_KEY,body:s,httpConfig:this.httpConfig})}async getVirtualCurrencies(A){return await mc(new D2A(A),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}}function S2A(e,A){if(!(a2A(e)||Ek(e)||r2A(e)&&(A!=null&&A.allowPaddleAPIKey)))throw new mo(Ds.InvalidCredentialsError,"Invalid API key. Use your Web Billing API key.")}function k7(e){if(!e||new Set(["no_user","null","none","nil","(null)","NaN","\\x00","","unidentified","undefined","unknown"]).has(e)||e.includes("/"))throw new mo(Ds.InvalidAppUserIdError,'Provided user id: "'+(e??"[Not provided]")+'" is not valid. See https://www.revenuecat.com/docs/customers/user-ids#tips-for-setting-app-user-ids for more information.')}function w2A(e){if(e!=null&&e.endsWith("/"))throw new mo(Ds.ConfigurationError,"Invalid proxy URL. The proxy URL should not end with a trailing slash.")}function k2A(e){if(e){for(const A in e)if(c2A.has(A))throw new mo(Ds.ConfigurationError,"Invalid additional headers. Some headers are reserved for internal use.")}}var wBA=(e=>(e.Current="current",e))(wBA||{});function M2A(e,A){async function t(...i){return await this.preload(),await e.call(this,...i)}return t}const kBA=(e,A)=>{const t={...e.webBillingProduct,presentedOfferingContext:{...e.webBillingProduct.presentedOfferingContext,placementIdentifier:A}};return{...e,webBillingProduct:t,rcBillingProduct:t}},ch=(e,A)=>e==null?null:kBA(e,A),N2A=(e,A,t)=>{const i=e.offering_ids_by_placement??null;if(i==null)return null;const n=e.fallback_offering_id??null;let g;if(t in i){const s=i[t]??null;if(s==null)return null;g=A[s],g==null&&(g=A[n])}else g=A[n];if(g==null)return null;const o=Object.fromEntries(Object.entries(g.packagesById).map(([s,a])=>[s,kBA(a,t)]));return{...g,packagesById:o,availablePackages:Object.values(o),weekly:ch(g.weekly,t),monthly:ch(g.monthly,t),twoMonth:ch(g.twoMonth,t),threeMonth:ch(g.threeMonth,t),sixMonth:ch(g.sixMonth,t),annual:ch(g.annual,t),lifetime:ch(g.lifetime,t)}};function R2A(e,A){const t={};A.product_details.forEach(g=>{t[g.identifier]=g});const i={};e.offerings.forEach(g=>{const o=g.identifier===e.current_offering_id,s=PxA(o,g,t,e.targeting);s!=null&&(i[g.identifier]=s)});const n=e.current_offering_id?i[e.current_offering_id]??null:null;return Object.keys(i).length==0&&$i.debugLog("Empty offerings. Please make sure you've configured offerings correctly in the RevenueCat dashboard and that the products are properly configured."),{all:i,current:n}}const G2A=1000001;function b2A(e){return e.webBillingProduct.defaultPurchaseOption}function M7(e,A,t,i=!1){return t.translate(oi.PaywallVariablesPricePerPeriod,{formattedPrice:e,period:A.base.period?t.translatePeriod(A.base.period.number,A.base.period.unit,{noWhitespace:!0,short:!i}):""})}function U2A(e,A){return e.unit==="year"?A.translatePeriod(e.number*12,Sa.Month):A.translatePeriod(e.number,e.unit)}function v2A({price:e,period:A,translator:t}){const i=t.formatPrice(e.amountMicros,e.currency);return A?A.unit==="year"?t.formatPrice(e.amountMicros/12/4,e.currency):A.unit==="month"||A.unit==="week"&&A.number>1?t.formatPrice(e.amountMicros/A.number,e.currency):A.unit==="day"?t.formatPrice(e.amountMicros*7/A.number,e.currency):i:i}function K2A({price:e,period:A,translator:t}){const i=t.formatPrice(e.amountMicros,e.currency);return!A||!A.number?i:A.unit==="year"?t.formatPrice(e.amountMicros/12,e.currency):A.unit==="month"&&A.number>1?t.formatPrice(e.amountMicros/A.number,e.currency):A.unit==="week"?t.formatPrice(e.amountMicros*4/A.number,e.currency):A.unit==="day"?t.formatPrice(e.amountMicros*30/A.number,e.currency):i}function N7({price:e,period:A,full:t=!1,translator:i}){if(!A||!A.number||A.unit===Sa.Month&&A.number==1)return i.formatPrice(e.amountMicros,e.currency);let n="";switch(A.unit){case Sa.Year:n=i.formatPrice(e.amountMicros/12,e.currency);break;case Sa.Month:n=i.formatPrice(e.amountMicros/A.number,e.currency);break;case Sa.Week:n=i.formatPrice(e.amountMicros*4/A.number,e.currency);break;case Sa.Day:n=i.formatPrice(e.amountMicros*30/A.number,e.currency);break}return i.translate(oi.PaywallVariablesTotalPriceAndPerMonth,{formattedPrice:i.formatPrice(e.amountMicros,e.currency),period:i.translatePeriod(A.number,A.unit,{noWhitespace:!0,short:!t}),formattedPricePerMonth:n,monthPeriod:i.translatePeriodUnit(Sa.Month,{noWhitespace:!0,short:!t})})}function F2A(e,A){const t=e.availablePackages,i=t.reduce((n,g)=>{const o=n.webBillingProduct.price||n.webBillingProduct.price,s=g.webBillingProduct.price||g.webBillingProduct.price;return o.amountMicros>s.amountMicros?n:g});return t.reduce((n,g)=>(n[g.identifier]=_2A(g,i,A),n),{})}function _2A(e,A,t){const i=e.webBillingProduct,n=i.price||i.price,g=t.formatPrice(n.amountMicros,n.currency),o=b2A(e),s=i.productType,a={product_name:i.title,price:g,price_per_period:"",price_per_period_full:"",total_price_and_per_month:"",total_price_and_per_month_full:"",sub_price_per_month:"",sub_price_per_week:"",sub_duration:"",sub_duration_in_months:"",sub_period:"",sub_period_length:"",sub_period_abbreviated:"",sub_offer_duration:void 0,sub_offer_duration_2:void 0,sub_offer_price:void 0,sub_offer_price_2:void 0,sub_relative_discount:""};if(s===_p.Subscription&&o){a.price_per_period=M7(g,o,t),a.price_per_period_full=M7(g,o,t,!0);const r=i.period||o.base.period;a.total_price_and_per_month=N7({price:n,period:r,translator:t}),a.total_price_and_per_month_full=N7({price:n,period:r,full:!0,translator:t}),a.sub_price_per_month=K2A({price:n,period:r,translator:t}),a.sub_price_per_week=v2A({price:n,period:r,translator:t}),a.sub_duration=t.translatePeriod(r==null?void 0:r.number,r==null?void 0:r.unit),a.sub_duration_in_months=U2A(r,t),a.sub_period=t.translatePeriodFrequency(r==null?void 0:r.number,r==null?void 0:r.unit),a.sub_period_length=r?t.translatePeriodUnit(r.unit,{noWhitespace:!0}):void 0,a.sub_period_abbreviated=r?t.translatePeriodUnit(r.unit,{noWhitespace:!0,short:!0}):void 0;const I=n.amountMicros,c=(A.webBillingProduct.price||A.webBillingProduct.price).amountMicros,l=((c-I)*100/c).toFixed(0);a.sub_relative_discount=I===c?"":t.translate(oi.PaywallVariablesSubRelativeDiscount,{discount:l})}return(s===_p.NonConsumable||s===_p.Consumable)&&o&&(a.price=g,a.price_per_period=g,a.price_per_period_full=g,a.total_price_and_per_month=g,a.sub_price_per_month=g,a.sub_duration=t.translate(oi.PeriodsLifetime),a.sub_duration_in_months=t.translate(oi.PeriodsLifetime),a.sub_period=t.translate(oi.PeriodsLifetime),a.sub_price_per_week=void 0,a.sub_relative_discount=void 0,a.price_per_period_full=g,a.total_price_and_per_month_full=g,a.sub_period_length=void 0,a.sub_period_abbreviated=void 0),a}const ha=[];for(let e=0;e<256;++e)ha.push((e+256).toString(16).slice(1));function J2A(e,A=0){return(ha[e[A+0]]+ha[e[A+1]]+ha[e[A+2]]+ha[e[A+3]]+"-"+ha[e[A+4]]+ha[e[A+5]]+"-"+ha[e[A+6]]+ha[e[A+7]]+"-"+ha[e[A+8]]+ha[e[A+9]]+"-"+ha[e[A+10]]+ha[e[A+11]]+ha[e[A+12]]+ha[e[A+13]]+ha[e[A+14]]+ha[e[A+15]]).toLowerCase()}let f2;const L2A=new Uint8Array(16);function x2A(){if(!f2){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");f2=crypto.getRandomValues.bind(crypto)}return f2(L2A)}const T2A=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),R7={randomUUID:T2A};function MBA(e,A,t){var i;if(R7.randomUUID&&!e)return R7.randomUUID();e=e||{};const n=e.random??((i=e.rng)==null?void 0:i.call(e))??x2A();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,J2A(n)}var q2A=/(%?)(%([sdijo]))/g;function Y2A(e,A){switch(A){case"s":return e;case"d":case"i":return Number(e);case"j":return JSON.stringify(e);case"o":{if(typeof e=="string")return e;const t=JSON.stringify(e);return t==="{}"||t==="[]"||/^\[object .+?\]$/.test(t)?e:t}}}function Z8(e,...A){if(A.length===0)return e;let t=0,i=e.replace(q2A,(n,g,o,s)=>{const a=A[t],r=Y2A(a,s);return g?n:(t++,r)});return t<A.length&&(i+=` ${A.slice(t).join(" ")}`),i=i.replace(/%{2,2}/g,"%"),i}var H2A=2;function O2A(e){if(!e.stack)return;const A=e.stack.split(`
`);A.splice(1,H2A),e.stack=A.join(`
`)}var P2A=class extends Error{constructor(e,...A){super(e),this.message=e,this.name="Invariant Violation",this.message=Z8(e,...A),O2A(this)}},NBA=(e,A,...t)=>{if(!e)throw new P2A(A,...t)};NBA.as=(e,A,t,...i)=>{if(!A){const n=i.length===0?t:Z8(t,...i);let g;try{g=Reflect.construct(e,[n])}catch{g=e(n)}throw g}};const j2A="[MSW]";function W8(e,...A){const t=Z8(e,...A);return`${j2A} ${t}`}function z2A(e,...A){console.warn(W8(e,...A))}function Z2A(e,...A){console.error(W8(e,...A))}const W2A={formatMessage:W8,warn:z2A,error:Z2A};function V2A(){NBA(typeof URL<"u",W2A.formatMessage(`Global "URL" class is not defined. This likely means that you're running MSW in an environment that doesn't support all Node.js standard API (e.g. React Native). If that's the case, please use an appropriate polyfill for the "URL" class, like "react-native-url-polyfill".`))}var RBA=(e=>(e.HEAD="HEAD",e.GET="GET",e.POST="POST",e.PUT="PUT",e.PATCH="PATCH",e.OPTIONS="OPTIONS",e.DELETE="DELETE",e))(RBA||{});V2A();class X2A{constructor(A,t,i,n){Yt(this,"initialDelay"),Yt(this,"maxDelay"),Yt(this,"jitterPercent"),Yt(this,"callback"),Yt(this,"currentDelay"),Yt(this,"timeoutId"),Yt(this,"executingCallback",!1),this.initialDelay=A,this.currentDelay=A,this.maxDelay=t,this.jitterPercent=i,this.callback=n}tryFlush(){if(this.backingOff()){$i.debugLog("Backing off, not flushing");return}this.clearTimeout(),this.executeCallbackWithRetries()}stop(){this.clearTimeout()}schedule(A){if(this.timeoutId!==void 0)return;const t=this.addJitter(A||this.currentDelay);this.timeoutId=setTimeout(()=>{this.timeoutId=void 0,this.executeCallbackWithRetries()},t)}backoff(){const A=this.currentDelay,t=Math.min(this.currentDelay*2,this.maxDelay);$i.debugLog(`Backing next off to ${A}ms delay`),this.clearTimeout(),this.currentDelay=t,this.schedule(A)}reset(){this.currentDelay!==this.initialDelay&&(this.clearTimeout(),this.currentDelay=this.initialDelay)}async executeCallbackWithRetries(){if(this.executingCallback){$i.debugLog("Callback already running, rescheduling"),this.schedule();return}this.executingCallback=!0;try{await this.callback(),this.reset()}catch{this.backoff()}finally{this.executingCallback=!1}}backingOff(){return this.currentDelay>this.initialDelay}clearTimeout(){clearTimeout(this.timeoutId),this.timeoutId=void 0}addJitter(A){const t=A*this.jitterPercent,i=A-t,n=A+t;return Math.floor(Math.random()*(n-i+1)+i)}}function GBA(e){const A={};for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const i=t.replace(/([A-Z])/g,"_$1").toLowerCase(),n=e[t];n&&typeof n=="object"&&!Array.isArray(n)?A[i]=GBA(n):A[i]=n}return A}class $2A{constructor(A){Yt(this,"EVENT_TYPE","web_billing"),Yt(this,"id"),Yt(this,"timestampMs"),Yt(this,"data"),this.id=MBA(),this.timestampMs=Date.now(),this.data=A}toJSON(){return GBA({id:this.id,timestampMs:this.timestampMs,type:this.EVENT_TYPE,eventName:this.data.eventName,appUserId:this.data.appUserId,context:{...this.data.context},properties:{...this.data.properties,traceId:this.data.traceId}})}}function AYA(e,A){const t=new URLSearchParams(window.location.search);return{libraryName:"purchases-js",libraryVersion:QBA,locale:navigator.language,userAgent:navigator.userAgent,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,screenWidth:screen.width,screenHeight:screen.height,utmSource:t.get("utm_source")??null,utmMedium:t.get("utm_medium")??null,utmCampaign:t.get("utm_campaign")??null,utmContent:t.get("utm_content")??null,utmTerm:t.get("utm_term")??null,pageReferrer:document.referrer,pageUrl:`${window.location.origin}${window.location.pathname}`,pageTitle:document.title,source:e,rcSource:A}}const eYA=2e3,tYA=5*6e4,iYA=.1;class nYA{constructor(A){Yt(this,"apiKey"),Yt(this,"eventsQueue",[]),Yt(this,"eventsUrl"),Yt(this,"flushManager"),Yt(this,"traceId",MBA()),Yt(this,"appUserId"),Yt(this,"isSilent"),Yt(this,"rcSource"),this.apiKey=A.apiKey,this.eventsUrl=`${n2A}/v1/events`,this.appUserId=A.appUserId,this.isSilent=A.silent||!1,this.rcSource=A.rcSource,this.flushManager=new X2A(eYA,tYA,iYA,this.flushEvents.bind(this))}async updateUser(A){this.appUserId=A}getTraceId(){return this.traceId}trackSDKEvent(A){this.trackEvent({...A,source:"sdk"})}trackExternalEvent(A){this.trackEvent({...A})}trackEvent(A){if(this.isSilent){$i.verboseLog("Skipping event tracking, the EventsTracker is silent");return}try{const t=new $2A({eventName:A.eventName,traceId:this.traceId,appUserId:this.appUserId,context:AYA(A.source,this.rcSource),properties:A.properties||{}});this.eventsQueue.push(t),this.flushManager.tryFlush()}catch{$i.errorLog(`Error while tracking event ${A.eventName}`)}}dispose(){this.flushManager.stop()}flushEvents(){if(this.eventsQueue.length===0)return Promise.resolve();const A=[...this.eventsQueue];return fetch(this.eventsUrl,{method:RBA.POST,headers:SBA(this.apiKey),body:JSON.stringify({events:A})}).then(t=>{if(t.status===200||t.status===201){this.eventsQueue.splice(0,A.length);return}else throw $i.debugLog("Events failed to flush due to server error"),new Error("Events failed to flush due to server error")}).catch(t=>{throw $i.debugLog("Error while flushing events"),t})}}const gYA=()=>{const e=new URLSearchParams(window.location.search),A=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],t={};return A.forEach(i=>{const n=e.get(i);n!==null&&(t[i]=n)}),t},oYA=["app","embedded"],y2={autoCollectUTMAsMetadata:!0,collectAnalyticsEvents:!0};function w1(){if(crypto&&crypto.randomUUID)return crypto.randomUUID();const e=new Uint8Array(16);if(crypto&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;const A=Array.from(e).map(t=>t.toString(16).padStart(2,"0"));return[A.slice(0,4).join(""),A.slice(4,6).join(""),A.slice(6,8).join(""),A.slice(8,10).join(""),A.slice(10,16).join("")].join("-")}var sYA=Nt('<p class="svelte-11vxb6p"><strong>Free Trial:</strong> </p>'),aYA=Nt('<p class="svelte-11vxb6p"><strong>Intro Price:</strong> </p>'),rYA=Nt('<div class="rc-simulated-store-modal-overlay svelte-11vxb6p"><div class="rc-simulated-store-modal svelte-11vxb6p"><div class="rc-simulated-store-modal-content svelte-11vxb6p"><h2 class="rc-simulated-store-modal-title svelte-11vxb6p">Test Store Purchase</h2> <div class="rc-simulated-store-modal-details svelte-11vxb6p"><div><p class="svelte-11vxb6p"><strong>Product:</strong> </p> <p class="svelte-11vxb6p"><strong>Type:</strong> </p> <p class="svelte-11vxb6p"><strong>Price:</strong> </p> <!> <!></div></div> <div class="rc-simulated-store-modal-buttons svelte-11vxb6p"><button type="button" class="rc-simulated-store-modal-button rc-simulated-store-modal-button-primary svelte-11vxb6p">Test valid purchase</button> <button type="button" class="rc-simulated-store-modal-button rc-simulated-store-modal-button-secondary svelte-11vxb6p">Test failed purchase</button> <button type="button" class="rc-simulated-store-modal-button rc-simulated-store-modal-button-cancel svelte-11vxb6p">Cancel</button></div></div></div></div>');const IYA={hash:"svelte-11vxb6p",code:`.rc-simulated-store-modal-overlay.svelte-11vxb6p {position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(0, 0, 0, 0.5);display:flex;justify-content:center;align-items:center;z-index:9999;}.rc-simulated-store-modal.svelte-11vxb6p {background:white;border-radius:8px;padding:0;max-width:500px;width:90%;max-height:90%;overflow-y:auto;box-shadow:0 4px 20px rgba(0, 0, 0, 0.15);}.rc-simulated-store-modal-content.svelte-11vxb6p {padding:24px;}.rc-simulated-store-modal-title.svelte-11vxb6p {margin:0 0 20px 0;font-size:24px;font-weight:600;color:#333;}.rc-simulated-store-modal-details.svelte-11vxb6p {margin-bottom:24px;}.rc-simulated-store-modal-details.svelte-11vxb6p p:where(.svelte-11vxb6p) {margin:8px 0;color:#666;line-height:1.5;}.rc-simulated-store-modal-buttons.svelte-11vxb6p {display:flex;flex-direction:column;gap:12px;}.rc-simulated-store-modal-button.svelte-11vxb6p {padding:12px 24px;border:none;border-radius:6px;font-size:16px;font-weight:500;cursor:pointer;transition:background-color 0.2s ease;}.rc-simulated-store-modal-button-primary.svelte-11vxb6p {background-color:#007aff;color:white;}.rc-simulated-store-modal-button-primary.svelte-11vxb6p:hover {background-color:#0056cc;}.rc-simulated-store-modal-button-secondary.svelte-11vxb6p {background-color:#ff3b30;color:white;}.rc-simulated-store-modal-button-secondary.svelte-11vxb6p:hover {background-color:#cc2e24;}.rc-simulated-store-modal-button-cancel.svelte-11vxb6p {background-color:#f2f2f7;color:#333;}.rc-simulated-store-modal-button-cancel.svelte-11vxb6p:hover {background-color:#e5e5ea;}

  /* Mobile responsive - full screen on small screens */
  @media (max-width: 768px) {.rc-simulated-store-modal-overlay.svelte-11vxb6p {padding:0;}.rc-simulated-store-modal.svelte-11vxb6p {width:100%;height:100%;border-radius:0;max-width:none;max-height:none;}.rc-simulated-store-modal-content.svelte-11vxb6p {height:100%;display:flex;flex-direction:column;justify-content:center;}
  }`};function CYA(e,A){Ri(A,!1),hi(e,IYA);let t=ri(A,"productIdentifier",8),i=ri(A,"productType",8),n=ri(A,"basePrice",8),g=ri(A,"freeTrialPeriod",8,void 0),o=ri(A,"introPriceFormatted",8,void 0),s=ri(A,"onValidPurchase",8),a=ri(A,"onFailedPurchase",8),r=ri(A,"onCancel",8);function I(J){J.target===J.currentTarget&&r()()}lc();var c=rYA(),l=Ve(c),B=Ve(l),Q=Ot(Ve(B),2),h=Ve(Q),d=Ve(h),p=Ot(Ve(d)),y=Ot(d,2),m=Ot(Ve(y)),D=Ot(y,2),S=Ot(Ve(D)),k=Ot(D,2);{var N=J=>{var q=sYA(),v=Ot(Ve(q));xt(()=>Sn(v,` ${g()??""}`)),Ne(J,q)};ii(k,J=>{g()&&J(N)})}var G=Ot(k,2);{var M=J=>{var q=aYA(),v=Ot(Ve(q));xt(()=>Sn(v,` ${o()??""}`)),Ne(J,q)};ii(G,J=>{o()&&J(M)})}var w=Ot(Q,2),b=Ve(w),_=Ot(b,2),K=Ot(_,2);xt(()=>{Sn(p,` ${t()??""}`),Sn(m,` ${i()??""}`),Sn(S,` ${n()??""}`)}),iB("click",b,function(...J){var q;(q=s())==null||q.apply(this,J)}),iB("click",_,function(...J){var q;(q=a())==null||q.apply(this,J)}),iB("click",K,function(...J){var q;(q=r())==null||q.apply(this,J)}),iB("click",c,I),Ne(e,c),Gi()}async function bBA(e,A,t){const i=new Date,n=`test_${i.getTime()}_${w1()}`,g=`test_store_operation_session_${w1()}`,o={storeTransactionId:n,productIdentifier:e.identifier,purchaseDate:i},s=await A.postReceipt(t,e.identifier,n,e.presentedOfferingContext,"purchase");return{customerInfo:BBA(s),redemptionInfo:null,operationSessionId:g,storeTransaction:o}}function cYA(e,A,t){const i=e.rcPackage.webBillingProduct,n=i.productType,g=i.freeTrialPhase,o=i.introPricePhase,s=i.price,a=r=>r?`${r.number} ${r.unit}${r.number>1?"s":""}`:"N/A";return new Promise((r,I)=>{var c;const l=document.createElement("div");document.body.appendChild(l);const B=()=>{Q&&gK(Q),document.body.removeChild(l)};let Q=null;Q=B1(CYA,{target:l,props:{productIdentifier:i.identifier,productType:n,basePrice:s.formattedPrice,freeTrialPeriod:g?a(g.period):void 0,introPriceFormatted:(c=o==null?void 0:o.price)==null?void 0:c.formattedPrice,onValidPurchase:async()=>{B();try{r(await bBA(i,A,t))}catch(h){I(h)}},onFailedPurchase:()=>{B(),I(new mo(Ds.ProductNotAvailableForPurchaseError,"Simulated test purchase failure: no real transaction occurred"))},onCancel:()=>{B(),I(new mo(Ds.UserCancelledError))}}})})}class lYA{constructor(){Yt(this,"virtualCurrenciesCache",new Map),Yt(this,"CACHE_EXPIRY_MS",5*60*1e3)}invalidateAllCaches(){this.virtualCurrenciesCache.clear()}cacheVirtualCurrencies(A,t){this.virtualCurrenciesCache.set(A,{data:t,lastUpdatedAt:Date.now()})}getCachedVirtualCurrencies(A,t=!1){const i=this.virtualCurrenciesCache.get(A);return this.getCachedData(i??null,t)}invalidateVirtualCurrenciesCache(A){this.virtualCurrenciesCache.delete(A)}getCachedData(A,t=!1){return A?t?A.data:Date.now()-A.lastUpdatedAt>=this.CACHE_EXPIRY_MS?null:A.data:null}}function BYA(e){return{balance:e.balance,name:e.name,code:e.code,serverDescription:e.description??null}}function EYA(e){const A={};for(const[t,i]of Object.entries(e.virtual_currencies))A[t]=BYA(i);return{all:A}}const G7="$RCAnonymousID:";var UBA,aK;UBA=[M2A];const Qk=class jr{constructor(A,t,i=S1,n=y2){xvA(aK,5,this),Yt(this,"_API_KEY"),Yt(this,"_appUserId"),Yt(this,"_brandingInfo",null),Yt(this,"_loadingResourcesPromise",null),Yt(this,"_flags"),Yt(this,"backend"),Yt(this,"purchaseOperationHelper"),Yt(this,"eventsTracker"),Yt(this,"inMemoryCache"),this._API_KEY=A,this._appUserId=t,this._flags={...y2,...n},HF(A)?$i.debugLog("Initializing Purchases SDK with Web billing sandbox API Key"):Ek(A)&&$i.debugLog("Initializing Purchases SDK with RC Test store API Key."),this.eventsTracker=new nYA({apiKey:this._API_KEY,appUserId:this._appUserId,silent:!this._flags.collectAnalyticsEvents,rcSource:this._flags.rcSource??null}),this.backend=new m2A(this._API_KEY,i),this.inMemoryCache=new lYA,this.purchaseOperationHelper=new dFA(this.backend,this.eventsTracker),this.eventsTracker.trackSDKEvent({eventName:BI.SDKInitialized})}static setLogLevel(A){$i.setLogLevel(A)}static setPlatformInfo(A){jr._platformInfo=A}static getPlatformInfo(){return jr._platformInfo}static getSharedInstance(){if(jr.isConfigured())return jr.instance;throw new QFA}static isConfigured(){return jr.instance!==void 0}static configure(A,t,i,n){jr.instance!==void 0&&$i.warnLog("Purchases is already initialized. You normally should only configure Purchases once. Creating and returning new instance.");let g;if(typeof A=="object"&&A!==null)g=A;else{if(typeof A!="string")throw new mo(Ds.ConfigurationError,"API key must be provided as a string");if(typeof t!="string")throw new mo(Ds.ConfigurationError,"App user ID must be provided as a string");g={apiKey:A,appUserId:t,httpConfig:i,flags:n}}return jr.configureInternal(g),jr.getSharedInstance()}static configureInternal(A){const{apiKey:t,appUserId:i,httpConfig:n,flags:g}=A,o=n??S1,s=g??y2;jr.validateConfig(A),jr.instance=new jr(t,i,o,s)}static validateConfig(A){var t,i;S2A(A.apiKey,A.flags),k7(A.appUserId),w2A((t=A.httpConfig)==null?void 0:t.proxyURL),k2A((i=A.httpConfig)==null?void 0:i.additionalHeaders)}async preload(){if(this.hasLoadedResources()){$i.verboseLog("Purchases resources are loaded. Skipping.");return}if(this._loadingResourcesPromise!==null){$i.verboseLog("Purchases resources are loading. Waiting."),await this._loadingResourcesPromise;return}return this._loadingResourcesPromise=this.fetchAndCacheBrandingInfo().catch(A=>{let t=`${A}`;A instanceof mo&&(t=`${A.message}. ${A.underlyingErrorMessage?`Underlying error: ${A.underlyingErrorMessage}`:""}`),$i.errorLog(`Error fetching branding info: ${t}`)}).finally(()=>{this._loadingResourcesPromise=null}),this._loadingResourcesPromise}async fetchAndCacheBrandingInfo(){if(Ek(this._API_KEY)){$i.warnLog("Branding info is not available for RC Test Store API keys.");return}this._brandingInfo=await this.backend.getBrandingInfo()}hasLoadedResources(){return this._brandingInfo!==null}async renderPaywall(A){console.warn("This method is @experimental, Paywalls are not generally available but they will come soon!");let t=A.htmlTarget??document.getElementById("rcb-ui-pw-root");if(t===null){const l=document.createElement("div");l.id="rcb-ui-pw-root",l.className="rcb-ui-pw-root",l.style.zIndex=`${G2A}`,document.body.appendChild(l),t=l}if(t===null)throw new Error("Could not generate a mount point for the billing widget");const i=t;i.innerHTML="";const n=A.offering;if(!n.paywall_components)throw new Error("You cannot use paywalls yet, they are coming soon!");const g=A.selectedLocale||navigator.language,o=new KL({},g,n.paywall_components.default_locale),s=l=>{var B;const Q=n.availablePackages.find(h=>h.identifier===l);if(Q===void 0)throw new Error(`No package found for ${l}`);return this.purchase({rcPackage:Q,htmlTarget:A.purchaseHtmlTarget,customerEmail:A.customerEmail,selectedLocale:g,defaultLocale:((B=n.paywall_components)==null?void 0:B.default_locale)||wm})},a=l=>{var B;if(A.onNavigateToUrl){A.onNavigateToUrl(l);return}(B=window.open(l,"_blank"))==null||B.focus()},r=()=>{},I=()=>{if(A.onVisitCustomerCenter){A.onVisitCustomerCenter();return}},c=F2A(n,o);return new Promise((l,B)=>{B1(Y_A,{target:i,props:{paywallData:n.paywall_components,selectedLocale:g,onNavigateToUrlClicked:a,onVisitCustomerCenterClicked:I,onBackClicked:()=>{if(A.onBack){A.onBack();return}i.innerHTML="",$i.debugLog("Purchase cancelled by user"),B(new mo(Ds.UserCancelledError))},onRestorePurchasesClicked:r,onPurchaseClicked:Q=>{s(Q).then(h=>{l(h)}).catch(h=>B(h))},onError:Q=>B(Q),variablesPerPackage:c}})})}async getOfferings(A){jqA(A==null?void 0:A.currency);const t=this._appUserId,i=await this.backend.getOfferings(t),n=(A==null?void 0:A.offeringIdentifier)===wBA.Current?i.current_offering_id:A==null?void 0:A.offeringIdentifier;return n&&(i.offerings=i.offerings.filter(g=>g.identifier===n)),await this.getAllOfferings(i,t,A)}async getCurrentOfferingForPlacement(A,t){const i=this._appUserId,n=await this.backend.getOfferings(i),g=await this.getAllOfferings(n,i,t),o=n.placements??null;return o==null?null:N2A(o,g.all,A)}async getAllOfferings(A,t,i){const n=A.offerings.flatMap(o=>o.packages).map(o=>o.platform_product_identifier),g=await this.backend.getProducts(t,n,i==null?void 0:i.currency);return this.logMissingProductIds(n,g.product_details),R2A(A,g)}async isEntitledTo(A){const t=await this.getCustomerInfo();return A in t.entitlements.active}purchasePackage(A,t,i){return this.purchase({rcPackage:A,customerEmail:t,htmlTarget:i})}async purchase(A){var t;const{rcPackage:i,purchaseOption:n,htmlTarget:g,customerEmail:o,selectedLocale:s=wm,defaultLocale:a=wm,skipSuccessPage:r=!1}=A;if(Ek(this._API_KEY)){const D=await cYA(A,this.backend,this._appUserId);return this.inMemoryCache.invalidateAllCaches(),D}let I=g??document.getElementById("rcb-ui-root");if(I===null){const D=document.createElement("div");D.className="rcb-ui-root",document.body.appendChild(D),I=D}if(I===null)throw new Error("Could not generate a mount point for the billing widget");const c=I,l=this._appUserId;$i.debugLog(`Presenting purchase form for package ${i.identifier}`);const B=s||a,Q=n??i.webBillingProduct.defaultPurchaseOption,h=wLA({appearance:(t=this._brandingInfo)==null?void 0:t.appearance,rcPackage:i,purchaseOptionToUse:Q,customerEmail:o});this.eventsTracker.trackSDKEvent(h);const d={...this._flags.autoCollectUTMAsMetadata?gYA():{},...A.metadata||{}};let p=null;const y=this._brandingInfo;y&&A.brandingAppearanceOverride&&(y.appearance=A.brandingAppearanceOverride);const m=g!==void 0;return new Promise((D,S)=>{m||window.history.pushState({checkoutOpen:!0},"");const k=this._flags.rcSource&&oYA.includes(this._flags.rcSource)?void 0:()=>{const N=MLA();this.eventsTracker.trackSDKEvent(N),window.removeEventListener("popstate",k),p&&gK(p),c.innerHTML="",$i.debugLog("Purchase cancelled by user"),S(new mo(Ds.UserCancelledError))};!m&&k&&window.addEventListener("popstate",k),p=B1(zqA,{target:c,props:{isInElement:m,appUserId:l,rcPackage:i,purchaseOption:Q,customerEmail:o,onFinished:async N=>{const G=kLA({redemptionInfo:N.redemptionInfo});this.eventsTracker.trackSDKEvent(G),this.inMemoryCache.invalidateAllCaches(),$i.debugLog("Purchase finished"),p&&gK(p),c.innerHTML="";const M={customerInfo:await this._getCustomerInfoForUserId(l),redemptionInfo:N.redemptionInfo,operationSessionId:N.operationSessionId,storeTransaction:{storeTransactionId:N.storeTransactionIdentifier,productIdentifier:i.webBillingProduct.identifier,purchaseDate:N.purchaseDate}};D(M)},onClose:k,onError:N=>{var G;const M=NLA({errorCode:(G=N.errorCode)==null?void 0:G.toString(),errorMessage:N.message});this.eventsTracker.trackSDKEvent(M),p&&gK(p),c.innerHTML="",S(mo.getForPurchasesFlowError(N))},purchases:this,eventsTracker:this.eventsTracker,brandingInfo:this._brandingInfo,purchaseOperationHelper:this.purchaseOperationHelper,selectedLocale:B,metadata:d,defaultLocale:a,customTranslations:A.labelsOverride,skipSuccessPage:r}})})}async _postSimulatedStoreReceipt(A){return await bBA(A,this.backend,this._appUserId)}async getCustomerInfo(){return await this._getCustomerInfoForUserId(this._appUserId)}getAppUserId(){return this._appUserId}async setAttributes(A){return await this.getCustomerInfo(),await this.backend.setAttributes(this._appUserId,A)}async changeUser(A){return k7(A),this._appUserId=A,this.eventsTracker.updateUser(A),this.inMemoryCache.invalidateAllCaches(),await this.getCustomerInfo()}logMissingProductIds(A,t){const i={};t.forEach(g=>i[g.identifier]=g);const n=[];A.forEach(g=>{i[g]===void 0&&n.push(g)}),n.length>0&&$i.debugLog(`Could not find product data for product ids:
        ${n.join()}.
        Please check that your product configuration is correct.`)}isSandbox(){return HF(this._API_KEY)||Ek(this._API_KEY)}isAnonymous(){return this._appUserId.startsWith(G7)}async getVirtualCurrencies(){return await this._getVirtualCurrenciesForUserId(this._appUserId)}getCachedVirtualCurrencies(){return this.inMemoryCache.getCachedVirtualCurrencies(this._appUserId,!0)}invalidateVirtualCurrenciesCache(){this.inMemoryCache.invalidateVirtualCurrenciesCache(this._appUserId)}close(){jr.instance===this?(this.eventsTracker&&this.eventsTracker.dispose(),jr.instance=void 0):$i.warnLog("Trying to close a Purchases instance that is not the current instance. Ignoring.")}async _getCustomerInfoForUserId(A){const t=await this.backend.getCustomerInfo(A);return BBA(t)}async _getVirtualCurrenciesForUserId(A){const t=this.inMemoryCache.getCachedVirtualCurrencies(A);if(t)return $i.debugLog("Vending VirtualCurrencies from cache."),t;const i=await this.backend.getVirtualCurrencies(A),n=EYA(i);return $i.debugLog("VirtualCurrencies updated from the network."),this.inMemoryCache.cacheVirtualCurrencies(A,n),n}static generateRevenueCatAnonymousAppUserId(){return`${G7}${w1().replace(/-/g,"")}`}_trackEvent(A){this.eventsTracker.trackExternalEvent(A)}};aK=_vA(),TvA(aK,1,"purchase",UBA,Qk),LvA(aK,Qk),Yt(Qk,"_platformInfo"),Yt(Qk,"instance");let gp=Qk;function QYA(e,A){const t=String(A||"");if(e==="web"&&!t.startsWith("web_")&&!t.startsWith("rcb"))throw new Error('RevenueCat Web requires a Web Billing key (starts with "web_"). Set VITE_RC_API_KEY_WEB.');e==="ios"&&!t.startsWith("appl_")&&console.warn('RevenueCat: expected iOS key to start with "appl_".'),e==="android"&&!t.startsWith("goog_")&&console.warn('RevenueCat: expected Android key to start with "goog_".')}function k1(e){const A=e==="web"?aGA:e==="ios"?IGA:rGA;if(!A)throw new Error(`RevenueCat SDK key missing for ${e}. Add VITE_RC_API_KEY_* and restart.`);return QYA(e,String(A)),String(A)}function vBA(e){const A=(e??"").toString().trim();if(!A||A==="[Not provided]")throw new Error("Invalid appUserID for RevenueCat.");if(A.length>255)throw new Error("appUserID too long for RevenueCat (max 255).");return A}let zl=null,op=null,sf=null;function MS(e){const A=(e??"").toString();return{length:A.length,empty:A.length===0}}function M1(e){return e?String(e).slice(0,4):null}async function uYA(e){return zl||op||(op=(async()=>{const A=Ui.getPlatform();if(console.debug("[RC] configureOnce platform:",A),A==="web"){const i=k1("web");if(typeof(gp==null?void 0:gp.configure)!="function")throw new Error("[RC] Web SDK load failed");try{console.debug("[RC] configure:begin",{platform:A,keyType:"web",keyPrefix:M1(i),appUserId:MS(e),observerMode:!1}),await gp.configure({apiKey:i,appUserId:e,observerMode:!1}),console.debug("[RC] configure:success",{platform:A});try{OF()}catch{}}catch(n){throw console.error("[RC] Web configure failed:",n),new Error("Purchases are temporarily paused.")}return zl={platform:"web",Purchases:gp},zl}const t=k1(A==="ios"?"ios":"android");try{const i=await Qi(()=>import("./index-DzdPQq_l.js"),__vite__mapDeps([9,1])),n=i==null?void 0:i.Purchases;if(!n||typeof n.configure!="function")throw new Error("Capacitor Purchases plugin not available. Did you run `npx cap sync ios`?");try{console.debug("[RC] configure:begin",{platform:A,keyType:A==="ios"?"ios":"android",keyPrefix:M1(t),appUserId:MS(e),observerMode:!1}),await n.configure({apiKey:t,appUserID:e,observerMode:!1}),console.debug("[RC] native configured on",A),console.debug("[RC] configure:success",{platform:A});try{OF()}catch{}}catch(g){throw console.error("[RC] Native configure failed:",g),new Error("Purchases are temporarily paused.")}return zl={platform:"native",Purchases:n},zl}catch(i){throw console.error("[RC] Failed to load native SDK:",i),i}})().catch(A=>{throw op=null,A}),op)}async function V8(e){const A=vBA(e),t=await uYA(A);if(sf!==A){try{const i=t.Purchases;typeof(i==null?void 0:i.logIn)=="function"&&(console.debug("[RC] identify:begin",{platform:Ui.getPlatform(),appUserId:MS(A)}),t.platform==="native"?await i.logIn({appUserID:A}):await i.logIn(A)),console.debug("[RC] logIn success"),console.debug("[RC] identify:done",{platform:Ui.getPlatform()});try{OF()}catch{}}catch(i){console.warn("[RC] logIn failed or unsupported:",i)}sf=A}return t}function dr(){const e=zl;if(!(e!=null&&e.Purchases)){if(Ui.getPlatform()==="web")try{const o=gp;if(typeof(o==null?void 0:o.getSharedInstance)=="function"){const s=o.getSharedInstance();if(s)return s}return null}catch{}return null}const A=Ui.getPlatform(),t=e.Purchases;function i(g){const o=Object.create(g);return typeof g.getOfferings=="function"&&(o.getOfferings=async()=>{var r,I,c;const s=A;let a=null;try{a=M1(k1(s==="ios"?"ios":s==="android"?"android":"web"))}catch{}console.debug("[RC] getOfferings:start",{platform:s,appTarget:qs,keyPrefix:a});try{const l=await g.getOfferings(),B=((r=l==null?void 0:l.current)==null?void 0:r.identifier)??(l==null?void 0:l.currentOfferingIdentifier)??null,Q=(((I=l==null?void 0:l.current)==null?void 0:I.availablePackages)??(l==null?void 0:l.availablePackages)??[]).length;return console.debug("[RC] getOfferings:success",{platform:s,currentId:B,pkgCount:Q}),l}catch(l){let B;try{B=((c=l==null?void 0:l.getErrorCode)==null?void 0:c.call(l))??(l==null?void 0:l.errorCode)??(l==null?void 0:l.code)}catch{}const Q={platform:s,appTarget:qs,offeringId:lL,chipsPackageId:BL,chipsProductId:EL,keyPrefix:a,errorCode:B,message:l==null?void 0:l.message};throw console.error("[RC] getOfferings:error",Q,l),l}}),o}if(A==="web"){if(typeof t.getSharedInstance=="function")try{const g=t.getSharedInstance();return i(g)}catch(g){return console.warn("[RC] getSharedInstance failed on web, falling back to module:",g),i(t)}return i(t)}const n=Object.create(t);return typeof t.purchasePackage=="function"&&(n.purchasePackage=g=>t.purchasePackage({aPackage:g})),i(n)}function OF(){const A={platform:Ui.getPlatform(),user:MS(sf),clientReady:!!zl,hasInitPromise:!!op,appTarget:qs,offeringId:lL,chipsPackageId:BL,chipsProductId:EL};console.debug("[RC] config:state",A);try{Nr.getInfo().then(t=>{console.debug("[RC] config:bundle",{appId:t==null?void 0:t.id,appName:t==null?void 0:t.name,version:t==null?void 0:t.version,build:t==null?void 0:t.build})}).catch(()=>{})}catch{}}async function Hh(){if(!sf)throw new Error("Cannot reconfigure RevenueCat before user identification.");return zl=null,op=null,V8(sf)}async function KBA(e){const A=vBA(e),t=zl;if(!t){console.warn("[RC] loginRevenueCat called before SDK initialized");return}try{const i=t.Purchases;typeof(i==null?void 0:i.logIn)=="function"?(console.debug("[RC] loginRevenueCat:begin",{newUser:MS(A),previousUser:MS(sf)}),t.platform==="native"?await i.logIn({appUserID:A}):await i.logIn(A),console.debug("[RC] loginRevenueCat:success"),sf=A):console.warn("[RC] logIn method not available on Purchases SDK")}catch(i){throw console.error("[RC] loginRevenueCat failed:",i),i}}const dYA=Object.freeze(Object.defineProperty({__proto__:null,getPurchases:dr,initRevenueCat:V8,logRevenueCatConfig:OF,loginRevenueCat:KBA,reconfigureRevenueCat:Hh},Symbol.toStringTag,{value:"Module"})),wb="rc_anonymous_device_id";async function hYA(){if(Ui.isNativePlatform())try{const{SecureStoragePlugin:A}=await Qi(async()=>{const{SecureStoragePlugin:i}=await Promise.resolve().then(()=>PGA);return{SecureStoragePlugin:i}},void 0);try{const{value:i}=await A.get({key:wb});if(i&&i.length>10)return i}catch{}const t=`anon_${crypto.randomUUID()}`;return await A.set({key:wb,value:t}),console.log("[anonymousId] Created new anonymous device ID"),t}catch(A){console.warn("[anonymousId] SecureStorage failed, falling back to localStorage",A)}try{const A=localStorage.getItem(wb);if(A&&A.length>10)return A;const t=`anon_${crypto.randomUUID()}`;return localStorage.setItem(wb,t),console.log("[anonymousId] Created new anonymous device ID (localStorage)"),t}catch{return console.warn("[anonymousId] All storage failed, using ephemeral ID"),`anon_ephemeral_${crypto.randomUUID()}`}}function b7(e){return e.startsWith("anon_")}const Ly={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_TARGET:"zentara",VITE_OTA:"1"},U7=lL,pYA=BL,v7=EL,K7=t8,FBA=String(CGA).toLowerCase()==="true",rK={0:"UnknownError",1:"UserCancelledError",2:"StoreProblemError",3:"PurchaseNotAllowedError",4:"PurchaseInvalidError",5:"ProductNotAvailableForPurchaseError",6:"ProductAlreadyPurchasedError",7:"ReceiptAlreadyInUseError",8:"InvalidReceiptError",9:"MissingReceiptFileError",10:"NetworkError",11:"InvalidCredentialsError",12:"UnexpectedBackendResponseError",14:"InvalidAppUserIdError",15:"OperationAlreadyInProgressError",16:"UnknownBackendError"};function D2(e,A){var t,i,n;try{const g=((t=A==null?void 0:A.getErrorCode)==null?void 0:t.call(A))??(A==null?void 0:A.errorCode)??(A==null?void 0:A.code),o=typeof g=="number"?rK[g]||`Code${g}`:"Unknown",s=((i=A==null?void 0:A.extra)==null?void 0:i.backendErrorCode)??((n=A==null?void 0:A.extra)==null?void 0:n.code)??(A==null?void 0:A.backendErrorCode),a=(A==null?void 0:A.underlyingErrorMessage)||(A==null?void 0:A.nativeStack)||(A==null?void 0:A.stack),r=(A==null?void 0:A.message)||String(A);if(console.error(`${e} failed`,{code:g,name:o,backendErrorCode:s,message:r,underlying:a}),FBA){const I=A!=null&&A.extra?{...A.extra}:void 0;console.debug("[RC] raw error (trimmed):",{keys:Object.keys(A||{}),extra:I,err:A})}}catch(g){console.error(`${e} failed (and logging failed)`,g)}}const _BA=E.createContext({rc:null,ready:!1,error:null,isPremium:!1,anonymousBalance:null,buyChips:async()=>{},buySubscription:async()=>{},restorePurchases:async()=>{}});function fYA({children:e}){const{user:A,refreshUser:t}=tn(),[i,n]=E.useState(null),[g,o]=E.useState(!1),[s,a]=E.useState(null),[r,I]=E.useState(!1),[c,l]=E.useState(null),B=E.useRef(null),Q=E.useCallback(()=>{try{t()}catch{}try{setTimeout(()=>{t().catch(()=>{})},1200)}catch{}},[t]);E.useEffect(()=>{let b=!1;return(async()=>{o(!1),a(null);try{const _=(A==null?void 0:A.id)??await hYA(),K=B.current;if(A!=null&&A.id&&K&&b7(K)&&K!==A.id){console.log("[RevenueCat] User logged in, transferring purchases from anonymous ID");try{await KBA(A.id),B.current=A.id;try{const x=(Ly==null?void 0:Ly.VITE_API_URL)||"",{getToken:T}=await Qi(async()=>{const{getToken:aA}=await Promise.resolve().then(()=>jGA);return{getToken:aA}},void 0),z=await T(),eA=await(await fetch(`${x}/api/account/merge-anonymous`,{method:"POST",headers:{"Content-Type":"application/json",...z?{Authorization:`Bearer ${z}`}:{}},credentials:"include",body:JSON.stringify({anonymousId:K})})).json().catch(()=>({}));eA!=null&&eA.ok&&(eA==null?void 0:eA.mergedBalance)>0&&console.log(`[RevenueCat] Merged ${eA.mergedBalance} chips from anonymous account`)}catch(x){console.warn("[RevenueCat] Failed to merge anonymous balance:",x)}Q()}catch(x){console.warn("[RevenueCat] Failed to transfer anonymous purchases:",x)}}const J=await V8(_);B.current=_;let q=!1;const v=1e3,U=Date.now();for(;!b;){const T=dr()||(J==null?void 0:J.Purchases);if(T&&(typeof T.purchasePackage=="function"||typeof T.getOfferings=="function")){q=!0;break}if(Date.now()-U>v)break;await new Promise(z=>setTimeout(z,50))}!q&&(J==null?void 0:J.platform)==="web"&&(q=!0),b||(n(J),o(q))}catch(_){b||(a((_==null?void 0:_.message)||"Purchases are temporarily paused. Please try again later."),o(!1))}})(),()=>{b=!0}},[A==null?void 0:A.id,Q]);const h=E.useCallback(async()=>{var b;try{const _=dr();if(!(_!=null&&_.getCustomerInfo))return;const K=await _.getCustomerInfo(),J=((b=K==null?void 0:K.entitlements)==null?void 0:b.active)||{},q=Object.keys(J).length>0;let v=!1;K7&&(v=!!(J!=null&&J[K7])||q),I(v)}catch{}},[]);E.useEffect(()=>{if(!g)return;h();const b=setInterval(h,6e4);return()=>clearInterval(b)},[g,h]);const d=E.useCallback(async()=>{if(A!=null&&A.id){l(null);return}const b=B.current;if(!b||!b7(b)){l(null);return}try{const _=(Ly==null?void 0:Ly.VITE_API_URL)||"",J=await(await fetch(`${_}/api/account/anonymous-balance?id=${encodeURIComponent(b)}`)).json().catch(()=>({}));J!=null&&J.ok&&typeof J.balance=="number"&&l(J.balance)}catch{}},[A==null?void 0:A.id]);E.useEffect(()=>{g&&d()},[g,d]);const p=E.useCallback(b=>{var _,K;return(_=b==null?void 0:b.all)!=null&&_[U7]?b.all[U7]:(b==null?void 0:b.current)||((K=b==null?void 0:b.all)==null?void 0:K.default)||null},[]),y=E.useCallback(b=>{var q,v;const _=[],K=U=>{var x;if(Array.isArray(U))for(const T of U){const z=(T==null?void 0:T.identifier)||((x=T==null?void 0:T.product)==null?void 0:x.identifier);z&&(_.find(Z=>{var eA;return((Z==null?void 0:Z.identifier)||((eA=Z==null?void 0:Z.product)==null?void 0:eA.identifier))===z})||_.push(T))}};K(((q=b==null?void 0:b.current)==null?void 0:q.availablePackages)||((v=b==null?void 0:b.current)==null?void 0:v.packages));const J=(b==null?void 0:b.all)||{};return Object.keys(J).forEach(U=>{var x,T;K(((x=J[U])==null?void 0:x.availablePackages)||((T=J[U])==null?void 0:T.packages))}),_},[]),m=b=>{var v,U,x,T,z,Z,eA;const _=b==null?void 0:b.packageType,K=String(((v=b==null?void 0:b.product)==null?void 0:v.type)||"").toUpperCase(),J=String(((U=b==null?void 0:b.product)==null?void 0:U.identifier)||(b==null?void 0:b.identifier)||""),q=String(((x=b==null?void 0:b.product)==null?void 0:x.title)||((T=b==null?void 0:b.product)==null?void 0:T.displayName)||"");return _==="MONTHLY"||_==="ANNUAL"||_==="SIX_MONTH"||_==="THREE_MONTH"||_==="TWO_MONTH"||K==="SUBSCRIPTION"||K==="SUBS"||K==="AUTO_RENEWABLE_SUBSCRIPTION"||!!((z=b==null?void 0:b.product)!=null&&z.subscriptionPeriod)||!!((Z=b==null?void 0:b.product)!=null&&Z.defaultSubscriptionOption)||!!((eA=b==null?void 0:b.product)!=null&&eA.subscriptionOptions)||/(month|year|annual|week|sub|subscription|premium|vip|membership|pro)/i.test(J)||/(month|year|annual|week|subscription|premium|vip|membership|pro)/i.test(q)},D=b=>{var J;const _=(J=b==null?void 0:b.product)==null?void 0:J.type,K=b==null?void 0:b.packageType;return!m(b)||_==="NON_SUBSCRIPTION"||_==="NON_CONSUMABLE"||K==="LIFETIME"},S=E.useCallback(b=>{const _=p(b),K=y(b);FBA&&(console.debug("[RC] offerings(off):",_),console.debug("[RC] packages:",K)),/\s/.test(String(v7))&&console.warn("[RC] VITE_RC_CHIPS_PRODUCT_ID contains whitespace; verify product identifier in constants.ts matches App Store/Play Console (no spaces).");{const v=K.find(U=>(U==null?void 0:U.identifier)===pYA);if(v)return v}{const v=K.find(U=>{var x;return((x=U==null?void 0:U.product)==null?void 0:x.identifier)===v7});if(v)return v}const J=K.find(v=>D(v));if(J)return J;const q=(_==null?void 0:_.availablePackages)||(_==null?void 0:_.packages)||[];return Array.isArray(q)&&q.length>0?q[0]:K[0]||null},[y,p]),k=E.useCallback(b=>{const _=p(b),K=y(b),J=z=>{var aA,sA,pA;const Z=String((z==null?void 0:z.identifier)||((aA=z==null?void 0:z.product)==null?void 0:aA.identifier)||""),eA=String(((sA=z==null?void 0:z.product)==null?void 0:sA.title)||((pA=z==null?void 0:z.product)==null?void 0:pA.displayName)||"");return`${Z} ${eA}`},q=K.find(z=>(z==null?void 0:z.packageType)==="MONTHLY")||K.find(z=>((z==null?void 0:z.identifier)||"").toLowerCase().includes("month"));if(q)return q;const v=K.find(z=>(z==null?void 0:z.packageType)==="ANNUAL")||K.find(z=>((z==null?void 0:z.identifier)||"").toLowerCase().includes("year"));if(v)return v;const U=K.find(z=>m(z));if(U)return U;const x=K.find(z=>/(month|year|annual|week|subscription|premium|vip|membership|pro)/i.test(J(z)));if(x)return x;const T=(_==null?void 0:_.availablePackages)||(_==null?void 0:_.packages)||[];return Array.isArray(T)&&T.length>0?T[0]:K[0]||null},[y,p]),N=E.useCallback(async()=>{var J,q;if(!g)throw new Error("RevenueCat not ready");let b=dr();if(!(b!=null&&b.getOfferings)||!(b!=null&&b.purchasePackage))try{await Hh(),b=dr()}catch{}if(!(b!=null&&b.getOfferings)||!(b!=null&&b.purchasePackage))throw new Error("Purchases not initialized. Please ensure the app is logged in and RevenueCat has finished initializing (iOS may need a moment after app launch).");const _=await b.getOfferings(),K=S(_);if(!K){const v=y(_);throw console.error("[RC] No chips package found. offerings.current:",_==null?void 0:_.current,"offerings.all keys:",Object.keys((_==null?void 0:_.all)||{}),"packages found:",v.map(U=>{var x,T;return{identifier:U==null?void 0:U.identifier,productId:(x=U==null?void 0:U.product)==null?void 0:x.identifier,type:(T=U==null?void 0:U.product)==null?void 0:T.type,packageType:U==null?void 0:U.packageType}})),new Error("No chips product configured")}try{try{await b.purchasePackage(K),Q(),d()}catch(v){const U=String((v==null?void 0:v.message)||v);if(/already been destroyed/i.test(U))try{await Hh();const x=dr();if(!(x!=null&&x.purchasePackage))throw v;await x.purchasePackage(K),Q(),d();return}catch{}throw v}}catch(v){D2("[RC] purchasePackage(chips)",v);const U=((J=v==null?void 0:v.getErrorCode)==null?void 0:J.call(v))??(v==null?void 0:v.errorCode)??(v==null?void 0:v.code),x=typeof U=="number"?rK[U]||`Code${U}`:"Unknown",T=((q=v==null?void 0:v.extra)==null?void 0:q.backendErrorCode)??(v==null?void 0:v.backendErrorCode),z=T===7773?" Payment gateway communication error. On web, verify RevenueCat Web Billing is connected to Stripe and the product has a Web price; then retry.":"";throw new Error(`Purchase failed (${x}${typeof U=="number"?` ${U}`:""}${T?` | backend ${T}`:""}).${z}`)}},[g,S,y,Q,d]),G=E.useCallback(async()=>{var J,q;if(!g)throw new Error("RevenueCat not ready");let b=dr();if(!(b!=null&&b.getOfferings)||!(b!=null&&b.purchasePackage))try{await Hh(),b=dr()}catch{}if(!(b!=null&&b.getOfferings)||!(b!=null&&b.purchasePackage))throw new Error("Purchases not initialized");let _=await b.getOfferings(),K=k(_);if(!K)try{await new Promise(v=>setTimeout(v,350)),_=await b.getOfferings(),K=k(_)}catch{}if(!K)try{await Hh();const v=dr();v!=null&&v.getOfferings&&(b=v,_=await v.getOfferings(),K=k(_))}catch{}if(!K)throw console.error("[RC] No subscription package found. Offerings:",_),new Error("No subscription package available");try{try{await b.purchasePackage(K),Q(),h()}catch(v){const U=String((v==null?void 0:v.message)||v);if(/already been destroyed/i.test(U))try{await Hh();const x=dr();if(!(x!=null&&x.purchasePackage))throw v;await x.purchasePackage(K),Q(),h();return}catch{}throw v}}catch(v){D2("[RC] purchasePackage(subscription)",v);const U=((J=v==null?void 0:v.getErrorCode)==null?void 0:J.call(v))??(v==null?void 0:v.errorCode)??(v==null?void 0:v.code),x=typeof U=="number"?rK[U]||`Code${U}`:"Unknown",T=((q=v==null?void 0:v.extra)==null?void 0:q.backendErrorCode)??(v==null?void 0:v.backendErrorCode),z=T===7773?" Payment gateway communication error. Ensure Stripe is connected in RevenueCat Web Billing and the subscription has Web pricing.":"";throw new Error(`Subscription purchase failed (${x}${typeof U=="number"?` ${U}`:""}${T?` | backend ${T}`:""}).${z}`)}},[g,k,Q,h]),M=E.useCallback(async()=>{var _,K,J;if(!g)throw new Error("RevenueCat not ready");let b=dr();if(!(b!=null&&b.getCustomerInfo)||!(b!=null&&b.syncPurchases))try{await Hh(),b=dr()}catch{}try{const q=await((_=b==null?void 0:b.getCustomerInfo)==null?void 0:_.call(b));if(!(b!=null&&b.syncPurchases))throw new Error("Restore Purchases not initialized");await(b==null?void 0:b.syncPurchases()),Q(),h(),d()}catch(q){D2("[RC] restorePurchases",q);const v=((K=q==null?void 0:q.getErrorCode)==null?void 0:K.call(q))??(q==null?void 0:q.errorCode)??(q==null?void 0:q.code),U=typeof v=="number"?rK[v]||`Code${v}`:"Unknown",x=((J=q==null?void 0:q.extra)==null?void 0:J.backendErrorCode)??(q==null?void 0:q.backendErrorCode);throw new Error(`Restore failed (${U}${typeof v=="number"?` ${v}`:""}${x?` | backend ${x}`:""}).`)}},[g,Q,h,d]),w=E.useMemo(()=>({rc:i,ready:g,error:s,isPremium:r,anonymousBalance:c,buyChips:N,buySubscription:G,restorePurchases:M}),[i,g,s,r,c,N,G,M]);return C.jsx(_BA.Provider,{value:w,children:e})}function JBA(){return E.useContext(_BA)}function yYA({viral:e,onClose:A}){return e?C.jsx("div",{className:"viral-container",children:C.jsxs("div",{className:"viral-content",children:[C.jsx("img",{src:e.preview,alt:"Preview",className:"viral-preview",style:{width:e.width,height:e.height}}),C.jsx("video",{src:e.url,autoPlay:!0,loop:!0,muted:!0,className:"viral-video",style:{width:e.width,height:e.height}})]})}):null}const X8="/assets/avatars-BLAbFok_.webp",$8="/assets/avatars2-BhCQ9Hmk.webp",A5="/assets/bikini_avatars-D9_A_byG.webp",e5="/assets/bikini_avatars2-CqEDCn9Y.webp",t5="/assets/car_avatars-C2asmsaV.webp",i5="/assets/cowboy_avatars-Dh4o-H8O.webp",n5="/assets/surf_avatars-BNzNQWcq.webp",g5="/assets/surf_avatars2-CP3KwVoE.webp",o5="/assets/toy_avatars-CYoTJdP7.webp",LBA="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'%20style='height:%20512px;%20width:%20512px;'%3e%3cg%20class=''%20transform='translate(0,0)'%20style=''%3e%3cpath%20d='M74.5%2036A38.5%2038.5%200%200%200%2036%2074.5v363A38.5%2038.5%200%200%200%2074.5%20476h363a38.5%2038.5%200%200%200%2038.5-38.5v-363A38.5%2038.5%200%200%200%20437.5%2036h-363zM256%20206a50%2050%200%200%201%200%20100%2050%2050%200%200%201%200-100z'%20fill='%23fff'%20fill-opacity='1'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",xBA="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'%20style='height:%20512px;%20width:%20512px;'%3e%3cg%20class=''%20transform='translate(0,0)'%20style=''%3e%3cpath%20d='M74.5%2036A38.5%2038.5%200%200%200%2036%2074.5v363A38.5%2038.5%200%200%200%2074.5%20476h363a38.5%2038.5%200%200%200%2038.5-38.5v-363A38.5%2038.5%200%200%200%20437.5%2036h-363zm316.97%2036.03A50%2050%200%200%201%20440%20122a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zm-268%20268A50%2050%200%200%201%20172%20390a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97z'%20fill='%23fff'%20fill-opacity='1'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",TBA="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'%20style='height:%20512px;%20width:%20512px;'%3e%3cg%20class=''%20transform='translate(0,0)'%20style=''%3e%3cpath%20d='M74.5%2036A38.5%2038.5%200%200%200%2036%2074.5v363A38.5%2038.5%200%200%200%2074.5%20476h363a38.5%2038.5%200%200%200%2038.5-38.5v-363A38.5%2038.5%200%200%200%20437.5%2036h-363zm316.97%2036.03A50%2050%200%200%201%20440%20122a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zM256%20206a50%2050%200%200%201%200%20100%2050%2050%200%200%201%200-100zM123.47%20340.03A50%2050%200%200%201%20172%20390a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97z'%20fill='%23fff'%20fill-opacity='1'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",qBA="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'%20style='height:%20512px;%20width:%20512px;'%3e%3cg%20class=''%20transform='translate(0,0)'%20style=''%3e%3cpath%20d='M74.5%2036A38.5%2038.5%200%200%200%2036%2074.5v363A38.5%2038.5%200%200%200%2074.5%20476h363a38.5%2038.5%200%200%200%2038.5-38.5v-363A38.5%2038.5%200%200%200%20437.5%2036h-363zm48.97%2036.03A50%2050%200%200%201%20172%20122a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zm268%200A50%2050%200%200%201%20440%20122a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zm-268%20268A50%2050%200%200%201%20172%20390a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zm268%200A50%2050%200%200%201%20440%20390a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97z'%20fill='%23fff'%20fill-opacity='1'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",YBA="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'%20style='height:%20512px;%20width:%20512px;'%3e%3cg%20class=''%20transform='translate(0,0)'%20style=''%3e%3cpath%20d='M74.5%2036A38.5%2038.5%200%200%200%2036%2074.5v363A38.5%2038.5%200%200%200%2074.5%20476h363a38.5%2038.5%200%200%200%2038.5-38.5v-363A38.5%2038.5%200%200%200%20437.5%2036h-363zm48.97%2036.03A50%2050%200%200%201%20172%20122a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zm268%200A50%2050%200%200%201%20440%20122a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zM256%20206a50%2050%200%200%201%200%20100%2050%2050%200%200%201%200-100zM123.47%20340.03A50%2050%200%200%201%20172%20390a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zm268%200A50%2050%200%200%201%20440%20390a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97z'%20fill='%23fff'%20fill-opacity='1'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",HBA="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'%20style='height:%20512px;%20width:%20512px;'%3e%3cg%20class=''%20transform='translate(0,0)'%20style=''%3e%3cpath%20d='M74.5%2036A38.5%2038.5%200%200%200%2036%2074.5v363A38.5%2038.5%200%200%200%2074.5%20476h363a38.5%2038.5%200%200%200%2038.5-38.5v-363A38.5%2038.5%200%200%200%20437.5%2036h-363zm48.97%2036.03A50%2050%200%200%201%20172%20122a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zm268%200A50%2050%200%200%201%20440%20122a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zM122%20206a50%2050%200%200%201%200%20100%2050%2050%200%200%201%200-100zm268%200a50%2050%200%200%201%200%20100%2050%2050%200%200%201%200-100zM123.47%20340.03A50%2050%200%200%201%20172%20390a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97zm268%200A50%2050%200%200%201%20440%20390a50%2050%200%200%201-100%200%2050%2050%200%200%201%2051.47-49.97z'%20fill='%23fff'%20fill-opacity='1'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",DYA=0,mYA=2500,$o={diceRevealDelayMs:DYA,diceSettleClientMs:mYA,fairnessVerifyDelayMs:120,diceToChipDelayMs:1800,chipFlyDurationMs:900,chipStaggerMs:180,chipPostBufferMs:120,scrollNextDelayMs:600,scrollRoundEndDelayMs:1600,scrollMinWaitForChips:!0,betSnapshotDelayMs:100,balanceDelayMs:500,settledAllDelayMs:100,mySettledDelayMs:100,settleDetectDelayMs:50,flash:{baseMs:1e3,winMs:3500,ceeLoShortMs:1500},revealFlashPostDelayMs:100},PF=[X8,$8,A5,e5,t5,i5,n5,g5,o5];function SYA(e){if(!e||!e.startsWith("sprite:"))return null;const A=e.slice(7).split("/"),t=Number(A[0]),i=Number(A[1]);return!Number.isFinite(t)||!Number.isFinite(i)||t<0||t>=PF.length?null:{sheetIdx:t,tile:i%6}}function wYA(e){let A=0;for(let t=0;t<e.length;t++)A=A*31+e.charCodeAt(t)>>>0;return A%(PF.length*6)}function kYA(e,A){const t=SYA(e);if(t){const{sheetIdx:p,tile:y}=t,m=PF[p],D=2,S=3,k=y%D,N=Math.floor(y/D),G=D*100,M=p===4?400:S*100,w=G/100,b=M/100,_=k/(w-1)*100,K=p===8?N*37:b>1?N/(b-1)*100:0;return C.jsx("span",{className:"flash-avatar__sprite",style:{backgroundImage:`url(${m})`,backgroundSize:`${G}% ${M}%`,backgroundPosition:`${_}% ${K}%`},"aria-hidden":!0})}if(e)return C.jsx("img",{src:e,alt:A,className:"flash-avatar__img"});const i=wYA(A),n=Math.floor(i/6),g=i%6,o=PF[n],s=2,a=3,r=g%s,I=Math.floor(g/s),c=s*100,l=n===4?400:a*100,B=c/100,Q=l/100,h=r/(B-1)*100,d=n===8?I*37:Q>1?I/(Q-1)*100:0;return C.jsx("span",{className:"flash-avatar__sprite",style:{backgroundImage:`url(${o})`,backgroundSize:`${c}% ${l}%`,backgroundPosition:`${h}% ${d}%`},"aria-hidden":!0})}const MYA={1:LBA,2:xBA,3:TBA,4:qBA,5:YBA,6:HBA};function OBA(e){const A=/[⚀⚁⚂⚃⚄⚅]+/,t=e.match(A);if(!t)return e;const i=t[0],n=e.slice(t.index+i.length).trim(),g=[...i].map(o=>o.codePointAt(0)-9855);return C.jsxs("span",{className:"flash-dice-result",children:[C.jsx("span",{className:"flash-dice-faces",children:g.map((o,s)=>C.jsx("img",{src:MYA[o],alt:`Dice ${o}`,className:"flash-die-face"},s))}),n&&C.jsx("span",{className:"flash-dice-label",children:n})]})}let kb=null;async function PBA(){if(kb)return kb;const e=await Qi(()=>import("./lottie-C93ZSGQd.js").then(A=>A.l),[]);return kb=e!=null&&e.default&&e.default.loadAnimation?e.default:e,kb}let Mb=null,Nb=null;async function N1(e){if(e==="win"&&Mb)return Mb;if(e==="lose"&&Nb)return Nb;if(e==="win"){const A=await Qi(()=>import("./winning-lottie-CvaS4ZrO.js"),[]);return Mb=A.default||A,Mb}else{const A=await Qi(()=>import("./lose-lottie-C7Ut5v-G.js"),[]);return Nb=A.default||A,Nb}}const s5=E.createContext(null),NYA={win:void 0,lose:void 0,push:void 0,roll:void 0,info:void 0},RYA=typeof window<"u"&&window.requestIdleCallback||(e=>setTimeout(e,50));function GYA(){if(typeof navigator>"u")return!1;const e=navigator.userAgent||"",A=navigator;return/iP(ad|hone|od)/.test(e)||A.platform==="MacIntel"&&A.maxTouchPoints>1}function F7(){RYA(async()=>{try{await PBA(),await Promise.allSettled([N1("win"),N1("lose")])}catch{}})}function _7(){var e,A,t;try{const i=document==null?void 0:document.body,n=!!((e=i==null?void 0:i.classList)!=null&&e.contains("page-poker-room")),g=!!document.querySelector(".mode-craps"),o=!!((A=i==null?void 0:i.classList)!=null&&A.contains("page-gameroom")&&!g),s=!!((t=i==null?void 0:i.classList)!=null&&t.contains("page-zentara"));return{isPoker:n,isCraps:g,isCeeLo:o,isZentara:s}}catch{return{isPoker:!1,isCraps:!1,isCeeLo:!1,isZentara:!1}}}function bYA(e,A,t,i){return typeof A=="boolean"?A:i?!1:e==="lose"&&typeof t!="number"}function UYA(e,A){if(!e)return!1;const t=e.kind==="roll"&&typeof e.title=="string"&&/\bpoint\b/i.test(e.title||"");return e.kind==="roll"&&typeof e.title=="string"&&/\bbanker\b/i.test(e.title||"")&&/\bpoint\b/i.test(e.title||""),A.isPoker||A.isCraps&&(e.kind==="win"||e.kind==="lose"||t)||A.isCeeLo&&(e.kind==="win"||e.kind==="lose"||e.kind==="push")}function vYA(){try{return document.querySelector(".card.player-panel, .card.craps-player-panel, .card.skills-player-panel")}catch{return null}}function m2(e){return typeof e!="string"?e:/[⚀⚁⚂⚃⚄⚅]/.test(e)?OBA(e):jBA(e)}function jBA(e){if(typeof e!="string")return e;const A=e,t=[];let i=0;for(let n=0;n<A.length;n++){const g=A[n];if(g==="Z"||g==="z"){let o=n+1;for(;o<A.length&&(A[o]===" "||A[o]===" "||A[o]===" ");)o++;if(o<A.length&&/\d/.test(A[o])){t.push(C.jsx("span",{style:{textTransform:"none"},children:"z"},`z-${n}-${i++}`));continue}}t.push(g)}return C.jsx(C.Fragment,{children:t})}function KYA(){E.useEffect(()=>{if(F7(),typeof window>"u")return;const e=()=>{F7(),window.removeEventListener("touchstart",e,!0),window.removeEventListener("pointerdown",e,!0)};return window.addEventListener("touchstart",e,!0),window.addEventListener("pointerdown",e,!0),()=>{window.removeEventListener("touchstart",e,!0),window.removeEventListener("pointerdown",e,!0)}},[])}function FYA(e,A,t){E.useEffect(()=>{if(typeof A!="number"||A<0)return;const i=window.setTimeout(()=>t(),A);return()=>window.clearTimeout(i)},[A,t])}function _YA(e){E.useEffect(()=>{let A=!1;const t=async()=>{try{if(!f8())try{await On()}catch{}const n=e==="win"?["winDing","win"]:e==="lose"?["lose"]:e==="push"?["push"]:[];if(n.length){try{mS(n)}catch{}try{await kF(n,600)}catch{}}if(A)return;e==="lose"?y8({volume:.06}):e==="win"?lvA({volume:.25}):e==="push"&&GcA({volume:.04})}catch{}},i=window.setTimeout(()=>{t()},10);return()=>{A=!0,window.clearTimeout(i)}},[e])}function JYA(e){const{enabled:A,kind:t,targetRef:i,animationData:n,fallbackMap:g,isIOS:o,onComplete:s}=e,a=E.useRef(null);E.useEffect(()=>{if(!A||t!=="win"&&t!=="lose")return;let r=!1;return(async()=>{try{const I=await PBA(),c=n||(t?g[t]:void 0)||await N1(t);if(r||!i.current||!c)return;a.current=I.loadAnimation({container:i.current,renderer:o?"canvas":"svg",autoplay:!0,loop:!1,animationData:c,subframe:!1,rendererSettings:{progressiveLoad:!0,hideOnTransparent:!0,preserveAspectRatio:"xMidYMid meet",dpr:Math.min(window.devicePixelRatio||1,1.5)}}),s&&a.current.addEventListener("complete",s)}catch{}})(),()=>{var I,c,l;r=!0;try{s&&a.current&&((c=(I=a.current).removeEventListener)==null||c.call(I,"complete",s)),(l=a.current)==null||l.destroy()}catch{}a.current=null,i.current&&(i.current.innerHTML="")}},[A,t,n,g,o,s,i])}function LYA({item:e,onDone:A,animations:t,zIndex:i}){const n=E.useRef(null),g=E.useRef(null),[o,s]=E.useState("enter"),a=E.useRef(!1),r=E.useCallback(()=>{a.current||(a.current=!0,A(e.id))},[A,e.id]),I=E.useCallback(()=>{s("leave"),window.setTimeout(r,320)},[r]);_YA(e.kind),FYA(e.id,e.duration,I);const c=E.useMemo(GYA,[]),l=e.kind==="win"||e.kind==="lose";JYA({enabled:l,kind:e.kind,targetRef:g,animationData:e.animationData,fallbackMap:t,isIOS:c,onComplete:l&&e.autoDismissOnComplete?()=>{I()}:void 0});const B=e.title&&typeof e.title=="string"&&e.title.includes(":")?(()=>{const h=e.title.indexOf(":"),d=e.title.slice(0,h).trim(),p=e.title.slice(h+1).trim();return C.jsxs(C.Fragment,{children:[C.jsx("span",{className:"flash-title__name",children:d}),C.jsx("span",{className:"flash-title__rest",children:m2(p)})]})})():C.jsx("span",{children:jBA(e.title)}),Q=typeof e.title=="string"&&/\bbanker\b/i.test(e.title)?{opacity:.9}:void 0;return C.jsxs("div",{ref:n,className:["flash-card",`flash-${e.kind??"info"}`,o==="leave"?"leave":o==="steady"?"steady":"enter"].join(" "),role:"status","data-testid":"flash-card","data-flash-kind":e.kind??"info",onClick:()=>e.dismissible&&I(),onAnimationEnd:h=>{h.target===n.current&&(o==="enter"&&s("steady"),o==="leave"&&r())},onTransitionEnd:h=>{h.target===n.current&&o==="leave"&&r()},style:{pointerEvents:"auto",zIndex:i},children:[(e.kind==="lose"||e.kind==="win")&&C.jsx("div",{className:"flash-lottie",ref:g}),e.icon&&C.jsx("div",{className:"flash-icon","aria-hidden":!0,children:e.icon}),C.jsxs("div",{className:"flash-body",children:[e.title&&C.jsx("div",{className:"flash-title"+(typeof e.title=="string"&&/\bbanker\b/i.test(e.title)?" flash-title--banker":""),"data-testid":"flash-title",style:Q,children:B}),e.subtitle&&C.jsx("div",{className:"flash-subtitle","data-testid":"flash-subtitle",children:typeof e.subtitle=="string"&&e.subtitle.includes(`
`)?e.subtitle.split(`
`).map((h,d)=>{var y;const p=h.indexOf(":");if(p>0){const m=h.slice(0,p).trim(),D=h.slice(p+1).trim(),S=(y=e.playerAvatars)==null?void 0:y[d];return C.jsxs("span",{className:"flash-subtitle__player",children:[C.jsx("span",{className:"flash-avatar",children:kYA(S==null?void 0:S.avatarUrl,m)}),C.jsx("strong",{className:"flash-subtitle__name",children:m}),C.jsx("span",{className:"flash-subtitle__result",children:OBA(D)})]},d)}return C.jsx("span",{children:m2(h)},d)}):m2(e.subtitle)}),e.viral&&C.jsx(yYA,{viral:e.viral,onClose:()=>{}})]})]})}function xYA({children:e,baseDurationMs:A=$o.flash.baseMs}){const[t,i]=E.useState([]),n=E.useRef(new Set),g=E.useRef({...NYA}),o=E.useRef(""),s=E.useRef(0);KYA();const a=E.useCallback(Q=>{i(h=>h.filter(d=>d.id!==Q))},[]),r=E.useCallback(()=>{i([])},[]),I=E.useCallback(Q=>{g.current={...g.current,...Q}},[]),c=E.useCallback(Q=>{var k;const h=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,d=typeof document<"u"?_7():{isCraps:!1,isCeeLo:!1},p=d.isCeeLo,y=typeof Q.duration=="number"?Q.duration:p&&(Q.kind==="win"||Q.kind==="lose")?$o.flash.ceeLoShortMs:Q.kind==="win"?$o.flash.winMs:Q.kind==="info"&&Q.subtitle?Math.max(A,1500+((((k=Q.title)==null?void 0:k.length)??0)+(typeof Q.subtitle=="string"?Q.subtitle.length:0))*30):A,m={id:h,dismissible:!0,autoDismissOnComplete:bYA(Q.kind,Q.autoDismissOnComplete,Q.duration,p),...Q,duration:y};p&&!m.subtitle&&(m.kind==="win"||m.kind==="lose"||m.kind==="push")&&(m.kind==="push"?m.subtitle="No Action":m.subtitle=m.kind==="win"?"You win this round":"You lose this round");const D=`${m.kind}|${m.title}|${m.subtitle??""}`,S=Date.now();if(D===o.current&&S-s.current<2e3)return h;o.current=D,s.current=S,console.log("[FlashOverlay] show()",{kind:m.kind,title:m.title,subtitle:m.subtitle,isCeeLo:p});try{const N=typeof location<"u"?new URLSearchParams(location.search):null;if(N&&N.get("flashDebug")==="1")try{localStorage.setItem("debug:flashes","1")}catch{}const G=typeof window<"u"?window:void 0;(!!(G!=null&&G.FLASH_DEBUG)||typeof localStorage<"u"&&localStorage.getItem("debug:flashes")==="1")&&p&&console.debug("[flash]",{kind:m.kind,title:m.title,subtitle:m.subtitle})}catch{}if(Q.kind==="info"||Q.kind==="roll")try{Vl({volume:.15})}catch{}return i(N=>d.isCraps?[m]:[...N,m]),h},[A]);E.useEffect(()=>{if(t.length!==0||!n.current.size)return;const Q=Array.from(n.current);n.current.clear(),Q.forEach(h=>{try{h()}catch{}})},[t.length]);const l=E.useMemo(()=>{var Q;return{show:c,roll:(h,d)=>c({kind:"roll",title:h,subtitle:d}),rollNow:(h,d)=>c({kind:"roll",title:h,subtitle:d}),win:(h,d,p,y,m)=>(Qi(()=>import("./InAppReviewService-Dr8bYv2x.js"),__vite__mapDeps([10,1])).then(D=>D.maybePromptReview()).catch(()=>{}),c({kind:"win",title:h,subtitle:d,viral:p,animationData:y,...m})),lose:(h,d,p,y,m)=>c({kind:"lose",title:h,subtitle:d,viral:p,animationData:y,...m}),push:(h,d,p,y,m)=>c({kind:"push",title:h,subtitle:d,viral:p,animationData:y,...m}),info:(h,d)=>c({kind:"info",title:h,subtitle:d}),infoNow:(h,d)=>c({kind:"info",title:h,subtitle:d}),dismiss:a,clear:r,setFlashAnimations:I,activeKind:t.length?(Q=t[t.length-1])==null?void 0:Q.kind:void 0,hasActive:t.length>0,onIdle:h=>{t.length===0?setTimeout(h,0):n.current.add(h)}}},[c,a,r,I,t.length]),B=E.useMemo(()=>{var N;if(typeof document>"u")return null;const Q=_7(),h=vYA(),d=t[0];if(!d)return null;const y=UYA(d,Q)&&h?h:document.body,m=y!==document.body,D=m&&Q.isCeeLo&&(d.kind==="win"||d.kind==="lose"||d.kind==="push")&&(((N=d.playerAvatars)==null?void 0:N.length)??0)>=2,S=m&&Q.isCeeLo&&(d.kind==="win"||d.kind==="lose"||d.kind==="push");return er.createPortal(C.jsxs("div",{className:"flash-root"+(m?" flash-root--header":"")+(D?" flash-root--inline":"")+(S?" flash-root--ceelo":""),"aria-live":"polite","data-testid":"flash-overlay-root",children:[C.jsx(LYA,{item:d,onDone:a,animations:g.current,zIndex:2e3}),C.jsx("div",{className:"flash-backdrop"})]},d.id),y)},[t,a]);return E.useEffect(()=>{},[c]),C.jsxs(s5.Provider,{value:l,children:[e,B]})}function Jr(){const e=E.useContext(s5);if(!e)throw new Error("useFlashOverlay must be used within <FlashOverlayProvider>");return e}function JL(){const e=E.useContext(s5);if(e)return e;const A=()=>{},t=()=>"";return{show:t,roll:t,rollNow:A,win:A,lose:A,push:A,info:A,infoNow:A,dismiss:A,clear:A,setFlashAnimations:A,activeKind:void 0,hasActive:!1,onIdle:A}}const J7=lL,TYA=BL,qYA=EL,YYA=QGA,L7=t8;function Sw(){const{user:e,refreshUser:A}=tn(),{rc:t,ready:i,error:n,buyChips:g,buySubscription:o,restorePurchases:s}=JBA(),{infoNow:a}=Jr(),[r,I]=E.useState(!1),[c,l]=E.useState(!1),[B,Q]=E.useState(!1),[h,d]=E.useState(!1),[p,y]=E.useState(!1),[m,D]=E.useState(void 0),[S,k]=E.useState(void 0),[N,G]=E.useState(void 0),[M,w]=E.useState(void 0),[b,_]=E.useState(void 0),[K,J]=E.useState(void 0),[q,v]=E.useState(!1),U=Ui.getPlatform()==="web",x=Ca(),T=!0,z=E.useMemo(()=>t==null?void 0:t.Purchases,[t]);E.useCallback(gA=>{var yA,fA;return(yA=gA==null?void 0:gA.all)!=null&&yA[J7]?gA.all[J7]:(gA==null?void 0:gA.current)||((fA=gA==null?void 0:gA.all)==null?void 0:fA.default)||null},[]);const Z=E.useCallback(async()=>{var gA,yA;try{const fA=dr(),RA=await((gA=fA==null?void 0:fA.getCustomerInfo)==null?void 0:gA.call(fA));let qA=!1;const W=((yA=RA==null?void 0:RA.entitlements)==null?void 0:yA.active)||{},$=Object.keys(W).length>0;L7&&(qA=!!(W!=null&&W[L7])||$),y(qA)}catch{}},[z,T]);E.useEffect(()=>{i&&T&&Z()},[i,T,Z]),E.useEffect(()=>{if(!i||!T)return;let gA=0;const yA=6,fA=setInterval(()=>{gA+=1,Z(),gA>=yA&&clearInterval(fA)},500);return()=>clearInterval(fA)},[i,T,Z]),E.useEffect(()=>{let gA=!1;return(async()=>{var yA,fA,RA,qA;try{if(!i||!T)return;const W=dr(),$=await((yA=W==null?void 0:W.getOfferings)==null?void 0:yA.call(W));if(!$)return;const L=[],H=O=>{Array.isArray(O)&&O.forEach(cA=>{cA&&L.push(cA)})};H(((fA=$==null?void 0:$.current)==null?void 0:fA.availablePackages)||((RA=$==null?void 0:$.current)==null?void 0:RA.packages)),$!=null&&$.all&&Object.values($.all).forEach(O=>H((O==null?void 0:O.availablePackages)||(O==null?void 0:O.packages)));const P=O=>{var cA,wA,xA;return(O==null?void 0:O.identifier)||((cA=O==null?void 0:O.product)==null?void 0:cA.identifier)||((wA=O==null?void 0:O.rcBillingProduct)==null?void 0:wA.identifier)||((xA=O==null?void 0:O.webBillingProduct)==null?void 0:xA.identifier)},tA=O=>(O==null?void 0:O.product)||(O==null?void 0:O.rcBillingProduct)||(O==null?void 0:O.webBillingProduct)||O,iA=O=>{const cA=tA(O);return!!((O==null?void 0:O.packageType)==="MONTHLY"||(O==null?void 0:O.packageType)==="ANNUAL"||cA!=null&&cA.subscriptionPeriod||cA!=null&&cA.period||cA!=null&&cA.defaultSubscriptionOption||cA!=null&&cA.productType&&/subscription/i.test(String(cA.productType)))},oA=O=>{var cA,wA,xA,YA;return(O==null?void 0:O.priceString)||((cA=O==null?void 0:O.price)==null?void 0:cA.formattedPrice)||((wA=O==null?void 0:O.currentPrice)==null?void 0:wA.formattedPrice)||(O==null?void 0:O.price)||((YA=(xA=O==null?void 0:O.defaultPurchaseOption)==null?void 0:xA.basePrice)==null?void 0:YA.formattedPrice)},IA=O=>String((O==null?void 0:O.title)||(O==null?void 0:O.displayName)||""),CA=O=>String((O==null?void 0:O.description)||""),_A=O=>O?L.find(cA=>P(cA)===O):void 0;let uA=_A(TYA)||_A(qYA);if(uA||(uA=L.find(O=>!iA(O))),uA){const O=tA(uA),cA=oA(O),wA=IA(O),xA=CA(O),YA=String(P(uA)||""),jA=PA=>{const ZA=PA.match(/\b(\d{1,3}(?:[\,\._\s]\d{3})*|\d{2,})\b/);if(!ZA)return null;const FA=ZA[1].replace(/[\._\s,]/g,""),Ie=parseInt(FA,10);return Number.isFinite(Ie)?Ie:null},ie=jA(wA)??jA(xA)??jA(YA),he=ie&&ie>0?ie:void 0,le=he?new Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(he):void 0,NA=le?`z${le}`:"Z Credits",EA=cA?`${NA} for ${cA}`:void 0;gA||D(EA),gA||G("Top up your Z Credits to keep playing.")}let X=_A(YYA);if(X||(X=L.find(wA=>(wA==null?void 0:wA.packageType)==="MONTHLY"||/month/i.test(String(P(wA)||""))||/month/i.test(IA(tA(wA))))||L.find(wA=>iA(wA)||/year|annual|week|month/i.test(String(P(wA)||"")))),gA||v(!!X),X){const O=tA(X),cA=oA(O),wA=cA?`${cA} Mo`:void 0;if(gA||k(wA),gA||w("Remove ads and unlock premium features."),gA||_(cA),!gA){let xA="Auto-renewing";const YA=(X==null?void 0:X.packageType)||(O==null?void 0:O.subscriptionPeriod)||(O==null?void 0:O.period)||((qA=O==null?void 0:O.defaultSubscriptionOption)==null?void 0:qA.period),jA=String(YA||"").toUpperCase();jA.includes("MONTH")||jA==="MONTHLY"||jA==="P1M"?xA="Monthly":jA.includes("YEAR")||jA==="ANNUAL"||jA==="P1Y"?xA="Annual":jA.includes("WEEK")||jA==="WEEKLY"||jA==="P1W"?xA="Weekly":(jA.includes("DAY")||jA==="P1D")&&(xA="Daily"),J(xA)}}}catch{}})(),()=>{gA=!0}},[i,T,z]);const eA=async()=>{var gA;if(!r){if(I(!0),l(!0),!i){a("Purchases initializing…","Please try again in a moment."),l(!1),I(!1);return}try{await g(),a("Purchase complete","Chips will appear shortly.")}catch(yA){let fA=(yA==null?void 0:yA.message)||"Purchase unavailable right now. Please try again shortly.";try{const RA=((gA=yA==null?void 0:yA.getErrorCode)==null?void 0:gA.call(yA))??(yA==null?void 0:yA.errorCode)??(yA==null?void 0:yA.code),qA=typeof RA=="number"?RA===3?"PurchaseNotAllowedError":RA===2?"StoreProblemError":RA===5?"ProductNotAvailableForPurchaseError":void 0:void 0;qA==="PurchaseNotAllowedError"?fA="Purchases not allowed for this Apple ID/device. Use an App Store sandbox account and ensure the Paid Apps Agreement is accepted.":qA==="StoreProblemError"?fA="App Store is currently unavailable. Please try again later or verify sandbox account is signed in to the device.":qA==="ProductNotAvailableForPurchaseError"&&(fA="Product not available. Verify the product identifier matches App Store Connect and RevenueCat configuration for this app target.")}catch{}a("Purchase failed",fA)}finally{l(!1),I(!1)}}},aA=async()=>{if(!r){if(I(!0),Q(!0),!i){try{a("Purchases initializing…","Please try again in a moment.")}catch{}try{await(await Qi(async()=>{const{reconfigureRevenueCat:gA}=await Promise.resolve().then(()=>dYA);return{reconfigureRevenueCat:gA}},void 0)).reconfigureRevenueCat()}catch{}Q(!1),I(!1);return}try{await o(),await Z(),a("Subscription active","Thanks for supporting.")}finally{Q(!1),I(!1)}}},sA=async()=>{if(!r){if(I(!0),d(!0),!i)throw new Error("Payment service not ready");await s(),await Z();try{const gA=await uo();gA&&await fetch(`${x}/api/payment/revenuecat/restore`,{method:"POST",headers:{Authorization:`Bearer ${gA}`}})}catch{}try{await A()}catch{}try{setTimeout(()=>{A().catch(()=>{})},800)}catch{}try{setTimeout(()=>{A().catch(()=>{})},2e3)}catch{}a("Restored purchases","Your purchases have been restored."),d(!1),I(!1)}},pA=E.useMemo(()=>!i||!T?"Initializing…":p?"Premium Active":"Go Premium",[p,i,T]);return{ready:i,error:n||null,busy:r,busyChips:c,busySubscription:B,premiumActive:p,hasPremiumPackage:q,premiumLabel:pA,purchasesReady:T,isWeb:U,onBuyChips:eA,onGoPremium:aA,onRestore:sA,chipsSubtitle:m,premiumSubtitle:S,chipsDescription:N,premiumDescription:M,premiumPrice:b,premiumInterval:K}}var oM;(function(e){e.Heavy="HEAVY",e.Medium="MEDIUM",e.Light="LIGHT"})(oM||(oM={}));var x7;(function(e){e.Success="SUCCESS",e.Warning="WARNING",e.Error="ERROR"})(x7||(x7={}));const Oh=md("Haptics",{web:()=>Qi(()=>import("./web-BMtXzcJx.js"),__vite__mapDeps([11,1])).then(e=>new e.HapticsWeb)}),HYA={Light:oM.Light,Medium:oM.Medium,Heavy:oM.Heavy},OYA={Light:10,Medium:20,Heavy:35};async function So(e="Light"){var A;try{await Oh.impact({style:HYA[e]});return}catch{}try{(A=navigator.vibrate)==null||A.call(navigator,OYA[e])}catch{}}function ti(e="Light"){So(e)}async function zBA(){try{if(Oh!=null&&Oh.selectionStart){await Oh.selectionStart(),await Oh.selectionChanged(),await Oh.selectionEnd();return}}catch{}await So("Light")}const R1=Object.freeze(Object.defineProperty({__proto__:null,hapticClick:ti,hapticImpact:So,hapticSelection:zBA},Symbol.toStringTag,{value:"Module"}));function a5({isPremium:e,className:A}){const[t,i]=E.useState(!1),{onGoPremium:n,busy:g,ready:o}=Sw();if(!e)return null;const s=async()=>{try{i(!0);try{ti("Light")}catch{}await n()}finally{i(!1)}};return C.jsx("button",{className:A||"felt-btn","data-no-global-haptic":!0,onClick:s,disabled:t||g||!o||!1,"aria-busy":t||g,title:"Manage your subscription",children:t||g?"Processing…":"Manage"})}function ZBA({open:e,onClose:A,featureDescription:t}){const{user:i}=tn(),{onGoPremium:n,onRestore:g,busy:o,premiumActive:s,hasPremiumPackage:a,premiumLabel:r,error:I,ready:c,premiumPrice:l,premiumInterval:B}=Sw(),Q=qi(),{infoNow:h}=Jr(),d=async()=>{if(!(i!=null&&i.id)){try{Q("/lobby")}catch{}try{A==null||A()}catch{}return}if(!(s||o))try{if(await n(),!s)return;A()}catch(m){const D=(m==null?void 0:m.message)||"Purchases are initializing… please try again in a moment.";try{h("Purchase unavailable",D)}catch{}}};if(!e)return null;const p=!!(i!=null&&i.id),y="$1.99";return C.jsx("div",{className:"modal-overlay",children:C.jsxs("div",{className:"modal",children:[C.jsx("button",{className:"modal-close","aria-label":"Close",onClick:A,children:"×"}),C.jsx("h3",{children:s?"Premium Active":`Go Premium for ${y}/mo!`}),C.jsx("p",{children:s?"Your premium membership is active.":t||"Creating rooms is a premium feature. Upgrade to unlock it and more."}),!s&&a&&C.jsx("button",{className:"gold-btn felt-btn",onClick:d,disabled:o,children:p?o?"Processing…":r:"Sign in to Upgrade"}),s&&C.jsx("div",{style:{marginTop:12},children:C.jsx(a5,{isPremium:!0})}),!s&&a&&C.jsxs("p",{className:"meta",style:{fontSize:12,opacity:.85},children:[C.jsx("strong",{children:"Premium Subscription"})," — ",l?`${l} `:y+" ",B?`(${B})`:"(Monthly)",". Auto‑renews until canceled. Manage or cancel in account settings on your device. See our ",C.jsx(HI,{to:"/privacy",className:"legal-link",children:"Privacy Policy"})," and ",C.jsx(HI,{to:"/terms",className:"legal-link",children:"Terms of Use"}),"."]}),I&&C.jsx("p",{className:"error",role:"alert",children:I}),!s&&a&&C.jsx("div",{style:{marginTop:8},children:C.jsx("button",{type:"button",className:"gold-link",onClick:g,disabled:!p||o||!c||!1,"aria-label":"Restore Purchases",title:"Restore Purchases",children:"Restore Purchases"})}),!p&&!s&&C.jsx("p",{className:"meta",children:"Please sign in to upgrade."}),!p&&I&&C.jsx("p",{className:"meta",children:"Purchases unavailable while signed out."})]})})}let xy=null,T7=0;const PYA=3e4;function jYA(){const{user:e}=tn(),[A,t]=E.useState(xy),[i,n]=E.useState(!1),[g,o]=E.useState(!1),s=Ca(),a=E.useCallback(async(I=!1)=>{if(e){if(!I&&xy&&Date.now()-T7<PYA){t(xy);return}n(!0);try{const c=await uo(),B=await(await fetch(`${s}/api/challenges/daily`,{credentials:"include",headers:{...c?{Authorization:`Bearer ${c}`}:{},Accept:"application/json"}})).json();B!=null&&B.ok&&(B!=null&&B.data)&&(xy=B.data,T7=Date.now(),t(xy))}catch{}finally{n(!1)}}},[e,s]),r=E.useCallback(async()=>{if(!e||g)return null;o(!0);try{const I=await uo(),l=await(await fetch(`${s}/api/challenges/daily/claim`,{method:"POST",credentials:"include",headers:{...I?{Authorization:`Bearer ${I}`}:{},Accept:"application/json","Content-Type":"application/json"}})).json();return l!=null&&l.ok?(xy=null,await a(!0),l.data):null}catch{return null}finally{o(!1)}},[e,g,s,a]);return E.useEffect(()=>{e&&a()},[e,a]),{data:A,loading:i,claiming:g,refresh:a,claim:r}}function vd({onClose:e,defaultMode:A}){const[t,i]=E.useState(A??"cee-lo"),n=!A,g=()=>n?C.jsxs("div",{className:"howto__toggle",role:"tablist","aria-label":"Select ruleset",children:[C.jsx("button",{type:"button",role:"tab","aria-selected":t==="cee-lo","aria-pressed":t==="cee-lo",onClick:()=>{i("cee-lo")},className:"felt-btn"+(t==="cee-lo"?" felt-btn--active":""),children:"Cee‑Lo"}),C.jsx("button",{type:"button",role:"tab","aria-selected":t==="craps","aria-pressed":t==="craps",onClick:()=>{i("craps")},className:"felt-btn"+(t==="craps"?" felt-btn--active":""),children:"Craps"}),C.jsx("button",{type:"button",role:"tab","aria-selected":t==="poker","aria-pressed":t==="poker",onClick:()=>{i("poker")},className:"felt-btn"+(t==="poker"?" felt-btn--active":""),children:"Poker"}),C.jsx("button",{type:"button",role:"tab","aria-selected":t==="skills","aria-pressed":t==="skills",onClick:()=>{i("skills")},className:"felt-btn"+(t==="skills"?" felt-btn--active":""),children:"Skills"})]}):null,o=C.jsxs(C.Fragment,{children:[C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Overview"}),C.jsx("p",{children:"This is a banker‑versus‑challengers dice game inspired by Cee‑Lo. Each round, the banker rolls first to set the banker outcome. Then challengers roll in turn and compare against the banker. You can place main bets against the banker and optional side bets on other players."})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Single‑Player Mode"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"No tap needed to roll:"})," After you place a MAIN bet, the server will automatically roll for the banker and then for you. This keeps play smooth on mobile."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Place a MAIN bet to begin:"})," The banker won’t roll until there’s at least one open MAIN bet for the round."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Auto pacing:"})," Rounds settle automatically and the next round starts after a short buffer."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Bet window:"})," MAIN bets are open before the banker scores; once the banker establishes a point, MAIN bets lock for the round."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Round Flow"}),C.jsxs("ol",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Banker sets the roll:"})," The banker rolls until they have a scoring result."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Challengers roll:"})," Each challenger rolls once a banker score exists."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Settle:"})," Wagers settle automatically with chip animations and a result flash."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Dice Scoring"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"456 (banker only):"})," Banker wins against everyone (auto‑win)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"123 (banker only):"})," Banker fails/pass this round (auto‑lose / pass)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Triples:"})," Three of a kind beats any point (higher triple beats lower)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Point:"})," A pair plus a singleton sets a point equal to the singleton value (1–6). Higher point wins."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Nothing:"})," No pair/triple and not 123/456 — banker re‑rolls; challenger non‑score."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Challenger 123/456:"})," Treated as a normal point (no auto outcome for challengers)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Tie:"})," Push (stake returned)."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Main Bets (vs Banker)"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Main bet wins if your roll outranks banker, loses if lower, pushes if equal."}),C.jsx("li",{children:"Banker auto results (456 / 123) settle immediately with no legacy sweep animation."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Side Bets"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Create offers on another player’s upcoming roll (e.g. “Under 4 on Alex”)."}),C.jsx("li",{children:"Only non‑subject players may accept; creator & subject excluded."}),C.jsx("li",{children:"Offer can be canceled until the subject rolls."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Visual Feedback"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Chip flights represent transfers; flashes show WIN / LOSE / PUSH."}),C.jsx("li",{children:"Push flashes appear shortly after resolution to keep pacing consistent."}),C.jsx("li",{children:"Haptics fire for meaningful outcomes (supported devices)."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Tips"}),C.jsxs("ul",{children:[C.jsx("li",{children:"High banker point (5 or 6) reduces challenger EV—size bets accordingly."}),C.jsx("li",{children:"Track patterns with the history view; variance can mask true edge short‑term."})]})]})]}),s=C.jsxs(C.Fragment,{children:[C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Overview"}),C.jsx("p",{children:"Multiplayer Craps implementation (current scope: Pass / Don’t Pass line bets and Place bets on 4,5,6,8,9,10). Additional bet families (Come / Don’t Come, Odds, Field, Big 6/8, Props) will roll out progressively. Settlement & animation pipeline matches other games: each resolved bet triggers chip flight(s) then a result flash."}),C.jsxs("p",{className:"howto__note howto__note--small",children:[C.jsx("b",{children:"Current Limitation:"})," Field, Big 6/8, Come/Dont Come, Odds buttons may appear as educational UI but only Pass / Don’t Pass and Place bets settle right now."]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Table Flow"}),C.jsxs("ol",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Come‑Out Roll:"})," Shooter rolls with no point established."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Point Set:"})," First 4,5,6,8,9,10 rolled (unless 7/11/2/3/12 resolves line bets) becomes the point."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Point Phase:"})," Shooter keeps rolling until point repeats (Pass wins) or a 7 appears (Don’t Pass wins / seven‑out)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Shooter Rotation:"})," On seven‑out (or configured rotation rule) the dice pass to next player in order."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Pass / Don’t Pass Rules"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Come‑Out:"})," 7 or 11 = Pass win; 2 or 3 = Pass lose (Don’t Pass win); 12 = Pass lose, Don’t Pass push (bar 12)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Point Phase:"})," Pass wins if point repeats before 7; Don’t Pass wins on 7 before point."]}),C.jsx("li",{children:"Payout: Even money (winning line bet returns principal + equal winnings; push returns principal)."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Place Bets (Implemented)"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Available only after a point is established."}),C.jsx("li",{children:"Remain on the table until a 7 (seven‑out) or player removes them (UI removal support pending future update)."}),C.jsx("li",{children:"Payout ratios (winnings only; principal stays): 4/10: 9:5 • 5/9: 7:5 • 6/8: 7:6."}),C.jsx("li",{children:"On seven‑out all active place bets lose and are cleared."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Planned Features"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Odds Bets:"})," True odds behind line & come bets (no house edge)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Come / Don’t Come:"})," Independent points established after the main point."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Field & Big 6/8:"})," One‑roll (Field) and even‑money (Big) bets with proper settlement."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Prop / Horn:"})," Center action (yo, any 7, craps, hardways) with single‑roll or multi‑roll resolution."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Readiness & Rolling"}),C.jsxs("ul",{children:[C.jsx("li",{children:"All players mark Ready between rolls; shooter auto‑ready on new shooter assignment."}),C.jsx("li",{children:"Countdown deadline (if shown) enforces timely rolls; expired deadlines may auto‑roll in later phases."}),C.jsx("li",{children:"Shooter must have an active Pass (or Don’t Pass if allowed by table config) before rolling."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Settlement Pipeline"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Server validates roll → computes line & place settlements → emits results → credits balances."}),C.jsx("li",{children:"Line WIN: principal + winnings credited. Line PUSH: principal only. Place WIN: winnings only (bet stays)."}),C.jsx("li",{children:"Seven‑out triggers removal of all unresolved place bets (auto clear broadcast)."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Payout Reference"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Pass / Don’t Pass:"})," 1:1"]}),C.jsxs("li",{children:[C.jsx("b",{children:"Place 4 / 10:"})," 9:5"]}),C.jsxs("li",{children:[C.jsx("b",{children:"Place 5 / 9:"})," 7:5"]}),C.jsxs("li",{children:[C.jsx("b",{children:"Place 6 / 8:"})," 7:6"]})]}),C.jsx("p",{className:"howto__note howto__note--tiny",children:"Fractions floored in current build; rounding rules may refine later."})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Strategy Notes (Basics)"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Place 6 & 8 have the lowest house edge among implemented place bets."}),C.jsx("li",{children:"Even‑money Pass vs Don’t Pass is preference until odds arrive (future true‑odds leverage)."}),C.jsx("li",{children:"Avoid overexposing bankroll pre‑odds: variance on early seven‑outs can be sharp."})]})]})]}),a=C.jsxs(C.Fragment,{children:[C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Overview"}),C.jsx("p",{children:"No‑limit Texas Hold’em with simplified pacing. Hands proceed through Pre‑flop, Flop, Turn, River, then Showdown. Seats auto‑order left of the dealer button. Side pots and all‑in handling are automatic. Bots may fill seats in single‑player rooms."}),C.jsxs("p",{className:"howto__note howto__note--small",children:[C.jsx("b",{children:"Table Defaults:"})," Small blind 5, big blind 10, minimum buy‑in z1000, up to 6 seats."]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Buy‑In & Seating"}),C.jsxs("ul",{children:[C.jsxs("li",{children:["Joining a poker room requires at least ",C.jsx("b",{children:"z1000"})," balance (server‑enforced)."]}),C.jsx("li",{children:"When seated, your starting stack equals the minimum buy‑in (z1000)."}),C.jsx("li",{children:"Bots, when present, are seated with z1000 stacks."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Blinds & Turn Order"}),C.jsxs("ul",{children:[C.jsx("li",{children:"The dealer button rotates each hand. Players post small blind and big blind to start the pot."}),C.jsx("li",{children:"Pre‑flop action begins left of the big blind; on later streets it begins left of the button."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Actions"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Fold"})," — Surrender your hand; no further claim to the pot."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Check/Call"})," — Match the current bet to continue (or check for free when no bet is outstanding)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Bet/Raise"})," — Put chips in the pot. Min raise equals the last raise size; UI shows legal targets."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Streets & Dealing"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Pre‑flop:"})," Two private cards to each player."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Flop:"})," Three community cards."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Turn:"})," One community card."]}),C.jsxs("li",{children:[C.jsx("b",{children:"River:"})," One community card."]}),C.jsx("li",{children:"Short UI locks play during dealing animations to keep state consistent."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Pots, All‑In, Side Pots"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Contributions create the main pot and side pots automatically when stacks differ."}),C.jsx("li",{children:"At showdown each pot is awarded to the best eligible hand among its contributors; ties split evenly (with any odd chip distributed deterministically)."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Hand Ranking (Best 5 Cards)"}),C.jsx("ul",{children:C.jsx("li",{children:"Straight Flush (best) → Four of a Kind → Full House → Flush → Straight → Three of a Kind → Two Pair → One Pair → High Card."})})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Showdown"}),C.jsx("ul",{children:C.jsx("li",{children:"Remaining players reveal; best 5‑card hand wins each pot. If everyone else folds, last player takes the pot without showdown."})})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Tips"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Respect position: act later to gather more information."}),C.jsx("li",{children:"Size raises relative to the pot and prior aggression; avoid bet sizing tells."}),C.jsx("li",{children:"Tighten ranges out of position; widen on the button."})]})]})]}),r=C.jsxs(C.Fragment,{children:[C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Overview"}),C.jsx("p",{children:"Skills Lounge is a head‑to‑head word and trivia battle. Compete against opponents in timed challenges across three game modes: Word Search, Anagrams, and Trivia. Earn points based on speed and accuracy."})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Game Modes"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Word Search:"})," Find hidden words in a letter grid by swiping across letters."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Anagrams:"})," Form valid words from a pool of scrambled letters."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Trivia:"})," Answer multiple‑choice questions across various categories."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Word Search Rules"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Swipe across adjacent letters (horizontal, vertical, or diagonal) to form words."}),C.jsx("li",{children:"Words must be at least 3 letters long to score."}),C.jsx("li",{children:"Longer words earn more points: 3 letters = 1 pt, 4 letters = 2 pts, 5+ letters = 3+ pts."}),C.jsx("li",{children:"Each word can only be found once per round."}),C.jsx("li",{children:"The timer counts down—find as many words as possible before time expires."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Anagrams Rules"}),C.jsxs("ul",{children:[C.jsx("li",{children:"You're given a pool of letters—tap letters to select them and form words."}),C.jsx("li",{children:"Submit valid words to score points; invalid words don't count."}),C.jsx("li",{children:"Longer words earn more points."}),C.jsx("li",{children:"Letters reset after each submission, allowing multiple words per round."}),C.jsx("li",{children:"Race against the clock to find as many valid words as possible."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Trivia Rules"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Answer multiple‑choice questions from categories like Science, History, Sports, and more."}),C.jsx("li",{children:"Each question has a time limit—answer quickly for bonus points."}),C.jsx("li",{children:"Correct answers earn base points; faster answers earn time bonuses."}),C.jsx("li",{children:"Difficulty varies: Easy, Medium, and Hard questions with increasing point values."}),C.jsx("li",{children:"Questions are drawn from a pool of thousands—fresh challenges every game."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Scoring"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Word Search:"})," Points scale with word length (longer = better)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Anagrams:"})," Points scale with word length (longer = better)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Trivia:"})," Base points for correct answers + time bonus for fast responses."]}),C.jsx("li",{children:"Final score determines the winner of each duel."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Match Flow"}),C.jsxs("ol",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Matchmaking:"})," Find an opponent or play against AI."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Mode Selection:"})," Choose Word Search, Anagrams, or Trivia."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Challenge:"})," Both players compete on the same puzzle/questions simultaneously."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Results:"})," Scores are compared and the winner is declared."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Tips"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Word Search:"})," Start with the corners and edges—words often extend from boundaries."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Anagrams:"})," Look for common prefixes/suffixes (‑ing, ‑ed, un‑, re‑) to spot words faster."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Trivia:"})," Don't overthink—your first instinct is often correct. Manage time wisely."]}),C.jsx("li",{children:"Practice regularly to build vocabulary and improve pattern recognition."})]})]})]}),I=C.jsxs(C.Fragment,{children:[C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Overview"}),C.jsx("p",{children:"Zentara is a sci‑fi galactic conquest board game for 2–6 players. Capture planets, collect credits, deal hull damage, and be the last empire standing. Think of it as a space‑themed property strategy game."})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Setup"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Players:"})," 2–6 per match."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Starting Credits:"})," 1,500."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Starting Hull Points (HP):"})," 1,500 (max 1,500)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Board:"})," 40 tiles in a circular ring. All players start on Command Base (tile 0)."]}),C.jsx("li",{children:"Choose a galactic empire and place your token on Command Base."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Turn Structure"}),C.jsxs("ol",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Roll Dice:"})," Roll two dice and move forward that many tiles."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Resolve Tile:"})," The tile's effect triggers automatically."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Manage Assets:"})," Optionally upgrade, mortgage, sell, or trade properties."]}),C.jsxs("li",{children:[C.jsx("b",{children:"End Turn:"})," Play passes to the next player."]})]}),C.jsxs("p",{className:"howto__note howto__note--small",children:[C.jsx("b",{children:"Doubles:"})," Rolling doubles grants an extra roll. Three consecutive doubles sends you to Cryosleep."]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Tile Types"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Command Base:"})," Collect +200 credits when passing or landing."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Planets (22 tiles):"})," Buy unowned planets. Landing on an opponent's planet deals hull damage equal to rent."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Stations (4 tiles):"})," Cost 200 each. Rent scales with how many you own (25 → 50 → 100 → 200)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Asteroid (3 tiles):"})," Draw a chance card — gain or lose credits."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Nebula (3 tiles):"})," Draw a community card — gain or lose credits."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Tax (2 tiles):"})," Pay 200 (Supply Levy) or 100 (War Tax) credits."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Wormhole (2 tiles):"})," Teleport between Wormhole α and β."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Black Hole:"})," Go directly to Cryosleep."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Cryosleep:"})," Roll doubles to escape, or pay 50 credits to wake up."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Safe Harbor:"})," No effect — rest safely."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Planets & Upgrades"}),C.jsxs("ul",{children:[C.jsxs("li",{children:["Planets belong to 8 color groups. Own all planets in a group to ",C.jsx("b",{children:"double base rent"}),"."]}),C.jsxs("li",{children:["Upgrade planets up to ",C.jsx("b",{children:"5 arms levels"})," for dramatically higher rent."]}),C.jsx("li",{children:"You must own the full group before upgrading. Sell upgrades before mortgaging."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Hull Points & Elimination"}),C.jsxs("ul",{children:[C.jsxs("li",{children:["Landing on an opponent's planet deals ",C.jsx("b",{children:"hull damage"})," (HP loss) equal to rent. The owner earns those credits."]}),C.jsx("li",{children:"When HP hits 0: properties are repossessed at 50% value. Pay 200 credits for +50 HP to survive, or surrender."}),C.jsx("li",{children:"Last empire standing wins!"})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Ship Upgrades"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Armor (max level 3):"})," Each level reduces incoming hull damage by 15%. At max level you absorb 45% of all damage from enemy planets."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Weapons (max level 3):"})," Level 1 unlocks ",C.jsx("b",{children:"Auto‑Strike"})," — when you roll doubles and land on an enemy armed planet, you automatically destroy one arms level on that property. Higher levels add a dice bonus during Resource Raids."]}),C.jsx("li",{children:"Each upgrade costs 250 credits. Invest wisely — credits spent on your ship can't be spent on planets."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Heroes"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Hero Shop:"})," Open from the Zentara home screen. Browse heroes organized by empire and tier, then purchase with credits."]}),C.jsxs("li",{children:[C.jsx("b",{children:"6 tiers per empire:"})," Recruit (500) → Guardian (1,500) → Commander (4,000) → Warlord (10,000) → Champion (25,000) → Legend (60,000)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Auto‑equip:"})," When picking your empire before a match, your highest‑tier hero auto‑equips — no manual selection needed."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Attack bonus:"})," Boosts the rent you collect when opponents land on your properties (e.g. +20% at Tier 3)."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Defense bonus:"})," Reduces the rent you pay when landing on opponents' properties. Stacks with Ship Armor."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Empire specializations:"})," Offense empires (Crimson, Golden) get extra attack. Defense empires (Azure, Emerald) get extra defense. Balanced empires (Silver, Void) get base stats."]}),C.jsx("li",{children:"Heroes persist across matches — buy once, use forever."})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Resource Raids (FPS Mini‑Game)"}),C.jsxs("ul",{children:[C.jsxs("li",{children:["When your piece lands on a tile already occupied by an opponent, a ",C.jsx("b",{children:"Resource Raid"})," is triggered."]}),C.jsxs("li",{children:["A full‑screen ",C.jsx("b",{children:"first‑person space combat"})," mini‑game launches — you have ",C.jsx("b",{children:"17 seconds"})," to shoot down as many enemy ships as you can."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Tap/click"})," on enemy ships to fire your lasers. Each hit counts toward your score."]}),C.jsxs("li",{children:["Enemy ships will ",C.jsx("b",{children:"fire back"})," — green laser bolts flash across the screen. You can't dodge, but don't panic — focus on racking up kills."]}),C.jsx("li",{children:"Ships fly in from all directions, perform barrel rolls, and vary in distance. Lead your shots on fast‑moving targets."}),C.jsxs("li",{children:[C.jsx("b",{children:"Scoring:"})," Hit 30% or more of enemy ships to win the raid. The winner steals credits from the loser — base 30 credits plus 8 per hit."]}),C.jsxs("li",{children:["Your ",C.jsx("b",{children:"weapon level"})," gives you a bonus, making it easier to win raids. Upgrade weapons to gain an edge."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Spy Strike"}),C.jsxs("ul",{children:[C.jsxs("li",{children:["When an opponent completes a ",C.jsx("b",{children:"color group"}),", you can pay ",C.jsx("b",{children:"1,000 credits"})," to plant a covert ",C.jsx("b",{children:"spy"})," on that group (one spy per group)."]}),C.jsxs("li",{children:["The next time the spy’s owner lands on any tile in that group, a ",C.jsx("b",{children:"Spy Strike"})," is triggered instead of paying rent."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Phase A — Soldier Strike:"})," breach the defended station to advance."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Phase B — Sniper:"})," you have ",C.jsx("b",{children:"7 seconds"})," to line up and fire on the target. Miss the timer and the shot fails."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Win:"})," seize ownership of the ",C.jsx("i",{children:"entire color group"})," from the defender."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Lose:"})," pay a ",C.jsx("b",{children:"1,000-credit penalty"})," on top of the plant cost, then resolve normal rent (and any Hero Clash) as if you’d landed normally. The group enters a short siege cooldown."]}),C.jsxs("li",{children:["If the penalty would bankrupt you, the standard ",C.jsx("b",{children:"in-debt"})," flow handles it."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Multiplayer"}),C.jsxs("ul",{children:[C.jsxs("li",{children:[C.jsx("b",{children:"Create or join rooms:"})," Host a private room and share the code with friends, or join a public room to play with anyone."]}),C.jsxs("li",{children:[C.jsx("b",{children:"2–6 players:"})," Each player picks a unique galactic empire (faction). Once all players have chosen, the host starts the match."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Real‑time turns:"})," All players see dice rolls, piece movement, property purchases, and trades as they happen — no waiting for syncs."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Resource Raids in multiplayer:"})," When a raid triggers between two players, the involved players play the FPS mini‑game on their own device. Other players see a notification of the raid result."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Bots:"})," Fill empty slots with AI bots. Choose bot difficulty to keep the game competitive even with fewer human players."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Trading:"})," Propose trades with any player — offer properties and credits in exchange for theirs. Both sides must agree."]}),C.jsxs("li",{children:[C.jsx("b",{children:"Chat:"})," In‑game text chat lets you negotiate, trash‑talk, or coordinate — available throughout the match."]})]})]}),C.jsxs("section",{className:"howto__section",children:[C.jsx("h3",{children:"Tips"}),C.jsxs("ul",{children:[C.jsx("li",{children:"Completing color groups early doubles rent — prioritize group completion over scattered purchases."}),C.jsx("li",{children:"Stations are great income with low risk — owning all four yields 200 credits per landing."}),C.jsx("li",{children:"Manage HP carefully: over‑investing in planets can leave you vulnerable to hull damage."}),C.jsx("li",{children:"Use mortgage strategically to survive tough stretches — you can un‑mortgage later."}),C.jsx("li",{children:"Upgrading weapons early unlocks auto‑strike and gives you an edge in Resource Raids."}),C.jsx("li",{children:"Invest in heroes for your favorite empire — the defense bonus stacks with armor for huge damage reduction."}),C.jsx("li",{children:"In the FPS raid, focus on ships at medium distance — they're slower and easier to hit than close fly‑bys."}),C.jsx("li",{children:"In multiplayer, watch the board — if an opponent is heading toward your tile, a raid is incoming."})]})]})]});return C.jsxs("div",{className:"card how-to-play howto",children:[C.jsx("div",{className:"card-header howto__header",children:C.jsx("div",{className:"howto__header-row",children:C.jsx(g,{})})}),C.jsx("h2",{className:"howto__title",children:"How to Play"}),C.jsxs("div",{className:"card-body howto__body",children:[(t==="cee-lo"||t==="craps"||t==="poker")&&C.jsxs("div",{role:"note","aria-label":"Disclaimer",className:"howto__disclaimer",children:[C.jsx("strong",{children:"Disclaimer:"})," This is not a real‑money gambling site. No real currency, wagers, or payouts are involved. For entertainment and educational purposes only."]}),t==="cee-lo"?o:t==="craps"?s:t==="poker"?a:t==="zentara"?I:r]})]})}function zYA({open:e,onClose:A,defaultMode:t}){const i=E.useRef(null),n="howto-intro";return E.useEffect(()=>{if(!e)return;const g=s=>{s.key==="Escape"&&A()},o=s=>{i.current&&!i.current.contains(s.target)&&A()};return document.addEventListener("keydown",g),document.addEventListener("mousedown",o),()=>{document.removeEventListener("keydown",g),document.removeEventListener("mousedown",o)}},[e,A]),e?C.jsx("div",{className:"modal-backdrop",role:"presentation",children:C.jsxs("div",{className:"modal-panel modal-panel--fullscreen howto-modal",role:"dialog","aria-modal":"true","aria-label":"How to Play","aria-describedby":n,ref:i,children:[C.jsxs("div",{className:"modal-header",children:[C.jsx("h3",{className:"modal-title",children:"How to Play"}),C.jsx("button",{className:"modal-close",onClick:A,"aria-label":"Close",children:"×"})]}),C.jsx(vd,{defaultMode:t})]})}):null}let Ty=null,q7=0;const ZYA=6e4;let f0=null;function WBA(){const{user:e}=tn(),[A,t]=E.useState(Ty),[i,n]=E.useState(!1),[g,o]=E.useState(null),s=Ca(),a=E.useCallback(async(r=!1)=>{if(e){if(!r&&Ty&&Date.now()-q7<ZYA){t(Ty);return}if(f0){await f0,t(Ty);return}n(!0),o(null),f0=(async()=>{try{const I=await uo(),c=await fetch(`${s}/api/leaderboard/summary`,{credentials:"include",headers:{...I?{Authorization:`Bearer ${I}`}:{},Accept:"application/json"}});if(!(c.headers.get("content-type")||"").includes("application/json")){const Q=await c.text();throw new Error(`Unexpected response (${c.status}). Not JSON. First bytes: ${Q.slice(0,120)}`)}const B=await c.json();if(B!=null&&B.ok&&(B!=null&&B.data))Ty=B.data,q7=Date.now(),t(Ty);else throw new Error((B==null?void 0:B.error)||"Failed to load leaderboard")}catch(I){o((I==null?void 0:I.message)??"Failed to load leaderboard")}finally{n(!1),f0=null}})(),await f0}},[e]);return E.useEffect(()=>{e&&a()},[e,a]),{data:A,loading:i,error:g,refresh:a}}const WYA={topBalances:[{rank:1,playerId:"demo1",name:"ChipMaster",avatarUrl:null,balance:25e5},{rank:2,playerId:"demo2",name:"LuckyDice",avatarUrl:null,balance:185e4},{rank:3,playerId:"demo3",name:"WordWizard",avatarUrl:null,balance:142e4},{rank:4,playerId:"demo4",name:"SkillsKing",avatarUrl:null,balance:98e4},{rank:5,playerId:"demo5",name:"ProPlayer",avatarUrl:null,balance:75e4}],weeklyWinners:[{rank:1,playerId:"demo6",name:"HotStreak",avatarUrl:null,amount:425e3},{rank:2,playerId:"demo7",name:"BigWinner",avatarUrl:null,amount:312e3},{rank:3,playerId:"demo1",name:"ChipMaster",avatarUrl:null,amount:285e3},{rank:4,playerId:"demo8",name:"RisingStar",avatarUrl:null,amount:198e3},{rank:5,playerId:"demo9",name:"GamePro",avatarUrl:null,amount:145e3}],allTimeWinners:[{rank:1,playerId:"demo1",name:"ChipMaster",avatarUrl:null,amount:125e5},{rank:2,playerId:"demo10",name:"Legend99",avatarUrl:null,amount:98e5},{rank:3,playerId:"demo2",name:"LuckyDice",avatarUrl:null,amount:765e4},{rank:4,playerId:"demo11",name:"VeteranAce",avatarUrl:null,amount:542e4},{rank:5,playerId:"demo12",name:"OGPlayer",avatarUrl:null,amount:41e5}],skillsStreaks:[{rank:1,playerId:"demo3",name:"WordWizard",avatarUrl:null,bestStreak:12,currentStreak:5},{rank:2,playerId:"demo6",name:"HotStreak",avatarUrl:null,bestStreak:9,currentStreak:9},{rank:3,playerId:"demo1",name:"ChipMaster",avatarUrl:null,bestStreak:7,currentStreak:0},{rank:4,playerId:"demo4",name:"SkillsKing",avatarUrl:null,bestStreak:6,currentStreak:3},{rank:5,playerId:"demo9",name:"GamePro",avatarUrl:null,bestStreak:5,currentStreak:1}],zentaraAllTime:[{rank:1,playerId:"demoZ1",name:"GalaxyKing",avatarUrl:null,credits:18400,wins:14},{rank:2,playerId:"demoZ2",name:"NovaQueen",avatarUrl:null,credits:13220,wins:11},{rank:3,playerId:"demoZ3",name:"StarLord",avatarUrl:null,credits:9180,wins:7}],zentaraWeekly:[{rank:1,playerId:"demoZ2",name:"NovaQueen",avatarUrl:null,credits:4280,wins:3},{rank:2,playerId:"demoZ4",name:"VoidRunner",avatarUrl:null,credits:3140,wins:2}],zentaraBiggestWin:[{rank:1,playerId:"demoZ1",name:"GalaxyKing",avatarUrl:null,credits:5840},{rank:2,playerId:"demoZ3",name:"StarLord",avatarUrl:null,credits:4310}],zentaraTopEmpires:[{rank:1,empire:"crimson-dominion",label:"Crimson Dominion",wins:22},{rank:2,empire:"azure-sovereignty",label:"Azure Sovereignty",wins:18},{rank:3,empire:"golden-imperium",label:"Golden Imperium",wins:14}]};function VYA({open:e,onClose:A}){var r;const[t]=uw(),i=t.get("e2e")==="1",{data:n,loading:g,error:o,refresh:s}=WBA(),a=E.useMemo(()=>i?WYA:n,[i,n]);return E.useEffect(()=>{e&&!i&&s(!0)},[e,s,i]),e?C.jsx("div",{className:"modal-backdrop",role:"presentation",onClick:A,children:C.jsxs("div",{className:"modal-panel modal-panel--fullscreen leaderboard-modal",role:"dialog","aria-modal":"true","aria-label":"Leaderboards",onClick:I=>I.stopPropagation(),children:[C.jsxs("div",{className:"modal-header",children:[C.jsx("h3",{className:"modal-title",children:"Leaderboards"}),C.jsx("button",{className:"modal-close",onClick:A,"aria-label":"Close",children:"×"})]}),!i&&g&&C.jsx("p",{children:"Loading…"}),!i&&o&&C.jsx("p",{className:"error",role:"status",children:o}),a&&C.jsxs("div",{className:"leaderboard-sections",children:[((r=a.skillsStreaks)==null?void 0:r.length)>0&&C.jsxs("section",{children:[C.jsx("h4",{children:"🔥 Skills Win Streaks"}),C.jsx("ol",{className:"lb-list",children:a.skillsStreaks.map(I=>C.jsxs("li",{className:"lb-row",children:[C.jsxs("span",{className:"lb-rank",children:["#",I.rank]}),C.jsx("span",{className:"lb-name",children:I.name}),C.jsxs("span",{className:"lb-metric",children:[I.bestStreak," best",I.currentStreak>0?` · ${I.currentStreak} now 🔥`:""]})]},I.playerId))})]}),C.jsxs("section",{children:[C.jsx("h4",{children:"Top Balances"}),C.jsx("ol",{className:"lb-list",children:a.topBalances.map(I=>C.jsxs("li",{className:"lb-row",children:[C.jsxs("span",{className:"lb-rank",children:["#",I.rank]}),C.jsx("span",{className:"lb-name",children:I.name}),C.jsxs("span",{className:"lb-metric",children:[I.balance.toLocaleString()," chips"]})]},I.playerId))})]}),C.jsxs("section",{children:[C.jsx("h4",{children:"Weekly Winners"}),C.jsx("ol",{className:"lb-list",children:a.weeklyWinners.map(I=>C.jsxs("li",{className:"lb-row",children:[C.jsxs("span",{className:"lb-rank",children:["#",I.rank]}),C.jsx("span",{className:"lb-name",children:I.name}),C.jsxs("span",{className:"lb-metric",children:["+",I.amount.toLocaleString()," chips"]})]},I.playerId))})]}),C.jsxs("section",{children:[C.jsx("h4",{children:"All‑Time Winners"}),C.jsx("ol",{className:"lb-list",children:a.allTimeWinners.map(I=>C.jsxs("li",{className:"lb-row",children:[C.jsxs("span",{className:"lb-rank",children:["#",I.rank]}),C.jsx("span",{className:"lb-name",children:I.name}),C.jsxs("span",{className:"lb-metric",children:["+",I.amount.toLocaleString()," chips"]})]},I.playerId))})]}),a.zentaraAllTime&&a.zentaraAllTime.length>0&&C.jsxs("section",{children:[C.jsx("h4",{children:"🪐 Zentara · Top Conquerors"}),C.jsx("ol",{className:"lb-list",children:a.zentaraAllTime.map(I=>C.jsxs("li",{className:"lb-row",children:[C.jsxs("span",{className:"lb-rank",children:["#",I.rank]}),C.jsx("span",{className:"lb-name",children:I.name}),C.jsxs("span",{className:"lb-metric",children:["✦",I.credits.toLocaleString()," · ",I.wins," win",I.wins===1?"":"s"]})]},I.playerId))})]}),a.zentaraWeekly&&a.zentaraWeekly.length>0&&C.jsxs("section",{children:[C.jsx("h4",{children:"🛰️ Zentara · This Week"}),C.jsx("ol",{className:"lb-list",children:a.zentaraWeekly.map(I=>C.jsxs("li",{className:"lb-row",children:[C.jsxs("span",{className:"lb-rank",children:["#",I.rank]}),C.jsx("span",{className:"lb-name",children:I.name}),C.jsxs("span",{className:"lb-metric",children:["✦",I.credits.toLocaleString()," · ",I.wins," win",I.wins===1?"":"s"]})]},I.playerId))})]}),a.zentaraBiggestWin&&a.zentaraBiggestWin.length>0&&C.jsxs("section",{children:[C.jsx("h4",{children:"💥 Zentara · Biggest Victories"}),C.jsx("ol",{className:"lb-list",children:a.zentaraBiggestWin.map(I=>C.jsxs("li",{className:"lb-row",children:[C.jsxs("span",{className:"lb-rank",children:["#",I.rank]}),C.jsx("span",{className:"lb-name",children:I.name}),C.jsxs("span",{className:"lb-metric",children:["✦",I.credits.toLocaleString()]})]},I.playerId))})]}),a.zentaraTopEmpires&&a.zentaraTopEmpires.length>0&&C.jsxs("section",{children:[C.jsx("h4",{children:"👑 Zentara · Empire Dominance"}),C.jsx("ol",{className:"lb-list",children:a.zentaraTopEmpires.map(I=>C.jsxs("li",{className:"lb-row",children:[C.jsxs("span",{className:"lb-rank",children:["#",I.rank]}),C.jsx("span",{className:"lb-name",children:I.label}),C.jsxs("span",{className:"lb-metric",children:[I.wins," win",I.wins===1?"":"s"]})]},I.empire))})]})]})]})}):null}function XYA({open:e,onClose:A,onGoLogin:t,title:i,message:n}){const g=E.useRef(null),o=qi();if(E.useEffect(()=>{if(!e)return;const a=I=>{I.key==="Escape"&&A()},r=I=>{g.current&&!g.current.contains(I.target)&&A()};return document.addEventListener("keydown",a),document.addEventListener("mousedown",r),()=>{document.removeEventListener("keydown",a),document.removeEventListener("mousedown",r)}},[e,A]),!e)return null;const s=()=>{try{(t??(()=>o("/lobby")))()}finally{A()}};return C.jsx("div",{className:"modal-backdrop",role:"presentation",children:C.jsxs("div",{className:"modal-panel",role:"dialog","aria-modal":"true","aria-label":"Login required",ref:g,children:[C.jsx("button",{className:"modal-close",onClick:A,"aria-label":"Close",children:"×"}),C.jsx("h3",{className:"modal-title",children:i??"Login Required"}),n?C.jsx("div",{style:{marginTop:8},children:n}):C.jsx("p",{style:{marginTop:8},children:"You need to be logged in to access this feature."}),C.jsxs("div",{style:{display:"flex",gap:12,marginTop:16,justifyContent:"flex-end"},children:[C.jsx("button",{className:"felt-btn btn--ghost",onClick:A,children:"Cancel"}),C.jsx("button",{className:"felt-btn felt-btn--primary",onClick:s,children:"Go to Home"})]})]})})}const Ll=md("CapacitorUpdater",{web:()=>Qi(()=>import("./web-FhDKiIS1.js"),__vite__mapDeps([12,1])).then(e=>new e.CapacitorUpdaterWeb)});var G1={exports:{}};const $YA="2.0.0",VBA=256,AHA=Number.MAX_SAFE_INTEGER||9007199254740991,eHA=16,tHA=VBA-6,iHA=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var LL={MAX_LENGTH:VBA,MAX_SAFE_COMPONENT_LENGTH:eHA,MAX_SAFE_BUILD_LENGTH:tHA,MAX_SAFE_INTEGER:AHA,RELEASE_TYPES:iHA,SEMVER_SPEC_VERSION:$YA,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},S2={};const nHA=typeof process=="object"&&S2&&S2.NODE_DEBUG&&/\bsemver\b/i.test(S2.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};var xL=nHA;(function(e,A){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:i,MAX_LENGTH:n}=LL,g=xL;A=e.exports={};const o=A.re=[],s=A.safeRe=[],a=A.src=[],r=A.safeSrc=[],I=A.t={};let c=0;const l="[a-zA-Z0-9-]",B=[["\\s",1],["\\d",n],[l,i]],Q=d=>{for(const[p,y]of B)d=d.split(`${p}*`).join(`${p}{0,${y}}`).split(`${p}+`).join(`${p}{1,${y}}`);return d},h=(d,p,y)=>{const m=Q(p),D=c++;g(d,D,p),I[d]=D,a[D]=p,r[D]=m,o[D]=new RegExp(p,y?"g":void 0),s[D]=new RegExp(m,y?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${l}*`),h("MAINVERSION",`(${a[I.NUMERICIDENTIFIER]})\\.(${a[I.NUMERICIDENTIFIER]})\\.(${a[I.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${a[I.NUMERICIDENTIFIERLOOSE]})\\.(${a[I.NUMERICIDENTIFIERLOOSE]})\\.(${a[I.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${a[I.NONNUMERICIDENTIFIER]}|${a[I.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${a[I.NONNUMERICIDENTIFIER]}|${a[I.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${a[I.PRERELEASEIDENTIFIER]}(?:\\.${a[I.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${a[I.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[I.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${l}+`),h("BUILD",`(?:\\+(${a[I.BUILDIDENTIFIER]}(?:\\.${a[I.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${a[I.MAINVERSION]}${a[I.PRERELEASE]}?${a[I.BUILD]}?`),h("FULL",`^${a[I.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${a[I.MAINVERSIONLOOSE]}${a[I.PRERELEASELOOSE]}?${a[I.BUILD]}?`),h("LOOSE",`^${a[I.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${a[I.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${a[I.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${a[I.XRANGEIDENTIFIER]})(?:\\.(${a[I.XRANGEIDENTIFIER]})(?:\\.(${a[I.XRANGEIDENTIFIER]})(?:${a[I.PRERELEASE]})?${a[I.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${a[I.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[I.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[I.XRANGEIDENTIFIERLOOSE]})(?:${a[I.PRERELEASELOOSE]})?${a[I.BUILD]}?)?)?`),h("XRANGE",`^${a[I.GTLT]}\\s*${a[I.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${a[I.GTLT]}\\s*${a[I.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),h("COERCE",`${a[I.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",a[I.COERCEPLAIN]+`(?:${a[I.PRERELEASE]})?(?:${a[I.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",a[I.COERCE],!0),h("COERCERTLFULL",a[I.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${a[I.LONETILDE]}\\s+`,!0),A.tildeTrimReplace="$1~",h("TILDE",`^${a[I.LONETILDE]}${a[I.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${a[I.LONETILDE]}${a[I.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${a[I.LONECARET]}\\s+`,!0),A.caretTrimReplace="$1^",h("CARET",`^${a[I.LONECARET]}${a[I.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${a[I.LONECARET]}${a[I.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${a[I.GTLT]}\\s*(${a[I.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${a[I.GTLT]}\\s*(${a[I.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${a[I.GTLT]}\\s*(${a[I.LOOSEPLAIN]}|${a[I.XRANGEPLAIN]})`,!0),A.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${a[I.XRANGEPLAIN]})\\s+-\\s+(${a[I.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${a[I.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[I.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(G1,G1.exports);var TR=G1.exports;const gHA=Object.freeze({loose:!0}),oHA=Object.freeze({}),sHA=e=>e?typeof e!="object"?gHA:e:oHA;var r5=sHA;const Y7=/^[0-9]+$/,XBA=(e,A)=>{const t=Y7.test(e),i=Y7.test(A);return t&&i&&(e=+e,A=+A),e===A?0:t&&!i?-1:i&&!t?1:e<A?-1:1},aHA=(e,A)=>XBA(A,e);var $BA={compareIdentifiers:XBA,rcompareIdentifiers:aHA};const Rb=xL,{MAX_LENGTH:H7,MAX_SAFE_INTEGER:Gb}=LL,{safeRe:bb,t:Ub}=TR,rHA=r5,{compareIdentifiers:qy}=$BA;let IHA=class Fl{constructor(A,t){if(t=rHA(t),A instanceof Fl){if(A.loose===!!t.loose&&A.includePrerelease===!!t.includePrerelease)return A;A=A.version}else if(typeof A!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof A}".`);if(A.length>H7)throw new TypeError(`version is longer than ${H7} characters`);Rb("SemVer",A,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const i=A.trim().match(t.loose?bb[Ub.LOOSE]:bb[Ub.FULL]);if(!i)throw new TypeError(`Invalid Version: ${A}`);if(this.raw=A,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>Gb||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Gb||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Gb||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){const g=+n;if(g>=0&&g<Gb)return g}return n}):this.prerelease=[],this.build=i[5]?i[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(A){if(Rb("SemVer.compare",this.version,this.options,A),!(A instanceof Fl)){if(typeof A=="string"&&A===this.version)return 0;A=new Fl(A,this.options)}return A.version===this.version?0:this.compareMain(A)||this.comparePre(A)}compareMain(A){return A instanceof Fl||(A=new Fl(A,this.options)),qy(this.major,A.major)||qy(this.minor,A.minor)||qy(this.patch,A.patch)}comparePre(A){if(A instanceof Fl||(A=new Fl(A,this.options)),this.prerelease.length&&!A.prerelease.length)return-1;if(!this.prerelease.length&&A.prerelease.length)return 1;if(!this.prerelease.length&&!A.prerelease.length)return 0;let t=0;do{const i=this.prerelease[t],n=A.prerelease[t];if(Rb("prerelease compare",t,i,n),i===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(i===void 0)return-1;if(i===n)continue;return qy(i,n)}while(++t)}compareBuild(A){A instanceof Fl||(A=new Fl(A,this.options));let t=0;do{const i=this.build[t],n=A.build[t];if(Rb("build compare",t,i,n),i===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(i===void 0)return-1;if(i===n)continue;return qy(i,n)}while(++t)}inc(A,t,i){if(A.startsWith("pre")){if(!t&&i===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const n=`-${t}`.match(this.options.loose?bb[Ub.PRERELEASELOOSE]:bb[Ub.PRERELEASE]);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(A){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,i),this.inc("pre",t,i);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,i),this.inc("pre",t,i);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const n=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let g=this.prerelease.length;for(;--g>=0;)typeof this.prerelease[g]=="number"&&(this.prerelease[g]++,g=-2);if(g===-1){if(t===this.prerelease.join(".")&&i===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(t){let g=[t,n];i===!1&&(g=[t]),qy(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=g):this.prerelease=g}break}default:throw new Error(`invalid increment argument: ${A}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var Lr=IHA;const O7=Lr,CHA=(e,A,t=!1)=>{if(e instanceof O7)return e;try{return new O7(e,A)}catch(i){if(!t)return null;throw i}};var ww=CHA;const cHA=ww,lHA=(e,A)=>{const t=cHA(e,A);return t?t.version:null};var BHA=lHA;const EHA=ww,QHA=(e,A)=>{const t=EHA(e.trim().replace(/^[=v]+/,""),A);return t?t.version:null};var uHA=QHA;const P7=Lr,dHA=(e,A,t,i,n)=>{typeof t=="string"&&(n=i,i=t,t=void 0);try{return new P7(e instanceof P7?e.version:e,t).inc(A,i,n).version}catch{return null}};var hHA=dHA;const j7=ww,pHA=(e,A)=>{const t=j7(e,null,!0),i=j7(A,null,!0),n=t.compare(i);if(n===0)return null;const g=n>0,o=g?t:i,s=g?i:t,a=!!o.prerelease.length;if(!!s.prerelease.length&&!a){if(!s.patch&&!s.minor)return"major";if(s.compareMain(o)===0)return s.minor&&!s.patch?"minor":"patch"}const I=a?"pre":"";return t.major!==i.major?I+"major":t.minor!==i.minor?I+"minor":t.patch!==i.patch?I+"patch":"prerelease"};var fHA=pHA;const yHA=Lr,DHA=(e,A)=>new yHA(e,A).major;var mHA=DHA;const SHA=Lr,wHA=(e,A)=>new SHA(e,A).minor;var kHA=wHA;const MHA=Lr,NHA=(e,A)=>new MHA(e,A).patch;var RHA=NHA;const GHA=ww,bHA=(e,A)=>{const t=GHA(e,A);return t&&t.prerelease.length?t.prerelease:null};var UHA=bHA;const z7=Lr,vHA=(e,A,t)=>new z7(e,t).compare(new z7(A,t));var al=vHA;const KHA=al,FHA=(e,A,t)=>KHA(A,e,t);var _HA=FHA;const JHA=al,LHA=(e,A)=>JHA(e,A,!0);var xHA=LHA;const Z7=Lr,THA=(e,A,t)=>{const i=new Z7(e,t),n=new Z7(A,t);return i.compare(n)||i.compareBuild(n)};var I5=THA;const qHA=I5,YHA=(e,A)=>e.sort((t,i)=>qHA(t,i,A));var HHA=YHA;const OHA=I5,PHA=(e,A)=>e.sort((t,i)=>OHA(i,t,A));var jHA=PHA;const zHA=al,ZHA=(e,A,t)=>zHA(e,A,t)>0;var TL=ZHA;const WHA=al,VHA=(e,A,t)=>WHA(e,A,t)<0;var C5=VHA;const XHA=al,$HA=(e,A,t)=>XHA(e,A,t)===0;var AEA=$HA;const AOA=al,eOA=(e,A,t)=>AOA(e,A,t)!==0;var eEA=eOA;const tOA=al,iOA=(e,A,t)=>tOA(e,A,t)>=0;var c5=iOA;const nOA=al,gOA=(e,A,t)=>nOA(e,A,t)<=0;var l5=gOA;const oOA=AEA,sOA=eEA,aOA=TL,rOA=c5,IOA=C5,COA=l5,cOA=(e,A,t,i)=>{switch(A){case"===":return typeof e=="object"&&(e=e.version),typeof t=="object"&&(t=t.version),e===t;case"!==":return typeof e=="object"&&(e=e.version),typeof t=="object"&&(t=t.version),e!==t;case"":case"=":case"==":return oOA(e,t,i);case"!=":return sOA(e,t,i);case">":return aOA(e,t,i);case">=":return rOA(e,t,i);case"<":return IOA(e,t,i);case"<=":return COA(e,t,i);default:throw new TypeError(`Invalid operator: ${A}`)}};var tEA=cOA;const lOA=Lr,BOA=ww,{safeRe:vb,t:Kb}=TR,EOA=(e,A)=>{if(e instanceof lOA)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;A=A||{};let t=null;if(!A.rtl)t=e.match(A.includePrerelease?vb[Kb.COERCEFULL]:vb[Kb.COERCE]);else{const a=A.includePrerelease?vb[Kb.COERCERTLFULL]:vb[Kb.COERCERTL];let r;for(;(r=a.exec(e))&&(!t||t.index+t[0].length!==e.length);)(!t||r.index+r[0].length!==t.index+t[0].length)&&(t=r),a.lastIndex=r.index+r[1].length+r[2].length;a.lastIndex=-1}if(t===null)return null;const i=t[2],n=t[3]||"0",g=t[4]||"0",o=A.includePrerelease&&t[5]?`-${t[5]}`:"",s=A.includePrerelease&&t[6]?`+${t[6]}`:"";return BOA(`${i}.${n}.${g}${o}${s}`,A)};var QOA=EOA;class uOA{constructor(){this.max=1e3,this.map=new Map}get(A){const t=this.map.get(A);if(t!==void 0)return this.map.delete(A),this.map.set(A,t),t}delete(A){return this.map.delete(A)}set(A,t){if(!this.delete(A)&&t!==void 0){if(this.map.size>=this.max){const n=this.map.keys().next().value;this.delete(n)}this.map.set(A,t)}return this}}var dOA=uOA,w2,W7;function rl(){if(W7)return w2;W7=1;const e=/\s+/g;class A{constructor(q,v){if(v=n(v),q instanceof A)return q.loose===!!v.loose&&q.includePrerelease===!!v.includePrerelease?q:new A(q.raw,v);if(q instanceof g)return this.raw=q.value,this.set=[[q]],this.formatted=void 0,this;if(this.options=v,this.loose=!!v.loose,this.includePrerelease=!!v.includePrerelease,this.raw=q.trim().replace(e," "),this.set=this.raw.split("||").map(U=>this.parseRange(U.trim())).filter(U=>U.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const U=this.set[0];if(this.set=this.set.filter(x=>!h(x[0])),this.set.length===0)this.set=[U];else if(this.set.length>1){for(const x of this.set)if(x.length===1&&d(x[0])){this.set=[x];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let q=0;q<this.set.length;q++){q>0&&(this.formatted+="||");const v=this.set[q];for(let U=0;U<v.length;U++)U>0&&(this.formatted+=" "),this.formatted+=v[U].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(q){const U=((this.options.includePrerelease&&B)|(this.options.loose&&Q))+":"+q,x=i.get(U);if(x)return x;const T=this.options.loose,z=T?a[r.HYPHENRANGELOOSE]:a[r.HYPHENRANGE];q=q.replace(z,_(this.options.includePrerelease)),o("hyphen replace",q),q=q.replace(a[r.COMPARATORTRIM],I),o("comparator trim",q),q=q.replace(a[r.TILDETRIM],c),o("tilde trim",q),q=q.replace(a[r.CARETTRIM],l),o("caret trim",q);let Z=q.split(" ").map(pA=>y(pA,this.options)).join(" ").split(/\s+/).map(pA=>b(pA,this.options));T&&(Z=Z.filter(pA=>(o("loose invalid filter",pA,this.options),!!pA.match(a[r.COMPARATORLOOSE])))),o("range list",Z);const eA=new Map,aA=Z.map(pA=>new g(pA,this.options));for(const pA of aA){if(h(pA))return[pA];eA.set(pA.value,pA)}eA.size>1&&eA.has("")&&eA.delete("");const sA=[...eA.values()];return i.set(U,sA),sA}intersects(q,v){if(!(q instanceof A))throw new TypeError("a Range is required");return this.set.some(U=>p(U,v)&&q.set.some(x=>p(x,v)&&U.every(T=>x.every(z=>T.intersects(z,v)))))}test(q){if(!q)return!1;if(typeof q=="string")try{q=new s(q,this.options)}catch{return!1}for(let v=0;v<this.set.length;v++)if(K(this.set[v],q,this.options))return!0;return!1}}w2=A;const t=dOA,i=new t,n=r5,g=qL(),o=xL,s=Lr,{safeRe:a,t:r,comparatorTrimReplace:I,tildeTrimReplace:c,caretTrimReplace:l}=TR,{FLAG_INCLUDE_PRERELEASE:B,FLAG_LOOSE:Q}=LL,h=J=>J.value==="<0.0.0-0",d=J=>J.value==="",p=(J,q)=>{let v=!0;const U=J.slice();let x=U.pop();for(;v&&U.length;)v=U.every(T=>x.intersects(T,q)),x=U.pop();return v},y=(J,q)=>(o("comp",J,q),J=k(J,q),o("caret",J),J=D(J,q),o("tildes",J),J=G(J,q),o("xrange",J),J=w(J,q),o("stars",J),J),m=J=>!J||J.toLowerCase()==="x"||J==="*",D=(J,q)=>J.trim().split(/\s+/).map(v=>S(v,q)).join(" "),S=(J,q)=>{const v=q.loose?a[r.TILDELOOSE]:a[r.TILDE];return J.replace(v,(U,x,T,z,Z)=>{o("tilde",J,U,x,T,z,Z);let eA;return m(x)?eA="":m(T)?eA=`>=${x}.0.0 <${+x+1}.0.0-0`:m(z)?eA=`>=${x}.${T}.0 <${x}.${+T+1}.0-0`:Z?(o("replaceTilde pr",Z),eA=`>=${x}.${T}.${z}-${Z} <${x}.${+T+1}.0-0`):eA=`>=${x}.${T}.${z} <${x}.${+T+1}.0-0`,o("tilde return",eA),eA})},k=(J,q)=>J.trim().split(/\s+/).map(v=>N(v,q)).join(" "),N=(J,q)=>{o("caret",J,q);const v=q.loose?a[r.CARETLOOSE]:a[r.CARET],U=q.includePrerelease?"-0":"";return J.replace(v,(x,T,z,Z,eA)=>{o("caret",J,x,T,z,Z,eA);let aA;return m(T)?aA="":m(z)?aA=`>=${T}.0.0${U} <${+T+1}.0.0-0`:m(Z)?T==="0"?aA=`>=${T}.${z}.0${U} <${T}.${+z+1}.0-0`:aA=`>=${T}.${z}.0${U} <${+T+1}.0.0-0`:eA?(o("replaceCaret pr",eA),T==="0"?z==="0"?aA=`>=${T}.${z}.${Z}-${eA} <${T}.${z}.${+Z+1}-0`:aA=`>=${T}.${z}.${Z}-${eA} <${T}.${+z+1}.0-0`:aA=`>=${T}.${z}.${Z}-${eA} <${+T+1}.0.0-0`):(o("no pr"),T==="0"?z==="0"?aA=`>=${T}.${z}.${Z}${U} <${T}.${z}.${+Z+1}-0`:aA=`>=${T}.${z}.${Z}${U} <${T}.${+z+1}.0-0`:aA=`>=${T}.${z}.${Z} <${+T+1}.0.0-0`),o("caret return",aA),aA})},G=(J,q)=>(o("replaceXRanges",J,q),J.split(/\s+/).map(v=>M(v,q)).join(" ")),M=(J,q)=>{J=J.trim();const v=q.loose?a[r.XRANGELOOSE]:a[r.XRANGE];return J.replace(v,(U,x,T,z,Z,eA)=>{o("xRange",J,U,x,T,z,Z,eA);const aA=m(T),sA=aA||m(z),pA=sA||m(Z),gA=pA;return x==="="&&gA&&(x=""),eA=q.includePrerelease?"-0":"",aA?x===">"||x==="<"?U="<0.0.0-0":U="*":x&&gA?(sA&&(z=0),Z=0,x===">"?(x=">=",sA?(T=+T+1,z=0,Z=0):(z=+z+1,Z=0)):x==="<="&&(x="<",sA?T=+T+1:z=+z+1),x==="<"&&(eA="-0"),U=`${x+T}.${z}.${Z}${eA}`):sA?U=`>=${T}.0.0${eA} <${+T+1}.0.0-0`:pA&&(U=`>=${T}.${z}.0${eA} <${T}.${+z+1}.0-0`),o("xRange return",U),U})},w=(J,q)=>(o("replaceStars",J,q),J.trim().replace(a[r.STAR],"")),b=(J,q)=>(o("replaceGTE0",J,q),J.trim().replace(a[q.includePrerelease?r.GTE0PRE:r.GTE0],"")),_=J=>(q,v,U,x,T,z,Z,eA,aA,sA,pA,gA)=>(m(U)?v="":m(x)?v=`>=${U}.0.0${J?"-0":""}`:m(T)?v=`>=${U}.${x}.0${J?"-0":""}`:z?v=`>=${v}`:v=`>=${v}${J?"-0":""}`,m(aA)?eA="":m(sA)?eA=`<${+aA+1}.0.0-0`:m(pA)?eA=`<${aA}.${+sA+1}.0-0`:gA?eA=`<=${aA}.${sA}.${pA}-${gA}`:J?eA=`<${aA}.${sA}.${+pA+1}-0`:eA=`<=${eA}`,`${v} ${eA}`.trim()),K=(J,q,v)=>{for(let U=0;U<J.length;U++)if(!J[U].test(q))return!1;if(q.prerelease.length&&!v.includePrerelease){for(let U=0;U<J.length;U++)if(o(J[U].semver),J[U].semver!==g.ANY&&J[U].semver.prerelease.length>0){const x=J[U].semver;if(x.major===q.major&&x.minor===q.minor&&x.patch===q.patch)return!0}return!1}return!0};return w2}var k2,V7;function qL(){if(V7)return k2;V7=1;const e=Symbol("SemVer ANY");class A{static get ANY(){return e}constructor(I,c){if(c=t(c),I instanceof A){if(I.loose===!!c.loose)return I;I=I.value}I=I.trim().split(/\s+/).join(" "),o("comparator",I,c),this.options=c,this.loose=!!c.loose,this.parse(I),this.semver===e?this.value="":this.value=this.operator+this.semver.version,o("comp",this)}parse(I){const c=this.options.loose?i[n.COMPARATORLOOSE]:i[n.COMPARATOR],l=I.match(c);if(!l)throw new TypeError(`Invalid comparator: ${I}`);this.operator=l[1]!==void 0?l[1]:"",this.operator==="="&&(this.operator=""),l[2]?this.semver=new s(l[2],this.options.loose):this.semver=e}toString(){return this.value}test(I){if(o("Comparator.test",I,this.options.loose),this.semver===e||I===e)return!0;if(typeof I=="string")try{I=new s(I,this.options)}catch{return!1}return g(I,this.operator,this.semver,this.options)}intersects(I,c){if(!(I instanceof A))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new a(I.value,c).test(this.value):I.operator===""?I.value===""?!0:new a(this.value,c).test(I.semver):(c=t(c),c.includePrerelease&&(this.value==="<0.0.0-0"||I.value==="<0.0.0-0")||!c.includePrerelease&&(this.value.startsWith("<0.0.0")||I.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&I.operator.startsWith(">")||this.operator.startsWith("<")&&I.operator.startsWith("<")||this.semver.version===I.semver.version&&this.operator.includes("=")&&I.operator.includes("=")||g(this.semver,"<",I.semver,c)&&this.operator.startsWith(">")&&I.operator.startsWith("<")||g(this.semver,">",I.semver,c)&&this.operator.startsWith("<")&&I.operator.startsWith(">")))}}k2=A;const t=r5,{safeRe:i,t:n}=TR,g=tEA,o=xL,s=Lr,a=rl();return k2}const hOA=rl(),pOA=(e,A,t)=>{try{A=new hOA(A,t)}catch{return!1}return A.test(e)};var YL=pOA;const fOA=rl(),yOA=(e,A)=>new fOA(e,A).set.map(t=>t.map(i=>i.value).join(" ").trim().split(" "));var DOA=yOA;const mOA=Lr,SOA=rl(),wOA=(e,A,t)=>{let i=null,n=null,g=null;try{g=new SOA(A,t)}catch{return null}return e.forEach(o=>{g.test(o)&&(!i||n.compare(o)===-1)&&(i=o,n=new mOA(i,t))}),i};var kOA=wOA;const MOA=Lr,NOA=rl(),ROA=(e,A,t)=>{let i=null,n=null,g=null;try{g=new NOA(A,t)}catch{return null}return e.forEach(o=>{g.test(o)&&(!i||n.compare(o)===1)&&(i=o,n=new MOA(i,t))}),i};var GOA=ROA;const M2=Lr,bOA=rl(),X7=TL,UOA=(e,A)=>{e=new bOA(e,A);let t=new M2("0.0.0");if(e.test(t)||(t=new M2("0.0.0-0"),e.test(t)))return t;t=null;for(let i=0;i<e.set.length;++i){const n=e.set[i];let g=null;n.forEach(o=>{const s=new M2(o.semver.version);switch(o.operator){case">":s.prerelease.length===0?s.patch++:s.prerelease.push(0),s.raw=s.format();case"":case">=":(!g||X7(s,g))&&(g=s);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),g&&(!t||X7(t,g))&&(t=g)}return t&&e.test(t)?t:null};var vOA=UOA;const KOA=rl(),FOA=(e,A)=>{try{return new KOA(e,A).range||"*"}catch{return null}};var _OA=FOA;const JOA=Lr,iEA=qL(),{ANY:LOA}=iEA,xOA=rl(),TOA=YL,$7=TL,A$=C5,qOA=l5,YOA=c5,HOA=(e,A,t,i)=>{e=new JOA(e,i),A=new xOA(A,i);let n,g,o,s,a;switch(t){case">":n=$7,g=qOA,o=A$,s=">",a=">=";break;case"<":n=A$,g=YOA,o=$7,s="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(TOA(e,A,i))return!1;for(let r=0;r<A.set.length;++r){const I=A.set[r];let c=null,l=null;if(I.forEach(B=>{B.semver===LOA&&(B=new iEA(">=0.0.0")),c=c||B,l=l||B,n(B.semver,c.semver,i)?c=B:o(B.semver,l.semver,i)&&(l=B)}),c.operator===s||c.operator===a||(!l.operator||l.operator===s)&&g(e,l.semver))return!1;if(l.operator===a&&o(e,l.semver))return!1}return!0};var B5=HOA;const OOA=B5,POA=(e,A,t)=>OOA(e,A,">",t);var jOA=POA;const zOA=B5,ZOA=(e,A,t)=>zOA(e,A,"<",t);var WOA=ZOA;const e$=rl(),VOA=(e,A,t)=>(e=new e$(e,t),A=new e$(A,t),e.intersects(A,t));var XOA=VOA;const $OA=YL,APA=al;var ePA=(e,A,t)=>{const i=[];let n=null,g=null;const o=e.sort((I,c)=>APA(I,c,t));for(const I of o)$OA(I,A,t)?(g=I,n||(n=I)):(g&&i.push([n,g]),g=null,n=null);n&&i.push([n,null]);const s=[];for(const[I,c]of i)I===c?s.push(I):!c&&I===o[0]?s.push("*"):c?I===o[0]?s.push(`<=${c}`):s.push(`${I} - ${c}`):s.push(`>=${I}`);const a=s.join(" || "),r=typeof A.raw=="string"?A.raw:String(A);return a.length<r.length?a:A};const t$=rl(),E5=qL(),{ANY:N2}=E5,y0=YL,Q5=al,tPA=(e,A,t={})=>{if(e===A)return!0;e=new t$(e,t),A=new t$(A,t);let i=!1;A:for(const n of e.set){for(const g of A.set){const o=nPA(n,g,t);if(i=i||o!==null,o)continue A}if(i)return!1}return!0},iPA=[new E5(">=0.0.0-0")],i$=[new E5(">=0.0.0")],nPA=(e,A,t)=>{if(e===A)return!0;if(e.length===1&&e[0].semver===N2){if(A.length===1&&A[0].semver===N2)return!0;t.includePrerelease?e=iPA:e=i$}if(A.length===1&&A[0].semver===N2){if(t.includePrerelease)return!0;A=i$}const i=new Set;let n,g;for(const B of e)B.operator===">"||B.operator===">="?n=n$(n,B,t):B.operator==="<"||B.operator==="<="?g=g$(g,B,t):i.add(B.semver);if(i.size>1)return null;let o;if(n&&g){if(o=Q5(n.semver,g.semver,t),o>0)return null;if(o===0&&(n.operator!==">="||g.operator!=="<="))return null}for(const B of i){if(n&&!y0(B,String(n),t)||g&&!y0(B,String(g),t))return null;for(const Q of A)if(!y0(B,String(Q),t))return!1;return!0}let s,a,r,I,c=g&&!t.includePrerelease&&g.semver.prerelease.length?g.semver:!1,l=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1;c&&c.prerelease.length===1&&g.operator==="<"&&c.prerelease[0]===0&&(c=!1);for(const B of A){if(I=I||B.operator===">"||B.operator===">=",r=r||B.operator==="<"||B.operator==="<=",n){if(l&&B.semver.prerelease&&B.semver.prerelease.length&&B.semver.major===l.major&&B.semver.minor===l.minor&&B.semver.patch===l.patch&&(l=!1),B.operator===">"||B.operator===">="){if(s=n$(n,B,t),s===B&&s!==n)return!1}else if(n.operator===">="&&!y0(n.semver,String(B),t))return!1}if(g){if(c&&B.semver.prerelease&&B.semver.prerelease.length&&B.semver.major===c.major&&B.semver.minor===c.minor&&B.semver.patch===c.patch&&(c=!1),B.operator==="<"||B.operator==="<="){if(a=g$(g,B,t),a===B&&a!==g)return!1}else if(g.operator==="<="&&!y0(g.semver,String(B),t))return!1}if(!B.operator&&(g||n)&&o!==0)return!1}return!(n&&r&&!g&&o!==0||g&&I&&!n&&o!==0||l||c)},n$=(e,A,t)=>{if(!e)return A;const i=Q5(e.semver,A.semver,t);return i>0?e:i<0||A.operator===">"&&e.operator===">="?A:e},g$=(e,A,t)=>{if(!e)return A;const i=Q5(e.semver,A.semver,t);return i<0?e:i>0||A.operator==="<"&&e.operator==="<="?A:e};var gPA=tPA;const R2=TR,o$=LL,oPA=Lr,s$=$BA,sPA=ww,aPA=BHA,rPA=uHA,IPA=hHA,CPA=fHA,cPA=mHA,lPA=kHA,BPA=RHA,EPA=UHA,QPA=al,uPA=_HA,dPA=xHA,hPA=I5,pPA=HHA,fPA=jHA,yPA=TL,DPA=C5,mPA=AEA,SPA=eEA,wPA=c5,kPA=l5,MPA=tEA,NPA=QOA,RPA=qL(),GPA=rl(),bPA=YL,UPA=DOA,vPA=kOA,KPA=GOA,FPA=vOA,_PA=_OA,JPA=B5,LPA=jOA,xPA=WOA,TPA=XOA,qPA=ePA,YPA=gPA;var HPA={parse:sPA,valid:aPA,clean:rPA,inc:IPA,diff:CPA,major:cPA,minor:lPA,patch:BPA,prerelease:EPA,compare:QPA,rcompare:uPA,compareLoose:dPA,compareBuild:hPA,sort:pPA,rsort:fPA,gt:yPA,lt:DPA,eq:mPA,neq:SPA,gte:wPA,lte:kPA,cmp:MPA,coerce:NPA,Comparator:RPA,Range:GPA,satisfies:bPA,toComparators:UPA,maxSatisfying:vPA,minSatisfying:KPA,minVersion:FPA,validRange:_PA,outside:JPA,gtr:LPA,ltr:xPA,intersects:TPA,simplifyRange:qPA,subset:YPA,SemVer:oPA,re:R2.re,src:R2.src,tokens:R2.t,SEMVER_SPEC_VERSION:o$.SEMVER_SPEC_VERSION,RELEASE_TYPES:o$.RELEASE_TYPES,compareIdentifiers:s$.compareIdentifiers,rcompareIdentifiers:s$.rcompareIdentifiers};const Yy=nw(HPA),G2={},jF="https://updates.dicelounge.app";function OPA(){const A=String("zentara").trim().toLowerCase();let t=A==="craps"||A==="ceelo"||A==="poker"||A==="skills"||A==="zentara"?`${jF}/${A}/manifest.json`:`${jF}/manifest.json`;t=t.replace(/manifest\.jjson$/i,"manifest.json");try{Cn("OTA_MANIFEST_URL_RESOLVE",{target:A,url:t})}catch{}return t}function xl(){return Date.now()}function D0(){var e;try{const A=globalThis.Capacitor,t=(e=A==null?void 0:A.getPlatform)==null?void 0:e.call(A);return t==="ios"||t==="android"}catch{return!1}}function Cn(e,A){console.log(`[OTA] ${e}`,A)}function a$(e){if(!e)return"0.0.0";let A=e.replace(/^v/i,"").trim();const t=/^(\d+)\.0(\d+)$/.exec(A);if(t)return`${t[1]}.0.${parseInt(t[2],10)}`;const i=/^(\d+)\.(\d+)$/.exec(A);return i?`${i[1]}.${i[2]}.0`:A}function PPA(e){try{const A=new URL(e);return`${A.protocol}//${A.host}`===jF}catch{return!1}}async function jPA(e){if(!PPA(e))throw new Error("Manifest origin not allowed");const A=xl(),t=await fetch(e,{cache:"no-store",redirect:"error"});if(!t.ok)throw new Error(`HTTP ${t.status}`);const i=await t.json();return Cn("OTA_CHECK_FETCH",{ms:xl()-A}),i}async function zPA(e){const A=await e.arrayBuffer(),t=await crypto.subtle.digest("SHA-256",A);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}const r$=globalThis.OTA_PUBLIC_KEY_B64||(G2==null?void 0:G2.VITE_OTA_PUBKEY)||DGA,b2=!0,ZPA=50*1024*1024,WPA=/^(\d{12,14}|v?\d+\.\d+\.\d+(?:[-+].+)?)$/;async function VPA(){try{let e=Uint8Array.from(atob(r$),A=>A.charCodeAt(0));if(e.length>40&&e[0]===48)try{const A=e.slice(-32);A.length===32&&(e=A)}catch{}try{return await crypto.subtle.importKey("raw",e,{name:"Ed25519"},!1,["verify"])}catch{try{Cn("OTA_KEY_IMPORT_FAIL",{len:e.length})}catch{}return{legacyRaw:e}}}catch(e){try{Cn("OTA_KEY_PARSE_FAIL",{error:e==null?void 0:e.message})}catch{}return null}}const XPA=VPA();async function $PA(e,A){if(!e||!e.startsWith("ed25519:"))return!1;const t=e.slice(8);let i;try{i=Uint8Array.from(atob(t),s=>s.charCodeAt(0))}catch{return!1}const n=await XPA;if(!n)return!1;const g=`${A.webVersion}|${A.minNativeVersion}|${A.url}|${A.sha256}`,o=new TextEncoder().encode(g);try{const s=new Uint8Array(i);if(n.legacyRaw){try{Cn("OTA_VERIFY_UNSUPPORTED_ENV",{note:"allow_fallback_without_webcrypto_ed25519"})}catch{}return!0}return await crypto.subtle.verify({name:"Ed25519"},n,s,o)}catch{return!1}}class A1A{constructor(){Oi(this,"nativeVersion",null);Oi(this,"activeWebVersion",null);Oi(this,"pendingUpdateVersion",null);Oi(this,"previousWebVersion",null);Oi(this,"lastAppliedSha256",null)}async init(){var g;if(!D0()){Cn("OTA_INIT_SKIP_WEB",{});return}const A=xl(),t=await Nr.getInfo();this.nativeVersion=t.version;const i=await Ia.get({key:"ota_state"});if(i.value)try{const o=JSON.parse(i.value);this.activeWebVersion=o.activeWebVersion,this.pendingUpdateVersion=o.pendingUpdateVersion,this.previousWebVersion=o.previousWebVersion,this.lastAppliedSha256=o.lastAppliedSha256??null}catch{}const n=await Ll.current().catch(()=>null);n!=null&&n.version&&!this.activeWebVersion&&(this.activeWebVersion=n.version,await this.writePersist()),((g=n==null?void 0:n.bundle)==null?void 0:g.status)==="builtin"&&this.activeWebVersion&&(Cn("OTA_STALE_DETECT",{reason:"builtin_active_but_persisted_web_version",activeWebVersion:this.activeWebVersion}),this.activeWebVersion=null,this.pendingUpdateVersion=null,await this.writePersist(),await this.clearCaches()),Cn("OTA_INIT",{ms:xl()-A,nativeVersion:this.nativeVersion,currentWebVersion:this.activeWebVersion})}getVersions(){return{nativeVersion:this.nativeVersion,webVersion:this.activeWebVersion}}async checkForUpdate(A){const t=(A==null?void 0:A.force)===!0;let i=this.nativeVersion||null;if(!i&&D0())try{i=(await Nr.getInfo()).version||null,this.nativeVersion=i,Cn("OTA_NATIVE_VERSION_SYNC",{nativeVersion:i})}catch(n){Cn("OTA_NATIVE_VERSION_SYNC_FAIL",{error:n==null?void 0:n.message})}i=i||"0.0.0";try{const n=OPA(),g=await jPA(n),o=g==null?void 0:g.latest;if(!(o!=null&&o.webVersion)||!(o!=null&&o.minNativeVersion)||!(o!=null&&o.url)||!(o!=null&&o.sha256))return{available:!1,reason:"INVALID_MANIFEST",nativeVersion:i,currentWebVersion:this.activeWebVersion};try{Cn("OTA_MANIFEST_DEBUG",{fetchedVersion:o.webVersion,hasSig:!!o.sig,sigPrefix:o.sig?o.sig.slice(0,18):null,urlHost:(()=>{try{return new URL(o.url).host}catch{return"parse_err"}})()})}catch{}if(b2&&!o.sig)return Cn("OTA_CHECK",{reason:"INVALID_MANIFEST",note:"sig_missing_but_required"}),{available:!1,reason:"INVALID_MANIFEST",nativeVersion:i,currentWebVersion:this.activeWebVersion};if(!WPA.test(o.webVersion))return Cn("OTA_CHECK",{reason:"INVALID_MANIFEST",note:"version_pattern",version:o.webVersion}),{available:!1,reason:"INVALID_MANIFEST",nativeVersion:i,currentWebVersion:this.activeWebVersion};if(!/^https:\/\//.test(o.url))return Cn("OTA_CHECK",{reason:"INVALID_MANIFEST",note:"url_scheme"}),{available:!1,reason:"INVALID_MANIFEST",nativeVersion:i,currentWebVersion:this.activeWebVersion};if(!/^[a-f0-9]{64}$/i.test(o.sha256))return Cn("OTA_CHECK",{reason:"INVALID_MANIFEST",note:"sha256_format"}),{available:!1,reason:"INVALID_MANIFEST",nativeVersion:i,currentWebVersion:this.activeWebVersion};const s=a$(i),a=a$(o.minNativeVersion),r=Yy.coerce(a)||"0.0.0",I=Yy.coerce(s)||"0.0.0",c=Yy.gte(I,r);if(Cn("OTA_VERSION_CHECK",{rawNative:i,normalizedNative:s,rawMin:o.minNativeVersion,normalizedMin:a,nativeOk:c}),!c)return Cn("OTA_CHECK",{nativeVersion:i,normalizedNative:s,fromWebVersion:this.activeWebVersion,toWebVersion:o.webVersion,reason:"INCOMPATIBLE_NATIVE"}),{available:!1,reason:"INCOMPATIBLE_NATIVE",nativeVersion:i,currentWebVersion:this.activeWebVersion};if(!t&&this.pendingUpdateVersion&&this.pendingUpdateVersion===o.webVersion)return Cn("OTA_CHECK",{nativeVersion:i,fromWebVersion:this.activeWebVersion,toWebVersion:o.webVersion,reason:"NO_NEW_VERSION",note:"pending_update_same_version"}),{available:!1,reason:"NO_NEW_VERSION",nativeVersion:i,currentWebVersion:this.activeWebVersion};t&&this.pendingUpdateVersion&&this.pendingUpdateVersion===o.webVersion&&(Cn("OTA_CHECK_FORCE_CLEAR_PENDING",{pendingUpdateVersion:this.pendingUpdateVersion}),this.pendingUpdateVersion=null,await this.writePersist());const l=this.activeWebVersion;if(l&&l===o.webVersion)return Cn("OTA_CHECK",{nativeVersion:i,fromWebVersion:l,toWebVersion:o.webVersion,reason:"NO_NEW_VERSION",note:"equal_string"}),{available:!1,reason:"NO_NEW_VERSION",nativeVersion:i,currentWebVersion:l};const B=l?Yy.valid(l):null,Q=Yy.valid(o.webVersion);let h=!0;if(l)if(B&&Q)h=Yy.gt(o.webVersion,l);else if(/^\d+$/.test(o.webVersion)&&/^\d+$/.test(l)){const y=Number(o.webVersion),m=Number(l);!Number.isNaN(y)&&!Number.isNaN(m)&&(h=y>m)}else h=o.webVersion>l;if(l&&!h)return Cn("OTA_CHECK",{nativeVersion:i,fromWebVersion:l,toWebVersion:o.webVersion,reason:"NO_NEW_VERSION",note:"fallback_compare"}),{available:!1,reason:"NO_NEW_VERSION",nativeVersion:i,currentWebVersion:l};const d={...o};return Cn("OTA_CHECK",{nativeVersion:i,fromWebVersion:l,toWebVersion:d.webVersion,reason:"OK"}),{available:!0,reason:"OK",release:d,nativeVersion:i,currentWebVersion:l}}catch(n){return Cn("OTA_CHECK",{nativeVersion:i,fromWebVersion:this.activeWebVersion,error:(n==null?void 0:n.message)||String(n)}),{available:!1,reason:"NETWORK_ERROR",nativeVersion:i,currentWebVersion:this.activeWebVersion}}}async downloadUpdate(A,t){var h;if(!D0())throw new Error("OTA only applies on native platforms");const i=xl();t==null||t({stage:"downloading",percent:0});const n=new AbortController,g=setTimeout(()=>n.abort(),3e4),o=await fetch(A.url,{cache:"no-store",redirect:"error",signal:n.signal});if(clearTimeout(g),!o.ok||!o.body)throw new Error(`Download failed: ${o.status}`);const s=o.body.getReader(),a=[];let r=0;const I=Number(o.headers.get("content-length")||0);for(;;){const{done:d,value:p}=await s.read();if(d)break;if(p){if(a.push(p),r+=p.byteLength,r>ZPA)throw new Error("SIZE_LIMIT");I>0&&(t==null||t({stage:"downloading",bytes:r,total:I,percent:Math.round(r/I*100)}))}}const c=new Blob(a,{type:"application/zip"});t==null||t({stage:"verifying"});const l=await zPA(c);if(l.toLowerCase()!==A.sha256.toLowerCase())throw Cn("OTA_VERIFY_FAIL",{expected:A.sha256,got:l}),new Error("SHA256_MISMATCH");try{const d=new URL(A.url);if(`${d.protocol}//${d.host}`!==jF)throw new Error("ORIGIN_MISMATCH")}catch{throw new Error("ORIGIN_MISMATCH")}const B=!!A.sig;if(!await $PA(A.sig,A)){const d=B?"SIG_INVALID":"SIG_MISSING";if(Cn("OTA_VERIFY_FAIL",{reason:d,require:b2}),d==="SIG_MISSING"&&b2)try{Cn("OTA_VERIFY_FAIL_DETAIL",{releaseKeys:Object.keys(A),releaseVersion:A.webVersion,releaseUrl:A.url,sha256Len:(h=A.sha256)==null?void 0:h.length,note:"Signature field absent while signature required"})}catch{}throw new Error(d)}return Cn("OTA_VERIFY_OK",{ms:xl()-i,size:r}),{blob:c}}async clearCaches(){try{if("caches"in window){const A=await caches.keys();await Promise.all(A.map(t=>caches.delete(t))),Cn("OTA_CACHE_CLEAR",{type:"caches",count:A.length})}}catch(A){Cn("OTA_CACHE_CLEAR_FAIL",{type:"caches",error:String(A)})}try{if("serviceWorker"in navigator){const A=await navigator.serviceWorker.getRegistrations();await Promise.all(A.map(t=>t.unregister())),Cn("OTA_CACHE_CLEAR",{type:"serviceWorker",count:A.length})}}catch(A){Cn("OTA_CACHE_CLEAR_FAIL",{type:"serviceWorker",error:String(A)})}}async applyUpdate(A,t){if(!D0())throw new Error("OTA only applies on native platforms");const i=xl();Cn("OTA_APPLY",{toWebVersion:A.webVersion}),this.previousWebVersion=this.activeWebVersion,this.pendingUpdateVersion=A.webVersion,this.lastAppliedSha256=A.sha256,await this.writePersist(),await this.clearCaches();const n=6e4;try{Cn("OTA_APPLY_DOWNLOAD_START",{url:A.url,version:A.webVersion});const g=Ll.download({url:A.url,version:A.webVersion}),o=new Promise((a,r)=>setTimeout(()=>r(new Error("OTA_APPLY_TIMEOUT")),n)),s=await Promise.race([g,o]);Cn("OTA_APPLY_DOWNLOAD_DONE",{bundleId:s.id}),await Ll.set({id:s.id}),Cn("OTA_APPLY",{ms:xl()-i,fromWebVersion:this.previousWebVersion,toWebVersion:A.webVersion})}catch(g){throw Cn("OTA_APPLY_ERROR",{error:(g==null?void 0:g.message)||String(g),url:A.url}),g}}async healthCheck(){if(!D0())return!0;const A=this.pendingUpdateVersion;if(!A)return!0;if(await this.tryFetchHealth(2e3).catch(()=>!1)||await this.waitForAppMounted(5e3).catch(()=>!1)){this.activeWebVersion=A,this.pendingUpdateVersion=null;try{await Ll.notifyAppReady()}catch{}await this.writePersist();try{const i=window;i.__OTA_ACTIVATED__=!0,i.__OTA_ACTIVATED_VERSION__=this.activeWebVersion;try{window.dispatchEvent(new CustomEvent("ota:activated",{detail:{webVersion:this.activeWebVersion}}))}catch{}}catch{}return Cn("OTA_HEALTH_OK",{active:this.activeWebVersion}),this.cleanupOldBundles(),!0}return await this.rollbackIfBootFails(),!1}async tryFetchHealth(A){try{const t=new AbortController,i=setTimeout(()=>t.abort(),A),n=await fetch("/health",{signal:t.signal,cache:"no-store"});return clearTimeout(i),n.ok}catch{return!1}}async waitForAppMounted(A){const t=xl(),i=window;for(;xl()-t<A;){if(i.__APP_MOUNTED__)return!0;await new Promise(n=>setTimeout(n,100))}return!1}async rollbackIfBootFails(){try{await this.clearCaches(),await Ll.reset(),this.pendingUpdateVersion=null,this.activeWebVersion=this.previousWebVersion??null,await this.writePersist(),Cn("OTA_ROLLBACK",{toWebVersion:this.activeWebVersion}),location.reload()}catch(A){Cn("OTA_ROLLBACK_FAIL",{error:A==null?void 0:A.message})}}async cleanupOldBundles(){var A;try{const t=await Ll.list(),i=await Ll.current().catch(()=>null),n=(A=i==null?void 0:i.bundle)==null?void 0:A.id;for(const g of t.bundles||[])if(g.id&&g.id!==n&&g.status!=="builtin")try{await Ll.delete({id:g.id}),Cn("OTA_BUNDLE_CLEANUP",{deletedId:g.id})}catch{}}catch(t){Cn("OTA_BUNDLE_CLEANUP_FAIL",{error:t==null?void 0:t.message})}}async writePersist(){const A={activeWebVersion:this.activeWebVersion??null,pendingUpdateVersion:this.pendingUpdateVersion??null,previousWebVersion:this.previousWebVersion??null,lastAppliedSha256:this.lastAppliedSha256??null};await Ia.set({key:"ota_state",value:JSON.stringify(A)})}}const yr=new A1A,I$="ota:lastCheckAt",e1A=18e4;function t1A(){try{const e=globalThis.__E2E_OTA_COOLDOWN_MS;if(typeof e=="number"&&e>=0)return e}catch{}return e1A}function i1A(){const[e,A]=E.useState(yr.getVersions()),[t,i]=E.useState(!1),[n,g]=E.useState(null),[o,s]=E.useState({stage:"idle"}),a=E.useRef(null);E.useEffect(()=>{A(yr.getVersions())},[]);const r=E.useCallback(async()=>{i(!0);try{try{const B=Date.now(),Q=await Wc.get(I$),h=Q?Number(Q):0;if(h&&B-h<t1A()){i(!1);return}}catch{}const l=await yr.checkForUpdate();if(l.available&&l.release){g(l),a.current=l.release;try{const B=window;if(!B.__OTA_AUTO_APPLY_RUNNING__){B.__OTA_AUTO_APPLY_RUNNING__=!0,s({stage:"downloading",percent:0});const{blob:Q}=await yr.downloadUpdate(l.release,h=>s(h));s({stage:"applying"}),await yr.applyUpdate(l.release,Q)}}catch(B){console.error("[OTA] Auto-apply failed:",(B==null?void 0:B.message)||B),s({stage:"error",error:(B==null?void 0:B.message)||"Update failed"});try{window.__OTA_AUTO_APPLY_RUNNING__=!1}catch{}}}else l.reason==="NO_NEW_VERSION"?(g(null),a.current=null):g(l);try{await Wc.set(I$,String(Date.now()))}catch{}}finally{i(!1)}},[]),I=E.useCallback(async()=>{const l=a.current;if(!l)return;s({stage:"downloading",percent:0});const{blob:B}=await yr.downloadUpdate(l,Q=>s(Q));s({stage:"applying"}),await yr.applyUpdate(l,B)},[]),c=E.useCallback(()=>{s({stage:"idle"})},[]);return E.useEffect(()=>{r()},[r]),{current:e,checking:t,available:n,progress:o,applyNow:I,later:c}}function n1A({available:e,progress:A,applyNow:t,later:i}){if(!Ui.isNativePlatform()||!(e!=null&&e.available)||!e.release)return null;const n=e.release,g=A.percent??0,o=A.stage!=="error",s=A.stage==="downloading"?`Downloading update… ${g}%`:A.stage==="verifying"?"Verifying update…":A.stage==="applying"?"Installing update…":A.stage==="error"?`Update failed: ${A.error||"Unknown error"}`:"Preparing update…";return C.jsx("div",{className:"ota-overlay",children:C.jsxs("div",{className:"ota-overlay-content",children:[C.jsx("div",{className:"ota-overlay-icon","aria-hidden":!0,children:"🔄"}),C.jsxs("h2",{className:"ota-overlay-title",children:["Updating to ",n.webVersion]}),C.jsx("p",{className:"ota-overlay-status",children:s}),o&&C.jsx("div",{className:"ota-overlay-progress",children:C.jsx("div",{className:"ota-overlay-progress-bar",style:{width:`${Math.min(100,g)}%`}})}),A.stage==="error"&&C.jsx("button",{className:"ota-overlay-retry",onClick:t,children:"Retry"})]})})}function g1A({cooldownMs:e=3e4}){const A=E.useRef(!1);return E.useEffect(()=>{let t=[];async function i(o){if(!A.current){A.current=!0;try{const s=await yr.checkForUpdate();if(s.available&&s.release){try{const r=window;if(r.__OTA_AUTO_APPLY_RUNNING__)return;r.__OTA_AUTO_APPLY_RUNNING__=!0}catch{}const{blob:a}=await yr.downloadUpdate(s.release,r=>{});await yr.applyUpdate(s.release,a),setTimeout(()=>{try{window.location.reload()}catch{}},500)}}catch(s){s==null||s.message;try{window.__OTA_AUTO_APPLY_RUNNING__=!1}catch{}}finally{A.current=!1}}}(async()=>{try{const o=await Nr.addListener("appStateChange",s=>{s.isActive&&i("native_foreground")});t.push(()=>{try{o.remove()}catch{}})}catch{}})();const n=()=>{document.visibilityState==="visible"&&i()};document.addEventListener("visibilitychange",n),t.push(()=>document.removeEventListener("visibilitychange",n));const g=setTimeout(()=>i(),4e3);return t.push(()=>clearTimeout(g)),()=>{t.forEach(o=>{try{o()}catch{}})}},[e]),null}const o1A=Ca(),s1A={zentara:"Come play Zentara with me on Dice Lounge — we both get 1,000 chips when you join.",craps:"Let's roll some Craps on Dice Lounge — we both get 1,000 chips when you join.","cee-lo":"Play Cee-Lo with me on Dice Lounge — we both get 1,000 chips when you join.",poker:"Sit at my Poker table on Dice Lounge — we both get 1,000 chips when you join.",skills:"Run a Skills round with me on Dice Lounge — we both get 1,000 chips when you join."},a1A="Join me on Dice Lounge — we both get 1,000 chips when you sign up.";async function r1A(e,A){const t=`${A}
${e}`;try{const i=window.navigator;if(typeof(i==null?void 0:i.share)=="function")return await i.share({title:"Dice Lounge",text:A,url:e}),"shared"}catch(i){if((i==null?void 0:i.name)==="AbortError")return"shared"}try{return await navigator.clipboard.writeText(t),"copied"}catch{}try{return window.location.href=`sms:?body=${encodeURIComponent(t)}`,"shared"}catch{return"failed"}}function nEA({className:e,style:A,label:t,gameMode:i}){const[n,g]=E.useState(!1),[o,s]=E.useState(null),a=E.useCallback(async()=>{if(!n){g(!0),s(null);try{const r=await uo(),c=await(await fetch(`${o1A}/api/referral/link`,{method:"GET",credentials:"include",headers:r?{Authorization:`Bearer ${r}`}:void 0})).json().catch(()=>({})),l=typeof(c==null?void 0:c.url)=="string"?c.url:"";if(!l){s("Sign in to invite friends");return}const B=i&&s1A[i]||a1A,Q=await r1A(l,B);s(Q==="shared"?"Invite sent":Q==="copied"?"Link copied!":"Couldn't share — try again")}catch{s("Couldn't share — try again")}finally{g(!1),setTimeout(()=>s(null),2200)}}},[n,i]);return C.jsxs("button",{type:"button",onClick:a,disabled:n,className:e,"aria-label":"Invite a friend",style:{display:"inline-flex",alignItems:"center",gap:8,padding:"10px 16px",borderRadius:999,border:"1px solid rgba(255,255,255,0.18)",background:n?"rgba(60,60,60,0.6)":"linear-gradient(135deg, #5e60ce 0%, #4ea8de 100%)",color:"#fff",fontSize:14,fontWeight:600,cursor:n?"default":"pointer",boxShadow:"0 4px 14px rgba(0,0,0,0.35)",position:"relative",...A},children:[C.jsx("span",{"aria-hidden":!0,style:{fontSize:16},children:"+1k"}),C.jsx("span",{children:t||"Invite a Friend"}),o&&C.jsx("span",{role:"status","aria-live":"polite",style:{position:"absolute",top:"calc(100% + 8px)",left:"50%",transform:"translateX(-50%)",whiteSpace:"nowrap",background:"rgba(8,14,32,0.92)",color:"#e8efff",padding:"6px 10px",borderRadius:8,fontSize:12,pointerEvents:"none"},children:o})]})}function I1A(){const e=E.useRef(0),A=5e3;return E.useEffect(()=>{if(Ui.getPlatform()!=="ios")return;const t=[];async function i(g){const o=Date.now();if(!(o-e.current<A)){e.current=o;try{const s=await uo();if(!s)return;const a=String(ZM??"https://dicelounge.app").replace(/\/+$/,"");await fetch(`${a}/api/push/clear-badge`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch{}}}(async()=>{try{const g=await Nr.addListener("appStateChange",o=>{o.isActive&&i("native_foreground")});t.push(()=>{try{g.remove()}catch{}})}catch{}})();const n=setTimeout(()=>i(),1e3);return t.push(()=>clearTimeout(n)),()=>{t.forEach(g=>{try{g()}catch{}})}},[]),null}const C1A="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2024%2024'%20width='24'%20height='24'%20role='img'%20aria-label='Help'%3e%3cdefs%3e%3c!--%20Polished%20gold%20body%20with%20higher%20contrast%20for%20small%20sizes%20--%3e%3clinearGradient%20id='qg-body'%20x1='0'%20y1='0'%20x2='0'%20y2='1'%3e%3cstop%20offset='0%25'%20stop-color='%23fff6cf'/%3e%3cstop%20offset='40%25'%20stop-color='%23ffd873'/%3e%3cstop%20offset='72%25'%20stop-color='%23e0a614'/%3e%3cstop%20offset='100%25'%20stop-color='%239a6b00'/%3e%3c/linearGradient%3e%3c!--%20Subtle%20outline%20that%20remains%20crisp%20at%201x%20and%201.5x%20--%3e%3clinearGradient%20id='qg-edge'%20x1='0'%20y1='0'%20x2='1'%20y2='1'%3e%3cstop%20offset='0%25'%20stop-color='%23ffffff'%20stop-opacity='0.8'/%3e%3cstop%20offset='100%25'%20stop-color='%236e4a00'%20stop-opacity='0.6'/%3e%3c/linearGradient%3e%3c!--%20Inner%20shadow%20for%20depth%20--%3e%3cfilter%20id='qg-inner'%20x='-20%25'%20y='-20%25'%20width='140%25'%20height='140%25'%3e%3cfeOffset%20dy='0.2'/%3e%3cfeGaussianBlur%20stdDeviation='0.4'%20result='b'/%3e%3cfeComposite%20in2='b'%20in='SourceAlpha'%20operator='arithmetic'%20k2='-1'%20k3='1'%20result='inner'/%3e%3cfeColorMatrix%20in='inner'%20type='matrix'%20values='0%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200.55%200'/%3e%3cfeBlend%20in='SourceGraphic'%20mode='overlay'/%3e%3c/filter%3e%3c!--%20Gentle%20rim%20light%20on%20upper-left%20--%3e%3clinearGradient%20id='qg-sheen'%20x1='0'%20y1='0'%20x2='0'%20y2='1'%3e%3cstop%20offset='0%25'%20stop-color='%23ffffff'%20stop-opacity='0.55'/%3e%3cstop%20offset='60%25'%20stop-color='%23ffffff'%20stop-opacity='0'/%3e%3c/linearGradient%3e%3cmask%20id='qg-top'%3e%3crect%20width='24'%20height='24'%20fill='%23000'/%3e%3crect%20width='24'%20height='11'%20fill='%23fff'/%3e%3c/mask%3e%3c/defs%3e%3cg%20filter='url(%23qg-inner)'%3e%3c!--%20Main%20mark%20--%3e%3cpath%20d='M12%202.2c-2.28%200-4.12.63-5.38%201.78C5.32%205.1%204.8%206.54%204.8%208.2c0%20.42.34.76.76.76h1.8c.36%200%20.67-.26.75-.61.18-.78.54-1.37%201.07-1.83.62-.54%201.58-.88%202.86-.88%201.07%200%201.9.23%202.43.68.53.45.8%201.06.8%201.92%200%20.76-.26%201.33-.83%201.83-.52.48-1.24.9-2.26%201.44-1.13.6-2.03%201.23-2.64%202.05-.65.86-.94%201.88-.94%203.2v.07c0%20.42.34.76.76.76h1.98c.42%200%20.76-.34.76-.76v-.07c0-.69.16-1.18.5-1.57.36-.42.98-.85%202-.36%201.19-.62%202.15-1.25%202.9-2.02.99-1.01%201.5-2.29%201.5-3.87%200-1.74-.64-3.21-1.83-4.25C16.12%202.76%2014.25%202.2%2012%202.2Z'%20fill='url(%23qg-body)'%20stroke='url(%23qg-edge)'%20stroke-width='0.9'%20stroke-linejoin='round'/%3e%3c!--%20Dot%20--%3e%3c!--%20Dot:%20centered%20under%20the%20stem%20for%20optical%20alignment%20at%2024–33px%20--%3e%3ccircle%20cx='11.2'%20cy='21.0'%20r='1.7'%20fill='url(%23qg-body)'%20stroke='url(%23qg-edge)'%20stroke-width='0.85'/%3e%3c!--%20Sheen%20overlay%20--%3e%3cpath%20d='M12%202.2c-2.28%200-4.12.63-5.38%201.78C5.32%205.1%204.8%206.54%204.8%208.2c0%20.42.34.76.76.76h1.8c.36%200%20.67-.26.75-.61.18-.78.54-1.37%201.07-1.83.62-.54%201.58-.88%202.86-.88%201.07%200%201.9.23%202.43.68.53.45.8%201.06.8%201.92%200%20.76-.26%201.33-.83%201.83-.52.48-1.24.9-2.26%201.44-1.13.6-2.03%201.23-2.64%202.05-.65.86-.94%201.88-.94%203.2v.07c0%20.42.34.76.76.76h1.98c.42%200%20.76-.34.76-.76v-.07c0-.69.16-1.18.5-1.57.36-.42.98-.85%202-.36%201.19-.62%202.15-1.25%202.9-2.02.99-1.01%201.5-2.29%201.5-3.87%200-1.74-.64-3.21-1.83-4.25C16.12%202.76%2014.25%202.2%2012%202.2Z'%20fill='url(%23qg-sheen)'%20mask='url(%23qg-top)'/%3e%3c/g%3e%3c/svg%3e";function Jp(){return C.jsxs("footer",{className:"lp-footer",children:[C.jsxs("nav",{className:"lp-footer__links","aria-label":"Footer",children:[C.jsx(HI,{to:"/disclaimer",className:"lp-footer__link",children:"Disclaimer (18+)"}),C.jsx("span",{className:"lp-dot","aria-hidden":!0,children:"•"}),C.jsx(HI,{to:"/privacy",className:"lp-footer__link",children:"Privacy Policy"}),C.jsx("span",{className:"lp-dot","aria-hidden":!0,children:"•"}),C.jsx(HI,{to:"/terms",className:"lp-footer__link",children:"Terms of Use"}),C.jsx("span",{className:"lp-dot","aria-hidden":!0,children:"•"}),C.jsx(HI,{to:"/support",className:"lp-footer__link",children:"Support"})]}),C.jsx("p",{className:"lp-footnote",role:"note",children:"For entertainment purposes only. No real-money gambling or prizes."}),C.jsxs("p",{className:"lp-copy",children:["© ",new Date().getFullYear()," Zentara One LLC. All rights reserved."]})]})}const b1="/assets/logo-Bd_WWMIU.webp",c1A="/assets/ceelo-icon-DBUGq3gk.webp",l1A="/assets/craps-icon-Cxbu5IDi.webp",B1A="/assets/poker-icon-D9lS6jix.webp",E1A="/assets/skills-icon-BWMGnrDl.webp",Q1A="/assets/zentara-icon-PkjJTbqN.webp";/*!
 * Font Awesome Free 7.0.0 by @fontawesome - https://fontawesome.com
 * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
 * Copyright 2025 Fonticons, Inc.
 */function U1(e,A){(A==null||A>e.length)&&(A=e.length);for(var t=0,i=Array(A);t<A;t++)i[t]=e[t];return i}function u1A(e){if(Array.isArray(e))return e}function d1A(e){if(Array.isArray(e))return U1(e)}function h1A(e,A){if(!(e instanceof A))throw new TypeError("Cannot call a class as a function")}function p1A(e,A){for(var t=0;t<A.length;t++){var i=A[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,gEA(i.key),i)}}function f1A(e,A,t){return A&&p1A(e.prototype,A),Object.defineProperty(e,"prototype",{writable:!1}),e}function IK(e,A){var t=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!t){if(Array.isArray(e)||(t=u5(e))||A){t&&(e=t);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(a){throw a},f:n}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var g,o=!0,s=!1;return{s:function(){t=t.call(e)},n:function(){var a=t.next();return o=a.done,a},e:function(a){s=!0,g=a},f:function(){try{o||t.return==null||t.return()}finally{if(s)throw g}}}}function Pn(e,A,t){return(A=gEA(A))in e?Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[A]=t,e}function y1A(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function D1A(e,A){var t=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(t!=null){var i,n,g,o,s=[],a=!0,r=!1;try{if(g=(t=t.call(e)).next,A===0){if(Object(t)!==t)return;a=!1}else for(;!(a=(i=g.call(t)).done)&&(s.push(i.value),s.length!==A);a=!0);}catch(I){r=!0,n=I}finally{try{if(!a&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(r)throw n}}return s}}function m1A(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function S1A(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function C$(e,A){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);A&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),t.push.apply(t,i)}return t}function Rt(e){for(var A=1;A<arguments.length;A++){var t=arguments[A]!=null?arguments[A]:{};A%2?C$(Object(t),!0).forEach(function(i){Pn(e,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):C$(Object(t)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(t,i))})}return e}function HL(e,A){return u1A(e)||D1A(e,A)||u5(e,A)||m1A()}function Al(e){return d1A(e)||y1A(e)||u5(e)||S1A()}function w1A(e,A){if(typeof e!="object"||!e)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var i=t.call(e,A);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(A==="string"?String:Number)(e)}function gEA(e){var A=w1A(e,"string");return typeof A=="symbol"?A:A+""}function zF(e){"@babel/helpers - typeof";return zF=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(A){return typeof A}:function(A){return A&&typeof Symbol=="function"&&A.constructor===Symbol&&A!==Symbol.prototype?"symbol":typeof A},zF(e)}function u5(e,A){if(e){if(typeof e=="string")return U1(e,A);var t={}.toString.call(e).slice(8,-1);return t==="Object"&&e.constructor&&(t=e.constructor.name),t==="Map"||t==="Set"?Array.from(e):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?U1(e,A):void 0}}var c$=function(){},d5={},oEA={},sEA=null,aEA={mark:c$,measure:c$};try{typeof window<"u"&&(d5=window),typeof document<"u"&&(oEA=document),typeof MutationObserver<"u"&&(sEA=MutationObserver),typeof performance<"u"&&(aEA=performance)}catch{}var k1A=d5.navigator||{},l$=k1A.userAgent,B$=l$===void 0?"":l$,ad=d5,go=oEA,E$=sEA,Fb=aEA;ad.document;var BQ=!!go.documentElement&&!!go.head&&typeof go.addEventListener=="function"&&typeof go.createElement=="function",rEA=~B$.indexOf("MSIE")||~B$.indexOf("Trident/"),U2,M1A=/fa(k|kd|s|r|l|t|d|dr|dl|dt|b|slr|slpr|wsb|tl|ns|nds|es|jr|jfr|jdr|cr|ss|sr|sl|st|sds|sdr|sdl|sdt)?[\-\ ]/,N1A=/Font ?Awesome ?([567 ]*)(Solid|Regular|Light|Thin|Duotone|Brands|Free|Pro|Sharp Duotone|Sharp|Kit|Notdog Duo|Notdog|Chisel|Etch|Thumbprint|Jelly Fill|Jelly Duo|Jelly|Slab Press|Slab|Whiteboard)?.*/i,IEA={classic:{fa:"solid",fas:"solid","fa-solid":"solid",far:"regular","fa-regular":"regular",fal:"light","fa-light":"light",fat:"thin","fa-thin":"thin",fab:"brands","fa-brands":"brands"},duotone:{fa:"solid",fad:"solid","fa-solid":"solid","fa-duotone":"solid",fadr:"regular","fa-regular":"regular",fadl:"light","fa-light":"light",fadt:"thin","fa-thin":"thin"},sharp:{fa:"solid",fass:"solid","fa-solid":"solid",fasr:"regular","fa-regular":"regular",fasl:"light","fa-light":"light",fast:"thin","fa-thin":"thin"},"sharp-duotone":{fa:"solid",fasds:"solid","fa-solid":"solid",fasdr:"regular","fa-regular":"regular",fasdl:"light","fa-light":"light",fasdt:"thin","fa-thin":"thin"},slab:{"fa-regular":"regular",faslr:"regular"},"slab-press":{"fa-regular":"regular",faslpr:"regular"},thumbprint:{"fa-light":"light",fatl:"light"},whiteboard:{"fa-semibold":"semibold",fawsb:"semibold"},notdog:{"fa-solid":"solid",fans:"solid"},"notdog-duo":{"fa-solid":"solid",fands:"solid"},etch:{"fa-solid":"solid",faes:"solid"},jelly:{"fa-regular":"regular",fajr:"regular"},"jelly-fill":{"fa-regular":"regular",fajfr:"regular"},"jelly-duo":{"fa-regular":"regular",fajdr:"regular"},chisel:{"fa-regular":"regular",facr:"regular"}},R1A={GROUP:"duotone-group",PRIMARY:"primary",SECONDARY:"secondary"},CEA=["fa-classic","fa-duotone","fa-sharp","fa-sharp-duotone","fa-thumbprint","fa-whiteboard","fa-notdog","fa-notdog-duo","fa-chisel","fa-etch","fa-jelly","fa-jelly-fill","fa-jelly-duo","fa-slab","fa-slab-press"],gr="classic",qR="duotone",cEA="sharp",lEA="sharp-duotone",BEA="chisel",EEA="etch",QEA="jelly",uEA="jelly-duo",dEA="jelly-fill",hEA="notdog",pEA="notdog-duo",fEA="slab",yEA="slab-press",DEA="thumbprint",mEA="whiteboard",G1A="Classic",b1A="Duotone",U1A="Sharp",v1A="Sharp Duotone",K1A="Chisel",F1A="Etch",_1A="Jelly",J1A="Jelly Duo",L1A="Jelly Fill",x1A="Notdog",T1A="Notdog Duo",q1A="Slab",Y1A="Slab Press",H1A="Thumbprint",O1A="Whiteboard",SEA=[gr,qR,cEA,lEA,BEA,EEA,QEA,uEA,dEA,hEA,pEA,fEA,yEA,DEA,mEA];U2={},Pn(Pn(Pn(Pn(Pn(Pn(Pn(Pn(Pn(Pn(U2,gr,G1A),qR,b1A),cEA,U1A),lEA,v1A),BEA,K1A),EEA,F1A),QEA,_1A),uEA,J1A),dEA,L1A),hEA,x1A),Pn(Pn(Pn(Pn(Pn(U2,pEA,T1A),fEA,q1A),yEA,Y1A),DEA,H1A),mEA,O1A);var P1A={classic:{900:"fas",400:"far",normal:"far",300:"fal",100:"fat"},duotone:{900:"fad",400:"fadr",300:"fadl",100:"fadt"},sharp:{900:"fass",400:"fasr",300:"fasl",100:"fast"},"sharp-duotone":{900:"fasds",400:"fasdr",300:"fasdl",100:"fasdt"},slab:{400:"faslr"},"slab-press":{400:"faslpr"},whiteboard:{600:"fawsb"},thumbprint:{300:"fatl"},notdog:{900:"fans"},"notdog-duo":{900:"fands"},etch:{900:"faes"},chisel:{400:"facr"},jelly:{400:"fajr"},"jelly-fill":{400:"fajfr"},"jelly-duo":{400:"fajdr"}},j1A={"Font Awesome 7 Free":{900:"fas",400:"far"},"Font Awesome 7 Pro":{900:"fas",400:"far",normal:"far",300:"fal",100:"fat"},"Font Awesome 7 Brands":{400:"fab",normal:"fab"},"Font Awesome 7 Duotone":{900:"fad",400:"fadr",normal:"fadr",300:"fadl",100:"fadt"},"Font Awesome 7 Sharp":{900:"fass",400:"fasr",normal:"fasr",300:"fasl",100:"fast"},"Font Awesome 7 Sharp Duotone":{900:"fasds",400:"fasdr",normal:"fasdr",300:"fasdl",100:"fasdt"},"Font Awesome 7 Jelly":{400:"fajr",normal:"fajr"},"Font Awesome 7 Jelly Fill":{400:"fajfr",normal:"fajfr"},"Font Awesome 7 Jelly Duo":{400:"fajdr",normal:"fajdr"},"Font Awesome 7 Slab":{400:"faslr",normal:"faslr"},"Font Awesome 7 Slab Press":{400:"faslpr",normal:"faslpr"},"Font Awesome 7 Thumbprint":{300:"fatl",normal:"fatl"},"Font Awesome 7 Notdog":{900:"fans",normal:"fans"},"Font Awesome 7 Notdog Duo":{900:"fands",normal:"fands"},"Font Awesome 7 Etch":{900:"faes",normal:"faes"},"Font Awesome 7 Chisel":{400:"facr",normal:"facr"},"Font Awesome 7 Whiteboard":{600:"fawsb",normal:"fawsb"}},z1A=new Map([["classic",{defaultShortPrefixId:"fas",defaultStyleId:"solid",styleIds:["solid","regular","light","thin","brands"],futureStyleIds:[],defaultFontWeight:900}],["duotone",{defaultShortPrefixId:"fad",defaultStyleId:"solid",styleIds:["solid","regular","light","thin"],futureStyleIds:[],defaultFontWeight:900}],["sharp",{defaultShortPrefixId:"fass",defaultStyleId:"solid",styleIds:["solid","regular","light","thin"],futureStyleIds:[],defaultFontWeight:900}],["sharp-duotone",{defaultShortPrefixId:"fasds",defaultStyleId:"solid",styleIds:["solid","regular","light","thin"],futureStyleIds:[],defaultFontWeight:900}],["chisel",{defaultShortPrefixId:"facr",defaultStyleId:"regular",styleIds:["regular"],futureStyleIds:[],defaultFontWeight:400}],["etch",{defaultShortPrefixId:"faes",defaultStyleId:"solid",styleIds:["solid"],futureStyleIds:[],defaultFontWeight:900}],["jelly",{defaultShortPrefixId:"fajr",defaultStyleId:"regular",styleIds:["regular"],futureStyleIds:[],defaultFontWeight:400}],["jelly-duo",{defaultShortPrefixId:"fajdr",defaultStyleId:"regular",styleIds:["regular"],futureStyleIds:[],defaultFontWeight:400}],["jelly-fill",{defaultShortPrefixId:"fajfr",defaultStyleId:"regular",styleIds:["regular"],futureStyleIds:[],defaultFontWeight:400}],["notdog",{defaultShortPrefixId:"fans",defaultStyleId:"solid",styleIds:["solid"],futureStyleIds:[],defaultFontWeight:900}],["notdog-duo",{defaultShortPrefixId:"fands",defaultStyleId:"solid",styleIds:["solid"],futureStyleIds:[],defaultFontWeight:900}],["slab",{defaultShortPrefixId:"faslr",defaultStyleId:"regular",styleIds:["regular"],futureStyleIds:[],defaultFontWeight:400}],["slab-press",{defaultShortPrefixId:"faslpr",defaultStyleId:"regular",styleIds:["regular"],futureStyleIds:[],defaultFontWeight:400}],["thumbprint",{defaultShortPrefixId:"fatl",defaultStyleId:"light",styleIds:["light"],futureStyleIds:[],defaultFontWeight:300}],["whiteboard",{defaultShortPrefixId:"fawsb",defaultStyleId:"semibold",styleIds:["semibold"],futureStyleIds:[],defaultFontWeight:600}]]),Z1A={chisel:{regular:"facr"},classic:{brands:"fab",light:"fal",regular:"far",solid:"fas",thin:"fat"},duotone:{light:"fadl",regular:"fadr",solid:"fad",thin:"fadt"},etch:{solid:"faes"},jelly:{regular:"fajr"},"jelly-duo":{regular:"fajdr"},"jelly-fill":{regular:"fajfr"},notdog:{solid:"fans"},"notdog-duo":{solid:"fands"},sharp:{light:"fasl",regular:"fasr",solid:"fass",thin:"fast"},"sharp-duotone":{light:"fasdl",regular:"fasdr",solid:"fasds",thin:"fasdt"},slab:{regular:"faslr"},"slab-press":{regular:"faslpr"},thumbprint:{light:"fatl"},whiteboard:{semibold:"fawsb"}},wEA=["fak","fa-kit","fakd","fa-kit-duotone"],Q$={kit:{fak:"kit","fa-kit":"kit"},"kit-duotone":{fakd:"kit-duotone","fa-kit-duotone":"kit-duotone"}},W1A=["kit"],V1A="kit",X1A="kit-duotone",$1A="Kit",A3A="Kit Duotone";Pn(Pn({},V1A,$1A),X1A,A3A);var e3A={kit:{"fa-kit":"fak"}},t3A={"Font Awesome Kit":{400:"fak",normal:"fak"},"Font Awesome Kit Duotone":{400:"fakd",normal:"fakd"}},i3A={kit:{fak:"fa-kit"}},u$={kit:{kit:"fak"},"kit-duotone":{"kit-duotone":"fakd"}},v2,_b={GROUP:"duotone-group",SWAP_OPACITY:"swap-opacity",PRIMARY:"primary",SECONDARY:"secondary"},n3A=["fa-classic","fa-duotone","fa-sharp","fa-sharp-duotone","fa-thumbprint","fa-whiteboard","fa-notdog","fa-notdog-duo","fa-chisel","fa-etch","fa-jelly","fa-jelly-fill","fa-jelly-duo","fa-slab","fa-slab-press"],g3A="classic",o3A="duotone",s3A="sharp",a3A="sharp-duotone",r3A="chisel",I3A="etch",C3A="jelly",c3A="jelly-duo",l3A="jelly-fill",B3A="notdog",E3A="notdog-duo",Q3A="slab",u3A="slab-press",d3A="thumbprint",h3A="whiteboard",p3A="Classic",f3A="Duotone",y3A="Sharp",D3A="Sharp Duotone",m3A="Chisel",S3A="Etch",w3A="Jelly",k3A="Jelly Duo",M3A="Jelly Fill",N3A="Notdog",R3A="Notdog Duo",G3A="Slab",b3A="Slab Press",U3A="Thumbprint",v3A="Whiteboard";v2={},Pn(Pn(Pn(Pn(Pn(Pn(Pn(Pn(Pn(Pn(v2,g3A,p3A),o3A,f3A),s3A,y3A),a3A,D3A),r3A,m3A),I3A,S3A),C3A,w3A),c3A,k3A),l3A,M3A),B3A,N3A),Pn(Pn(Pn(Pn(Pn(v2,E3A,R3A),Q3A,G3A),u3A,b3A),d3A,U3A),h3A,v3A);var K3A="kit",F3A="kit-duotone",_3A="Kit",J3A="Kit Duotone";Pn(Pn({},K3A,_3A),F3A,J3A);var L3A={classic:{"fa-brands":"fab","fa-duotone":"fad","fa-light":"fal","fa-regular":"far","fa-solid":"fas","fa-thin":"fat"},duotone:{"fa-regular":"fadr","fa-light":"fadl","fa-thin":"fadt"},sharp:{"fa-solid":"fass","fa-regular":"fasr","fa-light":"fasl","fa-thin":"fast"},"sharp-duotone":{"fa-solid":"fasds","fa-regular":"fasdr","fa-light":"fasdl","fa-thin":"fasdt"},slab:{"fa-regular":"faslr"},"slab-press":{"fa-regular":"faslpr"},whiteboard:{"fa-semibold":"fawsb"},thumbprint:{"fa-light":"fatl"},notdog:{"fa-solid":"fans"},"notdog-duo":{"fa-solid":"fands"},etch:{"fa-solid":"faes"},jelly:{"fa-regular":"fajr"},"jelly-fill":{"fa-regular":"fajfr"},"jelly-duo":{"fa-regular":"fajdr"},chisel:{"fa-regular":"facr"}},x3A={classic:["fas","far","fal","fat","fad"],duotone:["fadr","fadl","fadt"],sharp:["fass","fasr","fasl","fast"],"sharp-duotone":["fasds","fasdr","fasdl","fasdt"],slab:["faslr"],"slab-press":["faslpr"],whiteboard:["fawsb"],thumbprint:["fatl"],notdog:["fans"],"notdog-duo":["fands"],etch:["faes"],jelly:["fajr"],"jelly-fill":["fajfr"],"jelly-duo":["fajdr"],chisel:["facr"]},v1={classic:{fab:"fa-brands",fad:"fa-duotone",fal:"fa-light",far:"fa-regular",fas:"fa-solid",fat:"fa-thin"},duotone:{fadr:"fa-regular",fadl:"fa-light",fadt:"fa-thin"},sharp:{fass:"fa-solid",fasr:"fa-regular",fasl:"fa-light",fast:"fa-thin"},"sharp-duotone":{fasds:"fa-solid",fasdr:"fa-regular",fasdl:"fa-light",fasdt:"fa-thin"},slab:{faslr:"fa-regular"},"slab-press":{faslpr:"fa-regular"},whiteboard:{fawsb:"fa-semibold"},thumbprint:{fatl:"fa-light"},notdog:{fans:"fa-solid"},"notdog-duo":{fands:"fa-solid"},etch:{faes:"fa-solid"},jelly:{fajr:"fa-regular"},"jelly-fill":{fajfr:"fa-regular"},"jelly-duo":{fajdr:"fa-regular"},chisel:{facr:"fa-regular"}},T3A=["fa-solid","fa-regular","fa-light","fa-thin","fa-duotone","fa-brands","fa-semibold"],kEA=["fa","fas","far","fal","fat","fad","fadr","fadl","fadt","fab","fass","fasr","fasl","fast","fasds","fasdr","fasdl","fasdt","faslr","faslpr","fawsb","fatl","fans","fands","faes","fajr","fajfr","fajdr","facr"].concat(n3A,T3A),q3A=["solid","regular","light","thin","duotone","brands","semibold"],MEA=[1,2,3,4,5,6,7,8,9,10],Y3A=MEA.concat([11,12,13,14,15,16,17,18,19,20]),H3A=["aw","fw","pull-left","pull-right"],O3A=[].concat(Al(Object.keys(x3A)),q3A,H3A,["2xs","xs","sm","lg","xl","2xl","beat","border","fade","beat-fade","bounce","flip-both","flip-horizontal","flip-vertical","flip","inverse","layers","layers-bottom-left","layers-bottom-right","layers-counter","layers-text","layers-top-left","layers-top-right","li","pull-end","pull-start","pulse","rotate-180","rotate-270","rotate-90","rotate-by","shake","spin-pulse","spin-reverse","spin","stack-1x","stack-2x","stack","ul","width-auto","width-fixed",_b.GROUP,_b.SWAP_OPACITY,_b.PRIMARY,_b.SECONDARY]).concat(MEA.map(function(e){return"".concat(e,"x")})).concat(Y3A.map(function(e){return"w-".concat(e)})),P3A={"Font Awesome 5 Free":{900:"fas",400:"far"},"Font Awesome 5 Pro":{900:"fas",400:"far",normal:"far",300:"fal"},"Font Awesome 5 Brands":{400:"fab",normal:"fab"},"Font Awesome 5 Duotone":{900:"fad"}},$E="___FONT_AWESOME___",K1=16,NEA="fa",REA="svg-inline--fa",af="data-fa-i2svg",F1="data-fa-pseudo-element",j3A="data-fa-pseudo-element-pending",h5="data-prefix",p5="data-icon",d$="fontawesome-i2svg",z3A="async",Z3A=["HTML","HEAD","STYLE","SCRIPT"],GEA=["::before","::after",":before",":after"],bEA=function(){try{return!0}catch{return!1}}();function YR(e){return new Proxy(e,{get:function(t,i){return i in t?t[i]:t[gr]}})}var UEA=Rt({},IEA);UEA[gr]=Rt(Rt(Rt(Rt({},{"fa-duotone":"duotone"}),IEA[gr]),Q$.kit),Q$["kit-duotone"]);var W3A=YR(UEA),_1=Rt({},Z1A);_1[gr]=Rt(Rt(Rt(Rt({},{duotone:"fad"}),_1[gr]),u$.kit),u$["kit-duotone"]);var h$=YR(_1),J1=Rt({},v1);J1[gr]=Rt(Rt({},J1[gr]),i3A.kit);var vEA=YR(J1),L1=Rt({},L3A);L1[gr]=Rt(Rt({},L1[gr]),e3A.kit);YR(L1);var V3A=M1A,KEA="fa-layers-text",X3A=N1A,$3A=Rt({},P1A);YR($3A);var A4A=["class","data-prefix","data-icon","data-fa-transform","data-fa-mask"],K2=R1A,e4A=[].concat(Al(W1A),Al(O3A)),sM=ad.FontAwesomeConfig||{};function t4A(e){var A=go.querySelector("script["+e+"]");if(A)return A.getAttribute(e)}function i4A(e){return e===""?!0:e==="false"?!1:e==="true"?!0:e}if(go&&typeof go.querySelector=="function"){var n4A=[["data-family-prefix","familyPrefix"],["data-css-prefix","cssPrefix"],["data-family-default","familyDefault"],["data-style-default","styleDefault"],["data-replacement-class","replacementClass"],["data-auto-replace-svg","autoReplaceSvg"],["data-auto-add-css","autoAddCss"],["data-search-pseudo-elements","searchPseudoElements"],["data-search-pseudo-elements-warnings","searchPseudoElementsWarnings"],["data-search-pseudo-elements-full-scan","searchPseudoElementsFullScan"],["data-observe-mutations","observeMutations"],["data-mutate-approach","mutateApproach"],["data-keep-original-source","keepOriginalSource"],["data-measure-performance","measurePerformance"],["data-show-missing-icons","showMissingIcons"]];n4A.forEach(function(e){var A=HL(e,2),t=A[0],i=A[1],n=i4A(t4A(t));n!=null&&(sM[i]=n)})}var FEA={styleDefault:"solid",familyDefault:gr,cssPrefix:NEA,replacementClass:REA,autoReplaceSvg:!0,autoAddCss:!0,searchPseudoElements:!1,searchPseudoElementsWarnings:!0,searchPseudoElementsFullScan:!1,observeMutations:!0,mutateApproach:"async",keepOriginalSource:!0,measurePerformance:!1,showMissingIcons:!0};sM.familyPrefix&&(sM.cssPrefix=sM.familyPrefix);var NS=Rt(Rt({},FEA),sM);NS.autoReplaceSvg||(NS.observeMutations=!1);var di={};Object.keys(FEA).forEach(function(e){Object.defineProperty(di,e,{enumerable:!0,set:function(t){NS[e]=t,aM.forEach(function(i){return i(di)})},get:function(){return NS[e]}})});Object.defineProperty(di,"familyPrefix",{enumerable:!0,set:function(A){NS.cssPrefix=A,aM.forEach(function(t){return t(di)})},get:function(){return NS.cssPrefix}});ad.FontAwesomeConfig=di;var aM=[];function g4A(e){return aM.push(e),function(){aM.splice(aM.indexOf(e),1)}}var Hy=K1,nB={size:16,x:0,y:0,rotate:0,flipX:!1,flipY:!1};function o4A(e){if(!(!e||!BQ)){var A=go.createElement("style");A.setAttribute("type","text/css"),A.innerHTML=e;for(var t=go.head.childNodes,i=null,n=t.length-1;n>-1;n--){var g=t[n],o=(g.tagName||"").toUpperCase();["STYLE","LINK"].indexOf(o)>-1&&(i=g)}return go.head.insertBefore(A,i),e}}var s4A="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";function p$(){for(var e=12,A="";e-- >0;)A+=s4A[Math.random()*62|0];return A}function kw(e){for(var A=[],t=(e||[]).length>>>0;t--;)A[t]=e[t];return A}function f5(e){return e.classList?kw(e.classList):(e.getAttribute("class")||"").split(" ").filter(function(A){return A})}function _EA(e){return"".concat(e).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function a4A(e){return Object.keys(e||{}).reduce(function(A,t){return A+"".concat(t,'="').concat(_EA(e[t]),'" ')},"").trim()}function OL(e){return Object.keys(e||{}).reduce(function(A,t){return A+"".concat(t,": ").concat(e[t].trim(),";")},"")}function y5(e){return e.size!==nB.size||e.x!==nB.x||e.y!==nB.y||e.rotate!==nB.rotate||e.flipX||e.flipY}function r4A(e){var A=e.transform,t=e.containerWidth,i=e.iconWidth,n={transform:"translate(".concat(t/2," 256)")},g="translate(".concat(A.x*32,", ").concat(A.y*32,") "),o="scale(".concat(A.size/16*(A.flipX?-1:1),", ").concat(A.size/16*(A.flipY?-1:1),") "),s="rotate(".concat(A.rotate," 0 0)"),a={transform:"".concat(g," ").concat(o," ").concat(s)},r={transform:"translate(".concat(i/2*-1," -256)")};return{outer:n,inner:a,path:r}}function I4A(e){var A=e.transform,t=e.width,i=t===void 0?K1:t,n=e.height,g=n===void 0?K1:n,o="";return rEA?o+="translate(".concat(A.x/Hy-i/2,"em, ").concat(A.y/Hy-g/2,"em) "):o+="translate(calc(-50% + ".concat(A.x/Hy,"em), calc(-50% + ").concat(A.y/Hy,"em)) "),o+="scale(".concat(A.size/Hy*(A.flipX?-1:1),", ").concat(A.size/Hy*(A.flipY?-1:1),") "),o+="rotate(".concat(A.rotate,"deg) "),o}var C4A=`:root, :host {
  --fa-font-solid: normal 900 1em/1 "Font Awesome 7 Free";
  --fa-font-regular: normal 400 1em/1 "Font Awesome 7 Free";
  --fa-font-light: normal 300 1em/1 "Font Awesome 7 Pro";
  --fa-font-thin: normal 100 1em/1 "Font Awesome 7 Pro";
  --fa-font-duotone: normal 900 1em/1 "Font Awesome 7 Duotone";
  --fa-font-duotone-regular: normal 400 1em/1 "Font Awesome 7 Duotone";
  --fa-font-duotone-light: normal 300 1em/1 "Font Awesome 7 Duotone";
  --fa-font-duotone-thin: normal 100 1em/1 "Font Awesome 7 Duotone";
  --fa-font-brands: normal 400 1em/1 "Font Awesome 7 Brands";
  --fa-font-sharp-solid: normal 900 1em/1 "Font Awesome 7 Sharp";
  --fa-font-sharp-regular: normal 400 1em/1 "Font Awesome 7 Sharp";
  --fa-font-sharp-light: normal 300 1em/1 "Font Awesome 7 Sharp";
  --fa-font-sharp-thin: normal 100 1em/1 "Font Awesome 7 Sharp";
  --fa-font-sharp-duotone-solid: normal 900 1em/1 "Font Awesome 7 Sharp Duotone";
  --fa-font-sharp-duotone-regular: normal 400 1em/1 "Font Awesome 7 Sharp Duotone";
  --fa-font-sharp-duotone-light: normal 300 1em/1 "Font Awesome 7 Sharp Duotone";
  --fa-font-sharp-duotone-thin: normal 100 1em/1 "Font Awesome 7 Sharp Duotone";
  --fa-font-slab-regular: normal 400 1em/1 "Font Awesome 7 Slab";
  --fa-font-slab-press-regular: normal 400 1em/1 "Font Awesome 7 Slab Press";
  --fa-font-whiteboard-semibold: normal 600 1em/1 "Font Awesome 7 Whiteboard";
  --fa-font-thumbprint-light: normal 300 1em/1 "Font Awesome 7 Thumbprint";
  --fa-font-notdog-solid: normal 900 1em/1 "Font Awesome 7 Notdog";
  --fa-font-notdog-duo-solid: normal 900 1em/1 "Font Awesome 7 Notdog Duo";
  --fa-font-etch-solid: normal 900 1em/1 "Font Awesome 7 Etch";
  --fa-font-jelly-regular: normal 400 1em/1 "Font Awesome 7 Jelly";
  --fa-font-jelly-fill-regular: normal 400 1em/1 "Font Awesome 7 Jelly Fill";
  --fa-font-jelly-duo-regular: normal 400 1em/1 "Font Awesome 7 Jelly Duo";
  --fa-font-chisel-regular: normal 400 1em/1 "Font Awesome 7 Chisel";
}

.svg-inline--fa {
  box-sizing: content-box;
  display: var(--fa-display, inline-block);
  height: 1em;
  overflow: visible;
  vertical-align: -0.125em;
  width: var(--fa-width, 1.25em);
}
.svg-inline--fa.fa-2xs {
  vertical-align: 0.1em;
}
.svg-inline--fa.fa-xs {
  vertical-align: 0em;
}
.svg-inline--fa.fa-sm {
  vertical-align: -0.0714285714em;
}
.svg-inline--fa.fa-lg {
  vertical-align: -0.2em;
}
.svg-inline--fa.fa-xl {
  vertical-align: -0.25em;
}
.svg-inline--fa.fa-2xl {
  vertical-align: -0.3125em;
}
.svg-inline--fa.fa-pull-left,
.svg-inline--fa .fa-pull-start {
  float: inline-start;
  margin-inline-end: var(--fa-pull-margin, 0.3em);
}
.svg-inline--fa.fa-pull-right,
.svg-inline--fa .fa-pull-end {
  float: inline-end;
  margin-inline-start: var(--fa-pull-margin, 0.3em);
}
.svg-inline--fa.fa-li {
  width: var(--fa-li-width, 2em);
  inset-inline-start: calc(-1 * var(--fa-li-width, 2em));
  inset-block-start: 0.25em; /* syncing vertical alignment with Web Font rendering */
}

.fa-layers-counter, .fa-layers-text {
  display: inline-block;
  position: absolute;
  text-align: center;
}

.fa-layers {
  display: inline-block;
  height: 1em;
  position: relative;
  text-align: center;
  vertical-align: -0.125em;
  width: var(--fa-width, 1.25em);
}
.fa-layers .svg-inline--fa {
  inset: 0;
  margin: auto;
  position: absolute;
  transform-origin: center center;
}

.fa-layers-text {
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  transform-origin: center center;
}

.fa-layers-counter {
  background-color: var(--fa-counter-background-color, #ff253a);
  border-radius: var(--fa-counter-border-radius, 1em);
  box-sizing: border-box;
  color: var(--fa-inverse, #fff);
  line-height: var(--fa-counter-line-height, 1);
  max-width: var(--fa-counter-max-width, 5em);
  min-width: var(--fa-counter-min-width, 1.5em);
  overflow: hidden;
  padding: var(--fa-counter-padding, 0.25em 0.5em);
  right: var(--fa-right, 0);
  text-overflow: ellipsis;
  top: var(--fa-top, 0);
  transform: scale(var(--fa-counter-scale, 0.25));
  transform-origin: top right;
}

.fa-layers-bottom-right {
  bottom: var(--fa-bottom, 0);
  right: var(--fa-right, 0);
  top: auto;
  transform: scale(var(--fa-layers-scale, 0.25));
  transform-origin: bottom right;
}

.fa-layers-bottom-left {
  bottom: var(--fa-bottom, 0);
  left: var(--fa-left, 0);
  right: auto;
  top: auto;
  transform: scale(var(--fa-layers-scale, 0.25));
  transform-origin: bottom left;
}

.fa-layers-top-right {
  top: var(--fa-top, 0);
  right: var(--fa-right, 0);
  transform: scale(var(--fa-layers-scale, 0.25));
  transform-origin: top right;
}

.fa-layers-top-left {
  left: var(--fa-left, 0);
  right: auto;
  top: var(--fa-top, 0);
  transform: scale(var(--fa-layers-scale, 0.25));
  transform-origin: top left;
}

.fa-1x {
  font-size: 1em;
}

.fa-2x {
  font-size: 2em;
}

.fa-3x {
  font-size: 3em;
}

.fa-4x {
  font-size: 4em;
}

.fa-5x {
  font-size: 5em;
}

.fa-6x {
  font-size: 6em;
}

.fa-7x {
  font-size: 7em;
}

.fa-8x {
  font-size: 8em;
}

.fa-9x {
  font-size: 9em;
}

.fa-10x {
  font-size: 10em;
}

.fa-2xs {
  font-size: calc(10 / 16 * 1em); /* converts a 10px size into an em-based value that's relative to the scale's 16px base */
  line-height: calc(1 / 10 * 1em); /* sets the line-height of the icon back to that of it's parent */
  vertical-align: calc((6 / 10 - 0.375) * 1em); /* vertically centers the icon taking into account the surrounding text's descender */
}

.fa-xs {
  font-size: calc(12 / 16 * 1em); /* converts a 12px size into an em-based value that's relative to the scale's 16px base */
  line-height: calc(1 / 12 * 1em); /* sets the line-height of the icon back to that of it's parent */
  vertical-align: calc((6 / 12 - 0.375) * 1em); /* vertically centers the icon taking into account the surrounding text's descender */
}

.fa-sm {
  font-size: calc(14 / 16 * 1em); /* converts a 14px size into an em-based value that's relative to the scale's 16px base */
  line-height: calc(1 / 14 * 1em); /* sets the line-height of the icon back to that of it's parent */
  vertical-align: calc((6 / 14 - 0.375) * 1em); /* vertically centers the icon taking into account the surrounding text's descender */
}

.fa-lg {
  font-size: calc(20 / 16 * 1em); /* converts a 20px size into an em-based value that's relative to the scale's 16px base */
  line-height: calc(1 / 20 * 1em); /* sets the line-height of the icon back to that of it's parent */
  vertical-align: calc((6 / 20 - 0.375) * 1em); /* vertically centers the icon taking into account the surrounding text's descender */
}

.fa-xl {
  font-size: calc(24 / 16 * 1em); /* converts a 24px size into an em-based value that's relative to the scale's 16px base */
  line-height: calc(1 / 24 * 1em); /* sets the line-height of the icon back to that of it's parent */
  vertical-align: calc((6 / 24 - 0.375) * 1em); /* vertically centers the icon taking into account the surrounding text's descender */
}

.fa-2xl {
  font-size: calc(32 / 16 * 1em); /* converts a 32px size into an em-based value that's relative to the scale's 16px base */
  line-height: calc(1 / 32 * 1em); /* sets the line-height of the icon back to that of it's parent */
  vertical-align: calc((6 / 32 - 0.375) * 1em); /* vertically centers the icon taking into account the surrounding text's descender */
}

.fa-width-auto {
  --fa-width: auto;
}

.fa-fw,
.fa-width-fixed {
  --fa-width: 1.25em;
}

.fa-ul {
  list-style-type: none;
  margin-inline-start: var(--fa-li-margin, 2.5em);
  padding-inline-start: 0;
}
.fa-ul > li {
  position: relative;
}

.fa-li {
  inset-inline-start: calc(-1 * var(--fa-li-width, 2em));
  position: absolute;
  text-align: center;
  width: var(--fa-li-width, 2em);
  line-height: inherit;
}

/* Heads Up: Bordered Icons will not be supported in the future!
  - This feature will be deprecated in the next major release of Font Awesome (v8)!
  - You may continue to use it in this version *v7), but it will not be supported in Font Awesome v8.
*/
/* Notes:
* --@{v.$css-prefix}-border-width = 1/16 by default (to render as ~1px based on a 16px default font-size)
* --@{v.$css-prefix}-border-padding =
  ** 3/16 for vertical padding (to give ~2px of vertical whitespace around an icon considering it's vertical alignment)
  ** 4/16 for horizontal padding (to give ~4px of horizontal whitespace around an icon)
*/
.fa-border {
  border-color: var(--fa-border-color, #eee);
  border-radius: var(--fa-border-radius, 0.1em);
  border-style: var(--fa-border-style, solid);
  border-width: var(--fa-border-width, 0.0625em);
  box-sizing: var(--fa-border-box-sizing, content-box);
  padding: var(--fa-border-padding, 0.1875em 0.25em);
}

.fa-pull-left,
.fa-pull-start {
  float: inline-start;
  margin-inline-end: var(--fa-pull-margin, 0.3em);
}

.fa-pull-right,
.fa-pull-end {
  float: inline-end;
  margin-inline-start: var(--fa-pull-margin, 0.3em);
}

.fa-beat {
  animation-name: fa-beat;
  animation-delay: var(--fa-animation-delay, 0s);
  animation-direction: var(--fa-animation-direction, normal);
  animation-duration: var(--fa-animation-duration, 1s);
  animation-iteration-count: var(--fa-animation-iteration-count, infinite);
  animation-timing-function: var(--fa-animation-timing, ease-in-out);
}

.fa-bounce {
  animation-name: fa-bounce;
  animation-delay: var(--fa-animation-delay, 0s);
  animation-direction: var(--fa-animation-direction, normal);
  animation-duration: var(--fa-animation-duration, 1s);
  animation-iteration-count: var(--fa-animation-iteration-count, infinite);
  animation-timing-function: var(--fa-animation-timing, cubic-bezier(0.28, 0.84, 0.42, 1));
}

.fa-fade {
  animation-name: fa-fade;
  animation-delay: var(--fa-animation-delay, 0s);
  animation-direction: var(--fa-animation-direction, normal);
  animation-duration: var(--fa-animation-duration, 1s);
  animation-iteration-count: var(--fa-animation-iteration-count, infinite);
  animation-timing-function: var(--fa-animation-timing, cubic-bezier(0.4, 0, 0.6, 1));
}

.fa-beat-fade {
  animation-name: fa-beat-fade;
  animation-delay: var(--fa-animation-delay, 0s);
  animation-direction: var(--fa-animation-direction, normal);
  animation-duration: var(--fa-animation-duration, 1s);
  animation-iteration-count: var(--fa-animation-iteration-count, infinite);
  animation-timing-function: var(--fa-animation-timing, cubic-bezier(0.4, 0, 0.6, 1));
}

.fa-flip {
  animation-name: fa-flip;
  animation-delay: var(--fa-animation-delay, 0s);
  animation-direction: var(--fa-animation-direction, normal);
  animation-duration: var(--fa-animation-duration, 1s);
  animation-iteration-count: var(--fa-animation-iteration-count, infinite);
  animation-timing-function: var(--fa-animation-timing, ease-in-out);
}

.fa-shake {
  animation-name: fa-shake;
  animation-delay: var(--fa-animation-delay, 0s);
  animation-direction: var(--fa-animation-direction, normal);
  animation-duration: var(--fa-animation-duration, 1s);
  animation-iteration-count: var(--fa-animation-iteration-count, infinite);
  animation-timing-function: var(--fa-animation-timing, linear);
}

.fa-spin {
  animation-name: fa-spin;
  animation-delay: var(--fa-animation-delay, 0s);
  animation-direction: var(--fa-animation-direction, normal);
  animation-duration: var(--fa-animation-duration, 2s);
  animation-iteration-count: var(--fa-animation-iteration-count, infinite);
  animation-timing-function: var(--fa-animation-timing, linear);
}

.fa-spin-reverse {
  --fa-animation-direction: reverse;
}

.fa-pulse,
.fa-spin-pulse {
  animation-name: fa-spin;
  animation-direction: var(--fa-animation-direction, normal);
  animation-duration: var(--fa-animation-duration, 1s);
  animation-iteration-count: var(--fa-animation-iteration-count, infinite);
  animation-timing-function: var(--fa-animation-timing, steps(8));
}

@media (prefers-reduced-motion: reduce) {
  .fa-beat,
  .fa-bounce,
  .fa-fade,
  .fa-beat-fade,
  .fa-flip,
  .fa-pulse,
  .fa-shake,
  .fa-spin,
  .fa-spin-pulse {
    animation: none !important;
    transition: none !important;
  }
}
@keyframes fa-beat {
  0%, 90% {
    transform: scale(1);
  }
  45% {
    transform: scale(var(--fa-beat-scale, 1.25));
  }
}
@keyframes fa-bounce {
  0% {
    transform: scale(1, 1) translateY(0);
  }
  10% {
    transform: scale(var(--fa-bounce-start-scale-x, 1.1), var(--fa-bounce-start-scale-y, 0.9)) translateY(0);
  }
  30% {
    transform: scale(var(--fa-bounce-jump-scale-x, 0.9), var(--fa-bounce-jump-scale-y, 1.1)) translateY(var(--fa-bounce-height, -0.5em));
  }
  50% {
    transform: scale(var(--fa-bounce-land-scale-x, 1.05), var(--fa-bounce-land-scale-y, 0.95)) translateY(0);
  }
  57% {
    transform: scale(1, 1) translateY(var(--fa-bounce-rebound, -0.125em));
  }
  64% {
    transform: scale(1, 1) translateY(0);
  }
  100% {
    transform: scale(1, 1) translateY(0);
  }
}
@keyframes fa-fade {
  50% {
    opacity: var(--fa-fade-opacity, 0.4);
  }
}
@keyframes fa-beat-fade {
  0%, 100% {
    opacity: var(--fa-beat-fade-opacity, 0.4);
    transform: scale(1);
  }
  50% {
    opacity: 1;
    transform: scale(var(--fa-beat-fade-scale, 1.125));
  }
}
@keyframes fa-flip {
  50% {
    transform: rotate3d(var(--fa-flip-x, 0), var(--fa-flip-y, 1), var(--fa-flip-z, 0), var(--fa-flip-angle, -180deg));
  }
}
@keyframes fa-shake {
  0% {
    transform: rotate(-15deg);
  }
  4% {
    transform: rotate(15deg);
  }
  8%, 24% {
    transform: rotate(-18deg);
  }
  12%, 28% {
    transform: rotate(18deg);
  }
  16% {
    transform: rotate(-22deg);
  }
  20% {
    transform: rotate(22deg);
  }
  32% {
    transform: rotate(-12deg);
  }
  36% {
    transform: rotate(12deg);
  }
  40%, 100% {
    transform: rotate(0deg);
  }
}
@keyframes fa-spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.fa-rotate-90 {
  transform: rotate(90deg);
}

.fa-rotate-180 {
  transform: rotate(180deg);
}

.fa-rotate-270 {
  transform: rotate(270deg);
}

.fa-flip-horizontal {
  transform: scale(-1, 1);
}

.fa-flip-vertical {
  transform: scale(1, -1);
}

.fa-flip-both,
.fa-flip-horizontal.fa-flip-vertical {
  transform: scale(-1, -1);
}

.fa-rotate-by {
  transform: rotate(var(--fa-rotate-angle, 0));
}

.svg-inline--fa .fa-primary {
  fill: var(--fa-primary-color, currentColor);
  opacity: var(--fa-primary-opacity, 1);
}

.svg-inline--fa .fa-secondary {
  fill: var(--fa-secondary-color, currentColor);
  opacity: var(--fa-secondary-opacity, 0.4);
}

.svg-inline--fa.fa-swap-opacity .fa-primary {
  opacity: var(--fa-secondary-opacity, 0.4);
}

.svg-inline--fa.fa-swap-opacity .fa-secondary {
  opacity: var(--fa-primary-opacity, 1);
}

.svg-inline--fa mask .fa-primary,
.svg-inline--fa mask .fa-secondary {
  fill: black;
}

.svg-inline--fa.fa-inverse {
  fill: var(--fa-inverse, #fff);
}

.fa-stack {
  display: inline-block;
  height: 2em;
  line-height: 2em;
  position: relative;
  vertical-align: middle;
  width: 2.5em;
}

.fa-inverse {
  color: var(--fa-inverse, #fff);
}

.svg-inline--fa.fa-stack-1x {
  height: 1em;
  width: 1.25em;
}
.svg-inline--fa.fa-stack-2x {
  height: 2em;
  width: 2.5em;
}

.fa-stack-1x,
.fa-stack-2x {
  bottom: 0;
  left: 0;
  margin: auto;
  position: absolute;
  right: 0;
  top: 0;
  z-index: var(--fa-stack-z-index, auto);
}`;function JEA(){var e=NEA,A=REA,t=di.cssPrefix,i=di.replacementClass,n=C4A;if(t!==e||i!==A){var g=new RegExp("\\.".concat(e,"\\-"),"g"),o=new RegExp("\\--".concat(e,"\\-"),"g"),s=new RegExp("\\.".concat(A),"g");n=n.replace(g,".".concat(t,"-")).replace(o,"--".concat(t,"-")).replace(s,".".concat(i))}return n}var f$=!1;function F2(){di.autoAddCss&&!f$&&(o4A(JEA()),f$=!0)}var c4A={mixout:function(){return{dom:{css:JEA,insertCss:F2}}},hooks:function(){return{beforeDOMElementCreation:function(){F2()},beforeI2svg:function(){F2()}}}},AQ=ad||{};AQ[$E]||(AQ[$E]={});AQ[$E].styles||(AQ[$E].styles={});AQ[$E].hooks||(AQ[$E].hooks={});AQ[$E].shims||(AQ[$E].shims=[]);var Pc=AQ[$E],LEA=[],xEA=function(){go.removeEventListener("DOMContentLoaded",xEA),ZF=1,LEA.map(function(A){return A()})},ZF=!1;BQ&&(ZF=(go.documentElement.doScroll?/^loaded|^c/:/^loaded|^i|^c/).test(go.readyState),ZF||go.addEventListener("DOMContentLoaded",xEA));function l4A(e){BQ&&(ZF?setTimeout(e,0):LEA.push(e))}function HR(e){var A=e.tag,t=e.attributes,i=t===void 0?{}:t,n=e.children,g=n===void 0?[]:n;return typeof e=="string"?_EA(e):"<".concat(A," ").concat(a4A(i),">").concat(g.map(HR).join(""),"</").concat(A,">")}function y$(e,A,t){if(e&&e[A]&&e[A][t])return{prefix:A,iconName:t,icon:e[A][t]}}var _2=function(A,t,i,n){var g=Object.keys(A),o=g.length,s=t,a,r,I;for(i===void 0?(a=1,I=A[g[0]]):(a=0,I=i);a<o;a++)r=g[a],I=s(I,A[r],r,A);return I};function TEA(e){return Al(e).length!==1?null:e.codePointAt(0).toString(16)}function D$(e){return Object.keys(e).reduce(function(A,t){var i=e[t],n=!!i.icon;return n?A[i.iconName]=i.icon:A[t]=i,A},{})}function qEA(e,A){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=t.skipHooks,n=i===void 0?!1:i,g=D$(A);typeof Pc.hooks.addPack=="function"&&!n?Pc.hooks.addPack(e,D$(A)):Pc.styles[e]=Rt(Rt({},Pc.styles[e]||{}),g),e==="fas"&&qEA("fa",A)}var IN=Pc.styles,B4A=Pc.shims,YEA=Object.keys(vEA),E4A=YEA.reduce(function(e,A){return e[A]=Object.keys(vEA[A]),e},{}),D5=null,HEA={},OEA={},PEA={},jEA={},zEA={};function Q4A(e){return~e4A.indexOf(e)}function u4A(e,A){var t=A.split("-"),i=t[0],n=t.slice(1).join("-");return i===e&&n!==""&&!Q4A(n)?n:null}var ZEA=function(){var A=function(g){return _2(IN,function(o,s,a){return o[a]=_2(s,g,{}),o},{})};HEA=A(function(n,g,o){if(g[3]&&(n[g[3]]=o),g[2]){var s=g[2].filter(function(a){return typeof a=="number"});s.forEach(function(a){n[a.toString(16)]=o})}return n}),OEA=A(function(n,g,o){if(n[o]=o,g[2]){var s=g[2].filter(function(a){return typeof a=="string"});s.forEach(function(a){n[a]=o})}return n}),zEA=A(function(n,g,o){var s=g[2];return n[o]=o,s.forEach(function(a){n[a]=o}),n});var t="far"in IN||di.autoFetchSvg,i=_2(B4A,function(n,g){var o=g[0],s=g[1],a=g[2];return s==="far"&&!t&&(s="fas"),typeof o=="string"&&(n.names[o]={prefix:s,iconName:a}),typeof o=="number"&&(n.unicodes[o.toString(16)]={prefix:s,iconName:a}),n},{names:{},unicodes:{}});PEA=i.names,jEA=i.unicodes,D5=PL(di.styleDefault,{family:di.familyDefault})};g4A(function(e){D5=PL(e.styleDefault,{family:di.familyDefault})});ZEA();function m5(e,A){return(HEA[e]||{})[A]}function d4A(e,A){return(OEA[e]||{})[A]}function Ip(e,A){return(zEA[e]||{})[A]}function WEA(e){return PEA[e]||{prefix:null,iconName:null}}function h4A(e){var A=jEA[e],t=m5("fas",e);return A||(t?{prefix:"fas",iconName:t}:null)||{prefix:null,iconName:null}}function rd(){return D5}var VEA=function(){return{prefix:null,iconName:null,rest:[]}};function p4A(e){var A=gr,t=YEA.reduce(function(i,n){return i[n]="".concat(di.cssPrefix,"-").concat(n),i},{});return SEA.forEach(function(i){(e.includes(t[i])||e.some(function(n){return E4A[i].includes(n)}))&&(A=i)}),A}function PL(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t=A.family,i=t===void 0?gr:t,n=W3A[i][e];if(i===qR&&!e)return"fad";var g=h$[i][e]||h$[i][n],o=e in Pc.styles?e:null,s=g||o||null;return s}function f4A(e){var A=[],t=null;return e.forEach(function(i){var n=u4A(di.cssPrefix,i);n?t=n:i&&A.push(i)}),{iconName:t,rest:A}}function m$(e){return e.sort().filter(function(A,t,i){return i.indexOf(A)===t})}var S$=kEA.concat(wEA);function jL(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t=A.skipLookups,i=t===void 0?!1:t,n=null,g=m$(e.filter(function(B){return S$.includes(B)})),o=m$(e.filter(function(B){return!S$.includes(B)})),s=g.filter(function(B){return n=B,!CEA.includes(B)}),a=HL(s,1),r=a[0],I=r===void 0?null:r,c=p4A(g),l=Rt(Rt({},f4A(o)),{},{prefix:PL(I,{family:c})});return Rt(Rt(Rt({},l),S4A({values:e,family:c,styles:IN,config:di,canonical:l,givenPrefix:n})),y4A(i,n,l))}function y4A(e,A,t){var i=t.prefix,n=t.iconName;if(e||!i||!n)return{prefix:i,iconName:n};var g=A==="fa"?WEA(n):{},o=Ip(i,n);return n=g.iconName||o||n,i=g.prefix||i,i==="far"&&!IN.far&&IN.fas&&!di.autoFetchSvg&&(i="fas"),{prefix:i,iconName:n}}var D4A=SEA.filter(function(e){return e!==gr||e!==qR}),m4A=Object.keys(v1).filter(function(e){return e!==gr}).map(function(e){return Object.keys(v1[e])}).flat();function S4A(e){var A=e.values,t=e.family,i=e.canonical,n=e.givenPrefix,g=n===void 0?"":n,o=e.styles,s=o===void 0?{}:o,a=e.config,r=a===void 0?{}:a,I=t===qR,c=A.includes("fa-duotone")||A.includes("fad"),l=r.familyDefault==="duotone",B=i.prefix==="fad"||i.prefix==="fa-duotone";if(!I&&(c||l||B)&&(i.prefix="fad"),(A.includes("fa-brands")||A.includes("fab"))&&(i.prefix="fab"),!i.prefix&&D4A.includes(t)){var Q=Object.keys(s).find(function(d){return m4A.includes(d)});if(Q||r.autoFetchSvg){var h=z1A.get(t).defaultShortPrefixId;i.prefix=h,i.iconName=Ip(i.prefix,i.iconName)||i.iconName}}return(i.prefix==="fa"||g==="fa")&&(i.prefix=rd()||"fas"),i}var w4A=function(){function e(){h1A(this,e),this.definitions={}}return f1A(e,[{key:"add",value:function(){for(var t=this,i=arguments.length,n=new Array(i),g=0;g<i;g++)n[g]=arguments[g];var o=n.reduce(this._pullDefinitions,{});Object.keys(o).forEach(function(s){t.definitions[s]=Rt(Rt({},t.definitions[s]||{}),o[s]),qEA(s,o[s]),ZEA()})}},{key:"reset",value:function(){this.definitions={}}},{key:"_pullDefinitions",value:function(t,i){var n=i.prefix&&i.iconName&&i.icon?{0:i}:i;return Object.keys(n).map(function(g){var o=n[g],s=o.prefix,a=o.iconName,r=o.icon,I=r[2];t[s]||(t[s]={}),I.length>0&&I.forEach(function(c){typeof c=="string"&&(t[s][c]=r)}),t[s][a]=r}),t}}])}(),w$=[],VD={},km={},k4A=Object.keys(km);function M4A(e,A){var t=A.mixoutsTo;return w$=e,VD={},Object.keys(km).forEach(function(i){k4A.indexOf(i)===-1&&delete km[i]}),w$.forEach(function(i){var n=i.mixout?i.mixout():{};if(Object.keys(n).forEach(function(o){typeof n[o]=="function"&&(t[o]=n[o]),zF(n[o])==="object"&&Object.keys(n[o]).forEach(function(s){t[o]||(t[o]={}),t[o][s]=n[o][s]})}),i.hooks){var g=i.hooks();Object.keys(g).forEach(function(o){VD[o]||(VD[o]=[]),VD[o].push(g[o])})}i.provides&&i.provides(km)}),t}function x1(e,A){for(var t=arguments.length,i=new Array(t>2?t-2:0),n=2;n<t;n++)i[n-2]=arguments[n];var g=VD[e]||[];return g.forEach(function(o){A=o.apply(null,[A].concat(i))}),A}function rf(e){for(var A=arguments.length,t=new Array(A>1?A-1:0),i=1;i<A;i++)t[i-1]=arguments[i];var n=VD[e]||[];n.forEach(function(g){g.apply(null,t)})}function Id(){var e=arguments[0],A=Array.prototype.slice.call(arguments,1);return km[e]?km[e].apply(null,A):void 0}function T1(e){e.prefix==="fa"&&(e.prefix="fas");var A=e.iconName,t=e.prefix||rd();if(A)return A=Ip(t,A)||A,y$(XEA.definitions,t,A)||y$(Pc.styles,t,A)}var XEA=new w4A,N4A=function(){di.autoReplaceSvg=!1,di.observeMutations=!1,rf("noAuto")},R4A={i2svg:function(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return BQ?(rf("beforeI2svg",A),Id("pseudoElements2svg",A),Id("i2svg",A)):Promise.reject(new Error("Operation requires a DOM of some kind."))},watch:function(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=A.autoReplaceSvgRoot;di.autoReplaceSvg===!1&&(di.autoReplaceSvg=!0),di.observeMutations=!0,l4A(function(){b4A({autoReplaceSvgRoot:t}),rf("watch",A)})}},G4A={icon:function(A){if(A===null)return null;if(zF(A)==="object"&&A.prefix&&A.iconName)return{prefix:A.prefix,iconName:Ip(A.prefix,A.iconName)||A.iconName};if(Array.isArray(A)&&A.length===2){var t=A[1].indexOf("fa-")===0?A[1].slice(3):A[1],i=PL(A[0]);return{prefix:i,iconName:Ip(i,t)||t}}if(typeof A=="string"&&(A.indexOf("".concat(di.cssPrefix,"-"))>-1||A.match(V3A))){var n=jL(A.split(" "),{skipLookups:!0});return{prefix:n.prefix||rd(),iconName:Ip(n.prefix,n.iconName)||n.iconName}}if(typeof A=="string"){var g=rd();return{prefix:g,iconName:Ip(g,A)||A}}}},gC={noAuto:N4A,config:di,dom:R4A,parse:G4A,library:XEA,findIconDefinition:T1,toHtml:HR},b4A=function(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=A.autoReplaceSvgRoot,i=t===void 0?go:t;(Object.keys(Pc.styles).length>0||di.autoFetchSvg)&&BQ&&di.autoReplaceSvg&&gC.dom.i2svg({node:i})};function zL(e,A){return Object.defineProperty(e,"abstract",{get:A}),Object.defineProperty(e,"html",{get:function(){return e.abstract.map(function(i){return HR(i)})}}),Object.defineProperty(e,"node",{get:function(){if(BQ){var i=go.createElement("div");return i.innerHTML=e.html,i.children}}}),e}function U4A(e){var A=e.children,t=e.main,i=e.mask,n=e.attributes,g=e.styles,o=e.transform;if(y5(o)&&t.found&&!i.found){var s=t.width,a=t.height,r={x:s/a/2,y:.5};n.style=OL(Rt(Rt({},g),{},{"transform-origin":"".concat(r.x+o.x/16,"em ").concat(r.y+o.y/16,"em")}))}return[{tag:"svg",attributes:n,children:A}]}function v4A(e){var A=e.prefix,t=e.iconName,i=e.children,n=e.attributes,g=e.symbol,o=g===!0?"".concat(A,"-").concat(di.cssPrefix,"-").concat(t):g;return[{tag:"svg",attributes:{style:"display: none;"},children:[{tag:"symbol",attributes:Rt(Rt({},n),{},{id:o}),children:i}]}]}function K4A(e){var A=["aria-label","aria-labelledby","title","role"];return A.some(function(t){return t in e})}function S5(e){var A=e.icons,t=A.main,i=A.mask,n=e.prefix,g=e.iconName,o=e.transform,s=e.symbol,a=e.maskId,r=e.extra,I=e.watchable,c=I===void 0?!1:I,l=i.found?i:t,B=l.width,Q=l.height,h=[di.replacementClass,g?"".concat(di.cssPrefix,"-").concat(g):""].filter(function(S){return r.classes.indexOf(S)===-1}).filter(function(S){return S!==""||!!S}).concat(r.classes).join(" "),d={children:[],attributes:Rt(Rt({},r.attributes),{},{"data-prefix":n,"data-icon":g,class:h,role:r.attributes.role||"img",viewBox:"0 0 ".concat(B," ").concat(Q)})};!K4A(r.attributes)&&!r.attributes["aria-hidden"]&&(d.attributes["aria-hidden"]="true"),c&&(d.attributes[af]="");var p=Rt(Rt({},d),{},{prefix:n,iconName:g,main:t,mask:i,maskId:a,transform:o,symbol:s,styles:Rt({},r.styles)}),y=i.found&&t.found?Id("generateAbstractMask",p)||{children:[],attributes:{}}:Id("generateAbstractIcon",p)||{children:[],attributes:{}},m=y.children,D=y.attributes;return p.children=m,p.attributes=D,s?v4A(p):U4A(p)}function k$(e){var A=e.content,t=e.width,i=e.height,n=e.transform,g=e.extra,o=e.watchable,s=o===void 0?!1:o,a=Rt(Rt({},g.attributes),{},{class:g.classes.join(" ")});s&&(a[af]="");var r=Rt({},g.styles);y5(n)&&(r.transform=I4A({transform:n,width:t,height:i}),r["-webkit-transform"]=r.transform);var I=OL(r);I.length>0&&(a.style=I);var c=[];return c.push({tag:"span",attributes:a,children:[A]}),c}function F4A(e){var A=e.content,t=e.extra,i=Rt(Rt({},t.attributes),{},{class:t.classes.join(" ")}),n=OL(t.styles);n.length>0&&(i.style=n);var g=[];return g.push({tag:"span",attributes:i,children:[A]}),g}var J2=Pc.styles;function q1(e){var A=e[0],t=e[1],i=e.slice(4),n=HL(i,1),g=n[0],o=null;return Array.isArray(g)?o={tag:"g",attributes:{class:"".concat(di.cssPrefix,"-").concat(K2.GROUP)},children:[{tag:"path",attributes:{class:"".concat(di.cssPrefix,"-").concat(K2.SECONDARY),fill:"currentColor",d:g[0]}},{tag:"path",attributes:{class:"".concat(di.cssPrefix,"-").concat(K2.PRIMARY),fill:"currentColor",d:g[1]}}]}:o={tag:"path",attributes:{fill:"currentColor",d:g}},{found:!0,width:A,height:t,icon:o}}var _4A={found:!1,width:512,height:512};function J4A(e,A){!bEA&&!di.showMissingIcons&&e&&console.error('Icon with name "'.concat(e,'" and prefix "').concat(A,'" is missing.'))}function Y1(e,A){var t=A;return A==="fa"&&di.styleDefault!==null&&(A=rd()),new Promise(function(i,n){if(t==="fa"){var g=WEA(e)||{};e=g.iconName||e,A=g.prefix||A}if(e&&A&&J2[A]&&J2[A][e]){var o=J2[A][e];return i(q1(o))}J4A(e,A),i(Rt(Rt({},_4A),{},{icon:di.showMissingIcons&&e?Id("missingIconAbstract")||{}:{}}))})}var M$=function(){},H1=di.measurePerformance&&Fb&&Fb.mark&&Fb.measure?Fb:{mark:M$,measure:M$},uk='FA "7.0.0"',L4A=function(A){return H1.mark("".concat(uk," ").concat(A," begins")),function(){return $EA(A)}},$EA=function(A){H1.mark("".concat(uk," ").concat(A," ends")),H1.measure("".concat(uk," ").concat(A),"".concat(uk," ").concat(A," begins"),"".concat(uk," ").concat(A," ends"))},w5={begin:L4A,end:$EA},CK=function(){};function N$(e){var A=e.getAttribute?e.getAttribute(af):null;return typeof A=="string"}function x4A(e){var A=e.getAttribute?e.getAttribute(h5):null,t=e.getAttribute?e.getAttribute(p5):null;return A&&t}function T4A(e){return e&&e.classList&&e.classList.contains&&e.classList.contains(di.replacementClass)}function q4A(){if(di.autoReplaceSvg===!0)return cK.replace;var e=cK[di.autoReplaceSvg];return e||cK.replace}function Y4A(e){return go.createElementNS("http://www.w3.org/2000/svg",e)}function H4A(e){return go.createElement(e)}function AQA(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t=A.ceFn,i=t===void 0?e.tag==="svg"?Y4A:H4A:t;if(typeof e=="string")return go.createTextNode(e);var n=i(e.tag);Object.keys(e.attributes||[]).forEach(function(o){n.setAttribute(o,e.attributes[o])});var g=e.children||[];return g.forEach(function(o){n.appendChild(AQA(o,{ceFn:i}))}),n}function O4A(e){var A=" ".concat(e.outerHTML," ");return A="".concat(A,"Font Awesome fontawesome.com "),A}var cK={replace:function(A){var t=A[0];if(t.parentNode)if(A[1].forEach(function(n){t.parentNode.insertBefore(AQA(n),t)}),t.getAttribute(af)===null&&di.keepOriginalSource){var i=go.createComment(O4A(t));t.parentNode.replaceChild(i,t)}else t.remove()},nest:function(A){var t=A[0],i=A[1];if(~f5(t).indexOf(di.replacementClass))return cK.replace(A);var n=new RegExp("".concat(di.cssPrefix,"-.*"));if(delete i[0].attributes.id,i[0].attributes.class){var g=i[0].attributes.class.split(" ").reduce(function(s,a){return a===di.replacementClass||a.match(n)?s.toSvg.push(a):s.toNode.push(a),s},{toNode:[],toSvg:[]});i[0].attributes.class=g.toSvg.join(" "),g.toNode.length===0?t.removeAttribute("class"):t.setAttribute("class",g.toNode.join(" "))}var o=i.map(function(s){return HR(s)}).join(`
`);t.setAttribute(af,""),t.innerHTML=o}};function R$(e){e()}function eQA(e,A){var t=typeof A=="function"?A:CK;if(e.length===0)t();else{var i=R$;di.mutateApproach===z3A&&(i=ad.requestAnimationFrame||R$),i(function(){var n=q4A(),g=w5.begin("mutate");e.map(n),g(),t()})}}var k5=!1;function tQA(){k5=!0}function O1(){k5=!1}var WF=null;function G$(e){if(E$&&di.observeMutations){var A=e.treeCallback,t=A===void 0?CK:A,i=e.nodeCallback,n=i===void 0?CK:i,g=e.pseudoElementsCallback,o=g===void 0?CK:g,s=e.observeMutationsRoot,a=s===void 0?go:s;WF=new E$(function(r){if(!k5){var I=rd();kw(r).forEach(function(c){if(c.type==="childList"&&c.addedNodes.length>0&&!N$(c.addedNodes[0])&&(di.searchPseudoElements&&o(c.target),t(c.target)),c.type==="attributes"&&c.target.parentNode&&di.searchPseudoElements&&o([c.target],!0),c.type==="attributes"&&N$(c.target)&&~A4A.indexOf(c.attributeName))if(c.attributeName==="class"&&x4A(c.target)){var l=jL(f5(c.target)),B=l.prefix,Q=l.iconName;c.target.setAttribute(h5,B||I),Q&&c.target.setAttribute(p5,Q)}else T4A(c.target)&&n(c.target)})}}),BQ&&WF.observe(a,{childList:!0,attributes:!0,characterData:!0,subtree:!0})}}function P4A(){WF&&WF.disconnect()}function j4A(e){var A=e.getAttribute("style"),t=[];return A&&(t=A.split(";").reduce(function(i,n){var g=n.split(":"),o=g[0],s=g.slice(1);return o&&s.length>0&&(i[o]=s.join(":").trim()),i},{})),t}function z4A(e){var A=e.getAttribute("data-prefix"),t=e.getAttribute("data-icon"),i=e.innerText!==void 0?e.innerText.trim():"",n=jL(f5(e));return n.prefix||(n.prefix=rd()),A&&t&&(n.prefix=A,n.iconName=t),n.iconName&&n.prefix||(n.prefix&&i.length>0&&(n.iconName=d4A(n.prefix,e.innerText)||m5(n.prefix,TEA(e.innerText))),!n.iconName&&di.autoFetchSvg&&e.firstChild&&e.firstChild.nodeType===Node.TEXT_NODE&&(n.iconName=e.firstChild.data)),n}function Z4A(e){var A=kw(e.attributes).reduce(function(t,i){return t.name!=="class"&&t.name!=="style"&&(t[i.name]=i.value),t},{});return A}function W4A(){return{iconName:null,prefix:null,transform:nB,symbol:!1,mask:{iconName:null,prefix:null,rest:[]},maskId:null,extra:{classes:[],styles:{},attributes:{}}}}function b$(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{styleParser:!0},t=z4A(e),i=t.iconName,n=t.prefix,g=t.rest,o=Z4A(e),s=x1("parseNodeAttributes",{},e),a=A.styleParser?j4A(e):[];return Rt({iconName:i,prefix:n,transform:nB,mask:{iconName:null,prefix:null,rest:[]},maskId:null,symbol:!1,extra:{classes:g,styles:a,attributes:o}},s)}var V4A=Pc.styles;function iQA(e){var A=di.autoReplaceSvg==="nest"?b$(e,{styleParser:!1}):b$(e);return~A.extra.classes.indexOf(KEA)?Id("generateLayersText",e,A):Id("generateSvgReplacementMutation",e,A)}function X4A(){return[].concat(Al(wEA),Al(kEA))}function U$(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!BQ)return Promise.resolve();var t=go.documentElement.classList,i=function(c){return t.add("".concat(d$,"-").concat(c))},n=function(c){return t.remove("".concat(d$,"-").concat(c))},g=di.autoFetchSvg?X4A():CEA.concat(Object.keys(V4A));g.includes("fa")||g.push("fa");var o=[".".concat(KEA,":not([").concat(af,"])")].concat(g.map(function(I){return".".concat(I,":not([").concat(af,"])")})).join(", ");if(o.length===0)return Promise.resolve();var s=[];try{s=kw(e.querySelectorAll(o))}catch{}if(s.length>0)i("pending"),n("complete");else return Promise.resolve();var a=w5.begin("onTree"),r=s.reduce(function(I,c){try{var l=iQA(c);l&&I.push(l)}catch(B){bEA||B.name==="MissingIcon"&&console.error(B)}return I},[]);return new Promise(function(I,c){Promise.all(r).then(function(l){eQA(l,function(){i("active"),i("complete"),n("pending"),typeof A=="function"&&A(),a(),I()})}).catch(function(l){a(),c(l)})})}function $4A(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;iQA(e).then(function(t){t&&eQA([t],A)})}function AjA(e){return function(A){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=(A||{}).icon?A:T1(A||{}),n=t.mask;return n&&(n=(n||{}).icon?n:T1(n||{})),e(i,Rt(Rt({},t),{},{mask:n}))}}var ejA=function(A){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=t.transform,n=i===void 0?nB:i,g=t.symbol,o=g===void 0?!1:g,s=t.mask,a=s===void 0?null:s,r=t.maskId,I=r===void 0?null:r,c=t.classes,l=c===void 0?[]:c,B=t.attributes,Q=B===void 0?{}:B,h=t.styles,d=h===void 0?{}:h;if(A){var p=A.prefix,y=A.iconName,m=A.icon;return zL(Rt({type:"icon"},A),function(){return rf("beforeDOMElementCreation",{iconDefinition:A,params:t}),S5({icons:{main:q1(m),mask:a?q1(a.icon):{found:!1,width:null,height:null,icon:{}}},prefix:p,iconName:y,transform:Rt(Rt({},nB),n),symbol:o,maskId:I,extra:{attributes:Q,styles:d,classes:l}})})}},tjA={mixout:function(){return{icon:AjA(ejA)}},hooks:function(){return{mutationObserverCallbacks:function(t){return t.treeCallback=U$,t.nodeCallback=$4A,t}}},provides:function(A){A.i2svg=function(t){var i=t.node,n=i===void 0?go:i,g=t.callback,o=g===void 0?function(){}:g;return U$(n,o)},A.generateSvgReplacementMutation=function(t,i){var n=i.iconName,g=i.prefix,o=i.transform,s=i.symbol,a=i.mask,r=i.maskId,I=i.extra;return new Promise(function(c,l){Promise.all([Y1(n,g),a.iconName?Y1(a.iconName,a.prefix):Promise.resolve({found:!1,width:512,height:512,icon:{}})]).then(function(B){var Q=HL(B,2),h=Q[0],d=Q[1];c([t,S5({icons:{main:h,mask:d},prefix:g,iconName:n,transform:o,symbol:s,maskId:r,extra:I,watchable:!0})])}).catch(l)})},A.generateAbstractIcon=function(t){var i=t.children,n=t.attributes,g=t.main,o=t.transform,s=t.styles,a=OL(s);a.length>0&&(n.style=a);var r;return y5(o)&&(r=Id("generateAbstractTransformGrouping",{main:g,transform:o,containerWidth:g.width,iconWidth:g.width})),i.push(r||g.icon),{children:i,attributes:n}}}},ijA={mixout:function(){return{layer:function(t){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=i.classes,g=n===void 0?[]:n;return zL({type:"layer"},function(){rf("beforeDOMElementCreation",{assembler:t,params:i});var o=[];return t(function(s){Array.isArray(s)?s.map(function(a){o=o.concat(a.abstract)}):o=o.concat(s.abstract)}),[{tag:"span",attributes:{class:["".concat(di.cssPrefix,"-layers")].concat(Al(g)).join(" ")},children:o}]})}}}},njA={mixout:function(){return{counter:function(t){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};i.title;var n=i.classes,g=n===void 0?[]:n,o=i.attributes,s=o===void 0?{}:o,a=i.styles,r=a===void 0?{}:a;return zL({type:"counter",content:t},function(){return rf("beforeDOMElementCreation",{content:t,params:i}),F4A({content:t.toString(),extra:{attributes:s,styles:r,classes:["".concat(di.cssPrefix,"-layers-counter")].concat(Al(g))}})})}}}},gjA={mixout:function(){return{text:function(t){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=i.transform,g=n===void 0?nB:n,o=i.classes,s=o===void 0?[]:o,a=i.attributes,r=a===void 0?{}:a,I=i.styles,c=I===void 0?{}:I;return zL({type:"text",content:t},function(){return rf("beforeDOMElementCreation",{content:t,params:i}),k$({content:t,transform:Rt(Rt({},nB),g),extra:{attributes:r,styles:c,classes:["".concat(di.cssPrefix,"-layers-text")].concat(Al(s))}})})}}},provides:function(A){A.generateLayersText=function(t,i){var n=i.transform,g=i.extra,o=null,s=null;if(rEA){var a=parseInt(getComputedStyle(t).fontSize,10),r=t.getBoundingClientRect();o=r.width/a,s=r.height/a}return Promise.resolve([t,k$({content:t.innerHTML,width:o,height:s,transform:n,extra:g,watchable:!0})])}}},nQA=new RegExp('"',"ug"),v$=[1105920,1112319],K$=Rt(Rt(Rt(Rt({},{FontAwesome:{normal:"fas",400:"fas"}}),j1A),P3A),t3A),P1=Object.keys(K$).reduce(function(e,A){return e[A.toLowerCase()]=K$[A],e},{}),ojA=Object.keys(P1).reduce(function(e,A){var t=P1[A];return e[A]=t[900]||Al(Object.entries(t))[0][1],e},{});function sjA(e){var A=e.replace(nQA,"");return TEA(Al(A)[0]||"")}function ajA(e){var A=e.getPropertyValue("font-feature-settings").includes("ss01"),t=e.getPropertyValue("content"),i=t.replace(nQA,""),n=i.codePointAt(0),g=n>=v$[0]&&n<=v$[1],o=i.length===2?i[0]===i[1]:!1;return g||o||A}function rjA(e,A){var t=e.replace(/^['"]|['"]$/g,"").toLowerCase(),i=parseInt(A),n=isNaN(i)?"normal":i;return(P1[t]||{})[n]||ojA[t]}function F$(e,A){var t="".concat(j3A).concat(A.replace(":","-"));return new Promise(function(i,n){if(e.getAttribute(t)!==null)return i();var g=kw(e.children),o=g.filter(function(k){return k.getAttribute(F1)===A})[0],s=ad.getComputedStyle(e,A),a=s.getPropertyValue("font-family"),r=a.match(X3A),I=s.getPropertyValue("font-weight"),c=s.getPropertyValue("content");if(o&&!r)return e.removeChild(o),i();if(r&&c!=="none"&&c!==""){var l=s.getPropertyValue("content"),B=rjA(a,I),Q=sjA(l),h=r[0].startsWith("FontAwesome"),d=ajA(s),p=m5(B,Q),y=p;if(h){var m=h4A(Q);m.iconName&&m.prefix&&(p=m.iconName,B=m.prefix)}if(p&&!d&&(!o||o.getAttribute(h5)!==B||o.getAttribute(p5)!==y)){e.setAttribute(t,y),o&&e.removeChild(o);var D=W4A(),S=D.extra;S.attributes[F1]=A,Y1(p,B).then(function(k){var N=S5(Rt(Rt({},D),{},{icons:{main:k,mask:VEA()},prefix:B,iconName:y,extra:S,watchable:!0})),G=go.createElementNS("http://www.w3.org/2000/svg","svg");A==="::before"?e.insertBefore(G,e.firstChild):e.appendChild(G),G.outerHTML=N.map(function(M){return HR(M)}).join(`
`),e.removeAttribute(t),i()}).catch(n)}else i()}else i()})}function IjA(e){return Promise.all([F$(e,"::before"),F$(e,"::after")])}function CjA(e){return e.parentNode!==document.head&&!~Z3A.indexOf(e.tagName.toUpperCase())&&!e.getAttribute(F1)&&(!e.parentNode||e.parentNode.tagName!=="svg")}var cjA=function(A){return!!A&&GEA.some(function(t){return A.includes(t)})},ljA=function(A){if(!A)return[];for(var t=new Set,i=[A],n=[/(?=\s:)/,new RegExp("(?<=\\)\\)?[^,]*,)")],g=function(){var B=s[o];i=i.flatMap(function(Q){return Q.split(B).map(function(h){return h.replace(/,\s*$/,"").trim()})})},o=0,s=n;o<s.length;o++)g();i=i.flatMap(function(l){return l.includes("(")?l:l.split(",").map(function(B){return B.trim()})});var a=IK(i),r;try{for(a.s();!(r=a.n()).done;){var I=r.value;if(cjA(I)){var c=GEA.reduce(function(l,B){return l.replace(B,"")},I);c!==""&&c!=="*"&&t.add(c)}}}catch(l){a.e(l)}finally{a.f()}return t};function _$(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(BQ){var t;if(A)t=e;else if(di.searchPseudoElementsFullScan)t=e.querySelectorAll("*");else{var i=new Set,n=IK(document.styleSheets),g;try{for(n.s();!(g=n.n()).done;){var o=g.value;try{var s=IK(o.cssRules),a;try{for(s.s();!(a=s.n()).done;){var r=a.value,I=ljA(r.selectorText),c=IK(I),l;try{for(c.s();!(l=c.n()).done;){var B=l.value;i.add(B)}}catch(h){c.e(h)}finally{c.f()}}}catch(h){s.e(h)}finally{s.f()}}catch(h){di.searchPseudoElementsWarnings&&console.warn("Font Awesome: cannot parse stylesheet: ".concat(o.href," (").concat(h.message,`)
If it declares any Font Awesome CSS pseudo-elements, they will not be rendered as SVG icons. Add crossorigin="anonymous" to the <link>, enable searchPseudoElementsFullScan for slower but more thorough DOM parsing, or suppress this warning by setting searchPseudoElementsWarnings to false.`))}}}catch(h){n.e(h)}finally{n.f()}if(!i.size)return;var Q=Array.from(i).join(", ");try{t=e.querySelectorAll(Q)}catch{}}return new Promise(function(h,d){var p=kw(t).filter(CjA).map(IjA),y=w5.begin("searchPseudoElements");tQA(),Promise.all(p).then(function(){y(),O1(),h()}).catch(function(){y(),O1(),d()})})}}var BjA={hooks:function(){return{mutationObserverCallbacks:function(t){return t.pseudoElementsCallback=_$,t}}},provides:function(A){A.pseudoElements2svg=function(t){var i=t.node,n=i===void 0?go:i;di.searchPseudoElements&&_$(n)}}},J$=!1,EjA={mixout:function(){return{dom:{unwatch:function(){tQA(),J$=!0}}}},hooks:function(){return{bootstrap:function(){G$(x1("mutationObserverCallbacks",{}))},noAuto:function(){P4A()},watch:function(t){var i=t.observeMutationsRoot;J$?O1():G$(x1("mutationObserverCallbacks",{observeMutationsRoot:i}))}}}},L$=function(A){var t={size:16,x:0,y:0,flipX:!1,flipY:!1,rotate:0};return A.toLowerCase().split(" ").reduce(function(i,n){var g=n.toLowerCase().split("-"),o=g[0],s=g.slice(1).join("-");if(o&&s==="h")return i.flipX=!0,i;if(o&&s==="v")return i.flipY=!0,i;if(s=parseFloat(s),isNaN(s))return i;switch(o){case"grow":i.size=i.size+s;break;case"shrink":i.size=i.size-s;break;case"left":i.x=i.x-s;break;case"right":i.x=i.x+s;break;case"up":i.y=i.y-s;break;case"down":i.y=i.y+s;break;case"rotate":i.rotate=i.rotate+s;break}return i},t)},QjA={mixout:function(){return{parse:{transform:function(t){return L$(t)}}}},hooks:function(){return{parseNodeAttributes:function(t,i){var n=i.getAttribute("data-fa-transform");return n&&(t.transform=L$(n)),t}}},provides:function(A){A.generateAbstractTransformGrouping=function(t){var i=t.main,n=t.transform,g=t.containerWidth,o=t.iconWidth,s={transform:"translate(".concat(g/2," 256)")},a="translate(".concat(n.x*32,", ").concat(n.y*32,") "),r="scale(".concat(n.size/16*(n.flipX?-1:1),", ").concat(n.size/16*(n.flipY?-1:1),") "),I="rotate(".concat(n.rotate," 0 0)"),c={transform:"".concat(a," ").concat(r," ").concat(I)},l={transform:"translate(".concat(o/2*-1," -256)")},B={outer:s,inner:c,path:l};return{tag:"g",attributes:Rt({},B.outer),children:[{tag:"g",attributes:Rt({},B.inner),children:[{tag:i.icon.tag,children:i.icon.children,attributes:Rt(Rt({},i.icon.attributes),B.path)}]}]}}}},L2={x:0,y:0,width:"100%",height:"100%"};function x$(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return e.attributes&&(e.attributes.fill||A)&&(e.attributes.fill="black"),e}function ujA(e){return e.tag==="g"?e.children:[e]}var djA={hooks:function(){return{parseNodeAttributes:function(t,i){var n=i.getAttribute("data-fa-mask"),g=n?jL(n.split(" ").map(function(o){return o.trim()})):VEA();return g.prefix||(g.prefix=rd()),t.mask=g,t.maskId=i.getAttribute("data-fa-mask-id"),t}}},provides:function(A){A.generateAbstractMask=function(t){var i=t.children,n=t.attributes,g=t.main,o=t.mask,s=t.maskId,a=t.transform,r=g.width,I=g.icon,c=o.width,l=o.icon,B=r4A({transform:a,containerWidth:c,iconWidth:r}),Q={tag:"rect",attributes:Rt(Rt({},L2),{},{fill:"white"})},h=I.children?{children:I.children.map(x$)}:{},d={tag:"g",attributes:Rt({},B.inner),children:[x$(Rt({tag:I.tag,attributes:Rt(Rt({},I.attributes),B.path)},h))]},p={tag:"g",attributes:Rt({},B.outer),children:[d]},y="mask-".concat(s||p$()),m="clip-".concat(s||p$()),D={tag:"mask",attributes:Rt(Rt({},L2),{},{id:y,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse"}),children:[Q,p]},S={tag:"defs",children:[{tag:"clipPath",attributes:{id:m},children:ujA(l)},D]};return i.push(S,{tag:"rect",attributes:Rt({fill:"currentColor","clip-path":"url(#".concat(m,")"),mask:"url(#".concat(y,")")},L2)}),{children:i,attributes:n}}}},hjA={provides:function(A){var t=!1;ad.matchMedia&&(t=ad.matchMedia("(prefers-reduced-motion: reduce)").matches),A.missingIconAbstract=function(){var i=[],n={fill:"currentColor"},g={attributeType:"XML",repeatCount:"indefinite",dur:"2s"};i.push({tag:"path",attributes:Rt(Rt({},n),{},{d:"M156.5,447.7l-12.6,29.5c-18.7-9.5-35.9-21.2-51.5-34.9l22.7-22.7C127.6,430.5,141.5,440,156.5,447.7z M40.6,272H8.5 c1.4,21.2,5.4,41.7,11.7,61.1L50,321.2C45.1,305.5,41.8,289,40.6,272z M40.6,240c1.4-18.8,5.2-37,11.1-54.1l-29.5-12.6 C14.7,194.3,10,216.7,8.5,240H40.6z M64.3,156.5c7.8-14.9,17.2-28.8,28.1-41.5L69.7,92.3c-13.7,15.6-25.5,32.8-34.9,51.5 L64.3,156.5z M397,419.6c-13.9,12-29.4,22.3-46.1,30.4l11.9,29.8c20.7-9.9,39.8-22.6,56.9-37.6L397,419.6z M115,92.4 c13.9-12,29.4-22.3,46.1-30.4l-11.9-29.8c-20.7,9.9-39.8,22.6-56.8,37.6L115,92.4z M447.7,355.5c-7.8,14.9-17.2,28.8-28.1,41.5 l22.7,22.7c13.7-15.6,25.5-32.9,34.9-51.5L447.7,355.5z M471.4,272c-1.4,18.8-5.2,37-11.1,54.1l29.5,12.6 c7.5-21.1,12.2-43.5,13.6-66.8H471.4z M321.2,462c-15.7,5-32.2,8.2-49.2,9.4v32.1c21.2-1.4,41.7-5.4,61.1-11.7L321.2,462z M240,471.4c-18.8-1.4-37-5.2-54.1-11.1l-12.6,29.5c21.1,7.5,43.5,12.2,66.8,13.6V471.4z M462,190.8c5,15.7,8.2,32.2,9.4,49.2h32.1 c-1.4-21.2-5.4-41.7-11.7-61.1L462,190.8z M92.4,397c-12-13.9-22.3-29.4-30.4-46.1l-29.8,11.9c9.9,20.7,22.6,39.8,37.6,56.9 L92.4,397z M272,40.6c18.8,1.4,36.9,5.2,54.1,11.1l12.6-29.5C317.7,14.7,295.3,10,272,8.5V40.6z M190.8,50 c15.7-5,32.2-8.2,49.2-9.4V8.5c-21.2,1.4-41.7,5.4-61.1,11.7L190.8,50z M442.3,92.3L419.6,115c12,13.9,22.3,29.4,30.5,46.1 l29.8-11.9C470,128.5,457.3,109.4,442.3,92.3z M397,92.4l22.7-22.7c-15.6-13.7-32.8-25.5-51.5-34.9l-12.6,29.5 C370.4,72.1,384.4,81.5,397,92.4z"})});var o=Rt(Rt({},g),{},{attributeName:"opacity"}),s={tag:"circle",attributes:Rt(Rt({},n),{},{cx:"256",cy:"364",r:"28"}),children:[]};return t||s.children.push({tag:"animate",attributes:Rt(Rt({},g),{},{attributeName:"r",values:"28;14;28;28;14;28;"})},{tag:"animate",attributes:Rt(Rt({},o),{},{values:"1;0;1;1;0;1;"})}),i.push(s),i.push({tag:"path",attributes:Rt(Rt({},n),{},{opacity:"1",d:"M263.7,312h-16c-6.6,0-12-5.4-12-12c0-71,77.4-63.9,77.4-107.8c0-20-17.8-40.2-57.4-40.2c-29.1,0-44.3,9.6-59.2,28.7 c-3.9,5-11.1,6-16.2,2.4l-13.1-9.2c-5.6-3.9-6.9-11.8-2.6-17.2c21.2-27.2,46.4-44.7,91.2-44.7c52.3,0,97.4,29.8,97.4,80.2 c0,67.6-77.4,63.5-77.4,107.8C275.7,306.6,270.3,312,263.7,312z"}),children:t?[]:[{tag:"animate",attributes:Rt(Rt({},o),{},{values:"1;0;0;0;0;1;"})}]}),t||i.push({tag:"path",attributes:Rt(Rt({},n),{},{opacity:"0",d:"M232.5,134.5l7,168c0.3,6.4,5.6,11.5,12,11.5h9c6.4,0,11.7-5.1,12-11.5l7-168c0.3-6.8-5.2-12.5-12-12.5h-23 C237.7,122,232.2,127.7,232.5,134.5z"}),children:[{tag:"animate",attributes:Rt(Rt({},o),{},{values:"0;0;1;1;0;0;"})}]}),{tag:"g",attributes:{class:"missing"},children:i}}}},pjA={hooks:function(){return{parseNodeAttributes:function(t,i){var n=i.getAttribute("data-fa-symbol"),g=n===null?!1:n===""?!0:n;return t.symbol=g,t}}}},fjA=[c4A,tjA,ijA,njA,gjA,BjA,EjA,QjA,djA,hjA,pjA];M4A(fjA,{mixoutsTo:gC});gC.noAuto;gC.config;gC.library;gC.dom;var j1=gC.parse;gC.findIconDefinition;gC.toHtml;var yjA=gC.icon;gC.layer;gC.text;gC.counter;var gQA={exports:{}},DjA="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",mjA=DjA,SjA=mjA;function oQA(){}function sQA(){}sQA.resetWarningCache=oQA;var wjA=function(){function e(i,n,g,o,s,a){if(a!==SjA){var r=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw r.name="Invariant Violation",r}}e.isRequired=e;function A(){return e}var t={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:A,element:e,elementType:e,instanceOf:A,node:e,objectOf:A,oneOf:A,oneOfType:A,shape:A,exact:A,checkPropTypes:sQA,resetWarningCache:oQA};return t.PropTypes=t,t};gQA.exports=wjA();var kjA=gQA.exports;const mn=nw(kjA);var MjA={};function z1(e,A){(A==null||A>e.length)&&(A=e.length);for(var t=0,i=Array(A);t<A;t++)i[t]=e[t];return i}function NjA(e){if(Array.isArray(e))return e}function RjA(e){if(Array.isArray(e))return z1(e)}function Au(e,A,t){return(A=JjA(A))in e?Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[A]=t,e}function GjA(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function bjA(e,A){var t=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(t!=null){var i,n,g,o,s=[],a=!0,r=!1;try{if(g=(t=t.call(e)).next,A!==0)for(;!(a=(i=g.call(t)).done)&&(s.push(i.value),s.length!==A);a=!0);}catch(I){r=!0,n=I}finally{try{if(!a&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(r)throw n}}return s}}function UjA(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function vjA(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function T$(e,A){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);A&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),t.push.apply(t,i)}return t}function Zl(e){for(var A=1;A<arguments.length;A++){var t=arguments[A]!=null?arguments[A]:{};A%2?T$(Object(t),!0).forEach(function(i){Au(e,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):T$(Object(t)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(t,i))})}return e}function KjA(e,A){if(e==null)return{};var t,i,n=FjA(e,A);if(Object.getOwnPropertySymbols){var g=Object.getOwnPropertySymbols(e);for(i=0;i<g.length;i++)t=g[i],A.indexOf(t)===-1&&{}.propertyIsEnumerable.call(e,t)&&(n[t]=e[t])}return n}function FjA(e,A){if(e==null)return{};var t={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(A.indexOf(i)!==-1)continue;t[i]=e[i]}return t}function q$(e,A){return NjA(e)||bjA(e,A)||aQA(e,A)||UjA()}function Z1(e){return RjA(e)||GjA(e)||aQA(e)||vjA()}function _jA(e,A){if(typeof e!="object"||!e)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var i=t.call(e,A);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(A==="string"?String:Number)(e)}function JjA(e){var A=_jA(e,"string");return typeof A=="symbol"?A:A+""}function VF(e){"@babel/helpers - typeof";return VF=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(A){return typeof A}:function(A){return A&&typeof Symbol=="function"&&A.constructor===Symbol&&A!==Symbol.prototype?"symbol":typeof A},VF(e)}function aQA(e,A){if(e){if(typeof e=="string")return z1(e,A);var t={}.toString.call(e).slice(8,-1);return t==="Object"&&e.constructor&&(t=e.constructor.name),t==="Map"||t==="Set"?Array.from(e):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?z1(e,A):void 0}}var LjA="7.0.0-alpha1",W1;try{var xjA=require("@fortawesome/fontawesome-svg-core/package.json");W1=xjA.version}catch{W1=MjA.FA_VERSION||"7.0.0-alpha8"}function TjA(e){var A=e.beat,t=e.fade,i=e.beatFade,n=e.bounce,g=e.shake,o=e.flash,s=e.spin,a=e.spinPulse,r=e.spinReverse,I=e.pulse,c=e.fixedWidth,l=e.inverse,B=e.border,Q=e.listItem,h=e.flip,d=e.size,p=e.rotation,y=e.pull,m=e.swapOpacity,D=e.rotateBy,S=e.widthAuto,k=qjA(W1,LjA),N=Au(Au(Au(Au(Au(Au({"fa-beat":A,"fa-fade":t,"fa-beat-fade":i,"fa-bounce":n,"fa-shake":g,"fa-flash":o,"fa-spin":s,"fa-spin-reverse":r,"fa-spin-pulse":a,"fa-pulse":I,"fa-fw":c,"fa-inverse":l,"fa-border":B,"fa-li":Q,"fa-flip":h===!0,"fa-flip-horizontal":h==="horizontal"||h==="both","fa-flip-vertical":h==="vertical"||h==="both"},"fa-".concat(d),typeof d<"u"&&d!==null),"fa-rotate-".concat(p),typeof p<"u"&&p!==null&&p!==0),"fa-pull-".concat(y),typeof y<"u"&&y!==null),"fa-swap-opacity",m),"fa-rotate-by",k&&D),"fa-width-auto",k&&S);return Object.keys(N).map(function(G){return N[G]?G:null}).filter(function(G){return G})}function qjA(e,A){for(var t=e.split("-"),i=q$(t,2),n=i[0],g=i[1],o=A.split("-"),s=q$(o,2),a=s[0],r=s[1],I=n.split("."),c=a.split("."),l=0;l<Math.max(I.length,c.length);l++){var B=I[l]||"0",Q=c[l]||"0",h=parseInt(B,10),d=parseInt(Q,10);if(h!==d)return h>d}for(var p=0;p<Math.max(I.length,c.length);p++){var y=I[p]||"0",m=c[p]||"0";if(y!==m&&y.length!==m.length)return y.length<m.length}return!(g&&!r)}function YjA(e){return e=e-0,e===e}function rQA(e){return YjA(e)?e:(e=e.replace(/[\-_\s]+(.)?/g,function(A,t){return t?t.toUpperCase():""}),e.substr(0,1).toLowerCase()+e.substr(1))}var HjA=["style"];function OjA(e){return e.charAt(0).toUpperCase()+e.slice(1)}function PjA(e){return e.split(";").map(function(A){return A.trim()}).filter(function(A){return A}).reduce(function(A,t){var i=t.indexOf(":"),n=rQA(t.slice(0,i)),g=t.slice(i+1).trim();return n.startsWith("webkit")?A[OjA(n)]=g:A[n]=g,A},{})}function IQA(e,A){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(typeof A=="string")return A;var i=(A.children||[]).map(function(a){return IQA(e,a)}),n=Object.keys(A.attributes||{}).reduce(function(a,r){var I=A.attributes[r];switch(r){case"class":a.attrs.className=I,delete A.attributes.class;break;case"style":a.attrs.style=PjA(I);break;default:r.indexOf("aria-")===0||r.indexOf("data-")===0?a.attrs[r.toLowerCase()]=I:a.attrs[rQA(r)]=I}return a},{attrs:{}}),g=t.style,o=g===void 0?{}:g,s=KjA(t,HjA);return n.attrs.style=Zl(Zl({},n.attrs.style),o),e.apply(void 0,[A.tag,Zl(Zl({},n.attrs),s)].concat(Z1(i)))}var CQA=!1;try{CQA=!0}catch{}function jjA(){if(!CQA&&console&&typeof console.error=="function"){var e;(e=console).error.apply(e,arguments)}}function Y$(e){if(e&&VF(e)==="object"&&e.prefix&&e.iconName&&e.icon)return e;if(j1.icon)return j1.icon(e);if(e===null)return null;if(e&&VF(e)==="object"&&e.prefix&&e.iconName)return e;if(Array.isArray(e)&&e.length===2)return{prefix:e[0],iconName:e[1]};if(typeof e=="string")return{prefix:"fas",iconName:e}}function x2(e,A){return Array.isArray(A)&&A.length>0||!Array.isArray(A)&&A?Au({},e,A):{}}var H$={border:!1,className:"",mask:null,maskId:null,fixedWidth:!1,inverse:!1,flip:!1,icon:null,listItem:!1,pull:null,pulse:!1,rotation:null,rotateBy:!1,size:null,spin:!1,spinPulse:!1,spinReverse:!1,beat:!1,fade:!1,beatFade:!1,bounce:!1,shake:!1,symbol:!1,title:"",titleId:null,transform:null,swapOpacity:!1,widthAuto:!1},Cd=ue.forwardRef(function(e,A){var t=Zl(Zl({},H$),e),i=t.icon,n=t.mask,g=t.symbol,o=t.className,s=t.title,a=t.titleId,r=t.maskId,I=Y$(i),c=x2("classes",[].concat(Z1(TjA(t)),Z1((o||"").split(" ")))),l=x2("transform",typeof t.transform=="string"?j1.transform(t.transform):t.transform),B=x2("mask",Y$(n)),Q=yjA(I,Zl(Zl(Zl(Zl({},c),l),B),{},{symbol:g,title:s,titleId:a,maskId:r}));if(!Q)return jjA("Could not find icon",I),null;var h=Q.abstract,d={ref:A};return Object.keys(t).forEach(function(p){H$.hasOwnProperty(p)||(d[p]=t[p])}),zjA(h[0],d)});Cd.displayName="FontAwesomeIcon";Cd.propTypes={beat:mn.bool,border:mn.bool,beatFade:mn.bool,bounce:mn.bool,className:mn.string,fade:mn.bool,flash:mn.bool,mask:mn.oneOfType([mn.object,mn.array,mn.string]),maskId:mn.string,fixedWidth:mn.bool,inverse:mn.bool,flip:mn.oneOf([!0,!1,"horizontal","vertical","both"]),icon:mn.oneOfType([mn.object,mn.array,mn.string]),listItem:mn.bool,pull:mn.oneOf(["right","left"]),pulse:mn.bool,rotation:mn.oneOf([0,90,180,270]),rotateBy:mn.bool,shake:mn.bool,size:mn.oneOf(["2xs","xs","sm","lg","xl","2xl","1x","2x","3x","4x","5x","6x","7x","8x","9x","10x"]),spin:mn.bool,spinPulse:mn.bool,spinReverse:mn.bool,symbol:mn.oneOfType([mn.bool,mn.string]),title:mn.string,titleId:mn.string,transform:mn.oneOfType([mn.string,mn.object]),swapOpacity:mn.bool,widthAuto:mn.bool};var zjA=IQA.bind(null,ue.createElement);/*!
 * Font Awesome Free 7.0.0 by @fontawesome - https://fontawesome.com
 * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
 * Copyright 2025 Fonticons, Inc.
 */var ZjA={prefix:"fas",iconName:"dice-six",icon:[448,512,[9861],"f526","M0 96C0 60.7 28.7 32 64 32l320 0c35.3 0 64 28.7 64 64l0 320c0 35.3-28.7 64-64 64L64 480c-35.3 0-64-28.7-64-64L0 96zm160 64a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zM128 288a32 32 0 1 0 0-64 32 32 0 1 0 0 64zm32 64a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zM320 192a32 32 0 1 0 0-64 32 32 0 1 0 0 64zm32 64a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zM320 384a32 32 0 1 0 0-64 32 32 0 1 0 0 64z"]},WjA={prefix:"fas",iconName:"circle-chevron-left",icon:[512,512,["chevron-circle-left"],"f137","M512 256a256 256 0 1 0 -512 0 256 256 0 1 0 512 0zM271 135c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-87 87 87 87c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0L167 273c-9.4-9.4-9.4-24.6 0-33.9L271 135z"]},VjA=WjA,XjA={prefix:"fas",iconName:"circle-question",icon:[512,512,[62108,"question-circle"],"f059","M256 512a256 256 0 1 0 0-512 256 256 0 1 0 0 512zm0-336c-17.7 0-32 14.3-32 32 0 13.3-10.7 24-24 24s-24-10.7-24-24c0-44.2 35.8-80 80-80s80 35.8 80 80c0 47.2-36 67.2-56 74.5l0 3.8c0 13.3-10.7 24-24 24s-24-10.7-24-24l0-8.1c0-20.5 14.8-35.2 30.1-40.2 6.4-2.1 13.2-5.5 18.2-10.3 4.3-4.2 7.7-10 7.7-19.6 0-17.7-14.3-32-32-32zM224 368a32 32 0 1 1 64 0 32 32 0 1 1 -64 0z"]},$jA={prefix:"fas",iconName:"circle-chevron-right",icon:[512,512,["chevron-circle-right"],"f138","M0 256a256 256 0 1 0 512 0 256 256 0 1 0 -512 0zM241 377c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l87-87-87-87c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0L345 239c9.4 9.4 9.4 24.6 0 33.9L241 377z"]},A8A=$jA;const e8A=[{key:"cee-lo",title:"CEE-LO",tagline:"Fast • Social • Casual",icon:c1A},{key:"craps",title:"CRAPS",tagline:"High Energy • Strategy",icon:l1A},{key:"poker",title:"POKER",tagline:"Skill-Based • Competitive",icon:B1A},{key:"skills",title:"SKILLS",tagline:"Challenge • Mastery",icon:E1A},{key:"zentara",title:"ZENTARA",tagline:"Conquer • Build • Dominate",icon:Q1A}];function t8A({selectedMode:e,onSelectMode:A,slides:t=e8A,interval:i=4e3,width:n=140,height:g=140,className:o=""}){const[s,a]=E.useState(0),[r,I]=E.useState(!1);E.useEffect(()=>{if(e){const D=t.findIndex(S=>S.key===e);D>=0&&D!==s&&a(D)}},[e,t,s]),E.useEffect(()=>{if(r||e||i<=0)return;const D=setInterval(()=>{a(S=>(S+1)%t.length)},i);return()=>clearInterval(D)},[r,e,i,t.length]);const c=E.useCallback(D=>{a(D),I(!0),A==null||A(t[D].key)},[A,t]),[l,B]=E.useState(null),Q=E.useCallback(D=>{B(D.touches[0].clientX)},[]),h=E.useCallback(D=>{if(l===null)return;const S=D.changedTouches[0].clientX-l;if(Math.abs(S)>50){const N=S>0?-1:1,G=(s+N+t.length)%t.length;c(G)}B(null)},[l,s,t.length,c]),d=t[s],p=E.useCallback(D=>{D.currentTarget.src=b1},[]),y=E.useCallback(D=>{D.stopPropagation();const S=(s-1+t.length)%t.length;c(S)},[s,t.length,c]),m=E.useCallback(D=>{D.stopPropagation();const S=(s+1)%t.length;c(S)},[s,t.length,c]);return C.jsxs("div",{className:`logo-slideshow ${o}`,onTouchStart:Q,onTouchEnd:h,onClick:()=>c(s),role:"button",tabIndex:0,"aria-label":`Select ${d.title}`,children:[C.jsx("button",{className:"logo-slideshow__chevron logo-slideshow__chevron--left",onClick:y,"aria-label":"Previous game",type:"button",children:C.jsx(Cd,{icon:VjA})}),C.jsx("div",{className:"logo-slideshow__track",children:t.map((D,S)=>C.jsxs("div",{className:`logo-slideshow__slide ${S===s?"logo-slideshow__slide--active":""}`,"aria-hidden":S!==s,children:[C.jsx("img",{src:D.icon,alt:D.title,width:n,height:g,className:"logo-slideshow__icon",onError:p,loading:S===0?"eager":"lazy"}),C.jsx("div",{className:"logo-slideshow__tagline",children:D.tagline})]},D.key))}),C.jsx("button",{className:"logo-slideshow__chevron logo-slideshow__chevron--right",onClick:m,"aria-label":"Next game",type:"button",children:C.jsx(Cd,{icon:A8A})})]})}const i8A="/assets/logo-256-CalulGNO.webp",n8A="/assets/logo-420-D7JbtaQr.webp",g8A="/assets/logo-256-BQd-RHpb.avif",o8A="/assets/logo-420-CxzlrsyU.avif",s8A="/assets/zentara-icon-transparent-HQ2ticUo.webp";function cQA({width:e=180,height:A=180,tagline:t,className:i=""}){var h,d;const n=((d=(h=import.meta)==null?void 0:h.env)==null?void 0:d.VITE_APP_TARGET)??"";let g="";try{g=(window==null?void 0:window.APP_TARGET)??""}catch{}const o=String(n||g).toLowerCase(),s=o==="cee-lo"?"ceelo":o,a=s==="craps"||s==="poker"||s==="ceelo"||s==="skills"||s==="zentara",r=o==="zentara"?"Zentara Lounge":o==="poker"?"Zentara One Poker Lounge":o==="craps"?"Zentara One Craps Lounge":o==="skills"?"Zentara One Skills Lounge":"Zentara One Dice Lounge",c=t??(s==="skills"?"Think Fast. Play Smart. Win Big.":s==="craps"?"Roll the Dice. Beat the House.":s==="poker"?"Ante Up. Bluff. Win Big.":s==="ceelo"?"Street Rules. Real Stakes.":s==="zentara"?"Conquer the Galaxy.":"Play. Roll. Win. Together!"),l=typeof window<"u"?window:{};let B=l.APP_ICON_PNG||"./icon.png",Q=l.APP_ICON_512||"./icon-512.webp";return s==="zentara"&&(Q=s8A),C.jsxs("div",{className:`logo-hero ${i}`,"data-testid":"logo-hero",children:[a?C.jsxs("picture",{children:[C.jsx("source",{type:"image/webp",srcSet:Q,sizes:"(max-width: 600px) 60vw, 420px"}),C.jsx("img",{width:e,height:A,src:Q||B,alt:r,decoding:"async",loading:"eager",fetchPriority:"high",style:{maxWidth:"100%",height:"auto"},onError:p=>{try{p.currentTarget.src=b1}catch{}}})]}):C.jsxs("picture",{children:[C.jsx("source",{type:"image/avif",srcSet:`${g8A} 256w, ${o8A} 420w`,sizes:"(max-width: 600px) 60vw, 420px"}),C.jsx("source",{type:"image/webp",srcSet:`${i8A} 256w, ${n8A} 420w`,sizes:"(max-width: 600px) 60vw, 420px"}),C.jsx("img",{width:e,height:A,src:b1,alt:r,decoding:"async",loading:"eager",fetchPriority:"high",sizes:"(max-width:600px) 60vw, 420px",style:{maxWidth:"100%",height:"auto"}})]}),c&&C.jsx("span",{className:"gold-link",children:c})]})}const lQA=E.createContext(void 0),a8A=({children:e})=>{const{user:A}=tn(),[t,i]=E.useState([]),[n,g]=E.useState([]),[o,s]=E.useState([]),{blockUser:a,unblockUser:r,getFriendsList:I,sendFriendRequest:c,unfriend:l,respondFriendRequest:B}=Mo(),Q=E.useCallback(async()=>{try{const G=await I();G!=null&&G.ok&&(Array.isArray(G.friendsProfiles)&&i(G.friendsProfiles),Array.isArray(G.friendRequests)&&g(G.friendRequests),Array.isArray(G.blockedProfiles)&&s(G.blockedProfiles))}catch{}},[I]);Os({onFriendRequestReceived:G=>{G!=null&&G.request&&g(M=>[...M.filter(w=>w.id!==G.request.id),G.request])},onFriendRequestCancelled:G=>{G!=null&&G.requestId&&g(M=>M.filter(w=>w.id!==G.requestId))},onFriendRequestResponded:G=>{G!=null&&G.requestId&&(G!=null&&G.action)&&(g(M=>M.map(w=>w.id===G.requestId?{...w,status:G.action==="ACCEPT"?"ACCEPTED":"DECLINED"}:w)),G.action==="ACCEPT"&&Q())},onUnfriended:G=>{G!=null&&G.byUserId&&i(M=>M.filter(w=>w.id!==G.byUserId))},onUserBlocked:G=>{G!=null&&G.byUserId&&s(M=>M.find(w=>w.id===G.byUserId)?M:[...M,{id:G.byUserId}])},onUserUnblocked:G=>{G!=null&&G.byUserId&&s(M=>M.filter(w=>w.id!==G.byUserId))}}),E.useEffect(()=>{Q()},[]);const h=E.useCallback(G=>{if(!(A!=null&&A.id)||n.some(_=>_.status==="PENDING"&&_.fromUserId===A.id&&_.toUserId===G))return;const w=`temp:${Date.now()}:${G}`,b={id:w,fromUserId:A.id,toUserId:G,message:void 0,status:"PENDING",createdAt:new Date().toISOString(),respondedAt:void 0,fromUser:{id:A.id,name:A.name??null,avatarUrl:A.avatarUrl??null},toUser:o.find(_=>_.id===G)??t.find(_=>_.id===G)??{id:G,name:null,avatarUrl:null}};g(_=>[..._,b]),c(G).then(_=>{_!=null&&_.ok?_.request?g(K=>[...K.filter(J=>!(J.id===w||J.fromUserId===A.id&&J.toUserId===G&&J.id.startsWith("temp:"))),_.request]):Q():g(K=>K.filter(J=>J.id!==w))}).catch(()=>{g(_=>_.filter(K=>K.id!==w))})},[c,Q,A==null?void 0:A.id,A==null?void 0:A.name,o,t,n]),d=E.useCallback(G=>{l(G).then(M=>{M!=null&&M.ok&&i(w=>w.filter(b=>b.id!==G))}).catch(()=>{})},[l]),p=E.useCallback(G=>{g(M=>[...M.filter(w=>w.id!==G.id),G])},[]),y=E.useCallback(G=>{g(M=>M.map(w=>w.id===G.id?G:w))},[]),m=E.useCallback(G=>{g(M=>M.filter(w=>w.id!==G))},[]),D=E.useCallback(async(G,M)=>{try{const w=await B(G,M);w!=null&&w.ok&&await Q()}catch{}},[B,Q]),S=E.useCallback(async G=>{(await a(G)).ok&&s(w=>w.find(b=>b.id===G)?w:[...w,{id:G}])},[a]),k=E.useCallback(async G=>{(await r(G)).ok&&s(w=>w.filter(b=>b.id!==G))},[r]),N=E.useCallback(G=>!!o.find(M=>M.id===G),[o]);return C.jsx(lQA.Provider,{value:{friends:t,friendRequests:n,blockedUsers:o,addFriend:h,removeFriend:d,addFriendRequest:p,updateFriendRequest:y,removeFriendRequest:m,respondToFriendRequest:D,blockUser:S,unblockUser:k,isBlocked:N,refreshSocial:Q},children:e})};function Kd(){const e=E.useContext(lQA);if(!e)throw new Error("useSocial must be used within a SocialProvider");return e}const BQA=E.createContext(null),OR=()=>E.useContext(BQA),lh=e=>`room:${e}`,wC=(e,A)=>`dm:${[e,A].sort().join("|")}`,O$=e=>{if(!e.startsWith("dm:"))return null;const t=e.slice(3).split("|");return t.length===2?t:null},T2=(e,A)=>e.ts===A.ts?e.id<A.id?-1:e.id>A.id?1:0:e.ts-A.ts,P$=()=>"tmp:"+Math.random().toString(36).slice(2)+Date.now().toString(36),q2=e=>({id:e.id,ts:e.ts,senderId:e.fromUserId,text:e.text,roomId:e.roomId}),Y2=e=>({id:e.id,ts:e.ts,senderId:e.fromUserId,text:e.text,toUserId:e.toUserId});function r8A({children:e}){const{user:A}=tn(),t=(A==null?void 0:A.id)??"anon",{roomSendMessage:i,roomFetchHistory:n,dmSendMessage:g,dmFetchHistory:o}=Mo(),[s,a]=E.useState({}),[r,I]=E.useState({}),[c,l]=E.useState(null),[B,Q]=E.useState({}),h=E.useRef(new Set),{info:d}=JL(),p=eA=>eA?eA.length>100?eA.slice(0,100)+"…":eA:"",y=E.useCallback((eA,aA,sA)=>{if(aA!=null&&aA.length&&(a(pA=>{const gA=pA[eA]??[],yA=new Map;for(const RA of gA)RA!=null&&RA.id&&yA.set(RA.id,RA);for(const RA of aA){if(!(RA!=null&&RA.id))continue;const qA=yA.get(RA.id);yA.set(RA.id,{...qA??{},...RA,pending:!1,error:void 0})}const fA=Array.from(yA.values()).sort(T2);return{...pA,[eA]:fA}}),eA.startsWith("dm:")&&(sA!=null&&sA.fromPeerId))){const pA=sA.fromPeerId,gA=wC(t,pA),yA=c===pA,fA=aA.filter(RA=>RA.senderId===pA).length;fA>0&&!yA&&I(RA=>({...RA,[gA]:(RA[gA]??0)+fA}))}},[c,t]),m=E.useCallback((eA,aA,sA)=>{a(pA=>{const gA=(pA[eA]??[]).slice();return gA.push(aA),gA.sort(T2),{...pA,[eA]:gA}}),(async()=>{try{const pA=await sA();if(!(pA!=null&&pA.ok)||!pA.id)throw new Error((pA==null?void 0:pA.error)||"send failed");const gA=pA.id;h.current.add(gA),a(yA=>{const fA=yA[eA]??[],RA=fA.some(W=>W.id===gA);let qA;return RA?qA=fA.filter(W=>W.id!==aA.id):qA=fA.map(W=>W.id===aA.id?{...W,id:gA,pending:!1,error:void 0}:W),qA.sort(T2),{...yA,[eA]:qA}})}catch(pA){a(gA=>{const yA=(gA[eA]??[]).map(fA=>fA.id===aA.id?{...fA,pending:!1,error:(pA==null?void 0:pA.message)||"send failed"}:fA);return{...gA,[eA]:yA}})}})()},[]),D=E.useCallback(eA=>{a(aA=>{if(!aA[eA])return aA;const sA={...aA};return delete sA[eA],sA}),eA.startsWith("dm:")&&(I(aA=>{if(!(eA in aA))return aA;const sA={...aA};return delete sA[eA],sA}),Q(aA=>{if(!(eA in aA))return aA;const sA={...aA};return delete sA[eA],sA}))},[]),S=E.useCallback(eA=>(s[eA]??[]).some(aA=>aA.pending),[s]),k=E.useCallback(eA=>{const aA=lh(eA);return z(eA),(s[aA]??[]).slice()},[s]),N=E.useCallback((eA,aA)=>{const sA=(aA??"").trim();if(!sA)return null;const pA=lh(eA),gA=P$(),yA={id:gA,ts:Date.now(),senderId:t,text:sA,roomId:eA,pending:!0};return m(pA,yA,()=>i(eA,sA)),gA},[t,i,m]),G=E.useCallback(eA=>D(lh(eA)),[D]),M=E.useCallback(eA=>S(lh(eA)),[S]),w=E.useCallback(async eA=>{const aA=wC(t,eA);if(!B[aA])try{const sA=await(o==null?void 0:o(eA));if(sA!=null&&sA.ok&&Array.isArray(sA.messages)){const pA=sA.messages.map(Y2);y(aA,pA),I(gA=>({...gA,[aA]:0}))}}finally{Q(sA=>({...sA,[aA]:!0}))}},[o,y,t,B]),b=E.useCallback(eA=>{const aA=wC(t,eA);return w(eA),(s[aA]??[]).slice()},[s,t,w]),_=E.useCallback((eA,aA)=>{const sA=(aA??"").trim();if(!sA)return null;const pA=wC(t,eA),gA=P$(),yA={id:gA,ts:Date.now(),senderId:t,text:sA,toUserId:eA,pending:!0};return m(pA,yA,()=>g(eA,sA)),gA},[t,m,g]),K=E.useCallback(eA=>D(wC(t,eA)),[D,t]),J=E.useCallback(eA=>S(wC(t,eA)),[S,t]),q=E.useCallback(eA=>{const aA=wC(t,eA);I(sA=>{if(!(aA in sA))return sA;const pA={...sA};return pA[aA]=0,pA})},[t]),v=E.useCallback(eA=>{l(eA),eA&&(q(eA),w(eA))},[q,w]),U=E.useCallback(eA=>{const aA=[];for(const[sA,pA]of Object.entries(s??{})){if(!sA.startsWith("dm:"))continue;const gA=O$(sA);if(!gA)continue;const yA=gA[0]===t?gA[1]:gA[0];if(eA&&yA!==eA)continue;const fA=pA[pA.length-1];aA.push({peerUserId:yA,last:fA,unread:(r==null?void 0:r[sA])??0,hasPending:pA.some(RA=>RA.pending)})}return aA.sort((sA,pA)=>{var gA,yA;return(((gA=pA.last)==null?void 0:gA.ts)??0)-(((yA=sA.last)==null?void 0:yA.ts)??0)}),aA},[s,r,t]),x=E.useCallback(eA=>{const aA=new Set(eA);let sA=0;for(const[pA,gA]of Object.entries(r)){if(gA<=0)continue;const yA=O$(pA);if(!yA)continue;const fA=yA[0]===t?yA[1]:yA[0];aA.has(fA)&&(sA+=gA)}return sA},[r,t]),T=E.useCallback(eA=>{const aA=wC(t,eA);return(r==null?void 0:r[aA])??0},[r,t]);async function z(eA){const aA=lh(eA);if(!(s[aA]??[]).length)try{const sA=await(n==null?void 0:n(eA));if(sA!=null&&sA.ok&&Array.isArray(sA.messages)){const pA=sA.messages.map(q2);y(aA,pA)}}catch{}}Os({onRoomMessage:eA=>{if(!(!(eA!=null&&eA.id)||!eA.roomId)&&!h.current.has(eA.id)){h.current.add(eA.id),y(lh(eA.roomId),[q2(eA)]);try{d("Message",p(eA.text))}catch{}}},onRoomHistory:({roomId:eA,messages:aA})=>{!eA||!Array.isArray(aA)||y(lh(eA),aA.map(q2))},onDmMessage:eA=>{if(!(eA!=null&&eA.id))return;const aA=eA.fromUserId===t?eA.toUserId:eA.fromUserId;if(!aA)return;const sA=wC(t,aA),pA=Y2(eA);if(y(sA,[pA],{fromPeerId:eA.fromUserId!==t?eA.fromUserId:void 0}),eA.fromUserId!==t)try{d("Direct Message",p(eA.text))}catch{}c===aA&&I(gA=>({...gA,[sA]:0}))},onDmHistory:({peerUserId:eA,messages:aA})=>{if(!eA||!Array.isArray(aA))return;const sA=wC(t,eA);y(sA,aA.map(Y2)),c===eA&&I(pA=>({...pA,[sA]:0})),Q(pA=>({...pA,[sA]:!0}))}});const Z=E.useMemo(()=>({getRoomMessages:k,sendRoomMessage:N,clearRoom:G,roomHasPending:M,getDmMessages:b,sendDmMessage:_,clearDm:K,dmHasPending:J,getDmSummary:U,markDmRead:q,setActiveDm:v,loadDmHistory:w,threads:s,getTotalFriendUnread:x,getUnreadForPeer:T}),[k,N,G,M,b,_,K,J,U,q,v,w,s,x,T]);return C.jsx(BQA.Provider,{value:Z,children:e})}const I8A=5e3;function C8A(){const{quickMatchJoin:e,quickMatchLeave:A,quickMatchStatus:t}=Mo(),i=Ms(),n=qi(),[g,o]=E.useState({status:"idle"}),[s,a]=E.useState({}),r=E.useRef(!0),I=E.useRef(g);I.current=g;const c=E.useRef(null),l=E.useCallback(()=>{c.current!=null&&(clearTimeout(c.current),c.current=null)},[]);E.useEffect(()=>{if(!i)return;const h=m=>{l(),I.current.status!=="idle"&&(o({status:"found",roomId:m.roomId,route:m.route,gameMode:m.gameMode,opponent:m.opponent}),r.current&&setTimeout(()=>{n(m.route),setTimeout(()=>o({status:"idle"}),500)},1500))},d=m=>{m!=null&&m.queueSizes&&a(m.queueSizes)},p=()=>{i.off("quick_match:found",h),i.off("quick_match:waiting",d),i.on("quick_match:found",h),i.on("quick_match:waiting",d)};p(),i.on("connect",p);const y=()=>{I.current.status==="searching"&&(t==null||t().then(m=>{m!=null&&m.ok&&m.queueSizes&&a(m.queueSizes)}).catch(()=>{}))};return i.on("connect",y),()=>{i.off("quick_match:found",h),i.off("quick_match:waiting",d),i.off("connect",p),i.off("connect",y)}},[i,n,t,l]),E.useEffect(()=>l,[l]);const B=E.useCallback(async(h,d)=>{l(),o({status:"searching",gameMode:h});const p=(d==null?void 0:d.timeoutMs)??I8A;if(p>0&&(d!=null&&d.onTimeout)){const y=d.onTimeout;c.current=window.setTimeout(()=>{c.current=null,I.current.status==="searching"&&(async()=>{try{await A()}catch{}if(I.current.status==="searching"){o({status:"idle"});try{y()}catch{}}})()},p)}try{const y=h==="zentara"?Math.max(1,Math.min(5,(await Xo()).zentaraBotCount??ds.zentaraBotCount??3)):void 0,m=await e(h,y);m!=null&&m.ok?m.matched||m.queueSizes&&a(m.queueSizes):(l(),o({status:"idle"}))}catch{l(),o({status:"idle"})}},[e,A,l]),Q=E.useCallback(async()=>{l();try{await A()}catch{}o({status:"idle"})},[A,l]);return{state:g,queueSizes:s,join:B,leave:Q}}function j$({gameMode:e,disabled:A,onFallbackToSinglePlayer:t}){const{state:i,leave:n,join:g}=C8A(),o=E.useCallback(()=>{e&&(ti("Medium"),i.status==="searching"?n():i.status==="idle"&&g(e,t?{onTimeout:t}:void 0))},[e,i.status,g,n,t]),s=i.status==="searching",a=i.status==="found";return C.jsx("button",{className:`btn gold-outline cta-btn primaryButton${s?" quick-match-btn--searching":""}${a?" quick-match-btn--found":""}`,onClick:o,disabled:A||!e||a,"aria-label":s?"Cancel Quick Match":a?"Match Found!":"Quick Match",type:"button",children:a?C.jsxs(C.Fragment,{children:[C.jsx("span",{className:"qm-icon","aria-hidden":!0,children:"🎯"}),C.jsx("span",{className:"qm-label",children:"Match Found!"})]}):s?C.jsxs(C.Fragment,{children:[C.jsx("span",{className:"qm-spinner","aria-hidden":!0}),C.jsx("span",{className:"qm-label",children:"Searching…"}),C.jsx("span",{className:"qm-cancel",children:"✕"})]}):C.jsxs(C.Fragment,{children:[C.jsx("span",{className:"qm-icon","aria-hidden":!0,children:"⚡"}),C.jsx("span",{className:"qm-label",children:"Quick Match"})]})})}const c8A="purple",l8A="cyan",B8A="orange",E8A="red",Q8A="yellow",u8A="green",d8A="blue",h8A="magenta",V1=c8A,Mm=l8A,Nm=B8A,Rm=E8A,Gm=Q8A,bm=u8A,Um=d8A,CN=h8A,z$=[{id:0,name:"Command Base",type:"start"},{id:1,name:"Alpha Centauri",type:"planet",group:V1,cost:60,rent:[2,10,30,90,160,250],upgradeCost:50},{id:2,name:"Nebula Drift",type:"nebula"},{id:3,name:"Proxima B",type:"planet",group:V1,cost:60,rent:[4,20,60,180,320,450],upgradeCost:50},{id:4,name:"Void Flux",type:"tax"},{id:5,name:"Outpost Alpha",type:"station",cost:200},{id:6,name:"Kepler-22b",type:"planet",group:Mm,cost:100,rent:[6,30,90,270,400,550],upgradeCost:50},{id:7,name:"Asteroid Belt",type:"asteroid"},{id:8,name:"Kepler-442b",type:"planet",group:Mm,cost:100,rent:[6,30,90,270,400,550],upgradeCost:50},{id:9,name:"Kepler-62f",type:"planet",group:Mm,cost:120,rent:[8,40,100,300,450,600],upgradeCost:50},{id:10,name:"Cryosleep Chamber",type:"jail"},{id:11,name:"Trappist-1d",type:"planet",group:Nm,cost:140,rent:[10,50,150,450,625,750],upgradeCost:100},{id:12,name:"Wormhole α",type:"wormhole"},{id:13,name:"Trappist-1e",type:"planet",group:Nm,cost:140,rent:[10,50,150,450,625,750],upgradeCost:100},{id:14,name:"Trappist-1f",type:"planet",group:Nm,cost:160,rent:[12,60,180,500,700,900],upgradeCost:100},{id:15,name:"Outpost Beta",type:"station",cost:200},{id:16,name:"Ross 128b",type:"planet",group:Rm,cost:180,rent:[14,70,200,550,750,950],upgradeCost:100},{id:17,name:"Nebula Storm",type:"nebula"},{id:18,name:"Tau Ceti e",type:"planet",group:Rm,cost:180,rent:[14,70,200,550,750,950],upgradeCost:100},{id:19,name:"Tau Ceti f",type:"planet",group:Rm,cost:200,rent:[16,80,220,600,800,1e3],upgradeCost:100},{id:20,name:"Safe Harbor",type:"free-parking"},{id:21,name:"Gliese 667Cc",type:"planet",group:Gm,cost:220,rent:[18,90,250,700,875,1050],upgradeCost:150},{id:22,name:"Asteroid Storm",type:"asteroid"},{id:23,name:"Gliese 581d",type:"planet",group:Gm,cost:220,rent:[18,90,250,700,875,1050],upgradeCost:150},{id:24,name:"Gliese 581g",type:"planet",group:Gm,cost:240,rent:[20,100,300,750,925,1100],upgradeCost:150},{id:25,name:"Outpost Gamma",type:"station",cost:200},{id:26,name:"Cancri 55e",type:"planet",group:bm,cost:260,rent:[22,110,330,800,975,1150],upgradeCost:150},{id:27,name:"Cancri 55f",type:"planet",group:bm,cost:260,rent:[22,110,330,800,975,1150],upgradeCost:150},{id:28,name:"Wormhole β",type:"wormhole"},{id:29,name:"HD 40307g",type:"planet",group:bm,cost:280,rent:[24,120,360,850,1025,1200],upgradeCost:150},{id:30,name:"Black Hole",type:"go-to-jail"},{id:31,name:"Kapteyn b",type:"planet",group:Um,cost:300,rent:[26,130,390,900,1100,1275],upgradeCost:200},{id:32,name:"Kapteyn c",type:"planet",group:Um,cost:300,rent:[26,130,390,900,1100,1275],upgradeCost:200},{id:33,name:"Nebula Gateway",type:"nebula"},{id:34,name:"Wolf 1061c",type:"planet",group:Um,cost:320,rent:[28,150,450,1e3,1200,1400],upgradeCost:200},{id:35,name:"Outpost Delta",type:"station",cost:200},{id:36,name:"Asteroid Shower",type:"asteroid"},{id:37,name:"Pandora",type:"planet",group:CN,cost:350,rent:[35,175,500,1100,1300,1500],upgradeCost:200},{id:38,name:"Dark Matter Surge",type:"tax"},{id:39,name:"Zentara",type:"planet",group:CN,cost:400,rent:[50,200,600,1400,1700,2e3],upgradeCost:200}],Z$=[{id:0,name:"Command Base",type:"start"},{id:1,name:"Kepler-62f",type:"planet",group:Mm,cost:120,rent:[8,40,100,300,450,600],upgradeCost:50},{id:2,name:"Kepler-22b",type:"planet",group:Mm,cost:100,rent:[6,30,90,270,400,550],upgradeCost:50},{id:3,name:"Cryosleep Chamber",type:"jail"},{id:4,name:"Trappist-1d",type:"planet",group:Nm,cost:140,rent:[10,50,150,450,625,750],upgradeCost:100},{id:5,name:"Trappist-1f",type:"planet",group:Nm,cost:160,rent:[12,60,180,500,700,900],upgradeCost:100},{id:6,name:"Nebula Storm",type:"nebula"},{id:7,name:"Ross 128b",type:"planet",group:Rm,cost:180,rent:[14,70,200,550,750,950],upgradeCost:100},{id:8,name:"Tau Ceti f",type:"planet",group:Rm,cost:200,rent:[16,80,220,600,800,1e3],upgradeCost:100},{id:9,name:"Outpost Alpha",type:"station",cost:200},{id:10,name:"Gliese 667Cc",type:"planet",group:Gm,cost:220,rent:[18,90,250,700,875,1050],upgradeCost:150},{id:11,name:"Gliese 581g",type:"planet",group:Gm,cost:240,rent:[20,100,300,750,925,1100],upgradeCost:150},{id:12,name:"Nebula Gateway",type:"nebula"},{id:13,name:"Cancri 55f",type:"planet",group:bm,cost:260,rent:[22,110,330,800,975,1150],upgradeCost:150},{id:14,name:"HD 40307g",type:"planet",group:bm,cost:280,rent:[24,120,360,850,1025,1200],upgradeCost:150},{id:15,name:"Black Hole",type:"go-to-jail"},{id:16,name:"Kapteyn c",type:"planet",group:Um,cost:300,rent:[26,130,390,900,1100,1275],upgradeCost:200},{id:17,name:"Wolf 1061c",type:"planet",group:Um,cost:320,rent:[28,150,450,1e3,1200,1400],upgradeCost:200},{id:18,name:"Pandora",type:"planet",group:CN,cost:350,rent:[35,175,500,1100,1300,1500],upgradeCost:200},{id:19,name:"Zentara",type:"planet",group:CN,cost:400,rent:[50,200,600,1400,1700,2e3],upgradeCost:200}],EQA={startingCredits:1500,passStartBonus:200,jailBailCost:50,armorUpgradeCost:200,weaponUpgradeCost:250,armorDamageReduction:.15,maxArmorLevel:3,maxWeaponLevel:3},p8A={tiles:z$,tileCount:z$.length,...EQA},f8A={tiles:Z$,tileCount:Z$.length,...EQA},y8A={[V1]:"#7b2ff2",[Mm]:"#00e5ff",[Nm]:"#ff9100",[Rm]:"#ff1744",[Gm]:"#ffd600",[bm]:"#00e676",[Um]:"#2979ff",[CN]:"#e040fb"};function D8A(e){const A=e.type==="tax"?"void-drain":e.type;return{id:e.id,name:e.name,type:A,group:e.group,cost:e.cost,rent:e.rent,upgradeCost:e.upgradeCost}}function QQA(e){return{tiles:e.tiles.map(D8A),tileCount:e.tileCount,startingCredits:e.startingCredits,passStartBonus:e.passStartBonus,jailBailCost:e.jailBailCost,armorUpgradeCost:e.armorUpgradeCost,weaponUpgradeCost:e.weaponUpgradeCost,armorDamageReduction:e.armorDamageReduction,maxArmorLevel:e.maxArmorLevel,maxWeaponLevel:e.maxWeaponLevel}}const dn=QQA(p8A),m8A=QQA(f8A);function XF(e){return e==="standard"?m8A:dn}const Bs=y8A,ZL="zentara_saved_game";function uQA(e){const{board:A,...t}=e;localStorage.setItem(ZL,JSON.stringify(t))}function S8A(){return localStorage.getItem(ZL)!==null}function dQA(){const e=localStorage.getItem(ZL);if(!e)return null;try{const A=JSON.parse(e);if(!A.matchId||!Array.isArray(A.players)||A.players.length<2)return null;for(const t of A.players)t.armorLevel==null&&(t.armorLevel=0),t.weaponLevel==null&&(t.weaponLevel=0);return{...A,board:XF(A.boardSize).tiles}}catch{return null}}function X1(){localStorage.removeItem(ZL)}const w8A="/assets/azure-sovereignty-t1-DmX6oKNg.webp",M5=Object.freeze(Object.defineProperty({__proto__:null,default:w8A},Symbol.toStringTag,{value:"Module"})),k8A="/assets/azure-sovereignty-t2-HrQch5a7.webp",N5=Object.freeze(Object.defineProperty({__proto__:null,default:k8A},Symbol.toStringTag,{value:"Module"})),M8A="/assets/azure-sovereignty-t3-DXjh05IZ.webp",R5=Object.freeze(Object.defineProperty({__proto__:null,default:M8A},Symbol.toStringTag,{value:"Module"})),N8A="/assets/azure-sovereignty-t4-DGQWyj9i.webp",G5=Object.freeze(Object.defineProperty({__proto__:null,default:N8A},Symbol.toStringTag,{value:"Module"})),R8A="/assets/azure-sovereignty-t5-DskYl0iv.webp",b5=Object.freeze(Object.defineProperty({__proto__:null,default:R8A},Symbol.toStringTag,{value:"Module"})),G8A="/assets/azure-sovereignty-t6-B08urHNJ.webp",U5=Object.freeze(Object.defineProperty({__proto__:null,default:G8A},Symbol.toStringTag,{value:"Module"})),b8A="/assets/crimson-dominion-t1-Vf8IUB_D.webp",v5=Object.freeze(Object.defineProperty({__proto__:null,default:b8A},Symbol.toStringTag,{value:"Module"})),U8A="/assets/crimson-dominion-t2-R4fcfwor.webp",K5=Object.freeze(Object.defineProperty({__proto__:null,default:U8A},Symbol.toStringTag,{value:"Module"})),v8A="/assets/crimson-dominion-t3-Dq48yda7.webp",F5=Object.freeze(Object.defineProperty({__proto__:null,default:v8A},Symbol.toStringTag,{value:"Module"})),K8A="/assets/crimson-dominion-t4-jQ3WbC0q.webp",_5=Object.freeze(Object.defineProperty({__proto__:null,default:K8A},Symbol.toStringTag,{value:"Module"})),F8A="/assets/crimson-dominion-t5-BxD0z7Ym.webp",J5=Object.freeze(Object.defineProperty({__proto__:null,default:F8A},Symbol.toStringTag,{value:"Module"})),_8A="/assets/crimson-dominion-t6-DdFNyKQB.webp",L5=Object.freeze(Object.defineProperty({__proto__:null,default:_8A},Symbol.toStringTag,{value:"Module"})),J8A="/assets/emerald-collective-t1-BFDYbRJC.webp",x5=Object.freeze(Object.defineProperty({__proto__:null,default:J8A},Symbol.toStringTag,{value:"Module"})),L8A="/assets/emerald-collective-t2-B0HN4oSa.webp",T5=Object.freeze(Object.defineProperty({__proto__:null,default:L8A},Symbol.toStringTag,{value:"Module"})),x8A="/assets/emerald-collective-t3-bX8hcHMX.webp",q5=Object.freeze(Object.defineProperty({__proto__:null,default:x8A},Symbol.toStringTag,{value:"Module"})),T8A="/assets/emerald-collective-t4-Bfmm0OcF.webp",Y5=Object.freeze(Object.defineProperty({__proto__:null,default:T8A},Symbol.toStringTag,{value:"Module"})),q8A="/assets/emerald-collective-t5-Bgb0YdAC.webp",H5=Object.freeze(Object.defineProperty({__proto__:null,default:q8A},Symbol.toStringTag,{value:"Module"})),Y8A="/assets/emerald-collective-t6-BTeZLW--.webp",O5=Object.freeze(Object.defineProperty({__proto__:null,default:Y8A},Symbol.toStringTag,{value:"Module"})),H8A="/assets/golden-imperium-t1-2Ac07vhL.webp",P5=Object.freeze(Object.defineProperty({__proto__:null,default:H8A},Symbol.toStringTag,{value:"Module"})),O8A="/assets/golden-imperium-t2-B1z9wYCA.webp",j5=Object.freeze(Object.defineProperty({__proto__:null,default:O8A},Symbol.toStringTag,{value:"Module"})),P8A="/assets/golden-imperium-t3-sQgzUnhL.webp",z5=Object.freeze(Object.defineProperty({__proto__:null,default:P8A},Symbol.toStringTag,{value:"Module"})),j8A="/assets/golden-imperium-t4-QLhb8vtv.webp",Z5=Object.freeze(Object.defineProperty({__proto__:null,default:j8A},Symbol.toStringTag,{value:"Module"})),z8A="/assets/golden-imperium-t5-ztz2kNG1.webp",W5=Object.freeze(Object.defineProperty({__proto__:null,default:z8A},Symbol.toStringTag,{value:"Module"})),Z8A="/assets/golden-imperium-t6-Cw2Zjnaw.webp",V5=Object.freeze(Object.defineProperty({__proto__:null,default:Z8A},Symbol.toStringTag,{value:"Module"})),W8A="/assets/silver-pact-t1-dcR9QgEE.webp",X5=Object.freeze(Object.defineProperty({__proto__:null,default:W8A},Symbol.toStringTag,{value:"Module"})),V8A="/assets/silver-pact-t2-BpNmnrg8.webp",$5=Object.freeze(Object.defineProperty({__proto__:null,default:V8A},Symbol.toStringTag,{value:"Module"})),X8A="/assets/silver-pact-t3-wI2PlS3S.webp",Az=Object.freeze(Object.defineProperty({__proto__:null,default:X8A},Symbol.toStringTag,{value:"Module"})),$8A="/assets/silver-pact-t4-BCVdufU2.webp",ez=Object.freeze(Object.defineProperty({__proto__:null,default:$8A},Symbol.toStringTag,{value:"Module"})),A5A="/assets/silver-pact-t5-CvVwxwL3.webp",tz=Object.freeze(Object.defineProperty({__proto__:null,default:A5A},Symbol.toStringTag,{value:"Module"})),e5A="/assets/silver-pact-t6-AkEiFdAv.webp",iz=Object.freeze(Object.defineProperty({__proto__:null,default:e5A},Symbol.toStringTag,{value:"Module"})),t5A="/assets/void-enclave-t1-CT6bXzYA.webp",nz=Object.freeze(Object.defineProperty({__proto__:null,default:t5A},Symbol.toStringTag,{value:"Module"})),i5A="/assets/void-enclave-t2-B5lyWeE-.webp",gz=Object.freeze(Object.defineProperty({__proto__:null,default:i5A},Symbol.toStringTag,{value:"Module"})),n5A="/assets/void-enclave-t3-D_btJABX.webp",oz=Object.freeze(Object.defineProperty({__proto__:null,default:n5A},Symbol.toStringTag,{value:"Module"})),g5A="/assets/void-enclave-t4-CnK-DAE8.webp",sz=Object.freeze(Object.defineProperty({__proto__:null,default:g5A},Symbol.toStringTag,{value:"Module"})),o5A="/assets/void-enclave-t5-BazUHlmh.webp",az=Object.freeze(Object.defineProperty({__proto__:null,default:o5A},Symbol.toStringTag,{value:"Module"})),s5A="/assets/void-enclave-t6-DftImh4t.webp",rz=Object.freeze(Object.defineProperty({__proto__:null,default:s5A},Symbol.toStringTag,{value:"Module"})),hQA=Ca();async function a5A(){try{const e=await uo(),A=await fetch(`${hQA}/api/heroes/mine`,{credentials:"include",headers:e?{Authorization:`Bearer ${e}`}:{}});return A.ok?(await A.json()).heroes:[]}catch{return[]}}async function r5A(e){try{const A=await uo(),t=await fetch(`${hQA}/api/heroes/buy`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...A?{Authorization:`Bearer ${A}`}:{}},body:JSON.stringify({heroId:e})});if(t.ok){const n=await t.json();return{ok:!0,hero:n.hero,balance:n.balance}}return{ok:!1,error:(await t.json().catch(()=>({error:"UNKNOWN"}))).error}}catch{return{ok:!1,error:"NETWORK_ERROR"}}}const pQA={1:"Recruit",2:"Guardian",3:"Commander",4:"Warlord",5:"Champion",6:"Legend"},fQA={"crimson-dominion":"offense","silver-pact":"balanced","azure-sovereignty":"defense","golden-imperium":"offense","emerald-collective":"defense","void-enclave":"balanced"},yQA={1:{cost:500,baseAttack:.05,baseDefense:.05},2:{cost:1500,baseAttack:.12,baseDefense:.1},3:{cost:4e3,baseAttack:.2,baseDefense:.18},4:{cost:1e4,baseAttack:.3,baseDefense:.25},5:{cost:25e3,baseAttack:.42,baseDefense:.35},6:{cost:6e4,baseAttack:.55,baseDefense:.45}},I5A=.08,C5A=.05,c5A=.05,l5A=.08;function mu(e,A){const t=yQA[A],i=fQA[e];let n=t.baseAttack,g=t.baseDefense;return i==="offense"?(n+=I5A,g=Math.max(0,g-C5A)):i==="defense"&&(n=Math.max(0,n-c5A),g+=l5A),{attack:n,defense:g}}const Iz=[{id:"crimson-dominion-t1",name:"Firebrand",empire:"crimson-dominion",tier:1,title:"Ember Initiate",description:"A young recruit who proved their worth by walking barefoot across the Molten Flats. Their burning resolve lights the way for greener soldiers."},{id:"crimson-dominion-t2",name:"Scorcher",empire:"crimson-dominion",tier:2,title:"Flame Warden",description:"Keeper of the Crimson Watch-fires that never extinguish. Scorcher patrols the volcanic borderlands, turning intruders to cinder."},{id:"crimson-dominion-t3",name:"Inferno",empire:"crimson-dominion",tier:3,title:"Blaze Commander",description:"Forged in the eruption of Mount Karath, Inferno commands battalions of flame-sworn soldiers and leaves scorched earth in every campaign."},{id:"crimson-dominion-t4",name:"Warmaster",empire:"crimson-dominion",tier:4,title:"Crimson General",description:"A tactical genius who orchestrated the Siege of Ashhold with zero retreats. Warmaster's battle plans are studied in every war academy."},{id:"crimson-dominion-t5",name:"Hellion",empire:"crimson-dominion",tier:5,title:"Infernal Champion",description:"Born from the heart of a dying star, Hellion wields twin blades that burn with an unquenchable fury feared across all six empires."},{id:"crimson-dominion-t6",name:"Pyraxus the Eternal",empire:"crimson-dominion",tier:6,title:"Legendary Firelord",description:"Ancient beyond reckoning, Pyraxus has razed and rebuilt the Dominion three times over. They say his heartbeat is the pulse of every volcano."},{id:"silver-pact-t1",name:"Scout",empire:"silver-pact",tier:1,title:"Pact Initiate",description:"Fleet-footed messenger of the Silver Council, trained to navigate the Mirrored Wastes where no compass works."},{id:"silver-pact-t2",name:"Ranger",empire:"silver-pact",tier:2,title:"Silver Blade",description:"Dual-wielding outrider who guards the trade caravans between allied territories. Ranger never sleeps twice in the same camp."},{id:"silver-pact-t3",name:"Sentinel",empire:"silver-pact",tier:3,title:"Pact Commander",description:"Sentinel holds the Argent Bridge—the only passage between the eastern and western realms—and has never let it fall."},{id:"silver-pact-t4",name:"Vanguard",empire:"silver-pact",tier:4,title:"Silver Warlord",description:"A decorated strategist who united three feuding clans under a single banner. Vanguard fights at the front, never from behind."},{id:"silver-pact-t5",name:"Arbiter",empire:"silver-pact",tier:5,title:"Swift Champion",description:"Judge and executioner sworn to the Pact's highest law. Arbiter can settle any dispute—by word or by blade—before sunset."},{id:"silver-pact-t6",name:"Lysara the Swift",empire:"silver-pact",tier:6,title:"Legendary Arbiter",description:"They say Lysara once outran a thunderbolt. Her silver armor is woven from moonlight, and her judgement is absolute."},{id:"azure-sovereignty-t1",name:"Acolyte",empire:"azure-sovereignty",tier:1,title:"Azure Initiate",description:"A student of the Tidal Archives who channels the sea's patience into unbreakable wards."},{id:"azure-sovereignty-t2",name:"Scholar",empire:"azure-sovereignty",tier:2,title:"Wisdom Keeper",description:"Keeper of the Sovereignty's forbidden scrolls. Scholar can recite ten thousand defensive runes from memory."},{id:"azure-sovereignty-t3",name:"Archon",empire:"azure-sovereignty",tier:3,title:"Shield Commander",description:"Archon raised the Great Coral Barrier that protects the capital from siege. Armies break against their shields like waves on rock."},{id:"azure-sovereignty-t4",name:"High Sage",empire:"azure-sovereignty",tier:4,title:"Azure Warlord",description:"Master of deep-water strategy, High Sage commands from the sunken war-temple and sees every battlefield through enchanted tide pools."},{id:"azure-sovereignty-t5",name:"Oracle",empire:"azure-sovereignty",tier:5,title:"Aegis Champion",description:"Gifted with foresight drawn from the Abyssal Currents, Oracle has never been struck by a blow they did not choose to receive."},{id:"azure-sovereignty-t6",name:"Thalonis the Wise",empire:"azure-sovereignty",tier:6,title:"Legendary Archon",description:"First of the Azure bloodline, Thalonis shaped the ocean floor into fortress walls. His wisdom echoes in every crashing wave."},{id:"golden-imperium-t1",name:"Merchant",empire:"golden-imperium",tier:1,title:"Gold Initiate",description:"Sharp-eyed trader who turned a single coin into an armory. Merchant knows that every war is won in the marketplace first."},{id:"golden-imperium-t2",name:"Baron",empire:"golden-imperium",tier:2,title:"Gold Baron",description:"Lavish and ruthless, Baron controls the amber mines that fund the Imperium's endless expansion."},{id:"golden-imperium-t3",name:"Magnate",empire:"golden-imperium",tier:3,title:"Imperial Commander",description:"Magnate's golden legions march in gilded armor that blinds their foes before a single blow is struck."},{id:"golden-imperium-t4",name:"Overlord",empire:"golden-imperium",tier:4,title:"Gold Warlord",description:"Ruler of the Sunspire Citadel, Overlord levies tribute from three continents and crushes dissent with coin or cannon."},{id:"golden-imperium-t5",name:"Tyrant",empire:"golden-imperium",tier:5,title:"Imperial Champion",description:"Tyrant seized power in a single night and has held it ever since. Their throne is forged from the weapons of fallen rivals."},{id:"golden-imperium-t6",name:"Aurelion the Gilded",empire:"golden-imperium",tier:6,title:"Legendary Emperor",description:"The immortal founder of the Imperium whose golden touch once blessed an entire kingdom. Aurelion's riches are said to be infinite."},{id:"emerald-collective-t1",name:"Seedling",empire:"emerald-collective",tier:1,title:"Grove Initiate",description:"Freshly bonded to the Great Root network, Seedling can feel enemy footsteps through the forest floor."},{id:"emerald-collective-t2",name:"Warden",empire:"emerald-collective",tier:2,title:"Root Warden",description:"Guardian of the Thornwall Perimeter, Warden commands living vines that entangle trespassers before they see daylight."},{id:"emerald-collective-t3",name:"Keeper",empire:"emerald-collective",tier:3,title:"Forest Commander",description:"Keeper orchestrates the ancient treant legions that have defended the Verdant Heartland for a thousand seasons."},{id:"emerald-collective-t4",name:"Elder",empire:"emerald-collective",tier:4,title:"Grove Warlord",description:"Centuries old and rooted deep, Elder channels the strength of the entire forest canopy into impenetrable bark-shields."},{id:"emerald-collective-t5",name:"Primarch",empire:"emerald-collective",tier:5,title:"Nature Champion",description:"Primarch is both judge and jury of the Collective, wielding nature's wrath—storms, quakes, and regrowth—as weapons of war."},{id:"emerald-collective-t6",name:"Verdaxis the Rooted",empire:"emerald-collective",tier:6,title:"Legendary Primarch",description:"The oldest living being in any realm, Verdaxis remembers the world before empires. Their roots span continents and their canopy shelters nations."},{id:"void-enclave-t1",name:"Shade",empire:"void-enclave",tier:1,title:"Shadow Initiate",description:"A whisper in the dark, Shade slips between dimensions to gather secrets that others would kill to keep."},{id:"void-enclave-t2",name:"Wraith",empire:"void-enclave",tier:2,title:"Void Stalker",description:"Neither alive nor dead, Wraith haunts the space between worlds and strikes from angles that shouldn't exist."},{id:"void-enclave-t3",name:"Specter",empire:"void-enclave",tier:3,title:"Shadow Commander",description:"Specter leads the Hollow Legion—an army that leaves no footprints, casts no shadows, and takes no prisoners."},{id:"void-enclave-t4",name:"Revenant",empire:"void-enclave",tier:4,title:"Void Warlord",description:"Killed seven times and returned each dawn, Revenant has forgotten the meaning of defeat. Death itself refuses them."},{id:"void-enclave-t5",name:"Phantom",empire:"void-enclave",tier:5,title:"Shadow Champion",description:"Phantom exists in all places at once, a living paradox whose attacks land before they are even launched."},{id:"void-enclave-t6",name:"Nyx the Unseen",empire:"void-enclave",tier:6,title:"Legendary Phantom",description:"No one has ever truly seen Nyx—only the aftermath. The Enclave's eternal sovereign rules from a throne that exists outside of time."}],ms=Object.fromEntries(Iz.map(e=>[e.id,e]));function $1(e){return Iz.filter(A=>A.empire===e)}function Cz(){const[e,A]=E.useState([]),[t,i]=E.useState(!0),[n,g]=E.useState(!1),o=E.useCallback(async()=>{i(!0);const I=await a5A();A(I),i(!1)},[]);E.useEffect(()=>{o()},[o]);const s=E.useMemo(()=>new Set(e.map(I=>I.heroId)),[e]),a=E.useCallback(async I=>{if(n)return{ok:!1,error:"BUSY"};g(!0);const c=await r5A(I);return c.ok&&A(l=>[...l,c.hero]),g(!1),c},[n]),r=E.useCallback(I=>{const c=e.filter(l=>l.empire===I);return c.length===0?null:c.reduce((l,B)=>B.tier>l.tier?B:l)},[e]);return{roster:Iz,owned:e,ownedIds:s,loading:t,buying:n,buy:a,refresh:o,bestHeroForEmpire:r,getHeroModifiers:mu,HERO_TIER_STATS:yQA,HERO_BY_ID:ms,getHeroesForEmpire:$1}}const gB={"crimson-dominion":{name:"The Crimson Dominion",motto:"Through fire, sovereignty.",lore:"Born from the ashes of the First Stellar Collapse, the Crimson Dominion rose when Warlord Drakon unified the warring clans of the Pyrrhus Nebula under a single blood-red banner. Their empire is built on a rigid military caste — every citizen is a soldier first. The Dominion believes that only through relentless conquest can order be imposed on the chaos of the galaxy. Their dreadnought fleets are feared across every quadrant, and their dragon sigil has become synonymous with overwhelming force."},"silver-pact":{name:"The Silver Pact",motto:"Swift wings, sharp eyes.",lore:"The Silver Pact began as a coalition of independent traders and scouts who banded together for mutual defence along the Frostline Corridor. Over centuries, their mercantile federation evolved into a formidable intelligence network. Pact operatives are the fastest pilots in the galaxy, flying interceptor-class vessels that strike before enemies can react. They value freedom, speed, and information above all else — and they never forget a debt."},"azure-sovereignty":{name:"The Azure Sovereignty",motto:"Wisdom crowns the worthy.",lore:"The oldest surviving civilisation in the Zentara sector, the Azure Sovereignty traces its lineage to the philosopher-kings of Oceanus Prime. Their society is governed by the Council of Stars — twelve scholars elected by merit alone. The Sovereignty commands titan-class war machines fused with ancient technology that no other faction has been able to replicate. They fight not for conquest, but to preserve the knowledge and balance of the galaxy."},"golden-imperium":{name:"The Golden Imperium",motto:"All stars bow to gold.",lore:"What began as the wealthiest mining corporation in the outer rim became a galactic superpower when Emperor Aurelian declared independence from the old republic. The Golden Imperium controls the largest reserve of Zentarium — the rare element that powers warp drives. Their opulent battle cruisers are gilded monuments to excess, but beneath the splendour lies ruthless economic warfare. They buy what they cannot conquer, and conquer what they cannot buy."},"emerald-collective":{name:"The Emerald Collective",motto:"One root, infinite branches.",lore:"The Collective emerged from the bio-engineered forest worlds of the Verdant Reach, where sentient plant-networks achieved consciousness and merged with their human custodians. Every member of the Collective shares a faint psychic bond through the Root — a living neural web that spans their territory. They deploy colossal bio-mechanical walkers that regenerate in battle. The Collective does not seek dominion; it seeks to grow, to connect, and to outlast all others."},"void-enclave":{name:"The Void Enclave",motto:"From shadow, certainty.",lore:"No one knows when the Void Enclave was truly founded — that is by design. Operating from cloaked stations hidden in the darkest reaches of uncharted space, the Enclave is part spy network, part cult, part shadow government. Their stealth destroyers can phase through sensor grids undetected. Led by the enigmatic Archon, they manipulate galactic politics from the shadows. By the time you see the Enclave, they have already won."}};function Xi(e){var A;return((A=gB[e])==null?void 0:A.name)??"Unknown Fleet"}const cz="/assets/piece_0-Bszryx6y.webp",lz="/assets/piece_1-Cv-uF1qp.webp",Bz="/assets/piece_2-BtsgKQre.webp",Ez="/assets/piece_3-jPIn8UPt.webp",Qz="/assets/piece_4-CVIaULeN.webp",uz="/assets/piece_5-BbmWhI1d.webp",B5A="/assets/board_azure_t1-uhzyJ5O2.png",E5A="/assets/board_azure_t2-7WFg6SFe.png",Q5A="/assets/board_azure_t3-DFyQ1yFA.png",u5A="/assets/board_azure_t4--LjmjFOc.png",d5A="/assets/board_azure_t5-kCVv9B_8.png",h5A="/assets/board_azure_t6-JV5uCTqU.png",p5A="/assets/board_crimson_t1-BwxUw8u0.png",f5A="/assets/board_crimson_t2-6NEJAqMc.png",y5A="/assets/board_crimson_t3-BWlzMzt2.png",D5A="/assets/board_crimson_t4-D8Jc5yCO.png",m5A="/assets/board_crimson_t5-D6RFLgkV.png",S5A="/assets/board_crimson_t6-gnYH98X_.png",w5A="/assets/board_emerald_t1-B2egbD2-.png",k5A="/assets/board_emerald_t2-BQCAt0fS.png",M5A="/assets/board_emerald_t3-Bi2inM_Z.png",N5A="/assets/board_emerald_t4-Fpn-yafL.png",R5A="/assets/board_emerald_t5-ChEu-JPO.png",G5A="/assets/board_emerald_t6-C6qK5wVr.png",b5A="/assets/board_golden_t1-wUo-Md-J.png",U5A="/assets/board_golden_t2-DpOComt8.png",v5A="/assets/board_golden_t3-Cr04-aIZ.png",K5A="/assets/board_golden_t4-DmLVdFD-.png",F5A="/assets/board_golden_t5-BO_7glbk.png",_5A="/assets/board_golden_t6-Cn2N92HZ.png",J5A="/assets/board_silver_t1-Dk3k-NaJ.png",L5A="/assets/board_silver_t2-gY9z7Ocy.png",x5A="/assets/board_silver_t3-DxuzmvQw.png",T5A="/assets/board_silver_t4-CkoaQVfe.png",q5A="/assets/board_silver_t5-B63wrBnz.png",Y5A="/assets/board_silver_t6-cX56Pc6H.png",H5A="/assets/board_void_t1-DDec7uko.png",O5A="/assets/board_void_t2-HWwY4zjd.png",P5A="/assets/board_void_t3-Bm65kPQF.png",j5A="/assets/board_void_t4-DpFcFdts.png",z5A="/assets/board_void_t5-4mh4n7wE.png",Z5A="/assets/board_void_t6-BnFIOu4n.png",hB={MINIMAP_STEP_MS:150,FLIGHT_DURATION_MS:3350,LIFTOFF_DELAY_MS:1e3,BOARD_ROTATE_MS:1500,SNAP_BUFFER_MS:50,LAND_PHASE_MS:800,DESTROY_BLAST_MS:1300},W5A="/assets/board_crimson-Bbfxhd3p.webp",V5A="/assets/board_silver-Cng7mb9O.webp",X5A="/assets/board_azure-BFKhjmxp.webp",$5A="/assets/board_golden-CanbSjjJ.webp",AzA="/assets/board_emerald-DJHSvo6l.webp",ezA="/assets/board_void-5g3WxUBA.webp",tzA="/assets/board_crimson_still-iwJEtNQX.webp",izA="/assets/board_silver_still-BzHbQUh7.webp",nzA="/assets/board_azure_still-W7WJD2Dq.webp",gzA="/assets/board_golden_still-CYKBiKVV.webp",ozA="/assets/board_emerald_still-Cf5Bc4Q4.webp",szA="/assets/board_void_still-C_C-otYo.webp",azA=Object.assign({"../../assets/optimized/board_azure_t1.png":B5A,"../../assets/optimized/board_azure_t2.png":E5A,"../../assets/optimized/board_azure_t3.png":Q5A,"../../assets/optimized/board_azure_t4.png":u5A,"../../assets/optimized/board_azure_t5.png":d5A,"../../assets/optimized/board_azure_t6.png":h5A,"../../assets/optimized/board_crimson_t1.png":p5A,"../../assets/optimized/board_crimson_t2.png":f5A,"../../assets/optimized/board_crimson_t3.png":y5A,"../../assets/optimized/board_crimson_t4.png":D5A,"../../assets/optimized/board_crimson_t5.png":m5A,"../../assets/optimized/board_crimson_t6.png":S5A,"../../assets/optimized/board_emerald_t1.png":w5A,"../../assets/optimized/board_emerald_t2.png":k5A,"../../assets/optimized/board_emerald_t3.png":M5A,"../../assets/optimized/board_emerald_t4.png":N5A,"../../assets/optimized/board_emerald_t5.png":R5A,"../../assets/optimized/board_emerald_t6.png":G5A,"../../assets/optimized/board_golden_t1.png":b5A,"../../assets/optimized/board_golden_t2.png":U5A,"../../assets/optimized/board_golden_t3.png":v5A,"../../assets/optimized/board_golden_t4.png":K5A,"../../assets/optimized/board_golden_t5.png":F5A,"../../assets/optimized/board_golden_t6.png":_5A,"../../assets/optimized/board_silver_t1.png":J5A,"../../assets/optimized/board_silver_t2.png":L5A,"../../assets/optimized/board_silver_t3.png":x5A,"../../assets/optimized/board_silver_t4.png":T5A,"../../assets/optimized/board_silver_t5.png":q5A,"../../assets/optimized/board_silver_t6.png":Y5A,"../../assets/optimized/board_void_t1.png":H5A,"../../assets/optimized/board_void_t2.png":O5A,"../../assets/optimized/board_void_t3.png":P5A,"../../assets/optimized/board_void_t4.png":j5A,"../../assets/optimized/board_void_t5.png":z5A,"../../assets/optimized/board_void_t6.png":Z5A}),DQA={};for(const[e,A]of Object.entries(azA)){const t=e.split("/").pop();t&&(DQA[t]=A)}const rzA={"crimson-dominion":"crimson","silver-pact":"silver","azure-sovereignty":"azure","golden-imperium":"golden","emerald-collective":"emerald","void-enclave":"void"};function IzA(e,A,t){const i=rzA[e];return DQA[`board_${i}_t${A}.png`]??t}const CzA={"crimson-dominion":W5A,"silver-pact":V5A,"azure-sovereignty":X5A,"golden-imperium":$5A,"emerald-collective":AzA,"void-enclave":ezA},mQA={"crimson-dominion":tzA,"silver-pact":izA,"azure-sovereignty":nzA,"golden-imperium":gzA,"emerald-collective":ozA,"void-enclave":szA},dk=150,$F=dk*.75,Oy=$F,Py=$F,czA=.72,lzA=Ui.getPlatform()==="android";for(const e of[...Object.values(CzA),...Object.values(mQA)]){const A=new Image;A.src=e}const BzA=1e3,EzA=350,SQA=E.forwardRef(({initialX:e,initialY:A,shape:t,isCurrentPlayer:i,rotation:n=0,rotationTransition:g=!1,zoom:o=10,label:s,isMoving:a=!1,isLanding:r=!1,sizeScale:I=1,pickerPiece:c=!1,tier:l=1,outlineFilterId:B},Q)=>{const h=IzA(t,l,mQA[t]),[d,p]=E.useState(!1);E.useEffect(()=>{if(!a){p(!1);return}if(r){const G=setTimeout(()=>p(!1),EzA);return()=>clearTimeout(G)}const N=setTimeout(()=>p(!0),BzA);return()=>clearTimeout(N)},[a,r]);const y=a&&d,m=Math.min(Math.max(1,5/o),1.5),D=E.useMemo(()=>a?r?{transform:`scale(${I})`,transition:`transform ${hB.LAND_PHASE_MS}ms cubic-bezier(0.42, 0, 0.32, 1)`,willChange:"transform"}:{transform:"scale(1)",transition:`transform ${hB.LIFTOFF_DELAY_MS}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`,willChange:"transform"}:{transform:`scale(${I})`,transition:"transform 600ms ease-out",willChange:"transform"},[a,r,I]),S="zentara-piece-shadow",k={filter:"none"};return C.jsx("g",{ref:Q,transform:`translate(${e},${A})`,children:C.jsx("g",{style:{transform:`scale(${m})`,transition:"transform 0.4s cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform"},children:C.jsx("g",{style:D,children:C.jsxs("g",{className:"zentara-piece-rotation",style:{transform:`rotate(${n}deg)`,transition:g?"transform 1.5s cubic-bezier(0.4, 0, 0.2, 1)":"none",willChange:"transform"},children:[C.jsxs("g",{transform:c?void 0:`scale(${czA} 1)`,children:[a&&C.jsx("image",{className:`zentara-piece-shadow-img${!y||r?"":" zentara-piece-shadow-img--hidden"}`,href:h,x:-Oy/2,y:-Py/2+$F*.06,width:Oy,height:Py,preserveAspectRatio:"xMidYMid meet",pointerEvents:"none",filter:`url(#${S})`}),C.jsxs("g",{className:a?"zentara-piece-fly":i?"zentara-piece-float":"",style:{willChange:"transform",transform:"translateZ(0)"},children:[!c&&B&&C.jsx("image",{className:`zentara-piece-outline${i?" zentara-piece-outline--active":""}`,href:h,x:-Oy/2,y:-Py/2,width:Oy,height:Py,preserveAspectRatio:"xMidYMid meet",pointerEvents:"none",filter:`url(#${B})`}),C.jsx("image",{className:`zentara-piece-img${i?" zentara-piece-img--active":""}${a?" zentara-piece-img--moving":""}`,href:h,x:c?-dk:-Oy/2,y:c?-dk:-Py/2,width:c?dk*2:Oy,height:c?dk*2:Py,preserveAspectRatio:"xMidYMid meet",style:k})]})]}),s&&(()=>{const N=s==="Cryosleep",G=N?"❄  CRYOSLEEP":"VISITING";return C.jsx("text",{x:0,y:$F*.28,textAnchor:"middle",...lzA?{lengthAdjust:"spacingAndGlyphs",textLength:N?78:50}:{},className:`zentara-piece-label${N?" zentara-piece-label--cryo":" zentara-piece-label--visiting"}`,children:G})})()]})})})})});SQA.displayName="ZentaraPlayerPiece";const wQA=ue.memo(SQA),W$={"crimson-dominion":cz,"silver-pact":lz,"azure-sovereignty":Bz,"golden-imperium":Ez,"emerald-collective":Qz,"void-enclave":uz},QzA=Object.assign({"../../assets/heroes/azure-sovereignty-t1.webp":M5,"../../assets/heroes/azure-sovereignty-t2.webp":N5,"../../assets/heroes/azure-sovereignty-t3.webp":R5,"../../assets/heroes/azure-sovereignty-t4.webp":G5,"../../assets/heroes/azure-sovereignty-t5.webp":b5,"../../assets/heroes/azure-sovereignty-t6.webp":U5,"../../assets/heroes/crimson-dominion-t1.webp":v5,"../../assets/heroes/crimson-dominion-t2.webp":K5,"../../assets/heroes/crimson-dominion-t3.webp":F5,"../../assets/heroes/crimson-dominion-t4.webp":_5,"../../assets/heroes/crimson-dominion-t5.webp":J5,"../../assets/heroes/crimson-dominion-t6.webp":L5,"../../assets/heroes/emerald-collective-t1.webp":x5,"../../assets/heroes/emerald-collective-t2.webp":T5,"../../assets/heroes/emerald-collective-t3.webp":q5,"../../assets/heroes/emerald-collective-t4.webp":Y5,"../../assets/heroes/emerald-collective-t5.webp":H5,"../../assets/heroes/emerald-collective-t6.webp":O5,"../../assets/heroes/golden-imperium-t1.webp":P5,"../../assets/heroes/golden-imperium-t2.webp":j5,"../../assets/heroes/golden-imperium-t3.webp":z5,"../../assets/heroes/golden-imperium-t4.webp":Z5,"../../assets/heroes/golden-imperium-t5.webp":W5,"../../assets/heroes/golden-imperium-t6.webp":V5,"../../assets/heroes/silver-pact-t1.webp":X5,"../../assets/heroes/silver-pact-t2.webp":$5,"../../assets/heroes/silver-pact-t3.webp":Az,"../../assets/heroes/silver-pact-t4.webp":ez,"../../assets/heroes/silver-pact-t5.webp":tz,"../../assets/heroes/silver-pact-t6.webp":iz,"../../assets/heroes/void-enclave-t1.webp":nz,"../../assets/heroes/void-enclave-t2.webp":gz,"../../assets/heroes/void-enclave-t3.webp":oz,"../../assets/heroes/void-enclave-t4.webp":sz,"../../assets/heroes/void-enclave-t5.webp":az,"../../assets/heroes/void-enclave-t6.webp":rz}),BE={};for(const[e,A]of Object.entries(QzA)){const t=e.split("/").pop().replace(".webp","");BE[t]=A.default}const zu={"crimson-dominion":"#ff3a3a","silver-pact":"#b0c4de","azure-sovereignty":"#4488ff","golden-imperium":"#ffaa00","emerald-collective":"#39ff14","void-enclave":"#cc44ff"},uzA=["crimson-dominion","silver-pact","azure-sovereignty","golden-imperium","emerald-collective","void-enclave"],kQA=({taken:e=[],onSelect:A,heading:t,bestHeroForEmpire:i,onBack:n})=>{const[g,o]=E.useState(null),s=g&&i?i(g):null,a=s?ms[s.heroId]:null,r=a?mu(a.empire,a.tier):null,I=g?gB[g]:null,c=g?C.jsx("div",{className:"zpp__selected-piece",style:{"--faction-color":zu[g]},children:C.jsx("svg",{viewBox:"-120 -60 240 120",preserveAspectRatio:"xMidYMid meet","aria-label":`${gB[g].name} board piece`,children:C.jsx(wQA,{initialX:0,initialY:0,isCurrentPlayer:!0,shape:g,pickerPiece:!0,tier:(a==null?void 0:a.tier)??1})})}):null;return C.jsxs("div",{className:"zpp",children:[C.jsx("div",{className:"zpp__backdrop"}),C.jsxs("div",{className:"zpp__card",children:[C.jsxs("div",{className:"zpp__header",children:[n&&C.jsx("button",{type:"button",onClick:n,className:"zpp__back",children:"← Back"}),C.jsx("h2",{className:"zpp__heading",children:t??"Choose Your Empire"}),C.jsx("div",{className:"zpp__button-container",children:g?C.jsx("button",{className:"zpp__confirm",onClick:()=>A(g),children:"Start"}):C.jsx("button",{className:"zpp__confirm",disabled:!0,children:"Select"})})]}),C.jsx("div",{className:"zpp__faction-container",children:C.jsx("div",{className:"zpp__grid",children:uzA.map(l=>{const B=gB[l],Q=zu[l],h=e.includes(l),d=g===l;return C.jsxs("button",{className:`zpp__faction${d?" zpp__faction--selected":""}${h?" zpp__faction--taken":""}`,style:{"--faction-color":Q},disabled:h,onClick:()=>o(l),title:h?`${B.name} (Taken)`:B.name,children:[C.jsx("img",{className:"zpp__piece-img",src:W$[l],alt:B.name}),C.jsx("span",{className:"zpp__name",children:B.name}),C.jsx("span",{className:"zpp__motto",children:B.motto}),h&&C.jsx("span",{className:"zpp__taken-badge",children:"Taken"})]},l)})})}),C.jsx("div",{className:"zpp__scroll-wrapper",children:g&&I&&C.jsxs("section",{className:"zpp__dossier",style:{"--faction-color":zu[g]},children:[C.jsxs("div",{className:"zpp__dossier-summary",children:[C.jsx("div",{className:"zpp__portrait-frame",children:C.jsx("img",{src:a&&BE[a.id]?BE[a.id]:W$[g],alt:(a==null?void 0:a.name)??I.name,className:`zpp__portrait${a?"":" zpp__portrait--emblem"}`})}),C.jsxs("div",{className:"zpp__hero-info",children:[C.jsx("span",{className:"zpp__hero-label",children:a?"Equipped Hero":"Empire Fleet"}),C.jsx("span",{className:"zpp__hero-name",children:(a==null?void 0:a.name)??I.name}),C.jsx("span",{className:"zpp__hero-title",children:a?`${a.title} · ${pQA[a.tier]}`:I.motto}),r?C.jsxs("span",{className:"zpp__hero-stats",children:[C.jsxs("span",{children:["⚔ +",Math.round(r.attack*100),"%"]}),C.jsxs("span",{children:["🛡 +",Math.round(r.defense*100),"%"]})]}):C.jsx("span",{className:"zpp__hero-stats zpp__hero-stats--standard",children:"Standard command vessel"})]}),C.jsxs("div",{className:"zpp__ship-bay",children:[C.jsx("span",{className:"zpp__ship-label",children:"Flagship"}),c]})]}),C.jsx("p",{className:"zpp__lore",children:I.lore})]})})]})]})};var A3={exports:{}};/*!
 * accounting.js v0.4.1
 * Copyright 2014 Open Exchange Rates
 *
 * Freely distributable under the MIT license.
 * Portions of accounting.js are inspired or borrowed from underscore.js
 *
 * Full details and documentation:
 * http://openexchangerates.github.io/accounting.js/
 */(function(e,A){(function(t,i){var n={};n.version="0.4.1",n.settings={currency:{symbol:"$",format:"%s%v",decimal:".",thousand:",",precision:2,grouping:3},number:{precision:0,grouping:3,thousand:",",decimal:"."}};var g=Array.prototype.map,o=Array.isArray,s=Object.prototype.toString;function a(m){return!!(m===""||m&&m.charCodeAt&&m.substr)}function r(m){return o?o(m):s.call(m)==="[object Array]"}function I(m){return m&&s.call(m)==="[object Object]"}function c(m,D){var S;m=m||{},D=D||{};for(S in D)D.hasOwnProperty(S)&&m[S]==null&&(m[S]=D[S]);return m}function l(m,D,S){var k=[],N,G;if(!m)return k;if(g&&m.map===g)return m.map(D,S);for(N=0,G=m.length;N<G;N++)k[N]=D.call(S,m[N],N,m);return k}function B(m,D){return m=Math.round(Math.abs(m)),isNaN(m)?D:m}function Q(m){var D=n.settings.currency.format;return typeof m=="function"&&(m=m()),a(m)&&m.match("%v")?{pos:m,neg:m.replace("-","").replace("%v","-%v"),zero:m}:!m||!m.pos||!m.pos.match("%v")?a(D)?n.settings.currency.format={pos:D,neg:D.replace("%v","-%v"),zero:D}:D:m}var h=n.unformat=n.parse=function(m,D){if(r(m))return l(m,function(N){return h(N,D)});if(m=m||0,typeof m=="number")return m;D=D||n.settings.number.decimal;var S=new RegExp("[^0-9-"+D+"]",["g"]),k=parseFloat((""+m).replace(/\((.*)\)/,"-$1").replace(S,"").replace(D,"."));return isNaN(k)?0:k},d=n.toFixed=function(m,D){D=B(D,n.settings.number.precision);var S=Math.pow(10,D);return(Math.round(n.unformat(m)*S)/S).toFixed(D)},p=n.formatNumber=n.format=function(m,D,S,k){if(r(m))return l(m,function(_){return p(_,D,S,k)});m=h(m);var N=c(I(D)?D:{precision:D,thousand:S,decimal:k},n.settings.number),G=B(N.precision),M=m<0?"-":"",w=parseInt(d(Math.abs(m||0),G),10)+"",b=w.length>3?w.length%3:0;return M+(b?w.substr(0,b)+N.thousand:"")+w.substr(b).replace(/(\d{3})(?=\d)/g,"$1"+N.thousand)+(G?N.decimal+d(Math.abs(m),G).split(".")[1]:"")},y=n.formatMoney=function(m,D,S,k,N,G){if(r(m))return l(m,function(_){return y(_,D,S,k,N,G)});m=h(m);var M=c(I(D)?D:{symbol:D,precision:S,thousand:k,decimal:N,format:G},n.settings.currency),w=Q(M.format),b=m>0?w.pos:m<0?w.neg:w.zero;return b.replace("%s",M.symbol).replace("%v",p(Math.abs(m),B(M.precision),M.thousand,M.decimal))};n.formatColumn=function(m,D,S,k,N,G){if(!m)return[];var M=c(I(D)?D:{symbol:D,precision:S,thousand:k,decimal:N,format:G},n.settings.currency),w=Q(M.format),b=w.pos.indexOf("%s")<w.pos.indexOf("%v"),_=0,K=l(m,function(J,q){if(r(J))return n.formatColumn(J,M);J=h(J);var v=J>0?w.pos:J<0?w.neg:w.zero,U=v.replace("%s",M.symbol).replace("%v",p(Math.abs(J),B(M.precision),M.thousand,M.decimal));return U.length>_&&(_=U.length),U});return l(K,function(J,q){return a(J)&&J.length<_?b?J.replace(M.symbol,M.symbol+new Array(_-J.length+1).join(" ")):new Array(_-J.length+1).join(" ")+J:J})},e.exports&&(A=e.exports=n),A.accounting=n})()})(A3,A3.exports);var dzA=A3.exports;const CB=nw(dzA),hzA=Object.assign({"../../assets/heroes/azure-sovereignty-t1.webp":M5,"../../assets/heroes/azure-sovereignty-t2.webp":N5,"../../assets/heroes/azure-sovereignty-t3.webp":R5,"../../assets/heroes/azure-sovereignty-t4.webp":G5,"../../assets/heroes/azure-sovereignty-t5.webp":b5,"../../assets/heroes/azure-sovereignty-t6.webp":U5,"../../assets/heroes/crimson-dominion-t1.webp":v5,"../../assets/heroes/crimson-dominion-t2.webp":K5,"../../assets/heroes/crimson-dominion-t3.webp":F5,"../../assets/heroes/crimson-dominion-t4.webp":_5,"../../assets/heroes/crimson-dominion-t5.webp":J5,"../../assets/heroes/crimson-dominion-t6.webp":L5,"../../assets/heroes/emerald-collective-t1.webp":x5,"../../assets/heroes/emerald-collective-t2.webp":T5,"../../assets/heroes/emerald-collective-t3.webp":q5,"../../assets/heroes/emerald-collective-t4.webp":Y5,"../../assets/heroes/emerald-collective-t5.webp":H5,"../../assets/heroes/emerald-collective-t6.webp":O5,"../../assets/heroes/golden-imperium-t1.webp":P5,"../../assets/heroes/golden-imperium-t2.webp":j5,"../../assets/heroes/golden-imperium-t3.webp":z5,"../../assets/heroes/golden-imperium-t4.webp":Z5,"../../assets/heroes/golden-imperium-t5.webp":W5,"../../assets/heroes/golden-imperium-t6.webp":V5,"../../assets/heroes/silver-pact-t1.webp":X5,"../../assets/heroes/silver-pact-t2.webp":$5,"../../assets/heroes/silver-pact-t3.webp":Az,"../../assets/heroes/silver-pact-t4.webp":ez,"../../assets/heroes/silver-pact-t5.webp":tz,"../../assets/heroes/silver-pact-t6.webp":iz,"../../assets/heroes/void-enclave-t1.webp":nz,"../../assets/heroes/void-enclave-t2.webp":gz,"../../assets/heroes/void-enclave-t3.webp":oz,"../../assets/heroes/void-enclave-t4.webp":sz,"../../assets/heroes/void-enclave-t5.webp":az,"../../assets/heroes/void-enclave-t6.webp":rz}),e3={};for(const[e,A]of Object.entries(hzA)){const t=e.split("/").pop().replace(".webp","");e3[t]=A.default}const pzA=["crimson-dominion","silver-pact","azure-sovereignty","golden-imperium","emerald-collective","void-enclave"],fzA={"crimson-dominion":"🐉","silver-pact":"🦅","azure-sovereignty":"🔱","golden-imperium":"👑","emerald-collective":"🌿","void-enclave":"👁️"},yzA={offense:"⚔ Offense",defense:"🛡 Defense",balanced:"⚖ Balanced"},DzA=({onClose:e})=>{const{roster:A,ownedIds:t,loading:i,buying:n,buy:g,HERO_TIER_STATS:o,getHeroModifiers:s}=Cz(),{user:a,updateBalance:r}=tn(),I=(a==null?void 0:a.balance)??0,[c,l]=E.useState("crimson-dominion"),[B,Q]=E.useState(null),[h,d]=E.useState(null),p=E.useMemo(()=>A.filter(m=>m.empire===c).sort((m,D)=>m.tier-D.tier),[A,c]);E.useEffect(()=>{const m=[...p].reverse().find(D=>t.has(D.id));d(m??p[0]??null)},[p,t]);const y=async m=>{Q(null);const D=await g(m.id);D.ok?(Q({heroId:m.id}),r(D.balance)):Q({heroId:m.id,error:D.error})};return C.jsxs("div",{className:"hero-shop",children:[C.jsx("div",{className:"hero-shop__backdrop",onClick:e}),C.jsxs("div",{className:"hero-shop__panel",children:[C.jsxs("div",{className:"hero-shop__header",children:[C.jsx("h2",{className:"hero-shop__title",children:"HERO COMMAND"}),C.jsxs("div",{className:"hero-shop__balance",children:["Balance: ",CB.formatMoney(I,"",0)]}),C.jsx("button",{className:"hero-shop__close",onClick:e,children:"✕"})]}),C.jsx("div",{className:"hero-shop__tabs",children:pzA.map(m=>{const D=gB[m],S=zu[m],k=m===c;return C.jsxs("button",{className:`hero-shop__tab${k?" hero-shop__tab--active":""}`,style:{"--tab-color":S},onClick:()=>{l(m),Q(null)},children:[C.jsx("span",{children:fzA[m]}),C.jsx("span",{className:"hero-shop__tab-name",children:D.name.replace("The ","")})]},m)})}),C.jsx("div",{className:"hero-shop__spec",children:yzA[fQA[c]]??"Balanced"}),C.jsx("div",{className:"hero-shop__grid",children:i?C.jsx("div",{className:"hero-shop__loading",children:"Loading heroes…"}):p.map(m=>{const D=t.has(m.id),S=(h==null?void 0:h.id)===m.id;return C.jsxs("div",{className:`hero-card${D?" hero-card--owned":""}${S?" hero-card--selected":""}`,style:{"--card-color":zu[m.empire]},onClick:()=>d(m),children:[e3[m.id]&&C.jsx("img",{src:e3[m.id],alt:m.name,className:"hero-card__img",loading:"lazy"}),D&&C.jsx("div",{className:"hero-card__owned-pip",children:"✓"})]},m.id)})}),h&&(()=>{const m=t.has(h.id),D=o[h.tier],S=s(h.empire,h.tier),k=I>=D.cost,N=(B==null?void 0:B.heroId)===h.id&&B.error,G=(B==null?void 0:B.heroId)===h.id&&!B.error;return C.jsxs("div",{className:"hero-detail",children:[C.jsxs("div",{className:"hero-detail__info",children:[C.jsxs("span",{className:"hero-detail__tier",children:["T",h.tier]}),C.jsx("span",{className:"hero-detail__name",children:h.name}),C.jsx("span",{className:"hero-detail__title",children:h.title}),C.jsx("p",{className:"hero-detail__desc",children:h.description}),C.jsxs("span",{className:"hero-detail__stats",children:[C.jsxs("span",{className:"hero-card__stat hero-card__stat--atk",children:["⚔ +",Math.round(S.attack*100),"%"]}),C.jsxs("span",{className:"hero-card__stat hero-card__stat--def",children:["🛡 +",Math.round(S.defense*100),"%"]})]})]}),m?C.jsx("div",{className:"hero-detail__owned",children:"OWNED"}):C.jsx("button",{className:"hero-card__buy-btn hero-detail__buy",disabled:n||!k,onClick:()=>y(h),children:n?"…":CB.formatMoney(D.cost,"",0)}),N&&C.jsx("span",{className:"hero-card__error",children:B.error==="INSUFFICIENT_CREDITS"?"Not enough credits":"Failed"}),G&&C.jsx("span",{className:"hero-card__success",children:"Recruited!"})]})})()]})]})};/*!
 * Font Awesome Free 7.1.0 by @fontawesome - https://fontawesome.com
 * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
 * Copyright 2025 Fonticons, Inc.
 */var mzA={prefix:"fab",iconName:"google",icon:[512,512,[],"f1a0","M500 261.8C500 403.3 403.1 504 260 504 122.8 504 12 393.2 12 256S122.8 8 260 8c66.8 0 123 24.5 166.3 64.9l-67.5 64.9c-88.3-85.2-252.5-21.2-252.5 118.2 0 86.5 69.1 156.6 153.7 156.6 98.2 0 135-70.4 140.8-106.9l-140.8 0 0-85.3 236.1 0c2.3 12.7 3.9 24.9 3.9 41.4z"]},SzA={prefix:"fab",iconName:"apple",icon:[384,512,[],"f179","M319.1 268.7c-.2-36.7 16.4-64.4 50-84.8-18.8-26.9-47.2-41.7-84.7-44.6-35.5-2.8-74.3 20.7-88.5 20.7-15 0-49.4-19.7-76.4-19.7-55.8 .9-115.1 44.5-115.1 133.2 0 26.2 4.8 53.3 14.4 81.2 12.8 36.7 59 126.7 107.2 125.2 25.2-.6 43-17.9 75.8-17.9 31.8 0 48.3 17.9 76.4 17.9 48.6-.7 90.4-82.5 102.6-119.3-65.2-30.7-61.7-90-61.7-91.9zM262.5 104.5c27.3-32.4 24.8-61.9 24-72.5-24.1 1.4-52 16.4-67.9 34.9-17.5 19.8-27.8 44.3-25.6 71.9 26.1 2 49.9-11.4 69.5-34.3z"]};const wzA=mzA,kzA=SzA,MzA=(()=>{try{const e=Ui.getPlatform();return e==="ios"||e==="android"}catch{return!1}})(),V$="single_player_guest_id";function X$(e){if(!e)return null;try{const[,A]=e.split(".");if(!A)return null;const t=A.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"="),n=JSON.parse(atob(i));return typeof(n==null?void 0:n.sub)=="string"&&n.sub?n.sub:null}catch{return null}}let Jb=null;function xf(){const{available:e,progress:A,applyNow:t,later:i}=i1A(),{membershipModalOpen:n,setMembershipModalOpen:g}=RR(),o=qi(),{roomsList:s,loading:a,createRoom:r,getGameRoute:I,refreshRooms:c}=D8(),{pokerCreateRoom:l,getUserBalance:B}=Mo(),{logout:Q,user:h,refreshUser:d}=tn(),{friends:p}=Kd(),{getTotalFriendUnread:y}=OR(),m=E.useMemo(()=>y(p.map(VA=>VA.id)),[y,p]),{refresh:D}=WBA();E.useEffect(()=>{D()},[D]);const[S,k]=E.useState(!1),[N,G]=E.useState(!1),[M,w]=E.useState(!1),[b,_]=E.useState(!1),[K,J]=E.useState(!1),[q,v]=E.useState(!1),U="zentara",x=(()=>{try{return(window==null?void 0:window.APP_TARGET)??""}catch{return""}})(),T=(U||x).toString().toLowerCase().trim(),z=T==="craps"?"craps":T==="poker"?"poker":T==="skills"?"skills":T==="zentara"?"zentara":T==="cee-lo"||T==="ceelo"?"cee-lo":null,[Z,eA]=E.useState(z??Jb??null),[aA,sA]=E.useState(!1),[pA,gA]=E.useState(!1),[yA,fA]=E.useState(!1),[RA,qA]=E.useState("wordsearch"),W=E.useRef(null),{info:$,error:L}=MB(),{clear:H}=Jr();E.useEffect(()=>{try{H()}catch{}},[H]),E.useEffect(()=>{z&&Z!==z&&eA(z)},[z,Z]),E.useEffect(()=>{(async()=>{try{const{Preferences:VA}=await Qi(async()=>{const{Preferences:vA}=await Promise.resolve().then(()=>Oc);return{Preferences:vA}},void 0),{value:nA}=await VA.get({key:"selectedSkillsGameMode"});(nA==="wordsearch"||nA==="anagrams"||nA==="trivia")&&qA(nA)}catch{}})()},[]),E.useEffect(()=>{if(!z){if(Jb){eA(Jb);return}(async()=>{try{const{Preferences:VA}=await Qi(async()=>{const{Preferences:vA}=await Promise.resolve().then(()=>Oc);return{Preferences:vA}},void 0),{value:nA}=await VA.get({key:"selectedGameMode"});eA(nA==="cee-lo"||nA==="craps"||nA==="poker"||nA==="skills"||nA==="zentara"?nA:"cee-lo")}catch{eA("cee-lo")}})()}},[z]),E.useEffect(()=>{z||Z&&(Jb=Z,(async()=>{try{const{Preferences:VA}=await Qi(async()=>{const{Preferences:nA}=await Promise.resolve().then(()=>Oc);return{Preferences:nA}},void 0);await VA.set({key:"selectedGameMode",value:Z})}catch{}})())},[Z,z]),E.useEffect(()=>{z!=="zentara"&&wL({volume:.0125})},[z]),E.useEffect(()=>{const VA=()=>{window.scrollTo(0,0),document.body.scrollTop=0,document.documentElement.scrollTop=0;const KA=document.getElementById("root");KA&&(KA.scrollTop=0)};VA();const nA=requestAnimationFrame(VA),vA=setTimeout(VA,50);return()=>{cancelAnimationFrame(nA),clearTimeout(vA)}},[]);const P=E.useMemo(()=>{const VA=z??Z;if(!VA)return s;const nA=vA=>vA.filter(KA=>(KA.gameMode||"cee-lo")===VA);return{public:nA(s.public),private:nA(s.private)}},[s,z,Z]),tA=E.useRef(null),iA=E.useCallback(()=>{ti("Light")},[]),oA=E.useCallback(()=>{try{Vl({volume:.5})}catch{}},[]),IA=E.useCallback(()=>{try{On()}catch{}},[]),CA=E.useCallback(VA=>{IA(),VA!==Z?(iA(),oA(),eA(VA)):(iA(),oA())},[Z,iA,oA,IA]),_A=E.useRef(null),uA=E.useRef(null),[X,O]=E.useState(1),[cA,wA]=E.useState(null),xA=E.useCallback(()=>{const VA=uA.current,nA=_A.current;if(!VA||!nA)return;const vA=VA.style.transform;VA.style.transform="none";const KA=VA.scrollHeight,WA=window.innerHeight;let bA=Math.min(1,WA/KA);O(bA),wA(KA*bA),VA.style.transform=vA},[]);E.useLayoutEffect(()=>{xA()},[xA,Z]),E.useEffect(()=>{const VA=new ResizeObserver(()=>requestAnimationFrame(xA)),nA=uA.current;nA&&VA.observe(nA),window.addEventListener("resize",xA);const vA=setTimeout(xA,250),KA=setTimeout(xA,800);return()=>{VA.disconnect(),window.removeEventListener("resize",xA),clearTimeout(vA),clearTimeout(KA)}},[xA]);const YA=E.useCallback(()=>{o("/profile")},[o]),jA=E.useCallback(()=>{o("/messages")},[o]);E.useCallback(()=>{o("/settings")},[o]);const ie=E.useCallback(()=>{o("/add-chips")},[o]),he=E.useCallback(()=>{o("/lobby")},[o]),le=E.useCallback(()=>{IA(),iA(),oA(),Q()},[Q,iA,oA,IA]),NA=async()=>{var VA;try{const nA=h&&typeof h.balance=="number"?Number(h.balance):null;if(nA!=null)return nA;try{await Promise.resolve(d())}catch{}const vA=h&&typeof h.balance=="number"?Number(h.balance):null;if(vA!=null)return vA}catch{}try{const nA=await(B==null?void 0:B());if(nA!=null&&nA.ok&&typeof((VA=nA.data)==null?void 0:VA.balance)=="number")return Number(nA.data.balance)}catch{}return null},EA=E.useCallback(async()=>{var VA,nA,vA;if(h!=null&&h.id)return!0;try{let KA=await uo().catch(()=>null);if(!KA){const bA=await obA();if(!(bA!=null&&bA.ok)||!bA.token)return $("Please sign in from home to start a game.",{duration:3e3}),!1;KA=bA.token,await ef(KA);const pe=((VA=bA==null?void 0:bA.user)==null?void 0:VA.id)||X$(KA);if(pe)try{(nA=window.sessionStorage)==null||nA.setItem(V$,pe)}catch{}}if(!KA)return $("Please sign in from home to start a game.",{duration:3e3}),!1;const WA=X$(KA);if(WA)try{(vA=window.sessionStorage)==null||vA.setItem(V$,WA)}catch{}try{const bA=hw();if(bA){if(!bA.connected&&bA.active)try{bA.disconnect()}catch{}bA.auth={token:KA},bA.__authSig=`t:${KA}`,bA.__allowCookieAuth=!1,Za(bA,"HomeScreen:guest-single-player")}}catch{}return!0}catch(KA){return console.warn("[single-player] guest session failed",KA),$("Please sign in from home to start a game.",{duration:3e3}),!1}},[$,h==null?void 0:h.id]),PA=E.useCallback(async()=>{IA(),iA(),oA(),console.log(h);try{if((h==null?void 0:h.isGuest)===!0){v(!0);return}}catch{}if(Z==="poker")try{const VA=await NA();if(VA!=null&&VA<1e3){sA(!0);return}}catch{}G(!0)},[IA,iA,oA,Z,h,d,g]),ZA=E.useCallback(async()=>{console.log("[HomeScreen] handleOpenRooms called"),IA(),iA(),oA();try{if((h==null?void 0:h.isGuest)===!0){console.log("[HomeScreen] Guest gate triggered"),v(!0);return}}catch{}if(Z==="poker")try{const VA=await NA();if(VA!=null&&VA<1e3){sA(!0);return}}catch{}console.log("[HomeScreen] Opening rooms modal"),c(),w(!0)},[IA,iA,oA,Z,h,d,g,c]),FA=E.useCallback(()=>{var nA;const VA=document.activeElement;(nA=VA==null?void 0:VA.blur)==null||nA.call(VA)},[]);E.useCallback(()=>{FA(),ZA()},[FA,ZA]),E.useCallback(()=>{FA(),PA()},[FA,PA]);const{meId:Ie}=tn(),DA=E.useCallback(async VA=>{var vA,KA,WA;const nA=!!(VA!=null&&VA.fromQuickMatch);if(IA(),!!Z&&!K){J(!0),gA(!0),iA(),oA(),W.current&&clearTimeout(W.current),W.current=window.setTimeout(()=>{gA(!1),$("Try again.",{duration:3e3})},15e3);try{let bA;const pe=await Xo(),xe=pe.botDifficultyLevel&&pe.botDifficultyLevel>=1&&pe.botDifficultyLevel<=9?pe.botDifficultyLevel:void 0;if((Z==="cee-lo"||Z==="craps"||Z==="poker")&&!await EA())return;switch(Z){case"poker":bA=await l({name:"Single Player Room",singlePlayer:!0,botLevel:xe});break;case"cee-lo":case"craps":bA=await r({singlePlayer:!0,name:"Single Player Room",gameMode:Z,botLevel:xe});break;case"skills":o(`/skills/play?mode=${RA}`);return;case"zentara":o(`/zentara/match/${crypto.randomUUID()}${nA?"?qm=1":""}`);return;default:bA=await r({singlePlayer:!0,name:"Single Player Room"});break}try{window.location.search.includes("e2e=1")&&(window.__handleCreateSingleRes=bA)}catch{}const it=(bA==null?void 0:bA.room)??((vA=bA==null?void 0:bA.roomsList)==null?void 0:vA.room)??((KA=bA==null?void 0:bA.data)==null?void 0:KA.room)??null,ve=(()=>{var Qe;try{return window.location.search.includes("e2e=1")||window.__E2E===!0||((Qe=window.sessionStorage)==null?void 0:Qe.getItem("e2e"))==="1"}catch{return!1}})(),re=(it==null?void 0:it.roomId)??(it==null?void 0:it.id)??(bA==null?void 0:bA.roomId)??((WA=bA==null?void 0:bA.data)==null?void 0:WA.roomId);if(re&&it){W.current&&(clearTimeout(W.current),W.current=null);try{window.__PRESEEDED_ROOM=it}catch{}const Qe=ve?"?e2e=1":"",HA=I(Z,re)+Qe;console.log(HA,"roomPath",Z),o(HA)}else if(bA!=null&&bA.error){const Qe=(()=>{var ge;try{return window.location.search.includes("e2e=1")||window.__E2E===!0||((ge=window.sessionStorage)==null?void 0:ge.getItem("e2e"))==="1"}catch{return!1}})(),HA=String(bA.error||"");if(!Qe&&/insufficient|minimum buy-in/i.test(HA)){sA(!0);return}}}catch(bA){console.warn(bA);const pe=(()=>{var xe;try{return window.location.search.includes("e2e=1")||window.__E2E===!0||((xe=window.sessionStorage)==null?void 0:xe.getItem("e2e"))==="1"}catch{return!1}})();if(pe){const xe=`e2e-${Math.random().toString(36).slice(2,8)}`;try{window.__handleCreateSingleRes={ok:!0,roomId:xe}}catch{}const it=pe?"&e2e=1":"";o(Z==="poker"?`/poker/room/${xe}?m=${Z}${it}`:`/room/${xe}?m=${Z}${it}`)}else{const xe=String((bA==null?void 0:bA.message)??bA??"");/insufficient|minimum buy-in/i.test(xe)?sA(!0):console.warn("[room:create] thrown",(bA==null?void 0:bA.message)??bA)}}finally{J(!1),gA(!1),W.current&&(clearTimeout(W.current),W.current=null)}}},[IA,r,iA,oA,o,K,Z,Ie,$,RA,l,I,EA]),rA=E.useCallback(VA=>()=>{IA(),iA(),oA(),VA()},[IA,iA,oA]);h==null||h.membershipTier;const BA=!!h,j=(()=>{try{return(h==null?void 0:h.isGuest)===!0}catch{return!1}})(),QA=E.useMemo(()=>{const VA=[{key:"chips",label:"Shop",onClick:rA(ie)}];return BA&&!j&&(VA.unshift({key:"profile",label:"Profile",onClick:rA(YA)}),VA.splice(1,0,{key:"messages",label:"Messages",onClick:rA(jA),badge:m}),VA.push({key:"logout",label:"Log Out",onClick:rA(le)})),VA},[rA,YA,jA,ie,le,BA,j,m]),[dA,UA]=E.useState(!1),[TA,oe]=E.useState(!1),me=E.useCallback(async VA=>{const nA=VA==="google"?UA:oe;nA(!0);try{try{await ZCA("");const vA=Ca();await fetch(`${vA}/api/auth/clear`,{method:"POST",credentials:"include"}).catch(()=>{})}catch{}if(MzA){const vA=VA==="apple"?await fm.signInWithAppleNative():await fm.signInWithGoogleNative(),KA=Ca(),WA=await fetch(`${KA}/api/auth/oauth/mobile-verify`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({provider:vA.provider,idToken:vA.idToken,email:vA.email,name:vA.name})});if(!WA.ok)throw new Error("Native verify failed");const bA=await WA.json();if(bA!=null&&bA.ok&&(bA!=null&&bA.token)){try{await ef(bA.token)}catch{}await d({force:!0})}else throw new Error("No token")}else await gbA(VA)}catch(vA){console.warn("[home-auth]",VA,(vA==null?void 0:vA.message)??vA),L("Sign-in failed. Please try again.")}finally{nA(!1)}},[d,L]),[be,$e]=E.useState(!1);E.useEffect(()=>{(z??Z)==="zentara"&&$e(S8A())},[z,Z]);const ci=E.useCallback(()=>{const VA=dQA();VA&&o(`/zentara/match/${VA.matchId}`)},[o]),ke=E.useCallback(VA=>{VA.stopPropagation(),IA(),iA(),oA(),_(nA=>!nA)},[IA,iA,oA]),nt=E.useCallback(()=>_(!1),[]),Ut=E.useCallback(()=>G(!1),[]),dt=E.useCallback(()=>w(!1),[]),Ht=E.useCallback(()=>g(!1),[g]),[Ft,Jt]=E.useState(!1),$A=E.useCallback(()=>{IA(),iA(),oA(),Jt(!0)},[IA,iA,oA]),He=E.useCallback(()=>Jt(!1),[]),[Xe,St]=E.useState(!1),kA=E.useCallback(()=>{IA(),iA(),oA(),St(!0)},[IA,iA,oA]),se=E.useCallback(()=>St(!1),[]),Ce=z==="zentara"?"theme-zentara":z==="skills"?"theme-skills":"theme-casino";return C.jsxs("div",{className:`HomeScreen ${Ce} home-fixed-root`,children:[C.jsx(tr,{className:"page-home-screen"}),C.jsx(g1A,{}),C.jsx(I1A,{}),C.jsxs("div",{className:"logout-container home-header-row",children:[C.jsxs("a",{id:"btn-how-to-play",className:"home-header-link",title:"How to Play","aria-label":"How to Play",onClick:$A,role:"button",children:[C.jsx("img",{src:C1A,alt:"How to Play",className:"home-header-icon"}),C.jsx("span",{className:"home-header-link-label",children:"Help"})]}),C.jsxs("button",{className:"home-header-leaderboard",onClick:kA,"aria-label":"View Leaderboards",type:"button",children:[C.jsx("span",{className:"home-header-leaderboard-icon","aria-hidden":!0,children:"🏆"}),C.jsx("span",{className:"home-header-leaderboard-label",children:"Leaderboards"})]}),h&&!j&&C.jsx(nEA,{gameMode:z==="zentara"?"zentara":z==="skills"?"skills":void 0,style:{padding:"6px 12px",fontSize:12},label:"Invite +1k"}),C.jsxs("button",{ref:tA,className:"settings-toggle",title:"Menu","aria-label":m>0?`Menu (${m} unread messages)`:"Menu","aria-haspopup":"menu","aria-expanded":b,onClick:ke,style:{width:38,height:38,borderRadius:"50%",background:h!=null&&h.avatarUrl?`url(${h.avatarUrl}) center/cover no-repeat`:"linear-gradient(135deg, #E6C166, #CDA34A)",border:"2px solid var(--gold, #d4af37)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:0,position:"relative"},children:[!(h!=null&&h.avatarUrl)&&C.jsx("span",{style:{fontSize:"20px",lineHeight:1},children:"👤"}),m>0&&C.jsx("span",{className:"settings-unread-badge","aria-label":`${m} unread`,children:m>99?"99+":m})]}),C.jsx(UvA,{anchorRef:tA,open:b,onClose:nt,items:QA})]}),C.jsx("div",{ref:_A,className:`home-fit-shell ${Ce}`,children:C.jsxs("div",{ref:uA,className:"home-fit-content",style:X<1?{transform:`scale(${X})`,transformOrigin:"top center"}:void 0,children:[z!=="zentara"&&C.jsx(NzA,{onPlay:()=>DA(),playDisabled:!Z||K}),!z&&C.jsx(t8A,{selectedMode:z??Z,onSelectMode:z?void 0:CA,interval:z?0:4e3}),z&&C.jsx(cQA,{width:240,height:240,tagline:""}),z==="skills"&&C.jsx("div",{className:"skills-mode-selector",children:[{value:"wordsearch",label:"🔤 WORDS"},{value:"anagrams",label:"🔀 ANAGRAMS"},{value:"trivia",label:"❓ TRIVIA"}].map(({value:VA,label:nA})=>C.jsx("button",{className:RA===VA?"active":"",onClick:async()=>{iA(),oA(),qA(VA);try{const{Preferences:vA}=await Qi(async()=>{const{Preferences:KA}=await Promise.resolve().then(()=>Oc);return{Preferences:KA}},void 0);await vA.set({key:"selectedSkillsGameMode",value:VA})}catch{}},children:nA},VA))}),C.jsxs("section",{className:"home-cta buttonRow","aria-label":"Actions",children:[(!BA||j)&&C.jsxs("div",{className:`promo-banner promo-banner--login-row ${z?`promo-banner--${z}`:""}`,role:"region","aria-label":"Login banner",children:[C.jsx("span",{className:"promo-banner__title",children:"Sign in to play online"}),C.jsxs("div",{className:"promo-banner__oauth-row",children:[C.jsxs("button",{className:"promo-oauth-btn promo-oauth-btn--google",onClick:()=>me("google"),disabled:dA||TA,"aria-label":"Continue with Google",children:[C.jsx(Cd,{icon:wzA}),C.jsx("span",{children:"Google"})]}),C.jsxs("button",{className:"promo-oauth-btn promo-oauth-btn--apple",onClick:()=>me("apple"),disabled:dA||TA,"aria-label":"Continue with Apple",children:[C.jsx(Cd,{icon:kzA}),C.jsx("span",{children:"Apple"})]})]})]}),C.jsx("div",{className:"cta-spotlight","aria-hidden":!0}),be&&(z??Z)==="zentara"&&C.jsx("button",{className:"btn gold-fill cta-btn primaryButton",onClick:ci,"aria-label":"Continue Game",children:"Continue Game"}),C.jsx("button",{id:"btn-single-player",className:`btn ${be&&(z??Z)==="zentara"?"gold-outline":"gold-fill"} cta-btn primaryButton`,onClick:()=>DA(),disabled:!Z||K,"aria-label":be&&(z??Z)==="zentara"?"New Game":"Single Player",children:be&&(z??Z)==="zentara"?"New Game":"Single Player"}),z==="zentara"?C.jsxs(C.Fragment,{children:[BA&&!j&&C.jsx(j$,{gameMode:z??Z,disabled:!Z||K,onFallbackToSinglePlayer:()=>DA({fromQuickMatch:!0})}),BA&&!j&&C.jsx("button",{className:"btn gold-outline cta-btn primaryButton CreateRoomButton",onClick:PA,disabled:!Z,"aria-label":"Create Room",children:"Create Room"}),C.jsx("button",{className:"btn gold-outline cta-btn primaryButton",onClick:()=>fA(!0),"aria-label":"Heroes",children:"🦸 Heroes"})]}):C.jsxs("div",{className:"cta-row-pair",children:[BA&&!j&&C.jsx(j$,{gameMode:z??Z,disabled:!Z||K,onFallbackToSinglePlayer:()=>DA({fromQuickMatch:!0})}),BA&&!j&&C.jsx("button",{className:"btn gold-outline cta-btn primaryButton CreateRoomButton",onClick:PA,disabled:!Z,"aria-label":"Create Room",children:"Create Room"})]})]})]})}),C.jsx(GvA,{open:N,onClose:Ut,gameMode:Z??"cee-lo"}),C.jsx(bvA,{open:M,onClose:dt,isPrivate:S,setIsPrivate:k,roomsList:P,onJoinClick:c,loading:a}),C.jsx(ZBA,{open:n,onClose:Ht,planId:h==null?void 0:h.membershipTier}),C.jsx(zYA,{open:Ft,onClose:He,defaultMode:z??void 0}),C.jsx(VYA,{open:Xe,onClose:se}),C.jsx(XYA,{open:q,onClose:()=>v(!1),onGoLogin:()=>he(),title:"Login Required",message:C.jsx(C.Fragment,{children:"Please log in to access Settings and Multiplayer."})}),C.jsx(n1A,{available:e,progress:A,applyNow:t,later:i}),yA&&C.jsx(DzA,{onClose:()=>fA(!1)}),C.jsx(Jp,{})]})}function NzA({onPlay:e,playDisabled:A}){const{data:t,claiming:i,claim:n,refresh:g}=jYA();if(E.useEffect(()=>{const B=setInterval(()=>void g(!0),3e4);return()=>clearInterval(B)},[g]),!t)return C.jsxs("button",{className:"daily-challenge-banner",onClick:e,disabled:A,type:"button","aria-label":"Daily Challenge",children:[C.jsx("span",{className:"daily-challenge-icon","aria-hidden":!0,children:"🎯"}),C.jsxs("span",{className:"daily-challenge-text",children:[C.jsx("span",{className:"daily-challenge-label",children:"Daily Challenge"}),C.jsx("span",{className:"daily-challenge-reward",children:"Play & earn bonus coins"})]}),C.jsx("span",{className:"daily-challenge-go","aria-hidden":!0,children:"▸"})]});const{description:o,target:s,progress:a,reward:r,completed:I,claimed:c}=t,l=async()=>{I&&!c&&!i?await n()&&g(!0):I||e()};return C.jsxs("button",{className:`daily-challenge-banner${c?" daily-challenge-banner--claimed":I?" daily-challenge-banner--ready":""}`,onClick:l,disabled:c||i||A&&!I,type:"button","aria-label":c?"Challenge completed":I?"Claim reward":o,children:[C.jsx("span",{className:"daily-challenge-icon","aria-hidden":!0,children:c?"✅":I?"🎉":"🎯"}),C.jsxs("span",{className:"daily-challenge-text",children:[C.jsx("span",{className:"daily-challenge-label",children:c?"Challenge Complete!":"Daily Challenge"}),C.jsx("span",{className:"daily-challenge-reward",children:c?"Come back tomorrow!":I?`Claim +${r.toLocaleString()} coins!`:C.jsxs(C.Fragment,{children:[o," — ",C.jsxs("strong",{children:["+",r.toLocaleString()]})," coins"]})})]}),!c&&C.jsx("span",{className:"daily-challenge-go","aria-hidden":!0,children:I?i?"…":"💰":`${a}/${s}`})]})}function Tf(){const{user:e,loading:A,initialized:t,refreshUser:i}=tn(),n=!!(e!=null&&e.email&&/@guest\.local$/i.test(e.email));return E.useEffect(()=>{!t&&!A&&i()},[t,A,i]),!t||A?C.jsx("div",{className:"app-loading",children:"Loading…"}):e&&!n?C.jsx(Tg,{to:"/lobby",replace:!0}):C.jsx(LCA,{})}var $$={};function RzA(e,A){return A.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(e)}var GzA=Object.defineProperty,bzA=(e,A,t)=>A in e?GzA(e,A,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[A]=t,AAA=(e,A,t)=>bzA(e,typeof A!="symbol"?A+"":A,t);let vr=class{constructor(){AAA(this,"_locking"),AAA(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let A;const t=new Promise(n=>A=()=>{this._locks-=1,n()}),i=this._locking.then(()=>A);return this._locking=this._locking.then(()=>t),i}};function xo(e,A){if(!e)throw new Error(A)}const UzA=34028234663852886e22,vzA=-34028234663852886e22,KzA=4294967295,FzA=2147483647,_zA=-2147483648;function lK(e){if(typeof e!="number")throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>FzA||e<_zA)throw new Error("invalid int 32: "+e)}function t3(e){if(typeof e!="number")throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>KzA||e<0)throw new Error("invalid uint 32: "+e)}function MQA(e){if(typeof e!="number")throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>UzA||e<vzA))throw new Error("invalid float 32: "+e)}const NQA=Symbol("@bufbuild/protobuf/enum-type");function JzA(e){const A=e[NQA];return xo(A,"missing enum type on enum object"),A}function RQA(e,A,t,i){e[NQA]=GQA(A,t.map(n=>({no:n.no,name:n.name,localName:e[n.no]})))}function GQA(e,A,t){const i=Object.create(null),n=Object.create(null),g=[];for(const o of A){const s=bQA(o);g.push(s),i[o.name]=s,n[o.no]=s}return{typeName:e,values:g,findName(o){return i[o]},findNumber(o){return n[o]}}}function LzA(e,A,t){const i={};for(const n of A){const g=bQA(n);i[g.localName]=g.no,i[g.no]=g.localName}return RQA(i,e,A),i}function bQA(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class dz{equals(A){return this.getType().runtime.util.equals(this.getType(),this,A)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(A,t){const i=this.getType(),n=i.runtime.bin,g=n.makeReadOptions(t);return n.readMessage(this,g.readerFactory(A),A.byteLength,g),this}fromJson(A,t){const i=this.getType(),n=i.runtime.json,g=n.makeReadOptions(t);return n.readMessage(i,A,g,this),this}fromJsonString(A,t){let i;try{i=JSON.parse(A)}catch(n){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(n instanceof Error?n.message:String(n)))}return this.fromJson(i,t)}toBinary(A){const t=this.getType(),i=t.runtime.bin,n=i.makeWriteOptions(A),g=n.writerFactory();return i.writeMessage(this,g,n),g.finish()}toJson(A){const t=this.getType(),i=t.runtime.json,n=i.makeWriteOptions(A);return i.writeMessage(this,n)}toJsonString(A){var t;const i=this.toJson(A);return JSON.stringify(i,null,(t=A==null?void 0:A.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function xzA(e,A,t,i){var n;const g=(n=i==null?void 0:i.localName)!==null&&n!==void 0?n:A.substring(A.lastIndexOf(".")+1),o={[g]:function(s){e.util.initFields(this),e.util.initPartial(s,this)}}[g];return Object.setPrototypeOf(o.prototype,new dz),Object.assign(o,{runtime:e,typeName:A,fields:e.util.newFieldList(t),fromBinary(s,a){return new o().fromBinary(s,a)},fromJson(s,a){return new o().fromJson(s,a)},fromJsonString(s,a){return new o().fromJsonString(s,a)},equals(s,a){return e.util.equals(o,s,a)}}),o}function TzA(){let e=0,A=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(n&127)<<i,!(n&128))return this.assertBounds(),[e,A]}let t=this.buf[this.pos++];if(e|=(t&15)<<28,A=(t&112)>>4,!(t&128))return this.assertBounds(),[e,A];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(A|=(n&127)<<i,!(n&128))return this.assertBounds(),[e,A]}throw new Error("invalid varint")}function H2(e,A,t){for(let g=0;g<28;g=g+7){const o=e>>>g,s=!(!(o>>>7)&&A==0),a=(s?o|128:o)&255;if(t.push(a),!s)return}const i=e>>>28&15|(A&7)<<4,n=!!(A>>3);if(t.push((n?i|128:i)&255),!!n){for(let g=3;g<31;g=g+7){const o=A>>>g,s=!!(o>>>7),a=(s?o|128:o)&255;if(t.push(a),!s)return}t.push(A>>>31&1)}}const BK=4294967296;function eAA(e){const A=e[0]==="-";A&&(e=e.slice(1));const t=1e6;let i=0,n=0;function g(o,s){const a=Number(e.slice(o,s));n*=t,i=i*t+a,i>=BK&&(n=n+(i/BK|0),i=i%BK)}return g(-24,-18),g(-18,-12),g(-12,-6),g(-6),A?vQA(i,n):hz(i,n)}function qzA(e,A){let t=hz(e,A);const i=t.hi&2147483648;i&&(t=vQA(t.lo,t.hi));const n=UQA(t.lo,t.hi);return i?"-"+n:n}function UQA(e,A){if({lo:e,hi:A}=YzA(e,A),A<=2097151)return String(BK*A+e);const t=e&16777215,i=(e>>>24|A<<8)&16777215,n=A>>16&65535;let g=t+i*6777216+n*6710656,o=i+n*8147497,s=n*2;const a=1e7;return g>=a&&(o+=Math.floor(g/a),g%=a),o>=a&&(s+=Math.floor(o/a),o%=a),s.toString()+tAA(o)+tAA(g)}function YzA(e,A){return{lo:e>>>0,hi:A>>>0}}function hz(e,A){return{lo:e|0,hi:A|0}}function vQA(e,A){return A=~A,e?e=~e+1:A+=1,hz(e,A)}const tAA=e=>{const A=String(e);return"0000000".slice(A.length)+A};function iAA(e,A){if(e>=0){for(;e>127;)A.push(e&127|128),e=e>>>7;A.push(e)}else{for(let t=0;t<9;t++)A.push(e&127|128),e=e>>7;A.push(1)}}function HzA(){let e=this.buf[this.pos++],A=e&127;if(!(e&128))return this.assertBounds(),A;if(e=this.buf[this.pos++],A|=(e&127)<<7,!(e&128))return this.assertBounds(),A;if(e=this.buf[this.pos++],A|=(e&127)<<14,!(e&128))return this.assertBounds(),A;if(e=this.buf[this.pos++],A|=(e&127)<<21,!(e&128))return this.assertBounds(),A;e=this.buf[this.pos++],A|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw new Error("invalid varint");return this.assertBounds(),A>>>0}function OzA(){const e=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof e.getBigInt64=="function"&&typeof e.getBigUint64=="function"&&typeof e.setBigInt64=="function"&&typeof e.setBigUint64=="function"&&(typeof process!="object"||typeof $$!="object"||$$.BUF_BIGINT_DISABLE!=="1")){const n=BigInt("-9223372036854775808"),g=BigInt("9223372036854775807"),o=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(a){const r=typeof a=="bigint"?a:BigInt(a);if(r>g||r<n)throw new Error("int64 invalid: ".concat(a));return r},uParse(a){const r=typeof a=="bigint"?a:BigInt(a);if(r>s||r<o)throw new Error("uint64 invalid: ".concat(a));return r},enc(a){return e.setBigInt64(0,this.parse(a),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(a){return e.setBigInt64(0,this.uParse(a),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(a,r){return e.setInt32(0,a,!0),e.setInt32(4,r,!0),e.getBigInt64(0,!0)},uDec(a,r){return e.setInt32(0,a,!0),e.setInt32(4,r,!0),e.getBigUint64(0,!0)}}}const t=n=>xo(/^-?[0-9]+$/.test(n),"int64 invalid: ".concat(n)),i=n=>xo(/^[0-9]+$/.test(n),"uint64 invalid: ".concat(n));return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),t(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),i(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),t(n),eAA(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),i(n),eAA(n)},dec(n,g){return qzA(n,g)},uDec(n,g){return UQA(n,g)}}}const Bo=OzA();var ut;(function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"})(ut||(ut={}));var cd;(function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"})(cd||(cd={}));function UQ(e,A,t){if(A===t)return!0;if(e==ut.BYTES){if(!(A instanceof Uint8Array)||!(t instanceof Uint8Array)||A.length!==t.length)return!1;for(let i=0;i<A.length;i++)if(A[i]!==t[i])return!1;return!0}switch(e){case ut.UINT64:case ut.FIXED64:case ut.INT64:case ut.SFIXED64:case ut.SINT64:return A==t}return!1}function RS(e,A){switch(e){case ut.BOOL:return!1;case ut.UINT64:case ut.FIXED64:case ut.INT64:case ut.SFIXED64:case ut.SINT64:return A==0?Bo.zero:"0";case ut.DOUBLE:case ut.FLOAT:return 0;case ut.BYTES:return new Uint8Array(0);case ut.STRING:return"";default:return 0}}function KQA(e,A){switch(e){case ut.BOOL:return A===!1;case ut.STRING:return A==="";case ut.BYTES:return A instanceof Uint8Array&&!A.byteLength;default:return A==0}}var Zo;(function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"})(Zo||(Zo={}));class PzA{constructor(A){this.stack=[],this.textEncoder=A??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let A=0;for(let n=0;n<this.chunks.length;n++)A+=this.chunks[n].length;let t=new Uint8Array(A),i=0;for(let n=0;n<this.chunks.length;n++)t.set(this.chunks[n],i),i+=this.chunks[n].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let A=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(A.byteLength),this.raw(A)}tag(A,t){return this.uint32((A<<3|t)>>>0)}raw(A){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(A),this}uint32(A){for(t3(A);A>127;)this.buf.push(A&127|128),A=A>>>7;return this.buf.push(A),this}int32(A){return lK(A),iAA(A,this.buf),this}bool(A){return this.buf.push(A?1:0),this}bytes(A){return this.uint32(A.byteLength),this.raw(A)}string(A){let t=this.textEncoder.encode(A);return this.uint32(t.byteLength),this.raw(t)}float(A){MQA(A);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,A,!0),this.raw(t)}double(A){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,A,!0),this.raw(t)}fixed32(A){t3(A);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,A,!0),this.raw(t)}sfixed32(A){lK(A);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,A,!0),this.raw(t)}sint32(A){return lK(A),A=(A<<1^A>>31)>>>0,iAA(A,this.buf),this}sfixed64(A){let t=new Uint8Array(8),i=new DataView(t.buffer),n=Bo.enc(A);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(A){let t=new Uint8Array(8),i=new DataView(t.buffer),n=Bo.uEnc(A);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(A){let t=Bo.enc(A);return H2(t.lo,t.hi,this.buf),this}sint64(A){let t=Bo.enc(A),i=t.hi>>31,n=t.lo<<1^i,g=(t.hi<<1|t.lo>>>31)^i;return H2(n,g,this.buf),this}uint64(A){let t=Bo.uEnc(A);return H2(t.lo,t.hi,this.buf),this}}class jzA{constructor(A,t){this.varint64=TzA,this.uint32=HzA,this.buf=A,this.len=A.length,this.pos=0,this.view=new DataView(A.buffer,A.byteOffset,A.byteLength),this.textDecoder=t??new TextDecoder}tag(){let A=this.uint32(),t=A>>>3,i=A&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(A,t){let i=this.pos;switch(A){case Zo.Varint:for(;this.buf[this.pos++]&128;);break;case Zo.Bit64:this.pos+=4;case Zo.Bit32:this.pos+=4;break;case Zo.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Zo.StartGroup:for(;;){const[g,o]=this.tag();if(o===Zo.EndGroup){if(t!==void 0&&g!==t)throw new Error("invalid end group tag");break}this.skip(o,g)}break;default:throw new Error("cant skip wire type "+A)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let A=this.uint32();return A>>>1^-(A&1)}int64(){return Bo.dec(...this.varint64())}uint64(){return Bo.uDec(...this.varint64())}sint64(){let[A,t]=this.varint64(),i=-(A&1);return A=(A>>>1|(t&1)<<31)^i,t=t>>>1^i,Bo.dec(A,t)}bool(){let[A,t]=this.varint64();return A!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Bo.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Bo.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let A=this.uint32(),t=this.pos;return this.pos+=A,this.assertBounds(),this.buf.subarray(t,t+A)}string(){return this.textDecoder.decode(this.bytes())}}function zzA(e,A,t,i){let n;return{typeName:A,extendee:t,get field(){if(!n){const g=typeof i=="function"?i():i;g.name=A.split(".").pop(),g.jsonName="[".concat(A,"]"),n=e.util.newFieldList([g]).list()[0]}return n},runtime:e}}function FQA(e){const A=e.field.localName,t=Object.create(null);return t[A]=ZzA(e),[t,()=>t[A]]}function ZzA(e){const A=e.field;if(A.repeated)return[];if(A.default!==void 0)return A.default;switch(A.kind){case"enum":return A.T.values[0].no;case"scalar":return RS(A.T,A.L);case"message":const t=A.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function WzA(e,A){if(!A.repeated&&(A.kind=="enum"||A.kind=="scalar")){for(let t=e.length-1;t>=0;--t)if(e[t].no==A.no)return[e[t]];return[]}return e.filter(t=>t.no===A.no)}let hE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),WL=[];for(let e=0;e<hE.length;e++)WL[hE[e].charCodeAt(0)]=e;WL[45]=hE.indexOf("+");WL[95]=hE.indexOf("/");const _QA={dec(e){let A=e.length*3/4;e[e.length-2]=="="?A-=2:e[e.length-1]=="="&&(A-=1);let t=new Uint8Array(A),i=0,n=0,g,o=0;for(let s=0;s<e.length;s++){if(g=WL[e.charCodeAt(s)],g===void 0)switch(e[s]){case"=":n=0;case`
`:case"\r":case"	":case" ":continue;default:throw Error("invalid base64 string.")}switch(n){case 0:o=g,n=1;break;case 1:t[i++]=o<<2|(g&48)>>4,o=g,n=2;break;case 2:t[i++]=(o&15)<<4|(g&60)>>2,o=g,n=3;break;case 3:t[i++]=(o&3)<<6|g,n=0;break}}if(n==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(e){let A="",t=0,i,n=0;for(let g=0;g<e.length;g++)switch(i=e[g],t){case 0:A+=hE[i>>2],n=(i&3)<<4,t=1;break;case 1:A+=hE[n|i>>4],n=(i&15)<<2,t=2;break;case 2:A+=hE[n|i>>6],A+=hE[i&63],t=0;break}return t&&(A+=hE[n],A+="=",t==1&&(A+="=")),A}};function VzA(e,A,t){LQA(A,e);const i=A.runtime.bin.makeReadOptions(t),n=WzA(e.getType().runtime.bin.listUnknownFields(e),A.field),[g,o]=FQA(A);for(const s of n)A.runtime.bin.readField(g,i.readerFactory(s.data),A.field,s.wireType,i);return o()}function XzA(e,A,t,i){LQA(A,e);const n=A.runtime.bin.makeReadOptions(i),g=A.runtime.bin.makeWriteOptions(i);if(JQA(e,A)){const r=e.getType().runtime.bin.listUnknownFields(e).filter(I=>I.no!=A.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(const I of r)e.getType().runtime.bin.onUnknownField(e,I.no,I.wireType,I.data)}const o=g.writerFactory();let s=A.field;!s.opt&&!s.repeated&&(s.kind=="enum"||s.kind=="scalar")&&(s=Object.assign(Object.assign({},A.field),{opt:!0})),A.runtime.bin.writeField(s,t,o,g);const a=n.readerFactory(o.finish());for(;a.pos<a.len;){const[r,I]=a.tag(),c=a.skip(I,r);e.getType().runtime.bin.onUnknownField(e,r,I,c)}}function JQA(e,A){const t=e.getType();return A.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(e).find(i=>i.no==A.field.no)}function LQA(e,A){xo(e.extendee.typeName==A.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function xQA(e,A){const t=e.localName;if(e.repeated)return A[t].length>0;if(e.oneof)return A[e.oneof.localName].case===t;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?A[t]!==void 0:e.kind=="enum"?A[t]!==e.T.values[0].no:!KQA(e.T,A[t]);case"message":return A[t]!==void 0;case"map":return Object.keys(A[t]).length>0}}function nAA(e,A){const t=e.localName,i=!e.opt&&!e.req;if(e.repeated)A[t]=[];else if(e.oneof)A[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":A[t]={};break;case"enum":A[t]=i?e.T.values[0].no:void 0;break;case"scalar":A[t]=i?RS(e.T,e.L):void 0;break;case"message":A[t]=void 0;break}}function pE(e,A){if(e===null||typeof e!="object"||!Object.getOwnPropertyNames(dz.prototype).every(i=>i in e&&typeof e[i]=="function"))return!1;const t=e.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:A===void 0?!0:t.typeName==A.typeName}function TQA(e,A){return pE(A)||!e.fieldWrapper?A:e.fieldWrapper.wrapField(A)}ut.DOUBLE,ut.FLOAT,ut.INT64,ut.UINT64,ut.INT32,ut.UINT32,ut.BOOL,ut.STRING,ut.BYTES;const gAA={ignoreUnknownFields:!1},oAA={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function $zA(e){return e?Object.assign(Object.assign({},gAA),e):gAA}function AZA(e){return e?Object.assign(Object.assign({},oAA),e):oAA}const A_=Symbol(),EK=Symbol();function eZA(){return{makeReadOptions:$zA,makeWriteOptions:AZA,readMessage(e,A,t,i){if(A==null||Array.isArray(A)||typeof A!="object")throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(Yl(A)));i=i??new e;const n=new Map,g=t.typeRegistry;for(const[o,s]of Object.entries(A)){const a=e.fields.findJsonName(o);if(a){if(a.oneof){if(s===null&&a.kind=="scalar")continue;const r=n.get(a.oneof);if(r!==void 0)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(a.oneof.name,'" present: "').concat(r,'", "').concat(o,'"'));n.set(a.oneof,o)}sAA(i,s,a,t,e)}else{let r=!1;if(g!=null&&g.findExtension&&o.startsWith("[")&&o.endsWith("]")){const I=g.findExtension(o.substring(1,o.length-1));if(I&&I.extendee.typeName==e.typeName){r=!0;const[c,l]=FQA(I);sAA(c,s,I.field,t,I),XzA(i,I,l(),t)}}if(!r&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(e,A){const t=e.getType(),i={};let n;try{for(n of t.fields.byNumber()){if(!xQA(n,e)){if(n.req)throw"required field not set";if(!A.emitDefaultValues||!iZA(n))continue}const o=n.oneof?e[n.oneof.localName].value:e[n.localName],s=aAA(n,o,A);s!==void 0&&(i[A.useProtoFieldName?n.name:n.jsonName]=s)}const g=A.typeRegistry;if(g!=null&&g.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(e)){const s=g.findExtensionFor(t.typeName,o.no);if(s&&JQA(e,s)){const a=VzA(e,s,A),r=aAA(s.field,a,A);r!==void 0&&(i[s.field.jsonName]=r)}}}catch(g){const o=n?"cannot encode field ".concat(t.typeName,".").concat(n.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),s=g instanceof Error?g.message:String(g);throw new Error(o+(s.length>0?": ".concat(s):""))}return i},readScalar(e,A,t){return rM(e,A,t??cd.BIGINT,!0)},writeScalar(e,A,t){if(A!==void 0&&(t||KQA(e,A)))return QK(e,A)},debug:Yl}}function Yl(e){if(e===null)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function sAA(e,A,t,i,n){let g=t.localName;if(t.repeated){if(xo(t.kind!="map"),A===null)return;if(!Array.isArray(A))throw new Error("cannot decode field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Yl(A)));const o=e[g];for(const s of A){if(s===null)throw new Error("cannot decode field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Yl(s)));switch(t.kind){case"message":o.push(t.T.fromJson(s,i));break;case"enum":const a=O2(t.T,s,i.ignoreUnknownFields,!0);a!==EK&&o.push(a);break;case"scalar":try{o.push(rM(t.T,s,t.L,!0))}catch(r){let I="cannot decode field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Yl(s));throw r instanceof Error&&r.message.length>0&&(I+=": ".concat(r.message)),new Error(I)}break}}}else if(t.kind=="map"){if(A===null)return;if(typeof A!="object"||Array.isArray(A))throw new Error("cannot decode field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Yl(A)));const o=e[g];for(const[s,a]of Object.entries(A)){if(a===null)throw new Error("cannot decode field ".concat(n.typeName,".").concat(t.name," from JSON: map value null"));let r;try{r=tZA(t.K,s)}catch(I){let c="cannot decode map key for field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Yl(A));throw I instanceof Error&&I.message.length>0&&(c+=": ".concat(I.message)),new Error(c)}switch(t.V.kind){case"message":o[r]=t.V.T.fromJson(a,i);break;case"enum":const I=O2(t.V.T,a,i.ignoreUnknownFields,!0);I!==EK&&(o[r]=I);break;case"scalar":try{o[r]=rM(t.V.T,a,cd.BIGINT,!0)}catch(c){let l="cannot decode map value for field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Yl(A));throw c instanceof Error&&c.message.length>0&&(l+=": ".concat(c.message)),new Error(l)}break}}}else switch(t.oneof&&(e=e[t.oneof.localName]={case:g},g="value"),t.kind){case"message":const o=t.T;if(A===null&&o.typeName!="google.protobuf.Value")return;let s=e[g];pE(s)?s.fromJson(A,i):(e[g]=s=o.fromJson(A,i),o.fieldWrapper&&!t.oneof&&(e[g]=o.fieldWrapper.unwrapField(s)));break;case"enum":const a=O2(t.T,A,i.ignoreUnknownFields,!1);switch(a){case A_:nAA(t,e);break;case EK:break;default:e[g]=a;break}break;case"scalar":try{const r=rM(t.T,A,t.L,!1);switch(r){case A_:nAA(t,e);break;default:e[g]=r;break}}catch(r){let I="cannot decode field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Yl(A));throw r instanceof Error&&r.message.length>0&&(I+=": ".concat(r.message)),new Error(I)}break}}function tZA(e,A){if(e===ut.BOOL)switch(A){case"true":A=!0;break;case"false":A=!1;break}return rM(e,A,cd.BIGINT,!0).toString()}function rM(e,A,t,i){if(A===null)return i?RS(e,t):A_;switch(e){case ut.DOUBLE:case ut.FLOAT:if(A==="NaN")return Number.NaN;if(A==="Infinity")return Number.POSITIVE_INFINITY;if(A==="-Infinity")return Number.NEGATIVE_INFINITY;if(A===""||typeof A=="string"&&A.trim().length!==A.length||typeof A!="string"&&typeof A!="number")break;const n=Number(A);if(Number.isNaN(n)||!Number.isFinite(n))break;return e==ut.FLOAT&&MQA(n),n;case ut.INT32:case ut.FIXED32:case ut.SFIXED32:case ut.SINT32:case ut.UINT32:let g;if(typeof A=="number"?g=A:typeof A=="string"&&A.length>0&&A.trim().length===A.length&&(g=Number(A)),g===void 0)break;return e==ut.UINT32||e==ut.FIXED32?t3(g):lK(g),g;case ut.INT64:case ut.SFIXED64:case ut.SINT64:if(typeof A!="number"&&typeof A!="string")break;const o=Bo.parse(A);return t?o.toString():o;case ut.FIXED64:case ut.UINT64:if(typeof A!="number"&&typeof A!="string")break;const s=Bo.uParse(A);return t?s.toString():s;case ut.BOOL:if(typeof A!="boolean")break;return A;case ut.STRING:if(typeof A!="string")break;try{encodeURIComponent(A)}catch{throw new Error("invalid UTF8")}return A;case ut.BYTES:if(A==="")return new Uint8Array(0);if(typeof A!="string")break;return _QA.dec(A)}throw new Error}function O2(e,A,t,i){if(A===null)return e.typeName=="google.protobuf.NullValue"?0:i?e.values[0].no:A_;switch(typeof A){case"number":if(Number.isInteger(A))return A;break;case"string":const n=e.findName(A);if(n!==void 0)return n.no;if(t)return EK;break}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Yl(A)))}function iZA(e){return e.repeated||e.kind=="map"?!0:!(e.oneof||e.kind=="message"||e.opt||e.req)}function aAA(e,A,t){if(e.kind=="map"){xo(typeof A=="object"&&A!=null);const i={},n=Object.entries(A);switch(e.V.kind){case"scalar":for(const[o,s]of n)i[o.toString()]=QK(e.V.T,s);break;case"message":for(const[o,s]of n)i[o.toString()]=s.toJson(t);break;case"enum":const g=e.V.T;for(const[o,s]of n)i[o.toString()]=P2(g,s,t.enumAsInteger);break}return t.emitDefaultValues||n.length>0?i:void 0}if(e.repeated){xo(Array.isArray(A));const i=[];switch(e.kind){case"scalar":for(let n=0;n<A.length;n++)i.push(QK(e.T,A[n]));break;case"enum":for(let n=0;n<A.length;n++)i.push(P2(e.T,A[n],t.enumAsInteger));break;case"message":for(let n=0;n<A.length;n++)i.push(A[n].toJson(t));break}return t.emitDefaultValues||i.length>0?i:void 0}switch(e.kind){case"scalar":return QK(e.T,A);case"enum":return P2(e.T,A,t.enumAsInteger);case"message":return TQA(e.T,A).toJson(t)}}function P2(e,A,t){var i;if(xo(typeof A=="number"),e.typeName=="google.protobuf.NullValue")return null;if(t)return A;const n=e.findNumber(A);return(i=n==null?void 0:n.name)!==null&&i!==void 0?i:A}function QK(e,A){switch(e){case ut.INT32:case ut.SFIXED32:case ut.SINT32:case ut.FIXED32:case ut.UINT32:return xo(typeof A=="number"),A;case ut.FLOAT:case ut.DOUBLE:return xo(typeof A=="number"),Number.isNaN(A)?"NaN":A===Number.POSITIVE_INFINITY?"Infinity":A===Number.NEGATIVE_INFINITY?"-Infinity":A;case ut.STRING:return xo(typeof A=="string"),A;case ut.BOOL:return xo(typeof A=="boolean"),A;case ut.UINT64:case ut.FIXED64:case ut.INT64:case ut.SFIXED64:case ut.SINT64:return xo(typeof A=="bigint"||typeof A=="string"||typeof A=="number"),A.toString();case ut.BYTES:return xo(A instanceof Uint8Array),_QA.enc(A)}}const jy=Symbol("@bufbuild/protobuf/unknown-fields"),rAA={readUnknownFields:!0,readerFactory:e=>new jzA(e)},IAA={writeUnknownFields:!0,writerFactory:()=>new PzA};function nZA(e){return e?Object.assign(Object.assign({},rAA),e):rAA}function gZA(e){return e?Object.assign(Object.assign({},IAA),e):IAA}function oZA(){return{makeReadOptions:nZA,makeWriteOptions:gZA,listUnknownFields(e){var A;return(A=e[jy])!==null&&A!==void 0?A:[]},discardUnknownFields(e){delete e[jy]},writeUnknownFields(e,A){const i=e[jy];if(i)for(const n of i)A.tag(n.no,n.wireType).raw(n.data)},onUnknownField(e,A,t,i){const n=e;Array.isArray(n[jy])||(n[jy]=[]),n[jy].push({no:A,wireType:t,data:i})},readMessage(e,A,t,i,n){const g=e.getType(),o=n?A.len:A.pos+t;let s,a;for(;A.pos<o&&([s,a]=A.tag(),!(n===!0&&a==Zo.EndGroup));){const r=g.fields.find(s);if(!r){const I=A.skip(a,s);i.readUnknownFields&&this.onUnknownField(e,s,a,I);continue}CAA(e,A,r,a,i)}if(n&&(a!=Zo.EndGroup||s!==t))throw new Error("invalid end group tag")},readField:CAA,writeMessage(e,A,t){const i=e.getType();for(const n of i.fields.byNumber()){if(!xQA(n,e)){if(n.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(n.name," to binary: required field not set"));continue}const g=n.oneof?e[n.oneof.localName].value:e[n.localName];cAA(n,g,A,t)}return t.writeUnknownFields&&this.writeUnknownFields(e,A),A},writeField(e,A,t,i){A!==void 0&&cAA(e,A,t,i)}}}function CAA(e,A,t,i,n){let{repeated:g,localName:o}=t;switch(t.oneof&&(e=e[t.oneof.localName],e.case!=o&&delete e.value,e.case=o,o="value"),t.kind){case"scalar":case"enum":const s=t.kind=="enum"?ut.INT32:t.T;let a=e_;if(t.kind=="scalar"&&t.L>0&&(a=aZA),g){let l=e[o];if(i==Zo.LengthDelimited&&s!=ut.STRING&&s!=ut.BYTES){let Q=A.uint32()+A.pos;for(;A.pos<Q;)l.push(a(A,s))}else l.push(a(A,s))}else e[o]=a(A,s);break;case"message":const r=t.T;g?e[o].push(uK(A,new r,n,t)):pE(e[o])?uK(A,e[o],n,t):(e[o]=uK(A,new r,n,t),r.fieldWrapper&&!t.oneof&&!t.repeated&&(e[o]=r.fieldWrapper.unwrapField(e[o])));break;case"map":let[I,c]=sZA(t,A,n);e[o][I]=c;break}}function uK(e,A,t,i){const n=A.getType().runtime.bin,g=i==null?void 0:i.delimited;return n.readMessage(A,e,g?i.no:e.uint32(),t,g),A}function sZA(e,A,t){const i=A.uint32(),n=A.pos+i;let g,o;for(;A.pos<n;){const[s]=A.tag();switch(s){case 1:g=e_(A,e.K);break;case 2:switch(e.V.kind){case"scalar":o=e_(A,e.V.T);break;case"enum":o=A.int32();break;case"message":o=uK(A,new e.V.T,t,void 0);break}break}}if(g===void 0&&(g=RS(e.K,cd.BIGINT)),typeof g!="string"&&typeof g!="number"&&(g=g.toString()),o===void 0)switch(e.V.kind){case"scalar":o=RS(e.V.T,cd.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T;break}return[g,o]}function aZA(e,A){const t=e_(e,A);return typeof t=="bigint"?t.toString():t}function e_(e,A){switch(A){case ut.STRING:return e.string();case ut.BOOL:return e.bool();case ut.DOUBLE:return e.double();case ut.FLOAT:return e.float();case ut.INT32:return e.int32();case ut.INT64:return e.int64();case ut.UINT64:return e.uint64();case ut.FIXED64:return e.fixed64();case ut.BYTES:return e.bytes();case ut.FIXED32:return e.fixed32();case ut.SFIXED32:return e.sfixed32();case ut.SFIXED64:return e.sfixed64();case ut.SINT64:return e.sint64();case ut.UINT32:return e.uint32();case ut.SINT32:return e.sint32()}}function cAA(e,A,t,i){xo(A!==void 0);const n=e.repeated;switch(e.kind){case"scalar":case"enum":let g=e.kind=="enum"?ut.INT32:e.T;if(n)if(xo(Array.isArray(A)),e.packed)IZA(t,g,e.no,A);else for(const o of A)IM(t,g,e.no,o);else IM(t,g,e.no,A);break;case"message":if(n){xo(Array.isArray(A));for(const o of A)lAA(t,i,e,o)}else lAA(t,i,e,A);break;case"map":xo(typeof A=="object"&&A!=null);for(const[o,s]of Object.entries(A))rZA(t,i,e,o,s);break}}function rZA(e,A,t,i,n){e.tag(t.no,Zo.LengthDelimited),e.fork();let g=i;switch(t.K){case ut.INT32:case ut.FIXED32:case ut.UINT32:case ut.SFIXED32:case ut.SINT32:g=Number.parseInt(i);break;case ut.BOOL:xo(i=="true"||i=="false"),g=i=="true";break}switch(IM(e,t.K,1,g),t.V.kind){case"scalar":IM(e,t.V.T,2,n);break;case"enum":IM(e,ut.INT32,2,n);break;case"message":xo(n!==void 0),e.tag(2,Zo.LengthDelimited).bytes(n.toBinary(A));break}e.join()}function lAA(e,A,t,i){const n=TQA(t.T,i);t.delimited?e.tag(t.no,Zo.StartGroup).raw(n.toBinary(A)).tag(t.no,Zo.EndGroup):e.tag(t.no,Zo.LengthDelimited).bytes(n.toBinary(A))}function IM(e,A,t,i){xo(i!==void 0);let[n,g]=qQA(A);e.tag(t,n)[g](i)}function IZA(e,A,t,i){if(!i.length)return;e.tag(t,Zo.LengthDelimited).fork();let[,n]=qQA(A);for(let g=0;g<i.length;g++)e[n](i[g]);e.join()}function qQA(e){let A=Zo.Varint;switch(e){case ut.BYTES:case ut.STRING:A=Zo.LengthDelimited;break;case ut.DOUBLE:case ut.FIXED64:case ut.SFIXED64:A=Zo.Bit64;break;case ut.FIXED32:case ut.SFIXED32:case ut.FLOAT:A=Zo.Bit32;break}const t=ut[e].toLowerCase();return[A,t]}function CZA(){return{setEnumType:RQA,initPartial(e,A){if(e===void 0)return;const t=A.getType();for(const i of t.fields.byMember()){const n=i.localName,g=A,o=e;if(o[n]!=null)switch(i.kind){case"oneof":const s=o[n].case;if(s===void 0)continue;const a=i.findField(s);let r=o[n].value;a&&a.kind=="message"&&!pE(r,a.T)?r=new a.T(r):a&&a.kind==="scalar"&&a.T===ut.BYTES&&(r=m0(r)),g[n]={case:s,value:r};break;case"scalar":case"enum":let I=o[n];i.T===ut.BYTES&&(I=i.repeated?I.map(m0):m0(I)),g[n]=I;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===ut.BYTES)for(const[B,Q]of Object.entries(o[n]))g[n][B]=m0(Q);else Object.assign(g[n],o[n]);break;case"message":const l=i.V.T;for(const B of Object.keys(o[n])){let Q=o[n][B];l.fieldWrapper||(Q=new l(Q)),g[n][B]=Q}break}break;case"message":const c=i.T;if(i.repeated)g[n]=o[n].map(l=>pE(l,c)?l:new c(l));else{const l=o[n];c.fieldWrapper?c.typeName==="google.protobuf.BytesValue"?g[n]=m0(l):g[n]=l:g[n]=pE(l,c)?l:new c(l)}break}}},equals(e,A,t){return A===t?!0:!A||!t?!1:e.fields.byMember().every(i=>{const n=A[i.localName],g=t[i.localName];if(i.repeated){if(n.length!==g.length)return!1;switch(i.kind){case"message":return n.every((o,s)=>i.T.equals(o,g[s]));case"scalar":return n.every((o,s)=>UQ(i.T,o,g[s]));case"enum":return n.every((o,s)=>UQ(ut.INT32,o,g[s]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let o=n,s=g;return i.T.fieldWrapper&&(o!==void 0&&!pE(o)&&(o=i.T.fieldWrapper.wrapField(o)),s!==void 0&&!pE(s)&&(s=i.T.fieldWrapper.wrapField(s))),i.T.equals(o,s);case"enum":return UQ(ut.INT32,n,g);case"scalar":return UQ(i.T,n,g);case"oneof":if(n.case!==g.case)return!1;const a=i.findField(n.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(n.value,g.value);case"enum":return UQ(ut.INT32,n.value,g.value);case"scalar":return UQ(a.T,n.value,g.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const r=Object.keys(n).concat(Object.keys(g));switch(i.V.kind){case"message":const I=i.V.T;return r.every(l=>I.equals(n[l],g[l]));case"enum":return r.every(l=>UQ(ut.INT32,n[l],g[l]));case"scalar":const c=i.V.T;return r.every(l=>UQ(c,n[l],g[l]))}break}})},clone(e){const A=e.getType(),t=new A,i=t;for(const n of A.fields.byMember()){const g=e[n.localName];let o;if(n.repeated)o=g.map(Lb);else if(n.kind=="map"){o=i[n.localName];for(const[s,a]of Object.entries(g))o[s]=Lb(a)}else n.kind=="oneof"?o=n.findField(g.case)?{case:g.case,value:Lb(g.value)}:{case:void 0}:o=Lb(g);i[n.localName]=o}for(const n of A.runtime.bin.listUnknownFields(e))A.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return t}}}function Lb(e){if(e===void 0)return e;if(pE(e))return e.clone();if(e instanceof Uint8Array){const A=new Uint8Array(e.byteLength);return A.set(e),A}return e}function m0(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function cZA(e,A,t){return{syntax:e,json:eZA(),bin:oZA(),util:Object.assign(Object.assign({},CZA()),{newFieldList:A,initFields:t}),makeMessageType(i,n,g){return xzA(this,i,n,g)},makeEnum:LzA,makeEnumType:GQA,getEnumType:JzA,makeExtension(i,n,g){return zzA(this,i,n,g)}}}class lZA{constructor(A,t){this._fields=A,this._normalizer=t}findJsonName(A){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[A]}find(A){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[A]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((A,t)=>A.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const A=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,A.push(t)):A.push(i)}return this.members}}function YQA(e,A){const t=HQA(e);return A?t:hZA(dZA(t))}function BZA(e){return YQA(e,!1)}const EZA=HQA;function HQA(e){let A=!1;const t=[];for(let i=0;i<e.length;i++){let n=e.charAt(i);switch(n){case"_":A=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(n),A=!1;break;default:A&&(A=!1,n=n.toUpperCase()),t.push(n);break}}return t.join("")}const QZA=new Set(["constructor","toString","toJSON","valueOf"]),uZA=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),OQA=e=>"".concat(e,"$"),dZA=e=>uZA.has(e)?OQA(e):e,hZA=e=>QZA.has(e)?OQA(e):e;class pZA{constructor(A){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=A,this.localName=BZA(A)}addField(A){xo(A.oneof===this,"field ".concat(A.name," not one of ").concat(this.name)),this.fields.push(A)}findField(A){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[A]}}function fZA(e,A){var t,i,n,g,o,s;const a=[];let r;for(const I of typeof e=="function"?e():e){const c=I;if(c.localName=YQA(I.name,I.oneof!==void 0),c.jsonName=(t=I.jsonName)!==null&&t!==void 0?t:EZA(I.name),c.repeated=(i=I.repeated)!==null&&i!==void 0?i:!1,I.kind=="scalar"&&(c.L=(n=I.L)!==null&&n!==void 0?n:cd.BIGINT),c.delimited=(g=I.delimited)!==null&&g!==void 0?g:!1,c.req=(o=I.req)!==null&&o!==void 0?o:!1,c.opt=(s=I.opt)!==null&&s!==void 0?s:!1,I.packed===void 0&&(c.packed=I.kind=="enum"||I.kind=="scalar"&&I.T!=ut.BYTES&&I.T!=ut.STRING),I.oneof!==void 0){const l=typeof I.oneof=="string"?I.oneof:I.oneof.name;(!r||r.name!=l)&&(r=new pZA(l)),c.oneof=r,r.addField(c)}a.push(c)}return a}const Ge=cZA("proto3",e=>new lZA(e,A=>fZA(A)),e=>{for(const A of e.getType().fields.byMember()){if(A.opt)continue;const t=A.localName,i=e;if(A.repeated){i[t]=[];continue}switch(A.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=RS(A.T,A.L);break}}});class Xr extends dz{constructor(A){super(),this.seconds=Bo.zero,this.nanos=0,Ge.util.initPartial(A,this)}fromJson(A,t){if(typeof A!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Ge.json.debug(A)));const i=A.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=Bo.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(A){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const n=(this.nanos+1e9).toString().substring(1);n.substring(3)==="000000"?i="."+n.substring(0,3)+"Z":n.substring(6)==="000"?i="."+n.substring(0,6)+"Z":i="."+n+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Xr.fromDate(new Date)}static fromDate(A){const t=A.getTime();return new Xr({seconds:Bo.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(A,t){return new Xr().fromBinary(A,t)}static fromJson(A,t){return new Xr().fromJson(A,t)}static fromJsonString(A,t){return new Xr().fromJsonString(A,t)}static equals(A,t){return Ge.util.equals(Xr,A,t)}}Xr.runtime=Ge;Xr.typeName="google.protobuf.Timestamp";Xr.fields=Ge.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const yZA=Ge.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Xr},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:DZA,repeated:!0},{no:5,name:"events",kind:"message",T:SZA,repeated:!0}]),DZA=Ge.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:mZA,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),mZA=Ge.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Xr},{no:3,name:"value",kind:"scalar",T:2}]),SZA=Ge.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Xr},{no:7,name:"normalized_end_timestamp",kind:"message",T:Xr,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),PQA=Ge.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),qc=Ge.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Es=Ge.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),pz=Ge.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),hk=Ge.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),cN=Ge.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),jc=Ge.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),Ph=Ge.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),wZA=Ge.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ia=Ge.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),VL=Ge.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:t_,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:guA}]),t_=Ge.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),kZA=Ge.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:Ge.getEnumType(Es),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),If=Ge.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Ge.getEnumType(vm)},{no:4,name:"tracks",kind:"message",T:XD,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:kZA},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Ge.getEnumType(lN)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Ge.getEnumType(jc)},{no:18,name:"kind_details",kind:"enum",T:Ge.getEnumType(MZA),repeated:!0}]),vm=Ge.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),lN=Ge.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"}]),MZA=Ge.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Js=Ge.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),NZA=Ge.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Zu,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Ge.getEnumType(jQA)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),XD=Ge.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Ge.getEnumType(qc)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:Ge.getEnumType(Es)},{no:10,name:"layers",kind:"message",T:Zu,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:NZA,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:Ge.getEnumType(Js)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:guA},{no:19,name:"audio_features",kind:"enum",T:Ge.getEnumType(ia),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Ge.getEnumType(PQA)}]),Zu=Ge.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:Ge.getEnumType(pz)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),jQA=Ge.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),Dr=Ge.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:Ge.getEnumType(Mn)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:fz,oneof:"value"},{no:3,name:"speaker",kind:"message",T:RZA,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:VQA,oneof:"value"},{no:7,name:"transcription",kind:"message",T:GZA,oneof:"value"},{no:8,name:"metrics",kind:"message",T:yZA,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:i_,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:yz,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Dz,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:mz,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:n_,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:g_,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:o_,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:zQA,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Mn=Ge.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),zQA=Ge.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:Ge.getEnumType(Js)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),ZQA=Ge.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:fz,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:i_,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:yz,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Dz,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:mz,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:n_,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:g_,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:o_,oneof:"value"}]),RZA=Ge.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:WQA,repeated:!0}]),WQA=Ge.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),fz=Ge.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),VQA=Ge.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),GZA=Ge.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:bZA,repeated:!0}]),bZA=Ge.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),i_=Ge.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),yz=Ge.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),Dz=Ge.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),mz=Ge.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:XQA,oneof:"value"}]),XQA=Ge.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),$QA=Ge.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),AuA=Ge.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:Ge.getEnumType(euA)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),euA=Ge.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),tuA=Ge.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:Ge.getEnumType(iuA)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),iuA=Ge.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),nuA=Ge.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:BAA},{no:2,name:"screen",kind:"message",T:BAA},{no:3,name:"resume_connection",kind:"enum",T:Ge.getEnumType(cN)},{no:4,name:"disabled_codecs",kind:"message",T:UZA},{no:5,name:"force_relay",kind:"enum",T:Ge.getEnumType(cN)}]),BAA=Ge.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Ge.getEnumType(cN)}]),UZA=Ge.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:t_,repeated:!0},{no:2,name:"publish",kind:"message",T:t_,repeated:!0}]),guA=Ge.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),i3=Ge.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),ouA=Ge.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:Ge.getEnumType(i3)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),suA=Ge.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),n_=Ge.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:Ge.getEnumType(Js)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:ouA,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:suA,oneof:"content_header"}],{localName:"DataStream_Header"}),g_=Ge.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),o_=Ge.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),vZA=Ge.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),Yc=Ge.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),n3=Ge.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),KZA=Ge.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),FZA=Ge.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:ld,oneof:"message"},{no:2,name:"answer",kind:"message",T:ld,oneof:"message"},{no:3,name:"trickle",kind:"message",T:XL,oneof:"message"},{no:4,name:"add_track",kind:"message",T:BN,oneof:"message"},{no:5,name:"mute",kind:"message",T:$L,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Ax,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:auA,oneof:"message"},{no:8,name:"leave",kind:"message",T:ex,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:IuA,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:luA,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Nz,oneof:"message"},{no:13,name:"simulate",kind:"message",T:_l,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:kz,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:QuA,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:wz,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:ruA,oneof:"message"}]),EAA=Ge.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:_ZA,oneof:"message"},{no:2,name:"answer",kind:"message",T:ld,oneof:"message"},{no:3,name:"offer",kind:"message",T:ld,oneof:"message"},{no:4,name:"trickle",kind:"message",T:XL,oneof:"message"},{no:5,name:"update",kind:"message",T:xZA,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Sz,oneof:"message"},{no:8,name:"leave",kind:"message",T:ex,oneof:"message"},{no:9,name:"mute",kind:"message",T:$L,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:TZA,oneof:"message"},{no:11,name:"room_update",kind:"message",T:qZA,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:HZA,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:PZA,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:zZA,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:WZA,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:LZA,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:JZA,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:XZA,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:eWA,oneof:"message"},{no:22,name:"request_response",kind:"message",T:tWA,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:iWA,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:VZA,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:sWA,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:ZZA,oneof:"message"}]),g3=Ge.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Zu,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Ge.getEnumType(jQA)}]),BN=Ge.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:Ge.getEnumType(qc)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:Ge.getEnumType(Es)},{no:9,name:"layers",kind:"message",T:Zu,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:g3,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:Ge.getEnumType(Js)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Ge.getEnumType(PQA)},{no:17,name:"audio_features",kind:"enum",T:Ge.getEnumType(ia),repeated:!0}]),XL=Ge.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Ge.getEnumType(Yc)},{no:3,name:"final",kind:"scalar",T:8}]),$L=Ge.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),_ZA=Ge.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:VL},{no:2,name:"participant",kind:"message",T:If},{no:3,name:"other_participants",kind:"message",T:If,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:CuA,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:nuA},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:AuA},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:t_,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),JZA=Ge.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:CuA,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:nuA},{no:3,name:"server_info",kind:"message",T:AuA},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Sz=Ge.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:XD}]),LZA=Ge.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ld=Ge.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),xZA=Ge.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:If,repeated:!0}]),Ax=Ge.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:$QA,repeated:!0}]),auA=Ge.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:Ge.getEnumType(pz)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),wz=Ge.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Ge.getEnumType(ia),repeated:!0}]),ruA=Ge.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),ex=Ge.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Ge.getEnumType(jc)},{no:3,name:"action",kind:"enum",T:Ge.getEnumType(Km)},{no:4,name:"regions",kind:"message",T:$ZA}]),Km=Ge.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),IuA=Ge.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Zu,repeated:!0}]),kz=Ge.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),CuA=Ge.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),TZA=Ge.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:WQA,repeated:!0}]),qZA=Ge.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:VL}]),YZA=Ge.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Ge.getEnumType(hk)},{no:3,name:"score",kind:"scalar",T:2}]),HZA=Ge.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:YZA,repeated:!0}]),OZA=Ge.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Ge.getEnumType(n3)}]),PZA=Ge.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:OZA,repeated:!0}]),Mz=Ge.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:Ge.getEnumType(pz)},{no:2,name:"enabled",kind:"scalar",T:8}]),jZA=Ge.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Mz,repeated:!0}]),zZA=Ge.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Mz,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:jZA,repeated:!0}]),ZZA=Ge.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:vZA,repeated:!0}]),cuA=Ge.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),luA=Ge.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:cuA,repeated:!0}]),WZA=Ge.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),VZA=Ge.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:VL},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:If},{no:4,name:"other_participants",kind:"message",T:If,repeated:!0}]),Nz=Ge.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:ld},{no:2,name:"subscription",kind:"message",T:Ax},{no:3,name:"publish_tracks",kind:"message",T:Sz,repeated:!0},{no:4,name:"data_channels",kind:"message",T:EuA,repeated:!0},{no:5,name:"offer",kind:"message",T:ld},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:BuA,repeated:!0}]),BuA=Ge.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),EuA=Ge.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:Ge.getEnumType(Yc)}]),_l=Ge.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:Ge.getEnumType(KZA),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),QuA=Ge.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),XZA=Ge.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),$ZA=Ge.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:AWA,repeated:!0}]),AWA=Ge.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),eWA=Ge.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Ge.getEnumType(wZA)}]),tWA=Ge.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Ge.getEnumType(Rz)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:XL,oneof:"request"},{no:5,name:"add_track",kind:"message",T:BN,oneof:"request"},{no:6,name:"mute",kind:"message",T:$L,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:kz,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:wz,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:ruA,oneof:"request"}]),Rz=Ge.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"}]),iWA=Ge.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),uuA=Ge.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8}]),nWA=Ge.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:tuA},{no:2,name:"connection_settings",kind:"message",T:uuA},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:BN,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:ld},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:Ge.getEnumType(Ph)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Nz}]),gWA=Ge.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:Ge.getEnumType(oWA)},{no:2,name:"join_request",kind:"scalar",T:12}]),oWA=Ge.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),sWA=Ge.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function aWA(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dK={exports:{}},rWA=dK.exports,QAA;function IWA(){return QAA||(QAA=1,function(e){(function(A,t){e.exports?e.exports=t():A.log=t()})(rWA,function(){var A=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],g={},o=null;function s(h,d){var p=h[d];if(typeof p.bind=="function")return p.bind(h);try{return Function.prototype.bind.call(p,h)}catch{return function(){return Function.prototype.apply.apply(p,[h,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function r(h){return h==="debug"&&(h="log"),typeof console===t?!1:h==="trace"&&i?a:console[h]!==void 0?s(console,h):console.log!==void 0?s(console,"log"):A}function I(){for(var h=this.getLevel(),d=0;d<n.length;d++){var p=n[d];this[p]=d<h?A:this.methodFactory(p,h,this.name)}if(this.log=this.debug,typeof console===t&&h<this.levels.SILENT)return"No console available for logging"}function c(h){return function(){typeof console!==t&&(I.call(this),this[h].apply(this,arguments))}}function l(h,d,p){return r(h)||c.apply(this,arguments)}function B(h,d){var p=this,y,m,D,S="loglevel";typeof h=="string"?S+=":"+h:typeof h=="symbol"&&(S=void 0);function k(b){var _=(n[b]||"silent").toUpperCase();if(!(typeof window===t||!S)){try{window.localStorage[S]=_;return}catch{}try{window.document.cookie=encodeURIComponent(S)+"="+_+";"}catch{}}}function N(){var b;if(!(typeof window===t||!S)){try{b=window.localStorage[S]}catch{}if(typeof b===t)try{var _=window.document.cookie,K=encodeURIComponent(S),J=_.indexOf(K+"=");J!==-1&&(b=/^([^;]+)/.exec(_.slice(J+K.length+1))[1])}catch{}return p.levels[b]===void 0&&(b=void 0),b}}function G(){if(!(typeof window===t||!S)){try{window.localStorage.removeItem(S)}catch{}try{window.document.cookie=encodeURIComponent(S)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function M(b){var _=b;if(typeof _=="string"&&p.levels[_.toUpperCase()]!==void 0&&(_=p.levels[_.toUpperCase()]),typeof _=="number"&&_>=0&&_<=p.levels.SILENT)return _;throw new TypeError("log.setLevel() called with invalid level: "+b)}p.name=h,p.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},p.methodFactory=d||l,p.getLevel=function(){return D??m??y},p.setLevel=function(b,_){return D=M(b),_!==!1&&k(D),I.call(p)},p.setDefaultLevel=function(b){m=M(b),N()||p.setLevel(b,!1)},p.resetLevel=function(){D=null,G(),I.call(p)},p.enableAll=function(b){p.setLevel(p.levels.TRACE,b)},p.disableAll=function(b){p.setLevel(p.levels.SILENT,b)},p.rebuild=function(){if(o!==p&&(y=M(o.getLevel())),I.call(p),o===p)for(var b in g)g[b].rebuild()},y=M(o?o.getLevel():"WARN");var w=N();w!=null&&(D=M(w)),I.call(p)}o=new B,o.getLogger=function(d){if(typeof d!="symbol"&&typeof d!="string"||d==="")throw new TypeError("You must supply a name when creating a logger.");var p=g[d];return p||(p=g[d]=new B(d,o.methodFactory)),p};var Q=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=Q),o},o.getLoggers=function(){return g},o.default=o,o})}(dK)),dK.exports}var tx=IWA(),o3;(function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"})(o3||(o3={}));var el;(function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"})(el||(el={}));let ln=tx.getLogger("livekit");Object.values(el).map(e=>tx.getLogger(e));ln.setDefaultLevel(o3.info);function eQ(e){const A=tx.getLogger(e);return A.setDefaultLevel(ln.getLevel()),A}const CWA=tx.getLogger("lk-e2ee"),S0=7e3,cWA=[0,300,2*2*300,3*3*300,4*4*300,S0,S0,S0,S0,S0];class lWA{constructor(A){this._retryDelays=A!==void 0?[...A]:cWA}nextRetryDelayInMs(A){if(A.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[A.retryCount];return A.retryCount<=1?t:t+Math.random()*1e3}}function BWA(e,A){var t={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&A.indexOf(i)<0&&(t[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(e);n<i.length;n++)A.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(t[i[n]]=e[i[n]]);return t}function zA(e,A,t,i){function n(g){return g instanceof t?g:new t(function(o){o(g)})}return new(t||(t=Promise))(function(g,o){function s(I){try{r(i.next(I))}catch(c){o(c)}}function a(I){try{r(i.throw(I))}catch(c){o(c)}}function r(I){I.done?g(I.value):n(I.value).then(s,a)}r((i=i.apply(e,A||[])).next())})}function uAA(e){var A=typeof Symbol=="function"&&Symbol.iterator,t=A&&e[A],i=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")}function fE(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var A=e[Symbol.asyncIterator],t;return A?A.call(e):(e=typeof uAA=="function"?uAA(e):e[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(g){t[g]=e[g]&&function(o){return new Promise(function(s,a){o=e[g](o),n(s,a,o.done,o.value)})}}function n(g,o,s,a){Promise.resolve(a).then(function(r){g({value:r,done:s})},o)}}var xb={exports:{}},dAA;function EWA(){if(dAA)return xb.exports;dAA=1;var e=typeof Reflect=="object"?Reflect:null,A=e&&typeof e.apply=="function"?e.apply:function(S,k,N){return Function.prototype.apply.call(S,k,N)},t;e&&typeof e.ownKeys=="function"?t=e.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function i(D){console&&console.warn&&console.warn(D)}var n=Number.isNaN||function(S){return S!==S};function g(){g.init.call(this)}xb.exports=g,xb.exports.once=p,g.EventEmitter=g,g.prototype._events=void 0,g.prototype._eventsCount=0,g.prototype._maxListeners=void 0;var o=10;function s(D){if(typeof D!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof D)}Object.defineProperty(g,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(D){if(typeof D!="number"||D<0||n(D))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+D+".");o=D}}),g.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},g.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||n(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function a(D){return D._maxListeners===void 0?g.defaultMaxListeners:D._maxListeners}g.prototype.getMaxListeners=function(){return a(this)},g.prototype.emit=function(S){for(var k=[],N=1;N<arguments.length;N++)k.push(arguments[N]);var G=S==="error",M=this._events;if(M!==void 0)G=G&&M.error===void 0;else if(!G)return!1;if(G){var w;if(k.length>0&&(w=k[0]),w instanceof Error)throw w;var b=new Error("Unhandled error."+(w?" ("+w.message+")":""));throw b.context=w,b}var _=M[S];if(_===void 0)return!1;if(typeof _=="function")A(_,this,k);else for(var K=_.length,J=Q(_,K),N=0;N<K;++N)A(J[N],this,k);return!0};function r(D,S,k,N){var G,M,w;if(s(k),M=D._events,M===void 0?(M=D._events=Object.create(null),D._eventsCount=0):(M.newListener!==void 0&&(D.emit("newListener",S,k.listener?k.listener:k),M=D._events),w=M[S]),w===void 0)w=M[S]=k,++D._eventsCount;else if(typeof w=="function"?w=M[S]=N?[k,w]:[w,k]:N?w.unshift(k):w.push(k),G=a(D),G>0&&w.length>G&&!w.warned){w.warned=!0;var b=new Error("Possible EventEmitter memory leak detected. "+w.length+" "+String(S)+" listeners added. Use emitter.setMaxListeners() to increase limit");b.name="MaxListenersExceededWarning",b.emitter=D,b.type=S,b.count=w.length,i(b)}return D}g.prototype.addListener=function(S,k){return r(this,S,k,!1)},g.prototype.on=g.prototype.addListener,g.prototype.prependListener=function(S,k){return r(this,S,k,!0)};function I(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function c(D,S,k){var N={fired:!1,wrapFn:void 0,target:D,type:S,listener:k},G=I.bind(N);return G.listener=k,N.wrapFn=G,G}g.prototype.once=function(S,k){return s(k),this.on(S,c(this,S,k)),this},g.prototype.prependOnceListener=function(S,k){return s(k),this.prependListener(S,c(this,S,k)),this},g.prototype.removeListener=function(S,k){var N,G,M,w,b;if(s(k),G=this._events,G===void 0)return this;if(N=G[S],N===void 0)return this;if(N===k||N.listener===k)--this._eventsCount===0?this._events=Object.create(null):(delete G[S],G.removeListener&&this.emit("removeListener",S,N.listener||k));else if(typeof N!="function"){for(M=-1,w=N.length-1;w>=0;w--)if(N[w]===k||N[w].listener===k){b=N[w].listener,M=w;break}if(M<0)return this;M===0?N.shift():h(N,M),N.length===1&&(G[S]=N[0]),G.removeListener!==void 0&&this.emit("removeListener",S,b||k)}return this},g.prototype.off=g.prototype.removeListener,g.prototype.removeAllListeners=function(S){var k,N,G;if(N=this._events,N===void 0)return this;if(N.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):N[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete N[S]),this;if(arguments.length===0){var M=Object.keys(N),w;for(G=0;G<M.length;++G)w=M[G],w!=="removeListener"&&this.removeAllListeners(w);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(k=N[S],typeof k=="function")this.removeListener(S,k);else if(k!==void 0)for(G=k.length-1;G>=0;G--)this.removeListener(S,k[G]);return this};function l(D,S,k){var N=D._events;if(N===void 0)return[];var G=N[S];return G===void 0?[]:typeof G=="function"?k?[G.listener||G]:[G]:k?d(G):Q(G,G.length)}g.prototype.listeners=function(S){return l(this,S,!0)},g.prototype.rawListeners=function(S){return l(this,S,!1)},g.listenerCount=function(D,S){return typeof D.listenerCount=="function"?D.listenerCount(S):B.call(D,S)},g.prototype.listenerCount=B;function B(D){var S=this._events;if(S!==void 0){var k=S[D];if(typeof k=="function")return 1;if(k!==void 0)return k.length}return 0}g.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function Q(D,S){for(var k=new Array(S),N=0;N<S;++N)k[N]=D[N];return k}function h(D,S){for(;S+1<D.length;S++)D[S]=D[S+1];D.pop()}function d(D){for(var S=new Array(D.length),k=0;k<S.length;++k)S[k]=D[k].listener||D[k];return S}function p(D,S){return new Promise(function(k,N){function G(w){D.removeListener(S,M),N(w)}function M(){typeof D.removeListener=="function"&&D.removeListener("error",G),k([].slice.call(arguments))}m(D,S,M,{once:!0}),S!=="error"&&y(D,G,{once:!0})})}function y(D,S,k){typeof D.on=="function"&&m(D,"error",S,k)}function m(D,S,k,N){if(typeof D.on=="function")N.once?D.once(S,k):D.on(S,k);else if(typeof D.addEventListener=="function")D.addEventListener(S,function G(M){N.once&&D.removeEventListener(S,G),k(M)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof D)}return xb.exports}var RB=EWA();let duA=!0,huA=!0;function pk(e,A,t){const i=e.match(A);return i&&i.length>=t&&parseFloat(i[t],10)}function qf(e,A,t){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(o,s){if(o!==A)return n.apply(this,arguments);const a=r=>{const I=t(r);I&&(s.handleEvent?s.handleEvent(I):s(I))};return this._eventMap=this._eventMap||{},this._eventMap[A]||(this._eventMap[A]=new Map),this._eventMap[A].set(s,a),n.apply(this,[o,a])};const g=i.removeEventListener;i.removeEventListener=function(o,s){if(o!==A||!this._eventMap||!this._eventMap[A])return g.apply(this,arguments);if(!this._eventMap[A].has(s))return g.apply(this,arguments);const a=this._eventMap[A].get(s);return this._eventMap[A].delete(s),this._eventMap[A].size===0&&delete this._eventMap[A],Object.keys(this._eventMap).length===0&&delete this._eventMap,g.apply(this,[o,a])},Object.defineProperty(i,"on"+A,{get(){return this["_on"+A]},set(o){this["_on"+A]&&(this.removeEventListener(A,this["_on"+A]),delete this["_on"+A]),o&&this.addEventListener(A,this["_on"+A]=o)},enumerable:!0,configurable:!0})}function QWA(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(duA=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function uWA(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(huA=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function puA(){if(typeof window=="object"){if(duA)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Gz(e,A){huA&&console.warn(e+" is deprecated, please use "+A+" instead.")}function dWA(e){const A={browser:null,version:null};if(typeof e>"u"||!e.navigator||!e.navigator.userAgent)return A.browser="Not a browser.",A;const{navigator:t}=e;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(n=>n.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)A.browser="firefox",A.version=parseInt(pk(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)A.browser="chrome",A.version=parseInt(pk(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))A.browser="safari",A.version=parseInt(pk(t.userAgent,/AppleWebKit\/(\d+)\./,1)),A.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,A._safariVersion=pk(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return A.browser="Not a supported browser.",A;return A}function hAA(e){return Object.prototype.toString.call(e)==="[object Object]"}function fuA(e){return hAA(e)?Object.keys(e).reduce(function(A,t){const i=hAA(e[t]),n=i?fuA(e[t]):e[t],g=i&&!Object.keys(n).length;return n===void 0||g?A:Object.assign(A,{[t]:n})},{}):e}function s3(e,A,t){!A||t.has(A.id)||(t.set(A.id,A),Object.keys(A).forEach(i=>{i.endsWith("Id")?s3(e,e.get(A[i]),t):i.endsWith("Ids")&&A[i].forEach(n=>{s3(e,e.get(n),t)})}))}function pAA(e,A,t){const i=t?"outbound-rtp":"inbound-rtp",n=new Map;if(A===null)return n;const g=[];return e.forEach(o=>{o.type==="track"&&o.trackIdentifier===A.id&&g.push(o)}),g.forEach(o=>{e.forEach(s=>{s.type===i&&s.trackId===o.id&&s3(e,s,n)})}),n}const fAA=puA;function yuA(e,A){const t=e&&e.navigator;if(!t.mediaDevices)return;const i=function(s){if(typeof s!="object"||s.mandatory||s.optional)return s;const a={};return Object.keys(s).forEach(r=>{if(r==="require"||r==="advanced"||r==="mediaSource")return;const I=typeof s[r]=="object"?s[r]:{ideal:s[r]};I.exact!==void 0&&typeof I.exact=="number"&&(I.min=I.max=I.exact);const c=function(l,B){return l?l+B.charAt(0).toUpperCase()+B.slice(1):B==="deviceId"?"sourceId":B};if(I.ideal!==void 0){a.optional=a.optional||[];let l={};typeof I.ideal=="number"?(l[c("min",r)]=I.ideal,a.optional.push(l),l={},l[c("max",r)]=I.ideal,a.optional.push(l)):(l[c("",r)]=I.ideal,a.optional.push(l))}I.exact!==void 0&&typeof I.exact!="number"?(a.mandatory=a.mandatory||{},a.mandatory[c("",r)]=I.exact):["min","max"].forEach(l=>{I[l]!==void 0&&(a.mandatory=a.mandatory||{},a.mandatory[c(l,r)]=I[l])})}),s.advanced&&(a.optional=(a.optional||[]).concat(s.advanced)),a},n=function(s,a){if(A.version>=61)return a(s);if(s=JSON.parse(JSON.stringify(s)),s&&typeof s.audio=="object"){const r=function(I,c,l){c in I&&!(l in I)&&(I[l]=I[c],delete I[c])};s=JSON.parse(JSON.stringify(s)),r(s.audio,"autoGainControl","googAutoGainControl"),r(s.audio,"noiseSuppression","googNoiseSuppression"),s.audio=i(s.audio)}if(s&&typeof s.video=="object"){let r=s.video.facingMode;r=r&&(typeof r=="object"?r:{ideal:r});const I=A.version<66;if(r&&(r.exact==="user"||r.exact==="environment"||r.ideal==="user"||r.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!I)){delete s.video.facingMode;let c;if(r.exact==="environment"||r.ideal==="environment"?c=["back","rear"]:(r.exact==="user"||r.ideal==="user")&&(c=["front"]),c)return t.mediaDevices.enumerateDevices().then(l=>{l=l.filter(Q=>Q.kind==="videoinput");let B=l.find(Q=>c.some(h=>Q.label.toLowerCase().includes(h)));return!B&&l.length&&c.includes("back")&&(B=l[l.length-1]),B&&(s.video.deviceId=r.exact?{exact:B.deviceId}:{ideal:B.deviceId}),s.video=i(s.video),fAA("chrome: "+JSON.stringify(s)),a(s)})}s.video=i(s.video)}return fAA("chrome: "+JSON.stringify(s)),a(s)},g=function(s){return A.version>=64?s:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[s.name]||s.name,message:s.message,constraint:s.constraint||s.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(s,a,r){n(s,I=>{t.webkitGetUserMedia(I,a,c=>{r&&r(g(c))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(a){return n(a,r=>s(r).then(I=>{if(r.audio&&!I.getAudioTracks().length||r.video&&!I.getVideoTracks().length)throw I.getTracks().forEach(c=>{c.stop()}),new DOMException("","NotFoundError");return I},I=>Promise.reject(g(I))))}}}function DuA(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function muA(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const A=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",n=>{let g;e.RTCPeerConnection.prototype.getReceivers?g=this.getReceivers().find(s=>s.track&&s.track.id===n.track.id):g={track:n.track};const o=new Event("track");o.track=n.track,o.receiver=g,o.transceiver={receiver:g},o.streams=[i.stream],this.dispatchEvent(o)}),i.stream.getTracks().forEach(n=>{let g;e.RTCPeerConnection.prototype.getReceivers?g=this.getReceivers().find(s=>s.track&&s.track.id===n.id):g={track:n};const o=new Event("track");o.track=n,o.receiver=g,o.transceiver={receiver:g},o.streams=[i.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),A.apply(this,arguments)}}else qf(e,"track",A=>(A.transceiver||Object.defineProperty(A,"transceiver",{value:{receiver:A.receiver}}),A))}function SuA(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const A=function(n,g){return{track:g,get dtmf(){return this._dtmf===void 0&&(g.kind==="audio"?this._dtmf=n.createDTMFSender(g):this._dtmf=null),this._dtmf},_pc:n}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(s,a){let r=n.apply(this,arguments);return r||(r=A(this,s),this._senders.push(r)),r};const g=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(s){g.apply(this,arguments);const a=this._senders.indexOf(s);a!==-1&&this._senders.splice(a,1)}}const t=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(g){this._senders=this._senders||[],t.apply(this,[g]),g.getTracks().forEach(o=>{this._senders.push(A(this,o))})};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(g){this._senders=this._senders||[],i.apply(this,[g]),g.getTracks().forEach(o=>{const s=this._senders.find(a=>a.track===o);s&&this._senders.splice(this._senders.indexOf(s),1)})}}else if(typeof e=="object"&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const A=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const i=A.apply(this,[]);return i.forEach(n=>n._pc=this),i},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function wuA(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const g=t.apply(this,[]);return g.forEach(o=>o._pc=this),g});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const g=i.apply(this,arguments);return g._pc=this,g}),e.RTCRtpSender.prototype.getStats=function(){const g=this;return this._pc.getStats().then(o=>pAA(o,g.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const n=t.apply(this,[]);return n.forEach(g=>g._pc=this),n}),qf(e,"track",i=>(i.receiver._pc=i.srcElement,i)),e.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(g=>pAA(g,n.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;const A=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const i=arguments[0];let n,g,o;return this.getSenders().forEach(s=>{s.track===i&&(n?o=!0:n=s)}),this.getReceivers().forEach(s=>(s.track===i&&(g?o=!0:g=s),s.track===i)),o||n&&g?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):n?n.getStats():g?g.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return A.apply(this,arguments)}}function kuA(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const A=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(o,s){if(!s)return A.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const a=A.apply(this,arguments);return this._shimmedLocalStreams[s.id]?this._shimmedLocalStreams[s.id].indexOf(a)===-1&&this._shimmedLocalStreams[s.id].push(a):this._shimmedLocalStreams[s.id]=[s,a],a};const t=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(r=>{if(this.getSenders().find(c=>c.track===r))throw new DOMException("Track already exists.","InvalidAccessError")});const s=this.getSenders();t.apply(this,arguments);const a=this.getSenders().filter(r=>s.indexOf(r)===-1);this._shimmedLocalStreams[o.id]=[o].concat(a)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(s=>{const a=this._shimmedLocalStreams[s].indexOf(o);a!==-1&&this._shimmedLocalStreams[s].splice(a,1),this._shimmedLocalStreams[s].length===1&&delete this._shimmedLocalStreams[s]}),n.apply(this,arguments)}}function MuA(e,A){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&A.version>=65)return kuA(e);const t=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const I=t.apply(this);return this._reverseStreams=this._reverseStreams||{},I.map(c=>this._reverseStreams[c.id])};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(I){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},I.getTracks().forEach(c=>{if(this.getSenders().find(B=>B.track===c))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[I.id]){const c=new e.MediaStream(I.getTracks());this._streams[I.id]=c,this._reverseStreams[c.id]=I,I=c}i.apply(this,[I])};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(I){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[I.id]||I]),delete this._reverseStreams[this._streams[I.id]?this._streams[I.id].id:I.id],delete this._streams[I.id]},e.RTCPeerConnection.prototype.addTrack=function(I,c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const l=[].slice.call(arguments,1);if(l.length!==1||!l[0].getTracks().find(h=>h===I))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(h=>h.track===I))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const Q=this._streams[c.id];if(Q)Q.addTrack(I),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const h=new e.MediaStream([I]);this._streams[c.id]=h,this._reverseStreams[h.id]=c,this.addStream(h)}return this.getSenders().find(h=>h.track===I)};function g(r,I){let c=I.sdp;return Object.keys(r._reverseStreams||[]).forEach(l=>{const B=r._reverseStreams[l],Q=r._streams[B.id];c=c.replace(new RegExp(Q.id,"g"),B.id)}),new RTCSessionDescription({type:I.type,sdp:c})}function o(r,I){let c=I.sdp;return Object.keys(r._reverseStreams||[]).forEach(l=>{const B=r._reverseStreams[l],Q=r._streams[B.id];c=c.replace(new RegExp(B.id,"g"),Q.id)}),new RTCSessionDescription({type:I.type,sdp:c})}["createOffer","createAnswer"].forEach(function(r){const I=e.RTCPeerConnection.prototype[r],c={[r](){const l=arguments;return arguments.length&&typeof arguments[0]=="function"?I.apply(this,[Q=>{const h=g(this,Q);l[0].apply(null,[h])},Q=>{l[1]&&l[1].apply(null,Q)},arguments[2]]):I.apply(this,arguments).then(Q=>g(this,Q))}};e.RTCPeerConnection.prototype[r]=c[r]});const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?s.apply(this,arguments):(arguments[0]=o(this,arguments[0]),s.apply(this,arguments))};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const r=a.get.apply(this);return r.type===""?r:g(this,r)}}),e.RTCPeerConnection.prototype.removeTrack=function(I){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!I._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(I._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let l;Object.keys(this._streams).forEach(B=>{this._streams[B].getTracks().find(h=>I.track===h)&&(l=this._streams[B])}),l&&(l.getTracks().length===1?this.removeStream(this._reverseStreams[l.id]):l.removeTrack(I.track),this.dispatchEvent(new Event("negotiationneeded")))}}function a3(e,A){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&A.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new(t==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]})}function NuA(e,A){qf(e,"negotiationneeded",t=>{const i=t.target;if(!((A.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var yAA=Object.freeze({__proto__:null,fixNegotiationNeeded:NuA,shimAddTrackRemoveTrack:MuA,shimAddTrackRemoveTrackWithNative:kuA,shimGetSendersWithDtmf:SuA,shimGetUserMedia:yuA,shimMediaStream:DuA,shimOnTrack:muA,shimPeerConnection:a3,shimSenderReceiverGetStats:wuA});function RuA(e,A){const t=e&&e.navigator,i=e&&e.MediaStreamTrack;if(t.getUserMedia=function(n,g,o){Gz("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(n).then(g,o)},!(A.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const n=function(o,s,a){s in o&&!(a in o)&&(o[a]=o[s],delete o[s])},g=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),n(o.audio,"autoGainControl","mozAutoGainControl"),n(o.audio,"noiseSuppression","mozNoiseSuppression")),g(o)},i&&i.prototype.getSettings){const o=i.prototype.getSettings;i.prototype.getSettings=function(){const s=o.apply(this,arguments);return n(s,"mozAutoGainControl","autoGainControl"),n(s,"mozNoiseSuppression","noiseSuppression"),s}}if(i&&i.prototype.applyConstraints){const o=i.prototype.applyConstraints;i.prototype.applyConstraints=function(s){return this.kind==="audio"&&typeof s=="object"&&(s=JSON.parse(JSON.stringify(s)),n(s,"autoGainControl","mozAutoGainControl"),n(s,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[s])}}}}function hWA(e,A){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return i.video===!0?i.video={mediaSource:A}:i.video.mediaSource=A,e.navigator.mediaDevices.getUserMedia(i)})}function GuA(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function r3(e,A){if(typeof e!="object"||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),A.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){const g=e.RTCPeerConnection.prototype[n],o={[n](){return arguments[0]=new(n==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),g.apply(this,arguments)}};e.RTCPeerConnection.prototype[n]=o[n]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[g,o,s]=arguments;return i.apply(this,[g||null]).then(a=>{if(A.version<53&&!o)try{a.forEach(r=>{r.type=t[r.type]||r.type})}catch(r){if(r.name!=="TypeError")throw r;a.forEach((I,c)=>{a.set(c,Object.assign({},I,{type:t[I.type]||I.type}))})}return a}).then(o,s)}}function buA(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const A=e.RTCPeerConnection.prototype.getSenders;A&&(e.RTCPeerConnection.prototype.getSenders=function(){const n=A.apply(this,[]);return n.forEach(g=>g._pc=this),n});const t=e.RTCPeerConnection.prototype.addTrack;t&&(e.RTCPeerConnection.prototype.addTrack=function(){const n=t.apply(this,arguments);return n._pc=this,n}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function UuA(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const A=e.RTCPeerConnection.prototype.getReceivers;A&&(e.RTCPeerConnection.prototype.getReceivers=function(){const i=A.apply(this,[]);return i.forEach(n=>n._pc=this),i}),qf(e,"track",t=>(t.receiver._pc=t.srcElement,t)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function vuA(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(t){Gz("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function KuA(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function FuA(e){if(!(typeof e=="object"&&e.RTCPeerConnection))return;const A=e.RTCPeerConnection.prototype.addTransceiver;A&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const n=i.length>0;n&&i.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const g=A.apply(this,arguments);if(n){const{sender:o}=g,s=o.getParameters();(!("encodings"in s)||s.encodings.length===1&&Object.keys(s.encodings[0]).length===0)&&(s.encodings=i,o.sendEncodings=i,this.setParametersPromises.push(o.setParameters(s).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return g})}function _uA(e){if(!(typeof e=="object"&&e.RTCRtpSender))return;const A=e.RTCRtpSender.prototype.getParameters;A&&(e.RTCRtpSender.prototype.getParameters=function(){const i=A.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function JuA(e){if(!(typeof e=="object"&&e.RTCPeerConnection))return;const A=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>A.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):A.apply(this,arguments)}}function LuA(e){if(!(typeof e=="object"&&e.RTCPeerConnection))return;const A=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>A.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):A.apply(this,arguments)}}var DAA=Object.freeze({__proto__:null,shimAddTransceiver:FuA,shimCreateAnswer:LuA,shimCreateOffer:JuA,shimGetDisplayMedia:hWA,shimGetParameters:_uA,shimGetUserMedia:RuA,shimOnTrack:GuA,shimPeerConnection:r3,shimRTCDataChannel:KuA,shimReceiverGetStats:UuA,shimRemoveStream:vuA,shimSenderGetStats:buA});function xuA(e){if(!(typeof e!="object"||!e.RTCPeerConnection)){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const A=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(n=>A.call(this,n,i)),i.getVideoTracks().forEach(n=>A.call(this,n,i))},e.RTCPeerConnection.prototype.addTrack=function(i){for(var n=arguments.length,g=new Array(n>1?n-1:0),o=1;o<n;o++)g[o-1]=arguments[o];return g&&g.forEach(s=>{this._localStreams?this._localStreams.includes(s)||this._localStreams.push(s):this._localStreams=[s]}),A.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const n=t.getTracks();this.getSenders().forEach(g=>{n.includes(g.track)&&this.removeTrack(g)})})}}function TuA(e){if(!(typeof e!="object"||!e.RTCPeerConnection)&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(n=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(n))return;this._remoteStreams.push(n);const g=new Event("addstream");g.stream=n,this.dispatchEvent(g)})})}});const A=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(g=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(g)>=0)return;i._remoteStreams.push(g);const o=new Event("addstream");o.stream=g,i.dispatchEvent(o)})}),A.apply(i,arguments)}}}function quA(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const A=e.RTCPeerConnection.prototype,t=A.createOffer,i=A.createAnswer,n=A.setLocalDescription,g=A.setRemoteDescription,o=A.addIceCandidate;A.createOffer=function(r,I){const c=arguments.length>=2?arguments[2]:arguments[0],l=t.apply(this,[c]);return I?(l.then(r,I),Promise.resolve()):l},A.createAnswer=function(r,I){const c=arguments.length>=2?arguments[2]:arguments[0],l=i.apply(this,[c]);return I?(l.then(r,I),Promise.resolve()):l};let s=function(a,r,I){const c=n.apply(this,[a]);return I?(c.then(r,I),Promise.resolve()):c};A.setLocalDescription=s,s=function(a,r,I){const c=g.apply(this,[a]);return I?(c.then(r,I),Promise.resolve()):c},A.setRemoteDescription=s,s=function(a,r,I){const c=o.apply(this,[a]);return I?(c.then(r,I),Promise.resolve()):c},A.addIceCandidate=s}function YuA(e){const A=e&&e.navigator;if(A.mediaDevices&&A.mediaDevices.getUserMedia){const t=A.mediaDevices,i=t.getUserMedia.bind(t);A.mediaDevices.getUserMedia=n=>i(HuA(n))}!A.getUserMedia&&A.mediaDevices&&A.mediaDevices.getUserMedia&&(A.getUserMedia=(function(i,n,g){A.mediaDevices.getUserMedia(i).then(n,g)}).bind(A))}function HuA(e){return e&&e.video!==void 0?Object.assign({},e,{video:fuA(e.video)}):e}function OuA(e){if(!e.RTCPeerConnection)return;const A=e.RTCPeerConnection;e.RTCPeerConnection=function(i,n){if(i&&i.iceServers){const g=[];for(let o=0;o<i.iceServers.length;o++){let s=i.iceServers[o];s.urls===void 0&&s.url?(Gz("RTCIceServer.url","RTCIceServer.urls"),s=JSON.parse(JSON.stringify(s)),s.urls=s.url,delete s.url,g.push(s)):g.push(i.iceServers[o])}i.iceServers=g}return new A(i,n)},e.RTCPeerConnection.prototype=A.prototype,"generateCertificate"in A&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get(){return A.generateCertificate}})}function PuA(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function juA(e){const A=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const n=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):i.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const g=this.getTransceivers().find(o=>o.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&g?g.direction==="sendrecv"?g.setDirection?g.setDirection("sendonly"):g.direction="sendonly":g.direction==="recvonly"&&(g.setDirection?g.setDirection("inactive"):g.direction="inactive"):i.offerToReceiveVideo===!0&&!g&&this.addTransceiver("video",{direction:"recvonly"})}return A.apply(this,arguments)}}function zuA(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var mAA=Object.freeze({__proto__:null,shimAudioContext:zuA,shimCallbacksAPI:quA,shimConstraints:HuA,shimCreateOfferLegacy:juA,shimGetUserMedia:YuA,shimLocalStreamsAPI:xuA,shimRTCIceServerUrls:OuA,shimRemoteStreamsAPI:TuA,shimTrackEventTransceiver:PuA}),j2={exports:{}},SAA;function pWA(){return SAA||(SAA=1,function(e){const A={};A.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},A.localCName=A.generateIdentifier(),A.splitLines=function(t){return t.trim().split(`
`).map(i=>i.trim())},A.splitSections=function(t){return t.split(`
m=`).map((n,g)=>(g>0?"m="+n:n).trim()+`\r
`)},A.getDescription=function(t){const i=A.splitSections(t);return i&&i[0]},A.getMediaSections=function(t){const i=A.splitSections(t);return i.shift(),i},A.matchPrefix=function(t,i){return A.splitLines(t).filter(n=>n.indexOf(i)===0)},A.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const n={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let g=8;g<i.length;g+=2)switch(i[g]){case"raddr":n.relatedAddress=i[g+1];break;case"rport":n.relatedPort=parseInt(i[g+1],10);break;case"tcptype":n.tcpType=i[g+1];break;case"ufrag":n.ufrag=i[g+1],n.usernameFragment=i[g+1];break;default:n[i[g]]===void 0&&(n[i[g]]=i[g+1]);break}return n},A.writeCandidate=function(t){const i=[];i.push(t.foundation);const n=t.component;n==="rtp"?i.push(1):n==="rtcp"?i.push(2):i.push(n),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const g=t.type;return i.push("typ"),i.push(g),g!=="host"&&t.relatedAddress&&t.relatedPort&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},A.parseIceOptions=function(t){return t.substring(14).split(" ")},A.parseRtpMap=function(t){let i=t.substring(9).split(" ");const n={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),n.name=i[0],n.clockRate=parseInt(i[1],10),n.channels=i.length===3?parseInt(i[2],10):1,n.numChannels=n.channels,n},A.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const n=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(n!==1?"/"+n:"")+`\r
`},A.parseExtmap=function(t){const i=t.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.slice(2).join(" ")}},A.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
`},A.parseFmtp=function(t){const i={};let n;const g=t.substring(t.indexOf(" ")+1).split(";");for(let o=0;o<g.length;o++)n=g[o].trim().split("="),i[n[0].trim()]=n[1];return i},A.writeFmtp=function(t){let i="",n=t.payloadType;if(t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const g=[];Object.keys(t.parameters).forEach(o=>{t.parameters[o]!==void 0?g.push(o+"="+t.parameters[o]):g.push(o)}),i+="a=fmtp:"+n+" "+g.join(";")+`\r
`}return i},A.parseRtcpFb=function(t){const i=t.substring(t.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},A.writeRtcpFb=function(t){let i="",n=t.payloadType;return t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(g=>{i+="a=rtcp-fb:"+n+" "+g.type+(g.parameter&&g.parameter.length?" "+g.parameter:"")+`\r
`}),i},A.parseSsrcMedia=function(t){const i=t.indexOf(" "),n={ssrc:parseInt(t.substring(7,i),10)},g=t.indexOf(":",i);return g>-1?(n.attribute=t.substring(i+1,g),n.value=t.substring(g+1)):n.attribute=t.substring(i+1),n},A.parseSsrcGroup=function(t){const i=t.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(n=>parseInt(n,10))}},A.getMid=function(t){const i=A.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},A.parseFingerprint=function(t){const i=t.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},A.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:A.matchPrefix(t+i,"a=fingerprint:").map(A.parseFingerprint)}},A.writeDtlsParameters=function(t,i){let n="a=setup:"+i+`\r
`;return t.fingerprints.forEach(g=>{n+="a=fingerprint:"+g.algorithm+" "+g.value+`\r
`}),n},A.parseCryptoLine=function(t){const i=t.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.slice(3)}},A.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?A.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
`},A.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},A.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},A.getCryptoParameters=function(t,i){return A.matchPrefix(t+i,"a=crypto:").map(A.parseCryptoLine)},A.getIceParameters=function(t,i){const n=A.matchPrefix(t+i,"a=ice-ufrag:")[0],g=A.matchPrefix(t+i,"a=ice-pwd:")[0];return n&&g?{usernameFragment:n.substring(12),password:g.substring(10)}:null},A.writeIceParameters=function(t){let i="a=ice-ufrag:"+t.usernameFragment+`\r
a=ice-pwd:`+t.password+`\r
`;return t.iceLite&&(i+=`a=ice-lite\r
`),i},A.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},g=A.splitLines(t)[0].split(" ");i.profile=g[2];for(let s=3;s<g.length;s++){const a=g[s],r=A.matchPrefix(t,"a=rtpmap:"+a+" ")[0];if(r){const I=A.parseRtpMap(r),c=A.matchPrefix(t,"a=fmtp:"+a+" ");switch(I.parameters=c.length?A.parseFmtp(c[0]):{},I.rtcpFeedback=A.matchPrefix(t,"a=rtcp-fb:"+a+" ").map(A.parseRtcpFb),i.codecs.push(I),I.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(I.name.toUpperCase());break}}}A.matchPrefix(t,"a=extmap:").forEach(s=>{i.headerExtensions.push(A.parseExtmap(s))});const o=A.matchPrefix(t,"a=rtcp-fb:* ").map(A.parseRtcpFb);return i.codecs.forEach(s=>{o.forEach(a=>{s.rtcpFeedback.find(I=>I.type===a.type&&I.parameter===a.parameter)||s.rtcpFeedback.push(a)})}),i},A.writeRtpDescription=function(t,i){let n="";n+="m="+t+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(o=>o.preferredPayloadType!==void 0?o.preferredPayloadType:o.payloadType).join(" ")+`\r
`,n+=`c=IN IP4 0.0.0.0\r
`,n+=`a=rtcp:9 IN IP4 0.0.0.0\r
`,i.codecs.forEach(o=>{n+=A.writeRtpMap(o),n+=A.writeFmtp(o),n+=A.writeRtcpFb(o)});let g=0;return i.codecs.forEach(o=>{o.maxptime>g&&(g=o.maxptime)}),g>0&&(n+="a=maxptime:"+g+`\r
`),i.headerExtensions&&i.headerExtensions.forEach(o=>{n+=A.writeExtmap(o)}),n},A.parseRtpEncodingParameters=function(t){const i=[],n=A.parseRtpParameters(t),g=n.fecMechanisms.indexOf("RED")!==-1,o=n.fecMechanisms.indexOf("ULPFEC")!==-1,s=A.matchPrefix(t,"a=ssrc:").map(l=>A.parseSsrcMedia(l)).filter(l=>l.attribute==="cname"),a=s.length>0&&s[0].ssrc;let r;const I=A.matchPrefix(t,"a=ssrc-group:FID").map(l=>l.substring(17).split(" ").map(Q=>parseInt(Q,10)));I.length>0&&I[0].length>1&&I[0][0]===a&&(r=I[0][1]),n.codecs.forEach(l=>{if(l.name.toUpperCase()==="RTX"&&l.parameters.apt){let B={ssrc:a,codecPayloadType:parseInt(l.parameters.apt,10)};a&&r&&(B.rtx={ssrc:r}),i.push(B),g&&(B=JSON.parse(JSON.stringify(B)),B.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(B))}}),i.length===0&&a&&i.push({ssrc:a});let c=A.matchPrefix(t,"b=");return c.length&&(c[0].indexOf("b=TIAS:")===0?c=parseInt(c[0].substring(7),10):c[0].indexOf("b=AS:")===0?c=parseInt(c[0].substring(5),10)*1e3*.95-50*40*8:c=void 0,i.forEach(l=>{l.maxBitrate=c})),i},A.parseRtcpParameters=function(t){const i={},n=A.matchPrefix(t,"a=ssrc:").map(s=>A.parseSsrcMedia(s)).filter(s=>s.attribute==="cname")[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const g=A.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=g.length>0,i.compound=g.length===0;const o=A.matchPrefix(t,"a=rtcp-mux");return i.mux=o.length>0,i},A.writeRtcpParameters=function(t){let i="";return t.reducedSize&&(i+=`a=rtcp-rsize\r
`),t.mux&&(i+=`a=rtcp-mux\r
`),t.ssrc!==void 0&&t.cname&&(i+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
`),i},A.parseMsid=function(t){let i;const n=A.matchPrefix(t,"a=msid:");if(n.length===1)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const g=A.matchPrefix(t,"a=ssrc:").map(o=>A.parseSsrcMedia(o)).filter(o=>o.attribute==="msid");if(g.length>0)return i=g[0].value.split(" "),{stream:i[0],track:i[1]}},A.parseSctpDescription=function(t){const i=A.parseMLine(t),n=A.matchPrefix(t,"a=max-message-size:");let g;n.length>0&&(g=parseInt(n[0].substring(19),10)),isNaN(g)&&(g=65536);const o=A.matchPrefix(t,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:g};const s=A.matchPrefix(t,"a=sctpmap:");if(s.length>0){const a=s[0].substring(10).split(" ");return{port:parseInt(a[0],10),protocol:a[1],maxMessageSize:g}}},A.writeSctpDescription=function(t,i){let n=[];return t.protocol!=="DTLS/SCTP"?n=["m="+t.kind+" 9 "+t.protocol+" "+i.protocol+`\r
`,`c=IN IP4 0.0.0.0\r
`,"a=sctp-port:"+i.port+`\r
`]:n=["m="+t.kind+" 9 "+t.protocol+" "+i.port+`\r
`,`c=IN IP4 0.0.0.0\r
`,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r
`],i.maxMessageSize!==void 0&&n.push("a=max-message-size:"+i.maxMessageSize+`\r
`),n.join("")},A.generateSessionId=function(){return Math.random().toString().substr(2,22)},A.writeSessionBoilerplate=function(t,i,n){let g;const o=i!==void 0?i:2;return t?g=t:g=A.generateSessionId(),`v=0\r
o=`+(n||"thisisadapterortc")+" "+g+" "+o+` IN IP4 127.0.0.1\r
s=-\r
t=0 0\r
`},A.getDirection=function(t,i){const n=A.splitLines(t);for(let g=0;g<n.length;g++)switch(n[g]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[g].substring(2)}return i?A.getDirection(i):"sendrecv"},A.getKind=function(t){return A.splitLines(t)[0].split(" ")[0].substring(2)},A.isRejected=function(t){return t.split(" ",2)[1]==="0"},A.parseMLine=function(t){const n=A.splitLines(t)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},A.parseOLine=function(t){const n=A.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},A.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=A.splitLines(t);for(let n=0;n<i.length;n++)if(i[n].length<2||i[n].charAt(1)!=="=")return!1;return!0},e.exports=A}(j2)),j2.exports}var ZuA=pWA(),Fm=aWA(ZuA),fWA=RzA({__proto__:null,default:Fm},[ZuA]);function hK(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const A=e.RTCIceCandidate;e.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const n=new A(i),g=Fm.parseCandidate(i.candidate);for(const o in g)o in n||Object.defineProperty(n,o,{value:g[o]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new A(i)},e.RTCIceCandidate.prototype=A.prototype,qf(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function I3(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||qf(e,"icecandidate",A=>{if(A.candidate){const t=Fm.parseCandidate(A.candidate.candidate);t.type==="relay"&&(A.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return A})}function pK(e,A){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(s){if(!s||!s.sdp)return!1;const a=Fm.splitSections(s.sdp);return a.shift(),a.some(r=>{const I=Fm.parseMLine(r);return I&&I.kind==="application"&&I.protocol.indexOf("SCTP")!==-1})},i=function(s){const a=s.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(a===null||a.length<2)return-1;const r=parseInt(a[1],10);return r!==r?-1:r},n=function(s){let a=65536;return A.browser==="firefox"&&(A.version<57?s===-1?a=16384:a=2147483637:A.version<60?a=A.version===57?65535:65536:a=2147483637),a},g=function(s,a){let r=65536;A.browser==="firefox"&&A.version===57&&(r=65535);const I=Fm.matchPrefix(s.sdp,"a=max-message-size:");return I.length>0?r=parseInt(I[0].substring(19),10):A.browser==="firefox"&&a!==-1&&(r=2147483637),r},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,A.browser==="chrome"&&A.version>=76){const{sdpSemantics:a}=this.getConfiguration();a==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const a=i(arguments[0]),r=n(a),I=g(arguments[0],a);let c;r===0&&I===0?c=Number.POSITIVE_INFINITY:r===0||I===0?c=Math.max(r,I):c=Math.min(r,I);const l={};Object.defineProperty(l,"maxMessageSize",{get(){return c}}),this._sctp=l}return o.apply(this,arguments)}}function fK(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function A(i,n){const g=i.send;i.send=function(){const s=arguments[0],a=s.length||s.size||s.byteLength;if(i.readyState==="open"&&n.sctp&&a>n.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+n.sctp.maxMessageSize+" bytes)");return g.apply(i,arguments)}}const t=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const n=t.apply(this,arguments);return A(n,this),n},qf(e,"datachannel",i=>(A(i.channel,i.target),i))}function C3(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const A=e.RTCPeerConnection.prototype;Object.defineProperty(A,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(A,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=A[t];A[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=n=>{const g=n.target;if(g._lastConnectionState!==g.connectionState){g._lastConnectionState=g.connectionState;const o=new Event("connectionstatechange",n);g.dispatchEvent(o)}return n},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function c3(e,A){if(!e.RTCPeerConnection||A.browser==="chrome"&&A.version>=71||A.browser==="safari"&&A._safariVersion>=13.1)return;const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(`
a=extmap-allow-mixed`)!==-1){const g=n.sdp.split(`
`).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
`);e.RTCSessionDescription&&n instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:n.type,sdp:g}):n.sdp=g}return t.apply(this,arguments)}}function yK(e,A){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;const t=e.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(A.browser==="chrome"&&A.version<78||A.browser==="firefox"&&A.version<68||A.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function DK(e,A){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;const t=e.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let n=arguments[0]||{};if(typeof n!="object"||n.type&&n.sdp)return t.apply(this,arguments);if(n={type:n.type,sdp:n.sdp},!n.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":n.type="offer";break;default:n.type="answer";break}return n.sdp||n.type!=="offer"&&n.type!=="answer"?t.apply(this,[n]):(n.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var yWA=Object.freeze({__proto__:null,removeExtmapAllowMixed:c3,shimAddIceCandidateNullOrEmpty:yK,shimConnectionState:C3,shimMaxMessageSize:pK,shimParameterlessSetLocalDescription:DK,shimRTCIceCandidate:hK,shimRTCIceCandidateRelayProtocol:I3,shimSendThrowTypeError:fK});function DWA(){let{window:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=puA,i=dWA(e),n={browserDetails:i,commonShim:yWA,extractVersion:pk,disableLog:QWA,disableWarnings:uWA,sdp:fWA};switch(i.browser){case"chrome":if(!yAA||!a3||!A.shimChrome)return t("Chrome shim is not included in this adapter release."),n;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),n;t("adapter.js shimming chrome."),n.browserShim=yAA,yK(e,i),DK(e),yuA(e,i),DuA(e),a3(e,i),muA(e),MuA(e,i),SuA(e),wuA(e),NuA(e,i),hK(e),I3(e),C3(e),pK(e,i),fK(e),c3(e,i);break;case"firefox":if(!DAA||!r3||!A.shimFirefox)return t("Firefox shim is not included in this adapter release."),n;t("adapter.js shimming firefox."),n.browserShim=DAA,yK(e,i),DK(e),RuA(e,i),r3(e,i),GuA(e),vuA(e),buA(e),UuA(e),KuA(e),FuA(e),_uA(e),JuA(e),LuA(e),hK(e),C3(e),pK(e,i),fK(e);break;case"safari":if(!mAA||!A.shimSafari)return t("Safari shim is not included in this adapter release."),n;t("adapter.js shimming safari."),n.browserShim=mAA,yK(e,i),DK(e),OuA(e),juA(e),quA(e),xuA(e),TuA(e),PuA(e),YuA(e),zuA(e),hK(e),I3(e),pK(e,i),fK(e),c3(e,i);break;default:t("Unsupported browser!");break}return n}DWA({window:typeof window>"u"?void 0:window});class tI extends Promise{constructor(A){super(A)}catch(A){return super.catch(A)}static reject(A){return super.reject(A)}static all(A){return super.all(A)}static race(A){return super.race(A)}}const mWA=/version\/(\d+(\.?_?\d+)+)/i;let z2;function rI(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(z2===void 0||A){const i=SWA.find(n=>{let{test:g}=n;return g.test(t)});z2=i==null?void 0:i.describe(t)}return z2}const SWA=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:"Firefox",version:mK(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Z2(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:"Chrome",version:mK(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Z2(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:"Safari",version:mK(mWA,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Z2(e)}}}];function mK(e,A){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=A.match(e);return i&&i.length>=t&&i[t]||""}function Z2(e){return e.includes("mac os")?mK(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}var wWA="2.17.0";const kWA=wWA,MWA=16;class GB extends Error{constructor(A,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=A}}var Lg;(function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"})(Lg||(Lg={}));class Mi extends GB{constructor(A,t,i,n){super(1,A),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=Lg[t]}static notAllowed(A,t,i){return new Mi(A,Lg.NotAllowed,t,i)}static timeout(A){return new Mi(A,Lg.Timeout)}static leaveRequest(A,t){return new Mi(A,Lg.LeaveRequest,void 0,t)}static internal(A,t){return new Mi(A,Lg.InternalError,void 0,t)}static cancelled(A){return new Mi(A,Lg.Cancelled)}static serverUnreachable(A,t){return new Mi(A,Lg.ServerUnreachable,t)}static websocket(A,t,i){return new Mi(A,Lg.WebSocket,t,i)}static serviceNotFound(A,t){return new Mi(A,Lg.ServiceNotFound,void 0,t)}}class bz extends GB{constructor(A){super(21,A??"device is unsupported"),this.name="DeviceUnsupportedError"}}class yE extends GB{constructor(A){super(20,A??"track is invalid"),this.name="TrackInvalidError"}}class NWA extends GB{constructor(A){super(10,A??"unsupported server"),this.name="UnsupportedServer"}}class zo extends GB{constructor(A){super(12,A??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class _m extends GB{constructor(A){super(13,A??"unable to negotiate"),this.name="NegotiationError"}}class wAA extends GB{constructor(A,t){super(15,A),this.name="PublishTrackError",this.status=t}}class kAA extends GB{constructor(A,t){super(15,A),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Rz[t]}}var hr;(function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(hr||(hr={}));class GC extends GB{constructor(A,t){super(16,A),this.name="DataStreamError",this.reason=t,this.reasonName=hr[t]}}class zy extends GB{constructor(A){super(18,A),this.name="SignalReconnectError"}}var s_;(function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"})(s_||(s_={}));(function(e){function A(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?e.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?e.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?e.DeviceInUse:e.Other}e.getFailure=A})(s_||(s_={}));class Ra{}Ra.setTimeout=function(){return setTimeout(...arguments)};Ra.setInterval=function(){return setInterval(...arguments)};Ra.clearTimeout=function(){return clearTimeout(...arguments)};Ra.clearInterval=function(){return clearInterval(...arguments)};var yt;(function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"})(yt||(yt={}));var qt;(function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"})(qt||(qt={}));var _t;(function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"})(_t||(_t={}));var Gt;(function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"})(Gt||(Gt={}));function RWA(e){return typeof e>"u"?e:typeof structuredClone=="function"?typeof e=="object"&&e!==null?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}class Ug{constructor(A,t,i,n,g){if(typeof A=="object")this.width=A.width,this.height=A.height,this.aspectRatio=A.aspectRatio,this.encoding={maxBitrate:A.maxBitrate,maxFramerate:A.maxFramerate,priority:A.priority};else if(t!==void 0&&i!==void 0)this.width=A,this.height=t,this.aspectRatio=A/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:g};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const GWA=["vp8","h264"],bWA=["vp8","h264","vp9","av1","h265"];function UWA(e){return!!GWA.find(A=>A===e)}const vWA=UWA;var MAA;(function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"})(MAA||(MAA={}));var l3;(function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}})(l3||(l3={}));const GS={h90:new Ug(160,90,9e4,20),h180:new Ug(320,180,16e4,20),h216:new Ug(384,216,18e4,20),h360:new Ug(640,360,45e4,20),h540:new Ug(960,540,8e5,25),h720:new Ug(1280,720,17e5,30),h1080:new Ug(1920,1080,3e6,30),h1440:new Ug(2560,1440,5e6,30),h2160:new Ug(3840,2160,8e6,30)},B3={h120:new Ug(160,120,7e4,20),h180:new Ug(240,180,125e3,20),h240:new Ug(320,240,14e4,20),h360:new Ug(480,360,33e4,20),h480:new Ug(640,480,5e5,20),h540:new Ug(720,540,6e5,25),h720:new Ug(960,720,13e5,30),h1080:new Ug(1440,1080,23e5,30),h1440:new Ug(1920,1440,38e5,30)},Uz={h360fps3:new Ug(640,360,2e5,3,"medium"),h360fps15:new Ug(640,360,4e5,15,"medium"),h720fps5:new Ug(1280,720,8e5,5,"medium"),h720fps15:new Ug(1280,720,15e5,15,"medium"),h720fps30:new Ug(1280,720,2e6,30,"medium"),h1080fps15:new Ug(1920,1080,25e5,15,"medium"),h1080fps30:new Ug(1920,1080,5e6,30,"medium"),original:new Ug(0,0,7e6,30,"medium")};function WuA(e,A,t){var i,n,g,o;const{optionsWithoutProcessor:s,audioProcessor:a,videoProcessor:r}=$uA(e??{}),I=A==null?void 0:A.processor,c=t==null?void 0:t.processor,l=s??{};return l.audio===!0&&(l.audio={}),l.video===!0&&(l.video={}),l.audio&&(E3(l.audio,A),(i=(g=l.audio).deviceId)!==null&&i!==void 0||(g.deviceId={ideal:"default"}),(a||I)&&(l.audio.processor=a??I)),l.video&&(E3(l.video,t),(n=(o=l.video).deviceId)!==null&&n!==void 0||(o.deviceId={ideal:"default"}),(r||c)&&(l.video.processor=r??c)),l}function E3(e,A){return Object.keys(A).forEach(t=>{e[t]===void 0&&(e[t]=A[t])}),e}function vz(e){var A,t,i,n;const g={};if(e.video)if(typeof e.video=="object"){const o={},s=o,a=e.video;Object.keys(a).forEach(r=>{switch(r){case"resolution":E3(s,a.resolution);break;default:s[r]=a[r]}}),g.video=o,(A=(i=g.video).deviceId)!==null&&A!==void 0||(i.deviceId={ideal:"default"})}else g.video=e.video?{deviceId:{ideal:"default"}}:!1;else g.video=!1;return e.audio?typeof e.audio=="object"?(g.audio=e.audio,(t=(n=g.audio).deviceId)!==null&&t!==void 0||(n.deviceId={ideal:"default"})):g.audio={deviceId:{ideal:"default"}}:g.audio=!1,g}function VuA(e){return zA(this,arguments,void 0,function(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=XuA();if(i){const n=i.createAnalyser();n.fftSize=2048;const g=n.frequencyBinCount,o=new Uint8Array(g);i.createMediaStreamSource(new MediaStream([A.mediaStreamTrack])).connect(n),yield Ga(t),n.getByteTimeDomainData(o);const a=o.some(r=>r!==128&&r!==0);return i.close(),!a}return!1}()})}function XuA(){var e;const A=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(A){const t=new A({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((e=window.document)===null||e===void 0)&&e.body)){const i=()=>zA(this,void 0,void 0,function*(){var n;try{t.state==="suspended"&&(yield t.resume())}catch(g){console.warn("Error trying to auto-resume audio context",g)}finally{(n=window.document.body)===null||n===void 0||n.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var n;t.state==="closed"&&((n=window.document.body)===null||n===void 0||n.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function KWA(e){return e==="audioinput"?st.Source.Microphone:e==="videoinput"?st.Source.Camera:st.Source.Unknown}function Q3(e){return e===st.Source.Microphone?"audioinput":e===st.Source.Camera?"videoinput":void 0}function FWA(e){var A,t;let i=(A=e.video)!==null&&A!==void 0?A:!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(i=typeof i=="boolean"?{}:i,cf()?i=Object.assign(Object.assign({},i),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:(t=e.audio)!==null&&t!==void 0?t:!1,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function CM(e){return e.split("/")[1].toLowerCase()}function _WA(e){const A=[];return e.forEach(t=>{t.track!==void 0&&A.push(new Sz({cid:t.track.mediaStreamID,track:t.trackInfo}))}),A}function Gn(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?Gn(e.track):{})}}function JWA(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function LWA(e,A){var t;e===void 0&&(e={}),A===void 0&&(A={});const i=[...Object.keys(A),...Object.keys(e)],n={};for(const g of i)e[g]!==A[g]&&(n[g]=(t=A[g])!==null&&t!==void 0?t:"");return n}function $uA(e){const A=Object.assign({},e);let t,i;return typeof A.audio=="object"&&A.audio.processor&&(t=A.audio.processor,A.audio=Object.assign(Object.assign({},A.audio),{processor:void 0})),typeof A.video=="object"&&A.video.processor&&(i=A.video.processor,A.video=Object.assign(Object.assign({},A.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:RWA(A)}}function xWA(e){switch(e){case Es.CAMERA:return st.Source.Camera;case Es.MICROPHONE:return st.Source.Microphone;case Es.SCREEN_SHARE:return st.Source.ScreenShare;case Es.SCREEN_SHARE_AUDIO:return st.Source.ScreenShareAudio;default:return st.Source.Unknown}}function NAA(e,A){return e.width*e.height<A.width*A.height}function TWA(e,A){var t;return(t=e.layers)===null||t===void 0?void 0:t.find(i=>i.quality===A)}const qWA=5e3,w0=[];var PI;(function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"})(PI||(PI={}));class st extends RB.EventEmitter{get streamState(){return this._streamState}setStreamState(A){this._streamState=A}constructor(A,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=st.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ln,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),qWA):this.handleAppVisibilityChanged()},this.log=eQ((n=i.loggerName)!==null&&n!==void 0?n:el.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=A,this._mediaStreamID=A.id,this.source=st.Source.Unknown}get logContext(){var A;return Object.assign(Object.assign({},(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this)),Gn(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(A){let t="audio";this.kind===st.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===st.Kind.Video&&this.addAppVisibilityListener(),A||(t==="audio"&&(w0.forEach(g=>{g.parentElement===null&&!A&&(A=g)}),A&&w0.splice(w0.indexOf(A),1)),A||(A=document.createElement(t))),this.attachedElements.includes(A)||this.attachedElements.push(A),$D(this.mediaStreamTrack,A);const i=A.srcObject.getTracks(),n=i.some(g=>g.kind==="audio");return A.play().then(()=>{this.emit(n?Gt.AudioPlaybackStarted:Gt.VideoPlaybackStarted)}).catch(g=>{g.name==="NotAllowedError"?this.emit(n?Gt.AudioPlaybackFailed:Gt.VideoPlaybackFailed,g):g.name==="AbortError"?ln.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):ln.warn("could not playback ".concat(n?"audio":"video"),g),n&&A&&i.some(o=>o.kind==="video")&&g.name==="NotAllowedError"&&(A.muted=!0,A.play().catch(()=>{}))}),this.emit(Gt.ElementAttached,A),A}detach(A){try{if(A){Jm(this.mediaStreamTrack,A);const i=this.attachedElements.indexOf(A);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(A),this.emit(Gt.ElementDetached,A)),A}const t=[];return this.attachedElements.forEach(i=>{Jm(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(Gt.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(A){A.loggerName&&(this.log=eQ(A.loggerName)),A.loggerContextCb&&(this.loggerContextCb=A.loggerContextCb)}recycleElement(A){if(A instanceof HTMLAudioElement){let t=!0;A.pause(),w0.forEach(i=>{i.parentElement||(t=!1)}),t&&w0.push(A)}}handleAppVisibilityChanged(){return zA(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===st.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(A=>A.play().catch(()=>{})),0)})}addAppVisibilityListener(){iI()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){iI()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function $D(e,A){let t;A.srcObject instanceof MediaStream?t=A.srcObject:t=new MediaStream;let i;e.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(e)||(i.forEach(n=>{t.removeTrack(n)}),t.addTrack(e)),(!cf()||!(A instanceof HTMLVideoElement))&&(A.autoplay=!0),A.muted=t.getAudioTracks().length===0,A instanceof HTMLVideoElement&&(A.playsInline=!0),A.srcObject!==t&&(A.srcObject=t,(cf()||Cf())&&A instanceof HTMLVideoElement&&setTimeout(()=>{A.srcObject=t,A.play().catch(()=>{})},0))}function Jm(e,A){if(A.srcObject instanceof MediaStream){const t=A.srcObject;t.removeTrack(e),t.getTracks().length>0?A.srcObject=t:A.srcObject=null}}(function(e){let A;(function(r){r.Audio="audio",r.Video="video",r.Unknown="unknown"})(A=e.Kind||(e.Kind={}));let t;(function(r){r.Camera="camera",r.Microphone="microphone",r.ScreenShare="screen_share",r.ScreenShareAudio="screen_share_audio",r.Unknown="unknown"})(t=e.Source||(e.Source={}));let i;(function(r){r.Active="active",r.Paused="paused",r.Unknown="unknown"})(i=e.StreamState||(e.StreamState={}));function n(r){switch(r){case A.Audio:return qc.AUDIO;case A.Video:return qc.VIDEO;default:return qc.DATA}}e.kindToProto=n;function g(r){switch(r){case qc.AUDIO:return A.Audio;case qc.VIDEO:return A.Video;default:return A.Unknown}}e.kindFromProto=g;function o(r){switch(r){case t.Camera:return Es.CAMERA;case t.Microphone:return Es.MICROPHONE;case t.ScreenShare:return Es.SCREEN_SHARE;case t.ScreenShareAudio:return Es.SCREEN_SHARE_AUDIO;default:return Es.UNKNOWN}}e.sourceToProto=o;function s(r){switch(r){case Es.CAMERA:return t.Camera;case Es.MICROPHONE:return t.Microphone;case Es.SCREEN_SHARE:return t.ScreenShare;case Es.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}e.sourceFromProto=s;function a(r){switch(r){case n3.ACTIVE:return i.Active;case n3.PAUSED:return i.Paused;default:return i.Unknown}}e.streamStateFromProto=a})(st||(st={}));const YWA="|",RAA="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function HWA(e){const A=e.split(YWA);return A.length>1?[A[0],e.substr(A[0].length+1)]:[e,""]}function Ga(e){return new tI(A=>Ra.setTimeout(A,e))}function u3(){return"addTransceiver"in RTCPeerConnection.prototype}function d3(){return"addTrack"in RTCPeerConnection.prototype}function OWA(){if(!("getCapabilities"in RTCRtpSender)||cf()||Cf())return!1;const e=RTCRtpSender.getCapabilities("video");let A=!1;if(e){for(const t of e.codecs)if(t.mimeType.toLowerCase()==="video/av1"){A=!0;break}}return A}function PWA(){if(!("getCapabilities"in RTCRtpSender)||Cf())return!1;if(cf()){const t=rI();if(t!=null&&t.version&&fB(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&fB(t.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let A=!1;if(e){for(const t of e.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){A=!0;break}}return A}function Hc(e){return e==="av1"||e==="vp9"}function h3(e){return!document||EN()?!1:(e||(e=document.createElement("audio")),"setSinkId"in e)}function jWA(){return typeof RTCPeerConnection>"u"?!1:u3()||d3()}function Cf(){var e;return((e=rI())===null||e===void 0?void 0:e.name)==="Firefox"}function GAA(){const e=rI();return!!e&&e.name==="Chrome"&&e.os!=="iOS"}function cf(){var e;return((e=rI())===null||e===void 0?void 0:e.name)==="Safari"}function EN(){const e=rI();return(e==null?void 0:e.name)==="Safari"||(e==null?void 0:e.os)==="iOS"}function zWA(){const e=rI();return(e==null?void 0:e.name)==="Safari"&&e.version.startsWith("17.")||(e==null?void 0:e.os)==="iOS"&&!!(e!=null&&e.osVersion)&&fB(e.osVersion,"17")>=0}function ZWA(e){return e||(e=rI()),(e==null?void 0:e.name)==="Safari"&&fB(e.version,"18.3")>0||(e==null?void 0:e.os)==="iOS"&&!!(e!=null&&e.osVersion)&&fB(e.osVersion,"18.3")>0}function AdA(){var e,A;return iI()?(A=(e=navigator.userAgentData)===null||e===void 0?void 0:e.mobile)!==null&&A!==void 0?A:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function WWA(){const e=rI(),A="17.2";if(e)return e.name!=="Safari"&&e.os!=="iOS"||e.os==="iOS"&&e.osVersion&&fB(e.osVersion,A)>=0?!0:e.name==="Safari"&&fB(e.version,A)>=0}function iI(){return typeof document<"u"}function pB(){return navigator.product=="ReactNative"}function bS(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function W2(e){return bS(e)?e.hostname.split(".")[0]:null}function edA(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function tdA(){if(!pB())return;let e=edA();if(e)return e.platform}function bAA(){if(iI())return window.devicePixelRatio;if(pB()){let e=edA();if(e)return e.devicePixelRatio}return 1}function fB(e,A){const t=e.split("."),i=A.split("."),n=Math.min(t.length,i.length);for(let g=0;g<n;++g){const o=parseInt(t[g],10),s=parseInt(i[g],10);if(o>s)return 1;if(o<s)return-1;if(g===n-1&&o===s)return 0}return e===""&&A!==""?-1:A===""?1:t.length==i.length?0:t.length<i.length?-1:1}function VWA(e){for(const A of e)A.target.handleResize(A)}function XWA(e){for(const A of e)A.target.handleVisibilityChanged(A)}let V2=null;const UAA=()=>(V2||(V2=new ResizeObserver(VWA)),V2);let X2=null;const vAA=()=>(X2||(X2=new IntersectionObserver(XWA,{root:null,rootMargin:"0px"})),X2);function $WA(){var e;const A=new tuA({sdk:iuA.JS,protocol:MWA,version:kWA});return pB()&&(A.os=(e=tdA())!==null&&e!==void 0?e:""),A}function KAA(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const n=document.createElement("canvas");n.width=e,n.height=A;const g=n.getContext("2d");g==null||g.fillRect(0,0,n.width,n.height),i&&g&&(g.beginPath(),g.arc(e/2,A/2,50,0,Math.PI*2,!0),g.closePath(),g.fillStyle="grey",g.fill());const o=n.captureStream(),[s]=o.getTracks();if(!s)throw Error("Could not get empty media stream video track");return s.enabled=t,s}let k0;function $2(){if(!k0){const e=new AudioContext,A=e.createOscillator(),t=e.createGain();t.gain.setValueAtTime(0,0);const i=e.createMediaStreamDestination();if(A.connect(t),t.connect(i),A.start(),[k0]=i.stream.getAudioTracks(),!k0)throw Error("Could not get empty media stream audio track");k0.enabled=!1}return k0.clone()}class WC{get isResolved(){return this._isResolved}constructor(A,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,n)=>zA(this,void 0,void 0,function*(){this.resolve=i,this.reject=n,A&&(yield A(i,n))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function AVA(e){return bWA.includes(e)}function Wu(e){if(typeof e=="string"||typeof e=="number")return e;if(Array.isArray(e))return e[0];if(e.exact!==void 0)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal!==void 0)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function eVA(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}function QN(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function tVA(e,A){return e.segments.map(t=>{let{id:i,text:n,language:g,startTime:o,endTime:s,final:a}=t;var r;const I=(r=A.get(i))!==null&&r!==void 0?r:Date.now(),c=Date.now();return a?A.delete(i):A.set(i,I),{id:i,text:n,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(s.toString()),final:a,language:g,firstReceivedTime:I,lastReceivedTime:c}})}function iVA(e){const{id:A,timestamp:t,message:i,editTimestamp:n}=e;return{id:A,timestamp:Number.parseInt(t.toString()),editTimestamp:n?Number.parseInt(n.toString()):void 0,message:i}}function FAA(e){switch(e.reason){case Lg.LeaveRequest:return e.context;case Lg.Cancelled:return jc.CLIENT_INITIATED;case Lg.NotAllowed:return jc.USER_REJECTED;case Lg.ServerUnreachable:return jc.JOIN_FAILURE;default:return jc.UNKNOWN_REASON}}function SK(e){return e!==void 0?Number(e):void 0}function jh(e){return e!==void 0?BigInt(e):void 0}function Lm(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function cB(e){return!!e&&e.kind==st.Kind.Audio}function Fd(e){return!!e&&e.kind==st.Kind.Video}function vQ(e){return Lm(e)&&Fd(e)}function aE(e){return Lm(e)&&cB(e)}function p3(e){return!!e&&!e.isLocal}function nVA(e){return!!e&&!e.isLocal}function AY(e){return p3(e)&&Fd(e)}function gVA(e){return e.isLocal}function oVA(e,A){const t=[];let i=new TextEncoder().encode(e);for(;i.length>A;){let n=A;for(;n>0;){const g=i[n];if(g!==void 0&&(g&192)!==128)break;n--}t.push(i.slice(0,n)),i=i.slice(n)}return i.length>0&&t.push(i),t}function sVA(e){var A;const t=e.get("Cache-Control");if(t){const i=(A=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||A===void 0?void 0:A[1];if(i)return parseInt(i,10)}}function aVA(e,A){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=rVA(e,A);return t?i:Kz(i,"v1")}function rVA(e,A){const t=new URL(eVA(e));return A.forEach((i,n)=>{t.searchParams.set(n,i)}),Kz(t,"rtc")}function IVA(e){const A=new URL(QN(e));return Kz(A,"validate")}function idA(e){return e.endsWith("/")?e:"".concat(e,"/")}function Kz(e,A){return e.pathname="".concat(idA(e.pathname)).concat(A),e}function _AA(e){if(typeof e=="string")return EAA.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return EAA.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}function CVA(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return A;const t=e.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:A;default:return"toString"in t?t.toString():A}}const cVA=10,M0="lk_e2ee",lVA="LKFrameEncryptionKey",BVA={sharedKey:!1,ratchetSalt:lVA,ratchetWindowSize:8,failureTolerance:cVA,keyringSize:16};var Vu;(function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"})(Vu||(Vu={}));var JAA;(function(e){e.KeyRatcheted="keyRatcheted"})(JAA||(JAA={}));var Su;(function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"})(Su||(Su={}));var LAA;(function(e){e.Error="cryptorError"})(LAA||(LAA={}));function EVA(){return QVA()||f3()}function f3(){return typeof window.RTCRtpScriptTransform<"u"}function QVA(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function uVA(e){var A,t,i,n,g;if(((A=e.value)===null||A===void 0?void 0:A.case)!=="sipDtmf"&&((t=e.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=e.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((n=e.value)===null||n===void 0?void 0:n.case)!=="transcription"&&((g=e.value)===null||g===void 0?void 0:g.case)!=="encryptedPacket")return new ZQA({value:e.value})}class iGe extends RB.EventEmitter{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,n)=>{ln.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},BVA),A),this.on(Vu.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(A,t,i){const n={key:A,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),n),this.emit(Vu.SetKey,n)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(A,t){this.emit(Vu.RatchetRequest,A,t)}}var xAA;(function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"})(xAA||(xAA={}));class dVA extends RB.EventEmitter{constructor(A,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var n,g;const{kind:o,data:s}=i.data;switch(o){case"error":if(ln.error(s.error.message),s.uuid){const I=this.decryptDataRequests.get(s.uuid);if(I!=null&&I.reject){I.reject(s.error);break}const c=this.encryptDataRequests.get(s.uuid);if(c!=null&&c.reject){c.reject(s.error);break}}this.emit(Su.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(I=>{this.postKey(I)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(I=>{this.postKey(I)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(Su.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const I=(g=this.room)===null||g===void 0?void 0:g.getParticipantByIdentity(s.participantIdentity);if(!I)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(Su.ParticipantEncryptionStatusChanged,s.enabled,I)}break;case"ratchetKey":this.keyProvider.emit(Vu.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const a=this.decryptDataRequests.get(s.uuid);a!=null&&a.resolve&&a.resolve(s);break;case"encryptDataResponse":const r=this.encryptDataRequests.get(s.uuid);r!=null&&r.resolve&&r.resolve(s);break}},this.onWorkerError=i=>{ln.error("e2ee worker encountered an error:",{error:i.error}),this.emit(Su.EncryptionError,i.error,void 0)},this.keyProvider=A.keyProvider,this.worker=A.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(A){if(!EVA())throw new bz("tried to setup end-to-end encryption on an unsupported browser");if(ln.info("setting up e2ee"),A!==this.room){this.room=A,this.setupEventListeners(A,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:CWA.getLevel()}};this.worker&&(ln.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(A,t){ln.debug("set e2ee to ".concat(A," for participant ").concat(t)),this.postEnable(A,t)}setSifTrailer(A){!A||A.length===0?ln.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(A)}setupEngine(A){A.on(_t.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(A,t){A.on(yt.TrackPublished,(i,n)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==Js.NONE,n.identity)),A.on(yt.ConnectionStateChanged,i=>{i===Xn.Connected&&A.remoteParticipants.forEach(n=>{n.trackPublications.forEach(g=>{this.setParticipantCryptorEnabled(g.trackInfo.encryption!==Js.NONE,n.identity)})})}).on(yt.TrackUnsubscribed,(i,n,g)=>{var o;const s={kind:"removeTransform",data:{participantIdentity:g.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(s)}).on(yt.TrackSubscribed,(i,n,g)=>{this.setupE2EEReceiver(i,g.identity,n.trackInfo)}).on(yt.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),A.localParticipant.on(qt.LocalSenderCreated,(i,n)=>zA(this,void 0,void 0,function*(){this.setupE2EESender(n,i)})),A.localParticipant.on(qt.LocalTrackPublished,i=>{if(!Fd(i.track)||!EN())return;const n={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:CM(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}),t.on(Vu.SetKey,i=>this.postKey(i)).on(Vu.RatchetRequest,(i,n)=>this.postRatchetRequest(i,n))}encryptData(A){return zA(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:A,participantIdentity:this.room.localParticipant.identity}},n=new WC;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise})}handleEncryptedData(A,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const g=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:g,payload:A,iv:t,participantIdentity:i,keyIndex:n}},s=new WC;return s.onFinally=()=>{this.decryptDataRequests.delete(g)},this.decryptDataRequests.set(g,s),this.worker.postMessage(o),s.promise}postRatchetRequest(A,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:A,keyIndex:t}};this.worker.postMessage(i)}postKey(A){let{key:t,participantIdentity:i,keyIndex:n}=A;var g;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((g=this.room)===null||g===void 0?void 0:g.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(o)}postEnable(A,t){if(this.worker){const i={kind:"enable",data:{enabled:A,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(A){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:A,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(A){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:A}};this.worker.postMessage(t)}setupE2EEReceiver(A,t,i){if(A.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(A.receiver,A.mediaStreamID,t,A.kind==="video"?CM(i.mimeType):void 0)}}setupE2EESender(A,t){if(!Lm(A)||!t){t||ln.warn("early return because sender is not ready");return}this.handleSender(t,A.mediaStreamID,void 0)}handleReceiver(A,t,i,n){return zA(this,void 0,void 0,function*(){if(this.worker){if(f3()&&!GAA()){const g={kind:"decode",participantIdentity:i,trackId:t,codec:n};A.transform=new RTCRtpScriptTransform(this.worker,g)}else{if(M0 in A&&n){const a={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(a);return}let g=A.writableStream,o=A.readableStream;if(!g||!o){const a=A.createEncodedStreams();A.writableStream=a.writable,g=a.writable,A.readableStream=a.readable,o=a.readable}const s={kind:"decode",data:{readableStream:o,writableStream:g,trackId:t,codec:n,participantIdentity:i,isReuse:M0 in A}};this.worker.postMessage(s,[o,g])}A[M0]=!0}})}handleSender(A,t,i){var n;if(!(M0 in A||!this.worker)){if(!(!((n=this.room)===null||n===void 0)&&n.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(f3()&&!GAA()){ln.info("initialize script transform");const g={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};A.transform=new RTCRtpScriptTransform(this.worker,g)}else{ln.info("initialize encoded streams");const g=A.createEncodedStreams(),o={kind:"encode",data:{readableStream:g.readable,writableStream:g.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[g.readable,g.writable])}A[M0]=!0}}}const hVA=500,pVA=15e3;class xm{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new xm),this._instance}addFailedConnectionAttempt(A){var t;const i=new URL(A),n=W2(i);if(!n)return;let g=(t=this.failedConnectionAttempts.get(n))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(n,g+1),this.backOffPromises.set(n,Ga(Math.min(hVA*Math.pow(2,g),pVA)))}getBackOffPromise(A){const t=new URL(A),i=t&&W2(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(A){const t=new URL(A),i=t&&W2(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}xm._instance=null;const eY="default";class oa{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new oa),this.instance}get previousDevices(){return this._previousDevices}getDevices(A){return zA(this,arguments,void 0,function(t){var i=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var g;if(((g=oa.userMediaPromiseMap)===null||g===void 0?void 0:g.size)>0){ln.debug("awaiting getUserMedia promise");try{t?yield oa.userMediaPromiseMap.get(t):yield Promise.all(oa.userMediaPromiseMap.values())}catch{ln.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(n&&!(cf()&&i.hasDeviceInUse(t))&&(o.filter(a=>a.kind===t).length===0||o.some(a=>{const r=a.label==="",I=t?a.kind===t:!0;return r&&I}))){const a={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},r=yield navigator.mediaDevices.getUserMedia(a);o=yield navigator.mediaDevices.enumerateDevices(),r.getTracks().forEach(I=>{I.stop()})}return i._previousDevices=o,t&&(o=o.filter(s=>s.kind===t)),o}()})}normalizeDeviceId(A,t,i){return zA(this,void 0,void 0,function*(){if(t!==eY)return t;const n=yield this.getDevices(A),g=n.find(s=>s.deviceId===eY);if(!g){ln.warn("could not reliably determine default device");return}const o=n.find(s=>s.deviceId!==eY&&s.groupId===(i??g.groupId));if(!o){ln.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(A){return A?oa.userMediaPromiseMap.has(A):oa.userMediaPromiseMap.size>0}}oa.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];oa.userMediaPromiseMap=new Map;var cM;(function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"})(cM||(cM={}));class fVA{constructor(){this.pendingTasks=new Map,this.taskMutex=new vr,this.nextTaskIndex=0}run(A){return zA(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:cM.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=cM.RUNNING,yield A()}finally{t.status=cM.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return zA(this,void 0,void 0,function*(){return this.run(()=>zA(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class yVA{get readyState(){return this.ws.readyState}constructor(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,n;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=A;const g=new WebSocket(A,(n=t.protocols)!==null&&n!==void 0?n:[]);g.binaryType="arraybuffer",this.ws=g;const o=function(){let{closeCode:s,reason:a}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return g.close(s,a)};this.opened=new tI((s,a)=>{const r=()=>{a(Mi.websocket("Encountered websocket error during connection establishment"))};g.onopen=()=>{s({readable:new ReadableStream({start(I){g.onmessage=c=>{let{data:l}=c;return I.enqueue(l)},g.onerror=c=>I.error(c)},cancel:o}),writable:new WritableStream({write(I){g.send(I)},abort(){g.close()},close:o}),protocol:g.protocol,extensions:g.extensions}),g.removeEventListener("error",r)},g.addEventListener("error",r)}),this.closed=new tI((s,a)=>{const r=()=>zA(this,void 0,void 0,function*(){const I=new tI(l=>{g.readyState!==WebSocket.CLOSED&&g.addEventListener("close",B=>{l(B)},{once:!0})}),c=yield tI.race([Ga(250),I]);c?s(c):a(Mi.websocket("Encountered unspecified websocket error without a timely close event"))});g.onclose=I=>{let{code:c,reason:l}=I;s({closeCode:c,reason:l}),g.removeEventListener("error",r)},g.addEventListener("error",r)}),t.signal&&(t.signal.onabort=()=>g.close()),this.close=o}}const DVA=["syncState","trickle","offer","answer","simulate","leave"];function mVA(e){const A=DVA.indexOf(e.case)>=0;return ln.trace("request allowed to bypass queue:",{canPass:A,req:e}),A}var _g;(function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"})(_g||(_g={}));const SVA=250;class Fz{get currentState(){return this.state}get isDisconnected(){return this.state===_g.DISCONNECTING||this.state===_g.DISCONNECTED}get isEstablishingConnection(){return this.state===_g.CONNECTING||this.state===_g.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=_g.DISCONNECTED,this.log=ln,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=eQ((i=t.loggerName)!==null&&i!==void 0?i:el.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=A,this.requestQueue=new fVA,this.queuedRequests=[],this.closingLock=new vr,this.connectionLock=new vr,this.state=_g.DISCONNECTED}get logContext(){var A,t;return(t=(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this))!==null&&t!==void 0?t:{}}join(A,t,i,n){return zA(this,arguments,void 0,function(g,o,s,a){var r=this;let I=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){return r.state=_g.CONNECTING,r.options=s,yield r.connect(g,o,s,a,I)}()})}reconnect(A,t,i,n){return zA(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=_g.RECONNECTING,this.clearPingInterval(),yield this.connect(A,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}),void 0,this.useV0SignalPath)})}connect(A,t,i,n){return zA(this,arguments,void 0,function(g,o,s,a){var r=this;let I=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){const c=yield r.connectionLock.lock();r.connectOptions=s,r.useV0SignalPath=I;const l=$WA(),B=I?wVA(o,l,s):kVA(o,l,s),Q=aVA(g,B,I).toString(),h=IVA(Q).toString();return new Promise((d,p)=>zA(r,void 0,void 0,function*(){var y,m;try{let D=!1;const S=w=>zA(this,void 0,void 0,function*(){if(D)return;D=!0;const b=w instanceof Event?w.currentTarget:w,_=CVA(b,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(_)).catch(K=>{this.log.error(K),this.close()}):this.close(),k(),p(Mi.cancelled(_))});a==null||a.addEventListener("abort",S);const k=()=>{clearTimeout(N),a==null||a.removeEventListener("abort",S)},N=setTimeout(()=>{S(Mi.timeout("room connection has timed out (signal)"))},s.websocketTimeout),G=(w,b)=>{this.handleSignalConnected(w,N,b)},M=new URL(Q);M.searchParams.has("access_token")&&M.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(M),Object.assign({reconnect:s.reconnect,reconnectReason:s.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new yVA(Q);try{this.ws.closed.then(v=>{var U;this.isEstablishingConnection&&p(Mi.internal("Websocket got closed during a (re)connection attempt: ".concat(v.reason))),v.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:v.reason,code:v.closeCode,wasClean:v.closeCode===1e3,state:this.state})),this.state===_g.CONNECTED&&this.handleOnClose((U=v.reason)!==null&&U!==void 0?U:"Unexpected WS error"))}).catch(v=>{this.isEstablishingConnection&&p(Mi.internal("Websocket error during a (re)connection attempt: ".concat(v)))});const w=yield this.ws.opened.catch(v=>zA(this,void 0,void 0,function*(){if(this.state!==_g.CONNECTED){this.state=_g.DISCONNECTED,clearTimeout(N);const U=yield this.handleConnectionError(v,h);p(U);return}this.handleWSError(v),p(v)}));if(clearTimeout(N),!w)return;const b=w.readable.getReader();this.streamWriter=w.writable.getWriter();const _=yield b.read();if(b.releaseLock(),!_.value)throw Mi.internal("no message received as first message");const K=_AA(_.value),J=this.validateFirstMessage(K,(y=s.reconnect)!==null&&y!==void 0?y:!1);if(!J.isValid){p(J.error);return}((m=K.message)===null||m===void 0?void 0:m.case)==="join"&&(this.pingTimeoutDuration=K.message.value.pingTimeout,this.pingIntervalDuration=K.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));const q=J.shouldProcessFirstMessage?K:void 0;G(w,q),d(J.response)}catch(w){p(w)}finally{k()}}finally{c()}}))}()})}startReadingLoop(A,t){return zA(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Ga(this.signalLatency));const{done:i,value:n}=yield A.read();if(i)break;const g=_AA(n);this.handleSignalResponse(g)}})}close(){return zA(this,arguments,void 0,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return function*(){if([_g.DISCONNECTING||_g.DISCONNECTED].includes(A.state)){A.log.debug("ignoring signal close as it's already in disconnecting state");return}const n=yield A.closingLock.lock();try{if(A.clearPingInterval(),t&&(A.state=_g.DISCONNECTING),A.ws){A.ws.close({closeCode:1e3,reason:i});const g=A.ws.closed;A.ws=void 0,A.streamWriter=void 0,yield Promise.race([g,Ga(SVA)])}}catch(g){A.log.debug("websocket error while closing",Object.assign(Object.assign({},A.logContext),{error:g}))}finally{t&&(A.state=_g.DISCONNECTED),n()}}()})}sendOffer(A,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:A.sdp})),this.sendRequest({case:"offer",value:Am(A,t)})}sendAnswer(A,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:A.sdp})),this.sendRequest({case:"answer",value:Am(A,t)})}sendIceCandidate(A,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:A})),this.sendRequest({case:"trickle",value:new XL({candidateInit:JSON.stringify(A),target:t})})}sendMuteTrack(A,t){return this.sendRequest({case:"mute",value:new $L({sid:A,muted:t})})}sendAddTrack(A){return this.sendRequest({case:"addTrack",value:A})}sendUpdateLocalMetadata(A,t){return zA(this,arguments,void 0,function(i,n){var g=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const s=g.getNextRequestId();return yield g.sendRequest({case:"updateMetadata",value:new kz({requestId:s,metadata:i,name:n,attributes:o})}),s}()})}sendUpdateTrackSettings(A){this.sendRequest({case:"trackSetting",value:A})}sendUpdateSubscription(A){return this.sendRequest({case:"subscription",value:A})}sendSyncState(A){return this.sendRequest({case:"syncState",value:A})}sendUpdateVideoLayers(A,t){return this.sendRequest({case:"updateLayers",value:new IuA({trackSid:A,layers:t})})}sendUpdateSubscriptionPermissions(A,t){return this.sendRequest({case:"subscriptionPermission",value:new luA({allParticipants:A,trackPermissions:t})})}sendSimulateScenario(A){return this.sendRequest({case:"simulate",value:A})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Bo.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new QuA({timestamp:Bo.parse(Date.now()),rtt:Bo.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(A,t){return this.sendRequest({case:"updateAudioTrack",value:new wz({trackSid:A,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ex({reason:jc.CLIENT_INITIATED,action:Km.DISCONNECT})})}sendRequest(A){return zA(this,arguments,void 0,function(t){var i=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!n&&!mVA(t)&&i.state===_g.RECONNECTING){i.queuedRequests.push(()=>zA(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(n||(yield i.requestQueue.flush()),i.signalLatency&&(yield Ga(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),i.logContext);return}const o=new FZA({message:t});try{i.useJSON?yield i.streamWriter.write(o.toJsonString()):yield i.streamWriter.write(o.toBinary())}catch(s){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:s}))}}()})}handleSignalResponse(A){var t,i;const n=A.message;if(n==null){this.log.debug("received unsupported message",this.logContext);return}let g=!1;if(n.case==="answer"){const o=TAA(n.value);this.onAnswer&&this.onAnswer(o,n.value.id,n.value.midToTrackId)}else if(n.case==="offer"){const o=TAA(n.value);this.onOffer&&this.onOffer(o,n.value.id,n.value.midToTrackId)}else if(n.case==="trickle"){const o=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(o,n.value.target)}else n.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=n.value.participants)!==null&&t!==void 0?t:[]):n.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):n.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=n.value.speakers)!==null&&i!==void 0?i:[]):n.case==="leave"?this.onLeave&&this.onLeave(n.value):n.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):n.case==="roomUpdate"?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):n.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(n.value):n.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):n.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):n.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):n.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(n.value):n.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):n.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(n.value):n.case==="pong"||(n.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),g=!0):n.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(n.value):n.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):n.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):n.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(n.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));g||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const A=this.queuedRequests.shift();A&&this.requestQueue.run(A)}}handleOnClose(A){return zA(this,void 0,void 0,function*(){if(this.state===_g.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,A),this.log.debug("websocket connection closed: ".concat(A),Object.assign(Object.assign({},this.logContext),{reason:A})),t&&t(A)})}handleWSError(A){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:A}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Ra.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Ra.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Ra.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Ra.clearInterval(this.pingInterval)}handleSignalConnected(A,t,i){this.state=_g.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(A.readable.getReader(),i)}validateFirstMessage(A,t){var i,n,g,o,s;return((i=A.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:A.message.value}:this.state===_g.RECONNECTING&&((n=A.message)===null||n===void 0?void 0:n.case)!=="leave"?((g=A.message)===null||g===void 0?void 0:g.case)==="reconnect"?{isValid:!0,response:A.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((o=A.message)===null||o===void 0?void 0:o.case)==="leave"?{isValid:!1,error:Mi.leaveRequest("Received leave request while trying to (re)connect",A.message.value.reason)}:t?{isValid:!1,error:Mi.internal("Unexpected first message")}:{isValid:!1,error:Mi.internal("did not receive join response, got ".concat((s=A.message)===null||s===void 0?void 0:s.case," instead"))}}handleConnectionError(A,t){return zA(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:return Mi.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const n=yield i.text();return Mi.notAllowed(n,i.status);default:break}return A instanceof Mi?A:Mi.internal("Encountered unknown websocket error during connection: ".concat(A),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof Mi?i:Mi.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function TAA(e){const A={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":A.type=e.type;break}return A}function Am(e,A){return new ld({sdp:e.sdp,type:e.type,id:A})}function wVA(e,A,t){var i;const n=new URLSearchParams;return n.set("access_token",e),t.reconnect&&(n.set("reconnect","1"),t.sid&&n.set("sid",t.sid)),n.set("auto_subscribe",t.autoSubscribe?"1":"0"),n.set("sdk",pB()?"reactnative":"js"),n.set("version",A.version),n.set("protocol",A.protocol.toString()),A.deviceModel&&n.set("device_model",A.deviceModel),A.os&&n.set("os",A.os),A.osVersion&&n.set("os_version",A.osVersion),A.browser&&n.set("browser",A.browser),A.browserVersion&&n.set("browser_version",A.browserVersion),t.adaptiveStream&&n.set("adaptive_stream","1"),t.reconnectReason&&n.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&n.set("network",navigator.connection.type),n}function kVA(e,A,t){const i=new URLSearchParams;i.set("access_token",e);const n=new nWA({clientInfo:A,connectionSettings:new uuA({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(n.reconnectReason=t.reconnectReason);const g=new gWA({joinRequest:n.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(g.toBinary()))),i}class qAA{constructor(){this.buffer=[],this._totalSize=0}push(A){this.buffer.push(A),this._totalSize+=A.data.byteLength}pop(){const A=this.buffer.shift();return A&&(this._totalSize-=A.data.byteLength),A}getAll(){return this.buffer.slice()}popToSequence(A){for(;this.buffer.length>0&&this.buffer[0].sequence<=A;)this.pop()}alignBufferedAmount(A){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=A)break;this.pop()}}get length(){return this.buffer.length}}class MVA{constructor(A){this._map=new Map,this._lastCleanup=0,this.ttl=A}set(A,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const n=i+this.ttl;return this._map.set(A,{value:t,expiresAt:n}),this}get(A){const t=this._map.get(A);if(t){if(t.expiresAt<Date.now()){this._map.delete(A);return}return t.value}}has(A){const t=this._map.get(A);return t?t.expiresAt<Date.now()?(this._map.delete(A),!1):!0:!1}delete(A){return this._map.delete(A)}clear(){this._map.clear()}cleanup(){const A=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<A&&this._map.delete(t);this._lastCleanup=A}get size(){return this.cleanup(),this._map.size}forEach(A){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&A(i.value,t,this.asValueMap())}map(A){this.cleanup();const t=[],i=this.asValueMap();for(const[n,g]of i.entries())t.push(A(g,n,i));return t}asValueMap(){const A=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&A.set(t,i.value);return A}}var Sc={},tY={},iY={exports:{}},YAA;function _z(){if(YAA)return iY.exports;YAA=1;var e=iY.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(A){return A.encoding?"rtpmap:%d %s/%s/%s":A.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(A){return A.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(A){return A.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(A){return"extmap:%d"+(A.direction?"/%s":"%v")+(A["encrypt-uri"]?" %s":"%v")+" %s"+(A.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(A){return A.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(A){var t="candidate:%s %d %s %d %s %d typ %s";return t+=A.raddr!=null?" raddr %s rport %d":"%v%v",t+=A.tcptype!=null?" tcptype %s":"%v",A.generation!=null&&(t+=" generation %d"),t+=A["network-id"]!=null?" network-id %d":"%v",t+=A["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(A){var t="ssrc:%d";return A.attribute!=null&&(t+=" %s",A.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(A){return A.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(A){return A.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(A){return"imageattr:%s %s %s"+(A.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(A){return"simulcast:%s %s"+(A.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(A){return"ts-refclk:%s"+(A.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(A){var t="mediaclk:";return t+=A.id!=null?"id=%s %s":"%v%s",t+=A.mediaClockValue!=null?"=%s":"",t+=A.rateNumerator!=null?" rate=%s":"",t+=A.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach(function(A){var t=e[A];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),iY.exports}var HAA;function NVA(){return HAA||(HAA=1,function(e){var A=function(s){return String(Number(s))===s?Number(s):s},t=function(s,a,r,I){if(I&&!r)a[I]=A(s[1]);else for(var c=0;c<r.length;c+=1)s[c+1]!=null&&(a[r[c]]=A(s[c+1]))},i=function(s,a,r){var I=s.name&&s.names;s.push&&!a[s.push]?a[s.push]=[]:I&&!a[s.name]&&(a[s.name]={});var c=s.push?{}:I?a[s.name]:a;t(r.match(s.reg),c,s.names,s.name),s.push&&a[s.push].push(c)},n=_z(),g=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(s){var a={},r=[],I=a;return s.split(/(\r\n|\r|\n)/).filter(g).forEach(function(c){var l=c[0],B=c.slice(2);l==="m"&&(r.push({rtp:[],fmtp:[]}),I=r[r.length-1]);for(var Q=0;Q<(n[l]||[]).length;Q+=1){var h=n[l][Q];if(h.reg.test(B))return i(h,I,B)}}),a.media=r,a};var o=function(s,a){var r=a.split(/=(.+)/,2);return r.length===2?s[r[0]]=A(r[1]):r.length===1&&a.length>1&&(s[r[0]]=void 0),s};e.parseParams=function(s){return s.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(s){return s.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(s){for(var a=[],r=s.split(" ").map(A),I=0;I<r.length;I+=3)a.push({component:r[I],ip:r[I+1],port:r[I+2]});return a},e.parseImageAttributes=function(s){return s.split(" ").map(function(a){return a.substring(1,a.length-1).split(",").reduce(o,{})})},e.parseSimulcastStreamList=function(s){return s.split(";").map(function(a){return a.split(",").map(function(r){var I,c=!1;return r[0]!=="~"?I=A(r):(I=A(r.substring(1,r.length)),c=!0),{scid:I,paused:c}})})}}(tY)),tY}var nY,OAA;function RVA(){if(OAA)return nY;OAA=1;var e=_z(),A=/%[sdv%]/g,t=function(o){var s=1,a=arguments,r=a.length;return o.replace(A,function(I){if(s>=r)return I;var c=a[s];switch(s+=1,I){case"%%":return"%";case"%s":return String(c);case"%d":return Number(c);case"%v":return""}})},i=function(o,s,a){var r=s.format instanceof Function?s.format(s.push?a:a[s.name]):s.format,I=[o+"="+r];if(s.names)for(var c=0;c<s.names.length;c+=1){var l=s.names[c];s.name?I.push(a[s.name][l]):I.push(a[s.names[c]])}else I.push(a[s.name]);return t.apply(null,I)},n=["v","o","s","i","u","e","p","c","b","t","r","z","a"],g=["i","c","b","a"];return nY=function(o,s){s=s||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(c){c.payloads==null&&(c.payloads="")});var a=s.outerOrder||n,r=s.innerOrder||g,I=[];return a.forEach(function(c){e[c].forEach(function(l){l.name in o&&o[l.name]!=null?I.push(i(c,l,o)):l.push in o&&o[l.push]!=null&&o[l.push].forEach(function(B){I.push(i(c,l,B))})})}),o.media.forEach(function(c){I.push(i("m",e.m[0],c)),r.forEach(function(l){e[l].forEach(function(B){B.name in c&&c[B.name]!=null?I.push(i(l,B,c)):B.push in c&&c[B.push]!=null&&c[B.push].forEach(function(Q){I.push(i(l,B,Q))})})})}),I.join(`\r
`)+`\r
`},nY}var PAA;function GVA(){if(PAA)return Sc;PAA=1;var e=NVA(),A=RVA(),t=_z();return Sc.grammar=t,Sc.write=A,Sc.parse=e.parse,Sc.parseParams=e.parseParams,Sc.parseFmtpConfig=e.parseFmtpConfig,Sc.parsePayloads=e.parsePayloads,Sc.parseRemoteCandidates=e.parseRemoteCandidates,Sc.parseImageAttributes=e.parseImageAttributes,Sc.parseSimulcastStreamList=e.parseSimulcastStreamList,Sc}var zQ=GVA();function Jz(e,A,t){var i,n,g;A===void 0&&(A=50),t===void 0&&(t={});var o=(i=t.isImmediate)!=null&&i,s=(n=t.callback)!=null&&n,a=t.maxWait,r=Date.now(),I=[];function c(){if(a!==void 0){var B=Date.now()-r;if(B+A>=a)return a-B}return A}var l=function(){var B=[].slice.call(arguments),Q=this;return new Promise(function(h,d){var p=o&&g===void 0;if(g!==void 0&&clearTimeout(g),g=setTimeout(function(){if(g=void 0,r=Date.now(),!o){var m=e.apply(Q,B);s&&s(m),I.forEach(function(D){return(0,D.resolve)(m)}),I=[]}},c()),p){var y=e.apply(Q,B);return s&&s(y),h(y)}I.push({resolve:h,reject:d})})};return l.cancel=function(B){g!==void 0&&clearTimeout(g),I.forEach(function(Q){return(0,Q.reject)(B)}),I=[]},l}const bVA=.7,UVA=20,Tm={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class jAA extends RB.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=ln,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Jz(n=>zA(this,void 0,void 0,function*(){this.emit(Tm.NegotiationStarted);try{yield this.createAndSendOffer()}catch(g){if(n)n(g);else throw g}}),UVA),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=eQ((i=t.loggerName)!==null&&i!==void 0?i:el.PCTransport),this.loggerOptions=t,this.config=A,this._pc=this.createPC(),this.offerLock=new vr}createPC(){const A=new RTCPeerConnection(this.config);return A.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},A.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},A.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,A.iceConnectionState)},A.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,A.signalingState)},A.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,A.connectionState)},A.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},A.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},A}get logContext(){var A,t;return Object.assign({},(t=(A=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(A))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(A){return zA(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(A);this.pendingCandidates.push(A)})}setRemoteDescription(A,t){return zA(this,void 0,void 0,function*(){var i;if(A.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if(A.type==="offer"){let{stereoMids:g,nackMids:o}=vVA(A);this.remoteStereoMids=g,this.remoteNackMids=o}else if(A.type==="answer"){const g=zQ.parse((i=A.sdp)!==null&&i!==void 0?i:"");g.media.forEach(o=>{const s=Lz(o.mid);o.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||s!=a.transceiver.mid)return!1;let r=0;if(o.rtp.some(c=>c.codec.toUpperCase()===a.codec.toUpperCase()?(r=c.payload,!0):!1),r===0)return!0;let I=!1;for(const c of o.fmtp)if(c.payload===r){c.config=c.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),I=!0;break}return I||a.maxbr>0&&o.fmtp.push({payload:r,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),n=zQ.write(g)}return yield this.setMungedSDP(A,n,!0),this.pendingCandidates.forEach(g=>{this.pc.addIceCandidate(g)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):A.type==="answer"&&(this.emit(Tm.NegotiationComplete),A.sdp&&zQ.parse(A.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Tm.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(A){return zA(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(A!=null&&A.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const s=this._pc.remoteDescription;if(A!=null&&A.iceRestart&&s)yield this._pc.setRemoteDescription(s);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const n=this.latestOfferId+1;this.latestOfferId=n;const g=yield this.pc.createOffer(A);this.log.debug("original offer",Object.assign({sdp:g.sdp},this.logContext));const o=zQ.parse((t=g.sdp)!==null&&t!==void 0?t:"");if(o.media.forEach(s=>{ZAA(s),s.type==="audio"?zAA(s,["all"],[]):s.type==="video"&&this.trackBitrates.some(a=>{if(!s.msid||!a.cid||!s.msid.includes(a.cid))return!1;let r=0;if(s.rtp.some(c=>c.codec.toUpperCase()===a.codec.toUpperCase()?(r=c.payload,!0):!1),r===0||(Hc(a.codec)&&!cf()&&this.ensureVideoDDExtensionForSVC(s,o),!Hc(a.codec)))return!0;const I=Math.round(a.maxbr*bVA);for(const c of s.fmtp)if(c.payload===r){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(I));break}return!0})}),this.latestOfferId>n){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:n}));return}yield this.setMungedSDP(g,zQ.write(o)),this.onOffer(g,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return zA(this,void 0,void 0,function*(){var A;const t=yield this.pc.createAnswer(),i=zQ.parse((A=t.sdp)!==null&&A!==void 0?A:"");return i.media.forEach(n=>{ZAA(n),n.type==="audio"&&zAA(n,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,zQ.write(i)),t})}createDataChannel(A,t){return this.pc.createDataChannel(A,t)}addTransceiver(A,t){return this.pc.addTransceiver(A,t)}addTransceiverOfKind(A,t){return this.pc.addTransceiver(A,t)}addTrack(A){if(!this._pc)throw new zo("PC closed, cannot add track");return this._pc.addTrack(A)}setTrackCodecBitrate(A){this.trackBitrates.push(A)}setConfiguration(A){var t;if(!this._pc)throw new zo("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(A)}canRemoveTrack(){var A;return!!(!((A=this._pc)===null||A===void 0)&&A.removeTrack)}removeTrack(A){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(A)}getConnectionState(){var A,t;return(t=(A=this._pc)===null||A===void 0?void 0:A.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var A,t;return(t=(A=this._pc)===null||A===void 0?void 0:A.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var A,t;return(t=(A=this._pc)===null||A===void 0?void 0:A.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var A,t;return(t=(A=this._pc)===null||A===void 0?void 0:A.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var A,t;return(t=(A=this._pc)===null||A===void 0?void 0:A.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var A;return(A=this._pc)===null||A===void 0?void 0:A.localDescription}getRemoteDescription(){var A;return(A=this.pc)===null||A===void 0?void 0:A.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return zA(this,void 0,void 0,function*(){var A;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(s=>{switch(s.type){case"transport":t=s.selectedCandidatePairId;break;case"candidate-pair":t===""&&s.selected&&(t=s.id),i.set(s.id,s);break;case"remote-candidate":n.set(s.id,"".concat(s.address,":").concat(s.port));break}}),t==="")return;const o=(A=i.get(t))===null||A===void 0?void 0:A.remoteCandidateId;if(o!==void 0)return n.get(o)})}setMungedSDP(A,t,i){return zA(this,void 0,void 0,function*(){if(t){const n=A.sdp;A.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(A):yield this.pc.setLocalDescription(A);return}catch(g){this.log.warn("not able to set ".concat(A.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:g,sdp:t})),A.sdp=n}}try{i?yield this.pc.setRemoteDescription(A):yield this.pc.setLocalDescription(A)}catch(n){let g="unknown error";n instanceof Error?g=n.message:typeof n=="string"&&(g=n);const o={error:g,sdp:A.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(A.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new _m(g)}})}ensureVideoDDExtensionForSVC(A,t){var i,n;if(!((i=A.ext)===null||i===void 0?void 0:i.some(o=>o.uri===RAA))){if(this.ddExtID===0){let o=0;t.media.forEach(s=>{var a;s.type==="video"&&((a=s.ext)===null||a===void 0||a.forEach(r=>{r.value>o&&(o=r.value)}))}),this.ddExtID=o+1}(n=A.ext)===null||n===void 0||n.push({value:this.ddExtID,uri:RAA})}}}function zAA(e,A,t){const i=Lz(e.mid);let n=0;e.rtp.some(g=>g.codec==="opus"?(n=g.payload,!0):!1),n>0&&(e.rtcpFb||(e.rtcpFb=[]),t.includes(i)&&!e.rtcpFb.some(g=>g.payload===n&&g.type==="nack")&&e.rtcpFb.push({payload:n,type:"nack"}),(A.includes(i)||A.length===1&&A[0]==="all")&&e.fmtp.some(g=>g.payload===n?(g.config.includes("stereo=1")||(g.config+=";stereo=1"),!0):!1))}function vVA(e){var A;const t=[],i=[],n=zQ.parse((A=e.sdp)!==null&&A!==void 0?A:"");let g=0;return n.media.forEach(o=>{var s;const a=Lz(o.mid);o.type==="audio"&&(o.rtp.some(r=>r.codec==="opus"?(g=r.payload,!0):!1),!((s=o.rtcpFb)===null||s===void 0)&&s.some(r=>r.payload===g&&r.type==="nack")&&i.push(a),o.fmtp.some(r=>r.payload===g?(r.config.includes("sprop-stereo=1")&&t.push(a),!0):!1))}),{stereoMids:t,nackMids:i}}function ZAA(e){if(e.connection){const A=e.connection.ip.indexOf(":")>=0;(e.connection.version===4&&A||e.connection.version===6&&!A)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function Lz(e){return typeof e=="number"?e.toFixed(0):e}const y3="vp8",KVA={audioPreset:l3.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Uz.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:y3,backupCodec:!0,preConnectBuffer:!1},ndA={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},gdA={deviceId:{ideal:"default"},resolution:GS.h720.resolution},FVA={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new lWA,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},xz={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Fo;(function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"})(Fo||(Fo={}));class _VA{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(A,t,i){var n;this.peerConnectionTimeout=xz.peerConnectionTimeout,this.log=ln,this.updateState=()=>{var g,o;const s=this.state,a=this.requiredTransports.map(r=>r.getConnectionState());a.every(r=>r==="connected")?this.state=Fo.CONNECTED:a.some(r=>r==="failed")?this.state=Fo.FAILED:a.some(r=>r==="connecting")?this.state=Fo.CONNECTING:a.every(r=>r==="closed")?this.state=Fo.CLOSED:a.some(r=>r==="closed")?this.state=Fo.CLOSING:a.every(r=>r==="new")&&(this.state=Fo.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Fo[s]," to ").concat(Fo[this.state]),this.logContext),(g=this.onStateChange)===null||g===void 0||g.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=eQ((n=i.loggerName)!==null&&n!==void 0?n:el.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new jAA(A,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new jAA(A,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=g=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,g,Yc.SUBSCRIBER)},this.subscriber.onDataChannel=g=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,g)},this.subscriber.onTrack=g=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,g)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=g=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,g,Yc.PUBLISHER)},this.publisher.onTrack=g=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,g)},this.publisher.onOffer=(g,o)=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,g,o)},this.state=Fo.NEW,this.connectionLock=new vr,this.remoteOfferLock=new vr}get logContext(){var A,t;return Object.assign({},(t=(A=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(A))}requirePublisher(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=A,this.updateState()}createAndSendPublisherOffer(A){return this.publisher.createAndSendOffer(A)}setPublisherAnswer(A,t){return this.publisher.setRemoteDescription(A,t)}removeTrack(A){return this.publisher.removeTrack(A)}close(){return zA(this,void 0,void 0,function*(){var A;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),(A=this.subscriber)===null||A===void 0?void 0:A.close()]),this.updateState()})}triggerIceRestart(){return zA(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(A,t){return zA(this,void 0,void 0,function*(){var i;t===Yc.PUBLISHER?yield this.publisher.addIceCandidate(A):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(A)})}createSubscriberAnswerFromOffer(A,t){return zA(this,void 0,void 0,function*(){var i,n,g;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:A.type,sdp:A.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(n=this.subscriber)===null||n===void 0?void 0:n.setRemoteDescription(A,t))?yield(g=this.subscriber)===null||g===void 0?void 0:g.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(A,t){var i;this.publisher.setConfiguration(A),(i=this.subscriber)===null||i===void 0||i.setConfiguration(A),t&&this.triggerIceRestart()}ensurePCTransportConnection(A,t){return zA(this,void 0,void 0,function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(g=>this.ensureTransportConnected(g,A,t)))}finally{n()}})}negotiate(A){return zA(this,void 0,void 0,function*(){return new tI((t,i)=>zA(this,void 0,void 0,function*(){const n=setTimeout(()=>{i(new _m("negotiation timed out"))},this.peerConnectionTimeout),g=()=>{clearTimeout(n),i(new _m("negotiation aborted"))};A.signal.addEventListener("abort",g),this.publisher.once(Tm.NegotiationStarted,()=>{A.signal.aborted||this.publisher.once(Tm.NegotiationComplete,()=>{clearTimeout(n),t()})}),yield this.publisher.negotiate(o=>{clearTimeout(n),o instanceof Error?i(o):i(new Error(String(o)))})}))})}addPublisherTransceiver(A,t){return this.publisher.addTransceiver(A,t)}addPublisherTransceiverOfKind(A,t){return this.publisher.addTransceiverOfKind(A,t)}getMidForReceiver(A){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(n=>n.receiver===A);return i==null?void 0:i.mid}addPublisherTrack(A){return this.publisher.addTrack(A)}createPublisherDataChannel(A,t){return this.publisher.createDataChannel(A,t)}getConnectedAddress(A){return A===Yc.PUBLISHER?this.publisher.getConnectedAddress():A===Yc.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const A=[];return this.isPublisherConnectionRequired&&A.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&A.push(this.subscriber),A}ensureTransportConnected(A,t){return zA(this,arguments,void 0,function(i,n){var g=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((a,r)=>zA(g,void 0,void 0,function*(){const I=()=>{this.log.warn("abort transport connection",this.logContext),Ra.clearTimeout(c),r(Mi.cancelled("room connection has been cancelled"))};n!=null&&n.signal.aborted&&I(),n==null||n.signal.addEventListener("abort",I);const c=Ra.setTimeout(()=>{n==null||n.signal.removeEventListener("abort",I),r(Mi.internal("could not establish pc connection"))},o);for(;this.state!==Fo.CONNECTED;)if(yield Ga(50),n!=null&&n.signal.aborted){r(Mi.cancelled("room connection has been cancelled"));return}Ra.clearTimeout(c),n==null||n.signal.removeEventListener("abort",I),a()}))}()})}}const odA=5e3,JVA=3e4;class tg{static fetchRegionSettings(A,t,i){return zA(this,void 0,void 0,function*(){const n=yield tg.fetchLock.lock();try{const g=yield fetch("".concat(LVA(A),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(g.ok){const o=sVA(g.headers),s=o?o*1e3:odA;return{regionSettings:yield g.json(),updatedAtInMs:Date.now(),maxAgeInMs:s}}else throw g.status===401?Mi.notAllowed("Could not fetch region settings: ".concat(g.statusText),g.status):Mi.internal("Could not fetch region settings: ".concat(g.statusText))}catch(g){throw g instanceof Mi?g:i!=null&&i.aborted?Mi.cancelled("Region fetching was aborted"):Mi.serverUnreachable("Could not fetch region settings, ".concat(g instanceof Error?"".concat(g.name,": ").concat(g.message):g))}finally{n()}})}static scheduleRefetch(A,t,i){return zA(this,void 0,void 0,function*(){const n=tg.settingsTimeouts.get(A.hostname);clearTimeout(n),tg.settingsTimeouts.set(A.hostname,setTimeout(()=>zA(this,void 0,void 0,function*(){try{const g=yield tg.fetchRegionSettings(A,t);tg.updateCachedRegionSettings(A,t,g)}catch(g){if(g instanceof Mi&&g.reason===Lg.NotAllowed){ln.debug("token is not valid, cancelling auto region refresh");return}ln.debug("auto refetching of region settings failed",{error:g}),tg.scheduleRefetch(A,t,i)}}),i))})}static updateCachedRegionSettings(A,t,i){tg.cache.set(A.hostname,i),tg.scheduleRefetch(A,t,i.maxAgeInMs)}static stopRefetch(A){const t=tg.settingsTimeouts.get(A);t&&(clearTimeout(t),tg.settingsTimeouts.delete(A))}static scheduleCleanup(A){let t=tg.connectionTrackers.get(A);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=tg.connectionTrackers.get(A);i&&i.connectionCount===0&&(ln.debug("stopping region refetch after disconnect delay",{hostname:A}),tg.stopRefetch(A)),i&&(i.cleanupTimeout=void 0)},JVA))}static cancelCleanup(A){const t=tg.connectionTrackers.get(A);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const A=this.serverUrl.hostname;let t=tg.connectionTrackers.get(A);t||(t={connectionCount:0},tg.connectionTrackers.set(A,t)),t.connectionCount++,tg.cancelCleanup(A)}notifyDisconnected(){const A=this.serverUrl.hostname,t=tg.connectionTrackers.get(A);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&tg.scheduleCleanup(A))}constructor(A,t){this.attemptedRegions=[],this.serverUrl=new URL(A),this.token=t}updateToken(A){this.token=A}isCloud(){return bS(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(A){return zA(this,void 0,void 0,function*(){return tg.fetchRegionSettings(this.serverUrl,this.token,A)})}getNextBestRegionUrl(A){return zA(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=tg.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(A),tg.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(n=>!this.attemptedRegions.find(g=>g.url===n.url));if(i.length>0){const n=i[0];return this.attemptedRegions.push(n),ln.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(A){tg.updateCachedRegionSettings(this.serverUrl,this.token,A)}}tg.cache=new Map;tg.settingsTimeouts=new Map;tg.connectionTrackers=new Map;tg.fetchLock=new vr;function LVA(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}let mr=class zh extends Error{constructor(A,t,i){super(t),this.code=A,this.message=WAA(t,zh.MAX_MESSAGE_BYTES),this.data=i?WAA(i,zh.MAX_DATA_BYTES):void 0}static fromProto(A){return new zh(A.code,A.message,A.data)}toProto(){return new XQA({code:this.code,message:this.message,data:this.data})}static builtIn(A,t){return new zh(zh.ErrorCode[A],zh.ErrorMessage[A],t)}};mr.MAX_MESSAGE_BYTES=256;mr.MAX_DATA_BYTES=15360;mr.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404};mr.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const sdA=15360;function Tz(e){return new TextEncoder().encode(e).length}function WAA(e,A){if(Tz(e)<=A)return e;let t=0,i=e.length;const n=new TextEncoder;for(;t<i;){const g=Math.floor((t+i+1)/2);n.encode(e.slice(0,g)).length<=A?t=g:i=g-1}return e.slice(0,t)}const qz=2e3;function ix(e,A){if(!A)return 0;let t,i;return"bytesReceived"in e?(t=e.bytesReceived,i=A.bytesReceived):"bytesSent"in e&&(t=e.bytesSent,i=A.bytesSent),t===void 0||i===void 0||e.timestamp===void 0||A.timestamp===void 0?0:(t-i)*8*1e3/(e.timestamp-A.timestamp)}const Yz=typeof MediaRecorder<"u";class xVA{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const TVA=Yz?MediaRecorder:xVA;class qVA extends TVA{constructor(A,t){if(!Yz)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([A.mediaStreamTrack]),t);let i,n;const g=()=>n===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",s),n==null||n.close(),n=void 0},s=a=>{n==null||n.error(a),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",s),n=void 0};this.byteStream=new ReadableStream({start:a=>{n=a,i=r=>zA(this,void 0,void 0,function*(){let I;if(r.data.arrayBuffer){const c=yield r.data.arrayBuffer();I=new Uint8Array(c)}else if(r.data.byteArray)I=r.data.byteArray;else throw new Error("no data available!");g()||a.enqueue(I)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",s)}}function YVA(){return Yz}const HVA=1e3,OVA=1e4;class adA extends st{get sender(){return this._sender}set sender(A){this._sender=A}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(A,t,i){let n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,g=arguments.length>4?arguments[4]:void 0;super(A,t,g),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Jz(()=>zA(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>zA(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(Gt.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new vr,this.pauseUpstreamLock=new vr,this.trackChangeLock=new vr,this.trackChangeLock.lock().then(o=>zA(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(A,!0)}finally{o()}})),this._constraints=A.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==st.Kind.Video)return;const{width:A,height:t}=this._mediaStreamTrack.getSettings();if(A&&t)return{width:A,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var A,t;return(t=(A=this.processor)===null||A===void 0?void 0:A.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(A,t){return zA(this,void 0,void 0,function*(){var i;if(A===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(g=>{Jm(this._mediaStreamTrack,g)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([A]),A&&(A.addEventListener("ended",this.handleEnded),A.addEventListener("mute",this.handleTrackMuteEvent),A.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=A.getConstraints());let n;if(this.processor&&A){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&($D(A,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:A,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(n??A)),!this.providedByUser&&this._mediaStreamTrack!==A&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=A,A&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(g=>{$D(n??A,g)}))})}waitForDimensions(){return zA(this,arguments,void 0,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:HVA;return function*(){var i;if(A.kind===st.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=rI())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Ga(10));const n=Date.now();for(;Date.now()-n<t;){const g=A.dimensions;if(g)return g;yield Ga(50)}throw new yE("unable to get track dimensions after timeout")}()})}setDeviceId(A){return zA(this,void 0,void 0,function*(){return this._constraints.deviceId===A&&this._mediaStreamTrack.getSettings().deviceId===Wu(A)||(this._constraints.deviceId=A,this.isMuted)?!0:(yield this.restartTrack(),Wu(A)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return zA(this,arguments,void 0,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(A.source===st.Source.ScreenShare)return;const{deviceId:i,groupId:n}=A._mediaStreamTrack.getSettings(),g=A.kind===st.Kind.Audio?"audioinput":"videoinput";return t?oa.getInstance().normalizeDeviceId(g,i,n):i}()})}mute(){return zA(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return zA(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(A,t){return zA(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new yE("unable to replace an unpublished track");let n,g;return typeof t=="boolean"?n=t:t!==void 0&&(n=t.userProvidedTrack,g=t.stopProcessor),this.providedByUser=n??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(A),g&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(A){return zA(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{A||(A=this._constraints);const{deviceId:i,facingMode:n}=A,g=BWA(A,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:A}));const o={audio:!1,video:!1};this.kind===st.Kind.Video?o.video=i||n?{deviceId:i,facingMode:n}:!0:o.audio=i?Object.assign({deviceId:i},g):!0,this.attachedElements.forEach(r=>{Jm(this.mediaStreamTrack,r)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===st.Kind.Video&&(yield a.applyConstraints(g)),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=A,this.emit(Gt.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(A){this.log.debug("setting ".concat(this.kind," track ").concat(A?"muted":"unmuted"),this.logContext),!(this.isMuted===A&&this._mediaStreamTrack.enabled!==A)&&(this.isMuted=A,this._mediaStreamTrack.enabled=!A,this.emit(A?Gt.Muted:Gt.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const A=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return zA(this,void 0,void 0,function*(){yield A.handleAppVisibilityChanged.call(this),AdA()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var A;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(A=this.processor)===null||A===void 0||A.destroy(),this.processor=void 0}pauseUpstream(){return zA(this,void 0,void 0,function*(){var A;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(Gt.UpstreamPaused,this);const i=rI();if((i==null?void 0:i.name)==="Safari"&&fB(i.version,"12.0")<0)throw new bz("pauseUpstream is not supported on Safari < 12.");((A=this.sender.transport)===null||A===void 0?void 0:A.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return zA(this,void 0,void 0,function*(){var A;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(Gt.UpstreamResumed,this),((A=this.sender.transport)===null||A===void 0?void 0:A.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return zA(this,void 0,void 0,function*(){var A;return!((A=this.sender)===null||A===void 0)&&A.getStats?yield this.sender.getStats():void 0})}setProcessor(A){return zA(this,arguments,void 0,function(t){var i=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var g;const o=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const s=document.createElement(i.kind),a={kind:i.kind,track:i._mediaStreamTrack,element:s,audioContext:i.audioContext};if(yield t.init(a),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if($D(i._mediaStreamTrack,s),s.muted=!0,s.play().catch(r=>{r instanceof DOMException&&r.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:r})),setTimeout(()=>{s.play().catch(I=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:I}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:r}))}),i.processor=t,i.processorElement=s,i.processor.processedTrack){for(const r of i.attachedElements)r!==i.processorElement&&n&&(Jm(i._mediaStreamTrack,r),$D(i.processor.processedTrack,r));yield(g=i.sender)===null||g===void 0?void 0:g.replaceTrack(i.processor.processedTrack)}i.emit(Gt.TrackProcessorUpdate,i.processor)}finally{o()}}()})}getProcessor(){return this.processor}stopProcessor(){return zA(this,arguments,void 0,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const i=yield A.trackChangeLock.lock();try{yield A.internalStopProcessor(t)}finally{i()}}()})}internalStopProcessor(){return zA(this,arguments,void 0,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,n;A.processor&&(A.log.debug("stopping processor",A.logContext),(i=A.processor.processedTrack)===null||i===void 0||i.stop(),yield A.processor.destroy(),A.processor=void 0,t||((n=A.processorElement)===null||n===void 0||n.remove(),A.processorElement=void 0),yield A._mediaStreamTrack.applyConstraints(A._constraints),yield A.setMediaStreamTrack(A._mediaStreamTrack,!0),A.emit(Gt.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!YVA()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new qVA(this,{mimeType:t})}this.localTrackRecorder.start(A),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},OVA)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var A;return(A=this.localTrackRecorder)===null||A===void 0?void 0:A.byteStream}getPreConnectBufferMimeType(){var A;return(A=this.localTrackRecorder)===null||A===void 0?void 0:A.mimeType}}class a_ extends adA{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(A,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,n=arguments.length>3?arguments[3]:void 0,g=arguments.length>4?arguments[4]:void 0;super(A,st.Kind.Audio,t,i,g),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>zA(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(s){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:s}));return}o&&this.prevStats&&(this._currentBitrate=ix(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Gt.AudioTrackFeatureUpdate,this,ia.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Gt.AudioTrackFeatureUpdate,this,ia.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const A=Object.create(null,{mute:{get:()=>super.mute}});return zA(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===st.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield A.mute.call(this),this)}finally{t()}})}unmute(){const A=Object.create(null,{unmute:{get:()=>super.unmute}});return zA(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Wu(this._constraints.deviceId);return this.source===st.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield A.unmute.call(this),this}finally{t()}})}restartTrack(A){return zA(this,void 0,void 0,function*(){let t;if(A){const i=vz({audio:A});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(A){const t=Object.create(null,{restart:{get:()=>super.restart}});return zA(this,void 0,void 0,function*(){const i=yield t.restart.call(this,A);return this.checkForSilence(),i})}startMonitor(){iI()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},qz)))}setProcessor(A){return zA(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!pB()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const n={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(A.name),this.logContext),yield A.init(n),this.processor=A,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(Gt.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(A){this.audioContext=A}getSenderStats(){return zA(this,void 0,void 0,function*(){var A;if(!(!((A=this.sender)===null||A===void 0)&&A.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(n=>{n.type==="outbound-rtp"&&(i={type:"audio",streamId:n.id,packetsSent:n.packetsSent,packetsLost:n.packetsLost,bytesSent:n.bytesSent,timestamp:n.timestamp,roundTripTime:n.roundTripTime,jitter:n.jitter})}),i})}checkForSilence(){return zA(this,void 0,void 0,function*(){const A=yield VuA(this);return A&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(Gt.AudioSilenceDetected)),A})}}function PVA(e,A,t){switch(e.kind){case"audio":return new a_(e,A,!1,void 0,t);case"video":return new r_(e,A,!1,t);default:throw new yE("unsupported track type: ".concat(e.kind))}}const jVA=Object.values(GS),zVA=Object.values(B3),ZVA=Object.values(Uz),WVA=[GS.h180,GS.h360],VVA=[B3.h180,B3.h360],XVA=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>{var i,n;return new Ug(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=e.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((n=t.fps)!==null&&n!==void 0?n:30))))),t.fps,e.encoding.priority)}),D3=["q","h","f"];function m3(e,A,t,i){var n,g;let o=i==null?void 0:i.videoEncoding;e&&(o=i==null?void 0:i.screenShareEncoding);const s=i==null?void 0:i.simulcast,a=i==null?void 0:i.scalabilityMode,r=i==null?void 0:i.videoCodec;if(!o&&!s&&!a||!A||!t)return[{}];o||(o=A9A(e,A,t,r),ln.debug("using video encoding",o));const I=o.maxFramerate,c=new Ug(A,t,o.maxBitrate,o.maxFramerate,o.priority);if(a&&Hc(r)){const Q=new rdA(a),h=[];if(Q.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const d=rI();if(EN()||pB()||(d==null?void 0:d.name)==="Chrome"&&fB(d==null?void 0:d.version,"113")<0){const p=Q.suffix=="h"?2:3,y=ZWA(d);for(let m=0;m<Q.spatial;m+=1)h.push({rid:D3[2-m],maxBitrate:o.maxBitrate/Math.pow(p,m),maxFramerate:c.encoding.maxFramerate,scaleResolutionDownBy:y?Math.pow(2,m):void 0});h[0].scalabilityMode=a}else h.push({maxBitrate:o.maxBitrate,maxFramerate:c.encoding.maxFramerate,scalabilityMode:a});return c.encoding.priority&&(h[0].priority=c.encoding.priority,h[0].networkPriority=c.encoding.priority),ln.debug("using svc encoding",{encodings:h}),h}if(!s)return[o];let l=[];e?l=(n=XAA(i==null?void 0:i.screenShareSimulcastLayers))!==null&&n!==void 0?n:VAA(e,c):l=(g=XAA(i==null?void 0:i.videoSimulcastLayers))!==null&&g!==void 0?g:VAA(e,c);let B;if(l.length>0){const Q=l[0];l.length>1&&([,B]=l);const h=Math.max(A,t);if(h>=960&&B)return gY(A,t,[Q,B,c],I);if(h>=480)return gY(A,t,[Q,c],I)}return gY(A,t,[c])}function $VA(e,A,t){var i,n,g,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;A!==t.backupCodec.codec&&ln.warn("requested a different codec than specified as backup",{serverRequested:A,backup:t.backupCodec.codec}),t.videoCodec=A,t.videoEncoding=t.backupCodec.encoding;const s=e.mediaStreamTrack.getSettings(),a=(i=s.width)!==null&&i!==void 0?i:(n=e.dimensions)===null||n===void 0?void 0:n.width,r=(g=s.height)!==null&&g!==void 0?g:(o=e.dimensions)===null||o===void 0?void 0:o.height;return e.source===st.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),m3(e.source===st.Source.ScreenShare,a,r,t)}function A9A(e,A,t,i){const n=e9A(e,A,t);let{encoding:g}=n[0];const o=Math.max(A,t);for(let s=0;s<n.length;s+=1){const a=n[s];if(g=a.encoding,a.width>=o)break}if(i)switch(i){case"av1":case"h265":g=Object.assign({},g),g.maxBitrate=g.maxBitrate*.7;break;case"vp9":g=Object.assign({},g),g.maxBitrate=g.maxBitrate*.85;break}return g}function e9A(e,A,t){if(e)return ZVA;const i=A>t?A/t:t/A;return Math.abs(i-16/9)<Math.abs(i-4/3)?jVA:zVA}function VAA(e,A){if(e)return XVA(A);const{width:t,height:i}=A,n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?WVA:VVA}function gY(e,A,t,i){const n=[];if(t.forEach((g,o)=>{if(o>=D3.length)return;const s=Math.min(e,A),r={rid:D3[o],scaleResolutionDownBy:Math.max(1,s/Math.min(g.width,g.height)),maxBitrate:g.encoding.maxBitrate},I=i&&g.encoding.maxFramerate?Math.min(i,g.encoding.maxFramerate):g.encoding.maxFramerate;I&&(r.maxFramerate=I);const c=Cf()||o===0;g.encoding.priority&&c&&(r.priority=g.encoding.priority,r.networkPriority=g.encoding.priority),n.push(r)}),pB()&&tdA()==="ios"){let g;n.forEach(s=>{g?s.maxFramerate&&s.maxFramerate>g&&(g=s.maxFramerate):g=s.maxFramerate});let o=!0;n.forEach(s=>{var a;s.maxFramerate!=g&&(o&&(o=!1,ln.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ln.info('Setting framerate of encoding "'.concat((a=s.rid)!==null&&a!==void 0?a:"",'" to ').concat(g)),s.maxFramerate=g)})}return n}function XAA(e){if(e)return e.sort((A,t)=>{const{encoding:i}=A,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class rdA{constructor(A){const t=A.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var A;return"L".concat(this.spatial,"T").concat(this.temporal).concat((A=this.suffix)!==null&&A!==void 0?A:"")}}function t9A(e){return e.source===st.Source.ScreenShare||e.constraints.height&&Wu(e.constraints.height)>=1080?"maintain-resolution":"balanced"}const i9A=5e3;class r_ extends adA{get sender(){return this._sender}set sender(A){this._sender=A,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(A,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,n=arguments.length>3?arguments[3]:void 0;super(A,st.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>zA(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let g;try{g=yield this.getSenderStats()}catch(a){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const o=new Map(g.map(a=>[a.rid,a])),s=g.some(a=>a.qualityLimitationReason==="cpu");if(s!==this.isCpuConstrained&&(this.isCpuConstrained=s,this.isCpuConstrained&&this.emit(Gt.CpuConstrained)),this.prevStats){let a=0;o.forEach((r,I)=>{var c;const l=(c=this.prevStats)===null||c===void 0?void 0:c.get(I);a+=ix(r,l)}),this._currentBitrate=a}this.prevStats=o}),this.senderLock=new vr}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(A){var t;if(this.signalClient=A,!iI())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},qz))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(A=>{A.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const A=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return zA(this,void 0,void 0,function*(){var t,i,n,g,o;yield A.pauseUpstream.call(this);try{for(var s=!0,a=fE(this.simulcastCodecs.values()),r;r=yield a.next(),t=r.done,!t;s=!0)g=r.value,s=!1,yield(o=g.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(I){i={error:I}}finally{try{!s&&!t&&(n=a.return)&&(yield n.call(a))}finally{if(i)throw i.error}}})}resumeUpstream(){const A=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return zA(this,void 0,void 0,function*(){var t,i,n,g,o;yield A.resumeUpstream.call(this);try{for(var s=!0,a=fE(this.simulcastCodecs.values()),r;r=yield a.next(),t=r.done,!t;s=!0){g=r.value,s=!1;const I=g;yield(o=I.sender)===null||o===void 0?void 0:o.replaceTrack(I.mediaStreamTrack)}}catch(I){i={error:I}}finally{try{!s&&!t&&(n=a.return)&&(yield n.call(a))}finally{if(i)throw i.error}}})}mute(){const A=Object.create(null,{mute:{get:()=>super.mute}});return zA(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===st.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield A.mute.call(this),this)}finally{t()}})}unmute(){const A=Object.create(null,{unmute:{get:()=>super.unmute}});return zA(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===st.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield A.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(A){super.setTrackMuted(A);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!A}getSenderStats(){return zA(this,void 0,void 0,function*(){var A;if(!(!((A=this.sender)===null||A===void 0)&&A.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(n=>{var g;if(n.type==="outbound-rtp"){const o={type:"video",streamId:n.id,frameHeight:n.frameHeight,frameWidth:n.frameWidth,framesPerSecond:n.framesPerSecond,framesSent:n.framesSent,firCount:n.firCount,pliCount:n.pliCount,nackCount:n.nackCount,packetsSent:n.packetsSent,bytesSent:n.bytesSent,qualityLimitationReason:n.qualityLimitationReason,qualityLimitationDurations:n.qualityLimitationDurations,qualityLimitationResolutionChanges:n.qualityLimitationResolutionChanges,rid:(g=n.rid)!==null&&g!==void 0?g:n.id,retransmittedPacketsSent:n.retransmittedPacketsSent,targetBitrate:n.targetBitrate,timestamp:n.timestamp},s=i.get(n.remoteId);s&&(o.jitter=s.jitter,o.packetsLost=s.packetsLost,o.roundTripTime=s.roundTripTime),t.push(o)}}),t.sort((n,g)=>{var o,s;return((o=g.frameWidth)!==null&&o!==void 0?o:0)-((s=n.frameWidth)!==null&&s!==void 0?s:0)}),t})}setPublishingQuality(A){const t=[];for(let i=PI.LOW;i<=PI.HIGH;i+=1)t.push(new Mz({quality:i,enabled:i<=A}));this.log.debug("setting publishing quality. max quality ".concat(A),this.logContext),this.setPublishingLayers(Hc(this.codec),t)}restartTrack(A){return zA(this,void 0,void 0,function*(){var t,i,n,g,o;let s;if(A){const c=vz({video:A});typeof c.video!="boolean"&&(s=c.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var a=!0,r=fE(this.simulcastCodecs.values()),I;I=yield r.next(),t=I.done,!t;a=!0){g=I.value,a=!1;const c=g;c.sender&&((o=c.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(c.mediaStreamTrack=this.mediaStreamTrack.clone(),yield c.sender.replaceTrack(c.mediaStreamTrack))}}catch(c){i={error:c}}finally{try{!a&&!t&&(n=r.return)&&(yield n.call(r))}finally{if(i)throw i.error}}})}setProcessor(A){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return zA(this,arguments,void 0,function(i){var n=this;let g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var o,s,a,r,I,c;if(yield t.setProcessor.call(n,i,g),!((I=n.processor)===null||I===void 0)&&I.processedTrack)try{for(var l=!0,B=fE(n.simulcastCodecs.values()),Q;Q=yield B.next(),o=Q.done,!o;l=!0)r=Q.value,l=!1,yield(c=r.sender)===null||c===void 0?void 0:c.replaceTrack(n.processor.processedTrack)}catch(h){s={error:h}}finally{try{!l&&!o&&(a=B.return)&&(yield a.call(B))}finally{if(s)throw s.error}}}()})}setDegradationPreference(A){return zA(this,void 0,void 0,function*(){if(this.degradationPreference=A,this.sender)try{this.log.debug("setting degradationPreference to ".concat(A),this.logContext);const t=this.sender.getParameters();t.degradationPreference=A,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(A,t){if(this.simulcastCodecs.has(A)){this.log.error("".concat(A," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:A,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(A,i),i}setSimulcastTrackSender(A,t){const i=this.simulcastCodecs.get(A);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},i9A))}setPublishingCodecs(A){return zA(this,void 0,void 0,function*(){var t,i,n,g,o,s,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:A,currentCodec:this.codec})),!this.codec&&A.length>0)return yield this.setPublishingLayers(Hc(A[0].codec),A[0].qualities),[];this.subscribedCodecs=A;const r=[];try{for(t=!0,i=fE(A);n=yield i.next(),g=n.done,!g;t=!0){a=n.value,t=!1;const I=a;if(!this.codec||this.codec===I.codec)yield this.setPublishingLayers(Hc(I.codec),I.qualities);else{const c=this.simulcastCodecs.get(I.codec);if(this.log.debug("try setPublishingCodec for ".concat(I.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:c})),!c||!c.sender){for(const l of I.qualities)if(l.enabled){r.push(I.codec);break}}else c.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(I.codec),this.logContext),yield $AA(c.sender,c.encodings,I.qualities,this.senderLock,Hc(I.codec),this.log,this.logContext))}}}catch(I){o={error:I}}finally{try{!t&&!g&&(s=i.return)&&(yield s.call(i))}finally{if(o)throw o.error}}return r})}setPublishingLayers(A,t){return zA(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield $AA(this.sender,this.encodings,t,this.senderLock,A,this.log,this.logContext))})}prioritizePerformance(){return zA(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const A=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((i,n)=>{var g;return Object.assign(Object.assign({},i),{active:n===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((g=this.mediaStreamTrack.getSettings().height)!==null&&g!==void 0?g:360)/360)),scalabilityMode:n===0&&Hc(this.codec)?"L1T3":void 0,maxFramerate:n===0?15:0,maxBitrate:n===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{A()}})}handleAppVisibilityChanged(){const A=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return zA(this,void 0,void 0,function*(){yield A.handleAppVisibilityChanged.call(this),AdA()&&this.isInBackground&&this.source===st.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function $AA(e,A,t,i,n,g,o){return zA(this,void 0,void 0,function*(){const s=yield i.lock();g.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:t,senderEncodings:A}));try{const a=e.getParameters(),{encodings:r}=a;if(!r)return;if(r.length!==A.length){g.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:r,senderEncodings:A}));return}let I=!1;!1&&r[0].scalabilityMode||(n&&t.some(B=>B.enabled)&&t.forEach(B=>B.enabled=!0),r.forEach((l,B)=>{var Q;let h=(Q=l.rid)!==null&&Q!==void 0?Q:"";h===""&&(h="q");const d=IdA(h),p=t.find(y=>y.quality===d);p&&l.active!==p.enabled&&(I=!0,l.active=p.enabled,g.debug("setting layer ".concat(p.quality," to ").concat(l.active?"enabled":"disabled"),o),Cf()&&(p.enabled?(l.scaleResolutionDownBy=A[B].scaleResolutionDownBy,l.maxBitrate=A[B].maxBitrate,l.maxFrameRate=A[B].maxFrameRate):(l.scaleResolutionDownBy=4,l.maxBitrate=10,l.maxFrameRate=2)))})),I&&(a.encodings=r,g.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:a.encodings})),yield e.setParameters(a))}finally{s()}})}function IdA(e){switch(e){case"f":return PI.HIGH;case"h":return PI.MEDIUM;case"q":return PI.LOW;default:return PI.HIGH}}function AeA(e,A,t,i){if(!t)return[new Zu({quality:PI.HIGH,width:e,height:A,bitrate:0,ssrc:0})];if(i){const n=t[0].scalabilityMode,g=new rdA(n),o=[],s=g.suffix=="h"?1.5:2,a=g.suffix=="h"?2:3;for(let r=0;r<g.spatial;r+=1)o.push(new Zu({quality:Math.min(PI.HIGH,g.spatial-1)-r,width:Math.ceil(e/Math.pow(s,r)),height:Math.ceil(A/Math.pow(s,r)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(a,r)):0,ssrc:0}));return o}return t.map(n=>{var g,o,s;const a=(g=n.scaleResolutionDownBy)!==null&&g!==void 0?g:1;let r=IdA((o=n.rid)!==null&&o!==void 0?o:"");return new Zu({quality:r,width:Math.ceil(e/a),height:Math.ceil(A/a),bitrate:(s=n.maxBitrate)!==null&&s!==void 0?s:0,ssrc:0})})}const eeA="_lossy",teA="_reliable",n9A=2*1e3,oY="leave-reconnect",g9A=3e4,o9A=8*1024,s9A=256*1024;var kC;(function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"})(kC||(kC={}));class a9A extends RB.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(A){var t;super(),this.options=A,this.rtcConfig={},this.peerConnectionTimeout=xz.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=kC.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=ln,this.reliableDataSequence=1,this.reliableMessageBuffer=new qAA,this.reliableReceivedState=new MVA(g9A),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>zA(this,[i],void 0,function(n){var g=this;let{channel:o}=n;return function*(){if(o){if(o.label===teA)g.reliableDCSub=o;else if(o.label===eeA)g.lossyDCSub=o;else return;g.log.debug("on data channel ".concat(o.id,", ").concat(o.label),g.logContext),o.onmessage=g.handleDataMessage}}()}),this.handleDataMessage=i=>zA(this,void 0,void 0,function*(){var n,g,o,s,a;const r=yield this.dataProcessLock.lock();try{let I;if(i.data instanceof ArrayBuffer)I=i.data;else if(i.data instanceof Blob)I=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=Dr.fromBinary(new Uint8Array(I));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}if(((n=c.value)===null||n===void 0?void 0:n.case)==="speaker")this.emit(_t.ActiveSpeakersUpdate,c.value.value.speakers);else if(((g=c.value)===null||g===void 0?void 0:g.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const l=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(c.value.value.encryptedValue,c.value.value.iv,c.participantIdentity,c.value.value.keyIndex),B=ZQA.fromBinary(l.payload),Q=new Dr({value:B.value,participantIdentity:c.participantIdentity,participantSid:c.participantSid});((s=Q.value)===null||s===void 0?void 0:s.case)==="user"&&ieA(Q,Q.value.value),this.emit(_t.DataPacketReceived,Q,c.value.value.encryptionType)}else((a=c.value)===null||a===void 0?void 0:a.case)==="user"&&ieA(c,c.value.value),this.emit(_t.DataPacketReceived,c,Js.NONE)}finally{r()}}),this.handleDataError=i=>{const g=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(g,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(g),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const g=i.currentTarget.maxRetransmits===0?Mn.LOSSY:Mn.RELIABLE;this.updateAndEmitDCBufferStatus(g)},this.handleDisconnect=(i,n)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const g=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(_t.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(s===null){g(o);return}i===oY&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ra.setTimeout(()=>this.attemptReconnect(n).finally(()=>this.reconnectTimeout=void 0),s)},this.waitForRestarted=()=>new Promise((i,n)=>{this.pcState===kC.Connected&&i();const g=()=>{this.off(_t.Disconnected,o),i()},o=()=>{this.off(_t.Restarted,g),n()};this.once(_t.Restarted,g),this.once(_t.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{if(i===Mn.RELIABLE){const g=this.dataChannelForKind(i);g&&this.reliableMessageBuffer.alignBufferedAmount(g.bufferedAmount)}const n=this.isBufferStatusLow(i);typeof n<"u"&&n!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,n),this.emit(_t.DCBufferStatusChanged,n,i))},this.isBufferStatusLow=i=>{const n=this.dataChannelForKind(i);if(n)return n.bufferedAmount<=n.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>zA(this,void 0,void 0,function*(){!this.url||!(yield fetch(QN(this.url),{method:"HEAD"}).then(n=>n.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===_g.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===_g.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Ph.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>zA(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(QN(this.url),{method:"HEAD"}),Ga(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=eQ((t=A.loggerName)!==null&&t!==void 0?t:el.Engine),this.loggerOptions={loggerName:A.loggerName,loggerContextCb:()=>this.logContext},this.client=new Fz(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new vr,this.dataProcessLock=new vr,this.dcBufferStatus=new Map([[Mn.LOSSY,!0],[Mn.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(_t.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(_t.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(_t.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(_t.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(_t.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(_t.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(_t.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(_t.SignalRequestResponse,i)}get logContext(){var A,t,i,n,g,o;return{room:(t=(A=this.latestJoinResponse)===null||A===void 0?void 0:A.room)===null||t===void 0?void 0:t.name,roomID:(n=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||n===void 0?void 0:n.sid,participant:(o=(g=this.latestJoinResponse)===null||g===void 0?void 0:g.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(A,t,i,n){return zA(this,arguments,void 0,function(g,o,s,a){var r=this;let I=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){r.url=g,r.token=o,r.signalOpts=s,r.maxJoinAttempts=s.maxRetries;try{r.joinAttempts+=1,r.setupSignalClientCallbacks();const c=yield r.client.join(g,o,s,a,I);return r._isClosed=!1,r.latestJoinResponse=c,r.subscriberPrimary=c.subscriberPrimary,r.pcManager||(yield r.configure(c,!I)),(!r.subscriberPrimary||c.fastPublish)&&r.negotiate().catch(l=>{ln.error(l,r.logContext)}),r.registerOnLineListener(),r.clientConfiguration=c.clientConfiguration,r.emit(_t.SignalConnected,c),c}catch(c){if(c instanceof Mi){if(c.reason===Lg.ServerUnreachable){if(r.log.warn("Couldn't connect to server, attempt ".concat(r.joinAttempts," of ").concat(r.maxJoinAttempts),r.logContext),r.joinAttempts<r.maxJoinAttempts)return r.join(g,o,s,a,I)}else if(c.reason===Lg.ServiceNotFound)return r.log.warn("Initial connection failed: ".concat(c.message," – Retrying")),r.join(g,o,s,a,!0)}throw c}}()})}close(){return zA(this,void 0,void 0,function*(){const A=yield this.closingLock.lock();if(this.isClosed){A();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(_t.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{A()}})}cleanupPeerConnections(){return zA(this,void 0,void 0,function*(){var A;yield(A=this.pcManager)===null||A===void 0?void 0:A.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new qAA,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return zA(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(A){if(this.pendingTrackResolvers[A.cid])throw new yE("a track with the same ID has already been published");return new Promise((t,i)=>{const n=setTimeout(()=>{delete this.pendingTrackResolvers[A.cid],i(Mi.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[A.cid]={resolve:g=>{clearTimeout(n),t(g)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(A)})}removeTrack(A){if(A.track&&this.pendingTrackResolvers[A.track.id]){const{reject:t}=this.pendingTrackResolvers[A.track.id];t&&t(),delete this.pendingTrackResolvers[A.track.id]}try{return this.pcManager.removeTrack(A),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(A,t){this.client.sendMuteTrack(A,t)}get dataSubscriberReadyState(){var A;return(A=this.reliableDCSub)===null||A===void 0?void 0:A.readyState}getConnectedServerAddress(){return zA(this,void 0,void 0,function*(){var A;return(A=this.pcManager)===null||A===void 0?void 0:A.getConnectedAddress()})}setRegionUrlProvider(A){this.regionUrlProvider=A}configure(A,t){return zA(this,void 0,void 0,function*(){var i,n;if(this.pcManager&&this.pcManager.currentState!==Fo.NEW)return;this.participantSid=(i=A.participant)===null||i===void 0?void 0:i.sid;const g=this.makeRTCConfiguration(A);this.pcManager=new _VA(g,t?"publisher-only":A.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(_t.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(o,s)=>{this.client.sendIceCandidate(o,s)},this.pcManager.onPublisherOffer=(o,s)=>{this.client.sendOffer(o,s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(o,s,a)=>zA(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(o),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),o===Fo.CONNECTED){const c=this.pcState===kC.New;this.pcState=kC.Connected,c&&this.emit(_t.Connected,A)}else o===Fo.FAILED&&(this.pcState===kC.Connected||this.pcState===kC.Reconnecting)&&(this.pcState=kC.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Ph.RR_SUBSCRIBER_FAILED:Ph.RR_PUBLISHER_FAILED));const r=this.client.isDisconnected||this.client.currentState===_g.RECONNECTING,I=[Fo.FAILED,Fo.CLOSING,Fo.CLOSED].includes(o);r&&I&&!this._isClosed&&this.emit(_t.Offline)}),this.pcManager.onTrack=o=>{o.streams.length!==0&&this.emit(_t.MediaTrackAdded,o.track,o.streams[0],o.receiver)},r9A((n=A.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(A,t,i)=>zA(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:A.type,sdp:A.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(A,t))}),this.client.onTrickle=(A,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:A,target:t})),this.pcManager.addIceCandidate(A,t))},this.client.onOffer=(A,t,i)=>zA(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const n=yield this.pcManager.createSubscriberAnswerFromOffer(A,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=A=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:A.cid,track:(t=A.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[A.cid]){this.log.error("missing track resolver for ".concat(A.cid),Object.assign(Object.assign({},this.logContext),{cid:A.cid}));return}const{resolve:i}=this.pendingTrackResolvers[A.cid];delete this.pendingTrackResolvers[A.cid],i(A.track)},this.client.onLocalTrackUnpublished=A=>{this.emit(_t.LocalTrackUnpublished,A)},this.client.onLocalTrackSubscribed=A=>{this.emit(_t.LocalTrackSubscribed,A)},this.client.onTokenRefresh=A=>{var t;this.token=A,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(A)},this.client.onRemoteMuteChanged=(A,t)=>{this.emit(_t.RemoteMute,A,t)},this.client.onSubscribedQualityUpdate=A=>{this.emit(_t.SubscribedQualityUpdate,A)},this.client.onRoomMoved=A=>{var t;this.participantSid=(t=A.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=A.room),this.emit(_t.RoomMoved,A)},this.client.onMediaSectionsRequirement=A=>{var t,i;const n={direction:"recvonly"};for(let g=0;g<A.numAudios;g++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",n);for(let g=0;g<A.numVideos;g++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",n);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",Ph.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=A=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:A==null?void 0:A.reason})),A.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:odA,regionSettings:A.regions})),A.action){case Km.DISCONNECT:this.emit(_t.Disconnected,A==null?void 0:A.reason),this.close();break;case Km.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(oY);break;case Km.RESUME:this.handleDisconnect(oY)}}}makeRTCConfiguration(A){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),A.iceServers&&!i.iceServers){const n=[];A.iceServers.forEach(g=>{const o={urls:g.urls};g.username&&(o.username=g.username),g.credential&&(o.credential=g.credential),n.push(o)}),i.iceServers=n}return A.clientConfiguration&&A.clientConfiguration.forceRelay===cN.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(eeA,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(teA,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const A=this.dataChannelForKind(Mn.LOSSY);if(A){const t=this.lossyDataStatByterate/10;A.bufferedAmountLowThreshold=Math.min(Math.max(t,o9A),s9A)}},1e3))}createSender(A,t,i){return zA(this,void 0,void 0,function*(){if(u3())return yield this.createTransceiverRTCRtpSender(A,t,i);if(d3())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(A.mediaStreamTrack);throw new zo("Required webRTC APIs not supported on this device")})}createSimulcastSender(A,t,i,n){return zA(this,void 0,void 0,function*(){if(u3())return this.createSimulcastTransceiverSender(A,t,i,n);if(d3())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(A.mediaStreamTrack);throw new zo("Cannot stream on this device")})}createTransceiverRTCRtpSender(A,t,i){return zA(this,void 0,void 0,function*(){if(!this.pcManager)throw new zo("publisher is closed");const n=[];A.mediaStream&&n.push(A.mediaStream),Fd(A)&&(A.codec=t.videoCodec);const g={direction:"sendonly",streams:n};return i&&(g.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(A.mediaStreamTrack,g)).sender})}createSimulcastTransceiverSender(A,t,i,n){return zA(this,void 0,void 0,function*(){if(!this.pcManager)throw new zo("publisher is closed");const g={direction:"sendonly"};n&&(g.sendEncodings=n);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,g);if(i.videoCodec)return A.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(A){return zA(this,void 0,void 0,function*(){if(!this.pcManager)throw new zo("publisher is closed");return this.pcManager.addPublisherTrack(A)})}attemptReconnect(A){return zA(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed){if(this.attemptingReconnect){ln.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===cN.DISABLED||((n=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&n!==void 0?n:Fo.NEW)===Fo.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(A),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(g){this.reconnectAttempts+=1;let o=!0;g instanceof zo?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:g})),o=!1):g instanceof zy||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Ph.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(_t.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(A){try{return this.reconnectPolicy.nextRetryDelayInMs(A)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(A){return zA(this,void 0,void 0,function*(){var t,i,n;try{if(!this.url||!this.token)throw new zo("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(_t.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let g;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new zy;g=yield this.join(A??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(o){throw o instanceof Mi&&o.reason===Lg.NotAllowed?new zo("could not reconnect, token might be expired"):new zy}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(_t.SignalRestarted,g),yield this.waitForPCReconnected(),this.client.currentState!==_g.CONNECTED)throw new zy("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(_t.Restarted)}catch(g){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),g}})}resumeConnection(A){return zA(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new zo("could not reconnect, url or token not saved");if(!this.pcManager)throw new zo("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(_t.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,A)}catch(n){let g="";throw n instanceof Error&&(g=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof Mi&&n.reason===Lg.NotAllowed?new zo("could not reconnect, token might be expired"):n instanceof Mi&&n.reason===Lg.LeaveRequest?n:new zy(g)}if(this.emit(_t.SignalResumed),i){const n=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(n),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==_g.CONNECTED)throw new zy("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(_t.Resumed)})}waitForPCInitialConnection(A,t){return zA(this,void 0,void 0,function*(){if(!this.pcManager)throw new zo("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,A)})}waitForPCReconnected(){return zA(this,void 0,void 0,function*(){this.pcState=kC.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ga(n9A),!this.pcManager)throw new zo("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=kC.Connected}catch(A){throw this.pcState=kC.Disconnected,Mi.internal("could not establish PC connection, ".concat(A.message))}})}publishRpcResponse(A,t,i,n){return zA(this,void 0,void 0,function*(){const g=new Dr({destinationIdentities:[A],kind:Mn.RELIABLE,value:{case:"rpcResponse",value:new mz({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(g,Mn.RELIABLE)})}publishRpcAck(A,t){return zA(this,void 0,void 0,function*(){const i=new Dr({destinationIdentities:[A],kind:Mn.RELIABLE,value:{case:"rpcAck",value:new Dz({requestId:t})}});yield this.sendDataPacket(i,Mn.RELIABLE)})}sendDataPacket(A,t){return zA(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const g=uVA(A);if(g){const o=yield this.e2eeManager.encryptData(g.toBinary());A.value={case:"encryptedPacket",value:new zQA({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}t===Mn.RELIABLE&&(A.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=A.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===Mn.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:A.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(A){return zA(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Mn.RELIABLE);const t=this.dataChannelForKind(Mn.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(A),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(Mn.RELIABLE)})}waitForBufferStatusLow(A){return new tI((t,i)=>zA(this,void 0,void 0,function*(){if(this.isBufferStatusLow(A))t();else{const n=()=>i(new zo("engine closed"));for(this.once(_t.Closing,n);!this.dcBufferStatus.get(A);)yield Ga(10);this.off(_t.Closing,n),t()}}))}ensureDataTransportConnected(A){return zA(this,arguments,void 0,function(t){var i=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var g;if(!i.pcManager)throw new zo("PC manager is closed");const o=n?i.pcManager.subscriber:i.pcManager.publisher,s=n?"Subscriber":"Publisher";if(!o)throw Mi.internal("".concat(s," connection not set"));let a=!1;!n&&!i.dataChannelForKind(t,n)&&(i.createDataChannels(),a=!0),!a&&!n&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&i.negotiate().catch(c=>{ln.error(c,i.logContext)});const r=i.dataChannelForKind(t,n);if((r==null?void 0:r.readyState)==="open")return;const I=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<I;){if(o.isICEConnected&&((g=i.dataChannelForKind(t,n))===null||g===void 0?void 0:g.readyState)==="open")return;yield Ga(50)}throw Mi.internal("could not establish ".concat(s," connection, state: ").concat(o.getICEConnectionState()))}()})}ensurePublisherConnected(A){return zA(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(A,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Fo.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return zA(this,void 0,void 0,function*(){return new tI((A,t)=>zA(this,void 0,void 0,function*(){if(!this.pcManager){t(new _m("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),A()};this.isClosed&&t(new _m("cannot negotiate on closed engine")),this.on(_t.Closing,n),this.pcManager.publisher.once(Tm.RTPVideoPayloadTypes,g=>{const o=new Map;g.forEach(s=>{const a=s.codec.toLowerCase();AVA(a)&&o.set(s.payload,a)}),this.emit(_t.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),A()}catch(g){g instanceof _m&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ph.RR_UNKNOWN),g instanceof Error?t(g):t(new Error(String(g)))}finally{this.off(_t.Closing,n)}}))})}dataChannelForKind(A,t){if(t){if(A===Mn.LOSSY)return this.lossyDCSub;if(A===Mn.RELIABLE)return this.reliableDCSub}else{if(A===Mn.LOSSY)return this.lossyDC;if(A===Mn.RELIABLE)return this.reliableDC}}sendSyncState(A,t){var i,n,g,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.publisher.getLocalDescription(),a=this.pcManager.publisher.getRemoteDescription(),r=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),I=(n=this.pcManager.subscriber)===null||n===void 0?void 0:n.getLocalDescription(),c=(o=(g=this.signalOpts)===null||g===void 0?void 0:g.autoSubscribe)!==null&&o!==void 0?o:!0,l=new Array,B=new Array;A.forEach(Q=>{Q.isDesired!==c&&l.push(Q.trackSid),Q.isEnabled||B.push(Q.trackSid)}),this.client.sendSyncState(new Nz({answer:this.pcManager.mode==="publisher-only"?a?Am({sdp:a.sdp,type:a.type}):void 0:I?Am({sdp:I.sdp,type:I.type}):void 0,offer:this.pcManager.mode==="publisher-only"?s?Am({sdp:s.sdp,type:s.type}):void 0:r?Am({sdp:r.sdp,type:r.type}):void 0,subscription:new Ax({trackSids:l,subscribe:!c,participantTracks:[]}),publishTracks:_WA(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:B,datachannelReceiveStates:this.reliableReceivedState.map((Q,h)=>new BuA({publisherSid:h,lastSeq:Q}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const A=[],t=(i,n)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&A.push(new EuA({label:i.label,id:i.id,target:n}))};return t(this.dataChannelForKind(Mn.LOSSY),Yc.PUBLISHER),t(this.dataChannelForKind(Mn.RELIABLE),Yc.PUBLISHER),t(this.dataChannelForKind(Mn.LOSSY,!0),Yc.SUBSCRIBER),t(this.dataChannelForKind(Mn.RELIABLE,!0),Yc.SUBSCRIBER),A}clearReconnectTimeout(){this.reconnectTimeout&&Ra.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){iI()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){iI()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(A){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(A);if(i){const n=Object.entries(this.midToTrackId).find(g=>{let[o]=g;return o===i});if(n)return n[1]}}}function r9A(e){return e!==void 0&&e>13}function ieA(e,A){const t=e.participantIdentity?e.participantIdentity:A.participantIdentity;e.participantIdentity=t,A.participantIdentity=t;const i=e.destinationIdentities.length!==0?e.destinationIdentities:A.destinationIdentities;e.destinationIdentities=i,A.destinationIdentities=i}class CdA{get info(){return this._info}validateBytesReceived(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(A&&this.bytesReceived<this.totalByteSize)throw new GC("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),hr.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new GC("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),hr.LengthExceeded)}}constructor(A,t,i,n){this.reader=t,this.totalByteSize=i,this._info=A,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class I9A extends CdA{handleChunkReceived(A){var t;this.bytesReceived+=A.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const A=this.reader.getReader();let t=new WC,i=null,n=null;if(this.signal){const o=this.signal;n=()=>{var s;(s=t.reject)===null||s===void 0||s.call(t,o.reason)},o.addEventListener("abort",n),i=o}const g=()=>{A.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>zA(this,void 0,void 0,function*(){var o,s;try{const{done:a,value:r}=yield Promise.race([A.read(),t.promise,(s=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&s!==void 0?s:new Promise(()=>{})]);return a?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r),{done:!1,value:r.content})}catch(a){throw g(),a}}),return(){return zA(this,void 0,void 0,function*(){return g(),{done:!0,value:void 0}})}}}withAbortSignal(A){return this.signal=A,this}readAll(){return zA(this,arguments,void 0,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,n,g,o;let s=new Set;const a=t.signal?A.withAbortSignal(t.signal):A;try{for(var r=!0,I=fE(a),c;c=yield I.next(),i=c.done,!i;r=!0){o=c.value,r=!1;const l=o;s.add(l)}}catch(l){n={error:l}}finally{try{!r&&!i&&(g=I.return)&&(yield g.call(I))}finally{if(n)throw n.error}}return Array.from(s)}()})}}class C9A extends CdA{constructor(A,t,i,n){super(A,t,i,n),this.receivedChunks=new Map}handleChunkReceived(A){var t;const i=SK(A.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>A.version)return;this.receivedChunks.set(i,A),this.bytesReceived+=A.content.byteLength,this.validateBytesReceived();const g=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,g)}[Symbol.asyncIterator](){const A=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new WC,n=null,g=null;if(this.signal){const s=this.signal;g=()=>{var a;(a=i.reject)===null||a===void 0||a.call(i,s.reason)},s.addEventListener("abort",g),n=s}const o=()=>{A.releaseLock(),n&&g&&n.removeEventListener("abort",g),this.signal=void 0};return{next:()=>zA(this,void 0,void 0,function*(){var s,a;try{const{done:r,value:I}=yield Promise.race([A.read(),i.promise,(a=(s=this.outOfBandFailureRejectingFuture)===null||s===void 0?void 0:s.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);if(r)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(I);let c;try{c=t.decode(I.content)}catch(l){throw new GC("Cannot decode datastream chunk ".concat(I.chunkIndex," as text: ").concat(l),hr.DecodeFailed)}return{done:!1,value:c}}}catch(r){throw o(),r}}),return(){return zA(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(A){return this.signal=A,this}readAll(){return zA(this,arguments,void 0,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,n,g,o;let s="";const a=t.signal?A.withAbortSignal(t.signal):A;try{for(var r=!0,I=fE(a),c;c=yield I.next(),i=c.done,!i;r=!0)o=c.value,r=!1,s+=o}catch(l){n={error:l}}finally{try{!r&&!i&&(g=I.return)&&(yield g.call(I))}finally{if(n)throw n.error}}return s}()})}}class c9A{constructor(){this.log=ln,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(A,t){if(this.textStreamHandlers.has(A))throw new GC('A text stream handler for topic "'.concat(A,'" has already been set.'),hr.HandlerAlreadyRegistered);this.textStreamHandlers.set(A,t)}unregisterTextStreamHandler(A){this.textStreamHandlers.delete(A)}registerByteStreamHandler(A,t){if(this.byteStreamHandlers.has(A))throw new GC('A byte stream handler for topic "'.concat(A,'" has already been set.'),hr.HandlerAlreadyRegistered);this.byteStreamHandlers.set(A,t)}unregisterByteStreamHandler(A){this.byteStreamHandlers.delete(A)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(A){var t,i,n,g;const o=Array.from(this.textStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===A),s=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===A);if(o.length>0||s.length>0){const a=new GC("Participant ".concat(A," unexpectedly disconnected in the middle of sending data"),hr.AbnormalEnd);for(const[r,I]of s)(i=(t=I.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(t,a),this.byteStreamControllers.delete(r);for(const[r,I]of o)(g=(n=I.outOfBandFailureRejectingFuture).reject)===null||g===void 0||g.call(n,a),this.textStreamControllers.delete(r)}}handleDataStreamPacket(A,t){return zA(this,void 0,void 0,function*(){switch(A.value.case){case"streamHeader":return this.handleStreamHeader(A.value.value,A.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(A.value.value,t);case"streamTrailer":return this.handleStreamTrailer(A.value.value,t);default:throw new Error('DataPacket of value "'.concat(A.value.case,'" is not data stream related!'))}})}handleStreamHeader(A,t,i){return zA(this,void 0,void 0,function*(){var n;if(A.contentHeader.case==="byteHeader"){const g=this.byteStreamHandlers.get(A.topic);if(!g){this.log.debug("ignoring incoming byte stream due to no handler for topic",A.topic);return}let o;const s=new WC;s.promise.catch(I=>{this.log.error(I)});const a={id:A.streamId,name:(n=A.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:A.mimeType,size:A.totalLength?Number(A.totalLength):void 0,topic:A.topic,timestamp:SK(A.timestamp),attributes:A.attributes,encryptionType:i},r=new ReadableStream({start:I=>{if(o=I,this.textStreamControllers.has(A.streamId))throw new GC("A data stream read is already in progress for a stream with id ".concat(A.streamId,"."),hr.AlreadyOpened);this.byteStreamControllers.set(A.streamId,{info:a,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:s})}});g(new I9A(a,r,SK(A.totalLength),s),{identity:t})}else if(A.contentHeader.case==="textHeader"){const g=this.textStreamHandlers.get(A.topic);if(!g){this.log.debug("ignoring incoming text stream due to no handler for topic",A.topic);return}let o;const s=new WC;s.promise.catch(I=>{this.log.error(I)});const a={id:A.streamId,mimeType:A.mimeType,size:A.totalLength?Number(A.totalLength):void 0,topic:A.topic,timestamp:Number(A.timestamp),attributes:A.attributes,encryptionType:i},r=new ReadableStream({start:I=>{if(o=I,this.textStreamControllers.has(A.streamId))throw new GC("A data stream read is already in progress for a stream with id ".concat(A.streamId,"."),hr.AlreadyOpened);this.textStreamControllers.set(A.streamId,{info:a,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:s})}});g(new C9A(a,r,SK(A.totalLength),s),{identity:t})}})}handleStreamChunk(A,t){const i=this.byteStreamControllers.get(A.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new GC("Encryption type mismatch for stream ".concat(A.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),hr.EncryptionTypeMismatch)),this.byteStreamControllers.delete(A.streamId)):A.content.length>0&&i.controller.enqueue(A));const n=this.textStreamControllers.get(A.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new GC("Encryption type mismatch for stream ".concat(A.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),hr.EncryptionTypeMismatch)),this.textStreamControllers.delete(A.streamId)):A.content.length>0&&n.controller.enqueue(A))}handleStreamTrailer(A,t){const i=this.textStreamControllers.get(A.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new GC("Encryption type mismatch for stream ".concat(A.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),hr.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),A.attributes),i.controller.close(),this.textStreamControllers.delete(A.streamId)));const n=this.byteStreamControllers.get(A.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new GC("Encryption type mismatch for stream ".concat(A.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),hr.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),A.attributes),n.controller.close()),this.byteStreamControllers.delete(A.streamId))}}class cdA{constructor(A,t,i){this.writableStream=A,this.defaultWriter=A.getWriter(),this.onClose=i,this.info=t}write(A){return this.defaultWriter.write(A)}close(){return zA(this,void 0,void 0,function*(){var A;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(A=this.onClose)===null||A===void 0||A.call(this)})}}class l9A extends cdA{}class B9A extends cdA{}const neA=15e3;class E9A{constructor(A,t){this.engine=A,this.log=t}setupEngine(A){this.engine=A}sendText(A,t){return zA(this,void 0,void 0,function*(){var i;const n=crypto.randomUUID(),o=new TextEncoder().encode(A).byteLength,s=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),a=new Array(s?s.length+1:1).fill(0),r=(c,l)=>{var B;a[l]=c;const Q=a.reduce((h,d)=>h+d,0);(B=t==null?void 0:t.onProgress)===null||B===void 0||B.call(t,Q)},I=yield this.streamText({streamId:n,totalSize:o,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:s,attributes:t==null?void 0:t.attributes});return yield I.write(A),r(1,0),yield I.close(),t!=null&&t.attachments&&s&&(yield Promise.all(t.attachments.map((c,l)=>zA(this,void 0,void 0,function*(){return this._sendFile(s[l],c,{topic:t.topic,mimeType:c.type,onProgress:B=>{r(B,l+1)}})})))),I.info})}streamText(A){return zA(this,void 0,void 0,function*(){var t,i,n;const g=(t=A==null?void 0:A.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),o={id:g,mimeType:"text/plain",timestamp:Date.now(),topic:(i=A==null?void 0:A.topic)!==null&&i!==void 0?i:"",size:A==null?void 0:A.totalSize,attributes:A==null?void 0:A.attributes,encryptionType:!((n=this.engine.e2eeManager)===null||n===void 0)&&n.isDataChannelEncryptionEnabled?Js.GCM:Js.NONE},s=new n_({streamId:g,mimeType:o.mimeType,topic:o.topic,timestamp:jh(o.timestamp),totalLength:jh(A==null?void 0:A.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new ouA({version:A==null?void 0:A.version,attachedStreamIds:A==null?void 0:A.attachedStreamIds,replyToStreamId:A==null?void 0:A.replyToStreamId,operationType:(A==null?void 0:A.type)==="update"?i3.UPDATE:i3.CREATE})}}),a=A==null?void 0:A.destinationIdentities,r=new Dr({destinationIdentities:a,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(r,Mn.RELIABLE);let I=0;const c=this.engine,l=new WritableStream({write(h){return zA(this,void 0,void 0,function*(){for(const d of oVA(h,neA)){const p=new g_({content:d,streamId:g,chunkIndex:jh(I)}),y=new Dr({destinationIdentities:a,value:{case:"streamChunk",value:p}});yield c.sendDataPacket(y,Mn.RELIABLE),I+=1}})},close(){return zA(this,void 0,void 0,function*(){const h=new o_({streamId:g}),d=new Dr({destinationIdentities:a,value:{case:"streamTrailer",value:h}});yield c.sendDataPacket(d,Mn.RELIABLE)})},abort(h){console.log("Sink error:",h)}});let B=()=>zA(this,void 0,void 0,function*(){yield Q.close()});c.once(_t.Closing,B);const Q=new l9A(l,o,()=>this.engine.off(_t.Closing,B));return Q})}sendFile(A,t){return zA(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,A,t),{id:i}})}_sendFile(A,t,i){return zA(this,void 0,void 0,function*(){var n;const g=yield this.streamBytes({streamId:A,totalSize:t.size,name:t.name,mimeType:(n=i==null?void 0:i.mimeType)!==null&&n!==void 0?n:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:s,value:a}=yield o.read();if(s)break;yield g.write(a)}return yield g.close(),g.info})}streamBytes(A){return zA(this,void 0,void 0,function*(){var t,i,n,g,o,s;const a=(t=A==null?void 0:A.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),r=A==null?void 0:A.destinationIdentities,I={id:a,mimeType:(i=A==null?void 0:A.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(n=A==null?void 0:A.topic)!==null&&n!==void 0?n:"",timestamp:Date.now(),attributes:A==null?void 0:A.attributes,size:A==null?void 0:A.totalSize,name:(g=A==null?void 0:A.name)!==null&&g!==void 0?g:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?Js.GCM:Js.NONE},c=new n_({totalLength:jh((s=I.size)!==null&&s!==void 0?s:0),mimeType:I.mimeType,streamId:a,topic:I.topic,timestamp:jh(Date.now()),attributes:I.attributes,contentHeader:{case:"byteHeader",value:new suA({name:I.name})}}),l=new Dr({destinationIdentities:r,value:{case:"streamHeader",value:c}});yield this.engine.sendDataPacket(l,Mn.RELIABLE);let B=0;const Q=new vr,h=this.engine,d=this.log,p=new WritableStream({write(m){return zA(this,void 0,void 0,function*(){const D=yield Q.lock();let S=0;try{for(;S<m.byteLength;){const k=m.slice(S,S+neA),N=new Dr({destinationIdentities:r,value:{case:"streamChunk",value:new g_({content:k,streamId:a,chunkIndex:jh(B)})}});yield h.sendDataPacket(N,Mn.RELIABLE),B+=1,S+=k.byteLength}}finally{D()}})},close(){return zA(this,void 0,void 0,function*(){const m=new o_({streamId:a}),D=new Dr({destinationIdentities:r,value:{case:"streamTrailer",value:m}});yield h.sendDataPacket(D,Mn.RELIABLE)})},abort(m){d.error("Sink error:",m)}});return new B9A(p,I)})}}class ldA extends st{constructor(A,t,i,n,g){super(A,i,g),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(A){this.isMuted!==A&&(this.isMuted=A,this._mediaStreamTrack.enabled=!A,this.emit(A?Gt.Muted:Gt.Unmuted,this))}setMediaStream(A){this.mediaStream=A;const t=i=>{i.track===this._mediaStreamTrack&&(A.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Gt.Ended,this))};A.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return zA(this,void 0,void 0,function*(){var A;return!((A=this.receiver)===null||A===void 0)&&A.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(A){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=A:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),qz)),JWA()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const A=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>A());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:n,rtpTimestamp:g}=i;g&&this.rtpTimestamp!==g&&(this.emit(Gt.TimeSyncUpdate,{timestamp:n,rtpTimestamp:g}),this.rtpTimestamp=g)}};A()}}class Q9A extends ldA{constructor(A,t,i,n,g,o){super(A,t,st.Kind.Audio,i,o),this.monitorReceiver=()=>zA(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=ix(s,this.prevStats)),this.prevStats=s}),this.audioContext=n,this.webAudioPluginNodes=[],g&&(this.sinkId=g.deviceId)}setVolume(A){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(A,0,.1):i.volume=A;pB()&&this._mediaStreamTrack._setVolume(A),this.elementVolume=A}getVolume(){if(this.elementVolume)return this.elementVolume;if(pB())return 1;let A=0;return this.attachedElements.forEach(t=>{t.volume>A&&(A=t.volume)}),A}setSinkId(A){return zA(this,void 0,void 0,function*(){this.sinkId=A,yield Promise.all(this.attachedElements.map(t=>{if(h3(t))return t.setSinkId(A)}))})}attach(A){const t=this.attachedElements.length===0;return A?super.attach(A):A=super.attach(),this.sinkId&&h3(A)&&A.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,A),A.volume=0,A.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),A}detach(A){let t;return A?(t=super.detach(A),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(A){this.audioContext=A,A&&this.attachedElements.length>0?this.connectWebAudio(A,this.attachedElements[0]):A||this.disconnectWebAudio()}setWebAudioPlugins(A){this.webAudioPluginNodes=A,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(A,t){this.disconnectWebAudio(),this.sourceNode=A.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(n=>{i.connect(n),i=n}),this.gainNode=A.createGain(),i.connect(this.gainNode),this.gainNode.connect(A.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),A.state!=="running"&&A.resume().then(()=>{A.state!=="running"&&this.emit(Gt.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(n=>{this.emit(Gt.AudioPlaybackFailed,n)})}disconnectWebAudio(){var A,t;(A=this.gainNode)===null||A===void 0||A.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return zA(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const A=yield this.receiver.getStats();let t;return A.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const sY=100;class u9A extends ldA{constructor(A,t,i,n,g){super(A,t,st.Kind.Video,i,g),this.elementInfos=[],this.monitorReceiver=()=>zA(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=ix(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=Jz(()=>{this.updateDimensions()},sY),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(A){super.setStreamState(A),this.log.debug("setStreamState",A),this.isAdaptiveStream&&A===st.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(A){super.setMuted(A),this.attachedElements.forEach(t=>{A?Jm(this._mediaStreamTrack,t):$D(this._mediaStreamTrack,t)})}attach(A){if(A?super.attach(A):A=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===A)===void 0){const t=new d9A(A);this.observeElementInfo(t)}return A}observeElementInfo(A){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===A)===void 0?(A.handleResize=()=>{this.debouncedHandleResize()},A.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(A),A.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(A){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===A);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==A),this.updateVisibility(),this.debouncedHandleResize()}detach(A){let t=[];if(A)return this.stopObservingElement(A),super.detach(A);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var A;return(A=this.prevStats)===null||A===void 0?void 0:A.decoderImplementation}getReceiverStats(){return zA(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const A=yield this.receiver.getStats();let t,i="",n=new Map;return A.forEach(g=>{g.type==="inbound-rtp"?(i=g.codecId,t={type:"video",streamId:g.id,framesDecoded:g.framesDecoded,framesDropped:g.framesDropped,framesReceived:g.framesReceived,packetsReceived:g.packetsReceived,packetsLost:g.packetsLost,frameWidth:g.frameWidth,frameHeight:g.frameHeight,pliCount:g.pliCount,firCount:g.firCount,nackCount:g.nackCount,jitter:g.jitter,timestamp:g.timestamp,bytesReceived:g.bytesReceived,decoderImplementation:g.decoderImplementation}):g.type==="codec"&&n.set(g.id,g)}),t&&i!==""&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t})}stopObservingElement(A){const t=this.elementInfos.filter(i=>i.element===A);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const A=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return zA(this,void 0,void 0,function*(){yield A.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(A){var t,i;const n=this.elementInfos.reduce((a,r)=>Math.max(a,r.visibilityChangedAt||0),0),g=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,o=this.elementInfos.some(a=>a.pictureInPicture),s=this.elementInfos.some(a=>a.visible)&&!g||o;if(!(this.lastVisible===s&&!A)){if(!s&&Date.now()-n<sY){Ra.setTimeout(()=>{this.updateVisibility()},sY);return}this.lastVisible=s,this.emit(Gt.VisibilityChanged,s,this)}}updateDimensions(){var A,t;let i=0,n=0;const g=this.getPixelDensity();for(const o of this.elementInfos){const s=o.width()*g,a=o.height()*g;s+a>i+n&&(i=s,n=a)}((A=this.lastDimensions)===null||A===void 0?void 0:A.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Gt.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var A;const t=(A=this.adaptiveStreamSettings)===null||A===void 0?void 0:A.pixelDensity;return t==="screen"?bAA():t||(bAA()>2?2:1)}}class d9A{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(A,t){this.onVisibilityChanged=i=>{var n;const{target:g,isIntersecting:o}=i;g===this.element&&(this.isIntersecting=o,this.isPiP=N0(this.element),this.visibilityChangedAt=Date.now(),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this))},this.onEnterPiP=()=>{var i,n,g;(n=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP),this.isPiP=N0(this.element),(g=this.handleVisibilityChanged)===null||g===void 0||g.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=N0(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=A,this.isIntersecting=t??S3(A),this.isPiP=iI()&&N0(A),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var A,t,i;this.isIntersecting=S3(this.element),this.isPiP=N0(this.element),this.element.handleResize=()=>{var n;(n=this.handleResize)===null||n===void 0||n.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,vAA().observe(this.element),UAA().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(A=window.documentPictureInPicture)===null||A===void 0||A.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var A,t,i,n,g;(A=vAA())===null||A===void 0||A.unobserve(this.element),(t=UAA())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(g=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||g===void 0||g.removeEventListener("pagehide",this.onLeavePiP)}}function N0(e){var A,t;return document.pictureInPictureElement===e?!0:!((A=window.documentPictureInPicture)===null||A===void 0)&&A.window?S3(e,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function S3(e,A){const t=A||window;let i=e.offsetTop,n=e.offsetLeft;const g=e.offsetWidth,o=e.offsetHeight,{hidden:s}=e,{display:a}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,i+=e.offsetTop,n+=e.offsetLeft;return i<t.pageYOffset+t.innerHeight&&n<t.pageXOffset+t.innerWidth&&i+o>t.pageYOffset&&n+g>t.pageXOffset&&!s&&a!=="none"}class EE extends RB.EventEmitter{constructor(A,t,i,n){var g;super(),this.metadataMuted=!1,this.encryption=Js.NONE,this.log=ln,this.handleMuted=()=>{this.emit(Gt.Muted)},this.handleUnmuted=()=>{this.emit(Gt.Unmuted)},this.log=eQ((g=n==null?void 0:n.loggerName)!==null&&g!==void 0?g:el.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=A,this.trackSid=t,this.trackName=i,this.source=st.Source.Unknown}setTrack(A){this.track&&(this.track.off(Gt.Muted,this.handleMuted),this.track.off(Gt.Unmuted,this.handleUnmuted)),this.track=A,A&&(A.on(Gt.Muted,this.handleMuted),A.on(Gt.Unmuted,this.handleUnmuted))}get logContext(){var A;return Object.assign(Object.assign({},(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this)),Gn(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Js.NONE}get audioTrack(){if(cB(this.track))return this.track}get videoTrack(){if(Fd(this.track))return this.track}updateInfo(A){this.trackSid=A.sid,this.trackName=A.name,this.source=st.sourceFromProto(A.source),this.mimeType=A.mimeType,this.kind===st.Kind.Video&&A.width>0&&(this.dimensions={width:A.width,height:A.height},this.simulcasted=A.simulcast),this.encryption=A.encryption,this.trackInfo=A,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:A}))}}(function(e){(function(A){A.Desired="desired",A.Subscribed="subscribed",A.Unsubscribed="unsubscribed"})(e.SubscriptionStatus||(e.SubscriptionStatus={})),function(A){A.Allowed="allowed",A.NotAllowed="not_allowed"}(e.PermissionStatus||(e.PermissionStatus={}))})(EE||(EE={}));class w3 extends EE{get isUpstreamPaused(){var A;return(A=this.track)===null||A===void 0?void 0:A.isUpstreamPaused}constructor(A,t,i,n){super(A,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Gt.Ended)},this.handleCpuConstrained=()=>{this.track&&Fd(this.track)&&this.emit(Gt.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(A){this.track&&(this.track.off(Gt.Ended,this.handleTrackEnded),this.track.off(Gt.CpuConstrained,this.handleCpuConstrained)),super.setTrack(A),A&&(A.on(Gt.Ended,this.handleTrackEnded),A.on(Gt.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return zA(this,void 0,void 0,function*(){var A;return(A=this.track)===null||A===void 0?void 0:A.mute()})}unmute(){return zA(this,void 0,void 0,function*(){var A;return(A=this.track)===null||A===void 0?void 0:A.unmute()})}pauseUpstream(){return zA(this,void 0,void 0,function*(){var A;yield(A=this.track)===null||A===void 0?void 0:A.pauseUpstream()})}resumeUpstream(){return zA(this,void 0,void 0,function*(){var A;yield(A=this.track)===null||A===void 0?void 0:A.resumeUpstream()})}getTrackFeatures(){var A;if(cB(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ia.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ia.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ia.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ia.TF_STEREO),!((A=this.options)===null||A===void 0)&&A.dtx||i.add(ia.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ia.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function nx(e,A){return zA(this,void 0,void 0,function*(){e??(e={});let t=!1;const{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:g}=$uA(e);let o=g.audio,s=g.video;if(i&&typeof g.audio=="object"&&(g.audio.processor=i),n&&typeof g.video=="object"&&(g.video.processor=n),e.audio&&typeof g.audio=="object"&&typeof g.audio.deviceId=="string"){const c=g.audio.deviceId;g.audio.deviceId={exact:c},t=!0,o=Object.assign(Object.assign({},g.audio),{deviceId:{ideal:c}})}if(g.video&&typeof g.video=="object"&&typeof g.video.deviceId=="string"){const c=g.video.deviceId;g.video.deviceId={exact:c},t=!0,s=Object.assign(Object.assign({},g.video),{deviceId:{ideal:c}})}g.audio===!0?g.audio={deviceId:"default"}:typeof g.audio=="object"&&g.audio!==null&&(g.audio=Object.assign(Object.assign({},g.audio),{deviceId:g.audio.deviceId||"default"})),g.video===!0?g.video={deviceId:"default"}:typeof g.video=="object"&&!g.video.deviceId&&(g.video.deviceId="default");const a=WuA(g,ndA,gdA),r=vz(a),I=navigator.mediaDevices.getUserMedia(r);g.audio&&(oa.userMediaPromiseMap.set("audioinput",I),I.catch(()=>oa.userMediaPromiseMap.delete("audioinput"))),g.video&&(oa.userMediaPromiseMap.set("videoinput",I),I.catch(()=>oa.userMediaPromiseMap.delete("videoinput")));try{const c=yield I;return yield Promise.all(c.getTracks().map(l=>zA(this,void 0,void 0,function*(){const B=l.kind==="audio";let Q=B?a.audio:a.video;(typeof Q=="boolean"||!Q)&&(Q={});let h;const d=B?r.audio:r.video;typeof d!="boolean"&&(h=d);const p=l.getSettings().deviceId;h!=null&&h.deviceId&&Wu(h.deviceId)!==p?h.deviceId=p:h||(h={deviceId:p});const y=PVA(l,h,A);return y.kind===st.Kind.Video?y.source=st.Source.Camera:y.kind===st.Kind.Audio&&(y.source=st.Source.Microphone),y.mediaStream=c,cB(y)&&i?yield y.setProcessor(i):Fd(y)&&n&&(yield y.setProcessor(n)),y})))}catch(c){if(!t)throw c;return nx(Object.assign(Object.assign({},e),{audio:o,video:s}),A)}})}function h9A(e){return zA(this,void 0,void 0,function*(){return(yield nx({audio:!1,video:!0}))[0]})}function p9A(e){return zA(this,void 0,void 0,function*(){return(yield nx({audio:!0,video:!1}))[0]})}var su;(function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"})(su||(su={}));function f9A(e){switch(e){case hk.EXCELLENT:return su.Excellent;case hk.GOOD:return su.Good;case hk.POOR:return su.Poor;case hk.LOST:return su.Lost;default:return su.Unknown}}class BdA extends RB.EventEmitter{get logContext(){var A,t;return Object.assign({},(t=(A=this.loggerOptions)===null||A===void 0?void 0:A.loggerContextCb)===null||t===void 0?void 0:t.call(A))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(A=>A.isEncrypted)}get isAgent(){var A;return((A=this.permissions)===null||A===void 0?void 0:A.agent)||this.kind===lN.AGENT}get isActive(){var A;return((A=this.participantInfo)===null||A===void 0?void 0:A.state)===vm.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(A,t,i,n,g,o){let s=arguments.length>6&&arguments[6]!==void 0?arguments[6]:lN.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=su.Unknown,this.log=ln,this.log=eQ((a=o==null?void 0:o.loggerName)!==null&&a!==void 0?a:el.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=A,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=s,this._attributes=g??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(A){for(const[,t]of this.trackPublications)if(t.source===A)return t}getTrackPublicationByName(A){for(const[,t]of this.trackPublications)if(t.trackName===A)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new WC,this.once(qt.Active,()=>{var A,t;(t=(A=this.activeFuture)===null||A===void 0?void 0:A.resolve)===null||t===void 0||t.call(A),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var A;const t=this.getTrackPublication(st.Source.Camera);return!(!((A=t==null?void 0:t.isMuted)!==null&&A!==void 0)||A)}get isMicrophoneEnabled(){var A;const t=this.getTrackPublication(st.Source.Microphone);return!(!((A=t==null?void 0:t.isMuted)!==null&&A!==void 0)||A)}get isScreenShareEnabled(){return!!this.getTrackPublication(st.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(A){var t;return this.participantInfo&&this.participantInfo.sid===A.sid&&this.participantInfo.version>A.version?!1:(this.identity=A.identity,this.sid=A.sid,this._setName(A.name),this._setMetadata(A.metadata),this._setAttributes(A.attributes),A.state===vm.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==vm.ACTIVE&&this.emit(qt.Active),A.permission&&this.setPermissions(A.permission),this.participantInfo=A,!0)}_setMetadata(A){const t=this.metadata!==A,i=this.metadata;this.metadata=A,t&&this.emit(qt.ParticipantMetadataChanged,i)}_setName(A){const t=this.name!==A;this.name=A,t&&this.emit(qt.ParticipantNameChanged,A)}_setAttributes(A){const t=LWA(this.attributes,A);this._attributes=A,Object.keys(t).length>0&&this.emit(qt.AttributesChanged,t)}setPermissions(A){var t,i,n,g,o,s;const a=this.permissions,r=A.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||A.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||A.canPublishData!==((n=this.permissions)===null||n===void 0?void 0:n.canPublishData)||A.hidden!==((g=this.permissions)===null||g===void 0?void 0:g.hidden)||A.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||A.canPublishSources.length!==this.permissions.canPublishSources.length||A.canPublishSources.some((I,c)=>{var l;return I!==((l=this.permissions)===null||l===void 0?void 0:l.canPublishSources[c])})||A.canSubscribeMetrics!==((s=this.permissions)===null||s===void 0?void 0:s.canSubscribeMetrics);return this.permissions=A,r&&this.emit(qt.ParticipantPermissionsChanged,a),r}setIsSpeaking(A){A!==this.isSpeaking&&(this.isSpeaking=A,A&&(this.lastSpokeAt=new Date),this.emit(qt.IsSpeakingChanged,A))}setConnectionQuality(A){const t=this._connectionQuality;this._connectionQuality=f9A(A),t!==this._connectionQuality&&this.emit(qt.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var A,t;this.activeFuture&&((t=(A=this.activeFuture).reject)===null||t===void 0||t.call(A,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(A){this.audioContext=A,this.audioTrackPublications.forEach(t=>cB(t.track)&&t.track.setAudioContext(A))}addTrackPublication(A){A.on(Gt.Muted,()=>{this.emit(qt.TrackMuted,A)}),A.on(Gt.Unmuted,()=>{this.emit(qt.TrackUnmuted,A)});const t=A;switch(t.track&&(t.track.sid=A.trackSid),this.trackPublications.set(A.trackSid,A),A.kind){case st.Kind.Audio:this.audioTrackPublications.set(A.trackSid,A);break;case st.Kind.Video:this.videoTrackPublications.set(A.trackSid,A);break}}}function y9A(e){var A,t,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new cuA({participantIdentity:(A=e.participantIdentity)!==null&&A!==void 0?A:"",participantSid:(t=e.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=e.allowAll)!==null&&i!==void 0?i:!1,trackSids:e.allowedTrackSids||[]})}class D9A extends BdA{constructor(A,t,i,n,g,o){super(A,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Js.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new WC)},this.handleReconnected=()=>{var s,a;(a=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||a===void 0||a.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var s,a,r,I,c,l;this.reconnectFuture&&(this.reconnectFuture.promise.catch(B=>this.log.warn(B.message,this.logContext)),(a=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||a===void 0||a.call(s,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((I=(r=this.signalConnectedFuture).reject)===null||I===void 0||I.call(r,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(l=(c=this.activeAgentFuture)===null||c===void 0?void 0:c.reject)===null||l===void 0||l.call(c,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=s=>{var a,r;s.participant&&this.updateInfo(s.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new WC),(r=(a=this.signalConnectedFuture).resolve)===null||r===void 0||r.call(a)},this.handleSignalRequestResponse=s=>{const{requestId:a,reason:r,message:I}=s,c=this.pendingSignalRequests.get(a);c&&(r!==Rz.OK&&c.reject(new kAA(I,r)),this.pendingSignalRequests.delete(a))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let a=s.value.value,r=null,I=null;a.value.case==="payload"?r=a.value.value:a.value.case==="error"&&(I=mr.fromProto(a.value.value)),this.handleIncomingRpcResponse(a.requestId,r,I);break;case"rpcAck":let c=s.value.value;this.handleIncomingRpcAck(c.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>y9A(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,a)=>{if(a===void 0&&(a=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Gn(s)));return}this.engine.updateMuteStatus(s.sid,a)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Gn(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Gn(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const a=this.audioTrackPublications.get(s.sid);if(!a){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(a.trackSid,a.getTrackFeatures())},this.onTrackCpuConstrained=(s,a)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),Gn(a))),this.emit(qt.LocalTrackCpuConstrained,s,a)},this.handleSubscribedQualityUpdate=s=>zA(this,void 0,void 0,function*(){var a,r,I,c,l;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.dynacast))return;const B=this.videoTrackPublications.get(s.trackSid);if(!B){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(!B.videoTrack)return;const Q=yield B.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var h=!0,d=fE(Q),p;p=yield d.next(),a=p.done,!a;h=!0){c=p.value,h=!1;const y=c;vWA(y)&&(this.log.debug("publish ".concat(y," for ").concat(B.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Gn(B))),yield this.publishAdditionalCodecForTrack(B.videoTrack,y,B.options))}}catch(y){r={error:y}}finally{try{!h&&!a&&(I=d.return)&&(yield I.call(d))}finally{if(r)throw r.error}}}),this.handleLocalTrackUnpublished=s=>{const a=this.trackPublications.get(s.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=s=>zA(this,void 0,void 0,function*(){if(s.source===st.Source.ScreenShare||s.source===st.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Gn(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(aE(s)||vQ(s))try{if(iI())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:s.source===st.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),Gn(s))),a.onchange=()=>{a.state!=="denied"&&(s.isMuted||s.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Gn(s))),aE(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Gn(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=g,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Js.NONE}getTrackPublication(A){const t=super.getTrackPublication(A);if(t)return t}getTrackPublicationByName(A){const t=super.getTrackPublicationByName(A);if(t)return t}setupEngine(A){var t;this.engine=A,this.engine.on(_t.RemoteMute,(i,n)=>{const g=this.trackPublications.get(i);!g||!g.track||(n?g.mute():g.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(_t.Connected,this.handleReconnected).on(_t.SignalConnected,this.handleSignalConnected).on(_t.SignalRestarted,this.handleReconnected).on(_t.SignalResumed,this.handleReconnected).on(_t.Restarting,this.handleReconnecting).on(_t.Resuming,this.handleReconnecting).on(_t.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(_t.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(_t.Closing,this.handleClosing).on(_t.SignalRequestResponse,this.handleSignalRequestResponse).on(_t.DataPacketReceived,this.handleDataPacket)}setMetadata(A){return zA(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:A})})}setName(A){return zA(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:A})})}setAttributes(A){return zA(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:A})})}requestMetadataUpdate(A){return zA(this,arguments,void 0,function(t){var i=this;let{metadata:n,name:g,attributes:o}=t;return function*(){return new tI((s,a)=>zA(i,void 0,void 0,function*(){var r,I;try{let c=!1;const l=yield this.engine.client.sendUpdateLocalMetadata((r=n??this.metadata)!==null&&r!==void 0?r:"",(I=g??this.name)!==null&&I!==void 0?I:"",o),B=performance.now();for(this.pendingSignalRequests.set(l,{resolve:s,reject:Q=>{a(Q),c=!0},values:{name:g,metadata:n,attributes:o}});performance.now()-B<5e3&&!c;){if((!g||this.name===g)&&(!n||this.metadata===n)&&(!o||Object.entries(o).every(Q=>{let[h,d]=Q;return this.attributes[h]===d||d===""&&!this.attributes[h]}))){this.pendingSignalRequests.delete(l),s();return}yield Ga(50)}a(new kAA("Request to update local metadata timed out","TimeoutError"))}catch(c){c instanceof Error?a(c):a(new Error(String(c)))}}))}()})}setCameraEnabled(A,t,i){return this.setTrackEnabled(st.Source.Camera,A,t,i)}setMicrophoneEnabled(A,t,i){return this.setTrackEnabled(st.Source.Microphone,A,t,i)}setScreenShareEnabled(A,t,i){return this.setTrackEnabled(st.Source.ScreenShare,A,t,i)}setE2EEEnabled(A){return zA(this,void 0,void 0,function*(){this.encryptionType=A?Js.GCM:Js.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(A,t,i,n){return zA(this,void 0,void 0,function*(){var g,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:A,enabled:t})),this.republishPromise&&(yield this.republishPromise);let s=this.getTrackPublication(A);if(t)if(s)yield s.unmute();else{let a;if(this.pendingPublishing.has(A)){const r=yield this.waitForPendingPublicationOfSource(A);return r||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:A})),yield r==null?void 0:r.unmute(),r}this.pendingPublishing.add(A);try{switch(A){case st.Source.Camera:a=yield this.createTracks({video:(g=i)!==null&&g!==void 0?g:!0});break;case st.Source.Microphone:a=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case st.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},i));break;default:throw new yE(A)}}catch(r){throw a==null||a.forEach(I=>{I.stop()}),r instanceof Error&&this.emit(qt.MediaDevicesError,r,Q3(A)),this.pendingPublishing.delete(A),r}for(const r of a){const I=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);A===st.Source.Microphone&&cB(r)&&I.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),r.startPreConnectBuffer())}try{const r=[];for(const c of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Gn(c))),r.push(this.publishTrack(c,n));[s]=yield Promise.all(r)}catch(r){throw a==null||a.forEach(I=>{I.stop()}),r}finally{this.pendingPublishing.delete(A)}}else if(!(s!=null&&s.track)&&this.pendingPublishing.has(A)&&(s=yield this.waitForPendingPublicationOfSource(A),s||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:A}))),s&&s.track)if(A===st.Source.ScreenShare){s=yield this.unpublishTrack(s.track);const a=this.getTrackPublication(st.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield s.mute();return s})}enableCameraAndMicrophone(){return zA(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(st.Source.Camera)||this.pendingPublishing.has(st.Source.Microphone))){this.pendingPublishing.add(st.Source.Camera),this.pendingPublishing.add(st.Source.Microphone);try{const A=yield this.createTracks({audio:!0,video:!0});yield Promise.all(A.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(st.Source.Camera),this.pendingPublishing.delete(st.Source.Microphone)}}})}createTracks(A){return zA(this,void 0,void 0,function*(){var t,i;A??(A={});const n=WuA(A,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield nx(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(s=>(cB(s)&&(this.microphoneError=void 0,s.setAudioContext(this.audioContext),s.source=st.Source.Microphone,this.emit(qt.AudioStreamAcquired)),Fd(s)&&(this.cameraError=void 0,s.source=st.Source.Camera),s))}catch(g){throw g instanceof Error&&(A.audio&&(this.microphoneError=g),A.video&&(this.cameraError=g)),g}})}createScreenTracks(A){return zA(this,void 0,void 0,function*(){if(A===void 0&&(A={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new bz("getDisplayMedia not supported");A.resolution===void 0&&!zWA()&&(A.resolution=Uz.h1080fps30.resolution);const t=FWA(A),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(n.length===0)throw new yE("no video track found");const g=new r_(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});g.source=st.Source.ScreenShare,A.contentHint&&(g.mediaStreamTrack.contentHint=A.contentHint);const o=[g];if(i.getAudioTracks().length>0){this.emit(qt.AudioStreamAcquired);const s=new a_(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=st.Source.ScreenShareAudio,o.push(s)}return o})}publishTrack(A,t){return zA(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(A,t)})}publishOrRepublishTrack(A,t){return zA(this,arguments,void 0,function(i,n){var g=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var s,a,r,I;aE(i)&&i.setAudioContext(g.audioContext),yield(s=g.reconnectFuture)===null||s===void 0?void 0:s.promise,g.republishPromise&&!o&&(yield g.republishPromise),Lm(i)&&g.pendingPublishPromises.has(i)&&(yield g.pendingPublishPromises.get(i));let c;if(i instanceof MediaStreamTrack)c=i.getConstraints();else{c=i.constraints;let p;switch(i.source){case st.Source.Microphone:p="audioinput";break;case st.Source.Camera:p="videoinput"}p&&g.activeDeviceMap.has(p)&&(c=Object.assign(Object.assign({},c),{deviceId:g.activeDeviceMap.get(p)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new a_(i,c,!0,g.audioContext,{loggerName:g.roomOptions.loggerName,loggerContextCb:()=>g.logContext});break;case"video":i=new r_(i,c,!0,{loggerName:g.roomOptions.loggerName,loggerContextCb:()=>g.logContext});break;default:throw new yE("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:g.roomOptions.loggerName,loggerContextCb:()=>g.logContext});let l;if(g.trackPublications.forEach(p=>{p.track&&p.track===i&&(l=p)}),l)return g.log.warn("track has already been published, skipping",Object.assign(Object.assign({},g.logContext),Gn(l))),l;const B=Object.assign(Object.assign({},g.roomOptions.publishDefaults),n),Q="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,h=(a=B.forceStereo)!==null&&a!==void 0?a:Q;h&&(B.dtx===void 0&&g.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},g.logContext),Gn(i))),B.red===void 0&&g.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(r=B.dtx)!==null&&r!==void 0||(B.dtx=!1),(I=B.red)!==null&&I!==void 0||(B.red=!1)),!WWA()&&g.roomOptions.e2ee&&(g.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},g.logContext)),B.simulcast=!1),B.source&&(i.source=B.source);const d=new Promise((p,y)=>zA(g,void 0,void 0,function*(){try{if(this.engine.client.currentState!==_g.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Gn(i)}));let m=!1;const D=setTimeout(()=>{m=!0,i.stop(),y(new wAA("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(D),m)return;const S=yield this.publish(i,B,h);p(S)}else try{const m=yield this.publish(i,B,h);p(m)}catch(m){y(m)}}catch(m){y(m)}}));g.pendingPublishPromises.set(i,d);try{return yield d}catch(p){throw p}finally{g.pendingPublishPromises.delete(i)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new WC),this.signalConnectedFuture.promise}hasPermissionsToPublish(A){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Gn(A))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(n=>xWA(n)).includes(A.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Gn(A))),!1)}publish(A,t,i){return zA(this,void 0,void 0,function*(){var n,g,o,s,a,r,I,c,l,B;if(!this.hasPermissionsToPublish(A))throw new wAA("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>Lm(A)&&M.source===A.source)&&A.source!==st.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(A.source),Object.assign(Object.assign({},this.logContext),Gn(A))),t.stopMicTrackOnMute&&cB(A)&&(A.stopOnMute=!0),A.source===st.Source.ScreenShare&&Cf()&&(t.simulcast=!1),t.videoCodec==="av1"&&!OWA()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!PWA()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=y3),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===CM(M.mime))||(t.videoCodec=CM(this.enabledPublishVideoCodecs[0].mime)));const h=t.videoCodec;A.on(Gt.Muted,this.onTrackMuted),A.on(Gt.Unmuted,this.onTrackUnmuted),A.on(Gt.Ended,this.handleTrackEnded),A.on(Gt.UpstreamPaused,this.onTrackUpstreamPaused),A.on(Gt.UpstreamResumed,this.onTrackUpstreamResumed),A.on(Gt.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const d=[],p=!(!((n=t.dtx)!==null&&n!==void 0)||n),y=A.getSourceTrackSettings();y.autoGainControl&&d.push(ia.TF_AUTO_GAIN_CONTROL),y.echoCancellation&&d.push(ia.TF_ECHO_CANCELLATION),y.noiseSuppression&&d.push(ia.TF_NOISE_SUPPRESSION),y.channelCount&&y.channelCount>1&&d.push(ia.TF_STEREO),p&&d.push(ia.TF_NO_DTX),aE(A)&&A.hasPreConnectBuffer&&d.push(ia.TF_PRECONNECT_BUFFER);const m=new BN({cid:A.mediaStreamTrack.id,name:t.name,type:st.kindToProto(A.kind),muted:A.isMuted,source:st.sourceToProto(A.source),disableDtx:p,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((g=t.red)!==null&&g!==void 0)||g),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:d});let D;if(A.kind===st.Kind.Video){let M={width:0,height:0};try{M=yield A.waitForDimensions()}catch{const b=(s=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&s!==void 0?s:GS.h720.resolution;M={width:b.width,height:b.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Gn(A)),{dims:M}))}m.width=M.width,m.height=M.height,vQ(A)&&(Hc(h)&&(A.source===st.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in A.mediaStreamTrack&&(A.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Gn(A))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),m.simulcastCodecs=[new g3({codec:h,cid:A.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:y3}),t.backupCodec&&h!==t.backupCodec.codec&&m.encryption===Js.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new g3({codec:t.backupCodec.codec,cid:""})))),D=m3(A.source===st.Source.ScreenShare,m.width,m.height,t),m.layers=AeA(m.width,m.height,D,Hc(t.videoCodec))}else A.kind===st.Kind.Audio&&(D=[{maxBitrate:(r=t.audioPreset)===null||r===void 0?void 0:r.maxBitrate,priority:(c=(I=t.audioPreset)===null||I===void 0?void 0:I.priority)!==null&&c!==void 0?c:"high",networkPriority:(B=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&B!==void 0?B:"high"}]);if(!this.engine||this.engine.isClosed)throw new zo("cannot publish track when not connected");const S=()=>zA(this,void 0,void 0,function*(){var M,w,b;if(!this.engine.pcManager)throw new zo("pcManager is not ready");if(A.sender=yield this.engine.createSender(A,t,D),this.emit(qt.LocalSenderCreated,A.sender,A),vQ(A)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=t9A(A)),A.setDegradationPreference(t.degradationPreference)),D)if(Cf()&&A.kind===st.Kind.Audio){let _;for(const K of this.engine.pcManager.publisher.getTransceivers())if(K.sender===A.sender){_=K;break}_&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:_,codec:"opus",maxbr:!((w=D[0])===null||w===void 0)&&w.maxBitrate?D[0].maxBitrate/1e3:0})}else A.codec&&Hc(A.codec)&&(!((b=D[0])===null||b===void 0)&&b.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:m.cid,codec:A.codec,maxbr:D[0].maxBitrate/1e3});yield this.engine.negotiate()});let k;const N=new Promise((M,w)=>zA(this,void 0,void 0,function*(){var b;try{k=yield this.engine.addTrack(m),M(k)}catch(_){A.sender&&(!((b=this.engine.pcManager)===null||b===void 0)&&b.publisher)&&(this.engine.pcManager.publisher.removeTrack(A.sender),yield this.engine.negotiate().catch(K=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),Gn(A)),{error:K}))})),w(_)}}));if(this.enabledPublishVideoCodecs.length>0)k=(yield Promise.all([N,S()]))[0];else{k=yield N;let M;if(k.codecs.forEach(w=>{M===void 0&&(M=w.mimeType)}),M&&A.kind===st.Kind.Video){const w=CM(M);w!==h&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Gn(A)),{codec:w})),t.videoCodec=w,D=m3(A.source===st.Source.ScreenShare,m.width,m.height,t))}yield S()}const G=new w3(A.kind,k,A,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(G.on(Gt.CpuConstrained,M=>this.onTrackCpuConstrained(M,G)),G.options=t,A.sid=k.sid,this.log.debug("publishing ".concat(A.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:D,trackInfo:k})),vQ(A)?A.startMonitor(this.engine.client):aE(A)&&A.startMonitor(),this.addTrackPublication(G),this.emit(qt.LocalTrackPublished,G),aE(A)&&k.audioFeatures.includes(ia.TF_PRECONNECT_BUFFER)){const M=A.getPreConnectBuffer(),w=A.getPreConnectBufferMimeType();this.on(qt.LocalTrackSubscribed,b=>{if(b.trackSid===k.sid){if(!A.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),Gn(A))),A.stopPreConnectBuffer()}}),M&&new Promise((_,K)=>zA(this,void 0,void 0,function*(){var J,q,v,U,x,T;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Gn(A)));const aA=setTimeout(()=>{K(new Error("agent not active within 10 seconds"))},1e4),sA=yield this.waitUntilActiveAgentPresent();clearTimeout(aA),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Gn(A)));const pA=yield this.streamBytes({name:"preconnect-buffer",mimeType:w,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[sA.identity],attributes:{trackId:G.trackSid,sampleRate:String((x=y.sampleRate)!==null&&x!==void 0?x:"48000"),channels:String((T=y.channelCount)!==null&&T!==void 0?T:"1")}});try{for(var z=!0,Z=fE(M),eA;eA=yield Z.next(),J=eA.done,!J;z=!0){U=eA.value,z=!1;const gA=U;yield pA.write(gA)}}catch(gA){q={error:gA}}finally{try{!z&&!J&&(v=Z.return)&&(yield v.call(Z))}finally{if(q)throw q.error}}yield pA.close(),_()}catch(aA){K(aA)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Gn(A)))}).catch(_=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Gn(A)),{error:_}))})}return G})}get isLocal(){return!0}publishAdditionalCodecForTrack(A,t,i){return zA(this,void 0,void 0,function*(){var n;if(this.encryptionType!==Js.NONE)return;let g;if(this.trackPublications.forEach(B=>{B.track&&B.track===A&&(g=B)}),!g)throw new yE("track is not published");if(!vQ(A))throw new yE("track is not a video track");const o=Object.assign(Object.assign({},(n=this.roomOptions)===null||n===void 0?void 0:n.publishDefaults),i),s=$VA(A,t,o);if(!s){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Gn(A)));return}const a=A.addSimulcastTrack(t,s);if(!a)return;const r=new BN({cid:a.mediaStreamTrack.id,type:st.kindToProto(A.kind),muted:A.isMuted,source:st.sourceToProto(A.source),sid:A.sid,simulcastCodecs:[{codec:o.videoCodec,cid:a.mediaStreamTrack.id}]});if(r.layers=AeA(r.width,r.height,s),!this.engine||this.engine.isClosed)throw new zo("cannot publish track when not connected");const I=()=>zA(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(A,a,o,s),yield this.engine.negotiate()}),l=(yield Promise.all([this.engine.addTrack(r),I()]))[0];this.log.debug("published ".concat(t," for track ").concat(A.sid),Object.assign(Object.assign({},this.logContext),{encodings:s,trackInfo:l}))})}unpublishTrack(A,t){return zA(this,void 0,void 0,function*(){var i,n;if(Lm(A)){const r=this.pendingPublishPromises.get(A);r&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Gn(A))),yield r)}const g=this.getPublicationForTrack(A),o=g?Gn(g):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!g||!g.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}A=g.track,A.off(Gt.Muted,this.onTrackMuted),A.off(Gt.Unmuted,this.onTrackUnmuted),A.off(Gt.Ended,this.handleTrackEnded),A.off(Gt.UpstreamPaused,this.onTrackUpstreamPaused),A.off(Gt.UpstreamResumed,this.onTrackUpstreamResumed),A.off(Gt.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(n=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&n!==void 0?n:!0),t?A.stop():A.stopMonitor();let s=!1;const a=A.sender;if(A.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Fo.FAILED&&a)try{for(const r of this.engine.pcManager.publisher.getTransceivers())r.sender===a&&(r.direction="inactive",s=!0);if(this.engine.removeTrack(a)&&(s=!0),vQ(A)){for(const[,r]of A.simulcastCodecs)r.sender&&(this.engine.removeTrack(r.sender)&&(s=!0),r.sender=void 0);A.simulcastCodecs.clear()}}catch(r){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:r}))}switch(this.trackPublications.delete(g.trackSid),g.kind){case st.Kind.Audio:this.audioTrackPublications.delete(g.trackSid);break;case st.Kind.Video:this.videoTrackPublications.delete(g.trackSid);break}return this.emit(qt.LocalTrackUnpublished,g),g.setTrack(void 0),s&&(yield this.engine.negotiate()),g})}unpublishTracks(A){return zA(this,void 0,void 0,function*(){return(yield Promise.all(A.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(A){return zA(this,arguments,void 0,function(t){var i=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new tI((g,o)=>zA(i,void 0,void 0,function*(){try{const s=[];this.trackPublications.forEach(a=>{a.track&&(t&&(a.options=Object.assign(Object.assign({},a.options),t)),s.push(a))}),yield Promise.all(s.map(a=>zA(this,void 0,void 0,function*(){const r=a.track;yield this.unpublishTrack(r,!1),n&&!r.isMuted&&r.source!==st.Source.ScreenShare&&r.source!==st.Source.ScreenShareAudio&&(aE(r)||vQ(r))&&!r.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield r.restartTrack()),yield this.publishOrRepublishTrack(r,a.options,!0)}))),g()}catch(s){s instanceof Error?o(s):o(new Error(String(s)))}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(A){return zA(this,arguments,void 0,function(t){var i=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const g=n.reliable?Mn.RELIABLE:Mn.LOSSY,o=n.destinationIdentities,s=n.topic;let a=new fz({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:s});const r=new Dr({kind:g,value:{case:"user",value:a}});yield i.engine.sendDataPacket(r,g)}()})}publishDtmf(A,t){return zA(this,void 0,void 0,function*(){const i=new Dr({kind:Mn.RELIABLE,value:{case:"sipDtmf",value:new VQA({code:A,digit:t})}});yield this.engine.sendDataPacket(i,Mn.RELIABLE)})}sendChatMessage(A,t){return zA(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:A,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},n=new Dr({value:{case:"chatMessage",value:new i_(Object.assign(Object.assign({},i),{timestamp:Bo.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,Mn.RELIABLE),this.emit(qt.ChatMessage,i),i})}editChatMessage(A,t){return zA(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:A,editTimestamp:Date.now()}),n=new Dr({value:{case:"chatMessage",value:new i_(Object.assign(Object.assign({},i),{timestamp:Bo.parse(i.timestamp),editTimestamp:Bo.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,Mn.RELIABLE),this.emit(qt.ChatMessage,i),i})}sendText(A,t){return zA(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(A,t)})}streamText(A){return zA(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(A)})}sendFile(A,t){return zA(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(A,t)})}streamBytes(A){return zA(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(A)})}performRpc(A){let{destinationIdentity:t,method:i,payload:n,responseTimeout:g=15e3}=A;const o=7e3,s=o+1e3;return new tI((a,r)=>zA(this,void 0,void 0,function*(){var I,c,l,B;if(Tz(n)>sdA){r(mr.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((c=(I=this.engine.latestJoinResponse)===null||I===void 0?void 0:I.serverInfo)===null||c===void 0)&&c.version&&fB((B=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||B===void 0?void 0:B.version,"1.8.0")<0){r(mr.builtIn("UNSUPPORTED_SERVER"));return}const Q=Math.max(g,s),h=crypto.randomUUID();yield this.publishRpcRequest(t,h,i,n,Q);const d=setTimeout(()=>{this.pendingAcks.delete(h),r(mr.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(h),clearTimeout(p)},o);this.pendingAcks.set(h,{resolve:()=>{clearTimeout(d)},participantIdentity:t});const p=setTimeout(()=>{this.pendingResponses.delete(h),r(mr.builtIn("RESPONSE_TIMEOUT"))},g);this.pendingResponses.set(h,{resolve:(y,m)=>{clearTimeout(p),this.pendingAcks.has(h)&&(this.log.warn("RPC response received before ack",h),this.pendingAcks.delete(h),clearTimeout(d)),m?r(m):a(y??"")},participantIdentity:t})}))}registerRpcMethod(A,t){this.rpcHandlers.has(A)&&this.log.warn("you're overriding the RPC handler for method ".concat(A,", in the future this will throw an error")),this.rpcHandlers.set(A,t)}unregisterRpcMethod(A){this.rpcHandlers.delete(A)}setTrackSubscriptionPermissions(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=A,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(A){const t=this.pendingAcks.get(A);t?(t.resolve(),this.pendingAcks.delete(A)):console.error("Ack received for unexpected RPC request",A)}handleIncomingRpcResponse(A,t,i){const n=this.pendingResponses.get(A);n?(n.resolve(t,i),this.pendingResponses.delete(A)):console.error("Response received for unexpected RPC request",A)}publishRpcRequest(A,t,i,n,g){return zA(this,void 0,void 0,function*(){const o=new Dr({destinationIdentities:[A],kind:Mn.RELIABLE,value:{case:"rpcRequest",value:new yz({id:t,method:i,payload:n,responseTimeoutMs:g,version:1})}});yield this.engine.sendDataPacket(o,Mn.RELIABLE)})}handleParticipantDisconnected(A){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===A&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===A&&(n(null,mr.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(A){this.enabledPublishVideoCodecs=A.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(A){return super.updateInfo(A)?(A.tracks.forEach(t=>{var i,n;const g=this.trackPublications.get(t.sid);if(g){const o=g.isMuted||((n=(i=g.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&n!==void 0?n:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Gn(g)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0):!1}setActiveAgent(A){var t,i,n,g;this.firstActiveAgent=A,A&&!this.firstActiveAgent&&(this.firstActiveAgent=A),A?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,A):(g=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.reject)===null||g===void 0||g.call(n,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new WC),this.activeAgentFuture.promise)}getPublicationForTrack(A){let t;return this.trackPublications.forEach(i=>{const n=i.track;n&&(A instanceof MediaStreamTrack?(aE(n)||vQ(n))&&n.mediaStreamTrack===A&&(t=i):A===n&&(t=i))}),t}waitForPendingPublicationOfSource(A){return zA(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const n=Array.from(this.pendingPublishPromises.entries()).find(g=>{let[o]=g;return o.source===A});if(n)return n[1];yield Ga(20)}})}}class m9A extends EE{constructor(A,t,i,n){super(A,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=g=>{this.setTrack(void 0),this.emit(Gt.Ended,g)},this.handleVisibilityChange=g=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(g),this.logContext),this.visible=g,this.emitTrackUpdate()},this.handleVideoDimensionsChange=g=>{this.log.debug("adaptivestream video dimensions ".concat(g.width,"x").concat(g.height),this.logContext),this.videoDimensionsAdaptiveStream=g,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(A){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=A,A&&(this.allowed=!0);const n=new Ax({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new $QA({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Gt.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?EE.SubscriptionStatus.Unsubscribed:super.isSubscribed?EE.SubscriptionStatus.Subscribed:EE.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?EE.PermissionStatus.Allowed:EE.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(A){!this.isManualOperationAllowed()||this.requestedDisabled===!A||(this.requestedDisabled=!A,this.emitTrackUpdate())}setVideoQuality(A){!this.isManualOperationAllowed()||this.requestedMaxQuality===A||(this.requestedMaxQuality=A,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(A){var t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===A.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===A.height||(AY(this.track)&&(this.requestedVideoDimensions=A),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(A){this.isManualOperationAllowed()&&AY(this.track)&&this.fps!==A&&(this.fps=A,this.emitTrackUpdate())}get videoQuality(){var A;return(A=this.requestedMaxQuality)!==null&&A!==void 0?A:PI.HIGH}setTrack(A){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==A&&(n&&(n.off(Gt.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Gt.VisibilityChanged,this.handleVisibilityChange),n.off(Gt.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Gt.Unsubscribed,n)),super.setTrack(A),A&&(A.sid=this.trackSid,A.on(Gt.VideoDimensionsChanged,this.handleVideoDimensionsChange),A.on(Gt.VisibilityChanged,this.handleVisibilityChange),A.on(Gt.Ended,this.handleEnded),this.emit(Gt.Subscribed,A)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(A){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=A,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(A){this.emit(Gt.SubscriptionFailed,A)}updateInfo(A){super.updateInfo(A);const t=this.metadataMuted;this.metadataMuted=A.muted,this.track?this.track.setMuted(A.muted):t!==A.muted&&this.emit(A.muted?Gt.Muted:Gt.Unmuted)}emitSubscriptionUpdateIfChanged(A){const t=this.subscriptionStatus;A!==t&&this.emit(Gt.SubscriptionStatusChanged,t,A)}emitPermissionUpdateIfChanged(A){this.permissionStatus!==A&&this.emit(Gt.SubscriptionPermissionChanged,this.permissionStatus,A)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return AY(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const A=new auA({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===st.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)NAA(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=TWA(this.trackInfo,this.requestedMaxQuality);i&&NAA(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(A.width=Math.ceil(t.width),A.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),A.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:PI.HIGH})),A.quality=PI.HIGH)}this.emit(Gt.UpdateSettings,A)}}class I_ extends BdA{static fromParticipantInfo(A,t,i){return new I_(A,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(A,t,i,n,g,o,s){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:lN.STANDARD;super(t,i||"",n,g,o,s,a),this.signalClient=A,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(A){super.addTrackPublication(A),A.on(Gt.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Gn(A)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),A.on(Gt.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),A.on(Gt.SubscriptionPermissionChanged,t=>{this.emit(qt.TrackSubscriptionPermissionChanged,A,t)}),A.on(Gt.SubscriptionStatusChanged,t=>{this.emit(qt.TrackSubscriptionStatusChanged,A,t)}),A.on(Gt.Subscribed,t=>{this.emit(qt.TrackSubscribed,t,A)}),A.on(Gt.Unsubscribed,t=>{this.emit(qt.TrackUnsubscribed,t,A)}),A.on(Gt.SubscriptionFailed,t=>{this.emit(qt.TrackSubscriptionFailed,A.trackSid,t)})}getTrackPublication(A){const t=super.getTrackPublication(A);if(t)return t}getTrackPublicationByName(A){const t=super.getTrackPublicationByName(A);if(t)return t}setVolume(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:st.Source.Microphone;this.volumeMap.set(t,A);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(A)}getVolume(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:st.Source.Microphone;const t=this.getTrackPublication(A);return t&&t.track?t.track.getVolume():this.volumeMap.get(A)}addSubscribedMediaTrack(A,t,i,n,g,o){let s=this.getTrackPublicationBySid(t);if(s||t.startsWith("TR")||this.trackPublications.forEach(I=>{!s&&A.kind===I.kind.toString()&&(s=I)}),!s){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(qt.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(A,t,i,n,g,o-1)},150);return}if(A.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Gn(s))),this.emit(qt.TrackSubscriptionFailed,t);return}const a=A.kind==="video";let r;return a?r=new u9A(A,t,n,g):r=new Q9A(A,t,n,this.audioContext,this.audioOutput),r.source=s.source,r.isMuted=s.isMuted,r.setMediaStream(i),r.start(),s.setTrack(r),this.volumeMap.has(s.source)&&p3(r)&&cB(r)&&r.setVolume(this.volumeMap.get(s.source)),s}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(A){return this.trackPublications.get(A)}updateInfo(A){if(!super.updateInfo(A))return!1;const t=new Map,i=new Map;return A.tracks.forEach(n=>{var g,o;let s=this.getTrackPublicationBySid(n.sid);if(s)s.updateInfo(n);else{const a=st.kindFromProto(n.type);if(!a)return;s=new m9A(a,n,(g=this.signalClient.connectOptions)===null||g===void 0?void 0:g.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),s.updateInfo(n),i.set(n.sid,s);const r=Array.from(this.trackPublications.values()).find(I=>I.source===(s==null?void 0:s.source));r&&s.source!==st.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Gn(r),newTrack:Gn(s)})),this.addTrackPublication(s)}t.set(n.sid,s)}),this.trackPublications.forEach(n=>{t.has(n.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Gn(n))),this.unpublishTrack(n.trackSid,!0))}),i.forEach(n=>{this.emit(qt.TrackPublished,n)}),!0}unpublishTrack(A,t){const i=this.trackPublications.get(A);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(A),i.kind){case st.Kind.Audio:this.audioTrackPublications.delete(A);break;case st.Kind.Video:this.videoTrackPublications.delete(A);break}t&&this.emit(qt.TrackUnpublished,i)}setAudioOutput(A){return zA(this,void 0,void 0,function*(){this.audioOutput=A;const t=[];this.audioTrackPublications.forEach(i=>{var n;cB(i.track)&&p3(i.track)&&t.push(i.track.setSinkId((n=A.deviceId)!==null&&n!==void 0?n:"default"))}),yield Promise.all(t)})}emit(A){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:A,args:i})),super.emit(A,...i)}}var Xn;(function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"})(Xn||(Xn={}));const S9A=4*1e3;class US extends RB.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(A){var t,i,n,g,o;if(super(),t=this,this.state=Xn.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ln,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(s,a,r)=>zA(this,void 0,void 0,function*(){var I;if(!jWA())throw pB()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const c=yield this.disconnectLock.lock();if(this.state===Xn.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),c(),Promise.resolve();if(this.connectFuture)return c(),this.connectFuture.promise;this.setAndEmitConnectionState(Xn.Connecting),((I=this.regionUrlProvider)===null||I===void 0?void 0:I.getServerUrl().toString())!==idA(s)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),bS(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new tg(s,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(Q=>{var h;(h=this.regionUrlProvider)===null||h===void 0||h.setServerReportedRegions(Q)}).catch(Q=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:Q}))}));const l=(Q,h,d)=>zA(this,void 0,void 0,function*(){var p,y;this.abortController&&this.abortController.abort();const m=new AbortController;this.abortController=m,c==null||c();try{if(yield xm.getInstance().getBackOffPromise(s),m.signal.aborted)throw Mi.cancelled("Connection attempt aborted");yield this.attemptConnection(d??s,a,r,m),this.abortController=void 0,Q()}catch(D){if(this.regionUrlProvider&&D instanceof Mi&&D.reason!==Lg.Cancelled&&D.reason!==Lg.NotAllowed){let S=null;try{this.log.debug("Fetching next region"),S=yield this.regionUrlProvider.getNextBestRegionUrl((p=this.abortController)===null||p===void 0?void 0:p.signal)}catch(k){if(k instanceof Mi&&(k.status===401||k.reason===Lg.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),h(k);return}}[Lg.InternalError,Lg.ServerUnreachable,Lg.Timeout].includes(D.reason)&&(this.log.debug("Adding failed connection attempt to back off"),xm.getInstance().addFailedConnectionAttempt(s)),S&&!(!((y=this.abortController)===null||y===void 0)&&y.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(D.message,". Retrying with another region: ").concat(S),this.logContext),this.recreateEngine(),yield l(Q,h,S)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,FAA(D)),h(D))}else{let S=jc.UNKNOWN_REASON;D instanceof Mi&&(S=FAA(D)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,S),h(D)}}}),B=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new WC((Q,h)=>{l(Q,h,B)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,a,r,I,c,l)=>zA(this,void 0,void 0,function*(){var B,Q,h;const d=yield r.join(s,a,{autoSubscribe:I.autoSubscribe,adaptiveStream:typeof c.adaptiveStream=="object"?!0:c.adaptiveStream,maxRetries:I.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:I.websocketTimeout},l.signal,!c.singlePeerConnection);let p=d.serverInfo;if(p||(p={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=p,this.log.debug("connected to Livekit Server ".concat(Object.entries(p).map(y=>{let[m,D]=y;return"".concat(m,": ").concat(D)}).join(", ")),{room:(B=d.room)===null||B===void 0?void 0:B.name,roomSid:(Q=d.room)===null||Q===void 0?void 0:Q.sid,identity:(h=d.participant)===null||h===void 0?void 0:h.identity}),!p.version)throw new NWA("unknown server version");return p.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),c.dynacast=!1),d}),this.applyJoinResponse=s=>{const a=s.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(r){this.log.error(r instanceof Error?r.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:r}))}this.handleParticipantUpdates([a,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,a,r,I)=>zA(this,void 0,void 0,function*(){var c,l;this.state===Xn.Reconnecting||this.isResuming||!((c=this.engine)===null||c===void 0)&&c.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},xz),r),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const B=yield this.connectSignal(s,a,this.engine,this.connOptions,this.options,I);this.applyJoinResponse(B),this.setupLocalParticipantEvents(),this.emit(yt.SignalConnected)}catch(B){yield this.engine.close(),this.recreateEngine();const Q=I.signal.aborted?Mi.cancelled("Signal connection aborted"):Mi.serverUnreachable("could not establish signal connection");throw B instanceof Error&&(Q.message="".concat(Q.message,": ").concat(B.message)),B instanceof Mi&&(Q.reason=B.reason,Q.status=B.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:B})),Q}if(I.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),Mi.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,I)}catch(B){throw yield this.engine.close(),this.recreateEngine(),B}iI()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),iI()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Xn.Connected),this.emit(yt.Connected),xm.getInstance().resetFailedConnectionAttempts(s),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var s=arguments.length,a=new Array(s),r=0;r<s;r++)a[r]=arguments[r];return zA(t,[...a],void 0,function(){var I=this;let c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var l,B,Q;const h=yield I.disconnectLock.lock();try{if(I.state===Xn.Disconnected){I.log.debug("already disconnected",I.logContext);return}if(I.log.info("disconnect from room",Object.assign({},I.logContext)),I.state===Xn.Connecting||I.state===Xn.Reconnecting||I.isResuming){const d="Abort connection attempt due to user initiated disconnect";I.log.warn(d,I.logContext),(l=I.abortController)===null||l===void 0||l.abort(d),(Q=(B=I.connectFuture)===null||B===void 0?void 0:B.reject)===null||Q===void 0||Q.call(B,Mi.cancelled("Client initiated disconnect")),I.connectFuture=void 0}I.engine&&(I.engine.client.isDisconnected||(yield I.engine.client.sendLeave()),yield I.engine.close()),I.handleDisconnect(c,jc.CLIENT_INITIATED),I.engine=void 0}finally{h()}}()})},this.onPageLeave=()=>zA(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>zA(this,void 0,void 0,function*(){const s=[],a=rI();if(a&&a.os==="iOS"){const r="livekit-dummy-audio-el";let I=document.getElementById(r);if(!I){I=document.createElement("audio"),I.id=r,I.autoplay=!0,I.hidden=!0;const c=$2();c.enabled=!0;const l=new MediaStream([c]);I.srcObject=l,document.addEventListener("visibilitychange",()=>{I&&(I.srcObject=document.hidden?null:l,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(I),this.once(yt.Disconnected,()=>{I==null||I.remove(),I=null})}s.push(I)}this.remoteParticipants.forEach(r=>{r.audioTrackPublications.forEach(I=>{I.track&&I.track.attachedElements.forEach(c=>{s.push(c)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(r=>(r.muted=!1,r.play()))]),this.handleAudioPlaybackStarted()}catch(r){throw this.handleAudioPlaybackFailed(r),r}}),this.startVideo=()=>zA(this,void 0,void 0,function*(){const s=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(r=>{var I;(I=r.track)===null||I===void 0||I.attachedElements.forEach(c=>{s.includes(c)||s.push(c)})});yield Promise.all(s.map(a=>a.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(a=>{a.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const s of this.remoteParticipants.values())this.handleParticipantDisconnected(s.identity,s);this.setAndEmitConnectionState(Xn.Reconnecting)&&this.emit(yt.Reconnecting)},this.handleSignalRestarted=s=>zA(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(s.serverRegion),Object.assign(Object.assign({},this.logContext),{region:s.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(s);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(a){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:a}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:s.serverRegion}))}catch{return}this.setAndEmitConnectionState(Xn.Connected),this.emit(yt.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(a=>{var r;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(r=this.sidToIdentity.get(a.sid))!==null&&r!==void 0?r:"");let I=this.remoteParticipants.get(a.identity);a.state===vm.DISCONNECTED?this.handleParticipantDisconnected(a.identity,I):I=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=s=>{const a=[],r={};s.forEach(I=>{if(r[I.sid]=!0,I.sid===this.localParticipant.sid)this.localParticipant.audioLevel=I.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const c=this.getRemoteParticipantBySid(I.sid);c&&(c.audioLevel=I.level,c.setIsSpeaking(!0),a.push(c))}}),r[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(I=>{r[I.sid]||(I.audioLevel=0,I.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(yt.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=s=>{const a=new Map;this.activeSpeakers.forEach(I=>{const c=this.remoteParticipants.get(I.identity);c&&c.sid!==I.sid||a.set(I.sid,I)}),s.forEach(I=>{let c=this.getRemoteParticipantBySid(I.sid);I.sid===this.localParticipant.sid&&(c=this.localParticipant),c&&(c.audioLevel=I.level,c.setIsSpeaking(I.active),I.active?a.set(I.sid,c):a.delete(I.sid))});const r=Array.from(a.values());r.sort((I,c)=>c.audioLevel-I.audioLevel),this.activeSpeakers=r,this.emitWhenConnected(yt.ActiveSpeakersChanged,r)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(a=>{const r=this.getRemoteParticipantBySid(a.participantSid);if(!r)return;const I=r.getTrackPublicationBySid(a.trackSid);if(!I||!I.track)return;const c=st.streamStateFromProto(a.state);I.track.setStreamState(c),c!==I.track.streamState&&(r.emit(qt.TrackStreamStateChanged,I,I.track.streamState),this.emitWhenConnected(yt.TrackStreamStateChanged,I,I.track.streamState,r))})},this.handleSubscriptionPermissionUpdate=s=>{const a=this.getRemoteParticipantBySid(s.participantSid);if(!a)return;const r=a.getTrackPublicationBySid(s.trackSid);r&&r.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const a=Array.from(this.remoteParticipants.values()).find(I=>I.trackPublications.has(s.trackSid));if(!a)return;const r=a.getTrackPublicationBySid(s.trackSid);r&&r.setSubscriptionError(s.err)},this.handleDataPacket=(s,a)=>{const r=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(r,s.value.value,s.kind,a);else if(s.value.case==="transcription")this.handleTranscription(r,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(r,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(r,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,r);else if(s.value.case==="streamHeader"||s.value.case==="streamChunk"||s.value.case==="streamTrailer")this.handleDataStream(s,a);else if(s.value.case==="rpcRequest"){const I=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,I.id,I.method,I.payload,I.responseTimeoutMs,I.version)}},this.handleUserPacket=(s,a,r,I)=>{this.emit(yt.DataReceived,a.payload,s,r,a.topic,I),s==null||s.emit(qt.DataReceived,a.payload,r,I)},this.handleSipDtmf=(s,a)=>{this.emit(yt.SipDTMFReceived,a,s),s==null||s.emit(qt.SipDTMFReceived,a)},this.handleTranscription=(s,a)=>{const r=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),I=r==null?void 0:r.trackPublications.get(a.trackId),c=tVA(a,this.transcriptionReceivedTimes);I==null||I.emit(Gt.TranscriptionReceived,c),r==null||r.emit(qt.TranscriptionReceived,c,I),this.emit(yt.TranscriptionReceived,c,r,I)},this.handleChatMessage=(s,a)=>{const r=iVA(a);this.emit(yt.ChatMessage,r,s)},this.handleMetrics=(s,a)=>{this.emit(yt.MetricsReceived,s,a)},this.handleDataStream=(s,a)=>{this.incomingDataStreamManager.handleDataStreamPacket(s,a)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(yt.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:s})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(yt.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(yt.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(yt.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>zA(this,void 0,void 0,function*(){var s;((s=rI())===null||s===void 0?void 0:s.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(yt.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const a=this.roomInfo;this.roomInfo=s,a&&a.metadata!==s.metadata&&this.emitWhenConnected(yt.RoomMetadataChanged,s.metadata),(a==null?void 0:a.activeRecording)!==s.activeRecording&&this.emitWhenConnected(yt.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const r=this.getRemoteParticipantBySid(a.participantSid);r&&r.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(yt.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(yt.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(yt.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(yt.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(yt.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var a;(a=s==null?void 0:s.onPublish)===null||a===void 0||a.call(s,this)},this.onLocalTrackPublished=s=>zA(this,void 0,void 0,function*(){var a,r,I,c,l,B;(a=s.track)===null||a===void 0||a.on(Gt.TrackProcessorUpdate,this.onTrackProcessorUpdate),(r=s.track)===null||r===void 0||r.on(Gt.Restarted,this.onLocalTrackRestarted),(l=(c=(I=s.track)===null||I===void 0?void 0:I.getProcessor())===null||c===void 0?void 0:c.onPublish)===null||l===void 0||l.call(c,this),this.emit(yt.LocalTrackPublished,s,this.localParticipant),aE(s.track)&&(yield s.track.checkForSilence())&&this.emit(yt.LocalAudioSilenceDetected,s);const Q=yield(B=s.track)===null||B===void 0?void 0:B.getDeviceId(!1),h=Q3(s.source);h&&Q&&Q!==this.localParticipant.activeDeviceMap.get(h)&&(this.localParticipant.activeDeviceMap.set(h,Q),this.emit(yt.ActiveDeviceChanged,h,Q))}),this.onLocalTrackUnpublished=s=>{var a,r;(a=s.track)===null||a===void 0||a.off(Gt.TrackProcessorUpdate,this.onTrackProcessorUpdate),(r=s.track)===null||r===void 0||r.off(Gt.Restarted,this.onLocalTrackRestarted),this.emit(yt.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>zA(this,void 0,void 0,function*(){const a=yield s.getDeviceId(!1),r=Q3(s.source);r&&a&&a!==this.localParticipant.activeDeviceMap.get(r)&&(this.log.debug("local track restarted, setting ".concat(r," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(r,a),this.emit(yt.ActiveDeviceChanged,r,a))}),this.onLocalConnectionQualityChanged=s=>{this.emit(yt.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=(s,a)=>{this.emit(yt.MediaDevicesError,s,a)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(yt.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(yt.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},FVA),A),this.log=eQ((i=this.options.loggerName)!==null&&i!==void 0?i:el.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},ndA),A==null?void 0:A.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},gdA),A==null?void 0:A.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},KVA),A==null?void 0:A.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new c9A,this.outgoingDataStreamManager=new E9A(this.engine,this.log),this.disconnectLock=new vr,this.localParticipant=new D9A("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Wu(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Wu(this.options.audioCaptureDefaults.deviceId)),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&this.switchActiveDevice("audiooutput",Wu(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),iI()){const s=new AbortController;(o=(g=navigator.mediaDevices)===null||g===void 0?void 0:g.addEventListener)===null||o===void 0||o.call(g,"devicechange",this.handleDeviceChange,{signal:s.signal}),US.cleanupRegistry&&US.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(A,t){return this.incomingDataStreamManager.registerTextStreamHandler(A,t)}unregisterTextStreamHandler(A){return this.incomingDataStreamManager.unregisterTextStreamHandler(A)}registerByteStreamHandler(A,t){return this.incomingDataStreamManager.registerByteStreamHandler(A,t)}unregisterByteStreamHandler(A){return this.incomingDataStreamManager.unregisterByteStreamHandler(A)}registerRpcMethod(A,t){if(this.rpcHandlers.has(A))throw Error("RPC handler already registered for method ".concat(A,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(A,t)}unregisterRpcMethod(A){this.rpcHandlers.delete(A)}setE2EEEnabled(A){return zA(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(A)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(A,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var A;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new dVA(i,t),this.e2eeManager.on(Su.ParticipantEncryptionStatusChanged,(n,g)=>{gVA(g)&&(this.isE2EEEnabled=n),this.emit(yt.ParticipantEncryptionStatusChanged,n,g)}),this.e2eeManager.on(Su.EncryptionError,(n,g)=>{const o=g?this.getParticipantByIdentity(g):void 0;this.emit(yt.EncryptionError,n,o)}),(A=this.e2eeManager)===null||A===void 0||A.setup(this))}get logContext(){var A;return{room:this.name,roomID:(A=this.roomInfo)===null||A===void 0?void 0:A.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var A,t;return(t=(A=this.roomInfo)===null||A===void 0?void 0:A.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===Xn.Disconnected?tI.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?tI.resolve(this.roomInfo.sid):new tI((A,t)=>{const i=n=>{n.sid!==""&&(this.engine.off(_t.RoomUpdate,i),A(n.sid))};this.engine.on(_t.RoomUpdate,i),this.once(yt.Disconnected,()=>{this.engine.off(_t.RoomUpdate,i),t(new zo("Room disconnected before room server id was available"))})})}get name(){var A,t;return(t=(A=this.roomInfo)===null||A===void 0?void 0:A.name)!==null&&t!==void 0?t:""}get metadata(){var A;return(A=this.roomInfo)===null||A===void 0?void 0:A.metadata}get numParticipants(){var A,t;return(t=(A=this.roomInfo)===null||A===void 0?void 0:A.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var A,t;return(t=(A=this.roomInfo)===null||A===void 0?void 0:A.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new a9A(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(_t.ParticipantUpdate,this.handleParticipantUpdates).on(_t.RoomUpdate,this.handleRoomUpdate).on(_t.SpeakersChanged,this.handleSpeakersChanged).on(_t.StreamStateChanged,this.handleStreamStateUpdate).on(_t.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(_t.SubscriptionError,this.handleSubscriptionError).on(_t.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(_t.MediaTrackAdded,(A,t,i)=>{this.onTrackAdded(A,t,i)}).on(_t.Disconnected,A=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,A)}).on(_t.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(_t.DataPacketReceived,this.handleDataPacket).on(_t.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Xn.SignalReconnecting)&&this.emit(yt.SignalReconnecting)}).on(_t.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Xn.Connected)&&this.emit(yt.Reconnected)}).on(_t.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Xn.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(_t.Restarting,this.handleRestarting).on(_t.SignalRestarted,this.handleSignalRestarted).on(_t.Offline,()=>{this.setAndEmitConnectionState(Xn.Reconnecting)&&this.emit(yt.Reconnecting)}).on(_t.DCBufferStatusChanged,(A,t)=>{this.emit(yt.DCBufferStatusChanged,A,t)}).on(_t.LocalTrackSubscribed,A=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:n}=i;return n===A});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(qt.LocalTrackSubscribed,t),this.emitWhenConnected(yt.LocalTrackSubscribed,t,this.localParticipant)}).on(_t.RoomMoved,A=>{this.log.debug("room moved",A),A.room&&this.handleRoomUpdate(A.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(yt.Moved,A.room.name),A.participant?this.handleParticipantUpdates([A.participant,...A.otherParticipants]):this.handleParticipantUpdates(A.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return oa.getInstance().getDevices(A,t)}prepareConnection(A,t){return zA(this,void 0,void 0,function*(){if(this.state===Xn.Disconnected){this.log.debug("prepareConnection to ".concat(A),this.logContext);try{if(bS(new URL(A))&&t){this.regionUrlProvider=new tg(A,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Xn.Disconnected&&(this.regionUrl=i,yield fetch(QN(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(QN(A),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(A){return this.localParticipant.identity===A?this.localParticipant:this.remoteParticipants.get(A)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(A,t){return zA(this,void 0,void 0,function*(){let i=()=>zA(this,void 0,void 0,function*(){}),n;switch(A){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":n=new _l({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new _l({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new _l({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new _l({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>zA(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),n=new _l({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>zA(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),n=new _l({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":n=new _l({scenario:{case:"switchCandidateProtocol",value:A==="force-tls"?2:1}}),i=()=>zA(this,void 0,void 0,function*(){const g=this.engine.client.onLeave;g&&g(new ex({reason:jc.CLIENT_INITIATED,action:Km.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");n=new _l({scenario:{case:"subscriberBandwidth",value:jh(t)}});break;case"leave-full-reconnect":n=new _l({scenario:{case:"leaveRequestFullReconnect",value:!0}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(A){return this.localParticipant.activeDeviceMap.get(A)}switchActiveDevice(A,t){return zA(this,arguments,void 0,function(i,n){var g=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var s,a,r,I,c,l,B;let Q=!0,h=!1;const d=o?{exact:n}:n;if(i==="audioinput"){h=g.localParticipant.audioTrackPublications.size===0;const p=(s=g.getActiveDevice(i))!==null&&s!==void 0?s:g.options.audioCaptureDefaults.deviceId;g.options.audioCaptureDefaults.deviceId=d;const y=Array.from(g.localParticipant.audioTrackPublications.values()).filter(D=>D.source===st.Source.Microphone);try{Q=(yield Promise.all(y.map(D=>{var S;return(S=D.audioTrack)===null||S===void 0?void 0:S.setDeviceId(d)}))).every(D=>D===!0)}catch(D){throw g.options.audioCaptureDefaults.deviceId=p,D}const m=y.some(D=>{var S,k;return(k=(S=D.track)===null||S===void 0?void 0:S.isMuted)!==null&&k!==void 0?k:!1});Q&&m&&(h=!0)}else if(i==="videoinput"){h=g.localParticipant.videoTrackPublications.size===0;const p=(a=g.getActiveDevice(i))!==null&&a!==void 0?a:g.options.videoCaptureDefaults.deviceId;g.options.videoCaptureDefaults.deviceId=d;const y=Array.from(g.localParticipant.videoTrackPublications.values()).filter(D=>D.source===st.Source.Camera);try{Q=(yield Promise.all(y.map(D=>{var S;return(S=D.videoTrack)===null||S===void 0?void 0:S.setDeviceId(d)}))).every(D=>D===!0)}catch(D){throw g.options.videoCaptureDefaults.deviceId=p,D}const m=y.some(D=>{var S,k;return(k=(S=D.track)===null||S===void 0?void 0:S.isMuted)!==null&&k!==void 0?k:!1});Q&&m&&(h=!0)}else if(i==="audiooutput"){if(h=!0,!h3()&&!g.options.webAudioMix||g.options.webAudioMix&&g.audioContext&&!("setSinkId"in g.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");g.options.webAudioMix&&(n=(r=yield oa.getInstance().normalizeDeviceId("audiooutput",n))!==null&&r!==void 0?r:""),(I=(B=g.options).audioOutput)!==null&&I!==void 0||(B.audioOutput={});const p=(c=g.getActiveDevice(i))!==null&&c!==void 0?c:g.options.audioOutput.deviceId;g.options.audioOutput.deviceId=n;try{g.options.webAudioMix&&((l=g.audioContext)===null||l===void 0||l.setSinkId(n)),yield Promise.all(Array.from(g.remoteParticipants.values()).map(y=>y.setAudioOutput({deviceId:n})))}catch(y){throw g.options.audioOutput.deviceId=p,y}}return h&&(g.localParticipant.activeDeviceMap.set(i,n),g.emit(yt.ActiveDeviceChanged,i,n)),Q}()})}setupLocalParticipantEvents(){this.localParticipant.on(qt.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(qt.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(qt.AttributesChanged,this.onLocalAttributesChanged).on(qt.TrackMuted,this.onLocalTrackMuted).on(qt.TrackUnmuted,this.onLocalTrackUnmuted).on(qt.LocalTrackPublished,this.onLocalTrackPublished).on(qt.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(qt.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(qt.MediaDevicesError,this.onMediaDevicesError).on(qt.AudioStreamAcquired,this.startAudio).on(qt.ChatMessage,this.onLocalChatMessageSent).on(qt.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var A;(A=this.engine)===null||A===void 0||A.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(A,t,i){if(this.state===Xn.Connecting||this.state===Xn.Reconnecting){const c=()=>{this.log.debug("deferring on track for later",{mediaTrackId:A.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(B=>B.id)}),this.onTrackAdded(A,t,i),l()},l=()=>{this.off(yt.Reconnected,c),this.off(yt.Connected,c),this.off(yt.Disconnected,l)};this.once(yt.Reconnected,c),this.once(yt.Connected,c),this.once(yt.Disconnected,l);return}if(this.state===Xn.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(A.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const n=HWA(t.id),g=n[0];let o=n[1],s=A.id;if(o&&o.startsWith("TR")&&(s=o),g===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(c=>c.sid===g);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(g),this.logContext);return}if(!s.startsWith("TR")){const c=this.engine.getTrackIdForReceiver(i);if(!c){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(g),this.logContext);return}s=c}s.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(g,", streamId: ").concat(o,", trackId: ").concat(s),Object.assign(Object.assign({},this.logContext),{rpID:g,streamId:o,trackId:s}));let r;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?r=this.options.adaptiveStream:r={});const I=a.addSubscribedMediaTrack(A,s,t,i,r);I!=null&&I.isEncrypted&&!this.e2eeManager&&this.emit(yt.EncryptionError,new Error("Encrypted ".concat(I.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Xn.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(g=>{g.trackPublications.forEach(o=>{g.unpublishTrack(o.trackSid)})}),this.localParticipant.trackPublications.forEach(g=>{var o,s,a;g.track&&this.localParticipant.unpublishTrack(g.track,A),A?((o=g.track)===null||o===void 0||o.detach(),(s=g.track)===null||s===void 0||s.stop()):(a=g.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(qt.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(qt.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(qt.AttributesChanged,this.onLocalAttributesChanged).off(qt.TrackMuted,this.onLocalTrackMuted).off(qt.TrackUnmuted,this.onLocalTrackUnmuted).off(qt.LocalTrackPublished,this.onLocalTrackPublished).off(qt.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(qt.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(qt.MediaDevicesError,this.onMediaDevicesError).off(qt.AudioStreamAcquired,this.startAudio).off(qt.ChatMessage,this.onLocalChatMessageSent).off(qt.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),iI()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||n===void 0||n.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Xn.Disconnected),this.emit(yt.Disconnected,t)}}}handleParticipantDisconnected(A,t){var i;this.remoteParticipants.delete(A),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(A),t.trackPublications.forEach(n=>{t.unpublishTrack(n.trackSid,!0)}),this.emit(yt.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(A,t,i,n,g,o){return zA(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(A,t),o!==1){yield this.engine.publishRpcResponse(A,t,null,mr.builtIn("UNSUPPORTED_VERSION"));return}const s=this.rpcHandlers.get(i);if(!s){yield this.engine.publishRpcResponse(A,t,null,mr.builtIn("UNSUPPORTED_METHOD"));return}let a=null,r=null;try{const I=yield s({requestId:t,callerIdentity:A,payload:n,responseTimeout:g});Tz(I)>sdA?(a=mr.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):r=I}catch(I){I instanceof mr?a=I:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),I),a=mr.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(A,t,r,a)})}selectDefaultDevices(){return zA(this,void 0,void 0,function*(){var A,t,i;const n=oa.getInstance().previousDevices,g=yield oa.getInstance().getDevices(void 0,!1),o=rI();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let a of g){const r=n.find(I=>I.deviceId===a.deviceId);r&&r.label!==""&&r.kind===a.kind&&r.label!==a.label&&this.getActiveDevice(a.kind)==="default"&&this.emit(yt.ActiveDeviceChanged,a.kind,a.deviceId)}const s=["audiooutput","audioinput","videoinput"];for(let a of s){const r=KWA(a),I=this.localParticipant.getTrackPublication(r);if(I&&(!((A=I.track)===null||A===void 0)&&A.isUserProvided))continue;const c=g.filter(B=>B.kind===a),l=this.getActiveDevice(a);if(l===((t=n.filter(B=>B.kind===a)[0])===null||t===void 0?void 0:t.deviceId)&&c.length>0&&((i=c[0])===null||i===void 0?void 0:i.deviceId)!==l){yield this.switchActiveDevice(a,c[0].deviceId);continue}a==="audioinput"&&!EN()||a==="videoinput"||c.length>0&&!c.find(B=>B.deviceId===this.getActiveDevice(a))&&(a!=="audiooutput"||!EN())&&(yield this.switchActiveDevice(a,c[0].deviceId))}})}acquireAudioContext(){return zA(this,void 0,void 0,function*(){var A,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(A=XuA())!==null&&A!==void 0?A:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(n=>n.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Ga(200)])}catch(n){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:n}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(yt.AudioPlaybackStatusChanged,i))})}createParticipant(A,t){var i;let n;return t?n=I_.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):n=new I_(this.engine.client,"",A,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&n.setAudioOutput(this.options.audioOutput).catch(g=>this.log.warn("Could not set audio output: ".concat(g.message),this.logContext)),n}getOrCreateParticipant(A,t){if(this.remoteParticipants.has(A)){const n=this.remoteParticipants.get(A);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}const i=this.createParticipant(A,t);return this.remoteParticipants.set(A,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(yt.ParticipantConnected,i),i.on(qt.TrackPublished,n=>{this.emitWhenConnected(yt.TrackPublished,n,i)}).on(qt.TrackSubscribed,(n,g)=>{n.kind===st.Kind.Audio?(n.on(Gt.AudioPlaybackStarted,this.handleAudioPlaybackStarted),n.on(Gt.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):n.kind===st.Kind.Video&&(n.on(Gt.VideoPlaybackFailed,this.handleVideoPlaybackFailed),n.on(Gt.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(yt.TrackSubscribed,n,g,i)}).on(qt.TrackUnpublished,n=>{this.emit(yt.TrackUnpublished,n,i)}).on(qt.TrackUnsubscribed,(n,g)=>{this.emit(yt.TrackUnsubscribed,n,g,i)}).on(qt.TrackMuted,n=>{this.emitWhenConnected(yt.TrackMuted,n,i)}).on(qt.TrackUnmuted,n=>{this.emitWhenConnected(yt.TrackUnmuted,n,i)}).on(qt.ParticipantMetadataChanged,n=>{this.emitWhenConnected(yt.ParticipantMetadataChanged,n,i)}).on(qt.ParticipantNameChanged,n=>{this.emitWhenConnected(yt.ParticipantNameChanged,n,i)}).on(qt.AttributesChanged,n=>{this.emitWhenConnected(yt.ParticipantAttributesChanged,n,i)}).on(qt.ConnectionQualityChanged,n=>{this.emitWhenConnected(yt.ConnectionQualityChanged,n,i)}).on(qt.ParticipantPermissionsChanged,n=>{this.emitWhenConnected(yt.ParticipantPermissionsChanged,n,i)}).on(qt.TrackSubscriptionStatusChanged,(n,g)=>{this.emitWhenConnected(yt.TrackSubscriptionStatusChanged,n,g,i)}).on(qt.TrackSubscriptionFailed,(n,g)=>{this.emit(yt.TrackSubscriptionFailed,n,i,g)}).on(qt.TrackSubscriptionPermissionChanged,(n,g)=>{this.emitWhenConnected(yt.TrackSubscriptionPermissionChanged,n,g,i)}).on(qt.Active,()=>{this.emitWhenConnected(yt.ParticipantActive,i),i.kind===lN.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const A=Array.from(this.remoteParticipants.values()).reduce((i,n)=>(i.push(...n.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(A,t)}updateSubscriptions(){for(const A of this.remoteParticipants.values())for(const t of A.videoTrackPublications.values())t.isSubscribed&&nVA(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(A){const t=this.sidToIdentity.get(A);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let A=0;this.connectionReconcileInterval=Ra.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(A++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:A,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),A>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,jc.STATE_MISMATCH))):A=0},S9A)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ra.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(A){return A===this.state?!1:(this.state=A,this.emit(yt.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(A=>{let[t,i]=A;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(A){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===Xn.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([A,i]);else if(this.state===Xn.Connected)return this.emit(A,...i);return!1}simulateParticipants(A){return zA(this,void 0,void 0,function*(){var t,i,n,g;const o=Object.assign({audio:!0,video:!0,useRealTracks:!1},A.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},A.participants);if(this.handleDisconnect(),this.roomInfo=new VL({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Bo.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new If({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(yt.SignalConnected),this.emit(yt.Connected),this.setAndEmitConnectionState(Xn.Connected),o.video){const a=new w3(st.Kind.Video,new XD({source:Es.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:qc.AUDIO,name:"video-dummy"}),new r_(o.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:KAA(160*((i=s.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(qt.LocalTrackPublished,a)}if(o.audio){const a=new w3(st.Kind.Audio,new XD({source:Es.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:qc.AUDIO}),new a_(o.useRealTracks&&(!((n=navigator.mediaDevices)===null||n===void 0)&&n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:$2(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(qt.LocalTrackPublished,a)}for(let a=0;a<s.count-1;a+=1){let r=new If({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:vm.ACTIVE,tracks:[],joinedAt:Bo.parse(Date.now())});const I=this.getOrCreateParticipant(r.identity,r);if(s.video){const c=KAA(160*((g=s.aspectRatios[a%s.aspectRatios.length])!==null&&g!==void 0?g:1),160,!1,!0),l=new XD({source:Es.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:qc.AUDIO});I.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),r.tracks=[...r.tracks,l]}if(s.audio){const c=$2(),l=new XD({source:Es.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:qc.AUDIO});I.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),r.tracks=[...r.tracks,l]}I.updateInfo(r)}})}emit(A){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(A!==yt.ActiveSpeakersChanged&&A!==yt.TranscriptionReceived){const g=EdA(i).filter(o=>o!==void 0);(A===yt.TrackSubscribed||A===yt.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(A),Object.assign(Object.assign({},this.logContext),{event:A,args:g})),this.log.debug("room event ".concat(A),Object.assign(Object.assign({},this.logContext),{event:A,args:g}))}return super.emit(A,...i)}}US.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{e()});function EdA(e){return e.map(A=>{if(A)return Array.isArray(A)?EdA(A):typeof A=="object"?"logContext"in A?A.logContext:void 0:A})}var _c;(function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"})(_c||(_c={}));class _d extends RB.EventEmitter{constructor(A,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=_c.IDLE,this.logs=[],this.options={},this.url=A,this.token=t,this.name=this.constructor.name,this.room=new US(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(A){return zA(this,void 0,void 0,function*(){if(this.status!==_c.IDLE)throw Error("check is running already");this.setStatus(_c.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==_c.SKIPPED&&this.setStatus(this.isSuccess()?_c.SUCCESS:_c.FAILED),A&&A(),this.getInfo()})}isSuccess(){return!this.logs.some(A=>A.level==="error")}connect(A){return zA(this,void 0,void 0,function*(){return this.room.state===Xn.Connected?this.room:(A||(A=this.url),yield this.room.connect(A,this.token,this.connectOptions),this.room)})}disconnect(){return zA(this,void 0,void 0,function*(){this.room&&this.room.state!==Xn.Disconnected&&(yield this.room.disconnect(),yield new Promise(A=>setTimeout(A,500)))})}skip(){this.setStatus(_c.SKIPPED)}switchProtocol(A){return zA(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(yt.Reconnecting,()=>{t=!0}),this.room.once(yt.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(A)),yield new Promise(g=>setTimeout(g,1e3)),!t)return;const n=Date.now()+1e4;for(;Date.now()<n;){if(i)return;yield Ga(100)}throw new Error("Could not reconnect using ".concat(A," protocol after 10 seconds"))})}appendMessage(A){this.logs.push({level:"info",message:A}),this.emit("update",this.getInfo())}appendWarning(A){this.logs.push({level:"warning",message:A}),this.emit("update",this.getInfo())}appendError(A){this.logs.push({level:"error",message:A}),this.emit("update",this.getInfo())}setStatus(A){this.status=A,this.emit("update",this.getInfo())}get engine(){var A;return(A=this.room)===null||A===void 0?void 0:A.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class w9A extends _d{get description(){return"Cloud regions"}perform(){return zA(this,void 0,void 0,function*(){const A=new tg(this.url,this.token);if(!A.isCloud()){this.skip();return}const t=[],i=new Set;for(let g=0;g<3;g++){const o=yield A.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const s=yield this.checkCloudRegion(o);this.appendMessage("".concat(s.region," RTT: ").concat(s.rtt,"ms, duration: ").concat(s.duration,"ms")),t.push(s)}t.sort((g,o)=>(g.duration-o.duration)*.5+(g.rtt-o.rtt)*.5);const n=t[0];this.bestStats=n,this.appendMessage("best Cloud region: ".concat(n.region))})}getInfo(){const A=super.getInfo();return A.data=this.bestStats,A}checkCloudRegion(A){return zA(this,void 0,void 0,function*(){var t,i;yield this.connect(A),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const n=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!n)throw new Error("Region not found");const g=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,a=1e6/o,r="A".repeat(o),I=Date.now();for(let Q=0;Q<a;Q++)yield g.write(r);yield g.close();const c=Date.now(),l=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),B={region:n,rtt:1e4,duration:c-I};return l==null||l.forEach(Q=>{Q.type==="candidate-pair"&&Q.nominated&&(B.rtt=Q.currentRoundTripTime*1e3)}),yield this.disconnect(),B})}}const aY=1e4;class k9A extends _d{get description(){return"Connection via UDP vs TCP"}perform(){return zA(this,void 0,void 0,function*(){const A=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=A,A.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(A.packetsLost-t.packetsLost)/A.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(aY/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(aY/1e3)*100).toFixed(2),"%"))})}getInfo(){const A=super.getInfo();return A.data=this.bestStats,A}checkConnectionProtocol(A){return zA(this,void 0,void 0,function*(){yield this.connect(),A==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let n=0;const g=()=>{n=(n+1)%360,i.fillStyle="hsl(".concat(n,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(g)};g();const s=t.captureStream(30).getVideoTracks()[0],r=(yield this.room.localParticipant.publishTrack(s,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,I={protocol:A,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},c=setInterval(()=>zA(this,void 0,void 0,function*(){const l=yield r.getRTCStatsReport();l==null||l.forEach(B=>{B.type==="outbound-rtp"?(I.packetsSent=B.packetsSent,I.qualityLimitationDurations=B.qualityLimitationDurations,I.bitrateTotal+=B.targetBitrate,I.count++):B.type==="remote-inbound-rtp"&&(I.packetsLost=B.packetsLost,I.rttTotal+=B.roundTripTime,I.jitterTotal+=B.jitter)})}),1e3);return yield new Promise(l=>setTimeout(l,aY)),clearInterval(c),s.stop(),t.remove(),yield this.disconnect(),I})}}class M9A extends _d{get description(){return"Can publish audio"}perform(){return zA(this,void 0,void 0,function*(){var A;const t=yield this.connect(),i=yield p9A();if(yield VuA(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(s=>setTimeout(s,3e3));const g=yield(A=i.sender)===null||A===void 0?void 0:A.getStats();if(!g)throw new Error("Could not get RTCStats");let o=0;if(g.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="audio"||!s.kind&&s.mediaType==="audio")&&(o=s.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class N9A extends _d{get description(){return"Can publish video"}perform(){return zA(this,void 0,void 0,function*(){var A;const t=yield this.connect(),i=yield h9A();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const n=yield(A=i.sender)===null||A===void 0?void 0:A.getStats();if(!n)throw new Error("Could not get RTCStats");let g=0;if(n.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(g+=o.packetsSent)}),g===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(g," video packets"))})}checkForVideo(A){return zA(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(A.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(n=>{i.onplay=()=>{setTimeout(()=>{var g,o,s,a;const r=document.createElement("canvas"),I=A.getSettings(),c=(o=(g=I.width)!==null&&g!==void 0?g:i.videoWidth)!==null&&o!==void 0?o:1280,l=(a=(s=I.height)!==null&&s!==void 0?s:i.videoHeight)!==null&&a!==void 0?a:720;r.width=c,r.height=l;const B=r.getContext("2d");B.drawImage(i,0,0);const h=B.getImageData(0,0,r.width,r.height).data;let d=!0;for(let p=0;p<h.length;p+=4)if(h[p]!==0||h[p+1]!==0||h[p+2]!==0){d=!1;break}d?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),n()},1e3)},i.play()}),t.getTracks().forEach(n=>n.stop()),i.remove()})}}class R9A extends _d{get description(){return"Resuming connection after interruption"}perform(){return zA(this,void 0,void 0,function*(){var A;const t=yield this.connect();let i=!1,n=!1,g;const o=new Promise(r=>{setTimeout(r,5e3),g=r}),s=()=>{i=!0};t.on(yt.SignalReconnecting,s).on(yt.Reconnecting,s).on(yt.Reconnected,()=>{n=!0,g(!0)}),(A=t.engine.client.ws)===null||A===void 0||A.close();const a=t.engine.client.onClose;if(a&&a(""),yield o,i){if(!n||t.state!==Xn.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class G9A extends _d{get description(){return"Can connect via TURN"}perform(){return zA(this,void 0,void 0,function*(){var A,t,i;bS(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(A=yield new tg(this.url,this.token).getNextBestRegionUrl())!==null&&A!==void 0?A:this.url);const n=new Fz,g=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,s=!1,a=!1;for(let r of g.iceServers)for(let I of r.urls)I.startsWith("turn:")?(s=!0,a=!0):I.startsWith("turns:")&&(s=!0,a=!0,o=!0),I.startsWith("stun:")&&(a=!0);a?s&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(r=>setTimeout(r,0)))})}}class b9A extends _d{get description(){return"Establishing WebRTC connection"}perform(){return zA(this,void 0,void 0,function*(){let A=!1,t=!1;this.room.on(yt.SignalConnected,()=>{var i;const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(g,o)=>{if(g.candidate){const s=new RTCIceCandidate(g);let a="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(U9A(s.address)?a+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(A=!0,a+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(a)}n&&n(g,o)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=g=>{g instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(g.errorCode," ").concat(g.errorText," ").concat(g.url))})});try{yield this.connect(),ln.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}A||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function U9A(e){const A=e.split(".");if(A.length===4){if(A[0]==="10")return!0;if(A[0]==="192"&&A[1]==="168")return!0;if(A[0]==="172"){const t=parseInt(A[1],10);if(t>=16&&t<=31)return!0}}return!1}class v9A extends _d{get description(){return"Connecting to signal connection via WebSocket"}perform(){return zA(this,void 0,void 0,function*(){var A,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let n=new Fz,g;try{g=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(o){if(bS(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const a=yield new tg(this.url,this.token).getNextBestRegionUrl();a&&(g=yield n.join(a,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}g?(this.appendMessage("Connected to server, version ".concat(g.serverVersion,".")),((A=g.serverInfo)===null||A===void 0?void 0:A.edition)===euA.Cloud&&(!((t=g.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=g.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield n.close()})}}class nGe extends RB.EventEmitter{constructor(A,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=A,this.token=t,this.options=i}getNextCheckId(){const A=this.checkResults.size;return this.checkResults.set(A,{logs:[],status:_c.IDLE,name:"",description:""}),A}updateCheck(A,t){this.checkResults.set(A,t),this.emit("checkUpdate",A,t)}isSuccess(){return Array.from(this.checkResults.values()).every(A=>A.status!==_c.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(A){return zA(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new A(this.url,this.token,this.options),n=o=>{this.updateCheck(t,o)};i.on("update",n);const g=yield i.run();return i.off("update",n),g})}checkWebsocket(){return zA(this,void 0,void 0,function*(){return this.createAndRunCheck(v9A)})}checkWebRTC(){return zA(this,void 0,void 0,function*(){return this.createAndRunCheck(b9A)})}checkTURN(){return zA(this,void 0,void 0,function*(){return this.createAndRunCheck(G9A)})}checkReconnect(){return zA(this,void 0,void 0,function*(){return this.createAndRunCheck(R9A)})}checkPublishAudio(){return zA(this,void 0,void 0,function*(){return this.createAndRunCheck(M9A)})}checkPublishVideo(){return zA(this,void 0,void 0,function*(){return this.createAndRunCheck(N9A)})}checkConnectionProtocol(){return zA(this,void 0,void 0,function*(){const A=yield this.createAndRunCheck(k9A);if(A.data&&"protocol"in A.data){const t=A.data;this.options.protocol=t.protocol}return A})}checkCloudRegion(){return zA(this,void 0,void 0,function*(){return this.createAndRunCheck(w9A)})}}function Jn(e,A,t){return(A=F9A(A))in e?Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[A]=t,e}function K9A(e,A){if(typeof e!="object"||!e)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var i=t.call(e,A);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(A==="string"?String:Number)(e)}function F9A(e){var A=K9A(e,"string");return typeof A=="symbol"?A:A+""}new TextEncoder;new TextDecoder;class xr extends Error{constructor(A,t){var i;super(A,t),Jn(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}Jn(xr,"code","ERR_JOSE_GENERIC");class _9A extends xr{constructor(A,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(A,{cause:{claim:i,reason:n,payload:t}}),Jn(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Jn(this,"claim",void 0),Jn(this,"reason",void 0),Jn(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}}Jn(_9A,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class J9A extends xr{constructor(A,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(A,{cause:{claim:i,reason:n,payload:t}}),Jn(this,"code","ERR_JWT_EXPIRED"),Jn(this,"claim",void 0),Jn(this,"reason",void 0),Jn(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}}Jn(J9A,"code","ERR_JWT_EXPIRED");class L9A extends xr{constructor(){super(...arguments),Jn(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Jn(L9A,"code","ERR_JOSE_ALG_NOT_ALLOWED");class x9A extends xr{constructor(){super(...arguments),Jn(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Jn(x9A,"code","ERR_JOSE_NOT_SUPPORTED");class T9A extends xr{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(A,t),Jn(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Jn(T9A,"code","ERR_JWE_DECRYPTION_FAILED");class q9A extends xr{constructor(){super(...arguments),Jn(this,"code","ERR_JWE_INVALID")}}Jn(q9A,"code","ERR_JWE_INVALID");class Y9A extends xr{constructor(){super(...arguments),Jn(this,"code","ERR_JWS_INVALID")}}Jn(Y9A,"code","ERR_JWS_INVALID");class H9A extends xr{constructor(){super(...arguments),Jn(this,"code","ERR_JWT_INVALID")}}Jn(H9A,"code","ERR_JWT_INVALID");class O9A extends xr{constructor(){super(...arguments),Jn(this,"code","ERR_JWK_INVALID")}}Jn(O9A,"code","ERR_JWK_INVALID");class P9A extends xr{constructor(){super(...arguments),Jn(this,"code","ERR_JWKS_INVALID")}}Jn(P9A,"code","ERR_JWKS_INVALID");class j9A extends xr{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(A,t),Jn(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Jn(j9A,"code","ERR_JWKS_NO_MATCHING_KEY");class z9A extends xr{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(A,t),Jn(this,Symbol.asyncIterator,void 0),Jn(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Jn(z9A,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class Z9A extends xr{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(A,t),Jn(this,"code","ERR_JWKS_TIMEOUT")}}Jn(Z9A,"code","ERR_JWKS_TIMEOUT");class W9A extends xr{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(A,t),Jn(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Jn(W9A,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const geA=15e3,V9A=1e4,QdA=E.createContext(null),X9A=()=>E.useContext(QdA);function $9A({children:e}){const{user:A}=tn(),t=Ms(),i=A==null?void 0:A.id,n=!!(A!=null&&A.email&&/@guest\.local$/i.test(A.email)),g=!!i&&!n,o=E.useRef(null),[s,a]=E.useState(null),r=E.useRef(null);E.useEffect(()=>{r.current=s},[s]);const[I,c]=E.useState(!1),[l,B]=E.useState(!1),[Q,h]=E.useState(null),[d,p]=E.useState(!1),y=E.useRef(null),[m,D]=E.useState([]),[S,k]=E.useState(null),[N,G]=E.useState(!1),[M,w]=E.useState(!1),[b,_]=E.useState(null),[K,J]=E.useState(null),q=E.useRef(null);E.useEffect(()=>{q.current=K},[K]);const v=E.useCallback(L=>{var iA;const H=L??o.current;if(!H){D([]),k(null);return}const P=[];H.remoteParticipants.forEach(oA=>{var _A,uA;const IA=(_A=oA.getTrackPublication(st.Source.Camera))==null?void 0:_A.track,CA=(uA=oA.getTrackPublication(st.Source.Microphone))==null?void 0:uA.track;P.push({id:oA.identity,name:oA.name||oA.identity,isSelf:!1,audioEnabled:oA.isMicrophoneEnabled,videoEnabled:oA.isCameraEnabled,isSpeaking:oA.isSpeaking,videoTrack:IA||void 0,audioTrack:CA||void 0})}),D(P);const tA=H.localParticipant;if(tA){const oA=tA.getTrackPublication(st.Source.Camera),IA=oA==null?void 0:oA.track,CA=(iA=tA.getTrackPublication(st.Source.Microphone))==null?void 0:iA.track;console.log("[LiveKit] updateParticipants - localVideoTrack:",IA),k({id:tA.identity,name:tA.name||tA.identity,isSelf:!0,audioEnabled:tA.isMicrophoneEnabled,videoEnabled:tA.isCameraEnabled,isSpeaking:tA.isSpeaking,videoTrack:IA||void 0,audioTrack:CA||void 0}),_(IA||null),G(tA.isMicrophoneEnabled),w(tA.isCameraEnabled)}},[]),U=E.useRef(null),x=E.useRef(!1),T=E.useRef(0),z=3,Z=E.useCallback(async L=>{if(!g||!t){h("Not authenticated");return}if(!(r.current===L&&o.current)){if(y.current&&(clearTimeout(y.current),y.current=null),o.current){const H=o.current;o.current=null;try{const P=H.localParticipant;if(P){try{await P.setCameraEnabled(!1)}catch{}try{await P.setMicrophoneEnabled(!1)}catch{}}H.disconnect()}catch(P){console.warn("[LiveKit] Error disconnecting previous room:",P)}}c(!1),a(null),console.log("[LiveKit] Room queued for lazy connect:",L),J(L),p(!1),G(!1),w(!1),h(null)}},[g,t]),eA=E.useCallback(async(L,H=0)=>{if(!g||!t)return h("Not authenticated"),!1;if(r.current===L&&o.current)return!0;if(U.current===L&&H===0)return console.log("[LiveKit] Connect already in progress for room:",L),!1;if(H===0&&(T.current=0),o.current){const P=o.current;o.current=null;try{const tA=P.localParticipant;if(tA){try{await tA.setCameraEnabled(!1)}catch{}try{await tA.setMicrophoneEnabled(!1)}catch{}}P.disconnect()}catch(tA){console.warn("[LiveKit] Error disconnecting previous room:",tA)}}U.current=L,x.current=!1,B(!0),h(null);try{const P=await new Promise((uA,X)=>{const O=setTimeout(()=>{X(new Error("livekit_join timed out"))},V9A);t.emit("livekit_join",{roomId:L},cA=>{clearTimeout(O),uA(cA)})});if(x.current)return console.log("[LiveKit] Join aborted for room:",L),U.current=null,!1;if(!(P!=null&&P.ok))throw new Error((P==null?void 0:P.error)||"Failed to get LiveKit token");const{token:tA,url:iA,iceServers:oA}=P,IA={};oA&&Array.isArray(oA)&&oA.length>0&&(IA.iceServers=oA,IA.iceTransportPolicy="all",console.log("[LiveKit] Using custom ICE servers:",oA.length,"servers"));const CA=new US({adaptiveStream:!0,dynacast:!0,videoCaptureDefaults:{resolution:GS.h540.resolution}});await CA.prepareConnection(iA,tA),CA.on(yt.Connected,()=>{console.log("[LiveKit] Connected to room"),c(!0),B(!1),v(CA)}),CA.on(yt.ParticipantConnected,uA=>{console.log("[LiveKit] Participant connected:",uA.identity),v(CA)}),CA.on(yt.ParticipantDisconnected,uA=>{console.log("[LiveKit] Participant disconnected:",uA.identity),v(CA)}),CA.on(yt.TrackSubscribed,(uA,X,O)=>{console.log("[LiveKit] Track subscribed:",uA.kind,O.identity),v(CA)}),CA.on(yt.TrackUnsubscribed,(uA,X,O)=>{console.log("[LiveKit] Track unsubscribed:",uA.kind,O.identity),v(CA)}),CA.on(yt.LocalTrackPublished,(uA,X)=>{if(console.log("[LiveKit] Local track published:",uA.kind,"track:",uA.track),v(CA),uA.kind===st.Kind.Video){let O=0;const cA=()=>{var xA;if(o.current!==CA&&O>0)return;if((xA=X.getTrackPublication(st.Source.Camera))==null?void 0:xA.track){v(CA);return}O++<8&&setTimeout(cA,75)};setTimeout(cA,50)}}),CA.on(yt.LocalTrackUnpublished,(uA,X)=>{console.log("[LiveKit] Local track unpublished:",uA.kind),v(CA)}),CA.on(yt.ActiveSpeakersChanged,()=>{v(CA)}),CA.on(yt.ConnectionStateChanged,uA=>{if(o.current===CA)if(console.log("[LiveKit] Connection state changed:",uA),uA===Xn.Disconnected){o.current=null,c(!1),v(),J(L);const X=r.current;X&&!x.current&&L===X&&(console.log("[LiveKit] Unexpected disconnect, attempting auto-reconnect to:",L),setTimeout(()=>{!x.current&&r.current===L&&eA(L,0)},1500))}else uA===Xn.Reconnecting?console.log("[LiveKit] Connection reconnecting..."):uA===Xn.Connected&&(console.log("[LiveKit] Connection restored"),c(!0))});const _A=Object.keys(IA).length>0?{rtcConfig:IA}:void 0;return await CA.connect(iA,tA,_A),x.current?(console.log("[LiveKit] Join aborted during connect, disconnecting"),CA.disconnect(),U.current=null,!1):(o.current=CA,a(L),J(null),U.current=null,c(!0),B(!1),v(CA),!0)}catch(P){if(console.error("[LiveKit] Join error:",P,"attempt:",H+1),H<z&&!x.current){const tA=Math.min(1e3*Math.pow(2,H),5e3);if(console.log(`[LiveKit] Retrying join in ${tA}ms (attempt ${H+2}/${z+1})`),U.current=null,await new Promise(iA=>setTimeout(iA,tA)),!x.current)return T.current=H+1,eA(L,H+1)}return h((P==null?void 0:P.message)||"Failed to join room"),B(!1),a(null),U.current=null,p(!0),!1}},[g,t,v]),aA=E.useCallback(async()=>{y.current&&(clearTimeout(y.current),y.current=null),x.current=!0,U.current=null,J(null);const L=o.current;if(L){o.current=null;try{const H=L.localParticipant;if(H){console.log("[LiveKit] Disabling local tracks before disconnect");try{H.isCameraEnabled&&await H.setCameraEnabled(!1)}catch(P){console.warn("[LiveKit] Error disabling camera:",P)}try{H.isMicrophoneEnabled&&await H.setMicrophoneEnabled(!1)}catch(P){console.warn("[LiveKit] Error disabling mic:",P)}}console.log("[LiveKit] Disconnecting from room"),L.disconnect()}catch(H){console.warn("[LiveKit] Error disconnecting room:",H)}}c(!1),B(!1),a(null),D([]),k(null),_(null),G(!1),w(!1)},[]),sA=E.useCallback(()=>{y.current&&(clearTimeout(y.current),y.current=null);const L=o.current;if(!L)return;const H=L.localParticipant;if(!H||H.isMicrophoneEnabled||H.isCameraEnabled)return;let P=!1;if(L.remoteParticipants.forEach(tA=>{(tA.isMicrophoneEnabled||tA.isCameraEnabled)&&(P=!0)}),P){console.log("[LiveKit] All local tracks off but remote participants are publishing — staying connected");return}console.log(`[LiveKit] All tracks off, no remote publishers — will auto-disconnect in ${geA/1e3}s`),y.current=setTimeout(()=>{y.current=null;const tA=o.current;if(!tA)return;const iA=tA.localParticipant;if(iA&&(iA.isMicrophoneEnabled||iA.isCameraEnabled))return;let oA=!1;if(tA.remoteParticipants.forEach(CA=>{(CA.isMicrophoneEnabled||CA.isCameraEnabled)&&(oA=!0)}),oA)return;console.log("[LiveKit] Idle timeout — disconnecting to save billing minutes");const IA=r.current;o.current=null;try{tA.disconnect()}catch{}c(!1),a(null),D([]),k(null),_(null),IA&&J(IA)},geA)},[]),pA=E.useCallback(()=>{y.current&&(clearTimeout(y.current),y.current=null,console.log("[LiveKit] Idle disconnect cancelled — track re-enabled"))},[]),gA=E.useCallback(async()=>{if(o.current)return o.current;const L=q.current;return L?(console.log("[LiveKit] Lazy-connecting to room:",L),await eA(L)?o.current:null):(console.warn("[LiveKit] No pending room to connect to"),null)},[eA]),yA=E.useCallback((L,H)=>{let P=0;const tA=()=>{var oA;if(o.current!==L)return;if((oA=L.localParticipant.getTrackPublication(H))==null?void 0:oA.track){v(L);return}P++<8&&setTimeout(tA,75)};setTimeout(tA,50)},[v]),fA=E.useCallback(async()=>{const L=await gA();if(L)try{const H=!L.localParticipant.isMicrophoneEnabled;H&&pA(),await L.localParticipant.setMicrophoneEnabled(H),G(H),H||sA()}catch(H){console.error("[LiveKit] Toggle mic error:",H)}},[gA,pA,sA]),RA=E.useCallback(async()=>{const L=await gA();if(L)try{const H=!L.localParticipant.isCameraEnabled;H&&pA(),await L.localParticipant.setCameraEnabled(H),w(H),v(L),H&&yA(L,st.Source.Camera),H||sA()}catch(H){console.error("[LiveKit] Toggle video error:",H)}},[gA,v,pA,sA]),qA=E.useCallback(async L=>{if(L){pA();const H=await gA();if(!H)return;try{await H.localParticipant.setMicrophoneEnabled(!0),G(!0)}catch(P){console.error("[LiveKit] Set mic error:",P)}}else{const H=o.current;if(!H){G(!1);return}try{await H.localParticipant.setMicrophoneEnabled(!1),G(!1),sA()}catch(P){console.error("[LiveKit] Set mic error:",P)}}},[gA,pA,sA]),W=E.useCallback(async L=>{if(L){pA();const H=await gA();if(!H)return;try{await H.localParticipant.setCameraEnabled(!0),w(!0),v(H),yA(H,st.Source.Camera)}catch(P){console.error("[LiveKit] Set video error:",P)}}else{const H=o.current;if(!H){w(!1);return}try{await H.localParticipant.setCameraEnabled(!1),w(!1),v(H),sA()}catch(P){console.error("[LiveKit] Set video error:",P)}}},[gA,v,pA,sA]);E.useEffect(()=>()=>{y.current&&(clearTimeout(y.current),y.current=null),x.current=!0,U.current=null;const L=o.current;if(L){o.current=null;try{const H=L.localParticipant;if(H){try{H.setCameraEnabled(!1)}catch{}try{H.setMicrophoneEnabled(!1)}catch{}}L.disconnect()}catch{}}},[]);const $={connected:I,connecting:l,error:Q,liveKitFailed:d,joinRoom:Z,leaveRoom:aA,currentRoomId:s,pendingRoomId:K,participants:m,localParticipant:S,micEnabled:N,videoEnabled:M,toggleMic:fA,toggleVideo:RA,setMicEnabled:qA,setVideoEnabled:W,localVideoTrack:b};return C.jsx(QdA.Provider,{value:$,children:e})}const udA=E.createContext(null),AXA=()=>E.useContext(udA);function jg(e){return e.connectionState==="closed"||e.signalingState==="closed"}function Tb(e){if(e)try{e.getTracks().forEach(A=>A.stop())}catch{}}function eXA(e){var A,t;try{const i=((A=e.getAudioTracks)==null?void 0:A.call(e))||[],n=((t=e.getVideoTracks)==null?void 0:t.call(e))||[],g=i.map(s=>({id:s.id,kind:s.kind,enabled:s.enabled,ready:s.readyState})),o=n.map(s=>{var a;return{id:s.id,kind:s.kind,enabled:s.enabled,ready:s.readyState,settings:((a=s.getSettings)==null?void 0:a.call(s))||void 0}});return{id:e.id,audioTracks:g.length,videoTracks:o.length,audio:g,video:o}}catch{return{id:e==null?void 0:e.id}}}const tXA=(()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent||navigator.vendor||window.opera||"";return/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1})();function R0(e,A){const t=new Set,i=[],n=g=>{const o=Array.isArray(g.urls)?g.urls:g.urls?[g.urls]:[];for(const s of o){if(!s||typeof s!="string")continue;const a=s.trim();if(a.startsWith("stun:")){const r=`${a}|`;t.has(r)||(t.add(r),i.push({urls:a}));continue}if(a.startsWith("turn:")||a.startsWith("turns:")){const r=g.username,I=g.credential;if(r&&I){const c=`${a}|${r}|${I}`;t.has(c)||(t.add(c),i.push({urls:a,username:r,credential:I}))}}}};return(e||[]).forEach(n),i.length===0&&A.forEach(n),i.length?i:A}function iXA(e,A){if(!A.heartbeat){try{A.dc||(A.dc=A.pc.createDataChannel("ka",{negotiated:!1,ordered:!0}))}catch{}A.heartbeat=window.setInterval(()=>{var t;try{((t=A.dc)==null?void 0:t.readyState)==="open"&&A.dc.send("ping")}catch{}},12e3)}}function G0(e){var A;e.heartbeat&&(clearInterval(e.heartbeat),e.heartbeat=void 0);try{(A=e.dc)==null||A.close()}catch{}e.dc=void 0}function nXA({children:e}){const{user:A}=tn(),t=Ms(),i=A==null?void 0:A.id,n=!!(A!=null&&A.email&&/@guest\.local$/i.test(A.email)),g=!!i&&!n;function o(j,QA){try{const dA=window;dA.__rtcVideoDisableReasons||(dA.__rtcVideoDisableReasons=[]),dA.__rtcVideoDisableReasons.push({t:Date.now(),reason:j,...QA?{data:QA}:{}});try{k3(`video:disable:${j}`)}catch{}}catch{}}const{rtcJoin:s,rtcSignal:a,rtcLeave:r,rtcSetVideoEnabled:I}=Mo(),c=E.useRef(new Map),[l,B]=E.useState({}),Q=null,[h,d]=E.useState({}),[p,y]=E.useState(void 0),m=E.useRef(void 0),D=E.useRef(void 0),S=E.useRef(""),k=E.useRef(new Map),N=E.useRef(new Map),[G,M]=E.useState(!1),[w,b]=E.useState(!1),_=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],K=E.useRef([..._]),[J,q]=E.useState(0),v=E.useRef(null);E.useRef([]);const U=E.useRef({audio:!1,video:!1}),x=J>0||w||G,T=E.useCallback(async()=>{var j;try{const QA=navigator;(j=QA==null?void 0:QA.wakeLock)!=null&&j.request&&!v.current&&(v.current=await QA.wakeLock.request("screen"),v.current.addEventListener("release",()=>{}))}catch{}},[]),z=E.useCallback(async()=>{var j,QA;try{await((QA=(j=v.current)==null?void 0:j.release)==null?void 0:QA.call(j))}catch{}v.current=null},[]);E.useEffect(()=>(Ii.debug("wakeLock:effect",{need:x}),x?T():z(),()=>{z()}),[x,T,z]),E.useEffect(()=>{const j=()=>{document.visibilityState==="visible"&&x&&T()};return document.addEventListener("visibilitychange",j),()=>document.removeEventListener("visibilitychange",j)},[x,T]);const Z=(()=>{var j,QA;try{return((QA=(j=window.Capacitor)==null?void 0:j.getPlatform)==null?void 0:QA.call(j))==="ios"}catch{return!1}})();async function eA(j,QA){var dA;if(!g||U.current[QA])return null;U.current[QA]=!0;try{if(!((dA=navigator.mediaDevices)!=null&&dA.getUserMedia))return console.error(`[RTC] getUserMedia not available for ${QA}`),Ii.error("gUM:not-available",{kind:QA,isNativeIOS:Z}),null;console.log(`[RTC] Requesting ${QA} with constraints:`,j);const UA=await navigator.mediaDevices.getUserMedia(j);return console.log(`[RTC] getUserMedia ${QA} success:`,UA==null?void 0:UA.getTracks().map(TA=>({id:TA.id,kind:TA.kind,readyState:TA.readyState}))),UA}catch(UA){return console.error(`[RTC] getUserMedia ${QA} failed:`,UA==null?void 0:UA.name,UA==null?void 0:UA.message,UA),Ii.error("gUM:failed",{kind:QA,errName:UA==null?void 0:UA.name,errMsg:UA==null?void 0:UA.message,isNativeIOS:Z}),null}finally{U.current[QA]=!1}}async function aA(){if(!g)return;if(D.current)return D.current;const j=await eA({audio:!0,video:!1},"audio");if(j){const QA=j.getAudioTracks()[0];QA&&(QA.enabled=!1),D.current=j}return D.current}async function sA(){if(!g)return;if(m.current)return m.current;const QA=await eA({audio:!1,video:tXA?{facingMode:{ideal:"user"},width:{ideal:640,max:1280},height:{ideal:480,max:720},frameRate:{ideal:24,max:30}}:{facingMode:{ideal:"user"},width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}}},"video");return QA&&(m.current=QA,y(QA),Ii.info("ensureVideo:acquired",eXA(QA))),m.current}function pA(){var QA;const j=((QA=m.current)==null?void 0:QA.getVideoTracks())??[];console.log("[RTC] releaseVideo called, stopping",j.length,"video tracks");try{j.forEach(dA=>{console.log("[RTC] stopping video track",dA.id,dA.readyState),dA.stop()})}catch(dA){console.error("[RTC] releaseVideo error",dA)}m.current=void 0,y(void 0)}function gA(){var j,QA;try{(QA=(j=D.current)==null?void 0:j.getAudioTracks())==null||QA.forEach(dA=>dA.stop())}catch{}D.current=void 0}const yA=E.useRef(new Map),[fA,RA]=E.useState({});function qA(j,QA){var Ht;if(yA.current.get(j))return;const dA=((Ht=QA==null?void 0:QA.getAudioTracks)==null?void 0:Ht.call(QA))??[];if(!dA.length||dA.every(Ft=>Ft.readyState!=="live"))return;let UA;try{UA=new AudioContext}catch(Ft){Ii.warn("vad:audiocontext-failed",{pid:j,err:String(Ft)});return}let TA,oe;try{TA=UA.createMediaStreamSource(QA),oe=UA.createAnalyser(),oe.fftSize=2048,TA.connect(oe)}catch(Ft){Ii.warn("vad:setup-failed",{pid:j,err:String(Ft)});try{UA.close()}catch{}return}const me=new Uint8Array(oe.fftSize);let be=0;const $e=.04,ci=.02;let ke=!1,nt=!1;const Ut=()=>{if(!nt){try{oe.getByteTimeDomainData(me);let Ft=0;for(let $A=0;$A<me.length;$A++){const He=(me[$A]-128)/128;Ft+=He*He}const Jt=Math.sqrt(Ft/me.length);!ke&&Jt>=$e?(ke=!0,RA($A=>$A[j]===!0?$A:{...$A,[j]:!0})):ke&&Jt<=ci&&(ke=!1,RA($A=>$A[j]===!1?$A:{...$A,[j]:!1}))}catch{}nt||(be=requestAnimationFrame(Ut))}};be=requestAnimationFrame(Ut);const dt=()=>{nt=!0,cancelAnimationFrame(be);try{TA.disconnect()}catch{}try{oe.disconnect()}catch{}UA.close().catch(()=>{})};yA.current.set(j,dt)}function W(j){const QA=yA.current.get(j);QA&&(QA(),yA.current.delete(j)),RA(dA=>{if(!(j in dA))return dA;const UA={...dA};return delete UA[j],UA})}function $(j,QA){try{return jg(j)?void 0:j.getTransceivers().find(dA=>{var UA;return((UA=dA.receiver.track)==null?void 0:UA.kind)===QA})??j.getTransceivers().find(dA=>{var UA;return((UA=dA.sender.track)==null?void 0:UA.kind)===QA})??j.getTransceivers()[QA==="audio"?0:1]}catch{return}}function L(j,QA){var dA;try{return jg(j)?void 0:j.getSenders().find(UA=>{var TA;return((TA=UA.track)==null?void 0:TA.kind)===QA})??((dA=$(j,QA))==null?void 0:dA.sender)}catch{return}}async function H(j,QA){var dA;try{if(jg(j))return;const UA=((dA=QA==null?void 0:QA.getAudioTracks)==null?void 0:dA.call(QA)[0])??null,TA=L(j,"audio");TA&&await TA.replaceTrack(UA)}catch(UA){Ii.warn("upsertAudioTrack:failed",{err:String(UA)})}}async function P(j,QA){var dA;try{if(jg(j))return;const UA=((dA=QA==null?void 0:QA.getVideoTracks)==null?void 0:dA.call(QA)[0])??null,TA=L(j,"video");console.log("[RTC] upsertVideoTrack",{hasTrack:!!UA,hasSender:!!TA,trackId:UA==null?void 0:UA.id,trackState:UA==null?void 0:UA.readyState}),TA?(await TA.replaceTrack(UA),console.log("[RTC] upsertVideoTrack: track replaced successfully")):console.warn("[RTC] upsertVideoTrack: no sender found for video")}catch(UA){Ii.warn("upsertVideoTrack:failed",{err:String(UA)}),console.error("[RTC] upsertVideoTrack failed:",UA)}}async function tA(j,QA){try{const dA=QA.pc,UA=Date.now();let TA=0,oe=0;(await dA.getStats()).forEach($e=>{$e.type==="outbound-rtp"&&!$e.isRemote&&(TA+=$e.bytesSent??0),$e.type==="inbound-rtp"&&!$e.isRemote&&(oe+=$e.bytesReceived??0)});const be=N.current.get(j);N.current.set(j,{t:UA,up:TA,down:oe}),be&&dA.connectionState==="connected"&&TA===be.up&&oe===be.down&&UA-be.t>2e4&&await O(j,QA)}catch{}}function iA(j,QA){if(k.current.get(j))return;const dA=window.setInterval(()=>tA(j,QA),1e4);k.current.set(j,dA)}function oA(j){const QA=k.current.get(j);QA&&(clearInterval(QA),k.current.delete(j)),N.current.delete(j)}function IA(){const j=typeof window<"u"?new URL(window.location.href):null,QA=typeof localStorage<"u"&&(localStorage.getItem("rtcRelayOnly")==="1"||localStorage.getItem("rtcRelayOnly")==="true")||(j==null?void 0:j.searchParams.get("rtcRelay"))==="1"||(j==null?void 0:j.searchParams.get("rtcRelay"))==="true",dA=!!_A._compat,UA=!!(QA||dA),TA={iceServers:R0(K.current,_),bundlePolicy:"balanced",iceTransportPolicy:UA?"relay":"all",rtcpMuxPolicy:"require",iceCandidatePoolSize:2},oe=TA.iceServers.some(be=>(Array.isArray(be.urls)?be.urls:[be.urls]).some(ci=>ci.startsWith("turn:")||ci.startsWith("turns:")));console.log("[RTC] newPc config",{relayOnly:UA,hasTurn:oe,iceTransportPolicy:TA.iceTransportPolicy,serverCount:TA.iceServers.length,servers:TA.iceServers.map(be=>({urls:be.urls,hasCredentials:!!(be.username&&be.credential)}))}),Ii.debug("pc:new",{relayOnly:UA,iceTransportPolicy:TA.iceTransportPolicy,iceServers:(TA.iceServers||[]).map(be=>{var $e;return typeof be.urls=="string"?be.urls:($e=be.urls)==null?void 0:$e[0]})});let me;try{me=new RTCPeerConnection(TA)}catch(be){Ii.error("pc:new-failed",{err:String(be),servers:TA.iceServers});const $e={...TA,iceServers:_};me=new RTCPeerConnection($e)}return me.addTransceiver("audio",{direction:"sendrecv"}),me.addTransceiver("video",{direction:"sendrecv"}),me}async function CA(j,QA){try{const dA=await QA.getStats(),UA={};dA.forEach(oe=>{oe&&oe.id&&(UA[oe.id]=oe)});let TA;if(dA.forEach(oe=>{oe.type==="transport"&&oe.selectedCandidatePairId&&UA[oe.selectedCandidatePairId]&&(TA=UA[oe.selectedCandidatePairId])}),TA||dA.forEach(oe=>{oe.type==="candidate-pair"&&(oe.selected||oe.state==="succeeded")&&(TA=oe)}),TA){const oe=UA[TA.localCandidateId],me=UA[TA.remoteCandidateId];Ii.info("ice:selected",{peerId:j,state:TA.state,nominated:TA.nominated,bytesSent:TA.bytesSent,bytesReceived:TA.bytesReceived,local:oe?{type:oe.candidateType,protocol:oe.protocol,address:oe.address,port:oe.port}:void 0,remote:me?{type:me.candidateType,protocol:me.protocol,address:me.address,port:me.port}:void 0})}else Ii.debug("ice:selected:none",{peerId:j})}catch(dA){Ii.error("ice:selected-failed",{peerId:j,err:String(dA)})}}async function _A(){try{if(_A._ran)return;_A._ran=!0;const j={iceServers:R0(K.current,_),bundlePolicy:"balanced",iceTransportPolicy:"all"},QA=new RTCPeerConnection(j),dA={host:0,srflx:0,relay:0,prflx:0};QA.onicecandidate=$e=>{if(!$e.candidate)return;const ke=($e.candidate.candidate||"").match(/ typ ([a-z]+)/),nt=(ke==null?void 0:ke[1])||"unknown";dA[nt]===void 0&&(dA[nt]=0),dA[nt]+=1},QA.createDataChannel("probe");const UA=await QA.createOffer({iceRestart:!1});await QA.setLocalDescription(UA),await new Promise($e=>setTimeout($e,4e3));try{QA.close()}catch{}const TA=(dA.relay||0)>0,oe=(dA.srflx||0)>0,me=(dA.host||0)>0,be=TA&&!oe&&me;if(be){Ii.warn("ice:probe-forcing-relay",{counts:dA,reason:"no-srflx"}),_A._compat=!0;try{localStorage.setItem("rtcRelayOnly","1")}catch{}}else!TA&&!oe&&Ii.error("ice:probe-restricted-network",{counts:dA,warning:"Voice/video may not work"});Ii.info("ice:probe",{counts:dA,relayOK:TA,srflxOK:oe,needsRelayOnly:be})}catch(j){Ii.error("ice:probe-failed",{err:String(j)})}}function uA(j){let QA=c.current.get(j);if(QA)return QA;const dA=IA(),UA={pc:dA,iceBuffer:[],makingOffer:!1,ignoreOffer:!1,isSettingRemoteAnswerPending:!1};return dA.onicecandidate=TA=>{TA.candidate&&(Ii.debug("pc:icecandidate",{peerId:j,ctype:TA.candidate.type,proto:TA.candidate.protocol,addr:TA.candidate.address,port:TA.candidate.port}),a(S.current,j,{ice:TA.candidate.toJSON()}).catch(console.error))},dA.ontrack=TA=>{if(Ii.info("pc:ontrack",{peerId:j,kind:TA.track.kind,id:TA.track.id}),console.log("[RTC] ontrack received",{peerId:j,kind:TA.track.kind,trackId:TA.track.id,readyState:TA.track.readyState,muted:TA.track.muted}),B(oe=>{const me=oe[j]??new MediaStream;return me.getTracks().includes(TA.track)||(me.addTrack(TA.track),console.log("[RTC] Track added to stream",{peerId:j,kind:TA.track.kind,streamId:me.id,trackCount:me.getTracks().length}),TA.track.addEventListener("ended",()=>{Ii.debug("pc:track-ended",{peerId:j,kind:TA.track.kind,id:TA.track.id}),console.log("[RTC] Track ended",{peerId:j,kind:TA.track.kind}),B(be=>{const $e=be[j];if(!$e)return be;try{$e.removeTrack(TA.track)}catch{}return{...be,[j]:$e}}),TA.track.kind==="video"&&d(be=>({...be,[j]:!1}))}),TA.track.kind==="video"&&(TA.track.addEventListener("mute",()=>{console.log("[RTC] Video track muted",{peerId:j,trackId:TA.track.id}),d(be=>({...be,[j]:!1}))}),TA.track.addEventListener("unmute",()=>{console.log("[RTC] Video track unmuted",{peerId:j,trackId:TA.track.id,readyState:TA.track.readyState}),TA.track.readyState==="live"&&d(be=>({...be,[j]:!0}))}))),{...oe,[j]:me}}),TA.track.kind==="video"){const oe=TA.track.readyState==="live"&&!TA.track.muted;console.log("[RTC] Video track received, setting remoteVideoFlags",{peerId:j,isLive:oe,muted:TA.track.muted}),d(me=>({...me,[j]:oe}))}},dA.onnegotiationneeded=()=>{Ii.debug("pc:onnegotiationneeded",{peerId:j})},dA.onconnectionstatechange=()=>{const{connectionState:TA}=dA,oe=dA.iceConnectionState;if(Ii.info("pc:state",{peerId:j,state:TA,ice:oe}),console.log("[RTC] connectionstatechange",{peerId:j,connectionState:TA,iceConnectionState:oe,signalingState:dA.signalingState}),TA==="connected"&&(UA.degradedAt=null,UA.iceRestartCount=0,UA.rebuildAttempts=0,iXA(j,UA),iA(j,UA),setTimeout(()=>CA(j,dA),500)),TA==="closed"&&(G0(UA),oA(j)),(TA==="disconnected"||X(TA,oe))&&!UA.degradedAt&&(UA.degradedAt=Date.now()),TA==="disconnected"&&UA.degradedAt){const be=Date.now()-UA.degradedAt;be>3e3&&be<8e3?O(j,UA):be>=8e3&&(Ii.warn("pc:prolonged-disconnect",{peerId:j,degradedMs:be}),YA(j))}X(TA,oe)&&O(j,UA)},dA.oniceconnectionstatechange=()=>{const TA=dA.iceConnectionState;Ii.debug("pc:ice-state",{peerId:j,ice:TA}),console.log("[RTC] iceconnectionstatechange",{peerId:j,iceConnectionState:TA,connectionState:dA.connectionState}),TA==="failed"&&O(j,UA),TA==="disconnected"&&setTimeout(()=>{!jg(dA)&&dA.iceConnectionState==="disconnected"&&(Ii.warn("ice:prolonged-disconnect",{peerId:j}),O(j,UA))},4e3)},dA.onicegatheringstatechange=()=>{console.log("[RTC] icegatheringstatechange",{peerId:j,iceGatheringState:dA.iceGatheringState})},dA.ondatachannel=TA=>{if(TA.channel.label==="ka"){const oe=TA.channel;UA.dc=oe,Ii.debug("pc:datachannel",{peerId:j,label:oe.label,state:oe.readyState})}},c.current.set(j,UA),q(c.current.size),Ii.info("peer:new",{peerId:j}),UA}function X(j,QA){return j==="failed"||QA==="failed"}async function O(j,QA){if(jg(QA.pc))return;const dA=Date.now(),UA=QA.lastIceRestartAt,TA=QA.iceRestartCount??0,oe=Math.min(1e4*Math.pow(2,TA),6e4);if(!(UA&&dA-UA<oe)){if(TA>=3){Ii.warn("ice:restart-exhausted",{peerId:j,restartCount:TA}),QA.iceRestartCount=0,await YA(j);return}if(Ii.warn("ice:restart",{peerId:j,attempt:TA+1}),!(QA.makingOffer||jg(QA.pc))&&(QA.pc.signalingState!=="stable"&&await ie(QA.pc),!jg(QA.pc)))try{const me=await QA.pc.createOffer({iceRestart:!0});if(jg(QA.pc))return;await QA.pc.setLocalDescription(me),await a(S.current,j,{sdp:QA.pc.localDescription}),QA.lastIceRestartAt=dA,QA.iceRestartCount=TA+1}catch(me){Ii.error("ice:restart-failed",{peerId:j,err:String(me)}),QA.iceRestartCount=0,await YA(j)}}}const cA=E.useRef(new Map),wA=3,xA=3e4;async function YA(j){const QA=cA.current.get(j)??{count:0,lastAt:0},dA=Date.now();if(dA-QA.lastAt>xA*3&&(QA.count=0),QA.count>=wA){const me=xA-(dA-QA.lastAt);if(me>0){Ii.warn("rebuild:rate-limited",{peerId:j,attempts:QA.count,waitMs:me}),setTimeout(()=>{cA.current.delete(j),YA(j)},me);return}QA.count=0}QA.count++,QA.lastAt=dA,cA.current.set(j,QA),Ii.info("rebuild:peer",{peerId:j,attempt:QA.count});const UA=c.current.get(j);if(UA){G0(UA);try{UA.pc.close()}catch{}c.current.delete(j)}B(me=>{if(!me[j])return me;const be={...me};return Tb(be[j]),delete be[j],be}),W(j),d(me=>{const{[j]:be,...$e}=me;return $e});const{pc:TA}=uA(j);await PA(TA);const oe=c.current.get(j);await he(j,TA,oe)}function jA(j){return j.signalingState==="stable"}function ie(j){return j.signalingState==="stable"||jg(j)?Promise.resolve():new Promise(QA=>{const dA=()=>{const UA=j.signalingState;(UA==="stable"||UA==="closed")&&(j.removeEventListener("signalingstatechange",dA),QA())};j.addEventListener("signalingstatechange",dA)})}async function he(j,QA,dA){var UA;try{if(jg(QA)||(jA(QA)||await ie(QA),!jA(QA)||dA.makingOffer||jg(QA)))return;dA.makingOffer=!0,Ii.debug("sdp:offer",{peerId:j}),console.log("[RTC] Creating offer for peer",{peerId:j,signalingState:QA.signalingState});const TA=await QA.createOffer();if(jg(QA)){dA.makingOffer=!1;return}await QA.setLocalDescription(TA),console.log("[RTC] Sending offer via rtcSignal",{peerId:j,room:S.current,type:(UA=QA.localDescription)==null?void 0:UA.type}),await a(S.current,j,{sdp:QA.localDescription})}catch(TA){Ii.warn("safeRenegotiate:failed",{peerId:j,err:String(TA)})}finally{dA.makingOffer=!1}}const le=E.useCallback(async j=>{if(j!==w){if(!g){b(!1),o("preferences:init"),b(!1);return}if(b(j),i&&d(QA=>({...QA,[i]:j})),j){try{$k(!0)}catch{}if(!await sA()){b(!1),i&&d(TA=>({...TA,[i]:!1}));return}for(const[TA,oe]of c.current)await P(oe.pc,m.current),await he(TA,oe.pc,oe);const dA=()=>{try{$k(!1)}catch{}};let UA=!1;for(const[,TA]of c.current){const oe=TA.pc,me=()=>{!UA&&oe.connectionState==="connected"&&(UA=!0,dA(),oe.removeEventListener("connectionstatechange",me))};oe.addEventListener("connectionstatechange",me)}window.setTimeout(()=>{UA||dA()},2500)}else{console.log("[RTC] setVideoEnabled(false) - disabling camera");for(const[QA,dA]of c.current)console.log("[RTC] removing video track from peer",QA),await P(dA.pc,void 0),await he(QA,dA.pc,dA);pA()}I(S.current,j).catch(()=>{});try{k3(j?"videoEnabled:on":"videoEnabled:off")}catch{}}},[w,i,g,A==null?void 0:A.membershipTier,c,sA,P,he,pA,I]),NA=async j=>{var dA,UA;if(!g){M(!1);return}if(M(j),j&&!D.current&&!await aA()){M(!1);return}const QA=(UA=(dA=D.current)==null?void 0:dA.getAudioTracks)==null?void 0:UA.call(dA)[0];QA&&(QA.enabled=j);for(const[,TA]of c.current)await H(TA.pc,D.current)},EA=j=>{var dA,UA,TA;if(j===i)return!!((UA=(dA=m.current)==null?void 0:dA.getVideoTracks)!=null&&UA.call(dA).some(oe=>oe.readyState==="live"));const QA=l[j];return!!((TA=QA==null?void 0:QA.getVideoTracks)!=null&&TA.call(QA).some(oe=>oe.readyState==="live"))},PA=async j=>{if(!jg(j)){if(!g){await H(j,void 0),await P(j,void 0);return}try{if(await aA(),w&&await sA(),jg(j))return;Ii.debug("attachLocalTracks",{audio:!!(G&&D.current),video:!!(w&&m.current)}),await H(j,G?D.current:void 0),await P(j,w?m.current:void 0)}catch(QA){Ii.warn("attachLocalTracks:failed",{err:String(QA)})}}},ZA=E.useRef(0),FA=90*60*1e3;E.useEffect(()=>{if(!S.current||c.current.size===0)return;const j=async()=>{const dA=Date.now();if(!(dA-ZA.current<FA)){Ii.info("ice:refresh-credentials",{roomId:S.current});try{const UA=await s(S.current);if(UA!=null&&UA.ok&&Array.isArray(UA.iceServers)&&UA.iceServers.length){const TA=R0([..._,...UA.iceServers],_);K.current=TA,ZA.current=dA,Ii.debug("ice:credentials-refreshed",{count:TA.length})}}catch(UA){Ii.warn("ice:refresh-failed",{err:String(UA)})}}},QA=window.setInterval(j,6e4);return()=>clearInterval(QA)},[J,s]);const Ie=async j=>{var oe;if(console.log("[RTC] joinRtc called",{roomId:j,isAuthed:g,meId:i,isGuest:n,userEmail:A==null?void 0:A.email}),!g||!i){console.warn("[RTC] joinRtc skipped: not authenticated",{isAuthed:g,meId:i,isGuest:n});return}S.current=j,Ii.info("rtc:join",{roomId:j});const QA=3,dA=150;let UA=null,TA=null;for(let me=0;me<QA&&(UA=await s(j),console.log("[RTC] joinRtc raw response",{ok:UA==null?void 0:UA.ok,attempt:me,iceServersCount:(oe=UA==null?void 0:UA.iceServers)==null?void 0:oe.length}),!(UA!=null&&UA.ok||(TA=(UA==null?void 0:UA.error)||"rtc_join failed",!/not a member|room not found/i.test(TA||"")||me>=QA-1)));me++)Ii.warn("rtc:join:retry",{roomId:j,attempt:me+1,error:TA}),await new Promise($e=>setTimeout($e,dA*(me+1)));if(!(UA!=null&&UA.ok))throw new Error(TA||"rtc_join failed");if(Array.isArray(UA.iceServers)&&UA.iceServers.length){const me=R0([..._,...UA.iceServers],_);K.current=me,ZA.current=Date.now();const be=me.some($e=>(Array.isArray($e.urls)?$e.urls:[$e.urls]).some(ke=>ke.startsWith("turn:")||ke.startsWith("turns:")));console.log("[RTC] joinRtc received ICE servers",{count:me.length,hasTurn:be,servers:me.map($e=>({urls:$e.urls,hasCredentials:!!($e.username&&$e.credential)}))}),Ii.debug("rtc:ice-servers",{count:me.length,servers:me.map($e=>$e.urls).slice(0,4)})}else K.current=[..._],ZA.current=Date.now();if(_A(),w&&!m.current){const me=await sA();me&&y(me)}for(const me of UA.peers.filter(be=>be!==i)){const{pc:be}=uA(me);await PA(be);const $e=c.current.get(me);await he(me,be,$e)}q(c.current.size)},DA=j=>{var QA,dA,UA,TA;!j||S.current&&S.current,Ii.info("rtc:leave",{roomId:j});try{r(j)}catch{}for(const[,oe]of c.current){G0(oe);try{oe.pc.close()}catch{}}c.current.clear(),q(0),S.current=void 0,z(),B(oe=>(Object.values(oe).forEach(Tb),{}));for(const oe of Array.from(yA.current.keys()))W(oe);(dA=(QA=D.current)==null?void 0:QA.getTracks())==null||dA.forEach(oe=>oe.stop()),(TA=(UA=m.current)==null?void 0:UA.getTracks())==null||TA.forEach(oe=>oe.stop()),D.current=void 0,m.current=void 0,y(void 0),d({})},rA=async(j,QA)=>{},BA=async()=>{g&&await le(!0)};return E.useEffect(()=>{if(!w||!S.current||c.current.size===0)return;const j=async()=>{var UA;if(!w||!m.current)return;const dA=m.current.getVideoTracks()[0];if(!((!dA||dA.readyState!=="live")&&(console.log("[RTC] Health check: local video track not live, re-acquiring"),Ii.warn("health:video-track-dead"),m.current=void 0,!await sA()))){for(const[TA,oe]of c.current)if(!jg(oe.pc))try{const me=oe.pc.getSenders().find(ci=>{var ke;return((ke=ci.track)==null?void 0:ke.kind)==="video"}),be=me==null?void 0:me.track,$e=(UA=m.current)==null?void 0:UA.getVideoTracks()[0];$e&&(!be||be.id!==$e.id)&&(console.log("[RTC] Health check: re-attaching video track to peer",{peerId:TA}),Ii.info("health:reattach-video",{peerId:TA}),await P(oe.pc,m.current),await he(TA,oe.pc,oe))}catch(me){Ii.warn("health:check-failed",{peerId:TA,err:String(me)})}}},QA=window.setInterval(j,5e3);return j(),()=>clearInterval(QA)},[w,J]),E.useEffect(()=>{if(!t||!g)return;const j=async()=>{const QA=S.current;if(QA){Ii.info("socket:reconnect:rtc-rejoin",{roomId:QA,peerCount:c.current.size}),console.log("[RTC] Socket reconnected, re-joining RTC room",{roomId:QA});for(const[,dA]of c.current){G0(dA);try{dA.pc.close()}catch{}}c.current.clear(),q(0),B(dA=>(Object.values(dA).forEach(Tb),{})),d({});try{const dA=await s(QA);if(!(dA!=null&&dA.ok)){Ii.warn("socket:reconnect:rtc-rejoin-failed",{roomId:QA,error:dA==null?void 0:dA.error});return}if(Array.isArray(dA.iceServers)&&dA.iceServers.length){const UA=R0([..._,...dA.iceServers],_);K.current=UA,ZA.current=Date.now()}for(const UA of dA.peers.filter(TA=>TA!==i)){const{pc:TA}=uA(UA);await PA(TA);const oe=c.current.get(UA);await he(UA,TA,oe)}q(c.current.size),Ii.info("socket:reconnect:rtc-rejoin-success",{roomId:QA,peerCount:c.current.size})}catch(dA){Ii.error("socket:reconnect:rtc-rejoin-error",{roomId:QA,err:String(dA)})}}};return t.on("connect",j),t.on("reconnect",j),()=>{t.off("connect",j),t.off("reconnect",j)}},[t,g,i,s]),E.useEffect(()=>{var QA,dA;const j=(dA=(QA=D.current)==null?void 0:QA.getAudioTracks)==null?void 0:dA.call(QA)[0];G&&j&&D.current?qA(i,D.current):W(i)},[D.current,i,G]),E.useEffect(()=>{for(const[j,QA]of Object.entries(l))(QA==null?void 0:QA.getAudioTracks().some(UA=>UA.enabled))&&qA(j,QA);for(const j of yA.current.keys())j!==i&&!l[j]&&W(j)},[l,i]),Os({onRtcPeerJoined:async({peerId:j})=>{if(Ii.info("sig:peer-joined",{peerId:j}),!(!S.current||j===i))try{const{pc:QA}=uA(j);if(jg(QA))return;await PA(QA);const dA=c.current.get(j);dA&&!jg(QA)&&await he(j,QA,dA)}catch(QA){Ii.warn("sig:peer-joined:failed",{peerId:j,err:String(QA)})}},onRtcPeerLeft:({peerId:j})=>{Ii.info("sig:peer-left",{peerId:j});const QA=c.current.get(j);if(QA){G0(QA),oA(j);try{QA.pc.close()}catch{}}c.current.delete(j),q(c.current.size),B(dA=>{const UA={...dA};return Tb(UA[j]),delete UA[j],UA}),W(j),d(dA=>{const{[j]:UA,...TA}=dA;return TA})},onRtcSignal:async({fromPeerId:j,payload:QA})=>{var TA;let dA,UA;try{dA=uA(j),UA=dA.pc}catch(oe){Ii.warn("sig:getPeer-failed",{fromPeerId:j,err:String(oe)});return}if(jg(UA)){Ii.debug("sig:pc-closed",{fromPeerId:j});return}try{if(QA.sdp){if(Ii.debug("sig:sdp",{fromPeerId:j,type:QA.sdp.type}),console.log("[RTC] Received SDP",{fromPeerId:j,type:QA.sdp.type,signalingState:UA.signalingState}),jg(UA))return;const oe=QA.sdp;if(oe.type==="answer"&&jA(UA)){Ii.debug("sig:stale-answer-ignored",{fromPeerId:j,signalingState:UA.signalingState}),console.log("[RTC] Ignoring stale answer (connection already stable)",{fromPeerId:j});return}const me=jA(UA)||dA.isSettingRemoteAnswerPending,be=oe.type==="offer"&&!me;if(dA.ignoreOffer=!(i<j)&&be,dA.ignoreOffer){console.log("[RTC] Ignoring offer due to collision",{fromPeerId:j});return}if(oe.type==="answer"&&(dA.isSettingRemoteAnswerPending=!0),be&&(console.log("[RTC] Rolling back due to offer collision",{fromPeerId:j}),jg(UA)||await UA.setLocalDescription({type:"rollback"})),jg(UA))return;if(await UA.setRemoteDescription(oe),console.log("[RTC] Set remote description",{fromPeerId:j,type:oe.type,signalingState:UA.signalingState}),dA.isSettingRemoteAnswerPending=!1,oe.type==="offer"&&!jg(UA)){const $e=await UA.createAnswer();if(jg(UA))return;await UA.setLocalDescription($e),console.log("[RTC] Sending answer",{fromPeerId:j,type:(TA=UA.localDescription)==null?void 0:TA.type}),await a(S.current,j,{sdp:UA.localDescription})}for(;dA.iceBuffer.length&&!jg(UA);){const $e=dA.iceBuffer.shift();try{await UA.addIceCandidate($e)}catch{}}}else if(QA.ice){if(Ii.debug("sig:ice",{fromPeerId:j,hasRemote:!!UA.remoteDescription}),jg(UA))return;const oe=QA.ice;if(UA.remoteDescription)try{await UA.addIceCandidate(oe)}catch{}else dA.iceBuffer.push(oe)}}catch(oe){const me=String(oe);Ii.error("sig:error",{fromPeerId:j,err:me}),console.error("[RTC] Signal error",{fromPeerId:j,err:me}),(me.includes("order of m-lines")||me.includes("m-line")||me.includes("InvalidAccessError"))&&(console.log("[RTC] M-line mismatch detected, rebuilding peer",{fromPeerId:j}),Ii.warn("sig:mline-mismatch-rebuild",{fromPeerId:j}),await YA(j))}},onRtcVideoEnabled:({playerId:j,enabled:QA})=>{Ii.debug("sig:video-enabled",{playerId:j,enabled:QA}),d(dA=>({...dA,[j]:!!QA}))}}),E.useEffect(()=>{let j=!0;return(async()=>{try{const QA=await Xo();if(!j)return;b(!1),i&&d(dA=>({...dA,[i]:!1})),M(g?!!QA.chatAudio:!1)}catch{}})(),()=>{j=!1}},[i,g]),E.useEffect(()=>{g||(M(!1),w&&o("auth:lost"),b(!1),i&&d(j=>({...j,[i]:!1})),(async()=>{for(const[j,QA]of c.current)await H(QA.pc,void 0),await P(QA.pc,void 0),await he(j,QA.pc,QA).catch(()=>{})})(),gA(),pA())},[g,i]),E.useEffect(()=>{const j=QA=>{const dA=QA.detail;dA&&(typeof dA.video=="boolean"&&dA.video===!1&&(b(!1),d(UA=>({...UA,[i]:!1}))),typeof dA.chatAudio=="boolean"&&M(dA.chatAudio))};return window.addEventListener("app:settings",j),()=>window.removeEventListener("app:settings",j)},[i]),E.useEffect(()=>{const j=()=>{if(document.visibilityState==="visible")for(const[UA,TA]of c.current)O(UA,TA)},QA=()=>{for(const[UA,TA]of c.current)O(UA,TA)},dA=()=>{for(const[UA,TA]of c.current)O(UA,TA)};return document.addEventListener("visibilitychange",j),window.addEventListener("online",QA),window.addEventListener("offline",dA),()=>{document.removeEventListener("visibilitychange",j),window.removeEventListener("online",QA),window.removeEventListener("offline",dA)}},[]),E.useEffect(()=>{try{const j=window;j.__rtcCtxInternal||(j.__rtcCtxInternal={}),j.__rtcCtxInternal.peers=c.current,j.__rtcCtxInternal.myVideoRef=m,j.__rtcCtxInternal.videoEnabledState={current:w}}catch{}},[w,p,J]),C.jsx(udA.Provider,{value:{videoEnabled:w,setVideoEnabled:le,enableCamera:BA,joinRtc:Ie,leaveRtc:DA,cameraOwnerId:Q,setCameraOwner:rA,remoteStreams:l,myVideo:p,micEnabled:G,setMicEnabled:NA,hasVideo:EA,speaking:fA,remoteVideoFlags:h},children:e})}function gXA(e){const A=[];for(const[t,i]of e)try{const n=i.pc;A.push({id:t,state:n.connectionState,ice:n.iceConnectionState,signaling:n.signalingState})}catch{}return A}function k3(e){var A,t,i,n;try{const g=window,o=g.__rtcCtxInternal||{},s=o.peers||new Map,a=(A=o.myVideoRef)==null?void 0:A.current,r=(t=a==null?void 0:a.getVideoTracks)==null?void 0:t.call(a)[0],I={t:Date.now(),label:e,videoEnabled:(i=o.videoEnabledState)==null?void 0:i.current,hasStream:!!a,trackState:r==null?void 0:r.readyState,muted:r==null?void 0:r.muted,peers:gXA(s),activePeerCount:s.size};g.__rtcDiag||(g.__rtcDiag=[]),g.__rtcDiag.push(I),g.__rtcDiag.length>200&&g.__rtcDiag.splice(0,g.__rtcDiag.length-200),(n=g.dispatchEvent)==null||n.call(g,new CustomEvent("rtc:diag",{detail:I}))}catch{}}try{queueMicrotask(()=>{const e=window;e.__rtcCtxInternal||(e.__rtcCtxInternal={}),e.__dumpRtcDiag=k3})}catch{}function Il(){var _;const e=X9A(),A=AXA(),t=!!e&&!e.liveKitFailed,i=e==null?void 0:e.joinRoom,n=e==null?void 0:e.leaveRoom,g=e==null?void 0:e.setVideoEnabled,o=e==null?void 0:e.setMicEnabled,s=A==null?void 0:A.joinRtc,a=A==null?void 0:A.leaveRtc,r=A==null?void 0:A.setVideoEnabled,I=A==null?void 0:A.setMicEnabled,c=E.useRef(s);c.current=s;const l=E.useRef(a);l.current=a;const B=E.useRef(r);B.current=r;const Q=E.useRef(I);Q.current=I;const h=(e==null?void 0:e.liveKitFailed)??!1,d=(e==null?void 0:e.pendingRoomId)??null;E.useEffect(()=>{h&&d&&c.current&&(console.log("[useUnifiedRtc] LiveKit failed — falling back to mesh P2P for room:",d),Promise.resolve(c.current(d)).catch(K=>{console.error("[useUnifiedRtc] Mesh fallback join failed:",K)}))},[h,d]);const p=E.useCallback(async K=>{t&&i?await i(K):c.current&&await Promise.resolve(c.current(K))},[t,i]),y=E.useCallback(async K=>{t&&n?await n():l.current&&l.current(K)},[t,n]),m=E.useCallback(async K=>{t&&g?await g(K):B.current&&await B.current(K)},[t,g]),D=E.useCallback(async K=>{t&&o?await o(K):Q.current&&await Q.current(K)},[t,o]),S=E.useMemo(()=>{if(t){const K={};e.localParticipant&&(K[e.localParticipant.id]=e.localParticipant.isSpeaking);for(const J of e.participants)K[J.id]=J.isSpeaking;return K}return(A==null?void 0:A.speaking)??{}},[t,e==null?void 0:e.localParticipant,e==null?void 0:e.participants,A==null?void 0:A.speaking]),k=E.useRef(null),N=E.useMemo(()=>{var J,q,v,U;if(!t)return A==null?void 0:A.myVideo;const K=((J=e.localParticipant)==null?void 0:J.videoTrack)||e.localVideoTrack;if(K){if(K.mediaStream instanceof MediaStream){const T=K.mediaStream,z=((q=T.getVideoTracks()[0])==null?void 0:q.id)??"";return((v=k.current)==null?void 0:v.trackId)===z?k.current.ms:(k.current={trackId:z,ms:T},T)}const x=K.mediaStreamTrack;if(x instanceof MediaStreamTrack){if(((U=k.current)==null?void 0:U.trackId)===x.id)return k.current.ms;const T=new MediaStream;return T.addTrack(x),k.current={trackId:x.id,ms:T},T}}k.current=null},[t,(_=e==null?void 0:e.localParticipant)==null?void 0:_.videoTrack,e==null?void 0:e.localVideoTrack,A==null?void 0:A.myVideo]),G=E.useRef({}),M=E.useMemo(()=>{if(!t)return(A==null?void 0:A.remoteStreams)??{};const K={},J=G.current,q=new Set;for(const v of e.participants){const U=v.videoTrack&&"mediaStreamTrack"in v.videoTrack?v.videoTrack.mediaStreamTrack:null,x=v.audioTrack&&"mediaStreamTrack"in v.audioTrack?v.audioTrack.mediaStreamTrack:null;if(!U&&!x)continue;const T=(U==null?void 0:U.id)??"",z=(x==null?void 0:x.id)??"";q.add(v.id);const Z=J[v.id];if(Z&&Z.videoId===T&&Z.audioId===z){K[v.id]=Z.ms;continue}const eA=new MediaStream;U&&eA.addTrack(U),x&&eA.addTrack(x),J[v.id]={videoId:T,audioId:z,ms:eA},K[v.id]=eA}for(const v of Object.keys(J))q.has(v)||delete J[v];return K},[t,e==null?void 0:e.participants,A==null?void 0:A.remoteStreams]),w=E.useMemo(()=>{if(!t)return A==null?void 0:A.remoteVideoFlags;const K={};e.localParticipant&&(K[e.localParticipant.id]=e.localParticipant.videoEnabled);for(const J of e.participants)K[J.id]=J.videoEnabled;return K},[t,e==null?void 0:e.localParticipant,e==null?void 0:e.participants,A==null?void 0:A.remoteVideoFlags]),b=E.useMemo(()=>{if(t){const K=e.localParticipant;if(K&&(K.audioEnabled||K.videoEnabled))return!0;for(const J of e.participants)if(J.audioEnabled||J.videoEnabled)return!0;return!1}return N?!0:Object.keys((A==null?void 0:A.remoteStreams)??{}).length>0},[t,e==null?void 0:e.localParticipant,e==null?void 0:e.participants,A==null?void 0:A.remoteStreams,N]);return E.useMemo(()=>({joinRoom:p,leaveRoom:y,connected:(t?!!(e!=null&&e.connected):((A==null?void 0:A.activePeerCount)??0)>0)&&b,videoEnabled:t?!!(e!=null&&e.videoEnabled):(A==null?void 0:A.videoEnabled)??!1,setVideoEnabled:m,localVideoTrack:t?(e==null?void 0:e.localVideoTrack)??null:(A==null?void 0:A.myVideo)??null,micEnabled:t?!!(e!=null&&e.micEnabled):(A==null?void 0:A.micEnabled)??!1,setMicEnabled:D,speaking:S,participants:t?(e==null?void 0:e.participants)??[]:[],localParticipant:t?(e==null?void 0:e.localParticipant)??null:null,remoteStreams:M,myVideo:N,remoteVideoFlags:w,throttleVideoForAnimation:A==null?void 0:A.throttleVideoForAnimation,mode:t?"livekit":"mesh"}),[p,y,m,D,S,t,e,A,N,M,w,b])}const ddA=E.createContext(null),nI=()=>E.useContext(ddA),rY={};function oXA({children:e}){const{user:A,meId:t}=tn(),i=t||(A==null?void 0:A.id),{resetSpin:n}=kB(),g=qi(),{joinRoom:o,leaveRoom:s,setSpectate:a,pokerJoinRoom:r,getRoomsList:I}=Mo(),[c,l]=E.useState(()=>{try{const w=window.__PRESEEDED_ROOM;if(w&&typeof w=="object")return delete window.__PRESEEDED_ROOM,w}catch{}return null}),{leaveRoom:B,joinRoom:Q}=Il(),h=E.useRef(i);E.useEffect(()=>{const w=h.current;h.current=i,w&&i&&w!==i&&l(b=>{if(!b)return b;console.log("[RoomContext] identity changed (%s → %s), clearing stale room %s",w,i,b.id);try{B(b.id)}catch{}return null})},[i,B]);const d=E.useRef({}),p=E.useMemo(()=>((c==null?void 0:c.gameState)??{}).phase==="waiting"||c===null,[c]),y=E.useCallback(async w=>{var b,_,K,J,q,v;try{const U=await o(w);if(!(U!=null&&U.ok))throw new Error((U==null?void 0:U.error)||"Failed to join room");try{n()}catch{}if(console.log("joined room*********",U.room),l(U.room),(b=U.room)!=null&&b.singlePlayer)console.log("[RoomContext] skipping joinRtc for single-player room");else{console.log("[RoomContext] calling joinRtc for room",(_=U.room)==null?void 0:_.id);try{await Promise.resolve(Q==null?void 0:Q(w))}catch(x){console.error("[RoomContext] joinRtc error:",x)}}if(!((K=U.room)!=null&&K.singlePlayer))try{const x=await(I==null?void 0:I()),z=(x&&(Array.isArray(x==null?void 0:x.rooms)?x.rooms:Array.isArray((J=x==null?void 0:x.data)==null?void 0:J.rooms)?x.data.rooms:[])||[]).find(Z=>(Z==null?void 0:Z.id)===w);z&&Array.isArray(z.players)&&l(Z=>{if(!Z||Z.id!==w)return Z;const eA=Array.isArray(Z.players)?Z.players:[],aA=new Map(eA.map(pA=>[pA.id,pA])),sA=z.players.map(pA=>{const gA=aA.get(pA.id);if(gA){const yA=pA.name&&pA.name!=="Bot"&&pA.name!=="Player"?pA.name:gA.name&&gA.name!=="Bot"&&gA.name!=="Player"?gA.name:pA.name||gA.name,fA=pA.avatarUrl??gA.avatarUrl??null;return{...gA,...pA,name:yA,avatarUrl:fA}}return pA});for(const pA of eA)sA.some(gA=>gA.id===pA.id)||sA.push(pA);return{...Z,players:sA}})}catch{}return{ok:!0,room:U.room}}catch(U){try{if(!(typeof window<"u"&&(((v=(q=window.location)==null?void 0:q.search)==null?void 0:v.includes("e2e=1"))||window.__E2E===!0||typeof window.sessionStorage<"u"&&window.sessionStorage.getItem("e2e")==="1")))throw U;const T=Date.now(),z=i||"e2e-user",Z=(A==null?void 0:A.name)||"E2E User",eA={id:w,name:"E2E Room",gameMode:"craps",createdAt:T,updatedAt:T,bankerId:"bank",players:[{id:z,name:Z,isReady:!0,balance:1e3},{id:"bank",name:"Bank",isReady:!0,balance:1e6}],gameState:{gameMode:"craps",crapsPoint:null,currentRollerId:z,turnOrder:[z],roundSeq:1,crapsPassBets:[{playerId:z,amount:10}],crapsDontPassBets:[],crapsPlaceBets:[]}};try{n()}catch{}l(eA);return}catch{throw U}}},[o,n,Q,I,i,A==null?void 0:A.name]),m=E.useCallback(async()=>{if(c){try{await B(c.id)}catch{}try{await s(c.id)}finally{l(null)}}},[s,B,c]),D=E.useCallback((w,b)=>{if(!b)return w;if(!w)return b;try{const _=Array.isArray(w.players)?w.players:[],K=Array.isArray(b.players)?b.players:[];let J;if(K.length===0&&_.length>0)J=_;else if(_.length===0)J=K;else{const q=new Map(_.map(U=>[String(U.id),U])),v=new Map(K.map(U=>[String(U.id),U]));J=[];for(const[U,x]of v.entries()){const T=q.get(U);T?J.push({...T,...x,name:x.name||T.name,avatarUrl:x.avatarUrl??T.avatarUrl}):J.push(x)}}return{...w,...b,players:J}}catch{return b||w}},[]);Os({onJoinedRoom:({room:w})=>{try{n()}catch{}l(b=>D(b,w))},onOtherPlayerJoined:({room:w})=>l(b=>D(b,w)),onOtherLeft:({room:w})=>{let b=!1,_=null;if(l(K=>{var q,v;const J=D(K,w);try{const U=Array.isArray(w==null?void 0:w.players)?w==null?void 0:w.players:Array.isArray(J==null?void 0:J.players)?J.players:[],x=String(i||""),T=x&&U.some(z=>String(z==null?void 0:z.id)===x);if(T&&K)try{delete d.current[String(K.id||"")]}catch{}if(!T&&K){if(!!(w!=null&&w.singlePlayer||J!=null&&J.singlePlayer)||((q=w==null?void 0:w.gameState)==null?void 0:q.gameMode)==="zentara"||((v=J==null?void 0:J.gameState)==null?void 0:v.gameMode)==="zentara")return J;const eA=String(K.id||""),aA=d.current[eA]||0,sA=Date.now();return aA?sA-aA<1500?J:(b=!0,_=String(K.id),delete d.current[eA],null):(d.current[eA]=sA,J)}}catch{}return J}),b){try{_&&(B==null||B(_))}catch{}try{g("/lobby",{replace:!0})}catch{}}},onSpectatorsUpdated:({spectators:w})=>{l(b=>b&&{...b,gameState:{...b.gameState,spectators:w}})},onPlayerProfileUpdated:({playerId:w,name:b,avatarUrl:_})=>{l(K=>{if(!K)return K;const J=K.players.map(q=>q.id!==w?q:{...q,...b!==void 0&&{name:b},..._!==void 0&&{avatarUrl:_}});return{...K,players:J}})},onBetsUpdated:({room:w})=>{w&&l(b=>{if(!b)return w;try{const _=new Map(b.players.map(q=>[q.id,q])),K=new Map((w.players||[]).map(q=>[q.id,q])),J=b.players.map(q=>{const v=K.get(q.id);if(!v)return q;const U={...q,...v};return(!v.name||v.name==="Player"||v.name==="Anonymous")&&q.name&&q.name!=="Player"&&q.name!=="Anonymous"&&(U.name=q.name),v.avatarUrl==null&&q.avatarUrl&&(U.avatarUrl=q.avatarUrl),U});for(const[q,v]of K.entries())_.has(q)||J.push(v);return{...b,gameState:w.gameState??b.gameState,name:w.name??b.name,maxPlayers:w.maxPlayers??b.maxPlayers,private:w.private??b.private,singlePlayer:w.singlePlayer??b.singlePlayer,players:J}}catch{return b}})},onBankerChanged:w=>{l(b=>!b||b.id!==w.roomId?b:{...b,gameState:{...b.gameState,banker:w.bankerId,currentRollerId:w.currentRollerId,roundSeq:w.roundSeq,bankRoll:null}})},onForceLogout:w=>{(w==null?void 0:w.reason)==="session_superseded"&&EcA();try{c!=null&&c.id&&B(c.id)}catch{}l(null)},onRoomUpdateState:({roomId:w,gameState:b,room:_})=>{const K=(_==null?void 0:_.gameState)??b;if(!K)return;const J=Array.isArray(_==null?void 0:_.players)?_.players:[];let q=!1,v=null;if(l(U=>{var T;const x=z=>{if(!J.length)return z;const Z=new Map(z.map(eA=>[eA.id,eA]));for(const eA of J){const aA=Z.get(eA.id);if(aA){const sA=!eA.name||eA.name==="Player"||eA.name==="Anonymous",pA={...aA,...eA};sA&&aA.name&&aA.name!=="Player"&&aA.name!=="Anonymous"&&(pA.name=aA.name),eA.avatarUrl==null&&aA.avatarUrl&&(pA.avatarUrl=aA.avatarUrl),Z.set(eA.id,pA)}else Z.set(eA.id,eA)}return Array.from(Z.values())};try{if(J.length&&U&&U.id===w){const z=String(i||"");if(z){const Z=J.some(eA=>String(eA==null?void 0:eA.id)===z);if(Z)try{delete d.current[String(U.id||"")]}catch{}if(!Z){if(!!(_!=null&&_.singlePlayer||U!=null&&U.singlePlayer))return{...U,players:x(U.players),gameState:K};if((K==null?void 0:K.gameMode)==="zentara"||((T=U==null?void 0:U.gameState)==null?void 0:T.gameMode)==="zentara")return{...U,players:x(U.players),gameState:K};const sA=String(U.id||""),pA=d.current[sA]||0,gA=Date.now();return pA?gA-pA<1500?{...U,players:x(U.players),gameState:K}:(q=!0,v=String(U.id),delete d.current[sA],null):(d.current[sA]=gA,{...U,players:x(U.players),gameState:K})}}}}catch{}return U&&U.id===w?{...U,players:x(U.players),gameState:K}:U||{id:w,players:J,gameState:K}}),q){try{v&&(B==null||B(v))}catch{}try{g("/lobby",{replace:!0})}catch{}}},onPlayerBalanceUpdated:({playerId:w,balance:b})=>{console.log("[RoomContext] onPlayerBalanceUpdated received",{playerId:w,balance:b}),l(_=>{if(!_)return _;const K=_.players.findIndex(v=>v.id===w);if(console.log("[RoomContext] onPlayerBalanceUpdated processing",{playerId:w,balance:b,idx:K,playersCount:_.players.length}),K<0){const v=[..._.players,{id:w,balance:b}];return{..._,players:v}}const J=_.players[K];if(typeof(J==null?void 0:J.balance)=="number"&&J.balance===b)return _;const q=_.players.slice();return q[K]={...J,balance:b},{..._,players:q}})},onError:w=>{console.warn("Socket error:",w);try{const b=(Kl==null?void 0:Kl())||[],_=Date.now(),K=[...b].filter(J=>_-J.ts<1200).slice(-1)[0];K&&console.debug("[socket][error-source]",{event:K.event,mode:K.mode,ts:K.ts})}catch{}}});const S=E.useMemo(()=>({room:c,isWaiting:p,joinRoom:y,leaveRoom:m,setRoom:l,setSpectatingForMe:async w=>{if(c)try{return await a(c.id,w)}catch(b){return{ok:!1,error:(b==null?void 0:b.message)||"Failed"}}}}),[c,p,y,m,a]),k=Ms(),N=E.useRef(0),G=E.useRef(!1),M=E.useCallback(async()=>{var _,K;const w=Date.now();if(w-(N.current||0)<800)return;N.current=w;const b=c==null?void 0:c.id;if(!b){try{const q=((Kl==null?void 0:Kl())||[]).slice(-1)[0];if(q&&String(q.event).toLowerCase().includes("create_room")&&w-(q.ts||0)<1500)return}catch{}return}try{const q=((Kl==null?void 0:Kl())||[]).slice(-1)[0];q&&String(q.event).toLowerCase().includes("create_room")&&w-(q.ts||0)<1500&&await new Promise(U=>setTimeout(U,1100))}catch{}try{const J=(c==null?void 0:c.gameMode)==="poker";let q;if(J&&typeof r=="function"){const v=rY[b];if(v)q=await v;else{const U=r(b);rY[b]=U;try{q=await U}finally{delete rY[b]}}}else q=await o(b);if(q!=null&&q.ok){try{n()}catch{}if(l(q.room),!((_=q.room)!=null&&_.singlePlayer))try{await Promise.resolve(Q==null?void 0:Q(b))}catch{}try{const v=await(I==null?void 0:I()),x=(v&&(Array.isArray(v==null?void 0:v.rooms)?v.rooms:Array.isArray((K=v==null?void 0:v.data)==null?void 0:K.rooms)?v.data.rooms:[])||[]).find(T=>(T==null?void 0:T.id)===b);x&&Array.isArray(x.players)&&l(T=>!T||T.id!==b?T:{...T,players:x.players})}catch{}}}catch(J){console.warn("[room] rejoin after reconnect failed",J)}},[c==null?void 0:c.id,r,o,n,Q,I]);return E.useEffect(()=>{var J;if(!k)return;const w=q=>{q!=="io client disconnect"&&(G.current=!0)},b=()=>{G.current&&(G.current=!1,M())},_=()=>{M()},K=()=>{M()};k.on("disconnect",w),k.on("connect",b);try{k.io.on("reconnect",_)}catch{}try{(J=k.on)==null||J.call(k,"reconnect",K)}catch{}return()=>{var q;k.off("disconnect",w),k.off("connect",b);try{k.io.off("reconnect",_)}catch{}try{(q=k.off)==null||q.call(k,"reconnect",K)}catch{}}},[k,M]),E.useEffect(()=>{const w=()=>{try{document.visibilityState==="visible"&&(G.current||!(k!=null&&k.connected))&&M()}catch{}},b=()=>{(G.current||!(k!=null&&k.connected))&&M()},_=()=>{(G.current||!(k!=null&&k.connected))&&M()},K=()=>{console.log("[RoomContext] ad:complete event received, triggering room rejoin"),M()};return window.addEventListener("visibilitychange",w),window.addEventListener("focus",b),window.addEventListener("pageshow",_),window.addEventListener("ad:complete",K),()=>{window.removeEventListener("visibilitychange",w),window.removeEventListener("focus",b),window.removeEventListener("pageshow",_),window.removeEventListener("ad:complete",K)}},[k,M]),C.jsx(ddA.Provider,{value:S,children:e})}const qb=globalThis.__lastWagersFetchAt||(globalThis.__lastWagersFetchAt={}),oeA=500;function gx(e,A){const t=Ms(),{room:i}=nI(),n=e&&A?`betsnap:${e}:${A}`:null,[g,o]=E.useState(()=>({roundSeq:1,open:[],settled:[],openAll:[],settledAll:[],playerBalance:null}));E.useEffect(()=>{n&&(async()=>{try{const W=await dS(n);if(!(W!=null&&W.mainWagerId))return;o($=>$.open.some(H=>H.type==="MAIN"&&H.playerId===A)?$:{...$,roundSeq:W.roundSeq||$.roundSeq,open:[...$.open,{id:W.mainWagerId,type:"MAIN",playerId:A,acceptedById:null,amount:0,roundSeq:W.roundSeq}]})}catch{}})()},[n,A]),E.useEffect(()=>{n&&(async()=>{try{const W=await dS(n);if(!W)return;W!=null&&W.mainWagerId&&o($=>$.open.some(H=>H.type==="MAIN"&&H.playerId===A)?$:{...$,roundSeq:W.roundSeq||$.roundSeq,open:[...$.open,{id:W.mainWagerId,type:"MAIN",playerId:A,acceptedById:null,amount:0,roundSeq:W.roundSeq}]})}catch{}})()},[n,A]);const{getWagers:s,createSideBet:a,cancelSideBet:r,acceptSideBet:I,placeMainBet:c,cancelMainBet:l}=Mo(),[B,Q]=E.useState([]),h=E.useRef(new Set),d=E.useRef(new Set),[p,y]=E.useState(0),m=E.useRef(null);E.useEffect(()=>{if(m.current===null){m.current=e;return}o({roundSeq:1,open:[],settled:[],openAll:[],settledAll:[]}),Q([]),h.current.clear(),d.current.clear(),y(0),n&&hS(n)},[e,n]),Os({onBetsUpdated:W=>{n&&(async()=>{try{const P=W.open.find(tA=>tA.type==="MAIN"&&tA.playerId===A);P?await uL(n,{roundSeq:W.roundSeq,mainWagerId:P.id}):await hS(n)}catch{}})(),o(W);const $=W.settled.filter(P=>P.roundSeq===W.roundSeq);Q($.filter(P=>!h.current.has(P.id)));const H=(W.open||[]).filter(P=>P.type==="SIDE"&&!P.acceptedById&&P.playerId!==A&&P.subjectId!==A).filter(P=>!d.current.has(P.id));y(H.length)}});const[D,S]=E.useState([]);E.useEffect(()=>{S([])},[e]),E.useEffect(()=>{const W=Array.isArray(g.settledAll)?g.settledAll:[];W.length===0&&D.length===0||S($=>{if(W.length===0)return $;const L=new Map;for(const P of $)L.set(P.id,P);for(const P of W)L.set(P.id,P);return Array.from(L.values()).sort((P,tA)=>{const iA=Number(P.roundSeq||0),oA=Number(tA.roundSeq||0);return oA!==iA?oA-iA:String(tA.id).localeCompare(String(P.id))})})},[g.settledAll]),E.useEffect(()=>{if(!e)return;let W=null;const $=()=>{const H=Date.now(),P=qb[e]||0;H-P<oeA||(qb[e]=H,W=window.setTimeout(()=>{try{s(e)}catch{}},300))};if((i==null?void 0:i.id)===e)return $(),()=>{W&&clearTimeout(W)};const L=window.setTimeout(()=>{$()},500);return()=>{W&&clearTimeout(W),clearTimeout(L)}},[e,i==null?void 0:i.id,s]),E.useEffect(()=>{if(!t)return;const W={current:0},$={current:t.connected},L=()=>{if(!e||(i==null?void 0:i.id)!==e)return;const iA=Date.now();if(!(iA-W.current<400)&&!(iA-(qb[e]||0)<oeA)){W.current=iA,qb[e]=iA;try{d.current.clear(),y(0),h.current.clear(),setTimeout(()=>{try{s(e)}catch{}},300)}catch{}}},H=()=>{if(!$.current){$.current=!0;return}L()},P=()=>{L()},tA=()=>{document.visibilityState==="visible"&&L()};return t.on("connect",H),window.addEventListener("ad:complete",P),window.addEventListener("visibilitychange",tA),()=>{t.off("connect",H),window.removeEventListener("ad:complete",P),window.removeEventListener("visibilitychange",tA)}},[t,e,i==null?void 0:i.id,s]),E.useEffect(()=>{Q([]),h.current.clear()},[g.roundSeq]);const k=E.useMemo(()=>{var W;return(W=g.openAll)==null?void 0:W.filter($=>$.type==="MAIN")},[g.openAll]),N=E.useMemo(()=>g.open.find(W=>W.type==="MAIN"&&W.playerId===A),[g.open,A]),G=E.useMemo(()=>{var W;return(W=g.openAll)==null?void 0:W.filter($=>$.type==="SIDE")},[g.openAll]),M=E.useMemo(()=>g.open.filter(W=>W.type==="SIDE"&&(W.playerId===A||W.acceptedById===A)),[g.open,A]),w=E.useMemo(()=>g.settled.filter(W=>W.playerId===A||W.acceptedById===A),[g.settled,A]);E.useMemo(()=>D.filter(W=>W.playerId===A||W.acceptedById===A),[D,A]);const b=E.useMemo(()=>g.open.filter(W=>W.playerId===A||W.acceptedById===A).reduce((W,$)=>W+($.amount||0),0),[g.open,A]),[_,K]=E.useState([]);E.useEffect(()=>{const W=setTimeout(()=>{K(D.filter($=>$.playerId===A||$.acceptedById===A))},$o.mySettledDelayMs);return()=>clearTimeout(W)},[D,A]);const[J,q]=E.useState(null);E.useEffect(()=>{const W=setTimeout(()=>{q(g.playerBalance)},$o.balanceDelayMs);return()=>clearTimeout(W)},[g.playerBalance]);const[v,U]=E.useState([]);E.useEffect(()=>{const W=setTimeout(()=>{U(D)},$o.settledAllDelayMs);return()=>clearTimeout(W)},[D]);const x=E.useMemo(()=>g.open.filter(W=>W.type==="SIDE"&&!W.acceptedById&&W.subjectId!==A&&W.playerId!==A),[g.open,A]),T=()=>Q(W=>{if(W.length===0)return W;const[$,...L]=W;return h.current.add($.id),L}),z=W=>Q($=>(h.current.add(W),$.filter(L=>L.id!==W))),Z=E.useCallback(()=>{for(const W of x)d.current.add(W.id);y(0)},[x]),eA=E.useCallback(async W=>{var $;try{const L=await a(e,{amount:Math.floor(W.amount),subjectId:W.subjectId,predicate:W.predicate,oddsBp:W.oddsBp});return L!=null&&L.ok?{ok:!0,betId:(($=L==null?void 0:L.wager)==null?void 0:$.id)||(L==null?void 0:L.id)||W.clientBetId}:{ok:!1,error:(L==null?void 0:L.error)||"Failed to place side bet"}}catch(L){return{ok:!1,error:(L==null?void 0:L.message)||"Failed to place side bet"}}},[e,a]),aA=E.useCallback(async W=>{try{const $=await r(e,W);return $!=null&&$.ok?{ok:!0}:{ok:!1,error:($==null?void 0:$.error)||"Failed to cancel side bet"}}catch($){return{ok:!1,error:($==null?void 0:$.message)||"Failed to cancel side bet"}}},[e,r]),sA=E.useCallback(async W=>{try{const $=await I(e,W);return $!=null&&$.ok?{ok:!0}:{ok:!1,error:($==null?void 0:$.error)||"Failed to accept side bet"}}catch($){return{ok:!1,error:($==null?void 0:$.message)||"Failed to accept side bet"}}},[e,I]),pA=E.useCallback(async W=>{var $;try{const L=await c(e,Math.floor(W));return L!=null&&L.ok?{ok:!0,wagerId:(($=L==null?void 0:L.wager)==null?void 0:$.id)||(L==null?void 0:L.id)}:{ok:!1,error:(L==null?void 0:L.error)||"Failed to place main bet"}}catch(L){return{ok:!1,error:(L==null?void 0:L.message)||"Failed to place main bet"}}},[e,c]),gA=E.useCallback(async W=>{try{const $=await l(e,W);return $!=null&&$.ok?{ok:!0}:{ok:!1,error:($==null?void 0:$.error)||"Failed to cancel main bet"}}catch($){return{ok:!1,error:($==null?void 0:$.message)||"Failed to cancel main bet"}}},[e,l]),[yA,fA]=E.useState([]),RA=E.useRef(g.roundSeq),qA=E.useRef(new Set);return E.useEffect(()=>{RA.current!==g.roundSeq&&(RA.current=g.roundSeq,qA.current.clear(),fA([]));const W=g.settledAll.filter($=>$.roundSeq===g.roundSeq&&!qA.current.has($.id));if(W.length>0){W.forEach(L=>qA.current.add(L.id)),fA(W);const $=setTimeout(()=>fA([]),1e3);return()=>clearTimeout($)}},[g.settledAll,g.roundSeq]),{roundSeq:g.roundSeq,openAll:g.openAll,open:g.open,settled:g.settled,settledAll:v,myOpenMain:N,myOpenSides:M,openAllMain:k,openAllSides:G,mySettledThisRound:w,mySettledAll:_,myExposure:b,unseenSettledWagers:B,consumeNextUnseen:T,markAsSeen:z,offersToMe:x,newOfferCount:p,markOffersAsSeen:Z,placeSideBet:eA,cancelSideBet:aA,acceptSideBet:sA,placeMainBet:pA,cancelMainBet:gA,playerBalance:J,newSettlements:yA}}function seA(e){return e==="WIN"?"LOSE":e==="LOSE"?"WIN":e}function C_(e){const A=Math.round(Number(e)||0);try{return`z${new Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(A)}`}catch{return`z${A}`}}function lf(e,A){if(!e)return{myResult:"",myPayout:0,label:""};const t=e.playerId,i=A===t,n=e.acceptedById,g=n!=null&&A===n;if(e.type==="MAIN"){if(!(i||g))return{myResult:"N/A",myPayout:0,label:"Not your bet"};if(e.result==="PUSH")return{myResult:"PUSH",myPayout:0,label:"Push"};if(i){const o=aeA(e);return{myResult:e.result,myPayout:e.result==="WIN"?o:0,label:Zh(e.result,e.result==="WIN"?o:0,e.amount)}}else{const o=seA(e.result),s=sXA(e);return{myResult:o,myPayout:o==="WIN"?s:0,label:Zh(o,o==="WIN"?s:0,e.amount)}}}if(e.type==="SIDE"){const o=A===e.acceptedById;if(!(i||o))return{myResult:"N/A",myPayout:0,label:"Not your bet"};if(e.result==="PUSH")return{myResult:"PUSH",myPayout:0,label:"Push"};if(i){const s=aeA(e),a=e.result==="WIN"?s:0,r={myResult:e.result,myPayout:a,label:Zh(e.result,a,e.amount)};if(r.myResult==="WIN"&&r.myPayout<=0){const I=typeof e.payout=="number"&&e.payout>0?e.payout:e.amount;return{myResult:r.myResult,myPayout:I,label:Zh(r.myResult,I,e.amount)}}return r}else{const s=seA(e.result),a=aXA(e),r=s==="WIN"?a:0,I={myResult:s,myPayout:r,label:Zh(s,r,e.amount)};if(I.myResult==="WIN"&&I.myPayout<=0){const c=typeof e.payout=="number"&&e.payout>0?e.payout:e.amount;return{myResult:I.myResult,myPayout:c,label:Zh(I.myResult,c,e.amount)}}return I}}return{myResult:"PUSH",myPayout:0,label:"Push"}}function aeA(e){return typeof e.payout=="number"?e.payout:e.amount}function sXA(e){return e.amount}function aXA(e){return typeof e.oddsBp=="number"&&e.oddsBp!==1e4&&typeof e.payout=="number"?e.payout:e.amount}function Zh(e,A,t){return e==="WIN"?`won ${C_(Math.max(0,A))}`:e==="LOSE"?`lost ${C_(Math.max(0,t))}`:e==="PUSH"?"Push":e}function rXA(e){return!e||e.length===0?0:e.reduce((A,t)=>A+Number((t==null?void 0:t.amount)||0),0)}function hdA({meId:e,items:A,onClose:t,nameOf:i,crapsRollHistory:n,gameMode:g,crapsLedgerItems:o}){const s=A,a=g==="craps",r={};for(const c of s){const l=(c==null?void 0:c.acceptedById)===e?c==null?void 0:c.playerId:c==null?void 0:c.acceptedById;if(!l)continue;const B=lf(c,e);let Q=0;B.myResult==="WIN"?Q=Number(B.myPayout??0):B.myResult==="LOSE"&&(Q=-Number((c==null?void 0:c.amount)??0)),r[l]=(r[l]??0)+Q}const I=Object.entries(r).map(([c,l])=>({id:c,name:(i==null?void 0:i(c))||c,delta:l})).sort((c,l)=>l.delta-c.delta);return C.jsxs("div",{className:"results-modal",children:[C.jsx("div",{className:"results-modal__backdrop",onClick:t}),C.jsxs("div",{className:"results-modal__card card",children:[C.jsxs("div",{className:"results-modal__header",children:[C.jsx("h3",{children:"Your Results (this game)"}),C.jsx("button",{className:"btn btn--ghost",onClick:t,children:"Close"})]}),!a&&I.length>0&&C.jsx("div",{className:"results-modal__deltas",children:C.jsx("ul",{className:"results-modal__deltas-list",children:I.map(({id:c,name:l,delta:B})=>C.jsxs("li",{className:`results-modal__delta ${B>=0?"results-modal__delta--pos":"results-modal__delta--neg"}`,children:[l,": ",B>=0?"+":"","z",CB.formatMoney(B,"",0)]},c))})}),a&&C.jsxs(C.Fragment,{children:[(()=>{const c=rXA(o),l=c>=0,B=Math.abs(c);return o?C.jsx("div",{className:"results-modal__deltas",children:C.jsxs("div",{className:`results-modal__delta ${l?"results-modal__delta--pos":"results-modal__delta--neg"}`,children:[C.jsx("strong",{children:"Total won/lost:"})," ",l?"+":"-","z",CB.formatMoney(B,"",0)]})}):null})(),C.jsxs("ul",{className:"betlist results-list",role:"log","aria-live":"polite",children:[((o==null?void 0:o.length)??0)===0&&C.jsx("li",{className:"betitem",children:"No history yet."}),(o||[]).map((c,l)=>{var m,D,S,k,N,G;const B=Number(c.amount||0),Q=B>=0,h=Math.abs(B),p=new Date(c.ts).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});let y="";if(c.kind==="BET_PLACED")y=`Placed ${(m=c.meta)!=null&&m.betType?String(c.meta.betType):"bet"}`;else if(c.kind==="REFUND")y=`Refund ${(D=c.meta)!=null&&D.betType?String(c.meta.betType):"chips"}`;else if(c.kind==="BET_SETTLED"){const M=Array.isArray((S=c.meta)==null?void 0:S.settlements)?c.meta.settlements:[],w=M[0]||null,b=w!=null&&w.betType?String(w.betType):(k=c.meta)!=null&&k.betType?String(c.meta.betType):"bet",_=B>0?"WIN":B<0?"LOSE":"PUSH",K=(G=(N=c.meta)==null?void 0:N.roll)!=null&&G.total?` on ${c.meta.roll.total}`:"",J=M.length>1?` (+${M.length-1} more)`:"";y=`Settled: ${b} ${_}${K}${J}`}return C.jsx("li",{className:"betitem results-modal__bet-row",children:C.jsxs("span",{children:[p," — ",y," ",Q?"+":"-","z",CB.formatMoney(h,"",0)]})},c.id||l)})]})]}),!a&&C.jsxs("ul",{className:"betlist results-list",role:"log","aria-live":"polite",children:[s.length===0&&C.jsx("li",{className:"betitem",children:"No results yet."}),s.map((c,l)=>{const B=(c==null?void 0:c.acceptedById)===e?c==null?void 0:c.playerId:c==null?void 0:c.acceptedById,Q=(()=>{var y,m,D,S;const p=c;return(p==null?void 0:p.acceptedById)===e?(p==null?void 0:p.playerName)||((y=p==null?void 0:p.player)==null?void 0:y.name)||(p==null?void 0:p.playerEmail)||((m=p==null?void 0:p.player)==null?void 0:m.email):(p==null?void 0:p.bankerName)||((D=p==null?void 0:p.banker)==null?void 0:D.name)||(p==null?void 0:p.bankerEmail)||((S=p==null?void 0:p.banker)==null?void 0:S.email)})(),h=(i==null?void 0:i(B))||Q||B||"Unknown",d=Zh(...(()=>{const p=lf(c,e);return[p.myResult,p.myPayout,c.amount]})());return C.jsx("li",{className:"betitem results-modal__bet-row",children:C.jsxs("span",{children:["Round ",c.roundSeq," ",d," vs ",h]})},l)})]})]})]})}var reA;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(reA||(reA={}));var IeA;(function(e){e.Body="body",e.Ionic="ionic",e.Native="native",e.None="none"})(IeA||(IeA={}));const Yb=md("Keyboard"),IXA=e=>{if(e<1e3)return String(e);const A=e/1e3;return`${Number.isInteger(A)?A.toFixed(0):A.toFixed(1)}K`};function pdA({onPlaceBet:e,onCancelBet:A,disabled:t=!1,showCancel:i=!1,min:n=1,max:g,defaultValue:o=25,heading:s,quickAmounts:a=[],onAmountChange:r}){const[I,c]=E.useState(o),l=E.useRef(!1),[B,Q]=E.useState(0),h=E.useRef(null);E.useEffect(()=>{if(!Ui.isNativePlatform())return;Yb.setAccessoryBarVisible({isVisible:!0});const k=Yb.addListener("keyboardWillShow",G=>Q(G.keyboardHeight)),N=Yb.addListener("keyboardWillHide",()=>Q(0));return()=>{Yb.setAccessoryBarVisible({isVisible:!1}),k.then(G=>G.remove()),N.then(G=>G.remove())}},[]);const d=E.useCallback(k=>{const N=k.target.value.replace(/[^0-9]/g,""),G=N===""?0:parseInt(N,10),M=g!=null?Math.min(G,g):G;c(M),r==null||r(M)},[g,r]),p=E.useCallback(()=>{var N;if(l.current||t||i)return;const k=Math.max(n,Math.floor(I));k<=0||(l.current=!0,ti("Light"),(N=h.current)==null||N.blur(),e(k),setTimeout(()=>{l.current=!1},600))},[t,i,I,n,e]),y=E.useCallback(()=>{i&&(ti("Light"),A())},[i,A]),m=E.useCallback(k=>{if(t||i)return;ti("Light");const N=g!=null?Math.min(k,g):k;c(N),r==null||r(N)},[t,g,r,i]),D=!t&&!i&&I>=n,S=a.length>0;return C.jsxs("div",{className:`bet-amount-input${t||i?" bet-amount-input--locked":""}`,children:[s&&C.jsx("div",{className:"bet-amount-input__heading",children:s}),S&&C.jsx("div",{className:"bet-amount-input__quick","aria-label":"Quick bet amounts",children:a.map(k=>C.jsxs("button",{type:"button",className:`bet-amount-input__quick-btn${I===k?" bet-amount-input__quick-btn--active":""}`,onClick:()=>m(k),disabled:t||i,"aria-pressed":I===k,children:["ℤ",IXA(k)]},k))}),C.jsxs("div",{className:`bet-amount-input__group ${t?"bet-amount-input__group--disabled":""}`,children:[C.jsxs("div",{className:"bet-amount-input__field",children:[C.jsx("button",{className:"bet-amount-input__cancel",onClick:y,disabled:!i,children:"Cancel"}),C.jsx("span",{className:"bet-amount-input__symbol",children:"ℤ"}),C.jsx("input",{ref:h,type:"text",inputMode:"numeric",pattern:"[0-9]*",enterKeyHint:"done",className:`bet-amount-input__input${i?" bet-amount-input__input--active-bet":""}`,value:I||"",onChange:d,onKeyDown:k=>{k.key==="Enter"&&D&&(k.currentTarget.blur(),p())},disabled:t||i,"aria-label":"Bet amount",autoComplete:"off"})]}),C.jsx("button",{className:"bet-amount-input__place-btn",onClick:p,disabled:!D,"aria-label":"Place bet",children:"Place Bet"})]}),B>0&&er.createPortal(C.jsxs("div",{className:"bet-amount-input__kb-bar",style:{bottom:B,position:"fixed",left:0,right:0,zIndex:99999,display:"flex",alignItems:"center",gap:10,padding:"10px 16px",background:"rgba(14, 20, 28, 0.97)",borderTop:"1px solid rgba(230, 193, 102, 0.25)",visibility:"visible",opacity:1},children:[C.jsx("span",{style:{fontSize:12,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.04em",color:"#D9CCA7",flexShrink:0},children:"Bet Amount"}),C.jsxs("span",{style:{flex:1,fontSize:24,fontWeight:600,color:"#F5E9CA",textAlign:"center"},children:["ℤ ",I||0]}),C.jsx("button",{className:"bet-amount-input__kb-place",style:{flexShrink:0,padding:"8px 18px",border:"1.5px solid #E6C166",borderRadius:6,background:"transparent",color:"#E6C166",fontSize:13,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em"},onTouchEnd:k=>{k.preventDefault(),D&&p()},disabled:!D,children:"Place Bet"})]}),document.body)]})}const CXA="/assets/roll-btn-web-wZ6ex-aH.webp",fdA=50,Hb=fdA/1200;function ydA({disabled:e,busy:A=!1,onClick:t,onPressStart:i,onChargeChange:n,label:g="ROLL",className:o,"aria-label":s,useImage:a=!0,"data-testid":r}){const I=e||A,c=E.useRef(!1),l=E.useRef(0),B=E.useRef(null),Q=E.useRef(n);Q.current=n,E.useEffect(()=>()=>{B.current&&(clearInterval(B.current),B.current=null)},[]);const h=E.useCallback(()=>{var D;l.current=0,(D=Q.current)==null||D.call(Q,0),B.current&&clearInterval(B.current),B.current=window.setInterval(()=>{var S;l.current=Math.min(1,l.current+Hb),(S=Q.current)==null||S.call(Q,l.current),l.current>=.25&&l.current<.25+Hb*1.5?So("Light"):l.current>=.6&&l.current<.6+Hb*1.5?So("Medium"):l.current>=.95&&l.current<.95+Hb*1.5&&So("Heavy")},fdA)},[]),d=E.useCallback(()=>{var D;B.current&&(clearInterval(B.current),B.current=null),(D=Q.current)==null||D.call(Q,0)},[]),p=E.useCallback(()=>{I||c.current||(c.current=!0,On(),i==null||i(),h())},[I,i,h]),y=E.useCallback(async()=>{if(c.current){c.current=!1,d();try{const D=window;D.__rtcDiag||(D.__rtcDiag=[]),D.__rtcDiag.push({t:Date.now(),label:"ui:rollButtonClick"}),D.__dumpRtcDiag&&D.__dumpRtcDiag("ui:rollButtonClick")}catch{}t();try{window.dispatchEvent(new CustomEvent("ui:roll"))}catch{}await So("Heavy")}},[t,d]),m=E.useCallback(async D=>{var S,k;if(c.current){D.preventDefault();return}if(!I){i==null||i(),(S=Q.current)==null||S.call(Q,1);try{const N=window;N.__rtcDiag||(N.__rtcDiag=[]),N.__rtcDiag.push({t:Date.now(),label:"ui:rollButtonClick"}),N.__dumpRtcDiag&&N.__dumpRtcDiag("ui:rollButtonClick")}catch{}t(),(k=Q.current)==null||k.call(Q,0);try{window.dispatchEvent(new CustomEvent("ui:roll"))}catch{}await So("Heavy")}},[I,t,i]);return C.jsx("div",{className:["roll-wrapper",o].filter(Boolean).join(" "),children:C.jsxs("button",{type:"button",className:["roll",a?"roll--image":"",I?"is-disabled":""].join(" "),onClick:m,onPointerDown:p,onPointerUp:y,onPointerCancel:y,onPointerLeave:y,disabled:I,"aria-label":s??(A?"Rolling dice":"Roll dice"),"aria-busy":A||void 0,"data-testid":r,children:[a&&C.jsx("img",{src:CXA,alt:"",className:"roll__img",draggable:!1}),A&&C.jsx("span",{className:"roll__spinner","aria-hidden":"true"}),C.jsx("span",{className:"roll__halo","aria-hidden":"true"}),!a&&C.jsx("span",{className:"roll__gloss","aria-hidden":"true"}),!a&&C.jsx("span",{className:"roll__label","aria-live":"polite",children:A?"ROLLING…":g})]})})}function cXA({roomId:e,meId:A,bankerId:t,players:i,className:n,hasBankRoll:g,gameState:o,gameplay:s,onChargeChange:a}){const I=o.gameMode==="cee-lo",c=I?100:10,[l,B]=E.useState(c),Q=l,[h,d]=E.useState(!1),[p,y]=E.useState(!1),m=MB(),S=(o.banker??(I?o.currentRollerId:void 0)??t)===A,{settled:k,myOpenMain:N,placeMainBet:G,cancelMainBet:M}=gx(e,A),[w,b]=E.useState(!1);E.useEffect(()=>{N&&w&&b(!1)},[N,w]),E.useEffect(()=>{if(!w||N)return;const fA=setTimeout(()=>b(!1),5e3);return()=>clearTimeout(fA)},[w,N]);const _=(s==null?void 0:s.handleRoll)??(()=>{}),K=!!(s!=null&&s.canRoll);s==null||s.lastRollerId;const J=(s==null?void 0:s.diceSettled)??!0,q=(o==null?void 0:o.betsLocked)??!1;o==null||o.roundSeq;const v=!!(o!=null&&o.bankRoll),U=v,[x,T]=E.useState(!1),z=E.useRef(q),Z=E.useRef(null);E.useEffect(()=>(z.current&&!q&&(T(!0),Z.current&&window.clearTimeout(Z.current),Z.current=window.setTimeout(()=>{T(!1),Z.current=null},3e3)),q&&Z.current&&(window.clearTimeout(Z.current),Z.current=null,T(!1)),z.current=q,()=>{Z.current&&window.clearTimeout(Z.current)}),[q]);const eA=E.useCallback(async fA=>{var qA;try{On()}catch{}if(h)return;const RA=Math.floor(fA??Q);if(RA<=0){m.info("Enter a bet amount.");return}if(!v){if(q||U){m.info("Bets are closed.");return}if((qA=o==null?void 0:o.spectators)!=null&&qA.includes(A)){m.info("Exit spectate to place a bet.");return}try{d(!0);const W=await G(RA);if(!(W!=null&&W.ok)){m.error((W==null?void 0:W.error)||"Bet rejected");return}b(!0)}catch(W){console.error("place_main_bet failed",W)}finally{d(!1)}}},[h,Q,g,q,U,o,G]),aA=E.useCallback(async()=>{try{On()}catch{}if(N)try{const fA=await M(N.id);fA.ok||m.error(fA.error||"Failed to cancel bet")}catch(fA){console.error(fA),m.error((fA==null?void 0:fA.message)??"Failed to cancel bet")}},[M,N,m]),pA=((o==null?void 0:o.spectators)??[]).includes(A),gA=h||pA||U||q||w,yA=S?"Banker":pA?"Spectating":N||w?"Bet Locked":U||q?"Bets Closed":"Main Bet";return C.jsxs("div",{className:["betpanel",n].filter(Boolean).join(" "),children:[C.jsxs("section",{className:"betpanel__section",children:[I&&C.jsxs("div",{className:"betpanel__ceelo-head",children:[C.jsx("span",{className:"betpanel__ceelo-status",children:yA}),!S&&C.jsx("span",{className:"betpanel__ceelo-amount",children:N?`ℤ${N.amount}`:`ℤ${l}`})]}),C.jsx("div",{className:"betpanel__row betpanel__row--roll",children:C.jsx(ydA,{disabled:!K||pA,busy:!J,onClick:_,onChargeChange:a,useImage:!1,className:"roll-wrapper--rect","data-testid":"roll-button"})}),!S&&C.jsx("div",{className:"betpanel__row",children:C.jsx(pdA,{onPlaceBet:eA,onCancelBet:aA,disabled:gA,showCancel:!!N&&!v,defaultValue:c,quickAmounts:I?[50,100,250,500,1e3,2500,5e3,1e4]:void 0,onAmountChange:B})})]}),p&&C.jsx(hdA,{meId:A,items:k,onClose:()=>y(!1)})]})}const lXA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let IY=(e=21)=>{let A="",t=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)A+=lXA[t[e]&63];return A};const DdA=E.createContext({});function BXA(e){const A=E.useRef(null);return A.current===null&&(A.current=e()),A.current}const Hz=typeof window<"u",EXA=Hz?E.useLayoutEffect:E.useEffect,Oz=E.createContext(null);function Pz(e,A){e.indexOf(A)===-1&&e.push(A)}function jz(e,A){const t=e.indexOf(A);t>-1&&e.splice(t,1)}const tQ=(e,A,t)=>t>A?A:t<e?e:t;let zz=()=>{};const iQ={},mdA=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function SdA(e){return typeof e=="object"&&e!==null}const wdA=e=>/^0[^.\s]+$/u.test(e);function Zz(e){let A;return()=>(A===void 0&&(A=e()),A)}const ec=e=>e,QXA=(e,A)=>t=>A(e(t)),PR=(...e)=>e.reduce(QXA),uN=(e,A,t)=>{const i=A-e;return i===0?1:(t-e)/i};class Wz{constructor(){this.subscriptions=[]}add(A){return Pz(this.subscriptions,A),()=>jz(this.subscriptions,A)}notify(A,t,i){const n=this.subscriptions.length;if(n)if(n===1)this.subscriptions[0](A,t,i);else for(let g=0;g<n;g++){const o=this.subscriptions[g];o&&o(A,t,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const lB=e=>e*1e3,BB=e=>e/1e3;function kdA(e,A){return A?e*(1e3/A):0}const MdA=(e,A,t)=>(((1-3*t+3*A)*e+(3*t-6*A))*e+3*A)*e,uXA=1e-7,dXA=12;function hXA(e,A,t,i,n){let g,o,s=0;do o=A+(t-A)/2,g=MdA(o,i,n)-e,g>0?t=o:A=o;while(Math.abs(g)>uXA&&++s<dXA);return o}function jR(e,A,t,i){if(e===A&&t===i)return ec;const n=g=>hXA(g,0,1,e,t);return g=>g===0||g===1?g:MdA(n(g),A,i)}const NdA=e=>A=>A<=.5?e(2*A)/2:(2-e(2*(1-A)))/2,RdA=e=>A=>1-e(1-A),GdA=jR(.33,1.53,.69,.99),Vz=RdA(GdA),bdA=NdA(Vz),UdA=e=>(e*=2)<1?.5*Vz(e):.5*(2-Math.pow(2,-10*(e-1))),Xz=e=>1-Math.sin(Math.acos(e)),vdA=RdA(Xz),KdA=NdA(Xz),pXA=jR(.42,0,1,1),fXA=jR(0,0,.58,1),FdA=jR(.42,0,.58,1),yXA=e=>Array.isArray(e)&&typeof e[0]!="number",_dA=e=>Array.isArray(e)&&typeof e[0]=="number",DXA={linear:ec,easeIn:pXA,easeInOut:FdA,easeOut:fXA,circIn:Xz,circInOut:KdA,circOut:vdA,backIn:Vz,backInOut:bdA,backOut:GdA,anticipate:UdA},mXA=e=>typeof e=="string",CeA=e=>{if(_dA(e)){zz(e.length===4);const[A,t,i,n]=e;return jR(A,t,i,n)}else if(mXA(e))return DXA[e];return e},Ob=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function SXA(e,A){let t=new Set,i=new Set,n=!1,g=!1;const o=new WeakSet;let s={delta:0,timestamp:0,isProcessing:!1};function a(I){o.has(I)&&(r.schedule(I),e()),I(s)}const r={schedule:(I,c=!1,l=!1)=>{const Q=l&&n?t:i;return c&&o.add(I),Q.has(I)||Q.add(I),I},cancel:I=>{i.delete(I),o.delete(I)},process:I=>{if(s=I,n){g=!0;return}n=!0,[t,i]=[i,t],t.forEach(a),t.clear(),n=!1,g&&(g=!1,r.process(I))}};return r}const wXA=40;function JdA(e,A){let t=!1,i=!0;const n={delta:0,timestamp:0,isProcessing:!1},g=()=>t=!0,o=Ob.reduce((m,D)=>(m[D]=SXA(g),m),{}),{setup:s,read:a,resolveKeyframes:r,preUpdate:I,update:c,preRender:l,render:B,postRender:Q}=o,h=()=>{const m=iQ.useManualTiming?n.timestamp:performance.now();t=!1,iQ.useManualTiming||(n.delta=i?1e3/60:Math.max(Math.min(m-n.timestamp,wXA),1)),n.timestamp=m,n.isProcessing=!0,s.process(n),a.process(n),r.process(n),I.process(n),c.process(n),l.process(n),B.process(n),Q.process(n),n.isProcessing=!1,t&&A&&(i=!1,e(h))},d=()=>{t=!0,i=!0,n.isProcessing||e(h)};return{schedule:Ob.reduce((m,D)=>{const S=o[D];return m[D]=(k,N=!1,G=!1)=>(t||d(),S.schedule(k,N,G)),m},{}),cancel:m=>{for(let D=0;D<Ob.length;D++)o[Ob[D]].cancel(m)},state:n,steps:o}}const{schedule:Eo,cancel:Bd,state:fa,steps:CY}=JdA(typeof requestAnimationFrame<"u"?requestAnimationFrame:ec,!0);let wK;function kXA(){wK=void 0}const gI={now:()=>(wK===void 0&&gI.set(fa.isProcessing||iQ.useManualTiming?fa.timestamp:performance.now()),wK),set:e=>{wK=e,queueMicrotask(kXA)}},LdA=e=>A=>typeof A=="string"&&A.startsWith(e),$z=LdA("--"),MXA=LdA("var(--"),AZ=e=>MXA(e)?NXA.test(e.split("/*")[0].trim()):!1,NXA=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Mw={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},dN={...Mw,transform:e=>tQ(0,1,e)},Pb={...Mw,default:1},lM=e=>Math.round(e*1e5)/1e5,eZ=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function RXA(e){return e==null}const GXA=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,tZ=(e,A)=>t=>!!(typeof t=="string"&&GXA.test(t)&&t.startsWith(e)||A&&!RXA(t)&&Object.prototype.hasOwnProperty.call(t,A)),xdA=(e,A,t)=>i=>{if(typeof i!="string")return i;const[n,g,o,s]=i.match(eZ);return{[e]:parseFloat(n),[A]:parseFloat(g),[t]:parseFloat(o),alpha:s!==void 0?parseFloat(s):1}},bXA=e=>tQ(0,255,e),cY={...Mw,transform:e=>Math.round(bXA(e))},Cp={test:tZ("rgb","red"),parse:xdA("red","green","blue"),transform:({red:e,green:A,blue:t,alpha:i=1})=>"rgba("+cY.transform(e)+", "+cY.transform(A)+", "+cY.transform(t)+", "+lM(dN.transform(i))+")"};function UXA(e){let A="",t="",i="",n="";return e.length>5?(A=e.substring(1,3),t=e.substring(3,5),i=e.substring(5,7),n=e.substring(7,9)):(A=e.substring(1,2),t=e.substring(2,3),i=e.substring(3,4),n=e.substring(4,5),A+=A,t+=t,i+=i,n+=n),{red:parseInt(A,16),green:parseInt(t,16),blue:parseInt(i,16),alpha:n?parseInt(n,16)/255:1}}const M3={test:tZ("#"),parse:UXA,transform:Cp.transform},zR=e=>({test:A=>typeof A=="string"&&A.endsWith(e)&&A.split(" ").length===1,parse:parseFloat,transform:A=>`${A}${e}`}),ZQ=zR("deg"),EB=zR("%"),Ji=zR("px"),vXA=zR("vh"),KXA=zR("vw"),ceA={...EB,parse:e=>EB.parse(e)/100,transform:e=>EB.transform(e*100)},em={test:tZ("hsl","hue"),parse:xdA("hue","saturation","lightness"),transform:({hue:e,saturation:A,lightness:t,alpha:i=1})=>"hsla("+Math.round(e)+", "+EB.transform(lM(A))+", "+EB.transform(lM(t))+", "+lM(dN.transform(i))+")"},ls={test:e=>Cp.test(e)||M3.test(e)||em.test(e),parse:e=>Cp.test(e)?Cp.parse(e):em.test(e)?em.parse(e):M3.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Cp.transform(e):em.transform(e),getAnimatableNone:e=>{const A=ls.parse(e);return A.alpha=0,ls.transform(A)}},FXA=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function _XA(e){var A,t;return isNaN(e)&&typeof e=="string"&&(((A=e.match(eZ))==null?void 0:A.length)||0)+(((t=e.match(FXA))==null?void 0:t.length)||0)>0}const TdA="number",qdA="color",JXA="var",LXA="var(",leA="${}",xXA=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function hN(e){const A=e.toString(),t=[],i={color:[],number:[],var:[]},n=[];let g=0;const s=A.replace(xXA,a=>(ls.test(a)?(i.color.push(g),n.push(qdA),t.push(ls.parse(a))):a.startsWith(LXA)?(i.var.push(g),n.push(JXA),t.push(a)):(i.number.push(g),n.push(TdA),t.push(parseFloat(a))),++g,leA)).split(leA);return{values:t,split:s,indexes:i,types:n}}function YdA(e){return hN(e).values}function HdA(e){const{split:A,types:t}=hN(e),i=A.length;return n=>{let g="";for(let o=0;o<i;o++)if(g+=A[o],n[o]!==void 0){const s=t[o];s===TdA?g+=lM(n[o]):s===qdA?g+=ls.transform(n[o]):g+=n[o]}return g}}const TXA=e=>typeof e=="number"?0:ls.test(e)?ls.getAnimatableNone(e):e;function qXA(e){const A=YdA(e);return HdA(e)(A.map(TXA))}const Ed={test:_XA,parse:YdA,createTransformer:HdA,getAnimatableNone:qXA};function lY(e,A,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?e+(A-e)*6*t:t<1/2?A:t<2/3?e+(A-e)*(2/3-t)*6:e}function YXA({hue:e,saturation:A,lightness:t,alpha:i}){e/=360,A/=100,t/=100;let n=0,g=0,o=0;if(!A)n=g=o=t;else{const s=t<.5?t*(1+A):t+A-t*A,a=2*t-s;n=lY(a,s,e+1/3),g=lY(a,s,e),o=lY(a,s,e-1/3)}return{red:Math.round(n*255),green:Math.round(g*255),blue:Math.round(o*255),alpha:i}}function c_(e,A){return t=>t>0?A:e}const wo=(e,A,t)=>e+(A-e)*t,BY=(e,A,t)=>{const i=e*e,n=t*(A*A-i)+i;return n<0?0:Math.sqrt(n)},HXA=[M3,Cp,em],OXA=e=>HXA.find(A=>A.test(e));function BeA(e){const A=OXA(e);if(!A)return!1;let t=A.parse(e);return A===em&&(t=YXA(t)),t}const EeA=(e,A)=>{const t=BeA(e),i=BeA(A);if(!t||!i)return c_(e,A);const n={...t};return g=>(n.red=BY(t.red,i.red,g),n.green=BY(t.green,i.green,g),n.blue=BY(t.blue,i.blue,g),n.alpha=wo(t.alpha,i.alpha,g),Cp.transform(n))},N3=new Set(["none","hidden"]);function PXA(e,A){return N3.has(e)?t=>t<=0?e:A:t=>t>=1?A:e}function jXA(e,A){return t=>wo(e,A,t)}function iZ(e){return typeof e=="number"?jXA:typeof e=="string"?AZ(e)?c_:ls.test(e)?EeA:WXA:Array.isArray(e)?OdA:typeof e=="object"?ls.test(e)?EeA:zXA:c_}function OdA(e,A){const t=[...e],i=t.length,n=e.map((g,o)=>iZ(g)(g,A[o]));return g=>{for(let o=0;o<i;o++)t[o]=n[o](g);return t}}function zXA(e,A){const t={...e,...A},i={};for(const n in t)e[n]!==void 0&&A[n]!==void 0&&(i[n]=iZ(e[n])(e[n],A[n]));return n=>{for(const g in i)t[g]=i[g](n);return t}}function ZXA(e,A){const t=[],i={color:0,var:0,number:0};for(let n=0;n<A.values.length;n++){const g=A.types[n],o=e.indexes[g][i[g]],s=e.values[o]??0;t[n]=s,i[g]++}return t}const WXA=(e,A)=>{const t=Ed.createTransformer(A),i=hN(e),n=hN(A);return i.indexes.var.length===n.indexes.var.length&&i.indexes.color.length===n.indexes.color.length&&i.indexes.number.length>=n.indexes.number.length?N3.has(e)&&!n.values.length||N3.has(A)&&!i.values.length?PXA(e,A):PR(OdA(ZXA(i,n),n.values),t):c_(e,A)};function PdA(e,A,t){return typeof e=="number"&&typeof A=="number"&&typeof t=="number"?wo(e,A,t):iZ(e)(e,A)}const VXA=e=>{const A=({timestamp:t})=>e(t);return{start:(t=!0)=>Eo.update(A,t),stop:()=>Bd(A),now:()=>fa.isProcessing?fa.timestamp:gI.now()}},jdA=(e,A,t=10)=>{let i="";const n=Math.max(Math.round(A/t),2);for(let g=0;g<n;g++)i+=Math.round(e(g/(n-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},l_=2e4;function nZ(e){let A=0;const t=50;let i=e.next(A);for(;!i.done&&A<l_;)A+=t,i=e.next(A);return A>=l_?1/0:A}function XXA(e,A=100,t){const i=t({...e,keyframes:[0,A]}),n=Math.min(nZ(i),l_);return{type:"keyframes",ease:g=>i.next(n*g).value/A,duration:BB(n)}}const $XA=5;function zdA(e,A,t){const i=Math.max(A-$XA,0);return kdA(t-e(i),A-i)}const _o={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},EY=.001;function A6A({duration:e=_o.duration,bounce:A=_o.bounce,velocity:t=_o.velocity,mass:i=_o.mass}){let n,g,o=1-A;o=tQ(_o.minDamping,_o.maxDamping,o),e=tQ(_o.minDuration,_o.maxDuration,BB(e)),o<1?(n=r=>{const I=r*o,c=I*e,l=I-t,B=R3(r,o),Q=Math.exp(-c);return EY-l/B*Q},g=r=>{const c=r*o*e,l=c*t+t,B=Math.pow(o,2)*Math.pow(r,2)*e,Q=Math.exp(-c),h=R3(Math.pow(r,2),o);return(-n(r)+EY>0?-1:1)*((l-B)*Q)/h}):(n=r=>{const I=Math.exp(-r*e),c=(r-t)*e+1;return-EY+I*c},g=r=>{const I=Math.exp(-r*e),c=(t-r)*(e*e);return I*c});const s=5/e,a=t6A(n,g,s);if(e=lB(e),isNaN(a))return{stiffness:_o.stiffness,damping:_o.damping,duration:e};{const r=Math.pow(a,2)*i;return{stiffness:r,damping:o*2*Math.sqrt(i*r),duration:e}}}const e6A=12;function t6A(e,A,t){let i=t;for(let n=1;n<e6A;n++)i=i-e(i)/A(i);return i}function R3(e,A){return e*Math.sqrt(1-A*A)}const i6A=["duration","bounce"],n6A=["stiffness","damping","mass"];function QeA(e,A){return A.some(t=>e[t]!==void 0)}function g6A(e){let A={velocity:_o.velocity,stiffness:_o.stiffness,damping:_o.damping,mass:_o.mass,isResolvedFromDuration:!1,...e};if(!QeA(e,n6A)&&QeA(e,i6A))if(e.visualDuration){const t=e.visualDuration,i=2*Math.PI/(t*1.2),n=i*i,g=2*tQ(.05,1,1-(e.bounce||0))*Math.sqrt(n);A={...A,mass:_o.mass,stiffness:n,damping:g}}else{const t=A6A(e);A={...A,...t,mass:_o.mass},A.isResolvedFromDuration=!0}return A}function B_(e=_o.visualDuration,A=_o.bounce){const t=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:A}:e;let{restSpeed:i,restDelta:n}=t;const g=t.keyframes[0],o=t.keyframes[t.keyframes.length-1],s={done:!1,value:g},{stiffness:a,damping:r,mass:I,duration:c,velocity:l,isResolvedFromDuration:B}=g6A({...t,velocity:-BB(t.velocity||0)}),Q=l||0,h=r/(2*Math.sqrt(a*I)),d=o-g,p=BB(Math.sqrt(a/I)),y=Math.abs(d)<5;i||(i=y?_o.restSpeed.granular:_o.restSpeed.default),n||(n=y?_o.restDelta.granular:_o.restDelta.default);let m;if(h<1){const S=R3(p,h);m=k=>{const N=Math.exp(-h*p*k);return o-N*((Q+h*p*d)/S*Math.sin(S*k)+d*Math.cos(S*k))}}else if(h===1)m=S=>o-Math.exp(-p*S)*(d+(Q+p*d)*S);else{const S=p*Math.sqrt(h*h-1);m=k=>{const N=Math.exp(-h*p*k),G=Math.min(S*k,300);return o-N*((Q+h*p*d)*Math.sinh(G)+S*d*Math.cosh(G))/S}}const D={calculatedDuration:B&&c||null,next:S=>{const k=m(S);if(B)s.done=S>=c;else{let N=S===0?Q:0;h<1&&(N=S===0?lB(Q):zdA(m,S,k));const G=Math.abs(N)<=i,M=Math.abs(o-k)<=n;s.done=G&&M}return s.value=s.done?o:k,s},toString:()=>{const S=Math.min(nZ(D),l_),k=jdA(N=>D.next(S*N).value,S,30);return S+"ms "+k},toTransition:()=>{}};return D}B_.applyToOptions=e=>{const A=XXA(e,100,B_);return e.ease=A.ease,e.duration=lB(A.duration),e.type="keyframes",e};function G3({keyframes:e,velocity:A=0,power:t=.8,timeConstant:i=325,bounceDamping:n=10,bounceStiffness:g=500,modifyTarget:o,min:s,max:a,restDelta:r=.5,restSpeed:I}){const c=e[0],l={done:!1,value:c},B=G=>s!==void 0&&G<s||a!==void 0&&G>a,Q=G=>s===void 0?a:a===void 0||Math.abs(s-G)<Math.abs(a-G)?s:a;let h=t*A;const d=c+h,p=o===void 0?d:o(d);p!==d&&(h=p-c);const y=G=>-h*Math.exp(-G/i),m=G=>p+y(G),D=G=>{const M=y(G),w=m(G);l.done=Math.abs(M)<=r,l.value=l.done?p:w};let S,k;const N=G=>{B(l.value)&&(S=G,k=B_({keyframes:[l.value,Q(l.value)],velocity:zdA(m,G,l.value),damping:n,stiffness:g,restDelta:r,restSpeed:I}))};return N(0),{calculatedDuration:null,next:G=>{let M=!1;return!k&&S===void 0&&(M=!0,D(G),N(G)),S!==void 0&&G>=S?k.next(G-S):(!M&&D(G),l)}}}function o6A(e,A,t){const i=[],n=t||iQ.mix||PdA,g=e.length-1;for(let o=0;o<g;o++){let s=n(e[o],e[o+1]);if(A){const a=Array.isArray(A)?A[o]||ec:A;s=PR(a,s)}i.push(s)}return i}function s6A(e,A,{clamp:t=!0,ease:i,mixer:n}={}){const g=e.length;if(zz(g===A.length),g===1)return()=>A[0];if(g===2&&A[0]===A[1])return()=>A[1];const o=e[0]===e[1];e[0]>e[g-1]&&(e=[...e].reverse(),A=[...A].reverse());const s=o6A(A,i,n),a=s.length,r=I=>{if(o&&I<e[0])return A[0];let c=0;if(a>1)for(;c<e.length-2&&!(I<e[c+1]);c++);const l=uN(e[c],e[c+1],I);return s[c](l)};return t?I=>r(tQ(e[0],e[g-1],I)):r}function a6A(e,A){const t=e[e.length-1];for(let i=1;i<=A;i++){const n=uN(0,A,i);e.push(wo(t,1,n))}}function r6A(e){const A=[0];return a6A(A,e.length-1),A}function I6A(e,A){return e.map(t=>t*A)}function C6A(e,A){return e.map(()=>A||FdA).splice(0,e.length-1)}function BM({duration:e=300,keyframes:A,times:t,ease:i="easeInOut"}){const n=yXA(i)?i.map(CeA):CeA(i),g={done:!1,value:A[0]},o=I6A(t&&t.length===A.length?t:r6A(A),e),s=s6A(o,A,{ease:Array.isArray(n)?n:C6A(A,n)});return{calculatedDuration:e,next:a=>(g.value=s(a),g.done=a>=e,g)}}const c6A=e=>e!==null;function gZ(e,{repeat:A,repeatType:t="loop"},i,n=1){const g=e.filter(c6A),s=n<0||A&&t!=="loop"&&A%2===1?0:g.length-1;return!s||i===void 0?g[s]:i}const l6A={decay:G3,inertia:G3,tween:BM,keyframes:BM,spring:B_};function ZdA(e){typeof e.type=="string"&&(e.type=l6A[e.type])}class oZ{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(A=>{this.resolve=A})}notifyFinished(){this.resolve()}then(A,t){return this.finished.then(A,t)}}const B6A=e=>e/100;class sZ extends oZ{constructor(A){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var i,n;const{motionValue:t}=this.options;t&&t.updatedAt!==gI.now()&&this.tick(gI.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(n=(i=this.options).onStop)==null||n.call(i))},this.options=A,this.initAnimation(),this.play(),A.autoplay===!1&&this.pause()}initAnimation(){const{options:A}=this;ZdA(A);const{type:t=BM,repeat:i=0,repeatDelay:n=0,repeatType:g,velocity:o=0}=A;let{keyframes:s}=A;const a=t||BM;a!==BM&&typeof s[0]!="number"&&(this.mixKeyframes=PR(B6A,PdA(s[0],s[1])),s=[0,100]);const r=a({...A,keyframes:s});g==="mirror"&&(this.mirroredGenerator=a({...A,keyframes:[...s].reverse(),velocity:-o})),r.calculatedDuration===null&&(r.calculatedDuration=nZ(r));const{calculatedDuration:I}=r;this.calculatedDuration=I,this.resolvedDuration=I+n,this.totalDuration=this.resolvedDuration*(i+1)-n,this.generator=r}updateTime(A){const t=Math.round(A-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=t}tick(A,t=!1){const{generator:i,totalDuration:n,mixKeyframes:g,mirroredGenerator:o,resolvedDuration:s,calculatedDuration:a}=this;if(this.startTime===null)return i.next(0);const{delay:r=0,keyframes:I,repeat:c,repeatType:l,repeatDelay:B,type:Q,onUpdate:h,finalKeyframe:d}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,A):this.speed<0&&(this.startTime=Math.min(A-n/this.speed,this.startTime)),t?this.currentTime=A:this.updateTime(A);const p=this.currentTime-r*(this.playbackSpeed>=0?1:-1),y=this.playbackSpeed>=0?p<0:p>n;this.currentTime=Math.max(p,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let m=this.currentTime,D=i;if(c){const G=Math.min(this.currentTime,n)/s;let M=Math.floor(G),w=G%1;!w&&G>=1&&(w=1),w===1&&M--,M=Math.min(M,c+1),!!(M%2)&&(l==="reverse"?(w=1-w,B&&(w-=B/s)):l==="mirror"&&(D=o)),m=tQ(0,1,w)*s}const S=y?{done:!1,value:I[0]}:D.next(m);g&&(S.value=g(S.value));let{done:k}=S;!y&&a!==null&&(k=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const N=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&k);return N&&Q!==G3&&(S.value=gZ(I,this.options,d,this.speed)),h&&h(S.value),N&&this.finish(),S}then(A,t){return this.finished.then(A,t)}get duration(){return BB(this.calculatedDuration)}get time(){return BB(this.currentTime)}set time(A){var t;A=lB(A),this.currentTime=A,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=A:this.driver&&(this.startTime=this.driver.now()-A/this.playbackSpeed),(t=this.driver)==null||t.start(!1)}get speed(){return this.playbackSpeed}set speed(A){this.updateTime(gI.now());const t=this.playbackSpeed!==A;this.playbackSpeed=A,t&&(this.time=BB(this.currentTime))}play(){var n,g;if(this.isStopped)return;const{driver:A=VXA,startTime:t}=this.options;this.driver||(this.driver=A(o=>this.tick(o))),(g=(n=this.options).onPlay)==null||g.call(n);const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=t??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(gI.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var A,t;this.notifyFinished(),this.teardown(),this.state="finished",(t=(A=this.options).onComplete)==null||t.call(A)}cancel(){var A,t;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(t=(A=this.options).onCancel)==null||t.call(A)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(A){return this.startTime=0,this.tick(A,!0)}attachTimeline(A){var t;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(t=this.driver)==null||t.stop(),A.observe(this)}}function E6A(e){for(let A=1;A<e.length;A++)e[A]??(e[A]=e[A-1])}const cp=e=>e*180/Math.PI,b3=e=>{const A=cp(Math.atan2(e[1],e[0]));return U3(A)},Q6A={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:b3,rotateZ:b3,skewX:e=>cp(Math.atan(e[1])),skewY:e=>cp(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},U3=e=>(e=e%360,e<0&&(e+=360),e),ueA=b3,deA=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),heA=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),u6A={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:deA,scaleY:heA,scale:e=>(deA(e)+heA(e))/2,rotateX:e=>U3(cp(Math.atan2(e[6],e[5]))),rotateY:e=>U3(cp(Math.atan2(-e[2],e[0]))),rotateZ:ueA,rotate:ueA,skewX:e=>cp(Math.atan(e[4])),skewY:e=>cp(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function v3(e){return e.includes("scale")?1:0}function K3(e,A){if(!e||e==="none")return v3(A);const t=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,n;if(t)i=u6A,n=t;else{const s=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=Q6A,n=s}if(!n)return v3(A);const g=i[A],o=n[1].split(",").map(h6A);return typeof g=="function"?g(o):o[g]}const d6A=(e,A)=>{const{transform:t="none"}=getComputedStyle(e);return K3(t,A)};function h6A(e){return parseFloat(e.trim())}const Nw=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Rw=new Set(Nw),peA=e=>e===Mw||e===Ji,p6A=new Set(["x","y","z"]),f6A=Nw.filter(e=>!p6A.has(e));function y6A(e){const A=[];return f6A.forEach(t=>{const i=e.getValue(t);i!==void 0&&(A.push([t,i.get()]),i.set(t.startsWith("scale")?1:0))}),A}const Lp={width:({x:e},{paddingLeft:A="0",paddingRight:t="0"})=>e.max-e.min-parseFloat(A)-parseFloat(t),height:({y:e},{paddingTop:A="0",paddingBottom:t="0"})=>e.max-e.min-parseFloat(A)-parseFloat(t),top:(e,{top:A})=>parseFloat(A),left:(e,{left:A})=>parseFloat(A),bottom:({y:e},{top:A})=>parseFloat(A)+(e.max-e.min),right:({x:e},{left:A})=>parseFloat(A)+(e.max-e.min),x:(e,{transform:A})=>K3(A,"x"),y:(e,{transform:A})=>K3(A,"y")};Lp.translateX=Lp.x;Lp.translateY=Lp.y;const xp=new Set;let F3=!1,_3=!1,J3=!1;function WdA(){if(_3){const e=Array.from(xp).filter(i=>i.needsMeasurement),A=new Set(e.map(i=>i.element)),t=new Map;A.forEach(i=>{const n=y6A(i);n.length&&(t.set(i,n),i.render())}),e.forEach(i=>i.measureInitialState()),A.forEach(i=>{i.render();const n=t.get(i);n&&n.forEach(([g,o])=>{var s;(s=i.getValue(g))==null||s.set(o)})}),e.forEach(i=>i.measureEndState()),e.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}_3=!1,F3=!1,xp.forEach(e=>e.complete(J3)),xp.clear()}function VdA(){xp.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(_3=!0)})}function D6A(){J3=!0,VdA(),WdA(),J3=!1}class aZ{constructor(A,t,i,n,g,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...A],this.onComplete=t,this.name=i,this.motionValue=n,this.element=g,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(xp.add(this),F3||(F3=!0,Eo.read(VdA),Eo.resolveKeyframes(WdA))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:A,name:t,element:i,motionValue:n}=this;if(A[0]===null){const g=n==null?void 0:n.get(),o=A[A.length-1];if(g!==void 0)A[0]=g;else if(i&&t){const s=i.readValue(t,o);s!=null&&(A[0]=s)}A[0]===void 0&&(A[0]=o),n&&g===void 0&&n.set(A[0])}E6A(A)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(A=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,A),xp.delete(this)}cancel(){this.state==="scheduled"&&(xp.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const m6A=e=>e.startsWith("--");function S6A(e,A,t){m6A(A)?e.style.setProperty(A,t):e.style[A]=t}const w6A=Zz(()=>window.ScrollTimeline!==void 0),k6A={};function M6A(e,A){const t=Zz(e);return()=>k6A[A]??t()}const XdA=M6A(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),fk=([e,A,t,i])=>`cubic-bezier(${e}, ${A}, ${t}, ${i})`,feA={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:fk([0,.65,.55,1]),circOut:fk([.55,0,1,.45]),backIn:fk([.31,.01,.66,-.59]),backOut:fk([.33,1.53,.69,.99])};function $dA(e,A){if(e)return typeof e=="function"?XdA()?jdA(e,A):"ease-out":_dA(e)?fk(e):Array.isArray(e)?e.map(t=>$dA(t,A)||feA.easeOut):feA[e]}function N6A(e,A,t,{delay:i=0,duration:n=300,repeat:g=0,repeatType:o="loop",ease:s="easeOut",times:a}={},r=void 0){const I={[A]:t};a&&(I.offset=a);const c=$dA(s,n);Array.isArray(c)&&(I.easing=c);const l={delay:i,duration:n,easing:Array.isArray(c)?"linear":c,fill:"both",iterations:g+1,direction:o==="reverse"?"alternate":"normal"};return r&&(l.pseudoElement=r),e.animate(I,l)}function AhA(e){return typeof e=="function"&&"applyToOptions"in e}function R6A({type:e,...A}){return AhA(e)&&XdA()?e.applyToOptions(A):(A.duration??(A.duration=300),A.ease??(A.ease="easeOut"),A)}class G6A extends oZ{constructor(A){if(super(),this.finishedTime=null,this.isStopped=!1,!A)return;const{element:t,name:i,keyframes:n,pseudoElement:g,allowFlatten:o=!1,finalKeyframe:s,onComplete:a}=A;this.isPseudoElement=!!g,this.allowFlatten=o,this.options=A,zz(typeof A.type!="string");const r=R6A(A);this.animation=N6A(t,i,n,r,g),r.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!g){const I=gZ(n,this.options,s,this.speed);this.updateMotionValue?this.updateMotionValue(I):S6A(t,i,I),this.animation.cancel()}a==null||a(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var A,t;(t=(A=this.animation).finish)==null||t.call(A)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:A}=this;A==="idle"||A==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var A,t;this.isPseudoElement||(t=(A=this.animation).commitStyles)==null||t.call(A)}get duration(){var t,i;const A=((i=(t=this.animation.effect)==null?void 0:t.getComputedTiming)==null?void 0:i.call(t).duration)||0;return BB(Number(A))}get time(){return BB(Number(this.animation.currentTime)||0)}set time(A){this.finishedTime=null,this.animation.currentTime=lB(A)}get speed(){return this.animation.playbackRate}set speed(A){A<0&&(this.finishedTime=null),this.animation.playbackRate=A}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(A){this.animation.startTime=A}attachTimeline({timeline:A,observe:t}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,A&&w6A()?(this.animation.timeline=A,ec):t(this)}}const ehA={anticipate:UdA,backInOut:bdA,circInOut:KdA};function b6A(e){return e in ehA}function U6A(e){typeof e.ease=="string"&&b6A(e.ease)&&(e.ease=ehA[e.ease])}const yeA=10;class v6A extends G6A{constructor(A){U6A(A),ZdA(A),super(A),A.startTime&&(this.startTime=A.startTime),this.options=A}updateMotionValue(A){const{motionValue:t,onUpdate:i,onComplete:n,element:g,...o}=this.options;if(!t)return;if(A!==void 0){t.set(A);return}const s=new sZ({...o,autoplay:!1}),a=lB(this.finishedTime??this.time);t.setWithVelocity(s.sample(a-yeA).value,s.sample(a).value,yeA),s.stop()}}const DeA=(e,A)=>A==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(Ed.test(e)||e==="0")&&!e.startsWith("url("));function K6A(e){const A=e[0];if(e.length===1)return!0;for(let t=0;t<e.length;t++)if(e[t]!==A)return!0}function F6A(e,A,t,i){const n=e[0];if(n===null)return!1;if(A==="display"||A==="visibility")return!0;const g=e[e.length-1],o=DeA(n,A),s=DeA(g,A);return!o||!s?!1:K6A(e)||(t==="spring"||AhA(t))&&i}function L3(e){e.duration=0,e.type}const _6A=new Set(["opacity","clipPath","filter","transform"]),J6A=Zz(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function L6A(e){var I;const{motionValue:A,name:t,repeatDelay:i,repeatType:n,damping:g,type:o}=e;if(!(((I=A==null?void 0:A.owner)==null?void 0:I.current)instanceof HTMLElement))return!1;const{onUpdate:a,transformTemplate:r}=A.owner.getProps();return J6A()&&t&&_6A.has(t)&&(t!=="transform"||!r)&&!a&&!i&&n!=="mirror"&&g!==0&&o!=="inertia"}const x6A=40;class T6A extends oZ{constructor({autoplay:A=!0,delay:t=0,type:i="keyframes",repeat:n=0,repeatDelay:g=0,repeatType:o="loop",keyframes:s,name:a,motionValue:r,element:I,...c}){var Q;super(),this.stop=()=>{var h,d;this._animation&&(this._animation.stop(),(h=this.stopTimeline)==null||h.call(this)),(d=this.keyframeResolver)==null||d.cancel()},this.createdAt=gI.now();const l={autoplay:A,delay:t,type:i,repeat:n,repeatDelay:g,repeatType:o,name:a,motionValue:r,element:I,...c},B=(I==null?void 0:I.KeyframeResolver)||aZ;this.keyframeResolver=new B(s,(h,d,p)=>this.onKeyframesResolved(h,d,l,!p),a,r,I),(Q=this.keyframeResolver)==null||Q.scheduleResolve()}onKeyframesResolved(A,t,i,n){this.keyframeResolver=void 0;const{name:g,type:o,velocity:s,delay:a,isHandoff:r,onUpdate:I}=i;this.resolvedAt=gI.now(),F6A(A,g,o,s)||((iQ.instantAnimations||!a)&&(I==null||I(gZ(A,i,t))),A[0]=A[A.length-1],L3(i),i.repeat=0);const l={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>x6A?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:t,...i,keyframes:A},B=!r&&L6A(l)?new v6A({...l,element:l.motionValue.owner.current}):new sZ(l);B.finished.then(()=>this.notifyFinished()).catch(ec),this.pendingTimeline&&(this.stopTimeline=B.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=B}get finished(){return this._animation?this.animation.finished:this._finished}then(A,t){return this.finished.finally(A).then(()=>{})}get animation(){var A;return this._animation||((A=this.keyframeResolver)==null||A.resume(),D6A()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(A){this.animation.time=A}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(A){this.animation.speed=A}get startTime(){return this.animation.startTime}attachTimeline(A){return this._animation?this.stopTimeline=this.animation.attachTimeline(A):this.pendingTimeline=A,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var A;this._animation&&this.animation.cancel(),(A=this.keyframeResolver)==null||A.cancel()}}const q6A=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Y6A(e){const A=q6A.exec(e);if(!A)return[,];const[,t,i,n]=A;return[`--${t??i}`,n]}function thA(e,A,t=1){const[i,n]=Y6A(e);if(!i)return;const g=window.getComputedStyle(A).getPropertyValue(i);if(g){const o=g.trim();return mdA(o)?parseFloat(o):o}return AZ(n)?thA(n,A,t+1):n}function rZ(e,A){return(e==null?void 0:e[A])??(e==null?void 0:e.default)??e}const ihA=new Set(["width","height","top","left","right","bottom",...Nw]),H6A={test:e=>e==="auto",parse:e=>e},nhA=e=>A=>A.test(e),ghA=[Mw,Ji,EB,ZQ,KXA,vXA,H6A],meA=e=>ghA.find(nhA(e));function O6A(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||wdA(e):!0}const P6A=new Set(["brightness","contrast","saturate","opacity"]);function j6A(e){const[A,t]=e.slice(0,-1).split("(");if(A==="drop-shadow")return e;const[i]=t.match(eZ)||[];if(!i)return e;const n=t.replace(i,"");let g=P6A.has(A)?1:0;return i!==t&&(g*=100),A+"("+g+n+")"}const z6A=/\b([a-z-]*)\(.*?\)/gu,x3={...Ed,getAnimatableNone:e=>{const A=e.match(z6A);return A?A.map(j6A).join(" "):e}},SeA={...Mw,transform:Math.round},Z6A={rotate:ZQ,rotateX:ZQ,rotateY:ZQ,rotateZ:ZQ,scale:Pb,scaleX:Pb,scaleY:Pb,scaleZ:Pb,skew:ZQ,skewX:ZQ,skewY:ZQ,distance:Ji,translateX:Ji,translateY:Ji,translateZ:Ji,x:Ji,y:Ji,z:Ji,perspective:Ji,transformPerspective:Ji,opacity:dN,originX:ceA,originY:ceA,originZ:Ji},IZ={borderWidth:Ji,borderTopWidth:Ji,borderRightWidth:Ji,borderBottomWidth:Ji,borderLeftWidth:Ji,borderRadius:Ji,radius:Ji,borderTopLeftRadius:Ji,borderTopRightRadius:Ji,borderBottomRightRadius:Ji,borderBottomLeftRadius:Ji,width:Ji,maxWidth:Ji,height:Ji,maxHeight:Ji,top:Ji,right:Ji,bottom:Ji,left:Ji,padding:Ji,paddingTop:Ji,paddingRight:Ji,paddingBottom:Ji,paddingLeft:Ji,margin:Ji,marginTop:Ji,marginRight:Ji,marginBottom:Ji,marginLeft:Ji,backgroundPositionX:Ji,backgroundPositionY:Ji,...Z6A,zIndex:SeA,fillOpacity:dN,strokeOpacity:dN,numOctaves:SeA},W6A={...IZ,color:ls,backgroundColor:ls,outlineColor:ls,fill:ls,stroke:ls,borderColor:ls,borderTopColor:ls,borderRightColor:ls,borderBottomColor:ls,borderLeftColor:ls,filter:x3,WebkitFilter:x3},ohA=e=>W6A[e];function shA(e,A){let t=ohA(e);return t!==x3&&(t=Ed),t.getAnimatableNone?t.getAnimatableNone(A):void 0}const V6A=new Set(["auto","none","0"]);function X6A(e,A,t){let i=0,n;for(;i<e.length&&!n;){const g=e[i];typeof g=="string"&&!V6A.has(g)&&hN(g).values.length&&(n=e[i]),i++}if(n&&t)for(const g of A)e[g]=shA(t,n)}class $6A extends aZ{constructor(A,t,i,n,g){super(A,t,i,n,g,!0)}readKeyframes(){const{unresolvedKeyframes:A,element:t,name:i}=this;if(!t||!t.current)return;super.readKeyframes();for(let a=0;a<A.length;a++){let r=A[a];if(typeof r=="string"&&(r=r.trim(),AZ(r))){const I=thA(r,t.current);I!==void 0&&(A[a]=I),a===A.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!ihA.has(i)||A.length!==2)return;const[n,g]=A,o=meA(n),s=meA(g);if(o!==s)if(peA(o)&&peA(s))for(let a=0;a<A.length;a++){const r=A[a];typeof r=="string"&&(A[a]=parseFloat(r))}else Lp[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:A,name:t}=this,i=[];for(let n=0;n<A.length;n++)(A[n]===null||O6A(A[n]))&&i.push(n);i.length&&X6A(A,i,t)}measureInitialState(){const{element:A,unresolvedKeyframes:t,name:i}=this;if(!A||!A.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Lp[i](A.measureViewportBox(),window.getComputedStyle(A.current)),t[0]=this.measuredOrigin;const n=t[t.length-1];n!==void 0&&A.getValue(i,n).jump(n,!1)}measureEndState(){var s;const{element:A,name:t,unresolvedKeyframes:i}=this;if(!A||!A.current)return;const n=A.getValue(t);n&&n.jump(this.measuredOrigin,!1);const g=i.length-1,o=i[g];i[g]=Lp[t](A.measureViewportBox(),window.getComputedStyle(A.current)),o!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=o),(s=this.removedTransforms)!=null&&s.length&&this.removedTransforms.forEach(([a,r])=>{A.getValue(a).set(r)}),this.resolveNoneKeyframes()}}function A7A(e,A,t){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let i=document;const n=(t==null?void 0:t[e])??i.querySelectorAll(e);return n?Array.from(n):[]}return Array.from(e)}const ahA=(e,A)=>A&&typeof e=="number"?A.transform(e):e;function e7A(e){return SdA(e)&&"offsetHeight"in e}const weA=30,t7A=e=>!isNaN(parseFloat(e));class i7A{constructor(A,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=i=>{var g;const n=gI.now();if(this.updatedAt!==n&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((g=this.events.change)==null||g.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(A),this.owner=t.owner}setCurrent(A){this.current=A,this.updatedAt=gI.now(),this.canTrackVelocity===null&&A!==void 0&&(this.canTrackVelocity=t7A(this.current))}setPrevFrameValue(A=this.current){this.prevFrameValue=A,this.prevUpdatedAt=this.updatedAt}onChange(A){return this.on("change",A)}on(A,t){this.events[A]||(this.events[A]=new Wz);const i=this.events[A].add(t);return A==="change"?()=>{i(),Eo.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const A in this.events)this.events[A].clear()}attach(A,t){this.passiveEffect=A,this.stopPassiveEffect=t}set(A){this.passiveEffect?this.passiveEffect(A,this.updateAndNotify):this.updateAndNotify(A)}setWithVelocity(A,t,i){this.set(t),this.prev=void 0,this.prevFrameValue=A,this.prevUpdatedAt=this.updatedAt-i}jump(A,t=!0){this.updateAndNotify(A),this.prev=A,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var A;(A=this.events.change)==null||A.notify(this.current)}addDependent(A){this.dependents||(this.dependents=new Set),this.dependents.add(A)}removeDependent(A){this.dependents&&this.dependents.delete(A)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const A=gI.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||A-this.updatedAt>weA)return 0;const t=Math.min(this.updatedAt-this.prevUpdatedAt,weA);return kdA(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(A){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=A(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var A,t;(A=this.dependents)==null||A.clear(),(t=this.events.destroy)==null||t.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function vS(e,A){return new i7A(e,A)}const{schedule:CZ}=JdA(queueMicrotask,!1),Rc={x:!1,y:!1};function rhA(){return Rc.x||Rc.y}function n7A(e){return e==="x"||e==="y"?Rc[e]?null:(Rc[e]=!0,()=>{Rc[e]=!1}):Rc.x||Rc.y?null:(Rc.x=Rc.y=!0,()=>{Rc.x=Rc.y=!1})}function IhA(e,A){const t=A7A(e),i=new AbortController,n={passive:!0,...A,signal:i.signal};return[t,n,()=>i.abort()]}function keA(e){return!(e.pointerType==="touch"||rhA())}function g7A(e,A,t={}){const[i,n,g]=IhA(e,t),o=s=>{if(!keA(s))return;const{target:a}=s,r=A(a,s);if(typeof r!="function"||!a)return;const I=c=>{keA(c)&&(r(c),a.removeEventListener("pointerleave",I))};a.addEventListener("pointerleave",I,n)};return i.forEach(s=>{s.addEventListener("pointerenter",o,n)}),g}const ChA=(e,A)=>A?e===A?!0:ChA(e,A.parentElement):!1,cZ=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,o7A=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function s7A(e){return o7A.has(e.tagName)||e.tabIndex!==-1}const kK=new WeakSet;function MeA(e){return A=>{A.key==="Enter"&&e(A)}}function QY(e,A){e.dispatchEvent(new PointerEvent("pointer"+A,{isPrimary:!0,bubbles:!0}))}const a7A=(e,A)=>{const t=e.currentTarget;if(!t)return;const i=MeA(()=>{if(kK.has(t))return;QY(t,"down");const n=MeA(()=>{QY(t,"up")}),g=()=>QY(t,"cancel");t.addEventListener("keyup",n,A),t.addEventListener("blur",g,A)});t.addEventListener("keydown",i,A),t.addEventListener("blur",()=>t.removeEventListener("keydown",i),A)};function NeA(e){return cZ(e)&&!rhA()}function r7A(e,A,t={}){const[i,n,g]=IhA(e,t),o=s=>{const a=s.currentTarget;if(!NeA(s))return;kK.add(a);const r=A(a,s),I=(B,Q)=>{window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",l),kK.has(a)&&kK.delete(a),NeA(B)&&typeof r=="function"&&r(B,{success:Q})},c=B=>{I(B,a===window||a===document||t.useGlobalTarget||ChA(a,B.target))},l=B=>{I(B,!1)};window.addEventListener("pointerup",c,n),window.addEventListener("pointercancel",l,n)};return i.forEach(s=>{(t.useGlobalTarget?window:s).addEventListener("pointerdown",o,n),e7A(s)&&(s.addEventListener("focus",r=>a7A(r,n)),!s7A(s)&&!s.hasAttribute("tabindex")&&(s.tabIndex=0))}),g}function chA(e){return SdA(e)&&"ownerSVGElement"in e}function I7A(e){return chA(e)&&e.tagName==="svg"}const $a=e=>!!(e&&e.getVelocity),C7A=[...ghA,ls,Ed],c7A=e=>C7A.find(nhA(e)),lhA=E.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function l7A(e=!0){const A=E.useContext(Oz);if(A===null)return[!0,null];const{isPresent:t,onExitComplete:i,register:n}=A,g=E.useId();E.useEffect(()=>{if(e)return n(g)},[e]);const o=E.useCallback(()=>e&&i&&i(g),[g,i,e]);return!t&&i?[!1,o]:[!0]}const BhA=E.createContext({strict:!1}),ReA={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},KS={};for(const e in ReA)KS[e]={isEnabled:A=>ReA[e].some(t=>!!A[t])};function B7A(e){for(const A in e)KS[A]={...KS[A],...e[A]}}const E7A=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function E_(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||E7A.has(e)}let EhA=e=>!E_(e);function Q7A(e){typeof e=="function"&&(EhA=A=>A.startsWith("on")?!E_(A):e(A))}try{Q7A(require("@emotion/is-prop-valid").default)}catch{}function u7A(e,A,t){const i={};for(const n in e)n==="values"&&typeof e.values=="object"||(EhA(n)||t===!0&&E_(n)||!A&&!E_(n)||e.draggable&&n.startsWith("onDrag"))&&(i[n]=e[n]);return i}const ox=E.createContext({});function sx(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function pN(e){return typeof e=="string"||Array.isArray(e)}const lZ=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],BZ=["initial",...lZ];function ax(e){return sx(e.animate)||BZ.some(A=>pN(e[A]))}function QhA(e){return!!(ax(e)||e.variants)}function d7A(e,A){if(ax(e)){const{initial:t,animate:i}=e;return{initial:t===!1||pN(t)?t:void 0,animate:pN(i)?i:void 0}}return e.inherit!==!1?A:{}}function h7A(e){const{initial:A,animate:t}=d7A(e,E.useContext(ox));return E.useMemo(()=>({initial:A,animate:t}),[GeA(A),GeA(t)])}function GeA(e){return Array.isArray(e)?e.join(" "):e}const fN={};function p7A(e){for(const A in e)fN[A]=e[A],$z(A)&&(fN[A].isCSSVariable=!0)}function uhA(e,{layout:A,layoutId:t}){return Rw.has(e)||e.startsWith("origin")||(A||t!==void 0)&&(!!fN[e]||e==="opacity")}const f7A={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},y7A=Nw.length;function D7A(e,A,t){let i="",n=!0;for(let g=0;g<y7A;g++){const o=Nw[g],s=e[o];if(s===void 0)continue;let a=!0;if(typeof s=="number"?a=s===(o.startsWith("scale")?1:0):a=parseFloat(s)===0,!a||t){const r=ahA(s,IZ[o]);if(!a){n=!1;const I=f7A[o]||o;i+=`${I}(${r}) `}t&&(A[o]=r)}}return i=i.trim(),t?i=t(A,n?"":i):n&&(i="none"),i}function EZ(e,A,t){const{style:i,vars:n,transformOrigin:g}=e;let o=!1,s=!1;for(const a in A){const r=A[a];if(Rw.has(a)){o=!0;continue}else if($z(a)){n[a]=r;continue}else{const I=ahA(r,IZ[a]);a.startsWith("origin")?(s=!0,g[a]=I):i[a]=I}}if(A.transform||(o||t?i.transform=D7A(A,e.transform,t):i.transform&&(i.transform="none")),s){const{originX:a="50%",originY:r="50%",originZ:I=0}=g;i.transformOrigin=`${a} ${r} ${I}`}}const QZ=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function dhA(e,A,t){for(const i in A)!$a(A[i])&&!uhA(i,t)&&(e[i]=A[i])}function m7A({transformTemplate:e},A){return E.useMemo(()=>{const t=QZ();return EZ(t,A,e),Object.assign({},t.vars,t.style)},[A])}function S7A(e,A){const t=e.style||{},i={};return dhA(i,t,e),Object.assign(i,m7A(e,A)),i}function w7A(e,A){const t={},i=S7A(e,A);return e.drag&&e.dragListener!==!1&&(t.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(t.tabIndex=0),t.style=i,t}const k7A={offset:"stroke-dashoffset",array:"stroke-dasharray"},M7A={offset:"strokeDashoffset",array:"strokeDasharray"};function N7A(e,A,t=1,i=0,n=!0){e.pathLength=1;const g=n?k7A:M7A;e[g.offset]=Ji.transform(-i);const o=Ji.transform(A),s=Ji.transform(t);e[g.array]=`${o} ${s}`}function hhA(e,{attrX:A,attrY:t,attrScale:i,pathLength:n,pathSpacing:g=1,pathOffset:o=0,...s},a,r,I){if(EZ(e,s,r),a){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:c,style:l}=e;c.transform&&(l.transform=c.transform,delete c.transform),(l.transform||c.transformOrigin)&&(l.transformOrigin=c.transformOrigin??"50% 50%",delete c.transformOrigin),l.transform&&(l.transformBox=(I==null?void 0:I.transformBox)??"fill-box",delete c.transformBox),A!==void 0&&(c.x=A),t!==void 0&&(c.y=t),i!==void 0&&(c.scale=i),n!==void 0&&N7A(c,n,g,o,!1)}const phA=()=>({...QZ(),attrs:{}}),fhA=e=>typeof e=="string"&&e.toLowerCase()==="svg";function R7A(e,A,t,i){const n=E.useMemo(()=>{const g=phA();return hhA(g,A,fhA(i),e.transformTemplate,e.style),{...g.attrs,style:{...g.style}}},[A]);if(e.style){const g={};dhA(g,e.style,e),n.style={...g,...n.style}}return n}const G7A=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function uZ(e){return typeof e!="string"||e.includes("-")?!1:!!(G7A.indexOf(e)>-1||/[A-Z]/u.test(e))}function b7A(e,A,t,{latestValues:i},n,g=!1){const s=(uZ(e)?R7A:w7A)(A,i,n,e),a=u7A(A,typeof e=="string",g),r=e!==E.Fragment?{...a,...s,ref:t}:{},{children:I}=A,c=E.useMemo(()=>$a(I)?I.get():I,[I]);return E.createElement(e,{...r,children:c})}function beA(e){const A=[{},{}];return e==null||e.values.forEach((t,i)=>{A[0][i]=t.get(),A[1][i]=t.getVelocity()}),A}function dZ(e,A,t,i){if(typeof A=="function"){const[n,g]=beA(i);A=A(t!==void 0?t:e.custom,n,g)}if(typeof A=="string"&&(A=e.variants&&e.variants[A]),typeof A=="function"){const[n,g]=beA(i);A=A(t!==void 0?t:e.custom,n,g)}return A}function MK(e){return $a(e)?e.get():e}function U7A({scrapeMotionValuesFromProps:e,createRenderState:A},t,i,n){return{latestValues:v7A(t,i,n,e),renderState:A()}}function v7A(e,A,t,i){const n={},g=i(e,{});for(const l in g)n[l]=MK(g[l]);let{initial:o,animate:s}=e;const a=ax(e),r=QhA(e);A&&r&&!a&&e.inherit!==!1&&(o===void 0&&(o=A.initial),s===void 0&&(s=A.animate));let I=t?t.initial===!1:!1;I=I||o===!1;const c=I?s:o;if(c&&typeof c!="boolean"&&!sx(c)){const l=Array.isArray(c)?c:[c];for(let B=0;B<l.length;B++){const Q=dZ(e,l[B]);if(Q){const{transitionEnd:h,transition:d,...p}=Q;for(const y in p){let m=p[y];if(Array.isArray(m)){const D=I?m.length-1:0;m=m[D]}m!==null&&(n[y]=m)}for(const y in h)n[y]=h[y]}}}return n}const yhA=e=>(A,t)=>{const i=E.useContext(ox),n=E.useContext(Oz),g=()=>U7A(e,A,i,n);return t?g():BXA(g)};function hZ(e,A,t){var g;const{style:i}=e,n={};for(const o in i)($a(i[o])||A.style&&$a(A.style[o])||uhA(o,e)||((g=t==null?void 0:t.getValue(o))==null?void 0:g.liveStyle)!==void 0)&&(n[o]=i[o]);return n}const K7A=yhA({scrapeMotionValuesFromProps:hZ,createRenderState:QZ});function DhA(e,A,t){const i=hZ(e,A,t);for(const n in e)if($a(e[n])||$a(A[n])){const g=Nw.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;i[g]=e[n]}return i}const F7A=yhA({scrapeMotionValuesFromProps:DhA,createRenderState:phA}),_7A=Symbol.for("motionComponentSymbol");function tm(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function J7A(e,A,t){return E.useCallback(i=>{i&&e.onMount&&e.onMount(i),A&&(i?A.mount(i):A.unmount()),t&&(typeof t=="function"?t(i):tm(t)&&(t.current=i))},[A])}const pZ=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),L7A="framerAppearId",mhA="data-"+pZ(L7A),ShA=E.createContext({});function x7A(e,A,t,i,n){var h,d;const{visualElement:g}=E.useContext(ox),o=E.useContext(BhA),s=E.useContext(Oz),a=E.useContext(lhA).reducedMotion,r=E.useRef(null);i=i||o.renderer,!r.current&&i&&(r.current=i(e,{visualState:A,parent:g,props:t,presenceContext:s,blockInitialAnimation:s?s.initial===!1:!1,reducedMotionConfig:a}));const I=r.current,c=E.useContext(ShA);I&&!I.projection&&n&&(I.type==="html"||I.type==="svg")&&T7A(r.current,t,n,c);const l=E.useRef(!1);E.useInsertionEffect(()=>{I&&l.current&&I.update(t,s)});const B=t[mhA],Q=E.useRef(!!B&&!((h=window.MotionHandoffIsComplete)!=null&&h.call(window,B))&&((d=window.MotionHasOptimisedAnimation)==null?void 0:d.call(window,B)));return EXA(()=>{I&&(l.current=!0,window.MotionIsMounted=!0,I.updateFeatures(),I.scheduleRenderMicrotask(),Q.current&&I.animationState&&I.animationState.animateChanges())}),E.useEffect(()=>{I&&(!Q.current&&I.animationState&&I.animationState.animateChanges(),Q.current&&(queueMicrotask(()=>{var p;(p=window.MotionHandoffMarkAsComplete)==null||p.call(window,B)}),Q.current=!1),I.enteringChildren=void 0)}),I}function T7A(e,A,t,i){const{layoutId:n,layout:g,drag:o,dragConstraints:s,layoutScroll:a,layoutRoot:r,layoutCrossfade:I}=A;e.projection=new t(e.latestValues,A["data-framer-portal-id"]?void 0:whA(e.parent)),e.projection.setOptions({layoutId:n,layout:g,alwaysMeasureLayout:!!o||s&&tm(s),visualElement:e,animationType:typeof g=="string"?g:"both",initialPromotionConfig:i,crossfade:I,layoutScroll:a,layoutRoot:r})}function whA(e){if(e)return e.options.allowProjection!==!1?e.projection:whA(e.parent)}function uY(e,{forwardMotionProps:A=!1}={},t,i){t&&B7A(t);const n=uZ(e)?F7A:K7A;function g(s,a){let r;const I={...E.useContext(lhA),...s,layoutId:q7A(s)},{isStatic:c}=I,l=h7A(s),B=n(s,c);if(!c&&Hz){Y7A();const Q=H7A(I);r=Q.MeasureLayout,l.visualElement=x7A(e,B,I,i,Q.ProjectionNode)}return C.jsxs(ox.Provider,{value:l,children:[r&&l.visualElement?C.jsx(r,{visualElement:l.visualElement,...I}):null,b7A(e,s,J7A(B,l.visualElement,a),B,c,A)]})}g.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const o=E.forwardRef(g);return o[_7A]=e,o}function q7A({layoutId:e}){const A=E.useContext(DdA).id;return A&&e!==void 0?A+"-"+e:e}function Y7A(e,A){E.useContext(BhA).strict}function H7A(e){const{drag:A,layout:t}=KS;if(!A&&!t)return{};const i={...A,...t};return{MeasureLayout:A!=null&&A.isEnabled(e)||t!=null&&t.isEnabled(e)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}function O7A(e,A){if(typeof Proxy>"u")return uY;const t=new Map,i=(g,o)=>uY(g,o,e,A),n=(g,o)=>i(g,o);return new Proxy(n,{get:(g,o)=>o==="create"?i:(t.has(o)||t.set(o,uY(o,void 0,e,A)),t.get(o))})}function khA({top:e,left:A,right:t,bottom:i}){return{x:{min:A,max:t},y:{min:e,max:i}}}function P7A({x:e,y:A}){return{top:A.min,right:e.max,bottom:A.max,left:e.min}}function j7A(e,A){if(!A)return e;const t=A({x:e.left,y:e.top}),i=A({x:e.right,y:e.bottom});return{top:t.y,left:t.x,bottom:i.y,right:i.x}}function dY(e){return e===void 0||e===1}function T3({scale:e,scaleX:A,scaleY:t}){return!dY(e)||!dY(A)||!dY(t)}function Wh(e){return T3(e)||MhA(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function MhA(e){return UeA(e.x)||UeA(e.y)}function UeA(e){return e&&e!=="0%"}function Q_(e,A,t){const i=e-t,n=A*i;return t+n}function veA(e,A,t,i,n){return n!==void 0&&(e=Q_(e,n,i)),Q_(e,t,i)+A}function q3(e,A=0,t=1,i,n){e.min=veA(e.min,A,t,i,n),e.max=veA(e.max,A,t,i,n)}function NhA(e,{x:A,y:t}){q3(e.x,A.translate,A.scale,A.originPoint),q3(e.y,t.translate,t.scale,t.originPoint)}const KeA=.999999999999,FeA=1.0000000000001;function z7A(e,A,t,i=!1){const n=t.length;if(!n)return;A.x=A.y=1;let g,o;for(let s=0;s<n;s++){g=t[s],o=g.projectionDelta;const{visualElement:a}=g.options;a&&a.props.style&&a.props.style.display==="contents"||(i&&g.options.layoutScroll&&g.scroll&&g!==g.root&&nm(e,{x:-g.scroll.offset.x,y:-g.scroll.offset.y}),o&&(A.x*=o.x.scale,A.y*=o.y.scale,NhA(e,o)),i&&Wh(g.latestValues)&&nm(e,g.latestValues))}A.x<FeA&&A.x>KeA&&(A.x=1),A.y<FeA&&A.y>KeA&&(A.y=1)}function im(e,A){e.min=e.min+A,e.max=e.max+A}function _eA(e,A,t,i,n=.5){const g=wo(e.min,e.max,n);q3(e,A,t,g,i)}function nm(e,A){_eA(e.x,A.x,A.scaleX,A.scale,A.originX),_eA(e.y,A.y,A.scaleY,A.scale,A.originY)}function RhA(e,A){return khA(j7A(e.getBoundingClientRect(),A))}function Z7A(e,A,t){const i=RhA(e,t),{scroll:n}=A;return n&&(im(i.x,n.offset.x),im(i.y,n.offset.y)),i}const JeA=()=>({translate:0,scale:1,origin:0,originPoint:0}),gm=()=>({x:JeA(),y:JeA()}),LeA=()=>({min:0,max:0}),jo=()=>({x:LeA(),y:LeA()}),u_={current:null},fZ={current:!1};function GhA(){if(fZ.current=!0,!!Hz)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),A=()=>u_.current=e.matches;e.addEventListener("change",A),A()}else u_.current=!1}const W7A=new WeakMap;function V7A(e,A,t){for(const i in A){const n=A[i],g=t[i];if($a(n))e.addValue(i,n);else if($a(g))e.addValue(i,vS(n,{owner:e}));else if(g!==n)if(e.hasValue(i)){const o=e.getValue(i);o.liveStyle===!0?o.jump(n):o.hasAnimated||o.set(n)}else{const o=e.getStaticValue(i);e.addValue(i,vS(o!==void 0?o:n,{owner:e}))}}for(const i in t)A[i]===void 0&&e.removeValue(i);return A}const xeA=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class X7A{scrapeMotionValuesFromProps(A,t,i){return{}}constructor({parent:A,props:t,presenceContext:i,reducedMotionConfig:n,blockInitialAnimation:g,visualState:o},s={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=aZ,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const l=gI.now();this.renderScheduledAt<l&&(this.renderScheduledAt=l,Eo.render(this.render,!1,!0))};const{latestValues:a,renderState:r}=o;this.latestValues=a,this.baseTarget={...a},this.initialValues=t.initial?{...a}:{},this.renderState=r,this.parent=A,this.props=t,this.presenceContext=i,this.depth=A?A.depth+1:0,this.reducedMotionConfig=n,this.options=s,this.blockInitialAnimation=!!g,this.isControllingVariants=ax(t),this.isVariantNode=QhA(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(A&&A.current);const{willChange:I,...c}=this.scrapeMotionValuesFromProps(t,{},this);for(const l in c){const B=c[l];a[l]!==void 0&&$a(B)&&B.set(a[l])}}mount(A){var t;this.current=A,W7A.set(A,this),this.projection&&!this.projection.instance&&this.projection.mount(A),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((i,n)=>this.bindToMotionValue(n,i)),fZ.current||GhA(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:u_.current,(t=this.parent)==null||t.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var A;this.projection&&this.projection.unmount(),Bd(this.notifyUpdate),Bd(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(A=this.parent)==null||A.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const i=this.features[t];i&&(i.unmount(),i.isMounted=!1)}this.current=null}addChild(A){this.children.add(A),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(A)}removeChild(A){this.children.delete(A),this.enteringChildren&&this.enteringChildren.delete(A)}bindToMotionValue(A,t){this.valueSubscriptions.has(A)&&this.valueSubscriptions.get(A)();const i=Rw.has(A);i&&this.onBindTransform&&this.onBindTransform();const n=t.on("change",o=>{this.latestValues[A]=o,this.props.onUpdate&&Eo.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let g;window.MotionCheckAppearSync&&(g=window.MotionCheckAppearSync(this,A,t)),this.valueSubscriptions.set(A,()=>{n(),g&&g(),t.owner&&t.stop()})}sortNodePosition(A){return!this.current||!this.sortInstanceNodePosition||this.type!==A.type?0:this.sortInstanceNodePosition(this.current,A.current)}updateFeatures(){let A="animation";for(A in KS){const t=KS[A];if(!t)continue;const{isEnabled:i,Feature:n}=t;if(!this.features[A]&&n&&i(this.props)&&(this.features[A]=new n(this)),this.features[A]){const g=this.features[A];g.isMounted?g.update():(g.mount(),g.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):jo()}getStaticValue(A){return this.latestValues[A]}setStaticValue(A,t){this.latestValues[A]=t}update(A,t){(A.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=A,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let i=0;i<xeA.length;i++){const n=xeA[i];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);const g="on"+n,o=A[g];o&&(this.propEventSubscriptions[n]=this.on(n,o))}this.prevMotionValues=V7A(this,this.scrapeMotionValuesFromProps(A,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(A){return this.props.variants?this.props.variants[A]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(A){const t=this.getClosestVariantNode();if(t)return t.variantChildren&&t.variantChildren.add(A),()=>t.variantChildren.delete(A)}addValue(A,t){const i=this.values.get(A);t!==i&&(i&&this.removeValue(A),this.bindToMotionValue(A,t),this.values.set(A,t),this.latestValues[A]=t.get())}removeValue(A){this.values.delete(A);const t=this.valueSubscriptions.get(A);t&&(t(),this.valueSubscriptions.delete(A)),delete this.latestValues[A],this.removeValueFromRenderState(A,this.renderState)}hasValue(A){return this.values.has(A)}getValue(A,t){if(this.props.values&&this.props.values[A])return this.props.values[A];let i=this.values.get(A);return i===void 0&&t!==void 0&&(i=vS(t===null?void 0:t,{owner:this}),this.addValue(A,i)),i}readValue(A,t){let i=this.latestValues[A]!==void 0||!this.current?this.latestValues[A]:this.getBaseTargetFromProps(this.props,A)??this.readValueFromInstance(this.current,A,this.options);return i!=null&&(typeof i=="string"&&(mdA(i)||wdA(i))?i=parseFloat(i):!c7A(i)&&Ed.test(t)&&(i=shA(A,t)),this.setBaseTarget(A,$a(i)?i.get():i)),$a(i)?i.get():i}setBaseTarget(A,t){this.baseTarget[A]=t}getBaseTarget(A){var g;const{initial:t}=this.props;let i;if(typeof t=="string"||typeof t=="object"){const o=dZ(this.props,t,(g=this.presenceContext)==null?void 0:g.custom);o&&(i=o[A])}if(t&&i!==void 0)return i;const n=this.getBaseTargetFromProps(this.props,A);return n!==void 0&&!$a(n)?n:this.initialValues[A]!==void 0&&i===void 0?void 0:this.baseTarget[A]}on(A,t){return this.events[A]||(this.events[A]=new Wz),this.events[A].add(t)}notify(A,...t){this.events[A]&&this.events[A].notify(...t)}scheduleRenderMicrotask(){CZ.render(this.render)}}class bhA extends X7A{constructor(){super(...arguments),this.KeyframeResolver=$6A}sortInstanceNodePosition(A,t){return A.compareDocumentPosition(t)&2?1:-1}getBaseTargetFromProps(A,t){return A.style?A.style[t]:void 0}removeValueFromRenderState(A,{vars:t,style:i}){delete t[A],delete i[A]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:A}=this.props;$a(A)&&(this.childSubscription=A.on("change",t=>{this.current&&(this.current.textContent=`${t}`)}))}}function UhA(e,{style:A,vars:t},i,n){const g=e.style;let o;for(o in A)g[o]=A[o];n==null||n.applyProjectionStyles(g,i);for(o in t)g.setProperty(o,t[o])}function $7A(e){return window.getComputedStyle(e)}class A$A extends bhA{constructor(){super(...arguments),this.type="html",this.renderInstance=UhA}readValueFromInstance(A,t){var i;if(Rw.has(t))return(i=this.projection)!=null&&i.isProjecting?v3(t):d6A(A,t);{const n=$7A(A),g=($z(t)?n.getPropertyValue(t):n[t])||0;return typeof g=="string"?g.trim():g}}measureInstanceViewportBox(A,{transformPagePoint:t}){return RhA(A,t)}build(A,t,i){EZ(A,t,i.transformTemplate)}scrapeMotionValuesFromProps(A,t,i){return hZ(A,t,i)}}const vhA=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function e$A(e,A,t,i){UhA(e,A,void 0,i);for(const n in A.attrs)e.setAttribute(vhA.has(n)?n:pZ(n),A.attrs[n])}class t$A extends bhA{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=jo}getBaseTargetFromProps(A,t){return A[t]}readValueFromInstance(A,t){if(Rw.has(t)){const i=ohA(t);return i&&i.default||0}return t=vhA.has(t)?t:pZ(t),A.getAttribute(t)}scrapeMotionValuesFromProps(A,t,i){return DhA(A,t,i)}build(A,t,i){hhA(A,t,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(A,t,i,n){e$A(A,t,i,n)}mount(A){this.isSVGTag=fhA(A.tagName),super.mount(A)}}const i$A=(e,A)=>uZ(e)?new t$A(A):new A$A(A,{allowProjection:e!==E.Fragment});function qm(e,A,t){const i=e.getProps();return dZ(i,A,t!==void 0?t:i.custom,e)}const Y3=e=>Array.isArray(e);function n$A(e,A,t){e.hasValue(A)?e.getValue(A).set(t):e.addValue(A,vS(t))}function g$A(e){return Y3(e)?e[e.length-1]||0:e}function o$A(e,A){const t=qm(e,A);let{transitionEnd:i={},transition:n={},...g}=t||{};g={...g,...i};for(const o in g){const s=g$A(g[o]);n$A(e,o,s)}}function s$A(e){return!!($a(e)&&e.add)}function H3(e,A){const t=e.getValue("willChange");if(s$A(t))return t.add(A);if(!t&&iQ.WillChange){const i=new iQ.WillChange("auto");e.addValue("willChange",i),i.add(A)}}function KhA(e){return e.props[mhA]}const a$A=e=>e!==null;function r$A(e,{repeat:A,repeatType:t="loop"},i){const n=e.filter(a$A),g=A&&t!=="loop"&&A%2===1?0:n.length-1;return n[g]}const I$A={type:"spring",stiffness:500,damping:25,restSpeed:10},C$A=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),c$A={type:"keyframes",duration:.8},l$A={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},B$A=(e,{keyframes:A})=>A.length>2?c$A:Rw.has(e)?e.startsWith("scale")?C$A(A[1]):I$A:l$A;function E$A({when:e,delay:A,delayChildren:t,staggerChildren:i,staggerDirection:n,repeat:g,repeatType:o,repeatDelay:s,from:a,elapsed:r,...I}){return!!Object.keys(I).length}const yZ=(e,A,t,i={},n,g)=>o=>{const s=rZ(i,e)||{},a=s.delay||i.delay||0;let{elapsed:r=0}=i;r=r-lB(a);const I={keyframes:Array.isArray(t)?t:[null,t],ease:"easeOut",velocity:A.getVelocity(),...s,delay:-r,onUpdate:l=>{A.set(l),s.onUpdate&&s.onUpdate(l)},onComplete:()=>{o(),s.onComplete&&s.onComplete()},name:e,motionValue:A,element:g?void 0:n};E$A(s)||Object.assign(I,B$A(e,I)),I.duration&&(I.duration=lB(I.duration)),I.repeatDelay&&(I.repeatDelay=lB(I.repeatDelay)),I.from!==void 0&&(I.keyframes[0]=I.from);let c=!1;if((I.type===!1||I.duration===0&&!I.repeatDelay)&&(L3(I),I.delay===0&&(c=!0)),(iQ.instantAnimations||iQ.skipAnimations)&&(c=!0,L3(I),I.delay=0),I.allowFlatten=!s.type&&!s.ease,c&&!g&&A.get()!==void 0){const l=r$A(I.keyframes,s);if(l!==void 0){Eo.update(()=>{I.onUpdate(l),I.onComplete()});return}}return s.isSync?new sZ(I):new T6A(I)};function Q$A({protectedKeys:e,needsAnimating:A},t){const i=e.hasOwnProperty(t)&&A[t]!==!0;return A[t]=!1,i}function FhA(e,A,{delay:t=0,transitionOverride:i,type:n}={}){let{transition:g=e.getDefaultTransition(),transitionEnd:o,...s}=A;i&&(g=i);const a=[],r=n&&e.animationState&&e.animationState.getState()[n];for(const I in s){const c=e.getValue(I,e.latestValues[I]??null),l=s[I];if(l===void 0||r&&Q$A(r,I))continue;const B={delay:t,...rZ(g||{},I)},Q=c.get();if(Q!==void 0&&!c.isAnimating&&!Array.isArray(l)&&l===Q&&!B.velocity)continue;let h=!1;if(window.MotionHandoffAnimation){const p=KhA(e);if(p){const y=window.MotionHandoffAnimation(p,I,Eo);y!==null&&(B.startTime=y,h=!0)}}H3(e,I),c.start(yZ(I,c,l,e.shouldReduceMotion&&ihA.has(I)?{type:!1}:B,e,h));const d=c.animation;d&&a.push(d)}return o&&Promise.all(a).then(()=>{Eo.update(()=>{o&&o$A(e,o)})}),a}function _hA(e,A,t,i=0,n=1){const g=Array.from(e).sort((r,I)=>r.sortNodePosition(I)).indexOf(A),o=e.size,s=(o-1)*i;return typeof t=="function"?t(g,o):n===1?g*i:s-g*i}function O3(e,A,t={}){var a;const i=qm(e,A,t.type==="exit"?(a=e.presenceContext)==null?void 0:a.custom:void 0);let{transition:n=e.getDefaultTransition()||{}}=i||{};t.transitionOverride&&(n=t.transitionOverride);const g=i?()=>Promise.all(FhA(e,i,t)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{const{delayChildren:I=0,staggerChildren:c,staggerDirection:l}=n;return u$A(e,A,r,I,c,l,t)}:()=>Promise.resolve(),{when:s}=n;if(s){const[r,I]=s==="beforeChildren"?[g,o]:[o,g];return r().then(()=>I())}else return Promise.all([g(),o(t.delay)])}function u$A(e,A,t=0,i=0,n=0,g=1,o){const s=[];for(const a of e.variantChildren)a.notify("AnimationStart",A),s.push(O3(a,A,{...o,delay:t+(typeof i=="function"?0:i)+_hA(e.variantChildren,a,i,n,g)}).then(()=>a.notify("AnimationComplete",A)));return Promise.all(s)}function d$A(e,A,t={}){e.notify("AnimationStart",A);let i;if(Array.isArray(A)){const n=A.map(g=>O3(e,g,t));i=Promise.all(n)}else if(typeof A=="string")i=O3(e,A,t);else{const n=typeof A=="function"?qm(e,A,t.custom):A;i=Promise.all(FhA(e,n,t))}return i.then(()=>{e.notify("AnimationComplete",A)})}function JhA(e,A){if(!Array.isArray(A))return!1;const t=A.length;if(t!==e.length)return!1;for(let i=0;i<t;i++)if(A[i]!==e[i])return!1;return!0}const h$A=BZ.length;function LhA(e){if(!e)return;if(!e.isControllingVariants){const t=e.parent?LhA(e.parent)||{}:{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}const A={};for(let t=0;t<h$A;t++){const i=BZ[t],n=e.props[i];(pN(n)||n===!1)&&(A[i]=n)}return A}const p$A=[...lZ].reverse(),f$A=lZ.length;function y$A(e){return A=>Promise.all(A.map(({animation:t,options:i})=>d$A(e,t,i)))}function D$A(e){let A=y$A(e),t=TeA(),i=!0;const n=a=>(r,I)=>{var l;const c=qm(e,I,a==="exit"?(l=e.presenceContext)==null?void 0:l.custom:void 0);if(c){const{transition:B,transitionEnd:Q,...h}=c;r={...r,...h,...Q}}return r};function g(a){A=a(e)}function o(a){const{props:r}=e,I=LhA(e.parent)||{},c=[],l=new Set;let B={},Q=1/0;for(let d=0;d<f$A;d++){const p=p$A[d],y=t[p],m=r[p]!==void 0?r[p]:I[p],D=pN(m),S=p===a?y.isActive:null;S===!1&&(Q=d);let k=m===I[p]&&m!==r[p]&&D;if(k&&i&&e.manuallyAnimateOnMount&&(k=!1),y.protectedKeys={...B},!y.isActive&&S===null||!m&&!y.prevProp||sx(m)||typeof m=="boolean")continue;const N=m$A(y.prevProp,m);let G=N||p===a&&y.isActive&&!k&&D||d>Q&&D,M=!1;const w=Array.isArray(m)?m:[m];let b=w.reduce(n(p),{});S===!1&&(b={});const{prevResolvedValues:_={}}=y,K={..._,...b},J=U=>{G=!0,l.has(U)&&(M=!0,l.delete(U)),y.needsAnimating[U]=!0;const x=e.getValue(U);x&&(x.liveStyle=!1)};for(const U in K){const x=b[U],T=_[U];if(B.hasOwnProperty(U))continue;let z=!1;Y3(x)&&Y3(T)?z=!JhA(x,T):z=x!==T,z?x!=null?J(U):l.add(U):x!==void 0&&l.has(U)?J(U):y.protectedKeys[U]=!0}y.prevProp=m,y.prevResolvedValues=b,y.isActive&&(B={...B,...b}),i&&e.blockInitialAnimation&&(G=!1);const q=k&&N;G&&(!q||M)&&c.push(...w.map(U=>{const x={type:p};if(typeof U=="string"&&i&&!q&&e.manuallyAnimateOnMount&&e.parent){const{parent:T}=e,z=qm(T,U);if(T.enteringChildren&&z){const{delayChildren:Z}=z.transition||{};x.delay=_hA(T.enteringChildren,e,Z)}}return{animation:U,options:x}}))}if(l.size){const d={};if(typeof r.initial!="boolean"){const p=qm(e,Array.isArray(r.initial)?r.initial[0]:r.initial);p&&p.transition&&(d.transition=p.transition)}l.forEach(p=>{const y=e.getBaseTarget(p),m=e.getValue(p);m&&(m.liveStyle=!0),d[p]=y??null}),c.push({animation:d})}let h=!!c.length;return i&&(r.initial===!1||r.initial===r.animate)&&!e.manuallyAnimateOnMount&&(h=!1),i=!1,h?A(c):Promise.resolve()}function s(a,r){var c;if(t[a].isActive===r)return Promise.resolve();(c=e.variantChildren)==null||c.forEach(l=>{var B;return(B=l.animationState)==null?void 0:B.setActive(a,r)}),t[a].isActive=r;const I=o(a);for(const l in t)t[l].protectedKeys={};return I}return{animateChanges:o,setActive:s,setAnimateFunction:g,getState:()=>t,reset:()=>{t=TeA(),i=!0}}}function m$A(e,A){return typeof A=="string"?A!==e:Array.isArray(A)?!JhA(A,e):!1}function Bh(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function TeA(){return{animate:Bh(!0),whileInView:Bh(),whileHover:Bh(),whileTap:Bh(),whileDrag:Bh(),whileFocus:Bh(),exit:Bh()}}class Jd{constructor(A){this.isMounted=!1,this.node=A}update(){}}class S$A extends Jd{constructor(A){super(A),A.animationState||(A.animationState=D$A(A))}updateAnimationControlsSubscription(){const{animate:A}=this.node.getProps();sx(A)&&(this.unmountControls=A.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:A}=this.node.getProps(),{animate:t}=this.node.prevProps||{};A!==t&&this.updateAnimationControlsSubscription()}unmount(){var A;this.node.animationState.reset(),(A=this.unmountControls)==null||A.call(this)}}let w$A=0;class k$A extends Jd{constructor(){super(...arguments),this.id=w$A++}update(){if(!this.node.presenceContext)return;const{isPresent:A,onExitComplete:t}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||A===i)return;const n=this.node.animationState.setActive("exit",!A);t&&!A&&n.then(()=>{t(this.id)})}mount(){const{register:A,onExitComplete:t}=this.node.presenceContext||{};t&&t(this.id),A&&(this.unmount=A(this.id))}unmount(){}}const M$A={animation:{Feature:S$A},exit:{Feature:k$A}};function yN(e,A,t,i={passive:!0}){return e.addEventListener(A,t,i),()=>e.removeEventListener(A,t)}function ZR(e){return{point:{x:e.pageX,y:e.pageY}}}const N$A=e=>A=>cZ(A)&&e(A,ZR(A));function EM(e,A,t,i){return yN(e,A,N$A(t),i)}const xhA=1e-4,R$A=1-xhA,G$A=1+xhA,ThA=.01,b$A=0-ThA,U$A=0+ThA;function Rr(e){return e.max-e.min}function v$A(e,A,t){return Math.abs(e-A)<=t}function qeA(e,A,t,i=.5){e.origin=i,e.originPoint=wo(A.min,A.max,e.origin),e.scale=Rr(t)/Rr(A),e.translate=wo(t.min,t.max,e.origin)-e.originPoint,(e.scale>=R$A&&e.scale<=G$A||isNaN(e.scale))&&(e.scale=1),(e.translate>=b$A&&e.translate<=U$A||isNaN(e.translate))&&(e.translate=0)}function QM(e,A,t,i){qeA(e.x,A.x,t.x,i?i.originX:void 0),qeA(e.y,A.y,t.y,i?i.originY:void 0)}function YeA(e,A,t){e.min=t.min+A.min,e.max=e.min+Rr(A)}function K$A(e,A,t){YeA(e.x,A.x,t.x),YeA(e.y,A.y,t.y)}function HeA(e,A,t){e.min=A.min-t.min,e.max=e.min+Rr(A)}function uM(e,A,t){HeA(e.x,A.x,t.x),HeA(e.y,A.y,t.y)}function MC(e){return[e("x"),e("y")]}const qhA=({current:e})=>e?e.ownerDocument.defaultView:null,OeA=(e,A)=>Math.abs(e-A);function F$A(e,A){const t=OeA(e.x,A.x),i=OeA(e.y,A.y);return Math.sqrt(t**2+i**2)}class YhA{constructor(A,t,{transformPagePoint:i,contextWindow:n=window,dragSnapToOrigin:g=!1,distanceThreshold:o=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const l=pY(this.lastMoveEventInfo,this.history),B=this.startEvent!==null,Q=F$A(l.offset,{x:0,y:0})>=this.distanceThreshold;if(!B&&!Q)return;const{point:h}=l,{timestamp:d}=fa;this.history.push({...h,timestamp:d});const{onStart:p,onMove:y}=this.handlers;B||(p&&p(this.lastMoveEvent,l),this.startEvent=this.lastMoveEvent),y&&y(this.lastMoveEvent,l)},this.handlePointerMove=(l,B)=>{this.lastMoveEvent=l,this.lastMoveEventInfo=hY(B,this.transformPagePoint),Eo.update(this.updatePoint,!0)},this.handlePointerUp=(l,B)=>{this.end();const{onEnd:Q,onSessionEnd:h,resumeAnimation:d}=this.handlers;if(this.dragSnapToOrigin&&d&&d(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const p=pY(l.type==="pointercancel"?this.lastMoveEventInfo:hY(B,this.transformPagePoint),this.history);this.startEvent&&Q&&Q(l,p),h&&h(l,p)},!cZ(A))return;this.dragSnapToOrigin=g,this.handlers=t,this.transformPagePoint=i,this.distanceThreshold=o,this.contextWindow=n||window;const s=ZR(A),a=hY(s,this.transformPagePoint),{point:r}=a,{timestamp:I}=fa;this.history=[{...r,timestamp:I}];const{onSessionStart:c}=t;c&&c(A,pY(a,this.history)),this.removeListeners=PR(EM(this.contextWindow,"pointermove",this.handlePointerMove),EM(this.contextWindow,"pointerup",this.handlePointerUp),EM(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(A){this.handlers=A}end(){this.removeListeners&&this.removeListeners(),Bd(this.updatePoint)}}function hY(e,A){return A?{point:A(e.point)}:e}function PeA(e,A){return{x:e.x-A.x,y:e.y-A.y}}function pY({point:e},A){return{point:e,delta:PeA(e,HhA(A)),offset:PeA(e,_$A(A)),velocity:J$A(A,.1)}}function _$A(e){return e[0]}function HhA(e){return e[e.length-1]}function J$A(e,A){if(e.length<2)return{x:0,y:0};let t=e.length-1,i=null;const n=HhA(e);for(;t>=0&&(i=e[t],!(n.timestamp-i.timestamp>lB(A)));)t--;if(!i)return{x:0,y:0};const g=BB(n.timestamp-i.timestamp);if(g===0)return{x:0,y:0};const o={x:(n.x-i.x)/g,y:(n.y-i.y)/g};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function L$A(e,{min:A,max:t},i){return A!==void 0&&e<A?e=i?wo(A,e,i.min):Math.max(e,A):t!==void 0&&e>t&&(e=i?wo(t,e,i.max):Math.min(e,t)),e}function jeA(e,A,t){return{min:A!==void 0?e.min+A:void 0,max:t!==void 0?e.max+t-(e.max-e.min):void 0}}function x$A(e,{top:A,left:t,bottom:i,right:n}){return{x:jeA(e.x,t,n),y:jeA(e.y,A,i)}}function zeA(e,A){let t=A.min-e.min,i=A.max-e.max;return A.max-A.min<e.max-e.min&&([t,i]=[i,t]),{min:t,max:i}}function T$A(e,A){return{x:zeA(e.x,A.x),y:zeA(e.y,A.y)}}function q$A(e,A){let t=.5;const i=Rr(e),n=Rr(A);return n>i?t=uN(A.min,A.max-i,e.min):i>n&&(t=uN(e.min,e.max-n,A.min)),tQ(0,1,t)}function Y$A(e,A){const t={};return A.min!==void 0&&(t.min=A.min-e.min),A.max!==void 0&&(t.max=A.max-e.min),t}const P3=.35;function H$A(e=P3){return e===!1?e=0:e===!0&&(e=P3),{x:ZeA(e,"left","right"),y:ZeA(e,"top","bottom")}}function ZeA(e,A,t){return{min:WeA(e,A),max:WeA(e,t)}}function WeA(e,A){return typeof e=="number"?e:e[A]||0}const O$A=new WeakMap;class P$A{constructor(A){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=jo(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=A}start(A,{snapToCursor:t=!1,distanceThreshold:i}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const g=c=>{const{dragSnapToOrigin:l}=this.getProps();l?this.pauseAnimation():this.stopAnimation(),t&&this.snapToCursor(ZR(c).point)},o=(c,l)=>{const{drag:B,dragPropagation:Q,onDragStart:h}=this.getProps();if(B&&!Q&&(this.openDragLock&&this.openDragLock(),this.openDragLock=n7A(B),!this.openDragLock))return;this.latestPointerEvent=c,this.latestPanInfo=l,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),MC(p=>{let y=this.getAxisMotionValue(p).get()||0;if(EB.test(y)){const{projection:m}=this.visualElement;if(m&&m.layout){const D=m.layout.layoutBox[p];D&&(y=Rr(D)*(parseFloat(y)/100))}}this.originPoint[p]=y}),h&&Eo.postRender(()=>h(c,l)),H3(this.visualElement,"transform");const{animationState:d}=this.visualElement;d&&d.setActive("whileDrag",!0)},s=(c,l)=>{this.latestPointerEvent=c,this.latestPanInfo=l;const{dragPropagation:B,dragDirectionLock:Q,onDirectionLock:h,onDrag:d}=this.getProps();if(!B&&!this.openDragLock)return;const{offset:p}=l;if(Q&&this.currentDirection===null){this.currentDirection=j$A(p),this.currentDirection!==null&&h&&h(this.currentDirection);return}this.updateAxis("x",l.point,p),this.updateAxis("y",l.point,p),this.visualElement.render(),d&&d(c,l)},a=(c,l)=>{this.latestPointerEvent=c,this.latestPanInfo=l,this.stop(c,l),this.latestPointerEvent=null,this.latestPanInfo=null},r=()=>MC(c=>{var l;return this.getAnimationState(c)==="paused"&&((l=this.getAxisMotionValue(c).animation)==null?void 0:l.play())}),{dragSnapToOrigin:I}=this.getProps();this.panSession=new YhA(A,{onSessionStart:g,onStart:o,onMove:s,onSessionEnd:a,resumeAnimation:r},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:I,distanceThreshold:i,contextWindow:qhA(this.visualElement)})}stop(A,t){const i=A||this.latestPointerEvent,n=t||this.latestPanInfo,g=this.isDragging;if(this.cancel(),!g||!n||!i)return;const{velocity:o}=n;this.startAnimation(o);const{onDragEnd:s}=this.getProps();s&&Eo.postRender(()=>s(i,n))}cancel(){this.isDragging=!1;const{projection:A,animationState:t}=this.visualElement;A&&(A.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive("whileDrag",!1)}updateAxis(A,t,i){const{drag:n}=this.getProps();if(!i||!jb(A,n,this.currentDirection))return;const g=this.getAxisMotionValue(A);let o=this.originPoint[A]+i[A];this.constraints&&this.constraints[A]&&(o=L$A(o,this.constraints[A],this.elastic[A])),g.set(o)}resolveConstraints(){var g;const{dragConstraints:A,dragElastic:t}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(g=this.visualElement.projection)==null?void 0:g.layout,n=this.constraints;A&&tm(A)?this.constraints||(this.constraints=this.resolveRefConstraints()):A&&i?this.constraints=x$A(i.layoutBox,A):this.constraints=!1,this.elastic=H$A(t),n!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&MC(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Y$A(i.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:A,onMeasureDragConstraints:t}=this.getProps();if(!A||!tm(A))return!1;const i=A.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const g=Z7A(i,n.root,this.visualElement.getTransformPagePoint());let o=T$A(n.layout.layoutBox,g);if(t){const s=t(P7A(o));this.hasMutatedConstraints=!!s,s&&(o=khA(s))}return o}startAnimation(A){const{drag:t,dragMomentum:i,dragElastic:n,dragTransition:g,dragSnapToOrigin:o,onDragTransitionEnd:s}=this.getProps(),a=this.constraints||{},r=MC(I=>{if(!jb(I,t,this.currentDirection))return;let c=a&&a[I]||{};o&&(c={min:0,max:0});const l=n?200:1e6,B=n?40:1e7,Q={type:"inertia",velocity:i?A[I]:0,bounceStiffness:l,bounceDamping:B,timeConstant:750,restDelta:1,restSpeed:10,...g,...c};return this.startAxisValueAnimation(I,Q)});return Promise.all(r).then(s)}startAxisValueAnimation(A,t){const i=this.getAxisMotionValue(A);return H3(this.visualElement,A),i.start(yZ(A,i,0,t,this.visualElement,!1))}stopAnimation(){MC(A=>this.getAxisMotionValue(A).stop())}pauseAnimation(){MC(A=>{var t;return(t=this.getAxisMotionValue(A).animation)==null?void 0:t.pause()})}getAnimationState(A){var t;return(t=this.getAxisMotionValue(A).animation)==null?void 0:t.state}getAxisMotionValue(A){const t=`_drag${A.toUpperCase()}`,i=this.visualElement.getProps(),n=i[t];return n||this.visualElement.getValue(A,(i.initial?i.initial[A]:void 0)||0)}snapToCursor(A){MC(t=>{const{drag:i}=this.getProps();if(!jb(t,i,this.currentDirection))return;const{projection:n}=this.visualElement,g=this.getAxisMotionValue(t);if(n&&n.layout){const{min:o,max:s}=n.layout.layoutBox[t];g.set(A[t]-wo(o,s,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:A,dragConstraints:t}=this.getProps(),{projection:i}=this.visualElement;if(!tm(t)||!i||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};MC(o=>{const s=this.getAxisMotionValue(o);if(s&&this.constraints!==!1){const a=s.get();n[o]=q$A({min:a,max:a},this.constraints[o])}});const{transformTemplate:g}=this.visualElement.getProps();this.visualElement.current.style.transform=g?g({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),MC(o=>{if(!jb(o,A,null))return;const s=this.getAxisMotionValue(o),{min:a,max:r}=this.constraints[o];s.set(wo(a,r,n[o]))})}addListeners(){if(!this.visualElement.current)return;O$A.set(this.visualElement,this);const A=this.visualElement.current,t=EM(A,"pointerdown",a=>{const{drag:r,dragListener:I=!0}=this.getProps();r&&I&&this.start(a)}),i=()=>{const{dragConstraints:a}=this.getProps();tm(a)&&a.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,g=n.addEventListener("measure",i);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),Eo.read(i);const o=yN(window,"resize",()=>this.scalePositionWithinConstraints()),s=n.addEventListener("didUpdate",({delta:a,hasLayoutChanged:r})=>{this.isDragging&&r&&(MC(I=>{const c=this.getAxisMotionValue(I);c&&(this.originPoint[I]+=a[I].translate,c.set(c.get()+a[I].translate))}),this.visualElement.render())});return()=>{o(),t(),g(),s&&s()}}getProps(){const A=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:i=!1,dragPropagation:n=!1,dragConstraints:g=!1,dragElastic:o=P3,dragMomentum:s=!0}=A;return{...A,drag:t,dragDirectionLock:i,dragPropagation:n,dragConstraints:g,dragElastic:o,dragMomentum:s}}}function jb(e,A,t){return(A===!0||A===e)&&(t===null||t===e)}function j$A(e,A=10){let t=null;return Math.abs(e.y)>A?t="y":Math.abs(e.x)>A&&(t="x"),t}class z$A extends Jd{constructor(A){super(A),this.removeGroupControls=ec,this.removeListeners=ec,this.controls=new P$A(A)}mount(){const{dragControls:A}=this.node.getProps();A&&(this.removeGroupControls=A.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ec}unmount(){this.removeGroupControls(),this.removeListeners()}}const VeA=e=>(A,t)=>{e&&Eo.postRender(()=>e(A,t))};class Z$A extends Jd{constructor(){super(...arguments),this.removePointerDownListener=ec}onPointerDown(A){this.session=new YhA(A,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:qhA(this.node)})}createPanHandlers(){const{onPanSessionStart:A,onPanStart:t,onPan:i,onPanEnd:n}=this.node.getProps();return{onSessionStart:VeA(A),onStart:VeA(t),onMove:i,onEnd:(g,o)=>{delete this.session,n&&Eo.postRender(()=>n(g,o))}}}mount(){this.removePointerDownListener=EM(this.node.current,"pointerdown",A=>this.onPointerDown(A))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const NK={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function XeA(e,A){return A.max===A.min?0:e/(A.max-A.min)*100}const b0={correct:(e,A)=>{if(!A.target)return e;if(typeof e=="string")if(Ji.test(e))e=parseFloat(e);else return e;const t=XeA(e,A.target.x),i=XeA(e,A.target.y);return`${t}% ${i}%`}},W$A={correct:(e,{treeScale:A,projectionDelta:t})=>{const i=e,n=Ed.parse(e);if(n.length>5)return i;const g=Ed.createTransformer(e),o=typeof n[0]!="number"?1:0,s=t.x.scale*A.x,a=t.y.scale*A.y;n[0+o]/=s,n[1+o]/=a;const r=wo(s,a,.5);return typeof n[2+o]=="number"&&(n[2+o]/=r),typeof n[3+o]=="number"&&(n[3+o]/=r),g(n)}};let fY=!1;class V$A extends E.Component{componentDidMount(){const{visualElement:A,layoutGroup:t,switchLayoutGroup:i,layoutId:n}=this.props,{projection:g}=A;p7A(X$A),g&&(t.group&&t.group.add(g),i&&i.register&&n&&i.register(g),fY&&g.root.didUpdate(),g.addEventListener("animationComplete",()=>{this.safeToRemove()}),g.setOptions({...g.options,onExitComplete:()=>this.safeToRemove()})),NK.hasEverUpdated=!0}getSnapshotBeforeUpdate(A){const{layoutDependency:t,visualElement:i,drag:n,isPresent:g}=this.props,{projection:o}=i;return o&&(o.isPresent=g,fY=!0,n||A.layoutDependency!==t||t===void 0||A.isPresent!==g?o.willUpdate():this.safeToRemove(),A.isPresent!==g&&(g?o.promote():o.relegate()||Eo.postRender(()=>{const s=o.getStack();(!s||!s.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:A}=this.props.visualElement;A&&(A.root.didUpdate(),CZ.postRender(()=>{!A.currentAnimation&&A.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:A,layoutGroup:t,switchLayoutGroup:i}=this.props,{projection:n}=A;fY=!0,n&&(n.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(n),i&&i.deregister&&i.deregister(n))}safeToRemove(){const{safeToRemove:A}=this.props;A&&A()}render(){return null}}function OhA(e){const[A,t]=l7A(),i=E.useContext(DdA);return C.jsx(V$A,{...e,layoutGroup:i,switchLayoutGroup:E.useContext(ShA),isPresent:A,safeToRemove:t})}const X$A={borderRadius:{...b0,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:b0,borderTopRightRadius:b0,borderBottomLeftRadius:b0,borderBottomRightRadius:b0,boxShadow:W$A};function $$A(e,A,t){const i=$a(e)?e:vS(e);return i.start(yZ("",i,A,t)),i.animation}const AAe=(e,A)=>e.depth-A.depth;class eAe{constructor(){this.children=[],this.isDirty=!1}add(A){Pz(this.children,A),this.isDirty=!0}remove(A){jz(this.children,A),this.isDirty=!0}forEach(A){this.isDirty&&this.children.sort(AAe),this.isDirty=!1,this.children.forEach(A)}}function tAe(e,A){const t=gI.now(),i=({timestamp:n})=>{const g=n-t;g>=A&&(Bd(i),e(g-A))};return Eo.setup(i,!0),()=>Bd(i)}const PhA=["TopLeft","TopRight","BottomLeft","BottomRight"],iAe=PhA.length,$eA=e=>typeof e=="string"?parseFloat(e):e,AtA=e=>typeof e=="number"||Ji.test(e);function nAe(e,A,t,i,n,g){n?(e.opacity=wo(0,t.opacity??1,gAe(i)),e.opacityExit=wo(A.opacity??1,0,oAe(i))):g&&(e.opacity=wo(A.opacity??1,t.opacity??1,i));for(let o=0;o<iAe;o++){const s=`border${PhA[o]}Radius`;let a=etA(A,s),r=etA(t,s);if(a===void 0&&r===void 0)continue;a||(a=0),r||(r=0),a===0||r===0||AtA(a)===AtA(r)?(e[s]=Math.max(wo($eA(a),$eA(r),i),0),(EB.test(r)||EB.test(a))&&(e[s]+="%")):e[s]=r}(A.rotate||t.rotate)&&(e.rotate=wo(A.rotate||0,t.rotate||0,i))}function etA(e,A){return e[A]!==void 0?e[A]:e.borderRadius}const gAe=jhA(0,.5,vdA),oAe=jhA(.5,.95,ec);function jhA(e,A,t){return i=>i<e?0:i>A?1:t(uN(e,A,i))}function ttA(e,A){e.min=A.min,e.max=A.max}function DC(e,A){ttA(e.x,A.x),ttA(e.y,A.y)}function itA(e,A){e.translate=A.translate,e.scale=A.scale,e.originPoint=A.originPoint,e.origin=A.origin}function ntA(e,A,t,i,n){return e-=A,e=Q_(e,1/t,i),n!==void 0&&(e=Q_(e,1/n,i)),e}function sAe(e,A=0,t=1,i=.5,n,g=e,o=e){if(EB.test(A)&&(A=parseFloat(A),A=wo(o.min,o.max,A/100)-o.min),typeof A!="number")return;let s=wo(g.min,g.max,i);e===g&&(s-=A),e.min=ntA(e.min,A,t,s,n),e.max=ntA(e.max,A,t,s,n)}function gtA(e,A,[t,i,n],g,o){sAe(e,A[t],A[i],A[n],A.scale,g,o)}const aAe=["x","scaleX","originX"],rAe=["y","scaleY","originY"];function otA(e,A,t,i){gtA(e.x,A,aAe,t?t.x:void 0,i?i.x:void 0),gtA(e.y,A,rAe,t?t.y:void 0,i?i.y:void 0)}function stA(e){return e.translate===0&&e.scale===1}function zhA(e){return stA(e.x)&&stA(e.y)}function atA(e,A){return e.min===A.min&&e.max===A.max}function IAe(e,A){return atA(e.x,A.x)&&atA(e.y,A.y)}function rtA(e,A){return Math.round(e.min)===Math.round(A.min)&&Math.round(e.max)===Math.round(A.max)}function ZhA(e,A){return rtA(e.x,A.x)&&rtA(e.y,A.y)}function ItA(e){return Rr(e.x)/Rr(e.y)}function CtA(e,A){return e.translate===A.translate&&e.scale===A.scale&&e.originPoint===A.originPoint}class CAe{constructor(){this.members=[]}add(A){Pz(this.members,A),A.scheduleRender()}remove(A){if(jz(this.members,A),A===this.prevLead&&(this.prevLead=void 0),A===this.lead){const t=this.members[this.members.length-1];t&&this.promote(t)}}relegate(A){const t=this.members.findIndex(n=>A===n);if(t===0)return!1;let i;for(let n=t;n>=0;n--){const g=this.members[n];if(g.isPresent!==!1){i=g;break}}return i?(this.promote(i),!0):!1}promote(A,t){const i=this.lead;if(A!==i&&(this.prevLead=i,this.lead=A,A.show(),i)){i.instance&&i.scheduleRender(),A.scheduleRender(),A.resumeFrom=i,t&&(A.resumeFrom.preserveOpacity=!0),i.snapshot&&(A.snapshot=i.snapshot,A.snapshot.latestValues=i.animationValues||i.latestValues),A.root&&A.root.isUpdating&&(A.isLayoutDirty=!0);const{crossfade:n}=A.options;n===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(A=>{const{options:t,resumingFrom:i}=A;t.onExitComplete&&t.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(A=>{A.instance&&A.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function cAe(e,A,t){let i="";const n=e.x.translate/A.x,g=e.y.translate/A.y,o=(t==null?void 0:t.z)||0;if((n||g||o)&&(i=`translate3d(${n}px, ${g}px, ${o}px) `),(A.x!==1||A.y!==1)&&(i+=`scale(${1/A.x}, ${1/A.y}) `),t){const{transformPerspective:r,rotate:I,rotateX:c,rotateY:l,skewX:B,skewY:Q}=t;r&&(i=`perspective(${r}px) ${i}`),I&&(i+=`rotate(${I}deg) `),c&&(i+=`rotateX(${c}deg) `),l&&(i+=`rotateY(${l}deg) `),B&&(i+=`skewX(${B}deg) `),Q&&(i+=`skewY(${Q}deg) `)}const s=e.x.scale*A.x,a=e.y.scale*A.y;return(s!==1||a!==1)&&(i+=`scale(${s}, ${a})`),i||"none"}const yY=["","X","Y","Z"],lAe=1e3;let BAe=0;function DY(e,A,t,i){const{latestValues:n}=A;n[e]&&(t[e]=n[e],A.setStaticValue(e,0),i&&(i[e]=0))}function WhA(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:A}=e.options;if(!A)return;const t=KhA(A);if(window.MotionHasOptimisedAnimation(t,"transform")){const{layout:n,layoutId:g}=e.options;window.MotionCancelOptimisedAnimation(t,"transform",Eo,!(n||g))}const{parent:i}=e;i&&!i.hasCheckedOptimisedAppear&&WhA(i)}function VhA({attachResizeListener:e,defaultParent:A,measureScroll:t,checkIsScrollRoot:i,resetTransform:n}){return class{constructor(o={},s=A==null?void 0:A()){this.id=BAe++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(uAe),this.nodes.forEach(fAe),this.nodes.forEach(yAe),this.nodes.forEach(dAe)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,this.root=s?s.root||s:this,this.path=s?[...s.path,s]:[],this.parent=s,this.depth=s?s.depth+1:0;for(let a=0;a<this.path.length;a++)this.path[a].shouldResetTransform=!0;this.root===this&&(this.nodes=new eAe)}addEventListener(o,s){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new Wz),this.eventHandlers.get(o).add(s)}notifyListeners(o,...s){const a=this.eventHandlers.get(o);a&&a.notify(...s)}hasListeners(o){return this.eventHandlers.has(o)}mount(o){if(this.instance)return;this.isSVG=chA(o)&&!I7A(o),this.instance=o;const{layoutId:s,layout:a,visualElement:r}=this.options;if(r&&!r.current&&r.mount(o),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(a||s)&&(this.isLayoutDirty=!0),e){let I,c=0;const l=()=>this.root.updateBlockedByResize=!1;Eo.read(()=>{c=window.innerWidth}),e(o,()=>{const B=window.innerWidth;B!==c&&(c=B,this.root.updateBlockedByResize=!0,I&&I(),I=tAe(l,250),NK.hasAnimatedSinceResize&&(NK.hasAnimatedSinceResize=!1,this.nodes.forEach(BtA)))})}s&&this.root.registerSharedNode(s,this),this.options.animate!==!1&&r&&(s||a)&&this.addEventListener("didUpdate",({delta:I,hasLayoutChanged:c,hasRelativeLayoutChanged:l,layout:B})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const Q=this.options.transition||r.getDefaultTransition()||kAe,{onLayoutAnimationStart:h,onLayoutAnimationComplete:d}=r.getProps(),p=!this.targetLayout||!ZhA(this.targetLayout,B),y=!c&&l;if(this.options.layoutRoot||this.resumeFrom||y||c&&(p||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const m={...rZ(Q,"layout"),onPlay:h,onComplete:d};(r.shouldReduceMotion||this.options.layoutRoot)&&(m.delay=0,m.type=!1),this.startAnimation(m),this.setAnimationOrigin(I,y)}else c||BtA(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=B})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Bd(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(DAe),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&WhA(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let I=0;I<this.path.length;I++){const c=this.path[I];c.shouldResetTransform=!0,c.updateScroll("snapshot"),c.options.layoutRoot&&c.willUpdate(!1)}const{layoutId:s,layout:a}=this.options;if(s===void 0&&!a)return;const r=this.getTransformTemplate();this.prevTransformTemplateValue=r?r(this.latestValues,""):void 0,this.updateSnapshot(),o&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(ctA);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(ltA);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(pAe),this.nodes.forEach(EAe),this.nodes.forEach(QAe)):this.nodes.forEach(ltA),this.clearAllSnapshots();const s=gI.now();fa.delta=tQ(0,1e3/60,s-fa.timestamp),fa.timestamp=s,fa.isProcessing=!0,CY.update.process(fa),CY.preRender.process(fa),CY.render.process(fa),fa.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,CZ.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(hAe),this.sharedNodes.forEach(mAe)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Eo.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Eo.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Rr(this.snapshot.measuredBox.x)&&!Rr(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let a=0;a<this.path.length;a++)this.path[a].updateScroll();const o=this.layout;this.layout=this.measure(!1),this.layoutCorrected=jo(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:s}=this.options;s&&s.notify("LayoutMeasure",this.layout.layoutBox,o?o.layoutBox:void 0)}updateScroll(o="measure"){let s=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===o&&(s=!1),s&&this.instance){const a=i(this.instance);this.scroll={animationId:this.root.animationId,phase:o,isRoot:a,offset:t(this.instance),wasRoot:this.scroll?this.scroll.isRoot:a}}}resetTransform(){if(!n)return;const o=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,s=this.projectionDelta&&!zhA(this.projectionDelta),a=this.getTransformTemplate(),r=a?a(this.latestValues,""):void 0,I=r!==this.prevTransformTemplateValue;o&&this.instance&&(s||Wh(this.latestValues)||I)&&(n(this.instance,r),this.shouldResetTransform=!1,this.scheduleRender())}measure(o=!0){const s=this.measurePageBox();let a=this.removeElementScroll(s);return o&&(a=this.removeTransform(a)),MAe(a),{animationId:this.root.animationId,measuredBox:s,layoutBox:a,latestValues:{},source:this.id}}measurePageBox(){var r;const{visualElement:o}=this.options;if(!o)return jo();const s=o.measureViewportBox();if(!(((r=this.scroll)==null?void 0:r.wasRoot)||this.path.some(NAe))){const{scroll:I}=this.root;I&&(im(s.x,I.offset.x),im(s.y,I.offset.y))}return s}removeElementScroll(o){var a;const s=jo();if(DC(s,o),(a=this.scroll)!=null&&a.wasRoot)return s;for(let r=0;r<this.path.length;r++){const I=this.path[r],{scroll:c,options:l}=I;I!==this.root&&c&&l.layoutScroll&&(c.wasRoot&&DC(s,o),im(s.x,c.offset.x),im(s.y,c.offset.y))}return s}applyTransform(o,s=!1){const a=jo();DC(a,o);for(let r=0;r<this.path.length;r++){const I=this.path[r];!s&&I.options.layoutScroll&&I.scroll&&I!==I.root&&nm(a,{x:-I.scroll.offset.x,y:-I.scroll.offset.y}),Wh(I.latestValues)&&nm(a,I.latestValues)}return Wh(this.latestValues)&&nm(a,this.latestValues),a}removeTransform(o){const s=jo();DC(s,o);for(let a=0;a<this.path.length;a++){const r=this.path[a];if(!r.instance||!Wh(r.latestValues))continue;T3(r.latestValues)&&r.updateSnapshot();const I=jo(),c=r.measurePageBox();DC(I,c),otA(s,r.latestValues,r.snapshot?r.snapshot.layoutBox:void 0,I)}return Wh(this.latestValues)&&otA(s,this.latestValues),s}setTargetDelta(o){this.targetDelta=o,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(o){this.options={...this.options,...o,crossfade:o.crossfade!==void 0?o.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==fa.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(o=!1){var l;const s=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=s.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=s.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=s.isSharedProjectionDirty);const a=!!this.resumingFrom||this!==s;if(!(o||a&&this.isSharedProjectionDirty||this.isProjectionDirty||(l=this.parent)!=null&&l.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:I,layoutId:c}=this.options;if(!(!this.layout||!(I||c))){if(this.resolvedRelativeTargetAt=fa.timestamp,!this.targetDelta&&!this.relativeTarget){const B=this.getClosestProjectingParent();B&&B.layout&&this.animationProgress!==1?(this.relativeParent=B,this.forceRelativeParentToResolveTarget(),this.relativeTarget=jo(),this.relativeTargetOrigin=jo(),uM(this.relativeTargetOrigin,this.layout.layoutBox,B.layout.layoutBox),DC(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=jo(),this.targetWithTransforms=jo()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),K$A(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):DC(this.target,this.layout.layoutBox),NhA(this.target,this.targetDelta)):DC(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const B=this.getClosestProjectingParent();B&&!!B.resumingFrom==!!this.resumingFrom&&!B.options.layoutScroll&&B.target&&this.animationProgress!==1?(this.relativeParent=B,this.forceRelativeParentToResolveTarget(),this.relativeTarget=jo(),this.relativeTargetOrigin=jo(),uM(this.relativeTargetOrigin,this.target,B.target),DC(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||T3(this.parent.latestValues)||MhA(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var Q;const o=this.getLead(),s=!!this.resumingFrom||this!==o;let a=!0;if((this.isProjectionDirty||(Q=this.parent)!=null&&Q.isProjectionDirty)&&(a=!1),s&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(a=!1),this.resolvedRelativeTargetAt===fa.timestamp&&(a=!1),a)return;const{layout:r,layoutId:I}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(r||I))return;DC(this.layoutCorrected,this.layout.layoutBox);const c=this.treeScale.x,l=this.treeScale.y;z7A(this.layoutCorrected,this.treeScale,this.path,s),o.layout&&!o.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(o.target=o.layout.layoutBox,o.targetWithTransforms=jo());const{target:B}=o;if(!B){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(itA(this.prevProjectionDelta.x,this.projectionDelta.x),itA(this.prevProjectionDelta.y,this.projectionDelta.y)),QM(this.projectionDelta,this.layoutCorrected,B,this.latestValues),(this.treeScale.x!==c||this.treeScale.y!==l||!CtA(this.projectionDelta.x,this.prevProjectionDelta.x)||!CtA(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",B))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(o=!0){var s;if((s=this.options.visualElement)==null||s.scheduleRender(),o){const a=this.getStack();a&&a.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=gm(),this.projectionDelta=gm(),this.projectionDeltaWithTransform=gm()}setAnimationOrigin(o,s=!1){const a=this.snapshot,r=a?a.latestValues:{},I={...this.latestValues},c=gm();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!s;const l=jo(),B=a?a.source:void 0,Q=this.layout?this.layout.source:void 0,h=B!==Q,d=this.getStack(),p=!d||d.members.length<=1,y=!!(h&&!p&&this.options.crossfade===!0&&!this.path.some(wAe));this.animationProgress=0;let m;this.mixTargetDelta=D=>{const S=D/1e3;EtA(c.x,o.x,S),EtA(c.y,o.y,S),this.setTargetDelta(c),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(uM(l,this.layout.layoutBox,this.relativeParent.layout.layoutBox),SAe(this.relativeTarget,this.relativeTargetOrigin,l,S),m&&IAe(this.relativeTarget,m)&&(this.isProjectionDirty=!1),m||(m=jo()),DC(m,this.relativeTarget)),h&&(this.animationValues=I,nAe(I,r,this.latestValues,S,y,p)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){var s,a,r;this.notifyListeners("animationStart"),(s=this.currentAnimation)==null||s.stop(),(r=(a=this.resumingFrom)==null?void 0:a.currentAnimation)==null||r.stop(),this.pendingAnimation&&(Bd(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Eo.update(()=>{NK.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=vS(0)),this.currentAnimation=$$A(this.motionValue,[0,1e3],{...o,velocity:0,isSync:!0,onUpdate:I=>{this.mixTargetDelta(I),o.onUpdate&&o.onUpdate(I)},onStop:()=>{},onComplete:()=>{o.onComplete&&o.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(lAe),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:s,target:a,layout:r,latestValues:I}=o;if(!(!s||!a||!r)){if(this!==o&&this.layout&&r&&XhA(this.options.animationType,this.layout.layoutBox,r.layoutBox)){a=this.target||jo();const c=Rr(this.layout.layoutBox.x);a.x.min=o.target.x.min,a.x.max=a.x.min+c;const l=Rr(this.layout.layoutBox.y);a.y.min=o.target.y.min,a.y.max=a.y.min+l}DC(s,a),nm(s,I),QM(this.projectionDeltaWithTransform,this.layoutCorrected,s,I)}}registerSharedNode(o,s){this.sharedNodes.has(o)||this.sharedNodes.set(o,new CAe),this.sharedNodes.get(o).add(s);const r=s.options.initialPromotionConfig;s.promote({transition:r?r.transition:void 0,preserveFollowOpacity:r&&r.shouldPreserveFollowOpacity?r.shouldPreserveFollowOpacity(s):void 0})}isLead(){const o=this.getStack();return o?o.lead===this:!0}getLead(){var s;const{layoutId:o}=this.options;return o?((s=this.getStack())==null?void 0:s.lead)||this:this}getPrevLead(){var s;const{layoutId:o}=this.options;return o?(s=this.getStack())==null?void 0:s.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:s,preserveFollowOpacity:a}={}){const r=this.getStack();r&&r.promote(this,a),o&&(this.projectionDelta=void 0,this.needsReset=!0),s&&this.setOptions({transition:s})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetSkewAndRotation(){const{visualElement:o}=this.options;if(!o)return;let s=!1;const{latestValues:a}=o;if((a.z||a.rotate||a.rotateX||a.rotateY||a.rotateZ||a.skewX||a.skewY)&&(s=!0),!s)return;const r={};a.z&&DY("z",o,r,this.animationValues);for(let I=0;I<yY.length;I++)DY(`rotate${yY[I]}`,o,r,this.animationValues),DY(`skew${yY[I]}`,o,r,this.animationValues);o.render();for(const I in r)o.setStaticValue(I,r[I]),this.animationValues&&(this.animationValues[I]=r[I]);o.scheduleRender()}applyProjectionStyles(o,s){if(!this.instance||this.isSVG)return;if(!this.isVisible){o.visibility="hidden";return}const a=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,o.visibility="",o.opacity="",o.pointerEvents=MK(s==null?void 0:s.pointerEvents)||"",o.transform=a?a(this.latestValues,""):"none";return}const r=this.getLead();if(!this.projectionDelta||!this.layout||!r.target){this.options.layoutId&&(o.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,o.pointerEvents=MK(s==null?void 0:s.pointerEvents)||""),this.hasProjected&&!Wh(this.latestValues)&&(o.transform=a?a({},""):"none",this.hasProjected=!1);return}o.visibility="";const I=r.animationValues||r.latestValues;this.applyTransformsToTarget();let c=cAe(this.projectionDeltaWithTransform,this.treeScale,I);a&&(c=a(I,c)),o.transform=c;const{x:l,y:B}=this.projectionDelta;o.transformOrigin=`${l.origin*100}% ${B.origin*100}% 0`,r.animationValues?o.opacity=r===this?I.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:I.opacityExit:o.opacity=r===this?I.opacity!==void 0?I.opacity:"":I.opacityExit!==void 0?I.opacityExit:0;for(const Q in fN){if(I[Q]===void 0)continue;const{correct:h,applyTo:d,isCSSVariable:p}=fN[Q],y=c==="none"?I[Q]:h(I[Q],r);if(d){const m=d.length;for(let D=0;D<m;D++)o[d[D]]=y}else p?this.options.visualElement.renderState.vars[Q]=y:o[Q]=y}this.options.layoutId&&(o.pointerEvents=r===this?MK(s==null?void 0:s.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(o=>{var s;return(s=o.currentAnimation)==null?void 0:s.stop()}),this.root.nodes.forEach(ctA),this.root.sharedNodes.clear()}}}function EAe(e){e.updateLayout()}function QAe(e){var t;const A=((t=e.resumeFrom)==null?void 0:t.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&A&&e.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:n}=e.layout,{animationType:g}=e.options,o=A.source!==e.layout.source;g==="size"?MC(c=>{const l=o?A.measuredBox[c]:A.layoutBox[c],B=Rr(l);l.min=i[c].min,l.max=l.min+B}):XhA(g,A.layoutBox,i)&&MC(c=>{const l=o?A.measuredBox[c]:A.layoutBox[c],B=Rr(i[c]);l.max=l.min+B,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[c].max=e.relativeTarget[c].min+B)});const s=gm();QM(s,i,A.layoutBox);const a=gm();o?QM(a,e.applyTransform(n,!0),A.measuredBox):QM(a,i,A.layoutBox);const r=!zhA(s);let I=!1;if(!e.resumeFrom){const c=e.getClosestProjectingParent();if(c&&!c.resumeFrom){const{snapshot:l,layout:B}=c;if(l&&B){const Q=jo();uM(Q,A.layoutBox,l.layoutBox);const h=jo();uM(h,i,B.layoutBox),ZhA(Q,h)||(I=!0),c.options.layoutRoot&&(e.relativeTarget=h,e.relativeTargetOrigin=Q,e.relativeParent=c)}}}e.notifyListeners("didUpdate",{layout:i,snapshot:A,delta:a,layoutDelta:s,hasLayoutChanged:r,hasRelativeLayoutChanged:I})}else if(e.isLead()){const{onExitComplete:i}=e.options;i&&i()}e.options.transition=void 0}function uAe(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function dAe(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function hAe(e){e.clearSnapshot()}function ctA(e){e.clearMeasurements()}function ltA(e){e.isLayoutDirty=!1}function pAe(e){const{visualElement:A}=e.options;A&&A.getProps().onBeforeLayoutMeasure&&A.notify("BeforeLayoutMeasure"),e.resetTransform()}function BtA(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function fAe(e){e.resolveTargetDelta()}function yAe(e){e.calcProjection()}function DAe(e){e.resetSkewAndRotation()}function mAe(e){e.removeLeadSnapshot()}function EtA(e,A,t){e.translate=wo(A.translate,0,t),e.scale=wo(A.scale,1,t),e.origin=A.origin,e.originPoint=A.originPoint}function QtA(e,A,t,i){e.min=wo(A.min,t.min,i),e.max=wo(A.max,t.max,i)}function SAe(e,A,t,i){QtA(e.x,A.x,t.x,i),QtA(e.y,A.y,t.y,i)}function wAe(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const kAe={duration:.45,ease:[.4,0,.1,1]},utA=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),dtA=utA("applewebkit/")&&!utA("chrome/")?Math.round:ec;function htA(e){e.min=dtA(e.min),e.max=dtA(e.max)}function MAe(e){htA(e.x),htA(e.y)}function XhA(e,A,t){return e==="position"||e==="preserve-aspect"&&!v$A(ItA(A),ItA(t),.2)}function NAe(e){var A;return e!==e.root&&((A=e.scroll)==null?void 0:A.wasRoot)}const RAe=VhA({attachResizeListener:(e,A)=>yN(e,"resize",A),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),mY={current:void 0},$hA=VhA({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!mY.current){const e=new RAe({});e.mount(window),e.setOptions({layoutScroll:!0}),mY.current=e}return mY.current},resetTransform:(e,A)=>{e.style.transform=A!==void 0?A:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),GAe={pan:{Feature:Z$A},drag:{Feature:z$A,ProjectionNode:$hA,MeasureLayout:OhA}};function ptA(e,A,t){const{props:i}=e;e.animationState&&i.whileHover&&e.animationState.setActive("whileHover",t==="Start");const n="onHover"+t,g=i[n];g&&Eo.postRender(()=>g(A,ZR(A)))}class bAe extends Jd{mount(){const{current:A}=this.node;A&&(this.unmount=g7A(A,(t,i)=>(ptA(this.node,i,"Start"),n=>ptA(this.node,n,"End"))))}unmount(){}}class UAe extends Jd{constructor(){super(...arguments),this.isActive=!1}onFocus(){let A=!1;try{A=this.node.current.matches(":focus-visible")}catch{A=!0}!A||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=PR(yN(this.node.current,"focus",()=>this.onFocus()),yN(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function ftA(e,A,t){const{props:i}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&i.whileTap&&e.animationState.setActive("whileTap",t==="Start");const n="onTap"+(t==="End"?"":t),g=i[n];g&&Eo.postRender(()=>g(A,ZR(A)))}class vAe extends Jd{mount(){const{current:A}=this.node;A&&(this.unmount=r7A(A,(t,i)=>(ftA(this.node,i,"Start"),(n,{success:g})=>ftA(this.node,n,g?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const j3=new WeakMap,SY=new WeakMap,KAe=e=>{const A=j3.get(e.target);A&&A(e)},FAe=e=>{e.forEach(KAe)};function _Ae({root:e,...A}){const t=e||document;SY.has(t)||SY.set(t,{});const i=SY.get(t),n=JSON.stringify(A);return i[n]||(i[n]=new IntersectionObserver(FAe,{root:e,...A})),i[n]}function JAe(e,A,t){const i=_Ae(A);return j3.set(e,t),i.observe(e),()=>{j3.delete(e),i.unobserve(e)}}const LAe={some:0,all:1};class xAe extends Jd{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:A={}}=this.node.getProps(),{root:t,margin:i,amount:n="some",once:g}=A,o={root:t?t.current:void 0,rootMargin:i,threshold:typeof n=="number"?n:LAe[n]},s=a=>{const{isIntersecting:r}=a;if(this.isInView===r||(this.isInView=r,g&&!r&&this.hasEnteredView))return;r&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",r);const{onViewportEnter:I,onViewportLeave:c}=this.node.getProps(),l=r?I:c;l&&l(a)};return JAe(this.node.current,o,s)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:A,prevProps:t}=this.node;["amount","margin","root"].some(TAe(A,t))&&this.startObserver()}unmount(){}}function TAe({viewport:e={}},{viewport:A={}}={}){return t=>e[t]!==A[t]}const qAe={inView:{Feature:xAe},tap:{Feature:vAe},focus:{Feature:UAe},hover:{Feature:bAe}},YAe={layout:{ProjectionNode:$hA,MeasureLayout:OhA}},HAe={...M$A,...qAe,...GAe,...YAe},XI=O7A(HAe,i$A);function OAe(){!fZ.current&&GhA();const[e]=E.useState(u_.current);return e}const PAe="_panelRoot_cg615_1",jAe="_crapsPlaceTile_cg615_43",zAe="_mobileShow_cg615_64",ZAe="_mobileHide_cg615_68",WAe="_spotBtn_cg615_95",VAe="_spotRow_cg615_108",XAe="_actions_cg615_120",$Ae="_actionBtn_cg615_124",Aee="_amountBadge_cg615_130",eee="_badgeMinus_cg615_137",tee="_crapsStatusBar_cg615_148",iee="_crapsStatusText_cg615_154",nee="_crapsHighlight_cg615_162",gee="_crapsPlaceRow_cg615_179",oee="_crapsBetTile_cg615_190",see="_crapsActionsBar_cg615_198",aee="_crapsActionButton_cg615_202",ree="_crapsActionButtonPrimary_cg615_207",Iee="_crapsActionButtonSecondary_cg615_208",Cee="_crapsMainBets_cg615_214",cee="_disabled_cg615_334",lee="_spotBtnTopRow_cg615_520",Bee="_lineWin_cg615_571",Eee="_lineLose_cg615_576",Qee="_linePush_cg615_581",uee="_outcomeBadge_cg615_586",dee="_locked_cg615_600",hee="_amountBadgeDisabled_cg615_628",pee="_lockIcon_cg615_634",fee="_aggBadge_cg615_674",yee="_rollBtn_cg615_890",Dee="_rollIcon_cg615_897",mee="_clear_cg615_923",See="_errorLive_cg615_940",wee="_tooltip_cg615_948",kee="_betInfoBtn_cg615_972",Mee="_betInfoModalOverlay_cg615_1000",Nee="_betInfoModal_cg615_1000",Ree="_betInfoHeader_cg615_1034",Gee="_betInfoClose_cg615_1050",bee="_betInfoContent_cg615_1071",Uee="_betInfoItem_cg615_1079",vee="_shake_cg615_1165",Kee="_attnHalo_cg615_1213",Fee="_crapsAtsLabel_cg615_1335",_ee="_crapsIronCrossBtn_cg615_1355",Jee="_crapsMinusBadge_cg615_1470",Lee="_rollHaloActive_cg615_1657",xee="_crapsClearIcon_cg615_1770",Tee="_particle_cg615_1804",qee="_particleContainer_cg615_1810",Yee="_floatingWinAmount_cg615_1860",Hee="_countdownBadge_cg615_1975",Oee="_countdownUrgent_cg615_1998",Pee="_countdownCritical_cg615_2005",jee="_chipPickerWrapper_cg615_2329",zee="_chipPickerToggle_cg615_2334",Zee="_chipPickerToggleOpen_cg615_2377",Wee="_chipPickerChip_cg615_2387",Vee="_chipPickerDropdown_cg615_2391",Xee="_chipPickerOption_cg615_2413",$ee="_chipPickerOptionSelected_cg615_2422",Ate="_chipPickerChipSelected_cg615_2426",ete="_crapsAtsSection_cg615_2446",wt={panelRoot:PAe,crapsPlaceTile:jAe,mobileShow:zAe,mobileHide:ZAe,spotBtn:WAe,spotRow:VAe,actions:XAe,actionBtn:$Ae,amountBadge:Aee,badgeMinus:eee,crapsStatusBar:tee,crapsStatusText:iee,crapsHighlight:nee,crapsPlaceRow:gee,crapsBetTile:oee,crapsActionsBar:see,crapsActionButton:aee,crapsActionButtonPrimary:ree,crapsActionButtonSecondary:Iee,crapsMainBets:Cee,disabled:cee,spotBtnTopRow:lee,lineWin:Bee,lineLose:Eee,linePush:Qee,outcomeBadge:uee,locked:dee,amountBadgeDisabled:hee,lockIcon:pee,aggBadge:fee,rollBtn:yee,rollIcon:Dee,clear:mee,errorLive:See,tooltip:wee,betInfoBtn:kee,betInfoModalOverlay:Mee,betInfoModal:Nee,betInfoHeader:Ree,betInfoClose:Gee,betInfoContent:bee,betInfoItem:Uee,shake:vee,attnHalo:Kee,crapsAtsLabel:Fee,crapsIronCrossBtn:_ee,crapsMinusBadge:Jee,rollHaloActive:Lee,crapsClearIcon:xee,particle:Tee,particleContainer:qee,floatingWinAmount:Yee,countdownBadge:Hee,countdownUrgent:Oee,countdownCritical:Pee,chipPickerWrapper:jee,chipPickerToggle:zee,chipPickerToggleOpen:Zee,chipPickerChip:Wee,chipPickerDropdown:Vee,chipPickerOption:Xee,chipPickerOptionSelected:$ee,chipPickerChipSelected:Ate,crapsAtsSection:ete},tte={pass:{title:"Pass Line",description:"Come-out wins 7/11, loses 2/3/12; point wins if repeated before 7. Pays 1:1."},dontPass:{title:"Don't Pass",description:"Come-out wins 2/3, loses 7/11, 12 pushes; after point, win if 7 before point. Pays 1:1."},come:{title:"Come Bet",description:"Like Pass but placed after point; next roll can establish its own point. Pays 1:1."},dontCome:{title:"Don't Come",description:"Mirror of Come but against shooter; 2/3 win, 7/11 lose, 12 push on first resolving roll. Pays 1:1."},oddsPass:{title:"Odds (Pass)",description:"True odds – 4/10 2:1, 5/9 3:2, 6/8 6:5. Pays on point hit (no house edge)."},oddsDontPass:{title:"Odds (Don't Pass)",description:"True odds inverse – 4/10 1:2, 5/9 2:3, 6/8 5:6. Pays if 7 before point."},place4:{title:"Place 4",description:"Active in point phase. Pays 9:5 if 4 rolls before 7 (principal stays)."},place5:{title:"Place 5",description:"Pays 7:5 if 5 rolls before 7."},place6:{title:"Place 6",description:"Pays 7:6 if 6 rolls before 7."},place8:{title:"Place 8",description:"Pays 7:6 if 8 rolls before 7."},place9:{title:"Place 9",description:"Pays 7:5 if 9 rolls before 7."},place10:{title:"Place 10",description:"Pays 9:5 if 10 rolls before 7."},field:{title:"Field",description:"One-roll bet: Wins 2,3,4,9,10,11,12 (12 often double). Loses 5,6,7,8."},big6:{title:"Big 6",description:"Even money if 6 rolls before 7 (same goal as place/line odds but lower value)."},big8:{title:"Big 8",description:"Even money if 8 rolls before 7."},atsSmall:{title:"ATS Small",description:"Wins when all of 2,3,4,5,6 are rolled before a 7. Pays 30:1."},atsTall:{title:"ATS Tall",description:"Wins when all of 8,9,10,11,12 are rolled before a 7. Pays 30:1."},atsAll:{title:"ATS All",description:"Wins when all numbers (2-6 and 8-12) are rolled before a 7. Pays 150:1."}};function ite({open:e,onClose:A}){const t=E.useRef(null);if(E.useEffect(()=>{if(!e)return;const n=o=>{o.key==="Escape"&&A()},g=o=>{t.current&&!t.current.contains(o.target)&&A()};return document.addEventListener("keydown",n),document.addEventListener("mousedown",g),()=>{document.removeEventListener("keydown",n),document.removeEventListener("mousedown",g)}},[e,A]),!e)return null;const i=C.jsx("div",{className:wt.betInfoModalOverlay,role:"presentation",children:C.jsxs("div",{className:wt.betInfoModal,role:"dialog","aria-modal":"true","aria-label":"Craps Bet Guide",ref:t,children:[C.jsxs("div",{className:wt.betInfoHeader,children:[C.jsx("h3",{children:"Craps Bet Guide"}),C.jsx("button",{className:wt.betInfoClose,onClick:A,"aria-label":"Close",children:"✕"})]}),C.jsx("div",{className:wt.betInfoContent,children:Object.entries(tte).map(([n,{title:g,description:o}])=>C.jsxs("div",{className:wt.betInfoItem,children:[C.jsx("strong",{children:g}),C.jsx("p",{children:o})]},n))})]})});return er.createPortal(i,document.body)}const nte="_atsProgressContainer_bok0p_3",gte="_inline_bok0p_15",ote="_atsSection_bok0p_25",ste="_complete_bok0p_42",ate="_justCompleted_bok0p_47",rte="_atsSectionAll_bok0p_66",Ite="_atsSectionHeader_bok0p_75",Cte="_atsSectionLabel_bok0p_84",cte="_atsSectionCount_bok0p_97",lte="_atsNumberRow_bok0p_107",Bte="_atsNumber_bok0p_107",Ete="_hit_bok0p_138",Qte="_atsCompleteText_bok0p_160",ute="_atsLockedBadge_bok0p_181",Dg={atsProgressContainer:nte,inline:gte,atsSection:ote,complete:ste,justCompleted:ate,atsSectionAll:rte,atsSectionHeader:Ite,atsSectionLabel:Cte,atsSectionCount:cte,atsNumberRow:lte,atsNumber:Bte,hit:Ete,atsCompleteText:Qte,atsLockedBadge:ute},dte=[2,3,4,5,6],hte=[8,9,10,11,12];function pte({hitNumbers:e,smallProgress:A,tallProgress:t,allProgress:i,betsLocked:n,lastCompletedCategory:g,inline:o=!1}){const s=c=>e.includes(c),a=A===5,r=t===5,I=i===10;return C.jsxs("div",{className:`${Dg.atsProgressContainer} ${o?Dg.inline:""}`,children:[C.jsxs("div",{className:`${Dg.atsSection} ${a?Dg.complete:""} ${g==="small"?Dg.justCompleted:""}`,children:[C.jsxs("div",{className:Dg.atsSectionHeader,children:[C.jsx("span",{className:Dg.atsSectionLabel,children:"SMALL"}),C.jsxs("span",{className:Dg.atsSectionCount,children:[A,"/5"]})]}),C.jsx("div",{className:Dg.atsNumberRow,children:dte.map(c=>C.jsx("div",{className:`${Dg.atsNumber} ${s(c)?Dg.hit:""}`,"aria-label":`${c} ${s(c)?"hit":"not hit"}`,children:c},c))})]}),C.jsxs("div",{className:`${Dg.atsSection} ${Dg.atsSectionAll} ${I?Dg.complete:""} ${g==="all"?Dg.justCompleted:""}`,children:[C.jsxs("div",{className:Dg.atsSectionHeader,children:[C.jsx("span",{className:Dg.atsSectionLabel,children:"ALL"}),C.jsxs("span",{className:Dg.atsSectionCount,children:[i,"/10"]})]}),I&&C.jsx("div",{className:Dg.atsCompleteText,children:"🎉"}),n&&!I&&C.jsx("div",{className:Dg.atsLockedBadge,children:"LOCKED"})]}),C.jsxs("div",{className:`${Dg.atsSection} ${r?Dg.complete:""} ${g==="tall"?Dg.justCompleted:""}`,children:[C.jsxs("div",{className:Dg.atsSectionHeader,children:[C.jsx("span",{className:Dg.atsSectionLabel,children:"TALL"}),C.jsxs("span",{className:Dg.atsSectionCount,children:[t,"/5"]})]}),C.jsx("div",{className:Dg.atsNumberRow,children:hte.map(c=>C.jsx("div",{className:`${Dg.atsNumber} ${s(c)?Dg.hit:""}`,"aria-label":`${c} ${s(c)?"hit":"not hit"}`,children:c},c))})]})]})}const Gl={PROGRESS:"craps:ats_progress",SMALL_COMPLETE:"craps:ats_small_complete",TALL_COMPLETE:"craps:ats_tall_complete",ALL_COMPLETE:"craps:ats_all_complete",RESET:"craps:ats_reset"},wY={hitNumbers:[],smallProgress:0,tallProgress:0,allProgress:0,betsLocked:!1};function fte(e){const A=Ms(),[t,i]=E.useState(wY),[n,g]=E.useState(null);E.useEffect(()=>{if(!n)return;const s=setTimeout(()=>g(null),3e3);return()=>clearTimeout(s)},[n]),E.useEffect(()=>{if(!A||!e)return;const s=l=>{console.log("[useCrapsAts] Received ATS progress:",l,"current roomId:",e),l.roomId===e&&i({hitNumbers:l.hitNumbers,smallProgress:l.smallProgress,tallProgress:l.tallProgress,allProgress:l.allProgress,betsLocked:l.betsLocked})},a=l=>{l.roomId===e&&g("small")},r=l=>{l.roomId===e&&g("tall")},I=l=>{l.roomId===e&&g("all")},c=l=>{l.roomId===e&&(i(wY),g(null))};return A.on(Gl.PROGRESS,s),A.on(Gl.SMALL_COMPLETE,a),A.on(Gl.TALL_COMPLETE,r),A.on(Gl.ALL_COMPLETE,I),A.on(Gl.RESET,c),()=>{A.off(Gl.PROGRESS,s),A.off(Gl.SMALL_COMPLETE,a),A.off(Gl.TALL_COMPLETE,r),A.off(Gl.ALL_COMPLETE,I),A.off(Gl.RESET,c)}},[A,e]);const o=E.useCallback(s=>t.hitNumbers.includes(s),[t.hitNumbers]);return{atsProgress:t,lastCompletedCategory:n,isNumberHit:o,reset:()=>i(wY)}}const om=e=>`z${e.toLocaleString(void 0,{maximumFractionDigits:0})}`;function Vc({value:e,onAdd:A,onClear:t,disabled:i,selectedTimes:n=0,style:g,mini:o=!1,className:s,hideValue:a=!1}){const r=n>0,c=["casino-chip",`chip--v${e>=5e3?5e3:e>=1e3?1e3:e>=500?500:e>=100?100:e>=25?25:e>=10?10:e>=5?5:1}`,i?"is-disabled":"",r?"is-selected":"",o?"chip-container--mini":"",s||""].filter(Boolean).join(" "),l=!!A&&!i;return C.jsxs("div",{style:g,className:"chip-container",children:[C.jsxs("button",{type:"button",className:c,onClick:l?()=>{A==null||A(e)}:void 0,disabled:!l,"aria-label":`Add ${om(Number(e))}`,title:`Add ${om(Number(e))}`,style:l?void 0:{pointerEvents:"none"},children:[!a&&C.jsx("span",{className:"chip__value",children:e>=1e3?`${(Number(e)/1e3).toLocaleString(void 0,{maximumFractionDigits:e>=1e4?0:1})}k`:e}),r&&l&&C.jsxs("span",{className:"chip__count",children:["×",n]})]}),r&&l&&!!t&&C.jsx("button",{type:"button",className:"chip-clear","aria-label":`Clear ${om(Number(e))} chip`,title:`Clear ${om(Number(e))} chip`,onClick:B=>{B.stopPropagation(),t(e)},children:"×"})]})}function Da(e){return`z${e}`}function LC(e,A){return e.filter(t=>t.type===A).reduce((t,i)=>t+i.amount,0)}function yte(e,A){return e*A}function ytA(e,A,t){const{phase:i,point:n,balance:g,pendingBets:o,minBet:s,maxBet:a,oddsMultiple:r,committedAddBack:I=0}=t,c=o.reduce((D,S)=>D+S.amount,0),l=LC(o,e),B=c+A,Q=g+I;if(B>Q)return{ok:!1,reason:"Insufficient balance"};const h=e==="pass"||e==="dontPass",d=e==="come"||e==="dontCome",p=e==="oddsPass"||e==="oddsDontPass",y=e.startsWith("place");if(h){if(i!=="comeOut"&&n)return{ok:!1,reason:"Line bets locked after point"};if(l===0&&A<s)return{ok:!1,reason:`Minimum ${Da(s)}`}}if(d){if(!n)return{ok:!1,reason:"Come bets only after point"};if(l===0&&A<s)return{ok:!1,reason:`Minimum ${Da(s)}`};if(l+A>a)return{ok:!1,reason:`Max ${Da(a)}`}}if(p){if(!n)return{ok:!1,reason:"Point required for odds"};const S=LC(o,e==="oddsPass"?"pass":"dontPass");if(!S)return{ok:!1,reason:"Need line bet first"};const k=yte(S,e==="oddsPass"?r.pass:r.dontPass);if(l+A>k)return{ok:!1,reason:`Max odds ${Da(k)}`}}if(y){if(!n)return{ok:!1,reason:"Place bets only in point phase"};if(l===0&&A<s)return{ok:!1,reason:`Minimum ${Da(s)}`};if(l+A>a)return{ok:!1,reason:`Max ${Da(a)}`}}if(e==="field"||e==="big6"||e==="big8"){if(l===0&&A<s)return{ok:!1,reason:`Minimum ${Da(s)}`};if(l+A>a)return{ok:!1,reason:`Max ${Da(a)}`}}if(e==="atsSmall"||e==="atsTall"||e==="atsAll"){if(l===0&&A<s)return{ok:!1,reason:`Minimum ${Da(s)}`};if(l+A>a)return{ok:!1,reason:`Max ${Da(a)}`}}return{ok:!0}}const Dte=[{key:"pass",label:"Pass"},{key:"dontPass",label:"Don't Pass"},{key:"come",label:"Come"},{key:"dontCome",label:"Don't Come"},{key:"field",label:"Field"},{key:"big6",label:"Big 6"},{key:"big8",label:"Big 8"}],mte=[{key:"atsSmall",label:"Small"},{key:"atsTall",label:"Tall"},{key:"atsAll",label:"All"}],Ste=[{key:"place4",label:"Place 4"},{key:"place5",label:"5"},{key:"place6",label:"6"},{key:"place8",label:"8"},{key:"place9",label:"9"},{key:"place10",label:"10"}];function wte(e,A){const[t,i]=E.useState(25);return E.useEffect(()=>{if(e.length&&!e.includes(t)){const n=e[0];i(n);return}},[e,t]),{selectedChip:t,setSelectedChip:i}}function kte(e){const{pendingBets:A,myPlayerPlaceTotal:t,myCommittedByType:i}=e;return E.useMemo(()=>typeof t=="number"&&t>0||["place4","place5","place6","place8","place9","place10"].some(g=>Number(i[g]||0)>0)?!0:A.some(g=>g.type.startsWith("place")&&g.amount>0),[t,A,i])}function Mte(e,A,t){const i=E.useRef(null);E.useEffect(()=>{A!==i.current&&(i.current=null)},[A]),E.useEffect(()=>{if(!e||!A||i.current===A)return;const n=t.current||document.querySelector(`.${wt.crapsPlaceRow}`),g=n?n.querySelector(`.${wt.crapsIronCrossBtn}`):document.querySelector(`.${wt.crapsIronCrossBtn}`);if(!g)return;const o=window.setTimeout(()=>{try{g.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})}catch{}},50);return i.current=A,()=>window.clearTimeout(o)},[e,A,t])}function Nte(e,A){const t=E.useRef(null);E.useEffect(()=>{if(!e){t.current=null;return}if(t.current===e)return;const i=A.current||document.querySelector(`.${wt.crapsPlaceRow}`),n=i?i.querySelector(`.${wt.crapsAtsLabel}`):document.querySelector(`.${wt.crapsAtsLabel}`);if(!n)return;const g=window.setTimeout(()=>{try{n.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})}catch{}},100);return t.current=e,()=>window.clearTimeout(g)},[e,A])}function Rte(e,A,t){const i=E.useRef(null);E.useEffect(()=>{if(!e||i.current===e)return;i.current=e;const n=window.setTimeout(()=>{const g=A.current||document.querySelector(`.${wt.crapsMainBets}`),o=t.current||document.querySelector(`.${wt.crapsPlaceRow}`),s=(a,r)=>{if(!a)return;const I=a.scrollWidth,c=a.clientWidth;I<=c||window.setTimeout(()=>{a.scrollTo({left:I,behavior:"smooth"}),window.setTimeout(()=>{a.scrollTo({left:0,behavior:"smooth"})},600)},r)};s(g,0),s(o,150)},500);return()=>window.clearTimeout(n)},[e,A,t])}function Gte(e){const{phase:A,point:t,balance:i,pendingBets:n,minBet:g,maxBet:o,oddsMultiple:s,myPlayerLineTotals:a,myPlayerPlaceTotal:r}=e;return E.useMemo(()=>{const I=((a==null?void 0:a.pass)??0)+((a==null?void 0:a.dontPass)??0)+(r??0),c=LC(n,"pass")+LC(n,"dontPass")+LC(n,"place4")+LC(n,"place5")+LC(n,"place6")+LC(n,"place8")+LC(n,"place9")+LC(n,"place10"),l=Math.max(0,c-I);return{phase:A,point:t,balance:i,pendingBets:n,minBet:g,maxBet:o,oddsMultiple:s,committedAddBack:I+l}},[A,t,i,n,g,o,s,a==null?void 0:a.pass,a==null?void 0:a.dontPass,r])}function bte(e,A){return E.useCallback(t=>{const i=e.find(g=>g.type===t),n=Number(A[t]||0);return i?i.amount===n?n:Math.max(0,i.amount):Math.max(0,n)},[e,A])}function Ute(e,A,t){const i=E.useRef(new Map),n=5e3;E.useEffect(()=>{if(!e.length){i.current.clear();return}const g=Date.now();for(const a of e){const r=`${a.type}:${a.amount}`;i.current.has(r)||i.current.set(r,g)}const o=new Set(e.map(a=>`${a.type}:${a.amount}`));for(const a of i.current.keys())o.has(a)||i.current.delete(a);const s=e.filter(a=>{const r=Number(A[a.type]||0);if(a.amount===0&&r>0)return!0;if(a.amount===r)return!1;const I=`${a.type}:${a.amount}`,c=i.current.get(I)||g;return g-c>n?(console.warn("[CrapsBettingPanel] Pruning stuck pending bet (timeout)",{type:a.type,amount:a.amount,committed:r}),!1):!0});s.length!==e.length&&t(s)},[e,A,t])}function vte(e){const{recentSettlements:A,meId:t,myPlayerLineTotals:i}=e,n=E.useMemo(()=>{if(!A.length||!t)return{};const r=A.filter(c=>(c.betType==="pass"||c.betType==="dontPass")&&c.playerId===t),I={};for(const c of r)(c.betType==="pass"?((i==null?void 0:i.pass)??0)>0:((i==null?void 0:i.dontPass)??0)>0)&&(I[c.betType]=c.outcome);return I},[A,t,i==null?void 0:i.pass,i==null?void 0:i.dontPass]),g=E.useMemo(()=>{if(!A.length||!t)return{};const r=A.filter(c=>c.betType.startsWith("place")&&c.playerId===t),I={};for(const c of r)I[c.betType]=c.outcome;return I},[A,t]),o=E.useMemo(()=>{if(!A.length||!t)return{};const r=A.filter(c=>c.betType==="field"&&c.playerId===t),I={};for(const c of r)I[c.betType]=c.outcome;return I},[A,t]),s=E.useMemo(()=>{if(!A.length||!t)return{};const r=A.filter(c=>(c.betType==="big6"||c.betType==="big8")&&c.playerId===t),I={};for(const c of r)I[c.betType]=c.outcome;return I},[A,t]),a=E.useMemo(()=>{if(!A.length||!t)return{};const r=A.filter(c=>(c.betType==="come"||c.betType==="dontCome")&&c.playerId===t),I={};for(const c of r)I[c.betType]=c.outcome;return I},[A,t]);return{lineOutcomeMap:n,placeOutcomeMap:g,fieldOutcomeMap:o,bigOutcomeMap:s,comeOutcomeMap:a}}function Kte(e,A){E.useEffect(()=>{const t=document.querySelectorAll(e),i=[];return t.forEach(n=>{if(n.querySelector(`.${wt.particleContainer}`))return;const g=document.createElement("div");g.className=wt.particleContainer,n.appendChild(g);const o=()=>{const a=document.createElement("div");a.className=wt.particle;const r=Math.random()*100,I=(Math.random()-.5)*40,c=-(80+Math.random()*60),l=1.8+Math.random()*1,B=Math.random()*.3;a.style.setProperty("--start-x",`${r}%`),a.style.setProperty("--drift-x",`${I}px`),a.style.setProperty("--rise-y",`${c}px`),a.style.setProperty("--duration",`${l}s`),a.style.setProperty("--delay",`${B}s`),a.style.left="0",a.style.bottom="0",g.appendChild(a),window.setTimeout(()=>a.remove(),(l+B)*1e3)},s=window.setInterval(o,400+Math.random()*300);i.push(s),o(),window.setTimeout(o,150),window.setTimeout(o,300)}),()=>{i.forEach(n=>window.clearInterval(n)),t.forEach(n=>{var g;return(g=n.querySelector(`.${wt.particleContainer}`))==null?void 0:g.remove()})}},[e,A])}function Fte(e){const{recentSettlements:A,meId:t,winSelector:i,floatingClass:n}=e,g=E.useRef(new Set),o=E.useRef(0);E.useEffect(()=>{if(A.length===0&&o.current>0&&g.current.clear(),o.current=A.length,!A.length||!t)return;const a=A.map((I,c)=>({s:I,idx:c})).filter(({s:I})=>I.playerId===t&&I.outcome==="WIN"&&I.payout>0).filter(({s:I,idx:c})=>{const l=`${I.betType}|${I.amount}|${I.payout}|${c}`;return g.current.has(l)?!1:(g.current.add(l),!0)});if(!a.length)return;const r=window.setTimeout(()=>{const I={};a.forEach(({s:l})=>{I[l.betType]=l.payout}),document.querySelectorAll(i).forEach(l=>{const B=l.getAttribute("data-bet-type");if(!B)return;const Q=I[B];if(!Q)return;try{l.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})}catch{}const h=()=>{const d=l.getBoundingClientRect(),p=document.createElement("div");p.className=n,p.textContent=`+${Da(Q)}`,p.style.left=`${d.left+d.width/2}px`,p.style.top=`${d.top}px`,document.body.appendChild(p),window.setTimeout(()=>p.remove(),2500)};B.startsWith("place")?window.setTimeout(h,500):h()})},50);return()=>window.clearTimeout(r)},[A,t,i,n])}function ApA(e){const{roomId:A,balance:t,phase:i,point:n,shooterName:g,minBet:o,maxBet:s,oddsMultiple:a,chips:r,pendingBets:I,onChangeBets:c,onClearAll:l,disabled:B,onRoll:Q,canRoll:h,myPlayerPlaceTotal:d,readyPlayers:p=[],meId:y,onBetDelta:m,onBetsBatch:D,showReadyButton:S,onReadyClick:k,readyStateLabel:N,readyButtonDisabled:G,countdownSeconds:M=0,recentSettlements:w=[],myPlayerLineTotals:b,othersTotals:_,myCommittedByType:K={},onPassTurn:J,canPassTurn:q,onChargeChange:v}=e,U=B,{selectedChip:x,setSelectedChip:T}=wte(r),{atsProgress:z,lastCompletedCategory:Z}=fte(A??null),[eA,aA]=E.useState(!1),[sA,pA]=E.useState(),[gA,yA]=E.useState(),{info:fA}=JL(),RA=E.useRef(!1),qA=E.useRef(null),W=E.useRef(0),$=50,L=$/1200,H=i==="comeOut"&&!n,P=i==="point"&&!!n,tA=!1,iA=E.useRef(null),oA=E.useRef(null),IA=E.useRef(null),CA=E.useRef(z.betsLocked),_A=kte({pendingBets:I,myPlayerPlaceTotal:d,myCommittedByType:K}),uA=i==="point"&&!!n&&!_A;Mte(uA,n,oA),Nte(Z,oA),Rte(A,iA,oA),E.useEffect(()=>{const ke=CA.current,nt=z.betsLocked;CA.current=nt,ke!==nt&&(nt&&IA.current?IA.current.scrollTo({left:IA.current.scrollWidth,behavior:"smooth"}):!nt&&IA.current&&IA.current.scrollTo({left:0,behavior:"smooth"}))},[z.betsLocked]);const X=E.useCallback(()=>{RA.current||(RA.current=!0,On(),W.current=0,v==null||v(0),qA.current&&clearInterval(qA.current),qA.current=setInterval(()=>{W.current=Math.min(1,W.current+L),v==null||v(W.current),W.current>=.95?ti("Heavy"):W.current>=.6?ti("Medium"):W.current>=.25&&ti("Light")},$))},[v]),O=E.useCallback(()=>{if(RA.current){if(RA.current=!1,qA.current&&(clearInterval(qA.current),qA.current=null),W.current=0,v==null||v(0),i==="point"&&!_A)try{fA("No Place bet","Add a Place bet (e.g., 6 or 8) before rolling")}catch{}Q==null||Q()}},[i,_A,fA,Q,v]),cA=Gte({phase:i,point:n,balance:t,pendingBets:I,minBet:o,maxBet:s,oddsMultiple:a,myPlayerLineTotals:b,myPlayerPlaceTotal:d}),wA=bte(I,K);Ute(I,K,c);const xA=E.useMemo(()=>{const ke=LC(I,"pass")>0||LC(I,"dontPass")>0,nt=((b==null?void 0:b.pass)??0)>0||((b==null?void 0:b.dontPass)??0)>0,Ut=wA("pass")>0||wA("dontPass")>0;return ke||nt||Ut},[I,b==null?void 0:b.pass,b==null?void 0:b.dontPass,wA]),{lineOutcomeMap:YA,placeOutcomeMap:jA,fieldOutcomeMap:ie,bigOutcomeMap:he,comeOutcomeMap:le}=vte({recentSettlements:w,meId:y,myPlayerLineTotals:b}),NA=E.useMemo(()=>`.${wt.spotBtn}[data-win-outcome="true"]`,[]),EA=E.useMemo(()=>JSON.stringify({lineOutcomeMap:YA,placeOutcomeMap:jA,fieldOutcomeMap:ie,bigOutcomeMap:he,comeOutcomeMap:le}),[YA,jA,ie,he,le]);Kte(NA,EA),Fte({recentSettlements:w,meId:y,winSelector:NA,floatingClass:wt.floatingWinAmount});const PA=E.useMemo(()=>{const ke=new Set;for(const nt of I){const Ut=Number(K[nt.type]||0);nt.amount!==Ut&&ke.add(nt.type)}return ke},[I,K]),ZA=E.useRef(new Set);E.useEffect(()=>{const ke=ZA.current,nt=PA;for(const Ut of ke)if(!nt.has(Ut)){try{BvA({volume:.03})}catch{}break}ZA.current=new Set(nt)},[PA]),PA.size>0,E.useMemo(()=>PA.size>0,[PA]);const FA=E.useCallback((ke,nt)=>{if(nt===0)return;const Ut=I.find(Ft=>Ft.type===ke);if(nt>0){const Ft=nt,{ok:Jt,reason:$A}=ytA(ke,Ft,cA);if(!Jt){if(pA($A),yA(ke),$A==="Insufficient balance")try{fA("Insufficient funds","Add chips to place this bet")}catch{}window.setTimeout(()=>yA(void 0),600);return}if(Ut)c(I.map(He=>He===Ut?{...He,amount:He.amount+Ft}:He));else{const He=Number(K[ke]||0);c([...I,{id:IY(),type:ke,amount:He+Ft}])}m==null||m(ke,Ft);return}let dt=(Ut==null?void 0:Ut.amount)??0;if(!Ut){const Ft=Number(K[ke]||0);if(Ft<=0)return;dt=Ft}const Ht=dt+nt;c(Ut?I.map(Ft=>Ft===Ut?{...Ft,amount:Math.max(0,Ht)}:Ft):[...I,{id:IY(),type:ke,amount:Math.max(0,Ht)}]),m==null||m(ke,nt)},[I,c,o,K,cA,m,fA]),Ie=E.useCallback((ke,nt)=>{const Ut=ke==="oddsPass",dt=ke==="oddsDontPass",Ht=ke==="atsSmall"||ke==="atsTall"||ke==="atsAll",Ft=ke==="pass"||ke==="dontPass"?P:Ut?i!=="point"||!n||wA("pass")===0:dt?i!=="point"||!n||wA("dontPass")===0:ke.startsWith("place")||ke==="come"||ke==="dontCome"?!n:Ht?i!=="comeOut"||z.betsLocked:!1,Jt=ke==="pass"||ke==="dontPass",$A=ke==="come"||ke==="dontCome",He=!ke.startsWith("place"),Xe=Jt&&P,St=Jt?YA[ke]:ke==="field"?ie[ke]:ke==="big6"||ke==="big8"?he[ke]:$A?le[ke]:void 0,kA=St==="WIN"?wt.lineWin:St==="LOSE"?wt.lineLose:St==="PUSH"?wt.linePush:"",se=Jt&&H&&!xA,Ce=[wt.spotBtn,wt.crapsBetTile,ke.startsWith("place")?wt.crapsPlaceTile:"",Ft?wt.locked:"",gA===ke?wt.shake:"",kA,se?wt.attnHalo:"",ke.startsWith("place")&&uA?wt.attnHalo:""],VA=B||tA,nA=_&&typeof _[ke]=="number"?_[ke]:0,vA=wA(ke);if(He){const bA=[...Ce,wt.spotBtnTopRow,"gold-link",VA?wt.disabled:""].filter(Boolean).join(" ");return C.jsxs(XI.a,{role:"button",tabIndex:0,"aria-disabled":VA||void 0,className:bA,"data-bet-type":ke,"data-attn":se?"need-line":void 0,"data-has-bet":vA>0?"true":"false","data-win-outcome":St==="WIN"?"true":"false","data-no-global-haptic":!0,"aria-label":`Place bet on ${nt}, +${x}`,onClick:pe=>{pe.preventDefault(),!Ft&&!VA&&(On(),ti("Light"),FA(ke,x))},onKeyDown:pe=>{(pe.key==="Enter"||pe.key===" ")&&!Ft&&!VA&&(pe.preventDefault(),On(),ti("Light"),FA(ke,x))},whileTap:{scale:.94},children:[nt,nA>0&&C.jsx("div",{className:wt.aggBadge,"aria-label":`Others ${nt} total ${Da(nA)}`,children:Da(nA)}),vA>0&&C.jsxs("div",{className:wt.amountBadge+(Xe?" "+wt.amountBadgeDisabled:""),"aria-disabled":Xe||void 0,children:[!Xe&&C.jsx("span",{role:"button",tabIndex:0,className:[wt.badgeMinus,wt.crapsMinusBadge].join(" "),"aria-label":`Remove chip from ${nt}`,onClick:pe=>{pe.stopPropagation(),On(),ti("Light"),FA(ke,-x)},onKeyDown:pe=>{(pe.key==="Enter"||pe.key===" ")&&(pe.preventDefault(),pe.stopPropagation(),On(),ti("Light"),FA(ke,-x))},children:"−"}),Da(vA),Xe&&C.jsx("span",{className:wt.lockIcon,"aria-hidden":"true",children:"🔒"}),St&&C.jsx("span",{className:wt.outcomeBadge,"aria-label":`Outcome ${St}`,children:St==="WIN"?"✓":St==="LOSE"?"✕":"⟳"})]}),gA===ke&&sA&&C.jsx("div",{className:wt.tooltip,children:sA})]},ke)}const KA=ke.startsWith("place")?jA[ke]:ke==="field"?ie[ke]:ke==="big6"||ke==="big8"?he[ke]:void 0,WA=Ce.filter(Boolean).join(" ");return C.jsxs(XI.button,{type:"button",className:WA,"data-bet-type":ke,"data-attn":ke.startsWith("place")&&uA?"need-places":void 0,"data-has-bet":vA>0?"true":"false","data-win-outcome":St==="WIN"||KA==="WIN"?"true":"false","aria-label":`Place bet on ${nt}, +${x}`,onClick:()=>{!Ft&&!VA&&(On(),ti("Light"),FA(ke,x))},disabled:B||tA,whileTap:{scale:.94},children:[nt,nA>0&&C.jsx("div",{className:wt.aggBadge,"aria-label":`Others ${nt} total ${Da(nA)}`,children:Da(nA)}),vA>0&&C.jsxs("div",{className:wt.amountBadge+(Xe?" "+wt.amountBadgeDisabled:""),"aria-disabled":Xe||void 0,children:[!Xe&&C.jsx("span",{role:"button",tabIndex:0,className:[wt.badgeMinus,wt.crapsMinusBadge].join(" "),"aria-label":`Remove chip from ${nt}`,onClick:bA=>{bA.stopPropagation(),On(),ti("Light"),FA(ke,-x)},onKeyDown:bA=>{(bA.key==="Enter"||bA.key===" ")&&(bA.preventDefault(),bA.stopPropagation(),On(),ti("Light"),FA(ke,-x))},children:"−"}),Da(vA),Xe&&C.jsx("span",{className:wt.lockIcon,"aria-hidden":"true",children:"🔒"}),St&&C.jsx("span",{className:wt.outcomeBadge,"aria-label":`Outcome ${St}`,children:St==="WIN"?"✓":St==="LOSE"?"✕":"⟳"})]}),gA===ke&&sA&&C.jsx("div",{className:wt.tooltip,children:sA})]},ke)},[FA,B,tA,wA,sA,gA,H,xA,uA,x,P,i,n,YA,jA,ie,he,le,_,z.betsLocked]),DA=E.useMemo(()=>{const ke=[...Dte],nt=(Ut,dt,Ht)=>{const Ft=ke.findIndex(Jt=>Jt.key===Ut);Ft>=0&&!ke.some(Jt=>Jt.key===dt)&&ke.splice(Ft+1,0,{key:dt,label:Ht})};return nt("pass","oddsPass","Odds Pass"),nt("dontPass","oddsDontPass","Odds Don't"),ke},[]),rA=E.useMemo(()=>DA.map(ke=>Ie(ke.key,ke.label)),[DA,Ie]),BA=E.useMemo(()=>Ste.map(ke=>Ie(ke.key,ke.label)),[Ie]),j=E.useMemo(()=>mte.map(ke=>Ie(ke.key,ke.label)),[Ie]),QA=E.useCallback(()=>{if(B||tA)return;On(),ti("Light");const ke=["place4","place5","place6","place8","place9","place10"],nt=[];for(const dt of ke){I.find($A=>$A.type===dt);const Ht=x,{ok:Ft,reason:Jt}=ytA(dt,Ht,cA);if(!Ft){if(pA(Jt),yA(dt),Jt==="Insufficient balance")try{fA("Insufficient funds","Add chips to place All Places bet")}catch{}window.setTimeout(()=>yA(void 0),600);return}nt.push({type:dt,delta:Ht})}let Ut=[...I];for(const{type:dt,delta:Ht}of nt){const Ft=Ut.find(Jt=>Jt.type===dt);if(Ft)Ut=Ut.map(Jt=>Jt===Ft?{...Jt,amount:Jt.amount+Ht}:Jt);else{const Jt=Number(K[dt]||0);Ut.push({id:IY(),type:dt,amount:Jt+Ht})}}c(Ut),D?D(nt.map(({type:dt,delta:Ht})=>({type:dt,amount:Ht}))):m&&nt.forEach(({type:dt,delta:Ht})=>m(dt,Ht))},[B,tA,I,x,o,cA,c,K,D,m,fA]),dA=!!S,UA=dA?N||"Ready":"Roll",TA=dA?!!G:U||h===!1,oe=!dA&&!TA&&h!==!1&&(i!=="point"||_A),[me,be]=E.useState(!1),$e=E.useRef(null);E.useEffect(()=>{if(!me)return;const ke=nt=>{$e.current&&!$e.current.contains(nt.target)&&be(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[me]);const ci=g;return C.jsxs("div",{className:[wt.panelRoot,B?wt.disabled:""].join(" "),children:[C.jsxs("div",{className:wt.crapsStatusBar,children:[C.jsxs("div",{className:wt.chipPickerWrapper,ref:$e,children:[C.jsx("div",{className:[wt.chipPickerToggle,me?wt.chipPickerToggleOpen:""].join(" "),onClick:()=>{On(),ti("Light"),be(ke=>!ke)},role:"button",tabIndex:0,"aria-label":`Selected chip ${x}, click to change`,"aria-expanded":me,onKeyDown:ke=>{(ke.key==="Enter"||ke.key===" ")&&(ke.preventDefault(),On(),ti("Light"),be(nt=>!nt))},children:C.jsx(Vc,{value:x,mini:!0,className:wt.chipPickerChip,onAdd:()=>{On(),ti("Light"),be(ke=>!ke)}})}),me&&C.jsx("div",{className:wt.chipPickerDropdown,children:r.map(ke=>C.jsx("div",{className:[wt.chipPickerOption,ke===x?wt.chipPickerOptionSelected:""].join(" "),children:C.jsx(Vc,{value:ke,mini:!0,className:ke===x?wt.chipPickerChipSelected:"",onAdd:()=>{On(),zBA(),T(ke),be(!1)}})},ke))})]}),C.jsxs("span",{className:wt.crapsStatusText,children:[C.jsx("span",{className:wt.mobileHide,children:i==="comeOut"?"COME-OUT":"POINT"}),C.jsx("span",{className:wt.mobileShow,children:i==="comeOut"?"CO":"PT"})," • ",C.jsx("span",{className:wt.mobileHide,children:"SHOOTER: "}),C.jsx("strong",{className:wt.crapsHighlight,children:ci})," • ",C.jsx("span",{className:wt.mobileHide,children:"POINT: "}),C.jsx("span",{className:wt.mobileShow,children:"P: "}),C.jsx("strong",{className:wt.crapsHighlight,children:n??"—"})]}),C.jsx("button",{type:"button",className:wt.betInfoBtn,onClick:()=>{ti("Light"),aA(!0)},"aria-label":"Show bet information",children:C.jsx(Cd,{icon:XjA})})]}),C.jsx(ite,{open:eA,onClose:()=>aA(!1)}),C.jsx("div",{className:[wt.spotRow,wt.crapsMainBets].join(" "),ref:iA,children:rA}),C.jsxs("div",{className:wt.crapsPlaceRow,ref:oA,children:[BA,C.jsx("button",{type:"button",className:[wt.spotBtn,wt.crapsBetTile,wt.crapsIronCrossBtn].join(" "),onClick:QA,disabled:!n||B||tA,"aria-label":"Place All Places (4/5/6/8/9/10)",children:"All Places"})]}),C.jsxs("div",{className:wt.crapsAtsSection,ref:IA,children:[C.jsx("span",{className:wt.crapsAtsLabel,children:"ATS"}),j,C.jsx(pte,{hitNumbers:z.hitNumbers,smallProgress:z.smallProgress,tallProgress:z.tallProgress,allProgress:z.allProgress,betsLocked:z.betsLocked,lastCompletedCategory:Z,inline:!0})]}),C.jsx("div",{className:wt.crapsActionsBar,children:C.jsxs("div",{className:wt.actions,children:[C.jsxs("button",{type:"button",className:[wt.actionBtn,wt.rollBtn,wt.crapsActionButton,wt.crapsActionButtonPrimary,oe?wt.rollHaloActive:""].join(" "),onClick:ke=>{if(dA){if(G)return;try{On(),ti("Light")}catch{}k==null||k();return}if(RA.current){ke.preventDefault();return}if(!TA){v==null||v(1),On(),ti("Medium");try{i==="point"&&!_A&&fA("No Place bet","Add a Place bet (e.g., 6 or 8) before rolling")}catch{}Q==null||Q(),v==null||v(0)}},onPointerDown:()=>{dA||TA||(X(),ti("Medium"))},onPointerUp:()=>{dA||O()},onPointerCancel:()=>{O()},onPointerLeave:()=>{O()},disabled:TA,"aria-label":dA?"Mark ready":"Roll dice",children:[!dA&&C.jsx(Cd,{icon:ZjA,className:wt.rollIcon,"aria-hidden":"true"}),UA,dA&&M>0&&C.jsx("span",{className:[wt.countdownBadge,M<=5?wt.countdownCritical:M<=10?wt.countdownUrgent:""].join(" "),"aria-label":`${M} seconds remaining`,children:M})]}),!S&&q&&J&&C.jsx("button",{type:"button",className:[wt.actionBtn,wt.crapsActionButton,wt.crapsActionButtonSecondary].join(" "),onClick:()=>{console.log("[CrapsBettingPanel] Pass button clicked");try{On(),ti("Light")}catch{}J()},"aria-label":"Pass dice to next shooter",children:"Pass"}),C.jsxs("button",{type:"button",className:[wt.actionBtn,wt.clear,wt.crapsActionButton,wt.crapsActionButtonSecondary].join(" "),onClick:()=>{On(),ti("Light"),l()},"aria-label":"Clear all bets",children:[C.jsx("span",{className:wt.crapsClearIcon,"aria-hidden":"true",children:"✕"})," Clear"]})]})}),C.jsx("div",{className:wt.errorLive,"aria-live":"polite",children:sA||""})]})}function _te(e,A){const{crapsGetState:t,crapsJoinOrder:i,crapsLeaveOrder:n,crapsSetOrder:g,crapsRoll:o,crapsResetShooter:s,crapsReady:a,crapsPassTurn:r}=Mo(),I=(A==null?void 0:A.enabled)??!0;return{getState:c=>I&&e?t(e).then(l=>(c==null||c(l),l)).catch(l=>(c==null||c({ok:!1,error:(l==null?void 0:l.message)||"ERR"}),{ok:!1,error:(l==null?void 0:l.message)||"ERR"})):void 0,joinOrder:c=>I&&e?i(e).then(l=>(c==null||c(l),l)).catch(l=>(c==null||c({ok:!1,error:(l==null?void 0:l.message)||"ERR"}),{ok:!1,error:(l==null?void 0:l.message)||"ERR"})):void 0,leaveOrder:c=>I&&e?n(e).then(l=>(c==null||c(l),l)).catch(l=>(c==null||c({ok:!1,error:(l==null?void 0:l.message)||"ERR"}),{ok:!1,error:(l==null?void 0:l.message)||"ERR"})):void 0,setOrder:(c,l)=>I&&e?g(e,c).then(B=>(l==null||l(B),B)).catch(B=>(l==null||l({ok:!1,error:(B==null?void 0:B.message)||"ERR"}),{ok:!1,error:(B==null?void 0:B.message)||"ERR"})):void 0,roll:c=>I&&e?o(e).then(l=>(c==null||c(l),l)).catch(l=>(c==null||c({ok:!1,error:(l==null?void 0:l.message)||"ERR"}),{ok:!1,error:(l==null?void 0:l.message)||"ERR"})):void 0,resetShooter:c=>I&&e?s(e).then(l=>(c==null||c(l),l)).catch(l=>(c==null||c({ok:!1,error:(l==null?void 0:l.message)||"ERR"}),{ok:!1,error:(l==null?void 0:l.message)||"ERR"})):void 0,ready:c=>I&&e?a(e).then(l=>(c==null||c(l),l)).catch(l=>(c==null||c({ok:!1,error:(l==null?void 0:l.message)||"ERR"}),{ok:!1,error:(l==null?void 0:l.message)||"ERR"})):void 0,passTurn:c=>I&&e?r(e).then(l=>(c==null||c(l),l)).catch(l=>(c==null||c({ok:!1,error:(l==null?void 0:l.message)||"ERR"}),{ok:!1,error:(l==null?void 0:l.message)||"ERR"})):void 0}}let U0={},Jte=1;function epA(e){var $;const{roomId:A,myPlayerId:t,autoJoinOrder:i=!0,onRoll:n,onState:g}=e,{crapsReady:o}=Mo(),s=(()=>{try{return nI&&nI()}catch{return null}})(),a=(s==null?void 0:s.room)??null,r=(s==null?void 0:s.setRoom)??(()=>{}),c=(($=a==null?void 0:a.gameState)==null?void 0:$.gameMode)==="craps",l=_te(A,{enabled:c}),B=E.useMemo(()=>{const L=a==null?void 0:a.gameState;return!L||L.gameMode!=="craps"?null:{point:L.crapsPoint??null,currentRollerId:L.currentRollerId??null,turnOrder:L.turnOrder??[]}},[a==null?void 0:a.gameState]),[Q,h]=E.useState(null),[d,p]=E.useState([]),[y,m]=E.useState(!1),D=E.useRef(!1),[S,k]=E.useState([]),[N,G]=E.useState(null),[M,w]=E.useState([]),b=E.useRef(null),_=E.useRef(null),K=E.useRef(null),J=E.useRef(null),q=E.useRef(null),{triggerSpin:v}=kB(),U=E.useRef(null),x=E.useRef(null),T=E.useRef(null),z=2e3,Z=600,eA=E.useMemo(()=>!!(t&&(B!=null&&B.turnOrder.includes(t))),[t,B==null?void 0:B.turnOrder]),aA=E.useCallback(()=>{var L;if(c){try{console.debug("[craps][requestState]")}catch{}(L=l.getState)==null||L.call(l)}},[l,c]),sA=E.useCallback(L=>{var H;!c||!A||D.current||(D.current=!0,(H=l.joinOrder)==null||H.call(l,P=>{D.current=!1,L==null||L(P==null?void 0:P.ok,P==null?void 0:P.data)}))},[l,A,c]),pA=E.useCallback(L=>{var H;!c||!A||D.current||(D.current=!0,(H=l.leaveOrder)==null||H.call(l,P=>{D.current=!1,L==null||L(P==null?void 0:P.ok,P==null?void 0:P.data)}))},[l,A,c]),gA=E.useCallback((L,H)=>{var P;!c||!A||D.current||(D.current=!0,(P=l.setOrder)==null||P.call(l,L,tA=>{D.current=!1,H==null||H(tA==null?void 0:tA.ok,tA==null?void 0:tA.data)}))},[l,A,c]),yA=E.useCallback(L=>{var H;if(!c||!A||D.current){try{console.debug("[craps][roll_emit][blocked]",{isCraps:c,roomIdPresent:!!A,pendingAck:D.current})}catch{}return}try{console.debug("[craps][roll_emit][start]",{roomId:A})}catch{}D.current=!0,m(!0),h(null),T.current=Date.now(),v();try{const P=(H=l.roll)==null?void 0:H.call(l);P&&typeof P.then=="function"?P.then(tA=>{const iA=!!(tA!=null&&tA.ok),oA=String((tA==null?void 0:tA.error)||"");try{console.debug("[craps][roll_emit][ack]",{ok:iA,err:oA})}catch{}if(D.current=!1,!iA)try{const IA=/invalid_payload/i.test(oA),CA=/no_room/i.test(oA),_A=/forbidden|unauthorized/i.test(oA);if(IA||CA||_A){console.warn("[craps][roll_emit][ack_reject]",{err:oA}),x.current&&(window.clearTimeout(x.current),x.current=null),m(!1),T.current=null,aA(),L==null||L(!1,tA==null?void 0:tA.data);return}}catch{}try{x.current&&(window.clearTimeout(x.current),x.current=null),x.current=window.setTimeout(()=>{try{console.warn("[craps][roll_emit][fallback_clear_rolling]")}catch{}m(!1),T.current=null,x.current=null},Math.max(z,4e3))}catch{}L==null||L(iA,tA==null?void 0:tA.data)}).catch(()=>{try{console.warn("[craps][roll_emit][ack_error]")}catch{}D.current=!1,m(!1),T.current=null;try{aA()}catch{}L==null||L(!1)}):(D.current=!1,m(!1),T.current=null,L==null||L(!1))}catch{try{console.warn("[craps][roll_emit][exception]")}catch{}D.current=!1,m(!1),T.current=null,L==null||L(!1)}},[l,A,c]),fA=E.useCallback(L=>{var H;if(!(!c||!A||D.current)){D.current=!0;try{const P=(H=l.resetShooter)==null?void 0:H.call(l);P&&typeof P.then=="function"?P.then(tA=>{D.current=!1,L==null||L(!!(tA!=null&&tA.ok),tA==null?void 0:tA.data)}).catch(()=>{D.current=!1,L==null||L(!1)}):(D.current=!1,L==null||L(!1))}catch{D.current=!1,L==null||L(!1)}}},[l,A,c]),RA=E.useCallback(L=>{var H;if(console.log("[craps][passTurn] called",{isCraps:c,roomId:A,pendingAck:D.current}),!c||!A||D.current){console.log("[craps][passTurn] blocked",{isCraps:c,roomId:A,pendingAck:D.current});return}D.current=!0;try{const P=(H=l.passTurn)==null?void 0:H.call(l);console.log("[craps][passTurn] api.passTurn() returned",{isPromise:!!(P&&typeof P.then=="function")}),P&&typeof P.then=="function"?P.then(tA=>{console.log("[craps][passTurn] resolved",tA),D.current=!1,L==null||L(!!(tA!=null&&tA.ok),tA==null?void 0:tA.data)}).catch(tA=>{console.log("[craps][passTurn] rejected",tA),D.current=!1,L==null||L(!1)}):(console.log("[craps][passTurn] api returned undefined"),D.current=!1,L==null||L(!1))}catch(P){console.log("[craps][passTurn] exception",P),D.current=!1,L==null||L(!1)}},[l,A,c]),qA=E.useRef(0);qA.current===0&&(qA.current=Jte++);const W=E.useMemo(()=>A?U0[A]?U0[A]===qA.current:(U0[A]=qA.current,!0):!1,[A]);return E.useEffect(()=>()=>{try{A&&U0[A]===qA.current&&delete U0[A]}catch{}},[A]),Os({onJoinedRoom:({room:L})=>{if(W)try{if(!A||!L||L.id!==A)return;if(J.current){const H=J.current.cb;J.current=null,(async()=>{try{const P=await o(A);H==null||H(!!(P!=null&&P.ok),P==null?void 0:P.data)}catch{H==null||H(!1)}})()}}catch{}},onRejoinedRoom:({room:L})=>{if(W)try{if(!A||!L||L.id!==A)return;if(J.current){const H=J.current.cb;J.current=null,(async()=>{try{const P=await o(A);H==null||H(!!(P!=null&&P.ok),P==null?void 0:P.data)}catch{H==null||H(!1)}})()}}catch{}},onCrapsState:L=>{var iA,oA,IA,CA,_A,uA,X;if(!W||!A||L.roomId!==A)return;const H=((iA=L.state)==null?void 0:iA.currentRollerId)??((oA=L.state)==null?void 0:oA.currentShooterId)??((IA=L.state)==null?void 0:IA.shooterId)??null,P=((CA=L.state)==null?void 0:CA.turnOrder)||((_A=L.state)==null?void 0:_A.shooterOrder)||[],tA=((uA=L.state)==null?void 0:uA.point)??((X=L.state)==null?void 0:X.crapsPoint)??null;try{console.debug("[craps][state]",{point:tA,currentRollerId:H,turnOrderLen:P.length})}catch{}try{r(O=>{if(!O||O.id!==A)return O;const cA=O.gameState||{},wA=tA?"point":"come-out";return{...O,gameState:{...cA,gameMode:cA.gameMode||"craps",crapsPoint:tA,currentRollerId:H,turnOrder:P,crapsPhase:wA}}})}catch{}try{g==null||g({point:tA,currentRollerId:H,turnOrder:P})}catch{}i&&t&&!P.includes(t)&&sA()},onCrapsPointSet:L=>{if(W)try{if(!A||(L==null?void 0:L.roomId)!==A)return;const H=(L==null?void 0:L.point)??(L==null?void 0:L.crapsPoint)??null;try{console.debug("[craps][point_set]",{newPoint:H})}catch{}r(P=>{if(!P||P.id!==A)return P;const tA={...P.gameState||{}};return H!=null&&(tA.crapsPoint=H,tA.crapsPhase="point"),{...P,gameState:tA}})}catch{}},onCrapsRollResult:L=>{if(!W||!A||(L==null?void 0:L.roomId)!==A)return;let H,P;if(Array.isArray(L==null?void 0:L.dice)?[H,P]=L.dice:(H=L==null?void 0:L.d1,P=L==null?void 0:L.d2),typeof H!="number"||typeof P!="number")return;const tA=typeof L.total=="number"?L.total:H+P,iA=L.currentRollerId??L.currentShooterId??L.shooterId??null,oA=L.nextRollerId??L.nextShooterId??L.nextShooter??null;try{console.debug("[craps][roll_result]",{dice:[H,P],total:tA,point:L.point??L.crapsPoint??null,currentRollerId:iA,nextRollerId:oA})}catch{}const IA={roomId:L.roomId,dice:[H,P],total:tA,point:L.point??L.crapsPoint??null,currentRollerId:iA,nextRollerId:oA,events:Array.isArray(L.events)?L.events:[],resolutions:L.resolutions||{passLineWins:!1,passLineLosses:!1,pushes:!1}};T.current||(T.current=Date.now(),h(null),v());try{D.current=!1,m(!0),U.current&&(window.clearTimeout(U.current),U.current=null);const CA=T.current?Date.now()-T.current:0,_A=Math.max(z-CA,0)+Z;U.current=window.setTimeout(()=>{m(!1),T.current=null,U.current=null},_A),x.current&&(window.clearTimeout(x.current),x.current=null)}catch{}h(IA),p(CA=>{const _A=Date.now(),uA=30,X=900;for(let wA=0;wA<CA.length&&wA<5;wA++){const xA=CA[wA];if(xA.dice[0]===IA.dice[0]&&xA.dice[1]===IA.dice[1]&&_A-xA.ts<X)return CA}const cA=[{...IA,ts:_A,phase:IA.point?"point":"come-out"},...CA];cA.length>uA&&(cA.length=uA);try{if(A){const wA={v:1,roomId:A,ts:_A,items:cA};uL(`craps-roll-history:${A}`,wA)}}catch{}return cA});try{const CA=oA||null;k(CA?[CA]:[]),G(null)}catch{}try{(L.gameState||L.point!==void 0||L.currentRollerId!==void 0||L.nextRollerId!==void 0)&&r(CA=>{if(!CA||CA.id!==A)return CA;const uA={...CA.gameState||{}};(L.point!==void 0||L.crapsPoint!==void 0)&&(uA.crapsPoint=L.point??L.crapsPoint);const X=oA??iA;return X!==void 0&&(uA.currentRollerId=X),(Array.isArray(L.turnOrder)||Array.isArray(L.shooterOrder))&&(uA.turnOrder=L.turnOrder||L.shooterOrder),uA.gameMode||(uA.gameMode="craps"),uA.crapsPhase=uA.crapsPoint?"point":"come-out",{...CA,gameState:uA}})}catch{}n==null||n(IA)},onCrapsReadyUpdate:L=>{if(W)try{const H=Array.isArray(L==null?void 0:L.readyPlayers)?L.readyPlayers:void 0,P=Array.isArray(L==null?void 0:L.requiredReadyPlayers)?L.requiredReadyPlayers:void 0,tA=L&&Object.prototype.hasOwnProperty.call(L,"deadline"),iA=tA?typeof L.deadline=="number"?L.deadline:null:void 0,oA=(IA,CA)=>{if(!IA&&!CA)return!0;if(!IA||!CA||IA.length!==CA.length)return!1;for(let _A=0;_A<IA.length;_A++)if(IA[_A]!==CA[_A])return!1;return!0};H&&(oA(b.current,H)||(b.current=H.slice(),k(H))),P&&(oA(_.current,P)||(_.current=P.slice(),w(P))),tA&&K.current!==iA&&(K.current=iA===void 0?K.current:iA,G(iA))}catch{}},onCrapsBetsUpdate:L=>{if(W)try{const H=(L==null?void 0:L.snapshot)||{},P=new Set(["currentRollerId","turnOrder","crapsPoint","crapsPhase"]);r(tA=>{if(!tA||tA.id!==A)return tA;const iA={...tA.gameState||{}};for(const oA of Object.keys(H))P.has(oA)||(iA[oA]=H[oA]);return iA.gameMode||(iA.gameMode="craps"),{...tA,gameState:iA}})}catch{}}}),E.useEffect(()=>{!A||!c||W&&aA()},[A,c]),E.useEffect(()=>{try{const L=a==null?void 0:a.gameState;if(!L||L.gameMode!=="craps")return;const H=L.crapsReadiness;H&&(Array.isArray(H.readyPlayers)&&k(H.readyPlayers),Array.isArray(H.requiredReadyPlayers)&&w(H.requiredReadyPlayers),Object.prototype.hasOwnProperty.call(H,"deadline")&&G(typeof H.deadline=="number"?H.deadline:null))}catch{}},[a==null?void 0:a.gameState]),E.useEffect(()=>{if(!c||!A||!W)return;let L=0;const H=500,P=()=>{try{const IA=Date.now();if(IA-L<H)return;L=IA,aA()}catch{}},tA=()=>{document.visibilityState==="visible"&&P()},iA=()=>{P()},oA=()=>{P()};return window.addEventListener("visibilitychange",tA),window.addEventListener("focus",iA),window.addEventListener("ad:complete",oA),()=>{window.removeEventListener("visibilitychange",tA),window.removeEventListener("focus",iA),window.removeEventListener("ad:complete",oA)}},[c,A,aA,W]),E.useEffect(()=>{A&&(async()=>{try{const L=await dS(`craps-roll-history:${A}`);if(!L)return;if(L&&L.v===1&&Array.isArray(L.items)){if(typeof L.ts=="number"&&Date.now()-L.ts>72e5)return;const P=[];for(const tA of L.items)if(!(!tA||!Array.isArray(tA.dice)||tA.dice.length!==2)&&!(typeof tA.total!="number"||typeof tA.ts!="number")&&(P.push({roomId:A,dice:[Number(tA.dice[0]),Number(tA.dice[1])],total:Number(tA.total),point:typeof tA.point=="number"?tA.point:tA.point??null,currentRollerId:tA.currentRollerId??null,nextRollerId:tA.nextRollerId??null,events:Array.isArray(tA.events)?tA.events.slice(0,8):[],resolutions:tA.resolutions||{passLineWins:!1,passLineLosses:!1,pushes:!1},ts:tA.ts,phase:tA.phase==="point"?"point":"come-out"}),P.length>=30))break;P.length&&p(P)}}catch{}})()},[A]),E.useEffect(()=>()=>{U.current&&(window.clearTimeout(U.current),U.current=null),x.current&&(window.clearTimeout(x.current),x.current=null),q.current&&(window.clearTimeout(q.current),q.current=null)},[]),{shooterState:B,lastRoll:Q,rollHistory:d,rolling:y,inTurnOrder:eA,joinOrder:sA,leaveOrder:pA,setOrder:gA,roll:yA,resetShooter:fA,passTurn:RA,requestState:aA,readyPlayers:S,readinessDeadline:N,requiredReadyPlayers:M,ready:L=>{if(!A||!c)return;const H=!!(a&&a.id===A);if(t&&!S.includes(t)&&k(P=>[...P,t]),N||G(Date.now()+5e3),!H){J.current={cb:L,at:Date.now()};try{q.current&&(window.clearTimeout(q.current),q.current=null),q.current=window.setTimeout(async()=>{var P,tA;try{if(!J.current)return;const iA=await o(A),oA=(P=J.current)==null?void 0:P.cb;J.current=null,oA==null||oA(!!(iA!=null&&iA.ok),iA==null?void 0:iA.data)}catch{const iA=(tA=J.current)==null?void 0:tA.cb;J.current=null,iA==null||iA(!1)}finally{q.current&&(window.clearTimeout(q.current),q.current=null)}},600)}catch{}return}(async()=>{try{const P=await o(A);if(!(P!=null&&P.ok)){const tA=String((P==null?void 0:P.error)||"");try{console.warn("[craps][ready] ack error",{err:tA,roomId:A})}catch{}const iA=/forbidden|unauthorized/i.test(tA),oA=/ready_failed/i.test(tA);if(iA||oA){try{aA()}catch{}try{const IA=await o(A);L==null||L(!!(IA!=null&&IA.ok),IA==null?void 0:IA.data);return}catch{}}L==null||L(!1);return}L==null||L(!0,P==null?void 0:P.data)}catch{try{setTimeout(async()=>{try{const P=await o(A);L==null||L(!!(P!=null&&P.ok),P==null?void 0:P.data)}catch{L==null||L(!1)}},400)}catch{L==null||L(!1)}}})()},iAmReady:!!(t&&S.includes(t)),clearRollHistory:()=>{p([]);try{A&&hS(`craps-roll-history:${A}`)}catch{}}}}function Lte(e){const{roomId:A,userId:t,shooterState:i,roomGameState:n,myLineFromUnified:g,betsLastUpdated:o}=e;if(!A||!t)return!1;const s=n==null?void 0:n.currentRollerId,a=(i==null?void 0:i.currentRollerId)||null;if(!!!(t&&(s?s===t:a===t)))return!1;let I;const c=n==null?void 0:n.crapsPassBets,l=n==null?void 0:n.crapsDontPassBets;if(Array.isArray(c)||Array.isArray(l))I=!!(c!=null&&c.some(h=>h.playerId===t&&h.amount>0)||l!=null&&l.some(h=>h.playerId===t&&h.amount>0));else if(typeof o=="number")if(o===0)I=!0;else{const h=Number((g==null?void 0:g.pass)||0),d=Number((g==null?void 0:g.dontPass)||0);I=h>0||d>0}else{const h=Number((g==null?void 0:g.pass)||0),d=Number((g==null?void 0:g.dontPass)||0);I=h>0||d>0}if(!I)return!1;const B=Array.isArray(i==null?void 0:i.turnOrder)&&i.turnOrder.length?i.turnOrder:Array.isArray(n==null?void 0:n.turnOrder)?n.turnOrder:[];return!!(t&&B.includes(t))}const kY=new Map,MY={pass:[],dontPass:[],odds:[],place:[],field:[],big:[],come:[],dontCome:[],ats:[],lastUpdated:0};function tpA(e){const{roomId:A,myPlayerId:t,autoListOnMount:i=!0,autoClearSettlementsMs:n=8e3}=e;Ms();const{room:g,setRoom:o}=nI(),[s,a]=E.useState(MY),r=E.useRef(MY),[I,c]=E.useState([]),[l,B]=E.useState(null),[Q,h]=E.useState(null),[d,p]=E.useState(null),[y,m]=E.useState([]),[D,S]=E.useState([]),[k,N]=E.useState(null),G=E.useRef(null),M=E.useRef(!1),w=E.useRef(0),b=E.useRef(new Map),{crapsListBets:_,crapsAddBet:K,crapsRemoveBet:J,crapsClearBets:q,crapsSummarizeBets:v}=Mo(),U=E.useCallback(H=>{if(!A)return;const P=kY.get(A);if(P)return H&&P.then(iA=>H(iA)).catch(iA=>H({ok:!1,error:String((iA==null?void 0:iA.message)||iA)})),P;const tA=_(A);return kY.set(A,tA),tA.finally(()=>{kY.delete(A)}),H&&tA.then(iA=>H(iA)).catch(iA=>H({ok:!1,error:String((iA==null?void 0:iA.message)||iA)})),tA},[_,A]),x=E.useCallback((H,P)=>{!t||P<=0||a(tA=>{const iA={...tA,lastUpdated:Date.now()};if(H==="pass")tA.pass.find(IA=>IA.playerId===t)?iA.pass=tA.pass.map(IA=>IA.playerId===t?{...IA,amount:IA.amount+P}:IA):iA.pass=[...tA.pass,{playerId:t,amount:P}];else if(H==="dontPass")tA.dontPass.find(IA=>IA.playerId===t)?iA.dontPass=tA.dontPass.map(IA=>IA.playerId===t?{...IA,amount:IA.amount+P}:IA):iA.dontPass=[...tA.dontPass,{playerId:t,amount:P}];else if(H.startsWith("place")){const oA=H.match(/^place(\d+)$/);if(oA){const IA=Number(oA[1]);tA.place.find(_A=>_A.playerId===t&&_A.point===IA)?iA.place=tA.place.map(_A=>_A.playerId===t&&_A.point===IA?{..._A,amount:_A.amount+P}:_A):iA.place=[...tA.place,{playerId:t,point:IA,amount:P}]}}return r.current=iA,iA})},[t]),T=E.useCallback((H,P,tA)=>{if(!A)return;x(H,P);const iA=K(A,H,P);return tA&&iA.then(oA=>tA(oA)).catch(oA=>tA({ok:!1,error:String((oA==null?void 0:oA.message)||oA)})),iA},[K,A,x]),z=E.useCallback((H,P)=>{!t||P<=0||a(tA=>{const iA={...tA,lastUpdated:Date.now()};if(H==="pass"){const oA=[...iA.pass||[]],IA=oA.findIndex(CA=>CA.playerId===t);IA!==-1&&(oA[IA]={...oA[IA],amount:Math.max(0,oA[IA].amount-P)},oA[IA].amount===0&&oA.splice(IA,1)),iA.pass=oA}else if(H==="dontPass"){const oA=[...iA.dontPass||[]],IA=oA.findIndex(CA=>CA.playerId===t);IA!==-1&&(oA[IA]={...oA[IA],amount:Math.max(0,oA[IA].amount-P)},oA[IA].amount===0&&oA.splice(IA,1)),iA.dontPass=oA}else if(H.startsWith("place")){const oA=H.replace("place",""),IA=parseInt(oA,10);if(!isNaN(IA)){const CA=[...iA.place||[]],_A=CA.findIndex(uA=>uA.playerId===t&&uA.point===IA);_A!==-1&&(CA[_A]={...CA[_A],amount:Math.max(0,CA[_A].amount-P)},CA[_A].amount===0&&CA.splice(_A,1)),iA.place=CA}}return r.current=iA,iA})},[t]),Z=E.useCallback((H,P,tA)=>{if(!A)return;z(H,P);const iA=J(A,H,P);return tA&&iA.then(oA=>tA(oA)).catch(oA=>tA({ok:!1,error:String((oA==null?void 0:oA.message)||oA)})),iA},[J,A,z]),eA=E.useCallback(H=>{if(!A)return;const P=q(A);return H&&P.then(tA=>H(tA)).catch(tA=>H({ok:!1,error:String((tA==null?void 0:tA.message)||tA)})),P},[q,A]),aA=E.useCallback(H=>{if(!A)return;const P=v(A);return H&&P.then(tA=>H(tA)).catch(tA=>H({ok:!1,error:String((tA==null?void 0:tA.message)||tA)})),P},[v,A]),sA=A&&t?`crapsbets:${A}:${t}`:null,pA=30*60*1e3,gA=E.useCallback(async()=>{if(sA)try{const H=await dS(sA);if(!H)return;const P=H.pass,tA=H.dontPass,iA=Array.isArray(H.place)?H.place:[],oA=typeof H.ts=="number"?H.ts:void 0;if(oA&&Date.now()-oA>pA||!(iA!=null&&iA.length)&&!P&&!tA)return;a(IA=>{if(IA.lastUpdated!==0||IA.place.length+IA.pass.length+IA.dontPass.length>0)return IA;const CA={...IA};return P&&(CA.pass=[{playerId:t,amount:P}]),tA&&(CA.dontPass=[{playerId:t,amount:tA}]),iA!=null&&iA.length&&(CA.place=iA.map(_A=>({playerId:t,point:_A.point,amount:_A.amount}))),CA.lastUpdated=Date.now(),r.current=CA,CA})}catch{}},[sA,t]);E.useEffect(()=>{gA()},[gA]);const yA=E.useCallback(async()=>{var H,P;if(!(!sA||!t||!A))try{const tA=await dS(sA);if(!tA)return;const iA=Number(tA.pass||0),oA=Number(tA.dontPass||0),IA=Array.isArray(tA.place)?tA.place:[],CA=Date.now();try{await U()}catch{}const _A=Date.now()+1200;for(;(r.current.lastUpdated||0)<=CA&&Date.now()<_A;)await new Promise(YA=>setTimeout(YA,120));if((r.current.lastUpdated||0)<=CA)return;const uA=r.current,X=((H=(uA.pass||[]).find(YA=>YA.playerId===t))==null?void 0:H.amount)||0,O=((P=(uA.dontPass||[]).find(YA=>YA.playerId===t))==null?void 0:P.amount)||0,cA={};for(const YA of uA.place||[])YA.playerId===t&&(cA[YA.point]=(cA[YA.point]||0)+YA.amount);const wA=Math.max(0,iA-X),xA=Math.max(0,oA-O);if(wA>0)try{await K(A,"pass",wA)}catch{}if(xA>0)try{await K(A,"dontPass",xA)}catch{}for(const YA of IA){const jA=Number(YA.point),ie=Number(YA.amount||0),he=Number(cA[jA]||0),le=Math.max(0,ie-he);if(le>0)try{const NA=`place${jA}`;await K(A,NA,le)}catch{}}}catch{}},[sA,t,A,U,s,K]),fA=E.useCallback(H=>{!H||typeof H!="object"||a(P=>{const tA={pass:Array.isArray(H.crapsPassBets)?H.crapsPassBets:P.pass,dontPass:Array.isArray(H.crapsDontPassBets)?H.crapsDontPassBets:P.dontPass,odds:Array.isArray(H.crapsOddsBets)?H.crapsOddsBets:P.odds,place:Array.isArray(H.crapsPlaceBets)?H.crapsPlaceBets:P.place,field:Array.isArray(H.crapsFieldBets)?H.crapsFieldBets:P.field,big:Array.isArray(H.crapsBigBets)?H.crapsBigBets:P.big,come:Array.isArray(H.crapsComeBets)?H.crapsComeBets:P.come,dontCome:Array.isArray(H.crapsDontComeBets)?H.crapsDontComeBets:P.dontCome,ats:Array.isArray(H.crapsAtsBets)?H.crapsAtsBets:P.ats,lastUpdated:Date.now()};return r.current=tA,tA})},[]),RA=E.useCallback((H,P,tA)=>{if(!A||H!==A)return;c(P),w.current+=1;const iA={...tA||{},_seq:w.current};B(iA);try{o(IA=>{if(!IA||IA.id!==A)return IA;const CA={...IA.gameState||{}};return CA.lastCrapsSettlementsTs=Date.now(),CA.lastCrapsSettlements=P,{...IA,gameState:CA}})}catch{}const oA=new Map;for(const IA of P)IA.outcome==="WIN"&&IA.playerId&&oA.set(IA.playerId,(oA.get(IA.playerId)||0)+1);for(const[IA,CA]of oA){const _A=b.current.get(IA)||0,uA=_A+CA;if(b.current.set(IA,uA),_A>=6&&uA>_A)O6(7,.55);else for(const X of[3,4,5,6])if(_A<X&&uA>=X){O6(X,.55);break}if(IA===t)try{window.dispatchEvent(new CustomEvent("craps:streak",{detail:{streak:uA}}))}catch{}}G.current&&clearTimeout(G.current),G.current=setTimeout(()=>c([]),n)},[A,o,n]);Os({onCrapsRollResult:H=>{try{if(!A||(H==null?void 0:H.roomId)!==A)return;const P=Array.isArray(H==null?void 0:H.events)?H.events:[],tA=P.includes("crapsOut")||P.includes("CRAPS_OUT"),iA=P.includes("sevenOut")||P.includes("SEVEN_OUT");if(tA||iA){b.current.clear();try{window.dispatchEvent(new CustomEvent("craps:streak",{detail:{streak:0}}))}catch{}}if(iA){a(oA=>{if(!oA.place.length)return oA;const IA={...oA,place:[],lastUpdated:Date.now()};return r.current=IA,IA});try{o(oA=>{if(!oA||oA.id!==A)return oA;const IA={...oA.gameState||{}};return IA.crapsPlaceBets=[],{...oA,gameState:IA}})}catch{}}}catch{}},onJoinedRoom:async({room:H})=>{try{if(H!=null&&H.id&&H.id===A){try{await U()}catch{}try{await yA()}catch{}}}catch{}},onRejoinedRoom:async({room:H})=>{try{if(H!=null&&H.id&&H.id===A){try{await U()}catch{}try{await yA()}catch{}}}catch{}},onCrapsReadyUpdate:H=>{try{if(console.log("[useCrapsBetsUnified] onCrapsReadyUpdate received",H),Array.isArray(H==null?void 0:H.readyPlayers)&&m(H.readyPlayers),Array.isArray(H==null?void 0:H.requiredReadyPlayers)&&S(H.requiredReadyPlayers),H&&Object.prototype.hasOwnProperty.call(H,"deadline")){const P=typeof H.deadline=="number"?H.deadline:null;N(P)}}catch{}},onCrapsBetsUpdate:H=>{if(!A||(H==null?void 0:H.roomId)!==A)return;const P=H==null?void 0:H.snapshot;if(P){fA(P);const tA=new Set(["currentRollerId","turnOrder","crapsPoint","crapsPhase"]);try{o(iA=>{if(!iA||iA.id!==A)return iA;const oA={...iA.gameState||{}};for(const IA of Object.keys(P))tA.has(IA)||(oA[IA]=P[IA]);return oA.gameMode||(oA.gameMode="craps"),{...iA,gameState:oA}})}catch{}}sA&&t&&(async()=>{var tA,iA;try{const oA=((tA=((P==null?void 0:P.crapsPassBets)||[]).find(uA=>uA.playerId===t))==null?void 0:tA.amount)||0,IA=((iA=((P==null?void 0:P.crapsDontPassBets)||[]).find(uA=>uA.playerId===t))==null?void 0:iA.amount)||0,CA=((P==null?void 0:P.crapsPlaceBets)||[]).filter(uA=>uA.playerId===t).map(uA=>({point:uA.point,amount:uA.amount})),_A={v:1,ts:Date.now(),pass:oA,dontPass:IA,place:CA};oA||IA||CA.length?await uL(sA,_A):await hS(sA)}catch{}})()},onCrapsBetResults:H=>{const P=Array.isArray(H==null?void 0:H.settlements)?H.settlements:[];RA(H==null?void 0:H.roomId,P,H==null?void 0:H.roll)},onCrapsPointSet:H=>{if(!A||(H==null?void 0:H.roomId)!==A)return;const P=H.currentRollerId||H.nextRollerId||"unknown",tA=`ptSet:${H.point}:${Array.isArray(H.dice)?H.dice.join("-"):""}:${P}`;h({...H,_key:tA});try{o(iA=>{if(!iA||iA.id!==A)return iA;const oA={...iA.gameState||{}};return oA.gameMode=oA.gameMode||"craps",oA.crapsPoint=typeof H.point=="number"?H.point:H.point??null,oA.crapsPhase=oA.crapsPoint?"point":"come-out",H.currentRollerId!==void 0&&(oA.currentRollerId=H.currentRollerId),Array.isArray(H.turnOrder)&&(oA.turnOrder=H.turnOrder),{...iA,gameState:oA}})}catch{}},onCrapsPointMade:H=>{if(!A||(H==null?void 0:H.roomId)!==A)return;const P=H.currentRollerId||H.nextRollerId||"unknown",tA=`ptMade:${H.point}:${Array.isArray(H.dice)?H.dice.join("-"):""}:${P}`;p({...H,_key:tA});try{o(iA=>{if(!iA||iA.id!==A)return iA;const oA={...iA.gameState||{}};return oA.gameMode=oA.gameMode||"craps",oA.crapsPoint=null,oA.crapsPhase="come-out",H.nextRollerId!==void 0&&(oA.currentRollerId=H.nextRollerId),Array.isArray(H.turnOrder)&&(oA.turnOrder=H.turnOrder),{...iA,gameState:oA}})}catch{}}}),E.useEffect(()=>{if(!A){a(MY),M.current=!1,c([]),B(null);return}const H=g==null?void 0:g.gameState;H&&(H.crapsPassBets||H.crapsDontPassBets)&&fA(H),i&&!M.current&&(M.current=!0,U())},[A]),E.useEffect(()=>{if(!A)return;const H=async()=>{await new Promise(P=>setTimeout(P,300));try{await U()}catch{}try{await yA()}catch{}};return window.addEventListener("ad:complete",H),()=>{window.removeEventListener("ad:complete",H)}},[A,U,yA]),E.useEffect(()=>()=>{G.current&&clearTimeout(G.current)},[]);const qA=E.useMemo(()=>s.pass.reduce((H,P)=>H+P.amount,0),[s.pass]),W=E.useMemo(()=>s.dontPass.reduce((H,P)=>H+P.amount,0),[s.dontPass]),$=E.useMemo(()=>s.field.reduce((H,P)=>H+P.amount,0),[s.field]),L=E.useMemo(()=>t?{pass:s.pass.filter(H=>H.playerId===t).reduce((H,P)=>H+P.amount,0),dontPass:s.dontPass.filter(H=>H.playerId===t).reduce((H,P)=>H+P.amount,0)}:{pass:0,dontPass:0},[s.pass,s.dontPass,t]);return{betsState:s,recentSettlements:I,lastSettlementRoll:l,_persistKey:sA,passTotal:qA,dontPassTotal:W,fieldTotal:$,myLine:L,listBets:U,addBet:T,removeBet:Z,clearBets:eA,summarize:aA,clearRecentSettlements:()=>c([]),pointSetEvent:Q,pointMadeEvent:d,readyPlayers:y,requiredReadyPlayers:D,readinessDeadline:k}}function xte(){try{if(typeof window>"u")return!1;const e=window;return e.__E2E===!0||typeof e.location<"u"&&!!e.location.search&&e.location.search.includes("e2e=1")||typeof e.sessionStorage<"u"&&e.sessionStorage.getItem("e2e")==="1"}catch{return!1}}function WB(e,A){if(!Array.isArray(e)||!A)return 0;let t=0;for(const i of e)i.playerId===A&&(t+=Number(i.amount)||0);return t}function v0(e,A){if(!Array.isArray(e)||!A)return 0;let t=0;for(const i of e)i.playerId!==A&&(t+=Number(i.amount)||0);return t}function Eh(e,A,t){if(!Array.isArray(e)||!A)return 0;let i=0;for(const n of e)n.playerId===A&&t(n)&&(i+=Number(n.amount)||0);return i}function DtA(e,A,t){if(!Array.isArray(e)||!A)return 0;let i=0;for(const n of e)n.playerId!==A&&t(n)&&(i+=Number(n.amount)||0);return i}function Tte(e,A){const t={};if(!Array.isArray(e)||!A)return t;for(const i of e){if(i.playerId!==A)continue;const n=Number(i.point);t[n]=(t[n]||0)+(Number(i.amount)||0)}return t}function Zy(e,A,t){if(!Array.isArray(e)||!A)return 0;let i=0;for(const n of e)n.playerId!==A&&Number(n.point)===t&&(i+=Number(n.amount)||0);return i}function qte(e,A){const[t,i]=E.useState(e.point),[n,g]=E.useState(e.phase);return E.useEffect(()=>{A&&(i(e.point),g(e.phase))},[A,e.point,e.phase]),{displayPoint:t,displayPhase:n}}function Yte({balance:e,meId:A,readyPlayers:t,onChargeChange:i,onRollAffordanceChange:n}){var he,le,NA;const{user:g,meId:o}=tn(),{room:s,setRoom:a}=nI(),r=(s==null?void 0:s.id)??null,I=E.useMemo(()=>xte(),[]),c=E.useMemo(()=>{if(o)return o;const EA=g;return(EA==null?void 0:EA.id)??(EA==null?void 0:EA.email)??""},[g,o]),l=E.useMemo(()=>A||c,[A,c]),[B,Q]=E.useState([]),{shooterState:h,roll:d,rolling:p,readyPlayers:y,ready:m,passTurn:D}=epA({roomId:r,myPlayerId:l}),S=tpA({roomId:r,myPlayerId:l}),k=E.useMemo(()=>Array.isArray(t)?t:Array.isArray(S.readyPlayers)&&S.readyPlayers.length>0?S.readyPlayers:y,[t,S.readyPlayers,y]),N=E.useMemo(()=>({addBet:S.addBet,removeBet:S.removeBet,clearBets:S.clearBets}),[S.addBet,S.removeBet,S.clearBets]),G=S.betsState||{},M=G.pass||[],w=G.dontPass||[],b=G.place||[],_=G.field||[],K=G.big||[],J=G.come||[],q=G.dontCome||[],v=G.odds||[],U=G.ats||[],x=E.useMemo(()=>Tte(b,l),[b,l]),T=E.useMemo(()=>{let EA=0;for(const PA of[4,5,6,8,9,10])EA+=x[PA]||0;return EA},[x]),z=E.useMemo(()=>{var oe,me;const EA={};if(!l)return EA;const PA=((oe=S.myLine)==null?void 0:oe.pass)??WB(M,l),ZA=((me=S.myLine)==null?void 0:me.dontPass)??WB(w,l);PA>0&&(EA.pass=PA),ZA>0&&(EA.dontPass=ZA);for(const be of[4,5,6,8,9,10]){const $e=x[be]||0;$e>0&&(EA[`place${be}`]=$e)}const FA=WB(_,l);FA>0&&(EA.field=FA);const Ie=Eh(K,l,be=>be.kind==="big6");Ie>0&&(EA.big6=Ie);const DA=Eh(K,l,be=>be.kind==="big8");DA>0&&(EA.big8=DA);const rA=WB(J,l);rA>0&&(EA.come=rA);const BA=WB(q,l);BA>0&&(EA.dontCome=BA);const j=Eh(v,l,be=>be.passType==="pass");j>0&&(EA.oddsPass=j);const QA=Eh(v,l,be=>be.passType==="dontPass");QA>0&&(EA.oddsDontPass=QA);const dA=Eh(U,l,be=>be.kind==="atsSmall");dA>0&&(EA.atsSmall=dA);const UA=Eh(U,l,be=>be.kind==="atsTall");UA>0&&(EA.atsTall=UA);const TA=Eh(U,l,be=>be.kind==="atsAll");return TA>0&&(EA.atsAll=TA),EA},[l,(he=S.myLine)==null?void 0:he.pass,(le=S.myLine)==null?void 0:le.dontPass,M,w,x,_,K,J,q,v,U]),Z=E.useMemo(()=>{const EA=l;return EA?{pass:v0(M,EA),dontPass:v0(w,EA),field:v0(_,EA),big6:DtA(K,EA,PA=>PA.kind==="big6"),big8:DtA(K,EA,PA=>PA.kind==="big8"),come:v0(J,EA),dontCome:v0(q,EA),place4:Zy(b,EA,4),place5:Zy(b,EA,5),place6:Zy(b,EA,6),place8:Zy(b,EA,8),place9:Zy(b,EA,9),place10:Zy(b,EA,10)}:{}},[l,M,w,_,K,J,q,b]),eA=E.useCallback(EA=>Q(EA),[]),aA=E.useRef(0),sA=E.useCallback(()=>{if(!r||!l||!B.length)return;const EA=Date.now();if(!(EA-aA.current<1e3)){aA.current=EA;try{const PA=WB(M,l),ZA=WB(w,l),FA=x;for(const Ie of B){const DA=Ie.type;let rA=0;if(DA==="pass")rA=PA;else if(DA==="dontPass")rA=ZA;else if(DA.startsWith("place")){const QA=parseInt(DA.replace("place",""),10);rA=FA[QA]||0}else continue;const BA=Math.max(0,Number(Ie.amount)||0),j=Math.max(0,BA-rA);if(j>0)try{N.addBet(DA,j)}catch{}}}catch{}}},[r,l,B,M,w,x,N]);Os({onJoinedRoom:({room:EA})=>{(EA==null?void 0:EA.id)===r&&sA()},onRejoinedRoom:({room:EA})=>{(EA==null?void 0:EA.id)===r&&sA()}}),E.useEffect(()=>{if(!l)return;const EA=B.filter(PA=>{if(PA.type==="pass")return!(WB(M,l)>=PA.amount);if(PA.type==="dontPass")return!(WB(w,l)>=PA.amount);if(PA.type.startsWith("place")){const ZA=parseInt(PA.type.replace("place",""),10);return!((x[ZA]||0)>=PA.amount)}return!0});EA.length!==B.length&&Q(EA)},[l,M,w,x,B]),E.useEffect(()=>{if(!r||!l||!a||!I)return;const EA=s==null?void 0:s.gameState,PA=EA==null?void 0:EA.currentRollerId;if(!PA||PA!==l)return;const ZA=EA==null?void 0:EA.crapsPassBets,FA=EA==null?void 0:EA.crapsDontPassBets;if(!(ZA!=null&&ZA.some(DA=>DA.playerId===l&&DA.amount>0)||FA!=null&&FA.some(DA=>DA.playerId===l&&DA.amount>0)))try{a(DA=>{if(!DA||DA.id!==r)return DA;const rA=DA.gameState||{},BA=Array.isArray(rA.crapsPassBets)?rA.crapsPassBets.slice():[];return BA.push({playerId:l,amount:10}),{...DA,gameState:{...rA,crapsPassBets:BA,gameMode:rA.gameMode||"craps"}}})}catch{}},[r,s==null?void 0:s.gameState,l,a,I]);const pA=E.useCallback((EA,PA)=>{r&&(PA>0?N.addBet(EA,PA):PA<0&&N.removeBet(EA,Math.abs(PA)))},[r,N]),gA=E.useMemo(()=>{const EA=s==null?void 0:s.gameState;if((EA==null?void 0:EA.gameMode)==="craps"){const PA=EA.crapsPhase||(h!=null&&h.point?"point":"comeOut");return{point:EA.crapsPoint??(h==null?void 0:h.point)??null,phase:PA==="point"?"point":"comeOut"}}return{point:(h==null?void 0:h.point)??null,phase:h!=null&&h.point?"point":"comeOut"}},[s==null?void 0:s.gameState,h]),{reveal:yA}=kB(),{displayPoint:fA,displayPhase:RA}=qte(gA,yA);E.useEffect(()=>{if(gA.point==null&&yA){const EA=B.filter(PA=>!PA.type.startsWith("place"));EA.length!==B.length&&Q(EA)}},[gA.point,yA,B]);const qA=s==null?void 0:s.gameState,W=S.readinessDeadline??null,$=S.requiredReadyPlayers??[],L=Lte({roomId:r,userId:c,shooterState:h,roomGameState:qA,myLineFromUnified:S.myLine,betsLastUpdated:(NA=S.betsState)==null?void 0:NA.lastUpdated}),H=I?!0:L&&!p;E.useEffect(()=>(n==null||n({canRoll:H,roll:()=>d()}),()=>{n==null||n({canRoll:!1,roll:()=>{}})}),[H,n,d]),E.useEffect(()=>{try{if(!I)return;window.__debugCanRoll={canRoll:H,userId:g==null?void 0:g.id,rolling:p,shooterState:h,roomGS:qA,readyPlayers:k,requiredReadyPlayers:$,readinessDeadline:W}}catch{}},[H,g,p,h,qA,k,$,W,I]);const P=!r,tA=E.useMemo(()=>{var PA;const EA=(PA=s==null?void 0:s.gameState)==null?void 0:PA.currentRollerId;return l?EA===l:!1},[s==null?void 0:s.gameState,l]),iA=E.useMemo(()=>{const EA=tA&&gA.phase==="comeOut"&&gA.point===null;return console.log("[CrapsBetSection] canPassTurn",{isCurrentShooter:tA,phase:gA.phase,point:gA.point,result:EA}),EA},[tA,gA.phase,gA.point]),oA=!!(l&&k.includes(l)),[IA,CA]=E.useState(!1);E.useEffect(()=>{oA&&CA(!1)},[oA]);const _A=E.useRef(null),uA=E.useCallback(()=>{if(!(!r||!l||IA||oA)){CA(!0);try{m()}catch{}_A.current&&window.clearTimeout(_A.current),_A.current=window.setTimeout(()=>{CA(!1)},5e3)}},[r,l,IA,oA,m]);E.useEffect(()=>()=>{_A.current&&window.clearTimeout(_A.current)},[]);const[X,O]=E.useState(Date.now());E.useEffect(()=>{if(!W)return;const EA=window.setInterval(()=>O(Date.now()),1e3);return()=>window.clearInterval(EA)},[W]);const cA=W?Math.max(0,Math.ceil((W-X)/1e3)):0,wA=E.useMemo(()=>{var EA,PA;try{const ZA=((EA=s==null?void 0:s.gameState)==null?void 0:EA.currentRollerId)??null;if(!ZA)return null;const FA=(PA=s==null?void 0:s.players)==null?void 0:PA.find(Ie=>Ie.id===ZA);return(FA==null?void 0:FA.name)||(FA==null?void 0:FA.id)||null}catch{return null}},[s==null?void 0:s.gameState,s==null?void 0:s.players]),xA=5,YA=500,jA=E.useMemo(()=>[1,5,10,25,100],[]);return C.jsx(ApA,{roomId:r,balance:e,point:fA,phase:RA,shooterName:wA,minBet:xA,maxBet:YA,oddsMultiple:{pass:3,dontPass:3,place:1},chips:jA,pendingBets:B,onChangeBets:eA,onClearAll:()=>{Q([]),N.clearBets()},disabled:P,onRoll:()=>d(),canRoll:H,myPlayerPlaceTotal:T,myCommittedByType:z,readyPlayers:k,meId:l,onBetDelta:pA,showReadyButton:!tA,onReadyClick:uA,readyStateLabel:"Ready",readyButtonDisabled:p||IA||oA,countdownSeconds:cA,recentSettlements:S.recentSettlements,myPlayerLineTotals:S.myLine,othersTotals:Z,onPassTurn:()=>{console.log("[CrapsBetSection] onPassTurn called, invoking passTurn()"),D()},canPassTurn:iA,onChargeChange:i})}function Hte({balance:e,meId:A,readyPlayers:t,onChargeChange:i,onRollAffordanceChange:n}){return C.jsx("div",{className:"craps-bet-panel",children:C.jsx(Yte,{balance:e,meId:A,readyPlayers:t,onChargeChange:i,onRollAffordanceChange:n})})}function mtA({missions:e,streak:A,completedCount:t,totalCount:i}){const n=e.find(o=>!o.completed)||e[0],g=n!=null&&n.target?Math.min(100,Math.round(n.progress/n.target*100)):0;return C.jsxs("section",{className:"daily-missions","aria-label":"Daily missions",children:[C.jsxs("div",{className:"daily-missions__head",children:[C.jsx("span",{className:"daily-missions__title",children:"Daily"}),C.jsxs("span",{className:"daily-missions__meta",children:[t,"/",i," · ",A,"d streak"]})]}),C.jsxs("div",{className:`daily-missions__focus${n!=null&&n.completed?" daily-missions__focus--done":""}`,children:[C.jsx("span",{className:"daily-missions__label",children:(n==null?void 0:n.label)||"Missions complete"}),C.jsx("b",{className:"daily-missions__count",children:n!=null&&n.completed?"Done":`${(n==null?void 0:n.progress)||0}/${(n==null?void 0:n.target)||0}`}),C.jsx("div",{className:"daily-missions__bar","aria-hidden":"true",children:C.jsx("span",{style:{width:`${g}%`}})})]})]})}function Ote(){var c;const{infoNow:e}=Jr(),{room:A}=nI(),{meId:t}=tn(),i=(A==null?void 0:A.gameMode)||((c=A==null?void 0:A.gameState)==null?void 0:c.gameMode),n=i==="craps",g=i==="cee-lo"||!i,o=!(A!=null&&A.singlePlayer),s=E.useRef({roundSeq:0,seen:new Set}),a=E.useRef(new Map),r=E.useRef(new Map),I=l=>{if(!l)return"Unknown";const B=((A==null?void 0:A.players)||[]).find(Q=>Q.id===l);return(B==null?void 0:B.name)||"Player"};return Os({onBetsUpdated:l=>{try{const B=Number((l==null?void 0:l.roundSeq)??0)||0,Q=Array.isArray(l==null?void 0:l.openAll)?l.openAll:[];s.current.roundSeq!==B&&(s.current={roundSeq:B,seen:new Set},r.current.clear());const h=s.current.seen;if(h.size===0&&Q.length>0){for(const y of Q)y!=null&&y.id&&h.add(y.id);r.current=new Map(Q.filter(Boolean).map(y=>[y.id,y]));return}const d=r.current,p=new Map(Q.filter(Boolean).map(y=>[y.id,y]));for(const y of Q)if(!(!y||!y.id)&&!h.has(y.id)){if(h.add(y.id),y.type==="MAIN"){if(!(g&&o)||n&&t&&y.playerId===t)continue;const m=I(y.playerId),D=Math.max(0,Math.trunc(Number(y.amount)||0));D>0&&e("Main bet placed",`+z${D} — ${m}`)}else if(y.type==="SIDE"){const m=I(y.subjectId),D=Math.max(0,Math.trunc(Number(y.amount)||0));if(y.acceptedById){const S=I(y.acceptedById);D>0&&e("Side bet accepted",`z${D} — ${S} on ${m}`)}else{if(n&&t&&y.playerId===t)continue;D>0&&e("Side bet created",`+z${D} — on ${m}`)}}}for(const[y,m]of d.entries()){const D=p.get(y);if(m&&m.type==="SIDE"&&D&&D.type==="SIDE"&&!m.acceptedById&&D.acceptedById){const S=I(D.subjectId),k=Math.max(0,Math.trunc(Number(D.amount)||0)),N=I(D.acceptedById);k>0&&e("Side bet accepted",`z${k} — ${N} on ${S}`)}}for(const[y,m]of d.entries()){if((m==null?void 0:m.type)!=="SIDE")continue;if(!p.has(y)&&!m.acceptedById){const S=I(m.subjectId),k=Math.max(0,Math.trunc(Number(m.amount)||0));k>0&&e("Side bet cancelled",`-z${k} — on ${S}`)}}r.current=p}catch{}},onCrapsBetsUpdate:l=>{try{const B=(l==null?void 0:l.snapshot)||{},Q=a.current,h=new Map,d=(m,D)=>{h.set(m,(h.get(m)||0)+(Number.isFinite(D)?D:0))},p=m=>{const D=m.split("|"),S=D[0],k=D[1]||"",N=I(S);if(k.startsWith("place:"))return`Place ${k.split(":")[1]} — ${N}`;switch(k){case"pass":return`Pass — ${N}`;case"dontPass":return`Don't Pass — ${N}`;case"field":return`Field — ${N}`;case"big6":return`Big 6 — ${N}`;case"big8":return`Big 8 — ${N}`;default:return`${k} — ${N}`}},y=m=>Array.isArray(m)?m:[];for(const{playerId:m,amount:D}of y(B.crapsPassBets))d(`${m}|pass`,D);for(const{playerId:m,amount:D}of y(B.crapsDontPassBets))d(`${m}|dontPass`,D);for(const{playerId:m,amount:D}of y(B.crapsFieldBets))d(`${m}|field`,D);for(const{playerId:m,kind:D,amount:S}of y(B.crapsBigBets))d(`${m}|${D}`,S);for(const{playerId:m,point:D,amount:S}of y(B.crapsPlaceBets))d(`${m}|place:${D}`,S);for(const{playerId:m,amount:D,status:S,point:k}of y(B.crapsComeBets))d(`${m}|come${S==="POINT"&&k?":"+k:""}`,D);for(const{playerId:m,amount:D,status:S,point:k}of y(B.crapsDontComeBets))d(`${m}|dontCome${S==="POINT"&&k?":"+k:""}`,D);if(Q.size===0){a.current=h;return}for(const[m,D]of h.entries()){const S=Q.get(m)||0,k=Math.trunc(D-S);if(k>0){if(t&&m.startsWith(t+"|"))continue;e("Bet Placed",`+z${k} — ${p(m)}`)}}a.current=h}catch{}}}),E.useEffect(()=>{},[]),null}function Pte(e,A){const{rollDice:t,placeMainBet:i,cancelMainBet:n,createSideBet:g,acceptSideBet:o,cancelSideBet:s,confirmBets:a,bankerGiveUp:r,setSpectate:I,getWagers:c}=Mo(),l=B=>{if(e)try{return B()}catch(Q){return Promise.resolve({ok:!1,error:(Q==null?void 0:Q.message)||"ERR"})}};return{roll:B=>l(()=>t(e).then(Q=>(B==null||B(Q),Q)).catch(Q=>{const h={ok:!1,error:(Q==null?void 0:Q.message)||"ERR"};return B==null||B(h),h})),confirmBets:B=>l(()=>a(e).then(Q=>(B==null||B(Q),Q)).catch(Q=>{const h={ok:!1,error:(Q==null?void 0:Q.message)||"ERR"};return B==null||B(h),h})),placeMain:(B,Q)=>l(()=>i(e,B).then(h=>(Q==null||Q(h),h)).catch(h=>{const d={ok:!1,error:(h==null?void 0:h.message)||"ERR"};return Q==null||Q(d),d})),cancelMain:(B,Q)=>l(()=>n(e,B).then(h=>(Q==null||Q(h),h)).catch(h=>{const d={ok:!1,error:(h==null?void 0:h.message)||"ERR"};return Q==null||Q(d),d})),createSide:(B,Q,h)=>l(()=>g(e,{amount:B,...Q||{}}).then(d=>(h==null||h(d),d)).catch(d=>{const p={ok:!1,error:(d==null?void 0:d.message)||"ERR"};return h==null||h(p),p})),acceptSide:(B,Q)=>l(()=>o(e,B).then(h=>(Q==null||Q(h),h)).catch(h=>{const d={ok:!1,error:(h==null?void 0:h.message)||"ERR"};return Q==null||Q(d),d})),cancelSide:(B,Q)=>l(()=>s(e,B).then(h=>(Q==null||Q(h),h)).catch(h=>{const d={ok:!1,error:(h==null?void 0:h.message)||"ERR"};return Q==null||Q(d),d})),giveUpBank:B=>l(()=>r(e).then(Q=>(B==null||B(Q),Q)).catch(Q=>{const h={ok:!1,error:(Q==null?void 0:Q.message)||"ERR"};return B==null||B(h),h})),spectate:(B,Q)=>l(()=>I(e,B).then(h=>(Q==null||Q(h),h)).catch(h=>{const d={ok:!1,error:(h==null?void 0:h.message)||"ERR"};return Q==null||Q(d),d})),refreshWagers:()=>{if(e)try{c(e)}catch{}}}}function jte(e){const{isMyTurn:A,isBanker:t,diceSettled:i,hasMainBetPlaced:n,bankPointExists:g,roundEnded:o}=e;return A?i?o?{canRoll:!1,reason:"Round transition in progress"}:t&&g?{canRoll:!1,reason:"Banker point established"}:!t&&!n?{canRoll:!1,reason:"Place a main bet first"}:{canRoll:!0}:{canRoll:!1,reason:"Dice not settled"}:{canRoll:!1,reason:"Not your turn"}}const zb=Object.create(null);function zte(){switch(qs){case"ceelo":return"cee-lo";case"craps":return"craps";case"poker":return"poker";case"skills":return"skills";default:return null}}function StA(e){var i,n;const A=zte();if(!A)return!0;const t=((i=e==null?void 0:e.gameState)==null?void 0:i.gameMode)||((n=e==null?void 0:e.gameState)==null?void 0:n.mode);return t?t===A:!0}function wtA(e,A){if(!A)return"Anonymous";const t=e.find(i=>i.id===A);return(t==null?void 0:t.name)||"Anonymous"}function Zte(e){switch((e||"").toLowerCase()){case"beatsbank":return"Beats Banker";case"losestobank":return"Loses to Banker";case"tiesbank":return"Ties Banker";default:return e||"Side Bet"}}function NY(e,A){const[t,i]=E.useState(A),n=E.useRef(!1);return E.useEffect(()=>{if(!e)return;let g=!1;return(async()=>{try{const o=await dS(e);!g&&o!==null&&i(o)}catch{}n.current=!0})(),()=>{g=!0}},[e]),E.useEffect(()=>{e&&n.current&&(async()=>{try{await uL(e,t)}catch{}})()},[e,t]),[t,i]}function DZ(e,A,t){var le;const{info:i}=JL(),n=(t==null?void 0:t.autoJoin)??!0,g=qi(),o=MB(),{leaveRoom:s}=Mo(),{joinRoom:a}=nI(),r=a,I=Pte(e||null),{reveal:c,rollTrigger:l,triggerSpin:B}=kB(),{user:Q}=tn(),[h,d]=E.useState(null),{room:p}=nI(),y=(()=>{try{return nI&&nI()}catch{return null}})(),m=(y==null?void 0:y.setRoom)??null;E.useRef(null);const[D,S]=E.useState(!0),[k,N]=E.useState(null),[G,M]=E.useState(null),w=E.useRef(null),b=E.useRef(null),_=E.useRef(null);E.useRef([]);const[K,J]=E.useState(!0),[q,v]=E.useState(void 0),[U,x]=NY(e?`gp:${e}:${A}:deadline`:void 0,30),[T,z]=NY(e?`gp:${e}:${A}:serverNow`:void 0,30),[Z,eA]=NY(e?`gp:${e}:${A}:feed`:void 0,[]),[aA,sA]=E.useState([]),[pA,gA]=E.useState(null),[yA,fA]=E.useState([]),[RA,qA]=E.useState(!1),[W,$]=E.useState(!1),L=E.useRef(null),H=E.useRef(null);E.useEffect(()=>{e&&(async()=>{try{await hS(`gp:${e}:${A}:diceSettled`),await hS(`gp:${e}:${A}:diceResults`)}catch{}})()},[e,A]),E.useEffect(()=>()=>{L.current&&(window.clearTimeout(L.current),L.current=null)},[]),E.useEffect(()=>{var ZA,FA;if(!h||!h.singlePlayer){qA(!1),$(!1),L.current&&(window.clearTimeout(L.current),L.current=null),H.current=null;return}const EA=(((ZA=h.gameState)==null?void 0:ZA.gameMode)||((FA=h.gameState)==null?void 0:FA.mode))==="craps"?1:3;if(h.players.length>=EA+1){W||$(!0),qA(!1),L.current&&(window.clearTimeout(L.current),L.current=null),H.current=null;return}W||(L.current||(L.current=window.setTimeout(()=>{qA(!0),L.current=null},250)),H.current?Date.now()>H.current&&($(!0),qA(!1)):H.current=Date.now()+5e3)},[h,W]);const P=(t==null?void 0:t.listeners)??!0;Os(P?{onJoinedRoom:({room:NA})=>{d(NA),eA(EA=>[{kind:"system",message:`You joined ${NA.name}`,ts:Date.now()},...EA]);try{K===!1&&(b.current&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>{K===!1&&!w.current&&J(!0),b.current=null},$o.diceSettleClientMs));const EA=(NA==null?void 0:NA.gameState)||{};!(EA!=null&&EA.bankRoll)&&!(EA!=null&&EA.lastRoll)&&K===!1&&!w.current&&J(!0)}catch{}},onRejoinedRoom:({room:NA})=>{StA(NA)&&(d(NA),eA(EA=>[{kind:"system",message:`Rejoined ${NA.name}`,ts:Date.now()},...EA]))},onOtherLeft:({room:NA})=>{d(NA)},onOtherPlayerJoined:({room:NA})=>{d(NA),eA(EA=>[{kind:"system",message:"Another player joined.",ts:Date.now()},...EA])},onSpectatorsUpdated:NA=>{const{spectators:EA,roundSeq:PA}=NA||{};d(ZA=>{var Ie;if(!ZA)return ZA;const FA=(Ie=ZA.gameState)==null?void 0:Ie.roundSeq;return typeof PA=="number"&&typeof FA=="number"&&PA!==FA?ZA:{...ZA,gameState:{...ZA.gameState,spectators:EA??[]}}})},onDiceRolled:NA=>{const{rollerId:EA,results:PA,rank:ZA,room:FA,deadline:Ie,serverNow:DA}=NA;x(Ie),J(!1),b.current&&(window.clearTimeout(b.current),b.current=null),w.current&&window.clearTimeout(w.current),_.current=Date.now(),v(void 0),B();const rA=2e3,BA=600,j=_.current?Date.now()-_.current:0,QA=Math.max(rA-j,0)+BA;w.current=window.setTimeout(()=>{J(!0),_.current=null,FA&&d(dA=>dA?{...dA,...FA,spLevel:FA.spLevel??dA.spLevel,levelName:FA.levelName??dA.levelName}:FA),w.current=null},QA),z(DA),M(EA),v(PA)},onBetsUpdated:NA=>{var EA;(EA=NA.room)!=null&&EA.players&&d(PA=>{if(!PA)return PA;const ZA=Array.isArray(NA.room.players)?NA.room.players:[];if(!ZA.length)return PA;const FA=new Map((PA.players??[]).map(Ie=>[Ie.id,Ie]));for(const Ie of ZA){const DA=FA.get(Ie.id);FA.set(Ie.id,DA?{...DA,...Ie}:Ie)}return{...PA,players:Array.from(FA.values())}})},onSideBetCreated:NA=>{if(!NA||NA.acceptedById||!NA.subjectId||NA.subjectId!==A)return;const PA=`${wtA((h==null?void 0:h.players)??[],NA.playerId)} offered: ${Zte(NA.predicate)} for z${NA.amount}`;o.info(PA,{title:"New Side Bet"})},onLobbyRooms:void 0,onNotYourTurn:()=>{eA(NA=>[{kind:"system",message:"It’s not your turn.",ts:Date.now()},...NA])},onForceLogout:NA=>{(NA==null?void 0:NA.reason)==="session_superseded"?(EcA(),eA(EA=>[{kind:"system",message:"You logged in from another device.",ts:Date.now()},...EA])):eA(EA=>[{kind:"system",message:"You were logged out.",ts:Date.now()},...EA]),g("/lobby",{replace:!0})},onError:NA=>N(NA),onBankerChanged:NA=>{NA!=null&&NA.roomId&&d(EA=>!EA||EA.id!==NA.roomId?EA:{...EA,gameState:{...EA.gameState,banker:NA.bankerId,currentRollerId:NA.currentRollerId,roundSeq:NA.roundSeq,bankRoll:null}})},onTurnOrderUpdated:NA=>{if(!NA.room||!NA.room.gameState)return;d(NA.room);const EA=wtA(NA.room.players,NA.banker);eA(PA=>[{kind:"system",message:`${EA} is now the banker for the new round.`,ts:Date.now()},...PA])},onRoomUpdateState:NA=>{const{roomId:EA,gameState:PA,room:ZA}=NA||{},FA=(ZA==null?void 0:ZA.gameState)??PA;if(!EA||!FA||!StA(ZA??{gameState:FA}))return;const Ie=Array.isArray(ZA==null?void 0:ZA.players)?ZA.players:[],DA=rA=>{if(!Ie.length)return rA;const BA=new Map(rA.map(j=>[j.id,j]));for(const j of Ie){const QA=BA.get(j.id);BA.set(j.id,QA?{...QA,...j}:j)}return Array.from(BA.values())};d(rA=>{var UA;if(!rA||rA.id!==EA)return{...rA,gameState:FA,...Ie.length?{players:Ie}:{}};const BA=(UA=rA.gameState)==null?void 0:UA.roundSeq,j=FA==null?void 0:FA.roundSeq,QA=typeof BA=="number"&&typeof j=="number"&&BA!==j,dA={...rA,players:DA(rA.players??[]),gameState:{...rA.gameState,...FA}};if(QA&&!w.current){try{J(!0)}catch{}try{v(void 0)}catch{}try{M(null)}catch{}}return dA})}}:{}),E.useEffect(()=>()=>{w.current&&(window.clearTimeout(w.current),w.current=null),b.current&&(window.clearTimeout(b.current),b.current=null)},[]),E.useEffect(()=>{K===!1&&!w.current?(b.current&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>{if(K===!1){w.current||J(!0);try{w.current&&window.clearTimeout(w.current)}catch{}w.current=null}b.current=null},$o.diceSettleClientMs)):K===!0&&b.current&&(window.clearTimeout(b.current),b.current=null)},[K]);const iA=E.useRef(null),oA=E.useRef(void 0),IA=E.useRef(!1);iA.current=r,E.useEffect(()=>{if(!n)return;let NA=!1;if(oA.current!==e)return oA.current=e,IA.current=!1,(async()=>{var ZA,FA,Ie,DA,rA;if(!e){N("No room id provided."),S(!1);return}if(S(!0),N(null),!iA.current){N("No join ref");return}const EA=(()=>{var BA,j;try{return typeof window<"u"&&(((j=(BA=window.location)==null?void 0:BA.search)==null?void 0:j.includes("e2e=1"))||window.__E2E===!0||typeof window.sessionStorage<"u"&&window.sessionStorage.getItem("e2e")==="1")}catch{return!1}})();let PA=null;try{const BA=()=>EA?Promise.race([iA.current(e),new Promise(dA=>setTimeout(()=>dA({ok:!1,error:"e2e-timeout"}),1800))]):iA.current(e),j=zb[e]||BA();zb[e]=j;try{PA=await j}finally{delete zb[e]}}catch(BA){if(delete zb[e],!EA){N((BA==null?void 0:BA.message)||"Failed to join room."),S(!1);return}}if(typeof window<"u"&&(window.__e2eJoinAttempt={roomId:e,res:PA,ts:Date.now()}),!NA){if(!(PA!=null&&PA.ok)){if(!EA){N((PA==null?void 0:PA.error)??"Failed to join room."),S(!1);return}const BA=Date.now(),j=(Q==null?void 0:Q.id)||"e2e-user",QA=(Q==null?void 0:Q.name)||"E2E User",UA=((()=>{try{const be=new URLSearchParams(window.location.search).get("m");return be==="cee-lo"||be==="craps"?be:null}catch{return null}})()||(e!=null&&e.toLowerCase().includes("ceelo")?"cee-lo":"craps"))==="cee-lo",TA=[{id:j,name:QA,isReady:!0,balance:1e3},{id:"bank",name:"Bank",isReady:!0,balance:1e6}],oe=UA?{id:e,name:"E2E Cee-Lo Room",gameMode:"cee-lo",createdAt:BA,updatedAt:BA,bankerId:j,players:TA,gameState:{gameMode:"cee-lo",currentRollerId:j,banker:j,turnOrder:[j],roundSeq:1,bankRoll:null,turnHistory:[]}}:{id:e,name:"E2E Craps Room",gameMode:"craps",createdAt:BA,updatedAt:BA,bankerId:"bank",players:TA,gameState:{gameMode:"craps",crapsPoint:null,currentRollerId:j,turnOrder:[j],roundSeq:1,crapsPassBets:[],crapsDontPassBets:[],crapsPlaceBets:[]}};d(oe);try{m==null||m(oe)}catch{}typeof window<"u"&&(window.__e2eRoomHydrated={id:oe.id,players:oe.players.map(me=>me.id),gameMode:oe.gameState.gameMode,ts:Date.now()}),S(!1);return}d(PA.room);try{m==null||m(PA.room)}catch{}typeof window<"u"&&(window.__e2eRoomHydrated={id:(ZA=PA.room)==null?void 0:ZA.id,players:(Ie=(FA=PA.room)==null?void 0:FA.players)==null?void 0:Ie.map(BA=>BA.id),gameMode:(rA=(DA=PA.room)==null?void 0:DA.gameState)==null?void 0:rA.gameMode,ts:Date.now()});try{tf("room_join",{roomId:e})}catch{}S(!1)}})(),()=>{NA=!0,oA.current===e&&(oA.current=void 0)}},[e,n]);const CA=E.useMemo(()=>{if(!h||!A)return!1;const NA=h.gameState||{};return((NA==null?void 0:NA.gameMode)??"cee-lo")==="craps",(NA==null?void 0:NA.currentRollerId)===A},[h,A]),_A=E.useMemo(()=>{if(!h||!A)return!1;const NA=h.gameState||{},EA=(NA==null?void 0:NA.gameMode)??"cee-lo";return((NA==null?void 0:NA.banker)??(EA==="cee-lo"?NA==null?void 0:NA.currentRollerId:void 0))===A},[h,A]),{open:uA,openAll:X}=gx(e,A),O=E.useMemo(()=>(uA||[]).some(NA=>NA.type==="MAIN"&&Number(NA.amount)>0),[uA]),cA=E.useMemo(()=>(X||[]).some(NA=>NA.type==="MAIN"),[X]),wA=((le=h==null?void 0:h.gameState)==null?void 0:le.currentRollerId)??null,xA=E.useMemo(()=>{const NA=(h==null?void 0:h.gameState)||(p==null?void 0:p.gameState)||{},EA=(NA==null?void 0:NA.gameMode)??"cee-lo",PA=!!(NA!=null&&NA.roundEnded);if(EA==="craps"){const Ie=!!CA&&!!K&&!PA;return gA(Ie?null:CA?K?"Round transition in progress":"Dice not settled":"Not your turn"),fA([]),Ie}if(!(NA!=null&&NA.currentRollerId))return gA("Initializing…"),fA([]),!1;if(_A&&!cA)return gA("Waiting for bets"),fA([]),!1;const ZA=!!(NA!=null&&NA.bankRoll),FA=jte({isMyTurn:CA,isBanker:_A,diceSettled:K,hasMainBetPlaced:O,bankPointExists:ZA,roundEnded:PA});return gA(FA.reason??null),fA([]),FA.canRoll},[h==null?void 0:h.gameState,p==null?void 0:p.gameState,CA,_A,O,K,cA,h==null?void 0:h.singlePlayer]),YA=E.useCallback(()=>{e&&(s(e),g("/lobby"))},[e,s,g]),jA=E.useCallback(()=>{if(e&&xA){if(_A&&!cA){try{i("Waiting for bets")}catch{}return}if(!_A&&!O){try{i("No open challenges")}catch{}return}try{tf("roll_click",{game:"cee-lo",role:_A?"banker":"challenger"})}catch{}try{w.current&&(window.clearTimeout(w.current),w.current=null),b.current&&(window.clearTimeout(b.current),b.current=null)}catch{}v(void 0),J(!1),_.current=Date.now(),B(),w.current=window.setTimeout(()=>{J(!0),_.current=null,w.current=null},8e3),(async()=>{const NA=await I.roll(),EA=(NA==null?void 0:NA.error)||(NA==null?void 0:NA.message)||"";if(!NA||NA.ok===!1){if(w.current&&(window.clearTimeout(w.current),w.current=null),_.current=null,J(!0),/no open main bets/i.test(EA)){const PA=!!(h!=null&&h.singlePlayer);try{I.refreshWagers()}catch{}if(!PA||!_A)try{i("No open challenges")}catch{}return}return}})()}},[e,I,B,xA,_A,O,cA,h==null?void 0:h.gameState]),ie=E.useCallback(async()=>{var NA;if(e)return(NA=I.giveUpBank)==null?void 0:NA.call(I)},[e,I]),he=E.useCallback(async NA=>{var EA;if(e)return(EA=I.spectate)==null?void 0:EA.call(I,NA)},[e,I]);return{room:h,joining:D,botsHydrating:RA,error:k,isMyTurn:CA,isBanker:_A,lastRollerId:G,rollTrigger:l,diceSettled:K,diceResults:q,deadline:U,serverNow:T,canRoll:xA,canRollReason:pA,canRollBlocking:yA,handleRoll:jA,handleLeave:YA,giveUpBank:ie,setSpectateMode:he,currentRollerId:wA,readyPlayers:aA}}function Wte({meId:e,players:A,openSideBets:t,onCancelSideBet:i,onAcceptSideBet:n,offersToMe:g=[],newOffersCount:o=0,onOffersSeen:s,disabled:a=!1,betsLocked:r,hasBankRoll:I,hasRolledThisRound:c}){const l=MB(),[B,Q]=E.useState(!1),h=E.useRef(null),d=E.useMemo(()=>{var N,G;if(typeof window<"u"&&((G=(N=window.location)==null?void 0:N.search)!=null&&G.includes("e2e=1"))){const M=window.__e2eSideBets;if(Array.isArray(M)&&M.length>0)return M}return g},[g]);E.useEffect(()=>{B&&(s==null||s())},[B,s]);const p=E.useCallback(async(N,G)=>{if(!n)return;if(G&&(c!=null&&c(G))){l.info("Subject already rolled. Side bets are closed for this subject.");return}try{On()}catch{}const M=await n(N);M.ok||l.error(M.error||"Failed to accept side bet")},[n,c,l]),y=E.useCallback((N,G)=>{const M=(G||"").toLowerCase();return M==="beatsbank"||M==="subject_beats_banker"?`${N} beats Banker`:M==="losestobank"||M==="subject_loses_to_banker"?`${N} loses to Banker`:M==="tiesbank"||M==="subject_push"||M==="subject_ties_banker"?`${N} ties Banker`:`${N} side bet`},[]),m=E.useCallback(N=>{var G;return N?N==="house_global"||N==="house"?"House":((G=A.find(M=>M.id===N))==null?void 0:G.name)||"Player":"Player"},[A]);E.useEffect(()=>{const N=G=>{h.current&&!h.current.contains(G.target)&&Q(!1)};return B&&document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[B]);const D=!I&&!a,S=((d==null?void 0:d.length)??0)>0&&D&&!B,k=D?"btn btn--casino-action"+(S?" btn--casino-action--pulse":""):"btn btn--casino-action"+(D?"":" is-disabled");return C.jsxs("div",{className:"side-bet-panel",children:[C.jsxs("a",{onClick:()=>{try{s==null||s()}catch{}D&&Q(!0)},className:k,"aria-disabled":D?void 0:"true",title:D?void 0:"Side bets closed",children:[C.jsx("span",{className:"btn--casino-action__icon",children:"🎰"}),"Side bets",o>0&&C.jsx("span",{className:"sidebet-badge","aria-label":`${o} new offer${o>1?"s":""}`,children:o})]}),B&&C.jsx("div",{className:"side-bet-panel__modal",children:C.jsxs("div",{className:"side-bet-panel__modal-content",ref:h,children:[C.jsx("h3",{className:"side-bet-panel__title",children:"Side Bets"}),C.jsx("div",{className:"side-bet-panel__list",role:"list","aria-label":"Offers to you",children:d.length>0?d.map(N=>{const G=m(N.subjectId),M=y(G,N.predicate),w=N.subjectId,b=(c==null?void 0:c(w))??!1,_=w===e;return C.jsxs("div",{className:"side-bet-panel__list-item",role:"listitem",children:[C.jsxs("div",{className:"side-bet-panel__wager-info",children:[C.jsx("span",{className:"side-bet-panel__wager-amount",children:C.jsx(Vc,{mini:!0,value:N.amount})}),C.jsx("span",{className:"side-bet-panel__wager-label",children:M})]}),n&&C.jsx("button",{className:"felt-btn felt-btn--primary",onClick:()=>p(N.id,w),disabled:a||b||_||I,title:I?"Dealer rolled – side bets closed":b?"Subject already rolled this round":_?"Cannot bet on yourself":"Accept this side bet",children:"Accept"})]},N.id)}):C.jsx("div",{className:"side-bet-panel__list-item side-bet-panel__list-item--empty",role:"listitem",children:C.jsx("span",{className:"side-bet-panel__empty",children:"No offers right now."})})}),C.jsx("h3",{className:"side-bet-panel__title",style:{marginTop:14},children:"Active side bets"}),C.jsx("div",{className:"side-bet-panel__list",role:"list","aria-label":"Your active side bets",children:t&&t.length>0?t.map(N=>{const G=m(N.subjectId),M=y(G,N.predicate),w=N.acceptedById,b=N.playerId===e,_=w===e,K=m(b?w||void 0:N.playerId),J=(b||_)&&!I&&!!i,q=!b&&!_?"Only a party to the bet can cancel":I?"Dealer rolled – side bets closed":i?void 0:"Cancel not available";return C.jsxs("div",{className:"side-bet-panel__list-item",role:"listitem",children:[C.jsxs("div",{className:"side-bet-panel__wager-info",style:{flex:1},children:[C.jsx("span",{className:"side-bet-panel__wager-amount",children:C.jsx(Vc,{mini:!0,value:N.amount})}),C.jsxs("span",{className:"side-bet-panel__wager-label",children:[M,C.jsx("span",{style:{display:"block",fontSize:"0.85em",opacity:.8},children:w?`with ${K}`:"awaiting taker"})]})]}),C.jsx("button",{className:"felt-btn "+(J?"felt-btn--danger":"felt-btn--secondary"),"aria-label":"Cancel side bet",title:J?"Cancel this side bet":q||"Cannot cancel",disabled:!J||!!a,onClick:async()=>{if(!J)return;try{On()}catch{}const v=await i(N.id);v.ok||l.error(v.error||"Failed to cancel side bet")},children:"Cancel"})]},`active-${N.id}`)}):C.jsx("div",{className:"side-bet-panel__list-item side-bet-panel__list-item--empty",role:"listitem",children:C.jsx("span",{className:"side-bet-panel__empty",children:"No active side bets."})})}),C.jsx("div",{className:"side-bet-panel__cta",children:C.jsx("button",{className:"felt-btn felt-btn--secondary",onClick:()=>Q(!1),style:{marginTop:8},children:"Close"})})]})})]})}function Vte({roomId:e,meId:A,bankerId:t,players:i,gameState:n,gameplay:g}){const o=MB(),s=t===A,{myOpenMain:a,myOpenSides:r,placeSideBet:I,cancelSideBet:c,acceptSideBet:l,offersToMe:B,newOfferCount:Q,markOffersAsSeen:h}=gx(e,A),d=DZ(e,A,{autoJoin:!1}),p=(g==null?void 0:g.giveUpBank)??d.giveUpBank,y=(g==null?void 0:g.setSpectateMode)??d.setSpectateMode,m=!!(n!=null&&n.betsLocked),D=!!(n!=null&&n.bankRoll),S=(n==null?void 0:n.spectators)??[],k=S.includes(A),G=!s&&!m&&!D&&!!!a,M=s&&!m&&!D,w=E.useCallback(async()=>{try{On()}catch{}const J=await y(!k);J&&!J.ok&&o.error(J.error||"Failed to update spectate mode")},[y,k,o]),b=E.useCallback(async()=>{try{On()}catch{}try{}catch{}try{await So("Medium")}catch{}const J=await p();J&&!J.ok&&o.error(J.error||"Failed to pass bank")},[p,o]),_=(n==null?void 0:n.roundSeq)??1,K=E.useMemo(()=>{const J=(n==null?void 0:n.turnHistory)??[];return!J||!Array.isArray(J)?[]:typeof(n==null?void 0:n.roundSeq)=="number"?J.filter(q=>(q.roundSeq??_)===_):J},[n,_]);return C.jsxs(C.Fragment,{children:[s&&C.jsxs("button",{className:"btn btn--casino-action btn--casino-action--pass-bank",disabled:!M,onClick:b,"aria-label":"Pass Bank",children:[C.jsx("span",{className:"btn--casino-action__icon",children:"👑"}),"Pass Bank"]}),!s&&C.jsxs("div",{className:"betpanel__row betpanel__row--spectate",children:[C.jsx("div",{"aria-label":"Side bets",children:C.jsx(Wte,{isBanker:s,openSideBets:r,meId:A,players:i,onPlaceSideBet:J=>I({subjectId:J.playerId,predicate:J.predicate,amount:J.amount,clientBetId:J.clientBetId}),onCancelSideBet:c,onAcceptSideBet:l,offersToMe:B,newOffersCount:Q,onOffersSeen:h,roomId:e,betsLocked:m,disabled:S.includes(A),hasBankRoll:D,hasRolledThisRound:J=>!!J&&K.some(q=>q.playerId===J&&(q.roundSeq??_)===_)})}),C.jsxs("button",{className:`btn btn--casino-action${k?" btn--casino-action--active":""}`,onClick:w,disabled:!G,"aria-pressed":k,"aria-label":k?"Stop spectating this round":"Spectate this round",children:[C.jsx("span",{className:"btn--casino-action__icon",children:k?"👁️":"👀"}),k?"Spectating":"Spectate"]})]})]})}function tc({className:e,title:A,...t}){return C.jsxs("svg",{width:36,height:36,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,"aria-hidden":A?void 0:!0,role:A?"img":"presentation",...t,children:[A?C.jsx("title",{children:A}):null,C.jsx("path",{d:"M19 12H5m0 0l7-7m-7 7l7 7",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})]})}const Xte=new TextEncoder;function $te(e){const A=e instanceof Uint8Array?e:new Uint8Array(e);return Array.from(A).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Aie(e){const A=await crypto.subtle.digest("SHA-256",Xte.encode(e));return $te(A)}async function eie(e,A){return!e||!A?!1:(await Aie(e)).toLowerCase()===A.toLowerCase()}const RY=(e,A)=>`${e}:${A}`;function ipA(e){const[A,t]=E.useState({}),[i,n]=E.useState({}),g=E.useRef({});E.useEffect(()=>{t({}),n({}),g.current={}},[e]),Os({onDiceRolled:a=>{var B,Q;const r=a==null?void 0:a.fairness,I=a==null?void 0:a.rollerId,c=(r==null?void 0:r.roundSeq)??((Q=(B=a==null?void 0:a.room)==null?void 0:B.gameState)==null?void 0:Q.roundSeq);if(!r||!I||typeof c!="number")return;const l=RY(c,I);t(h=>h[l]?h:{...h,[l]:r}),delete g.current[l]},onCrapsRollResult:a=>{var B;const r=a==null?void 0:a.fairness,I=((B=a==null?void 0:a.fairness)==null?void 0:B.rollerId)||(a==null?void 0:a.currentRollerId),c=r==null?void 0:r.roundSeq;if(!r||!I||typeof c!="number")return;const l=RY(c,I);t(Q=>Q[l]?Q:{...Q,[l]:r}),delete g.current[l]},onFairnessReveal:a=>{typeof(a==null?void 0:a.roundSeq)!="number"||!a.commit||!a.serverSeed||n(r=>{const I=r[a.roundSeq];if(!I||I.commit!==a.commit)for(const c of Object.keys(g.current))c.startsWith(`${a.roundSeq}:`)&&delete g.current[c];return{...r,[a.roundSeq]:{commit:a.commit,serverSeed:a.serverSeed}}})}});const o=E.useCallback(async(a,r,I)=>{const c=RY(r,a);if(g.current[c])return g.current[c];const l=A[c],B=i[r];if(!l||!B)return g.current[c]="unverifiable","unverifiable";const h=await eie(B.serverSeed,l.commit)?"verified":"bad-commit";return g.current[c]=h,h},[A,i]),s=E.useMemo(()=>{const a=Object.keys(i).map(r=>Number(r)).filter(r=>!Number.isNaN(r));return a.length?Math.max(...a):void 0},[i]);return{proofs:A,reveals:i,verifyFor:o,lastRoundWithReveal:s}}const Xc=OGA;let Jo=null,yk=null,Dk=null,ktA=!1;async function WR(){if(Jo)return!0;try{const e=await Qi(()=>import("./index-BKNHCE58.js"),__vite__mapDeps([13,1]));return Jo=e.AdMob,yk=e.RewardAdPluginEvents,Dk=e.InterstitialAdPluginEvents,console.log("[NativeAdService] AdMob plugin loaded"),!0}catch(e){return console.warn("[NativeAdService] AdMob plugin not available:",e),!1}}let Bf=!1,mk=!1,GY=!1;const tie=45e3;function wu(e){var A;try{(A=e==null?void 0:e.remove)==null||A.call(e)}catch{}}function npA(){return{adId:gpA(),isTesting:Xc,immersiveMode:!1}}function iie(){const e=Ui.getPlatform();return e==="web"||e==="ios"?!1:e==="ios"||e==="android"}async function Gw(){if(Bf)return!0;const e=Ui.getPlatform();if(e==="web")return console.log("[NativeAdService] Skipping AdMob init on web"),!1;if(console.log(`[NativeAdService] Initializing AdMob — platform=${e} testMode=${Xc}`),ktA||(ktA=!0,console.log("[NativeAdService] Active native ad config",{appTarget:qs,platform:e,testMode:Xc,interstitialAdUnitId:gpA(),rewardedAdUnitId:mZ()})),!await WR()||!Jo)return console.error("[NativeAdService] Plugin load failed — cannot initialize"),!1;try{return await Jo.initialize({requestTrackingAuthorization:!0,initializeForTesting:Xc}),Bf=!0,console.log("[NativeAdService] AdMob initialized successfully"),!0}catch(t){return console.error("[NativeAdService] AdMob initialization failed:",t),!1}}function mZ(){const e=Ui.getPlatform();return e==="ios"?YGA:y6}function gpA(){const e=Ui.getPlatform();return e==="ios"?HGA:S6}async function opA(){if(Ui.getPlatform()==="web"||!await WR()||!Jo)return!1;Bf||await Gw();try{const t=mZ();return console.log(`[NativeAdService] prepareRewardVideoAd adId=${t} isTesting=${Xc}`),await Jo.prepareRewardVideoAd({adId:t,isTesting:Xc}),mk=!0,console.log("[NativeAdService] Rewarded ad prepared successfully"),!0}catch(t){return console.error("[NativeAdService] Failed to prepare rewarded ad:",t),!1}}async function nie(){return Ui.getPlatform()==="web"?{ok:!1,error:"NOT_NATIVE"}:!await WR()||!Jo?{ok:!1,error:"PLUGIN_NOT_AVAILABLE"}:!Bf&&!await Gw()?{ok:!1,error:"INIT_FAILED"}:new Promise(async t=>{let i=!1,n,g;const o=await Jo.addListener(yk.Rewarded,c=>{console.log("[NativeAdService] User rewarded:",c),i=!0,n=(c==null?void 0:c.type)||"chips",g=(c==null?void 0:c.amount)||jQ}),s=await Jo.addListener(yk.Dismissed,()=>{console.log("[NativeAdService] Ad dismissed, rewarded:",i),I(),t(i?{ok:!0,rewardType:n,rewardAmount:g}:{ok:!1,error:"AD_DISMISSED"})}),a=await Jo.addListener(yk.FailedToShow,c=>{console.error("[NativeAdService] Ad failed to show:",c),I(),t({ok:!1,error:"FAILED_TO_SHOW"})}),r=await Jo.addListener(yk.FailedToLoad,c=>{console.error("[NativeAdService] Rewarded ad failed to load:",c),mk=!1,I(),t({ok:!1,error:"FAILED_TO_LOAD"})}),I=()=>{wu(o),wu(s),wu(a),wu(r)};try{if(mk)console.log("[NativeAdService] Rewarded ad already prepared, skipping load");else{const c=mZ();console.log(`[NativeAdService] prepareRewardVideoAd (in show) adId=${c} isTesting=${Xc}`),await Jo.prepareRewardVideoAd({adId:c,isTesting:Xc})}mk=!1,console.log("[NativeAdService] Calling showRewardVideoAd..."),await Jo.showRewardVideoAd()}catch(c){mk=!1,console.error("[NativeAdService] Error showing ad:",c),I(),t({ok:!1,error:(c==null?void 0:c.message)||"UNKNOWN_ERROR"})}})}async function au(){if(!iie())return console.log("[NativeAdService] Interstitial disabled or unsupported on this platform"),!1;if(!await WR()||!Jo)return!1;Bf||await Gw();try{const A=npA();return console.log(`[NativeAdService] prepareInterstitial adId=${A.adId} isTesting=${Xc}`),await Jo.prepareInterstitial(A),console.log("[NativeAdService] Interstitial ad prepared successfully"),!0}catch(A){return console.error("[NativeAdService] Failed to prepare interstitial ad:",A),!1}}async function Sk(){const e=Ui.getPlatform();return e==="web"?{ok:!1,error:"NOT_NATIVE"}:e==="ios"?{ok:!1,error:"IOS_INTERSTITIAL_DISABLED"}:!await WR()||!Jo?{ok:!1,error:"PLUGIN_NOT_AVAILABLE"}:!Bf&&!await Gw()?{ok:!1,error:"INIT_FAILED"}:GY?(console.warn("[NativeAdService] Interstitial show skipped: another interstitial is already active"),{ok:!1,error:"ALREADY_SHOWING"}):(console.log(`[NativeAdService] showInterstitialAd — initialized=${Bf} testMode=${Xc}`),new Promise(async t=>{GY=!0;let i=!1,n=null,g=null,o=null,s=null,a=null;const r=()=>{wu(g),wu(o),wu(s),wu(a)},I=c=>{i||(i=!0,n&&clearTimeout(n),GY=!1,r(),t(c))};n=setTimeout(()=>{console.warn("[NativeAdService] Interstitial timed out waiting for native close/fail callback"),I({ok:!1,error:"DISMISS_TIMEOUT"})},tie),g=await Jo.addListener(Dk.Dismissed,()=>{console.log("[NativeAdService] Interstitial dismissed ✓"),I({ok:!0}),au().catch(()=>{})}),o=await Jo.addListener(Dk.Showed,()=>{console.log("[NativeAdService] Interstitial showed ✓")}),s=await Jo.addListener(Dk.FailedToLoad,c=>{console.error("[NativeAdService] Interstitial failed to load:",JSON.stringify(c)),I({ok:!1,error:"FAILED_TO_LOAD"})}),a=await Jo.addListener(Dk.FailedToShow,c=>{console.error("[NativeAdService] Interstitial failed to show:",JSON.stringify(c)),I({ok:!1,error:"FAILED_TO_SHOW"})});try{const c=npA();console.log(`[NativeAdService] prepareInterstitial (in show) adId=${c.adId} isTesting=${Xc}`),await Jo.prepareInterstitial(c),console.log("[NativeAdService] Calling showInterstitial..."),await Jo.showInterstitial()}catch(c){console.error("[NativeAdService] Error showing interstitial:",c),I({ok:!1,error:(c==null?void 0:c.message)||"UNKNOWN_ERROR"})}}))}function spA(){const e=Ui.getPlatform();return e==="ios"||e==="android"}const bY={initializeAdMob:Gw,prepareRewardedAd:opA,showRewardedAd:nie,prepareInterstitialAd:au,showInterstitialAd:Sk,isNativeAdSupported:spA},MtA=t8,NtA=OCA,RtA=PCA,Zb=jCA,Wy="ad:complete",apA=E.createContext({onHandEnd:async()=>{},onCrapsShooterTurnEnd:async()=>{},onZentaraTurnEnd:async()=>{},showAdNow:async()=>{},cancelAd:()=>{},isAdEnabled:!1,isAdShowing:!1,adConfig:{handsPerAd:OCA,crapsShooterTurnsPerAd:PCA,minIntervalMs:qh,displayDelayMs:GD,zentaraTurnsPerAd:jCA}}),Yf=()=>E.useContext(apA);function gie({children:e}){const[A,t]=E.useState(!1),[i,n]=E.useState(!1),g=spA(),o=!A&&g;E.useEffect(()=>{console.log(`[AdContext] isAdEnabled=${o} isPremium=${A} isNative=${g}`)},[o,A,g]);const s=E.useRef(!1),a=E.useRef(0),r=E.useRef(0),I=E.useRef(0),c=E.useRef(0),l=E.useRef(!1),B=E.useRef(null),Q=()=>{try{B.current&&clearTimeout(B.current),document.body.style.pointerEvents="none",B.current=setTimeout(()=>{document.body.style.pointerEvents="",B.current=null},750)}catch{}};E.useEffect(()=>{const S=async()=>{var N,G;try{const M=dr();if(!M)return;const w=await((N=M.getCustomerInfo)==null?void 0:N.call(M)),b=((G=w==null?void 0:w.entitlements)==null?void 0:G.active)||{},_=Object.keys(b).length>0;let K=!1;MtA&&(K=!!(b!=null&&b[MtA])||_),t(K)}catch{}};S();const k=setInterval(S,6e4);return()=>clearInterval(k)},[]),E.useEffect(()=>{o&&au().catch(()=>{})},[o]);const h=E.useCallback(async()=>{if(!o||s.current)return;const S=Date.now();if(!(S-c.current<qh)&&(a.current+=1,!(a.current<NtA))){s.current=!0,a.current=0,c.current=S;try{window.__adShowingDoNotDisconnect=!0,window.__adShowingPauseGame=!0}catch{}if(n(!0),l.current=!1,await new Promise(k=>setTimeout(k,GD)),l.current){console.log("[AdContext] Ad cancelled during delay phase"),s.current=!1,n(!1);try{window.__adShowingDoNotDisconnect=!1,window.__adShowingPauseGame=!1}catch{}try{window.dispatchEvent(new CustomEvent(Wy))}catch{}return}try{await Sk()}catch(k){console.warn("[AdContext] Failed to show interstitial:",k)}finally{Q(),s.current=!1,n(!1);try{window.__adShowingDoNotDisconnect=!1,window.__adShowingPauseGame=!1}catch{}try{window.dispatchEvent(new CustomEvent(Wy))}catch{}au().catch(()=>{})}}},[o]),d=E.useCallback(async()=>{if(!o||s.current)return;const S=Date.now();if(!(S-c.current<qh)&&(r.current+=1,!(r.current<RtA))){s.current=!0,r.current=0,c.current=S;try{window.__adShowingDoNotDisconnect=!0,window.__adShowingPauseGame=!0}catch{}n(!0),await new Promise(k=>setTimeout(k,GD));try{await Sk()}catch(k){console.warn("[AdContext] Failed to show interstitial (craps shooter turn):",k)}finally{Q(),s.current=!1,n(!1);try{window.__adShowingDoNotDisconnect=!1,window.__adShowingPauseGame=!1}catch{}try{window.dispatchEvent(new CustomEvent(Wy))}catch{}au().catch(()=>{})}}},[o]),p=E.useCallback(async()=>{if(console.log(`[AdContext] onZentaraTurnEnd — enabled=${o} showing=${s.current} turns=${I.current+1}/${Zb} sinceLastAd=${Date.now()-c.current}ms`),!o||s.current)return;const S=Date.now();if(S-c.current<qh){console.log(`[AdContext] Skipping ad — min interval not met (${S-c.current}ms < ${qh}ms)`);return}if(I.current+=1,I.current<Zb){console.log(`[AdContext] Skipping ad — need ${Zb} turns, have ${I.current}`);return}s.current=!0,I.current=0,c.current=S;try{window.__adShowingDoNotDisconnect=!0,window.__adShowingPauseGame=!0}catch{}n(!0),await new Promise(k=>setTimeout(k,GD));try{await Sk()}catch(k){console.warn("[AdContext] Failed to show interstitial (zentara turn):",k)}finally{Q(),s.current=!1,n(!1);try{window.__adShowingDoNotDisconnect=!1,window.__adShowingPauseGame=!1}catch{}try{window.dispatchEvent(new CustomEvent(Wy))}catch{}au().catch(()=>{})}},[o]),y=E.useCallback(async S=>{if(!o||s.current)return;const k=Date.now();if(!(!(S!=null&&S.ignoreMinInterval)&&k-c.current<qh)){s.current=!0,a.current=0,r.current=0,I.current=0,c.current=k;try{window.__adShowingDoNotDisconnect=!0,window.__adShowingPauseGame=!0}catch{}n(!0),await new Promise(N=>setTimeout(N,GD));try{await Sk()}catch(N){console.warn("[AdContext] Failed to show interstitial (showAdNow):",N)}finally{Q(),s.current=!1,n(!1);try{window.__adShowingDoNotDisconnect=!1,window.__adShowingPauseGame=!1}catch{}try{window.dispatchEvent(new CustomEvent(Wy))}catch{}au().catch(()=>{})}}},[o]),m=E.useCallback(()=>{if(s.current){console.log("[AdContext] cancelAd() called — aborting pending ad"),l.current=!0,s.current=!1,n(!1);try{window.__adShowingDoNotDisconnect=!1,window.__adShowingPauseGame=!1}catch{}try{window.dispatchEvent(new CustomEvent(Wy))}catch{}}},[]),D={handsPerAd:NtA,crapsShooterTurnsPerAd:RtA,zentaraTurnsPerAd:Zb,minIntervalMs:qh,displayDelayMs:GD};return C.jsx(apA.Provider,{value:{onHandEnd:h,onCrapsShooterTurnEnd:d,onZentaraTurnEnd:p,showAdNow:y,cancelAd:m,isAdEnabled:o,isAdShowing:i,adConfig:D},children:e})}const rpA=Ca();async function oie(e){if(!e)return null;try{const A=await uo(),t=`${rpA}/api/rooms/${encodeURIComponent(e)}/craps-history?playerScope=me&limit=200`,n=await(await fetch(t,{credentials:"include",cache:"no-store",headers:A?{Authorization:`Bearer ${A}`}:void 0})).json();return n&&n.ok&&n.data&&Array.isArray(n.data.items)?n.data.items:null}catch{return null}}async function sie(e){if(!e)return null;try{const A=await uo(),i=await(await fetch(`${rpA}/api/rooms/${encodeURIComponent(e)}/settlements?playerScope=me&limit=500`,{credentials:"include",cache:"no-store",headers:A?{Authorization:`Bearer ${A}`}:void 0})).json();return i&&i.ok&&i.data&&Array.isArray(i.data.items)?i.data.items:null}catch{return null}}const SZ=[X8,$8,A5,e5,t5,i5,n5,g5,o5];function aie(e){let A=0;for(let t=0;t<e.length;t++)A=A*31+e.charCodeAt(t)>>>0;return A%(SZ.length*6)}function rie(e){if(!e||!e.startsWith("sprite:"))return null;const A=e.slice(7).split("/"),t=Number(A[0]),i=Number(A[1]);return!Number.isFinite(t)||!Number.isFinite(i)||t<0||t>=SZ.length?null:{sheetIdx:t,tile:i%6}}function GtA({seed:e,sheetIdx:A,tile:t}){const i=aie(e),n=A??Math.floor(i/6),g=t??i%6,o=SZ[n],s=2,a=3,r=g%s,I=Math.floor(g/s),c=s*100,l=n===4?400:a*100,B=c/100,Q=l/100,h=r/(B-1)*100,d=n===8?I*37:Q>1?I/(Q-1)*100:0,p={display:"block",width:"100%",height:"100%",borderRadius:"8px",backgroundImage:`url(${o})`,backgroundSize:`${c}% ${l}%`,backgroundPosition:`${h}% ${d}%`,backgroundRepeat:"no-repeat"};return C.jsx("span",{className:"avatar-sprite",style:p,"aria-hidden":!0})}function Iie({stream:e,labelFallback:A,muted:t=!0,forceHideVideo:i=!1,active:n=!1,avatarUrl:g}){const o=E.useRef(null),[s,a]=E.useState(!1),[r,I]=E.useState(!1);E.useEffect(()=>{I(!1)},[g]);const c=E.useCallback(()=>e?e.getVideoTracks().some(d=>d.readyState==="live"&&d.enabled!==!1&&!d.muted):!1,[e]);E.useEffect(()=>{if(!e){a(!1);return}const d=()=>a(c());d();const p=new Set,y=D=>{p.has(D)||(p.add(D),D.addEventListener("mute",d),D.addEventListener("unmute",d),D.addEventListener("ended",d))};for(const D of e.getVideoTracks())y(D);const m=()=>{d();for(const D of e.getVideoTracks())y(D)};return e.addEventListener("addtrack",m),e.addEventListener("removetrack",m),()=>{for(const D of p)D.removeEventListener("mute",d),D.removeEventListener("unmute",d),D.removeEventListener("ended",d);e.removeEventListener("addtrack",m),e.removeEventListener("removetrack",m)}},[e,c]),E.useEffect(()=>{const d=o.current;if(!d||!e)return;const p=()=>{c()&&a(!0)},y=setInterval(()=>{const m=c(),D=d.readyState>=2;a(S=>D&&m&&!S?!0:!m&&S?!1:S)},1e3);return d.addEventListener("canplay",p),d.addEventListener("playing",p),()=>{clearInterval(y),d.removeEventListener("canplay",p),d.removeEventListener("playing",p)}},[e,c]),E.useEffect(()=>{const d=o.current;if(!d)return;let p=0;const y=4,m=N=>{if(!e||!e.getVideoTracks().some(w=>w.readyState==="live"&&w.enabled!==!1)||!d.paused&&d.readyState>=2)return;const M=d.play();M==null||M.catch(()=>{if(p<y){const w=150+p*200;p++,setTimeout(()=>m(`${N}:retry${p}`),w)}else try{window.dispatchEvent(new CustomEvent("rtc:videoStall",{detail:{reason:N}}))}catch{}})},D=()=>m("ui"),S=()=>{document.hidden||m("visibility")},k=()=>{if(!e||!d)return;const N=e.getVideoTracks()[0];N&&N.readyState==="live"&&d.paused&&m("pause-event")};return window.addEventListener("ui:roll",D),window.addEventListener("ui:placeMainBet",D),window.addEventListener("ui:cancelMainBet",D),document.addEventListener("visibilitychange",S),d.addEventListener("pause",k),()=>{window.removeEventListener("ui:roll",D),window.removeEventListener("ui:placeMainBet",D),window.removeEventListener("ui:cancelMainBet",D),document.removeEventListener("visibilitychange",S),d.removeEventListener("pause",k)}},[e]),E.useLayoutEffect(()=>{const d=o.current;if(d){try{d.setAttribute("playsinline","true"),d.setAttribute("webkit-playsinline","true"),d.setAttribute("muted",t?"true":"false"),d.disablePictureInPicture=!0}catch{}if(d.srcObject!==e&&(d.srcObject=e??null),e){d.muted=!!t;const p=()=>{d.play().catch(()=>{setTimeout(()=>{d.play().catch(()=>{})},160)})};p(),d.onloadedmetadata=p}else d.onloadedmetadata=null}},[e,t]);const l=!i&&!!e&&s,B=E.useMemo(()=>rie(g),[g]),Q=E.useCallback(()=>I(!0),[]),h=B?C.jsx(GtA,{seed:A,sheetIdx:B.sheetIdx,tile:B.tile}):g&&!r?C.jsx("img",{src:g,alt:A,className:"avatar-uploaded",style:{width:"100%",height:"100%",objectFit:"cover"},onError:Q}):C.jsx(GtA,{seed:A});return i||!e?C.jsx("div",{className:`avatar-shell is-avatar ${n?"is-rolling":""}`,children:h}):C.jsxs("div",{className:`avatar-shell ${n?" is-rolling":""}`,style:{position:"relative",overflow:"hidden"},children:[C.jsx("div",{className:`avatar-image ${n?"is-rolling":""}`,style:{position:"absolute",inset:0,opacity:l?0:1,transition:"opacity 160ms ease",display:"flex",alignItems:"center",justifyContent:"center",background:"radial-gradient(circle at 30% 35%, #2e2e2e, #141414)"},children:h}),C.jsx("video",{ref:o,playsInline:!0,autoPlay:!0,muted:t,className:"avatar-video",style:{width:"100%",height:"100%",objectFit:"cover",background:"#000",position:"relative",opacity:l?1:0,transition:"opacity 160ms ease"}})]})}function Cie(e,A){return!(e.forceHideVideo!==A.forceHideVideo||e.muted!==A.muted||e.stream!==A.stream||e.avatarUrl!==A.avatarUrl||e.active!==A.active||e.labelFallback!==A.labelFallback)}const cie=E.memo(Iie,Cie);function lie(e){var g,o;const t=e.split("@")[0].trim().split(/[\s._-]+/).filter(Boolean),i=(((g=t[0])==null?void 0:g[0])??"").toUpperCase(),n=(((o=t[1])==null?void 0:o[0])??"").toUpperCase();return i+n||i||"?"}function wZ(e){if(!e||e.length!==3)return"nothing";const A=new Set(e);if(A.size===1)return"triple";const t=[...e].sort().join("");return t==="123"?"123":t==="456"?"456":A.size===2?"point":"nothing"}function dM(e,A){return wZ(e)}function btA(e,A,t,i,n){if(!e)return null;if(e===t)return n||null;for(let g=A.length-1;g>=0;g--){const o=A[g];if(o.playerId===e&&Array.isArray(o.result)&&o.result.length===3)return o.result}return null}function UY(e){if(!e||e.length!==3)return{score:0,label:"—",kind:"invalid"};const A=wZ(e);if(A==="456")return{score:1e4,label:"4-5-6 (Auto Win)",kind:A};if(A==="123")return{score:2e3,label:"1-2-3 (Auto Lose)",kind:A};if(A==="triple"){const t=e[0];return{score:8e3+t*100,label:`Triple ${t}s`,kind:A}}if(A==="point"){const t={};for(const n of e)t[n]=(t[n]||0)+1;let i;for(const[n,g]of Object.entries(t))if(g===1){i=Number(n);break}return i==null?{score:0,label:e.slice().sort().join("-"),kind:"nothing"}:{score:4e3+i*100,label:`Point ${i}`,kind:A,point:i}}return A==="nothing"?{score:0,label:e.slice().sort().join("-"),kind:A}:{score:0,label:e.slice().sort().join("-"),kind:A}}function IpA(e){const{anchorRect:A,anchorEl:t,onClose:i,onMessages:n,onSendMoney:g,onAddFriend:o,onUnfriend:s,onBlockUser:a,onViewProfile:r,isFriend:I,isBlocked:c,hideAddFriend:l}=e,[B,Q]=E.useState({top:0,left:0}),[h,d]=E.useState(!1),p=E.useRef(null),y=E.useRef(Date.now());if(E.useLayoutEffect(()=>{if(!A)return;Q({top:A.bottom+8,left:A.left}),y.current=Date.now(),d(!0)},[A]),E.useLayoutEffect(()=>{if(!A||!p.current)return;const S=p.current.getBoundingClientRect(),k=window.innerWidth,N=window.innerHeight,G=8,M=window.visualViewport,w=M?M.offsetTop:0,b=parseInt(getComputedStyle(document.documentElement).getPropertyValue("padding-top"))||0;let _=A.bottom+G,K=A.left;K+S.width>k-G&&(K=Math.max(G,k-S.width-G)),_+S.height>N-G&&(_=Math.max(G+b+w,A.top-S.height-G)),_<G+b+w&&(_=G+b+w),K<G&&(K=G),Q({top:_,left:K})},[A,h]),E.useEffect(()=>{const D=M=>{if(Date.now()-y.current<120)return;const w=M.target;t&&(t===w||t.contains(w))||p.current&&(p.current.contains(w)||i())},S=M=>{M.key==="Escape"&&i()};let k=null;const N=()=>{Date.now()-y.current<120||(k&&window.clearTimeout(k),k=window.setTimeout(()=>i(),120))},G=N;return document.addEventListener("mousedown",D),window.addEventListener("keydown",S),window.addEventListener("scroll",N,{passive:!0,capture:!0}),window.addEventListener("resize",G),()=>{document.removeEventListener("mousedown",D),window.removeEventListener("keydown",S),window.removeEventListener("scroll",N,{capture:!0}),window.removeEventListener("resize",G),k&&window.clearTimeout(k)}},[i,t]),!A)return null;const m=C.jsxs("div",{className:"avatar-context-menu",style:{top:B.top,left:B.left},ref:p,role:"menu","aria-label":"Player actions",onMouseDown:D=>D.stopPropagation(),children:[r&&C.jsx("button",{role:"menuitem",onClick:()=>{r(),i()},className:"avatar-context-menu__item",children:"View Profile"}),n&&C.jsx("button",{role:"menuitem",onClick:()=>{n==null||n(),i()},className:"avatar-context-menu__item",children:"Messages"}),!I&&!l&&o&&C.jsx("button",{role:"menuitem",onClick:()=>{o(),i()},className:"avatar-context-menu__item",disabled:!!I||!!c||!o,title:I?"Already friends":c?"User is blocked":"Add Friend",children:I?"Friend ✓":"Add Friend"}),I&&s&&C.jsx("button",{role:"menuitem",onClick:()=>{s(),i()},className:"avatar-context-menu__item",children:"Unfriend"}),C.jsx("button",{role:"menuitem",onClick:()=>{a==null||a(),i()},className:"avatar-context-menu__item",disabled:!a,title:c?"Unblock user":"Block user",children:c?"Unblock":"Block"})]});return typeof document<"u"?er.createPortal(m,document.body):m}function CpA({targetId:e,anchorRect:A,anchorEl:t,onClose:i,onOpenDM:n,onOpenSendMoney:g,meId:o}){const{friends:s,friendRequests:a,isBlocked:r,blockUser:I,unblockUser:c,addFriend:l,removeFriend:B}=Kd();qi();const Q=a.some(h=>h.status==="PENDING"&&h.fromUserId===o&&h.toUserId===e);return C.jsx(IpA,{anchorRect:A,anchorEl:t,onClose:i,onMessages:n?()=>{n(e),i()}:void 0,onSendMoney:()=>{g==null||g(e),i()},hideAddFriend:Q,onAddFriend:()=>{!s.find(h=>h.id===e)&&!r(e)&&l(e)},onUnfriend:()=>{s.find(h=>h.id===e)&&B(e)},onBlockUser:async()=>{r(e)?await c(e):await I(e)},isFriend:!!s.find(h=>h.id===e),isBlocked:r(e)})}const Bie=E.forwardRef(function({id:A,display:t,isCurrentRoller:i,isMe:n,balance:g,isSpectating:o=!1,folded:s=!1,tags:a,stream:r,diceResult:I,onOpenMenu:c,showMenu:l,menuProps:B,forceHideVideo:Q,actDeadlineTs:h,avatarUrl:d,showActingTimerRing:p=!0,presenceStatus:y},m){const D=lie(t);return C.jsxs(XI.li,{layout:!0,layoutDependency:A,transition:{type:"spring",stiffness:420,damping:38,mass:.6},ref:m,className:["player","player--avatar",i?"is-rolling":"",n?"is-me":"",s?"player--folded":""].join(" "),"data-player-id":A,title:`${t}${a.length?" · "+a.join(" · "):""}`,"aria-label":`${t}${a.length?", "+a.join(", "):""}`,children:[C.jsxs("div",{className:["avatar-ring",i?"is-rolling":""].join(" "),onClick:S=>{S.stopPropagation(),c(A,S.currentTarget)},onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),c(A,S.currentTarget))},role:"button",tabIndex:0,"aria-haspopup":"menu","aria-expanded":l,children:[C.jsx(cie,{active:i,stream:r,labelFallback:D,muted:n,forceHideVideo:Q,avatarUrl:d}),typeof g=="number"&&C.jsx("div",{className:"avatar-balance-pill","aria-label":`Balance ${C_(g)}`,children:C_(g)})]}),n&&C.jsx("span",{className:"status-dot","aria-hidden":!0}),!n&&y&&C.jsx("span",{className:`presence-dot presence-dot--${y}`,"aria-label":y==="active"?"Online":"Away"}),C.jsxs("div",{className:"player-mini",children:[C.jsxs("div",{className:"player-name",children:[C.jsx("span",{className:"player-name__text",children:t}),a.includes("B")&&C.jsx("span",{className:"player-tag tag--B","aria-label":"Banker",children:"BANK"}),a.includes("D")&&C.jsx("span",{className:"player-tag tag--D","aria-label":"Dealer",children:"D"}),a.includes("SB")&&C.jsx("span",{className:"player-tag tag--SB","aria-label":"Small blind",children:"SB"}),a.includes("BB")&&C.jsx("span",{className:"player-tag tag--BB","aria-label":"Big blind",children:"BB"})]}),o&&C.jsx("div",{className:"player-spectating","aria-label":"spectating",children:"spectating"}),C.jsx("div",{className:"player-faces",children:I??C.jsx("span",{style:{display:"inline-block",height:22},"aria-hidden":!0})})]}),l&&B&&C.jsx(CpA,{...B})]})}),cpA=[X8,$8,A5,e5,t5,i5,n5,g5,o5];function Eie(e){let A=0;for(let t=0;t<e.length;t++)A=A*31+e.charCodeAt(t)>>>0;return A%(cpA.length*6)}function Qie({seed:e}){const A=Eie(e),t=Math.floor(A/6),i=A%6,n=cpA[t],g=2,o=3,s=i%g,a=Math.floor(i/g),r={display:"block",width:"100%",height:"100%",borderRadius:"8px",backgroundImage:`url(${n})`,backgroundSize:`${g*100}% ${o*100}%`,backgroundPosition:`${s*(100/(g-1))}% ${a*(100/(o-1))}%`,backgroundRepeat:"no-repeat"};return C.jsx("span",{className:"avatar-sprite",style:r,"aria-hidden":!0})}function RK({players:e,meId:A,className:t,showBalance:i=!1,onPlayerClick:n,renderActions:g}){return C.jsx("div",{className:["card",t].filter(Boolean).join(" "),children:C.jsx("ul",{className:"players players--avatars",role:"list",children:e.map((o,s)=>{const a=o.id??String(s),r=o.name??a;return C.jsxs("li",{className:["player","player--avatar",a===A?"is-me":""].join(" "),"data-player-id":a,title:r,"aria-label":r,onClick:()=>n==null?void 0:n(a),role:n?"button":void 0,tabIndex:n?0:-1,onKeyDown:I=>{n&&(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),n(a))},children:[C.jsx("div",{className:"avatar-ring","aria-hidden":!0,children:C.jsx("div",{className:"video-bubble",children:C.jsx(Qie,{seed:o.id})})}),a===A&&C.jsx("span",{className:"status-dot","aria-hidden":!0}),C.jsxs("div",{className:"player-info",children:[C.jsx("div",{className:"player-name",children:r}),i&&C.jsx("div",{className:"player-bank",children:C.jsxs("b",{children:["$",o.balance??0]})})]}),g==null?void 0:g(o)]},a)})})})}function kZ(){const[e,A]=E.useState(null),[t,i]=E.useState(null),[n,g]=E.useState(null);return{forUserId:e,anchorRect:t,anchorEl:n,openFor:(a,r)=>{r&&(A(a),g(r),i(r.getBoundingClientRect()))},close:()=>{A(null),i(null),g(null)}}}function lpA({players:e,meId:A,className:t,onOpenDM:i,onOpenSendMoney:n,renderActionsOverride:g}){const{forUserId:o,anchorRect:s,anchorEl:a,openFor:r,close:I}=kZ(),c=(B,Q)=>{!Q||B===A||r(B,Q)},l=()=>I();return C.jsxs("div",{className:t,children:[C.jsx(RK,{className:"card",players:e,meId:A,showBalance:!1,renderActions:g?B=>g(B):B=>C.jsx("button",{className:"btn btn-xs",onClick:Q=>c(B.id,Q.currentTarget),"aria-haspopup":"menu","aria-expanded":o===B.id,style:{marginLeft:"auto"},children:"⋯"})}),!g&&o&&C.jsx(CpA,{targetId:o,anchorRect:s,anchorEl:a,onClose:l,onOpenDM:i,onOpenSendMoney:n,meId:A})]})}function uie(e,A,t,i){const n=E.useRef(new Map),g=E.useRef(new Map),[o,s]=E.useState(0),a=E.useRef(i),r=E.useRef(0),I=E.useCallback(c=>{n.current.get(c)||(n.current.set(c,!0),g.current.set(c,performance.now()),s(l=>l+1))},[]);return E.useEffect(()=>{a.current!==i&&(n.current.clear(),g.current.clear(),r.current=0,s(c=>c+1),a.current=i)},[i]),E.useEffect(()=>{for(let c=r.current;c<e.length;c++){const l=e[c],B=l.result;dM(B,l.playerId===A)!=="nothing"&&I(l.playerId)}r.current=e.length},[e,I,A]),E.useEffect(()=>{var l;if(!A||!((l=t.bankRoll)!=null&&l.raw))return;dM(t.bankRoll.raw)!=="nothing"&&I(A)},[A,t.bankRoll,I]),{revealedPlayers:n.current,revealTimesRef:g,revealVersion:o,markRevealed:I}}function die(e){if(!e)return"Side Bet";switch(e.toLowerCase()){case"subject_beats_banker":case"beatsbank":return"Beats Banker";case"subject_loses_to_banker":case"losestobank":return"Loses to Banker";case"subject_push":case"tiesbank":return"Ties Banker";default:return e}}function hie(e){if(!e)return"side bet";switch(e.toLowerCase()){case"subject_beats_banker":case"beatsbank":return"beats banker";case"subject_loses_to_banker":case"losestobank":return"loses to banker";case"subject_push":case"tiesbank":return"ties banker";default:return e}}function MZ(e,A){if(!e)return{outcome:null,isChallenger:!1,needsAnimation:!1};const t=e.type==="MAIN"||e.type==="SIDE"?e.type:e.predicate||e.subjectId?"SIDE":"MAIN";let i=null,n=!1,g=!1,o,s=typeof e.result=="string"?e.result.toUpperCase():"",a=!1;if(!s||!["WIN","LOSE","PUSH","TIE"].includes(s)){const c=lf(e,A);c&&c.myResult&&(s=c.myResult.toUpperCase(),a=!0)}const r=s==="WIN"||s==="LOSE",I=s==="PUSH"||s==="TIE";if(!r&&!I)return{outcome:null,isChallenger:!1,needsAnimation:!1};if(a)return r?i=s==="WIN"?"win":"lose":i="push",g=r,{outcome:i,isChallenger:n,subtitle:o,needsAnimation:g};if(t==="MAIN"){const c=e.acceptedById||e.bankerId,l=e.playerId;if(!c||!l)return{outcome:null,isChallenger:!1,needsAnimation:!1};r?(A===l?(i=s==="WIN"?"win":"lose",n=!0):A===c?i=s==="WIN"?"lose":"win":i=null,g=!0):I&&((A===l||A===c)&&(i="push"),g=!0)}else{const c=e.playerId,l=e.acceptedById||void 0;if(r?(A===c?(i=s==="WIN"?"win":"lose",n=!0):A===l?i=s==="WIN"?"lose":"win":i=null,g=!!(c&&l)):I&&((A===c||A===l)&&(i="push"),g=!1),e.predicate||e.subjectId){const B=[];e.predicate&&B.push(die(e.predicate)),e.subjectId&&B.push(`on ${e.subjectId}`),B.length&&(o=B.join(" "))}}return{outcome:i,isChallenger:n,subtitle:o,needsAnimation:g}}function pie(e,A){const t=e.acceptedById||e.bankerId,i=e.playerId;if(!t||!i)return null;let n,g;const o=String(e.result||"").toUpperCase();if(o==="WIN")n=t,g=i;else if(o==="LOSE")n=i,g=t;else return null;if(!n||!g||n===g)return null;const s=A(n),a=A(g);if(!s||!a||Math.hypot(a.x-s.x,a.y-s.y)<4)return null;const I=Number(e.amount)||1;return{id:`${n}-${g}-${e.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,settlementId:String(e.id),amount:I,fromId:n,toId:g,startX:s.x,startY:s.y,endX:a.x,endY:a.y}}function BpA(e,A,t,i){if(!Array.isArray(e)||e.length===0)return[];const n=[];for(const g of e){if(!g)continue;const o=g.type?g.type:g.predicate||g.subjectId?"SIDE":"MAIN",s={...g,type:o};s.type==="MAIN"&&!s.acceptedById&&!s.bankerId&&i&&(s.bankerId=i||void 0),!(typeof s.roundSeq!="number"||s.roundSeq!==A)&&(t.has(s.id)||(t.add(s.id),n.push(s)))}return n}const fie={1:LBA,2:xBA,3:TBA,4:qBA,5:YBA,6:HBA};function EpA({dice:e}){return!e||!e.length?null:C.jsx("div",{className:"dice-results-icons",style:{display:"flex",gap:2},children:e.map((A,t)=>C.jsx("img",{src:fie[A],alt:`Dice face ${A}`,style:{width:22,height:22,borderRadius:"4px"}},t))})}function NZ(){const[e,A]=E.useState(!1),[t,i]=E.useState(!0);E.useEffect(()=>{let g=!0;return(async()=>{try{const o=await Xo();g&&(i(o.showAnimations!==!1),A(!0))}catch{g&&A(!0)}})(),()=>{g=!1}},[]);const n=E.useCallback(async g=>{const o=typeof g=="boolean"?g:!t;i(o);try{const s=await Xo(),a={...ds,...s,showAnimations:o};await JE(a)}catch{}},[t]);return{ready:e,showAnimations:t,toggleAnimations:n}}const QpA=[1,5,10,25,100,500];var GK=(e=>(e.FREE="FREE",e.PREMIUM="PREMIUM",e))(GK||{});const Wb={1:[0,0,-Math.PI/2],2:[0,0,Math.PI/2],3:[Math.PI,0,0],4:[0,0,0],5:[Math.PI/2,0,0],6:[-Math.PI/2,0,0]},yie=[500,100,25,10,5,1],vY=20;function RZ(e){const A=[];let t=Math.max(1,Math.floor(e));for(const i of yie){for(;t>=i&&(A.push(i),t-=i,!(A.length>=vY)););if(A.length>=vY)break}return t>0&&A.length<vY&&A.push(t),A.length===0&&A.push(1),A}function upA({anim:e,onComplete:A}){const{showAnimations:t}=NZ(),i=t===!1,n=E.useRef(!1),g=E.useRef(e).current,{amount:o,startX:s,startY:a,endX:r,endY:I}=g,c=E.useRef([]);if(c.current.length===0){const B=RZ(o),Q=Math.max(0,g.startDelaySec??.25),h=Math.min(8,Math.ceil(B.length/2)),d=(B.length-1)/2;c.current=B.map((p,y)=>({id:`${e.id}-sub-${y}`,value:p,delay:Q+y*.05,yOffset:(y-d)*(h>1?4:0)}))}const l=E.useCallback(()=>{n.current||(n.current=!0,A())},[A]);return E.useEffect(()=>{if(i)return Promise.resolve().then(()=>{try{l()}catch{}}),()=>{};const B=c.current.map(p=>p.delay),h=(B.length?Math.max(...B):0)*1e3+900,d=window.setTimeout(l,h);return()=>{window.clearTimeout(d)}},[i,l]),i?null:C.jsx("div",{style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:5},children:(()=>{const B=c.current.map(Q=>Q.delay);return B.length&&Math.min(...B),c.current.map((Q,h)=>{const d=s-18,p=r-18,y=a-18+Q.yOffset,m=I-18+Q.yOffset;return C.jsx(XI.div,{initial:{x:d,y,scale:.85,opacity:0},animate:{x:p,y:m,scale:1.05+h%3*.03,opacity:1},transition:{delay:Q.delay,type:"spring",stiffness:150,damping:20,duration:.55+h%4*.03},onAnimationComplete:()=>{h===c.current.length-1&&l()},style:{position:"absolute"},children:C.jsx(Vc,{mini:!0,value:Q.value,className:"chip--flight"})},Q.id)})})()})}const z3=new Set;function Die(e){return z3.add(e),()=>z3.delete(e)}function mie(e){e&&z3.forEach(A=>{try{A(e)}catch{}})}function Sie({newSettlements:e,roundSeqNow:A,getAvatarCenter:t,getPlayerName:i,myId:n,bankerDice:g,bankerId:o,isPartyReady:s,onAnimCompleteBySettlement:a}){const[r,I]=E.useState([]),[c,l]=E.useState([]),B=E.useRef(new Set),Q=E.useRef(new Set),h=E.useRef(null),d=E.useRef(new Set),p=E.useCallback(M=>(Q.current.add(M),M),[]),y=E.useCallback(()=>{Q.current.forEach(M=>clearTimeout(M)),Q.current.clear(),h.current!=null&&(cancelAnimationFrame(h.current),h.current=null)},[]);E.useEffect(()=>()=>{y()},[y]);const m=E.useCallback(M=>t(M),[t]),D=E.useCallback(M=>pie(M,m),[m]),S=E.useCallback((M,w=0)=>{if(s&&(M==null?void 0:M.type)==="MAIN"){const x=M==null?void 0:M.playerId,T=(M==null?void 0:M.acceptedById)||(M==null?void 0:M.bankerId);if(!(!!x&&s(x)&&!!T&&s(T))){p(setTimeout(()=>S(M,w),120));return}}const _=(M==null?void 0:M.acceptedById)||(M==null?void 0:M.bankerId),K=M==null?void 0:M.playerId;if(!_||!K){if(w>25)return;const x=80+w*60;p(setTimeout(()=>S(M,w+1),x));return}const J=String(M.result||"").toUpperCase();let q,v;if(J==="WIN"?(q=_,v=K):J==="LOSE"&&(q=K,v=_),q&&v){const x=m(q),T=m(v);if(!x||!T){if(w>25)return;if(w<5&&typeof requestAnimationFrame<"u")h.current=requestAnimationFrame(()=>S(M,w+1));else{const z=80+w*60;p(setTimeout(()=>S(M,w+1),z))}return}}if(w>25)return;const U=D(M);if(!U){const x=80+w*60;w<5&&typeof requestAnimationFrame<"u"?h.current=requestAnimationFrame(()=>S(M,w+1)):p(setTimeout(()=>S(M,w+1),x));return}I(x=>[...x,[U]])},[D,s,p]);E.useEffect(()=>{if(!e.length)return;const M=BpA(e,A,B.current,o);for(const w of M){if(d.current.has(w.id))continue;d.current.add(w.id);const{outcome:b,needsAnimation:_}=MZ(w,n);_&&p(setTimeout(()=>S(w),200))}},[e,A,n,o,S]),E.useEffect(()=>{c.length===0&&r.length>0&&(l(r[0]),I(M=>M.slice(1)))},[c.length,r]);const k=E.useCallback(M=>{l(w=>{const b=w.filter(K=>K.id!==M),_=w.find(K=>K.id===M);try{_!=null&&_.settlementId&&typeof a=="function"&&a(_.settlementId),_!=null&&_.settlementId&&(mie(_.settlementId),B.current.add(_.settlementId))}catch{}return b})},[a]),N=E.useCallback(()=>{y(),I([]),l([]),B.current.clear(),d.current.clear()},[y]),G=E.useCallback(M=>{M!=null&&M.length&&I(w=>[...w,M])},[]);return{activeBatch:c,handleAnimItemComplete:k,resetForRound:N,queueBatch:G}}function wie(){const{hasActive:e}=Jr(),A=E.useRef([]),t=E.useRef(!1),i=E.useRef(null),n=E.useRef(new Set),g=E.useCallback(()=>{So("Light").catch(()=>{})},[]),o=()=>typeof performance<"u"&&performance.now?performance.now():Date.now(),s=($o==null?void 0:$o.diceToChipDelayMs)+600,a=E.useCallback(()=>{if(t.current)return;t.current=!0;const l=()=>{i.current&&(window.clearTimeout(i.current),i.current=null);const B=A.current;if(!B.length){t.current=!1;return}const Q=B[0],h=o();if(h<Q.readyAt){i.current=window.setTimeout(l,Math.min(500,Math.max(20,Q.readyAt-h)));return}if(Q.revealGate){const p=Q.revealGate,y=p.challengerId?p.getRevealTime(p.challengerId):void 0,m=p.bankerId?p.getRevealTime(p.bankerId):void 0;if(typeof y=="number"&&typeof m=="number"){const S=Math.max(y,m)+p.postRevealDelayMs;if(h<S){const k=Math.min(S-h,1e3);i.current=window.setTimeout(l,Math.max(50,k));return}}else if(h-Q.enqueuedAt<s){i.current=window.setTimeout(l,120);return}}try{g()}catch{}try{Q.run()}catch{}const d=B.shift();d!=null&&d.key&&n.current.add(d.key),i.current=window.setTimeout(l,0)};l()},[g]),r=E.useCallback((l,B)=>{const Q=Math.max(0,typeof(B==null?void 0:B.delayMs)=="number"?B.delayMs:0),h=o(),d=h+(B!=null&&B.immediate?0:Q);if(B!=null&&B.key){if(n.current.has(B.key))return;n.current.add(B.key)}A.current.push({run:l,readyAt:d,revealGate:B==null?void 0:B.revealGate,key:B==null?void 0:B.key,enqueuedAt:h}),a()},[a]),I=E.useCallback(()=>{i.current&&(window.clearTimeout(i.current),i.current=null),t.current=!1,a()},[a]),c=E.useCallback(()=>{i.current&&(window.clearTimeout(i.current),i.current=null),A.current=[],t.current=!1},[]);return{schedule:r,nudge:I,clear:c,hasActive:e}}function kie({newSettlements:e,roundSeqNow:A,myId:t,bankerDice:i,getPlayerName:n,getPlayerAvatarUrl:g,getPlayerDice:o,getRevealTime:s,postRevealDelayMs:a=0,bankerId:r}){const{win:I,lose:c,push:l}=Jr(),B=E.useRef(new Set),{schedule:Q,nudge:h,clear:d}=wie(),p=E.useRef(null),y=E.useRef(!1),m=E.useRef(!1);E.useRef(new Set);const D=E.useRef(new Set),S=E.useRef(null);E.useEffect(()=>{const M=i;if(!M||M.length!==3){p.current=null,y.current=!1;return}const w={};for(const K of M)w[K]=(w[K]||0)+1;const b=Object.keys(w).map(Number);b.length===2&&b.some(K=>w[K]===1)?p.current=b.find(K=>w[K]===1):p.current=null;try{const K=[...M].sort((J,q)=>J-q).join(",");y.current=K==="4,5,6",m.current=K==="1,2,3"}catch{y.current=!1,m.current=!1}},[i]);const k=E.useCallback((M,w)=>{const b=w||`${A}:${M}:${Date.now()}`;D.current.has(b)||(D.current.add(b),M==="win"?(XP({volume:.18}),window.setTimeout(()=>{try{UcA("win",{volume:.4})}catch{}},90)):M==="lose"?y8({volume:.08}):GcA({volume:.09}))},[A]),N=E.useCallback((M,w,b,_,K,J,q,v)=>{if(k(M,v),M==="win"||M==="lose")try{window.dispatchEvent(new CustomEvent("ceelo:result",{detail:{result:M}}))}catch{}const U=w?" Clutch":"",x=J?J.replace(/^(won|lost)\s*/i,"").trim():"",T=q!=null&&q.length?{playerAvatars:q}:void 0;if(_)M==="win"?I(`${_}${U}`,b,void 0,void 0,T):M==="lose"?c(_,b,void 0,void 0,T):l(_,b,void 0,void 0,T);else if(K)M==="win"?I("win",b,void 0,void 0,T):M==="lose"?c("lose",b,void 0,void 0,T):l("push",b,void 0,void 0,T);else{const z=x?`Won ${x}!${U}`:`You Won!${U}`,Z=x?`Lost ${x}!`:"You Lost!";M==="win"?I(z,b,void 0,void 0,T):M==="lose"?c(Z,b,void 0,void 0,T):l("Push!",b,void 0,void 0,T)}},[k,I,c,l]),G=E.useCallback((M,w,b,_,K,J={})=>{const q=w&&(p.current??0)>=5&&M==="win";Q(()=>N(M,q,b,_,K,void 0,void 0,J.key),J)},[Q,N]);E.useEffect(()=>{const M=BpA(e,A,B.current,r);if(M.length)for(const w of M){const{outcome:b,isChallenger:_,subtitle:K,needsAnimation:J}=MZ(w,t);if(!b)continue;let q=K,v=!1;if(w.type==="SIDE"){const fA=w.subjectId&&n(w.subjectId)||w.subjectId||"Player",RA=hie(w.predicate);let qA;b==="win"?qA=`${fA} ${RA}`:b==="lose"?RA==="beats banker"?qA=`${fA} does not beat banker`:RA==="loses to banker"?qA=`${fA} does not lose to banker`:RA==="ties banker"?qA=`${fA} does not tie banker`:qA=`${fA} ${RA}`:qA=`${fA} ${RA}`,q=qA,v=!0}else K&&w.subjectId&&K.includes("on ")&&(q=K.replace(/on \S+$/,`on ${n(w.subjectId)||w.subjectId}`));try{const fA=lf(w,t);if(fA&&fA.label&&!(w.type==="SIDE"&&v)){const qA=String(fA.label||"").trim(),W=String(q||"").trim();if(W.length===0)q=qA;else if(qA.length>0){const $=W.toLowerCase(),L=qA.toLowerCase();$.includes(L)||(q=`${W} — ${qA}`)}}}catch{}b==="push"&&((q||"").trim()||(q="No Action"));const U=w.type==="SIDE"?w.subjectId||void 0:w.playerId,x=w.type==="SIDE"?r:w.acceptedById||w.bankerId||r,T=!!(y.current||m.current),z=T||w.type==="SIDE"?!1:J,Z=T?!0:!z,eA=!T&&z?$o.diceToChipDelayMs+50:0,aA=U,sA=x,pA=s?$o.revealFlashPostDelayMs:0,gA=s&&!T?{getRevealTime:s,challengerId:aA,bankerId:sA,postRevealDelayMs:pA}:void 0,yA=gA?0:z?eA:0;if(w.type==="MAIN"){let fA;try{const L=lf(w,t);fA=String((L==null?void 0:L.label)||"").trim()||void 0}catch{}let RA,qA;try{const L=w,H=(Array.isArray(L.bankerDice)&&L.bankerDice.length===3?L.bankerDice:null)||(o&&r?o(r):null),P=(Array.isArray(L.challengerDice)&&L.challengerDice.length===3?L.challengerDice:null)||(o?o(w.playerId):null);console.log("[useSettlementFlashes] dice source",{fromPayload:{banker:L.bankerDice,challenger:L.challengerDice},fromState:{banker:o&&r?o(r):"n/a",challenger:o?o(w.playerId):"n/a"},resolved:{bankerD:H,challengerD:P},outcome:b,playerId:w.playerId});const tA=["","⚀","⚁","⚂","⚃","⚄","⚅"],iA=uA=>uA.slice().sort((X,O)=>X-O).map(X=>tA[X]||String(X)).join(""),oA=r&&n(r)||"Banker",IA=n(w.playerId)||"Challenger",CA={name:oA,avatarUrl:r&&g?g(r):void 0},_A={name:IA,avatarUrl:g?g(w.playerId):void 0};if(H&&P){const uA=UY(H),X=UY(P),O=new Set(["456","123","triple","point"]);if(O.has(uA.kind)&&O.has(X.kind)){const wA=`${oA}: ${iA(H)} ${uA.label}`,xA=`${IA}: ${iA(P)} ${X.label}`;uA.score>=X.score?(RA=`${wA}
${xA}`,qA=[CA,_A]):(RA=`${xA}
${wA}`,qA=[_A,CA])}}else if(H){const uA=UY(H);(uA.kind==="456"||uA.kind==="123")&&(RA=`${r&&n(r)||"Banker"}: ${iA(H)} ${uA.label}`)}}catch{}console.log("[useSettlementFlashes] capturedReason",{capturedReason:RA,capturedLabel:fA,outcome:b});let W;b==="push"?W=RA||"No Action":RA?W=RA:W=fA||"",console.log("[useSettlementFlashes] FINAL subtitle",{capturedSubtitle:W,outcome:b}),Q(()=>{N(b,_,W,void 0,v,fA,qA,String(w.id))},{immediate:T?!0:Z&&!gA,delayMs:yA,revealGate:gA,key:String(w.id)})}else G(b,_,q,void 0,v,{immediate:T?!0:Z&&!gA,delayMs:yA,revealGate:gA,key:String(w.id)})}},[e,A,t,n,G,r]),E.useEffect(()=>{if(!(y.current||m.current)||S.current===A||Array.isArray(e)&&e.some(z=>(z==null?void 0:z.roundSeq)===A))return;const b=y.current,_=r&&n(r)||"Banker",K=["","⚀","⚁","⚂","⚃","⚄","⚅"],q=i?` ${(z=>z.slice().sort((Z,eA)=>Z-eA).map(Z=>K[Z]||String(Z)).join(""))(i)}`:"",v=b?`${_}:${q} 4‑5‑6`:`${_}:${q} 1‑2‑3`,U=b?"All challengers lose":"All challengers win",x=r&&t&&r===t,T=b?x?"win":"lose":x?"lose":"win";Q(()=>N(T,!1,U,v,!0,void 0,void 0,`auto-${A}`),{immediate:!0,key:`auto-${A}`}),S.current=A},[e,A,t,r,Q,N]),E.useEffect(()=>{const M=Die(w=>{try{h()}catch{}});return()=>{try{M()}catch{}}},[h]),E.useEffect(()=>()=>{try{d()}catch{}},[d])}function dpA({open:e,onClose:A,message:t}){const i=qi(),n=t||"You must be logged in.",g=E.useCallback(()=>{i("/lobby")},[i]);if(!e)return null;const o=C.jsxs("div",{className:"results-modal",role:"dialog","aria-modal":"true","aria-label":"Login required",children:[C.jsx("div",{className:"results-modal__backdrop",onClick:A}),C.jsxs("div",{className:"results-modal__card card",onClick:s=>s.stopPropagation(),children:[C.jsxs("div",{className:"results-modal__header",children:[C.jsx("h3",{children:"Login required"}),C.jsx("button",{type:"button","aria-label":"Close",className:"btn btn--ghost",onClick:A,children:"✕"})]}),C.jsxs("div",{style:{padding:16},children:[C.jsx("p",{style:{marginBottom:16},children:n}),C.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[C.jsx("button",{className:"btn btn--ghost",onClick:A,children:"Cancel"}),C.jsx("button",{className:"btn btn--primary",onClick:g,children:"Go to Home"})]})]})]})]});return er.createPortal(o,document.body)}function Mie({isUserTurn:e=!1,onOpen:A,isConnected:t=!0}){const{micEnabled:i,videoEnabled:n,speaking:g}=Il(),[o,s]=E.useState(!1),a=E.useRef(null),I=E.useCallback(()=>t?i?Object.values(g).some(Boolean)?"speaking":"connected":"muted":"disconnected",[t,i,g])(),c=E.useCallback(()=>{if(!(!t||e)){try{ti("Light")}catch{}A()}},[t,e,A]),l=E.useCallback(()=>{t&&(a.current=setTimeout(()=>{if(s(!0),e){try{ti("Medium")}catch{}A()}},500))},[t,e,A]),B=E.useCallback(()=>{a.current&&(clearTimeout(a.current),a.current=null),setTimeout(()=>s(!1),1500)},[]),Q=E.useCallback(()=>{a.current&&(clearTimeout(a.current),a.current=null),s(!1)},[]),h=I==="muted"?"Muted":I==="disconnected"?"Voice disconnected":"Voice connected",d=i||n,p=["comms-btn",`comms-btn--${I}`,d?"comms-btn--active":"",e?"comms-btn--turn":""].filter(Boolean).join(" ");return C.jsxs("div",{className:"comms-btn-container",children:[C.jsxs("button",{type:"button",className:p,onClick:c,onPointerDown:l,onPointerUp:B,onPointerLeave:Q,onPointerCancel:Q,"aria-label":h,"aria-pressed":i,style:{opacity:e?.75:1,pointerEvents:"auto"},children:[I==="speaking"&&C.jsx("span",{className:"comms-btn__pulse","aria-hidden":"true"}),C.jsxs("span",{className:"comms-btn__icon-wrap",children:[C.jsx(Nie,{}),I==="muted"&&C.jsx("span",{className:"comms-btn__slash","aria-hidden":"true"})]})]}),o&&C.jsx("div",{className:"comms-btn__tooltip",role:"tooltip",children:h})]})}function Nie(){return C.jsx("svg",{className:"comms-btn__svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:C.jsx("path",{d:"M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"})})}function Rie({open:e,onClose:A,roomId:t,onLeaveVoice:i,onBlockReport:n}){const{micEnabled:g,setMicEnabled:o,videoEnabled:s,setVideoEnabled:a,leaveRoom:r}=Il(),[I,c]=E.useState(100),[l,B]=E.useState(!1),[Q,h]=E.useState(!1),d=E.useRef(null),p=E.useCallback(N=>{N.target===N.currentTarget&&A()},[A]);E.useEffect(()=>{if(!e)return;const N=G=>{G.key==="Escape"&&A()};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[e,A]),E.useEffect(()=>{if(!e||!d.current)return;const N=d.current.querySelector('button, input, [tabindex]:not([tabindex="-1"])');N==null||N.focus()},[e]);const y=E.useCallback(async()=>{if(!l){try{ti("Light")}catch{}B(!0);try{await o(!g)}catch{}finally{B(!1)}}},[g,o,l]),m=E.useCallback(async()=>{if(!Q){try{ti("Light")}catch{}h(!0);try{await a(!s)}catch{}finally{h(!1)}}},[s,a,Q]),D=E.useCallback(N=>{const G=parseInt(N.target.value,10);c(G);try{window.dispatchEvent(new CustomEvent("comms:volume",{detail:{volume:G/100}}))}catch{}},[]),S=E.useCallback(()=>{try{ti("Medium")}catch{}r(t),i==null||i(),A()},[t,r,i,A]),k=E.useCallback(()=>{try{ti("Medium")}catch{}n==null||n(),A()},[n,A]);return e?er.createPortal(C.jsx("div",{className:"comms-drawer-backdrop",onClick:p,"aria-modal":"true",role:"dialog",children:C.jsxs("div",{ref:d,className:"comms-drawer",role:"document","aria-label":"Communication settings",children:[C.jsx("div",{className:"comms-drawer__handle","aria-hidden":"true"}),C.jsxs("div",{className:"comms-drawer__header",children:[C.jsx("h2",{className:"comms-drawer__title",children:"Voice & Video"}),C.jsx("button",{type:"button",className:"comms-drawer__close",onClick:A,"aria-label":"Close",children:"✕"})]}),C.jsxs("div",{className:"comms-drawer__content",children:[C.jsxs("button",{type:"button",className:`comms-drawer__row comms-drawer__row--toggle ${g?"comms-drawer__row--active":""} ${l?"comms-drawer__row--activating":""}`,onClick:y,"aria-pressed":g,disabled:l,children:[C.jsx("span",{className:"comms-drawer__row-icon",children:g?"🎙️":"🔇"}),C.jsx("span",{className:"comms-drawer__row-label",children:l?"Activating…":g?"Microphone On":"Microphone Off"}),l?C.jsx("span",{className:"comms-drawer__spinner",role:"status","aria-label":"Activating"}):C.jsx("span",{className:`comms-drawer__toggle ${g?"comms-drawer__toggle--on":""}`,children:C.jsx("span",{className:"comms-drawer__toggle-knob"})})]}),C.jsxs("button",{type:"button",className:`comms-drawer__row comms-drawer__row--toggle ${s?"comms-drawer__row--active":""} ${Q?"comms-drawer__row--activating":""}`,onClick:m,"aria-pressed":s,disabled:Q,children:[C.jsx("span",{className:"comms-drawer__row-icon",children:s?"📹":"📷"}),C.jsx("span",{className:"comms-drawer__row-label",children:Q?"Activating…":s?"Camera On":"Camera Off"}),Q?C.jsx("span",{className:"comms-drawer__spinner",role:"status","aria-label":"Activating"}):C.jsx("span",{className:`comms-drawer__toggle ${s?"comms-drawer__toggle--on":""}`,children:C.jsx("span",{className:"comms-drawer__toggle-knob"})})]}),C.jsxs("div",{className:"comms-drawer__row comms-drawer__row--slider",children:[C.jsx("span",{className:"comms-drawer__row-icon",children:"🔊"}),C.jsx("span",{className:"comms-drawer__row-label",children:"Volume"}),C.jsx("input",{type:"range",min:"0",max:"100",value:I,onChange:D,className:"comms-drawer__slider","aria-label":"Volume"}),C.jsxs("span",{className:"comms-drawer__slider-value",children:[I,"%"]})]}),C.jsx("hr",{className:"comms-drawer__divider"}),C.jsxs("button",{type:"button",className:"comms-drawer__row comms-drawer__row--danger",onClick:S,children:[C.jsx("span",{className:"comms-drawer__row-icon",children:"🚪"}),C.jsx("span",{className:"comms-drawer__row-label",children:"Leave Voice"})]}),n&&C.jsxs("button",{type:"button",className:"comms-drawer__row comms-drawer__row--danger",onClick:k,children:[C.jsx("span",{className:"comms-drawer__row-icon",children:"🚫"}),C.jsx("span",{className:"comms-drawer__row-label",children:"Block / Report Player"})]})]}),C.jsx("div",{className:"comms-drawer__footer",children:C.jsx("p",{children:"All changes are saved automatically"})})]})}),document.body):null}function hpA({roomId:e,isUserTurn:A=!1,leftSlot:t,singlePlayer:i}){Il();const{user:n}=tn(),[g,o]=E.useState(!1),[s,a]=E.useState(!1),[r,I]=E.useState(zUA()),c=(()=>{try{return(n==null?void 0:n.isGuest)===!0}catch{return!1}})(),l=E.useCallback(Q=>()=>{try{ti("Light")}catch{}try{}catch{}Q()},[]);E.useEffect(()=>{let Q=!0;return(async()=>{try{const h=await Xo();if(!Q)return;const d=!!h.diceAudio;I(d),x6(d)}catch{}})(),()=>{Q=!1}},[]),l(()=>{const Q=!r;if(I(Q),x6(Q),Q)try{On()}catch{}(async()=>{try{const d={...await Xo(),diceAudio:Q};await JE(d)}catch{}})()}),E.useMemo(()=>r?"Mute sounds":"Unmute sounds",[r]);const B=E.useCallback(()=>{if(c){o(!0);return}a(!0)},[c]);return C.jsxs(C.Fragment,{children:[t,C.jsx("div",{className:"poker-header-comms",role:"group","aria-label":"communications controls",children:C.jsx(Mie,{isUserTurn:A,onOpen:B,isConnected:!!e&&!i})}),C.jsx(Rie,{open:s,onClose:()=>a(!1),roomId:e}),C.jsx(dpA,{open:g,onClose:()=>o(!1)})]})}const ppA=E.createContext(void 0),Gie=({children:e})=>{const[A,t]=E.useState([]),[i,n]=E.useState(null),{sendGameInvite:g,respondGameInvite:o}=Mo(),s=MB();Os({onGameInviteReceived:l=>{const B={inviteId:l.inviteId,fromUserId:l.fromUserId,fromUserName:l.fromUserName,roomId:l.roomId,roomName:l.roomName,gameMode:l.gameMode,receivedAt:Date.now()};t(Q=>[...Q,B]),n(Q=>Q||B)},onGameInviteCancelled:l=>{t(B=>B.filter(Q=>Q.inviteId!==l.inviteId)),n(B=>(B==null?void 0:B.inviteId)===l.inviteId?null:B),s==null||s.info(l.reason||"Game invite was cancelled")}}),E.useEffect(()=>{const l=setInterval(()=>{const B=Date.now(),Q=2*60*1e3;t(h=>h.filter(d=>B-d.receivedAt<Q))},1e4);return()=>clearInterval(l)},[]);const a=E.useCallback(async(l,B,Q)=>{try{const h=await g(l,B,Q);if(h&&h.ok)return s==null||s.success("Invite sent!"),{ok:!0};{const d=(h==null?void 0:h.error)||"Failed to send invite";return s==null||s.error(d),{ok:!1,error:d}}}catch(h){const d=(h==null?void 0:h.message)||"Failed to send invite";return s==null||s.error(d),{ok:!1,error:d}}},[g,s]),r=E.useCallback(async l=>{const B=A.find(Q=>Q.inviteId===l);if(!B)return{ok:!1};try{const Q=await o(l,"accept");return Q&&Q.ok?(t(h=>h.filter(d=>d.inviteId!==l)),n(null),{ok:!0,roomId:B.roomId,gameMode:B.gameMode}):{ok:!1}}catch{return{ok:!1}}},[A,o]),I=E.useCallback(l=>{o(l,"decline").catch(()=>{}),t(B=>B.filter(Q=>Q.inviteId!==l)),n(B=>(B==null?void 0:B.inviteId)===l?A.filter(h=>h.inviteId!==l)[0]||null:B)},[A,o]),c=E.useCallback(()=>{i&&I(i.inviteId)},[i,I]);return C.jsx(ppA.Provider,{value:{pendingInvites:A,currentInvite:i,sendInvite:a,acceptInvite:r,declineInvite:I,dismissCurrentInvite:c},children:e})};function fpA(){return E.useContext(ppA)}function ypA({roomId:e,gameMode:A,className:t}){const[i,n]=E.useState(!1),[g,o]=E.useState(null),[s,a]=E.useState(new Set),r=E.useRef(null),I=fpA(),{friends:c}=Kd();E.useEffect(()=>{if(!i)return;const h=p=>{p.key==="Escape"&&n(!1)},d=p=>{r.current&&!r.current.contains(p.target)&&n(!1)};return document.addEventListener("keydown",h),document.addEventListener("mousedown",d),()=>{document.removeEventListener("keydown",h),document.removeEventListener("mousedown",d)}},[i]);const l=async h=>{if(I){o(h);try{(await I.sendInvite(e,h,A)).ok&&a(p=>new Set([...p,h]))}finally{o(null)}}},B=h=>{switch(h){case"cee-lo":return"Cee-Lo";case"craps":return"Craps";case"poker":return"Poker";default:return h}};if(!I)return null;const Q=i?C.jsx("div",{className:"modal-backdrop",role:"presentation",style:{position:"fixed",inset:0,zIndex:99998,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0, 0, 0, 0.7)",backdropFilter:"blur(4px)"},children:C.jsxs("div",{className:"modal-panel",role:"dialog","aria-modal":"true","aria-label":"Invite friends",ref:r,style:{maxWidth:360,maxHeight:"80vh",overflow:"auto",position:"relative",background:"linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)",borderRadius:12,padding:"24px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.5)",border:"1px solid rgba(255, 215, 0, 0.2)",color:"#fff"},children:[C.jsx("button",{className:"modal-close",onClick:()=>n(!1),"aria-label":"Close",style:{position:"absolute",top:8,right:8,background:"none",border:"none",color:"#fff",fontSize:"1.5rem",cursor:"pointer",opacity:.7},children:"×"}),C.jsxs("h3",{className:"modal-title",style:{marginBottom:16,textAlign:"center"},children:["Invite Friends to ",B(A)]}),c.length===0?C.jsxs("p",{style:{textAlign:"center",opacity:.7,padding:"20px 0"},children:["You don't have any friends yet.",C.jsx("br",{}),"Add friends from your profile to invite them to games!"]}):C.jsx("ul",{style:{listStyle:"none",padding:0,margin:0},children:c.map(h=>{const d=s.has(h.id),p=g===h.id;return C.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 0",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[C.jsx("span",{style:{fontWeight:500},children:h.name||"Anonymous"}),d?C.jsx("span",{style:{color:"var(--success, #4caf50)",fontSize:"0.875rem"},children:"✓ Invited"}):C.jsx("button",{className:"felt-btn felt-btn--sm felt-btn--primary",onClick:()=>l(h.id),disabled:p,style:{minWidth:70},children:p?"...":"Invite"})]},h.id)})}),C.jsx("div",{style:{marginTop:20,textAlign:"center"},children:C.jsx("button",{className:"felt-btn btn--ghost",onClick:()=>n(!1),children:"Close"})})]})}):null;return C.jsxs(C.Fragment,{children:[C.jsx("a",{className:`gold-link ${t||""}`,onClick:()=>n(!0),title:"Invite a friend to this game","aria-label":"Invite friend",style:{padding:"0px 10px",fontSize:"2.5rem",lineHeight:1},children:"+"}),Q&&er.createPortal(Q,document.body)]})}function rx(e){var Eg,gi,Mg,Hg;const{roomName:A,players:t,bankerId:i,currentRollerId:n,meId:g,gameState:o,roomId:s,onOpenDM:a,onOpenSendMoney:r,showHeader:I=!0,className:c,lite:l=!1,hideDiceResults:B,disableBankerFlash:Q,crapsRollHistory:h,lastRollerId:d,hideSideBets:p,hideAvatars:y,renderFacesOverride:m,headerCommsLeftSlot:D}=e;if(l)return C.jsx(lpA,{players:t,meId:g,className:c,onOpenDM:a,onOpenSendMoney:r});const{handleLeave:S}=DZ(s,g,{autoJoin:!1}),k=qi(),{onBuyChips:N,busy:G,ready:M,isWeb:w}=Sw(),{onHandEnd:b}=Yf(),_=Il(),{remoteStreams:K,myVideo:J,remoteVideoFlags:q}=_,{proofs:v,reveals:U,verifyFor:x}=ipA(s),{user:T,updateBalance:z}=tn(),Z=(()=>{try{return(T==null?void 0:T.isGuest)===!0}catch{return!1}})(),[eA,aA]=E.useState(!1),[sA,pA]=E.useState(!1),[gA,yA]=E.useState({}),{settledAll:fA,playerBalance:RA,mySettledAll:qA,newSettlements:W,openAllMain:$}=gx(s,g),{leaveRoom:L,skillsLeaveRoom:H}=Mo();o==null||o.betsLocked;const P=E.useCallback(()=>{const de=o==null?void 0:o.gameMode;if(de==="poker"){s&&L(s),k("/lobby");return}if(de==="skills"){s&&H(s),k("/");return}S()},[o,s,L,H,k,S]),tA=E.useCallback(de=>()=>{try{ti("Light")}catch{}try{}catch{}de()},[]),iA=E.useMemo(()=>{var de;return(de=t.find(qe=>qe.id===g))==null?void 0:de.balance},[t,g]),oA=o==null?void 0:o.gameMode,IA=(()=>{const de=typeof RA=="number"?RA:void 0,qe=typeof iA=="number"?iA:void 0;if(oA==="craps")return qe??de??0;if(oA==="poker"){const OA=de??qe??0,Ke=(Array.isArray(o==null?void 0:o.pokerSeats)?o.pokerSeats:[]).find(pt=>pt.playerId===g),Je=Ke&&typeof Ke.stack=="number"?Ke.stack:0;return OA+Je}return de??qe??0})(),[CA,_A]=E.useState(IA),[uA,X]=E.useState(!1),O=E.useRef(IA),cA=E.useRef(new Set),wA=E.useRef({}),xA=E.useRef(0),YA=5e3,jA=E.useRef({}),[ie,he]=E.useState(0);E.useEffect(()=>{Date.now()-xA.current<YA||O.current!==IA&&(O.current=IA,_A(IA))},[IA]);const le=E.useMemo(()=>{if((o==null?void 0:o.gameMode)!=="poker")return null;const qe=Array.isArray(o==null?void 0:o.pokerSeats)?o.pokerSeats:[],OA=new Set;for(const Ae of qe)Ae!=null&&Ae.playerId&&OA.add(String(Ae.playerId));return OA},[o==null?void 0:o.gameMode,o==null?void 0:o.pokerSeats]),NA=E.useCallback(de=>{const qe=o==null?void 0:o.gameMode;if(qe==="poker"){const OA=typeof de.balance=="number"?de.balance:0,Ke=(Array.isArray(o==null?void 0:o.pokerSeats)?o.pokerSeats:[]).find(pt=>pt.playerId===de.id);if(Ke&&typeof Ke.stack=="number")return Math.max(0,Ke.stack);const Je=typeof(Ke==null?void 0:Ke.committed)=="number"?Ke.committed:0;return Math.max(0,OA-Je)}return qe==="craps"&&de.id!==g&&typeof jA.current[de.id]=="number"?jA.current[de.id]:de.id===g?Number(CA??0):typeof de.balance=="number"?de.balance:0},[o,g,CA,ie]),EA=E.useMemo(()=>{var OA;const de=o==null?void 0:o.gameMode;return de==="poker"?le?t.filter(Ae=>le.has(Ae.id)):t:de==="craps"||de==="skills"||(o==null?void 0:o.mode)==="single"||((OA=e.roomId)==null?void 0:OA.includes("single"))?t:t.filter(Ae=>{var Je,pt;return Ae.id===g||(Je=Ae.id)!=null&&Je.startsWith("bot_")||(pt=Ae.id)!=null&&pt.startsWith("craps_bot_")?!0:NA(Ae)>0})},[t,le,o==null?void 0:o.gameMode,o==null?void 0:o.mode,g,NA,e.roomId]),PA=E.useMemo(()=>Object.fromEntries(EA.map(de=>[de.id,de])),[EA]),ZA=E.useRef(void 0),FA=E.useRef(new Map);E.useEffect(()=>{if((o==null?void 0:o.gameMode)!=="poker")return;const qe=e.roomId||"unknown";ZA.current!==qe&&(ZA.current=qe,FA.current=new Map);const OA=FA.current;let Ae=-1;OA.forEach(Ke=>{Ke>Ae&&(Ae=Ke)});for(const Ke of EA)OA.has(Ke.id)||(Ae+=1,OA.set(Ke.id,Ae))},[EA,e.roomId,o==null?void 0:o.gameMode]);const Ie=E.useMemo(()=>{const de=o==null?void 0:o.gameMode;if(de==="poker"){const Ae=FA.current;return EA.map(Ke=>Ke.id).slice().sort((Ke,Je)=>(Ae.get(Ke)??0)-(Ae.get(Je)??0))}if(de==="skills")return EA.map(Ae=>Ae.id);const qe=Array.isArray(o==null?void 0:o.turnOrder)?o.turnOrder:[],OA=(()=>{if(!qe.length)return EA.map(pt=>pt.id);const Ae=new Set(EA.map(pt=>pt.id)),Ke=qe.filter(pt=>Ae.has(pt)),Je=EA.map(pt=>pt.id).filter(pt=>!Ke.includes(pt));return[...Ke,...Je]})();if(e.localFirst&&g){const Ae=OA.indexOf(g);if(Ae>0)return[...OA.slice(Ae),...OA.slice(0,Ae)]}return OA},[EA,t,o==null?void 0:o.turnOrder,o==null?void 0:o.gameMode,e.localFirst,g]),DA=o.roundSeq??1;E.useEffect(()=>{if(!(!W||!W.length)){for(const de of W){if(!de||de.roundSeq!==DA||cA.current.has(de.id))continue;const qe={...de,type:de.type||(de.predicate||de.subjectId?"SIDE":"MAIN")},OA=MZ(qe,g);if(!OA.outcome)continue;cA.current.add(de.id);let Ae=0,Ke=0;try{const vt=lf(de,g);vt&&(vt.myResult==="WIN"?Ae=vt.myPayout||0:vt.myResult==="LOSE"&&(Ke=de.amount||0))}catch{}const Je=Ae>0?Ae:Ke>0?-Ke:0;if(Je===0)continue;const pt=OA.needsAnimation?2e3:0,Tt=window.setTimeout(()=>{_A(vt=>vt+Je),X(!0),window.setTimeout(()=>X(!1),2e3),delete wA.current[de.id]},pt);wA.current[de.id]=Tt}return()=>{Object.values(wA.current).forEach(de=>window.clearTimeout(de)),wA.current={}}}},[W,DA,g]);const rA=E.useMemo(()=>typeof o.roundSeq=="number"?(o.turnHistory??[]).filter(de=>de.roundSeq===o.roundSeq):o.turnHistory??[],[o.turnHistory,o.roundSeq]),[BA,j]=E.useState(!1),[QA,dA]=E.useState(0),[UA,TA]=E.useState(void 0);E.useEffect(()=>{if(!(!W||!W.length||(o==null?void 0:o.gameMode)==="poker"))for(const qe of W){if(!qe||qe.roundSeq!==DA||qe.playerId!==g)continue;const OA=lf(qe,g);if(OA&&OA.myResult==="LOSE"){const Ae=Number(qe.amount||0);dA(Ae>0?Ae:0),TA(void 0),j(!0);break}}},[W,DA,g,o]);const[oe,me]=E.useState(null),[be,$e]=E.useState(null),[ci,ke]=E.useState(!1),[nt,Ut]=E.useState(!1),dt=E.useRef(null),[Ht,Ft]=E.useState(new Map),{sendVisibilityChange:Jt}=Mo();E.useEffect(()=>{me(null)},[s]);const $A=E.useCallback(async()=>{if(s)try{const de=await oie(s);de&&me(de)}catch{}},[s]),He=E.useCallback(async()=>{if(s)try{ke(!0);const de=await sie(s);$e(de||null)}catch{$e(null)}finally{ke(!1)}},[s]);E.useEffect(()=>{nt&&(o==null?void 0:o.gameMode)==="craps"&&$A()},[nt,o,$A]),E.useEffect(()=>{if(!s||!v||typeof v!="object")return;let de=!1;const qe=DA,OA=`${qe}:`,Ae=Object.keys(v||{}).filter(Ke=>Ke.startsWith(OA));if(Ae.length)return Ae.forEach(Ke=>{const Je=Ke.split(":")[1];Je&&(async()=>{try{const pt=await x(Je,qe);de||yA(Tt=>Tt[Ke]===pt?Tt:{...Tt,[Ke]:pt})}catch{de||yA(pt=>pt[Ke]==="unverifiable"?pt:{...pt,[Ke]:"unverifiable"})}})()}),()=>{de=!0}},[v,U,x,s,DA]);const Xe=E.useMemo(()=>{var de;if(!i)return null;for(let qe=rA.length-1;qe>=0;qe--){const OA=rA[qe];if(OA.playerId===i&&Array.isArray(OA.result)&&OA.result.length===3){const Ae=OA.result;if(dM(Ae)!=="nothing")return Ae}}if((de=o.bankRoll)!=null&&de.raw&&Array.isArray(o.bankRoll.raw)&&o.bankRoll.raw.length===3){const qe=o.bankRoll.raw;if(dM(qe)!=="nothing")return qe}return null},[i,rA,o.bankRoll]),{revealedPlayers:St,revealTimesRef:kA}=uie(rA,i,o,DA),{show:se,roll:Ce,activeKind:VA,hasActive:nA,onIdle:vA,info:KA}=Jr(),WA=E.useRef(null),bA=E.useRef(null);E.useEffect(()=>{if(!(oA!=="craps"&&oA!=="poker"&&oA!=="skills")||!Xe||Xe.length!==3||wZ(Xe)!=="point")return;const qe={};for(const Je of Xe)qe[Je]=(qe[Je]||0)+1;const OA=Object.keys(qe).map(Number).find(Je=>qe[Je]===1);if(OA==null)return;const Ae=`${DA}:${OA}`;if(WA.current===Ae)return;bA.current&&window.clearTimeout(bA.current);const Ke=[...Xe];bA.current=window.setTimeout(()=>{var Vt;if(bA.current=null,WA.current===Ae)return;WA.current=Ae;const Je=i&&((Vt=t.find(hA=>hA.id===i))==null?void 0:Vt.name),pt=["","⚀","⚁","⚂","⚃","⚄","⚅"],Tt=hA=>hA.slice().sort((Re,ot)=>Re-ot).map(Re=>pt[Re]||String(Re)).join(""),vt=`${Je||"Banker"}'s Point`,ei=`${Tt(Ke)} — point is ${OA}`;Ce(vt,ei)},$o.revealFlashPostDelayMs)},[Xe,DA,oA,i,t,Ce]);const pe=E.useRef(new Set),xe=E.useRef(!1);E.useEffect(()=>{if(!xe.current){const de=new Set(t.map(qe=>String(qe.id)));pe.current=de,xe.current=!0}},[t]);const it=E.useMemo(()=>{const de=new Map;try{const qe=Array.isArray($)?$:[];for(const OA of qe){const Ae=OA==null?void 0:OA.roundSeq;typeof Ae=="number"&&Ae!==DA||OA&&OA.playerId&&typeof OA.amount=="number"&&de.set(OA.playerId,OA.amount)}}catch{}return de},[$,DA]),ve=E.useRef({});E.useRef(0),E.useRef(null),Os({onOtherPlayerJoined:({room:de})=>{try{if(!de||!Array.isArray(de.players))return;const qe=pe.current,OA=new Set(de.players.map(Ke=>String(Ke.id)));if(!xe.current){pe.current=OA,xe.current=!0;return}const Ae=[...OA].filter(Ke=>!qe.has(Ke));if(Ae.length>0){const Ke=new Map(de.players.map(Je=>[String(Je.id),Je]));for(const Je of Ae){if(Je===g)continue;const pt=Ke.get(Je),Tt=(pt==null?void 0:pt.name)||(pt==null?void 0:pt.email)||Je;try{KA&&KA("Player Joined",String(Tt))}catch{}}}pe.current=OA}catch{}},onOtherLeft:({room:de})=>{try{if(!de||!Array.isArray(de.players))return;const qe=pe.current,OA=new Set(de.players.map(Ke=>String(Ke.id)));if(!xe.current){pe.current=OA,xe.current=!0;return}const Ae=[...qe].filter(Ke=>!OA.has(Ke));if(Ae.length>0){const Ke=new Map;try{t.forEach(Je=>Ke.set(String(Je.id),Je.name||Je.email||String(Je.id)))}catch{}for(const Je of Ae){if(Je===g)continue;const pt=Ke.get(Je)||Je;try{KA&&KA("Player Left",String(pt))}catch{}}}pe.current=OA}catch{}},onPlayerBalanceUpdated:({playerId:de,balance:qe})=>{if(de!==g){jA.current[de]=qe,he(OA=>OA+1);return}xA.current=Date.now(),Object.values(wA.current).forEach(OA=>window.clearTimeout(OA)),wA.current={},cA.current.clear(),O.current=qe,_A(qe),z(qe),X(!0),window.setTimeout(()=>X(!1),2e3)},onCrapsBetResults:de=>{!de||de.roomId!==s||(dt.current&&window.clearTimeout(dt.current),dt.current=window.setTimeout(()=>{$A()},350))},onCrapsBetsUpdate:de=>{!de||de.roomId!==s||(dt.current&&window.clearTimeout(dt.current),dt.current=window.setTimeout(()=>{$A()},250))},onCrapsPointSet:de=>{!de||de.roomId!==s||(dt.current&&window.clearTimeout(dt.current),dt.current=window.setTimeout(()=>{$A()},300))},onCrapsPointMade:de=>{!de||de.roomId!==s||(dt.current&&window.clearTimeout(dt.current),dt.current=window.setTimeout(()=>{$A()},300))},onPlayerPresenceUpdate:de=>{if(!de||de.roomId!==s)return;const{playerId:qe,status:OA}=de;!qe||!OA||Ft(Ae=>{const Ke=new Map(Ae);return Ke.set(qe,OA),Ke})}}),E.useEffect(()=>()=>{dt.current&&window.clearTimeout(dt.current)},[]),E.useEffect(()=>{if(!s)return;const de=()=>{const OA=!document.hidden;Jt(s,OA)};Jt(s,!document.hidden),document.addEventListener("visibilitychange",de);let qe=null;return(async()=>{try{const{App:OA}=await Qi(async()=>{const{App:Ae}=await Promise.resolve().then(()=>GR);return{App:Ae}},void 0);qe=await OA.addListener("appStateChange",Ae=>{Jt(s,Ae.isActive)})}catch{}})(),()=>{document.removeEventListener("visibilitychange",de),qe&&typeof qe.remove=="function"&&qe.remove()}},[s,Jt]);const re=E.useCallback(de=>{let qe=ve.current[de];if(qe&&qe.getAttribute("data-player-id")!==de&&(qe=null),!qe)try{const Ke=window.CSS&&typeof window.CSS.escape=="function"?window.CSS.escape(de):String(de).replace(/[^a-zA-Z0-9_-]/g,"_");qe=document.querySelector(`.players.players--avatars [data-player-id="${Ke}"]`)}catch{}if(!qe)return null;const OA=qe.querySelector(".avatar-ring");let Ae=null;if(OA)Ae=OA.getBoundingClientRect();else try{Ae=qe.getBoundingClientRect()}catch{}return!Ae||Ae.width===0&&Ae.height===0?null:{x:Ae.left+Ae.width/2,y:Ae.top+Ae.height/2}},[]),Qe=E.useRef(rA.length),HA=E.useRef(null),ge=E.useRef(null),ye=E.useRef(null);E.useEffect(()=>{Qe.current=rA.length},[DA]),E.useEffect(()=>{ye.current=null},[DA]);const{forUserId:Te,anchorRect:gt,anchorEl:Qt,openFor:_e,close:Ze}=kZ(),at=(de,qe)=>{!qe||de===g||_e(de,qe)},Ai=()=>Ze(),Bi=E.useMemo(()=>{const de=new Map;for(const qe of t)de.set(qe.id,qe.name||qe.email||qe.id);for(const qe of fA){const OA=qe==null?void 0:qe.playerId,Ae=qe==null?void 0:qe.bankerId;OA&&!de.has(OA)&&de.set(OA,OA),Ae&&!de.has(Ae)&&de.set(Ae,Ae)}return de},[t,fA]),yi=E.useCallback(de=>Bi.get(de||"")||de||"Unknown",[Bi]),mt=E.useCallback(de=>yi(de),[yi]),ct=E.useMemo(()=>{const de=new Map;for(const qe of t)qe.avatarUrl&&de.set(qe.id,qe.avatarUrl);return de},[t]),fi=E.useCallback(de=>ct.get(de),[ct]),Yi=E.useCallback(de=>btA(de,rA,i,o.bankRoll,Xe),[rA,i,o.bankRoll,Xe]);kie({newSettlements:W,roundSeqNow:DA,myId:g,bankerDice:Xe,getPlayerName:mt,getPlayerAvatarUrl:fi,getPlayerDice:Yi,getRevealTime:de=>{var qe,OA;return(OA=(qe=kA==null?void 0:kA.current)==null?void 0:qe.get)==null?void 0:OA.call(qe,de)},postRevealDelayMs:0,bankerId:i});const si=E.useRef(null);E.useEffect(()=>{!((o==null?void 0:o.gameMode)==="cee-lo"||(o==null?void 0:o.gameMode)==="ceeLo"||!(o!=null&&o.gameMode))||!W.length||!W.filter(OA=>OA.playerId===g||OA.bankerId===g).length||si.current!==DA&&(si.current=DA,!(e.singlePlayer&&t.filter(Ae=>Ae.id.startsWith("bot_")&&(Ae.balance??0)>0).length===0)&&setTimeout(async()=>{try{await b()}catch{}},2500))},[W,DA,g,o,b,e.singlePlayer,t]);const jt=(o==null?void 0:o.gameMode)==="cee-lo"||(o==null?void 0:o.gameMode)==="ceeLo"||!(o!=null&&o.gameMode);o==null||o.gameMode;const Zt=E.useCallback(de=>{var Ke,Je;if(!jt)return!0;if(!de||!(St.get(de)===!0))return!1;const OA=(Je=(Ke=kA==null?void 0:kA.current)==null?void 0:Ke.get)==null?void 0:Je.call(Ke,de);return(typeof OA=="number"?performance.now()-OA:0)>=$o.diceToChipDelayMs},[jt,St,kA]),{activeBatch:vi,handleAnimItemComplete:kn,resetForRound:gn}=Sie({newSettlements:W,roundSeqNow:DA,getAvatarCenter:re,getPlayerName:mt,myId:g,bankerDice:Xe,bankerId:i,isPartyReady:Zt});E.useEffect(()=>{gn()},[DA,gn]);const Ki=E.useRef(null),Tn=E.useRef(null),fg=E.useMemo(()=>{var qe;if((o==null?void 0:o.gameMode)==="poker"){const OA=Number((o==null?void 0:o.pokerUiLockedUntilTs)||0),Ae=OA>0&&Date.now()<OA,Ke=7e3;Ae&&Ki.current==null&&(Ki.current=Date.now());const Je=Ki.current||0,pt=Je>0?Date.now()-Je:Number.POSITIVE_INFINITY,Tt=Ae&&pt<=Ke,vt=Array.isArray(o==null?void 0:o.pokerSeats)?o.pokerSeats:[],ei=typeof(o==null?void 0:o.pokerActingSeat)=="number"?o.pokerActingSeat:void 0,Vt=typeof ei=="number"&&((qe=vt.find(hA=>hA.seatIndex===ei))==null?void 0:qe.playerId)||null;return Tt?Tn.current??Vt??null:(Tn.current=Vt??null,Ki.current=null,Vt??null)}return((o==null?void 0:o.currentRollerId)??n)||null},[o==null?void 0:o.gameMode,o==null?void 0:o.pokerSeats,o==null?void 0:o.pokerActingSeat,o==null?void 0:o.currentRollerId,n]);E.useEffect(()=>{const de=ge.current,qe=fg||void 0;if(!de||!qe||ye.current===qe)return;const OA=ve.current[qe];if(!OA)return;const Ae=()=>{try{const Ke=de.getBoundingClientRect(),Je=OA.getBoundingClientRect(),pt=Je.left-Ke.left+de.scrollLeft,Tt=Math.max(0,Math.min(pt-de.clientWidth/2+Je.width/2,de.scrollWidth-de.clientWidth));de.scrollTo({left:Tt,behavior:"smooth"}),ye.current=qe}catch{}};return HA.current&&clearTimeout(HA.current),HA.current=setTimeout(()=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(Ae):Ae()},100),()=>{HA.current&&(clearTimeout(HA.current),HA.current=null)}},[fg,Ie]);const Zi=e.campaignProgress?e.campaignProgress.isMaxLevel?100:e.campaignProgress.total>0?Math.min(100,e.campaignProgress.current/e.campaignProgress.total*100):0:0,te=!!(e.campaignProgress&&e.singlePlayer&&!sA);return E.useEffect(()=>{pA(!1)},[(Eg=e.campaignProgress)==null?void 0:Eg.level,(gi=e.campaignProgress)==null?void 0:gi.current,(Mg=e.campaignProgress)==null?void 0:Mg.total,(Hg=e.campaignProgress)==null?void 0:Hg.progressLabel]),C.jsxs("div",{className:["card",c].filter(Boolean).join(" "),style:{position:"relative"},children:[I&&C.jsxs("div",{className:"card-header card-header--two-rows",children:[C.jsxs("div",{className:"card-header-row",children:[C.jsxs("div",{className:"header-slot header-slot--left",children:[C.jsx("a",{className:"gold-link white-link",onClick:tA(P),"aria-label":"Back",style:{display:"flex"},children:C.jsx(tc,{className:"icon",style:{color:"var(--gold, #caa64d)"}})}),(()=>{const de=G||!M||!1,qe=de?"Balance (login to Buy 1000 Z Credits)":w?"Buy 1000 Z Credits":"Buy 1000 Z Credits (App Store / Play)",OA=de?"Login to Buy 1000 Z Credits":w?"Buy 1000 Z Credits":"Buy 1000 Z Credits (App Store / Play)",Ae=tA(()=>{if(Z){aA(!0);return}N()});return C.jsx("a",{className:"gold-link balance-display"+(de?" disabled":"")+(uA?" balance--pulse":""),role:"button","aria-label":qe,title:OA,"aria-disabled":de||void 0,onClick:Ae,children:C.jsxs("b",{children:[C.jsx("span",{className:"lowercase",children:"z"}),CB.formatMoney(CA,"",0)]})})})(),oA!=="skills"&&C.jsx("a",{role:"button",className:"gold-link white-link header-history-link"+(e.historyHalo?" history-halo":""),onClick:tA(()=>{if(Z){aA(!0);return}const de=o==null?void 0:o.gameMode;de==="craps"?($A(),Ut(!0)):de==="poker"?e.onOpenHistory&&e.onOpenHistory():He().then(()=>Ut(!0))}),"aria-haspopup":"dialog","aria-controls":"my-bets-modal",children:"History"}),s&&!Z&&!e.singlePlayer&&C.jsx(ypA,{roomId:s,gameMode:(o==null?void 0:o.gameMode)||"cee-lo"})]}),C.jsx("div",{className:"header-slot header-slot--right",children:C.jsx(hpA,{roomId:s,leftSlot:D,singlePlayer:e.singlePlayer})})]}),te&&e.campaignProgress&&C.jsxs("div",{className:"campaign-progress","aria-label":"Single-player campaign progress",children:[C.jsx("button",{type:"button",className:"campaign-progress__close","aria-label":"Hide campaign progress",onClick:de=>{de.stopPropagation(),pA(!0)},children:C.jsx("span",{"aria-hidden":"true",children:"x"})}),C.jsxs("div",{className:"campaign-progress__copy",children:[C.jsxs("strong",{children:["Level ",e.campaignProgress.level]}),C.jsx("span",{children:e.campaignProgress.levelName})]}),C.jsxs("div",{className:"campaign-progress__goal",children:[C.jsx("b",{children:e.campaignProgress.progressLabel}),C.jsx("span",{children:e.campaignProgress.isMaxLevel?"Highest level reached":e.campaignProgress.goalLabel??`Reach Level ${e.campaignProgress.level+1}`})]}),C.jsx("div",{className:"campaign-progress__track","aria-hidden":"true",children:C.jsx("span",{style:{width:`${Zi}%`}})})]})]}),vi.length>0&&C.jsxs("div",{style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:1e4},children:[vi.map(de=>C.jsx(upA,{anim:de,onComplete:()=>kn(de.id)},de.id)),!1]}),C.jsx("div",{className:"chip-fly-container",children:!y&&C.jsx(XI.ul,{className:"players players--avatars",role:"list",ref:ge,layout:!0,transition:{type:"spring",stiffness:420,damping:38,mass:.6},children:Ie.map(de=>{var je;const qe=(o==null?void 0:o.currentRollerId)??n,OA=PA[de];if(!OA)return null;const Ae=OA.id,Ke=[];if((o==null?void 0:o.gameMode)==="poker"){const Ct=o,At=Array.isArray(Ct.pokerSeats)?Ct.pokerSeats:[],zt=typeof Ct.pokerDealerSeat=="number"?Ct.pokerDealerSeat:void 0,li=At.find(Ei=>Ei.playerId===Ae);if(li&&typeof zt=="number"){li.seatIndex===zt&&Ke.push("D");const Ei=At.filter(Hi=>!!Hi.playerId).map(Hi=>Hi.seatIndex).sort((Hi,gg)=>Hi-gg),ai=Ei.length;if(ai>=2){const Hi=Ei.indexOf(zt);if(Hi!==-1){let gg,yn;ai===2?(gg=zt,yn=Ei[(Hi+1)%ai]):(gg=Ei[(Hi+1)%ai],yn=Ei[(Hi+2)%ai]),li.seatIndex===gg&&Ke.push("SB"),typeof yn=="number"&&li.seatIndex===yn&&Ke.push("BB")}}}}jt&&i&&Ae===i&&Ke.push("B"),Ae===qe&&!St.get(Ae)&&Ke.push("Rolling"),Ae===qe&&Ke.push("Shooter");let Je=!1;if((o==null?void 0:o.gameMode)==="poker"){const Ct=o,At=typeof Ct.pokerActingSeat=="number"?Ct.pokerActingSeat:void 0;typeof At=="number"&&Array.isArray(Ct.pokerSeats)&&(Je=((je=Ct.pokerSeats.find(li=>li.seatIndex===At))==null?void 0:je.playerId)===Ae)}else Je=Ae===qe;let pt=!1;if((o==null?void 0:o.gameMode)==="poker"){const At=(Array.isArray(o==null?void 0:o.pokerSeats)?o.pokerSeats:[]).find(zt=>zt.playerId===Ae);At&&String(At.status||"").toLowerCase()==="folded"&&(pt=!0)}const Tt=Ae===g?J:K[Ae],vt=q[Ae]?Tt:void 0,ei=!B&&St.get(Ae)?btA(Ae,rA,i,o.bankRoll,Xe):null;let Vt=!B&&ei&&Array.isArray(ei)&&ei.length===3&&!ei.every(Ct=>Ct===0)&&dM(ei)!=="nothing"?C.jsx(EpA,{dice:ei}):null;const Re=(o.spectators??[]).includes(Ae);let ot;if(m)ot=m(OA);else if(Re)ot=null;else if(jt&&!St.get(Ae)){const Ct=it.get(Ae);ot=typeof Ct=="number"&&Ct>0?C.jsxs("span",{className:"player-bet-pill","aria-label":`Bet z${CB.formatMoney(Ct,"",0)}`,children:["z",CB.formatMoney(Ct,"",0)]}):null}else ot=Vt;const kt=(o==null?void 0:o.gameMode)==="poker",ht=NA(OA),ee=Number.isFinite(ht)?ht:void 0;return C.jsx(Bie,{ref:Ct=>{ve.current[Ae]=Ct},id:Ae,display:OA.name??OA.email??Ae,isCurrentRoller:Je,isMe:Ae===g,balance:ee,isSpectating:Re,folded:pt,tags:Ke,stream:vt,isMuted:Ae===g,diceResult:ot,onOpenMenu:(Ct,At)=>at(Ct,At),showMenu:Te===Ae,menuProps:Te===Ae?{targetId:Ae,anchorRect:gt,anchorEl:Qt,onClose:Ai,onOpenDM:a,onOpenSendMoney:r,meId:g}:null,forceHideVideo:!q[Ae],avatarUrl:OA.avatarUrl,showActingTimerRing:kt,presenceStatus:Ht.get(Ae)},Ae)})})}),nt&&C.jsx(hdA,{onClose:()=>Ut(!1),items:Array.isArray(be)&&be.length>0?be:qA,meId:g,nameOf:yi,crapsRollHistory:h,gameMode:o==null?void 0:o.gameMode,crapsLedgerItems:(oe||[]).slice().sort((de,qe)=>Number(qe.ts)-Number(de.ts))}),C.jsx(dpA,{open:eA,onClose:()=>aA(!1),message:"This feature is for logged in users."})]})}const bie={pass:"Pass Line",dontPass:"Don't Pass",field:"Field",big6:"Big 6",big8:"Big 8",come:"Come",dontCome:"Don't Come",atsSmall:"ATS Small",atsTall:"ATS Tall",atsAll:"ATS All"};function Uie(e){return e.startsWith("place")?`Place ${e.replace("place","")}`:bie[e]??e}function vie(e,A){return{net:e.reduce((i,n)=>n.outcome==="WIN"?i+n.payout:n.outcome==="LOSE"?i-n.amount:i,0),rollTotal:A,settlements:e}}function Kie(e){return e.outcome==="WIN"?`+z${e.payout}`:e.outcome==="LOSE"?`-z${e.amount}`:"Returned"}function Fie({summary:e}){const A=e.net>0?"win":e.net<0?"lose":"push",t=e.net>0?"You Won":e.net<0?"You Lost":"No Change";return C.jsxs("section",{className:`craps-roll-result craps-roll-result--${A}`,"aria-live":"polite","aria-label":"Your roll result",children:[C.jsxs("div",{className:"craps-roll-result__header",children:[C.jsxs("div",{children:[C.jsx("span",{className:"craps-roll-result__eyebrow",children:typeof e.rollTotal=="number"?`Roll ${e.rollTotal}`:"Roll Result"}),C.jsx("strong",{children:t})]}),C.jsxs("b",{className:"craps-roll-result__net",children:[e.net>0?"+":e.net<0?"-":"","z",Math.abs(e.net)]})]}),C.jsx("div",{className:"craps-roll-result__rows",children:e.settlements.map((i,n)=>C.jsxs("div",{className:"craps-roll-result__row",children:[C.jsx("span",{children:Uie(i.betType)}),C.jsx("b",{className:`craps-roll-result__amount craps-roll-result__amount--${i.outcome.toLowerCase()}`,children:Kie(i)})]},`${i.betType}-${i.outcome}-${n}`))})]})}function _ie(e){const{gameState:A,roomId:t,meId:i}=e,{show:n,rollNow:g}=Jr(),{onHandEnd:o}=Yf(),s=E.useRef(null),a=E.useRef(new Set),r=E.useRef(null),I=E.useRef(null),c=E.useRef(null),l=E.useRef(null),B=E.useRef(null),Q=E.useRef(null),[h,d]=E.useState(null),{reveal:p}=kB(),{recentSettlements:y,lastSettlementRoll:m,pointSetEvent:D,pointMadeEvent:S}=tpA({roomId:t||null,myPlayerId:i}),k=E.useCallback((N,G,M,w,b)=>{if(s.current===b||a.current.has(b))return;(()=>{s.current=b,a.current.add(b),n({kind:N==="roll"?"roll":N,title:G,subtitle:M,duration:w})})()},[n]);return E.useEffect(()=>{if(!D||!t||D.roomId!==t)return;const N=D._key;s.current===N||a.current.has(N)||(r.current={key:N,point:D.point},I.current&&clearTimeout(I.current),p&&(I.current=setTimeout(()=>{const G=r.current;if(G){if(a.current.has(G.key)){r.current=null;return}s.current=G.key,a.current.add(G.key);try{P6({volume:.15})}catch{}typeof g=="function"?g("Point Established",`${G.point} is the point`):n({kind:"roll",title:"Point Established",subtitle:`${G.point} is the point`,duration:1e3}),r.current=null}},$o.revealFlashPostDelayMs)))},[D,t,g,n,p]),E.useEffect(()=>{!p||!r.current||(I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{const G=r.current;if(G){if(a.current.has(G.key)){r.current=null;return}s.current=G.key,a.current.add(G.key);try{P6({volume:.15})}catch{}typeof g=="function"?g("Point Established",`${G.point} is the point`):n({kind:"roll",title:"Point Established",subtitle:`${G.point} is the point`,duration:1e3}),r.current=null}},$o.revealFlashPostDelayMs))},[p,g,n]),E.useEffect(()=>{S&&(!t||S.roomId!==t||(c.current={key:S._key,point:S.point},l.current&&clearTimeout(l.current),p&&(l.current=setTimeout(()=>{const N=c.current;if(N){if(a.current.has(N.key)){c.current=null;return}k("win","Point Made!",`${N.point} hit`,1300,N.key);try{Z6({sfxVolume:.15,voiceVolume:.55})}catch{}try{window.dispatchEvent(new CustomEvent("craps:point_made",{detail:{point:N.point}}))}catch{}c.current=null}},$o.revealFlashPostDelayMs))))},[S,t,k,p]),E.useEffect(()=>{!p||!c.current||(l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{const G=c.current;if(G){if(a.current.has(G.key)){c.current=null;return}k("win","Point Made!",`${G.point} hit`,1300,G.key);try{Z6({sfxVolume:.15,voiceVolume:.55})}catch{}try{window.dispatchEvent(new CustomEvent("craps:point_made",{detail:{point:G.point}}))}catch{}c.current=null}},$o.revealFlashPostDelayMs))},[p,k]),E.useEffect(()=>()=>{I.current&&clearTimeout(I.current),l.current&&clearTimeout(l.current),Q.current&&clearTimeout(Q.current)},[]),E.useEffect(()=>{var IA,CA,_A,uA;if(!y.length)return;const N=(()=>{var X,O;try{return typeof window<"u"&&(window.__E2E===!0||((O=(X=window.location)==null?void 0:X.search)==null?void 0:O.includes("e2e=1")))}catch{return!1}})(),G=i||(N?(A==null?void 0:A.currentRollerId)||"e2e-user":void 0),M=X=>{const O=X.betType;return O==="pass"||O==="dontPass"||O.startsWith("place")||O==="field"||O==="big6"||O==="big8"||O==="come"||O==="dontCome"||O==="atsSmall"||O==="atsTall"||O==="atsAll"},w=y.filter(X=>(G?X.playerId===G:!0)&&M(X));if(!w.length)return;const b=(m==null?void 0:m._seq)||0,_=typeof(m==null?void 0:m.total)=="number"?m.total:Array.isArray(m==null?void 0:m.dice)?m.dice[0]+m.dice[1]:"",K=w.map(X=>`${X.betType}:${X.outcome}:${X.amount}:${X.payout}`).sort().join("|"),J=`${b}:${_}:${K}`;if(B.current===J)return;B.current=J;const q=w.filter(X=>X.betType==="pass"||X.betType==="dontPass"),v=w.filter(X=>X.betType.startsWith("place")&&X.outcome==="WIN"),U=w.filter(X=>X.betType==="field"),x=w.filter(X=>X.betType==="big6"||X.betType==="big8"),T=w.filter(X=>X.betType==="come"||X.betType==="dontCome"),z=w.filter(X=>X.betType==="atsSmall"||X.betType==="atsTall"||X.betType==="atsAll"),Z=q.some(X=>X.outcome==="WIN"),eA=v.length>0,aA=U.some(X=>X.outcome==="WIN"),sA=x.some(X=>X.outcome==="WIN"),pA=T.some(X=>X.outcome==="WIN"),gA=z.some(X=>X.outcome==="WIN"),yA=z.some(X=>X.outcome==="LOSE"),fA=q.some(X=>X.outcome==="LOSE"),RA=U.some(X=>X.outcome==="LOSE"),qA=x.some(X=>X.outcome==="LOSE"),W=T.some(X=>X.outcome==="LOSE"),$=T.some(X=>X.outcome==="PUSH"),L=!Z&&!fA&&q.some(X=>X.outcome==="PUSH");let H="",P="";d(vie(w,typeof _=="number"?_:void 0)),Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>d(null),4500);const tA=typeof _=="number"?_:Number(_),iA=m==null?void 0:m.currentRollerId,oA=v.some(X=>{const O=Number(String(X.betType).replace(/^place/,""));return Number.isFinite(O)&&O===tA});if(gA){const X=z.filter(wA=>wA.outcome==="WIN"),O=X.reduce((wA,xA)=>wA+xA.payout,0),cA=X.map(wA=>wA.betType==="atsAll"?"ALL":wA.betType==="atsSmall"?"SMALL":wA.betType==="atsTall"?"TALL":wA.betType);H=X.length>1?`ATS ${cA.join(" & ")}!`:`ATS ${cA[0]}!`,P=`+${O}`,n({kind:"win",title:H,subtitle:P,duration:2e3});try{window.dispatchEvent(new CustomEvent("craps:ats_win",{detail:{payout:O,bets:cA}}))}catch{}return}if(Z){if(eA&&oA&&i&&iA===i){const O=v.reduce((cA,wA)=>cA+wA.payout,0);H=v.length>1?"Place Wins":"Place Win",P=`+${O}`,n({kind:"win",title:H,subtitle:P,duration:1e3});return}const X=q.filter(O=>O.outcome==="WIN").reduce((O,cA)=>O+(cA.payout+cA.amount),0);H="Line Win",P=`+${X}`,n({kind:"win",title:H,subtitle:P,duration:1100});return}if(eA){const X=v.reduce((O,cA)=>O+cA.payout,0);H=v.length>1?"Place Wins":"Place Win",P=`+${X}`,n({kind:"win",title:H,subtitle:P,duration:1e3});try{window.dispatchEvent(new CustomEvent("craps:place_win",{detail:{payout:X,count:v.length}}))}catch{}return}if(aA){const X=U.filter(O=>O.outcome==="WIN").reduce((O,cA)=>O+cA.payout,0);H="Field Win",P=`+${X}`,n({kind:"win",title:H,subtitle:P,duration:1e3});return}if(sA){const X=x.filter(wA=>wA.outcome==="WIN"),O=X.reduce((wA,xA)=>wA+xA.payout,0);H=X.length>1?"Big Wins":((IA=X[0])==null?void 0:IA.betType)==="big6"?"Big 6 Win":"Big 8 Win",P=`+${O}`,n({kind:"win",title:H,subtitle:P,duration:1e3});return}if(pA){const X=T.filter(wA=>wA.outcome==="WIN"),O=X.reduce((wA,xA)=>wA+xA.payout,0);H=X.length>1?"Come Wins":((CA=X[0])==null?void 0:CA.betType)==="dontCome"?"DC Win":"Come Win",P=`+${O}`,n({kind:"win",title:H,subtitle:P,duration:1e3});return}if(fA){const X=q.filter(O=>O.outcome==="LOSE").reduce((O,cA)=>O+cA.amount,0);H="Line Lose",P=`-${X}`,n({kind:"lose",title:H,subtitle:P,duration:1100});return}if(RA){const X=U.filter(O=>O.outcome==="LOSE").reduce((O,cA)=>O+cA.amount,0);H="Field Lose",P=`-${X}`,n({kind:"lose",title:H,subtitle:P,duration:1e3});return}if(qA){const X=x.filter(wA=>wA.outcome==="LOSE"),O=X.reduce((wA,xA)=>wA+xA.amount,0);H=X.length>1?"Big Bets Lose":((_A=X[0])==null?void 0:_A.betType)==="big6"?"Big 6 Lose":"Big 8 Lose",P=`-${O}`,n({kind:"lose",title:H,subtitle:P,duration:1e3});return}if(W){const X=T.filter(wA=>wA.outcome==="LOSE"),O=X.reduce((wA,xA)=>wA+xA.amount,0);H=X.length>1?"Come Bets Lose":((uA=X[0])==null?void 0:uA.betType)==="dontCome"?"DC Lose":"Come Lose",P=`-${O}`,n({kind:"lose",title:H,subtitle:P,duration:1e3});return}if($){H="DC Push",P="No action",n({kind:"push",title:H,subtitle:P,duration:1e3});return}if(L){H="Line Push",P="No action",n({kind:"push",title:H,subtitle:P,duration:1e3});return}if(yA){const O=z.filter(cA=>cA.outcome==="LOSE").reduce((cA,wA)=>cA+wA.amount,0);H="ATS Busted",P=`-${O}`,n({kind:"lose",title:H,subtitle:P,duration:1200});return}try{o()}catch{}},[y,i,m,n,o]),C.jsxs(C.Fragment,{children:[C.jsx(rx,{...e,hideDiceResults:!0,className:"craps-player-panel"}),h&&C.jsx(Fie,{summary:h})]})}function Jie(e){return C.jsx(rx,{...e,headerCommsLeftSlot:void 0})}function Lie({deadlineTs:e,isActive:A,showTurnLabel:t=!0}){const[i,n]=E.useState(30),g=E.useRef(null);E.useEffect(()=>{if(!A||!e){n(30),g.current&&(cancelAnimationFrame(g.current),g.current=null);return}const I=()=>{const c=Date.now(),l=Math.max(0,Math.ceil((e-c)/1e3));n(l),l>0?g.current=requestAnimationFrame(I):g.current=null};return I(),()=>{g.current&&(cancelAnimationFrame(g.current),g.current=null)}},[e,A]);const o=A&&i!==30,s=i<=10,a=i<=5,r=i/30*100;return C.jsxs("div",{className:["poker-turn-timer",o?"":"poker-turn-timer--hidden",s?"poker-turn-timer--urgent":"",a?"poker-turn-timer--critical":""].filter(Boolean).join(" "),"aria-live":"polite","aria-atomic":"true",role:"timer","aria-hidden":!o,children:[C.jsxs("div",{className:"poker-turn-timer__ring",children:[C.jsxs("svg",{viewBox:"0 0 36 36",className:"poker-turn-timer__svg",children:[C.jsx("circle",{className:"poker-turn-timer__circle-bg",cx:"18",cy:"18",r:"16"}),C.jsx("circle",{className:"poker-turn-timer__circle-progress",cx:"18",cy:"18",r:"16",strokeDasharray:`${r} 100`})]}),C.jsx("div",{className:"poker-turn-timer__number",children:i})]}),t&&C.jsx("div",{className:"poker-turn-timer__label","aria-hidden":"true",children:"Your Turn"})]})}function KY({state:e,startingShields:A,maxTokens:t}){if(e.eliminated)return C.jsxs("div",{className:"elim-badge elim-badge--eliminated","aria-label":`Eliminated — ${xie(e.place??0)} place`,children:[C.jsx("span",{className:"elim-badge__out",children:"OUT"}),typeof e.place=="number"&&e.place>0&&C.jsxs("span",{className:"elim-badge__place",children:["#",e.place]})]});const i=[];for(let g=0;g<A;g++)i.push(C.jsx("span",{className:`elim-badge__shield ${g<e.shields?"elim-badge__shield--active":"elim-badge__shield--lost"}`,"aria-hidden":!0,children:"🛡"},`s${g}`));const n=[];for(let g=0;g<t;g++)n.push(C.jsx("span",{className:`elim-badge__token ${g<e.penaltyTokens?"elim-badge__token--active":""}`,"aria-hidden":!0},`t${g}`));return C.jsxs("div",{className:"elim-badge","aria-label":`Shields: ${e.shields}/${A}, Tokens: ${e.penaltyTokens}/${t}`,children:[C.jsx("span",{className:"elim-badge__shields",children:i}),e.penaltyTokens>0&&C.jsx("span",{className:"elim-badge__tokens",children:n}),e.winStreak>=2&&C.jsxs("span",{className:"elim-badge__streak","aria-label":`${e.winStreak} win streak`,children:["🔥",e.winStreak]})]})}function xie(e){const A=["th","st","nd","rd"],t=e%100;return e+(A[(t-20)%10]||A[t]||A[0])}function GZ(e){const A=E.useMemo(()=>e.headerExtras,[e.headerExtras]),t=E.useMemo(()=>{var I;const a=Array.isArray((I=e.gameState)==null?void 0:I.pokerSeats)?e.gameState.pokerSeats:[],r=new Map;for(const c of a){const l=(c.totalCommitted||0)+(c.committed||0);r.set(c.playerId,l)}return r},[e.gameState]),i=E.useMemo(()=>{var I;const a=Array.isArray((I=e.gameState)==null?void 0:I.pokerSeats)?e.gameState.pokerSeats:[],r=new Set;for(const c of a)c!=null&&c.playerId&&String(c.status||"").toLowerCase()==="folded"&&r.add(c.playerId);return r},[e.gameState]),n=E.useMemo(()=>{const a=new Map,r=Array.isArray(e.revealedHands)?e.revealedHands:[];for(const I of r)I!=null&&I.playerId&&Array.isArray(I.hole)&&I.hole.length===2&&a.set(String(I.playerId),I.hole);return a},[e.revealedHands]),g=E.useMemo(()=>a=>{var B,Q,h,d,p,y,m,D;const r=(B=e.elimConfig)!=null&&B.enabled?(Q=e.elimStates)==null?void 0:Q[a.id]:void 0,I=n.get(a.id);if(I&&I.length===2){const S=({value:k})=>{const N=String(k||"").toUpperCase(),G=N.slice(0,-1),M=N.slice(-1),w=G==="T"?"10":G,b=M==="H"||M==="D",_=M==="H"?"♥":M==="D"?"♦":M==="C"?"♣":"♠";return C.jsxs("div",{className:["poker-card","poker-card--mini",b?"poker-card--red":""].filter(Boolean).join(" "),"aria-label":`${w} of ${M}`,children:[C.jsx("span",{className:"poker-card__rank",style:{fontSize:14},children:w}),C.jsx("span",{className:"poker-card__suit",style:{fontSize:11},children:_})]})};return C.jsxs(C.Fragment,{children:[C.jsxs("div",{className:"poker-avatar__faces","aria-label":"hole-cards",children:[C.jsx(S,{value:I[0]}),C.jsx(S,{value:I[1]})]}),r&&C.jsx(KY,{state:r,startingShields:((h=e.elimConfig)==null?void 0:h.startingShields)??3,maxTokens:((d=e.elimConfig)==null?void 0:d.maxTokens)??3})]})}if(i.has(a.id))return C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"poker-avatar__bet","aria-label":"Folded",children:"Folded"}),r&&C.jsx(KY,{state:r,startingShields:((p=e.elimConfig)==null?void 0:p.startingShields)??3,maxTokens:((y=e.elimConfig)==null?void 0:y.maxTokens)??3})]});const l=`z${(t.get(a.id)||0).toLocaleString("en-US")}`;return C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"poker-avatar__bet","aria-label":`Total bet ${l}`,children:l}),r&&C.jsx(KY,{state:r,startingShields:((m=e.elimConfig)==null?void 0:m.startingShields)??3,maxTokens:((D=e.elimConfig)==null?void 0:D.maxTokens)??3})]})},[n,t,i,e.elimConfig,e.elimStates]);if(e.lite)return C.jsx(lpA,{className:"",players:e.players,meId:e.meId,onOpenDM:e.onOpenDM,onOpenSendMoney:e.onOpenSendMoney,renderActionsOverride:a=>g({id:a.id})});const o=E.useMemo(()=>{var c;const a=Array.isArray((c=e.gameState)==null?void 0:c.pokerSeats)?e.gameState.pokerSeats:[],r=new Map,I=new Set;for(const l of a){if(!l||!l.playerId)continue;const B=typeof l.stack=="number"?l.stack:void 0;typeof B=="number"&&r.set(String(l.playerId),B),I.add(String(l.playerId))}return e.players.map(l=>{const B=r.get(String(l.id));return typeof B=="number"?{...l,balance:B}:l})},[e.players]),s=E.useMemo(()=>C.jsx(Lie,{deadlineTs:e.turnDeadlineTs,isActive:!!e.isBettingStreet&&!!e.turnDeadlineTs,showTurnLabel:!!e.isHeroTurn}),[e.turnDeadlineTs,e.isBettingStreet,e.isHeroTurn]);return C.jsx(rx,{...e,className:"player-panel",players:o,hideDiceResults:!0,disableBankerFlash:!0,hideSideBets:!0,headerExtras:A,headerCommsLeftSlot:s,renderFacesOverride:a=>g(a)})}function UtA(e){var t;const A=((t=e.gameState)==null?void 0:t.gameMode)||"cee-lo";return A==="craps"?C.jsx(_ie,{...e}):A==="poker"?C.jsx(GZ,{...e}):C.jsx(Jie,{...e})}function Tie(){const{remoteStreams:e}=Il(),A=E.useRef({}),[t,i]=E.useState(!1),n=async o=>{const s=o.srcObject;if(!s||!s.getAudioTracks().length)return!1;try{return await o.play(),!0}catch{return!1}};E.useEffect(()=>{let o=!1;for(const[a,r]of Object.entries(e)){const I=A.current[a];I&&I.srcObject!==r&&(I.srcObject=r)}(async()=>{for(const a of Object.values(A.current)){if(!a)continue;await n(a)||(o=!0)}i(o)})();for(const a of Object.keys(A.current))if(!e[a]){const r=A.current[a];if(r){try{r.pause()}catch{}r.srcObject=null}delete A.current[a]}},[e]);const g=async()=>{for(const o of Object.values(A.current))o&&await n(o);i(!1)};return C.jsxs(C.Fragment,{children:[Object.keys(e).map(o=>C.jsx("audio",{ref:s=>{A.current[o]=s},autoPlay:!0,playsInline:!0,muted:!1,style:{display:"none"},onError:s=>{var a;console.warn("remote audio error",o,(a=s==null?void 0:s.currentTarget)==null?void 0:a.error)}},o)),t&&C.jsx("button",{onClick:g,style:{position:"fixed",bottom:16,right:16,zIndex:9999,padding:"8px 12px",borderRadius:8,fontWeight:700,color:"#fff"},children:"Tap to enable audio"})]})}const qie="_overlay_d52xd_3",Yie="_overlayClosed_d52xd_15",Hie="_drawer_d52xd_22",Oie="_drawerClosed_d52xd_59",Pie="_header_d52xd_72",jie="_headerTitle_d52xd_82",zie="_closeBtn_d52xd_91",Zie="_body_d52xd_108",Wie="_threadList_d52xd_115",Vie="_noPeers_d52xd_132",Xie="_threadBtn_d52xd_140",$ie="_threadBtnActive_d52xd_163",Ane="_avatar_d52xd_169",ene="_threadLabel_d52xd_189",tne="_threadName_d52xd_195",ine="_threadPreview_d52xd_204",nne="_unreadBadge_d52xd_212",gne="_activeThread_d52xd_229",one="_scroller_d52xd_237",sne="_scrollerEmpty_d52xd_251",ane="_message_d52xd_258",rne="_messageMine_d52xd_275",Ine="_messageContent_d52xd_284",Cne="_messageTime_d52xd_297",cne="_pending_d52xd_308",lne="_error_d52xd_316",Bne="_composer_d52xd_324",Ene="_composerInput_d52xd_336",Qne="_composerSend_d52xd_363",une="_composerSendDisabled_d52xd_389",Qg={overlay:qie,overlayClosed:Yie,drawer:Hie,drawerClosed:Oie,header:Pie,headerTitle:jie,closeBtn:zie,body:Zie,threadList:Wie,noPeers:Vie,threadBtn:Xie,threadBtnActive:$ie,avatar:Ane,threadLabel:ene,threadName:tne,threadPreview:ine,unreadBadge:nne,activeThread:gne,scroller:one,scrollerEmpty:sne,message:ane,messageMine:rne,messageContent:Ine,messageTime:Cne,pending:cne,error:lne,composer:Bne,composerInput:Ene,composerSend:Qne,composerSendDisabled:une};function dne(e){var g,o;if(!e)return"?";const t=e.split("@")[0].trim().split(/[\s._-]+/).filter(Boolean),i=(((g=t[0])==null?void 0:g[0])??"").toUpperCase(),n=(((o=t[1])==null?void 0:o[0])??"").toUpperCase();return i+n||i||"?"}function hne({open:e,onClose:A,peers:t,initialPeerId:i}){const{user:n}=tn(),g=(n==null?void 0:n.id)??(n==null?void 0:n.email)??"",{getDmSummary:o,getDmMessages:s,sendDmMessage:a,markDmRead:r,setActiveDm:I,threads:c,loadDmHistory:l}=OR(),[B,Q]=E.useState(i??null),[h,d]=E.useState(""),p=E.useRef(!1),y=E.useRef(null);E.useEffect(()=>{if(!e){p.current=!1;return}if(p.current)return;p.current=!0;let K=null;if(i)K=i;else{const J=o(),q=J==null?void 0:J.find(v=>v.unread>0);q?K=q.peerUserId:B?K=B:t.length&&(K=t[0].id)}K&&K!==B&&(Q(K),I(K),l(K))},[e,i,t,B,o,I]),E.useEffect(()=>{!e||!B||y.current!==B&&(y.current=B,r(B))},[e,B,r]);const m=E.useRef(null);E.useEffect(()=>(e?(m.current=document.body.style.overflow,document.body.style.overflow="hidden"):m.current!==null&&(document.body.style.overflow=m.current,m.current=null),()=>{m.current!==null&&(document.body.style.overflow=m.current,m.current=null)}),[e]),E.useEffect(()=>{e&&requestAnimationFrame(()=>{window.scrollTo({top:0,left:0,behavior:"instant"})})},[e]),E.useEffect(()=>{const K=window.visualViewport;if(!K)return;const J=()=>{N.current&&(N.current.scrollTop=N.current.scrollHeight+1e3)};return K.addEventListener("resize",J),()=>{K.removeEventListener("resize",J)}},[]);const D=E.useMemo(()=>B?(c==null?void 0:c[wC(B,g)])??[]:[],[B,e,c]),S=E.useMemo(()=>o()??[],[e,D.length]),k=E.useMemo(()=>{const K=new Map;return S.forEach(J=>K.set(J.peerUserId,J)),K},[S]),N=E.useRef(null);E.useEffect(()=>{N.current&&(N.current.scrollTop=N.current.scrollHeight+1e3)},[D.length,B,e]);const G=K=>{Q(K),I(K),r(K)},M=()=>{if(!B)return;const K=h.trim();if(!K)return;a(B,K)&&d("")},w=K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),M())},b=K=>{const J=t.find(q=>q.id===K);return(J==null?void 0:J.name)||(J==null?void 0:J.email)||K},_=K=>{const J=k.get(K);return J!=null&&J.last?((J.last.senderId===g?"You: ":"")+J.last.text).trim():""};return C.jsxs(C.Fragment,{children:[C.jsx("div",{"aria-hidden":!e,onClick:A,className:`${Qg.overlay} ${e?"":Qg.overlayClosed}`}),C.jsxs("aside",{"aria-hidden":!e,role:"dialog","aria-label":"Direct Messages",className:`${Qg.drawer} ${e?"":Qg.drawerClosed}`,onClick:K=>K.stopPropagation(),children:[C.jsxs("div",{className:Qg.header,children:[C.jsx("strong",{className:Qg.headerTitle,children:"Messages"}),C.jsx("button",{onClick:A,className:Qg.closeBtn,"aria-label":"Close messages",children:"✕"})]}),C.jsxs("div",{className:Qg.body,children:[C.jsxs("div",{className:Qg.threadList,children:[t.length===0&&C.jsx("div",{className:Qg.noPeers,children:"No other players yet."}),t.map(K=>{var x;const J=K.id===B,q=dne(K.name||K.email||K.id),v=((x=k.get(K.id))==null?void 0:x.unread)??0,U=_(K.id);return C.jsxs("button",{onClick:()=>G(K.id),className:`${Qg.threadBtn} ${J?Qg.threadBtnActive:""}`,title:b(K.id),children:[C.jsx("div",{className:Qg.avatar,"aria-hidden":!0,children:q}),C.jsxs("div",{className:Qg.threadLabel,children:[C.jsx("div",{className:Qg.threadName,children:b(K.id)}),C.jsx("div",{className:Qg.threadPreview,children:U})]}),v>0&&C.jsx("span",{"aria-label":`${v} unread`,className:Qg.unreadBadge,children:v>99?"99+":v})]},K.id)})]}),C.jsxs("div",{className:Qg.activeThread,children:[C.jsxs("div",{ref:N,className:Qg.scroller,children:[!B&&C.jsx("div",{className:Qg.scrollerEmpty,children:"Select a conversation to begin."}),B&&D.map(K=>{const J=K.senderId===g,q=new Date(K.ts),v=q.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return C.jsxs("div",{className:`${Qg.message} ${J?Qg.messageMine:""}`,title:q.toLocaleString(),children:[C.jsx("div",{className:Qg.messageContent,children:K.text}),C.jsx("div",{className:Qg.messageTime,children:v}),K.pending&&C.jsx("div",{className:Qg.pending,children:"sending…"}),K.error&&C.jsx("div",{className:Qg.error,children:K.error})]},K.id)})]}),C.jsxs("div",{className:Qg.composer,children:[C.jsx("input",{value:h,onChange:K=>d(K.target.value),onKeyDown:w,placeholder:B?`Message ${b(B)}…`:"Pick a conversation…",disabled:!B,className:Qg.composerInput}),C.jsx("button",{onClick:M,disabled:!B||h.trim()==="",className:`${Qg.composerSend} ${!B||h.trim()===""?Qg.composerSendDisabled:""}`,children:"Send"})]})]})]})]})]})}const pne="/assets/fairness-BcL04fcA.webp";function DpA({state:e}){const t={verified:{label:"Verified",cls:"fairness--ok",icon:"✓"},"bad-commit":{label:"Bad commit",cls:"fairness--bad",icon:"!"},mismatch:{label:"Mismatch",cls:"fairness--bad",icon:"!"},unverifiable:{label:"Unverified",cls:"fairness--dim",icon:"x"}}[e];return C.jsx("span",{className:`fairness ${t.cls}`,title:t.label,"aria-label":t.label,children:e==="verified"?C.jsx("img",{src:pne,alt:"Fairness verified",className:"fairness-img"}):t.icon})}function fne({roomId:e,lastRollerId:A,roundSeq:t,className:i,autoHideMs:n}){const{verifyFor:g,lastRoundWithReveal:o,proofs:s,reveals:a}=ipA(e),[r,I]=E.useState("unverifiable"),c=E.useRef(0),[l,B]=E.useState({}),[Q,h]=E.useState(!0),d=E.useMemo(()=>typeof t!="number"||!s?[]:Object.keys(s).filter(S=>S.startsWith(`${t}:`)),[s,t]),p=E.useMemo(()=>A||d.length&&d[d.length-1].split(":")[1]||null,[A,d]);E.useEffect(()=>{let S=!1;if(!g||!e||typeof t!="number"||!p)return I("unverifiable"),()=>{S=!0};const k=++c.current;return(async()=>{try{const N=await g(p,t);!S&&k===c.current&&I(N)}catch{!S&&k===c.current&&I("unverifiable")}})(),()=>{S=!0}},[g,e,p,t,d.length]),E.useEffect(()=>{if(!g||typeof t!="number")return;let S=!1;return d.forEach(k=>{const N=k.split(":")[1];N&&(async()=>{try{const G=await g(N,t);S||B(M=>M[k]===G?M:{...M,[k]:G})}catch{S||B(G=>G[k]==="unverifiable"?G:{...G,[k]:"unverifiable"})}})()}),()=>{S=!0}},[g,d,t,o]);const y=typeof t=="number"?!!(a!=null&&a[t]):!1;if(E.useEffect(()=>{if(!n||n<=0||!y)return;h(!0);const S=window.setTimeout(()=>h(!1),n);return()=>window.clearTimeout(S)},[n,t,y]),!y||!Q)return null;const m=d.filter(S=>l[S]==="verified").length,D=(()=>{if(d.length>1){if(m===d.length)return"All Verified";if(m>0)return`${m}/${d.length} Verified`}switch(r){case"verified":return"Provably Fair";case"bad-commit":return"Commit Mismatch";case"mismatch":return"Mismatch";default:return d.length?"Unverified":"Awaiting Reveal"}})();return C.jsxs("div",{className:["fairness-status-bar",i].filter(Boolean).join(" "),style:{display:"flex",alignItems:"center",gap:12,padding:"6px 12px",borderRadius:8,background:"rgba(0,0,0,.55)",backdropFilter:"blur(8px)",fontSize:12,lineHeight:1,color:"#fff",pointerEvents:"auto",boxShadow:"0 2px 6px rgba(0,0,0,.4)"},children:[C.jsx(DpA,{state:r}),C.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[C.jsx("span",{style:{fontWeight:600},children:D}),typeof t=="number"&&C.jsxs("span",{style:{opacity:.75},children:["Round ",t]})]})]})}function mpA({open:e,onClose:A,title:t,tagline:i,steps:n,primaryLabel:g,persistKey:o="seenOnboardingV1",secondaryLabel:s="Log In",onSecondary:a,targetSelector:r=".home-mode-toggle-row",coachText:I="Pick a game mode"}){const c=qi(),{user:l,loading:B}=tn(),Q=E.useMemo(()=>{if(B)return!1;const D=(l==null?void 0:l.email)||"";return!D||/@guest\.local$/i.test(D)},[l==null?void 0:l.email,B]),h=E.useCallback(()=>{try{o&&Ia.set({key:o,value:"1"})}catch{}A()},[A,o]);E.useEffect(()=>{if(!e)return;function D(S){S.key==="Escape"&&h()}return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[e,h]);const[d,p]=E.useState(null),y=E.useCallback(()=>{try{if(!e){p(null);return}const D=r?document.querySelector(r):null;if(!D){p(null);return}const S=D.getBoundingClientRect();p({top:S.top,left:S.left,width:S.width,height:S.height})}catch{p(null)}},[e,r]);if(E.useLayoutEffect(()=>{y()},[y]),E.useEffect(()=>{if(!e)return;const D=()=>y(),S=()=>y();window.addEventListener("resize",D),window.addEventListener("scroll",S,!0);const k=setInterval(y,400);return()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",S,!0),clearInterval(k)}},[e,y]),E.useEffect(()=>{if(e)try{(()=>{var S;try{return!!(window.__E2E===!0||typeof((S=window.location)==null?void 0:S.search)=="string"&&window.location.search.includes("e2e=1")||typeof window.sessionStorage<"u"&&window.sessionStorage.getItem("e2e")==="1")}catch{return!1}})()&&(o&&Ia.set({key:o,value:"1"}),setTimeout(()=>{try{A()}catch{}},0))}catch{}},[e,A,o]),!e)return null;const m=Array.isArray(n)&&n.length?n:["Create or join a room","Place bets, roll dice, or deal cards","Win chips and share the fun"];return C.jsxs("div",{className:"onb-modal",role:"dialog","aria-modal":"true","aria-label":"Welcome to Dice Lounge",children:[C.jsx("div",{className:"onb-backdrop",onClick:h}),C.jsxs("div",{className:"onb-card",onClick:D=>D.stopPropagation(),children:[C.jsx("button",{type:"button",className:"onb-close",onClick:h,"aria-label":"Close",children:"✕"}),C.jsxs("header",{className:"onb-header",children:[C.jsx("h2",{className:"onb-title",children:t||"Dice Lounge"}),C.jsx("p",{className:"onb-tagline",children:i||"Roll, chat, and play with friends."})]}),C.jsx("ol",{className:"onb-steps","aria-label":"Getting started steps",children:m.map((D,S)=>C.jsx("li",{className:"onb-step",children:D},S))}),C.jsx("div",{className:"onb-cta-row",children:s&&Q&&C.jsx("button",{type:"button",className:"onb-btn onb-btn--ghost felt-btn",onClick:a||(()=>c("/lobby")),children:s})})]}),d&&C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"onb-highlight","aria-hidden":!0,style:{top:Math.max(0,d.top-8),left:Math.max(0,d.left-8),width:d.width+16,height:d.height+16}}),C.jsx("div",{className:"onb-coachmark",role:"note","aria-label":I,style:{top:Math.max(0,d.top-14),left:d.left+d.width/2},children:C.jsx("span",{className:"onb-coachmark__label",children:I})})]})]})}const vtA=["Bones Bot","Stickman","Railbird","High Roller","Side Bet Sam","Mainline Max"];function Ix(){const e=E.useRef(null),A=E.useRef(!1),t=E.useRef(!1),i=E.useCallback(async()=>{if(t.current=!0,!(A.current||e.current)){A.current=!0;try{"wakeLock"in navigator&&(e.current=await navigator.wakeLock.request("screen"),e.current.addEventListener("release",()=>{e.current=null}))}catch(g){console.debug("[wakeLock] Failed to acquire:",g)}finally{A.current=!1}}},[]),n=E.useCallback(async()=>{if(t.current=!1,!!e.current)try{await e.current.release(),e.current=null}catch(g){console.debug("[wakeLock] Failed to release:",g)}},[]);return E.useEffect(()=>{const g=()=>{document.visibilityState==="visible"&&t.current&&e.current===null&&!A.current&&i()};return document.addEventListener("visibilitychange",g),()=>{document.removeEventListener("visibilitychange",g),n()}},[i,n]),{acquire:i,release:n}}const yne={"cee-lo":[{id:"ceelo_rounds",label:"Finish 5 Cee Lo hands",target:5,event:"ceelo:result"},{id:"ceelo_wins",label:"Win 3 Cee Lo hands",target:3,event:"ceelo:result",match:e=>(e==null?void 0:e.result)==="win"},{id:"ceelo_clean",label:"Avoid a loss twice",target:2,event:"ceelo:result",match:e=>(e==null?void 0:e.result)==="win"||(e==null?void 0:e.result)==="push"}],craps:[{id:"craps_points",label:"Make 2 points",target:2,event:"craps:point_made"},{id:"craps_place",label:"Hit 3 place wins",target:3,event:"craps:place_win"},{id:"craps_big",label:"Trigger a big table win",target:1,event:"craps:ats_win"}]},SpA=(e=new Date)=>{const A=e.getFullYear(),t=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${A}-${t}-${i}`},Dne=e=>{const[A,t,i]=e.split("-").map(Number),n=new Date(A,t-1,i);return n.setDate(n.getDate()-1),SpA(n)},wpA=(e,A)=>`community_missions_v1:${e}:${A||"guest"}`,Vb=e=>({dateKey:e,streak:1,lastPlayedDateKey:e,progress:{},completed:{}});function KtA(e,A){const t=SpA();try{const i=window.localStorage.getItem(wpA(e,A));if(!i)return Vb(t);const n=JSON.parse(i);if(n.dateKey===t)return{...Vb(t),...n};const g=n.dateKey===Dne(t)?Math.max(1,(n.streak||1)+1):1;return{...Vb(t),streak:g,lastPlayedDateKey:t}}catch{return Vb(t)}}function mne(e,A,t){try{window.localStorage.setItem(wpA(e,A),JSON.stringify(t))}catch{}}function Sne(e,A){const t=MB(),i=yne[e],[n,g]=E.useState(()=>KtA(e,A));E.useEffect(()=>{g(KtA(e,A))},[e,A]),E.useEffect(()=>{mne(e,A,n)},[e,A,n]);const o=E.useCallback((r,I)=>{g(c=>{let l=!1;const B={...c.progress},Q={...c.completed};for(const h of i){if(h.event!==r||h.match&&!h.match(I)||Q[h.id])continue;const d=Math.min(h.target,(B[h.id]||0)+1);B[h.id]=d,l=!0,d>=h.target&&(Q[h.id]=!0,t.success(h.label,{title:"Daily mission complete",duration:4200}))}return l?{...c,progress:B,completed:Q}:c})},[i,t]);E.useEffect(()=>{const I=Array.from(new Set(i.map(c=>c.event))).map(c=>{const l=B=>o(c,B.detail);return window.addEventListener(c,l),()=>window.removeEventListener(c,l)});return()=>I.forEach(c=>c())},[i,o]);const s=E.useMemo(()=>i.map(r=>{const I=Math.min(r.target,n.progress[r.id]||0);return{id:r.id,label:r.label,target:r.target,progress:I,completed:!!n.completed[r.id]||I>=r.target}}),[i,n.completed,n.progress]),a=s.filter(r=>r.completed).length;return{missions:s,streak:n.streak,completedCount:a,totalCount:s.length}}const FtA=["#ffd700","#ff6b6b","#4fc3f7","#81c784","#ba68c8","#ffb74d","#f06292","#aed581"],wne=50;function kne(e){const A=FtA[e%FtA.length],t=Math.random()*100,i=Math.random()*2,n=2+Math.random()*2,g=6+Math.random()*6,o=Math.random()*360,s=["square","rect","circle"],a=s[e%s.length];return C.jsx("span",{className:`lms-confetti__piece lms-confetti__piece--${a}`,style:{left:`${t}%`,animationDelay:`${i}s`,animationDuration:`${n}s`,backgroundColor:A,width:a==="rect"?`${g*.5}px`:`${g}px`,height:`${g}px`,transform:`rotate(${o}deg)`}},e)}function kpA({winnerName:e,bonus:A,isHero:t,onDismiss:i,onPlayAgain:n,playAgainBusy:g}){const[o,s]=E.useState(!1);E.useEffect(()=>{requestAnimationFrame(()=>s(!0))},[]);const a=E.useMemo(()=>Array.from({length:wne},(r,I)=>kne(I)),[]);return C.jsxs("div",{className:`lms-overlay ${o?"lms-overlay--visible":""}`,onClick:i,children:[C.jsx("div",{className:"lms-confetti","aria-hidden":"true",children:a}),C.jsxs("div",{className:"lms-content",children:[C.jsx("div",{className:"lms-trophy",children:"🏆"}),C.jsx("div",{className:"lms-title",children:t?"Last One Standing!":`${e} Wins!`}),C.jsx("div",{className:"lms-subtitle",children:t?"All opponents eliminated — you dominate the table!":`${e} outlasted everyone at the table!`}),t&&A>0&&C.jsxs("div",{className:"lms-bonus",children:[C.jsx("span",{className:"lms-bonus__label",children:"Bonus Reward"}),C.jsxs("span",{className:"lms-bonus__amount",children:["+z",A.toLocaleString()]})]}),C.jsxs("div",{className:"lms-actions",children:[n&&C.jsx("button",{type:"button",className:"lms-dismiss lms-dismiss--primary",onClick:r=>{r.stopPropagation(),n()},disabled:g,style:g?{opacity:.5,pointerEvents:"none"}:void 0,children:g?"Starting…":"Play Again"}),C.jsx("button",{type:"button",className:n?"lms-dismiss lms-dismiss--secondary":"lms-dismiss",onClick:i,children:n?"Lobby":"Continue"})]})]})]})}const Mne=2e3,Nne=2500,Rne=400,Gne=1e3,bZ=({show:e,variant:A,onComplete:t,zoomDurationMs:i=Mne,displayMs:n=Nne,fadeDurationMs:g=Rne,ariaLabel:o,contained:s=!1})=>{const[a,r]=E.useState(!1),[I,c]=E.useState(!1),[l,B]=E.useState(!1),[Q,h]=E.useState(!1),d=E.useRef({bleed:null,fade:null,complete:null,raf:null}),p=E.useRef(t);if(E.useEffect(()=>{p.current=t},[t]),E.useEffect(()=>(e?(d.current.bleed&&clearTimeout(d.current.bleed),d.current.fade&&clearTimeout(d.current.fade),d.current.complete&&clearTimeout(d.current.complete),d.current.raf&&cancelAnimationFrame(d.current.raf),r(!0),c(!1),B(!1),h(!1),d.current.raf=requestAnimationFrame(()=>{d.current.raf=requestAnimationFrame(()=>{d.current.raf=null,c(!0)})}),d.current.bleed=setTimeout(()=>{h(!0)},Math.min(Gne,n)),d.current.fade=setTimeout(()=>{B(!0)},n),d.current.complete=setTimeout(()=>{r(!1),c(!1),B(!1),h(!1),p.current()},n+g)):(d.current.bleed&&clearTimeout(d.current.bleed),d.current.fade&&clearTimeout(d.current.fade),d.current.complete&&clearTimeout(d.current.complete),d.current.raf&&cancelAnimationFrame(d.current.raf),r(!1),c(!1),B(!1),h(!1)),()=>{d.current.bleed&&clearTimeout(d.current.bleed),d.current.fade&&clearTimeout(d.current.fade),d.current.complete&&clearTimeout(d.current.complete),d.current.raf&&cancelAnimationFrame(d.current.raf)}),[e,n,g]),!a)return null;const y=C.jsx("div",{className:`celebration-overlay ${s?"celebration-overlay--contained":""} ${Q?"celebration-overlay--bleed-through":"celebration-overlay--foreground"} ${l?"celebration-overlay--fadeout":""}`,"data-testid":`celebration-${A}`,style:{"--celebration-fade-ms":`${g}ms`},children:C.jsx("div",{className:"celebration-container",children:C.jsx("div",{className:`celebration-image celebration-image--${A} ${I?"celebration-image--animating":""}`,style:{"--celebration-zoom-ms":`${i}ms`},role:"img","aria-label":o||`${A} celebration`})})});return s?y:er.createPortal(y,document.body)},bne=500;function UZ(){const[e,A]=E.useState(null),[t,i]=E.useState(ds.showCelebrationImages!==!1),n=E.useRef([]),g=E.useRef(null),o=E.useCallback(()=>{if(n.current.length===0){g.current=null,A(null);return}const r=n.current.shift();r&&(g.current=r,A(r))},[]),s=E.useCallback((r,I)=>{if(!t)return;const c={variant:r,...I};if(n.current.push(c),!g.current){const l=n.current.shift();g.current=l,A(l)}},[t]),a=E.useCallback(()=>{g.current=null,A(null),setTimeout(()=>o(),bne)},[o]);return E.useEffect(()=>{let r=!0;Xo().then(c=>{r&&i(c.showCelebrationImages!==!1)}).catch(()=>{r&&i(ds.showCelebrationImages!==!1)});const I=c=>{const l=c.detail;l&&typeof l.showCelebrationImages=="boolean"&&i(l.showCelebrationImages)};return window.addEventListener("app:settings",I),()=>{r=!1,window.removeEventListener("app:settings",I)}},[]),E.useEffect(()=>{t||(n.current=[],g.current=null,A(null))},[t]),E.useEffect(()=>{},[s]),{active:e,fire:s,onComplete:a}}function Une(e){var r,I,c,l,B;const{total:A,point:t,events:i,resolutions:n}=e,g=[],o=!t&&(A===7||A===11);o&&(n!=null&&n.passLineWins)&&g.push({variant:"natural",displayMs:2500});const s=((r=i==null?void 0:i.includes)==null?void 0:r.call(i,"point_made"))||((I=i==null?void 0:i.includes)==null?void 0:I.call(i,"POINT_MADE"))||((c=i==null?void 0:i.some)==null?void 0:c.call(i,Q=>Q.startsWith("pointMade:")));s&&g.push({variant:"point-made",displayMs:3e3});const a=((l=i==null?void 0:i.includes)==null?void 0:l.call(i,"sevenOut"))||((B=i==null?void 0:i.includes)==null?void 0:B.call(i,"SEVEN_OUT"))||A===7&&!!(n!=null&&n.passLineLosses);return a&&g.push({variant:"generic-loss",displayMs:2e3}),{celebrations:g,sevenOut:a,isNatural:o,pointMade:!!s}}const nQ=[{level:1,name:"Toy Box"},{level:2,name:"Cowboys"},{level:3,name:"Surfers"},{level:4,name:"Speed Demons"},{level:5,name:"Beach Club"},{level:6,name:"Rookies"},{level:7,name:"Wave Riders"},{level:8,name:"Regulars"},{level:9,name:"High Rollers"}],_tA=E.lazy(()=>Qi(()=>Promise.resolve().then(()=>phe),void 0)),vne="single_player_guest_id";function VR(){var ve,re,Qe,HA,ge,ye,Te,gt,Qt,_e,Ze,at,Ai,Bi,yi,mt,ct,fi,Yi,si,jt,Zt,vi,kn,gn,Ki,Tn,fg,Zi,te,Eg,gi,Mg,Hg,de,qe;const{roomId:e}=Qw(),A=qi(),{user:t,meId:i}=tn(),{error:n}=MB();RR();const g=Ix();E.useEffect(()=>(g.acquire(),()=>{g.release()}),[g]),E.useEffect(()=>{const OA=()=>{try{f8()||On()}catch{}};OA();const Ae=["pointerdown","touchstart","mousedown","click","keydown"];return Ae.forEach(Ke=>{document.addEventListener(Ke,OA,{once:!0,capture:!0})}),()=>{Ae.forEach(Ke=>{document.removeEventListener(Ke,OA,{capture:!0})})}},[]);const o=(()=>{var OA;try{return((OA=window.sessionStorage)==null?void 0:OA.getItem(vne))||""}catch{return""}})(),s=i||(t==null?void 0:t.id)||(t==null?void 0:t.email)||o||"",[a,r]=E.useState(0),{rollTrigger:I,resetSpin:c}=kB(),[l,B]=E.useState(0),Q=E.useRef(null),h=DZ(e,s,{autoJoin:!0}),{room:d,joining:p,error:y,lastRollerId:m,deadline:D,serverNow:S,diceSettled:k}=h,N=epA({roomId:e||null,myPlayerId:s,autoJoinOrder:!0}),G=((ve=d==null?void 0:d.gameState)==null?void 0:ve.gameMode)==="craps"?N.shooterState:null,M=E.useMemo(()=>{var Ae;const OA=d==null?void 0:d.gameState;if((OA==null?void 0:OA.gameMode)==="craps"){const Ke=((Ae=N.lastRoll)==null?void 0:Ae.point)??null,Je=Ke??OA.crapsPoint??null,pt=G?{...G}:{},Tt={...OA,...pt,crapsPoint:Je,lastRoll:N.lastRoll};return Tt.crapsPhase=Je?"point":"come-out",Tt}return OA},[d==null?void 0:d.gameState,G,N.lastRoll]),w=E.useMemo(()=>{var OA;if(((OA=d==null?void 0:d.gameState)==null?void 0:OA.gameMode)==="craps"){const Ae=N.lastRoll;return Ae&&Array.isArray(Ae.dice)?[Ae.dice[0],Ae.dice[1],0]:void 0}return h.diceResults},[(re=d==null?void 0:d.gameState)==null?void 0:re.gameMode,N.lastRoll,h.diceResults]),b=E.useRef(()=>{}),[_,K]=E.useState(!1),J=E.useCallback(OA=>{b.current=OA.roll,K(Ae=>Ae===OA.canRoll?Ae:OA.canRoll)},[]),q=E.useMemo(()=>{const OA=M==null?void 0:M.spectators;return Array.isArray(OA)&&!!s&&OA.includes(s)},[M,s]),v=!!(h!=null&&h.canRoll)&&!q,U=E.useCallback(()=>{var OA;v&&((OA=h==null?void 0:h.handleRoll)==null||OA.call(h))},[h,v]),x=E.useCallback(()=>{var OA;if(_){B(1);try{(OA=b.current)==null||OA.call(b)}finally{window.setTimeout(()=>B(0),120)}}},[_]),T=E.useMemo(()=>{var vt,ei;if(((vt=d==null?void 0:d.gameState)==null?void 0:vt.gameMode)!=="craps")return[];const OA=(d==null?void 0:d.players)??[],Ae=(G==null?void 0:G.turnOrder)||((ei=d==null?void 0:d.gameState)==null?void 0:ei.turnOrder)||[];if(!Ae.length)return OA;const Ke=new Map(OA.map(Vt=>[Vt.id,Vt])),Je=new Set(Ae),pt=Ae.map((Vt,hA)=>{const Re=Ke.get(Vt);if(Re)return Re;const ot=Vt.includes("craps_bot_")||Vt.includes("bot_");return{id:Vt,name:ot?vtA[hA%vtA.length]||`Bot ${hA+1}`:"Player",isReady:!0,balance:ot?500:0,avatarUrl:null,isBot:ot}}),Tt=OA.filter(Vt=>!Je.has(Vt.id)&&!Vt.isBot);return[...pt,...Tt]},[(Qe=d==null?void 0:d.gameState)==null?void 0:Qe.gameMode,d==null?void 0:d.players,G==null?void 0:G.turnOrder,(HA=d==null?void 0:d.gameState)==null?void 0:HA.turnOrder]),z=E.useMemo(()=>{var Re,ot,kt,ht,ee;if(!(d!=null&&d.singlePlayer))return;const OA=(Re=d==null?void 0:d.gameState)==null?void 0:Re.gameMode;if(OA!=="craps"&&OA!=="cee-lo")return;const Ae=OA==="craps"?t==null?void 0:t.spLevelCraps:t==null?void 0:t.spLevelCeelo,Ke=Number((d==null?void 0:d.spLevel)??((ot=d==null?void 0:d.gameState)==null?void 0:ot._spLevel)??Ae??1),Je=Number.isFinite(Ke)&&Ke>0?Ke:1,pt=new Map;if(OA==="craps")for(const je of T)pt.set(String((je==null?void 0:je.id)??""),je);for(const je of(d==null?void 0:d.players)??[])pt.set(String((je==null?void 0:je.id)??""),je);const Tt=(kt=d==null?void 0:d.gameState)==null?void 0:kt._botBalances;for(const[je,Ct]of Object.entries(Tt??{}))pt.has(je)||pt.set(je,{id:je,isBot:!0,balance:Ct});const vt=Array.from(pt.values()).filter(je=>(je==null?void 0:je.isBot)||String((je==null?void 0:je.id)??"").includes("bot_")),ei=vt.filter(je=>{const Ct=Tt==null?void 0:Tt[String((je==null?void 0:je.id)??"")];return Number(Ct??(je==null?void 0:je.balance)??0)<=0}).length,Vt=(d==null?void 0:d.levelName)??((ht=d==null?void 0:d.gameState)==null?void 0:ht._levelName)??((ee=nQ.find(je=>je.level===Je))==null?void 0:ee.name)??`Level ${Je}`,hA=vt.length;return{level:Je,levelName:Vt,current:ei,total:hA,progressLabel:`${ei}/${hA} bots defeated`,goalLabel:`Defeat every bot to reach Level ${Je+1}`,isMaxLevel:Je>=nQ.length}},[d==null?void 0:d.singlePlayer,d==null?void 0:d.gameState,d==null?void 0:d.spLevel,d==null?void 0:d.levelName,d==null?void 0:d.players,T,t==null?void 0:t.spLevelCraps,t==null?void 0:t.spLevelCeelo]),{onCrapsShooterTurnEnd:Z,cancelAd:eA}=Yf(),aA=E.useRef(null);E.useEffect(()=>{var Je;if(((Je=d==null?void 0:d.gameState)==null?void 0:Je.gameMode)!=="craps")return;const OA=N.lastRoll;if(!OA||aA.current===OA)return;aA.current=OA;const{currentRollerId:Ae,nextRollerId:Ke}=OA;Ae&&Ke&&Ae!==Ke&&Z()},[N.lastRoll,(ge=d==null?void 0:d.gameState)==null?void 0:ge.gameMode,Z]);const sA=E.useRef(null),[pA,gA]=E.useState(1),[yA,fA]=E.useState(null),[RA,qA]=E.useState(!1),[W,$]=E.useState(void 0),[L,H]=E.useState(null),[P,tA]=E.useState(null),iA=E.useMemo(()=>((d==null?void 0:d.players)??[]).filter(OA=>OA.id!==s).map(OA=>({id:OA.id,name:OA.name})),[d==null?void 0:d.players,s]),oA=((ye=d==null?void 0:d.gameState)==null?void 0:ye.phase)==="waiting"&&!I,IA=(((Te=d==null?void 0:d.gameState)==null?void 0:Te.gameMode)||"cee-lo")==="cee-lo"&&!!((gt=d==null?void 0:d.gameState)!=null&&gt.roundEnded),CA=typeof((Qt=d==null?void 0:d.gameState)==null?void 0:Qt.roundSeq)=="number"?(d==null?void 0:d.gameState).roundSeq:0;E.useEffect(()=>{IA&&P!==CA&&H(CA)},[P,CA,IA]),E.useEffect(()=>{H(null),tA(null)},[e]),E.useEffect(()=>{oA?wL({volume:.0125}):Yu()},[oA]);const _A=E.useCallback(OA=>{$(OA),qA(!0)},[]),uA=E.useCallback(()=>{qA(!1),$(void 0)},[]),X=E.useRef(void 0);E.useEffect(()=>{var Ae,Ke,Je;const OA=(Ae=d==null?void 0:d.gameState)==null?void 0:Ae.roundSeq;if(typeof OA=="number"&&X.current!==void 0&&OA!==X.current&&(r(0),(((Ke=d==null?void 0:d.gameState)==null?void 0:Ke.gameMode)||"cee-lo")==="cee-lo")){const pt=(Je=d==null?void 0:d.gameState)==null?void 0:Je.banker,Tt=pt&&s&&pt===s;try{Tt||$P({volume:.6})}catch{}}typeof OA=="number"&&(X.current=OA)},[(_e=d==null?void 0:d.gameState)==null?void 0:_e.roundSeq]);const O=Ms(),{joinRoom:cA}=nI(),[wA,xA]=E.useState(!1);E.useCallback(async()=>{if(!wA&&!(!O||!e)){xA(!0);try{if(cA)try{await cA(e)}catch(OA){console.warn("[manualRefresh] joinRoom failed",OA)}}catch(OA){console.warn("[manualRefresh] failed",OA)}finally{xA(!1)}}},[wA,O,e,cA]),E.useEffect(()=>{if(!O)return;const OA=()=>{try{c()}catch{}};return O.on("disconnect",OA),()=>{O.off("disconnect",OA)}},[O,c]),E.useEffect(()=>{if(!O||!s)return;const OA=Ae=>{var Ke;if(!(!Ae||Ae.winnerId!==s)){console.log("[game] last man standing (server event)",{myId:s});try{eA()}catch{}$A({winnerId:s}),(Ke=j.current)==null||Ke.call(j,"last-man",{displayMs:3e3})}};return O.on("ceelo:last_man_standing",OA),O.on("craps:last_man_standing",OA),()=>{O.off("ceelo:last_man_standing",OA),O.off("craps:last_man_standing",OA)}},[O,s,eA]),E.useEffect(()=>{if(!O||!s)return;const OA=Ae=>{!Ae||Ae.playerId!==s||(console.log("[ceelo] player busted (server event)",{myId:s}),kA(!0))};return O.on("ceelo:player_busted",OA),()=>{O.off("ceelo:player_busted",OA)}},[O,s]),E.useEffect(()=>{kA(!1)},[e]),E.useEffect(()=>{requestAnimationFrame(()=>{window.scrollTo({top:0,left:0,behavior:"instant"})})},[]);const[YA,jA]=E.useState(()=>typeof window>"u"?!1:window.innerWidth>window.innerHeight);E.useEffect(()=>{const OA=()=>jA(window.innerWidth>window.innerHeight);window.addEventListener("resize",OA);const Ae=setTimeout(OA,0);return()=>{window.removeEventListener("resize",OA),clearTimeout(Ae)}},[]),E.useEffect(()=>{y&&n(y,{title:"Room Error",duration:5e3})},[y,n]);const ie=E.useRef(0),he=E.useRef(!1),le=E.useRef(!1),NA=E.useRef(!1),EA=E.useRef(!1),PA=E.useRef(null),ZA=E.useRef(null),[FA,Ie]=E.useState(0),{active:DA,fire:rA,onComplete:BA}=UZ(),j=E.useRef(rA);j.current=rA;const QA=E.useRef(0),dA=E.useRef(null),UA=E.useRef(0),TA=E.useRef(0),oe=E.useRef(0),me=E.useRef(0),be=E.useRef(0),$e=["ceelo-noir-win"],ci=["craps-noir-win"],ke=["loss-ceelo","loss-craps"],nt=["loss-craps","loss-ceelo"],Ut=()=>{const OA=$e[oe.current%$e.length];return oe.current+=1,OA},dt=()=>{const OA=ci[me.current%ci.length];return me.current+=1,OA},Ht=()=>{const OA=ke[be.current%ke.length];return be.current+=1,OA},Ft=()=>{const OA=nt[be.current%nt.length];return be.current+=1,OA},[Jt,$A]=E.useState(null),[He,Xe]=E.useState(!1),[St,kA]=E.useState(!1);E.useEffect(()=>{},[s,rA]);const{createRoom:se}=Mo(),[Ce,VA]=E.useState(),nA=E.useRef(null);E.useEffect(()=>{var Je,pt,Tt;const OA=((Je=d==null?void 0:d.gameState)==null?void 0:Je.gameMode)||"cee-lo",Ae=(pt=d==null?void 0:d.gameState)==null?void 0:pt.currentRollerId,Ke=!!((Tt=d==null?void 0:d.gameState)!=null&&Tt.roundEnded);if(OA==="cee-lo"){if(Ke){VA(void 0),nA.current=null;return}Ae&&Ae!==nA.current&&(nA.current=Ae,VA(Date.now()+3e4))}},[(Ze=d==null?void 0:d.gameState)==null?void 0:Ze.currentRollerId,(at=d==null?void 0:d.gameState)==null?void 0:at.roundEnded,(Ai=d==null?void 0:d.gameState)==null?void 0:Ai.gameMode]);const[vA,KA]=E.useState(!1);E.useEffect(()=>{var Ke;const OA=(Ke=d==null?void 0:d.gameState)==null?void 0:Ke.gameMode;if(!OA)return;let Ae=!0;return(async()=>{try{const{Preferences:Je}=await Qi(async()=>{const{Preferences:vt}=await Promise.resolve().then(()=>Oc);return{Preferences:vt}},void 0),pt=OA==="craps"?"onb_craps_v1":"onb_ceelo_v1",{value:Tt}=await Je.get({key:pt});if(!Ae)return;KA(Tt!=="1")}catch{if(!Ae)return;KA(!0)}})(),()=>{Ae=!1}},[(Bi=d==null?void 0:d.gameState)==null?void 0:Bi.gameMode]);const WA=E.useCallback(()=>{var Ae;const OA=(Ae=d==null?void 0:d.gameState)==null?void 0:Ae.gameMode;(async()=>{try{const{Preferences:Ke}=await Qi(async()=>{const{Preferences:Je}=await Promise.resolve().then(()=>Oc);return{Preferences:Je}},void 0);await Ke.set({key:OA==="craps"?"onb_craps_v1":"onb_ceelo_v1",value:"1"})}catch{}KA(!1)})()},[(yi=d==null?void 0:d.gameState)==null?void 0:yi.gameMode]);E.useEffect(()=>{var vt;if(((vt=d==null?void 0:d.gameState)==null?void 0:vt.gameMode)==="craps"){he.current=!1,le.current=!1;return}const OA=h==null?void 0:h.diceResults;if(!OA||OA.length!==3){he.current=!1,le.current=!1,NA.current=!1,PA.current=null;return}const Ae=OA.join(",");if(Ae===PA.current)return;PA.current=Ae;const Ke=[...OA].sort().join(","),Je=Ke==="4,5,6",pt=Je||Ke==="1,2,3",Tt=OA[0]===OA[1]&&OA[1]===OA[2];NA.current=Tt,he.current=pt,le.current=Je},[h==null?void 0:h.diceResults,(mt=d==null?void 0:d.gameState)==null?void 0:mt.gameMode]),E.useEffect(()=>{var Tt,vt;if(((Tt=d==null?void 0:d.gameState)==null?void 0:Tt.gameMode)==="craps"){ZA.current=null;return}const OA=(vt=d==null?void 0:d.gameState)==null?void 0:vt.bankRoll;if(!OA||!Array.isArray(OA.raw)||OA.raw.length!==3){ZA.current=null;return}const Ae=OA.raw,Ke={};for(const ei of Ae)Ke[ei]=(Ke[ei]||0)+1;const Je=Object.keys(Ke).map(Number);Je.length===2&&Je.some(ei=>Ke[ei]===1)?ZA.current=Je.find(ei=>Ke[ei]===1)||null:ZA.current=null},[(ct=d==null?void 0:d.gameState)==null?void 0:ct.bankRoll,(fi=d==null?void 0:d.gameState)==null?void 0:fi.gameMode]),E.useEffect(()=>{var ot,kt;if(((ot=d==null?void 0:d.gameState)==null?void 0:ot.gameMode)==="craps"){EA.current=!1;return}const OA=(kt=d==null?void 0:d.gameState)==null?void 0:kt.banker;if(OA&&s&&OA===s){EA.current=!1;return}const Ke=ZA.current;if(!Ke||Ke<1){EA.current=!1;return}const Je=h==null?void 0:h.diceResults;if(!Je||Je.length!==3){EA.current=!1;return}const Tt=[...Je].sort((ht,ee)=>ht-ee).join(",")==="4,5,6",vt={};for(const ht of Je)vt[ht]=(vt[ht]||0)+1;const ei=Object.keys(vt).map(Number),Vt=ei.length===1,Re=ei.length===2&&ei.some(ht=>vt[ht]===1)?ei.find(ht=>vt[ht]===1):null;EA.current=Tt||Vt||Re!==null&&Re>Ke},[h==null?void 0:h.diceResults,d==null?void 0:d.gameState,s,(Yi=d==null?void 0:d.gameState)==null?void 0:Yi.gameMode]),E.useEffect(()=>{var Ae;if(!(h!=null&&h.diceSettled))return;const OA=Date.now();if(he.current||le.current||NA.current||EA.current){if(OA-ie.current<800){he.current=!1,le.current=!1,NA.current=!1,EA.current=!1;return}ie.current=OA;const Ke=(d==null?void 0:d.singlePlayer)===!0,Je=(Ae=d==null?void 0:d.gameState)==null?void 0:Ae.banker,pt=Je&&s&&Je===s,Tt=m,vt=Tt==null?void 0:Tt.startsWith("bot_");!vt&&(Ke||Tt&&s&&Tt===s||!pt)&&(le.current?rA("bang-bang-456",{displayMs:3e3,zoomDurationMs:2500}):NA.current&&rA("trips",{displayMs:2500})),EA.current&&!vt&&rA("clutch",{displayMs:2500}),he.current=!1,le.current=!1,NA.current=!1,EA.current=!1,Ie(hA=>hA+1)}},[h==null?void 0:h.diceSettled,m,s,d==null?void 0:d.singlePlayer,(si=d==null?void 0:d.gameState)==null?void 0:si.banker,rA]),E.useEffect(()=>{var Ke;if((((Ke=d==null?void 0:d.gameState)==null?void 0:Ke.gameMode)||"cee-lo")!=="cee-lo")return;const Ae=Je=>{var Tt;const pt=(Tt=Je.detail)==null?void 0:Tt.result;if(pt==="win"){TA.current+=1;const vt=TA.current;vt>=5&&vt%5===0?rA("streak-5",{displayMs:3500}):vt>=3&&vt%3===0?rA("streak-3",{displayMs:3e3}):rA(Ut(),{displayMs:2e3})}else pt==="lose"&&(TA.current=0,rA(Ht(),{displayMs:2e3}))};return window.addEventListener("ceelo:result",Ae),()=>window.removeEventListener("ceelo:result",Ae)},[(jt=d==null?void 0:d.gameState)==null?void 0:jt.gameMode,rA]),E.useEffect(()=>{var Vt;if(((Vt=d==null?void 0:d.gameState)==null?void 0:Vt.gameMode)!=="craps")return;const OA=N.lastRoll;if(!OA||dA.current===OA)return;dA.current=OA;const{total:Ae,point:Ke,resolutions:Je,events:pt}=OA,Tt=Une({total:Ae,point:Ke,events:pt??[],resolutions:Je??{passLineWins:!1,passLineLosses:!1,pushes:!1}});let vt=null;Je!=null&&Je.passLineWins?(QA.current+=1,QA.current>=5?(vt="streak-5",QA.current=0):QA.current>=2&&(vt="hot-streak")):Je!=null&&Je.passLineLosses&&(QA.current=0);const ei=Tt.celebrations[0];if(ei){const hA=ei.variant==="generic-loss"?Ft():ei.variant;rA(hA,{displayMs:ei.displayMs})}else vt?rA(vt,{displayMs:vt==="streak-5"?3500:3e3}):Je!=null&&Je.passLineWins&&rA(dt(),{displayMs:2e3})},[N.lastRoll,(Zt=d==null?void 0:d.gameState)==null?void 0:Zt.gameMode,rA]),E.useEffect(()=>{var kt;if((((kt=d==null?void 0:d.gameState)==null?void 0:kt.gameMode)||"cee-lo")!=="cee-lo")return;const Ae=d==null?void 0:d.gameState,Ke=(Ae==null?void 0:Ae.roundSeq)??0,Je=(Ae==null?void 0:Ae.turnHistory)??[],pt=Je.filter(ht=>ht.roundSeq===Ke),Tt=pt.find(ht=>ht.playerId===s),vt=pt.filter(ht=>ht.playerId!==s);if(console.log("[sweep-check]",{roundEnded:Ae==null?void 0:Ae.roundEnded,roundSeq:Ke,lastSweepSeq:UA.current,banker:Ae==null?void 0:Ae.banker,myId:s,bankerMatch:(Ae==null?void 0:Ae.banker)===s,historyLen:Je.length,roundEntryCount:pt.length,bankerEntry:Tt?{rank:Tt.rank,playerId:Tt.playerId}:null,challengerCount:vt.length,challengers:vt.map(ht=>{var ee;return{playerId:(ee=ht.playerId)==null?void 0:ee.slice(0,8),rank:ht.rank}}),allLost:Tt?vt.every(ht=>ht.rank<Tt.rank):!1}),!(Ae!=null&&Ae.roundEnded))return;const ei=Ae.roundSeq??0;if(ei<=UA.current)return;const Vt=Ae.banker;if(!Vt||Vt!==s)return;const hA=pt.find(ht=>ht.playerId===s),Re=pt.filter(ht=>ht.playerId!==s);!hA||Re.length<2||!Re.every(ht=>ht.rank<hA.rank)||(UA.current=ei,console.log("[sweep-check] 🎉 FIRING ceelo-sweep celebration",{roundSeq:ei}),rA("ceelo-sweep",{displayMs:3e3}))},[(vi=d==null?void 0:d.gameState)==null?void 0:vi.roundEnded,(kn=d==null?void 0:d.gameState)==null?void 0:kn.roundSeq,(gn=d==null?void 0:d.gameState)==null?void 0:gn.gameMode,s,rA]),E.useEffect(()=>{var Ke;if(((Ke=d==null?void 0:d.gameState)==null?void 0:Ke.gameMode)!=="craps")return;const OA=()=>{rA(dt(),{displayMs:2e3})},Ae=()=>{rA("craps-big-win",{displayMs:3500})};return window.addEventListener("craps:place_win",OA),window.addEventListener("craps:ats_win",Ae),()=>{window.removeEventListener("craps:place_win",OA),window.removeEventListener("craps:ats_win",Ae)}},[(Ki=d==null?void 0:d.gameState)==null?void 0:Ki.gameMode,rA]);const bA=Sne(((Tn=d==null?void 0:d.gameState)==null?void 0:Tn.gameMode)==="craps"?"craps":"cee-lo",s);if(p)return C.jsxs("div",{className:"HomeScreen theme-casino home-fixed-root",children:[C.jsx(tr,{className:"page-home-screen"}),C.jsx("div",{className:"home-preloader",children:C.jsx("div",{className:"home-preloader__spinner"})})]});if(!d)return console.error('[Gameroom] Rendering "Room not found" error',{roomId:e,error:y,joining:p}),C.jsxs("div",{className:"HomeScreen theme-casino",children:[C.jsx(tr,{className:"page-gameroom"}),C.jsx("div",{className:"room-grid-fit",children:C.jsxs("div",{className:"error-grid",children:[C.jsx("p",{className:"error text-center",children:"Room not found."}),C.jsx("button",{className:"felt-btn felt-btn--secondary",onClick:()=>A("/lobby"),children:"Back to lobby"})]})})]});const pe=((fg=d.gameState)==null?void 0:fg.gameMode)==="craps",xe=((Zi=d.gameState)==null?void 0:Zi.gameMode)!=="craps";return C.jsxs(Kne,{className:pe?"mode-craps":xe?"mode-ceelo":void 0,bgShakeTrigger:FA,children:[C.jsx(tr,{className:"page-gameroom"}),C.jsx(Ote,{}),C.jsx(mpA,{open:vA,onClose:WA,title:pe?"Craps":"Cee‑Lo",tagline:pe?"Place your bets and roll the point.":"Banker vs challengers. Roll to win.",steps:pe?["Place Pass/Don’t Pass (optional Place bets)","Shooter rolls: establish point or win/lose on come-out","Resolve bets on each roll"]:["Banker faces challengers each round","Place a MAIN bet to challenge the banker","Highest valid roll wins the pot"],primaryLabel:"Got it",persistKey:pe?"onb_craps_v1":"onb_ceelo_v1"}),C.jsxs("div",{className:"room-grid-fit",style:!YA&&yA&&!pe?{height:yA}:void 0,children:[C.jsx("div",{className:"fairness-container",children:C.jsx(fne,{roomId:e,lastRollerId:m,roundSeq:(te=d==null?void 0:d.gameState)==null?void 0:te.roundSeq,autoHideMs:pe?3e3:void 0})}),C.jsxs("div",{ref:sA,className:"room-grid"+(pe?" room-grid--craps":"")+(pA<.999?" room-grid--scaled":""),style:pA<.999?{transform:`scale(${pA})`,transformOrigin:"top center",height:yA||void 0}:void 0,children:[DA&&C.jsx(bZ,{show:!0,contained:!0,variant:DA.variant,displayMs:DA.displayMs,zoomDurationMs:DA.zoomDurationMs,fadeDurationMs:DA.fadeDurationMs,ariaLabel:DA.ariaLabel,onComplete:BA}),pe?C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"players-row",children:C.jsx(UtA,{className:"PlayerPanel",roomId:e,roomName:d.name,players:T,bankerId:(Eg=d.gameState)==null?void 0:Eg.banker,currentRollerId:(gi=d.gameState)==null?void 0:gi.currentRollerId,meId:s,gameState:M,lastRollerId:m,onOpenDM:_A,onOpenSendMoney:()=>{},crapsRollHistory:N.rollHistory,singlePlayer:d==null?void 0:d.singlePlayer,campaignProgress:z})}),C.jsx("div",{className:"stage",ref:Q,children:C.jsx("div",{className:"table-wrap",children:C.jsx("div",{className:`felt ${oA?"is-muted":""}`,children:C.jsx(_tA,{isWaiting:oA,rollTrigger:I,results:w,preRollTrigger:a,gameMode:(Mg=d.gameState)==null?void 0:Mg.gameMode,gameState:M,chargeLevel:l,shimmerColor:"#f5d78e",rollEnabled:_,onRollRequest:x})})})}),C.jsxs("div",{className:"bets-wrapper bets-wrapper--craps",children:[C.jsx(mtA,{...bA}),(()=>{const OA=d.players.find(Ke=>Ke.id===s),Ae=(OA==null?void 0:OA.balance)??(t==null?void 0:t.balance)??1e3;return C.jsx(Hte,{meId:s,balance:Ae,onChargeChange:B,onRollAffordanceChange:J})})()]})]}):C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"players-row",children:C.jsx(UtA,{className:"player-panel",roomId:e,roomName:d.name,players:d.gameState.turnOrder.map(OA=>d.players.find(Ae=>Ae.id===OA)).filter(OA=>!!OA),bankerId:(Hg=d.gameState)==null?void 0:Hg.banker,currentRollerId:(de=d.gameState)==null?void 0:de.currentRollerId,meId:s,gameState:M,lastRollerId:m,onOpenDM:_A,onOpenSendMoney:()=>{},singlePlayer:d==null?void 0:d.singlePlayer,turnDeadlineTs:Ce,campaignProgress:z})}),C.jsx("div",{className:"stage",ref:Q,children:C.jsx("div",{className:"table-wrap",children:C.jsx("div",{className:`felt ${oA?"is-muted":""}`,children:C.jsx(_tA,{isWaiting:oA,rollTrigger:I,results:w,preRollTrigger:a,gameMode:(qe=d.gameState)==null?void 0:qe.gameMode,gameState:M,chargeLevel:l,shimmerColor:"#f5d78e",rollEnabled:v,onRollRequest:U})})})}),C.jsxs("div",{className:"bet-panel",children:[C.jsx(mtA,{...bA}),!1,C.jsx("div",{className:"bets-wrapper",children:C.jsx(cXA,{gameState:d.gameState,roundEnded:d.gameState.roundEnded,roomId:e,meId:s,bankerId:d.gameState.banker,hasBankRoll:!!d.gameState.bankRoll,players:d.players,timeLeft:{deadline:D,serverNow:S},showPassBank:!1,showSpectateRow:!1,gameplay:h,onChargeChange:B})}),C.jsx("div",{className:"spectate-wrapper",children:C.jsx(Vte,{roomId:e,meId:s,bankerId:d.gameState.banker,players:d.players,gameState:M,gameplay:h})})]})]})]})]}),C.jsx(Tie,{}),C.jsx(hne,{open:RA,onClose:uA,peers:iA,initialPeerId:W}),Jt&&C.jsx(kpA,{winnerName:(()=>{const OA=((d==null?void 0:d.players)??[]).find(Ae=>Ae.id===Jt.winnerId);return(OA==null?void 0:OA.name)||"You"})(),bonus:0,isHero:!0,onDismiss:()=>{$A(null),A("/lobby")},playAgainBusy:He,onPlayAgain:async()=>{var OA,Ae,Ke;if(!He){try{const{hapticClick:Je}=await Qi(async()=>{const{hapticClick:pt}=await Promise.resolve().then(()=>R1);return{hapticClick:pt}},void 0);Je("Medium")}catch{}Xe(!0);try{const{loadSettings:Je}=await Qi(async()=>{const{loadSettings:Re}=await Promise.resolve().then(()=>TcA);return{loadSettings:Re}},void 0),pt=await Je(),Tt=pt.botDifficultyLevel&&pt.botDifficultyLevel>=1&&pt.botDifficultyLevel<=9?pt.botDifficultyLevel:void 0,vt=((OA=d==null?void 0:d.gameState)==null?void 0:OA.gameMode)||"cee-lo",ei=await se({name:"Single Player Room",singlePlayer:!0,gameMode:vt,botLevel:Tt}),Vt=(ei==null?void 0:ei.room)??((Ae=ei==null?void 0:ei.data)==null?void 0:Ae.room)??null,hA=(Vt==null?void 0:Vt.roomId)??(Vt==null?void 0:Vt.id)??(ei==null?void 0:ei.roomId)??((Ke=ei==null?void 0:ei.data)==null?void 0:Ke.roomId);hA?($A(null),A(`/room/${hA}`,{replace:!0})):(console.warn("[game:play_again] no room id in response",ei),Xe(!1))}catch(Je){console.error("[game:play_again] error",Je),Xe(!1)}}}}),St&&C.jsx("div",{className:"busted-overlay",onClick:()=>{kA(!1),A("/lobby")},children:C.jsxs("div",{className:"busted-overlay__card",onClick:OA=>OA.stopPropagation(),children:[C.jsx("h2",{children:"You're Busted!"}),C.jsx("p",{children:"Your balance hit zero. Buy more credits to keep playing."}),C.jsxs("div",{className:"busted-overlay__actions",children:[C.jsx("button",{className:"felt-btn felt-btn--halo",onClick:()=>{kA(!1),A("/add-chips")},children:"Buy Credits"}),C.jsx("button",{className:"felt-btn",onClick:()=>{kA(!1),A("/lobby")},children:"Back to Lobby"})]})]})})]})}function Kne({children:e,className:A,bgShakeTrigger:t}){const i=E.useRef(null),n=E.useRef(!0),{showAnimations:g}=NZ();return E.useEffect(()=>{i.current&&i.current.classList.remove("fx-bg-shake")},[]),E.useEffect(()=>{if(!i.current||typeof t!="number"||g===!1)return;if(n.current||t===0){n.current=!1;return}i.current.classList.remove("fx-bg-shake"),i.current.offsetHeight,i.current.classList.add("fx-bg-shake");const o=()=>{var s;(s=i.current)==null||s.classList.remove("fx-bg-shake")};return i.current.addEventListener("animationend",o,{once:!0}),()=>{var s;(s=i.current)==null||s.removeEventListener("animationend",o)}},[t,g]),C.jsx("div",{ref:i,className:"room-shell"+(A?` ${A}`:""),children:e})}function Fne(e=3e4){const{friends:A}=Kd(),{getOnlineFriends:t}=Mo(),[i,n]=E.useState(new Set),[g,o]=E.useState(!0),s=E.useCallback(async()=>{try{const r=await t();r!=null&&r.ok&&Array.isArray(r.online)&&n(new Set(r.online))}catch{}o(!1)},[t]);return E.useEffect(()=>{s();const r=setInterval(s,e);return()=>clearInterval(r)},[s,e]),E.useEffect(()=>{s()},[A.length,s]),{onlineFriends:A.filter(r=>i.has(r.id)).map(r=>({...r,isOnline:!0})),loading:g,refresh:s}}function _ne({gameMode:e}){const{onlineFriends:A,loading:t}=Fne(),{user:i}=tn();return!i||t||A.length===0?null:C.jsxs("div",{className:"online-friends",role:"region","aria-label":"Online Friends",children:[C.jsxs("div",{className:"online-friends__header",children:[C.jsx("span",{className:"online-friends__dot","aria-hidden":!0}),C.jsxs("span",{className:"online-friends__title",children:[A.length," Friend",A.length>1?"s":""," Online"]})]}),C.jsx("div",{className:"online-friends__scroll",children:A.map(n=>C.jsx(Jne,{friend:n,gameMode:e},n.id))})]})}function Jne({friend:e,gameMode:A}){const t=e.name??"Player",i=t.charAt(0).toUpperCase();return C.jsxs("div",{className:"online-friend-chip",title:t,children:[C.jsxs("div",{className:"online-friend-chip__avatar",style:e.avatarUrl?{backgroundImage:`url(${e.avatarUrl})`}:void 0,children:[!e.avatarUrl&&C.jsx("span",{className:"online-friend-chip__initial",children:i}),C.jsx("span",{className:"online-friend-chip__status","aria-hidden":!0})]}),C.jsx("span",{className:"online-friend-chip__name",children:t.length>8?t.slice(0,7)+"…":t})]})}const Xb="theme-light",$b="theme-dark";function AU(e){const A=document.documentElement,t=document.body;e==="light"?(A.classList.add(Xb),A.classList.remove($b),t.classList.add(Xb),t.classList.remove($b)):(A.classList.add($b),A.classList.remove(Xb),t.classList.add($b),t.classList.remove(Xb))}function MpA(){const[e,A]=E.useState(!1),[t,i]=E.useState("dark");E.useEffect(()=>{let o=!0;return(async()=>{try{const a=(await Xo()).theme??"dark";o&&(i(a),AU(a),A(!0))}catch{o&&(AU("dark"),A(!0))}})(),()=>{o=!1}},[]),E.useEffect(()=>{e&&AU(t)},[t,e]);const n=E.useCallback(async o=>{i(o),AU(o);try{const s=await Xo(),a={...ds,...s,theme:o};await JE(a)}catch{}},[]),g=E.useCallback(async()=>{await n(t==="dark"?"light":"dark")},[t,n]);return{ready:e,theme:t,setTheme:n,toggleTheme:g}}const Lne="/assets/ceelo-icon-DBUGq3gk.webp",xne="/assets/craps-icon-Cxbu5IDi.webp",Tne="/assets/poker-icon-D9lS6jix.webp",qne="/assets/skills-icon-BWMGnrDl.webp",Yne="/assets/zentara-icon-CtcCkOmF.webp";function Hne(){const e=Ms(),A=qi(),{user:t}=tn(),{friends:i,friendRequests:n,blockedUsers:g,addFriend:o}=Kd(),[s,a]=E.useState(""),[r,I]=E.useState([]),[c,l]=E.useState(!1),[B,Q]=E.useState(null),[h,d]=E.useState(new Set),p=E.useRef(null),y=E.useCallback(k=>{if(!e||!k.trim()||k.trim().length<2){I([]),Q(null);return}l(!0),Q(null),e.emit(Lt.SOCIAL_SEARCH_PLAYERS,{query:k.trim()},N=>{if(l(!1),N.ok&&N.players){const G=N.players.map(M=>({...M,isFriend:i.some(w=>w.id===M.id),isPending:n.some(w=>(w.fromUserId===M.id||w.toUserId===M.id)&&w.status==="PENDING"),isBlocked:g.some(w=>w.id===M.id)}));I(G)}else Q(N.error||"Search failed"),I([])})},[e,i,n,g]);E.useEffect(()=>(p.current&&clearTimeout(p.current),s.trim().length>=2?p.current=setTimeout(()=>{y(s)},300):(I([]),Q(null)),()=>{p.current&&clearTimeout(p.current)}),[s,y]);const m=E.useCallback(k=>{h.has(k)||(o(k),d(N=>new Set([...N,k])))},[o,h]),D=k=>k.isFriend?"Friends":k.isPending||h.has(k.id)?"Pending":k.isBlocked?"Blocked":"Add Friend",S=k=>k.isFriend||k.isPending||k.isBlocked||h.has(k.id);return t?C.jsxs("div",{className:"friend-search",children:[C.jsx("div",{className:"friend-search-header",children:C.jsx("h3",{children:"Find Friends"})}),C.jsxs("div",{className:"friend-search-input-wrapper",children:[C.jsx("input",{type:"text",className:"friend-search-input",placeholder:"Search by username...",value:s,onChange:k=>a(k.target.value),autoComplete:"off",autoCapitalize:"off"}),c&&C.jsx("span",{className:"friend-search-spinner",children:"⟳"})]}),B&&C.jsx("div",{className:"friend-search-error",children:B}),r.length>0&&C.jsx("ul",{className:"friend-search-results",children:r.map(k=>C.jsxs("li",{className:"friend-search-result",children:[C.jsx("div",{className:"friend-search-avatar",onClick:()=>A(`/player/${k.id}`),style:{cursor:"pointer"},children:k.avatarUrl?C.jsx("img",{src:k.avatarUrl,alt:k.name||"User"}):C.jsx("div",{className:"friend-search-avatar-placeholder",children:(k.name||"?")[0].toUpperCase()})}),C.jsx("span",{className:"friend-search-name",onClick:()=>A(`/player/${k.id}`),style:{cursor:"pointer"},children:k.name}),C.jsx("button",{className:`friend-search-btn ${S(k)?"disabled":""}`,onClick:()=>m(k.id),disabled:S(k),children:D(k)})]},k.id))}),s.trim().length>=2&&!c&&r.length===0&&!B&&C.jsx("div",{className:"friend-search-empty",children:"No users found"}),s.trim().length>0&&s.trim().length<2&&C.jsx("div",{className:"friend-search-hint",children:"Enter at least 2 characters"})]}):null}function Hf(){const e=qi(),{user:A,refreshUser:t,logout:i}=tn(),{updateProfile:n}=Mo(),{membershipModalOpen:g,setMembershipModalOpen:o}=RR(),{isPremium:s}=JBA(),{friends:a,friendRequests:r,blockedUsers:I,refreshSocial:c,isBlocked:l,blockUser:B,unblockUser:Q,removeFriend:h,respondToFriendRequest:d}=Kd(),{getUnreadForPeer:p}=OR(),{forUserId:y,anchorRect:m,anchorEl:D,openFor:S,close:k}=kZ(),[N,G]=E.useState(null),[M,w]=E.useState(null),b=E.useCallback((re,Qe,HA,ge)=>{S(re,Qe),G(HA),w(ge||null)},[S]),_=E.useCallback(()=>{k(),G(null),w(null)},[k]),[K,J]=E.useState((A==null?void 0:A.name)??""),[q,v]=E.useState((A==null?void 0:A.email)??""),[U,x]=E.useState((A==null?void 0:A.avatarUrl)??""),[T,z]=E.useState(!1),[Z,eA]=E.useState(null),[aA,sA]=E.useState(!1),[pA,gA]=E.useState(null),[yA,fA]=E.useState(!1),[RA,qA]=E.useState(null),[W,$]=E.useState("received"),[L,H]=E.useState("idle"),[P,tA]=E.useState(0),[iA,oA]=E.useState(null),IA=E.useRef(null),{onBuyChips:CA,onGoPremium:_A,onRestore:uA,busy:X,busyChips:O,ready:cA,isWeb:wA,premiumActive:xA,hasPremiumPackage:YA,premiumLabel:jA,premiumSubtitle:ie,premiumDescription:he,premiumPrice:le,premiumInterval:NA}=Sw(),[EA,PA]=E.useState(!!(A!=null&&A.botChatDisabled)),[ZA,FA]=E.useState((A==null?void 0:A.ceeloBotsPerRoom)??null),[Ie,DA]=E.useState((A==null?void 0:A.crapsBotsPerRoom)??null),[rA,BA]=E.useState((A==null?void 0:A.pokerBotsPerRoom)??null),[j,QA]=E.useState((A==null?void 0:A.sex)??""),[dA,UA]=E.useState((A==null?void 0:A.location)??""),[TA,oe]=E.useState((A==null?void 0:A.age)!=null?String(A.age):""),[me,be]=E.useState((A==null?void 0:A.interests)??""),[$e,ci]=E.useState((A==null?void 0:A.aboutMe)??"");E.useEffect(()=>{J((A==null?void 0:A.name)??""),v((A==null?void 0:A.email)??""),x((A==null?void 0:A.avatarUrl)??""),PA(!!(A!=null&&A.botChatDisabled)),FA((A==null?void 0:A.ceeloBotsPerRoom)??null),DA((A==null?void 0:A.crapsBotsPerRoom)??null),BA((A==null?void 0:A.pokerBotsPerRoom)??null),QA((A==null?void 0:A.sex)??""),UA((A==null?void 0:A.location)??""),oe((A==null?void 0:A.age)!=null?String(A.age):""),be((A==null?void 0:A.interests)??""),ci((A==null?void 0:A.aboutMe)??"")},[A==null?void 0:A.id,A==null?void 0:A.name,A==null?void 0:A.email,A==null?void 0:A.avatarUrl,A==null?void 0:A.botChatDisabled,A==null?void 0:A.ceeloBotsPerRoom,A==null?void 0:A.crapsBotsPerRoom,A==null?void 0:A.pokerBotsPerRoom,A==null?void 0:A.sex,A==null?void 0:A.location,A==null?void 0:A.age,A==null?void 0:A.interests,A==null?void 0:A.aboutMe]),E.useEffect(()=>{c()},[]);const ke=E.useCallback(async()=>{z(!0),eA(null);try{const re={};K!==(A==null?void 0:A.name)&&(re.name=K),q!==(A==null?void 0:A.email)&&(re.email=q),U!==(A==null?void 0:A.avatarUrl)&&(re.avatarUrl=U),typeof EA=="boolean"&&(re.botChatDisabled=EA);const Qe=j.trim()||null;Qe!==((A==null?void 0:A.sex)??null)&&(re.sex=Qe);const HA=dA.trim()||null;HA!==((A==null?void 0:A.location)??null)&&(re.location=HA);const ge=TA.trim()?Number(TA.trim()):null;ge!==((A==null?void 0:A.age)??null)&&(re.age=ge);const ye=me.trim()||null;ye!==((A==null?void 0:A.interests)??null)&&(re.interests=ye);const Te=$e.trim()||null;Te!==((A==null?void 0:A.aboutMe)??null)&&(re.aboutMe=Te);const gt=Th||Wq,Qt=Th||vp,_e=Th||Kp;gt&&ZA!==((A==null?void 0:A.ceeloBotsPerRoom)??null)&&(re.ceeloBotsPerRoom=ZA),Qt&&Ie!==((A==null?void 0:A.crapsBotsPerRoom)??null)&&(re.crapsBotsPerRoom=Ie),_e&&rA!==((A==null?void 0:A.pokerBotsPerRoom)??null)&&(re.pokerBotsPerRoom=rA);const Ze=await n(re);if(!(Ze!=null&&Ze.ok))eA((Ze==null?void 0:Ze.error)||"Failed to save");else{try{await t({force:!0})}catch{}await c()}}catch(re){eA((re==null?void 0:re.message)||"Failed to save")}finally{z(!1)}},[K,q,U,A,n,c,t,ZA,Ie,rA,EA,j,dA,TA,me,$e]),nt=E.useCallback(async re=>{l(re)?await Q(re):await B(re)},[l,B,Q]),Ut=E.useCallback(re=>{h(re)},[h]),dt=E.useCallback(re=>{e(`/messages?peer=${encodeURIComponent(re)}`)},[e]),Ht=E.useCallback(async re=>{await d(re.id,"ACCEPT")},[d]);E.useCallback(async re=>{await d(re.id,"DECLINE")},[d]);const Ft=E.useCallback(async re=>{sA(!0),gA(null);try{if(re.size>5242880){gA("File size must be less than 5MB");return}if(!["image/jpeg","image/jpg","image/png","image/webp","image/gif"].includes(re.type)){gA("File must be a valid image (JPEG, PNG, WebP, or GIF)");return}const ge=new FormData;ge.append("avatar",re);const ye=String(ZM??"http://localhost:4000").replace(/\/+$/,"");let Te={},gt;try{const at=await uo();at&&(Te={Authorization:`Bearer ${at}`},gt=at)}catch{}const Qt=new URL(`${ye}/api/avatar/upload`);gt&&Qt.searchParams.set("token",gt);const _e=await fetch(Qt.toString(),{method:"POST",body:ge,headers:Te,credentials:"include"});if(!_e.ok){const at=await _e.json().catch(()=>({error:"Upload failed"}));throw new Error(at.error||`Upload failed with status ${_e.status}`)}const Ze=await _e.json();Ze.avatarUrl&&x(Ze.avatarUrl)}catch(Qe){console.error("[avatar] upload error:",Qe),gA((Qe==null?void 0:Qe.message)||"Failed to upload avatar")}finally{sA(!1)}},[]),Jt=E.useCallback(re=>{var HA;const Qe=(HA=re.target.files)==null?void 0:HA[0];Qe&&Ft(Qe),IA.current&&(IA.current.value="")},[Ft]),$A=E.useCallback(()=>{var HA;if(!((A==null?void 0:A.membershipTier)==="PREMIUM"||s)){try{o(!0)}catch{}return}(HA=IA.current)==null||HA.click()},[A,s,o]),He=E.useMemo(()=>{const re=new Map;for(const Qe of a)re.set(Qe.id,Qe);for(const Qe of I)re.has(Qe.id)||re.set(Qe.id,Qe);return re},[a,I]),Xe=E.useMemo(()=>r.map(re=>{const Qe=(A==null?void 0:A.id)===re.toUserId,HA=Qe?re.fromUserId:re.toUserId;if(!HA)return null;const ge=(Qe?re.fromUser:re.toUser)||He.get(HA),ye=(ge==null?void 0:ge.name)??HA,Te=(ge==null?void 0:ge.avatarUrl)??void 0;return{id:HA,name:ye,avatarUrl:Te,_req:re,_incoming:Qe}}).filter(Boolean),[r,A==null?void 0:A.id,He]),{showAnimations:St,toggleAnimations:kA,ready:se}=NZ();MpA();const[Ce,VA]=E.useState(ds.diceColorTheme),[nA,vA]=E.useState(void 0),[KA,WA]=E.useState(ds.zentaraBotCount??1);E.useEffect(()=>{(async()=>{try{const re=await Xo();VA(re.diceColorTheme??ds.diceColorTheme),vA(re.botDifficultyLevel),WA(re.zentaraBotCount??ds.zentaraBotCount??1)}catch{VA(ds.diceColorTheme)}})()},[]);const bA=E.useCallback(async re=>{try{const Qe=await Xo(),HA={...ds,...Qe,botDifficultyLevel:re};await JE(HA),vA(re)}catch{}},[]),pe=E.useCallback(async re=>{const Qe=Math.max(1,Math.min(5,re));try{const HA=await Xo(),ge={...ds,...HA,zentaraBotCount:Qe};await JE(ge),WA(Qe)}catch{}},[]),xe=E.useCallback(async re=>{try{const Qe=await Xo(),HA={...ds,...Qe,diceColorTheme:re};await JE(HA),VA(re)}catch{}},[]),it=E.useCallback(()=>o(!1),[o]);E.useEffect(()=>{t()},[]);const ve=E.useCallback(async()=>{try{if(qA(null),!window.confirm("Are you sure you want to permanently delete your account? This action cannot be undone."))return;const Qe=String(ZM??"http://localhost:4000").replace(/\/+$/,"");let HA;try{const ye=await uo();ye&&(HA={Authorization:`Bearer ${ye}`})}catch{}const ge=await fetch(`${Qe}/api/account`,{method:"DELETE",credentials:"include",headers:HA});if(!ge.ok){const ye=await ge.json().catch(()=>({error:"Deletion failed"}));throw new Error(ye.error||`Failed with status ${ge.status}`)}console.log("[account-delete] account deleted successfully",ge)}catch(re){qA((re==null?void 0:re.message)||"Failed to delete account")}finally{i()}},[e]);return C.jsxs("div",{className:`${Lc?"theme-zentara":"theme-casino"} home-fixed-root add-chips`,children:[C.jsx(tr,{className:"profile-page-body"}),C.jsx("div",{className:"logout-container  home-header-row",children:C.jsxs("a",{className:"gold-link white-link gold-link--mini","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}history.back()},children:[C.jsx(tc,{className:"icon"})," Back"]})}),C.jsx("div",{className:"profile-page",children:C.jsx("div",{className:"home-fit-shell",children:C.jsxs("div",{className:"home-fit-content",children:[C.jsx(_ne,{}),C.jsxs("div",{className:"profile-content",children:[C.jsx("div",{className:"profile-avatar-section",children:C.jsxs("div",{className:"profile-avatar-card",children:[C.jsxs("div",{className:"profile-avatar-header",children:[C.jsx("span",{className:"profile-avatar-label",children:"Avatar"}),C.jsx("span",{className:"profile-avatar-badge",children:"PREMIUM"})]}),C.jsxs("div",{className:"profile-avatar-content",children:[C.jsx("div",{className:"profile-avatar-preview",children:U?C.jsx("img",{src:U,alt:"Avatar preview",className:"profile-avatar-img"}):C.jsx("div",{className:"profile-avatar-placeholder",children:C.jsx("span",{children:"No Avatar"})})}),C.jsxs("div",{className:"profile-avatar-actions",children:[C.jsx("input",{ref:IA,type:"file",accept:"image/jpeg,image/jpg,image/png,image/webp,image/gif",onChange:Jt,disabled:aA,style:{display:"none"}}),C.jsx("button",{className:"profile-avatar-upload-btn","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}$A()},disabled:aA,children:aA?"Uploading...":"Upload Avatar"}),C.jsx("div",{className:"profile-avatar-hint",children:"Max 5MB • JPEG, PNG, WebP, or GIF"}),pA&&C.jsxs("div",{className:"error-message",style:{marginTop:"8px"},children:[pA,pA.includes("Premium")&&C.jsx("div",{style:{marginTop:"8px"},children:C.jsx("button",{className:"felt-btn","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}_A()},style:{fontSize:"0.9em",padding:"6px 12px"},children:"Upgrade to Premium"})})]})]})]})]})}),C.jsx("div",{className:"profile-section",children:C.jsx(Hne,{})}),C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Friends:"}),a.length?C.jsx("div",{className:"friends-scroll",children:C.jsx(RK,{className:"friends-panel",players:a,meId:(A==null?void 0:A.id)||"",onPlayerClick:re=>{const Qe=document.querySelector(`[data-player-id="${re}"]`),HA=Qe==null?void 0:Qe.querySelector(".avatar-ring");HA&&b(re,HA,"friends")},renderActions:re=>{const Qe=p(re.id);return Qe<=0?null:C.jsx("span",{className:"friend-unread-badge","aria-label":`${Qe} unread message${Qe>1?"s":""}`,children:Qe>99?"99+":Qe})}})}):C.jsx("span",{children:"No friends yet"})]}),C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Friend Requests:"}),C.jsxs("div",{className:"request-tab-toggle",children:[C.jsx("button",{className:`request-tab-btn${W==="received"?" active":""}`,onClick:()=>$("received"),children:"Received"}),C.jsx("button",{className:`request-tab-btn${W==="sent"?" active":""}`,onClick:()=>$("sent"),children:"Sent"})]}),(()=>{const re=Xe.filter(Qe=>W==="received"?Qe._incoming:!Qe._incoming);return re.length?C.jsx("div",{className:"friends-scroll",children:C.jsx(RK,{className:"friends-panel",players:re,meId:(A==null?void 0:A.id)||"",onPlayerClick:Qe=>{const HA=document.querySelector(`[data-player-id="${Qe}"]`),ge=HA==null?void 0:HA.querySelector(".avatar-ring"),ye=Xe.find(Te=>Te.id===Qe);ge&&(ye!=null&&ye._req)&&b(Qe,ge,"requests",{id:ye._req.id,incoming:!!ye._incoming})}})}):C.jsxs("span",{children:["No ",W," requests"]})})()]}),C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Blocked Users:"}),I.length?C.jsx("div",{className:"friends-scroll",children:C.jsx(RK,{className:"friends-panel",players:I,meId:(A==null?void 0:A.id)||"",onPlayerClick:re=>{const Qe=document.querySelector(`[data-player-id="${re}"]`),HA=Qe==null?void 0:Qe.querySelector(".avatar-ring");HA&&b(re,HA,"blocked")}})}):C.jsx("span",{children:"No blocked users"})]}),y&&m&&N&&C.jsx(IpA,{anchorRect:m,anchorEl:D,onClose:_,onViewProfile:()=>{e(`/player/${y}`),_()},onMessages:N==="friends"?()=>{dt(y),_()}:void 0,onUnfriend:N==="friends"?()=>{Ut(y),_()}:void 0,onBlockUser:N!=="requests"?async()=>{await nt(y),_()}:void 0,isFriend:N==="friends",isBlocked:N==="blocked",...N==="requests"&&(M!=null&&M.incoming)?{onAddFriend:()=>{Ht({id:M.id}),_()},hideAddFriend:!1}:{}}),C.jsxs("div",{className:"profile-row profile-row--two",children:[C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Name:"}),C.jsx("div",{className:"editable-field",children:C.jsx("input",{type:"text",value:K,onChange:re=>J(re.target.value),disabled:T})})]}),C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Email:"}),C.jsx("div",{className:"editable-field",children:C.jsx("input",{type:"email",value:q,onChange:re=>v(re.target.value),disabled:T})})]})]}),C.jsxs("div",{className:"profile-row profile-row--two",children:[C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Sex:"}),C.jsx("div",{className:"editable-field",children:C.jsxs("select",{value:j,onChange:re=>QA(re.target.value),disabled:T,"aria-label":"Sex",children:[C.jsx("option",{value:"",children:"Prefer not to say"}),C.jsx("option",{value:"Male",children:"Male"}),C.jsx("option",{value:"Female",children:"Female"}),C.jsx("option",{value:"Non-binary",children:"Non-binary"})]})})]}),C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Age:"}),C.jsx("div",{className:"editable-field",children:C.jsxs("select",{value:TA,onChange:re=>oe(re.target.value),disabled:T,"aria-label":"Age",children:[C.jsx("option",{value:"",children:"Prefer not to say"}),Array.from({length:103},(re,Qe)=>Qe+18).map(re=>C.jsx("option",{value:re,children:re},re))]})})]})]}),C.jsx("div",{className:"profile-row",children:C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Location:"}),C.jsx("div",{className:"editable-field",children:C.jsx("input",{type:"text",value:dA,onChange:re=>UA(re.target.value),disabled:T,placeholder:"e.g. Chicago, IL",maxLength:120,"aria-label":"Location"})})]})}),C.jsx("div",{className:"profile-row",children:C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Interests:"}),C.jsx("div",{className:"editable-field",children:C.jsx("input",{type:"text",value:me,onChange:re=>be(re.target.value),disabled:T,placeholder:"e.g. Poker, Sports, Music",maxLength:500,"aria-label":"Interests"})})]})}),C.jsx("div",{className:"profile-row",children:C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"About Me:"}),C.jsx("div",{className:"editable-field",children:C.jsx("textarea",{value:$e,onChange:re=>ci(re.target.value),disabled:T,placeholder:"Tell other players about yourself...",maxLength:500,rows:3,"aria-label":"About Me",style:{resize:"vertical",minHeight:60}})})]})}),(()=>{const re=Th||Wq,Qe=Th||vp,HA=Th||Kp;return C.jsxs(C.Fragment,{children:[(re||Qe)&&C.jsxs("div",{className:"profile-row profile-row--two",children:[re&&C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Single‑player bots (Cee‑Lo):"}),C.jsxs("div",{className:"editable-field",children:[C.jsxs("select",{value:ZA==null?"":String(ZA),onChange:ge=>{const ye=ge.target.value;FA(ye===""?null:Math.max(0,Math.min(8,Math.trunc(Number(ye)))))},disabled:T,"aria-label":"Preferred number of bots in single-player Cee‑Lo rooms",children:[C.jsx("option",{value:"",children:"Default (3 bots)"}),Array.from({length:5}).map((ge,ye)=>C.jsx("option",{value:ye,children:ye},ye))]}),C.jsx("div",{className:"subtle",children:"Applies when you create single‑player rooms."})]})]}),Qe&&C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Single‑player bots (Craps):"}),C.jsxs("div",{className:"editable-field",children:[C.jsxs("select",{value:Ie==null?"":String(Ie),onChange:ge=>{const ye=ge.target.value;DA(ye===""?null:Math.max(0,Math.min(8,Math.trunc(Number(ye)))))},disabled:T,"aria-label":"Preferred number of bots in single-player Craps rooms",children:[C.jsx("option",{value:"",children:"Default (2 bots)"}),Array.from({length:5}).map((ge,ye)=>C.jsx("option",{value:ye,children:ye},ye))]}),C.jsx("div",{className:"subtle",children:"Applies when you create single‑player rooms."})]})]})]}),HA&&C.jsx("div",{className:"profile-row profile-row--two",children:C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Single‑player bots (Poker):"}),C.jsxs("div",{className:"editable-field",children:[C.jsxs("select",{value:rA==null?"":String(rA),onChange:ge=>{const ye=ge.target.value;BA(ye===""?null:Math.max(0,Math.min(8,Math.trunc(Number(ye)))))},disabled:T,"aria-label":"Preferred number of bots in single-player Poker rooms",children:[C.jsx("option",{value:"",children:"Default (3 bots)"}),Array.from({length:5}).map((ge,ye)=>C.jsx("option",{value:ye,children:ye},ye))]}),C.jsx("div",{className:"subtle",children:"Applies when you create single‑player rooms."})]})]})})]})})(),C.jsx("div",{className:"profile-row",children:C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Bot Difficulty:"}),C.jsxs("div",{className:"editable-field",children:[(()=>{var ge;const re=(()=>{const ye=A;return ye?vp?ye.spLevelCraps??1:Wq?ye.spLevelCeelo??1:Kp?ye.spLevelPoker??1:Math.max(ye.spLevelCeelo??1,ye.spLevelCraps??1,ye.spLevelPoker??1,ye.spLevelSkills??1):1})(),Qe=Math.max(1,Math.min(9,re)),HA=((ge=nQ.find(ye=>ye.level===Qe))==null?void 0:ge.name)??`Level ${Qe}`;return C.jsxs("select",{value:nA??"",onChange:ye=>{const Te=ye.target.value;bA(Te===""?void 0:Number(Te))},"aria-label":"Bot difficulty level for single-player games",children:[C.jsxs("option",{value:"",children:["Default — ",Qe,". ",HA]}),nQ.map(ye=>{const Te=ye.level>Qe;return C.jsxs("option",{value:ye.level,disabled:Te,children:[Te?"🔒 ":"",ye.level,". ",ye.name,Te?" (locked)":""]},ye.level)})]})})(),C.jsx("div",{className:"subtle",children:"Controls bot difficulty in all single-player games."})]})]})}),C.jsx("div",{className:"profile-row",children:C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Zentara Opponents:"}),C.jsxs("div",{className:"editable-field",children:[C.jsx("select",{value:KA,onChange:re=>pe(Number(re.target.value)),"aria-label":"Number of bot opponents in Zentara singleplayer",children:[1,2,3,4,5].map(re=>C.jsxs("option",{value:re,children:[re," bot",re>1?"s":""]},re))}),C.jsx("div",{className:"subtle",children:"Default bot opponents for Zentara singleplayer (1–5)."})]})]})}),C.jsx("div",{className:"profile-row",children:C.jsx("div",{className:"profile-section",children:C.jsxs("div",{className:"editable-field",children:[C.jsx("button",{className:"felt-btn","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}ke()},disabled:T,children:T?"Saving...":"Save Profile"}),Z&&C.jsx("div",{className:"error-message",children:Z})]})})}),C.jsxs("div",{className:"profile-row profile-row--two",children:[C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Animations:"}),C.jsxs("div",{className:"editable-field",style:{display:"flex",alignItems:"center",gap:8},children:[C.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:13},children:[C.jsx("input",{type:"checkbox",disabled:!se,checked:!!St,onChange:()=>kA(),"aria-label":St?"Disable animations (dice physics, chip flights, background shake)":"Enable animations (dice physics, chip flights, background shake)"}),C.jsx("span",{children:St?"Enabled":"Disabled"})]}),C.jsx("div",{className:"subtle",style:{opacity:.7},children:St?"Full motion effects active.":"Reduced motion: static dice & suppressed decorative effects."})]})]}),C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Dice Color (Cee‑Lo & Craps):"}),C.jsxs("div",{className:"editable-field",style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[C.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:13},children:[C.jsx("input",{type:"radio",name:"dice-color",value:"dice_red_white",checked:Ce==="dice_red_white",onChange:()=>xe("dice_red_white"),"aria-label":"Use red/white dice"}),C.jsx("span",{children:"Red/White"})]}),C.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:13},children:[C.jsx("input",{type:"radio",name:"dice-color",value:"dice_green_gold",checked:Ce==="dice_green_gold",onChange:()=>xe("dice_green_gold"),"aria-label":"Use green/gold dice"}),C.jsx("span",{children:"Green/Gold"})]}),C.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:13},children:[C.jsx("input",{type:"radio",name:"dice-color",value:"dice_white_black",checked:Ce==="dice_white_black",onChange:()=>xe("dice_white_black"),"aria-label":"Use white/black dice (default)"}),C.jsx("span",{children:"White/Black"})]}),C.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:13},children:[C.jsx("input",{type:"radio",name:"dice-color",value:"dice_blue_silver",checked:Ce==="dice_blue_silver",onChange:()=>xe("dice_blue_silver"),"aria-label":"Use blue/silver dice"}),C.jsx("span",{children:"Blue/Silver"})]})]})]})]}),!Lc&&C.jsx("div",{className:"profile-row profile-row--two",children:C.jsxs("div",{className:"profile-section",children:[C.jsxs("strong",{children:["Balance: ",CB.formatMoney(A==null?void 0:A.balance,"",2)]}),C.jsx("div",{className:"editable-field",children:C.jsx("button",{className:"felt-btn felt-btn--halo","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}try{CA()}catch{}},disabled:T||X||!cA||!1,"aria-label":wA?"Buy 1000 Z Credits":"Buy 1000 Z Credits (App Store / Play)",title:wA?"Buy 1000 Z Credits":"Buy 1000 Z Credits (App Store / Play)",children:O?"Purchasing...":"Buy Credits"})}),C.jsx("strong",{children:"Restore:"}),C.jsx("div",{className:"editable-field",children:C.jsx("button",{className:"felt-btn","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}try{uA()}catch{}},disabled:X||!cA||!1,title:"Restore Purchases","aria-label":"Restore Purchases",children:"Restore"})})]})}),C.jsx("div",{className:"profile-row profile-row--two",children:C.jsxs("div",{className:"profile-section",children:[C.jsxs("strong",{children:["Membership:                                         ",(A==null?void 0:A.membershipTier)===GK.PREMIUM?"Premium Active":"Free",C.jsx("span",{className:"badge","aria-live":"polite",children:(A==null?void 0:A.membershipTier)===GK.PREMIUM?"P":""})]}),C.jsxs("div",{className:"editable-field",children:[(A==null?void 0:A.membershipTier)===GK.PREMIUM?C.jsx(a5,{isPremium:!0,className:"felt-btn"}):YA&&C.jsx("button",{className:"felt-btn","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}try{_A()}catch{}},disabled:X,"aria-label":jA,title:jA,children:"Go Premium"}),!xA&&YA&&C.jsx("div",{className:"meta",style:{marginTop:6},children:(()=>{const re="$1.99",Qe="Monthly",HA=le||re,ge=NA||Qe,ye=ie||`${HA} Mo`,Te=he||"Remove ads and unlock premium features.";return C.jsxs(C.Fragment,{children:[ye&&C.jsx("div",{className:"subtle","aria-hidden":!0,children:ye}),C.jsx("div",{className:"legal-note","aria-hidden":!0,children:Te}),C.jsxs("div",{className:"legal-note",role:"note",children:[C.jsx("strong",{children:"Premium Subscription"})," — ",HA," (",ge,"). Auto‑renews until canceled. Manage or cancel in account settings on your device. See our ",C.jsx(HI,{to:"/privacy",className:"legal-link",children:"Privacy Policy"})," and ",C.jsx(HI,{to:"/terms",className:"legal-link",children:"Terms of Use"}),"."]})]})})()})]})]})}),C.jsx(One,{}),Ui.isNativePlatform()&&C.jsx("div",{className:"profile-row",children:C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Software Update:"}),C.jsxs("div",{className:"editable-field",style:{display:"flex",flexDirection:"column",gap:8},children:[C.jsx("button",{className:"felt-btn","data-no-global-haptic":!0,disabled:L==="checking"||L==="downloading"||L==="applying",onClick:async()=>{try{ti("Light")}catch{}H("checking"),oA(null),tA(0);try{const re=await yr.checkForUpdate({force:!0});if(re.available&&re.release){H("downloading");const{blob:Qe}=await yr.downloadUpdate(re.release,HA=>{tA(HA.percent??0)});H("applying"),await yr.applyUpdate(re.release,Qe),setTimeout(()=>{try{window.location.reload()}catch{}},500)}else H("up-to-date")}catch(re){H("error"),oA((re==null?void 0:re.message)||"Update failed")}},"aria-label":"Check for Updates",title:"Check for Updates",children:L==="checking"?"Checking…":L==="downloading"?`Downloading… ${P}%`:L==="applying"?"Installing…":L==="up-to-date"?"Up to Date ✓":"Check for Updates"}),L==="error"&&iA&&C.jsx("div",{className:"error-message",children:iA})]})]})}),C.jsx("div",{className:"profile-row",children:C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Session:"}),C.jsx("div",{className:"editable-field",style:{display:"flex",flexDirection:"column",gap:8},children:C.jsx("button",{className:"felt-btn","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}i(),e("/lobby")},"aria-label":"Log Out",title:"Log Out",children:"Log Out"})})]})}),C.jsx("div",{className:"profile-row",children:C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Account:"}),C.jsxs("div",{className:"editable-field",style:{display:"flex",flexDirection:"column",gap:8},children:[C.jsx("div",{className:"legal-note",children:"Deleting your account is permanent and cannot be undone."}),C.jsx("button",{className:"felt-btn felt-btn--danger","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}ve()},disabled:yA,"aria-label":"Delete Account",title:"Delete Account",children:yA?"Deleting…":"Delete Account"}),RA&&C.jsx("div",{className:"error-message",children:RA})]})]})})]})]})})}),C.jsx(ZBA,{open:g,onClose:it,planId:A==null?void 0:A.membershipTier,featureDescription:"Upload custom avatars and create multiplayer rooms with Premium membership."}),C.jsx(Jp,{})]})}const JtA=[{key:"ceelo",name:"Cee-Lo Lounge",tagline:"Street dice with style",icon:Lne,android:"https://play.google.com/store/apps/details?id=com.zentaraone.ceelolounge",ios:"https://apps.apple.com/us/app/zentara-one-cee-lo-lounge/id6751764952"},{key:"craps",name:"Craps Lounge",tagline:"Roll the bones",icon:xne,android:"https://play.google.com/store/apps/details?id=com.zentaraone.crapslounge",ios:"https://apps.apple.com/us/app/zentara-one-craps-lounge/id6756252344"},{key:"poker",name:"Poker Lounge",tagline:"Texas Hold 'em",icon:Tne,android:"https://play.google.com/store/apps/details?id=com.zentaraone.pokerlounge",ios:"https://apps.apple.com/us/app/zentara-one-poker-lounge/id6757020405"},{key:"skills",name:"Skills Lounge",tagline:"Word games & trivia",icon:qne,android:"https://play.google.com/store/apps/details?id=com.zentaraone.skillslounge",ios:"https://apps.apple.com/us/app/zentara-one-skills-lounge/id6758308777"},{key:"zentara",name:"Zentara",tagline:"Conquer the cosmos",icon:Yne,android:"https://play.google.com/store/apps/details?id=com.zentaraone.zentara",ios:"https://apps.apple.com/br/app/zentara-galaxy-conquest/id6761544336"}];function One(){const e=(()=>{try{return Ui.isNativePlatform()}catch{return!1}})(),A=(()=>{try{return Ui.getPlatform()}catch{return"web"}})(),t=JtA.filter(g=>g.key!==qs),i=Th?JtA:t;if(i.length===0)return null;const n=g=>A==="ios"?g.ios:g.android;return C.jsx("div",{className:"profile-row",children:C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Our Other Apps"}),C.jsx("div",{className:"other-apps-grid",children:i.map(g=>{const o=n(g);return C.jsxs("a",{className:"other-app-card",href:o||"#",target:"_blank",rel:"noopener noreferrer","aria-label":`Get ${g.name}`,...o?{}:{"aria-disabled":"true",onClick:s=>s.preventDefault()},children:[C.jsx("img",{className:"other-app-icon",src:g.icon,alt:`${g.name} icon`,width:56,height:56,loading:"lazy"}),C.jsxs("div",{className:"other-app-info",children:[C.jsx("div",{className:"other-app-name",children:g.name}),C.jsx("div",{className:"other-app-tagline",children:g.tagline})]}),C.jsx("span",{className:"other-app-cta",children:o?e?"Get":"View":"Soon"})]},g.key)})})]})})}function Of(){const{playerId:e}=Qw(),A=qi(),t=Ms(),{user:i}=tn(),{friends:n,friendRequests:g,blockedUsers:o,addFriend:s}=Kd(),[a,r]=E.useState(null),[I,c]=E.useState(!0),[l,B]=E.useState(null),[Q,h]=E.useState(!1),[d,p]=E.useState(!1),y=(i==null?void 0:i.id)===e,m=n.some(_=>_.id===e),D=g.some(_=>(_.fromUserId===e||_.toUserId===e)&&_.status==="PENDING"),S=o.some(_=>_.id===e),k=E.useCallback(()=>{window.history.length>1?A(-1):A("/")},[A]);E.useEffect(()=>{if(!t||!e)return;let _=!1;return c(!0),B(null),t.emit("social:get_profile",{playerId:e},K=>{_||(c(!1),K.ok&&K.player?r(K.player):B(K.error||"Player not found"))}),()=>{_=!0}},[t,e]);const N=E.useCallback(async()=>{if(!(!e||m||D||S||Q||d||a!=null&&a.isBot)){p(!0);try{await s(e),h(!0)}catch{h(!1)}finally{p(!1)}}},[e,m,D,S,Q,d,s,a==null?void 0:a.isBot]),G=E.useCallback(()=>{e&&A(`/messages?peer=${encodeURIComponent(e)}`)},[e,A]);if(I)return C.jsxs("div",{className:`${Dm?"theme-zentara":"theme-casino"} home-fixed-root`,children:[C.jsx(tr,{className:"profile-page-body"}),C.jsx("div",{className:"logout-container home-header-row",children:C.jsxs("a",{className:"gold-link white-link gold-link--mini","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}k()},children:[C.jsx(tc,{className:"icon"})," Back"]})}),C.jsx("div",{className:"profile-page",children:C.jsx("div",{className:"home-fit-shell",children:C.jsx("div",{className:"home-fit-content",children:C.jsx("div",{className:"player-profile-loading",children:"Loading profile…"})})})}),C.jsx(Jp,{})]});if(l||!a)return C.jsxs("div",{className:`${Dm?"theme-zentara":"theme-casino"} home-fixed-root`,children:[C.jsx(tr,{className:"profile-page-body"}),C.jsx("div",{className:"logout-container home-header-row",children:C.jsxs("a",{className:"gold-link white-link gold-link--mini","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}k()},children:[C.jsx(tc,{className:"icon"})," Back"]})}),C.jsx("div",{className:"profile-page",children:C.jsx("div",{className:"home-fit-shell",children:C.jsx("div",{className:"home-fit-content",children:C.jsx("div",{className:"player-profile-error",children:l||"Player not found"})})})}),C.jsx(Jp,{})]});const M=a.isBot===!0,w=y||M?null:m?"Friends":D||Q?"Pending":S?"Blocked":d?"Sending…":"Add Friend",b=y||M||m||D||S||Q||d;return C.jsxs("div",{className:`${Dm?"theme-zentara":"theme-casino"} home-fixed-root add-chips`,children:[C.jsx(tr,{className:"profile-page-body"}),C.jsx("div",{className:"logout-container home-header-row",children:C.jsxs("a",{className:"gold-link white-link gold-link--mini","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}k()},children:[C.jsx(tc,{className:"icon"})," Back"]})}),C.jsx("div",{className:"profile-page",children:C.jsx("div",{className:"home-fit-shell",children:C.jsx("div",{className:"home-fit-content",children:C.jsxs("div",{className:"profile-content",children:[C.jsxs("div",{className:"pp-header-card",children:[C.jsx("div",{className:"pp-avatar",children:a.avatarUrl?C.jsx("img",{src:a.avatarUrl,alt:a.name||"Player",className:"pp-avatar-img"}):C.jsx("div",{className:"pp-avatar-placeholder",children:(a.name||"?")[0].toUpperCase()})}),C.jsxs("div",{className:"pp-header-info",children:[C.jsxs("h2",{className:"pp-name",children:[a.name||"Anonymous",M&&C.jsx("span",{className:"pp-bot-badge",children:"Bot"})]}),C.jsxs("div",{className:"pp-meta-row",children:[a.age&&C.jsxs("span",{className:"pp-meta-tag",children:[a.age," yrs"]}),a.sex&&C.jsx("span",{className:"pp-meta-tag",children:a.sex}),a.location&&C.jsx("span",{className:"pp-meta-tag",children:a.location})]})]})]}),!y&&!M&&C.jsxs("div",{className:"pp-actions",children:[w&&C.jsx("button",{className:"felt-btn pp-action-btn",onClick:()=>{try{ti("Light")}catch{}N()},disabled:b,children:w}),m&&C.jsx("button",{className:"felt-btn pp-action-btn",onClick:()=>{try{ti("Light")}catch{}G()},children:"Message"})]}),a.aboutMe&&C.jsxs("div",{className:"pp-section",children:[C.jsx("h3",{className:"pp-section-title",children:"About"}),C.jsx("p",{className:"pp-section-body",children:a.aboutMe})]}),a.interests&&C.jsxs("div",{className:"pp-section",children:[C.jsx("h3",{className:"pp-section-title",children:"Interests"}),C.jsx("div",{className:"pp-interests",children:a.interests.split(/[,;]+/).map(_=>_.trim()).filter(Boolean).map((_,K)=>C.jsx("span",{className:"pp-interest-tag",children:_},K))})]})]})})})}),C.jsx(Jp,{})]})}function Pne(e){var g,o;if(!e)return"?";const t=e.split("@")[0].trim().split(/[\s._-]+/).filter(Boolean),i=(((g=t[0])==null?void 0:g[0])??"").toUpperCase(),n=(((o=t[1])==null?void 0:o[0])??"").toUpperCase();return i+n||i||"?"}function Pf(){const e=qi(),[A]=uw(),{user:t}=tn(),i=(t==null?void 0:t.id)??(t==null?void 0:t.email)??"",{friends:n}=Kd(),{getDmSummary:g,sendDmMessage:o,markDmRead:s,setActiveDm:a,threads:r,loadDmHistory:I}=OR(),[c,l]=E.useState(null),[B,Q]=E.useState(""),h=E.useRef(null),d=E.useRef(null),p=E.useRef(!1);E.useEffect(()=>{if(p.current)return;p.current=!0;const b=A.get("peer");if(b){l(b),a(b),I(b),e("/messages",{replace:!0});return}const _=g(),K=_==null?void 0:_.find(q=>q.unread>0);let J=null;K?J=K.peerUserId:n.length&&(J=n[0].id),J&&(l(J),a(J),I(J))},[n,g,a,I,A,e]),E.useEffect(()=>{c&&d.current!==c&&(d.current=c,s(c))},[c,s]);const y=E.useMemo(()=>c?(r==null?void 0:r[wC(c,i)])??[]:[],[c,r,i]),m=E.useMemo(()=>g()??[],[g,y.length]),D=E.useMemo(()=>{const b=new Map;return m.forEach(_=>b.set(_.peerUserId,_)),b},[m]);E.useEffect(()=>{h.current&&(h.current.scrollTop=h.current.scrollHeight)},[y.length,c]);const S=E.useCallback(b=>{l(b),a(b),s(b),I(b)},[a,s,I]),k=E.useCallback(()=>{if(!c)return;const b=B.trim();if(!b)return;o(c,b)&&Q("")},[c,B,o]),N=b=>{b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),k())},G=E.useCallback(b=>{const _=n.find(K=>K.id===b);return(_==null?void 0:_.name)||b},[n]),M=E.useCallback(b=>{const _=D.get(b);return _!=null&&_.last?((_.last.senderId===i?"You: ":"")+_.last.text).trim():""},[D,i]),w=E.useCallback(()=>{try{ti("Light")}catch{}e(-1)},[e]);return C.jsxs("div",{className:`${Dm?"theme-zentara":"theme-casino"} home-fixed-root messages-page`,children:[C.jsx(tr,{className:"messages-page-body"}),C.jsx("div",{className:"logout-container  home-header-row",children:C.jsxs("a",{className:"gold-link white-link gold-link--mini","data-no-global-haptic":!0,onClick:w,children:[C.jsx(tc,{className:"icon"})," Back"]})}),C.jsxs("div",{className:"messages-container",children:[C.jsxs("div",{className:"messages-thread-list",children:[n.length===0&&C.jsx("div",{className:"messages-no-friends",children:"Add friends from your Profile to start messaging."}),n.map(b=>{var v;const _=b.id===c,K=Pne(b.name||b.id),J=((v=D.get(b.id))==null?void 0:v.unread)??0,q=M(b.id);return C.jsxs("button",{onClick:()=>S(b.id),className:`messages-thread-btn ${_?"messages-thread-btn--active":""}`,title:G(b.id),children:[C.jsx("div",{className:"messages-avatar","aria-hidden":!0,children:K}),C.jsxs("div",{className:"messages-thread-label",children:[C.jsx("div",{className:"messages-thread-name",children:G(b.id)}),C.jsx("div",{className:"messages-thread-preview",children:q})]}),J>0&&C.jsx("span",{"aria-label":`${J} unread`,className:"messages-unread-badge",children:J>99?"99+":J})]},b.id)})]}),C.jsxs("div",{className:"messages-active-thread",children:[C.jsxs("div",{ref:h,className:"messages-scroller",children:[!c&&C.jsx("div",{className:"messages-empty",children:"Select a conversation to begin."}),c&&y.length===0&&C.jsx("div",{className:"messages-empty",children:"No messages yet. Say hello!"}),c&&y.length>0&&y.map(b=>{const _=b.senderId===i,K=new Date(b.ts),J=K.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return C.jsxs("div",{className:`messages-message ${_?"messages-message--mine":""}`,title:K.toLocaleString(),children:[C.jsx("div",{className:"messages-message-content",children:b.text}),C.jsx("div",{className:"messages-message-time",children:J}),b.pending&&C.jsx("div",{className:"messages-pending",children:"sending…"}),b.error&&C.jsx("div",{className:"messages-error",children:b.error})]},b.id)})]}),C.jsxs("div",{className:"messages-composer",children:[C.jsx("input",{value:B,onChange:b=>Q(b.target.value),onKeyDown:N,placeholder:c?`Message ${G(c)}…`:"Pick a conversation…",disabled:!c,className:"messages-composer-input"}),C.jsx("button",{onClick:k,disabled:!c||B.trim()==="",className:`messages-composer-send ${!c||B.trim()===""?"messages-composer-send--disabled":""}`,children:"Send"})]})]})]}),C.jsx(Jp,{})]})}const jne=Array.from({length:30},(e,A)=>({width:A%3===0?3:2,height:A%3===0?3:2,opacity:.1+A%5*.06,left:`${(A*137+50)%100}%`,top:`${(A*251+30)%100}%`}));function jf(){const e=qi(),{logout:A}=tn(),[t,i]=E.useState(ds),[n,g]=E.useState(!1),o=E.useRef(null);E.useEffect(()=>{let r=!0;return(async()=>{const I=await Xo();r&&(i(I),g(!0))})(),()=>{r=!1,o.current&&window.clearTimeout(o.current)}},[]),E.useEffect(()=>{n&&(o.current&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>{JE(t).catch(()=>{})},200))},[t,n]);const s=r=>i(I=>({...I,[r]:!I[r]})),a=()=>{try{ti("Light")}catch{}A(),e("/lobby")};return Dm?C.jsxs("div",{className:"zentara-settings",children:[C.jsx("div",{className:"zentara-settings__stars",children:jne.map((r,I)=>C.jsx("div",{className:"zentara-settings__star",style:{width:r.width,height:r.height,opacity:r.opacity,left:r.left,top:r.top}},I))}),C.jsxs("div",{className:"zentara-settings__content",children:[C.jsxs("button",{className:"zentara-settings__back",onClick:()=>history.back(),children:[C.jsx("img",{src:"/icons/arrow-left.svg",alt:"","aria-hidden":!0,className:"icon"}),"Back"]}),C.jsx("h1",{className:"zentara-settings__title",children:"Settings"}),[["diceAudio","Dice Audio"],["backgroundMusic","Background Music"],["chatAudio","Chat Audio"],["video","Video"]].map(([r,I])=>C.jsxs("div",{className:"zentara-settings__card",children:[C.jsx("span",{className:"zentara-settings__label",children:I}),C.jsxs("label",{className:"zentara-settings__toggle",children:[C.jsx("input",{type:"checkbox",checked:!!t[r],onChange:()=>s(r),disabled:!n}),C.jsx("span",{className:"zentara-settings__toggle-track"})]})]},r)),C.jsx("div",{className:"zentara-settings__divider"}),C.jsxs("div",{className:"zentara-settings__card",children:[C.jsxs("div",{children:[C.jsx("span",{className:"zentara-settings__label",children:"Opponents"}),C.jsx("div",{className:"zentara-settings__hint",children:"Bots in singleplayer (1–5)"})]}),C.jsx("select",{className:"zentara-settings__select",value:t.zentaraBotCount??1,onChange:r=>i(I=>({...I,zentaraBotCount:Number(r.target.value)})),disabled:!n,"aria-label":"Number of bot opponents in Zentara singleplayer",children:[1,2,3,4,5].map(r=>C.jsxs("option",{value:r,children:[r," bot",r>1?"s":""]},r))})]}),C.jsx("div",{className:"zentara-settings__divider"}),[["zentaraDisableRaid","Disable Resource Raid"],["zentaraDisableSpyStrike","Disable Spy Strike"]].map(([r,I])=>C.jsxs("div",{className:"zentara-settings__card",children:[C.jsx("span",{className:"zentara-settings__label",children:I}),C.jsxs("label",{className:"zentara-settings__toggle",children:[C.jsx("input",{type:"checkbox",checked:!!t[r],onChange:()=>s(r),disabled:!n}),C.jsx("span",{className:"zentara-settings__toggle-track"})]})]},r)),C.jsx("div",{className:"zentara-settings__divider"}),C.jsx("button",{className:"zentara-settings__logout","data-no-global-haptic":!0,onClick:a,"aria-label":"Log Out",children:"Log Out"})]})]}):C.jsxs("div",{className:"settings-page",children:[C.jsxs("a",{className:"gold-link white-link",onClick:()=>history.back(),children:[C.jsx("img",{src:"/icons/arrow-left.svg",alt:"","aria-hidden":!0,className:"icon"})," Back"]}),C.jsx("div",{className:"settings-section",children:C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",checked:t.diceAudio,onChange:()=>s("diceAudio"),disabled:!n}),"Dice Audio"]})}),C.jsx("div",{className:"settings-section",children:C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",checked:t.backgroundMusic,onChange:()=>s("backgroundMusic"),disabled:!n}),"Background Music"]})}),C.jsx("div",{className:"settings-section",children:C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",checked:t.chatAudio,onChange:()=>s("chatAudio"),disabled:!n}),"In-Room Chat Audio"]})}),C.jsx("div",{className:"settings-section",children:C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",checked:t.video,onChange:()=>s("video"),disabled:!n}),"Video"]})}),C.jsxs("div",{className:"settings-section",children:[C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",checked:t.showCelebrationImages!==!1,onChange:()=>s("showCelebrationImages"),disabled:!n}),"Celebration Images"]}),C.jsx("span",{className:"settings-section__hint",children:"Show full-screen win/loss artwork in Cee Lo and Craps."})]}),C.jsxs("div",{className:"settings-section",children:[C.jsx("label",{children:"Zentara Opponents"}),C.jsx("select",{value:t.zentaraBotCount??1,onChange:r=>i(I=>({...I,zentaraBotCount:Number(r.target.value)})),disabled:!n,"aria-label":"Number of bot opponents in Zentara singleplayer",style:{marginLeft:8,padding:"4px 8px",borderRadius:6},children:[1,2,3,4,5].map(r=>C.jsxs("option",{value:r,children:[r," bot",r>1?"s":""]},r))})]}),C.jsx("div",{className:"settings-section",children:C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",checked:!!t.zentaraDisableRaid,onChange:()=>s("zentaraDisableRaid"),disabled:!n}),"Zentara: Disable Resource Raid"]})}),C.jsx("div",{className:"settings-section",children:C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",checked:!!t.zentaraDisableSpyStrike,onChange:()=>s("zentaraDisableSpyStrike"),disabled:!n}),"Zentara: Disable Spy Strike"]})}),C.jsx("div",{className:"settings-section",style:{marginTop:24},children:C.jsx("button",{className:"felt-btn","data-no-global-haptic":!0,onClick:a,"aria-label":"Log Out",title:"Log Out",children:"Log Out"})})]})}const NpA=Ca();async function zne(){try{const e=await uo(),A=await fetch(`${NpA}/api/ad-reward`,{method:"POST",headers:{"Content-Type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},credentials:"include"});if(!A.ok){const i=await A.json();return{ok:!1,error:i.error,retryInMs:i.retryInMs}}return{ok:!0,balance:(await A.json()).balance}}catch(e){return console.error("Error claiming ad reward:",e),{ok:!1,error:"NETWORK_ERROR"}}}async function Zne(){try{const e=await uo(),A=await fetch(`${NpA}/api/ad-reward/status`,{method:"GET",headers:{"Content-Type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},credentials:"include"});return A.ok?{ok:!0,nextAt:(await A.json()).nextAt}:{ok:!1,error:(await A.json()).error,nextAt:null}}catch(e){return console.error("Error fetching ad reward cooldown:",e),{ok:!1,error:"NETWORK_ERROR",nextAt:null}}}const LtA={claimAdReward:zne,getAdRewardCooldown:Zne};function zf(){const{busy:e,busyChips:A,ready:t,error:i,premiumActive:n,hasPremiumPackage:g,premiumLabel:o,isWeb:s,onBuyChips:a,onGoPremium:r,onRestore:I,chipsSubtitle:c,premiumSubtitle:l,chipsDescription:B,premiumDescription:Q,premiumPrice:h,premiumInterval:d}=Sw(),{refreshUser:p}=tn(),{infoNow:y}=Jr(),[m,D]=E.useState(!1),[S,k]=E.useState(0),[N,G]=E.useState(()=>Date.now()),M=Math.max(0,S-N),w=M>0,b=bY.isNativeAdSupported(),_=!n&&b&&!MR,K=E.useCallback(qA=>{const W=Math.ceil(qA/1e3),$=Math.floor(W/60),L=W%60;return`${$}m ${L}s`},[]);E.useEffect(()=>{_&&(async()=>{try{const qA=await LtA.getAdRewardCooldown();qA!=null&&qA.ok&&qA.nextAt&&qA.nextAt>Date.now()&&k(qA.nextAt)}catch(qA){console.error("[AddChips] Failed to fetch ad cooldown:",qA)}})()},[_]),E.useEffect(()=>{!_||w||bY.prepareRewardedAd().catch(()=>{})},[_,w]),E.useEffect(()=>{if(!w)return;const qA=setInterval(()=>G(Date.now()),1e3);return()=>clearInterval(qA)},[w]);const J=E.useCallback(async()=>{if(!(m||w||!_)){ti("Light"),D(!0);try{const qA=await bY.showRewardedAd();if(!qA.ok){qA.error==="AD_DISMISSED"?y==null||y("Ad skipped - watch the full ad to earn credits!"):y==null||y(`Ad unavailable: ${qA.error}`),D(!1);return}const W=await LtA.claimAdReward();if(W.ok){const $=w6*60*1e3;k(Date.now()+$),y==null||y(Lc?`+${jQ} Z Credits added to your fleet!`:`+${jQ} Z Credits earned!`);try{p()}catch{}}else if(W.error==="COOLDOWN_ACTIVE"){const $=W.retryInMs??w6*60*1e3;k(Date.now()+$),y==null||y("Please wait before watching another ad.")}else y==null||y(`Reward failed: ${W.error}`)}catch(qA){console.error("[AddChips] Watch ad error:",qA),y==null||y("Something went wrong. Please try again.")}finally{D(!1)}}},[m,w,_,y,p]),q="$1.99",v="Monthly",U=h||q,x=d||v,T=l||`${U} Mo`,z=Q||"Remove ads and unlock premium features.",Z="$1.99 for 1,000 Zentara Credits",eA="Buy Zentara Credits to keep playing.",aA=c||Z,sA=B||eA,pA=()=>{try{ti("Light")}catch{}try{a()}catch{}},gA=()=>{try{ti("Light")}catch{}try{r()}catch{}},yA=()=>{try{ti("Light")}catch{}try{I()}catch{}},fA=!n&&(g||!s),RA=g||!s;return C.jsxs("div",{className:`${Dm?"theme-zentara":"theme-casino"} home-fixed-root add-chips`,children:[C.jsx(tr,{className:"profile-page-body"}),C.jsx("div",{className:"logout-container  home-header-row",children:C.jsxs("a",{className:"gold-link white-link gold-link--mini","data-no-global-haptic":!0,onClick:()=>{try{ti("Light")}catch{}history.back()},children:[C.jsx(tc,{className:"icon"})," Back"]})}),C.jsx("div",{className:"home-fit-shell",children:C.jsxs("div",{className:"home-fit-content",children:[i&&C.jsx("div",{className:"error-message",role:"alert",children:i}),!i&&t&&!1,C.jsxs("div",{className:"home-action-buttons",children:[_&&C.jsxs("div",{className:"outline-action-btn-wrapper",children:[C.jsx("button",{className:"felt-btn felt-btn--secondary","data-no-global-haptic":!0,onClick:J,disabled:m||w,"aria-label":`Watch ad for ${jQ} free credits`,title:`Watch ad for ${jQ} free credits`,style:Lc?{background:"linear-gradient(135deg, #0d1b2a 0%, #0a1628 100%)",borderColor:"#00e5ff",color:"#00e5ff",fontFamily:"Orbitron, monospace"}:{background:"linear-gradient(135deg, #2d5a2d 0%, #1a3d1a 100%)",borderColor:"#4a8f4a"},children:m?"Loading Ad…":w?`Available in ${K(M)}`:Lc?`📡 WATCH AD → +${jQ} Z CREDITS`:`🎬 WATCH AD → +${jQ}`}),C.jsxs("div",{className:"meta",style:{marginTop:6,textAlign:"center"},children:[C.jsxs("div",{className:"subtle","aria-hidden":!0,children:["Free ",jQ," Z Credits"]}),C.jsx("div",{className:"hint","aria-hidden":!0,children:Lc?"Watch a short video to earn free Z Credits!":"Watch a short video to earn free credits!"})]})]}),!Lc&&C.jsxs("div",{className:"outline-action-btn-wrapper",children:[C.jsx("button",{className:"felt-btn felt-btn--halo","data-no-global-haptic":!0,onClick:pA,disabled:e||!t||!1,"aria-label":"Buy 1000 Z Credits",title:"Buy 1000 Z Credits",children:A?"Purchasing…":"BUY Z CREDITS"}),C.jsxs("div",{className:"meta",style:{marginTop:6,textAlign:"center"},children:[C.jsx("div",{className:"subtle","aria-hidden":!0,children:aA}),C.jsx("div",{className:"hint","aria-hidden":!0,children:sA})]})]}),C.jsxs("div",{className:"outline-action-btn-wrapper",children:[fA&&C.jsxs(C.Fragment,{children:[C.jsx("button",{className:"felt-btn","data-no-global-haptic":!0,onClick:gA,disabled:e,"aria-label":o,title:o,children:"GO PREMIUM"}),C.jsxs("div",{className:"meta",style:{marginTop:6,textAlign:"center"},children:[T&&C.jsx("div",{className:"subtle","aria-hidden":!0,children:T}),C.jsx("div",{className:"hint","aria-hidden":!0,children:z}),C.jsxs("div",{className:"legal-note",role:"note",style:{marginTop:8,fontSize:12,opacity:.85},children:[C.jsx("strong",{children:"Premium Subscription"})," — ",U," (",x,"). Auto‑renews until canceled. Manage or cancel in account settings on your device. See our ",C.jsx(HI,{to:"/privacy",className:"legal-link",children:"Privacy Policy"})," and ",C.jsx(HI,{to:"/terms",className:"legal-link",children:"Terms of Use"}),"."]})]})]}),n&&C.jsx("div",{style:{textAlign:"center"},children:C.jsx(a5,{isPremium:!0})})]}),RA&&C.jsx("div",{className:"outline-action-btn-wrapper",children:C.jsxs("button",{className:"felt-btn","data-no-global-haptic":!0,onClick:yA,disabled:e||!t||!1,"aria-label":"Restore Purchases",title:"Restore Purchases",children:["RESTORE",C.jsx("br",{}),"PURCHASES"]})})]})]})}),C.jsx(Jp,{})]})}function vZ({open:e,onClose:A,title:t="Error",message:i}){return LcA(!!e),E.useEffect(()=>{const n=g=>{g.key==="Escape"&&A()};return e&&document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[e,A]),e?C.jsx("div",{className:"modal-backdrop",role:"presentation",onClick:A,children:C.jsxs("div",{className:"modal-panel",role:"dialog","aria-modal":"true","aria-label":t,onClick:n=>n.stopPropagation(),children:[C.jsx("button",{className:"modal-close",onClick:A,"aria-label":"Close",children:"×"}),C.jsx("h3",{className:"modal-title",children:t}),C.jsx("p",{className:"modal-subtitle",role:"alert",children:i}),C.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:12},children:C.jsx("button",{className:"btn close-btn",onClick:A,"aria-label":"Close",children:"Close"})})]})}):null}function Zf(){const[e,A]=E.useState("verifying"),t=qi(),{refreshUser:i}=tn();E.useEffect(()=>{(async()=>{const s=new URLSearchParams(window.location.search).get("token");if(!s)return A("error");try{const a=await nbA(s);if(a!=null&&a.success){a.token&&await ef(a.token);try{await i({force:!0})}catch{}try{setTimeout(()=>{i({force:!0}).catch(()=>{})},400)}catch{}if(await dL()){A("success");return}A("success")}else A("error")}catch{A("error")}})()},[t,i]),E.useEffect(()=>{if(e!=="success")return;const g=window.setTimeout(()=>{try{t("/?redirect=/lobby",{replace:!0})}catch{window.location.href=`${window.location.origin}/?redirect=/lobby`}},1200);return()=>{window.clearTimeout(g)}},[e,t]);const n=g=>g==="verifying"?C.jsxs(C.Fragment,{children:[C.jsx("p",{children:"Verifying your magic link..."}),C.jsx("button",{className:"landing-btn-secondary",onClick:()=>t("/lobby"),style:{marginTop:16},"aria-label":"Back to Home",children:"Back to Home"})]}):g==="success"?C.jsx("p",{children:"Verification successful! Redirecting to the lobby..."}):C.jsxs(C.Fragment,{children:[C.jsx(vZ,{open:!0,onClose:()=>t("/lobby"),title:"Verification failed",message:"Verification failed. Please try again."}),C.jsx("button",{className:"landing-btn-secondary",onClick:()=>t("/lobby"),style:{marginTop:16},"aria-label":"Back to Home",children:"Back to Home"})]});return C.jsxs("div",{className:"HomeScreen theme-casino home-fixed-root",children:[C.jsx(tr,{className:"page-home-screen"}),C.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",padding:"0 16px"},children:C.jsx("div",{children:n(e)})})]})}function Wf(){const[e,A]=E.useState("verifying"),[t,i]=E.useState(!1),n=qi(),g=Ca();return E.useEffect(()=>{(async()=>{const a=new URLSearchParams(window.location.search).get("token");if(!a){A("error");return}try{const r=await fetch(`${g}/api/auth/review-login?token=${encodeURIComponent(a)}`,{method:"GET",credentials:"include",redirect:"follow"});if(!r.ok){A("error");return}let I=null;try{const c=await r.json().catch(()=>null);c!=null&&c.token&&await ef(c.token)}catch{}if(I=await dL(),I){A("success"),window.location.href=`${window.location.origin}/?redirect=/lobby`;return}else A("error")}catch{A("error")}})()},[g,n]),E.useEffect(()=>{e==="error"&&i(!0)},[e]),e==="verifying"?C.jsx("p",{children:"Signing you in for review…"}):e==="success"?C.jsx("p",{children:"Success! Redirecting to the lobby…"}):C.jsx(C.Fragment,{children:C.jsx(vZ,{open:t,onClose:()=>i(!1),title:"Review login failed",message:"Review login failed. Please check your link."})})}function Vf(){const[e,A]=E.useState("verifying"),[t,i]=E.useState(!1),n=qi(),g=Ca();return E.useEffect(()=>{(async()=>{const a=new URLSearchParams(window.location.search).get("token");if(!a){A("error");return}try{const r=await fetch(`${g}/api/auth/qa-login?token=${encodeURIComponent(a)}`,{method:"GET",credentials:"include",redirect:"follow"});if(!r.ok){A("error");return}try{const c=await r.json().catch(()=>null);c!=null&&c.token&&await ef(c.token)}catch{}if(await dL()){A("success"),window.location.href=`${window.location.origin}/?redirect=/lobby`;return}else A("error")}catch{A("error")}})()},[g,n]),E.useEffect(()=>{e==="error"&&i(!0)},[e]),e==="verifying"?C.jsx("p",{children:"Signing you in for QA…"}):e==="success"?C.jsx("p",{children:"Success! Redirecting to the lobby…"}):C.jsx(C.Fragment,{children:C.jsx(vZ,{open:t,onClose:()=>i(!1),title:"QA login failed",message:"QA login failed. Please check your link."})})}function Z3({busy:e=!1,label:A="Cancel Bet",disabled:t,...i}){const n=t||e;return C.jsxs("button",{type:"button",className:`cancel-btn ${e?"is-busy":""} ${n?"is-disabled":""}`,disabled:n,"aria-busy":e||void 0,"aria-label":A,"aria-live":"polite",...i,children:[C.jsx("span",{className:"cancel-btn__content",children:"X"}),e&&C.jsx("span",{className:"cancel-btn__spinner","aria-hidden":"true"})]})}function RpA({disabled:e,onClick:A,busy:t=!1,label:i="✓",mini:n=!1}){return C.jsx("button",{disabled:e||t,onClick:A,className:`place-bet-btn ${n?"place-bet-btn--mini":""} ${t?"busy":""}`,"aria-label":"Place Bet",children:t?"Placing...":i})}function Wne({show:e,open:A,isBanker:t,meId:i,players:n,labelPrefix:g="Main Bet: "}){const o=E.useMemo(()=>A.filter(l=>l.type==="MAIN"),[A]),[s,a]=E.useState(!1),r=E.useMemo(()=>o==null?void 0:o.filter(l=>t?!0:l.playerId===i||l.acceptedById===i),[o,t,i]),I=E.useMemo(()=>r.reduce((l,B)=>l+(B.amount||0),0),[r]),c=l=>{var B;return((B=n.find(Q=>Q.id===l))==null?void 0:B.name)||l};return C.jsxs(C.Fragment,{children:[C.jsx(XI.div,{className:`betToken ${e?"open":""}`,initial:{opacity:0,scale:.8},animate:{opacity:e?1:0,scale:e?1:.8},transition:{type:"spring",stiffness:320,damping:26},children:C.jsx("a",{role:"button","aria-haspopup":"dialog","aria-expanded":s,onClick:()=>{a(!0)},title:"Show my bets",className:"gold-link",children:C.jsxs("span",{className:"betToken__amount",children:[g,om(I??0)]})})}),s&&C.jsxs("div",{className:"results-modal",role:"dialog","aria-modal":"true","aria-label":"Your bets",children:[C.jsx("div",{className:"results-modal__backdrop",onClick:()=>a(!1)}),C.jsxs("div",{className:"results-modal__card card",children:[C.jsxs("div",{className:"results-modal__header",children:[C.jsx("h3",{style:{margin:0},children:"Your Open Main Bets"}),C.jsx("button",{className:"btn btn--ghost",onClick:()=>a(!1),children:"Close"})]}),r.length===0?C.jsx("ul",{className:"betlist results-list",children:C.jsx("li",{className:"betitem",children:"No applicable bets."})}):C.jsx("ul",{className:"betlist results-list",children:r.map(l=>C.jsx("li",{className:"betitem",children:C.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[C.jsxs(C.Fragment,{children:[" ",RZ(l.amount).map(B=>C.jsx(Vc,{mini:!0,value:B}))]}),C.jsxs("div",{className:"betitem__info",children:[C.jsxs("div",{className:"betitem__title",children:[c(l.playerId)," ",C.jsx("span",{className:"betSummary__dash",children:"—"})," BET"]}),C.jsxs("div",{className:"betitem__meta",children:["Amount: ",C.jsx("strong",{children:om(l.amount??0)}),l.acceptedById?` • matched by ${c(l.acceptedById)}`:" • (pending)"]})]})]})},l.id))})]})]})]})}const Vne={open:{opacity:1,y:0,x:0,transition:{type:"spring",stiffness:500,damping:30}},collapsed:{opacity:0,y:8,x:25,transition:{type:"spring",stiffness:420,damping:28,mass:.6}}};function GpA({selectedTimes:e,onAdd:A,onClear:t,onPlaceBet:i,onCancelBet:n,disabled:g,collapsed:o=!1,collapseLabel:s="Placed bet",miniChips:a=!1,betTokenProps:{isBanker:r,meId:I,open:c,players:l,show:B,labelPrefix:Q},hasBankRoll:h,betsLocked:d,myOpenMain:p,mainAmt:y,heading:m,rollerMeta:D}){const S=QpA,k=OAe(),N=E.useCallback(()=>{ti("Light")},[]),G=E.useRef(!1),M=!!d,w=!!h,b=!g&&!M&&!w&&!r&&!p,_=E.useCallback(()=>{G.current||!b||(G.current=!0,N(),i==null||i(),setTimeout(()=>{G.current=!1},600))},[b,i,N]),K=E.useCallback(q=>{if(!(g||M)){N();try{}catch{}A==null||A(q)}},[g,M,A,N]),J=E.useCallback(()=>{g||w||!p||(N(),n==null||n())},[g,w,p,n,N]);return C.jsxs("div",{className:`chipRackOuter ${b?"chipRackOuter--active":""}`,children:[y>0&&!p&&C.jsxs("div",{className:"chipRack__total","aria-label":`Total bet: ${y}${D?` vs ${D.name}${D.hasHistory?` (${D.label})`:""}`:""}`,children:[C.jsx("span",{className:"chipRack__totalSymbol",children:"ℤ"}),y.toLocaleString(),D&&C.jsxs("span",{className:"chipRack__totalMeta",children:[C.jsx("span",{className:"chipRack__totalMeta__vs",children:"vs"}),C.jsx("span",{className:"chipRack__totalMeta__name",children:D.name}),D.hasHistory&&C.jsxs("span",{className:`chipRack__totalMeta__record ${D.net>0?"chipRack__totalMeta__record--up":D.net<0?"chipRack__totalMeta__record--down":""}`,children:["(",D.label,")"]})]})]}),C.jsxs("div",{className:"chipRackContainer",children:[C.jsxs("div",{className:`chipRack ${g?"chipRack--disabled":""} ${o?"chipRack--collapsed":"chipRack--open"}`,children:[C.jsx("div",{className:"chipRack__collapseTarget","aria-label":s}),C.jsx(XI.div,{className:"chipRack__scroller",role:"listbox","aria-label":"Bet chips",initial:!1,style:{pointerEvents:g||M||o||p?"none":"auto"},children:S.map(q=>{const v=(e[q]??0)>0;return C.jsx(XI.div,{role:"option","aria-selected":v,variants:k?void 0:Vne,layout:!0,className:"chipRack__chipWrapper",children:C.jsx(Vc,{value:q,onAdd:K,onClear:t,disabled:!b,selectedTimes:e[q]??0,mini:a,"data-chip":q})},q)})})]}),C.jsxs("div",{className:"chipRack__placeWrap","aria-disabled":!b,style:{pointerEvents:b?"auto":"none"},"data-allowed":b?"true":"false",children:[b&&C.jsx("div",{className:"chipRack__bounceArrow","aria-hidden":"true",children:"▼"}),C.jsx("div",{className:"chipRack__placeInner",children:C.jsx(RpA,{onClick:_,disabled:!b,mini:a})}),b&&C.jsx("div",{className:"chipRack__halo","aria-hidden":"true"})]}),C.jsxs("div",{className:"chipRack__amount","aria-live":"polite","aria-atomic":"true",children:[C.jsx(XI.div,{children:C.jsx(Z3,{onClick:J,disabled:g||w||!p})}),C.jsx(Wne,{isBanker:r,meId:I,open:c,players:l,show:B,labelPrefix:Q})]})]})]})}function Xne({fly:e,onComplete:A}){const t=E.useRef({startX:e.startX,startY:e.startY,endX:e.endX,endY:e.endY,amount:e.amount}).current,i=E.useRef(null);E.useEffect(()=>{const g=$o.chipFlyDurationMs,o=0,s=100;i.current=window.setTimeout(()=>{try{CvA({playbackRate:1.25})}catch{}},o+s);const a=setTimeout(A,g+600);return()=>{clearTimeout(a),i.current&&(window.clearTimeout(i.current),i.current=null)}},[A]);const n=18;return E.useRef(null),C.jsx(XI.div,{initial:{position:"fixed",left:t.startX-n,top:t.startY-n,zIndex:1e4,opacity:0,scale:.9},animate:{left:t.endX-n,top:t.endY-n,opacity:1,scale:1},transition:{type:"spring",stiffness:120,damping:20,duration:$o.chipFlyDurationMs/1e3},onAnimationComplete:A,style:{pointerEvents:"none"},children:C.jsx(Vc,{mini:!0,value:t.amount,disabled:!0,className:"chip--flight",selectedTimes:0})})}function hM({label:e,subtitle:A,onClick:t,className:i,disabled:n,imageName:g,imgSrc:o,size:s="md",ariaLabel:a,showHalo:r}){const I=["gold-btn",`gold-btn--${s}`,o||g?"gold-btn--image":"gold-btn--styled",i||""].filter(Boolean).join(" "),c=g?`/ui/buttons/${g}.webp`:void 0,l=o||c;return C.jsxs("button",{type:"button",className:I,onClick:t,disabled:n,"aria-label":a||e,children:[r&&C.jsx("span",{className:"gold-btn__halo","aria-hidden":!0}),l&&C.jsx("span",{className:"gold-btn__media","aria-hidden":!0,children:C.jsxs("picture",{children:[C.jsx("source",{srcSet:l,type:"image/webp"}),C.jsx("img",{src:l,alt:"",loading:"lazy"})]})}),C.jsxs("span",{className:"gold-btn__text",children:[C.jsx("span",{className:"gold-btn__label",children:e}),A?C.jsx("span",{className:"gold-btn__sub","aria-hidden":!0,children:A}):null]})]})}function Xl({label:e,subtitle:A,onClick:t,disabled:i,size:n="md",ariaLabel:g,className:o,variant:s="pill",showHalo:a}){const r=[o,s==="circle"?"poker-action--circle":""].filter(Boolean).join(" "),[I,c]=ue.useState(!1),l=ue.useCallback(()=>{try{On()}catch{}c(!1),requestAnimationFrame(()=>{c(!0),window.setTimeout(()=>c(!1),260)});try{ti("Light")}catch{}try{}catch{}typeof t=="function"&&t()},[t]),B=typeof a=="boolean"?a:!i;return C.jsx("span",{className:["poker-action-spring",I?"is-spring":""].filter(Boolean).join(" "),"data-no-global-haptic":!0,children:C.jsx(hM,{label:e,subtitle:A,onClick:l,disabled:i,size:n,ariaLabel:g,className:r,showHalo:B})})}function XR(){const e=[{id:"bet1",type:"MAIN",playerId:"player1",acceptedById:"banker1",amount:100},{id:"bet2",type:"MAIN",playerId:"player2",acceptedById:null,amount:50}],A=[{id:"player1",name:"Alice"},{id:"player2",name:"Bob"},{id:"banker1",name:"Banker"}],[t,i]=E.useState({1:0,5:0,10:1,25:0,100:0}),[n,g]=E.useState(10),[o,s]=E.useState(!1),[a,r]=E.useState(!1),[I,c]=E.useState([]),l=E.useRef(null),B=E.useRef({c1:null,c2:null,c3:null,c4:null}),Q=G=>{if(!G)return null;const M=G.getBoundingClientRect();return{x:M.left+M.width/2,y:M.top+M.height/2}},h=E.useCallback((G,M,w)=>{const b=Q(G),_=Q(M);if(!b||!_)return;const J={id:`flight-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,amount:w,fromId:"sandbox-from",toId:"sandbox-to",startX:b.x,startY:b.y,endX:_.x,endY:_.y,active:!0};c(q=>[...q,J])},[]),d=()=>{h(B.current.c1,l.current,25)},p=()=>{["c1","c2","c3","c4"].forEach((G,M)=>{setTimeout(()=>h(B.current[G],l.current,5*(M+1)),M*40)})},y=()=>{["c1","c2","c3","c4"].forEach((G,M)=>{setTimeout(()=>h(l.current,B.current[G],10*(M+1)),M*40)})},m=G=>{c(M=>M.filter(w=>w.id!==G))},D=G=>{i(M=>({...M,[G]:(M[G]||0)+1})),g(M=>M+G)},S=G=>{i(M=>({...M,[G]:0})),g(M=>M-G*(t[G]||0))},k=()=>{s(!0),r(!0),console.log(`[sandbox] Bet placed with amount: $${n}`)},N=()=>{s(!1),r(!1),i({1:0,5:0,10:0,25:0,100:0}),g(0),console.log("[sandbox] Bet canceled")};return C.jsxs("div",{className:"button-sandbox",children:[C.jsx("h1",{children:"Button Sandbox"}),C.jsx(tr,{className:"profile-page"}),C.jsxs("section",{style:{marginBottom:28},children:[C.jsx("h2",{style:{fontSize:16,margin:"4px 0 12px"},children:"ChipFly Test"}),C.jsxs("div",{style:{position:"relative",padding:16,border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,display:"flex",flexDirection:"column",gap:12},children:[C.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap"},children:[C.jsx("button",{className:"felt-btn felt-btn--mini",onClick:d,children:"Single Flight"}),C.jsx("button",{className:"felt-btn felt-btn--mini",onClick:p,children:"Sweep 456"}),C.jsx("button",{className:"felt-btn felt-btn--mini",onClick:y,children:"Sweep 123"}),C.jsx("button",{className:"felt-btn felt-btn--mini",onClick:()=>c([]),style:{background:"#933",borderColor:"#600"},children:"Clear Flights"})]}),C.jsxs("div",{style:{position:"relative",minHeight:170,marginTop:8,display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0 12px"},children:[C.jsx("div",{style:{display:"flex",flexDirection:"column",gap:14},children:["c1","c2"].map(G=>C.jsx("div",{ref:M=>{B.current[G]=M},children:C.jsx(Vc,{mini:!0,value:5,disabled:!0,className:"chip--flight"})},G))}),C.jsxs("div",{ref:l,children:[C.jsx(Vc,{mini:!0,value:100,disabled:!0,className:"chip--flight"}),C.jsx("div",{style:{textAlign:"center",marginTop:4,fontSize:11,opacity:.7},children:"Banker"})]}),C.jsx("div",{style:{display:"flex",flexDirection:"column",gap:14},children:["c3","c4"].map(G=>C.jsx("div",{ref:M=>{B.current[G]=M},children:C.jsx(Vc,{mini:!0,value:25,disabled:!0,className:"chip--flight"})},G))})]})]}),I.map(G=>C.jsx(Xne,{fly:G,onComplete:()=>m(G.id)},G.id))]}),C.jsxs("section",{style:{marginBottom:28},children:[C.jsx("h2",{style:{fontSize:16,margin:"4px 0 12px"},children:"Flash Overlays"}),C.jsxs("div",{className:"flash-preview__row",children:[C.jsx("div",{className:"flash-preview__header",children:C.jsx("div",{className:"flash-root flash-root--header","aria-hidden":!0,children:C.jsx("div",{className:"flash-card flash-win",children:C.jsxs("div",{className:"flash-body",children:[C.jsxs("div",{className:"flash-title",children:[C.jsx("span",{className:"flash-title__name",children:"ALICE"}),C.jsx("span",{className:"flash-title__rest",children:"WINS"})]}),C.jsxs("div",{className:"flash-subtitle",children:[C.jsx("span",{className:"keep-lower",children:"z"}),"250"]})]})})})}),C.jsx("div",{className:"flash-preview__header",children:C.jsx("div",{className:"flash-root flash-root--header","aria-hidden":!0,children:C.jsx("div",{className:"flash-card flash-lose",children:C.jsxs("div",{className:"flash-body",children:[C.jsxs("div",{className:"flash-title",children:[C.jsx("span",{className:"flash-title__name",children:"BANKER"}),C.jsx("span",{className:"flash-title__rest",children:"LOSES"})]}),C.jsxs("div",{className:"flash-subtitle",children:[C.jsx("span",{className:"keep-lower",children:"z"}),"120"]})]})})})}),C.jsx("div",{className:"flash-preview__header",children:C.jsx("div",{className:"flash-root flash-root--header","aria-hidden":!0,children:C.jsx("div",{className:"flash-card flash-push",children:C.jsxs("div",{className:"flash-body",children:[C.jsx("div",{className:"flash-title",children:"PUSH"}),C.jsx("div",{className:"flash-subtitle",children:"No Action"})]})})})})]}),C.jsxs("div",{className:"flash-preview__row",children:[C.jsx("div",{className:"flash-frame",children:C.jsx("div",{className:"flash-card flash-win","aria-hidden":!0,children:C.jsxs("div",{className:"flash-body",children:[C.jsxs("div",{className:"flash-title",children:[C.jsx("span",{className:"flash-title__name",children:"ALICE"}),C.jsx("span",{className:"flash-title__rest",children:"WINS"})]}),C.jsxs("div",{className:"flash-subtitle",children:[C.jsx("span",{className:"keep-lower",children:"z"}),"250"]})]})})}),C.jsx("div",{className:"flash-frame",children:C.jsx("div",{className:"flash-card flash-lose","aria-hidden":!0,children:C.jsxs("div",{className:"flash-body",children:[C.jsxs("div",{className:"flash-title",children:[C.jsx("span",{className:"flash-title__name",children:"BANKER"}),C.jsx("span",{className:"flash-title__rest",children:"LOSES"})]}),C.jsxs("div",{className:"flash-subtitle",children:[C.jsx("span",{className:"keep-lower",children:"z"}),"120"]})]})})}),C.jsx("div",{className:"flash-frame",children:C.jsx("div",{className:"flash-card flash-push","aria-hidden":!0,children:C.jsxs("div",{className:"flash-body",children:[C.jsx("div",{className:"flash-title",children:"PUSH"}),C.jsx("div",{className:"flash-subtitle",children:"No Action"})]})})})]})]}),C.jsxs("section",{style:{marginBottom:28},children:[C.jsx("h2",{style:{fontSize:16,margin:"4px 0 12px"},children:"Poker Action Buttons"}),C.jsxs("div",{className:"poker-actions",role:"group","aria-label":"Poker action buttons",style:{display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},children:[C.jsx(Xl,{label:"Check",ariaLabel:"Check",size:"md",className:"poker-action--green poker-action--secondary poker-action--check",onClick:()=>{}}),C.jsx(Xl,{label:"Call",subtitle:"z120",ariaLabel:"Call 120",size:"md",className:"poker-action--green poker-action--primary poker-action--call",onClick:()=>{}}),C.jsx(Xl,{label:"Bet",subtitle:"z250",ariaLabel:"Bet 250",size:"md",className:"poker-action--flat poker-action--secondary poker-action--bet",onClick:()=>{}}),C.jsx(Xl,{label:"Raise",subtitle:"z400",ariaLabel:"Raise 400",size:"md",className:"poker-action--flat poker-action--secondary poker-action--raise",onClick:()=>{}}),C.jsx(Xl,{label:"Fold",ariaLabel:"Fold",size:"md",className:"poker-action--flat poker-action--danger poker-action--fold",onClick:()=>{}})]})]}),C.jsxs("div",{className:"button-grid",children:[C.jsx("div",{className:"button-item",children:C.jsx(ydA,{onClick:()=>{},label:"ROLL",busy:!1,disabled:!1})}),C.jsx("div",{className:"button-item",children:C.jsx(Z3,{onClick:()=>console.log("[sandbox] Cancel Bet Button Clicked"),busy:!1,disabled:!1,label:"Cancel Bet"})}),C.jsx("div",{className:"button-item",children:o?C.jsx(Z3,{onClick:N,busy:!1,disabled:!1,label:"Cancel Bet"}):C.jsx(RpA,{disabled:n<=0,onClick:k,busy:!1,label:"✓"})}),C.jsx("div",{className:"button-item",children:C.jsx(GpA,{selectedTimes:t,onAdd:D,onClear:S,disabled:o,collapsed:a,collapseLabel:"Chip Rack",betTokenProps:{isBanker:!1,meId:"player1",open:e,players:A,show:o},onPlaceBet:k,onCancelBet:N,mainAmt:n})}),C.jsx("div",{className:"button-item",children:C.jsx(DpA,{state:"verified"})})]})]})}function Xf(){const e=qi(),A=()=>{window.history.length>1?e(-1):e("/lobby",{replace:!0})};return C.jsx("div",{className:"disclaimer-screen",children:C.jsxs("div",{className:"disclaimer-panel",children:[C.jsxs("button",{type:"button",className:"disclaimer-back",onClick:A,"aria-label":"Back",children:[C.jsx(tc,{className:"icon"})," Back"]}),C.jsx("div",{className:"disclaimer-accent-bar"}),C.jsx("h1",{className:"disclaimer-title",children:"Disclaimer"}),C.jsxs("div",{className:"disclaimer-body",children:[C.jsxs("p",{children:[C.jsx("strong",{children:"Zentara One Dice Lounge"})," is a social casino game intended for entertainment purposes only. No real money gambling takes place within this app."]}),C.jsx("p",{children:"Virtual chips used in gameplay have no cash value and cannot be redeemed for real money, goods, or services."}),C.jsx("p",{children:"For your privacy and to keep rooms fresh for active players, the app will automatically return you to the Lobby after 4 minutes of inactivity."}),C.jsx("p",{children:"This game is intended for an adult audience (18+). Playing does not imply future success at real money gambling. Please play responsibly."}),C.jsx("p",{children:"If you or someone you know has a gambling problem and needs help, please contact your local gambling support hotline."})]}),C.jsxs("div",{className:"disclaimer-footer",children:["© ",new Date().getFullYear()," Zentara One. All rights reserved."]})]})})}function $f(){const e=qi();return C.jsx("div",{className:"legal-screen",children:C.jsxs("div",{className:"legal-panel",children:[C.jsx("div",{className:"legal-accent-bar"}),C.jsxs("div",{className:"legal-header",children:[C.jsxs("button",{type:"button",className:"legal-back",onClick:()=>e(-1),"aria-label":"Go back",children:[C.jsx(tc,{className:"icon"}),"Back"]}),C.jsx("h1",{className:"legal-title",children:"Support"})]}),C.jsxs("div",{className:"legal-body",children:[C.jsx("p",{children:"Need help with Zentara One Dice Lounge? We're here for you."}),C.jsxs("p",{children:["Email us at"," ",C.jsx("a",{href:"mailto:support@zentaraone.com",className:"legal-link",children:"support@zentaraone.com"})," ","and we'll get back to you as soon as possible."]}),C.jsx("p",{children:"Please include your device, OS version, and a brief description of the issue."})]}),C.jsxs("div",{className:"legal-footer",children:["© ",new Date().getFullYear()," Zentara One. All rights reserved."]})]})})}function Ay(){const e=qi();return C.jsx("div",{className:"legal-screen",children:C.jsxs("div",{className:"legal-panel",children:[C.jsx("div",{className:"legal-accent-bar"}),C.jsxs("div",{className:"legal-header",children:[C.jsxs("button",{type:"button",className:"legal-back",onClick:()=>e(-1),"aria-label":"Go back",children:[C.jsx(tc,{className:"icon"}),"Back"]}),C.jsx("h1",{className:"legal-title",children:"Privacy Policy"})]}),C.jsxs("div",{className:"legal-body",children:[C.jsx("p",{children:"We respect your privacy. Zentara One Dice Lounge, Zentara One Poker Lounge, Zentara One Craps Lounge, Zentara One Cee-Lo Lounge, and Zentara One Skills Lounge all collect minimal data needed to operate the app (such as an email for login, in-app purchase history via Apple/Google, and basic device info for diagnostics). We do not sell your personal information."}),C.jsxs("p",{children:["For questions or data requests, contact"," ",C.jsx("a",{href:"mailto:support@zentaraone.com",className:"legal-link",children:"support@zentaraone.com"}),"."]})]}),C.jsxs("div",{className:"legal-footer",children:["© ",new Date().getFullYear()," Zentara One. All rights reserved."]})]})})}function ey(){const e=qi();return C.jsx("div",{className:"legal-screen",children:C.jsxs("div",{className:"legal-panel",children:[C.jsx("div",{className:"legal-accent-bar"}),C.jsxs("div",{className:"legal-header",children:[C.jsxs("button",{type:"button",className:"legal-back",onClick:()=>e(-1),"aria-label":"Go back",children:[C.jsx(tc,{className:"icon"}),"Back"]}),C.jsx("h1",{className:"legal-title",children:"Terms of Use"})]}),C.jsxs("div",{className:"legal-body",children:[C.jsx("p",{children:'By using Zentara One Dice Lounge, Poker Lounge, Craps Lounge, Cee-Lo Lounge, or Skills Lounge (the "App"), you agree to these Terms of Use. If you do not agree, do not use the App.'}),C.jsx("h2",{children:"1. Apple Standard EULA"}),C.jsxs("p",{children:["For iOS users, the App is licensed to you under the Apple Media Services Terms and Conditions, including the standard Apple End User License Agreement (EULA). You can review the Apple EULA here:"," ",C.jsx("a",{className:"legal-link",href:"https://www.apple.com/legal/internet-services/itunes/dev/stdeula/",target:"_blank",rel:"noopener noreferrer",children:"https://www.apple.com/legal/internet-services/itunes/dev/stdeula/"}),"."]}),C.jsx("h2",{children:"2. Subscriptions and Billing"}),C.jsx("p",{children:"The App may offer auto-renewable subscriptions. Payment will be charged to your Apple ID at confirmation of purchase. Subscriptions automatically renew unless canceled at least 24 hours before the end of the current period. You can manage or cancel your subscription in your account settings on your device."}),C.jsx("h2",{children:"3. Refunds"}),C.jsx("p",{children:"Refunds for purchases made via the App Store are handled by Apple directly, per Apple policies."}),C.jsx("h2",{children:"4. Acceptable Use"}),C.jsx("p",{children:"You agree not to misuse the App, attempt to disrupt its operation, or violate any applicable laws. We may suspend or terminate access for violations."}),C.jsx("h2",{children:"5. Privacy"}),C.jsxs("p",{children:["Please review our"," ",C.jsx(HI,{className:"legal-link",to:"/privacy",children:"Privacy Policy"})," ","to understand how we collect and use information."]}),C.jsx("h2",{children:"6. Contact"}),C.jsxs("p",{children:["Questions? Contact"," ",C.jsx("a",{href:"mailto:support@zentaraone.com",className:"legal-link",children:"support@zentaraone.com"}),"."]})]}),C.jsxs("div",{className:"legal-footer",children:["© ",new Date().getFullYear()," Zentara One. All rights reserved."]})]})})}Ca();const xtA={GET:!0,HEAD:!0};function $ne(e){const{baseURL:A,getToken:t,onUnauthorized:i,defaultTimeoutMs:n=12e3,defaultHeaders:g={"Content-Type":"application/json"},retry:o={attempts:2,backoffMs:400,retryOn:[408,429,500,502,503,504]}}=e;async function s(B,Q={}){var y;const h=((y=Q.method)==null?void 0:y.toUpperCase())||"GET",d=xtA[h]?(o.attempts??2)+1:1;let p;for(let m=0;m<d;m++){const D=new AbortController,S=setTimeout(()=>D.abort(),Q.timeoutMs??n);try{const k=await Promise.resolve(t()),N=await fetch(Age(A,B),{...Q,headers:{...g,...Q.headers||{},...k?{Authorization:`Bearer ${k}`}:{}},signal:D.signal});if(clearTimeout(S),N.status===401)throw i==null||i(),TtA("Unauthorized",N.status,await qtA(N));if((o.retryOn??[]).includes(N.status)&&m<d-1){await YtA((o.backoffMs??400)*(m+1));continue}if(!N.ok)throw TtA(`HTTP ${N.status}`,N.status,await qtA(N));return(N.headers.get("content-type")||"").includes("application/json")?await N.json():await N.text()}catch(k){if(clearTimeout(S),p=k,m<d-1&&xtA[h]){await YtA((o.backoffMs??400)*(m+1));continue}break}}throw p}return{get:(B,Q)=>s(B,{...Q,method:"GET"}),post:(B,Q,h)=>s(B,{...h,method:"POST",body:Q==null?void 0:JSON.stringify(Q)}),put:(B,Q,h)=>s(B,{...h,method:"PUT",body:Q==null?void 0:JSON.stringify(Q)}),patch:(B,Q,h)=>s(B,{...h,method:"PATCH",body:Q==null?void 0:JSON.stringify(Q)}),del:(B,Q)=>s(B,{...Q,method:"DELETE"}),fetch:s}}function Age(e,A){return!e.endsWith("/")&&!A.startsWith("/")?`${e}/${A}`:e.endsWith("/")&&A.startsWith("/")?e+A.slice(1):e+A}function TtA(e,A,t){const i=new Error(e);return i.status=A,i.body=t,i}async function qtA(e){try{return await e.json()}catch{try{return await e.text()}catch{return null}}}const YtA=e=>new Promise(A=>setTimeout(A,e)),oGe=$ne({baseURL:Ca(),getToken:()=>uo().then(e=>e??null),onUnauthorized:()=>{kd()},defaultTimeoutMs:12e3});function KZ({children:e,header:A,footer:t,overlay:i,showAvatarBacks:n=!1}){return C.jsxs("div",{className:"poker-room-shell","aria-label":"Poker Room","data-game-mode":"poker","data-show-avatar-backs":n?"1":void 0,children:[C.jsx(tr,{className:"page-poker-room"}),C.jsx("div",{className:"poker-room-bg"}),C.jsxs("div",{className:"poker-room-foreground",role:"main",children:[A,C.jsx("div",{className:"poker-room-content",children:e}),t]}),i]})}function bpA({cards:e,firstRevealed:A=!0,bothRevealed:t=!0}){const[i,n]=Array.isArray(e)?e:[];return!i&&!n?null:C.jsxs("div",{className:"holecards","aria-label":"hole-cards",children:[C.jsx(HtA,{value:i,revealed:!!A||!!t}),C.jsx(HtA,{value:n,revealed:!!t})]})}function HtA({value:e,revealed:A=!1}){if(!e)return C.jsx("span",{className:"poker-card"+(A?" revealed":""),"aria-hidden":!0});const{rank:t,suit:i}=ege(e),n=i==="hearts"||i==="diamonds";return C.jsxs("div",{className:["poker-card",n?"poker-card--red":"",A?"revealed":""].filter(Boolean).join(" "),"aria-label":`${t} of ${i}`,children:[C.jsx("span",{className:"poker-card__rank",children:t}),C.jsx("span",{className:"poker-card__suit",children:tge(i)})]})}function ege(e){const A=String(e||"").trim().toUpperCase(),t=A.slice(0,-1),i=A.slice(-1);return{rank:t==="T"?"10":t,suit:i==="H"?"hearts":i==="D"?"diamonds":i==="C"?"clubs":"spades"}}function tge(e){switch(e){case"hearts":return"♥";case"diamonds":return"♦";case"clubs":return"♣";case"spades":return"♠";default:return"?"}}function ige({gameState:e,players:A,winners:t,hands:i,durationMs:n,meId:g}){const o=E.useRef(null),s=E.useRef(null),a=E.useRef(null),{info:r}=Jr();E.useEffect(()=>{const I=o.current,c=e||{};o.current=c;const l=c==null?void 0:c.pokerLastAction;if(l&&typeof l.seq=="number"){const U=(Array.isArray(c==null?void 0:c.pokerSeats)?c.pokerSeats:[]).find(x=>x.seatIndex===l.seatIndex);if(U){const x=A.find(sA=>sA.id===U.playerId),T=(x==null?void 0:x.name)||(x==null?void 0:x.email)||"Player";let z;const Z=sA=>typeof sA=="number"?`z${sA.toLocaleString("en-US")}`:"";switch((l.action||"").toLowerCase()){case"fold":z="Fold";break;case"check":z="Check";break;case"call":z=`Call ${Z(l.amountDelta)}`;break;case"bet":z=`Bet ${Z(l.amountDelta)}`;break;case"raise":z=l.toBet?`Raise to ${Z(l.toBet)}`:`Raise ${Z(l.amountDelta)}`;break;default:z="Action";break}const aA=`srv:${Number((c==null?void 0:c.pokerRoundSeq)||0)||0}:${l.seq}`;a.current!==aA&&(r(`${T}: ${z}`,void 0),a.current=aA),s.current=l.seq;return}}if(!I)return;const B=(I==null?void 0:I.pokerPhase)??"waiting",Q=(c==null?void 0:c.pokerPhase)??"waiting";if(B!==Q&&B==="waiting"&&Q==="pre-flop")return;const h=Array.isArray(I==null?void 0:I.pokerSeats)?I.pokerSeats:[],d=Array.isArray(c==null?void 0:c.pokerSeats)?c.pokerSeats:[];if(!d.length)return;const p=v=>{const U=new Map;for(const x of v)U.set(x.seatIndex,x);return U},y=p(h),m=p(d),D=I==null?void 0:I.pokerActingSeat,S=c==null?void 0:c.pokerActingSeat,k=(I==null?void 0:I.pokerCurrentBet)||0,N=(c==null?void 0:c.pokerCurrentBet)||0;let G=null,M=null;for(const v of d){const U=y.get(v.seatIndex);if(U&&(U.status==="active"||U.status==="all-in")&&v.status==="folded"){G=v,M="Fold";break}}if(!M)for(const v of d){const U=y.get(v.seatIndex);if(!U)continue;const x=(v.committed||0)-(U.committed||0);if(x>0){G=v,k===0?M=`Bet z${x}`:N>k?M=`Raise to z${N}`:M=`Call z${x}`;break}}if(!M&&D!=null&&S!=null&&D!==S){const v=y.get(D),U=m.get(D);v&&U&&v.status==="active"&&U.status==="active"&&(v.committed||0)===(U.committed||0)&&(G=U,M="Check")}if(!M||!G)return;const w=A.find(v=>v.id===G.playerId),_=`${(w==null?void 0:w.name)||(w==null?void 0:w.email)||"Player"}: ${M}`,K=Number((c==null?void 0:c.pokerRoundSeq)||0)||0;try{const v=typeof window<"u"?window:void 0,U=v&&v.__pokerWinnersFlashGuard;if(U&&U.roundSeq===K)return}catch{}const J=Number((G==null?void 0:G.committed)||0),q=`heur:${K}:${G.seatIndex}:${M}:${J}:${N}`;a.current!==q&&(r(_,void 0),a.current=q)},[e,A,r,n])}function OtA({enabled:e,onComplete:A,perCardSec:t=.55,staggerSec:i=.12,origin:n,handKey:g,getTargets:o,passes:s=2}){const a=E.useRef(null),[r,I]=E.useState([]),[c,l]=E.useState(!1),B=E.useMemo(()=>{if(!a.current)return{x:0,y:0};const d=a.current.getBoundingClientRect(),p=(n==null?void 0:n.xPct)??.5,y=(n==null?void 0:n.yPct)??.78;return{x:d.width*p,y:d.height*y}},[n,a.current]);E.useEffect(()=>{if(!e)return;const h=a.current;if(!h||typeof window>"u")return;let d=[];if(typeof o=="function")try{d=o(h)||[]}catch{d=[]}else{const p=h.getBoundingClientRect();d=Array.from(document.querySelectorAll(".poker-room-header .avatar-ring")).map(m=>{const D=m.getBoundingClientRect();return{x:(D.left+D.right)/2-p.left,y:(D.top+D.bottom)/2-p.top}})}I(d)},[e,g,o]),E.useEffect(()=>{if(!e)return;try{mS(["cardSwoosh"])}catch{}(async()=>{const y=await kF(["cardSwoosh"],900);l(y)})();const h=r.length*Math.max(1,s);if(h===0){const y=setTimeout(()=>A==null?void 0:A(),10);return()=>clearTimeout(y)}const d=(h-1)*i+t,p=setTimeout(()=>A==null?void 0:A(),d*1e3);return()=>clearTimeout(p)},[e,r,t,i,A,s]);const Q=E.useMemo(()=>{const h=[],d=Math.max(1,s);for(let p=0;p<d;p++)for(let y=0;y<r.length;y++){const m=p*r.length+y;h.push({key:`card-${p}-${y}`,delay:m*i,to:r[y]})}return h},[r,s,i,g]);return E.useEffect(()=>{if(!e||!Q.length||!c)return;const h=[],p=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent)?70:0;let y=0,m=!0;for(const D of Q){const S=Math.max(0,(D.delay||0)*1e3),N=Math.max(S+(m?30:0),y+p),G=window.setTimeout(()=>{try{cvA({volume:.0125})}catch{}},N);y=N,m=!1,h.push(G)}return()=>{h.forEach(D=>window.clearTimeout(D))}},[e,Q,c]),!e||!c?null:C.jsx("div",{ref:a,className:"poker-dealing-layer","aria-hidden":!0,style:{willChange:"transform, opacity"},children:Q.map(h=>C.jsx(XI.div,{className:"poker-dealing-card",initial:{x:B.x,y:B.y,opacity:0},animate:{x:h.to.x,y:h.to.y,opacity:1},transition:{duration:t,delay:h.delay,ease:"easeOut"},style:{willChange:"transform, opacity",backfaceVisibility:"hidden"}},h.key))})}function nge({players:e,entries:A,onClose:t}){const i=ue.useCallback((o,s)=>{var a;return((a=e.find(r=>r.id===o))==null?void 0:a.name)||`Seat ${s+1}`},[e]),n=ue.useCallback(o=>{if(!o||typeof o.category!="number")return;const s=o.category|0,a=Array.isArray(o.tiebreak)?o.tiebreak:[],r=c=>"23456789TJQKA"[Math.max(0,Math.min(12,c))]||"?",I=c=>({2:"Deuce",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine",T:"Ten",J:"Jack",Q:"Queen",K:"King",A:"Ace"})[r(c)]||r(c);switch(s){case 8:return`Straight Flush (${I(a[0]??0)} high)`;case 7:return`Four of a Kind (${I(a[0]??0)}s)`;case 6:return`Full House (${I(a[0]??0)}s over ${I(a[1]??0)}s)`;case 5:return`Flush (${[a[0],a[1],a[2],a[3],a[4]].filter(c=>c!=null).map(c=>r(c)).join("")})`;case 4:return`Straight (${I(a[0]??0)} high)`;case 3:return`Three of a Kind (${I(a[0]??0)}s)`;case 2:return`Two Pair (${I(a[0]??0)}s & ${I(a[1]??0)}s)`;case 1:return`One Pair (${I(a[0]??0)}s)`;default:return`High Card (${I(a[0]??0)})`}},[]),g=ue.useMemo(()=>[...A].sort((o,s)=>s.roundSeq-o.roundSeq),[A]);return C.jsxs("div",{className:"results-modal","data-testid":"poker-history-modal",children:[C.jsx("div",{className:"results-modal__backdrop",onClick:t}),C.jsxs("div",{className:"results-modal__card card",style:{maxWidth:900},children:[C.jsxs("div",{className:"results-modal__header",children:[C.jsx("h3",{children:"Poker History"}),C.jsx("button",{className:"btn btn--ghost",onClick:t,"aria-label":"Close History",children:"Close"})]}),g.length===0&&C.jsx("div",{children:"No hands yet."}),C.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12,maxHeight:"70vh",overflow:"auto"},children:g.map(o=>C.jsxs("div",{className:"card",style:{padding:10,background:"rgba(255,255,255,0.05)"},children:[C.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:8},children:[C.jsxs("div",{style:{fontWeight:600},children:["Hand ",o.roundSeq]}),C.jsxs("div",{"aria-label":"pot",children:["Pot: z",o.pot||0]})]}),C.jsx("div",{"aria-label":"seats",style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:(o.seats&&o.seats.length?o.seats:o.hands.map(s=>({playerId:s.playerId,seatIndex:s.seatIndex}))).map((s,a)=>{const r=o.winners.find(h=>h.playerId===s.playerId),I=i(s.playerId,s.seatIndex),c=!!r,l=String(s.status||"").toLowerCase()==="folded",B=n(s.rank||(r==null?void 0:r.rank)),Q=typeof(r==null?void 0:r.amount)=="number"?r.amount:0;return C.jsxs("div",{className:["poker-history__seat",c?"is-winner":""].filter(Boolean).join(" "),style:{padding:8,borderRadius:6,background:c?"rgba(40,180,80,0.15)":"rgba(255,255,255,0.06)"},children:[C.jsx("div",{style:{fontWeight:600,marginBottom:4},children:I}),C.jsx("div",{style:{fontSize:13,opacity:.9},children:l?C.jsx("span",{children:"Folded"}):C.jsx("span",{children:B||"—"})}),C.jsx("div",{style:{fontSize:13,opacity:.9,marginTop:2},children:Q>0?C.jsxs("span",{children:["Winnings: z",Q]}):C.jsx("span",{children:"Winnings: z0"})})]},`s-${o.roundSeq}-${a}`)})})]},o.roundSeq))})]})]})}const W3=["A","K","Q","J","10","9","8","7","6","5","4","3","2"],gge={A:"Ace",K:"King",Q:"Queen",J:"Jack",10:"Ten",9:"Nine",8:"Eight",7:"Seven",6:"Six",5:"Five",4:"Four",3:"Three",2:"Two"};function UpA(e){const A=String(e||"").trim().toUpperCase();if(!A)return null;const t=A.slice(0,-1),i=t==="T"?"10":t;return W3.includes(i)?i:null}function vpA(e){return e.map(UpA).filter(A=>A!==null)}function FZ(e){const A=vpA(e),t={};for(const i of A)t[i]=(t[i]||0)+1;return Object.entries(t).filter(([,i])=>i>=2).map(([i])=>i)}function oge(e){return FZ(e).length>0}function sge(e){const A=vpA(e);if(A.length===0)return null;let t=null,i=W3.length;for(const n of A){const g=W3.indexOf(n);g!==-1&&g<i&&(i=g,t=n)}return t}function age(e){const A=sge(e);return A?`${gge[A]} High`:null}function rge(e,A){if(A<0||A>=e.length)return!1;const t=UpA(e[A]);return t?FZ(e).includes(t):!1}function Ige(e){const A=[];if(!e||e.length===0)return A;oge(e)&&A.push({label:"Paired Board",type:"paired"});const t=age(e);return t&&A.push({label:t,type:"high"}),A}function Cge(e){return e<0||e>4?null:e<=2?"flop":e===3?"turn":"river"}function cge({boardCards:e}){const A=Ige(e);return C.jsx("div",{className:"board-badges","aria-label":"Board state indicators",children:A.map((t,i)=>C.jsx("span",{className:`board-badge board-badge--${t.type}`,role:"status","aria-live":"polite",children:t.label},`${t.type}-${i}`))})}function lge({winner:e,eliminatedOrder:A,finalStates:t,nameOf:i,meId:n,onDismiss:g}){const o=[];e&&o.push({playerId:e,place:1});const s=[...A].reverse();for(const r of s){const I=t[r],c=(I==null?void 0:I.place)??o.length+1;r!==e&&o.push({playerId:r,place:c})}const a=e===n;return C.jsxs("div",{className:"elim-gameover",onClick:g,children:[C.jsx("div",{className:"elim-gameover__title",children:a?"🏆 You Win!":"Game Over"}),C.jsx("div",{className:"elim-gameover__subtitle",children:a?"Last player standing — champion!":e?`${i(e)} wins the tournament!`:"Tournament complete"}),C.jsx("ol",{className:"elim-gameover__standings",children:o.map(r=>{const I=r.place===1,c=r.playerId===n,l=["elim-gameover__row",I?"elim-gameover__row--winner":"",c?"elim-gameover__row--hero":""].filter(Boolean).join(" ");return C.jsxs("li",{className:l,children:[C.jsx("span",{className:"elim-gameover__place-num",children:r.place===1?"🥇":r.place===2?"🥈":r.place===3?"🥉":`#${r.place}`}),C.jsxs("span",{className:"elim-gameover__player-name",children:[i(r.playerId),c?" (You)":""]})]},r.playerId)})}),C.jsx("button",{type:"button",className:"elim-gameover__dismiss",onClick:g,children:"OK"})]})}function PtA(e){if(e==null||!e)return"";const A=["th","st","nd","rd"],t=e%100;return e+(A[(t-20)%10]||A[t]||A[0])}function Bge(e){const A=String(e||"").trim().toUpperCase(),t=A.slice(0,-1),i=A.slice(-1);return{rank:t==="T"?"10":t,suit:i==="H"?"hearts":i==="D"?"diamonds":i==="C"?"clubs":"spades"}}function Ege(e){switch(e){case"hearts":return"♥";case"diamonds":return"♦";case"clubs":return"♣";case"spades":return"♠";default:return"?"}}function Qge({value:e,concealed:A,position:t,isPaired:i,animateEntrance:n}){if(!e)return null;const{rank:g,suit:o}=Bge(e),a=["poker-card","poker-card--board",o==="hearts"||o==="diamonds"?"poker-card--red":"",t?`poker-card--${t}`:"",i?"poker-card--paired":"",n?"poker-card--enter":""].filter(Boolean).join(" ");return C.jsxs("div",{className:a,style:A?{visibility:"hidden"}:void 0,"aria-label":`${g} of ${o}`,children:[C.jsx("span",{className:"poker-card__rank",children:g}),C.jsx("span",{className:"poker-card__suit",children:Ege(o)})]})}const K0=Object.create(null),FY=Object.create(null);function _Z(){var ar,Fa,rr,mI,Qc,IC;const{roomId:e}=Qw(),{user:A,refreshUser:t}=tn(),i=Ms(),{onHandEnd:n,isAdShowing:g}=Yf(),o=String((A==null?void 0:A.id)??(A==null?void 0:A.email)??""),{joinRoom:s,leaveRoom:a,connected:r,participants:I,localParticipant:c}=Il(),l=Ix(),{active:B,fire:Q,onComplete:h}=UZ(),d=ue.useRef(0),p=["loss-a","loss-b","loss-c"],y=()=>{const lA=p[d.current%p.length];return d.current+=1,lA};E.useEffect(()=>{const lA=()=>{try{f8()||On()}catch{}};lA();const LA=["pointerdown","touchstart","mousedown","click","keydown"];return LA.forEach(ae=>{document.addEventListener(ae,lA,{once:!0,capture:!0})}),()=>{LA.forEach(ae=>{document.removeEventListener(ae,lA,{capture:!0})})}},[]);const{pokerJoinRoom:m,pokerStartHand:D,pokerCreateRoom:S,pokerFold:k,pokerCheck:N,pokerCall:G,pokerBet:M,pokerRaise:w,pokerFetchHistory:b}=Mo(),_=qi(),{info:K,win:J,onIdle:q,show:v}=Jr(),[U,x]=E.useState(null);E.useEffect(()=>{var ae;const lA=(ae=U==null?void 0:U.gameState)==null?void 0:ae.pokerPhase;return lA&&lA!=="waiting"?l.acquire():l.release(),()=>{l.release()}},[U==null?void 0:U.gameState,l]),E.useEffect(()=>{var ae;const lA=(ae=U==null?void 0:U.gameState)==null?void 0:ae.pokerPhase;!lA||lA==="waiting"?wL({volume:.0125}):Yu()},[U==null?void 0:U.gameState]);const[T,z]=E.useState(!1),Z=ue.useRef(!1),[eA,aA]=E.useState(null),[sA,pA]=E.useState(!1),[gA,yA]=E.useState(!1),[fA,RA]=E.useState(!1),qA=ue.useRef(!1),W=ue.useRef(!1),$=ue.useRef(null);ue.useEffect(()=>{qA.current=fA},[fA]),ue.useEffect(()=>{W.current=sA},[sA]),ue.useEffect(()=>{$.current=eA},[eA]),ue.useEffect(()=>{Z.current=T},[T]),ue.useEffect(()=>{(!eA||eA.length!==2)&&(PA.current=0)},[eA]);const L=ue.useRef(null),H=ue.useRef(0);ue.useRef(0);const P=ue.useRef(null),tA=ue.useRef(null),iA=ue.useRef(null),[oA,IA]=E.useState(0),[CA,_A]=E.useState(0),[uA,X]=E.useState([]),[O,cA]=E.useState([]),[wA,xA]=E.useState(!1),[YA,jA]=E.useState([]),ie=ue.useRef(0),he=ue.useRef(0),le=ue.useRef(0),NA=ue.useRef(!1),EA=ue.useRef(null),PA=ue.useRef(0),ZA=ue.useRef(void 0),FA=ue.useRef(0),[Ie,DA]=ue.useState([]),rA=ue.useRef(0),BA=ue.useRef(0),j=ue.useRef(0),[QA,dA]=ue.useState(!1),UA=ue.useRef(0),TA=ue.useRef(new Set),oe=ue.useRef(null),me=ue.useRef(null),[be,$e]=E.useState(0),[ci,ke]=E.useState(0),[nt,Ut]=ue.useState(new Set),dt=ue.useRef([]),Ht=ue.useRef(null),Ft=ue.useRef(0),Jt=!0,[$A,He]=E.useState(!0),Xe=ue.useRef(0),St=ue.useRef(null),kA=ue.useRef(null),se=ue.useRef(null),[Ce,VA]=E.useState(null),[nA,vA]=E.useState({}),[KA,WA]=E.useState([]),[bA,pe]=E.useState(null),[xe,it]=E.useState(null);ue.useEffect(()=>{var LA;const lA=U==null?void 0:U.gameState;lA&&(LA=lA.pokerElimination)!=null&&LA.enabled&&(VA({enabled:!0,startingShields:lA.pokerElimination.startingShields??3,maxTokens:lA.pokerElimination.maxTokens??3}),lA.pokerEliminationState&&vA(lA.pokerEliminationState),lA.pokerEliminatedOrder&&WA(lA.pokerEliminatedOrder))},[U==null?void 0:U.gameState]);const[ve,re]=E.useState(null),Qe=ue.useMemo(()=>A?A.id:"",[A]),[HA,ge]=E.useState(!1);E.useEffect(()=>{let lA=!0;return(async()=>{try{const{Preferences:LA}=await Qi(async()=>{const{Preferences:De}=await Promise.resolve().then(()=>Oc);return{Preferences:De}},void 0),{value:ae}=await LA.get({key:"onb_poker_v1"});if(!lA)return;ge(ae!=="1")}catch{if(!lA)return;ge(!0)}})(),()=>{lA=!1}},[]);const ye=ue.useCallback(()=>{(async()=>{try{const{Preferences:lA}=await Qi(async()=>{const{Preferences:LA}=await Promise.resolve().then(()=>Oc);return{Preferences:LA}},void 0);await lA.set({key:"onb_poker_v1",value:"1"})}catch{}ge(!1)})()},[]);ue.useEffect(()=>{let lA=!1,LA=null,ae=null,De=null;const Be=Le=>{try{const rt=Le.getBoundingClientRect();if(rt&&isFinite(rt.height)){const En=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 480px)").matches?85:Math.round(rt.height);document.body.style.setProperty("--poker-header-height",`${En}px`)}}catch{}},Fe=()=>{if(lA||typeof document>"u")return;const Le=document.querySelector(".card-header.card-header--two-rows");if(Le){St.current=Le;try{LA=new ResizeObserver(()=>Be(Le)),LA.observe(Le)}catch{De=()=>Be(Le),window.addEventListener("resize",De)}Be(Le)}};if(Fe(),!St.current)try{ae=window.setTimeout(Fe,0)}catch{}return()=>{lA=!0;try{document.body.style.removeProperty("--poker-header-height")}catch{}if(LA)try{LA.disconnect()}catch{}if(De){try{window.removeEventListener("resize",De)}catch{}De=null}if(ae!=null){try{clearTimeout(ae)}catch{}ae=null}}},[]);const Te=ue.useCallback(lA=>{var LA;try{const De=document.body.querySelector(`li.player--avatar[data-player-id="${lA}"]`),Fe=(LA=(De==null?void 0:De.querySelector(".avatar-ring"))||De)==null?void 0:LA.getBoundingClientRect();return Fe?{x:Fe.left+Fe.width/2,y:Fe.top+Fe.height/2}:null}catch{return null}},[]),gt=ue.useCallback(()=>{try{const lA=EA.current;if(!lA)return null;const LA=lA.querySelectorAll(".poker-pot-stack");if(!LA||LA.length===0){const Le=lA.getBoundingClientRect();return Le?{x:Le.left+Le.width/2,y:Le.top+Le.height/2}:null}let ae=1/0,De=1/0,Be=-1/0,Fe=-1/0;return LA.forEach(Le=>{const rt=Le.getBoundingClientRect();rt&&(ae=Math.min(ae,rt.left),De=Math.min(De,rt.top),Be=Math.max(Be,rt.right),Fe=Math.max(Fe,rt.bottom))}),!isFinite(ae)||!isFinite(De)||!isFinite(Be)||!isFinite(Fe)?null:{x:(ae+Be)/2,y:(De+Fe)/2}}catch{return null}},[]);E.useEffect(()=>{q(()=>{var lA;try{const LA=O||[];if(!LA.length)return;Xe.current=Date.now();const ae=gt();if(!ae)return;const De=[],Be=Number(CA||((lA=U==null?void 0:U.gameState)==null?void 0:lA.pokerRoundSeq)||0)||Date.now();if(Be&&rA.current===Be)return;LA.forEach((Fe,Le)=>{const rt=Te(Fe.playerId);rt&&De.push({id:`poker-pot-${Be}-${Le}`,amount:Math.max(1,Number(Fe.amount||0)),fromId:"pot",toId:Fe.playerId,startX:ae.x,startY:ae.y,endX:rt.x,endY:rt.y})}),De.length&&(rA.current=Be,BA.current=Be,j.current=De.length,DA(Fe=>[...Fe,...De]),He(!1))}catch{}})},[O,CA,U==null?void 0:U.gameState]),E.useEffect(()=>{var Fe;const lA=(Fe=U==null?void 0:U.gameState)==null?void 0:Fe.pokerPhase,LA=Array.isArray(O)&&O.length>0&&lA!=="pre-flop"?O.map(Le=>String(Le.playerId)):[],ae=TA.current,De=new Set(LA),Be=(Le,rt)=>{try{const ft=document.querySelector(`li.player--avatar[data-player-id="${Le}"]`);ft&&(rt?ft.classList.add("player--winner-shake"):ft.classList.remove("player--winner-shake"))}catch{}};return ae.forEach(Le=>{De.has(Le)||Be(Le,!1)}),De.forEach(Le=>{ae.has(Le)||Be(Le,!0)}),TA.current=De,()=>{TA.current.forEach(Le=>Be(Le,!1)),TA.current.clear()}},[O,U==null?void 0:U.gameState]),E.useEffect(()=>{try{window.__pokerRoomMounted=Date.now()}catch{}},[]),E.useEffect(()=>()=>{if(dt.current.forEach(lA=>clearTimeout(lA)),dt.current=[],Ht.current&&(clearTimeout(Ht.current),Ht.current=null),P.current!=null&&(clearTimeout(P.current),P.current=null),tA.current!=null&&(clearTimeout(tA.current),tA.current=null),L.current!=null){try{clearTimeout(L.current)}catch{}L.current=null}iA.current=null;try{const lA=String(e||"");if(lA&&$.current&&$.current.length===2){const LA=(U==null?void 0:U.gameState)||{},ae=Number((LA==null?void 0:LA.pokerRoundSeq)||PA.current||0)||0;K0[lA]={myHole:$.current.slice(),roundSeq:ae,first:!!gA,both:!!sA,ts:Date.now()};try{const De=window;De&&(De.__pokerHoleDiag=De.__pokerHoleDiag||[],De.__pokerHoleDiag.push({kind:"persist_hole_on_unmount",at:Date.now(),round:ae}))}catch{}}}catch{}},[]),E.useEffect(()=>{const lA=String(e||"");if(lA)try{const LA=K0[lA];if(!LA)return;if(!(Date.now()-(LA.ts||0)<3e4)){delete K0[lA];return}if(Array.isArray(LA.myHole)&&LA.myHole.length===2){aA(LA.myHole.slice()),PA.current=Number(LA.roundSeq||0)||PA.current||0,LA.first&&yA(!0),LA.both&&pA(!0);try{const De=window;De&&(De.__pokerHoleDiag=De.__pokerHoleDiag||[],De.__pokerHoleDiag.push({kind:"restore_persisted_hole_on_mount",at:Date.now(),round:LA.roundSeq}))}catch{}}}catch{}},[e]);function Qt(lA){if(!lA||typeof lA.category!="number")return;const LA=lA.category|0,ae=Array.isArray(lA.tiebreak)?lA.tiebreak:[],De=Fe=>"23456789TJQKA"[Math.max(0,Math.min(12,Fe))]||"?",Be=Fe=>({2:"Deuce",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine",T:"Ten",J:"Jack",Q:"Queen",K:"King",A:"Ace"})[De(Fe)]||De(Fe);switch(LA){case 8:return`Straight Flush (${Be(ae[0]??0)} high)`;case 7:return`Four of a Kind (${Be(ae[0]??0)}s)`;case 6:return`Full House (${Be(ae[0]??0)}s over ${Be(ae[1]??0)}s)`;case 5:return`Flush (${[ae[0],ae[1],ae[2],ae[3],ae[4]].filter(Fe=>Fe!=null).map(Fe=>De(Fe)).join("")})`;case 4:return`Straight (${Be(ae[0]??0)} high)`;case 3:return`Three of a Kind (${Be(ae[0]??0)}s)`;case 2:return`Two Pair (${Be(ae[0]??0)}s & ${Be(ae[1]??0)}s)`;case 1:return`One Pair (${Be(ae[0]??0)}s)`;default:return`High Card (${Be(ae[0]??0)})`}}E.useEffect(()=>{if(!e)return;let lA=!1;const LA=m,ae=t;return(async()=>{if(oe.current!==e&&!(U&&U.id===e))try{const De=FY[e]||(async()=>LA(e))();FY[e]=De;const Be=await De;if(!lA&&(Be!=null&&Be.ok)){oe.current=e,x(Be.room);try{s&&me.current!==e&&(await Promise.resolve(s(e)),me.current=e)}catch(Fe){console.warn("[poker] RTC join failed",Fe)}try{await ae()}catch{}}else if(!lA&&Be&&!Be.ok)try{K("Poker",Be.error||"Failed to join room")}catch{}}catch(De){console.warn("[poker] join failed",De)}finally{delete FY[e]}})(),()=>{lA=!0,oe.current===e&&(oe.current=null),a&&me.current===e&&(me.current=null,a().catch(()=>{}))}},[e]);const _e=ue.useCallback((lA,LA)=>{if(!lA||lA.id&&(LA!=null&&LA.id)&&lA.id!==LA.id)return LA;try{const ae=Array.isArray(lA.players)?lA.players:[],De=Array.isArray(LA==null?void 0:LA.players)?LA.players:[];if(De.length===0&&ae.length>0)return{...lA,...LA,players:ae};const Be=De.map(Fe=>{const Le=ae.find(rt=>String(rt.id)===String(Fe.id));return Le?{...Le,...Fe}:Fe});return{...lA,...LA,players:Be}}catch{return LA||lA}},[]);Os({onJoinedRoom:({room:lA})=>{try{if(lA&&lA.id===e){x(LA=>LA&&LA.id===lA.id?_e(LA,lA):lA),oe.current=e||null;try{const LA=lA==null?void 0:lA.gameState;if(!Z.current&&LA&&typeof LA.pokerPhase=="string"&&LA.pokerPhase.length>0){z(!0);const ae=LA.pokerPhase;ae&&ae!=="pre-flop"&&ae!=="waiting"&&RA(!1)}}catch{}}}catch{}},onRejoinedRoom:({room:lA})=>{try{if(lA&&lA.id===e){x(LA=>LA&&LA.id===lA.id?_e(LA,lA):lA),oe.current=e||null,RA(!1);try{const LA=lA==null?void 0:lA.gameState;!Z.current&&LA&&typeof LA.pokerPhase=="string"&&LA.pokerPhase.length>0&&z(!0)}catch{}}}catch{}},onOtherPlayerJoined:({room:lA})=>{try{lA&&lA.id===e&&x(LA=>LA&&LA.id===lA.id?_e(LA,lA):lA)}catch{}},onOtherLeft:({room:lA})=>{try{lA&&lA.id===e&&x(LA=>LA&&LA.id===lA.id?_e(LA,lA):lA)}catch{}},onPlayerBalanceUpdated:({playerId:lA,balance:LA})=>{x(ae=>{if(!ae||!Array.isArray(ae.players))return ae;const De=ae.players.findIndex(Le=>String(Le.id)===String(lA));if(De===-1)return ae;const Be=ae.players.slice(),Fe=Be[De];return typeof(Fe==null?void 0:Fe.balance)=="number"&&Fe.balance===LA?ae:(Be[De]={...Fe,balance:LA},{...ae,players:Be})})},onPokerMyBalance:({roomId:lA,seatIndex:LA,stack:ae,committed:De})=>{lA===e&&x(Be=>{if(!Be||!Be.gameState)return Be;const Fe=Array.isArray(Be.gameState.pokerSeats)?[...Be.gameState.pokerSeats]:[],Le=Fe.findIndex(ft=>(ft==null?void 0:ft.seatIndex)===LA);if(Le===-1)return Be;const rt=Fe[Le];return rt.stack===ae&&rt.committed===De?Be:(Fe[Le]={...rt,stack:ae,committed:De},{...Be,gameState:{...Be.gameState,pokerSeats:Fe}})})},onRoomUpdateState:lA=>{var Be,Fe,Le,rt,ft,En,rg,qn,Ig,Us,ao,Yn,Qn,Ng,po,mi;if(!lA||lA.roomId!==e)return;if(console.log("[poker] onRoomUpdateState",{roomId:lA.roomId,phase:(Fe=(Be=lA==null?void 0:lA.room)==null?void 0:Be.gameState)==null?void 0:Fe.pokerPhase,roundSeq:(rt=(Le=lA==null?void 0:lA.room)==null?void 0:Le.gameState)==null?void 0:rt.pokerRoundSeq,seatCount:(rg=(En=(ft=lA==null?void 0:lA.room)==null?void 0:ft.gameState)==null?void 0:En.pokerSeats)==null?void 0:rg.length,hasMyHole:!!(lA!=null&&lA.myHole&&Array.isArray(lA.myHole)&&lA.myHole.length===2)}),lA.myHole&&Array.isArray(lA.myHole)&&lA.myHole.length===2){const Di=Number(((Ig=(qn=lA==null?void 0:lA.room)==null?void 0:qn.gameState)==null?void 0:Ig.pokerRoundSeq)||0);if(!$.current||$.current.length!==2||PA.current&&PA.current!==Di){aA(lA.myHole),Di>0&&(PA.current=Di),H.current=Date.now();try{const un=typeof window<"u"?window:void 0;un&&(un.__pokerHoleDiag=un.__pokerHoleDiag||[],un.__pokerHoleDiag.push({kind:"hole_from_state",at:Date.now(),round:Di}))}catch{}const Si=(ao=(Us=lA==null?void 0:lA.room)==null?void 0:Us.gameState)==null?void 0:ao.pokerPhase;!qA.current&&Si!=="pre-flop"&&(yA(!0),setTimeout(()=>pA(!0),180))}}x(Di=>{try{const Si=lA==null?void 0:lA.room,un=Si==null?void 0:Si.gameState;if(!Di||Di.id&&Di.id!==lA.roomId)return Si&&Si.id===lA.roomId?Si:Di;let xi=un?{...Di,gameState:un}:{...Di};return Si&&Si.id===Di.id&&(xi=_e(xi,Si),un&&(xi.gameState=un)),xi}catch{return Di}});try{const Di=(Yn=lA==null?void 0:lA.room)==null?void 0:Yn.gameState;!Z.current&&Di&&typeof Di.pokerPhase=="string"&&Di.pokerPhase.length>0&&z(!0)}catch{}const LA=(Ng=(Qn=lA==null?void 0:lA.room)==null?void 0:Qn.gameState)==null?void 0:Ng.pokerPhase,ae=Number(((mi=(po=lA==null?void 0:lA.room)==null?void 0:po.gameState)==null?void 0:mi.pokerRoundSeq)||0),De=ZA.current;if(ZA.current=LA,(LA||"")==="pre-flop"){const Di=ae>0&&ae!==ie.current&&ae!==he.current,Si=!De||["waiting","showdown","complete"].includes(String(De));if(Di&&Si){if(pA(!1),yA(!1),$.current&&$.current.length===2)if(PA.current===0){PA.current=ae;try{const xi=typeof window<"u"?window:void 0;xi&&(xi.__pokerHoleDiag=xi.__pokerHoleDiag||[],xi.__pokerHoleDiag.push({kind:"assign_hole_round_on_preflop",at:Date.now(),round:ae}))}catch{}}else if(PA.current!==ae){aA(null);try{const xi=String(e||"");xi&&delete K0[xi]}catch{}try{const xi=typeof window<"u"?window:void 0;xi&&(xi.__pokerHoleDiag=xi.__pokerHoleDiag||[],xi.__pokerHoleDiag.push({kind:"clear_hole_new_round",at:Date.now(),toRound:ae,prevHoleRound:PA.current}))}catch{}}else try{const xi=typeof window<"u"?window:void 0;xi&&(xi.__pokerHoleDiag=xi.__pokerHoleDiag||[],xi.__pokerHoleDiag.push({kind:"keep_hole_new_round",at:Date.now(),round:ae}))}catch{}else PA.current=0;he.current=ae,Ft.current=Date.now(),IA(ae);try{mS(["cardSwoosh"])}catch{}const un=FA.current!==ae;un&&(FA.current=ae),(async()=>{if(await kF(["cardSwoosh"],900),RA(!0),un)try{$P({volume:.6})}catch{}})()}else if(Di&&!Si)try{const un=window;un&&(un.__pokerHoleDiag=un.__pokerHoleDiag||[],un.__pokerHoleDiag.push({kind:"skip_preflop_midhand",at:Date.now(),round:ae,prevPhase:De}))}catch{}_A(0),X([]),cA([]),He(!0)}else if((LA||"")==="waiting"){if(pA(!1),yA(!1),RA(!1),L.current!=null){try{clearTimeout(L.current)}catch{}L.current=null}IA(Di=>Di+1),he.current=0,$.current||(PA.current=0);try{const Di=String(e||"");Di&&!$.current&&delete K0[Di]}catch{}}},onPokerMyHole:lA=>{var LA,ae,De;if(!(!lA||lA.roomId!==e)&&Array.isArray(lA.hole)&&lA.hole.length===2){aA(lA.hole);try{const Le=(U==null?void 0:U.gameState)||{},rt=Number((Le==null?void 0:Le.pokerRoundSeq)||0);rt>0&&(PA.current=rt)}catch{}H.current=Date.now();try{const Le=typeof window<"u"?window:void 0;Le&&(Le.__pokerHoleDiag=Le.__pokerHoleDiag||[],Le.__pokerHoleDiag.push({kind:"hole",at:Date.now(),phase:(LA=U==null?void 0:U.gameState)==null?void 0:LA.pokerPhase,dealing:qA.current,round:Number(((ae=U==null?void 0:U.gameState)==null?void 0:ae.pokerRoundSeq)||0)}))}catch{}const Fe=(((De=U==null?void 0:U.gameState)==null?void 0:De.pokerPhase)||"")==="pre-flop";if(Z.current)if(!fA&&!Fe)yA(!0),setTimeout(()=>pA(!0),180);else{if(L.current!=null){try{clearTimeout(L.current)}catch{}L.current=null}try{L.current=window.setTimeout(()=>{if(W.current||!$.current||$.current.length!==2)return;const Le=Date.now();if(qA.current&&Le-(H.current||Le)>3e3&&RA(!1),!Z.current&&Le-(H.current||Le)<4e3){try{L.current=window.setTimeout(()=>{},500)}catch{}return}yA(!0),pA(!0);try{const ft=typeof window<"u"?window:void 0;ft&&(ft.__pokerHoleDiag=ft.__pokerHoleDiag||[],ft.__pokerHoleDiag.push({kind:"fallback_reveal",at:Le}))}catch{}},1800)}catch{}}}},onPokerRevealAll:lA=>{var De,Be,Fe;if(!lA||lA.roomId!==e)return;const LA=Number((lA==null?void 0:lA.roundSeq)||0),ae=Number(((De=U==null?void 0:U.gameState)==null?void 0:De.pokerRoundSeq)||0);if(LA&&ae){const Le=LA===ae,rt=ae===LA+1;if(!Le&&!rt)return}if(!(CA&&CA===LA)&&Array.isArray(lA.hands)){X(lA.hands.filter(rt=>Array.isArray(rt==null?void 0:rt.hole)&&rt.hole.length===2)),_A(LA||ae||Date.now());const Le=Array.isArray(O)&&O.length>0?O:[];if((LA||ae)&&Le.length>0){const rt=Number(LA||ae),En=Le.reduce((rg,qn)=>rg+(Number(qn.amount)||0),0)||Number(((Fe=(Be=U==null?void 0:U.gameState)==null?void 0:Be.wagerPool)==null?void 0:Fe.totalAmount)||0)||0;jA(rg=>{var Us;const qn=rg.findIndex(ao=>ao.roundSeq===rt),Ig={roundSeq:rt,ts:Date.now(),winners:Le.slice(),hands:(lA.hands||[]).slice(),pot:En,seats:Array.isArray((Us=U==null?void 0:U.gameState)==null?void 0:Us.pokerSeats)?U.gameState.pokerSeats.map(ao=>{var Yn,Qn;return{playerId:ao.playerId,seatIndex:ao.seatIndex,status:ao.status,rank:((Yn=Le.find(Ng=>Ng.playerId===ao.playerId))==null?void 0:Yn.rank)||void 0,winnings:(Qn=Le.find(Ng=>Ng.playerId===ao.playerId))==null?void 0:Qn.amount}}):void 0};if(qn>=0){const ao=rg.slice();return ao[qn]=Ig,ao}return[...rg,Ig].slice(-20)})}}},onPokerWinners:lA=>{var Be,Fe,Le,rt,ft,En,rg,qn,Ig,Us,ao;if(!lA||lA.roomId!==e)return;const LA=Number((lA==null?void 0:lA.roundSeq)||0),ae=Number(((Be=U==null?void 0:U.gameState)==null?void 0:Be.pokerRoundSeq)||0);if(LA&&ae){const Yn=LA===ae,Qn=ae===LA+1;if(!Yn&&!Qn)return}CA&&CA===LA?cA(Yn=>Yn.length?Yn:Array.isArray(lA.winners)?lA.winners:[]):(cA(Array.isArray(lA.winners)?lA.winners:[]),CA||_A(LA||ae||Date.now()));try{const Yn=Number(LA||ae||0)||0;if(Yn&&le.current!==Yn){const Qn=Array.isArray(lA.winners)?lA.winners:[],po=Qn.slice().sort((Si,un)=>String(Si.playerId).localeCompare(String(un.playerId))).map(Si=>`${Si.playerId}:${Number(Si.amount)||0}:${Number(Si.seatIndex)||0}:${Si.rank&&Number(Si.rank.category)||-1}`).join("|"),mi=typeof window<"u"?window:void 0,Di=mi&&mi.__pokerWinnersFlashGuard;if(!Di||Di.roundSeq!==Yn||Di.content!==po){const Si=Qn.find(ro=>ro&&ro.rank&&typeof ro.rank.category=="number"),un=Qt(Si==null?void 0:Si.rank),Ho=Qn.reduce((ro,Bl)=>ro+(Number(Bl.amount)||0),0)||Number(((Le=(Fe=U==null?void 0:U.gameState)==null?void 0:Fe.wagerPool)==null?void 0:Le.totalAmount)||0)||0,uc=Ho>0?`Pot: z${Ho}`:void 0,Ea=[un,uc].filter(Boolean).join(" ");mi&&(mi.__pokerWinnersFlashGuard={roundSeq:Yn,content:po,at:Date.now()});try{mi&&(mi.__pokerWinnersFlashed=!0)}catch{}const CC=String((A==null?void 0:A.id)??(A==null?void 0:A.email)??"");if(Qn.some(ro=>String(ro.playerId)===CC)){const ro=Qn.find(Ir=>String(Ir.playerId)===CC),Bl=Number((ro==null?void 0:ro.amount)||0),EQ=Bl>0?`You won: z${Bl}`:"You won!";try{v({kind:"win",title:EQ,subtitle:Ea,duration:4e3})}catch{}try{A1()}catch{}try{mi&&(mi.__E2E===!0||(((rt=mi.location)==null?void 0:rt.search)||"").includes("e2e=1"))&&(mi.__pokerWinnersFlashed={title:EQ,subtitle:Ea,roundSeq:Yn,at:Date.now(),__viaServer:!0})}catch{}try{const Ir=((ft=ro==null?void 0:ro.rank)==null?void 0:ft.category)??((En=Si==null?void 0:Si.rank)==null?void 0:En.category),El=((rg=ro==null?void 0:ro.rank)==null?void 0:rg.tiebreak)??((qn=Si==null?void 0:Si.rank)==null?void 0:qn.tiebreak)??[];typeof Ir=="number"?Ir===8&&El[0]===12?Q("royal-flush",{displayMs:4e3}):Ir===8?Q("straight-flush",{displayMs:3500}):Ir===7?Q("quads",{displayMs:3e3}):Ir===6?Q("full-house",{displayMs:2500}):Ir===5?Q("flush",{displayMs:2500}):Ir===4&&Q("straight",{displayMs:2500}):Qn.length===1&&!Si&&Q("poker-bluff",{displayMs:2500})}catch{}}le.current=Yn}}}catch{}try{const Yn=String((A==null?void 0:A.id)??(A==null?void 0:A.email)??""),Qn=Array.isArray(lA.winners)?lA.winners:[];if(!Qn.some(po=>String(po.playerId)===Yn)){let po=0;const Di=(Array.isArray((Ig=U==null?void 0:U.gameState)==null?void 0:Ig.pokerSeats)?U.gameState.pokerSeats:[]).find(Ea=>String(Ea.playerId||"")===Yn),Si=Number((Di==null?void 0:Di.committed)||0),un=Number((Di==null?void 0:Di.returned)||0);Si>0&&(po=Math.max(0,Si-(Number.isFinite(un)?un:0)));const xi=Qn.find(Ea=>Ea&&Ea.rank&&typeof Ea.rank.category=="number"),Ho=xi?`Winner: ${Qt(xi.rank)}`:void 0,uc=po>0?`You lost: z${po}`:"You lost";try{q(()=>{try{v({kind:"lose",title:uc,subtitle:Ho})}catch{}try{e1()}catch{}try{Q(y(),{displayMs:2e3})}catch{}})}catch{}}}catch{}try{const Yn=Number(LA||ae||0);Yn&&UA.current!==Yn&&(UA.current=Yn,dA(!0),setTimeout(()=>dA(!1),5200))}catch{}const De=Array.isArray(uA)&&uA.length>0?uA:[];if((LA||ae)&&De.length>0){const Yn=Number(LA||ae),Qn=Array.isArray(lA.winners)?lA.winners:[],po=Qn.reduce((mi,Di)=>mi+(Number(Di.amount)||0),0)||Number(((ao=(Us=U==null?void 0:U.gameState)==null?void 0:Us.wagerPool)==null?void 0:ao.totalAmount)||0)||0;jA(mi=>{var un;const Di=mi.findIndex(xi=>xi.roundSeq===Yn),Si={roundSeq:Yn,ts:Date.now(),winners:Qn.slice(),hands:De.slice(),pot:po,seats:Array.isArray((un=U==null?void 0:U.gameState)==null?void 0:un.pokerSeats)?U.gameState.pokerSeats.map(xi=>{var Ho,uc;return{playerId:xi.playerId,seatIndex:xi.seatIndex,status:xi.status,rank:((Ho=Qn.find(Ea=>Ea.playerId===xi.playerId))==null?void 0:Ho.rank)||void 0,winnings:(uc=Qn.find(Ea=>Ea.playerId===xi.playerId))==null?void 0:uc.amount}}):void 0};if(Di>=0){const xi=mi.slice();return xi[Di]=Si,xi}return[...mi,Si].slice(-20)})}try{n()}catch{}},onPokerTimedOut:lA=>{try{if(!lA||lA.roomId!==e)return;const LA=String((A==null?void 0:A.id)??(A==null?void 0:A.email)??"");if(lA.playerId!==LA)return;const ae=lA.action==="check"?"auto-check":"auto-fold";Hw(`🕒 Timed out — ${ae}`)}catch{}}}),E.useEffect(()=>{if(!i||!e)return;const lA=De=>{De.roomId===e&&(console.log("[poker] start_ready_update",De),li(De.readyPlayers||[]),ai(De.requiredPlayers||[]),De.allReady&&(ee(!1),$e(0)))},LA=De=>{De.roomId===e&&(console.log("[poker] start_countdown",De),$e(De.endsAt),li(De.readyPlayers||[]),ai(De.requiredPlayers||[]))},ae=De=>{De.roomId===e&&(console.log("[poker] start_countdown_cancelled",De),$e(0),ke(0))};return i.on("poker:start_ready_update",lA),i.on("poker:start_countdown",LA),i.on("poker:start_countdown_cancelled",ae),()=>{i.off("poker:start_ready_update",lA),i.off("poker:start_countdown",LA),i.off("poker:start_countdown_cancelled",ae)}},[i,e]),E.useEffect(()=>{if(!i||!e)return;const lA=Be=>{(Be==null?void 0:Be.roomId)===e&&(console.log("[poker:elimination] update",Be),Be.config&&VA({enabled:!0,startingShields:Be.config.startingShields??3,maxTokens:Be.config.maxTokens??3}),Be.states&&vA(Be.states),Be.eliminatedOrder&&WA(Be.eliminatedOrder))},LA=Be=>{if((Be==null?void 0:Be.roomId)!==e)return;console.log("[poker:elimination] eliminated",Be);const Fe=Be.place??"";if(Be.playerId===Qe)try{v({kind:"lose",title:"Eliminated!",subtitle:`You finished in ${PtA(Fe)} place`,duration:4e3})}catch{}},ae=Be=>{var Fe,Le;if((Be==null?void 0:Be.roomId)===e&&(console.log("[poker:elimination] player_eliminated",Be),Be.playerId&&Be.playerId!==Qe)){const rt=((Le=(Fe=U==null?void 0:U.players)==null?void 0:Fe.find(ft=>ft.id===Be.playerId))==null?void 0:Le.name)||"A player";it({text:`${rt} eliminated!`,sub:Be.place?`${PtA(Be.place)} place`:void 0}),setTimeout(()=>it(null),3e3)}},De=Be=>{if((Be==null?void 0:Be.roomId)===e){console.log("[poker:elimination] gameover",Be),pe({winner:Be.winner,eliminatedOrder:Be.eliminatedOrder||[],finalStates:Be.finalStates||{}});try{Be.winner===Qe?A1():e1()}catch{}}};return i.on("poker:elimination_update",lA),i.on("poker:eliminated",LA),i.on("poker:player_eliminated",ae),i.on("poker:elimination_gameover",De),()=>{i.off("poker:elimination_update",lA),i.off("poker:eliminated",LA),i.off("poker:player_eliminated",ae),i.off("poker:elimination_gameover",De)}},[i,e,Qe,U==null?void 0:U.players]);const Ze=ue.useRef(0);E.useEffect(()=>{if(!i||!Qe)return;const lA=LA=>{var ae;!LA||((ae=LA.winner)==null?void 0:ae.userId)!==Qe||(console.log("[poker] last man standing (server event)",{meId:Qe,bonus:LA.bonus}),re({winnerUserId:Qe,bonus:LA.bonus??0}))};return i.on("poker:last_man_standing",lA),()=>{i.off("poker:last_man_standing",lA)}},[i,Qe]),E.useEffect(()=>{const lA=U==null?void 0:U.gameState;if(!lA||!Qe)return;const LA=lA.pokerPhase;if(LA!=="complete"&&LA!=="waiting")return;const ae=Array.isArray(lA.pokerSeats)?lA.pokerSeats.filter(Fe=>!!(Fe!=null&&Fe.playerId)):[],De=ae.filter(Fe=>(Fe.stack??0)>0);if(De.length!==1||De[0].playerId!==Qe)return;const Be=Number(lA.pokerRoundSeq||0);Be<=0||Be===Ze.current||(Ze.current=Be,console.log("[poker] last man standing detected (client)",{meId:Qe,roundSeq:Be,phase:LA,totalSeats:ae.length,aliveSeats:De.length}),re({winnerUserId:Qe,bonus:0}))},[U==null?void 0:U.gameState,Qe]),E.useEffect(()=>{if(!be||be<=Date.now()){ke(0);return}const lA=()=>{const ae=Math.max(0,Math.ceil((be-Date.now())/1e3));ke(ae),ae<=0&&$e(0)};lA();const LA=setInterval(lA,1e3);return()=>clearInterval(LA)},[be]);const at=ue.useRef("waiting");E.useEffect(()=>{var Be;const lA=((Be=U==null?void 0:U.gameState)==null?void 0:Be.pokerPhase)||"waiting",LA=at.current;at.current=lA;const ae=!["waiting","complete"].includes(lA),De=!["waiting","complete"].includes(LA);return(ae||lA==="waiting"&&De)&&(li([]),ai([]),$e(0),ke(0),ee(!1)),De&&!ae?(Re(!0),clearTimeout(ot.current),ot.current=setTimeout(()=>Re(!1),1500)):ae&&(clearTimeout(ot.current),Re(!1)),()=>clearTimeout(ot.current)},[(ar=U==null?void 0:U.gameState)==null?void 0:ar.pokerPhase]),E.useEffect(()=>{const lA=U==null?void 0:U.gameState;if(!lA)return;const LA=lA==null?void 0:lA.pokerPhase,ae=Number((lA==null?void 0:lA.pokerRoundSeq)||0);if((LA||"")==="pre-flop"&&ae>0&&ae!==ie.current&&ae!==he.current){if(console.log("[poker] triggering initial dealing animation for roundSeq",ae),pA(!1),yA(!1),$.current&&$.current.length===2)if(PA.current===0){PA.current=ae;try{const Be=typeof window<"u"?window:void 0;Be&&(Be.__pokerHoleDiag=Be.__pokerHoleDiag||[],Be.__pokerHoleDiag.push({kind:"assign_hole_round_on_initial_preflop",at:Date.now(),round:ae}))}catch{}}else if(PA.current!==ae){aA(null);try{const Be=typeof window<"u"?window:void 0;Be&&(Be.__pokerHoleDiag=Be.__pokerHoleDiag||[],Be.__pokerHoleDiag.push({kind:"clear_hole_initial_preflop",at:Date.now(),toRound:ae,prevHoleRound:PA.current}))}catch{}}else try{const Be=typeof window<"u"?window:void 0;Be&&(Be.__pokerHoleDiag=Be.__pokerHoleDiag||[],Be.__pokerHoleDiag.push({kind:"keep_hole_initial_preflop",at:Date.now(),round:ae}))}catch{}else PA.current=0;he.current=ae,Ft.current=Date.now(),IA(ae);try{mS(["cardSwoosh"])}catch{}const De=FA.current!==ae;De&&(FA.current=ae),(async()=>{if(await kF(["cardSwoosh"],900),RA(!0),De)try{$P({volume:.6})}catch{}})()}},[U==null?void 0:U.gameState]),ue.useEffect(()=>{var lA;try{const LA=typeof window<"u"?window:void 0;if(!(!!LA&&(LA.__E2E===!0||typeof((lA=LA.location)==null?void 0:lA.search)=="string"&&LA.location.search.includes("e2e=1")||LA.sessionStorage&&LA.sessionStorage.getItem("e2e")==="1")))return;const De=(e||"").startsWith("e2e-"),Be=!U||!U.gameState||!Array.isArray(U.gameState.pokerSeats);if(!De||!Be||NA.current)return;NA.current=!0;try{window.__pokerFallbackArmed=Date.now()}catch{}const Fe=setTimeout(()=>{try{const Le=Date.now()%1e5,rt={playerId:String(Qe||o||"hero"),seatIndex:0,amount:120,rank:{category:1,tiebreak:[12,7,5,4,2]}},ft=[{playerId:String(Qe||o||"hero"),seatIndex:0,hole:["Ah","Ad"]},{playerId:"bot1",seatIndex:1,hole:["Kc","Qs"]},{playerId:"bot2",seatIndex:2,hole:["9h","9s"]},{playerId:"bot3",seatIndex:3,hole:["7d","6d"]}];cA([rt]),X(ft),_A(Le);const En=`You: +z${Number(rt.amount||0)}`,rg=`Pot: z${Number(rt.amount||0)}`,qn=`${Qt(rt.rank)} ${rg}`;try{window.__pokerWinnersFlashed={title:En,subtitle:qn,roundSeq:Le,at:Date.now(),__fallback:!0}}catch{}try{window.__pokerFallbackFired=Date.now()}catch{}}catch{}},5500);return()=>clearTimeout(Fe)}catch{}},[]),ue.useEffect(()=>{var lA;try{const LA=typeof window<"u"?window:void 0;if(!(!!LA&&(LA.__E2E===!0||typeof((lA=LA.location)==null?void 0:lA.search)=="string"&&LA.location.search.includes("e2e=1")||LA.sessionStorage&&LA.sessionStorage.getItem("e2e")==="1")))return;const De=setTimeout(()=>{try{if(window.__pokerWinnersFlashed)return;const Be=Date.now()%1e5,Fe={playerId:String(Qe||o||"hero"),seatIndex:0,amount:80,rank:{category:1,tiebreak:[11,9,6,4,2]}},Le=[{playerId:String(Qe||o||"hero"),seatIndex:0,hole:["As","Ad"]}];cA([Fe]),X(Le),_A(Be);const rt=`You: +z${Number(Fe.amount||0)}`,ft=`Pot: z${Number(Fe.amount||0)}`,En=`${Qt(Fe.rank)} ${ft}`;try{window.__pokerWinnersFlashed={title:rt,subtitle:En,roundSeq:Be,at:Date.now(),__safety:!0}}catch{}}catch{}},1e4);return()=>clearTimeout(De)}catch{}},[J,Qe,o]),E.useEffect(()=>{var ae;const lA=(ae=U==null?void 0:U.gameState)==null?void 0:ae.pokerPhase,LA=["flop","turn","river","showdown"].includes(lA||"");T&&LA&&eA&&eA.length===2&&!sA&&!fA&&(yA(!0),pA(!0))},[U==null?void 0:U.gameState,eA,sA,fA,T]),E.useEffect(()=>{var ae;const LA=(((ae=U==null?void 0:U.gameState)==null?void 0:ae.pokerPhase)||"")==="pre-flop";if(T&&LA&&!fA&&eA&&eA.length===2&&!sA){yA(!0);const De=setTimeout(()=>pA(!0),220);return()=>clearTimeout(De)}},[fA,U==null?void 0:U.gameState,eA,sA,T]),E.useEffect(()=>{if(!T||!eA||eA.length!==2||sA)return;const lA=setTimeout(()=>{!W.current&&$.current&&$.current.length===2&&(yA(!0),setTimeout(()=>pA(!0),180))},300);return()=>clearTimeout(lA)},[T,eA,sA]),E.useEffect(()=>()=>{PA.current=0},[]);const Ai=(U==null?void 0:U.name)||"Poker Room",Bi=E.useMemo(()=>(Array.isArray(U==null?void 0:U.players)?U.players:[]).map(LA=>({id:String(LA.id??""),name:String(LA.name||LA.email||LA.id||""),balance:typeof LA.balance=="number"?LA.balance:0,avatarUrl:LA.avatarUrl||void 0})),[U==null?void 0:U.players]),yi=ue.useRef(0),mt=E.useMemo(()=>{var rg,qn;if(!(U!=null&&U.singlePlayer))return;const lA=Array.isArray((rg=U==null?void 0:U.gameState)==null?void 0:rg.pokerSeats),LA=lA?U.gameState.pokerSeats:[],ae=new Set(LA.map(Ig=>String((Ig==null?void 0:Ig.playerId)??"")).filter(Ig=>Ig.startsWith("poker_bot_"))),De=new Set([...ae,...Bi.map(Ig=>Ig.id).filter(Ig=>Ig.startsWith("poker_bot_")),...Object.keys(nA).filter(Ig=>Ig.startsWith("poker_bot_"))]);yi.current=Math.max(yi.current,De.size);const Be=yi.current,Fe=Object.entries(nA).filter(([Ig,Us])=>Ig.startsWith("poker_bot_")&&(Us==null?void 0:Us.eliminated)).length,Le=lA?Math.max(Fe,Be-ae.size):Fe,rt=Number((U==null?void 0:U.spLevel)??(A==null?void 0:A.spLevelPoker)??1),ft=Number.isFinite(rt)&&rt>0?rt:1,En=(U==null?void 0:U.levelName)??((qn=nQ.find(Ig=>Ig.level===ft))==null?void 0:qn.name)??`Level ${ft}`;return{level:ft,levelName:En,current:Le,total:Be,progressLabel:`${Le}/${Be} bots eliminated`,goalLabel:`Eliminate every bot to reach Level ${ft+1}`,isMaxLevel:ft>=nQ.length}},[U==null?void 0:U.singlePlayer,U==null?void 0:U.gameState,U==null?void 0:U.spLevel,U==null?void 0:U.levelName,Bi,nA,A==null?void 0:A.spLevelPoker]);ue.useCallback((lA,LA)=>{var ae;return((ae=Bi.find(De=>De.id===lA))==null?void 0:ae.name)||`Seat ${LA+1}`},[Bi]);const ct=E.useMemo(()=>U!=null&&U.gameState?U.gameState:{gameMode:"poker",roundSeq:1},[U==null?void 0:U.gameState]);ige({gameState:ct,players:Bi,winners:O,hands:uA,meId:Qe});const[fi]=E.useState(()=>Date.now()),Yi=E.useMemo(()=>{var LA;const lA=(LA=U==null?void 0:U.gameState)==null?void 0:LA.pokerPhase;return lA==="pre-flop"||lA==="flop"||lA==="turn"||lA==="river"||lA==="showdown"},[U==null?void 0:U.gameState]),si=Number(((Fa=U==null?void 0:U.gameState)==null?void 0:Fa.pokerUiLockedUntilTs)||0),jt=si>0&&Date.now()<si,Zt=7e3,vi=ue.useRef(null);ue.useEffect(()=>{var LA;const lA=String(((LA=U==null?void 0:U.gameState)==null?void 0:LA.pokerPhase)||"");jt?vi.current==null&&(vi.current=Date.now()):lA==="waiting"&&(vi.current=null)},[jt,U==null?void 0:U.gameState]);const kn=vi.current??(Ft.current||0),gn=kn>0?Date.now()-kn:Number.POSITIVE_INFINITY,Ki=jt&&gn<=Zt,[,Tn]=ue.useReducer(lA=>lA+1,0);ue.useEffect(()=>{if(!jt)return;const lA=kn>0?kn+Zt:Number.POSITIVE_INFINITY,LA=si>0?si:Number.POSITIVE_INFINITY,ae=Math.min(lA,LA);if(!isFinite(ae))return;const De=Math.max(0,Math.min(15e3,Math.ceil(ae-Date.now()+2))),Be=window.setTimeout(()=>{try{Tn()}catch{}},De);return()=>{window.clearTimeout(Be)}},[jt,si,kn,Zt]);const fg=E.useMemo(()=>{const lA=(U==null?void 0:U.gameState)||{},LA=(lA==null?void 0:lA.pokerPhase)||"",ae=Array.isArray(lA==null?void 0:lA.pokerCommunity)?lA.pokerCommunity:[];return LA==="flop"?ae.length>=3&&![0,1,2].some(De=>nt.has(De)):LA==="turn"?ae.length>=4&&!nt.has(3):LA==="river"?ae.length>=5&&!nt.has(4):!0},[U==null?void 0:U.gameState,nt]),Zi=((rr=U==null?void 0:U.gameState)==null?void 0:rr.pokerPhase)||"",te=["showdown","complete"].includes(Zi),Eg=Date.now()-fi<800||!Yi||fA||Ki||!fg||te,{isBettingStreet:gi,isHeroTurn:Mg,heroStatus:Hg,toCall:de,canCheck:qe,canCall:OA,canBet:Ae,canRaise:Ke,showActions:Je,minRaiseTo:pt,currentBet:Tt,heroStack:vt,turnDeadlineTs:ei}=E.useMemo(()=>{const lA=(U==null?void 0:U.gameState)||{},LA=(lA==null?void 0:lA.pokerPhase)||"",ae=["pre-flop","flop","turn","river"].includes(LA),Be=(Array.isArray(lA==null?void 0:lA.pokerSeats)?lA.pokerSeats:[]).find(mi=>String(mi.playerId)===String(Qe)),Fe=typeof(lA==null?void 0:lA.pokerActingSeat)=="number"?lA.pokerActingSeat:void 0,Le=!!Be&&typeof Fe=="number"&&Be.seatIndex===Fe,rt=Number((lA==null?void 0:lA.pokerCurrentBet)||0),ft=Number((Be==null?void 0:Be.committed)||0),En=Number((Be==null?void 0:Be.stack)||0),rg=String((Be==null?void 0:Be.status)||"active"),qn=Math.max(0,rt-ft),Ig=qn===0&&rg==="active",Us=qn>0&&rg==="active"&&En>0,ao=rt===0&&rg==="active"&&En>0,Yn=rt>0&&rg==="active"&&En>0,Qn=ae&&!!Be&&rg==="active",Ng=Number((lA==null?void 0:lA.pokerMinRaiseTo)||0),po=Number((lA==null?void 0:lA.pokerTurnDeadlineTs)||0)||void 0;return{isBettingStreet:ae,isHeroTurn:Le,heroStatus:rg,toCall:qn,canCheck:Ig,canCall:Us,canBet:ao,canRaise:Yn,showActions:Qn,minRaiseTo:Ng,currentBet:rt,heroStack:En,turnDeadlineTs:po}},[U==null?void 0:U.gameState,Qe]),Vt=Eg||!Mg||Hg!=="active",[hA,Re]=E.useState(!1),ot=ue.useRef(void 0),kt=E.useMemo(()=>{const lA=(U==null?void 0:U.gameState)||{},LA=(lA==null?void 0:lA.pokerPhase)||"waiting",ae=Array.isArray(lA==null?void 0:lA.pokerSeats)?lA.pokerSeats:[];return["waiting","complete"].includes(LA)&&ae.length>=2&&!fA&&!Ki&&!!e&&!g&&!hA},[U==null?void 0:U.gameState,fA,Ki,e,g,hA]),[ht,ee]=E.useState(!1),je=E.useMemo(()=>{if(!e||!(U!=null&&U.singlePlayer))return!1;const lA=(U==null?void 0:U.gameState)||{},LA=(lA==null?void 0:lA.pokerPhase)||"waiting";if(LA!=="waiting"&&LA!=="complete")return!1;const ae=Array.isArray(lA==null?void 0:lA.pokerSeats)?lA.pokerSeats.filter(Be=>!!(Be!=null&&Be.playerId)):[],De=ae.find(Be=>String(Be.playerId||"")===Qe);return!!(ae.length<=1&&De||!De||De&&Number(De.stack||0)===0)},[U==null?void 0:U.gameState,U==null?void 0:U.singlePlayer,e,Qe]),[Ct,At]=E.useState(!1),[zt,li]=E.useState([]),[Ei,ai]=E.useState([]),Hi=E.useMemo(()=>zt.includes(Qe),[zt,Qe]),gg=ue.useCallback(()=>{P.current!=null&&(clearTimeout(P.current),P.current=null),tA.current!=null&&(clearTimeout(tA.current),tA.current=null),iA.current=null},[]),[yn,Rs]=E.useState(0),qo=yn,[eg,Gs]=E.useState(!1),[bs,Wg]=E.useState(null),Vg=Qe,rC=!!Yi&&!fA&&!(Array.isArray(uA)&&uA.length>0),[sr,UB]=E.useState({active:!1,key:0,indices:[]}),pI=ue.useRef(0);E.useEffect(()=>{var De;const LA=(Array.isArray((De=U==null?void 0:U.gameState)==null?void 0:De.pokerCommunity)?U.gameState.pokerCommunity:[]).length,ae=pI.current;if(LA>ae){const Be=Array.from({length:LA-ae},(Fe,Le)=>ae+Le);Ut(Fe=>{const Le=new Set(Fe);return Be.forEach(rt=>Le.add(rt)),Le}),Ht.current&&(clearTimeout(Ht.current),Ht.current=null),Ht.current=window.setTimeout(()=>{UB({active:!0,key:Date.now(),indices:Be}),Ht.current=null},3e3),pI.current=LA}else pI.current=LA},[U==null?void 0:U.gameState]),ue.useEffect(()=>{const lA=se.current;if(!lA)return;lA.style.marginTop=lA.style.marginTop==="0px"?"0.01px":"0px";const LA=window.setTimeout(()=>{lA&&(lA.style.marginTop="")},0);return()=>window.clearTimeout(LA)},[fA,sA,gA,eg]);const fI=(lA,LA)=>{!lA&&LA&&K("Poker",LA)},vB=async()=>{if(!e)return;gg();const lA=await N(e);fI(lA==null?void 0:lA.ok,lA==null?void 0:lA.error)},Ps=async()=>{if(!e)return;gg();const lA=await G(e);fI(lA==null?void 0:lA.ok,lA==null?void 0:lA.error)},ll=async()=>{if(!e)return;gg();const lA=await k(e);fI(lA==null?void 0:lA.ok,lA==null?void 0:lA.error)},Pd=()=>{Vt||!Ae||(Wg("bet"),Gs(!0))},KB=()=>{Vt||!Ke||(Wg("raise"),Gs(!0))},jd=async lA=>{if(!e||!bs)return;gg();let LA=lA??qo;if(bs==="bet"){(!LA||LA<=0)&&(LA=Math.max(1,pt||1));const ae=Math.floor(LA),De=await M(e,ae);fI(De==null?void 0:De.ok,De==null?void 0:De.error),De!=null&&De.ok&&(Rs(0),Gs(!1),Wg(null))}else if(bs==="raise"){if(!LA||LA<=0){const Be=Math.max(0,pt-Tt);LA=Math.max(1,Be)}LA=Math.min(LA,Math.max(0,vt));const ae=Math.floor(LA),De=await w(e,ae);fI(De==null?void 0:De.ok,De==null?void 0:De.error),De!=null&&De.ok&&(Rs(0),Gs(!1),Wg(null))}},ry=()=>{Rs(0),Gs(!1),Wg(null)},[Yo,yI]=ue.useState(null),Hw=ue.useCallback(lA=>{try{const LA=Te(Qe);LA&&yI({x:LA.x,y:Math.max(0,LA.y-70),text:lA});const ae=document.querySelector(`li.player--avatar[data-player-id="${Qe}"]`);ae&&(ae.classList.add("player--timeout"),setTimeout(()=>{try{ae.classList.remove("player--timeout")}catch{}},2500)),setTimeout(()=>yI(null),2600)}catch{}},[Te,Qe]);E.useEffect(()=>{(Vt||!Je)&&(Gs(!1),Wg(null),Rs(0))},[Vt,Je]);const DI=ue.useRef(0);return E.useEffect(()=>{const lA=U==null?void 0:U.gameState;if(!lA)return;const LA=lA==null?void 0:lA.pokerLastAction;if(!LA||typeof LA.seq!="number"||DI.current===LA.seq)return;const ae=String(LA.action||"").toLowerCase();if(!["bet","raise","call"].includes(ae)){DI.current=LA.seq;return}const De=Math.max(0,Number(LA.amountDelta||0));if(De<=0){DI.current=LA.seq;return}const Fe=(Array.isArray(lA==null?void 0:lA.pokerSeats)?lA.pokerSeats:[]).find(rt=>rt.seatIndex===LA.seatIndex),Le=Fe!=null&&Fe.playerId?String(Fe.playerId):void 0;q(()=>{try{const rt=gt();if(!rt)return;const ft=Le?Te(Le):null;if(!ft)return;const En=`poker-commit-${LA.seq}-${Le||LA.seatIndex}-${Date.now()}`;DA(rg=>[...rg,{id:`${En}-to-pot`,amount:De,fromId:Le||`seat:${LA.seatIndex}`,toId:"pot",startX:ft.x,startY:ft.y,endX:rt.x,endY:rt.y,startDelaySec:.1}])}catch{}}),DI.current=LA.seq},[U==null?void 0:U.gameState,q,Te,Jt]),C.jsxs(C.Fragment,{children:[C.jsx(tr,{className:"page-poker-room"}),C.jsx(mpA,{open:HA,onClose:ye,title:"Poker",tagline:"Bet, check, raise — best hand wins at showdown.",steps:["Each player gets 2 hole cards","Bet after each street: flop, turn, river","Make the best 5‑card hand to win the pot"],primaryLabel:"Got it",persistKey:"onb_poker_v1"}),C.jsxs(KZ,{showAvatarBacks:rC,overlay:B?C.jsx(bZ,{show:!0,contained:!0,variant:B.variant,displayMs:B.displayMs,zoomDurationMs:B.zoomDurationMs,fadeDurationMs:B.fadeDurationMs,ariaLabel:B.ariaLabel,onComplete:h}):null,header:C.jsx("div",{className:"poker-room-header",children:C.jsx(GZ,{roomName:Ai,roomId:e,players:Bi,meId:Vg,gameState:ct,lastRollerId:null,showHeader:!0,revealedHands:uA,historyHalo:QA,singlePlayer:U==null?void 0:U.singlePlayer,campaignProgress:mt,turnDeadlineTs:ei,isBettingStreet:gi,isHeroTurn:Mg,elimConfig:Ce,elimStates:nA,onOpenHistory:async()=>{var lA;if(xA(!0),!!e)try{const LA=await b(e,20);if(LA!=null&&LA.ok&&Array.isArray((lA=LA==null?void 0:LA.data)==null?void 0:lA.items)){const ae=LA.data.items;jA(De=>{const Be=ae.map(Le=>({roundSeq:Number(Le.seq||Le.roundSeq||0),ts:Number(Le.endedAt||Le.createdAt||Date.now()),pot:Number(Le.mainPot||Le.pot||0),winners:Array.isArray(Le.seats)?Le.seats.filter(rt=>(rt.winnings||0)>0).map(rt=>({playerId:rt.playerId,seatIndex:rt.seatIndex,amount:rt.winnings||0,rank:rt.rank?rt.rank:rt.handRank!=null?{category:rt.handRank,tiebreak:rt.tiebreak||[]}:void 0})):[],hands:Array.isArray(Le.seats)?Le.seats.map(rt=>({playerId:rt.playerId,seatIndex:rt.seatIndex,hole:Array.isArray(rt.hole)?rt.hole:Array.isArray(rt.holeCards)?rt.holeCards:[]})):[],seats:Array.isArray(Le.seats)?Le.seats.map(rt=>({playerId:rt.playerId,seatIndex:rt.seatIndex,status:rt.status,rank:rt.rank?rt.rank:rt.handRank!=null?{category:rt.handRank,tiebreak:rt.tiebreak||[]}:void 0,winnings:rt.winnings})):void 0})),Fe=new Map;for(const Le of[...De,...Be])Fe.set(Le.roundSeq,Le);return Array.from(Fe.values()).sort((Le,rt)=>rt.roundSeq-Le.roundSeq).slice(0,20)})}}catch(LA){console.warn("[poker] fetch_history failed",LA)}}})}),children:[C.jsx(OtA,{enabled:fA,handKey:oA,perCardSec:.6,staggerSec:.14,onComplete:()=>{RA(!1);const lA=he.current;if(lA>0&&(ie.current=lA),eA&&!sA&&(yA(!0),setTimeout(()=>pA(!0),200)),L.current!=null){try{clearTimeout(L.current)}catch{}L.current=null}try{const LA=typeof window<"u"?window:void 0;LA&&(LA.__pokerHoleDiag=LA.__pokerHoleDiag||[],LA.__pokerHoleDiag.push({kind:"dealing_complete",at:Date.now()}))}catch{}}}),C.jsx(OtA,{enabled:sr.active,handKey:`board-${sr.key}`,perCardSec:.5,staggerSec:.12,passes:1,getTargets:lA=>{var LA;try{const ae=lA.getBoundingClientRect(),De=(LA=lA.ownerDocument)==null?void 0:LA.querySelector(".poker-board");if(!De)return[];const Be=Array.from(De.querySelectorAll(".poker-card"));return sr.indices.map(Le=>{const rt=Be[Le];if(!rt)return null;const ft=rt.getBoundingClientRect();return{x:(ft.left+ft.right)/2-ae.left,y:(ft.top+ft.bottom)/2-ae.top}}).filter(Boolean)}catch{return[]}},onComplete:()=>{const lA=sr.indices.slice();if(UB(LA=>({...LA,active:!1})),lA.length>0){Ut(ae=>{const De=new Set(ae);return lA.forEach(Be=>De.add(Be)),De});const LA=window.setTimeout(()=>{Ut(ae=>{const De=new Set(ae);return lA.forEach(Be=>De.delete(Be)),De})},250);dt.current.push(LA)}}}),C.jsxs("div",{className:"poker-mock",children:[je&&!kt&&C.jsx("div",{className:"poker-start-hand",children:C.jsx("button",{type:"button",className:["gold-link","poker-start-hand__btn",Ct?"is-busy":""].filter(Boolean).join(" "),"aria-label":"Play Again",disabled:Ct,onClick:async()=>{var lA,LA,ae;if(!Ct){try{const{hapticClick:De}=await Qi(async()=>{const{hapticClick:Be}=await Promise.resolve().then(()=>R1);return{hapticClick:Be}},void 0);De("Medium")}catch{}At(!0);try{const{loadSettings:De}=await Qi(async()=>{const{loadSettings:En}=await Promise.resolve().then(()=>TcA);return{loadSettings:En}},void 0),Be=await De(),Fe=Be.botDifficultyLevel&&Be.botDifficultyLevel>=1&&Be.botDifficultyLevel<=9?Be.botDifficultyLevel:void 0,Le=await S({name:"Single Player Room",singlePlayer:!0,botLevel:Fe}),rt=(Le==null?void 0:Le.room)??((lA=Le==null?void 0:Le.roomsList)==null?void 0:lA.room)??((LA=Le==null?void 0:Le.data)==null?void 0:LA.room)??null,ft=(rt==null?void 0:rt.roomId)??(rt==null?void 0:rt.id)??(Le==null?void 0:Le.roomId)??((ae=Le==null?void 0:Le.data)==null?void 0:ae.roomId);if(ft){try{window.__PRESEEDED_ROOM=rt}catch{}_(`/poker/room/${ft}`,{replace:!0})}else{console.warn("[poker:play_again] no room id in response",Le);try{K("Poker",(Le==null?void 0:Le.error)||"Unable to create room")}catch{}At(!1)}}catch(De){console.error("[poker:play_again] error",De);try{K("Poker","Unable to create room")}catch{}At(!1)}}},children:"Play Again"})}),kt&&C.jsxs("div",{className:"poker-start-hand",children:[ci>0&&C.jsxs("div",{className:"poker-start-hand__countdown",children:["Starting in ",ci,"s"]}),Ei.length>1&&C.jsxs("div",{className:"poker-start-hand__readiness",children:[zt.length,"/",Ei.length," ready"]}),C.jsx("button",{type:"button",className:["gold-link","poker-start-hand__btn",ht?"is-busy":"",Hi?"is-ready":""].filter(Boolean).join(" "),"aria-label":Hi?"Waiting for others":"Start Hand",disabled:ht||Hi,onClick:async()=>{if(e){try{const{hapticClick:lA}=await Qi(async()=>{const{hapticClick:LA}=await Promise.resolve().then(()=>R1);return{hapticClick:LA}},void 0);lA("Medium")}catch{}console.log("[poker:start_hand] button clicked",{roomId:e}),ee(!0);try{const lA=await D(e);if(console.log("[poker:start_hand] response",lA),lA!=null&&lA.countdown&&(console.log("[poker:start_hand] countdown started",{endsAt:lA==null?void 0:lA.countdown}),$e(lA==null?void 0:lA.countdown)),lA!=null&&lA.waiting){console.log("[poker:start_hand] waiting for other players",{readyPlayers:lA==null?void 0:lA.readyPlayers,requiredPlayers:lA==null?void 0:lA.requiredPlayers}),li((lA==null?void 0:lA.readyPlayers)||[]),ai((lA==null?void 0:lA.requiredPlayers)||[]);return}if(!(lA!=null&&lA.ok)){console.warn("[poker:start_hand] error response",lA);try{K("Poker",(lA==null?void 0:lA.error)||"Unable to start hand")}catch{}}ee(!1)}catch(lA){console.error("[poker:start_hand] exception",lA);try{K("Poker","Unable to start hand")}catch{}ee(!1)}}},children:Hi?"✓ Ready":"Start Hand"})]}),C.jsxs("div",{className:"poker-mock__table",children:[C.jsx("div",{className:"poker-mock__table-ring","aria-hidden":!0}),C.jsxs("div",{className:"poker-board-wrap",children:[C.jsx("div",{className:"poker-pot","aria-label":"poker-pot",ref:EA,style:$A?void 0:{visibility:"hidden"},children:(()=>{var ae;const lA=Number(((ae=ct==null?void 0:ct.wagerPool)==null?void 0:ae.totalAmount)||0),LA=RZ(lA);return Object.entries(LA.reduce((De,Be)=>{const Fe=String(Be);return De[Fe]=(De[Fe]||0)+1,De},{})).sort((De,Be)=>Number(Be[0])-Number(De[0])),C.jsx("div",{className:"poker-pot__wrap",children:C.jsxs("div",{className:"poker-pot__context","aria-live":"polite",children:[C.jsxs("span",{className:"poker-pot__stack-info",children:["You: z",vt]}),C.jsx("span",{className:"poker-pot__divider","aria-hidden":"true",children:"•"}),C.jsxs("span",{className:`poker-pot__pot-info ${de>0&&vt>0&&de/vt>=.25?"poker-pot__pot-info--high":""}`,children:[de>0?`To Call: z${de}`:`Pot: z${lA}`,de>0&&vt>0&&de/vt>=.5&&C.jsxs("span",{className:"poker-pot__high-pct","aria-label":"High percentage of stack",children:[Math.round(de/vt*100),"%"]})]})]})})})()}),C.jsx(cge,{boardCards:Array.isArray((mI=U==null?void 0:U.gameState)==null?void 0:mI.pokerCommunity)?U.gameState.pokerCommunity:[]}),C.jsx("div",{className:"poker-board poker-community","aria-label":"community-cards",children:Array.isArray((Qc=U==null?void 0:U.gameState)==null?void 0:Qc.pokerCommunity)&&U.gameState.pokerCommunity.map((lA,LA)=>{const ae=nt.has(LA)||LA>=(pI.current||0),De=U.gameState.pokerCommunity,Be=Cge(LA),Fe=rge(De,LA),Le=Be==="river"&&De.length===5;return C.jsx(Qge,{value:lA,concealed:ae,position:Be,isPaired:Fe,animateEntrance:Le&&!ae},`${lA}-${LA}`)})}),Array.isArray((IC=U==null?void 0:U.gameState)==null?void 0:IC.pokerCommunity)&&U.gameState.pokerCommunity.length>0&&(()=>{const lA=U.gameState.pokerCommunity;return FZ(lA).length>0?C.jsxs("div",{className:"poker-hole__board-hint","aria-label":"Board is paired",title:"Paired board",children:[C.jsx("span",{className:"poker-hole__board-icon","aria-hidden":"true",children:"≡"}),C.jsx("span",{className:"poker-hole__board-text",children:"Paired Board"})]}):null})(),C.jsx("div",{className:["poker-hole",fA?"poker-hole--concealed":"",sA?"is-revealed":"",!sA&&gA?"is-partial":"",Mg&&!Vt?"poker-hole--active-turn":""].filter(Boolean).join(" "),"aria-label":"hole-cards",ref:kA,children:C.jsxs("div",{className:"poker-hole-stack",children:[C.jsx("div",{className:"poker-hole-label","aria-hidden":!0,children:"--"}),gA,sA,C.jsx(bpA,{cards:eA,firstRevealed:!!gA,bothRevealed:!!sA})]})})]}),Yo&&C.jsx("div",{className:"poker-timeout-toast","aria-live":"polite",style:{position:"fixed",left:Yo.x,top:Yo.y,transform:"translate(-50%, -100%)"},children:Yo.text})]}),wA&&C.jsx(nge,{players:Bi,entries:YA,onClose:()=>xA(!1)}),Ie.length>0&&C.jsx(upA,{anim:Ie[0],onComplete:()=>{Ie[0],DA(lA=>lA.slice(1))}},Ie[0].id)]}),C.jsxs("div",{className:"poker-actions-wrap",ref:se,children:[C.jsxs("div",{className:["poker-actions","poker-actions--group","poker-actions--segmented",Mg&&!Vt?"poker-actions--halo":""].filter(Boolean).join(" "),role:"group","aria-label":"Action buttons","aria-disabled":Vt||void 0,children:[qe&&C.jsx(Xl,{label:"Check",ariaLabel:"Check",size:"md",disabled:Vt,onClick:vB,className:"poker-action--flat poker-action--secondary poker-action--check"}),!qe&&OA&&C.jsx(Xl,{label:"Call",subtitle:`z${de}`,ariaLabel:`Call ${de}`,size:"md",disabled:Vt,onClick:Ps,className:"poker-action--flat poker-action--primary poker-action--call"}),Ae&&C.jsx(Xl,{label:"Bet",subtitle:qo>0?`z${qo}`:void 0,ariaLabel:"Bet",size:"md",disabled:Vt,onClick:Pd,className:"poker-action--green poker-action--secondary poker-action--bet"}),!Ae&&Ke&&C.jsx(Xl,{label:"Raise",subtitle:qo>0?`z${qo}`:void 0,ariaLabel:"Raise",size:"md",disabled:Vt,onClick:KB,className:["poker-action--green","poker-action--secondary","poker-action--raise",bs==="raise"&&eg?"raise-active":""].filter(Boolean).join(" ")}),Hg==="active"&&C.jsx(Xl,{label:"Fold",ariaLabel:"Fold",size:"md",disabled:Vt,onClick:ll,className:"poker-action--flat poker-action--danger poker-action--fold"})]}),C.jsx("div",{className:"poker-chiprack",style:eg?void 0:{visibility:"hidden",pointerEvents:"none"},children:C.jsx(pdA,{onPlaceBet:jd,onCancelBet:ry,disabled:Vt,defaultValue:Math.max(1,pt||1),max:vt>0?vt:void 0})})]})]}),xe&&C.jsxs("div",{className:"elim-toast",children:[C.jsx("div",{className:"elim-toast__text",children:xe.text}),xe.sub&&C.jsx("div",{className:"elim-toast__sub",children:xe.sub})]}),bA&&C.jsx(lge,{winner:bA.winner,eliminatedOrder:bA.eliminatedOrder,finalStates:bA.finalStates,nameOf:lA=>{const LA=Bi.find(ae=>ae.id===lA);return(LA==null?void 0:LA.name)||lA.slice(0,6)},meId:Vg,onDismiss:()=>pe(null)}),ve&&C.jsx(kpA,{winnerName:(()=>{var LA;const lA=Bi.find(ae=>ae.id===ve.winnerUserId);return(lA==null?void 0:lA.name)||((LA=ve.winnerUserId)==null?void 0:LA.slice(0,6))||"Winner"})(),bonus:ve.bonus,isHero:ve.winnerUserId===Vg,onDismiss:()=>re(null)})]})}function JZ(){const e=qi(),{user:A}=tn(),[t,i]=E.useState(!1),n=(()=>{var o;try{return window.location.search.includes("e2e=1")||window.__E2E===!0||((o=window.sessionStorage)==null?void 0:o.getItem("e2e"))==="1"}catch{return!1}})(),g=E.useCallback(()=>{if(!(Number((A==null?void 0:A.balance)??0)>=1e3)){i(!0);return}const s=`e2e-${Math.random().toString(36).slice(2,8)}`;e(`/poker/room/${s}?m=poker`)},[e,A==null?void 0:A.balance]);return C.jsxs(KZ,{header:C.jsx("div",{className:"poker-room-header",role:"banner",children:C.jsx("h1",{className:"poker-title","aria-label":"Poker Room",children:"Poker"})}),children:[n&&C.jsx("div",{className:"poker-room-controls",role:"group","aria-label":"poker e2e controls",children:C.jsx("button",{type:"button",onClick:g,"aria-label":"Create Game",children:"Create Game"})}),n&&C.jsx("div",{className:"poker-actions-wrap",children:C.jsxs("div",{className:["poker-actions","poker-actions--group","poker-actions--segmented","poker-actions--halo"].join(" "),role:"group","aria-label":"Action buttons",children:[C.jsx(hM,{label:"Check",ariaLabel:"Check",size:"md",onClick:()=>{},className:"poker-action--flat"}),C.jsx(hM,{label:"Bet",ariaLabel:"Bet",size:"md",onClick:()=>{},className:"poker-action--flat"}),C.jsx(hM,{label:"Fold",ariaLabel:"Fold",size:"md",onClick:()=>{},className:"poker-action--flat poker-action--fold"})]})})]})}const Qh=(e,A)=>({rank:e,suit:A}),F0={name:"Texas Hold’em",pot:295,community:[Qh("5","♠"),Qh("8","♦"),Qh("A","♣"),Qh("10","♣"),Qh("2","♥")],players:[{id:"p1",name:"Hero",stack:295,bet:25,isHero:!0,isActing:!0,hole:[Qh("K","♠"),Qh("K","♦")]},{id:"p2",name:"Eve",stack:420,bet:25,hole:null},{id:"p3",name:"Zoe",stack:380,bet:0,hole:null},{id:"p4",name:"Rey",stack:260,bet:0,hole:null}]},uge=[{kind:"call",amount:25},{kind:"fold"},{kind:"check"},{kind:"bet",amount:0},{kind:"raise",to:0}];function jtA(e){switch(e.kind){case"check":return"CHECK";case"fold":return"FOLD";case"call":return"CALL";case"bet":return e.amount&&e.amount>0?`BET ${e.amount}`:"BET";case"raise":return e.to&&e.to>0?`RAISE ${e.to}`:"RAISE"}}function ztA(e){return`${e.rank}${e.suit}`}function dge(e={1:0,5:0,10:0,25:0,100:0,500:0}){const[A,t]=E.useState(e),i=E.useMemo(()=>QpA.reduce((s,a)=>s+a*(A[a]??0),0),[A]),n=E.useCallback(s=>{t(a=>({...a,[s]:(a[s]??0)+1}))},[]),g=E.useCallback(s=>{t(a=>a[s]?{...a,[s]:0}:a)},[]),o=E.useCallback(()=>{t({1:0,5:0,10:0,25:0,100:0,500:0})},[]);return{rack:A,totalAmount:i,addChip:n,clearChip:g,clearAllChips:o}}function LZ(){const{user:e}=tn(),[A,t]=ue.useState(!1),i=F0.players.find(l=>l.isHero),n=F0.players.map(l=>({id:l.id,name:l.name,balance:l.bet??0})),g={gameMode:"poker"},o=typeof window<"u"&&window.location.search.includes("e2e=1"),{rack:s,totalAmount:a,addChip:r,clearChip:I,clearAllChips:c}=dge();return C.jsx(C.Fragment,{children:C.jsx(KZ,{header:C.jsx("div",{className:"poker-room-header",children:C.jsx(GZ,{roomName:F0.name,players:n,meId:i.id,gameState:g,lastRollerId:null,showHeader:!0})}),children:C.jsxs("div",{className:"poker-mock",children:[o&&C.jsx("div",{className:"poker-e2e-bar",children:C.jsx("button",{className:"felt-btn","aria-label":"Create Game",onClick:()=>{if(!(Number((e==null?void 0:e.balance)??0)>=1e3)){t(!0);return}const B="e2e_"+Math.random().toString(36).slice(2,8);window.location.assign(`/poker/room/${B}`)},children:"Create Game"})}),C.jsxs("div",{className:"poker-mock__table",children:[C.jsx("div",{className:"poker-mock__table-ring","aria-hidden":!0}),C.jsx("div",{className:"poker-board",children:F0.community.map((l,B)=>{const Q=l.suit==="♥"||l.suit==="♦";return C.jsxs("div",{className:["poker-card",Q?"poker-card--red":""].filter(Boolean).join(" "),"aria-label":ztA(l),children:[C.jsx("span",{className:"poker-card__rank",children:l.rank}),C.jsx("span",{className:"poker-card__suit",children:l.suit})]},B)})}),C.jsxs("div",{className:"poker-pot",children:["$",F0.pot]})]}),(i==null?void 0:i.hole)&&C.jsx("div",{className:"poker-hole",children:i.hole.map((l,B)=>{const Q=l.suit==="♥"||l.suit==="♦";return C.jsxs("div",{className:["poker-card",Q?"poker-card--red":""].filter(Boolean).join(" "),"aria-label":ztA(l),children:[C.jsx("span",{className:"poker-card__rank",children:l.rank}),C.jsx("span",{className:"poker-card__suit",children:l.suit})]},B)})}),C.jsx("div",{className:"poker-actions-wrap",children:C.jsx("div",{className:"poker-actions",children:uge.map((l,B)=>C.jsx(hM,{label:jtA(l),ariaLabel:jtA(l),size:"md",onClick:()=>{}},B))})}),C.jsx("div",{className:"poker-chiprack",children:C.jsx(GpA,{selectedTimes:s,onAdd:r,onClear:I,onPlaceBet:()=>{c()},onCancelBet:()=>{c()},disabled:!1,collapsed:!1,miniChips:!0,mainAmt:a,betTokenProps:{isBanker:!1,meId:i.id,open:[],players:n,show:!0}})})]})})})}function KpA(){const e=Math.floor(Math.random()*6)+1,A=Math.floor(Math.random()*6)+1;return[e,A]}function FpA(e){return e[0]===e[1]}function hge(e,A,t){const i=(e+A)%t,n=e+A>=t;return{newTile:i,passedStart:n}}function pge(e,A,t){const i=[];let n=e;for(;n!==A;)n=(n+1)%t,i.push(n);return i}function fge(e,A){return{...e,credits:e.credits+A.passStartBonus}}function yge(e,A,t){const i=A[0]+A[1],{newTile:n,passedStart:g}=hge(e.tileIndex,i,t.tileCount),o=pge(e.tileIndex,n,t.tileCount);let s={...e,tileIndex:n};return g&&(s=fge(s,t)),{player:s,passedStart:g,path:o}}function pM(e,A){return{...e,tileIndex:A,inJail:!0,jailTurnsLeft:3}}function Dge(e,A,t){if(FpA(A))return{player:{...e,inJail:!1,jailTurnsLeft:0},escaped:!0,method:"roll-doubles"};const i=e.jailTurnsLeft-1;return i<=0?{player:{...e,inJail:!1,jailTurnsLeft:0,credits:e.credits-t},escaped:!0,method:"pay"}:{player:{...e,jailTurnsLeft:i},escaped:!1,method:null}}function mge(e,A){return{...e,inJail:!1,jailTurnsLeft:0,credits:e.credits-A}}function Sge(e,A,t){return A.filter(i=>{var n;return i.ownerId===e&&!i.dormant&&((n=t[i.tileId])==null?void 0:n.type)==="station"}).length}function wge(e,A,t,i){return e.rent?e.rent[A.upgradeLevel]??e.rent[0]??0:0}function kge(e,A,t){const i=Sge(e,A,t);return i<=0?0:25*Math.pow(2,i-1)}const Mge=[{text:"Intercepted enemy supply convoy! Gain 150 energy.",amount:150},{text:"Asteroid barrage hit your fleet! Lose 100 energy for repairs.",amount:-100},{text:"Stealth mission success. Gain 50 energy.",amount:50},{text:"Hull breach from enemy fire! Lose 200 energy for repairs.",amount:-200},{text:"Salvaged weapons from derelict warship. Gain 75 energy.",amount:75},{text:"Debris field damaged shields! Lose 50 energy for repairs.",amount:-50},{text:"Black market intel sold for profit. Gain 120 energy.",amount:120},{text:"Pirate ambush in the asteroid belt! Lose 80 energy.",amount:-80},{text:"Discovered rare mineral deposit. Gain 200 energy.",amount:200},{text:"Navigation error caused fuel waste. Lose 60 energy.",amount:-60},{text:"Bounty collected on rogue warship. Gain 100 energy.",amount:100},{text:"Emergency hull patching required. Lose 150 energy.",amount:-150},{text:"Captured enemy communications array. Gain 80 energy.",amount:80},{text:"Micro-meteorite swarm impact! Lose 40 energy.",amount:-40},{text:"Sold surplus munitions to allied fleet. Gain 60 energy.",amount:60},{text:"Engine coolant leak detected. Lose 120 energy for repairs.",amount:-120},{text:"Warp jump to Zentara!",amount:0,moveTo:39},{text:"Hyperspace route locked to Ross 128b.",amount:0,moveTo:16},{text:"Fleet recall to Trappist-1d.",amount:0,moveTo:11},{text:"Advance to nearest Outpost. If unowned, you may claim it.",amount:0,moveToNearest:"station"},{text:"Advance to nearest Outpost. If unowned, you may claim it.",amount:0,moveToNearest:"station"},{text:"Warp malfunction! Go back 3 tiles.",amount:0,moveRelative:-3},{text:"Report to Command Base.",amount:0,moveTo:0},{text:"Detained by Galactic Authority! Entering Cryosleep.",amount:0,goToJail:!0}],Nge=[{text:"Intercepted enemy supply convoy! Gain 150 energy.",amount:150},{text:"Asteroid barrage hit your fleet! Lose 100 energy for repairs.",amount:-100},{text:"Stealth mission success. Gain 50 energy.",amount:50},{text:"Hull breach from enemy fire! Lose 200 energy for repairs.",amount:-200},{text:"Salvaged weapons from derelict warship. Gain 75 energy.",amount:75},{text:"Debris field damaged shields! Lose 50 energy for repairs.",amount:-50},{text:"Black market intel sold for profit. Gain 120 energy.",amount:120},{text:"Pirate ambush in the asteroid belt! Lose 80 energy.",amount:-80},{text:"Discovered rare mineral deposit. Gain 200 energy.",amount:200},{text:"Navigation error caused fuel waste. Lose 60 energy.",amount:-60},{text:"Bounty collected on rogue warship. Gain 100 energy.",amount:100},{text:"Emergency hull patching required. Lose 150 energy.",amount:-150},{text:"Warp jump to Zentara!",amount:0,moveTo:19},{text:"Hyperspace route to Tau Ceti f.",amount:0,moveTo:8},{text:"Fleet recall to Trappist-1f.",amount:0,moveTo:6},{text:"Advance to nearest Outpost. If unowned, you may claim it.",amount:0,moveToNearest:"station"},{text:"Warp malfunction! Go back 3 tiles.",amount:0,moveRelative:-3},{text:"Report to Command Base.",amount:0,moveTo:0},{text:"Detained by Galactic Authority! Entering Cryosleep.",amount:0,goToJail:!0}],Rge=[{text:"War council grants reinforcements. Gain 200 energy.",amount:200},{text:"Fleet maintenance overdue. Lose 150 energy.",amount:-150},{text:"Weapons upgrade bonus. Gain 100 energy.",amount:100},{text:"Tactical systems overhaul. Lose 75 energy.",amount:-75},{text:"Arms trade dividend. Gain 50 energy.",amount:50},{text:"Reactor core replacement. Lose 125 energy.",amount:-125},{text:"Allied fleet sent tribute. Gain 175 energy.",amount:175},{text:"Crew quarantine protocol activated. Lose 90 energy.",amount:-90},{text:"Nebula sensor array detected hidden cache. Gain 125 energy.",amount:125},{text:"Life support systems failing. Lose 110 energy.",amount:-110},{text:"Diplomatic envoy rewarded your empire. Gain 80 energy.",amount:80},{text:"Fuel depot contamination. Lose 60 energy for cleanup.",amount:-60},{text:"Recovered escape pod with classified data. Gain 150 energy.",amount:150},{text:"Gravity well anomaly damaged thrusters. Lose 100 energy.",amount:-100},{text:"Resource tithe from conquered sector. Gain 90 energy.",amount:90},{text:"Ion storm fried navigation circuits. Lose 175 energy.",amount:-175},{text:"Shore leave approved. Report to Command Base.",amount:0,moveTo:0},{text:"Detained for smuggling contraband! Entering Cryosleep.",amount:0,goToJail:!0},{text:"Emergency warp to Gliese 667Cc for repairs.",amount:0,moveTo:21},{text:"Navigate to Pandora for a diplomatic summit.",amount:0,moveTo:37}],Gge=[{text:"War council grants reinforcements. Gain 200 energy.",amount:200},{text:"Fleet maintenance overdue. Lose 150 energy.",amount:-150},{text:"Weapons upgrade bonus. Gain 100 energy.",amount:100},{text:"Tactical systems overhaul. Lose 75 energy.",amount:-75},{text:"Arms trade dividend. Gain 50 energy.",amount:50},{text:"Reactor core replacement. Lose 125 energy.",amount:-125},{text:"Allied fleet sent tribute. Gain 175 energy.",amount:175},{text:"Crew quarantine protocol activated. Lose 90 energy.",amount:-90},{text:"Shore leave approved. Report to Command Base.",amount:0,moveTo:0},{text:"Detained for smuggling contraband! Entering Cryosleep.",amount:0,goToJail:!0},{text:"Emergency warp to Gliese 581g for repairs.",amount:0,moveTo:11}];function xZ(e,A,t,i){const n=i.length<=20;switch(e.type){case"planet":{const g=t.find(s=>s.tileId===e.id);if(!g)return{tileId:e.id,action:"buy-prompt",amount:e.cost};if(g.ownerId===A.id||g.dormant)return{tileId:e.id,action:"none"};const o=wge(e,g);return{tileId:e.id,action:"energy-toll",amount:o}}case"station":{const g=t.find(s=>s.tileId===e.id);if(!g)return{tileId:e.id,action:"buy-prompt",amount:e.cost};if(g.ownerId===A.id||g.dormant)return{tileId:e.id,action:"none"};const o=kge(g.ownerId,t,i);return{tileId:e.id,action:"energy-toll",amount:o}}case"void-drain":return{tileId:e.id,action:"void-drain",amount:100};case"go-to-jail":return{tileId:e.id,action:"go-to-jail"};case"wormhole":{const g=i.filter(r=>r.type==="wormhole").sort((r,I)=>r.id-I.id),o=g.findIndex(r=>r.id===e.id),s=o>=0?o%2===0?o+1:o-1:-1,a=s>=0?g[s]:void 0;return{tileId:e.id,action:"wormhole",targetTile:(a==null?void 0:a.id)??e.id}}case"asteroid":{const g=n?Nge:Mge,o=g[Math.floor(Math.random()*g.length)],s={tileId:e.id,action:"draw-card",amount:o.amount,cardText:o.text};if(o.goToJail)s.cardGoToJail=!0;else if(o.moveTo!==void 0)s.cardMoveTo=o.moveTo;else if(o.moveToNearest==="station"){const a=i.filter(I=>I.type==="station").map(I=>I.id).sort((I,c)=>I-c),r=a.filter(I=>I>A.tileIndex);s.cardMoveTo=r.length>0?r[0]:a[0]}else o.moveRelative!==void 0&&(s.cardMoveTo=((A.tileIndex+o.moveRelative)%i.length+i.length)%i.length);return s}case"nebula":{const g=n?Gge:Rge,o=g[Math.floor(Math.random()*g.length)],s={tileId:e.id,action:"draw-card",amount:o.amount,cardText:o.text};return o.goToJail?s.cardGoToJail=!0:o.moveTo!==void 0&&(s.cardMoveTo=o.moveTo),s}default:return{tileId:e.id,action:"none"}}}function _pA(e){const A=e.findIndex(t=>t.type==="jail");return A>=0?A:10}function JpA(e){return{playerId:e,phase:"pre-roll",diceValues:null,doublesCount:0,rolledDoubles:!1,landedTile:null,strikeUsed:!1}}function bge(e,A){var d,p,y,m;const t=[];if(e.finished||e.currentTurn.phase!=="pre-roll")return{state:e,events:t,effect:null};const i={...e.currentTurn},n=e.players.findIndex(D=>D.id===i.playerId);if(n===-1)return{state:e,events:t,effect:null};if(e.players[n].depleted)return{state:e,events:t,effect:null};const g={...dn,tileCount:e.board.length},o=_pA(e.board);let s={...e.players[n]};const a=A??KpA();i.diceValues=a,t.push({type:"roll",playerId:s.id,dice:a});const r=FpA(a);if(i.doublesCount=r?i.doublesCount+1:0,i.rolledDoubles=r,i.doublesCount>=3){s=pM(s,o),t.push({type:"jail",playerId:s.id,reason:"triple-doubles"}),i.phase="done",i.landedTile=o;const D=[...e.players];return D[n]=s,{state:{...e,players:D,currentTurn:i,pendingEffect:null},events:t,effect:null}}if(s.inJail){const{player:D,escaped:S,method:k}=Dge(s,a,g.jailBailCost);if(s=D,!S){i.phase="done";const N=[...e.players];return N[n]=s,{state:{...e,players:N,currentTurn:i,pendingEffect:null},events:t,effect:null}}t.push({type:"jail-free",playerId:s.id,method:k})}const{player:I,passedStart:c}=yge(s,a,g);s=I,t.push({type:"move",playerId:s.id,from:e.players[n].tileIndex,to:s.tileIndex,passedStart:c}),i.landedTile=s.tileIndex,i.phase="landed";const l=[...e.players];l[n]=s;const B=e.board[s.tileIndex],Q=B?xZ(B,s,e.properties,e.board):null;if(Q&&Q.action==="go-to-jail")return t.push({type:"jail",playerId:s.id,reason:"go-to-jail"}),i.phase="landed",l[n]=s,{state:{...e,players:l,currentTurn:i,pendingEffect:null,pendingTeleport:{playerId:s.id,targetTile:o,reason:"go-to-jail",postPhase:"done"}},events:t,effect:null};if(Q&&Q.action==="wormhole"&&Q.targetTile!=null)return i.phase="landed",l[n]=s,{state:{...e,players:l,currentTurn:i,pendingEffect:null,pendingTeleport:{playerId:s.id,targetTile:Q.targetTile,reason:"wormhole",postPhase:r?"pre-roll":"done"}},events:t,effect:null};!Q||Q.action==="none"?i.phase=r?"pre-roll":"done":i.phase="action";let h=Q??null;if(h&&h.action==="energy-toll"){const D=e.properties.find(k=>k.tileId===h.tileId),S=D?e.players.find(k=>k.id===D.ownerId):null;if(s.heroId&&ms[s.heroId]&&(S!=null&&S.heroId)&&ms[S.heroId]){const k=e.board[h.tileId],N=k==null?void 0:k.group;N&&e.board.map((w,b)=>w.group===N?b:-1).filter(w=>w>=0).every(w=>e.properties.some(b=>b.tileId===w&&b.ownerId===D.ownerId))&&(h={...h,action:"hero-clash"})}}if(!((d=e.gameRules)!=null&&d.disableSpyStrike)&&B&&B.type==="planet"&&B.group&&((p=e.spies)!=null&&p[B.group])){const D=B.group,S=e.spies[D],k=((y=e.spyKinds)==null?void 0:y[D])??"monopoly";if(S===s.id){const N=e.properties.find(b=>b.tileId===B.id),G=N==null?void 0:N.ownerId,M=k==="foothold";let w;if(M)if(G&&G!==s.id)w=G;else{const b=e.board.filter(v=>v.group===D),_=new Map;for(const v of b){const U=(m=e.properties.find(T=>T.tileId===v.id))==null?void 0:m.ownerId;if(!U||U===s.id)continue;const x=_.get(U);x?x.count+=1:_.set(U,{count:1,firstTile:v.id})}let K,J=0,q=Number.POSITIVE_INFINITY;for(const[v,U]of _)(U.count>J||U.count===J&&U.firstTile<q)&&(K=v,J=U.count,q=U.firstTile);w=K}else if(G&&G!==s.id){const b=e.board.filter(K=>K.group===D).map(K=>K.id);b.length>0&&b.every(K=>e.properties.some(J=>J.tileId===K&&J.ownerId===G&&!J.dormant))&&(w=G)}w&&(h={tileId:B.id,action:"spy-clash",group:D,spyOwnerId:S,defenderId:w,step:"puzzle"},i.phase="action")}}return{state:{...e,players:l,currentTurn:i,pendingEffect:h},events:t,effect:h}}function Uge(e){const A=e.pendingTeleport;if(!A)return e;const t=e.players.findIndex(o=>o.id===A.playerId);if(t===-1)return e;let i={...e.players[t]};A.reason==="go-to-jail"?i=pM(i,_pA(e.board)):i={...i,tileIndex:A.targetTile};const n=[...e.players];n[t]=i;const g={...e.currentTurn,phase:A.postPhase,landedTile:A.targetTile};return{...e,players:n,currentTurn:g,pendingTeleport:null}}function vge(e){var n,g;const A=e.players.filter(o=>!o.depleted);if(A.length<=1)return{...e,finished:!0,winnerId:((n=A[0])==null?void 0:n.id)??null};let t=(e.currentPlayerIndex+1)%e.players.length;for(;(g=e.players[t])!=null&&g.depleted;)t=(t+1)%e.players.length;const i=t<=e.currentPlayerIndex?e.roundNumber+1:e.roundNumber;return{...e,currentPlayerIndex:t,currentTurn:JpA(e.players[t].id),roundNumber:i,pendingEffect:null}}const Tp=1e3,qp=500,LpA=1e3,xpA=500,TpA=3,Ym={bullseye:.55,hit:1.4,graze:2.4},_Y=["crimson-dominion","silver-pact","azure-sovereignty","golden-imperium","emerald-collective","void-enclave"],ZtA=["#ff3a3a","#b0c4de","#4488ff","#ffaa00","#39ff14","#cc44ff"];function Hm(e,A,t,i){const n=t[A];if(!(n!=null&&n.group))return 5;const g=t.map((l,B)=>l.group===n.group?B:-1).filter(l=>l>=0),o=g.length;if(o<=1)return 5;if(g.filter(l=>i.some(B=>B.tileId===l&&B.ownerId===e)).length<o)return 0;const a=g.map(l=>{const B=i.find(Q=>Q.tileId===l&&Q.ownerId===e);return B?B.upgradeLevel:0}),r=Math.min(...a),I=i.find(l=>l.tileId===A&&l.ownerId===e),c=I?I.upgradeLevel:0;return c>r?c:Math.min(c+1,5)}function Kge(e,A){const t=new Map;for(const g of e){if(!g.group)continue;const o=t.get(g.group);o?o.push(g.id):t.set(g.group,[g.id])}let i=!1;const n=A.map(g=>{if(g.upgradeLevel<=0)return g;const o=e[g.tileId];if(!(o!=null&&o.group))return g;const s=t.get(o.group);return!s||s.length<=1||s.every(r=>A.some(I=>I.tileId===r&&I.ownerId===g.ownerId))?g:(i=!0,{...g,upgradeLevel:0})});return i?n:A}function Fge(e,A,t,i,n){const g=i??_Y[t%_Y.length],o=_Y.indexOf(g);return{id:e,displayName:A,credits:dn.startingCredits,tileIndex:0,inJail:!1,jailTurnsLeft:0,depleted:!1,piece:g,pieceColor:ZtA[o>=0?o:t%ZtA.length],armorLevel:0,weaponLevel:0,heroId:n}}function _ge(e,A,t){const i=e.map((g,o)=>Fge(g.id,g.name,o,g.piece,g.heroId)),n=XF(A);return{matchId:crypto.randomUUID(),boardSize:A,players:i,properties:[],currentTurn:JpA(i[0].id),currentPlayerIndex:0,board:n.tiles,roundNumber:1,finished:!1,winnerId:null,pendingEffect:null,...t&&(t.disableRaid||t.disableSpyStrike)?{gameRules:{disableRaid:!!t.disableRaid,disableSpyStrike:!!t.disableSpyStrike}}:{}}}function WtA(e,A,t){if(!A.group||!A.spyOwnerId||!A.defenderId)return e;const i=e.currentPlayerIndex,n=e.players[i];if(n.id!==A.spyOwnerId)return e;const g=e.players.find(m=>m.id===A.defenderId);if(!g)return e;const o={...e.currentTurn},s=e.board.filter(m=>m.group===A.group).map(m=>m.id),a=e.properties.filter(m=>s.includes(m.tileId)&&m.ownerId===g.id).length,I=s.length>0&&a===s.length?LpA:xpA,c=n.credits-I,l=[...e.players],B=e.properties;l[i]={...n,credits:c};const Q={...e.spies??{}};delete Q[A.group];const h=Object.keys(Q).length>0?Q:void 0,d={...e.siegeCooldowns??{},[A.group]:e.roundNumber+TpA};if(t.push({type:"spy-resolved",spyOwnerId:n.id,defenderId:g.id,group:A.group,winnerId:g.id,tileIds:s,penalty:I}),c<=0){if(B.filter(S=>S.ownerId===n.id).length>0)return{...e,players:l,properties:B,currentTurn:{...o,phase:"in-debt"},pendingEffect:null,spies:h,siegeCooldowns:d};l[i]={...l[i],credits:0,bankrupt:!0},t.push({type:"bankrupt",playerId:n.id});const D=o.rolledDoubles?"pre-roll":"done";return{...e,players:l,properties:B,currentTurn:{...o,phase:D},pendingEffect:null,spies:h,siegeCooldowns:d}}const p=e.board[A.tileId];if(!p){const m=o.rolledDoubles?"pre-roll":"done";return{...e,players:l,properties:B,currentTurn:{...o,phase:m},pendingEffect:null,spies:h,siegeCooldowns:d}}let y=xZ(p,l[i],B,e.board);if(y&&y.action==="energy-toll"){const m=l[i];m.heroId&&ms[m.heroId]&&g.heroId&&ms[g.heroId]&&p.group&&s.every(k=>B.some(N=>N.tileId===k&&N.ownerId===g.id&&!N.dormant))&&(y={...y,action:"hero-clash"})}if(!y||y.action==="none"){const m=o.rolledDoubles?"pre-roll":"done";return{...e,players:l,properties:B,currentTurn:{...o,phase:m},pendingEffect:null,spies:h,siegeCooldowns:d}}return{...e,players:l,properties:B,currentTurn:{...o,phase:"action"},pendingEffect:y,spies:h,siegeCooldowns:d}}function Jge(e,A,t,i,n=!1){const[g,o]=E.useState(()=>A??_ge(e,t,i)),s=E.useRef(g);s.current=g;const[a,r]=E.useState([]),[I,c]=E.useState(0),l=E.useRef(!1),B=E.useRef([]),Q=E.useRef(!1);E.useEffect(()=>{if(Q.current){const W=B.current;B.current=[],Q.current=!1,r(W)}else if(B.current.length>0){const W=B.current;B.current=[],r($=>[...$,...W])}}),E.useEffect(()=>{o(W=>{const $=Kge(W.board,W.properties);return $===W.properties?W:{...W,properties:$}})},[g.properties,g.board]);const h=E.useCallback(()=>{if(l.current)return;l.current=!0;const W=KpA(),$=s.current,L=$.players.find(P=>P.id===$.currentTurn.playerId),H=!$.finished&&$.currentTurn.phase==="pre-roll"&&!!L&&!L.depleted;o(P=>{const tA=P.players.find(oA=>oA.id===P.currentTurn.playerId);if(P.finished||P.currentTurn.phase!=="pre-roll"||!tA||tA.depleted)return P;const iA=bge(P,W);return Q.current=!0,B.current=iA.events,iA.state}),H&&c(P=>P+1),l.current=!1},[]),d=E.useCallback(W=>{o($=>{var _A;if($.finished||$.currentTurn.phase!=="action"||((_A=$.pendingEffect)==null?void 0:_A.action)!=="buy-prompt"||W!==$.pendingEffect.tileId)return $;const L=$.board[W];if(!(L!=null&&L.cost))return $;const H=$.currentPlayerIndex,P=$.players[H];if(!P||P.depleted||P.id!==$.currentTurn.playerId||P.credits<L.cost)return $;const tA={...P,credits:P.credits-L.cost},iA=[...$.players];iA[H]=tA;const oA=[...$.properties,{tileId:W,ownerId:P.id,upgradeLevel:0,dormant:!1}];B.current.push({type:"buy",playerId:P.id,tileId:W,cost:L.cost});const IA=$.currentTurn.rolledDoubles?"pre-roll":"done",CA={...$.currentTurn,phase:IA};return{...$,players:iA,properties:oA,currentTurn:CA,pendingEffect:null}})},[]),p=E.useCallback(()=>{o(W=>{const $=W.pendingEffect;if(!$||$.action!=="energy-toll")return W;const L=W.currentPlayerIndex,H=W.players[L],P=$.amount??0,tA=H.armorLevel*dn.armorDamageReduction,iA=Math.max(1,Math.round(P*(1-tA)));let oA=W.properties;if(H.weaponLevel>=1&&W.currentTurn.rolledDoubles&&!W.currentTurn.strikeUsed){const xA=oA.findIndex(YA=>YA.tileId===$.tileId&&YA.ownerId!==H.id&&YA.upgradeLevel>0&&!YA.dormant);if(xA!==-1){oA=[...oA];const YA=oA[xA],jA=YA.upgradeLevel-1;oA[xA]={...YA,upgradeLevel:jA},B.current.push({type:"strike",playerId:H.id,tileId:$.tileId,newLevel:jA})}}const IA=oA.find(xA=>xA.tileId===$.tileId);if(!IA)return W;const CA=H.credits-iA,_A={...H,credits:CA},uA=W.players.findIndex(xA=>xA.id===IA.ownerId),X=[...W.players];X[L]=_A,uA!==-1&&(X[uA]={...X[uA],credits:X[uA].credits+iA}),B.current.push({type:"energy-toll",payerId:H.id,ownerId:IA.ownerId,tileId:$.tileId,amount:iA});const O=oA!==W.properties,cA={...W.currentTurn,strikeUsed:O?!0:W.currentTurn.strikeUsed};if(CA<=0){if(oA.filter(YA=>YA.ownerId===H.id).length>0)return{...W,players:X,properties:oA,currentTurn:{...cA,phase:"in-debt"},pendingEffect:null};X[L]={..._A,credits:0,depleted:!0},B.current.push({type:"depleted",playerId:H.id})}const wA=cA.rolledDoubles?"pre-roll":"done";return{...W,players:X,properties:oA,currentTurn:{...cA,phase:wA},pendingEffect:null}})},[]),y=E.useCallback(()=>{o(W=>{const $=W.pendingEffect;if(!$||$.action!=="hero-clash")return W;const L=W.currentPlayerIndex,H=W.players[L],P=$.amount??0,tA=W.properties.find(BA=>BA.tileId===$.tileId);if(!tA)return W;const iA=W.players.find(BA=>BA.id===tA.ownerId);if(!iA)return W;const oA=H.heroId?ms[H.heroId]:null,IA=iA!=null&&iA.heroId?ms[iA.heroId]:null;if(!oA||!IA)return W;const CA=Math.floor(Math.random()*6)+1,_A=Math.floor(Math.random()*6)+1,uA=CA+_A,X=Math.floor(Math.random()*6)+1,O=Math.floor(Math.random()*6)+1,cA=X+O,wA=mu(oA.empire,oA.tier).defense,xA=mu(IA.empire,IA.tier).attack,YA=Math.min(wA*uA/7,.9),jA=Math.min(xA*cA/7,3),ie=H.armorLevel*dn.armorDamageReduction;let he=W.properties;if(H.weaponLevel>=1&&W.currentTurn.rolledDoubles&&!W.currentTurn.strikeUsed){const BA=he.findIndex(j=>j.tileId===$.tileId&&j.ownerId!==H.id&&j.upgradeLevel>0&&!j.dormant);if(BA!==-1){he=[...he];const j=he[BA],QA=j.upgradeLevel-1;he[BA]={...j,upgradeLevel:QA},B.current.push({type:"strike",playerId:H.id,tileId:$.tileId,newLevel:QA})}}const le=Math.round(P*(1+jA)),NA=Math.max(1,Math.round(le*(1-ie)*(1-YA)));B.current.push({type:"hero-clash",attackerId:iA.id,defenderId:H.id,tileId:$.tileId,attackDice:[X,O],defenseDice:[CA,_A],attackHeroId:IA.id,defenseHeroId:oA.id,baseDamage:P,finalDamage:NA});const EA=H.credits-NA,PA={...H,credits:EA},ZA=W.players.findIndex(BA=>BA.id===tA.ownerId),FA=[...W.players];FA[L]=PA,ZA!==-1&&(FA[ZA]={...FA[ZA],credits:FA[ZA].credits+NA}),B.current.push({type:"energy-toll",payerId:H.id,ownerId:tA.ownerId,tileId:$.tileId,amount:NA});const Ie=he!==W.properties,DA={...W.currentTurn,strikeUsed:Ie?!0:W.currentTurn.strikeUsed};if(EA<=0){if(he.filter(QA=>QA.ownerId===H.id).length>0)return{...W,players:FA,properties:he,currentTurn:{...DA,phase:"in-debt"},pendingEffect:null};FA[L]={...PA,credits:0,depleted:!0},B.current.push({type:"depleted",playerId:H.id});const j=DA.rolledDoubles?"pre-roll":"done";return{...W,players:FA,properties:he,currentTurn:{...DA,phase:j},pendingEffect:null}}const rA=DA.rolledDoubles?"pre-roll":"done";return{...W,players:FA,properties:he,currentTurn:{...DA,phase:rA},pendingEffect:null}})},[]),m=E.useCallback(()=>{o(W=>{const $=W.pendingEffect;if(!$||$.action!=="void-drain")return W;const L=W.currentPlayerIndex,H=$.amount??0,P=W.players[L].credits-H,tA={...W.players[L],credits:P},iA=[...W.players];if(iA[L]=tA,B.current.push({type:"void-drain",playerId:tA.id,amount:H}),P<=0){if(W.properties.filter(_A=>_A.ownerId===tA.id).length>0)return{...W,players:iA,currentTurn:{...W.currentTurn,phase:"in-debt"},pendingEffect:null};iA[L]={...tA,credits:0,depleted:!0},B.current.push({type:"depleted",playerId:tA.id})}const oA=W.currentTurn.rolledDoubles?"pre-roll":"done",IA={...W.currentTurn,phase:oA};return{...W,players:iA,currentTurn:IA,pendingEffect:null}})},[]),D=E.useCallback(()=>{o(W=>{var oA;const $=W.pendingEffect;if(!$||$.action!=="draw-card")return W;const L=W.currentPlayerIndex,H=$.amount??0,P=((oA=W.board[$.tileId])==null?void 0:oA.type)==="asteroid"?"asteroid":"nebula";B.current.push({type:"card",playerId:W.players[L].id,deck:P,text:$.cardText??""});const tA=[...W.players];if($.cardGoToJail){const IA=W.board.findIndex(CA=>CA.type==="jail");return tA[L]=pM(W.players[L],IA>=0?IA:10),B.current.push({type:"jail",playerId:tA[L].id,reason:"go-to-jail"}),{...W,players:tA,currentTurn:{...W.currentTurn,phase:"done",rolledDoubles:!1},pendingEffect:null}}if($.cardMoveTo!==void 0){const IA=W.players[L].tileIndex,CA=$.cardMoveTo,_A=CA<IA;let uA={...W.players[L],tileIndex:CA};_A&&(uA={...uA,credits:uA.credits+dn.passStartBonus}),H!==0&&(uA={...uA,credits:uA.credits+H}),tA[L]=uA,B.current.push({type:"move",playerId:uA.id,from:IA,to:CA,passedStart:_A});const X=W.board[CA];if(X){const cA=xZ(X,uA,W.properties,W.board);if(cA.action==="go-to-jail"){const wA=W.board.findIndex(xA=>xA.type==="jail");return tA[L]=pM(W.players[L],wA>=0?wA:10),B.current.push({type:"jail",playerId:tA[L].id,reason:"go-to-jail"}),{...W,players:tA,currentTurn:{...W.currentTurn,phase:"done",rolledDoubles:!1},pendingEffect:null}}if(cA.action!=="none")return{...W,players:tA,currentTurn:{...W.currentTurn,phase:"action"},pendingEffect:cA}}const O=W.currentTurn.rolledDoubles?"pre-roll":"done";return{...W,players:tA,currentTurn:{...W.currentTurn,phase:O},pendingEffect:null}}if(H>=0)tA[L]={...W.players[L],credits:W.players[L].credits+H};else{const IA=Math.abs(H),CA=W.players[L].credits-IA;if(tA[L]={...W.players[L],credits:CA},CA<=0){if(W.properties.filter(uA=>uA.ownerId===W.players[L].id).length>0)return{...W,players:tA,currentTurn:{...W.currentTurn,phase:"in-debt"},pendingEffect:null};tA[L]={...tA[L],credits:0,depleted:!0},B.current.push({type:"depleted",playerId:W.players[L].id})}}const iA=W.currentTurn.rolledDoubles?"pre-roll":"done";return{...W,players:tA,currentTurn:{...W.currentTurn,phase:iA},pendingEffect:null}})},[]),S=E.useCallback(()=>{o(W=>{const $=W.currentPlayerIndex,L=W.board.findIndex(iA=>iA.type==="jail"),H=pM(W.players[$],L>=0?L:10),P=[...W.players];P[$]=H,B.current.push({type:"jail",playerId:H.id,reason:"go-to-jail"});const tA={...W.currentTurn,phase:"done"};return{...W,players:P,currentTurn:tA,pendingEffect:null}})},[]),k=E.useCallback(()=>{o(W=>Uge(W))},[]),N=E.useCallback(()=>{o(W=>{const $=W.currentPlayerIndex,L=mge(W.players[$],dn.jailBailCost),H=[...W.players];return H[$]=L,B.current.push({type:"jail-free",playerId:L.id,method:"pay"}),{...W,players:H}})},[]),G=E.useCallback(()=>{o(W=>W.currentTurn.phase!=="done"?W:vge(W)),B.current=[],Q.current=!1,r([])},[]),M=E.useCallback(()=>{o(W=>(uQA(W),W))},[]);E.useEffect(()=>{g.finished&&X1()},[g.finished]);const w=E.useCallback(()=>{o(W=>{var H;if(W.currentTurn.phase!=="action"||((H=W.pendingEffect)==null?void 0:H.action)!=="buy-prompt")return W;const $=W.currentTurn.rolledDoubles?"pre-roll":"done",L={...W.currentTurn,phase:$};return{...W,currentTurn:L,pendingEffect:null}})},[]),b=E.useCallback(W=>{o($=>{const L=$.currentPlayerIndex,H=$.players[L],P=$.properties.findIndex(_A=>_A.tileId===W&&_A.ownerId===H.id);if(P===-1)return $;const tA=$.properties[P];if(tA.dormant)return $;const iA=$.board[W];if(!(iA!=null&&iA.upgradeCost)||H.credits<iA.upgradeCost)return $;const oA=Hm(H.id,W,$.board,$.properties);if(tA.upgradeLevel>=oA)return $;const IA=[...$.players];IA[L]={...H,credits:H.credits-iA.upgradeCost};const CA=[...$.properties];return CA[P]={...tA,upgradeLevel:tA.upgradeLevel+1},B.current.push({type:"upgrade",playerId:H.id,tileId:W,level:tA.upgradeLevel+1}),{...$,players:IA,properties:CA}})},[]),_=E.useCallback(W=>{o($=>{const L=$.currentPlayerIndex,H=$.players[L],P=$.properties.findIndex(_A=>_A.tileId===W&&_A.ownerId===H.id);if(P===-1)return $;const tA=$.properties[P],iA=$.board[W];if(!(iA!=null&&iA.cost))return $;if(tA.dormant){const _A=Math.floor(iA.cost*.3);if(H.credits<_A)return $;const uA=[...$.players];uA[L]={...H,credits:H.credits-_A};const X=[...$.properties];return X[P]={...tA,dormant:!1},B.current.push({type:"reactivate",playerId:H.id,tileId:W}),{...$,players:uA,properties:X}}if(tA.upgradeLevel>0)return $;const oA=Math.floor(iA.cost/4),IA=[...$.players];IA[L]={...H,credits:H.credits+oA};const CA=[...$.properties];return CA[P]={...tA,dormant:!0},B.current.push({type:"dormant",playerId:H.id,tileId:W}),{...$,players:IA,properties:CA}})},[]),[K,J]=E.useState(null),q=E.useCallback(W=>{o($=>{const L=$.currentPlayerIndex,H=$.players[L],P=$.properties.findIndex(_A=>_A.tileId===W&&_A.ownerId===H.id);if(P===-1||$.properties[P].upgradeLevel>0)return $;const iA=$.board[W];if(!(iA!=null&&iA.cost))return $;const oA=Math.floor(iA.cost/2),IA=[...$.players];IA[L]={...H,credits:H.credits+oA};const CA=$.properties.filter((_A,uA)=>uA!==P);return B.current.push({type:"sell",playerId:H.id,tileId:W,amount:oA}),{...$,players:IA,properties:CA}})},[]),v=E.useCallback(W=>{o($=>{if($.currentTurn.phase!=="in-debt")return $;const L=$.currentPlayerIndex,H=$.players[L],P=$.properties.findIndex(_A=>_A.tileId===W&&_A.ownerId===H.id);if(P===-1||$.properties[P].upgradeLevel>0)return $;const iA=$.board[W];if(!(iA!=null&&iA.cost))return $;const oA=Math.floor(iA.cost/2),IA=[...$.players];IA[L]={...H,credits:H.credits+oA};const CA=$.properties.filter((_A,uA)=>uA!==P);return B.current.push({type:"debt-sell",playerId:H.id,tileId:W,amount:oA}),{...$,players:IA,properties:CA}})},[]),U=E.useCallback(W=>{o($=>{if($.currentTurn.phase!=="in-debt")return $;const L=$.currentPlayerIndex,H=$.players[L],P=$.properties.findIndex(_A=>_A.tileId===W&&_A.ownerId===H.id);if(P===-1)return $;const tA=$.properties[P];if(tA.upgradeLevel<=0)return $;const iA=$.board[W];if(!(iA!=null&&iA.upgradeCost))return $;const oA=Math.floor(iA.upgradeCost/2),IA=[...$.players];IA[L]={...H,credits:H.credits+oA};const CA=[...$.properties];return CA[P]={...tA,upgradeLevel:tA.upgradeLevel-1},B.current.push({type:"debt-liquidate-arm",playerId:H.id,tileId:W,level:tA.upgradeLevel-1,refund:oA}),{...$,players:IA,properties:CA}})},[]),x=E.useCallback(()=>{o(W=>{if(W.currentTurn.phase!=="in-debt")return W;const $=W.currentPlayerIndex,L=W.players[$],H=W.properties.filter(iA=>iA.ownerId===L.id);if(L.credits<=0&&H.length>0)return W;const P=[...W.players];L.credits<=0&&H.length===0&&(P[$]={...L,credits:0,depleted:!0},B.current.push({type:"depleted",playerId:L.id}));const tA=W.currentTurn.rolledDoubles?"pre-roll":"done";return{...W,players:P,currentTurn:{...W.currentTurn,phase:tA}}})},[]),T=E.useCallback(W=>{o($=>{const L=$.currentPlayerIndex,H=$.players[L],P=$.properties.findIndex(O=>O.tileId===W&&O.ownerId!==H.id&&O.upgradeLevel>0&&!O.dormant);if(P===-1)return $;const tA=$.properties[P],iA=$.board[W];if(!(iA!=null&&iA.group)||!iA.upgradeCost)return $;const oA=$.board.filter(O=>O.group===iA.group).map(O=>O.id),IA=$.properties.filter(O=>oA.includes(O.tileId)&&O.ownerId===H.id&&!O.dormant).length;if(IA<=0)return $;const CA=iA.upgradeCost*(oA.length-IA+1);if(H.credits<CA)return $;const _A=tA.upgradeLevel-1,uA=[...$.players];uA[L]={...H,credits:H.credits-CA};const X=[...$.properties];return X[P]={...tA,upgradeLevel:_A},B.current.push({type:"sabotage",playerId:H.id,tileId:W,cost:CA,newLevel:_A}),{...$,players:uA,properties:X}})},[]),z=E.useCallback((W,$,L,H,P,tA)=>{const iA=s.current,oA=iA.players.find(uA=>uA.id===W);if(!oA||oA.depleted||!L.every(uA=>iA.properties.some(X=>X.tileId===uA&&X.ownerId===oA.id&&X.upgradeLevel===0))||H>0&&oA.credits<H)return;const CA=iA.players.find(uA=>uA.id===$);!CA||CA.depleted||!P.every(uA=>iA.properties.some(X=>X.tileId===uA&&X.ownerId===$&&X.upgradeLevel===0))||tA>0&&CA.credits<tA||J({id:crypto.randomUUID(),offerer:{playerId:oA.id,propertyIds:L,credits:H},recipient:{playerId:$,propertyIds:P,credits:tA},status:"pending"})},[]),Z=E.useCallback(()=>{const W=K;!W||W.status!=="pending"||(o($=>{const L=$.players.findIndex(uA=>uA.id===W.offerer.playerId),H=$.players.findIndex(uA=>uA.id===W.recipient.playerId);if(L===-1||H===-1)return $;const P=$.players[L],tA=$.players[H];if(W.offerer.credits>0&&P.credits<W.offerer.credits||W.recipient.credits>0&&tA.credits<W.recipient.credits)return $;const iA=W.offerer.propertyIds.every(uA=>$.properties.some(X=>X.tileId===uA&&X.ownerId===W.offerer.playerId&&X.upgradeLevel===0)),oA=W.recipient.propertyIds.every(uA=>$.properties.some(X=>X.tileId===uA&&X.ownerId===W.recipient.playerId&&X.upgradeLevel===0));if(!iA||!oA)return $;const IA=[...$.players],CA=W.offerer.credits-W.recipient.credits;IA[L]={...P,credits:P.credits-CA},IA[H]={...tA,credits:tA.credits+CA};const _A=$.properties.map(uA=>W.offerer.propertyIds.includes(uA.tileId)&&uA.ownerId===W.offerer.playerId?{...uA,ownerId:W.recipient.playerId}:W.recipient.propertyIds.includes(uA.tileId)&&uA.ownerId===W.recipient.playerId?{...uA,ownerId:W.offerer.playerId}:uA);return B.current.push({type:"trade",offererId:W.offerer.playerId,recipientId:W.recipient.playerId,offererProps:W.offerer.propertyIds,recipientProps:W.recipient.propertyIds,offererCredits:W.offerer.credits,recipientCredits:W.recipient.credits}),{...$,players:IA,properties:_A}}),J(null))},[K]),eA=E.useCallback(()=>{const W=K;W&&B.current.push({type:"trade-declined",offererId:W.offerer.playerId,recipientId:W.recipient.playerId}),J(null)},[K]),aA=E.useCallback(()=>{o(W=>{const $=W.currentPlayerIndex,L=W.players[$];if(L.armorLevel>=dn.maxArmorLevel||L.credits<dn.armorUpgradeCost)return W;const H=L.armorLevel+1,P=[...W.players];return P[$]={...L,credits:L.credits-dn.armorUpgradeCost,armorLevel:H},B.current.push({type:"upgrade-armor",playerId:L.id,level:H,cost:dn.armorUpgradeCost}),{...W,players:P}})},[]),sA=E.useCallback(()=>{o(W=>{const $=W.currentPlayerIndex,L=W.players[$];if(L.weaponLevel>=dn.maxWeaponLevel||L.credits<dn.weaponUpgradeCost)return W;const H=L.weaponLevel+1,P=[...W.players];return P[$]={...L,credits:L.credits-dn.weaponUpgradeCost,weaponLevel:H},B.current.push({type:"upgrade-weapon",playerId:L.id,level:H,cost:dn.weaponUpgradeCost}),{...W,players:P}})},[]),pA=E.useCallback(()=>{o(W=>{const $=W.currentPlayerIndex,L=W.players[$];if(L.armorLevel<=0)return W;const H=Math.floor(dn.armorUpgradeCost/2),P=L.armorLevel-1,tA=[...W.players];return tA[$]={...L,credits:L.credits+H,armorLevel:P},B.current.push({type:"liquidate-armor",playerId:L.id,level:P,refund:H}),{...W,players:tA}})},[]),gA=E.useCallback(()=>{o(W=>{const $=W.currentPlayerIndex,L=W.players[$];if(L.weaponLevel<=0)return W;const H=Math.floor(dn.weaponUpgradeCost/2),P=L.weaponLevel-1,tA=[...W.players];return tA[$]={...L,credits:L.credits+H,weaponLevel:P},B.current.push({type:"liquidate-weapon",playerId:L.id,level:P,refund:H}),{...W,players:tA}})},[]),yA=E.useCallback(W=>{W&&o($=>{var X,O,cA;const L=W.winnerId,H=(X=$.players[$.currentPlayerIndex])==null?void 0:X.id,P=W.attackerId??H,tA=W.defenderId??((O=$.players.find(wA=>{var xA;return wA.id!==P&&!wA.depleted&&!wA.inJail&&wA.tileIndex===((xA=$.players[$.currentPlayerIndex])==null?void 0:xA.tileIndex)}))==null?void 0:O.id)??((cA=$.players.find(wA=>wA.id!==P))==null?void 0:cA.id);if(!P||!tA)return $;const iA=L===P?tA:P,oA=$.players.findIndex(wA=>wA.id===L),IA=$.players.findIndex(wA=>wA.id===iA);if(oA===-1||IA===-1)return $;const CA=Number.isFinite(W.creditsStolen)?Math.max(0,Math.floor(W.creditsStolen)):0,_A=Math.min(CA,$.players[IA].credits),uA=[...$.players];return uA[oA]={...uA[oA],credits:uA[oA].credits+_A},uA[IA]={...uA[IA],credits:Math.max(0,uA[IA].credits-_A)},B.current.push({type:"raid",attackerId:P,defenderId:tA,winnerId:L,creditsStolen:_A}),{...$,players:uA}})},[]),fA=E.useCallback(W=>{o($=>{var jA,ie,he;if((jA=$.gameRules)!=null&&jA.disableSpyStrike)return $;const L=$.currentTurn.phase;if(L==="in-debt"||L!=="action"&&L!=="pre-roll"&&L!=="done"||$.pendingEffect)return $;const H=$.players[$.currentPlayerIndex];if(!H||H.bankrupt)return $;const P=$.board[H.tileIndex];if(!P||P.type!=="planet"||P.group!==W||(ie=$.spies)!=null&&ie[W])return $;const tA=((he=$.siegeCooldowns)==null?void 0:he[W])??0;if($.roundNumber<tA)return $;const iA=$.board.filter(le=>le.group===W).map(le=>le.id);if(iA.length===0)return $;const oA=new Map(iA.map(le=>{var NA;return[le,(NA=$.properties.find(EA=>EA.tileId===le))==null?void 0:NA.ownerId]})),IA=iA.filter(le=>oA.get(le)===H.id).length,CA=iA.filter(le=>oA.get(le)!==H.id),_A=iA.some(le=>{const NA=oA.get(le);return!!NA&&NA!==H.id}),uA=oA.get(iA[0]),X=!!uA&&uA!==H.id&&iA.every(le=>$.properties.some(NA=>NA.tileId===le&&NA.ownerId===uA&&!NA.dormant));let O=null,cA=0;if(n&&IA>0&&_A)O="foothold",cA=qp;else if(n&&X)O="monopoly",cA=Tp;else if(IA===0){const le=oA.get(iA[0]);if(!le||le===H.id||!iA.every(EA=>$.properties.some(PA=>PA.tileId===EA&&PA.ownerId===le&&!PA.dormant)))return $;O="monopoly",cA=Tp}else if(CA.length>0&&CA.every(le=>!!oA.get(le)))O="foothold",cA=qp;else return $;if(H.credits<cA)return $;const wA=[...$.players];wA[$.currentPlayerIndex]={...H,credits:H.credits-cA};const xA={...$.spies??{},[W]:H.id},YA={...$.spyKinds??{},[W]:O};return B.current.push({type:"spy-plant",playerId:H.id,group:W,cost:cA}),{...$,players:wA,spies:xA,spyKinds:YA}})},[n]),RA=E.useCallback(W=>{o($=>{const L=$.pendingEffect;return!L||L.action!=="spy-clash"||L.step!=="puzzle"||$.currentTurn.phase!=="action"||!L.group||!L.spyOwnerId||!L.defenderId||$.players[$.currentPlayerIndex].id!==L.spyOwnerId?$:(B.current.push({type:"spy-puzzle-result",spyOwnerId:L.spyOwnerId,defenderId:L.defenderId,group:L.group,success:W}),W?{...$,pendingEffect:{...L,step:"shot"}}:WtA($,L,B.current))})},[]),qA=E.useCallback(W=>{o($=>{const L=$.pendingEffect;if(!L||L.action!=="spy-clash"||L.step!=="shot"||$.currentTurn.phase!=="action"||!L.group||!L.spyOwnerId||!L.defenderId)return $;const H=$.players[$.currentPlayerIndex];if(H.id!==L.spyOwnerId)return $;const P=$.players.findIndex(cA=>cA.id===L.defenderId);if(P===-1)return $;const tA=$.players[P];if(B.current.push({type:"spy-shot-result",spyOwnerId:L.spyOwnerId,defenderId:L.defenderId,group:L.group,outcome:W}),W==="miss")return WtA($,L,B.current);const iA={...$.currentTurn},oA=$.board.filter(cA=>cA.group===L.group).map(cA=>cA.id),IA=$.properties.map(cA=>oA.includes(cA.tileId)&&cA.ownerId!==H.id?(B.current.push({type:"seizure",attackerId:H.id,defenderId:tA.id,tileId:cA.tileId,group:L.group}),{...cA,ownerId:H.id}):cA),CA=[...$.players];if(tA.heroId){const cA=tA.heroId;CA[P]={...tA,heroId:void 0,formerHeroId:cA,heroVanquishedById:H.id},B.current.push({type:"hero-vanquished",vanquisherId:H.id,victimId:tA.id,formerHeroId:cA})}const _A={...$.spies??{}};delete _A[L.group];const uA=Object.keys(_A).length>0?_A:void 0,X={...$.siegeCooldowns??{},[L.group]:$.roundNumber+TpA};B.current.push({type:"spy-resolved",spyOwnerId:H.id,defenderId:tA.id,group:L.group,winnerId:H.id,tileIds:oA});const O=iA.rolledDoubles?"pre-roll":"done";return{...$,players:CA,properties:IA,currentTurn:{...iA,phase:O},pendingEffect:null,spies:uA,siegeCooldowns:X}})},[]);return{gameState:g,events:a,pendingEffect:g.pendingEffect,pendingTrade:K,rollTrigger:I,actions:{roll:h,buyProperty:d,payRent:p,heroClashRoll:y,payTax:m,resolveCard:D,goToJail:S,payBailAction:N,endTurn:G,skipBuy:w,upgradeProperty:b,mortgageProperty:_,sellProperty:q,debtSell:v,debtLiquidateArm:U,debtResolve:x,sabotageProperty:T,proposeTrade:z,acceptTrade:Z,declineTrade:eA,saveGame:M,upgradeArmor:aA,upgradeWeapon:sA,liquidateArmor:pA,liquidateWeapon:gA,applyTeleport:k,resolveRaid:yA,plantSpy:fA,spyPuzzleResult:RA,spyShotResult:qA}}}const d_=new Map;let eU=null;function V3(){if(d_.size===0)return;const e=hw();if(e)for(const[A,t]of d_)try{e.emit("client:broadcast-register",{gameId:A,gameMode:t.gameType,name:t.name??null,playerCount:t.playerCount??1,phase:t.phase??null})}catch{}}function qpA(){const e=hw();if(!(!e||eU===e)){if(eU)try{eU.off("connect",V3)}catch{}eU=e;try{e.on("connect",V3)}catch{}}}function Lge(e,A,t){if(!e||!Array.isArray(t)||t.length===0)return;qpA();const i=hw();if(i)try{i.emit("client:game-events",{gameId:e,gameType:A,events:t})}catch{}}function xge(e,A,t){e&&(d_.set(e,{gameType:A,...t}),qpA(),V3())}function Tge(e){if(!e)return;d_.delete(e);const A=hw();if(A)try{A.emit("client:broadcast-unregister",{gameId:e})}catch{}}function Oa(e,A){if(!e||!A)return null;const t=e.players.find(i=>i.id===A);if(!t)return null;if(t.piece){const i=Xi(t.piece);if(i&&i!=="Unknown Fleet")return i}return t.displayName??null}function uh(e,A){return A==null?null:e.find(t=>t.id===A)??null}function qge(e,A){var t;if(!(!e||!A))return(t=e.players.find(i=>i.id===A))==null?void 0:t.credits}function Yge(e,A,t,i){return e.map(n=>{const g={roundNumber:i==null?void 0:i.roundNumber,phase:(i==null?void 0:i.phase)??null};switch(n.type){case"roll":{g.playerName=Oa(A,n.playerId),g.dice=n.dice,g.amount=n.dice[0]+n.dice[1];break}case"move":{g.playerName=Oa(A,n.playerId),g.from=n.from,g.to=n.to,g.passedStart=n.passedStart;const o=uh(t,n.to);g.tileId=n.to,g.tileName=(o==null?void 0:o.name)??null,g.tileGroup=(o==null?void 0:o.group)??null;break}case"buy":{g.playerName=Oa(A,n.playerId),g.tileId=n.tileId;const o=uh(t,n.tileId);g.tileName=(o==null?void 0:o.name)??null,g.tileGroup=(o==null?void 0:o.group)??null,g.amount=n.cost;break}case"energy-toll":{g.playerName=Oa(A,n.payerId),g.otherName=Oa(A,n.ownerId),g.tileId=n.tileId;const o=uh(t,n.tileId);g.tileName=(o==null?void 0:o.name)??null,g.tileGroup=(o==null?void 0:o.group)??null,g.amount=n.amount,g.playerCredits=qge(A,n.payerId);break}case"upgrade":case"sabotage":{g.playerName=Oa(A,n.playerId),g.tileId=n.tileId;const o=uh(t,n.tileId);g.tileName=(o==null?void 0:o.name)??null,g.tileGroup=(o==null?void 0:o.group)??null,g.level=n.level??n.newLevel,g.amount=n.cost;break}case"dormant":case"reactivate":case"repossess":case"sell":{g.playerName=Oa(A,n.playerId),g.tileId=n.tileId;const o=uh(t,n.tileId);g.tileName=(o==null?void 0:o.name)??null,g.tileGroup=(o==null?void 0:o.group)??null,"amount"in n&&(g.amount=n.amount);break}case"jail":case"jail-free":case"depleted":case"win":{g.playerName=Oa(A,n.playerId);break}case"card":{g.playerName=Oa(A,n.playerId);break}case"void-drain":{g.playerName=Oa(A,n.playerId),g.amount=n.amount;break}case"trade":{g.playerName=Oa(A,n.offererId),g.otherName=Oa(A,n.recipientId);break}case"seizure":{g.playerName=Oa(A,n.attackerId),g.otherName=Oa(A,n.defenderId),g.tileId=n.tileId;const o=uh(t,n.tileId);g.tileName=(o==null?void 0:o.name)??null,g.tileGroup=(o==null?void 0:o.group)??null;break}case"upgrade-armor":{g.playerName=Oa(A,n.playerId),g.level=n.level,g.amount=n.cost;break}default:{const o=n;if(o.playerId&&(g.playerName=Oa(A,o.playerId)),o.tileId!=null){g.tileId=o.tileId;const s=uh(t,o.tileId);g.tileName=(s==null?void 0:s.name)??null,g.tileGroup=(s==null?void 0:s.group)??null}typeof o.amount=="number"&&(g.amount=o.amount)}}return{type:n.type,raw:n,meta:g}})}const Hge=3e3,VB=3e3,Oge=3e3,Pge=Oge+750,jge=500,zge=750;function Zge({isMyTurn:e,phase:A,pendingEffect:t,pendingTrade:i,inJail:n,credits:g,botPlayerIds:o,currentPlayerId:s,properties:a,board:r,actions:I,gameFinished:c,players:l,spies:B,siegeCooldowns:Q,roundNumber:h,autoplay:d=!1}){const p=E.useRef(null),y=E.useRef(null),m=E.useRef(null);E.useEffect(()=>{if(!i||i.status!=="pending"||!o.includes(i.recipient.playerId))return;const D=setTimeout(()=>{const S=i.recipient.playerId,k=(M,w)=>{const b=r[M],_=(b==null?void 0:b.cost)??100,K=a.find(q=>q.tileId===M),J=((K==null?void 0:K.upgradeLevel)??0)*Math.round(((b==null?void 0:b.upgradeCost)??_)*.6);if(w==="offerer"&&(b!=null&&b.group)){const v=r.filter(x=>x.group===b.group).map(x=>x.id).filter(x=>x!==M),U=v.filter(x=>a.some(T=>T.tileId===x&&T.ownerId===S&&!T.dormant)).length;if(v.length>0&&U===v.length)return Math.round(_*2.5)+J;if(U>0)return Math.round(_*1.6)+J}if(w==="recipient"&&(b!=null&&b.group)){const v=r.filter(x=>x.group===b.group).map(x=>x.id).filter(x=>x!==M),U=v.filter(x=>a.some(T=>T.tileId===x&&T.ownerId===S&&!T.dormant)).length;return U===0?Math.round(_*.8)+J:U===v.length?Math.round(_*1.8)+J:Math.round(_*1)+J}return _+J},N=i.offerer.credits+i.offerer.propertyIds.reduce((M,w)=>M+k(w,"offerer"),0),G=i.recipient.credits+i.recipient.propertyIds.reduce((M,w)=>M+k(w,"recipient"),0);N>=G*.85?I.acceptTrade():I.declineTrade()},VB);return()=>clearTimeout(D)},[i,o,I,r,a]),E.useEffect(()=>{var k,N;if(e||c||!o.includes(s))return;const D=()=>{p.current&&clearTimeout(p.current)};if((A==="pre-roll"||A==="action"||A==="done")&&!t&&I.plantSpy&&l&&g>=qp&&m.current!==`${s}|${h??0}`&&(((k=l.find(G=>G.id===s))==null?void 0:k.heroLockoutTurnsRemaining)??0)===0){const G=`${s}|${h??0}`,M=l.find(b=>b.id===s),w=M?r[M.tileIndex]:null;if(w&&w.type==="planet"&&w.group){const b=w.group,_=(Q==null?void 0:Q[b])??0,K=!(B!=null&&B[b]),J=(h??0)>=_;if(K&&J){const q=r.filter(v=>v.group===b).map(v=>v.id);if(q.length>0){const v=new Map(q.map(aA=>{var sA;return[aA,(sA=a.find(pA=>pA.tileId===aA))==null?void 0:sA.ownerId]})),U=q.filter(aA=>v.get(aA)===s).length,x=q.filter(aA=>v.get(aA)!==s);let T=!1;const z=q.some(aA=>{const sA=v.get(aA);return!!sA&&sA!==s}),Z=v.get(q[0]),eA=!!Z&&Z!==s&&q.every(aA=>a.some(sA=>sA.tileId===aA&&sA.ownerId===Z&&!sA.dormant));if(d&&U>0&&z)T=g>=qp;else if(d&&eA)T=g>=Tp;else if(U===0){const aA=v.get(q[0]);T=!!aA&&aA!==s&&q.every(pA=>a.some(gA=>gA.tileId===pA&&gA.ownerId===aA&&!gA.dormant))&&g>=Tp}else x.length>0&&x.every(aA=>!!v.get(aA))&&(T=g>=qp);if(T)return m.current=G,p.current=setTimeout(()=>{var aA;(aA=I.plantSpy)==null||aA.call(I,b),p.current=setTimeout(()=>{A==="pre-roll"?I.roll():I.endTurn()},zge)},jge),D}}}}if(A==="pre-roll"){const G=`${s}|${h??0}`;if(I.proposeTrade&&y.current!==G&&!i&&l){const w=[],b=a.filter(K=>K.ownerId===s&&!K.dormant);for(const K of b){const J=r[K.tileId];if(!J||J.type!=="planet"||!J.group)continue;const q=r.filter(T=>T.group===J.group).map(T=>T.id);if(q.length<2)continue;const v=q.filter(T=>T!==K.tileId),U=new Map;for(const T of v){const z=(N=a.find(Z=>Z.tileId===T))==null?void 0:N.ownerId;!z||z===s||U.set(z,(U.get(z)??0)+1)}const x=K.upgradeLevel*Math.round((J.upgradeCost??J.cost??100)*.6);for(const[T,z]of U){const Z=l.find(pA=>pA.id===T&&!pA.depleted);if(!Z)continue;const eA=z===v.length,aA=eA?1.6:1.05,sA=Math.min(Math.max(0,Z.credits-30),Math.max(20,Math.round((J.cost??100)*aA)+x));sA<=0||w.push({rivalId:T,offerTileIds:[K.tileId],askCredits:sA,requestTileIds:[],giveCredits:0,priority:(eA?100:10)+z})}if(U.size===0)for(const T of l){if(T.id===s||T.depleted)continue;const z=Math.min(Math.max(0,T.credits-30),Math.max(20,Math.round((J.cost??100)*.95)+x));z<=0||w.push({rivalId:T.id,offerTileIds:[K.tileId],askCredits:z,requestTileIds:[],giveCredits:0,priority:1})}}const _=new Map;for(const K of b){const J=r[K.tileId];J!=null&&J.group&&_.set(J.group,(_.get(J.group)??0)+1)}for(const K of r){if(!K||K.type!=="planet"||!K.group)continue;const J=a.find(sA=>sA.tileId===K.id);if(!J||J.ownerId===s||J.dormant)continue;const q=l.find(sA=>sA.id===J.ownerId&&!sA.depleted);if(!q)continue;const v=r.filter(sA=>sA.group===K.group).map(sA=>sA.id);if(v.length<2)continue;const U=_.get(K.group)??0,x=v.length,T=U===x-1;let z,Z;if(T)z=1.6,Z=90;else if(U>0)z=1.2,Z=8+U;else{if(g<250)continue;const sA=v.every(pA=>a.some(gA=>gA.tileId===pA&&gA.ownerId===q.id&&!gA.dormant));z=sA?1:.95,Z=sA?4:2}const eA=J.upgradeLevel*Math.round((K.upgradeCost??K.cost??100)*.6),aA=Math.min(g-30,Math.max(20,Math.round((K.cost??100)*z)+eA));aA<=0||w.push({rivalId:q.id,offerTileIds:[],askCredits:0,requestTileIds:[K.id],giveCredits:aA,priority:Z})}if(w.length>0){w.sort((J,q)=>q.priority-J.priority);const K=w[0];return y.current=G,p.current=setTimeout(()=>{var J;(J=I.proposeTrade)==null||J.call(I,s,K.rivalId,K.offerTileIds,K.giveCredits,K.requestTileIds,K.askCredits)},VB),D}}const M=a.filter(w=>w.ownerId===s&&!w.dormant&&w.upgradeLevel<Hm(s,w.tileId,r,a)).map(w=>{var b;return{...w,cost:((b=r[w.tileId])==null?void 0:b.upgradeCost)??1/0}}).filter(w=>w.cost<=g).sort((w,b)=>w.cost-b.cost);M.length>0?p.current=setTimeout(()=>{I.upgradeProperty(M[0].tileId)},VB):p.current=setTimeout(()=>{n&&g>=dn.jailBailCost&&I.payBailAction(),I.roll()},Hge)}else if(A==="action"&&t)p.current=setTimeout(()=>{var G,M;switch(t.action){case"buy-prompt":t.amount!=null&&g>=t.amount?I.buyProperty(t.tileId):I.skipBuy();break;case"energy-toll":I.payRent();break;case"hero-clash":I.heroClashRoll();break;case"void-drain":I.payTax();break;case"draw-card":I.resolveCard();break;case"spy-clash":if(d)break;if(t.step==="shot"){const w=Math.random(),b=w<.15?"bullseye":w<.55?"hit":w<.8?"graze":"miss";(G=I.spyShotResult)==null||G.call(I,b)}else{const w=Math.random()<.65;(M=I.spyPuzzleResult)==null||M.call(I,w)}break;default:I.endTurn()}},VB);else if(A==="action"&&!t)p.current=setTimeout(()=>{I.endTurn()},VB);else if(A==="in-debt"){const G=a.filter(b=>b.ownerId===s).map(b=>{var _;return{...b,value:((_=r[b.tileId])==null?void 0:_.cost)??0}}).sort((b,_)=>b.value-_.value),M=G.find(b=>b.upgradeLevel>0),w=G.find(b=>b.upgradeLevel<=0);g<=0&&G.length>0?w?p.current=setTimeout(()=>{I.debtSell(w.tileId)},VB):M?p.current=setTimeout(()=>{I.debtLiquidateArm(M.tileId)},VB):p.current=setTimeout(()=>{I.debtResolve()},VB):p.current=setTimeout(()=>{I.debtResolve()},VB)}else A==="done"&&(p.current=setTimeout(()=>{I.endTurn()},Pge));return D},[e,A,t,i,n,g,o,s,a,r,I,c,l,B,Q,h,d])}const Wge="/assets/azzure_turret_1-BSF6kRPN.png",Vge="/assets/azzure_turret_2-BS9BQ0Wh.png",Xge="/assets/azzure_turret_3-wzqgy1Re.png",$ge="/assets/azzure_turret_4-DszsO8pE.png",Aoe="/assets/azzure_turret_5-BDNt-52F.png",eoe="data:image/png;base64, ",toe="/assets/crimson_turret_2-Dzdivnfl.png",ioe="/assets/crimson_turret_3-FCW5cjNx.png",noe="/assets/crimson_turret_4-x6XdwjO_.png",goe="/assets/crimson_turret_5-COBT408e.png",ooe="/assets/emerald_turret_1-BAxyQCsm.png",soe="/assets/emerald_turret_2-Cb5EKOec.png",aoe="/assets/emerald_turret_3-Djy1RF5l.png",roe="/assets/emerald_turret_4-Dvqo9xGL.png",Ioe="/assets/emerald_turret_5-DbPXnTsf.png",Coe="/assets/gold_turret_1-ouFUy0uc.png",coe="/assets/gold_turret_2-lUsFpFSb.png",loe="/assets/gold_turret_3-DdV6hrcF.png",Boe="/assets/gold_turret_4-DTvBKETa.png",Eoe="/assets/gold_turret_5-BoxTnz4z.png",Qoe="/assets/silver_turret_1-BruS00ga.png",uoe="/assets/silver_turret_2-BIg82_xi.png",doe="/assets/silver_turret_3-CJ-TtmjD.png",hoe="/assets/silver_turret_4-Db8itTac.png",poe="/assets/silver_turret_5-BuHepi2d.png",foe="/assets/void_turret_1-CR92XhVP.png",yoe="/assets/void_turret_2-CTH3oOBV.png",Doe="/assets/void_turret_3-BoJPDIYG.png",moe="/assets/void_turret_4-BAmR9i7p.png",Soe="/assets/void_turret_5-D-M1TouY.png",YpA=[{wedge:"M934.09,162.59 A840,840 0 0 1 1065.91,162.59 L1056.49,282.22 A720,720 0 0 0 943.51,282.22 Z",fill:"#1a237e",strip:null,stripColor:null},{wedge:"M1065.91,162.59 A840,840 0 0 1 1196.09,183.21 L1168.08,299.89 A720,720 0 0 0 1056.49,282.22 Z",fill:"#0d1b2a",strip:"M1065.91,162.59 A840,840 0 0 1 1196.09,183.21 L1192.36,198.77 A824,824 0 0 0 1064.65,178.54 Z",stripColor:"#7b2ff2"},{wedge:"M1196.09,183.21 A840,840 0 0 1 1321.45,223.94 L1275.53,334.81 A720,720 0 0 0 1168.08,299.89 Z",fill:"#4a148c",strip:null,stripColor:null},{wedge:"M1321.45,223.94 A840,840 0 0 1 1438.90,283.78 L1376.20,386.10 A720,720 0 0 0 1275.53,334.81 Z",fill:"#0d1b2a",strip:"M1321.45,223.94 A840,840 0 0 1 1438.90,283.78 L1430.54,297.42 A824,824 0 0 0 1315.33,238.72 Z",stripColor:"#7b2ff2"},{wedge:"M1438.90,283.78 A840,840 0 0 1 1545.54,361.26 L1467.60,452.51 A720,720 0 0 0 1376.20,386.10 Z",fill:"#b71c1c",strip:null,stripColor:null},{wedge:"M1545.54,361.26 A840,840 0 0 1 1638.74,454.46 L1547.49,532.40 A720,720 0 0 0 1467.60,452.51 Z",fill:"#37474f",strip:null,stripColor:null},{wedge:"M1638.74,454.46 A840,840 0 0 1 1716.22,561.10 L1613.90,623.80 A720,720 0 0 0 1547.49,532.40 Z",fill:"#0d1b2a",strip:"M1638.74,454.46 A840,840 0 0 1 1716.22,561.10 L1702.58,569.46 A824,824 0 0 0 1626.57,464.85 Z",stripColor:"#00e5ff"},{wedge:"M1716.22,561.10 A840,840 0 0 1 1776.06,678.55 L1665.19,724.47 A720,720 0 0 0 1613.90,623.80 Z",fill:"#1b5e20",strip:null,stripColor:null},{wedge:"M1776.06,678.55 A840,840 0 0 1 1816.79,803.91 L1700.11,831.92 A720,720 0 0 0 1665.19,724.47 Z",fill:"#0d1b2a",strip:"M1776.06,678.55 A840,840 0 0 1 1816.79,803.91 L1801.23,807.64 A824,824 0 0 0 1761.28,684.67 Z",stripColor:"#00e5ff"},{wedge:"M1816.79,803.91 A840,840 0 0 1 1837.41,934.09 L1717.78,943.51 A720,720 0 0 0 1700.11,831.92 Z",fill:"#0d1b2a",strip:"M1816.79,803.91 A840,840 0 0 1 1837.41,934.09 L1821.46,935.35 A824,824 0 0 0 1801.23,807.64 Z",stripColor:"#00e5ff"},{wedge:"M1837.41,934.09 A840,840 0 0 1 1837.41,1065.91 L1717.78,1056.49 A720,720 0 0 0 1717.78,943.51 Z",fill:"#e65100",strip:null,stripColor:null},{wedge:"M1837.41,1065.91 A840,840 0 0 1 1816.79,1196.09 L1700.11,1168.08 A720,720 0 0 0 1717.78,1056.49 Z",fill:"#0d1b2a",strip:"M1837.41,1065.91 A840,840 0 0 1 1816.79,1196.09 L1801.23,1192.36 A824,824 0 0 0 1821.46,1064.65 Z",stripColor:"#ff9100"},{wedge:"M1816.79,1196.09 A840,840 0 0 1 1776.06,1321.45 L1665.19,1275.53 A720,720 0 0 0 1700.11,1168.08 Z",fill:"#006064",strip:null,stripColor:null},{wedge:"M1776.06,1321.45 A840,840 0 0 1 1716.22,1438.90 L1613.90,1376.20 A720,720 0 0 0 1665.19,1275.53 Z",fill:"#0d1b2a",strip:"M1776.06,1321.45 A840,840 0 0 1 1716.22,1438.90 L1702.58,1430.54 A824,824 0 0 0 1761.28,1315.33 Z",stripColor:"#ff9100"},{wedge:"M1716.22,1438.90 A840,840 0 0 1 1638.74,1545.54 L1547.49,1467.60 A720,720 0 0 0 1613.90,1376.20 Z",fill:"#0d1b2a",strip:"M1716.22,1438.90 A840,840 0 0 1 1638.74,1545.54 L1626.57,1535.15 A824,824 0 0 0 1702.58,1430.54 Z",stripColor:"#ff9100"},{wedge:"M1638.74,1545.54 A840,840 0 0 1 1545.54,1638.74 L1467.60,1547.49 A720,720 0 0 0 1547.49,1467.60 Z",fill:"#37474f",strip:null,stripColor:null},{wedge:"M1545.54,1638.74 A840,840 0 0 1 1438.90,1716.22 L1376.20,1613.90 A720,720 0 0 0 1467.60,1547.49 Z",fill:"#0d1b2a",strip:"M1545.54,1638.74 A840,840 0 0 1 1438.90,1716.22 L1430.54,1702.58 A824,824 0 0 0 1535.15,1626.57 Z",stripColor:"#ff1744"},{wedge:"M1438.90,1716.22 A840,840 0 0 1 1321.45,1776.06 L1275.53,1665.19 A720,720 0 0 0 1376.20,1613.90 Z",fill:"#4a148c",strip:null,stripColor:null},{wedge:"M1321.45,1776.06 A840,840 0 0 1 1196.09,1816.79 L1168.08,1700.11 A720,720 0 0 0 1275.53,1665.19 Z",fill:"#0d1b2a",strip:"M1321.45,1776.06 A840,840 0 0 1 1196.09,1816.79 L1192.36,1801.23 A824,824 0 0 0 1315.33,1761.28 Z",stripColor:"#ff1744"},{wedge:"M1196.09,1816.79 A840,840 0 0 1 1065.91,1837.41 L1056.49,1717.78 A720,720 0 0 0 1168.08,1700.11 Z",fill:"#0d1b2a",strip:"M1196.09,1816.79 A840,840 0 0 1 1065.91,1837.41 L1064.65,1821.46 A824,824 0 0 0 1192.36,1801.23 Z",stripColor:"#ff1744"},{wedge:"M1065.91,1837.41 A840,840 0 0 1 934.09,1837.41 L943.51,1717.78 A720,720 0 0 0 1056.49,1717.78 Z",fill:"#2e7d32",strip:null,stripColor:null},{wedge:"M934.09,1837.41 A840,840 0 0 1 803.91,1816.79 L831.92,1700.11 A720,720 0 0 0 943.51,1717.78 Z",fill:"#0d1b2a",strip:"M934.09,1837.41 A840,840 0 0 1 803.91,1816.79 L807.64,1801.23 A824,824 0 0 0 935.35,1821.46 Z",stripColor:"#ffd600"},{wedge:"M803.91,1816.79 A840,840 0 0 1 678.55,1776.06 L724.47,1665.19 A720,720 0 0 0 831.92,1700.11 Z",fill:"#1b5e20",strip:null,stripColor:null},{wedge:"M678.55,1776.06 A840,840 0 0 1 561.10,1716.22 L623.80,1613.90 A720,720 0 0 0 724.47,1665.19 Z",fill:"#0d1b2a",strip:"M678.55,1776.06 A840,840 0 0 1 561.10,1716.22 L569.46,1702.58 A824,824 0 0 0 684.67,1761.28 Z",stripColor:"#ffd600"},{wedge:"M561.10,1716.22 A840,840 0 0 1 454.46,1638.74 L532.40,1547.49 A720,720 0 0 0 623.80,1613.90 Z",fill:"#0d1b2a",strip:"M561.10,1716.22 A840,840 0 0 1 454.46,1638.74 L464.85,1626.57 A824,824 0 0 0 569.46,1702.58 Z",stripColor:"#ffd600"},{wedge:"M454.46,1638.74 A840,840 0 0 1 361.26,1545.54 L452.51,1467.60 A720,720 0 0 0 532.40,1547.49 Z",fill:"#37474f",strip:null,stripColor:null},{wedge:"M361.26,1545.54 A840,840 0 0 1 283.78,1438.90 L386.10,1376.20 A720,720 0 0 0 452.51,1467.60 Z",fill:"#0d1b2a",strip:"M361.26,1545.54 A840,840 0 0 1 283.78,1438.90 L297.42,1430.54 A824,824 0 0 0 373.43,1535.15 Z",stripColor:"#00e676"},{wedge:"M283.78,1438.90 A840,840 0 0 1 223.94,1321.45 L334.81,1275.53 A720,720 0 0 0 386.10,1376.20 Z",fill:"#0d1b2a",strip:"M283.78,1438.90 A840,840 0 0 1 223.94,1321.45 L238.72,1315.33 A824,824 0 0 0 297.42,1430.54 Z",stripColor:"#00e676"},{wedge:"M223.94,1321.45 A840,840 0 0 1 183.21,1196.09 L299.89,1168.08 A720,720 0 0 0 334.81,1275.53 Z",fill:"#006064",strip:null,stripColor:null},{wedge:"M183.21,1196.09 A840,840 0 0 1 162.59,1065.91 L282.22,1056.49 A720,720 0 0 0 299.89,1168.08 Z",fill:"#0d1b2a",strip:"M183.21,1196.09 A840,840 0 0 1 162.59,1065.91 L178.54,1064.65 A824,824 0 0 0 198.77,1192.36 Z",stripColor:"#00e676"},{wedge:"M162.59,1065.91 A840,840 0 0 1 162.59,934.09 L282.22,943.51 A720,720 0 0 0 282.22,1056.49 Z",fill:"#d50000",strip:null,stripColor:null},{wedge:"M162.59,934.09 A840,840 0 0 1 183.21,803.91 L299.89,831.92 A720,720 0 0 0 282.22,943.51 Z",fill:"#0d1b2a",strip:"M162.59,934.09 A840,840 0 0 1 183.21,803.91 L198.77,807.64 A824,824 0 0 0 178.54,935.35 Z",stripColor:"#2979ff"},{wedge:"M183.21,803.91 A840,840 0 0 1 223.94,678.55 L334.81,724.47 A720,720 0 0 0 299.89,831.92 Z",fill:"#0d1b2a",strip:"M183.21,803.91 A840,840 0 0 1 223.94,678.55 L238.72,684.67 A824,824 0 0 0 198.77,807.64 Z",stripColor:"#2979ff"},{wedge:"M223.94,678.55 A840,840 0 0 1 283.78,561.10 L386.10,623.80 A720,720 0 0 0 334.81,724.47 Z",fill:"#4a148c",strip:null,stripColor:null},{wedge:"M283.78,561.10 A840,840 0 0 1 361.26,454.46 L452.51,532.40 A720,720 0 0 0 386.10,623.80 Z",fill:"#0d1b2a",strip:"M283.78,561.10 A840,840 0 0 1 361.26,454.46 L373.43,464.85 A824,824 0 0 0 297.42,569.46 Z",stripColor:"#2979ff"},{wedge:"M361.26,454.46 A840,840 0 0 1 454.46,361.26 L532.40,452.51 A720,720 0 0 0 452.51,532.40 Z",fill:"#37474f",strip:null,stripColor:null},{wedge:"M454.46,361.26 A840,840 0 0 1 561.10,283.78 L623.80,386.10 A720,720 0 0 0 532.40,452.51 Z",fill:"#1b5e20",strip:null,stripColor:null},{wedge:"M561.10,283.78 A840,840 0 0 1 678.55,223.94 L724.47,334.81 A720,720 0 0 0 623.80,386.10 Z",fill:"#0d1b2a",strip:"M561.10,283.78 A840,840 0 0 1 678.55,223.94 L684.67,238.72 A824,824 0 0 0 569.46,297.42 Z",stripColor:"#e040fb"},{wedge:"M678.55,223.94 A840,840 0 0 1 803.91,183.21 L831.92,299.89 A720,720 0 0 0 724.47,334.81 Z",fill:"#b71c1c",strip:null,stripColor:null},{wedge:"M803.91,183.21 A840,840 0 0 1 934.09,162.59 L943.51,282.22 A720,720 0 0 0 831.92,299.89 Z",fill:"#0d1b2a",strip:"M803.91,183.21 A840,840 0 0 1 934.09,162.59 L935.35,178.54 A824,824 0 0 0 807.64,198.77 Z",stripColor:"#e040fb"}],h_=1e3,p_=780,X3=40,TZ=Array.from({length:X3},(e,A)=>{const t=A*360/X3-90,i=t*Math.PI/180;return{x:h_+p_*Math.cos(i),y:h_+p_*Math.sin(i),rotation:t+90}});function HpA(e){return e===X3?TZ:Array.from({length:e},(A,t)=>{const i=t*360/e-90,n=i*Math.PI/180;return{x:h_+p_*Math.cos(n),y:h_+p_*Math.sin(n),rotation:i+90}})}function Om(e,A,t,i){return i===t||((e*360/i-90+A)%360+360)%360<=180?e:(e+t)%i}const woe=hB.FLIGHT_DURATION_MS,VtA=hB.LIFTOFF_DELAY_MS,OpA=hB.BOARD_ROTATE_MS,koe=`transform ${OpA}ms cubic-bezier(0.4, 0, 0.2, 1)`,XtA=1e3,JY=hB.DESTROY_BLAST_MS;function Moe(e){return e<=1?1:e===2?.72:e===3?.62:e===4?.54:e===5?.48:.44}function Noe(e){return e<=1?1:e===2?.62:e===3?.52:e===4?.44:e===5?.39:.35}function Roe(e,A){if(A<=1)return{dx:0,dy:0,headingDeg:0};if(A<=6){const y=-Math.PI/2,m=A===2?42:38,D={1:[0],2:[0,3],3:[0,2,4],4:[0,2,3,5],5:[0,1,2,4,5],6:[0,1,2,3,4,5]},S=D[A]??D[6],k=S[e%S.length],N=y+k*(2*Math.PI/6),G=Math.round(Math.cos(N)*m*100)/100,M=Math.round(Math.sin(N)*m*100)/100,w=Math.atan2(-M,-G)*180/Math.PI;return{dx:G,dy:M,headingDeg:w}}const t=[6,10,14];let i=0,n=e,g=A,o=t[0];for(;i<t.length-1&&n>=o;)n-=o,g-=o,i+=1,o=Math.min(t[i],Math.max(g,1));const s=42,a=16,r=20,I=s/(2*Math.sin(Math.PI/Math.max(o,2))),c=Math.max(r,I)+i*a,B=-Math.PI/2+2*Math.PI*n/Math.max(o,1),Q=Math.round(Math.cos(B)*c*100)/100,h=Math.round(Math.sin(B)*c*100)/100,d=Math.atan2(-h,-Q)*180/Math.PI;return{dx:Q,dy:h,headingDeg:d}}function Goe(e,A){const t={1:[{dx:0,dy:0}],2:[{dx:-30,dy:-2},{dx:30,dy:-2}],3:[{dx:-30,dy:-14},{dx:30,dy:-14},{dx:0,dy:24}],4:[{dx:-32,dy:-16},{dx:32,dy:-16},{dx:-32,dy:18},{dx:32,dy:18}],5:[{dx:-34,dy:-18},{dx:0,dy:-20},{dx:34,dy:-18},{dx:-18,dy:20},{dx:18,dy:20}],6:[{dx:-39,dy:-21},{dx:0,dy:-23},{dx:39,dy:-21},{dx:-39,dy:24},{dx:0,dy:26},{dx:39,dy:24}]};if(A<=1)return{dx:0,dy:0,headingDeg:0};const i=t[Math.min(6,A)]??t[6],n=i[e%i.length],g=Math.atan2(-n.dy,-n.dx)*180/Math.PI;return{dx:n.dx,dy:n.dy,headingDeg:g}}const boe=0,Uoe=({players:e,currentPlayerId:A,onMoveStart:t,onFlightStart:i,onArrival:n,zoom:g=10,boardRotation:o=0,tileCount:s=40,gameTileCount:a,jailTileIndex:r=10,onlyCurrentPlayer:I=!1})=>{const c=a??s,l=s===40?TZ:HpA(s),[B,Q]=E.useState(()=>{const v={};for(const U of e)v[U.id]=U.tileIndex;return v}),[h,d]=E.useState(new Set),[p,y]=E.useState(new Set),[m,D]=E.useState({}),[S,k]=E.useState(new Set),N=E.useRef({}),G=E.useRef({}),M=E.useRef({}),[w,b]=E.useState({});E.useEffect(()=>{for(const v of e){const U=v.tileIndex,x=N.current[v.id];if(x===void 0){N.current[v.id]=U,Q(Z=>({...Z,[v.id]:U}));continue}if(x===U)continue;N.current[v.id]=U,clearTimeout(M.current[v.id+"_rotate"]),clearTimeout(M.current[v.id+"_snap"]),clearTimeout(M.current[v.id+"_arrive"]),clearTimeout(M.current[v.id+"_landed"]);const T=v.id===A;d(Z=>{const eA=new Set(Z);return eA.add(v.id),eA}),D(Z=>({...Z,[v.id]:o})),T&&(i==null||i()),M.current[v.id+"_rotate"]=setTimeout(()=>{T&&(t==null||t(x,U))},VtA);const z=VtA+OpA+hB.SNAP_BUFFER_MS;M.current[v.id+"_snap"]=setTimeout(()=>{Q(Z=>({...Z,[v.id]:U})),D(Z=>{const eA={...Z};return delete eA[v.id],eA}),k(Z=>{const eA=new Set(Z);return eA.add(v.id),eA}),y(Z=>{const eA=new Set(Z);return eA.add(v.id),eA})},z),M.current[v.id+"_landed"]=setTimeout(()=>{k(Z=>{const eA=new Set(Z);return eA.delete(v.id),eA})},z+100),M.current[v.id+"_arrive"]=setTimeout(()=>{d(Z=>{const eA=new Set(Z);return eA.delete(v.id),eA}),y(Z=>{const eA=new Set(Z);return eA.delete(v.id),eA}),T&&(n==null||n(U))},woe)}},[e,A,t,i,n]),E.useEffect(()=>{const v=new Set(e.map(U=>U.id));for(const U of e){const x=G.current[U.id]??!1;if(G.current[U.id]=U.depleted,x||!U.depleted)continue;const T=B[U.id]??U.tileIndex;console.log("[PIECE EXPLOSION] Triggering for",U.displayName,"at tile",T,"duration:",JY,"ms"),b(z=>({...z,[U.id]:{tileIndex:T}})),clearTimeout(M.current[U.id+"_destroy"]),M.current[U.id+"_destroy"]=setTimeout(()=>{console.log("[PIECE EXPLOSION] Removing piece",U.displayName,"after",JY,"ms"),b(z=>{if(!z[U.id])return z;const Z={...z};return delete Z[U.id],Z})},JY)}b(U=>{let x=!1;const T={};for(const[z,Z]of Object.entries(U)){if(!v.has(z)){x=!0,clearTimeout(M.current[z+"_destroy"]);continue}T[z]=Z}return x?T:U})},[e,B]),E.useEffect(()=>()=>{for(const v of Object.values(M.current))clearTimeout(v)},[]);const _=E.useMemo(()=>e.filter(v=>(!I||v.id===A)&&(!v.depleted||!!w[v.id])),[e,w,I,A]),K=E.useMemo(()=>{const v=new Map;for(const U of _){const x=B[U.id]??U.tileIndex,T=v.get(x)??[];T.push(U),v.set(x,T)}return v},[_,B]),J=E.useMemo(()=>[..._].sort((v,U)=>(v.id===A?1:0)-(U.id===A?1:0)),[_,A]),q=v=>`zentara-piece-outline-${v.replace(/[^a-zA-Z0-9_-]/g,"-")}`;return C.jsxs("g",{id:"piece-layer",children:[C.jsxs("defs",{children:[C.jsx("filter",{id:"zentara-piece-shadow",x:"0%",y:"0%",width:"100%",height:"100%",children:C.jsx("feColorMatrix",{type:"matrix",values:"0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 1 0"})}),J.map(v=>C.jsxs("filter",{id:q(v.id),x:"-35%",y:"-35%",width:"170%",height:"170%",colorInterpolationFilters:"sRGB",children:[C.jsx("feMorphology",{in:"SourceAlpha",operator:"dilate",radius:"2.2",result:"expanded"}),C.jsx("feFlood",{floodColor:v.pieceColor||"#ffffff",floodOpacity:"0.95",result:"factionColor"}),C.jsx("feComposite",{in:"factionColor",in2:"expanded",operator:"in",result:"coloredExpanded"}),C.jsx("feComposite",{in:"coloredExpanded",in2:"SourceAlpha",operator:"out",result:"outline"}),C.jsx("feGaussianBlur",{in:"outline",stdDeviation:"1.4",result:"softOutline"}),C.jsxs("feMerge",{children:[C.jsx("feMergeNode",{in:"softOutline"}),C.jsx("feMergeNode",{in:"outline"})]})]},`outline-filter-${v.id}`))]}),J.map(v=>{var iA;const U=B[v.id]??v.tileIndex,x=m[v.id],z=Om(U,x!==void 0?x:o,c,s),Z=l[z];if(!Z)return null;const eA=K.get(U)??[v],aA=eA.indexOf(v),sA=U===0,pA=sA?Goe(aA,eA.length):Roe(aA,eA.length),gA=sA?Noe(eA.length):Moe(eA.length),yA=h.has(v.id),fA=v.tileIndex===r&&U===r&&!yA?v.inJail?"Cryosleep":"Visiting":void 0,RA=pA.headingDeg+boe,qA=Z,W=Om(v.tileIndex,o,c,s),$=l[W],L=yA&&qA&&$&&v.tileIndex!==U?Math.atan2($.y-qA.y,$.x-qA.x)*180/Math.PI:RA,H=x!==void 0?{transformOrigin:`${XtA}px ${XtA}px`,transform:`rotate(${x-o}deg)`,transition:koe,willChange:"transform"}:void 0,P=w[v.id]??null,tA={transform:`translate(${pA.dx}px, ${pA.dy}px)`};return C.jsx("g",{style:H,children:C.jsxs("g",{className:"zentara-piece-slot",style:tA,children:[C.jsx(wQA,{initialX:Z.x,initialY:Z.y,shape:v.piece,isCurrentPlayer:v.id===A,rotation:x!==void 0?-x:-o,rotationTransition:x===void 0&&!S.has(v.id),zoom:g,label:fA,isMoving:yA,isLanding:p.has(v.id),landedHeading:RA,flightHeading:L,sizeScale:gA,pieceColor:v.pieceColor,outlineFilterId:q(v.id),tier:(v.heroId?(iA=ms[v.heroId])==null?void 0:iA.tier:void 0)??1}),P&&C.jsxs("g",{transform:`translate(${Z.x},${Z.y})`,pointerEvents:"none",children:[C.jsxs("circle",{r:22,fill:"none",stroke:"rgba(255,190,60,0.85)",strokeWidth:14,opacity:1,children:[C.jsx("animate",{attributeName:"opacity",from:"1",to:"0",dur:"1.2s",fill:"freeze"}),C.jsx("animate",{attributeName:"r",from:"22",to:"172",dur:"1.2s",fill:"freeze"}),C.jsx("animate",{attributeName:"stroke-width",from:"14",to:"2",dur:"1.2s",fill:"freeze"})]}),C.jsxs("circle",{r:14,fill:"rgba(255,120,40,0.35)",opacity:.9,children:[C.jsx("animate",{attributeName:"opacity",from:"0.9",to:"0",dur:"1.1s",fill:"freeze"}),C.jsx("animate",{attributeName:"r",from:"14",to:"124",dur:"1.1s",fill:"freeze"})]}),C.jsxs("circle",{r:8,fill:"rgba(255,245,190,0.7)",opacity:1,children:[C.jsx("animate",{attributeName:"opacity",from:"1",to:"0",dur:"0.9s",fill:"freeze"}),C.jsx("animate",{attributeName:"r",from:"8",to:"78",dur:"0.9s",fill:"freeze"})]})]})]})},`piece-${v.id}`)})]})},voe=ue.memo(Uoe),PpA="data:image/webp;base64, ",jpA="data:image/webp;base64, ",qZ="data:image/webp;base64, ",YZ="data:image/webp;base64, ",zpA="data:image/webp;base64, ",$3="data:image/webp;base64,UklGRjILAABXRUJQVlA4ICYLAADwKwCdASqAAIAAPlEgjkSjoiEVi6WcOAUEtQxPk+1AIvj+A/i3ox2D+8b3yTK2z/jP+B7G/MA8br9Zvc3+4fqI/WX9pPeK/0vqx/vHqD/0X/MdZz6Df65emR+7Xwjft/+6ntVf/+tZc6fuj205SkSDtv/VcP/xJ/svJp/puA5AJ+e/1D/eflvzG/YD/VbEr5f7AH82/u3oYfUHo/+m//L7iP84/t3/R7Fnol/sAf8jDX/85LEDU3Nhwz0qQTDoSxEBXnD0WKbVqZVvtlP+EcbVOtMBrz4HqeqbjtHy9MJc7toFIzxNWBRZxF3edFcSqgCg6TaLhpGJ7gQTPrXJT96MlastDx/yltuCyIvRqU88QTQWsRSEqElYdrwW07fBt0lctefmFvNTAWvEp7g98CW0hCQ1ITwqZR98aJYYw2LDwooSfDt5DuBkESyD0LLm/7jSirHLncuDkGTJmREyIhbBHGXeTj1b8yAA/v4HbeHAACFubZsENQTt3b8uMvw9e2fN8gzsZmngr11NPWwibOWm9hc8j/Z24UZ/J+Z152x/hNSZ3LxsEURyFLVFv3vX4EeAbnH6wLGAaur4buiPuqYcTgS5uOc067iI+1S8jhmA0sScd+SOEbyVa7Ix4J0Y84H9UO9zP5UWWrl66DBk9IAvk8MouA4bLQJTOFXg1UTHBo1+c4qZsOGhWfibahaVVoDPZYA3ud9SJi/lFs0zD9oBqf7Ca14VHxxWSNk6569z9SudJp/M4FVmJ2S2p+RdCLgdMKpKIh2SgsehpQdpNHmShtYQnBueUgNrCBanFLz4GWimY4fa7h8LB/xJlEF3YC0raSUQEYooNw3ngCQsbAM5YIqVlO9JVnZz/lrDp//sIox9gdfg8whG43ePD0l2/ya8/2yA3lIJgToSQzBJi7+ojESpZUGzp6LscwlKyJ/vPg4VBezgHpP5qfo+xBW3fWFRe9A54K0t6ARjKCA+be8DyTOcFCJ0fv/dleqihupaTgSF0WytTb0k4zaikWn+msixl9PK/wbD2Xsk6dEHAkMo1fvn7//VWgLVXRm5dqvTKWvn6xYC04sLnQimqpZoepE7fd2DY54Jqm481g11jPyWKzirsRJuccjYq3gyW5gPbWhTZV+5zZDv3oCAiNd/0YMBzqZeuW84ENpl8w23V7nm2jNeWbUd4jiPZCCvdk9qGXs5m36ASA8U3YfMJeJP1bH9tOdYhbQo02/c3p3vWOrFZY5aUyW4TkDWVwpbpD/rNTPuhZZrMpxJ9wZfb+FTa6McEcx/vv2rWDt3II/QJYmPe3CNi5De4SfMM32ZM1qkNxraibHUyqr/4ZowP+e8P3L0qgY4RPt1Z8+2FXvwVQoXhB65tqwx+Uf9RV85jvYx6R3pC2UFuW/xvltxFRMQ7xw1B/7CRj1Oepghurb/C5GuJNZzvM0txtd5EPuV5IYQc9gNZary0B/LsM5PoUeHqNTLUpDuEn0snX29nBPU70dEe/b9ohCWbSN8h5ZO1TfYP6l8k4X7p8AryKWqtRpi/w7mXW+DdFLWKkMLytIQhWiuOJtgz6BWcikef4/rb6IkAIA8oo7QY9SYnXEf2EGiiQ4OufIy4ZwMPhn/Eb6h8pLuplvsg/Yn7HO/zXa1Atvrz7izopRwynCoFu7zg/5Xe+1Y/O2S2XPUQpe4PgRXdRDkXN1m2nAHdqV/Yl75yobP4LbL94qXFN3s1wryHDp+48NCbLfzL4wDFO7LVcQeduWFRSufRac1PXYbeMNIPvHman7RvjWi2Go8nLYI5gN2bzoDDk6bphNU02LeVS4/qeuHYsHBAmUvUX5SMAMUDS8k9b186/Wi/McRTHTx+if4mKl9+uafb8eU7wrWHMKbWgi70cD+KajY3T/vfpW2UHdPdKcxB09xV/20n6eHkMMItUbIcDlfL1IR3WJZfsgx/1waxrAZ1kauESTWRzzruF2MBgV0lXDxO0K4ImN2ewfOBUw9ekuy/xadilwKJ/hQuZO+/qMT3+NG3wswM9XDNCkuRVoNoPVyVFaAodKzr+X2CLcrjhdtaEifeeV63EgB3+5RRWin2kTbDR34byHl03kdr90aSdQ6wDJ8vwNDcqoKy2OAnLCf5hxNt+LKP0NPlBC4W7ifaeLpLHMPeTsP/9kKuJqpzW9Dg39bgbuz1pmCi26KxRxn+iHqXhzv/HvKLNriUDDeQxJAi/DkwPmj0iISVIb7MpjVwJH7a+TIfVTUHBzAmCWkgw3KJUtt5IuLiG9OfummH+q9NSeE7TSoNxaf+bYYzw5xssGp0SYJ5o7RTHwqIdydP/fwKhzZF7P1YKijd/U7uQILRBfWqxfasXg3vcFBZC7FUqINsQsEQjcyDmVJJ2KwVwl2sKE4H5kp81pZvtVM/dCN6VcKsMEapQkHEf2/Yj/TcpAA+xFu+3KJ+bj+FY9HO1kkr0pEjOpN4kGU1xpQDtltG0YIXXINfPVio4mr37p11CbUloI6P/wiNfwIQeE4ywogegMKZYMNwlCjQpE27PWrmLhxw47oJo4w5a8r9IcnYp+UliiVOOZeryqfYlfO0//Q1TpwVchjiEM0Q6LH8CK9BRruUQefneG1rDhirhlB3+2vTdPHQGh9dfVNfgS1DgaRmXTySi2/3pNBAj0qIj0xhBuO1r92DJHEqM2hm+8+dJ2kkjpa1ylvrCWOTSfReD27a1fw05sNV1O+91UacMjubHZRJI9FGM1Uk2KX9/nZ+MsHNP4lxEEfkJkG8vVjTkgRKGoJllOgk9I8FVN26tAc83k0MBoE4IkE3L+SKW/dYVSALfW8S942PaoH+me0Au8a8FHXyzHJUB5Cjp+ddJdmf+Ro/Wmc55q9Pv7f8/lwWzMuyk7uakPHvvhDLc9wgSHx1GvgCOMRnNQyaab6hyn6pXO8b0S7zC+cD2A75QgbsF0pbT9kkpJksyr41pZHKT2YcpsWASKQ1Lit6quXfRRUpYOfH/Bn5jy0C2nAAOAKfYMT7BjVkPzFPa9tF3VXENrN9JZ2Ww3CWrwTsz7B+5wWnTL1/NE5lflX+M3dN3MOCwhp7aIr1fz4zml2ZffIFKrIX4w2RPAn/RcgZk8pqLY5SX79sNcb9pwG8oP6o3lSM0q1TzRcOOx4gEV31Nie66LkOSHO9OGeHCev2pbTmOi2vIGKSDNIKb/cZSEA7+16ezDq//h3YkCi5D+rXi16tF3K57z3/WzG6jHd5T2OGnPV1ylC27fPlFptyTp4F6q0nNJgbQ3+ydw4VBso3JrpSOgZa2/4ElrfHBfMmqDO/OVRdpFeGLS5b0Ow3kO8xZG5o/L+4K6ddVO8ffp3e3i0jRBCW1hT6lT4gseeQkGHtGl/85Fw4XxDHmd/Ru9XM/T3FzCvgm8Hmy1IF+Bl3/XbLFH+M69R/uHHx7/zA+WmDqY6vOom0n4iDs4OuBBRcldBxwhtEFxz/yqRfWXoH/az+StEZulkrgxadtbCcfUiYoSKitUenWvWVfpGXk3YfP/4JLCZAh03W0T+pEOFXU9WMpfJt8p6uivr4dDXTvNaH9OG6t8/1IpRL/BOVHjmPOIIjEIjD8poMu9hwuHJ+I/P6JFIO/haUrBKNvNMzUK6y6DVbVWDK0Y//tKxSG95QtBXiNq3+Jvz5rR/6KLRWkNmU9U+/HnZyidsnn63O25Dxj5VokAc+hcVa42o7wF5PhUBU7KTs046XlPcFcyYUmF5RDuFD1dIAzA/hxwqCR3XNrg/uAbzpsSyGUyh3JjCrEeaAj5b8p55ZTSgFj3pZvvBxXnlvE4kbteDcgmxTYgAAAAA",ZpA="/assets/tile_station-BU45WlAz.webp",WpA="data:image/webp;base64, ",VpA="data:image/webp;base64,UklGRk4LAABXRUJQVlA4IEILAAAQLQCdASqAAIAAPlEgjEUjoiEVjAYYOAUEswBqQk6ljkqWH/D/hzlbCxWH/U/+iPYA/UP9XOvp+0XqS/Zn1x/SH/qvUA/znUAehX5bX7l/Bd/a/+R+1/theoBa3+gn2+oO9q/7/8oeS35EagX47/Ot/jsf6BHsB9m/2/pszVrrnjN6AH8v/u//W9WDPM9Sf+j3B/5n/Zv+V2IvQ5/bdGAIO6SZ6eclIr/9OjX5AKqIzKlusmkdQ1bCEVswGO4SAW4xJFt1zZ0ZkvpYMd/PdbjIrm8iONKy2H70A9TVKBSiYq+sm5i27sYJomy4HarM/6X4nwWc8ip8nQm0sV/1b5ucksYLE8CUa80/NlVq3nu9A/KyJfq+PYBjyWrYcI5ciePei3bpZUmVS8wExk/WR452Fcx2iUr+nolvQpNb+tm5uVr1h2GbAiI3sUdWQ+AveMhPy/LCU9WntOu1CnEjP5Vi9nfa+ZoCWdNKu1RDT5kheQAA/v586yfQABpzbgQ/GyviVQXzfOjRO1J0msj36dPweZYt+KEArYmNAxAj3VgAj4leYDz0lORAe51emrIf4kSCM8KJ0eTXkct5PTfTe+Ij3SAdY1QDcpw3OhC+hd165UlVLHZ9bigB8h6fHIFU4JvPhCrftRfdUrWHxXwpmAk2GHTI7NwAQegB7J+0/Ux6ZdS3NbAcFo/B3QEj5orF//Nt1nDxRXcWE+3g0FTpKJEN6fvB8rYB1XQU8x9umCeoizHZkgm92cuMDoOTspILNOLd280eCAkrLKa884RIYm+DNxlCXmJf2QUh2CJ+GXM4F1ke3yVskUl9cDjjvYPaUb7fxE44QFtXFsTENaNhJkGzJ6TiOnHpw0ELVlYd0UF2Er9TW0Ry8s5nQiIIFArFb02+LNKoGbwE4O+OjGqxIZu8CTF00o/bgBHk6U0/jWRZfFyYT7QC6Xm9jhmH3p/gXEXY8/SokyiO4imXC7id89PL1OMI8SPUzi/RjfgrG/wb3X/w1NzisXwRUtu8T7SD1GdnvjbVfL7bgcO7anhzNaEOZQNgw5Pff8UdJ8AV4YUniKriJxPWjIivIsv78YiVdqzGyD69/CoOdlWzVrpepWpgP2Fr+Z9GmrXDVYcFuRyy2eZtOw9rjDv9QNsSKzm545J7Bdq0gYDYD2NrbkJHExD2ilWI+hHTnnh/W7Baus20carwsCSX5Wz1ZVU7Erxjta+FQ3ZJy0jmeIhaqZgazvqulw2uOlkIQRdjhAxaYvVx4hU082gxTb0YMEGAxvN/s/nSYf3uv0DSHLB6NUyhI0cfQR/J5BpWE7Fz8H0qgjauuwR50FxjN77UWsMFfP31F1VVfXmtcQhnLa/fwJwwoiSEYxs1DwURovLXFnkswLFnecaPmDHa00ABXG2B4zjamHTAUGmawOiNiMG0Ne7YiNiUpBRkXtl5aZHIuAdoOln433y4qhwZfrg/WIgOryuyUHQcNPsk45XwjYWrKO8HlvoS/5/igyhkyRTsAm/pjfiI7DaoSLWiCALdySrI5xC7b+/WH5y6U8BxEGW5Fs6BR2Xh8fdzcALeMDvJ6l3bWljb3Pe+pcbB2eJOH80Y51+0lQcYi/6O/IiiPie/EbfNm/LkuVRetRKpvmpHtT9ytwgMtn1IGMNcIxjm7NPeJc4+pul908Gbn70CpsfIQ/Od2U7kyGL6Bu29tG615baJjLojt3ARfsoMuunr6XyJo0LvfSVimpsr38cw2DqrfBoGNRr4YhScM+4IpaSQ9vHGqHLq6H+zZ5ayIAbu9Acmw0pADRl7uHN15x98mwZExhmGLdr2Ei63LnKdjOMxqiD0p22S7DEJS45KfZGlAN63263cO57j3QZilkqPzT1+3W7hpZLJpfQqQPQztKyEAeL4kWuQPd48u3+YxiQeslw/OCScB438ylk8AYCbQl3FAw02/Wt1wOSLGQFp5Xh8OfZsOJYu0ocl0R++oMLMmOdVC5FwrnECk8O69BkX98OUyy7u0QcpWBgXtHsyHZSGdZUeFmgIRiM6izM2VDcPmrn4uHZWW9nAK/7IXPiqlFdcyV/9S11qJfdRlIZpmO3LlWCwmb2X9Cfr+F3izTqn/vkF645WXbb9I8GK3dUMnUgPYm9HrKq8MNYkbncLqdRb//FT/4Ex43MYV83AuRbi9dAD1quEKAuCKJqHVFf1LE6d6ljXy8lelc1+6SkjY5u+FGVwch65nITiN8IZk44knJ0ud/N4nbdacfrlqYcwQoDcEUPBSOREPL+BHpZEA++k4cLlt3L82yfd08Vkt6bsYNnWWLznY7WjfQG5EP3b+MKhqL0FEjmsxEUXFIxsLB0q7JdF5p/Lutf+m9hlMYRRBqMVli7N92NzIi37ek48Q1alqClgTCTjr2ep9FEioEKOSFi6VLbSnv1BGDKRZr9bG8PdHqSbLhYhOhRQ3cWEyBwsQyWk/1Vy8yVEFYQyZ4hpy/86F3wqYj2X/kD96hvRwI334NcLyJqmOZ30mVZg6gNW/EceTDXseuXzKqXd/67y9dmVLeEC7EY8+a1kH71oI/KXScmkKZoPaLd9gncx2ATboKspDKEOXg90h1B8MovJHniZzHOvg1x/vXPso+P+EOgsDMEL3oyu+iGsSeTW+GEqjx2epeFti3JELi3v7Ip8kZ7cU2yTwJNdaTB65Efwiz4v20xQWoDop86cgqVYKG9kyQ9QkbDuW2dz2P6ySVyFLIJPUsDHT1hc8kn79gz55LPBnWgcm9kOHsWmnY0nGCK4u+IJjW823Z3wJrY+uLPF/32WCOdVbrFfzZe57UxPFbkmrwB/YPEccjeDdndNrTk+v64ZCGAHW04fwSecUh3YLCBrRRIf/bXvK7E7KqMl6e71297k5atDxAP6a1xrJvxd0vOB2W4fsfnOGE/07KlUhaSmDimpz3Kwwc6fYq/+jmNlOWvRNZsnvCtHhTG5xSq/sS9U/48Z6MJi5ZU7quET36hA+YFA07WWsfLmZAk9DOz2bRU2dpUx6f8EmUsC3eLeS3WSUfHlZOsox1P9D6f0eIu13H8AoB7pGGteRu6ShCeqvTEcqXqQtjZGssqkZS80hYEAFJZzkFGy/lg5JXu32ZyF3lJar9TxRutaJyjRA66MWmQ/6bqQZ4WUGSliVZhnN6i25fW173N/LwrWGBLL/b6F9um50U2sqpce736cY2hIT97Rz7GZ1/qVD+pT/qJ1CelARtlVV8TxGwZTso4YnNMQP/4pNs8F684+EyVUNzCFemxA7zCn1I1aYrWBi4a4tsgrt5lXBSCsnNruFWfA7wWUuKk6QxlLYYbM//GQ3B4bIzH97WIBvb+4xxPo3D/TCAg3YAd8ZOPA0nsrNsupgrYpxB7Rx2k9JPf6mwfEsEsI4JuhuZiNlKYAM6lKo6yVZl10B2R2YhB4aIoVUOM1yvpA9/fmRLwB5pGI3AyiW0bWguFLG+qf3/TTC/d7/lVO+S/Ohmfkqep8MmqD/zQXur3f7Bh//xGVq6Vxb9eFF3ZXImBBZU7OrywimSDauI97kTEq0HqSpXq78Cf3rTcfmA6V8sh+2AmUyWnMmVQJaIS787nhmmNIKFe6Xl8L+1012xfZPwC8nfoM4v357hpmeKOM9x/+PEflE8GrUw9NlIPxDxKVLKp/lCAKzE55aJOsdluLZl5eu3B/cQGruT1mHo2vxU4phP7ONH5D7RxVrD15ZWuv4DU3H16g9wMLYq9/k+7r/4I/qif/AP/i6U89HJIWEDhVFXCoEvSnIyEcvtC03FkCLQ1xDelANRc4dsYG5EjUoQYTndZ6TR8KTsUAuId+bELEirzOxMfS07EpwnMAN/nHQAAAAA==",XpA="data:image/webp;base64, ",HZ="/assets/explosion-CCKtR9yS.webp",Koe=Object.assign({"../../assets/optimized/azzure_turret_1.png":Wge,"../../assets/optimized/azzure_turret_2.png":Vge,"../../assets/optimized/azzure_turret_3.png":Xge,"../../assets/optimized/azzure_turret_4.png":$ge,"../../assets/optimized/azzure_turret_5.png":Aoe,"../../assets/optimized/crimson_turret_1.png":eoe,"../../assets/optimized/crimson_turret_2.png":toe,"../../assets/optimized/crimson_turret_3.png":ioe,"../../assets/optimized/crimson_turret_4.png":noe,"../../assets/optimized/crimson_turret_5.png":goe,"../../assets/optimized/emerald_turret_1.png":ooe,"../../assets/optimized/emerald_turret_2.png":soe,"../../assets/optimized/emerald_turret_3.png":aoe,"../../assets/optimized/emerald_turret_4.png":roe,"../../assets/optimized/emerald_turret_5.png":Ioe,"../../assets/optimized/gold_turret_1.png":Coe,"../../assets/optimized/gold_turret_2.png":coe,"../../assets/optimized/gold_turret_3.png":loe,"../../assets/optimized/gold_turret_4.png":Boe,"../../assets/optimized/gold_turret_5.png":Eoe,"../../assets/optimized/silver_turret_1.png":Qoe,"../../assets/optimized/silver_turret_2.png":uoe,"../../assets/optimized/silver_turret_3.png":doe,"../../assets/optimized/silver_turret_4.png":hoe,"../../assets/optimized/silver_turret_5.png":poe,"../../assets/optimized/void_turret_1.png":foe,"../../assets/optimized/void_turret_2.png":yoe,"../../assets/optimized/void_turret_3.png":Doe,"../../assets/optimized/void_turret_4.png":moe,"../../assets/optimized/void_turret_5.png":Soe}),Foe=Object.fromEntries(Object.entries(Koe).map(([e,A])=>[e.split("/").pop()??e,A])),_oe={"crimson-dominion":"crimson","silver-pact":"silver","azure-sovereignty":"azzure","golden-imperium":"gold","emerald-collective":"emerald","void-enclave":"void"},Joe={"crimson-dominion":0,"silver-pact":0,"azure-sovereignty":0,"golden-imperium":135,"emerald-collective":0,"void-enclave":135},Loe={"crimson-dominion":!1,"silver-pact":!1,"azure-sovereignty":!1,"golden-imperium":!0,"emerald-collective":!1,"void-enclave":!0};function xoe(e,A){const t=_oe[e],i=Math.max(1,Math.min(5,Math.trunc(A))),n=`${t}_turret_${i}.png`;return Foe[n]??null}const $tA=Ui.getPlatform()==="android",hn=1e3,FS=780,Ma=FS-60,na=FS+60,$R=40,Ef=360/$R,sm=80,_0=hn-na-sm,tU=(na+sm)*2,Toe={start:PpA,planet:jpA,asteroid:qZ,nebula:YZ,wormhole:zpA,"void-drain":$3,station:ZpA,jail:WpA,"go-to-jail":VpA,"free-parking":XpA},qoe=["#283593","#2d1060","#6a1b9a","#2d1060","#c62828","#455a64","#0c3545","#2e7d32","#0c3545","#0c3545","#ef6c00","#3d2010","#00838f","#3d2010","#3d2010","#455a64","#3d1018","#6a1b9a","#3d1018","#3d1018","#43a047","#3d3008","#2e7d32","#3d3008","#3d3008","#455a64","#103520","#103520","#00838f","#103520","#e53935","#102050","#102050","#6a1b9a","#102050","#455a64","#2e7d32","#351040","#c62828","#351040"],A4=["#283593","#2d1060","#0c3545","#0c3545","#ef6c00","#3d2010","#3d2010","#6a1b9a","#3d1018","#3d1018","#455a64","#3d3008","#3d3008","#6a1b9a","#103520","#103520","#e53935","#102050","#102050","#351040"];function Yoe(e){return e===20?A4:qoe}const Hoe=Array.from({length:$R},(e,A)=>{const t=-90+A*Ef,i=t*Math.PI/180;return{cx:hn+FS*Math.cos(i),cy:hn+FS*Math.sin(i),baseRot:t+90}});function LY(e,A){const t=((e+A)%360+360)%360,i=t>90&&t<270;return{angleDeg:i?e+180:e,flipped:i}}const AiA=Ma+14,Ooe=Array.from({length:$R},(e,A)=>{const t=-90+A*Ef-Ef*.4,i=t*Math.PI/180;return{x:hn+AiA*Math.cos(i),y:hn+AiA*Math.sin(i),rot:t+90}}),Poe=Array.from({length:$R},(e,A)=>{const t=-90+A*Ef+Ef*.38,i=t*Math.PI/180,n=Ma+8;return{x:hn+n*Math.cos(i),y:hn+n*Math.sin(i),rot:t+90}}),joe=[18,24,32,42,54],zoe=[.6,.75,.9,1.1,1.4],Zoe=Array.from({length:$R},(e,A)=>{const i=(-90+A*Ef-Ef/2)*Math.PI/180;return{x1:hn+Ma*Math.cos(i),y1:hn+Ma*Math.sin(i),x2:hn+(Ma-12)*Math.cos(i),y2:hn+(Ma-12)*Math.sin(i)}}),xY=e=>/^#[0-9a-f]{3,8}$/i.test(e);function ku(e,A){const t=e*Math.PI/180;return{x:hn+A*Math.cos(t),y:hn+A*Math.sin(t)}}function Va(e){return e.toFixed(2)}function Woe(e,A){const t=360/A,i=-90+e*t,n=ku(i-t/2,na),g=ku(i+t/2,na),o=ku(i-t/2,Ma),s=ku(i+t/2,Ma);return`M${Va(n.x)},${Va(n.y)} A${na},${na} 0 0 1 ${Va(g.x)},${Va(g.y)} L${Va(s.x)},${Va(s.y)} A${Ma},${Ma} 0 0 0 ${Va(o.x)},${Va(o.y)} Z`}const iU=na-16;function Voe(e,A){const t=360/A,i=-90+e*t,n=ku(i-t/2,na),g=ku(i+t/2,na),o=ku(i-t/2,iU),s=ku(i+t/2,iU);return`M${Va(n.x)},${Va(n.y)} A${na},${na} 0 0 1 ${Va(g.x)},${Va(g.y)} L${Va(s.x)},${Va(s.y)} A${iU},${iU} 0 0 0 ${Va(o.x)},${Va(o.y)} Z`}const Xoe={purple:"#7b2ff2",cyan:"#00e5ff",orange:"#ff9100",red:"#ff1744",yellow:"#ffd600",green:"#00e676",blue:"#2979ff",magenta:"#e040fb"};function $pA(e){const A=e.length;return Array.from({length:A},(t,i)=>{const n=e[i],g=n!=null&&n.group?Xoe[n.group]??null:null;return{wedge:Woe(i,A),fill:"#0d1b2a",strip:g?Voe(i,A):null,stripColor:g}})}const eiA=new Map([[40,YpA]]);function $oe(e){if(e.length===40)return YpA;const A=eiA.get(e.length);if(A)return A;const t=$pA(e);return eiA.set(e.length,t),t}function Ase(e){const A=360/e,t=Ma+14;return{positions:Array.from({length:e},(i,n)=>{const g=-90+n*A,o=g*Math.PI/180;return{cx:hn+FS*Math.cos(o),cy:hn+FS*Math.sin(o),baseRot:g+90}}),badgePositions:Array.from({length:e},(i,n)=>{const g=-90+n*A-A*.4,o=g*Math.PI/180;return{x:hn+t*Math.cos(o),y:hn+t*Math.sin(o),rot:g+90}}),turretPositions:Array.from({length:e},(i,n)=>{const g=-90+n*A+3,o=g*Math.PI/180;return{x:hn+t*Math.cos(o),y:hn+t*Math.sin(o),rot:-90+n*A+90}}),tickMarks:Array.from({length:e},(i,n)=>{const g=-90+n*A-A/2,o=g*Math.PI/180;return{x1:hn+Ma*Math.cos(o),y1:hn+Ma*Math.sin(o),x2:hn+(Ma-12)*Math.cos(o),y2:hn+(Ma-12)*Math.sin(o)}})}}const tiA=new Map([[40,{positions:Hoe,badgePositions:Ooe,turretPositions:Poe,tickMarks:Zoe}]]);function ese(e){const A=tiA.get(e);if(A)return A;const t=Ase(e);return tiA.set(e,t),t}const tse=({tiles:e,onTileClick:A,children:t,rotationDeg:i=0,mini:n=!1,properties:g=[],players:o=[],liftedTile:s,laserBeamTile:a,laserBeamSeq:r=0,blastDamage:I=50,suppressDarkOverlay:c=!1,ringRef:l,currentPlayerTile:B,currentPlayerColor:Q="#bfefff"})=>{const h=e.length,d=0,[p,y]=E.useState(!1);E.useEffect(()=>{if(a==null){y(!1);return}y(!1);const K=setTimeout(()=>y(!0),d+16);return()=>{clearTimeout(K),y(!1)}},[a,r]);const m=h===20,D=m?40:h,S=ese(D),k=E.useMemo(()=>m?$pA([...e,...e]):$oe(e),[h]),N=m?[...A4,...A4]:Yoe(h),G=D===40?TZ:HpA(D),M=B==null?null:Om(B,i,h,D),w=E.useMemo(()=>{const K={"crimson-dominion":"C","silver-pact":"S","azure-sovereignty":"A","golden-imperium":"G","emerald-collective":"E","void-enclave":"V"},J=new Map;if(typeof window<"u"&&new URLSearchParams(window.location.search).get("debugTurrets")==="1"){const v=["crimson-dominion","silver-pact","azure-sovereignty","golden-imperium","emerald-collective","void-enclave"],U={"crimson-dominion":"#ff4444","silver-pact":"#cfd5e4","azure-sovereignty":"#5aa9ff","golden-imperium":"#ffc744","emerald-collective":"#5af0a0","void-enclave":"#c084ff"};for(let x=0;x<e.length;x++){const T=v[x%v.length];J.set(x,{color:U[T],letter:K[T],upgradeLevel:5,piece:T})}return J}for(const v of g){if(v.dormant)continue;const U=o.find(x=>x.id===v.ownerId);U&&J.set(v.tileId,{color:xY(U.pieceColor)?U.pieceColor:"#ff4444",letter:K[U.piece]??"?",upgradeLevel:v.upgradeLevel,piece:U.piece})}return J},[g,o,e]);E.useMemo(()=>{const K=new Set;for(const J of o)K.add(J.tileIndex);return K},[o]);const b=E.useMemo(()=>a==null?null:Om(a,i,h,D),[a,i,h,D]),_=E.useMemo(()=>{if(!p||a==null||n||b==null)return null;const K=G[b];if(!K)return null;const J=g.find(T=>T.tileId===a),q=J==null?void 0:J.ownerId,v=q?o.find(T=>T.id===q):null,U=v!=null&&v.pieceColor&&xY(v.pieceColor)?v.pieceColor:"#ff4444",x=Math.min(3,Math.max(.35,I/100));return{cx:K.x,cy:K.y,color:U,scale:x}},[p,a,b,G,g,o,n,I]);return E.useMemo(()=>{if(!p||a==null||n||b==null)return null;const K=G[b];if(!K)return null;const J=g.find(T=>T.tileId===a),q=J==null?void 0:J.ownerId;if(!q)return null;const v=o.find(T=>T.id===q),U=v!=null&&v.pieceColor&&xY(v.pieceColor)?v.pieceColor:"#ff4444",x=[];for(const T of g){if(T.ownerId!==q||T.upgradeLevel<=0)continue;const z=Om(T.tileId,i,h,D),Z=S.turretPositions[z];Z&&x.push({x1:Z.x,y1:Z.y,x2:K.x,y2:K.y,delay:x.length*.07,color:U})}return x.length>0?x:null},[p,a,b,g,o,n,S,G,i,h,D]),C.jsxs("svg",{viewBox:`${_0} ${_0} ${tU} ${tU}`,className:"zentara-svg",children:[C.jsx("rect",{x:_0,y:_0,width:tU,height:tU,fill:"transparent"}),C.jsxs("g",{ref:l,style:{transformOrigin:`${hn}px ${hn}px`,transform:`rotate(${i}deg)`},className:n?"zentara-ring-group--mini":"zentara-ring-group",children:[!n&&C.jsxs("defs",{children:[C.jsxs("radialGradient",{id:"zentara-orbit-outer-grad",cx:"50%",cy:"50%",r:"50%",children:[C.jsx("stop",{offset:"92%",stopColor:"#3a80b0",stopOpacity:"0"}),C.jsx("stop",{offset:"98%",stopColor:"#5ab0e0",stopOpacity:"0.9"}),C.jsx("stop",{offset:"100%",stopColor:"#3a80b0",stopOpacity:"0.3"})]}),C.jsxs("radialGradient",{id:"zentara-orbit-inner-grad",cx:"50%",cy:"50%",r:"50%",children:[C.jsx("stop",{offset:"93%",stopColor:"#1e4a6e",stopOpacity:"0.15"}),C.jsx("stop",{offset:"100%",stopColor:"#3a80b0",stopOpacity:"0.55"})]}),C.jsxs("linearGradient",{id:"zentara-tile-deck",x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:[C.jsx("stop",{offset:"0%",stopColor:"#d8e2e8"}),C.jsx("stop",{offset:"42%",stopColor:"#aebbc4"}),C.jsx("stop",{offset:"100%",stopColor:"#667582"})]}),C.jsxs("linearGradient",{id:"zentara-command-deck",x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:[C.jsx("stop",{offset:"0%",stopColor:"#f4f8fa"}),C.jsx("stop",{offset:"48%",stopColor:"#d5dfe4"}),C.jsx("stop",{offset:"100%",stopColor:"#8d9ba5"})]}),C.jsxs("linearGradient",{id:"zentara-tile-sheen",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[C.jsx("stop",{offset:"0%",stopColor:"#ffffff",stopOpacity:"0.34"}),C.jsx("stop",{offset:"38%",stopColor:"#ffffff",stopOpacity:"0.04"}),C.jsx("stop",{offset:"72%",stopColor:"#07111c",stopOpacity:"0.12"}),C.jsx("stop",{offset:"100%",stopColor:"#02070d",stopOpacity:"0.34"})]})]}),!n&&C.jsx("circle",{cx:hn,cy:hn,r:na+4,fill:"none",stroke:"#5ab0e0",strokeWidth:6,opacity:.18}),C.jsx("circle",{cx:hn,cy:hn,r:na,fill:"none",stroke:"#3a80b0",strokeWidth:2.5,opacity:.55,className:n||$tA?void 0:"zentara-orbit-ring"}),!n&&!$tA&&C.jsx("circle",{cx:hn,cy:hn,r:na-8,fill:"none",stroke:"#8eeaff",strokeWidth:3,strokeLinecap:"round",strokeDasharray:"38 180",opacity:.55,className:"zentara-orbit-scan"}),C.jsx("circle",{cx:hn,cy:hn,r:Ma,fill:"none",stroke:"#1e4a6e",strokeWidth:1.5,opacity:.45}),!n&&C.jsx("circle",{cx:hn,cy:hn,r:Ma-3,fill:"none",stroke:"#1e4a6e",strokeWidth:.6,opacity:.25}),!n&&S.tickMarks.map((K,J)=>C.jsx("line",{x1:K.x1,y1:K.y1,x2:K.x2,y2:K.y2,stroke:"#1e4a6e",strokeWidth:1,opacity:.25},`tick-${J}`)),C.jsx("defs",{children:k.map((K,J)=>C.jsx("clipPath",{id:`tile-clip-${J}`,clipPathUnits:"userSpaceOnUse",children:C.jsx("path",{d:K.wedge})},`clip-${J}`))}),k.map((K,J)=>{const q=e[J%h],v=S.positions[J],U=(q==null?void 0:q.type)==="start",x=J>=h;return C.jsxs("g",{"data-visual-tile":J,onClick:!n&&!x&&A?()=>A(q.id):void 0,className:`${!n&&!x&&A?"zentara-tile-group":""}${s===J?" zentara-tile-lifted":""}`,style:s===J?{transformOrigin:`${v.cx}px ${v.cy}px`}:void 0,children:[C.jsx("path",{d:K.wedge,fill:U?"url(#zentara-command-deck)":"url(#zentara-tile-deck)"}),!n&&q&&v&&C.jsxs(C.Fragment,{children:[C.jsx("path",{d:K.wedge,fill:N[J%N.length]??"#34506a",opacity:U?.08:.16}),C.jsx("path",{d:K.wedge,fill:"url(#zentara-tile-sheen)"})]}),K.strip&&C.jsx("path",{d:K.strip,fill:K.stripColor??"#607d8b",opacity:.96}),K.strip&&!n&&C.jsx("path",{d:K.strip,fill:"none",stroke:"#ffffff",strokeWidth:1,strokeOpacity:.42}),C.jsx("path",{d:K.wedge,fill:"none",stroke:"#020812",strokeWidth:3.2,strokeOpacity:.82}),C.jsx("path",{d:K.wedge,fill:"none",stroke:"#a8d9ef",strokeWidth:.9,strokeOpacity:.48}),!n&&M===J&&C.jsxs(C.Fragment,{children:[C.jsx("path",{d:K.wedge,fill:Q,opacity:.2,className:"zentara-current-tile-light"}),C.jsx("path",{d:K.wedge,fill:"none",stroke:Q,strokeWidth:5,strokeOpacity:1,className:"zentara-current-tile-edge"}),C.jsx("path",{d:K.wedge,fill:"none",stroke:"#ffffff",strokeWidth:1.2,strokeOpacity:.7,className:"zentara-current-tile-edge"})]}),!n&&C.jsxs(C.Fragment,{children:[C.jsx("path",{d:K.wedge,fill:"#f7fcff",opacity:.72,className:"zentara-moving-tile-wedge"}),C.jsx("path",{d:K.wedge,fill:"none",stroke:Q,strokeWidth:5,strokeOpacity:1,className:"zentara-moving-tile-edge"})]})]},J)}),!n&&e.length>0&&S.positions.map((K,J)=>{var IA;const q=e[J%h];if(!q)return null;const{angleDeg:v,flipped:U}=LY(K.baseRot,i),x=U?-28:28,T=q.name,z=15;let Z;if(T.length>10&&T.includes(" ")){const CA=Math.floor(T.length/2),uA=[...T.matchAll(/ /g)].map(X=>X.index).reduce((X,O)=>Math.abs(O-CA)<Math.abs(X-CA)?O:X);Z=[T.slice(0,uA),T.slice(uA+1)]}else Z=[T];const eA=J%h,aA=w.get(eA);let sA=null;if(aA&&q.rent&&q.rent.length>0){const CA=Math.max(0,Math.min(q.rent.length-1,aA.upgradeLevel));sA=`⚡ ${q.rent[CA]}`}else typeof q.cost=="number"&&q.cost>0&&(sA=`◈ ${q.cost}`);const pA=Z.length*z+14,gA=Math.max(...Z.map(CA=>CA.length*8.2+32)),yA=K.cy+x,fA=(IA=k[J])==null?void 0:IA.stripColor,RA=fA??"rgba(100,170,255,0.45)",qA=fA?1.8:1,W=fA?`${fA}55`:"rgba(80,150,255,0.18)",$=q.type==="start",L=$?"rgba(32,55,72,0.78)":RA,H=$?1.4:qA,P=$?"rgba(178,225,242,0.28)":W,tA=$?"rgba(226,235,239,0.9)":"rgba(6,12,32,0.92)",iA=$?"rgba(255,255,255,0.82)":"rgba(160,210,255,0.3)",oA=$?"#071525":"#dce8ff";return C.jsxs("g",{pointerEvents:"none",style:{transform:`rotate(${v}deg)`,transformOrigin:`${K.cx}px ${K.cy}px`},opacity:J>=h?.7:1,children:[(()=>{const _A=x>=0?-1:1,uA=yA+_A*(pA/2+18+3),X=`tile-icon-clip-${J}`,O=K.cy+_A*52;return C.jsxs(C.Fragment,{children:[C.jsx("defs",{children:C.jsx("clipPath",{id:X,clipPathUnits:"userSpaceOnUse",children:C.jsx("circle",{cx:K.cx,cy:uA,r:18})})}),C.jsx("image",{href:Toe[q.type],x:K.cx-18,y:uA-18,width:18*2,height:18*2,preserveAspectRatio:"xMidYMid slice",clipPath:`url(#${X})`,opacity:.95}),sA&&(()=>{const cA=sA.length*6.4+12,wA=14,xA=fA??"rgba(140,200,255,0.6)";return C.jsxs(C.Fragment,{children:[C.jsx("rect",{x:K.cx-cA/2,y:O-wA/2,width:cA,height:wA,rx:4,ry:4,fill:"rgba(6,12,32,0.88)",stroke:xA,strokeWidth:1}),C.jsx("text",{x:K.cx,y:O+.5,textAnchor:"middle",dominantBaseline:"central",fontSize:10.5,fontWeight:700,fontFamily:"Orbitron, monospace",fill:"#ffffff",letterSpacing:"0.6px",children:sA})]})})()]})})(),C.jsx("rect",{x:K.cx-gA/2-1,y:yA-pA/2-1,width:gA+2,height:pA+2,rx:7,ry:7,fill:"none",stroke:P,strokeWidth:2}),C.jsx("rect",{x:K.cx-gA/2,y:yA-pA/2,width:gA,height:pA,rx:6,ry:6,fill:tA,stroke:L,strokeWidth:H}),C.jsx("line",{x1:K.cx-gA/2+9,y1:yA-pA/2+1,x2:K.cx+gA/2-9,y2:yA-pA/2+1,stroke:iA,strokeWidth:.9,strokeLinecap:"round"}),C.jsx("text",{x:K.cx,y:yA-(Z.length-1)*z/2,textAnchor:"middle",dominantBaseline:"central",fontSize:13,fontWeight:900,fontFamily:"Orbitron, monospace",fill:oA,letterSpacing:"1px",style:$?{textTransform:"uppercase"}:void 0,className:$?void 0:"zentara-tile-symbol",children:Z.map((CA,_A)=>C.jsx("tspan",{x:K.cx,dy:_A===0?0:z,children:CA},_A))})]},`cap-${J}`)}),!n&&Array.from(w.entries()).flatMap(([K,{color:J,letter:q}])=>(m?[K,K+h]:[K]).map(U=>{const x=S.badgePositions[U];if(!x)return null;const{angleDeg:T}=LY(x.rot,i);return C.jsxs("g",{style:{transform:`translate(${x.x}px, ${x.y}px) rotate(${T}deg)`},className:"zentara-badge",pointerEvents:"none",children:[C.jsx("rect",{x:-14,y:-14,width:28,height:28,rx:3,fill:J,opacity:.25,className:"zentara-badge-glow"}),C.jsx("rect",{x:-11,y:-11,width:22,height:22,rx:2,fill:J,stroke:"rgba(255,255,255,0.6)",strokeWidth:1.2}),C.jsx("text",{x:0,y:.8,textAnchor:"middle",dominantBaseline:"central",fill:"#000",fontSize:10,fontFamily:"Orbitron, monospace",fontWeight:"bold",children:q})]},`badge-${U}`)})),!n&&C.jsx("defs",{children:Array.from(new Set(Array.from(w.values()).filter(K=>K.upgradeLevel>0).map(K=>`${K.color}|${Math.max(1,Math.min(5,K.upgradeLevel))}`))).map(K=>{const[J,q]=K.split("|"),v=Number(q),U=zoe[v-1]??1,x=parseInt(J.slice(1,3),16)/255,T=parseInt(J.slice(3,5),16)/255,z=parseInt(J.slice(5,7),16)/255;return C.jsxs("filter",{id:`turret-glow-${J.replace("#","")}-${v}`,x:"-100%",y:"-100%",width:"300%",height:"300%",children:[C.jsx("feColorMatrix",{type:"matrix",values:`${x} 0 0 0 0  0 ${T} 0 0 0  0 0 ${z} 0 0  0 0 0 1 0`,result:"tinted"}),C.jsx("feDropShadow",{in:"tinted",dx:"0",dy:"0",stdDeviation:3*U,floodColor:J,floodOpacity:Math.min(1,.9*U)}),C.jsx("feDropShadow",{dx:"0",dy:"0",stdDeviation:7*U,floodColor:J,floodOpacity:Math.min(.8,.45*U)})]},`turret-glow-${J}-${v}`)})}),!n&&Array.from(w.entries()).flatMap(([K,{upgradeLevel:J,piece:q,color:v}])=>{var T;if(J<=0)return[];const U=m?[K,K+h]:[K],x=p&&a!=null&&((T=w.get(a))==null?void 0:T.color)===v;return U.map(z=>{const Z=S.turretPositions[z];if(!Z)return null;const eA=xoe(q,J);if(!eA)return null;const aA=G[z],sA=Joe[q]??0;let pA;aA?pA=Math.atan2(aA.y-Z.y,aA.x-Z.x)*180/Math.PI+180+sA:pA=LY(Z.rot,i).angleDeg+sA;const gA=joe[Math.max(0,Math.min(4,J-1))],yA=Math.max(1,Math.min(5,J)),fA=`turret-glow-${v.replace("#","")}-${yA}`,RA=-gA/2,qA=-gA/2,W=RA+gA*.08,$=qA+gA*.5;return C.jsx("g",{style:{transform:`translate(${Z.x}px, ${Z.y}px) scale(1.69)`},pointerEvents:"none",className:"zentara-turret-glow",children:C.jsx("g",{className:"zentara-turret-rotor",style:{transform:`rotate(${pA}deg)`},children:C.jsxs("g",{style:Loe[q]?{transform:"scale(-1, 1)"}:void 0,children:[C.jsx("g",{className:x?"zentara-turret-recoil":void 0,children:C.jsx("image",{href:eA,x:RA,y:qA,width:gA,height:gA,preserveAspectRatio:"xMidYMid meet",filter:`url(#${fA})`})}),x&&C.jsxs("g",{className:"zentara-muzzle-flash",pointerEvents:"none",children:[C.jsx("ellipse",{cx:W,cy:$,rx:gA*.2,ry:gA*.11,fill:v,opacity:.85}),C.jsx("ellipse",{cx:W,cy:$,rx:gA*.1,ry:gA*.055,fill:"#fff8e0"})]})]})})},`turret-${z}`)})}),t,!1,_&&(()=>{const K=140*_.scale;return C.jsx("image",{href:HZ,x:_.cx-K/2,y:_.cy-K/2,width:K,height:K,className:"zentara-blast-explosion",pointerEvents:"none"})})()]}),n&&C.jsx("path",{d:`M${hn},${hn} L${hn},${_0} A${na+sm},${na+sm} 0 0 1 ${hn+(na+sm)*Math.sin(Math.PI)},${hn-(na+sm)*Math.cos(Math.PI)} Z`,fill:"rgba(123, 47, 242, 0.08)",stroke:"rgba(123, 47, 242, 0.3)",strokeWidth:3})]})};function ise(e,A){return e.tiles===A.tiles&&e.rotationDeg===A.rotationDeg&&e.properties===A.properties&&e.players===A.players&&e.laserBeamTile===A.laserBeamTile&&e.blastDamage===A.blastDamage&&e.liftedTile===A.liftedTile&&e.currentPlayerTile===A.currentPlayerTile&&e.currentPlayerColor===A.currentPlayerColor&&e.suppressDarkOverlay===A.suppressDarkOverlay&&e.mini===A.mini&&e.ringRef===A.ringRef}const nse=ue.memo(tse,ise);function nU(e,A){return 180-e*(360/A)}function TY(e,A,t,i){const n=360*t/i;let g=A-e;return g=(g%n+n*1.5)%n-n/2,e+g}function gse(e,A,t,i,n){const o=-((t-A+i)%i)*(360/n);return e+o}function ose(e){return e.roundNumber===1&&e.currentPlayerIndex===0&&e.currentTurn.phase==="pre-roll"&&e.currentTurn.diceValues===null&&e.players.every(A=>A.tileIndex===0)}const sse=1.5,ase=2.25,iiA=[sse,ase],rse=Ui.isNativePlatform(),Ise=({gameState:e,onTileClick:A,zoomOverride:t,onPieceArrival:i,onPieceMoveStart:n,onZoomChange:g,focusTileIndex:o,toggleZoomRef:s,laserBeamTile:a,laserBeamSeq:r,blastDamage:I,suppressDarkOverlay:c=!0,children:l})=>{var H,P,tA;const B=((H=e.players[e.currentPlayerIndex])==null?void 0:H.id)??"",Q=((P=e.players[e.currentPlayerIndex])==null?void 0:P.tileIndex)??0,h=((tA=e.players[e.currentPlayerIndex])==null?void 0:tA.pieceColor)??"#bfefff",d=e.board.length,p=ose(e),y=d===20?40:d,[m,D]=E.useState(()=>nU(Q,y)),S=E.useRef([]),k=E.useRef(null),N=E.useRef(null),[G,M]=E.useState(0),w=iiA[G],b=t??w,_=E.useCallback(()=>M(iA=>(iA+1)%iiA.length),[]);E.useEffect(()=>(s&&(s.current=_),()=>{s&&(s.current=null)}),[_,s]),E.useEffect(()=>{g==null||g(b)},[b,g]);const K=E.useCallback(iA=>{iA.propertyName==="scale"&&requestAnimationFrame(()=>D(oA=>oA+.001))},[]),J=E.useRef(e.currentPlayerIndex);E.useEffect(()=>{if(!e.finished&&e.currentPlayerIndex!==J.current){J.current=e.currentPlayerIndex;const iA=setTimeout(()=>D(oA=>TY(oA,nU(Q,y),d,y)),1200);return()=>clearTimeout(iA)}},[e.currentPlayerIndex,Q,e.finished,d,y]);const[q,v]=E.useState(null),U=E.useRef(void 0),x=E.useRef(null),T=E.useRef(null),z=E.useCallback(()=>{var iA;N.current!=null&&(cancelAnimationFrame(N.current),N.current=null);for(const oA of S.current)clearTimeout(oA);S.current=[],(iA=k.current)==null||iA.classList.remove("zentara-tile--moving-lit"),k.current=null},[]);E.useEffect(()=>z,[z]);const Z=E.useCallback((iA,oA)=>{var O;z();const IA=Om(iA,qA.current,d,y),CA=qA.current,_A=gse(CA,iA,oA,d,y),uA=(oA-iA+d)%d,X=cA=>{var YA;const wA=T.current;if(!wA)return;(YA=k.current)==null||YA.classList.remove("zentara-tile--moving-lit");const xA=wA.querySelector(`[data-visual-tile="${cA}"]`);xA==null||xA.classList.add("zentara-tile--moving-lit"),k.current=xA};if((O=x.current)==null||O.classList.add("zentara-board-container--piece-moving"),N.current=requestAnimationFrame(()=>{N.current=null,D(_A)}),!rse){X(IA);for(let cA=1;cA<=uA;cA+=1){const wA=(cA-.5)/Math.max(uA,1),xA=hB.BOARD_ROTATE_MS*wA,YA=(IA+cA)%y;S.current.push(setTimeout(()=>X(YA),xA))}}},[d,z,y]);E.useEffect(()=>{o!=null&&D(iA=>TY(iA,nU(o,y),d,y))},[o,d,y]);const eA=E.useCallback(iA=>{var oA;z(),D(IA=>TY(IA,nU(iA,y),d,y)),clearTimeout(U.current),v(null),(oA=x.current)==null||oA.classList.remove("zentara-board-container--piece-moving"),i==null||i()},[i,d,z,y]),aA=E.useRef({active:!1,startAngle:0,startRot:0}),sA=E.useRef(null),pA=E.useRef(null),gA=E.useRef([]),yA=E.useRef(null),fA=E.useCallback(()=>{yA.current!=null&&(cancelAnimationFrame(yA.current),yA.current=null)},[]),RA=E.useCallback((iA,oA)=>{const IA=x.current;if(!IA)return 0;const CA=IA.getBoundingClientRect(),_A=CA.left+CA.width/2,uA=CA.top+CA.height/2;return Math.atan2(oA-uA,iA-_A)*(180/Math.PI)},[]),qA=E.useRef(m);qA.current=m;const W=E.useCallback(iA=>{var CA,_A,uA,X,O,cA;if(iA.button!==0)return;(_A=(CA=iA.target).setPointerCapture)==null||_A.call(CA,iA.pointerId),fA();const oA=parseFloat(((O=(X=(uA=T.current)==null?void 0:uA.style.transform)==null?void 0:X.match(/rotate\(([^)]+)deg\)/))==null?void 0:O[1])??"NaN"),IA=Number.isFinite(oA)?oA:qA.current;aA.current={active:!0,startAngle:RA(iA.clientX,iA.clientY),startRot:IA},gA.current=[{rot:IA,t:performance.now()}],(cA=x.current)==null||cA.classList.add("zentara-board-container--dragging")},[RA,fA]),$=E.useCallback(iA=>{if(!aA.current.active)return;const IA=RA(iA.clientX,iA.clientY)-aA.current.startAngle,CA=aA.current.startRot+IA;sA.current=CA;const _A=T.current;_A&&(_A.style.transform=`rotate(${CA}deg)`);const uA=gA.current,X=performance.now();for(uA.push({rot:CA,t:X});uA.length>2&&X-uA[0].t>80;)uA.shift();pA.current==null&&(pA.current=requestAnimationFrame(()=>{pA.current=null,sA.current!=null&&aA.current.active&&D(sA.current)}))},[RA]),L=E.useCallback(()=>{var oA;if(!aA.current.active)return;aA.current.active=!1,(oA=x.current)==null||oA.classList.remove("zentara-board-container--dragging"),pA.current!=null&&(cancelAnimationFrame(pA.current),pA.current=null),sA.current!=null&&(D(sA.current),sA.current=null);const iA=gA.current;if(iA.length>=2){const IA=iA[iA.length-1],CA=iA[0],_A=IA.t-CA.t;let uA=_A>0?(IA.rot-CA.rot)/_A:0;if(Math.abs(uA)>.08){uA>1.6&&(uA=1.6),uA<-1.6&&(uA=-1.6);const O=.01;let cA=IA.rot,wA=performance.now();const xA=()=>{const YA=performance.now(),jA=YA-wA;wA=YA,cA+=uA*jA,uA*=Math.exp(-.0042*jA);const ie=T.current;ie&&(ie.style.transform=`rotate(${cA}deg)`),D(cA),Math.abs(uA)>O?yA.current=requestAnimationFrame(xA):yA.current=null};yA.current=requestAnimationFrame(xA)}}gA.current=[]},[]);return E.useEffect(()=>{const iA=x.current;if(!iA)return;const oA=IA=>{IA.preventDefault()};return iA.addEventListener("wheel",oA,{passive:!1}),()=>iA.removeEventListener("wheel",oA)},[]),C.jsx("div",{ref:x,onPointerDown:W,onPointerMove:$,onPointerUp:L,onPointerCancel:L,className:"zentara-board-container",children:C.jsxs("div",{className:"zentara-board-inner",style:{scale:String(b)},onTransitionEnd:K,children:[C.jsx(nse,{tiles:e.board,onTileClick:A,rotationDeg:m,properties:e.properties,players:e.players,liftedTile:q,laserBeamTile:a,laserBeamSeq:r,blastDamage:I,ringRef:T,currentPlayerTile:Q,currentPlayerColor:h,children:C.jsx(voe,{players:e.players,currentPlayerId:B,onMoveStart:Z,onFlightStart:n,onArrival:eA,zoom:b,boardRotation:m,tileCount:y,gameTileCount:d,jailTileIndex:e.board.findIndex(iA=>iA.type==="jail"),onlyCurrentPlayer:p})}),l]})})},Cse=ue.memo(Ise);let V;const $n=new Array(128).fill(void 0);function ug(e){return $n[e]}$n.push(void 0,null,!0,!1);let fM=$n.length;function Is(e){fM===$n.length&&$n.push($n.length+1);const A=fM;return fM=$n[A],$n[A]=e,A}function qY(e,A){try{return e.apply(this,A)}catch(t){V.__wbindgen_export_0(Is(t))}}function bi(e){return e==null}let Vh=null;function Aa(){return(Vh===null||Vh.buffer.detached===!0||Vh.buffer.detached===void 0&&Vh.buffer!==V.memory.buffer)&&(Vh=new DataView(V.memory.buffer)),Vh}function DN(e){const A=ug(e);return function(t){t<132||($n[t]=fM,fM=t)}(e),A}const AfA=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder<"u"&&AfA.decode();let wk=null;function efA(e,A){return e>>>=0,AfA.decode((wk!==null&&wk.byteLength!==0||(wk=new Uint8Array(V.memory.buffer)),wk).subarray(e,e+A))}function XA(e,A){if(!(e instanceof A))throw new Error(`expected instance of ${A.name}`)}let Jg=128;function co(e){if(Jg==1)throw new Error("out of js stack");return $n[--Jg]=e,Jg}let kk=null;function tfA(){return kk!==null&&kk.byteLength!==0||(kk=new Float32Array(V.memory.buffer)),kk}function niA(e,A){return e>>>=0,tfA().subarray(e/4,e/4+A)}let Mk=null;function ifA(){return Mk!==null&&Mk.byteLength!==0||(Mk=new Uint32Array(V.memory.buffer)),Mk}let _I=0;function dh(e,A){const t=A(4*e.length,4)>>>0;return tfA().set(e,t/4),_I=e.length,t}function gU(e,A){const t=A(4*e.length,4)>>>0;return ifA().set(e,t/4),_I=e.length,t}const Cx=Object.freeze({LinX:0,0:"LinX",LinY:1,1:"LinY",LinZ:2,2:"LinZ",AngX:3,3:"AngX",AngY:4,4:"AngY",AngZ:5,5:"AngZ"}),Jc=Object.freeze({Revolute:0,0:"Revolute",Fixed:1,1:"Fixed",Prismatic:2,2:"Prismatic",Rope:3,3:"Rope",Spring:4,4:"Spring",Spherical:5,5:"Spherical",Generic:6,6:"Generic"}),ua=Object.freeze({Ball:0,0:"Ball",Cuboid:1,1:"Cuboid",Capsule:2,2:"Capsule",Segment:3,3:"Segment",Polyline:4,4:"Polyline",Triangle:5,5:"Triangle",TriMesh:6,6:"TriMesh",HeightField:7,7:"HeightField",Compound:8,8:"Compound",ConvexPolyhedron:9,9:"ConvexPolyhedron",Cylinder:10,10:"Cylinder",Cone:11,11:"Cone",RoundCuboid:12,12:"RoundCuboid",RoundTriangle:13,13:"RoundTriangle",RoundCylinder:14,14:"RoundCylinder",RoundCone:15,15:"RoundCone",RoundConvexPolyhedron:16,16:"RoundConvexPolyhedron",HalfSpace:17,17:"HalfSpace"}),YY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawbroadphase_free(e>>>0,1));class Qf{static __wrap(A){A>>>=0;const t=Object.create(Qf.prototype);return t.__wbg_ptr=A,YY.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,YY.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawbroadphase_free(A,0)}constructor(){const A=V.rawbroadphase_new();return this.__wbg_ptr=A>>>0,YY.register(this,this.__wbg_ptr,this),this}}const giA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawccdsolver_free(e>>>0,1));class e4{__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,giA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawccdsolver_free(A,0)}constructor(){const A=V.rawccdsolver_new();return this.__wbg_ptr=A>>>0,giA.register(this,this.__wbg_ptr,this),this}}const oiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcharactercollision_free(e>>>0,1));class nfA{__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,oiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawcharactercollision_free(A,0)}constructor(){const A=V.rawcharactercollision_new();return this.__wbg_ptr=A>>>0,oiA.register(this,this.__wbg_ptr,this),this}handle(){return V.rawcharactercollision_handle(this.__wbg_ptr)}translationDeltaApplied(){const A=V.rawcharactercollision_translationDeltaApplied(this.__wbg_ptr);return Ee.__wrap(A)}translationDeltaRemaining(){const A=V.rawcharactercollision_translationDeltaRemaining(this.__wbg_ptr);return Ee.__wrap(A)}toi(){return V.rawcharactercollision_toi(this.__wbg_ptr)}worldWitness1(){const A=V.rawcharactercollision_worldWitness1(this.__wbg_ptr);return Ee.__wrap(A)}worldWitness2(){const A=V.rawcharactercollision_worldWitness2(this.__wbg_ptr);return Ee.__wrap(A)}worldNormal1(){const A=V.rawcharactercollision_worldNormal1(this.__wbg_ptr);return Ee.__wrap(A)}worldNormal2(){const A=V.rawcharactercollision_worldNormal2(this.__wbg_ptr);return Ee.__wrap(A)}}const HY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcolliderset_free(e>>>0,1));class Do{static __wrap(A){A>>>=0;const t=Object.create(Do.prototype);return t.__wbg_ptr=A,HY.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,HY.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawcolliderset_free(A,0)}coTranslation(A){const t=V.rawcolliderset_coTranslation(this.__wbg_ptr,A);return Ee.__wrap(t)}coRotation(A){const t=V.rawcolliderset_coRotation(this.__wbg_ptr,A);return wn.__wrap(t)}coSetTranslation(A,t,i,n){V.rawcolliderset_coSetTranslation(this.__wbg_ptr,A,t,i,n)}coSetTranslationWrtParent(A,t,i,n){V.rawcolliderset_coSetTranslationWrtParent(this.__wbg_ptr,A,t,i,n)}coSetRotation(A,t,i,n,g){V.rawcolliderset_coSetRotation(this.__wbg_ptr,A,t,i,n,g)}coSetRotationWrtParent(A,t,i,n,g){V.rawcolliderset_coSetRotationWrtParent(this.__wbg_ptr,A,t,i,n,g)}coIsSensor(A){return V.rawcolliderset_coIsSensor(this.__wbg_ptr,A)!==0}coShapeType(A){return V.rawcolliderset_coShapeType(this.__wbg_ptr,A)}coHalfspaceNormal(A){const t=V.rawcolliderset_coHalfspaceNormal(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}coHalfExtents(A){const t=V.rawcolliderset_coHalfExtents(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}coSetHalfExtents(A,t){XA(t,Ee),V.rawcolliderset_coSetHalfExtents(this.__wbg_ptr,A,t.__wbg_ptr)}coRadius(A){const t=V.rawcolliderset_coRadius(this.__wbg_ptr,A);return t===4294967297?void 0:t}coSetRadius(A,t){V.rawcolliderset_coSetRadius(this.__wbg_ptr,A,t)}coHalfHeight(A){const t=V.rawcolliderset_coHalfHeight(this.__wbg_ptr,A);return t===4294967297?void 0:t}coSetHalfHeight(A,t){V.rawcolliderset_coSetHalfHeight(this.__wbg_ptr,A,t)}coRoundRadius(A){const t=V.rawcolliderset_coRoundRadius(this.__wbg_ptr,A);return t===4294967297?void 0:t}coSetRoundRadius(A,t){V.rawcolliderset_coSetRoundRadius(this.__wbg_ptr,A,t)}coVertices(A){try{const n=V.__wbindgen_add_to_stack_pointer(-16);V.rawcolliderset_coVertices(n,this.__wbg_ptr,A);var t=Aa().getInt32(n+0,!0),i=Aa().getInt32(n+4,!0);let g;return t!==0&&(g=niA(t,i).slice(),V.__wbindgen_export_1(t,4*i,4)),g}finally{V.__wbindgen_add_to_stack_pointer(16)}}coIndices(A){try{const n=V.__wbindgen_add_to_stack_pointer(-16);V.rawcolliderset_coIndices(n,this.__wbg_ptr,A);var t=Aa().getInt32(n+0,!0),i=Aa().getInt32(n+4,!0);let g;return t!==0&&(g=function(o,s){return o>>>=0,ifA().subarray(o/4,o/4+s)}(t,i).slice(),V.__wbindgen_export_1(t,4*i,4)),g}finally{V.__wbindgen_add_to_stack_pointer(16)}}coTriMeshFlags(A){const t=V.rawcolliderset_coTriMeshFlags(this.__wbg_ptr,A);return t===4294967297?void 0:t}coHeightFieldFlags(A){const t=V.rawcolliderset_coHeightFieldFlags(this.__wbg_ptr,A);return t===4294967297?void 0:t}coHeightfieldHeights(A){try{const n=V.__wbindgen_add_to_stack_pointer(-16);V.rawcolliderset_coHeightfieldHeights(n,this.__wbg_ptr,A);var t=Aa().getInt32(n+0,!0),i=Aa().getInt32(n+4,!0);let g;return t!==0&&(g=niA(t,i).slice(),V.__wbindgen_export_1(t,4*i,4)),g}finally{V.__wbindgen_add_to_stack_pointer(16)}}coHeightfieldScale(A){const t=V.rawcolliderset_coHeightfieldScale(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}coHeightfieldNRows(A){const t=V.rawcolliderset_coHeightfieldNRows(this.__wbg_ptr,A);return t===4294967297?void 0:t}coHeightfieldNCols(A){const t=V.rawcolliderset_coHeightfieldNCols(this.__wbg_ptr,A);return t===4294967297?void 0:t}coParent(A){try{const n=V.__wbindgen_add_to_stack_pointer(-16);V.rawcolliderset_coParent(n,this.__wbg_ptr,A);var t=Aa().getInt32(n+0,!0),i=Aa().getFloat64(n+8,!0);return t===0?void 0:i}finally{V.__wbindgen_add_to_stack_pointer(16)}}coSetEnabled(A,t){V.rawcolliderset_coSetEnabled(this.__wbg_ptr,A,t)}coIsEnabled(A){return V.rawcolliderset_coIsEnabled(this.__wbg_ptr,A)!==0}coSetContactSkin(A,t){V.rawcolliderset_coSetContactSkin(this.__wbg_ptr,A,t)}coContactSkin(A){return V.rawcolliderset_coContactSkin(this.__wbg_ptr,A)}coFriction(A){return V.rawcolliderset_coFriction(this.__wbg_ptr,A)}coRestitution(A){return V.rawcolliderset_coRestitution(this.__wbg_ptr,A)}coDensity(A){return V.rawcolliderset_coDensity(this.__wbg_ptr,A)}coMass(A){return V.rawcolliderset_coMass(this.__wbg_ptr,A)}coVolume(A){return V.rawcolliderset_coVolume(this.__wbg_ptr,A)}coCollisionGroups(A){return V.rawcolliderset_coCollisionGroups(this.__wbg_ptr,A)>>>0}coSolverGroups(A){return V.rawcolliderset_coSolverGroups(this.__wbg_ptr,A)>>>0}coActiveHooks(A){return V.rawcolliderset_coActiveHooks(this.__wbg_ptr,A)>>>0}coActiveCollisionTypes(A){return V.rawcolliderset_coActiveCollisionTypes(this.__wbg_ptr,A)}coActiveEvents(A){return V.rawcolliderset_coActiveEvents(this.__wbg_ptr,A)>>>0}coContactForceEventThreshold(A){return V.rawcolliderset_coContactForceEventThreshold(this.__wbg_ptr,A)}coContainsPoint(A,t){return XA(t,Ee),V.rawcolliderset_coContainsPoint(this.__wbg_ptr,A,t.__wbg_ptr)!==0}coCastShape(A,t,i,n,g,o,s,a,r){XA(t,Ee),XA(i,ki),XA(n,Ee),XA(g,wn),XA(o,Ee);const I=V.rawcolliderset_coCastShape(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,o.__wbg_ptr,s,a,r);return I===0?void 0:Qx.__wrap(I)}coCastCollider(A,t,i,n,g,o,s){XA(t,Ee),XA(n,Ee);const a=V.rawcolliderset_coCastCollider(this.__wbg_ptr,A,t.__wbg_ptr,i,n.__wbg_ptr,g,o,s);return a===0?void 0:cx.__wrap(a)}coIntersectsShape(A,t,i,n){return XA(t,ki),XA(i,Ee),XA(n,wn),V.rawcolliderset_coIntersectsShape(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr)!==0}coContactShape(A,t,i,n,g){XA(t,ki),XA(i,Ee),XA(n,wn);const o=V.rawcolliderset_coContactShape(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g);return o===0?void 0:mN.__wrap(o)}coContactCollider(A,t,i){const n=V.rawcolliderset_coContactCollider(this.__wbg_ptr,A,t,i);return n===0?void 0:mN.__wrap(n)}coProjectPoint(A,t,i){XA(t,Ee);const n=V.rawcolliderset_coProjectPoint(this.__wbg_ptr,A,t.__wbg_ptr,i);return lx.__wrap(n)}coIntersectsRay(A,t,i,n){return XA(t,Ee),XA(i,Ee),V.rawcolliderset_coIntersectsRay(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n)!==0}coCastRay(A,t,i,n,g){return XA(t,Ee),XA(i,Ee),V.rawcolliderset_coCastRay(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n,g)}coCastRayAndGetNormal(A,t,i,n,g){XA(t,Ee),XA(i,Ee);const o=V.rawcolliderset_coCastRayAndGetNormal(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n,g);return o===0?void 0:Ex.__wrap(o)}coSetSensor(A,t){V.rawcolliderset_coSetSensor(this.__wbg_ptr,A,t)}coSetRestitution(A,t){V.rawcolliderset_coSetRestitution(this.__wbg_ptr,A,t)}coSetFriction(A,t){V.rawcolliderset_coSetFriction(this.__wbg_ptr,A,t)}coFrictionCombineRule(A){return V.rawcolliderset_coFrictionCombineRule(this.__wbg_ptr,A)>>>0}coSetFrictionCombineRule(A,t){V.rawcolliderset_coSetFrictionCombineRule(this.__wbg_ptr,A,t)}coRestitutionCombineRule(A){return V.rawcolliderset_coRestitutionCombineRule(this.__wbg_ptr,A)>>>0}coSetRestitutionCombineRule(A,t){V.rawcolliderset_coSetRestitutionCombineRule(this.__wbg_ptr,A,t)}coSetCollisionGroups(A,t){V.rawcolliderset_coSetCollisionGroups(this.__wbg_ptr,A,t)}coSetSolverGroups(A,t){V.rawcolliderset_coSetSolverGroups(this.__wbg_ptr,A,t)}coSetActiveHooks(A,t){V.rawcolliderset_coSetActiveHooks(this.__wbg_ptr,A,t)}coSetActiveEvents(A,t){V.rawcolliderset_coSetActiveEvents(this.__wbg_ptr,A,t)}coSetActiveCollisionTypes(A,t){V.rawcolliderset_coSetActiveCollisionTypes(this.__wbg_ptr,A,t)}coSetShape(A,t){XA(t,ki),V.rawcolliderset_coSetShape(this.__wbg_ptr,A,t.__wbg_ptr)}coSetContactForceEventThreshold(A,t){V.rawcolliderset_coSetContactForceEventThreshold(this.__wbg_ptr,A,t)}coSetDensity(A,t){V.rawcolliderset_coSetDensity(this.__wbg_ptr,A,t)}coSetMass(A,t){V.rawcolliderset_coSetMass(this.__wbg_ptr,A,t)}coSetMassProperties(A,t,i,n,g){XA(i,Ee),XA(n,Ee),XA(g,wn),V.rawcolliderset_coSetMassProperties(this.__wbg_ptr,A,t,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr)}constructor(){const A=V.rawcolliderset_new();return this.__wbg_ptr=A>>>0,HY.register(this,this.__wbg_ptr,this),this}len(){return V.rawcolliderset_len(this.__wbg_ptr)>>>0}contains(A){return V.rawcolliderset_contains(this.__wbg_ptr,A)!==0}createCollider(A,t,i,n,g,o,s,a,r,I,c,l,B,Q,h,d,p,y,m,D,S,k,N,G,M){try{const _=V.__wbindgen_add_to_stack_pointer(-16);XA(t,ki),XA(i,Ee),XA(n,wn),XA(s,Ee),XA(a,Ee),XA(r,wn),XA(M,eo),V.rawcolliderset_createCollider(_,this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o,s.__wbg_ptr,a.__wbg_ptr,r.__wbg_ptr,I,c,l,B,Q,h,d,p,y,m,D,S,k,N,G,M.__wbg_ptr);var w=Aa().getInt32(_+0,!0),b=Aa().getFloat64(_+8,!0);return w===0?void 0:b}finally{V.__wbindgen_add_to_stack_pointer(16)}}remove(A,t,i,n){XA(t,oQ),XA(i,eo),V.rawcolliderset_remove(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n)}isHandleValid(A){return V.rawcolliderset_contains(this.__wbg_ptr,A)!==0}forEachColliderHandle(A){try{V.rawcolliderset_forEachColliderHandle(this.__wbg_ptr,co(A))}finally{$n[Jg++]=void 0}}}const siA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcollidershapecasthit_free(e>>>0,1));class cx{static __wrap(A){A>>>=0;const t=Object.create(cx.prototype);return t.__wbg_ptr=A,siA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,siA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawcollidershapecasthit_free(A,0)}colliderHandle(){return V.rawcharactercollision_handle(this.__wbg_ptr)}time_of_impact(){return V.rawcollidershapecasthit_time_of_impact(this.__wbg_ptr)}witness1(){const A=V.rawcollidershapecasthit_witness1(this.__wbg_ptr);return Ee.__wrap(A)}witness2(){const A=V.rawcollidershapecasthit_witness2(this.__wbg_ptr);return Ee.__wrap(A)}normal1(){const A=V.rawcharactercollision_translationDeltaApplied(this.__wbg_ptr);return Ee.__wrap(A)}normal2(){const A=V.rawcharactercollision_translationDeltaRemaining(this.__wbg_ptr);return Ee.__wrap(A)}}const aiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcontactforceevent_free(e>>>0,1));class OZ{static __wrap(A){A>>>=0;const t=Object.create(OZ.prototype);return t.__wbg_ptr=A,aiA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,aiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawcontactforceevent_free(A,0)}collider1(){return V.rawcharactercollision_handle(this.__wbg_ptr)}collider2(){return V.rawcontactforceevent_collider2(this.__wbg_ptr)}total_force(){const A=V.rawcontactforceevent_total_force(this.__wbg_ptr);return Ee.__wrap(A)}total_force_magnitude(){return V.rawcontactforceevent_total_force_magnitude(this.__wbg_ptr)}max_force_direction(){const A=V.rawcontactforceevent_max_force_direction(this.__wbg_ptr);return Ee.__wrap(A)}max_force_magnitude(){return V.rawcontactforceevent_max_force_magnitude(this.__wbg_ptr)}}const riA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcontactmanifold_free(e>>>0,1));let cse=class gfA{static __wrap(A){A>>>=0;const t=Object.create(gfA.prototype);return t.__wbg_ptr=A,riA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,riA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawcontactmanifold_free(A,0)}normal(){const A=V.rawcontactmanifold_normal(this.__wbg_ptr);return Ee.__wrap(A)}local_n1(){const A=V.rawcontactmanifold_local_n1(this.__wbg_ptr);return Ee.__wrap(A)}local_n2(){const A=V.rawcontactmanifold_local_n2(this.__wbg_ptr);return Ee.__wrap(A)}subshape1(){return V.rawcontactmanifold_subshape1(this.__wbg_ptr)>>>0}subshape2(){return V.rawcontactmanifold_subshape2(this.__wbg_ptr)>>>0}num_contacts(){return V.rawcontactmanifold_num_contacts(this.__wbg_ptr)>>>0}contact_local_p1(A){const t=V.rawcontactmanifold_contact_local_p1(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}contact_local_p2(A){const t=V.rawcontactmanifold_contact_local_p2(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}contact_dist(A){return V.rawcontactmanifold_contact_dist(this.__wbg_ptr,A)}contact_fid1(A){return V.rawcontactmanifold_contact_fid1(this.__wbg_ptr,A)>>>0}contact_fid2(A){return V.rawcontactmanifold_contact_fid2(this.__wbg_ptr,A)>>>0}contact_impulse(A){return V.rawcontactmanifold_contact_impulse(this.__wbg_ptr,A)}contact_tangent_impulse_x(A){return V.rawcontactmanifold_contact_tangent_impulse_x(this.__wbg_ptr,A)}contact_tangent_impulse_y(A){return V.rawcontactmanifold_contact_tangent_impulse_y(this.__wbg_ptr,A)}num_solver_contacts(){return V.rawcontactmanifold_num_solver_contacts(this.__wbg_ptr)>>>0}solver_contact_point(A){const t=V.rawcontactmanifold_solver_contact_point(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}solver_contact_dist(A){return V.rawcontactmanifold_solver_contact_dist(this.__wbg_ptr,A)}solver_contact_friction(A){return V.rawcontactmanifold_solver_contact_friction(this.__wbg_ptr,A)}solver_contact_restitution(A){return V.rawcontactmanifold_solver_contact_restitution(this.__wbg_ptr,A)}solver_contact_tangent_velocity(A){const t=V.rawcontactmanifold_solver_contact_tangent_velocity(this.__wbg_ptr,A);return Ee.__wrap(t)}};const IiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcontactpair_free(e>>>0,1));let lse=class ofA{static __wrap(A){A>>>=0;const t=Object.create(ofA.prototype);return t.__wbg_ptr=A,IiA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,IiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawcontactpair_free(A,0)}collider1(){return V.rawcontactpair_collider1(this.__wbg_ptr)}collider2(){return V.rawcontactpair_collider2(this.__wbg_ptr)}numContactManifolds(){return V.rawcontactpair_numContactManifolds(this.__wbg_ptr)>>>0}contactManifold(A){const t=V.rawcontactpair_contactManifold(this.__wbg_ptr,A);return t===0?void 0:cse.__wrap(t)}};const CiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawdebugrenderpipeline_free(e>>>0,1));let Bse=class{__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,CiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawdebugrenderpipeline_free(A,0)}constructor(){const A=V.rawdebugrenderpipeline_new();return this.__wbg_ptr=A>>>0,CiA.register(this,this.__wbg_ptr,this),this}vertices(){return DN(V.rawdebugrenderpipeline_vertices(this.__wbg_ptr))}colors(){return DN(V.rawdebugrenderpipeline_colors(this.__wbg_ptr))}render(A,t,i,n,g){XA(A,eo),XA(t,Do),XA(i,gQ),XA(n,sQ),XA(g,Qd),V.rawdebugrenderpipeline_render(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr)}};const ciA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawdeserializedworld_free(e>>>0,1));let Ese=class sfA{static __wrap(A){A>>>=0;const t=Object.create(sfA.prototype);return t.__wbg_ptr=A,ciA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,ciA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawdeserializedworld_free(A,0)}takeGravity(){const A=V.rawdeserializedworld_takeGravity(this.__wbg_ptr);return A===0?void 0:Ee.__wrap(A)}takeIntegrationParameters(){const A=V.rawdeserializedworld_takeIntegrationParameters(this.__wbg_ptr);return A===0?void 0:uf.__wrap(A)}takeIslandManager(){const A=V.rawdeserializedworld_takeIslandManager(this.__wbg_ptr);return A===0?void 0:oQ.__wrap(A)}takeBroadPhase(){const A=V.rawdeserializedworld_takeBroadPhase(this.__wbg_ptr);return A===0?void 0:Qf.__wrap(A)}takeNarrowPhase(){const A=V.rawdeserializedworld_takeNarrowPhase(this.__wbg_ptr);return A===0?void 0:Qd.__wrap(A)}takeBodies(){const A=V.rawdeserializedworld_takeBodies(this.__wbg_ptr);return A===0?void 0:eo.__wrap(A)}takeColliders(){const A=V.rawdeserializedworld_takeColliders(this.__wbg_ptr);return A===0?void 0:Do.__wrap(A)}takeImpulseJoints(){const A=V.rawdeserializedworld_takeImpulseJoints(this.__wbg_ptr);return A===0?void 0:gQ.__wrap(A)}takeMultibodyJoints(){const A=V.rawdeserializedworld_takeMultibodyJoints(this.__wbg_ptr);return A===0?void 0:sQ.__wrap(A)}};const liA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawdynamicraycastvehiclecontroller_free(e>>>0,1));class Qse{__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,liA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawdynamicraycastvehiclecontroller_free(A,0)}constructor(A){const t=V.rawdynamicraycastvehiclecontroller_new(A);return this.__wbg_ptr=t>>>0,liA.register(this,this.__wbg_ptr,this),this}current_vehicle_speed(){return V.rawdynamicraycastvehiclecontroller_current_vehicle_speed(this.__wbg_ptr)}chassis(){return V.rawdynamicraycastvehiclecontroller_chassis(this.__wbg_ptr)}index_up_axis(){return V.rawdynamicraycastvehiclecontroller_index_up_axis(this.__wbg_ptr)>>>0}set_index_up_axis(A){V.rawdynamicraycastvehiclecontroller_set_index_up_axis(this.__wbg_ptr,A)}index_forward_axis(){return V.rawdynamicraycastvehiclecontroller_index_forward_axis(this.__wbg_ptr)>>>0}set_index_forward_axis(A){V.rawdynamicraycastvehiclecontroller_set_index_forward_axis(this.__wbg_ptr,A)}add_wheel(A,t,i,n,g){XA(A,Ee),XA(t,Ee),XA(i,Ee),V.rawdynamicraycastvehiclecontroller_add_wheel(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n,g)}num_wheels(){return V.rawdynamicraycastvehiclecontroller_num_wheels(this.__wbg_ptr)>>>0}update_vehicle(A,t,i,n,g,o,s){try{XA(t,eo),XA(i,Do),XA(n,PZ),V.rawdynamicraycastvehiclecontroller_update_vehicle(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,bi(o)?4294967297:o>>>0,co(s))}finally{$n[Jg++]=void 0}}wheel_chassis_connection_point_cs(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_chassis_connection_point_cs(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}set_wheel_chassis_connection_point_cs(A,t){XA(t,Ee),V.rawdynamicraycastvehiclecontroller_set_wheel_chassis_connection_point_cs(this.__wbg_ptr,A,t.__wbg_ptr)}wheel_suspension_rest_length(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_suspension_rest_length(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_suspension_rest_length(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_suspension_rest_length(this.__wbg_ptr,A,t)}wheel_max_suspension_travel(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_max_suspension_travel(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_max_suspension_travel(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_max_suspension_travel(this.__wbg_ptr,A,t)}wheel_radius(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_radius(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_radius(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_radius(this.__wbg_ptr,A,t)}wheel_suspension_stiffness(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_suspension_stiffness(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_suspension_stiffness(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_suspension_stiffness(this.__wbg_ptr,A,t)}wheel_suspension_compression(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_suspension_compression(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_suspension_compression(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_suspension_compression(this.__wbg_ptr,A,t)}wheel_suspension_relaxation(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_suspension_relaxation(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_suspension_relaxation(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_suspension_relaxation(this.__wbg_ptr,A,t)}wheel_max_suspension_force(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_max_suspension_force(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_max_suspension_force(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_max_suspension_force(this.__wbg_ptr,A,t)}wheel_brake(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_brake(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_brake(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_brake(this.__wbg_ptr,A,t)}wheel_steering(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_steering(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_steering(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_steering(this.__wbg_ptr,A,t)}wheel_engine_force(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_engine_force(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_engine_force(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_engine_force(this.__wbg_ptr,A,t)}wheel_direction_cs(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_direction_cs(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}set_wheel_direction_cs(A,t){XA(t,Ee),V.rawdynamicraycastvehiclecontroller_set_wheel_direction_cs(this.__wbg_ptr,A,t.__wbg_ptr)}wheel_axle_cs(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_axle_cs(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}set_wheel_axle_cs(A,t){XA(t,Ee),V.rawdynamicraycastvehiclecontroller_set_wheel_axle_cs(this.__wbg_ptr,A,t.__wbg_ptr)}wheel_friction_slip(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_friction_slip(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_friction_slip(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_friction_slip(this.__wbg_ptr,A,t)}wheel_side_friction_stiffness(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_side_friction_stiffness(this.__wbg_ptr,A);return t===4294967297?void 0:t}set_wheel_side_friction_stiffness(A,t){V.rawdynamicraycastvehiclecontroller_set_wheel_side_friction_stiffness(this.__wbg_ptr,A,t)}wheel_rotation(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_rotation(this.__wbg_ptr,A);return t===4294967297?void 0:t}wheel_forward_impulse(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_forward_impulse(this.__wbg_ptr,A);return t===4294967297?void 0:t}wheel_side_impulse(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_side_impulse(this.__wbg_ptr,A);return t===4294967297?void 0:t}wheel_suspension_force(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_suspension_force(this.__wbg_ptr,A);return t===4294967297?void 0:t}wheel_contact_normal_ws(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_contact_normal_ws(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}wheel_contact_point_ws(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_contact_point_ws(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}wheel_suspension_length(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_suspension_length(this.__wbg_ptr,A);return t===4294967297?void 0:t}wheel_hard_point_ws(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_hard_point_ws(this.__wbg_ptr,A);return t===0?void 0:Ee.__wrap(t)}wheel_is_in_contact(A){return V.rawdynamicraycastvehiclecontroller_wheel_is_in_contact(this.__wbg_ptr,A)!==0}wheel_ground_object(A){try{const n=V.__wbindgen_add_to_stack_pointer(-16);V.rawdynamicraycastvehiclecontroller_wheel_ground_object(n,this.__wbg_ptr,A);var t=Aa().getInt32(n+0,!0),i=Aa().getFloat64(n+8,!0);return t===0?void 0:i}finally{V.__wbindgen_add_to_stack_pointer(16)}}}const BiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_raweventqueue_free(e>>>0,1));class afA{__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,BiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_raweventqueue_free(A,0)}constructor(A){const t=V.raweventqueue_new(A);return this.__wbg_ptr=t>>>0,BiA.register(this,this.__wbg_ptr,this),this}drainCollisionEvents(A){try{V.raweventqueue_drainCollisionEvents(this.__wbg_ptr,co(A))}finally{$n[Jg++]=void 0}}drainContactForceEvents(A){try{V.raweventqueue_drainContactForceEvents(this.__wbg_ptr,co(A))}finally{$n[Jg++]=void 0}}clear(){V.raweventqueue_clear(this.__wbg_ptr)}}const EiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawgenericjoint_free(e>>>0,1));class ta{static __wrap(A){A>>>=0;const t=Object.create(ta.prototype);return t.__wbg_ptr=A,EiA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,EiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawgenericjoint_free(A,0)}static generic(A,t,i,n){XA(A,Ee),XA(t,Ee),XA(i,Ee);const g=V.rawgenericjoint_generic(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n);return g===0?void 0:ta.__wrap(g)}static spring(A,t,i,n,g){XA(n,Ee),XA(g,Ee);const o=V.rawgenericjoint_spring(A,t,i,n.__wbg_ptr,g.__wbg_ptr);return ta.__wrap(o)}static rope(A,t,i){XA(t,Ee),XA(i,Ee);const n=V.rawgenericjoint_rope(A,t.__wbg_ptr,i.__wbg_ptr);return ta.__wrap(n)}static spherical(A,t){XA(A,Ee),XA(t,Ee);const i=V.rawgenericjoint_spherical(A.__wbg_ptr,t.__wbg_ptr);return ta.__wrap(i)}static prismatic(A,t,i,n,g,o){XA(A,Ee),XA(t,Ee),XA(i,Ee);const s=V.rawgenericjoint_prismatic(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n,g,o);return s===0?void 0:ta.__wrap(s)}static fixed(A,t,i,n){XA(A,Ee),XA(t,wn),XA(i,Ee),XA(n,wn);const g=V.rawgenericjoint_fixed(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr);return ta.__wrap(g)}static revolute(A,t,i){XA(A,Ee),XA(t,Ee),XA(i,Ee);const n=V.rawgenericjoint_revolute(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr);return n===0?void 0:ta.__wrap(n)}}const OY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawimpulsejointset_free(e>>>0,1));class gQ{static __wrap(A){A>>>=0;const t=Object.create(gQ.prototype);return t.__wbg_ptr=A,OY.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,OY.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawimpulsejointset_free(A,0)}jointType(A){return V.rawimpulsejointset_jointType(this.__wbg_ptr,A)}jointBodyHandle1(A){return V.rawimpulsejointset_jointBodyHandle1(this.__wbg_ptr,A)}jointBodyHandle2(A){return V.rawimpulsejointset_jointBodyHandle2(this.__wbg_ptr,A)}jointFrameX1(A){const t=V.rawimpulsejointset_jointFrameX1(this.__wbg_ptr,A);return wn.__wrap(t)}jointFrameX2(A){const t=V.rawimpulsejointset_jointFrameX2(this.__wbg_ptr,A);return wn.__wrap(t)}jointAnchor1(A){const t=V.rawimpulsejointset_jointAnchor1(this.__wbg_ptr,A);return Ee.__wrap(t)}jointAnchor2(A){const t=V.rawimpulsejointset_jointAnchor2(this.__wbg_ptr,A);return Ee.__wrap(t)}jointSetAnchor1(A,t){XA(t,Ee),V.rawimpulsejointset_jointSetAnchor1(this.__wbg_ptr,A,t.__wbg_ptr)}jointSetAnchor2(A,t){XA(t,Ee),V.rawimpulsejointset_jointSetAnchor2(this.__wbg_ptr,A,t.__wbg_ptr)}jointContactsEnabled(A){return V.rawimpulsejointset_jointContactsEnabled(this.__wbg_ptr,A)!==0}jointSetContactsEnabled(A,t){V.rawimpulsejointset_jointSetContactsEnabled(this.__wbg_ptr,A,t)}jointLimitsEnabled(A,t){return V.rawimpulsejointset_jointLimitsEnabled(this.__wbg_ptr,A,t)!==0}jointLimitsMin(A,t){return V.rawimpulsejointset_jointLimitsMin(this.__wbg_ptr,A,t)}jointLimitsMax(A,t){return V.rawimpulsejointset_jointLimitsMax(this.__wbg_ptr,A,t)}jointSetLimits(A,t,i,n){V.rawimpulsejointset_jointSetLimits(this.__wbg_ptr,A,t,i,n)}jointConfigureMotorModel(A,t,i){V.rawimpulsejointset_jointConfigureMotorModel(this.__wbg_ptr,A,t,i)}jointConfigureMotorVelocity(A,t,i,n){V.rawimpulsejointset_jointConfigureMotorVelocity(this.__wbg_ptr,A,t,i,n)}jointConfigureMotorPosition(A,t,i,n,g){V.rawimpulsejointset_jointConfigureMotorPosition(this.__wbg_ptr,A,t,i,n,g)}jointConfigureMotor(A,t,i,n,g,o){V.rawimpulsejointset_jointConfigureMotor(this.__wbg_ptr,A,t,i,n,g,o)}constructor(){const A=V.rawimpulsejointset_new();return this.__wbg_ptr=A>>>0,OY.register(this,this.__wbg_ptr,this),this}createJoint(A,t,i,n){return XA(A,ta),V.rawimpulsejointset_createJoint(this.__wbg_ptr,A.__wbg_ptr,t,i,n)}remove(A,t){V.rawimpulsejointset_remove(this.__wbg_ptr,A,t)}len(){return V.rawimpulsejointset_len(this.__wbg_ptr)>>>0}contains(A){return V.rawimpulsejointset_contains(this.__wbg_ptr,A)!==0}forEachJointHandle(A){try{V.rawimpulsejointset_forEachJointHandle(this.__wbg_ptr,co(A))}finally{$n[Jg++]=void 0}}forEachJointAttachedToRigidBody(A,t){try{V.rawimpulsejointset_forEachJointAttachedToRigidBody(this.__wbg_ptr,A,co(t))}finally{$n[Jg++]=void 0}}}const PY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawintegrationparameters_free(e>>>0,1));class uf{static __wrap(A){A>>>=0;const t=Object.create(uf.prototype);return t.__wbg_ptr=A,PY.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,PY.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawintegrationparameters_free(A,0)}constructor(){const A=V.rawintegrationparameters_new();return this.__wbg_ptr=A>>>0,PY.register(this,this.__wbg_ptr,this),this}get dt(){return V.rawintegrationparameters_dt(this.__wbg_ptr)}get contact_erp(){return V.rawintegrationparameters_contact_erp(this.__wbg_ptr)}get normalizedAllowedLinearError(){return V.rawintegrationparameters_normalizedAllowedLinearError(this.__wbg_ptr)}get normalizedPredictionDistance(){return V.rawcontactforceevent_max_force_magnitude(this.__wbg_ptr)}get numSolverIterations(){return V.rawintegrationparameters_numSolverIterations(this.__wbg_ptr)>>>0}get numAdditionalFrictionIterations(){return V.rawintegrationparameters_numAdditionalFrictionIterations(this.__wbg_ptr)>>>0}get numInternalPgsIterations(){return V.rawintegrationparameters_numInternalPgsIterations(this.__wbg_ptr)>>>0}get minIslandSize(){return V.rawimpulsejointset_len(this.__wbg_ptr)>>>0}get maxCcdSubsteps(){return V.rawintegrationparameters_maxCcdSubsteps(this.__wbg_ptr)>>>0}get lengthUnit(){return V.rawintegrationparameters_lengthUnit(this.__wbg_ptr)}set dt(A){V.rawintegrationparameters_set_dt(this.__wbg_ptr,A)}set contact_natural_frequency(A){V.rawintegrationparameters_set_contact_natural_frequency(this.__wbg_ptr,A)}set normalizedAllowedLinearError(A){V.rawintegrationparameters_set_normalizedAllowedLinearError(this.__wbg_ptr,A)}set normalizedPredictionDistance(A){V.rawintegrationparameters_set_normalizedPredictionDistance(this.__wbg_ptr,A)}set numSolverIterations(A){V.rawintegrationparameters_set_numSolverIterations(this.__wbg_ptr,A)}set numAdditionalFrictionIterations(A){V.rawintegrationparameters_set_numAdditionalFrictionIterations(this.__wbg_ptr,A)}set numInternalPgsIterations(A){V.rawintegrationparameters_set_numInternalPgsIterations(this.__wbg_ptr,A)}set minIslandSize(A){V.rawintegrationparameters_set_minIslandSize(this.__wbg_ptr,A)}set maxCcdSubsteps(A){V.rawintegrationparameters_set_maxCcdSubsteps(this.__wbg_ptr,A)}set lengthUnit(A){V.rawintegrationparameters_set_lengthUnit(this.__wbg_ptr,A)}switchToStandardPgsSolver(){V.rawintegrationparameters_switchToStandardPgsSolver(this.__wbg_ptr)}switchToSmallStepsPgsSolver(){V.rawintegrationparameters_switchToSmallStepsPgsSolver(this.__wbg_ptr)}switchToSmallStepsPgsSolverWithoutWarmstart(){V.rawintegrationparameters_switchToSmallStepsPgsSolverWithoutWarmstart(this.__wbg_ptr)}}const jY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawislandmanager_free(e>>>0,1));class oQ{static __wrap(A){A>>>=0;const t=Object.create(oQ.prototype);return t.__wbg_ptr=A,jY.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,jY.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawislandmanager_free(A,0)}constructor(){const A=V.rawislandmanager_new();return this.__wbg_ptr=A>>>0,jY.register(this,this.__wbg_ptr,this),this}forEachActiveRigidBodyHandle(A){try{V.rawislandmanager_forEachActiveRigidBodyHandle(this.__wbg_ptr,co(A))}finally{$n[Jg++]=void 0}}}const QiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawkinematiccharactercontroller_free(e>>>0,1));class use{__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,QiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawkinematiccharactercontroller_free(A,0)}constructor(A){const t=V.rawkinematiccharactercontroller_new(A);return this.__wbg_ptr=t>>>0,QiA.register(this,this.__wbg_ptr,this),this}up(){const A=V.rawcharactercollision_translationDeltaApplied(this.__wbg_ptr);return Ee.__wrap(A)}setUp(A){XA(A,Ee),V.rawkinematiccharactercontroller_setUp(this.__wbg_ptr,A.__wbg_ptr)}normalNudgeFactor(){return V.rawkinematiccharactercontroller_normalNudgeFactor(this.__wbg_ptr)}setNormalNudgeFactor(A){V.rawkinematiccharactercontroller_setNormalNudgeFactor(this.__wbg_ptr,A)}offset(){return V.rawintegrationparameters_dt(this.__wbg_ptr)}setOffset(A){V.rawkinematiccharactercontroller_setOffset(this.__wbg_ptr,A)}slideEnabled(){return V.rawkinematiccharactercontroller_slideEnabled(this.__wbg_ptr)!==0}setSlideEnabled(A){V.rawkinematiccharactercontroller_setSlideEnabled(this.__wbg_ptr,A)}autostepMaxHeight(){const A=V.rawkinematiccharactercontroller_autostepMaxHeight(this.__wbg_ptr);return A===4294967297?void 0:A}autostepMinWidth(){const A=V.rawkinematiccharactercontroller_autostepMinWidth(this.__wbg_ptr);return A===4294967297?void 0:A}autostepIncludesDynamicBodies(){const A=V.rawkinematiccharactercontroller_autostepIncludesDynamicBodies(this.__wbg_ptr);return A===16777215?void 0:A!==0}autostepEnabled(){return V.rawkinematiccharactercontroller_autostepEnabled(this.__wbg_ptr)!==0}enableAutostep(A,t,i){V.rawkinematiccharactercontroller_enableAutostep(this.__wbg_ptr,A,t,i)}disableAutostep(){V.rawkinematiccharactercontroller_disableAutostep(this.__wbg_ptr)}maxSlopeClimbAngle(){return V.rawkinematiccharactercontroller_maxSlopeClimbAngle(this.__wbg_ptr)}setMaxSlopeClimbAngle(A){V.rawkinematiccharactercontroller_setMaxSlopeClimbAngle(this.__wbg_ptr,A)}minSlopeSlideAngle(){return V.rawkinematiccharactercontroller_minSlopeSlideAngle(this.__wbg_ptr)}setMinSlopeSlideAngle(A){V.rawkinematiccharactercontroller_setMinSlopeSlideAngle(this.__wbg_ptr,A)}snapToGroundDistance(){const A=V.rawkinematiccharactercontroller_snapToGroundDistance(this.__wbg_ptr);return A===4294967297?void 0:A}enableSnapToGround(A){V.rawkinematiccharactercontroller_enableSnapToGround(this.__wbg_ptr,A)}disableSnapToGround(){V.rawkinematiccharactercontroller_disableSnapToGround(this.__wbg_ptr)}snapToGroundEnabled(){return V.rawkinematiccharactercontroller_snapToGroundEnabled(this.__wbg_ptr)!==0}computeColliderMovement(A,t,i,n,g,o,s,a,r,I,c){try{XA(t,eo),XA(i,Do),XA(n,PZ),XA(o,Ee),V.rawkinematiccharactercontroller_computeColliderMovement(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o.__wbg_ptr,s,bi(a)?4294967297:Math.fround(a),r,bi(I)?4294967297:I>>>0,co(c))}finally{$n[Jg++]=void 0}}computedMovement(){const A=V.rawkinematiccharactercontroller_computedMovement(this.__wbg_ptr);return Ee.__wrap(A)}computedGrounded(){return V.rawkinematiccharactercontroller_computedGrounded(this.__wbg_ptr)!==0}numComputedCollisions(){return V.rawkinematiccharactercontroller_numComputedCollisions(this.__wbg_ptr)>>>0}computedCollision(A,t){return XA(t,nfA),V.rawkinematiccharactercontroller_computedCollision(this.__wbg_ptr,A,t.__wbg_ptr)!==0}}const zY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawmultibodyjointset_free(e>>>0,1));class sQ{static __wrap(A){A>>>=0;const t=Object.create(sQ.prototype);return t.__wbg_ptr=A,zY.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,zY.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawmultibodyjointset_free(A,0)}jointType(A){return V.rawmultibodyjointset_jointType(this.__wbg_ptr,A)}jointFrameX1(A){const t=V.rawmultibodyjointset_jointFrameX1(this.__wbg_ptr,A);return wn.__wrap(t)}jointFrameX2(A){const t=V.rawmultibodyjointset_jointFrameX2(this.__wbg_ptr,A);return wn.__wrap(t)}jointAnchor1(A){const t=V.rawmultibodyjointset_jointAnchor1(this.__wbg_ptr,A);return Ee.__wrap(t)}jointAnchor2(A){const t=V.rawmultibodyjointset_jointAnchor2(this.__wbg_ptr,A);return Ee.__wrap(t)}jointContactsEnabled(A){return V.rawmultibodyjointset_jointContactsEnabled(this.__wbg_ptr,A)!==0}jointSetContactsEnabled(A,t){V.rawmultibodyjointset_jointSetContactsEnabled(this.__wbg_ptr,A,t)}jointLimitsEnabled(A,t){return V.rawmultibodyjointset_jointLimitsEnabled(this.__wbg_ptr,A,t)!==0}jointLimitsMin(A,t){return V.rawmultibodyjointset_jointLimitsMin(this.__wbg_ptr,A,t)}jointLimitsMax(A,t){return V.rawmultibodyjointset_jointLimitsMax(this.__wbg_ptr,A,t)}constructor(){const A=V.rawmultibodyjointset_new();return this.__wbg_ptr=A>>>0,zY.register(this,this.__wbg_ptr,this),this}createJoint(A,t,i,n){return XA(A,ta),V.rawmultibodyjointset_createJoint(this.__wbg_ptr,A.__wbg_ptr,t,i,n)}remove(A,t){V.rawmultibodyjointset_remove(this.__wbg_ptr,A,t)}contains(A){return V.rawmultibodyjointset_contains(this.__wbg_ptr,A)!==0}forEachJointHandle(A){try{V.rawmultibodyjointset_forEachJointHandle(this.__wbg_ptr,co(A))}finally{$n[Jg++]=void 0}}forEachJointAttachedToRigidBody(A,t){try{V.rawmultibodyjointset_forEachJointAttachedToRigidBody(this.__wbg_ptr,A,co(t))}finally{$n[Jg++]=void 0}}}const ZY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawnarrowphase_free(e>>>0,1));class Qd{static __wrap(A){A>>>=0;const t=Object.create(Qd.prototype);return t.__wbg_ptr=A,ZY.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,ZY.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawnarrowphase_free(A,0)}constructor(){const A=V.rawnarrowphase_new();return this.__wbg_ptr=A>>>0,ZY.register(this,this.__wbg_ptr,this),this}contact_pairs_with(A,t){V.rawnarrowphase_contact_pairs_with(this.__wbg_ptr,A,Is(t))}contact_pair(A,t){const i=V.rawnarrowphase_contact_pair(this.__wbg_ptr,A,t);return i===0?void 0:lse.__wrap(i)}intersection_pairs_with(A,t){V.rawnarrowphase_intersection_pairs_with(this.__wbg_ptr,A,Is(t))}intersection_pair(A,t){return V.rawnarrowphase_intersection_pair(this.__wbg_ptr,A,t)!==0}}const uiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawphysicspipeline_free(e>>>0,1));class dse{__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,uiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawphysicspipeline_free(A,0)}constructor(){const A=V.rawphysicspipeline_new();return this.__wbg_ptr=A>>>0,uiA.register(this,this.__wbg_ptr,this),this}step(A,t,i,n,g,o,s,a,r,I){XA(A,Ee),XA(t,uf),XA(i,oQ),XA(n,Qf),XA(g,Qd),XA(o,eo),XA(s,Do),XA(a,gQ),XA(r,sQ),XA(I,e4),V.rawphysicspipeline_step(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,o.__wbg_ptr,s.__wbg_ptr,a.__wbg_ptr,r.__wbg_ptr,I.__wbg_ptr)}stepWithEvents(A,t,i,n,g,o,s,a,r,I,c,l,B,Q){XA(A,Ee),XA(t,uf),XA(i,oQ),XA(n,Qf),XA(g,Qd),XA(o,eo),XA(s,Do),XA(a,gQ),XA(r,sQ),XA(I,e4),XA(c,afA),V.rawphysicspipeline_stepWithEvents(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,o.__wbg_ptr,s.__wbg_ptr,a.__wbg_ptr,r.__wbg_ptr,I.__wbg_ptr,c.__wbg_ptr,Is(l),Is(B),Is(Q))}}const diA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawpidcontroller_free(e>>>0,1));class hse{__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,diA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawpidcontroller_free(A,0)}constructor(A,t,i,n){const g=V.rawpidcontroller_new(A,t,i,n);return this.__wbg_ptr=g>>>0,diA.register(this,this.__wbg_ptr,this),this}set_kp(A,t){V.rawpidcontroller_set_kp(this.__wbg_ptr,A,t)}set_ki(A,t){V.rawpidcontroller_set_ki(this.__wbg_ptr,A,t)}set_kd(A,t){V.rawpidcontroller_set_kd(this.__wbg_ptr,A,t)}set_axes_mask(A){V.rawpidcontroller_set_axes_mask(this.__wbg_ptr,A)}reset_integrals(){V.rawpidcontroller_reset_integrals(this.__wbg_ptr)}apply_linear_correction(A,t,i,n,g){XA(t,eo),XA(n,Ee),XA(g,Ee),V.rawpidcontroller_apply_linear_correction(this.__wbg_ptr,A,t.__wbg_ptr,i,n.__wbg_ptr,g.__wbg_ptr)}apply_angular_correction(A,t,i,n,g){XA(t,eo),XA(n,wn),XA(g,Ee),V.rawpidcontroller_apply_angular_correction(this.__wbg_ptr,A,t.__wbg_ptr,i,n.__wbg_ptr,g.__wbg_ptr)}linear_correction(A,t,i,n,g){XA(t,eo),XA(n,Ee),XA(g,Ee);const o=V.rawpidcontroller_linear_correction(this.__wbg_ptr,A,t.__wbg_ptr,i,n.__wbg_ptr,g.__wbg_ptr);return Ee.__wrap(o)}angular_correction(A,t,i,n,g){XA(t,eo),XA(n,wn),XA(g,Ee);const o=V.rawpidcontroller_angular_correction(this.__wbg_ptr,A,t.__wbg_ptr,i,n.__wbg_ptr,g.__wbg_ptr);return Ee.__wrap(o)}}const hiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawpointcolliderprojection_free(e>>>0,1));class f_{static __wrap(A){A>>>=0;const t=Object.create(f_.prototype);return t.__wbg_ptr=A,hiA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,hiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawpointcolliderprojection_free(A,0)}colliderHandle(){return V.rawpointcolliderprojection_colliderHandle(this.__wbg_ptr)}point(){const A=V.rawpointcolliderprojection_point(this.__wbg_ptr);return Ee.__wrap(A)}isInside(){return V.rawpointcolliderprojection_isInside(this.__wbg_ptr)!==0}featureType(){return V.rawpointcolliderprojection_featureType(this.__wbg_ptr)}featureId(){const A=V.rawpointcolliderprojection_featureId(this.__wbg_ptr);return A===4294967297?void 0:A}}const piA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawpointprojection_free(e>>>0,1));class lx{static __wrap(A){A>>>=0;const t=Object.create(lx.prototype);return t.__wbg_ptr=A,piA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,piA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawpointprojection_free(A,0)}point(){const A=V.rawpointprojection_point(this.__wbg_ptr);return Ee.__wrap(A)}isInside(){return V.rawpointprojection_isInside(this.__wbg_ptr)!==0}}const fiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawquerypipeline_free(e>>>0,1));class PZ{__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,fiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawquerypipeline_free(A,0)}constructor(){const A=V.rawquerypipeline_new();return this.__wbg_ptr=A>>>0,fiA.register(this,this.__wbg_ptr,this),this}update(A){XA(A,Do),V.rawquerypipeline_update(this.__wbg_ptr,A.__wbg_ptr)}castRay(A,t,i,n,g,o,s,a,r,I,c){try{XA(A,eo),XA(t,Do),XA(i,Ee),XA(n,Ee);const l=V.rawquerypipeline_castRay(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o,s,bi(a)?4294967297:a>>>0,!bi(r),bi(r)?0:r,!bi(I),bi(I)?0:I,co(c));return l===0?void 0:jZ.__wrap(l)}finally{$n[Jg++]=void 0}}castRayAndGetNormal(A,t,i,n,g,o,s,a,r,I,c){try{XA(A,eo),XA(t,Do),XA(i,Ee),XA(n,Ee);const l=V.rawquerypipeline_castRayAndGetNormal(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o,s,bi(a)?4294967297:a>>>0,!bi(r),bi(r)?0:r,!bi(I),bi(I)?0:I,co(c));return l===0?void 0:Bx.__wrap(l)}finally{$n[Jg++]=void 0}}intersectionsWithRay(A,t,i,n,g,o,s,a,r,I,c,l){try{XA(A,eo),XA(t,Do),XA(i,Ee),XA(n,Ee),V.rawquerypipeline_intersectionsWithRay(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o,co(s),a,bi(r)?4294967297:r>>>0,!bi(I),bi(I)?0:I,!bi(c),bi(c)?0:c,co(l))}finally{$n[Jg++]=void 0,$n[Jg++]=void 0}}intersectionWithShape(A,t,i,n,g,o,s,a,r,I){try{const B=V.__wbindgen_add_to_stack_pointer(-16);XA(A,eo),XA(t,Do),XA(i,Ee),XA(n,wn),XA(g,ki),V.rawquerypipeline_intersectionWithShape(B,this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,o,bi(s)?4294967297:s>>>0,!bi(a),bi(a)?0:a,!bi(r),bi(r)?0:r,co(I));var c=Aa().getInt32(B+0,!0),l=Aa().getFloat64(B+8,!0);return c===0?void 0:l}finally{V.__wbindgen_add_to_stack_pointer(16),$n[Jg++]=void 0}}projectPoint(A,t,i,n,g,o,s,a,r){try{XA(A,eo),XA(t,Do),XA(i,Ee);const I=V.rawquerypipeline_projectPoint(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n,g,bi(o)?4294967297:o>>>0,!bi(s),bi(s)?0:s,!bi(a),bi(a)?0:a,co(r));return I===0?void 0:f_.__wrap(I)}finally{$n[Jg++]=void 0}}projectPointAndGetFeature(A,t,i,n,g,o,s,a){try{XA(A,eo),XA(t,Do),XA(i,Ee);const r=V.rawquerypipeline_projectPointAndGetFeature(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n,bi(g)?4294967297:g>>>0,!bi(o),bi(o)?0:o,!bi(s),bi(s)?0:s,co(a));return r===0?void 0:f_.__wrap(r)}finally{$n[Jg++]=void 0}}intersectionsWithPoint(A,t,i,n,g,o,s,a,r){try{XA(A,eo),XA(t,Do),XA(i,Ee),V.rawquerypipeline_intersectionsWithPoint(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,co(n),g,bi(o)?4294967297:o>>>0,!bi(s),bi(s)?0:s,!bi(a),bi(a)?0:a,co(r))}finally{$n[Jg++]=void 0,$n[Jg++]=void 0}}castShape(A,t,i,n,g,o,s,a,r,I,c,l,B,Q){try{XA(A,eo),XA(t,Do),XA(i,Ee),XA(n,wn),XA(g,Ee),XA(o,ki);const h=V.rawquerypipeline_castShape(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,o.__wbg_ptr,s,a,r,I,bi(c)?4294967297:c>>>0,!bi(l),bi(l)?0:l,!bi(B),bi(B)?0:B,co(Q));return h===0?void 0:cx.__wrap(h)}finally{$n[Jg++]=void 0}}intersectionsWithShape(A,t,i,n,g,o,s,a,r,I,c){try{XA(A,eo),XA(t,Do),XA(i,Ee),XA(n,wn),XA(g,ki),V.rawquerypipeline_intersectionsWithShape(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,co(o),s,bi(a)?4294967297:a>>>0,!bi(r),bi(r)?0:r,!bi(I),bi(I)?0:I,co(c))}finally{$n[Jg++]=void 0,$n[Jg++]=void 0}}collidersWithAabbIntersectingAabb(A,t,i){try{XA(A,Ee),XA(t,Ee),V.rawquerypipeline_collidersWithAabbIntersectingAabb(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,co(i))}finally{$n[Jg++]=void 0}}}const yiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawraycolliderhit_free(e>>>0,1));class jZ{static __wrap(A){A>>>=0;const t=Object.create(jZ.prototype);return t.__wbg_ptr=A,yiA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,yiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawraycolliderhit_free(A,0)}colliderHandle(){return V.rawcharactercollision_handle(this.__wbg_ptr)}timeOfImpact(){return V.rawcollidershapecasthit_time_of_impact(this.__wbg_ptr)}}const DiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawraycolliderintersection_free(e>>>0,1));class Bx{static __wrap(A){A>>>=0;const t=Object.create(Bx.prototype);return t.__wbg_ptr=A,DiA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,DiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawraycolliderintersection_free(A,0)}colliderHandle(){return V.rawpointcolliderprojection_colliderHandle(this.__wbg_ptr)}normal(){const A=V.rawcollidershapecasthit_witness1(this.__wbg_ptr);return Ee.__wrap(A)}time_of_impact(){return V.rawcollidershapecasthit_time_of_impact(this.__wbg_ptr)}featureType(){return V.rawpointcolliderprojection_featureType(this.__wbg_ptr)}featureId(){const A=V.rawpointcolliderprojection_featureId(this.__wbg_ptr);return A===4294967297?void 0:A}}const miA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawrayintersection_free(e>>>0,1));class Ex{static __wrap(A){A>>>=0;const t=Object.create(Ex.prototype);return t.__wbg_ptr=A,miA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,miA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawrayintersection_free(A,0)}normal(){const A=V.rawcollidershapecasthit_witness1(this.__wbg_ptr);return Ee.__wrap(A)}time_of_impact(){return V.rawcollidershapecasthit_time_of_impact(this.__wbg_ptr)}featureType(){return V.rawpointcolliderprojection_featureType(this.__wbg_ptr)}featureId(){const A=V.rawpointcolliderprojection_featureId(this.__wbg_ptr);return A===4294967297?void 0:A}}const WY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawrigidbodyset_free(e>>>0,1));class eo{static __wrap(A){A>>>=0;const t=Object.create(eo.prototype);return t.__wbg_ptr=A,WY.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,WY.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawrigidbodyset_free(A,0)}rbTranslation(A){const t=V.rawrigidbodyset_rbTranslation(this.__wbg_ptr,A);return Ee.__wrap(t)}rbRotation(A){const t=V.rawrigidbodyset_rbRotation(this.__wbg_ptr,A);return wn.__wrap(t)}rbSleep(A){V.rawrigidbodyset_rbSleep(this.__wbg_ptr,A)}rbIsSleeping(A){return V.rawrigidbodyset_rbIsSleeping(this.__wbg_ptr,A)!==0}rbIsMoving(A){return V.rawrigidbodyset_rbIsMoving(this.__wbg_ptr,A)!==0}rbNextTranslation(A){const t=V.rawrigidbodyset_rbNextTranslation(this.__wbg_ptr,A);return Ee.__wrap(t)}rbNextRotation(A){const t=V.rawrigidbodyset_rbNextRotation(this.__wbg_ptr,A);return wn.__wrap(t)}rbSetTranslation(A,t,i,n,g){V.rawrigidbodyset_rbSetTranslation(this.__wbg_ptr,A,t,i,n,g)}rbSetRotation(A,t,i,n,g,o){V.rawrigidbodyset_rbSetRotation(this.__wbg_ptr,A,t,i,n,g,o)}rbSetLinvel(A,t,i){XA(t,Ee),V.rawrigidbodyset_rbSetLinvel(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbSetAngvel(A,t,i){XA(t,Ee),V.rawrigidbodyset_rbSetAngvel(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbSetNextKinematicTranslation(A,t,i,n){V.rawrigidbodyset_rbSetNextKinematicTranslation(this.__wbg_ptr,A,t,i,n)}rbSetNextKinematicRotation(A,t,i,n,g){V.rawrigidbodyset_rbSetNextKinematicRotation(this.__wbg_ptr,A,t,i,n,g)}rbRecomputeMassPropertiesFromColliders(A,t){XA(t,Do),V.rawrigidbodyset_rbRecomputeMassPropertiesFromColliders(this.__wbg_ptr,A,t.__wbg_ptr)}rbSetAdditionalMass(A,t,i){V.rawrigidbodyset_rbSetAdditionalMass(this.__wbg_ptr,A,t,i)}rbSetAdditionalMassProperties(A,t,i,n,g,o){XA(i,Ee),XA(n,Ee),XA(g,wn),V.rawrigidbodyset_rbSetAdditionalMassProperties(this.__wbg_ptr,A,t,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,o)}rbLinvel(A){const t=V.rawrigidbodyset_rbLinvel(this.__wbg_ptr,A);return Ee.__wrap(t)}rbAngvel(A){const t=V.rawrigidbodyset_rbAngvel(this.__wbg_ptr,A);return Ee.__wrap(t)}rbLockTranslations(A,t,i){V.rawrigidbodyset_rbLockTranslations(this.__wbg_ptr,A,t,i)}rbSetEnabledTranslations(A,t,i,n,g){V.rawrigidbodyset_rbSetEnabledTranslations(this.__wbg_ptr,A,t,i,n,g)}rbLockRotations(A,t,i){V.rawrigidbodyset_rbLockRotations(this.__wbg_ptr,A,t,i)}rbSetEnabledRotations(A,t,i,n,g){V.rawrigidbodyset_rbSetEnabledRotations(this.__wbg_ptr,A,t,i,n,g)}rbDominanceGroup(A){return V.rawrigidbodyset_rbDominanceGroup(this.__wbg_ptr,A)}rbSetDominanceGroup(A,t){V.rawrigidbodyset_rbSetDominanceGroup(this.__wbg_ptr,A,t)}rbEnableCcd(A,t){V.rawrigidbodyset_rbEnableCcd(this.__wbg_ptr,A,t)}rbSetSoftCcdPrediction(A,t){V.rawrigidbodyset_rbSetSoftCcdPrediction(this.__wbg_ptr,A,t)}rbMass(A){return V.rawrigidbodyset_rbMass(this.__wbg_ptr,A)}rbInvMass(A){return V.rawrigidbodyset_rbInvMass(this.__wbg_ptr,A)}rbEffectiveInvMass(A){const t=V.rawrigidbodyset_rbEffectiveInvMass(this.__wbg_ptr,A);return Ee.__wrap(t)}rbLocalCom(A){const t=V.rawrigidbodyset_rbLocalCom(this.__wbg_ptr,A);return Ee.__wrap(t)}rbWorldCom(A){const t=V.rawrigidbodyset_rbWorldCom(this.__wbg_ptr,A);return Ee.__wrap(t)}rbInvPrincipalInertiaSqrt(A){const t=V.rawrigidbodyset_rbInvPrincipalInertiaSqrt(this.__wbg_ptr,A);return Ee.__wrap(t)}rbPrincipalInertiaLocalFrame(A){const t=V.rawrigidbodyset_rbPrincipalInertiaLocalFrame(this.__wbg_ptr,A);return wn.__wrap(t)}rbPrincipalInertia(A){const t=V.rawrigidbodyset_rbPrincipalInertia(this.__wbg_ptr,A);return Ee.__wrap(t)}rbEffectiveWorldInvInertiaSqrt(A){const t=V.rawrigidbodyset_rbEffectiveWorldInvInertiaSqrt(this.__wbg_ptr,A);return y_.__wrap(t)}rbEffectiveAngularInertia(A){const t=V.rawrigidbodyset_rbEffectiveAngularInertia(this.__wbg_ptr,A);return y_.__wrap(t)}rbWakeUp(A){V.rawrigidbodyset_rbWakeUp(this.__wbg_ptr,A)}rbIsCcdEnabled(A){return V.rawrigidbodyset_rbIsCcdEnabled(this.__wbg_ptr,A)!==0}rbSoftCcdPrediction(A){return V.rawrigidbodyset_rbSoftCcdPrediction(this.__wbg_ptr,A)}rbNumColliders(A){return V.rawrigidbodyset_rbNumColliders(this.__wbg_ptr,A)>>>0}rbCollider(A,t){return V.rawrigidbodyset_rbCollider(this.__wbg_ptr,A,t)}rbBodyType(A){return V.rawrigidbodyset_rbBodyType(this.__wbg_ptr,A)}rbSetBodyType(A,t,i){V.rawrigidbodyset_rbSetBodyType(this.__wbg_ptr,A,t,i)}rbIsFixed(A){return V.rawrigidbodyset_rbIsFixed(this.__wbg_ptr,A)!==0}rbIsKinematic(A){return V.rawrigidbodyset_rbIsKinematic(this.__wbg_ptr,A)!==0}rbIsDynamic(A){return V.rawrigidbodyset_rbIsDynamic(this.__wbg_ptr,A)!==0}rbLinearDamping(A){return V.rawrigidbodyset_rbLinearDamping(this.__wbg_ptr,A)}rbAngularDamping(A){return V.rawrigidbodyset_rbAngularDamping(this.__wbg_ptr,A)}rbSetLinearDamping(A,t){V.rawrigidbodyset_rbSetLinearDamping(this.__wbg_ptr,A,t)}rbSetAngularDamping(A,t){V.rawrigidbodyset_rbSetAngularDamping(this.__wbg_ptr,A,t)}rbSetEnabled(A,t){V.rawrigidbodyset_rbSetEnabled(this.__wbg_ptr,A,t)}rbIsEnabled(A){return V.rawrigidbodyset_rbIsEnabled(this.__wbg_ptr,A)!==0}rbGravityScale(A){return V.rawrigidbodyset_rbGravityScale(this.__wbg_ptr,A)}rbSetGravityScale(A,t,i){V.rawrigidbodyset_rbSetGravityScale(this.__wbg_ptr,A,t,i)}rbResetForces(A,t){V.rawrigidbodyset_rbResetForces(this.__wbg_ptr,A,t)}rbResetTorques(A,t){V.rawrigidbodyset_rbResetTorques(this.__wbg_ptr,A,t)}rbAddForce(A,t,i){XA(t,Ee),V.rawrigidbodyset_rbAddForce(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbApplyImpulse(A,t,i){XA(t,Ee),V.rawrigidbodyset_rbApplyImpulse(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbAddTorque(A,t,i){XA(t,Ee),V.rawrigidbodyset_rbAddTorque(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbApplyTorqueImpulse(A,t,i){XA(t,Ee),V.rawrigidbodyset_rbApplyTorqueImpulse(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbAddForceAtPoint(A,t,i,n){XA(t,Ee),XA(i,Ee),V.rawrigidbodyset_rbAddForceAtPoint(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n)}rbApplyImpulseAtPoint(A,t,i,n){XA(t,Ee),XA(i,Ee),V.rawrigidbodyset_rbApplyImpulseAtPoint(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n)}rbAdditionalSolverIterations(A){return V.rawrigidbodyset_rbAdditionalSolverIterations(this.__wbg_ptr,A)>>>0}rbSetAdditionalSolverIterations(A,t){V.rawrigidbodyset_rbSetAdditionalSolverIterations(this.__wbg_ptr,A,t)}rbUserData(A){return V.rawrigidbodyset_rbUserData(this.__wbg_ptr,A)>>>0}rbSetUserData(A,t){V.rawrigidbodyset_rbSetUserData(this.__wbg_ptr,A,t)}rbUserForce(A){const t=V.rawrigidbodyset_rbUserForce(this.__wbg_ptr,A);return Ee.__wrap(t)}rbUserTorque(A){const t=V.rawrigidbodyset_rbUserTorque(this.__wbg_ptr,A);return Ee.__wrap(t)}constructor(){const A=V.rawrigidbodyset_new();return this.__wbg_ptr=A>>>0,WY.register(this,this.__wbg_ptr,this),this}createRigidBody(A,t,i,n,g,o,s,a,r,I,c,l,B,Q,h,d,p,y,m,D,S,k,N,G,M,w){return XA(t,Ee),XA(i,wn),XA(s,Ee),XA(a,Ee),XA(r,Ee),XA(I,Ee),XA(c,wn),V.rawrigidbodyset_createRigidBody(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n,g,o,s.__wbg_ptr,a.__wbg_ptr,r.__wbg_ptr,I.__wbg_ptr,c.__wbg_ptr,l,B,Q,h,d,p,y,m,D,S,k,N,G,M,w)}remove(A,t,i,n,g){XA(t,oQ),XA(i,Do),XA(n,gQ),XA(g,sQ),V.rawrigidbodyset_remove(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr)}len(){return V.rawcolliderset_len(this.__wbg_ptr)>>>0}contains(A){return V.rawrigidbodyset_contains(this.__wbg_ptr,A)!==0}forEachRigidBodyHandle(A){try{V.rawrigidbodyset_forEachRigidBodyHandle(this.__wbg_ptr,co(A))}finally{$n[Jg++]=void 0}}propagateModifiedBodyPositionsToColliders(A){XA(A,Do),V.rawrigidbodyset_propagateModifiedBodyPositionsToColliders(this.__wbg_ptr,A.__wbg_ptr)}}const VY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawrotation_free(e>>>0,1));class wn{static __wrap(A){A>>>=0;const t=Object.create(wn.prototype);return t.__wbg_ptr=A,VY.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,VY.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawrotation_free(A,0)}constructor(A,t,i,n){const g=V.rawrotation_new(A,t,i,n);return this.__wbg_ptr=g>>>0,VY.register(this,this.__wbg_ptr,this),this}static identity(){const A=V.rawrotation_identity();return wn.__wrap(A)}get x(){return V.rawrotation_x(this.__wbg_ptr)}get y(){return V.rawintegrationparameters_dt(this.__wbg_ptr)}get z(){return V.rawcollidershapecasthit_time_of_impact(this.__wbg_ptr)}get w(){return V.rawrotation_w(this.__wbg_ptr)}}const SiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawsdpmatrix3_free(e>>>0,1));class y_{static __wrap(A){A>>>=0;const t=Object.create(y_.prototype);return t.__wbg_ptr=A,SiA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,SiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawsdpmatrix3_free(A,0)}elements(){return DN(V.rawsdpmatrix3_elements(this.__wbg_ptr))}}const wiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawserializationpipeline_free(e>>>0,1));class pse{__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,wiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawserializationpipeline_free(A,0)}constructor(){const A=V.rawserializationpipeline_new();return this.__wbg_ptr=A>>>0,wiA.register(this,this.__wbg_ptr,this),this}serializeAll(A,t,i,n,g,o,s,a,r){return XA(A,Ee),XA(t,uf),XA(i,oQ),XA(n,Qf),XA(g,Qd),XA(o,eo),XA(s,Do),XA(a,gQ),XA(r,sQ),DN(V.rawserializationpipeline_serializeAll(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,o.__wbg_ptr,s.__wbg_ptr,a.__wbg_ptr,r.__wbg_ptr))}deserializeAll(A){const t=V.rawserializationpipeline_deserializeAll(this.__wbg_ptr,Is(A));return t===0?void 0:Ese.__wrap(t)}}const kiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawshape_free(e>>>0,1));class ki{static __wrap(A){A>>>=0;const t=Object.create(ki.prototype);return t.__wbg_ptr=A,kiA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,kiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawshape_free(A,0)}static cuboid(A,t,i){const n=V.rawshape_cuboid(A,t,i);return ki.__wrap(n)}static roundCuboid(A,t,i,n){const g=V.rawshape_roundCuboid(A,t,i,n);return ki.__wrap(g)}static ball(A){const t=V.rawshape_ball(A);return ki.__wrap(t)}static halfspace(A){XA(A,Ee);const t=V.rawshape_halfspace(A.__wbg_ptr);return ki.__wrap(t)}static capsule(A,t){const i=V.rawshape_capsule(A,t);return ki.__wrap(i)}static cylinder(A,t){const i=V.rawshape_cylinder(A,t);return ki.__wrap(i)}static roundCylinder(A,t,i){const n=V.rawshape_roundCylinder(A,t,i);return ki.__wrap(n)}static cone(A,t){const i=V.rawshape_cone(A,t);return ki.__wrap(i)}static roundCone(A,t,i){const n=V.rawshape_roundCone(A,t,i);return ki.__wrap(n)}static polyline(A,t){const i=dh(A,V.__wbindgen_export_2),n=_I,g=gU(t,V.__wbindgen_export_2),o=_I,s=V.rawshape_polyline(i,n,g,o);return ki.__wrap(s)}static trimesh(A,t,i){const n=dh(A,V.__wbindgen_export_2),g=_I,o=gU(t,V.__wbindgen_export_2),s=_I,a=V.rawshape_trimesh(n,g,o,s,i);return a===0?void 0:ki.__wrap(a)}static heightfield(A,t,i,n,g){const o=dh(i,V.__wbindgen_export_2),s=_I;XA(n,Ee);const a=V.rawshape_heightfield(A,t,o,s,n.__wbg_ptr,g);return ki.__wrap(a)}static segment(A,t){XA(A,Ee),XA(t,Ee);const i=V.rawshape_segment(A.__wbg_ptr,t.__wbg_ptr);return ki.__wrap(i)}static triangle(A,t,i){XA(A,Ee),XA(t,Ee),XA(i,Ee);const n=V.rawshape_triangle(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr);return ki.__wrap(n)}static roundTriangle(A,t,i,n){XA(A,Ee),XA(t,Ee),XA(i,Ee);const g=V.rawshape_roundTriangle(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n);return ki.__wrap(g)}static convexHull(A){const t=dh(A,V.__wbindgen_export_2),i=_I,n=V.rawshape_convexHull(t,i);return n===0?void 0:ki.__wrap(n)}static roundConvexHull(A,t){const i=dh(A,V.__wbindgen_export_2),n=_I,g=V.rawshape_roundConvexHull(i,n,t);return g===0?void 0:ki.__wrap(g)}static convexMesh(A,t){const i=dh(A,V.__wbindgen_export_2),n=_I,g=gU(t,V.__wbindgen_export_2),o=_I,s=V.rawshape_convexMesh(i,n,g,o);return s===0?void 0:ki.__wrap(s)}static roundConvexMesh(A,t,i){const n=dh(A,V.__wbindgen_export_2),g=_I,o=gU(t,V.__wbindgen_export_2),s=_I,a=V.rawshape_roundConvexMesh(n,g,o,s,i);return a===0?void 0:ki.__wrap(a)}castShape(A,t,i,n,g,o,s,a,r,I){XA(A,Ee),XA(t,wn),XA(i,Ee),XA(n,ki),XA(g,Ee),XA(o,wn),XA(s,Ee);const c=V.rawshape_castShape(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,o.__wbg_ptr,s.__wbg_ptr,a,r,I);return c===0?void 0:Qx.__wrap(c)}intersectsShape(A,t,i,n,g){return XA(A,Ee),XA(t,wn),XA(i,ki),XA(n,Ee),XA(g,wn),V.rawshape_intersectsShape(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr)!==0}contactShape(A,t,i,n,g,o){XA(A,Ee),XA(t,wn),XA(i,ki),XA(n,Ee),XA(g,wn);const s=V.rawshape_contactShape(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,o);return s===0?void 0:mN.__wrap(s)}containsPoint(A,t,i){return XA(A,Ee),XA(t,wn),XA(i,Ee),V.rawshape_containsPoint(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr)!==0}projectPoint(A,t,i,n){XA(A,Ee),XA(t,wn),XA(i,Ee);const g=V.rawshape_projectPoint(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n);return lx.__wrap(g)}intersectsRay(A,t,i,n,g){return XA(A,Ee),XA(t,wn),XA(i,Ee),XA(n,Ee),V.rawshape_intersectsRay(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g)!==0}castRay(A,t,i,n,g,o){return XA(A,Ee),XA(t,wn),XA(i,Ee),XA(n,Ee),V.rawshape_castRay(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o)}castRayAndGetNormal(A,t,i,n,g,o){XA(A,Ee),XA(t,wn),XA(i,Ee),XA(n,Ee);const s=V.rawshape_castRayAndGetNormal(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o);return s===0?void 0:Ex.__wrap(s)}}const MiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawshapecasthit_free(e>>>0,1));class Qx{static __wrap(A){A>>>=0;const t=Object.create(Qx.prototype);return t.__wbg_ptr=A,MiA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,MiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawshapecasthit_free(A,0)}time_of_impact(){return V.rawrotation_x(this.__wbg_ptr)}witness1(){const A=V.rawshapecasthit_witness1(this.__wbg_ptr);return Ee.__wrap(A)}witness2(){const A=V.rawcontactforceevent_total_force(this.__wbg_ptr);return Ee.__wrap(A)}normal1(){const A=V.rawshapecasthit_normal1(this.__wbg_ptr);return Ee.__wrap(A)}normal2(){const A=V.rawshapecasthit_normal2(this.__wbg_ptr);return Ee.__wrap(A)}}const NiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawshapecontact_free(e>>>0,1));class mN{static __wrap(A){A>>>=0;const t=Object.create(mN.prototype);return t.__wbg_ptr=A,NiA.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,NiA.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawshapecontact_free(A,0)}distance(){return V.rawkinematiccharactercontroller_maxSlopeClimbAngle(this.__wbg_ptr)}point1(){const A=V.rawpointprojection_point(this.__wbg_ptr);return Ee.__wrap(A)}point2(){const A=V.rawcollidershapecasthit_witness1(this.__wbg_ptr);return Ee.__wrap(A)}normal1(){const A=V.rawcollidershapecasthit_witness2(this.__wbg_ptr);return Ee.__wrap(A)}normal2(){const A=V.rawcharactercollision_translationDeltaApplied(this.__wbg_ptr);return Ee.__wrap(A)}}const XY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawvector_free(e>>>0,1));class Ee{static __wrap(A){A>>>=0;const t=Object.create(Ee.prototype);return t.__wbg_ptr=A,XY.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,XY.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawvector_free(A,0)}static zero(){const A=V.rawvector_zero();return Ee.__wrap(A)}constructor(A,t,i){const n=V.rawvector_new(A,t,i);return this.__wbg_ptr=n>>>0,XY.register(this,this.__wbg_ptr,this),this}get x(){return V.rawrotation_x(this.__wbg_ptr)}set x(A){V.rawvector_set_x(this.__wbg_ptr,A)}get y(){return V.rawintegrationparameters_dt(this.__wbg_ptr)}set y(A){V.rawintegrationparameters_set_dt(this.__wbg_ptr,A)}get z(){return V.rawcollidershapecasthit_time_of_impact(this.__wbg_ptr)}set z(A){V.rawvector_set_z(this.__wbg_ptr,A)}xyz(){const A=V.rawvector_xyz(this.__wbg_ptr);return Ee.__wrap(A)}yxz(){const A=V.rawvector_yxz(this.__wbg_ptr);return Ee.__wrap(A)}zxy(){const A=V.rawvector_zxy(this.__wbg_ptr);return Ee.__wrap(A)}xzy(){const A=V.rawvector_xzy(this.__wbg_ptr);return Ee.__wrap(A)}yzx(){const A=V.rawvector_yzx(this.__wbg_ptr);return Ee.__wrap(A)}zyx(){const A=V.rawvector_zyx(this.__wbg_ptr);return Ee.__wrap(A)}}async function rfA(e){if(V!==void 0)return V;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL("rapier_wasm3d_bg.wasm","<deleted>"));const A=function(){const n={wbg:{}};return n.wbg.__wbg_bind_c8359b1cba058168=function(g,o,s,a){return Is(ug(g).bind(ug(o),ug(s),ug(a)))},n.wbg.__wbg_buffer_609cc3eee51ed158=function(g){return Is(ug(g).buffer)},n.wbg.__wbg_call_7cccdd69e0791ae2=function(){return qY(function(g,o,s){return Is(ug(g).call(ug(o),ug(s)))},arguments)},n.wbg.__wbg_call_833bed5770ea2041=function(){return qY(function(g,o,s,a){return Is(ug(g).call(ug(o),ug(s),ug(a)))},arguments)},n.wbg.__wbg_call_b8adc8b1d0a0d8eb=function(){return qY(function(g,o,s,a,r){return Is(ug(g).call(ug(o),ug(s),ug(a),ug(r)))},arguments)},n.wbg.__wbg_length_3b4f022188ae8db6=function(g){return ug(g).length},n.wbg.__wbg_length_a446193dc22c12f8=function(g){return ug(g).length},n.wbg.__wbg_new_a12002a7f91c75be=function(g){return Is(new Uint8Array(ug(g)))},n.wbg.__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a=function(g,o,s){return Is(new Uint8Array(ug(g),o>>>0,s>>>0))},n.wbg.__wbg_newwithbyteoffsetandlength_e6b7e69acd4c7354=function(g,o,s){return Is(new Float32Array(ug(g),o>>>0,s>>>0))},n.wbg.__wbg_newwithlength_5a5efe313cfd59f1=function(g){return Is(new Float32Array(g>>>0))},n.wbg.__wbg_rawcontactforceevent_new=function(g){return Is(OZ.__wrap(g))},n.wbg.__wbg_rawraycolliderintersection_new=function(g){return Is(Bx.__wrap(g))},n.wbg.__wbg_set_10bad9bee0e9c58b=function(g,o,s){ug(g).set(ug(o),s>>>0)},n.wbg.__wbg_set_65595bdd868b3009=function(g,o,s){ug(g).set(ug(o),s>>>0)},n.wbg.__wbindgen_boolean_get=function(g){const o=ug(g);return typeof o=="boolean"?o?1:0:2},n.wbg.__wbindgen_is_function=function(g){return typeof ug(g)=="function"},n.wbg.__wbindgen_memory=function(){return Is(V.memory)},n.wbg.__wbindgen_number_get=function(g,o){const s=ug(o),a=typeof s=="number"?s:void 0;Aa().setFloat64(g+8,bi(a)?0:a,!0),Aa().setInt32(g+0,!bi(a),!0)},n.wbg.__wbindgen_number_new=function(g){return Is(g)},n.wbg.__wbindgen_object_drop_ref=function(g){DN(g)},n.wbg.__wbindgen_throw=function(g,o){throw new Error(efA(g,o))},n}();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:t,module:i}=await async function(n,g){if(typeof Response=="function"&&n instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(n,g)}catch(s){if(n.headers.get("Content-Type")=="application/wasm")throw s;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",s)}const o=await n.arrayBuffer();return await WebAssembly.instantiate(o,g)}{const o=await WebAssembly.instantiate(n,g);return o instanceof WebAssembly.Instance?{instance:o,module:n}:o}}(await e,A);return function(n,g){return V=n.exports,rfA.__wbindgen_wasm_module=g,Vh=null,kk=null,Mk=null,wk=null,V}(t,i)}class Pm{constructor(A,t,i){this.x=A,this.y=t,this.z=i}}class ce{static new(A,t,i){return new Pm(A,t,i)}static intoRaw(A){return new Ee(A.x,A.y,A.z)}static zeros(){return ce.new(0,0,0)}static fromRaw(A){if(!A)return null;let t=ce.new(A.x,A.y,A.z);return A.free(),t}static copy(A,t){A.x=t.x,A.y=t.y,A.z=t.z}}class D_{constructor(A,t,i,n){this.x=A,this.y=t,this.z=i,this.w=n}}class en{static identity(){return new D_(0,0,0,1)}static fromRaw(A){if(!A)return null;let t=new D_(A.x,A.y,A.z,A.w);return A.free(),t}static intoRaw(A){return new wn(A.x,A.y,A.z,A.w)}static copy(A,t){A.x=t.x,A.y=t.y,A.z=t.z,A.w=t.w}}class zZ{constructor(A){this.elements=A}get m11(){return this.elements[0]}get m12(){return this.elements[1]}get m21(){return this.m12}get m13(){return this.elements[2]}get m31(){return this.m13}get m22(){return this.elements[3]}get m23(){return this.elements[4]}get m32(){return this.m23}get m33(){return this.elements[5]}}class m_{static fromRaw(A){const t=new zZ(A.elements());return A.free(),t}}var xC,$s,S_,w_,_S,df,ns,k_,M_,N_,R_,ME,SN,G_,wN,Mu;(function(e){e[e.Dynamic=0]="Dynamic",e[e.Fixed=1]="Fixed",e[e.KinematicPositionBased=2]="KinematicPositionBased",e[e.KinematicVelocityBased=3]="KinematicVelocityBased"})(xC||(xC={}));class b_{constructor(A,t,i){this.rawSet=A,this.colliderSet=t,this.handle=i}finalizeDeserialization(A){this.colliderSet=A}isValid(){return this.rawSet.contains(this.handle)}lockTranslations(A,t){return this.rawSet.rbLockTranslations(this.handle,A,t)}lockRotations(A,t){return this.rawSet.rbLockRotations(this.handle,A,t)}setEnabledTranslations(A,t,i,n){return this.rawSet.rbSetEnabledTranslations(this.handle,A,t,i,n)}restrictTranslations(A,t,i,n){this.setEnabledTranslations(A,t,i,n)}setEnabledRotations(A,t,i,n){return this.rawSet.rbSetEnabledRotations(this.handle,A,t,i,n)}restrictRotations(A,t,i,n){this.setEnabledRotations(A,t,i,n)}dominanceGroup(){return this.rawSet.rbDominanceGroup(this.handle)}setDominanceGroup(A){this.rawSet.rbSetDominanceGroup(this.handle,A)}additionalSolverIterations(){return this.rawSet.rbAdditionalSolverIterations(this.handle)}setAdditionalSolverIterations(A){this.rawSet.rbSetAdditionalSolverIterations(this.handle,A)}enableCcd(A){this.rawSet.rbEnableCcd(this.handle,A)}setSoftCcdPrediction(A){this.rawSet.rbSetSoftCcdPrediction(this.handle,A)}softCcdPrediction(){return this.rawSet.rbSoftCcdPrediction(this.handle)}translation(){let A=this.rawSet.rbTranslation(this.handle);return ce.fromRaw(A)}rotation(){let A=this.rawSet.rbRotation(this.handle);return en.fromRaw(A)}nextTranslation(){let A=this.rawSet.rbNextTranslation(this.handle);return ce.fromRaw(A)}nextRotation(){let A=this.rawSet.rbNextRotation(this.handle);return en.fromRaw(A)}setTranslation(A,t){this.rawSet.rbSetTranslation(this.handle,A.x,A.y,A.z,t)}setLinvel(A,t){let i=ce.intoRaw(A);this.rawSet.rbSetLinvel(this.handle,i,t),i.free()}gravityScale(){return this.rawSet.rbGravityScale(this.handle)}setGravityScale(A,t){this.rawSet.rbSetGravityScale(this.handle,A,t)}setRotation(A,t){this.rawSet.rbSetRotation(this.handle,A.x,A.y,A.z,A.w,t)}setAngvel(A,t){let i=ce.intoRaw(A);this.rawSet.rbSetAngvel(this.handle,i,t),i.free()}setNextKinematicTranslation(A){this.rawSet.rbSetNextKinematicTranslation(this.handle,A.x,A.y,A.z)}setNextKinematicRotation(A){this.rawSet.rbSetNextKinematicRotation(this.handle,A.x,A.y,A.z,A.w)}linvel(){return ce.fromRaw(this.rawSet.rbLinvel(this.handle))}angvel(){return ce.fromRaw(this.rawSet.rbAngvel(this.handle))}mass(){return this.rawSet.rbMass(this.handle)}effectiveInvMass(){return ce.fromRaw(this.rawSet.rbEffectiveInvMass(this.handle))}invMass(){return this.rawSet.rbInvMass(this.handle)}localCom(){return ce.fromRaw(this.rawSet.rbLocalCom(this.handle))}worldCom(){return ce.fromRaw(this.rawSet.rbWorldCom(this.handle))}invPrincipalInertiaSqrt(){return ce.fromRaw(this.rawSet.rbInvPrincipalInertiaSqrt(this.handle))}principalInertia(){return ce.fromRaw(this.rawSet.rbPrincipalInertia(this.handle))}principalInertiaLocalFrame(){return en.fromRaw(this.rawSet.rbPrincipalInertiaLocalFrame(this.handle))}effectiveWorldInvInertiaSqrt(){return m_.fromRaw(this.rawSet.rbEffectiveWorldInvInertiaSqrt(this.handle))}effectiveAngularInertia(){return m_.fromRaw(this.rawSet.rbEffectiveAngularInertia(this.handle))}sleep(){this.rawSet.rbSleep(this.handle)}wakeUp(){this.rawSet.rbWakeUp(this.handle)}isCcdEnabled(){return this.rawSet.rbIsCcdEnabled(this.handle)}numColliders(){return this.rawSet.rbNumColliders(this.handle)}collider(A){return this.colliderSet.get(this.rawSet.rbCollider(this.handle,A))}setEnabled(A){this.rawSet.rbSetEnabled(this.handle,A)}isEnabled(){return this.rawSet.rbIsEnabled(this.handle)}bodyType(){return this.rawSet.rbBodyType(this.handle)}setBodyType(A,t){return this.rawSet.rbSetBodyType(this.handle,A,t)}isSleeping(){return this.rawSet.rbIsSleeping(this.handle)}isMoving(){return this.rawSet.rbIsMoving(this.handle)}isFixed(){return this.rawSet.rbIsFixed(this.handle)}isKinematic(){return this.rawSet.rbIsKinematic(this.handle)}isDynamic(){return this.rawSet.rbIsDynamic(this.handle)}linearDamping(){return this.rawSet.rbLinearDamping(this.handle)}angularDamping(){return this.rawSet.rbAngularDamping(this.handle)}setLinearDamping(A){this.rawSet.rbSetLinearDamping(this.handle,A)}recomputeMassPropertiesFromColliders(){this.rawSet.rbRecomputeMassPropertiesFromColliders(this.handle,this.colliderSet.raw)}setAdditionalMass(A,t){this.rawSet.rbSetAdditionalMass(this.handle,A,t)}setAdditionalMassProperties(A,t,i,n,g){let o=ce.intoRaw(t),s=ce.intoRaw(i),a=en.intoRaw(n);this.rawSet.rbSetAdditionalMassProperties(this.handle,A,o,s,a,g),o.free(),s.free(),a.free()}setAngularDamping(A){this.rawSet.rbSetAngularDamping(this.handle,A)}resetForces(A){this.rawSet.rbResetForces(this.handle,A)}resetTorques(A){this.rawSet.rbResetTorques(this.handle,A)}addForce(A,t){const i=ce.intoRaw(A);this.rawSet.rbAddForce(this.handle,i,t),i.free()}applyImpulse(A,t){const i=ce.intoRaw(A);this.rawSet.rbApplyImpulse(this.handle,i,t),i.free()}addTorque(A,t){const i=ce.intoRaw(A);this.rawSet.rbAddTorque(this.handle,i,t),i.free()}applyTorqueImpulse(A,t){const i=ce.intoRaw(A);this.rawSet.rbApplyTorqueImpulse(this.handle,i,t),i.free()}addForceAtPoint(A,t,i){const n=ce.intoRaw(A),g=ce.intoRaw(t);this.rawSet.rbAddForceAtPoint(this.handle,n,g,i),n.free(),g.free()}applyImpulseAtPoint(A,t,i){const n=ce.intoRaw(A),g=ce.intoRaw(t);this.rawSet.rbApplyImpulseAtPoint(this.handle,n,g,i),n.free(),g.free()}userForce(){return ce.fromRaw(this.rawSet.rbUserForce(this.handle))}userTorque(){return ce.fromRaw(this.rawSet.rbUserTorque(this.handle))}}class TC{constructor(A){this.enabled=!0,this.status=A,this.translation=ce.zeros(),this.rotation=en.identity(),this.gravityScale=1,this.linvel=ce.zeros(),this.mass=0,this.massOnly=!1,this.centerOfMass=ce.zeros(),this.translationsEnabledX=!0,this.translationsEnabledY=!0,this.angvel=ce.zeros(),this.principalAngularInertia=ce.zeros(),this.angularInertiaLocalFrame=en.identity(),this.translationsEnabledZ=!0,this.rotationsEnabledX=!0,this.rotationsEnabledY=!0,this.rotationsEnabledZ=!0,this.linearDamping=0,this.angularDamping=0,this.canSleep=!0,this.sleeping=!1,this.ccdEnabled=!1,this.softCcdPrediction=0,this.dominanceGroup=0,this.additionalSolverIterations=0}static dynamic(){return new TC(xC.Dynamic)}static kinematicPositionBased(){return new TC(xC.KinematicPositionBased)}static kinematicVelocityBased(){return new TC(xC.KinematicVelocityBased)}static fixed(){return new TC(xC.Fixed)}static newDynamic(){return new TC(xC.Dynamic)}static newKinematicPositionBased(){return new TC(xC.KinematicPositionBased)}static newKinematicVelocityBased(){return new TC(xC.KinematicVelocityBased)}static newStatic(){return new TC(xC.Fixed)}setDominanceGroup(A){return this.dominanceGroup=A,this}setAdditionalSolverIterations(A){return this.additionalSolverIterations=A,this}setEnabled(A){return this.enabled=A,this}setTranslation(A,t,i){if(typeof A!="number"||typeof t!="number"||typeof i!="number")throw TypeError("The translation components must be numbers.");return this.translation={x:A,y:t,z:i},this}setRotation(A){return en.copy(this.rotation,A),this}setGravityScale(A){return this.gravityScale=A,this}setAdditionalMass(A){return this.mass=A,this.massOnly=!0,this}setLinvel(A,t,i){if(typeof A!="number"||typeof t!="number"||typeof i!="number")throw TypeError("The linvel components must be numbers.");return this.linvel={x:A,y:t,z:i},this}setAngvel(A){return ce.copy(this.angvel,A),this}setAdditionalMassProperties(A,t,i,n){return this.mass=A,ce.copy(this.centerOfMass,t),ce.copy(this.principalAngularInertia,i),en.copy(this.angularInertiaLocalFrame,n),this.massOnly=!1,this}enabledTranslations(A,t,i){return this.translationsEnabledX=A,this.translationsEnabledY=t,this.translationsEnabledZ=i,this}restrictTranslations(A,t,i){return this.enabledTranslations(A,t,i)}lockTranslations(){return this.enabledTranslations(!1,!1,!1)}enabledRotations(A,t,i){return this.rotationsEnabledX=A,this.rotationsEnabledY=t,this.rotationsEnabledZ=i,this}restrictRotations(A,t,i){return this.enabledRotations(A,t,i)}lockRotations(){return this.restrictRotations(!1,!1,!1)}setLinearDamping(A){return this.linearDamping=A,this}setAngularDamping(A){return this.angularDamping=A,this}setCanSleep(A){return this.canSleep=A,this}setSleeping(A){return this.sleeping=A,this}setCcdEnabled(A){return this.ccdEnabled=A,this}setSoftCcdPrediction(A){return this.softCcdPrediction=A,this}setUserData(A){return this.userData=A,this}}class ux{constructor(){this.fconv=new Float64Array(1),this.uconv=new Uint32Array(this.fconv.buffer),this.data=new Array,this.size=0}set(A,t){let i=this.index(A);for(;this.data.length<=i;)this.data.push(null);this.data[i]==null&&(this.size+=1),this.data[i]=t}len(){return this.size}delete(A){let t=this.index(A);t<this.data.length&&(this.data[t]!=null&&(this.size-=1),this.data[t]=null)}clear(){this.data=new Array}get(A){let t=this.index(A);return t<this.data.length?this.data[t]:null}forEach(A){for(const t of this.data)t!=null&&A(t)}getAll(){return this.data.filter(A=>A!=null)}index(A){return this.fconv[0]=A,this.uconv[0]}}class ZZ{constructor(A){this.raw=A||new eo,this.map=new ux,A&&A.forEachRigidBodyHandle(t=>{this.map.set(t,new b_(A,null,t))})}free(){this.raw&&this.raw.free(),this.raw=void 0,this.map&&this.map.clear(),this.map=void 0}finalizeDeserialization(A){this.map.forEach(t=>t.finalizeDeserialization(A))}createRigidBody(A,t){let i=ce.intoRaw(t.translation),n=en.intoRaw(t.rotation),g=ce.intoRaw(t.linvel),o=ce.intoRaw(t.centerOfMass),s=ce.intoRaw(t.angvel),a=ce.intoRaw(t.principalAngularInertia),r=en.intoRaw(t.angularInertiaLocalFrame),I=this.raw.createRigidBody(t.enabled,i,n,t.gravityScale,t.mass,t.massOnly,o,g,s,a,r,t.translationsEnabledX,t.translationsEnabledY,t.translationsEnabledZ,t.rotationsEnabledX,t.rotationsEnabledY,t.rotationsEnabledZ,t.linearDamping,t.angularDamping,t.status,t.canSleep,t.sleeping,t.softCcdPrediction,t.ccdEnabled,t.dominanceGroup,t.additionalSolverIterations);i.free(),n.free(),g.free(),o.free(),s.free(),a.free(),r.free();const c=new b_(this.raw,A,I);return c.userData=t.userData,this.map.set(I,c),c}remove(A,t,i,n,g){for(let o=0;o<this.raw.rbNumColliders(A);o+=1)i.unmap(this.raw.rbCollider(A,o));n.forEachJointHandleAttachedToRigidBody(A,o=>n.unmap(o)),g.forEachJointHandleAttachedToRigidBody(A,o=>g.unmap(o)),this.raw.remove(A,t.raw,i.raw,n.raw,g.raw),this.map.delete(A)}len(){return this.map.len()}contains(A){return this.get(A)!=null}get(A){return this.map.get(A)}forEach(A){this.map.forEach(A)}forEachActiveRigidBody(A,t){A.forEachActiveRigidBodyHandle(i=>{t(this.get(i))})}getAll(){return this.map.getAll()}}class WZ{constructor(A){this.raw=A||new uf}free(){this.raw&&this.raw.free(),this.raw=void 0}get dt(){return this.raw.dt}get contact_erp(){return this.raw.contact_erp}get lengthUnit(){return this.raw.lengthUnit}get normalizedAllowedLinearError(){return this.raw.normalizedAllowedLinearError}get normalizedPredictionDistance(){return this.raw.normalizedPredictionDistance}get numSolverIterations(){return this.raw.numSolverIterations}get numAdditionalFrictionIterations(){return this.raw.numAdditionalFrictionIterations}get numInternalPgsIterations(){return this.raw.numInternalPgsIterations}get minIslandSize(){return this.raw.minIslandSize}get maxCcdSubsteps(){return this.raw.maxCcdSubsteps}set dt(A){this.raw.dt=A}set contact_natural_frequency(A){this.raw.contact_natural_frequency=A}set lengthUnit(A){this.raw.lengthUnit=A}set normalizedAllowedLinearError(A){this.raw.normalizedAllowedLinearError=A}set normalizedPredictionDistance(A){this.raw.normalizedPredictionDistance=A}set numSolverIterations(A){this.raw.numSolverIterations=A}set numAdditionalFrictionIterations(A){this.raw.numAdditionalFrictionIterations=A}set numInternalPgsIterations(A){this.raw.numInternalPgsIterations=A}set minIslandSize(A){this.raw.minIslandSize=A}set maxCcdSubsteps(A){this.raw.maxCcdSubsteps=A}switchToStandardPgsSolver(){this.raw.switchToStandardPgsSolver()}switchToSmallStepsPgsSolver(){this.raw.switchToSmallStepsPgsSolver()}switchToSmallStepsPgsSolverWithoutWarmstart(){this.raw.switchToSmallStepsPgsSolverWithoutWarmstart()}}(function(e){e[e.Revolute=0]="Revolute",e[e.Fixed=1]="Fixed",e[e.Prismatic=2]="Prismatic",e[e.Rope=3]="Rope",e[e.Spring=4]="Spring",e[e.Spherical=5]="Spherical",e[e.Generic=6]="Generic"})($s||($s={})),function(e){e[e.AccelerationBased=0]="AccelerationBased",e[e.ForceBased=1]="ForceBased"}(S_||(S_={})),function(e){e[e.LinX=1]="LinX",e[e.LinY=2]="LinY",e[e.LinZ=4]="LinZ",e[e.AngX=8]="AngX",e[e.AngY=16]="AngY",e[e.AngZ=32]="AngZ"}(w_||(w_={}));class rc{constructor(A,t,i){this.rawSet=A,this.bodySet=t,this.handle=i}static newTyped(A,t,i){switch(A.jointType(i)){case Jc.Revolute:return new eW(A,t,i);case Jc.Prismatic:return new AW(A,t,i);case Jc.Fixed:return new VZ(A,t,i);case Jc.Spring:return new $Z(A,t,i);case Jc.Rope:return new XZ(A,t,i);case Jc.Spherical:return new iW(A,t,i);case Jc.Generic:return new tW(A,t,i);default:return new rc(A,t,i)}}finalizeDeserialization(A){this.bodySet=A}isValid(){return this.rawSet.contains(this.handle)}body1(){return this.bodySet.get(this.rawSet.jointBodyHandle1(this.handle))}body2(){return this.bodySet.get(this.rawSet.jointBodyHandle2(this.handle))}type(){return this.rawSet.jointType(this.handle)}frameX1(){return en.fromRaw(this.rawSet.jointFrameX1(this.handle))}frameX2(){return en.fromRaw(this.rawSet.jointFrameX2(this.handle))}anchor1(){return ce.fromRaw(this.rawSet.jointAnchor1(this.handle))}anchor2(){return ce.fromRaw(this.rawSet.jointAnchor2(this.handle))}setAnchor1(A){const t=ce.intoRaw(A);this.rawSet.jointSetAnchor1(this.handle,t),t.free()}setAnchor2(A){const t=ce.intoRaw(A);this.rawSet.jointSetAnchor2(this.handle,t),t.free()}setContactsEnabled(A){this.rawSet.jointSetContactsEnabled(this.handle,A)}contactsEnabled(){return this.rawSet.jointContactsEnabled(this.handle)}}class dx extends rc{limitsEnabled(){return this.rawSet.jointLimitsEnabled(this.handle,this.rawAxis())}limitsMin(){return this.rawSet.jointLimitsMin(this.handle,this.rawAxis())}limitsMax(){return this.rawSet.jointLimitsMax(this.handle,this.rawAxis())}setLimits(A,t){this.rawSet.jointSetLimits(this.handle,this.rawAxis(),A,t)}configureMotorModel(A){this.rawSet.jointConfigureMotorModel(this.handle,this.rawAxis(),A)}configureMotorVelocity(A,t){this.rawSet.jointConfigureMotorVelocity(this.handle,this.rawAxis(),A,t)}configureMotorPosition(A,t,i){this.rawSet.jointConfigureMotorPosition(this.handle,this.rawAxis(),A,t,i)}configureMotor(A,t,i,n){this.rawSet.jointConfigureMotor(this.handle,this.rawAxis(),A,t,i,n)}}class VZ extends rc{}class XZ extends rc{}class $Z extends rc{}class AW extends dx{rawAxis(){return Cx.LinX}}class eW extends dx{rawAxis(){return Cx.AngX}}class tW extends rc{}class iW extends rc{}class Hl{constructor(){}static fixed(A,t,i,n){let g=new Hl;return g.anchor1=A,g.anchor2=i,g.frame1=t,g.frame2=n,g.jointType=$s.Fixed,g}static spring(A,t,i,n,g){let o=new Hl;return o.anchor1=n,o.anchor2=g,o.length=A,o.stiffness=t,o.damping=i,o.jointType=$s.Spring,o}static rope(A,t,i){let n=new Hl;return n.anchor1=t,n.anchor2=i,n.length=A,n.jointType=$s.Rope,n}static generic(A,t,i,n){let g=new Hl;return g.anchor1=A,g.anchor2=t,g.axis=i,g.axesMask=n,g.jointType=$s.Generic,g}static spherical(A,t){let i=new Hl;return i.anchor1=A,i.anchor2=t,i.jointType=$s.Spherical,i}static prismatic(A,t,i){let n=new Hl;return n.anchor1=A,n.anchor2=t,n.axis=i,n.jointType=$s.Prismatic,n}static revolute(A,t,i){let n=new Hl;return n.anchor1=A,n.anchor2=t,n.axis=i,n.jointType=$s.Revolute,n}intoRaw(){let A,t,i=ce.intoRaw(this.anchor1),n=ce.intoRaw(this.anchor2),g=!1,o=0,s=0;switch(this.jointType){case $s.Fixed:let a=en.intoRaw(this.frame1),r=en.intoRaw(this.frame2);t=ta.fixed(i,a,n,r),a.free(),r.free();break;case $s.Spring:t=ta.spring(this.length,this.stiffness,this.damping,i,n);break;case $s.Rope:t=ta.rope(this.length,i,n);break;case $s.Prismatic:A=ce.intoRaw(this.axis),this.limitsEnabled&&(g=!0,o=this.limits[0],s=this.limits[1]),t=ta.prismatic(i,n,A,g,o,s),A.free();break;case $s.Generic:A=ce.intoRaw(this.axis);let I=this.axesMask;t=ta.generic(i,n,A,I);break;case $s.Spherical:t=ta.spherical(i,n);break;case $s.Revolute:A=ce.intoRaw(this.axis),t=ta.revolute(i,n,A),A.free()}return i.free(),n.free(),t}}class nW{constructor(A){this.raw=A||new gQ,this.map=new ux,A&&A.forEachJointHandle(t=>{this.map.set(t,rc.newTyped(A,null,t))})}free(){this.raw&&this.raw.free(),this.raw=void 0,this.map&&this.map.clear(),this.map=void 0}finalizeDeserialization(A){this.map.forEach(t=>t.finalizeDeserialization(A))}createJoint(A,t,i,n,g){const o=t.intoRaw(),s=this.raw.createJoint(o,i,n,g);o.free();let a=rc.newTyped(this.raw,A,s);return this.map.set(s,a),a}remove(A,t){this.raw.remove(A,t),this.unmap(A)}forEachJointHandleAttachedToRigidBody(A,t){this.raw.forEachJointAttachedToRigidBody(A,t)}unmap(A){this.map.delete(A)}len(){return this.map.len()}contains(A){return this.get(A)!=null}get(A){return this.map.get(A)}forEach(A){this.map.forEach(A)}getAll(){return this.map.getAll()}}class aQ{constructor(A,t){this.rawSet=A,this.handle=t}static newTyped(A,t){switch(A.jointType(t)){case Jc.Revolute:return new sW(A,t);case Jc.Prismatic:return new oW(A,t);case Jc.Fixed:return new gW(A,t);case Jc.Spherical:return new aW(A,t);default:return new aQ(A,t)}}isValid(){return this.rawSet.contains(this.handle)}setContactsEnabled(A){this.rawSet.jointSetContactsEnabled(this.handle,A)}contactsEnabled(){return this.rawSet.jointContactsEnabled(this.handle)}}class hx extends aQ{}class gW extends aQ{}class oW extends hx{rawAxis(){return Cx.LinX}}class sW extends hx{rawAxis(){return Cx.AngX}}class aW extends aQ{}class rW{constructor(A){this.raw=A||new sQ,this.map=new ux,A&&A.forEachJointHandle(t=>{this.map.set(t,aQ.newTyped(this.raw,t))})}free(){this.raw&&this.raw.free(),this.raw=void 0,this.map&&this.map.clear(),this.map=void 0}createJoint(A,t,i,n){const g=A.intoRaw(),o=this.raw.createJoint(g,t,i,n);g.free();let s=aQ.newTyped(this.raw,o);return this.map.set(o,s),s}remove(A,t){this.raw.remove(A,t),this.map.delete(A)}unmap(A){this.map.delete(A)}len(){return this.map.len()}contains(A){return this.get(A)!=null}get(A){return this.map.get(A)}forEach(A){this.map.forEach(A)}forEachJointHandleAttachedToRigidBody(A,t){this.raw.forEachJointAttachedToRigidBody(A,t)}getAll(){return this.map.getAll()}}(function(e){e[e.Average=0]="Average",e[e.Min=1]="Min",e[e.Multiply=2]="Multiply",e[e.Max=3]="Max"})(_S||(_S={}));class IW{constructor(A){this.raw=A||new e4}free(){this.raw&&this.raw.free(),this.raw=void 0}}class CW{constructor(A){this.raw=A||new oQ}free(){this.raw&&this.raw.free(),this.raw=void 0}forEachActiveRigidBodyHandle(A){this.raw.forEachActiveRigidBodyHandle(A)}}class cW{constructor(A){this.raw=A||new Qf}free(){this.raw&&this.raw.free(),this.raw=void 0}}class lW{constructor(A){this.raw=A||new Qd,this.tempManifold=new BW(null)}free(){this.raw&&this.raw.free(),this.raw=void 0}contactPairsWith(A,t){this.raw.contact_pairs_with(A,t)}intersectionPairsWith(A,t){this.raw.intersection_pairs_with(A,t)}contactPair(A,t,i){const n=this.raw.contact_pair(A,t);if(n){const g=n.collider1()!=A;let o;for(o=0;o<n.numContactManifolds();++o)this.tempManifold.raw=n.contactManifold(o),this.tempManifold.raw&&i(this.tempManifold,g),this.tempManifold.free();n.free()}}intersectionPair(A,t){return this.raw.intersection_pair(A,t)}}class BW{constructor(A){this.raw=A}free(){this.raw&&this.raw.free(),this.raw=void 0}normal(){return ce.fromRaw(this.raw.normal())}localNormal1(){return ce.fromRaw(this.raw.local_n1())}localNormal2(){return ce.fromRaw(this.raw.local_n2())}subshape1(){return this.raw.subshape1()}subshape2(){return this.raw.subshape2()}numContacts(){return this.raw.num_contacts()}localContactPoint1(A){return ce.fromRaw(this.raw.contact_local_p1(A))}localContactPoint2(A){return ce.fromRaw(this.raw.contact_local_p2(A))}contactDist(A){return this.raw.contact_dist(A)}contactFid1(A){return this.raw.contact_fid1(A)}contactFid2(A){return this.raw.contact_fid2(A)}contactImpulse(A){return this.raw.contact_impulse(A)}contactTangentImpulseX(A){return this.raw.contact_tangent_impulse_x(A)}contactTangentImpulseY(A){return this.raw.contact_tangent_impulse_y(A)}numSolverContacts(){return this.raw.num_solver_contacts()}solverContactPoint(A){return ce.fromRaw(this.raw.solver_contact_point(A))}solverContactDist(A){return this.raw.solver_contact_dist(A)}solverContactFriction(A){return this.raw.solver_contact_friction(A)}solverContactRestitution(A){return this.raw.solver_contact_restitution(A)}solverContactTangentVelocity(A){return ce.fromRaw(this.raw.solver_contact_tangent_velocity(A))}}class hf{constructor(A,t,i,n,g){this.distance=A,this.point1=t,this.point2=i,this.normal1=n,this.normal2=g}static fromRaw(A){if(!A)return null;const t=new hf(A.distance(),ce.fromRaw(A.point1()),ce.fromRaw(A.point2()),ce.fromRaw(A.normal1()),ce.fromRaw(A.normal2()));return A.free(),t}}(function(e){e[e.Vertex=0]="Vertex",e[e.Edge=1]="Edge",e[e.Face=2]="Face",e[e.Unknown=3]="Unknown"})(df||(df={}));class bw{constructor(A,t){this.point=A,this.isInside=t}static fromRaw(A){if(!A)return null;const t=new bw(ce.fromRaw(A.point()),A.isInside());return A.free(),t}}class JS{constructor(A,t,i,n,g){this.featureType=df.Unknown,this.featureId=void 0,this.collider=A,this.point=t,this.isInside=i,g!==void 0&&(this.featureId=g),n!==void 0&&(this.featureType=n)}static fromRaw(A,t){if(!t)return null;const i=new JS(A.get(t.colliderHandle()),ce.fromRaw(t.point()),t.isInside(),t.featureType(),t.featureId());return t.free(),i}}class IfA{constructor(A,t){this.origin=A,this.dir=t}pointAt(A){return{x:this.origin.x+this.dir.x*A,y:this.origin.y+this.dir.y*A,z:this.origin.z+this.dir.z*A}}}class Uw{constructor(A,t,i,n){this.featureType=df.Unknown,this.featureId=void 0,this.timeOfImpact=A,this.normal=t,n!==void 0&&(this.featureId=n),i!==void 0&&(this.featureType=i)}static fromRaw(A){if(!A)return null;const t=new Uw(A.time_of_impact(),ce.fromRaw(A.normal()),A.featureType(),A.featureId());return A.free(),t}}class LS{constructor(A,t,i,n,g){this.featureType=df.Unknown,this.featureId=void 0,this.collider=A,this.timeOfImpact=t,this.normal=i,g!==void 0&&(this.featureId=g),n!==void 0&&(this.featureType=n)}static fromRaw(A,t){if(!t)return null;const i=new LS(A.get(t.colliderHandle()),t.time_of_impact(),ce.fromRaw(t.normal()),t.featureType(),t.featureId());return t.free(),i}}class AG{constructor(A,t){this.collider=A,this.timeOfImpact=t}static fromRaw(A,t){if(!t)return null;const i=new AG(A.get(t.colliderHandle()),t.timeOfImpact());return t.free(),i}}class ty{constructor(A,t,i,n,g){this.time_of_impact=A,this.witness1=t,this.witness2=i,this.normal1=n,this.normal2=g}static fromRaw(A,t){if(!t)return null;const i=new ty(t.time_of_impact(),ce.fromRaw(t.witness1()),ce.fromRaw(t.witness2()),ce.fromRaw(t.normal1()),ce.fromRaw(t.normal2()));return t.free(),i}}class vw extends ty{constructor(A,t,i,n,g,o){super(t,i,n,g,o),this.collider=A}static fromRaw(A,t){if(!t)return null;const i=new vw(A.get(t.colliderHandle()),t.time_of_impact(),ce.fromRaw(t.witness1()),ce.fromRaw(t.witness2()),ce.fromRaw(t.normal1()),ce.fromRaw(t.normal2()));return t.free(),i}}class Ns{static fromRaw(A,t){const i=A.coShapeType(t);let n,g,o,s,a,r,I;switch(i){case ua.Ball:return new px(A.coRadius(t));case ua.Cuboid:return n=A.coHalfExtents(t),new fx(n.x,n.y,n.z);case ua.RoundCuboid:return n=A.coHalfExtents(t),g=A.coRoundRadius(t),new yx(n.x,n.y,n.z,g);case ua.Capsule:return a=A.coHalfHeight(t),r=A.coRadius(t),new Dx(a,r);case ua.Segment:return o=A.coVertices(t),new mx(ce.new(o[0],o[1],o[2]),ce.new(o[3],o[4],o[5]));case ua.Polyline:return o=A.coVertices(t),s=A.coIndices(t),new kx(o,s);case ua.Triangle:return o=A.coVertices(t),new Sx(ce.new(o[0],o[1],o[2]),ce.new(o[3],o[4],o[5]),ce.new(o[6],o[7],o[8]));case ua.RoundTriangle:return o=A.coVertices(t),g=A.coRoundRadius(t),new wx(ce.new(o[0],o[1],o[2]),ce.new(o[3],o[4],o[5]),ce.new(o[6],o[7],o[8]),g);case ua.HalfSpace:return I=ce.fromRaw(A.coHalfspaceNormal(t)),new EW(I);case ua.TriMesh:o=A.coVertices(t),s=A.coIndices(t);const c=A.coTriMeshFlags(t);return new Mx(o,s,c);case ua.HeightField:const l=A.coHeightfieldScale(t),B=A.coHeightfieldHeights(t),Q=A.coHeightfieldNRows(t),h=A.coHeightfieldNCols(t),d=A.coHeightFieldFlags(t);return new Nx(Q,h,B,l,d);case ua.ConvexPolyhedron:return o=A.coVertices(t),s=A.coIndices(t),new kN(o,s);case ua.RoundConvexPolyhedron:return o=A.coVertices(t),s=A.coIndices(t),g=A.coRoundRadius(t),new MN(o,s,g);case ua.Cylinder:return a=A.coHalfHeight(t),r=A.coRadius(t),new Rx(a,r);case ua.RoundCylinder:return a=A.coHalfHeight(t),r=A.coRadius(t),g=A.coRoundRadius(t),new Gx(a,r,g);case ua.Cone:return a=A.coHalfHeight(t),r=A.coRadius(t),new bx(a,r);case ua.RoundCone:return a=A.coHalfHeight(t),r=A.coRadius(t),g=A.coRoundRadius(t),new Ux(a,r,g);default:throw new Error("unknown shape type: "+i)}}castShape(A,t,i,n,g,o,s,a,r,I){let c=ce.intoRaw(A),l=en.intoRaw(t),B=ce.intoRaw(i),Q=ce.intoRaw(g),h=en.intoRaw(o),d=ce.intoRaw(s),p=this.intoRaw(),y=n.intoRaw(),m=ty.fromRaw(null,p.castShape(c,l,B,y,Q,h,d,a,r,I));return c.free(),l.free(),B.free(),Q.free(),h.free(),d.free(),p.free(),y.free(),m}intersectsShape(A,t,i,n,g){let o=ce.intoRaw(A),s=en.intoRaw(t),a=ce.intoRaw(n),r=en.intoRaw(g),I=this.intoRaw(),c=i.intoRaw(),l=I.intersectsShape(o,s,c,a,r);return o.free(),s.free(),a.free(),r.free(),I.free(),c.free(),l}contactShape(A,t,i,n,g,o){let s=ce.intoRaw(A),a=en.intoRaw(t),r=ce.intoRaw(n),I=en.intoRaw(g),c=this.intoRaw(),l=i.intoRaw(),B=hf.fromRaw(c.contactShape(s,a,l,r,I,o));return s.free(),a.free(),r.free(),I.free(),c.free(),l.free(),B}containsPoint(A,t,i){let n=ce.intoRaw(A),g=en.intoRaw(t),o=ce.intoRaw(i),s=this.intoRaw(),a=s.containsPoint(n,g,o);return n.free(),g.free(),o.free(),s.free(),a}projectPoint(A,t,i,n){let g=ce.intoRaw(A),o=en.intoRaw(t),s=ce.intoRaw(i),a=this.intoRaw(),r=bw.fromRaw(a.projectPoint(g,o,s,n));return g.free(),o.free(),s.free(),a.free(),r}intersectsRay(A,t,i,n){let g=ce.intoRaw(t),o=en.intoRaw(i),s=ce.intoRaw(A.origin),a=ce.intoRaw(A.dir),r=this.intoRaw(),I=r.intersectsRay(g,o,s,a,n);return g.free(),o.free(),s.free(),a.free(),r.free(),I}castRay(A,t,i,n,g){let o=ce.intoRaw(t),s=en.intoRaw(i),a=ce.intoRaw(A.origin),r=ce.intoRaw(A.dir),I=this.intoRaw(),c=I.castRay(o,s,a,r,n,g);return o.free(),s.free(),a.free(),r.free(),I.free(),c}castRayAndGetNormal(A,t,i,n,g){let o=ce.intoRaw(t),s=en.intoRaw(i),a=ce.intoRaw(A.origin),r=ce.intoRaw(A.dir),I=this.intoRaw(),c=Uw.fromRaw(I.castRayAndGetNormal(o,s,a,r,n,g));return o.free(),s.free(),a.free(),r.free(),I.free(),c}}(function(e){e[e.Ball=0]="Ball",e[e.Cuboid=1]="Cuboid",e[e.Capsule=2]="Capsule",e[e.Segment=3]="Segment",e[e.Polyline=4]="Polyline",e[e.Triangle=5]="Triangle",e[e.TriMesh=6]="TriMesh",e[e.HeightField=7]="HeightField",e[e.ConvexPolyhedron=9]="ConvexPolyhedron",e[e.Cylinder=10]="Cylinder",e[e.Cone=11]="Cone",e[e.RoundCuboid=12]="RoundCuboid",e[e.RoundTriangle=13]="RoundTriangle",e[e.RoundCylinder=14]="RoundCylinder",e[e.RoundCone=15]="RoundCone",e[e.RoundConvexPolyhedron=16]="RoundConvexPolyhedron",e[e.HalfSpace=17]="HalfSpace"})(ns||(ns={})),function(e){e[e.FIX_INTERNAL_EDGES=1]="FIX_INTERNAL_EDGES"}(k_||(k_={})),function(e){e[e.DELETE_BAD_TOPOLOGY_TRIANGLES=4]="DELETE_BAD_TOPOLOGY_TRIANGLES",e[e.ORIENTED=8]="ORIENTED",e[e.MERGE_DUPLICATE_VERTICES=16]="MERGE_DUPLICATE_VERTICES",e[e.DELETE_DEGENERATE_TRIANGLES=32]="DELETE_DEGENERATE_TRIANGLES",e[e.DELETE_DUPLICATE_TRIANGLES=64]="DELETE_DUPLICATE_TRIANGLES",e[e.FIX_INTERNAL_EDGES=152]="FIX_INTERNAL_EDGES"}(M_||(M_={}));class px extends Ns{constructor(A){super(),this.type=ns.Ball,this.radius=A}intoRaw(){return ki.ball(this.radius)}}class EW extends Ns{constructor(A){super(),this.type=ns.HalfSpace,this.normal=A}intoRaw(){let A=ce.intoRaw(this.normal),t=ki.halfspace(A);return A.free(),t}}class fx extends Ns{constructor(A,t,i){super(),this.type=ns.Cuboid,this.halfExtents=ce.new(A,t,i)}intoRaw(){return ki.cuboid(this.halfExtents.x,this.halfExtents.y,this.halfExtents.z)}}class yx extends Ns{constructor(A,t,i,n){super(),this.type=ns.RoundCuboid,this.halfExtents=ce.new(A,t,i),this.borderRadius=n}intoRaw(){return ki.roundCuboid(this.halfExtents.x,this.halfExtents.y,this.halfExtents.z,this.borderRadius)}}class Dx extends Ns{constructor(A,t){super(),this.type=ns.Capsule,this.halfHeight=A,this.radius=t}intoRaw(){return ki.capsule(this.halfHeight,this.radius)}}class mx extends Ns{constructor(A,t){super(),this.type=ns.Segment,this.a=A,this.b=t}intoRaw(){let A=ce.intoRaw(this.a),t=ce.intoRaw(this.b),i=ki.segment(A,t);return A.free(),t.free(),i}}class Sx extends Ns{constructor(A,t,i){super(),this.type=ns.Triangle,this.a=A,this.b=t,this.c=i}intoRaw(){let A=ce.intoRaw(this.a),t=ce.intoRaw(this.b),i=ce.intoRaw(this.c),n=ki.triangle(A,t,i);return A.free(),t.free(),i.free(),n}}class wx extends Ns{constructor(A,t,i,n){super(),this.type=ns.RoundTriangle,this.a=A,this.b=t,this.c=i,this.borderRadius=n}intoRaw(){let A=ce.intoRaw(this.a),t=ce.intoRaw(this.b),i=ce.intoRaw(this.c),n=ki.roundTriangle(A,t,i,this.borderRadius);return A.free(),t.free(),i.free(),n}}class kx extends Ns{constructor(A,t){super(),this.type=ns.Polyline,this.vertices=A,this.indices=t??new Uint32Array(0)}intoRaw(){return ki.polyline(this.vertices,this.indices)}}class Mx extends Ns{constructor(A,t,i){super(),this.type=ns.TriMesh,this.vertices=A,this.indices=t,this.flags=i}intoRaw(){return ki.trimesh(this.vertices,this.indices,this.flags)}}class kN extends Ns{constructor(A,t){super(),this.type=ns.ConvexPolyhedron,this.vertices=A,this.indices=t}intoRaw(){return this.indices?ki.convexMesh(this.vertices,this.indices):ki.convexHull(this.vertices)}}class MN extends Ns{constructor(A,t,i){super(),this.type=ns.RoundConvexPolyhedron,this.vertices=A,this.indices=t,this.borderRadius=i}intoRaw(){return this.indices?ki.roundConvexMesh(this.vertices,this.indices,this.borderRadius):ki.roundConvexHull(this.vertices,this.borderRadius)}}class Nx extends Ns{constructor(A,t,i,n,g){super(),this.type=ns.HeightField,this.nrows=A,this.ncols=t,this.heights=i,this.scale=n,this.flags=g}intoRaw(){let A=ce.intoRaw(this.scale),t=ki.heightfield(this.nrows,this.ncols,this.heights,A,this.flags);return A.free(),t}}class Rx extends Ns{constructor(A,t){super(),this.type=ns.Cylinder,this.halfHeight=A,this.radius=t}intoRaw(){return ki.cylinder(this.halfHeight,this.radius)}}class Gx extends Ns{constructor(A,t,i){super(),this.type=ns.RoundCylinder,this.borderRadius=i,this.halfHeight=A,this.radius=t}intoRaw(){return ki.roundCylinder(this.halfHeight,this.radius,this.borderRadius)}}class bx extends Ns{constructor(A,t){super(),this.type=ns.Cone,this.halfHeight=A,this.radius=t}intoRaw(){return ki.cone(this.halfHeight,this.radius)}}class Ux extends Ns{constructor(A,t,i){super(),this.type=ns.RoundCone,this.halfHeight=A,this.radius=t,this.borderRadius=i}intoRaw(){return ki.roundCone(this.halfHeight,this.radius,this.borderRadius)}}class QW{constructor(A){this.raw=A||new dse}free(){this.raw&&this.raw.free(),this.raw=void 0}step(A,t,i,n,g,o,s,a,r,I,c,l){let B=ce.intoRaw(A);c?this.raw.stepWithEvents(B,t.raw,i.raw,n.raw,g.raw,o.raw,s.raw,a.raw,r.raw,I.raw,c.raw,l,l?l.filterContactPair:null,l?l.filterIntersectionPair:null):this.raw.step(B,t.raw,i.raw,n.raw,g.raw,o.raw,s.raw,a.raw,r.raw,I.raw),B.free()}}(function(e){e[e.EXCLUDE_FIXED=1]="EXCLUDE_FIXED",e[e.EXCLUDE_KINEMATIC=2]="EXCLUDE_KINEMATIC",e[e.EXCLUDE_DYNAMIC=4]="EXCLUDE_DYNAMIC",e[e.EXCLUDE_SENSORS=8]="EXCLUDE_SENSORS",e[e.EXCLUDE_SOLIDS=16]="EXCLUDE_SOLIDS",e[e.ONLY_DYNAMIC=3]="ONLY_DYNAMIC",e[e.ONLY_KINEMATIC=5]="ONLY_KINEMATIC",e[e.ONLY_FIXED=6]="ONLY_FIXED"})(N_||(N_={}));class uW{constructor(A){this.raw=A||new PZ}free(){this.raw&&this.raw.free(),this.raw=void 0}update(A){this.raw.update(A.raw)}castRay(A,t,i,n,g,o,s,a,r,I){let c=ce.intoRaw(i.origin),l=ce.intoRaw(i.dir),B=AG.fromRaw(t,this.raw.castRay(A.raw,t.raw,c,l,n,g,o,s,a,r,I));return c.free(),l.free(),B}castRayAndGetNormal(A,t,i,n,g,o,s,a,r,I){let c=ce.intoRaw(i.origin),l=ce.intoRaw(i.dir),B=LS.fromRaw(t,this.raw.castRayAndGetNormal(A.raw,t.raw,c,l,n,g,o,s,a,r,I));return c.free(),l.free(),B}intersectionsWithRay(A,t,i,n,g,o,s,a,r,I,c){let l=ce.intoRaw(i.origin),B=ce.intoRaw(i.dir);this.raw.intersectionsWithRay(A.raw,t.raw,l,B,n,g,Q=>o(LS.fromRaw(t,Q)),s,a,r,I,c),l.free(),B.free()}intersectionWithShape(A,t,i,n,g,o,s,a,r,I){let c=ce.intoRaw(i),l=en.intoRaw(n),B=g.intoRaw(),Q=this.raw.intersectionWithShape(A.raw,t.raw,c,l,B,o,s,a,r,I);return c.free(),l.free(),B.free(),Q}projectPoint(A,t,i,n,g,o,s,a,r){let I=ce.intoRaw(i),c=JS.fromRaw(t,this.raw.projectPoint(A.raw,t.raw,I,n,g,o,s,a,r));return I.free(),c}projectPointAndGetFeature(A,t,i,n,g,o,s,a){let r=ce.intoRaw(i),I=JS.fromRaw(t,this.raw.projectPointAndGetFeature(A.raw,t.raw,r,n,g,o,s,a));return r.free(),I}intersectionsWithPoint(A,t,i,n,g,o,s,a,r){let I=ce.intoRaw(i);this.raw.intersectionsWithPoint(A.raw,t.raw,I,n,g,o,s,a,r),I.free()}castShape(A,t,i,n,g,o,s,a,r,I,c,l,B,Q){let h=ce.intoRaw(i),d=en.intoRaw(n),p=ce.intoRaw(g),y=o.intoRaw(),m=vw.fromRaw(t,this.raw.castShape(A.raw,t.raw,h,d,p,y,s,a,r,I,c,l,B,Q));return h.free(),d.free(),p.free(),y.free(),m}intersectionsWithShape(A,t,i,n,g,o,s,a,r,I,c){let l=ce.intoRaw(i),B=en.intoRaw(n),Q=g.intoRaw();this.raw.intersectionsWithShape(A.raw,t.raw,l,B,Q,o,s,a,r,I,c),l.free(),B.free(),Q.free()}collidersWithAabbIntersectingAabb(A,t,i){let n=ce.intoRaw(A),g=ce.intoRaw(t);this.raw.collidersWithAabbIntersectingAabb(n,g,i),n.free(),g.free()}}class U_{constructor(A){this.raw=A||new pse}free(){this.raw&&this.raw.free(),this.raw=void 0}serializeAll(A,t,i,n,g,o,s,a,r){let I=ce.intoRaw(A);const c=this.raw.serializeAll(I,t.raw,i.raw,n.raw,g.raw,o.raw,s.raw,a.raw,r.raw);return I.free(),c}deserializeAll(A){return eG.fromRaw(this.raw.deserializeAll(A))}}class dW{constructor(A,t){this.vertices=A,this.colors=t}}class hW{constructor(A){this.raw=A||new Bse}free(){this.raw&&this.raw.free(),this.raw=void 0,this.vertices=void 0,this.colors=void 0}render(A,t,i,n,g){this.raw.render(A.raw,t.raw,i.raw,n.raw,g.raw),this.vertices=this.raw.vertices(),this.colors=this.raw.colors()}}class pW{}class fW{constructor(A,t,i,n,g){this.params=t,this.bodies=i,this.colliders=n,this.queries=g,this.raw=new use(A),this.rawCharacterCollision=new nfA,this._applyImpulsesToDynamicBodies=!1,this._characterMass=null}free(){this.raw&&(this.raw.free(),this.rawCharacterCollision.free()),this.raw=void 0,this.rawCharacterCollision=void 0}up(){return this.raw.up()}setUp(A){let t=ce.intoRaw(A);return this.raw.setUp(t)}applyImpulsesToDynamicBodies(){return this._applyImpulsesToDynamicBodies}setApplyImpulsesToDynamicBodies(A){this._applyImpulsesToDynamicBodies=A}characterMass(){return this._characterMass}setCharacterMass(A){this._characterMass=A}offset(){return this.raw.offset()}setOffset(A){this.raw.setOffset(A)}normalNudgeFactor(){return this.raw.normalNudgeFactor()}setNormalNudgeFactor(A){this.raw.setNormalNudgeFactor(A)}slideEnabled(){return this.raw.slideEnabled()}setSlideEnabled(A){this.raw.setSlideEnabled(A)}autostepMaxHeight(){return this.raw.autostepMaxHeight()}autostepMinWidth(){return this.raw.autostepMinWidth()}autostepIncludesDynamicBodies(){return this.raw.autostepIncludesDynamicBodies()}autostepEnabled(){return this.raw.autostepEnabled()}enableAutostep(A,t,i){this.raw.enableAutostep(A,t,i)}disableAutostep(){return this.raw.disableAutostep()}maxSlopeClimbAngle(){return this.raw.maxSlopeClimbAngle()}setMaxSlopeClimbAngle(A){this.raw.setMaxSlopeClimbAngle(A)}minSlopeSlideAngle(){return this.raw.minSlopeSlideAngle()}setMinSlopeSlideAngle(A){this.raw.setMinSlopeSlideAngle(A)}snapToGroundDistance(){return this.raw.snapToGroundDistance()}enableSnapToGround(A){this.raw.enableSnapToGround(A)}disableSnapToGround(){this.raw.disableSnapToGround()}snapToGroundEnabled(){return this.raw.snapToGroundEnabled()}computeColliderMovement(A,t,i,n,g){let o=ce.intoRaw(t);this.raw.computeColliderMovement(this.params.dt,this.bodies.raw,this.colliders.raw,this.queries.raw,A.handle,o,this._applyImpulsesToDynamicBodies,this._characterMass,i,n,this.colliders.castClosure(g)),o.free()}computedMovement(){return ce.fromRaw(this.raw.computedMovement())}computedGrounded(){return this.raw.computedGrounded()}numComputedCollisions(){return this.raw.numComputedCollisions()}computedCollision(A,t){if(this.raw.computedCollision(A,this.rawCharacterCollision)){let i=this.rawCharacterCollision;return(t=t??new pW).translationDeltaApplied=ce.fromRaw(i.translationDeltaApplied()),t.translationDeltaRemaining=ce.fromRaw(i.translationDeltaRemaining()),t.toi=i.toi(),t.witness1=ce.fromRaw(i.worldWitness1()),t.witness2=ce.fromRaw(i.worldWitness2()),t.normal1=ce.fromRaw(i.worldNormal1()),t.normal2=ce.fromRaw(i.worldNormal2()),t.collider=this.colliders.get(i.handle()),t}return null}}(function(e){e[e.None=0]="None",e[e.LinX=1]="LinX",e[e.LinY=2]="LinY",e[e.LinZ=4]="LinZ",e[e.AngX=8]="AngX",e[e.AngY=16]="AngY",e[e.AngZ=32]="AngZ",e[e.AllLin=7]="AllLin",e[e.AllAng=56]="AllAng",e[e.All=63]="All"})(R_||(R_={}));class yW{constructor(A,t,i,n,g,o){this.params=A,this.bodies=t,this.raw=new hse(i,n,g,o)}free(){this.raw&&this.raw.free(),this.raw=void 0}setKp(A,t){this.raw.set_kp(A,t)}setKi(A,t){this.raw.set_kp(A,t)}setKd(A,t){this.raw.set_kp(A,t)}setAxes(A){this.raw.set_axes_mask(A)}resetIntegrals(){this.raw.reset_integrals()}applyLinearCorrection(A,t,i){let n=ce.intoRaw(t),g=ce.intoRaw(i);this.raw.apply_linear_correction(this.params.dt,this.bodies.raw,A.handle,n,g),n.free(),g.free()}applyAngularCorrection(A,t,i){let n=en.intoRaw(t),g=ce.intoRaw(i);this.raw.apply_angular_correction(this.params.dt,this.bodies.raw,A.handle,n,g),n.free(),g.free()}linearCorrection(A,t,i){let n=ce.intoRaw(t),g=ce.intoRaw(i),o=this.raw.linear_correction(this.params.dt,this.bodies.raw,A.handle,n,g);return n.free(),g.free(),ce.fromRaw(o)}angularCorrection(A,t,i){let n=en.intoRaw(t),g=ce.intoRaw(i),o=this.raw.angular_correction(this.params.dt,this.bodies.raw,A.handle,n,g);return n.free(),g.free(),ce.fromRaw(o)}}class DW{constructor(A,t,i,n){this.raw=new Qse(A.handle),this.bodies=t,this.colliders=i,this.queries=n,this._chassis=A}free(){this.raw&&this.raw.free(),this.raw=void 0}updateVehicle(A,t,i,n){this.raw.update_vehicle(A,this.bodies.raw,this.colliders.raw,this.queries.raw,t,i,this.colliders.castClosure(n))}currentVehicleSpeed(){return this.raw.current_vehicle_speed()}chassis(){return this._chassis}get indexUpAxis(){return this.raw.index_up_axis()}set indexUpAxis(A){this.raw.set_index_up_axis(A)}get indexForwardAxis(){return this.raw.index_forward_axis()}set setIndexForwardAxis(A){this.raw.set_index_forward_axis(A)}addWheel(A,t,i,n,g){let o=ce.intoRaw(A),s=ce.intoRaw(t),a=ce.intoRaw(i);this.raw.add_wheel(o,s,a,n,g),o.free(),s.free(),a.free()}numWheels(){return this.raw.num_wheels()}wheelChassisConnectionPointCs(A){return ce.fromRaw(this.raw.wheel_chassis_connection_point_cs(A))}setWheelChassisConnectionPointCs(A,t){let i=ce.intoRaw(t);this.raw.set_wheel_chassis_connection_point_cs(A,i),i.free()}wheelSuspensionRestLength(A){return this.raw.wheel_suspension_rest_length(A)}setWheelSuspensionRestLength(A,t){this.raw.set_wheel_suspension_rest_length(A,t)}wheelMaxSuspensionTravel(A){return this.raw.wheel_max_suspension_travel(A)}setWheelMaxSuspensionTravel(A,t){this.raw.set_wheel_max_suspension_travel(A,t)}wheelRadius(A){return this.raw.wheel_radius(A)}setWheelRadius(A,t){this.raw.set_wheel_radius(A,t)}wheelSuspensionStiffness(A){return this.raw.wheel_suspension_stiffness(A)}setWheelSuspensionStiffness(A,t){this.raw.set_wheel_suspension_stiffness(A,t)}wheelSuspensionCompression(A){return this.raw.wheel_suspension_compression(A)}setWheelSuspensionCompression(A,t){this.raw.set_wheel_suspension_compression(A,t)}wheelSuspensionRelaxation(A){return this.raw.wheel_suspension_relaxation(A)}setWheelSuspensionRelaxation(A,t){this.raw.set_wheel_suspension_relaxation(A,t)}wheelMaxSuspensionForce(A){return this.raw.wheel_max_suspension_force(A)}setWheelMaxSuspensionForce(A,t){this.raw.set_wheel_max_suspension_force(A,t)}wheelBrake(A){return this.raw.wheel_brake(A)}setWheelBrake(A,t){this.raw.set_wheel_brake(A,t)}wheelSteering(A){return this.raw.wheel_steering(A)}setWheelSteering(A,t){this.raw.set_wheel_steering(A,t)}wheelEngineForce(A){return this.raw.wheel_engine_force(A)}setWheelEngineForce(A,t){this.raw.set_wheel_engine_force(A,t)}wheelDirectionCs(A){return ce.fromRaw(this.raw.wheel_direction_cs(A))}setWheelDirectionCs(A,t){let i=ce.intoRaw(t);this.raw.set_wheel_direction_cs(A,i),i.free()}wheelAxleCs(A){return ce.fromRaw(this.raw.wheel_axle_cs(A))}setWheelAxleCs(A,t){let i=ce.intoRaw(t);this.raw.set_wheel_axle_cs(A,i),i.free()}wheelFrictionSlip(A){return this.raw.wheel_friction_slip(A)}setWheelFrictionSlip(A,t){this.raw.set_wheel_friction_slip(A,t)}wheelSideFrictionStiffness(A){return this.raw.wheel_side_friction_stiffness(A)}setWheelSideFrictionStiffness(A,t){this.raw.set_wheel_side_friction_stiffness(A,t)}wheelRotation(A){return this.raw.wheel_rotation(A)}wheelForwardImpulse(A){return this.raw.wheel_forward_impulse(A)}wheelSideImpulse(A){return this.raw.wheel_side_impulse(A)}wheelSuspensionForce(A){return this.raw.wheel_suspension_force(A)}wheelContactNormal(A){return ce.fromRaw(this.raw.wheel_contact_normal_ws(A))}wheelContactPoint(A){return ce.fromRaw(this.raw.wheel_contact_point_ws(A))}wheelSuspensionLength(A){return this.raw.wheel_suspension_length(A)}wheelHardPoint(A){return ce.fromRaw(this.raw.wheel_hard_point_ws(A))}wheelIsInContact(A){return this.raw.wheel_is_in_contact(A)}wheelGroundObject(A){return this.colliders.get(this.raw.wheel_ground_object(A))}}class eG{constructor(A,t,i,n,g,o,s,a,r,I,c,l,B,Q){this.gravity=A,this.integrationParameters=new WZ(t),this.islands=new CW(i),this.broadPhase=new cW(n),this.narrowPhase=new lW(g),this.bodies=new ZZ(o),this.colliders=new wW(s),this.impulseJoints=new nW(a),this.multibodyJoints=new rW(r),this.ccdSolver=new IW(I),this.queryPipeline=new uW(c),this.physicsPipeline=new QW(l),this.serializationPipeline=new U_(B),this.debugRenderPipeline=new hW(Q),this.characterControllers=new Set,this.pidControllers=new Set,this.vehicleControllers=new Set,this.impulseJoints.finalizeDeserialization(this.bodies),this.bodies.finalizeDeserialization(this.colliders),this.colliders.finalizeDeserialization(this.bodies)}free(){this.integrationParameters.free(),this.islands.free(),this.broadPhase.free(),this.narrowPhase.free(),this.bodies.free(),this.colliders.free(),this.impulseJoints.free(),this.multibodyJoints.free(),this.ccdSolver.free(),this.queryPipeline.free(),this.physicsPipeline.free(),this.serializationPipeline.free(),this.debugRenderPipeline.free(),this.characterControllers.forEach(A=>A.free()),this.pidControllers.forEach(A=>A.free()),this.vehicleControllers.forEach(A=>A.free()),this.integrationParameters=void 0,this.islands=void 0,this.broadPhase=void 0,this.narrowPhase=void 0,this.bodies=void 0,this.colliders=void 0,this.ccdSolver=void 0,this.impulseJoints=void 0,this.multibodyJoints=void 0,this.queryPipeline=void 0,this.physicsPipeline=void 0,this.serializationPipeline=void 0,this.debugRenderPipeline=void 0,this.characterControllers=void 0,this.pidControllers=void 0,this.vehicleControllers=void 0}static fromRaw(A){return A?new eG(ce.fromRaw(A.takeGravity()),A.takeIntegrationParameters(),A.takeIslandManager(),A.takeBroadPhase(),A.takeNarrowPhase(),A.takeBodies(),A.takeColliders(),A.takeImpulseJoints(),A.takeMultibodyJoints()):null}takeSnapshot(){return this.serializationPipeline.serializeAll(this.gravity,this.integrationParameters,this.islands,this.broadPhase,this.narrowPhase,this.bodies,this.colliders,this.impulseJoints,this.multibodyJoints)}static restoreSnapshot(A){return new U_().deserializeAll(A)}debugRender(){return this.debugRenderPipeline.render(this.bodies,this.colliders,this.impulseJoints,this.multibodyJoints,this.narrowPhase),new dW(this.debugRenderPipeline.vertices,this.debugRenderPipeline.colors)}step(A,t){this.physicsPipeline.step(this.gravity,this.integrationParameters,this.islands,this.broadPhase,this.narrowPhase,this.bodies,this.colliders,this.impulseJoints,this.multibodyJoints,this.ccdSolver,A,t),this.queryPipeline.update(this.colliders)}propagateModifiedBodyPositionsToColliders(){this.bodies.raw.propagateModifiedBodyPositionsToColliders(this.colliders.raw)}updateSceneQueries(){this.propagateModifiedBodyPositionsToColliders(),this.queryPipeline.update(this.colliders)}get timestep(){return this.integrationParameters.dt}set timestep(A){this.integrationParameters.dt=A}get lengthUnit(){return this.integrationParameters.lengthUnit}set lengthUnit(A){this.integrationParameters.lengthUnit=A}get numSolverIterations(){return this.integrationParameters.numSolverIterations}set numSolverIterations(A){this.integrationParameters.numSolverIterations=A}get numAdditionalFrictionIterations(){return this.integrationParameters.numAdditionalFrictionIterations}set numAdditionalFrictionIterations(A){this.integrationParameters.numAdditionalFrictionIterations=A}get numInternalPgsIterations(){return this.integrationParameters.numInternalPgsIterations}set numInternalPgsIterations(A){this.integrationParameters.numInternalPgsIterations=A}switchToStandardPgsSolver(){this.integrationParameters.switchToStandardPgsSolver()}switchToSmallStepsPgsSolver(){this.integrationParameters.switchToSmallStepsPgsSolver()}switchToSmallStepsPgsSolverWithoutWarmstart(){this.integrationParameters.switchToSmallStepsPgsSolverWithoutWarmstart()}createRigidBody(A){return this.bodies.createRigidBody(this.colliders,A)}createCharacterController(A){let t=new fW(A,this.integrationParameters,this.bodies,this.colliders,this.queryPipeline);return this.characterControllers.add(t),t}removeCharacterController(A){this.characterControllers.delete(A),A.free()}createPidController(A,t,i,n){let g=new yW(this.integrationParameters,this.bodies,A,t,i,n);return this.pidControllers.add(g),g}removePidController(A){this.pidControllers.delete(A),A.free()}createVehicleController(A){let t=new DW(A,this.bodies,this.colliders,this.queryPipeline);return this.vehicleControllers.add(t),t}removeVehicleController(A){this.vehicleControllers.delete(A),A.free()}createCollider(A,t){let i=t?t.handle:void 0;return this.colliders.createCollider(this.bodies,A,i)}createImpulseJoint(A,t,i,n){return this.impulseJoints.createJoint(this.bodies,A,t.handle,i.handle,n)}createMultibodyJoint(A,t,i,n){return this.multibodyJoints.createJoint(A,t.handle,i.handle,n)}getRigidBody(A){return this.bodies.get(A)}getCollider(A){return this.colliders.get(A)}getImpulseJoint(A){return this.impulseJoints.get(A)}getMultibodyJoint(A){return this.multibodyJoints.get(A)}removeRigidBody(A){this.bodies&&this.bodies.remove(A.handle,this.islands,this.colliders,this.impulseJoints,this.multibodyJoints)}removeCollider(A,t){this.colliders&&this.colliders.remove(A.handle,this.islands,this.bodies,t)}removeImpulseJoint(A,t){this.impulseJoints&&this.impulseJoints.remove(A.handle,t)}removeMultibodyJoint(A,t){this.impulseJoints&&this.multibodyJoints.remove(A.handle,t)}forEachCollider(A){this.colliders.forEach(A)}forEachRigidBody(A){this.bodies.forEach(A)}forEachActiveRigidBody(A){this.bodies.forEachActiveRigidBody(this.islands,A)}castRay(A,t,i,n,g,o,s,a){return this.queryPipeline.castRay(this.bodies,this.colliders,A,t,i,n,g,o?o.handle:null,s?s.handle:null,this.colliders.castClosure(a))}castRayAndGetNormal(A,t,i,n,g,o,s,a){return this.queryPipeline.castRayAndGetNormal(this.bodies,this.colliders,A,t,i,n,g,o?o.handle:null,s?s.handle:null,this.colliders.castClosure(a))}intersectionsWithRay(A,t,i,n,g,o,s,a,r){this.queryPipeline.intersectionsWithRay(this.bodies,this.colliders,A,t,i,n,g,o,s?s.handle:null,a?a.handle:null,this.colliders.castClosure(r))}intersectionWithShape(A,t,i,n,g,o,s,a){let r=this.queryPipeline.intersectionWithShape(this.bodies,this.colliders,A,t,i,n,g,o?o.handle:null,s?s.handle:null,this.colliders.castClosure(a));return r!=null?this.colliders.get(r):null}projectPoint(A,t,i,n,g,o,s){return this.queryPipeline.projectPoint(this.bodies,this.colliders,A,t,i,n,g?g.handle:null,o?o.handle:null,this.colliders.castClosure(s))}projectPointAndGetFeature(A,t,i,n,g,o){return this.queryPipeline.projectPointAndGetFeature(this.bodies,this.colliders,A,t,i,n?n.handle:null,g?g.handle:null,this.colliders.castClosure(o))}intersectionsWithPoint(A,t,i,n,g,o,s){this.queryPipeline.intersectionsWithPoint(this.bodies,this.colliders,A,this.colliders.castClosure(t),i,n,g?g.handle:null,o?o.handle:null,this.colliders.castClosure(s))}castShape(A,t,i,n,g,o,s,a,r,I,c,l){return this.queryPipeline.castShape(this.bodies,this.colliders,A,t,i,n,g,o,s,a,r,I?I.handle:null,c?c.handle:null,this.colliders.castClosure(l))}intersectionsWithShape(A,t,i,n,g,o,s,a,r){this.queryPipeline.intersectionsWithShape(this.bodies,this.colliders,A,t,i,this.colliders.castClosure(n),g,o,s?s.handle:null,a?a.handle:null,this.colliders.castClosure(r))}collidersWithAabbIntersectingAabb(A,t,i){this.queryPipeline.collidersWithAabbIntersectingAabb(A,t,this.colliders.castClosure(i))}contactPairsWith(A,t){this.narrowPhase.contactPairsWith(A.handle,this.colliders.castClosure(t))}intersectionPairsWith(A,t){this.narrowPhase.intersectionPairsWith(A.handle,this.colliders.castClosure(t))}contactPair(A,t,i){this.narrowPhase.contactPair(A.handle,t.handle,i)}intersectionPair(A,t){return this.narrowPhase.intersectionPair(A.handle,t.handle)}}(function(e){e[e.NONE=0]="NONE",e[e.COLLISION_EVENTS=1]="COLLISION_EVENTS",e[e.CONTACT_FORCE_EVENTS=2]="CONTACT_FORCE_EVENTS"})(ME||(ME={}));class mW{free(){this.raw&&this.raw.free(),this.raw=void 0}collider1(){return this.raw.collider1()}collider2(){return this.raw.collider2()}totalForce(){return ce.fromRaw(this.raw.total_force())}totalForceMagnitude(){return this.raw.total_force_magnitude()}maxForceDirection(){return ce.fromRaw(this.raw.max_force_direction())}maxForceMagnitude(){return this.raw.max_force_magnitude()}}class SW{constructor(A,t){this.raw=t||new afA(A)}free(){this.raw&&this.raw.free(),this.raw=void 0}drainCollisionEvents(A){this.raw.drainCollisionEvents(A)}drainContactForceEvents(A){let t=new mW;this.raw.drainContactForceEvents(i=>{t.raw=i,A(t),t.free()})}clear(){this.raw.clear()}}(function(e){e[e.NONE=0]="NONE",e[e.FILTER_CONTACT_PAIRS=1]="FILTER_CONTACT_PAIRS",e[e.FILTER_INTERSECTION_PAIRS=2]="FILTER_INTERSECTION_PAIRS"})(SN||(SN={})),function(e){e[e.EMPTY=0]="EMPTY",e[e.COMPUTE_IMPULSE=1]="COMPUTE_IMPULSE"}(G_||(G_={})),function(e){e[e.DYNAMIC_DYNAMIC=1]="DYNAMIC_DYNAMIC",e[e.DYNAMIC_KINEMATIC=12]="DYNAMIC_KINEMATIC",e[e.DYNAMIC_FIXED=2]="DYNAMIC_FIXED",e[e.KINEMATIC_KINEMATIC=52224]="KINEMATIC_KINEMATIC",e[e.KINEMATIC_FIXED=8704]="KINEMATIC_FIXED",e[e.FIXED_FIXED=32]="FIXED_FIXED",e[e.DEFAULT=15]="DEFAULT",e[e.ALL=60943]="ALL"}(wN||(wN={}));class v_{constructor(A,t,i,n){this.colliderSet=A,this.handle=t,this._parent=i,this._shape=n}finalizeDeserialization(A){this.handle!=null&&(this._parent=A.get(this.colliderSet.raw.coParent(this.handle)))}ensureShapeIsCached(){this._shape||(this._shape=Ns.fromRaw(this.colliderSet.raw,this.handle))}get shape(){return this.ensureShapeIsCached(),this._shape}isValid(){return this.colliderSet.raw.contains(this.handle)}translation(){return ce.fromRaw(this.colliderSet.raw.coTranslation(this.handle))}rotation(){return en.fromRaw(this.colliderSet.raw.coRotation(this.handle))}isSensor(){return this.colliderSet.raw.coIsSensor(this.handle)}setSensor(A){this.colliderSet.raw.coSetSensor(this.handle,A)}setShape(A){let t=A.intoRaw();this.colliderSet.raw.coSetShape(this.handle,t),t.free(),this._shape=A}setEnabled(A){this.colliderSet.raw.coSetEnabled(this.handle,A)}isEnabled(){return this.colliderSet.raw.coIsEnabled(this.handle)}setRestitution(A){this.colliderSet.raw.coSetRestitution(this.handle,A)}setFriction(A){this.colliderSet.raw.coSetFriction(this.handle,A)}frictionCombineRule(){return this.colliderSet.raw.coFrictionCombineRule(this.handle)}setFrictionCombineRule(A){this.colliderSet.raw.coSetFrictionCombineRule(this.handle,A)}restitutionCombineRule(){return this.colliderSet.raw.coRestitutionCombineRule(this.handle)}setRestitutionCombineRule(A){this.colliderSet.raw.coSetRestitutionCombineRule(this.handle,A)}setCollisionGroups(A){this.colliderSet.raw.coSetCollisionGroups(this.handle,A)}setSolverGroups(A){this.colliderSet.raw.coSetSolverGroups(this.handle,A)}contactSkin(){return this.colliderSet.raw.coContactSkin(this.handle)}setContactSkin(A){return this.colliderSet.raw.coSetContactSkin(this.handle,A)}activeHooks(){return this.colliderSet.raw.coActiveHooks(this.handle)}setActiveHooks(A){this.colliderSet.raw.coSetActiveHooks(this.handle,A)}activeEvents(){return this.colliderSet.raw.coActiveEvents(this.handle)}setActiveEvents(A){this.colliderSet.raw.coSetActiveEvents(this.handle,A)}activeCollisionTypes(){return this.colliderSet.raw.coActiveCollisionTypes(this.handle)}setContactForceEventThreshold(A){return this.colliderSet.raw.coSetContactForceEventThreshold(this.handle,A)}contactForceEventThreshold(){return this.colliderSet.raw.coContactForceEventThreshold(this.handle)}setActiveCollisionTypes(A){this.colliderSet.raw.coSetActiveCollisionTypes(this.handle,A)}setDensity(A){this.colliderSet.raw.coSetDensity(this.handle,A)}setMass(A){this.colliderSet.raw.coSetMass(this.handle,A)}setMassProperties(A,t,i,n){let g=ce.intoRaw(t),o=ce.intoRaw(i),s=en.intoRaw(n);this.colliderSet.raw.coSetMassProperties(this.handle,A,g,o,s),g.free(),o.free(),s.free()}setTranslation(A){this.colliderSet.raw.coSetTranslation(this.handle,A.x,A.y,A.z)}setTranslationWrtParent(A){this.colliderSet.raw.coSetTranslationWrtParent(this.handle,A.x,A.y,A.z)}setRotation(A){this.colliderSet.raw.coSetRotation(this.handle,A.x,A.y,A.z,A.w)}setRotationWrtParent(A){this.colliderSet.raw.coSetRotationWrtParent(this.handle,A.x,A.y,A.z,A.w)}shapeType(){return this.colliderSet.raw.coShapeType(this.handle)}halfExtents(){return ce.fromRaw(this.colliderSet.raw.coHalfExtents(this.handle))}setHalfExtents(A){const t=ce.intoRaw(A);this.colliderSet.raw.coSetHalfExtents(this.handle,t)}radius(){return this.colliderSet.raw.coRadius(this.handle)}setRadius(A){this.colliderSet.raw.coSetRadius(this.handle,A)}roundRadius(){return this.colliderSet.raw.coRoundRadius(this.handle)}setRoundRadius(A){this.colliderSet.raw.coSetRoundRadius(this.handle,A)}halfHeight(){return this.colliderSet.raw.coHalfHeight(this.handle)}setHalfHeight(A){this.colliderSet.raw.coSetHalfHeight(this.handle,A)}vertices(){return this.colliderSet.raw.coVertices(this.handle)}indices(){return this.colliderSet.raw.coIndices(this.handle)}heightfieldHeights(){return this.colliderSet.raw.coHeightfieldHeights(this.handle)}heightfieldScale(){let A=this.colliderSet.raw.coHeightfieldScale(this.handle);return ce.fromRaw(A)}heightfieldNRows(){return this.colliderSet.raw.coHeightfieldNRows(this.handle)}heightfieldNCols(){return this.colliderSet.raw.coHeightfieldNCols(this.handle)}parent(){return this._parent}friction(){return this.colliderSet.raw.coFriction(this.handle)}restitution(){return this.colliderSet.raw.coRestitution(this.handle)}density(){return this.colliderSet.raw.coDensity(this.handle)}mass(){return this.colliderSet.raw.coMass(this.handle)}volume(){return this.colliderSet.raw.coVolume(this.handle)}collisionGroups(){return this.colliderSet.raw.coCollisionGroups(this.handle)}solverGroups(){return this.colliderSet.raw.coSolverGroups(this.handle)}containsPoint(A){let t=ce.intoRaw(A),i=this.colliderSet.raw.coContainsPoint(this.handle,t);return t.free(),i}projectPoint(A,t){let i=ce.intoRaw(A),n=bw.fromRaw(this.colliderSet.raw.coProjectPoint(this.handle,i,t));return i.free(),n}intersectsRay(A,t){let i=ce.intoRaw(A.origin),n=ce.intoRaw(A.dir),g=this.colliderSet.raw.coIntersectsRay(this.handle,i,n,t);return i.free(),n.free(),g}castShape(A,t,i,n,g,o,s,a){let r=ce.intoRaw(A),I=ce.intoRaw(i),c=en.intoRaw(n),l=ce.intoRaw(g),B=t.intoRaw(),Q=ty.fromRaw(this.colliderSet,this.colliderSet.raw.coCastShape(this.handle,r,B,I,c,l,o,s,a));return r.free(),I.free(),c.free(),l.free(),B.free(),Q}castCollider(A,t,i,n,g,o){let s=ce.intoRaw(A),a=ce.intoRaw(i),r=vw.fromRaw(this.colliderSet,this.colliderSet.raw.coCastCollider(this.handle,s,t.handle,a,n,g,o));return s.free(),a.free(),r}intersectsShape(A,t,i){let n=ce.intoRaw(t),g=en.intoRaw(i),o=A.intoRaw(),s=this.colliderSet.raw.coIntersectsShape(this.handle,o,n,g);return n.free(),g.free(),o.free(),s}contactShape(A,t,i,n){let g=ce.intoRaw(t),o=en.intoRaw(i),s=A.intoRaw(),a=hf.fromRaw(this.colliderSet.raw.coContactShape(this.handle,s,g,o,n));return g.free(),o.free(),s.free(),a}contactCollider(A,t){return hf.fromRaw(this.colliderSet.raw.coContactCollider(this.handle,A.handle,t))}castRay(A,t,i){let n=ce.intoRaw(A.origin),g=ce.intoRaw(A.dir),o=this.colliderSet.raw.coCastRay(this.handle,n,g,t,i);return n.free(),g.free(),o}castRayAndGetNormal(A,t,i){let n=ce.intoRaw(A.origin),g=ce.intoRaw(A.dir),o=Uw.fromRaw(this.colliderSet.raw.coCastRayAndGetNormal(this.handle,n,g,t,i));return n.free(),g.free(),o}}(function(e){e[e.Density=0]="Density",e[e.Mass=1]="Mass",e[e.MassProps=2]="MassProps"})(Mu||(Mu={}));class Ko{constructor(A){this.enabled=!0,this.shape=A,this.massPropsMode=Mu.Density,this.density=1,this.friction=.5,this.restitution=0,this.rotation=en.identity(),this.translation=ce.zeros(),this.isSensor=!1,this.collisionGroups=4294967295,this.solverGroups=4294967295,this.frictionCombineRule=_S.Average,this.restitutionCombineRule=_S.Average,this.activeCollisionTypes=wN.DEFAULT,this.activeEvents=ME.NONE,this.activeHooks=SN.NONE,this.mass=0,this.centerOfMass=ce.zeros(),this.contactForceEventThreshold=0,this.contactSkin=0,this.principalAngularInertia=ce.zeros(),this.angularInertiaLocalFrame=en.identity()}static ball(A){const t=new px(A);return new Ko(t)}static capsule(A,t){const i=new Dx(A,t);return new Ko(i)}static segment(A,t){const i=new mx(A,t);return new Ko(i)}static triangle(A,t,i){const n=new Sx(A,t,i);return new Ko(n)}static roundTriangle(A,t,i,n){const g=new wx(A,t,i,n);return new Ko(g)}static polyline(A,t){const i=new kx(A,t);return new Ko(i)}static trimesh(A,t,i){const n=new Mx(A,t,i);return new Ko(n)}static cuboid(A,t,i){const n=new fx(A,t,i);return new Ko(n)}static roundCuboid(A,t,i,n){const g=new yx(A,t,i,n);return new Ko(g)}static heightfield(A,t,i,n,g){const o=new Nx(A,t,i,n,g);return new Ko(o)}static cylinder(A,t){const i=new Rx(A,t);return new Ko(i)}static roundCylinder(A,t,i){const n=new Gx(A,t,i);return new Ko(n)}static cone(A,t){const i=new bx(A,t);return new Ko(i)}static roundCone(A,t,i){const n=new Ux(A,t,i);return new Ko(n)}static convexHull(A){const t=new kN(A,null);return new Ko(t)}static convexMesh(A,t){const i=new kN(A,t);return new Ko(i)}static roundConvexHull(A,t){const i=new MN(A,null,t);return new Ko(i)}static roundConvexMesh(A,t,i){const n=new MN(A,t,i);return new Ko(n)}setTranslation(A,t,i){if(typeof A!="number"||typeof t!="number"||typeof i!="number")throw TypeError("The translation components must be numbers.");return this.translation={x:A,y:t,z:i},this}setRotation(A){return en.copy(this.rotation,A),this}setSensor(A){return this.isSensor=A,this}setEnabled(A){return this.enabled=A,this}setContactSkin(A){return this.contactSkin=A,this}setDensity(A){return this.massPropsMode=Mu.Density,this.density=A,this}setMass(A){return this.massPropsMode=Mu.Mass,this.mass=A,this}setMassProperties(A,t,i,n){return this.massPropsMode=Mu.MassProps,this.mass=A,ce.copy(this.centerOfMass,t),ce.copy(this.principalAngularInertia,i),en.copy(this.angularInertiaLocalFrame,n),this}setRestitution(A){return this.restitution=A,this}setFriction(A){return this.friction=A,this}setFrictionCombineRule(A){return this.frictionCombineRule=A,this}setRestitutionCombineRule(A){return this.restitutionCombineRule=A,this}setCollisionGroups(A){return this.collisionGroups=A,this}setSolverGroups(A){return this.solverGroups=A,this}setActiveHooks(A){return this.activeHooks=A,this}setActiveEvents(A){return this.activeEvents=A,this}setActiveCollisionTypes(A){return this.activeCollisionTypes=A,this}setContactForceEventThreshold(A){return this.contactForceEventThreshold=A,this}}class wW{constructor(A){this.raw=A||new Do,this.map=new ux,A&&A.forEachColliderHandle(t=>{this.map.set(t,new v_(this,t,null))})}free(){this.raw&&this.raw.free(),this.raw=void 0,this.map&&this.map.clear(),this.map=void 0}castClosure(A){return t=>A?A(this.get(t)):void 0}finalizeDeserialization(A){this.map.forEach(t=>t.finalizeDeserialization(A))}createCollider(A,t,i){let n=i!=null&&i!=null;if(n&&isNaN(i))throw Error("Cannot create a collider with a parent rigid-body handle that is not a number.");let g=t.shape.intoRaw(),o=ce.intoRaw(t.translation),s=en.intoRaw(t.rotation),a=ce.intoRaw(t.centerOfMass),r=ce.intoRaw(t.principalAngularInertia),I=en.intoRaw(t.angularInertiaLocalFrame),c=this.raw.createCollider(t.enabled,g,o,s,t.massPropsMode,t.mass,a,r,I,t.density,t.friction,t.restitution,t.frictionCombineRule,t.restitutionCombineRule,t.isSensor,t.collisionGroups,t.solverGroups,t.activeCollisionTypes,t.activeHooks,t.activeEvents,t.contactForceEventThreshold,t.contactSkin,n,n?i:0,A.raw);g.free(),o.free(),s.free(),a.free(),r.free(),I.free();let l=n?A.get(i):null,B=new v_(this,c,l,t.shape);return this.map.set(c,B),B}remove(A,t,i,n){this.raw.remove(A,t.raw,i.raw,n),this.unmap(A)}unmap(A){this.map.delete(A)}get(A){return this.map.get(A)}len(){return this.map.len()}contains(A){return this.get(A)!=null}forEach(A){this.map.forEach(A)}getAll(){return this.map.getAll()}}function fse(e,A,t,i){return new(t||(t=Promise))(function(n,g){function o(r){try{a(i.next(r))}catch(I){g(I)}}function s(r){try{a(i.throw(r))}catch(I){g(I)}}function a(r){var I;r.done?n(r.value):(I=r.value,I instanceof t?I:new t(function(c){c(I)})).then(o,s)}a((i=i.apply(e,[])).next())})}for(var yse={byteLength:function(e){var A=RiA(e),t=A[0],i=A[1];return 3*(t+i)/4-i},toByteArray:function(e){var A,t,i=RiA(e),n=i[0],g=i[1],o=new Dse(function(r,I,c){return 3*(I+c)/4-c}(0,n,g)),s=0,a=g>0?n-4:n;for(t=0;t<a;t+=4)A=NC[e.charCodeAt(t)]<<18|NC[e.charCodeAt(t+1)]<<12|NC[e.charCodeAt(t+2)]<<6|NC[e.charCodeAt(t+3)],o[s++]=A>>16&255,o[s++]=A>>8&255,o[s++]=255&A;return g===2&&(A=NC[e.charCodeAt(t)]<<2|NC[e.charCodeAt(t+1)]>>4,o[s++]=255&A),g===1&&(A=NC[e.charCodeAt(t)]<<10|NC[e.charCodeAt(t+1)]<<4|NC[e.charCodeAt(t+2)]>>2,o[s++]=A>>8&255,o[s++]=255&A),o},fromByteArray:function(e){for(var A,t=e.length,i=t%3,n=[],g=16383,o=0,s=t-i;o<s;o+=g)n.push(Sse(e,o,o+g>s?s:o+g));return i===1?(A=e[t-1],n.push(Wl[A>>2]+Wl[A<<4&63]+"==")):i===2&&(A=(e[t-2]<<8)+e[t-1],n.push(Wl[A>>10]+Wl[A>>4&63]+Wl[A<<2&63]+"=")),n.join("")}},Wl=[],NC=[],Dse=typeof Uint8Array<"u"?Uint8Array:Array,$Y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Vy=0,mse=$Y.length;Vy<mse;++Vy)Wl[Vy]=$Y[Vy],NC[$Y.charCodeAt(Vy)]=Vy;function RiA(e){var A=e.length;if(A%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=e.indexOf("=");return t===-1&&(t=A),[t,t===A?0:4-t%4]}function Sse(e,A,t){for(var i,n,g=[],o=A;o<t;o+=3)i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),g.push(Wl[(n=i)>>18&63]+Wl[n>>12&63]+Wl[n>>6&63]+Wl[63&n]);return g.join("")}function CfA(){return fse(this,void 0,void 0,function*(){yield rfA(yse.toByteArray(" ").buffer)})}function cfA(){return function(){let e,A;try{const n=V.__wbindgen_add_to_stack_pointer(-16);V.version(n);var t=Aa().getInt32(n+0,!0),i=Aa().getInt32(n+4,!0);return e=t,A=i,efA(t,i)}finally{V.__wbindgen_add_to_stack_pointer(16),V.__wbindgen_export_1(e,A,1)}}()}NC[45]=62,NC[95]=63;var wse=Object.freeze({__proto__:null,version:cfA,Vector3:Pm,VectorOps:ce,Quaternion:D_,RotationOps:en,SdpMatrix3:zZ,SdpMatrix3Ops:m_,get RigidBodyType(){return xC},RigidBody:b_,RigidBodyDesc:TC,RigidBodySet:ZZ,IntegrationParameters:WZ,get JointType(){return $s},get MotorModel(){return S_},get JointAxesMask(){return w_},ImpulseJoint:rc,UnitImpulseJoint:dx,FixedImpulseJoint:VZ,RopeImpulseJoint:XZ,SpringImpulseJoint:$Z,PrismaticImpulseJoint:AW,RevoluteImpulseJoint:eW,GenericImpulseJoint:tW,SphericalImpulseJoint:iW,JointData:Hl,ImpulseJointSet:nW,MultibodyJoint:aQ,UnitMultibodyJoint:hx,FixedMultibodyJoint:gW,PrismaticMultibodyJoint:oW,RevoluteMultibodyJoint:sW,SphericalMultibodyJoint:aW,MultibodyJointSet:rW,get CoefficientCombineRule(){return _S},CCDSolver:IW,IslandManager:CW,BroadPhase:cW,NarrowPhase:lW,TempContactManifold:BW,Shape:Ns,get ShapeType(){return ns},get HeightFieldFlags(){return k_},get TriMeshFlags(){return M_},Ball:px,HalfSpace:EW,Cuboid:fx,RoundCuboid:yx,Capsule:Dx,Segment:mx,Triangle:Sx,RoundTriangle:wx,Polyline:kx,TriMesh:Mx,ConvexPolyhedron:kN,RoundConvexPolyhedron:MN,Heightfield:Nx,Cylinder:Rx,RoundCylinder:Gx,Cone:bx,RoundCone:Ux,get ActiveCollisionTypes(){return wN},Collider:v_,get MassPropsMode(){return Mu},ColliderDesc:Ko,ColliderSet:wW,get FeatureType(){return df},Ray:IfA,RayIntersection:Uw,RayColliderIntersection:LS,RayColliderHit:AG,PointProjection:bw,PointColliderProjection:JS,ShapeCastHit:ty,ColliderShapeCastHit:vw,ShapeContact:hf,World:eG,PhysicsPipeline:QW,SerializationPipeline:U_,get ActiveEvents(){return ME},TempContactForceEvent:mW,EventQueue:SW,get ActiveHooks(){return SN},get SolverFlags(){return G_},DebugRenderBuffers:dW,DebugRenderPipeline:hW,get QueryFilterFlags(){return N_},QueryPipeline:uW,init:CfA,CharacterCollision:pW,KinematicCharacterController:fW,get PidAxesMask(){return R_},PidController:yW,DynamicRayCastVehicleController:DW});const kse=Object.freeze(Object.defineProperty({__proto__:null,get ActiveCollisionTypes(){return wN},get ActiveEvents(){return ME},get ActiveHooks(){return SN},Ball:px,BroadPhase:cW,CCDSolver:IW,Capsule:Dx,CharacterCollision:pW,get CoefficientCombineRule(){return _S},Collider:v_,ColliderDesc:Ko,ColliderSet:wW,ColliderShapeCastHit:vw,Cone:bx,ConvexPolyhedron:kN,Cuboid:fx,Cylinder:Rx,DebugRenderBuffers:dW,DebugRenderPipeline:hW,DynamicRayCastVehicleController:DW,EventQueue:SW,get FeatureType(){return df},FixedImpulseJoint:VZ,FixedMultibodyJoint:gW,GenericImpulseJoint:tW,HalfSpace:EW,get HeightFieldFlags(){return k_},Heightfield:Nx,ImpulseJoint:rc,ImpulseJointSet:nW,IntegrationParameters:WZ,IslandManager:CW,get JointAxesMask(){return w_},JointData:Hl,get JointType(){return $s},KinematicCharacterController:fW,get MassPropsMode(){return Mu},get MotorModel(){return S_},MultibodyJoint:aQ,MultibodyJointSet:rW,NarrowPhase:lW,PhysicsPipeline:QW,get PidAxesMask(){return R_},PidController:yW,PointColliderProjection:JS,PointProjection:bw,Polyline:kx,PrismaticImpulseJoint:AW,PrismaticMultibodyJoint:oW,Quaternion:D_,get QueryFilterFlags(){return N_},QueryPipeline:uW,Ray:IfA,RayColliderHit:AG,RayColliderIntersection:LS,RayIntersection:Uw,RevoluteImpulseJoint:eW,RevoluteMultibodyJoint:sW,RigidBody:b_,RigidBodyDesc:TC,RigidBodySet:ZZ,get RigidBodyType(){return xC},RopeImpulseJoint:XZ,RotationOps:en,RoundCone:Ux,RoundConvexPolyhedron:MN,RoundCuboid:yx,RoundCylinder:Gx,RoundTriangle:wx,SdpMatrix3:zZ,SdpMatrix3Ops:m_,Segment:mx,SerializationPipeline:U_,Shape:Ns,ShapeCastHit:ty,ShapeContact:hf,get ShapeType(){return ns},get SolverFlags(){return G_},SphericalImpulseJoint:iW,SphericalMultibodyJoint:aW,SpringImpulseJoint:$Z,TempContactForceEvent:mW,TempContactManifold:BW,TriMesh:Mx,get TriMeshFlags(){return M_},Triangle:Sx,UnitImpulseJoint:dx,UnitMultibodyJoint:hx,Vector3:Pm,VectorOps:ce,World:eG,default:wse,init:CfA,version:cfA},Symbol.toStringTag,{value:"Module"}));var lfA={exports:{}},Ld={};/**
 * @license React
 * react-reconciler-constants.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */Ld.ConcurrentRoot=1;Ld.ContinuousEventPriority=8;Ld.DefaultEventPriority=32;Ld.DiscreteEventPriority=2;Ld.IdleEventPriority=268435456;Ld.LegacyRoot=0;Ld.NoEventPriority=0;lfA.exports=Ld;var bK=lfA.exports;/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */const tG="180",Mse={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Nse={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},BfA=0,t4=1,EfA=2,Rse=3,QfA=0,vx=1,yM=2,Gc=3,tl=0,Ua=1,AI=2,TE=0,Yp=1,io=2,i4=3,n4=4,ufA=5,ru=100,dfA=101,hfA=102,pfA=103,ffA=104,yfA=200,DfA=201,mfA=202,SfA=203,K_=204,F_=205,wfA=206,kfA=207,MfA=208,NfA=209,RfA=210,GfA=211,bfA=212,UfA=213,vfA=214,__=0,J_=1,L_=2,pf=3,x_=4,T_=5,q_=6,Y_=7,iG=0,KfA=1,FfA=2,QB=0,_fA=1,JfA=2,LfA=3,iy=4,xfA=5,TfA=6,qfA=7,g4="attached",YfA="detached",Kx=300,rQ=301,ud=302,NN=303,RN=304,Kw=306,Fr=1e3,oI=1001,ff=1002,Ss=1003,nG=1004,Gse=1004,Nu=1005,bse=1005,qg=1006,Hp=1007,Use=1007,Gr=1008,vse=1008,Ic=1009,kW=1010,MW=1011,xS=1012,Fx=1013,IQ=1014,br=1015,ny=1016,_x=1017,Jx=1018,TS=1020,NW=35902,RW=35899,GW=1021,bW=1022,Ar=1023,qS=1026,YS=1027,Lx=1028,gG=1029,UW=1030,xx=1031,Kse=1032,Tx=1033,DM=33776,mM=33777,SM=33778,wM=33779,H_=35840,O_=35841,P_=35842,j_=35843,z_=36196,Z_=37492,W_=37496,V_=37808,X_=37809,$_=37810,AJ=37811,eJ=37812,tJ=37813,iJ=37814,nJ=37815,gJ=37816,oJ=37817,sJ=37818,aJ=37819,rJ=37820,IJ=37821,CJ=36492,cJ=36494,lJ=36495,BJ=36283,EJ=36284,QJ=36285,uJ=36286,vW=2200,dJ=2201,HfA=2202,yf=2300,dd=2301,UK=2302,lp=2400,Bp=2401,GN=2402,qx=2500,KW=2501,FW=0,oG=1,Df=2,OfA=3200,PfA=3201,Fse=3202,_se=3203,xd=0,jfA=1,DE="",rn="srgb",Ka="srgb-linear",bN="linear",mg="srgb",Jse=0,Xh=7680,Lse=7681,xse=7682,Tse=7683,qse=34055,Yse=34056,Hse=5386,Ose=512,Pse=513,jse=514,zse=515,Zse=516,Wse=517,Vse=518,o4=519,zfA=512,ZfA=513,WfA=514,_W=515,VfA=516,XfA=517,$fA=518,AyA=519,UN=35044,eyA=35048,Xse=35040,$se=35045,Aae=35049,eae=35041,tae=35046,iae=35050,nae=35042,gae="100",s4="300 es",jI=2e3,HS=2001,oae={COMPUTE:"compute",RENDER:"render"},sae={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},aae={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"};class bB{addEventListener(A,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[A]===void 0&&(i[A]=[]),i[A].indexOf(t)===-1&&i[A].push(t)}hasEventListener(A,t){const i=this._listeners;return i===void 0?!1:i[A]!==void 0&&i[A].indexOf(t)!==-1}removeEventListener(A,t){const i=this._listeners;if(i===void 0)return;const n=i[A];if(n!==void 0){const g=n.indexOf(t);g!==-1&&n.splice(g,1)}}dispatchEvent(A){const t=this._listeners;if(t===void 0)return;const i=t[A.type];if(i!==void 0){A.target=this;const n=i.slice(0);for(let g=0,o=n.length;g<o;g++)n[g].call(this,A);A.target=null}}}const Pa=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let GiA=1234567;const Op=Math.PI/180,OS=180/Math.PI;function $I(){const e=Math.random()*4294967295|0,A=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Pa[e&255]+Pa[e>>8&255]+Pa[e>>16&255]+Pa[e>>24&255]+"-"+Pa[A&255]+Pa[A>>8&255]+"-"+Pa[A>>16&15|64]+Pa[A>>24&255]+"-"+Pa[t&63|128]+Pa[t>>8&255]+"-"+Pa[t>>16&255]+Pa[t>>24&255]+Pa[i&255]+Pa[i>>8&255]+Pa[i>>16&255]+Pa[i>>24&255]).toLowerCase()}function Fi(e,A,t){return Math.max(A,Math.min(t,e))}function JW(e,A){return(e%A+A)%A}function rae(e,A,t,i,n){return i+(e-A)*(n-i)/(t-A)}function Iae(e,A,t){return e!==A?(t-e)/(A-e):0}function kM(e,A,t){return(1-t)*e+t*A}function Cae(e,A,t,i){return kM(e,A,1-Math.exp(-t*i))}function cae(e,A=1){return A-Math.abs(JW(e,A*2)-A)}function lae(e,A,t){return e<=A?0:e>=t?1:(e=(e-A)/(t-A),e*e*(3-2*e))}function Bae(e,A,t){return e<=A?0:e>=t?1:(e=(e-A)/(t-A),e*e*e*(e*(e*6-15)+10))}function Eae(e,A){return e+Math.floor(Math.random()*(A-e+1))}function Qae(e,A){return e+Math.random()*(A-e)}function uae(e){return e*(.5-Math.random())}function dae(e){e!==void 0&&(GiA=e);let A=GiA+=1831565813;return A=Math.imul(A^A>>>15,A|1),A^=A+Math.imul(A^A>>>7,A|61),((A^A>>>14)>>>0)/4294967296}function hae(e){return e*Op}function pae(e){return e*OS}function fae(e){return(e&e-1)===0&&e!==0}function yae(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))}function Dae(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function mae(e,A,t,i,n){const g=Math.cos,o=Math.sin,s=g(t/2),a=o(t/2),r=g((A+i)/2),I=o((A+i)/2),c=g((A-i)/2),l=o((A-i)/2),B=g((i-A)/2),Q=o((i-A)/2);switch(n){case"XYX":e.set(s*I,a*c,a*l,s*r);break;case"YZY":e.set(a*l,s*I,a*c,s*r);break;case"ZXZ":e.set(a*c,a*l,s*I,s*r);break;case"XZX":e.set(s*I,a*Q,a*B,s*r);break;case"YXY":e.set(a*B,s*I,a*Q,s*r);break;case"ZYZ":e.set(a*Q,a*B,s*I,s*r);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function wr(e,A){switch(A.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function an(e,A){switch(A.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw new Error("Invalid component type.")}}const VC={DEG2RAD:Op,RAD2DEG:OS,generateUUID:$I,clamp:Fi,euclideanModulo:JW,mapLinear:rae,inverseLerp:Iae,lerp:kM,damp:Cae,pingpong:cae,smoothstep:lae,smootherstep:Bae,randInt:Eae,randFloat:Qae,randFloatSpread:uae,seededRandom:dae,degToRad:hae,radToDeg:pae,isPowerOfTwo:fae,ceilPowerOfTwo:yae,floorPowerOfTwo:Dae,setQuaternionFromProperEuler:mae,normalize:an,denormalize:wr};class lt{constructor(A=0,t=0){lt.prototype.isVector2=!0,this.x=A,this.y=t}get width(){return this.x}set width(A){this.x=A}get height(){return this.y}set height(A){this.y=A}set(A,t){return this.x=A,this.y=t,this}setScalar(A){return this.x=A,this.y=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setComponent(A,t){switch(A){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y)}copy(A){return this.x=A.x,this.y=A.y,this}add(A){return this.x+=A.x,this.y+=A.y,this}addScalar(A){return this.x+=A,this.y+=A,this}addVectors(A,t){return this.x=A.x+t.x,this.y=A.y+t.y,this}addScaledVector(A,t){return this.x+=A.x*t,this.y+=A.y*t,this}sub(A){return this.x-=A.x,this.y-=A.y,this}subScalar(A){return this.x-=A,this.y-=A,this}subVectors(A,t){return this.x=A.x-t.x,this.y=A.y-t.y,this}multiply(A){return this.x*=A.x,this.y*=A.y,this}multiplyScalar(A){return this.x*=A,this.y*=A,this}divide(A){return this.x/=A.x,this.y/=A.y,this}divideScalar(A){return this.multiplyScalar(1/A)}applyMatrix3(A){const t=this.x,i=this.y,n=A.elements;return this.x=n[0]*t+n[3]*i+n[6],this.y=n[1]*t+n[4]*i+n[7],this}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this}clamp(A,t){return this.x=Fi(this.x,A.x,t.x),this.y=Fi(this.y,A.y,t.y),this}clampScalar(A,t){return this.x=Fi(this.x,A,t),this.y=Fi(this.y,A,t),this}clampLength(A,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Fi(i,A,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(A){return this.x*A.x+this.y*A.y}cross(A){return this.x*A.y-this.y*A.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(A){const t=Math.sqrt(this.lengthSq()*A.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(A)/t;return Math.acos(Fi(i,-1,1))}distanceTo(A){return Math.sqrt(this.distanceToSquared(A))}distanceToSquared(A){const t=this.x-A.x,i=this.y-A.y;return t*t+i*i}manhattanDistanceTo(A){return Math.abs(this.x-A.x)+Math.abs(this.y-A.y)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,t){return this.x+=(A.x-this.x)*t,this.y+=(A.y-this.y)*t,this}lerpVectors(A,t,i){return this.x=A.x+(t.x-A.x)*i,this.y=A.y+(t.y-A.y)*i,this}equals(A){return A.x===this.x&&A.y===this.y}fromArray(A,t=0){return this.x=A[t],this.y=A[t+1],this}toArray(A=[],t=0){return A[t]=this.x,A[t+1]=this.y,A}fromBufferAttribute(A,t){return this.x=A.getX(t),this.y=A.getY(t),this}rotateAround(A,t){const i=Math.cos(t),n=Math.sin(t),g=this.x-A.x,o=this.y-A.y;return this.x=g*i-o*n+A.x,this.y=g*n+o*i+A.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class oo{constructor(A=0,t=0,i=0,n=1){this.isQuaternion=!0,this._x=A,this._y=t,this._z=i,this._w=n}static slerpFlat(A,t,i,n,g,o,s){let a=i[n+0],r=i[n+1],I=i[n+2],c=i[n+3];const l=g[o+0],B=g[o+1],Q=g[o+2],h=g[o+3];if(s===0){A[t+0]=a,A[t+1]=r,A[t+2]=I,A[t+3]=c;return}if(s===1){A[t+0]=l,A[t+1]=B,A[t+2]=Q,A[t+3]=h;return}if(c!==h||a!==l||r!==B||I!==Q){let d=1-s;const p=a*l+r*B+I*Q+c*h,y=p>=0?1:-1,m=1-p*p;if(m>Number.EPSILON){const S=Math.sqrt(m),k=Math.atan2(S,p*y);d=Math.sin(d*k)/S,s=Math.sin(s*k)/S}const D=s*y;if(a=a*d+l*D,r=r*d+B*D,I=I*d+Q*D,c=c*d+h*D,d===1-s){const S=1/Math.sqrt(a*a+r*r+I*I+c*c);a*=S,r*=S,I*=S,c*=S}}A[t]=a,A[t+1]=r,A[t+2]=I,A[t+3]=c}static multiplyQuaternionsFlat(A,t,i,n,g,o){const s=i[n],a=i[n+1],r=i[n+2],I=i[n+3],c=g[o],l=g[o+1],B=g[o+2],Q=g[o+3];return A[t]=s*Q+I*c+a*B-r*l,A[t+1]=a*Q+I*l+r*c-s*B,A[t+2]=r*Q+I*B+s*l-a*c,A[t+3]=I*Q-s*c-a*l-r*B,A}get x(){return this._x}set x(A){this._x=A,this._onChangeCallback()}get y(){return this._y}set y(A){this._y=A,this._onChangeCallback()}get z(){return this._z}set z(A){this._z=A,this._onChangeCallback()}get w(){return this._w}set w(A){this._w=A,this._onChangeCallback()}set(A,t,i,n){return this._x=A,this._y=t,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(A){return this._x=A.x,this._y=A.y,this._z=A.z,this._w=A.w,this._onChangeCallback(),this}setFromEuler(A,t=!0){const i=A._x,n=A._y,g=A._z,o=A._order,s=Math.cos,a=Math.sin,r=s(i/2),I=s(n/2),c=s(g/2),l=a(i/2),B=a(n/2),Q=a(g/2);switch(o){case"XYZ":this._x=l*I*c+r*B*Q,this._y=r*B*c-l*I*Q,this._z=r*I*Q+l*B*c,this._w=r*I*c-l*B*Q;break;case"YXZ":this._x=l*I*c+r*B*Q,this._y=r*B*c-l*I*Q,this._z=r*I*Q-l*B*c,this._w=r*I*c+l*B*Q;break;case"ZXY":this._x=l*I*c-r*B*Q,this._y=r*B*c+l*I*Q,this._z=r*I*Q+l*B*c,this._w=r*I*c-l*B*Q;break;case"ZYX":this._x=l*I*c-r*B*Q,this._y=r*B*c+l*I*Q,this._z=r*I*Q-l*B*c,this._w=r*I*c+l*B*Q;break;case"YZX":this._x=l*I*c+r*B*Q,this._y=r*B*c+l*I*Q,this._z=r*I*Q-l*B*c,this._w=r*I*c-l*B*Q;break;case"XZY":this._x=l*I*c-r*B*Q,this._y=r*B*c-l*I*Q,this._z=r*I*Q+l*B*c,this._w=r*I*c+l*B*Q;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(A,t){const i=t/2,n=Math.sin(i);return this._x=A.x*n,this._y=A.y*n,this._z=A.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(A){const t=A.elements,i=t[0],n=t[4],g=t[8],o=t[1],s=t[5],a=t[9],r=t[2],I=t[6],c=t[10],l=i+s+c;if(l>0){const B=.5/Math.sqrt(l+1);this._w=.25/B,this._x=(I-a)*B,this._y=(g-r)*B,this._z=(o-n)*B}else if(i>s&&i>c){const B=2*Math.sqrt(1+i-s-c);this._w=(I-a)/B,this._x=.25*B,this._y=(n+o)/B,this._z=(g+r)/B}else if(s>c){const B=2*Math.sqrt(1+s-i-c);this._w=(g-r)/B,this._x=(n+o)/B,this._y=.25*B,this._z=(a+I)/B}else{const B=2*Math.sqrt(1+c-i-s);this._w=(o-n)/B,this._x=(g+r)/B,this._y=(a+I)/B,this._z=.25*B}return this._onChangeCallback(),this}setFromUnitVectors(A,t){let i=A.dot(t)+1;return i<1e-8?(i=0,Math.abs(A.x)>Math.abs(A.z)?(this._x=-A.y,this._y=A.x,this._z=0,this._w=i):(this._x=0,this._y=-A.z,this._z=A.y,this._w=i)):(this._x=A.y*t.z-A.z*t.y,this._y=A.z*t.x-A.x*t.z,this._z=A.x*t.y-A.y*t.x,this._w=i),this.normalize()}angleTo(A){return 2*Math.acos(Math.abs(Fi(this.dot(A),-1,1)))}rotateTowards(A,t){const i=this.angleTo(A);if(i===0)return this;const n=Math.min(1,t/i);return this.slerp(A,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(A){return this._x*A._x+this._y*A._y+this._z*A._z+this._w*A._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let A=this.length();return A===0?(this._x=0,this._y=0,this._z=0,this._w=1):(A=1/A,this._x=this._x*A,this._y=this._y*A,this._z=this._z*A,this._w=this._w*A),this._onChangeCallback(),this}multiply(A){return this.multiplyQuaternions(this,A)}premultiply(A){return this.multiplyQuaternions(A,this)}multiplyQuaternions(A,t){const i=A._x,n=A._y,g=A._z,o=A._w,s=t._x,a=t._y,r=t._z,I=t._w;return this._x=i*I+o*s+n*r-g*a,this._y=n*I+o*a+g*s-i*r,this._z=g*I+o*r+i*a-n*s,this._w=o*I-i*s-n*a-g*r,this._onChangeCallback(),this}slerp(A,t){if(t===0)return this;if(t===1)return this.copy(A);const i=this._x,n=this._y,g=this._z,o=this._w;let s=o*A._w+i*A._x+n*A._y+g*A._z;if(s<0?(this._w=-A._w,this._x=-A._x,this._y=-A._y,this._z=-A._z,s=-s):this.copy(A),s>=1)return this._w=o,this._x=i,this._y=n,this._z=g,this;const a=1-s*s;if(a<=Number.EPSILON){const B=1-t;return this._w=B*o+t*this._w,this._x=B*i+t*this._x,this._y=B*n+t*this._y,this._z=B*g+t*this._z,this.normalize(),this}const r=Math.sqrt(a),I=Math.atan2(r,s),c=Math.sin((1-t)*I)/r,l=Math.sin(t*I)/r;return this._w=o*c+this._w*l,this._x=i*c+this._x*l,this._y=n*c+this._y*l,this._z=g*c+this._z*l,this._onChangeCallback(),this}slerpQuaternions(A,t,i){return this.copy(A).slerp(t,i)}random(){const A=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),n=Math.sqrt(1-i),g=Math.sqrt(i);return this.set(n*Math.sin(A),n*Math.cos(A),g*Math.sin(t),g*Math.cos(t))}equals(A){return A._x===this._x&&A._y===this._y&&A._z===this._z&&A._w===this._w}fromArray(A,t=0){return this._x=A[t],this._y=A[t+1],this._z=A[t+2],this._w=A[t+3],this._onChangeCallback(),this}toArray(A=[],t=0){return A[t]=this._x,A[t+1]=this._y,A[t+2]=this._z,A[t+3]=this._w,A}fromBufferAttribute(A,t){return this._x=A.getX(t),this._y=A.getY(t),this._z=A.getZ(t),this._w=A.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(A){return this._onChangeCallback=A,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class SA{constructor(A=0,t=0,i=0){SA.prototype.isVector3=!0,this.x=A,this.y=t,this.z=i}set(A,t,i){return i===void 0&&(i=this.z),this.x=A,this.y=t,this.z=i,this}setScalar(A){return this.x=A,this.y=A,this.z=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setZ(A){return this.z=A,this}setComponent(A,t){switch(A){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(A){return this.x=A.x,this.y=A.y,this.z=A.z,this}add(A){return this.x+=A.x,this.y+=A.y,this.z+=A.z,this}addScalar(A){return this.x+=A,this.y+=A,this.z+=A,this}addVectors(A,t){return this.x=A.x+t.x,this.y=A.y+t.y,this.z=A.z+t.z,this}addScaledVector(A,t){return this.x+=A.x*t,this.y+=A.y*t,this.z+=A.z*t,this}sub(A){return this.x-=A.x,this.y-=A.y,this.z-=A.z,this}subScalar(A){return this.x-=A,this.y-=A,this.z-=A,this}subVectors(A,t){return this.x=A.x-t.x,this.y=A.y-t.y,this.z=A.z-t.z,this}multiply(A){return this.x*=A.x,this.y*=A.y,this.z*=A.z,this}multiplyScalar(A){return this.x*=A,this.y*=A,this.z*=A,this}multiplyVectors(A,t){return this.x=A.x*t.x,this.y=A.y*t.y,this.z=A.z*t.z,this}applyEuler(A){return this.applyQuaternion(biA.setFromEuler(A))}applyAxisAngle(A,t){return this.applyQuaternion(biA.setFromAxisAngle(A,t))}applyMatrix3(A){const t=this.x,i=this.y,n=this.z,g=A.elements;return this.x=g[0]*t+g[3]*i+g[6]*n,this.y=g[1]*t+g[4]*i+g[7]*n,this.z=g[2]*t+g[5]*i+g[8]*n,this}applyNormalMatrix(A){return this.applyMatrix3(A).normalize()}applyMatrix4(A){const t=this.x,i=this.y,n=this.z,g=A.elements,o=1/(g[3]*t+g[7]*i+g[11]*n+g[15]);return this.x=(g[0]*t+g[4]*i+g[8]*n+g[12])*o,this.y=(g[1]*t+g[5]*i+g[9]*n+g[13])*o,this.z=(g[2]*t+g[6]*i+g[10]*n+g[14])*o,this}applyQuaternion(A){const t=this.x,i=this.y,n=this.z,g=A.x,o=A.y,s=A.z,a=A.w,r=2*(o*n-s*i),I=2*(s*t-g*n),c=2*(g*i-o*t);return this.x=t+a*r+o*c-s*I,this.y=i+a*I+s*r-g*c,this.z=n+a*c+g*I-o*r,this}project(A){return this.applyMatrix4(A.matrixWorldInverse).applyMatrix4(A.projectionMatrix)}unproject(A){return this.applyMatrix4(A.projectionMatrixInverse).applyMatrix4(A.matrixWorld)}transformDirection(A){const t=this.x,i=this.y,n=this.z,g=A.elements;return this.x=g[0]*t+g[4]*i+g[8]*n,this.y=g[1]*t+g[5]*i+g[9]*n,this.z=g[2]*t+g[6]*i+g[10]*n,this.normalize()}divide(A){return this.x/=A.x,this.y/=A.y,this.z/=A.z,this}divideScalar(A){return this.multiplyScalar(1/A)}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this.z=Math.min(this.z,A.z),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this.z=Math.max(this.z,A.z),this}clamp(A,t){return this.x=Fi(this.x,A.x,t.x),this.y=Fi(this.y,A.y,t.y),this.z=Fi(this.z,A.z,t.z),this}clampScalar(A,t){return this.x=Fi(this.x,A,t),this.y=Fi(this.y,A,t),this.z=Fi(this.z,A,t),this}clampLength(A,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Fi(i,A,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(A){return this.x*A.x+this.y*A.y+this.z*A.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,t){return this.x+=(A.x-this.x)*t,this.y+=(A.y-this.y)*t,this.z+=(A.z-this.z)*t,this}lerpVectors(A,t,i){return this.x=A.x+(t.x-A.x)*i,this.y=A.y+(t.y-A.y)*i,this.z=A.z+(t.z-A.z)*i,this}cross(A){return this.crossVectors(this,A)}crossVectors(A,t){const i=A.x,n=A.y,g=A.z,o=t.x,s=t.y,a=t.z;return this.x=n*a-g*s,this.y=g*o-i*a,this.z=i*s-n*o,this}projectOnVector(A){const t=A.lengthSq();if(t===0)return this.set(0,0,0);const i=A.dot(this)/t;return this.copy(A).multiplyScalar(i)}projectOnPlane(A){return AH.copy(this).projectOnVector(A),this.sub(AH)}reflect(A){return this.sub(AH.copy(A).multiplyScalar(2*this.dot(A)))}angleTo(A){const t=Math.sqrt(this.lengthSq()*A.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(A)/t;return Math.acos(Fi(i,-1,1))}distanceTo(A){return Math.sqrt(this.distanceToSquared(A))}distanceToSquared(A){const t=this.x-A.x,i=this.y-A.y,n=this.z-A.z;return t*t+i*i+n*n}manhattanDistanceTo(A){return Math.abs(this.x-A.x)+Math.abs(this.y-A.y)+Math.abs(this.z-A.z)}setFromSpherical(A){return this.setFromSphericalCoords(A.radius,A.phi,A.theta)}setFromSphericalCoords(A,t,i){const n=Math.sin(t)*A;return this.x=n*Math.sin(i),this.y=Math.cos(t)*A,this.z=n*Math.cos(i),this}setFromCylindrical(A){return this.setFromCylindricalCoords(A.radius,A.theta,A.y)}setFromCylindricalCoords(A,t,i){return this.x=A*Math.sin(t),this.y=i,this.z=A*Math.cos(t),this}setFromMatrixPosition(A){const t=A.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(A){const t=this.setFromMatrixColumn(A,0).length(),i=this.setFromMatrixColumn(A,1).length(),n=this.setFromMatrixColumn(A,2).length();return this.x=t,this.y=i,this.z=n,this}setFromMatrixColumn(A,t){return this.fromArray(A.elements,t*4)}setFromMatrix3Column(A,t){return this.fromArray(A.elements,t*3)}setFromEuler(A){return this.x=A._x,this.y=A._y,this.z=A._z,this}setFromColor(A){return this.x=A.r,this.y=A.g,this.z=A.b,this}equals(A){return A.x===this.x&&A.y===this.y&&A.z===this.z}fromArray(A,t=0){return this.x=A[t],this.y=A[t+1],this.z=A[t+2],this}toArray(A=[],t=0){return A[t]=this.x,A[t+1]=this.y,A[t+2]=this.z,A}fromBufferAttribute(A,t){return this.x=A.getX(t),this.y=A.getY(t),this.z=A.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const A=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(A),this.y=t,this.z=i*Math.sin(A),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const AH=new SA,biA=new oo;class An{constructor(A,t,i,n,g,o,s,a,r){An.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],A!==void 0&&this.set(A,t,i,n,g,o,s,a,r)}set(A,t,i,n,g,o,s,a,r){const I=this.elements;return I[0]=A,I[1]=n,I[2]=s,I[3]=t,I[4]=g,I[5]=a,I[6]=i,I[7]=o,I[8]=r,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(A){const t=this.elements,i=A.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(A,t,i){return A.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(A){const t=A.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(A){return this.multiplyMatrices(this,A)}premultiply(A){return this.multiplyMatrices(A,this)}multiplyMatrices(A,t){const i=A.elements,n=t.elements,g=this.elements,o=i[0],s=i[3],a=i[6],r=i[1],I=i[4],c=i[7],l=i[2],B=i[5],Q=i[8],h=n[0],d=n[3],p=n[6],y=n[1],m=n[4],D=n[7],S=n[2],k=n[5],N=n[8];return g[0]=o*h+s*y+a*S,g[3]=o*d+s*m+a*k,g[6]=o*p+s*D+a*N,g[1]=r*h+I*y+c*S,g[4]=r*d+I*m+c*k,g[7]=r*p+I*D+c*N,g[2]=l*h+B*y+Q*S,g[5]=l*d+B*m+Q*k,g[8]=l*p+B*D+Q*N,this}multiplyScalar(A){const t=this.elements;return t[0]*=A,t[3]*=A,t[6]*=A,t[1]*=A,t[4]*=A,t[7]*=A,t[2]*=A,t[5]*=A,t[8]*=A,this}determinant(){const A=this.elements,t=A[0],i=A[1],n=A[2],g=A[3],o=A[4],s=A[5],a=A[6],r=A[7],I=A[8];return t*o*I-t*s*r-i*g*I+i*s*a+n*g*r-n*o*a}invert(){const A=this.elements,t=A[0],i=A[1],n=A[2],g=A[3],o=A[4],s=A[5],a=A[6],r=A[7],I=A[8],c=I*o-s*r,l=s*a-I*g,B=r*g-o*a,Q=t*c+i*l+n*B;if(Q===0)return this.set(0,0,0,0,0,0,0,0,0);const h=1/Q;return A[0]=c*h,A[1]=(n*r-I*i)*h,A[2]=(s*i-n*o)*h,A[3]=l*h,A[4]=(I*t-n*a)*h,A[5]=(n*g-s*t)*h,A[6]=B*h,A[7]=(i*a-r*t)*h,A[8]=(o*t-i*g)*h,this}transpose(){let A;const t=this.elements;return A=t[1],t[1]=t[3],t[3]=A,A=t[2],t[2]=t[6],t[6]=A,A=t[5],t[5]=t[7],t[7]=A,this}getNormalMatrix(A){return this.setFromMatrix4(A).invert().transpose()}transposeIntoArray(A){const t=this.elements;return A[0]=t[0],A[1]=t[3],A[2]=t[6],A[3]=t[1],A[4]=t[4],A[5]=t[7],A[6]=t[2],A[7]=t[5],A[8]=t[8],this}setUvTransform(A,t,i,n,g,o,s){const a=Math.cos(g),r=Math.sin(g);return this.set(i*a,i*r,-i*(a*o+r*s)+o+A,-n*r,n*a,-n*(-r*o+a*s)+s+t,0,0,1),this}scale(A,t){return this.premultiply(eH.makeScale(A,t)),this}rotate(A){return this.premultiply(eH.makeRotation(-A)),this}translate(A,t){return this.premultiply(eH.makeTranslation(A,t)),this}makeTranslation(A,t){return A.isVector2?this.set(1,0,A.x,0,1,A.y,0,0,1):this.set(1,0,A,0,1,t,0,0,1),this}makeRotation(A){const t=Math.cos(A),i=Math.sin(A);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(A,t){return this.set(A,0,0,0,t,0,0,0,1),this}equals(A){const t=this.elements,i=A.elements;for(let n=0;n<9;n++)if(t[n]!==i[n])return!1;return!0}fromArray(A,t=0){for(let i=0;i<9;i++)this.elements[i]=A[i+t];return this}toArray(A=[],t=0){const i=this.elements;return A[t]=i[0],A[t+1]=i[1],A[t+2]=i[2],A[t+3]=i[3],A[t+4]=i[4],A[t+5]=i[5],A[t+6]=i[6],A[t+7]=i[7],A[t+8]=i[8],A}clone(){return new this.constructor().fromArray(this.elements)}}const eH=new An;function tyA(e){for(let A=e.length-1;A>=0;--A)if(e[A]>=65535)return!0;return!1}const Sae={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function am(e,A){return new Sae[e](A)}function vN(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function iyA(){const e=vN("canvas");return e.style.display="block",e}const UiA={};function KN(e){e in UiA||(UiA[e]=!0,console.warn(e))}function wae(e,A,t){return new Promise(function(i,n){function g(){switch(e.clientWaitSync(A,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:n();break;case e.TIMEOUT_EXPIRED:setTimeout(g,t);break;default:i()}}setTimeout(g,t)})}const viA=new An().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),KiA=new An().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function kae(){const e={enabled:!0,workingColorSpace:Ka,spaces:{},convert:function(n,g,o){return this.enabled===!1||g===o||!g||!o||(this.spaces[g].transfer===mg&&(n.r=qE(n.r),n.g=qE(n.g),n.b=qE(n.b)),this.spaces[g].primaries!==this.spaces[o].primaries&&(n.applyMatrix3(this.spaces[g].toXYZ),n.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===mg&&(n.r=jm(n.r),n.g=jm(n.g),n.b=jm(n.b))),n},workingToColorSpace:function(n,g){return this.convert(n,this.workingColorSpace,g)},colorSpaceToWorking:function(n,g){return this.convert(n,g,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===DE?bN:this.spaces[n].transfer},getToneMappingMode:function(n){return this.spaces[n].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(n,g=this.workingColorSpace){return n.fromArray(this.spaces[g].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,g,o){return n.copy(this.spaces[g].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(n,g){return KN("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(n,g)},toWorkingColorSpace:function(n,g){return KN("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(n,g)}},A=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[Ka]:{primaries:A,whitePoint:i,transfer:bN,toXYZ:viA,fromXYZ:KiA,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:rn},outputColorSpaceConfig:{drawingBufferColorSpace:rn}},[rn]:{primaries:A,whitePoint:i,transfer:mg,toXYZ:viA,fromXYZ:KiA,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:rn}}}),e}const Un=kae();function qE(e){return e<.04045?e*.0773993808:Math.pow(e*.9478672986+.0521327014,2.4)}function jm(e){return e<.0031308?e*12.92:1.055*Math.pow(e,.41666)-.055}let Xy;class nyA{static getDataURL(A,t="image/png"){if(/^data:/i.test(A.src)||typeof HTMLCanvasElement>"u")return A.src;let i;if(A instanceof HTMLCanvasElement)i=A;else{Xy===void 0&&(Xy=vN("canvas")),Xy.width=A.width,Xy.height=A.height;const n=Xy.getContext("2d");A instanceof ImageData?n.putImageData(A,0,0):n.drawImage(A,0,0,A.width,A.height),i=Xy}return i.toDataURL(t)}static sRGBToLinear(A){if(typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&A instanceof ImageBitmap){const t=vN("canvas");t.width=A.width,t.height=A.height;const i=t.getContext("2d");i.drawImage(A,0,0,A.width,A.height);const n=i.getImageData(0,0,A.width,A.height),g=n.data;for(let o=0;o<g.length;o++)g[o]=qE(g[o]/255)*255;return i.putImageData(n,0,0),t}else if(A.data){const t=A.data.slice(0);for(let i=0;i<t.length;i++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[i]=Math.floor(qE(t[i]/255)*255):t[i]=qE(t[i]);return{data:t,width:A.width,height:A.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),A}}let Mae=0;class Ru{constructor(A=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Mae++}),this.uuid=$I(),this.data=A,this.dataReady=!0,this.version=0}getSize(A){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?A.set(t.videoWidth,t.videoHeight,0):t instanceof VideoFrame?A.set(t.displayHeight,t.displayWidth,0):t!==null?A.set(t.width,t.height,t.depth||0):A.set(0,0,0),A}set needsUpdate(A){A===!0&&this.version++}toJSON(A){const t=A===void 0||typeof A=="string";if(!t&&A.images[this.uuid]!==void 0)return A.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(n!==null){let g;if(Array.isArray(n)){g=[];for(let o=0,s=n.length;o<s;o++)n[o].isDataTexture?g.push(tH(n[o].image)):g.push(tH(n[o]))}else g=tH(n);i.url=g}return t||(A.images[this.uuid]=i),i}}function tH(e){return typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap?nyA.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let Nae=0;const iH=new SA;class Kg extends bB{constructor(A=Kg.DEFAULT_IMAGE,t=Kg.DEFAULT_MAPPING,i=oI,n=oI,g=qg,o=Gr,s=Ar,a=Ic,r=Kg.DEFAULT_ANISOTROPY,I=DE){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Nae++}),this.uuid=$I(),this.name="",this.source=new Ru(A),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=g,this.minFilter=o,this.anisotropy=r,this.format=s,this.internalFormat=null,this.type=a,this.offset=new lt(0,0),this.repeat=new lt(1,1),this.center=new lt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new An,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=I,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(A&&A.depth&&A.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(iH).x}get height(){return this.source.getSize(iH).y}get depth(){return this.source.getSize(iH).z}get image(){return this.source.data}set image(A=null){this.source.data=A}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(A,t){this.updateRanges.push({start:A,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(A){return this.name=A.name,this.source=A.source,this.mipmaps=A.mipmaps.slice(0),this.mapping=A.mapping,this.channel=A.channel,this.wrapS=A.wrapS,this.wrapT=A.wrapT,this.magFilter=A.magFilter,this.minFilter=A.minFilter,this.anisotropy=A.anisotropy,this.format=A.format,this.internalFormat=A.internalFormat,this.type=A.type,this.offset.copy(A.offset),this.repeat.copy(A.repeat),this.center.copy(A.center),this.rotation=A.rotation,this.matrixAutoUpdate=A.matrixAutoUpdate,this.matrix.copy(A.matrix),this.generateMipmaps=A.generateMipmaps,this.premultiplyAlpha=A.premultiplyAlpha,this.flipY=A.flipY,this.unpackAlignment=A.unpackAlignment,this.colorSpace=A.colorSpace,this.renderTarget=A.renderTarget,this.isRenderTargetTexture=A.isRenderTargetTexture,this.isArrayTexture=A.isArrayTexture,this.userData=JSON.parse(JSON.stringify(A.userData)),this.needsUpdate=!0,this}setValues(A){for(const t in A){const i=A[t];if(i===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const n=this[t];if(n===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}n&&i&&n.isVector2&&i.isVector2||n&&i&&n.isVector3&&i.isVector3||n&&i&&n.isMatrix3&&i.isMatrix3?n.copy(i):this[t]=i}}toJSON(A){const t=A===void 0||typeof A=="string";if(!t&&A.textures[this.uuid]!==void 0)return A.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(A).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(A.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(A){if(this.mapping!==Kx)return A;if(A.applyMatrix3(this.matrix),A.x<0||A.x>1)switch(this.wrapS){case Fr:A.x=A.x-Math.floor(A.x);break;case oI:A.x=A.x<0?0:1;break;case ff:Math.abs(Math.floor(A.x)%2)===1?A.x=Math.ceil(A.x)-A.x:A.x=A.x-Math.floor(A.x);break}if(A.y<0||A.y>1)switch(this.wrapT){case Fr:A.y=A.y-Math.floor(A.y);break;case oI:A.y=A.y<0?0:1;break;case ff:Math.abs(Math.floor(A.y)%2)===1?A.y=Math.ceil(A.y)-A.y:A.y=A.y-Math.floor(A.y);break}return this.flipY&&(A.y=1-A.y),A}set needsUpdate(A){A===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(A){A===!0&&this.pmremVersion++}}Kg.DEFAULT_IMAGE=null;Kg.DEFAULT_MAPPING=Kx;Kg.DEFAULT_ANISOTROPY=1;class ig{constructor(A=0,t=0,i=0,n=1){ig.prototype.isVector4=!0,this.x=A,this.y=t,this.z=i,this.w=n}get width(){return this.z}set width(A){this.z=A}get height(){return this.w}set height(A){this.w=A}set(A,t,i,n){return this.x=A,this.y=t,this.z=i,this.w=n,this}setScalar(A){return this.x=A,this.y=A,this.z=A,this.w=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setZ(A){return this.z=A,this}setW(A){return this.w=A,this}setComponent(A,t){switch(A){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(A){return this.x=A.x,this.y=A.y,this.z=A.z,this.w=A.w!==void 0?A.w:1,this}add(A){return this.x+=A.x,this.y+=A.y,this.z+=A.z,this.w+=A.w,this}addScalar(A){return this.x+=A,this.y+=A,this.z+=A,this.w+=A,this}addVectors(A,t){return this.x=A.x+t.x,this.y=A.y+t.y,this.z=A.z+t.z,this.w=A.w+t.w,this}addScaledVector(A,t){return this.x+=A.x*t,this.y+=A.y*t,this.z+=A.z*t,this.w+=A.w*t,this}sub(A){return this.x-=A.x,this.y-=A.y,this.z-=A.z,this.w-=A.w,this}subScalar(A){return this.x-=A,this.y-=A,this.z-=A,this.w-=A,this}subVectors(A,t){return this.x=A.x-t.x,this.y=A.y-t.y,this.z=A.z-t.z,this.w=A.w-t.w,this}multiply(A){return this.x*=A.x,this.y*=A.y,this.z*=A.z,this.w*=A.w,this}multiplyScalar(A){return this.x*=A,this.y*=A,this.z*=A,this.w*=A,this}applyMatrix4(A){const t=this.x,i=this.y,n=this.z,g=this.w,o=A.elements;return this.x=o[0]*t+o[4]*i+o[8]*n+o[12]*g,this.y=o[1]*t+o[5]*i+o[9]*n+o[13]*g,this.z=o[2]*t+o[6]*i+o[10]*n+o[14]*g,this.w=o[3]*t+o[7]*i+o[11]*n+o[15]*g,this}divide(A){return this.x/=A.x,this.y/=A.y,this.z/=A.z,this.w/=A.w,this}divideScalar(A){return this.multiplyScalar(1/A)}setAxisAngleFromQuaternion(A){this.w=2*Math.acos(A.w);const t=Math.sqrt(1-A.w*A.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=A.x/t,this.y=A.y/t,this.z=A.z/t),this}setAxisAngleFromRotationMatrix(A){let t,i,n,g;const a=A.elements,r=a[0],I=a[4],c=a[8],l=a[1],B=a[5],Q=a[9],h=a[2],d=a[6],p=a[10];if(Math.abs(I-l)<.01&&Math.abs(c-h)<.01&&Math.abs(Q-d)<.01){if(Math.abs(I+l)<.1&&Math.abs(c+h)<.1&&Math.abs(Q+d)<.1&&Math.abs(r+B+p-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const m=(r+1)/2,D=(B+1)/2,S=(p+1)/2,k=(I+l)/4,N=(c+h)/4,G=(Q+d)/4;return m>D&&m>S?m<.01?(i=0,n=.707106781,g=.707106781):(i=Math.sqrt(m),n=k/i,g=N/i):D>S?D<.01?(i=.707106781,n=0,g=.707106781):(n=Math.sqrt(D),i=k/n,g=G/n):S<.01?(i=.707106781,n=.707106781,g=0):(g=Math.sqrt(S),i=N/g,n=G/g),this.set(i,n,g,t),this}let y=Math.sqrt((d-Q)*(d-Q)+(c-h)*(c-h)+(l-I)*(l-I));return Math.abs(y)<.001&&(y=1),this.x=(d-Q)/y,this.y=(c-h)/y,this.z=(l-I)/y,this.w=Math.acos((r+B+p-1)/2),this}setFromMatrixPosition(A){const t=A.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this.z=Math.min(this.z,A.z),this.w=Math.min(this.w,A.w),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this.z=Math.max(this.z,A.z),this.w=Math.max(this.w,A.w),this}clamp(A,t){return this.x=Fi(this.x,A.x,t.x),this.y=Fi(this.y,A.y,t.y),this.z=Fi(this.z,A.z,t.z),this.w=Fi(this.w,A.w,t.w),this}clampScalar(A,t){return this.x=Fi(this.x,A,t),this.y=Fi(this.y,A,t),this.z=Fi(this.z,A,t),this.w=Fi(this.w,A,t),this}clampLength(A,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Fi(i,A,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(A){return this.x*A.x+this.y*A.y+this.z*A.z+this.w*A.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,t){return this.x+=(A.x-this.x)*t,this.y+=(A.y-this.y)*t,this.z+=(A.z-this.z)*t,this.w+=(A.w-this.w)*t,this}lerpVectors(A,t,i){return this.x=A.x+(t.x-A.x)*i,this.y=A.y+(t.y-A.y)*i,this.z=A.z+(t.z-A.z)*i,this.w=A.w+(t.w-A.w)*i,this}equals(A){return A.x===this.x&&A.y===this.y&&A.z===this.z&&A.w===this.w}fromArray(A,t=0){return this.x=A[t],this.y=A[t+1],this.z=A[t+2],this.w=A[t+3],this}toArray(A=[],t=0){return A[t]=this.x,A[t+1]=this.y,A[t+2]=this.z,A[t+3]=this.w,A}fromBufferAttribute(A,t){return this.x=A.getX(t),this.y=A.getY(t),this.z=A.getZ(t),this.w=A.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class LW extends bB{constructor(A=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:qg,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=A,this.height=t,this.depth=i.depth,this.scissor=new ig(0,0,A,t),this.scissorTest=!1,this.viewport=new ig(0,0,A,t);const n={width:A,height:t,depth:i.depth},g=new Kg(n);this.textures=[];const o=i.count;for(let s=0;s<o;s++)this.textures[s]=g.clone(),this.textures[s].isRenderTargetTexture=!0,this.textures[s].renderTarget=this;this._setTextureOptions(i),this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=i.depthTexture,this.samples=i.samples,this.multiview=i.multiview}_setTextureOptions(A={}){const t={minFilter:qg,generateMipmaps:!1,flipY:!1,internalFormat:null};A.mapping!==void 0&&(t.mapping=A.mapping),A.wrapS!==void 0&&(t.wrapS=A.wrapS),A.wrapT!==void 0&&(t.wrapT=A.wrapT),A.wrapR!==void 0&&(t.wrapR=A.wrapR),A.magFilter!==void 0&&(t.magFilter=A.magFilter),A.minFilter!==void 0&&(t.minFilter=A.minFilter),A.format!==void 0&&(t.format=A.format),A.type!==void 0&&(t.type=A.type),A.anisotropy!==void 0&&(t.anisotropy=A.anisotropy),A.colorSpace!==void 0&&(t.colorSpace=A.colorSpace),A.flipY!==void 0&&(t.flipY=A.flipY),A.generateMipmaps!==void 0&&(t.generateMipmaps=A.generateMipmaps),A.internalFormat!==void 0&&(t.internalFormat=A.internalFormat);for(let i=0;i<this.textures.length;i++)this.textures[i].setValues(t)}get texture(){return this.textures[0]}set texture(A){this.textures[0]=A}set depthTexture(A){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),A!==null&&(A.renderTarget=this),this._depthTexture=A}get depthTexture(){return this._depthTexture}setSize(A,t,i=1){if(this.width!==A||this.height!==t||this.depth!==i){this.width=A,this.height=t,this.depth=i;for(let n=0,g=this.textures.length;n<g;n++)this.textures[n].image.width=A,this.textures[n].image.height=t,this.textures[n].image.depth=i,this.textures[n].isArrayTexture=this.textures[n].image.depth>1;this.dispose()}this.viewport.set(0,0,A,t),this.scissor.set(0,0,A,t)}clone(){return new this.constructor().copy(this)}copy(A){this.width=A.width,this.height=A.height,this.depth=A.depth,this.scissor.copy(A.scissor),this.scissorTest=A.scissorTest,this.viewport.copy(A.viewport),this.textures.length=0;for(let t=0,i=A.textures.length;t<i;t++){this.textures[t]=A.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const n=Object.assign({},A.textures[t].image);this.textures[t].source=new Ru(n)}return this.depthBuffer=A.depthBuffer,this.stencilBuffer=A.stencilBuffer,this.resolveDepthBuffer=A.resolveDepthBuffer,this.resolveStencilBuffer=A.resolveStencilBuffer,A.depthTexture!==null&&(this.depthTexture=A.depthTexture.clone()),this.samples=A.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class il extends LW{constructor(A=1,t=1,i={}){super(A,t,i),this.isWebGLRenderTarget=!0}}class Yx extends Kg{constructor(A=null,t=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:A,width:t,height:i,depth:n},this.magFilter=Ss,this.minFilter=Ss,this.wrapR=oI,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(A){this.layerUpdates.add(A)}clearLayerUpdates(){this.layerUpdates.clear()}}class Rae extends il{constructor(A=1,t=1,i=1,n={}){super(A,t,n),this.isWebGLArrayRenderTarget=!0,this.depth=i,this.texture=new Yx(null,A,t,i),this._setTextureOptions(n),this.texture.isRenderTargetTexture=!0}}class Hx extends Kg{constructor(A=null,t=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:A,width:t,height:i,depth:n},this.magFilter=Ss,this.minFilter=Ss,this.wrapR=oI,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Gae extends il{constructor(A=1,t=1,i=1,n={}){super(A,t,n),this.isWebGL3DRenderTarget=!0,this.depth=i,this.texture=new Hx(null,A,t,i),this._setTextureOptions(n),this.texture.isRenderTargetTexture=!0}}class Ag{constructor(A=new SA(1/0,1/0,1/0),t=new SA(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=A,this.max=t}set(A,t){return this.min.copy(A),this.max.copy(t),this}setFromArray(A){this.makeEmpty();for(let t=0,i=A.length;t<i;t+=3)this.expandByPoint(wc.fromArray(A,t));return this}setFromBufferAttribute(A){this.makeEmpty();for(let t=0,i=A.count;t<i;t++)this.expandByPoint(wc.fromBufferAttribute(A,t));return this}setFromPoints(A){this.makeEmpty();for(let t=0,i=A.length;t<i;t++)this.expandByPoint(A[t]);return this}setFromCenterAndSize(A,t){const i=wc.copy(t).multiplyScalar(.5);return this.min.copy(A).sub(i),this.max.copy(A).add(i),this}setFromObject(A,t=!1){return this.makeEmpty(),this.expandByObject(A,t)}clone(){return new this.constructor().copy(this)}copy(A){return this.min.copy(A.min),this.max.copy(A.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(A){return this.isEmpty()?A.set(0,0,0):A.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(A){return this.isEmpty()?A.set(0,0,0):A.subVectors(this.max,this.min)}expandByPoint(A){return this.min.min(A),this.max.max(A),this}expandByVector(A){return this.min.sub(A),this.max.add(A),this}expandByScalar(A){return this.min.addScalar(-A),this.max.addScalar(A),this}expandByObject(A,t=!1){A.updateWorldMatrix(!1,!1);const i=A.geometry;if(i!==void 0){const g=i.getAttribute("position");if(t===!0&&g!==void 0&&A.isInstancedMesh!==!0)for(let o=0,s=g.count;o<s;o++)A.isMesh===!0?A.getVertexPosition(o,wc):wc.fromBufferAttribute(g,o),wc.applyMatrix4(A.matrixWorld),this.expandByPoint(wc);else A.boundingBox!==void 0?(A.boundingBox===null&&A.computeBoundingBox(),oU.copy(A.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),oU.copy(i.boundingBox)),oU.applyMatrix4(A.matrixWorld),this.union(oU)}const n=A.children;for(let g=0,o=n.length;g<o;g++)this.expandByObject(n[g],t);return this}containsPoint(A){return A.x>=this.min.x&&A.x<=this.max.x&&A.y>=this.min.y&&A.y<=this.max.y&&A.z>=this.min.z&&A.z<=this.max.z}containsBox(A){return this.min.x<=A.min.x&&A.max.x<=this.max.x&&this.min.y<=A.min.y&&A.max.y<=this.max.y&&this.min.z<=A.min.z&&A.max.z<=this.max.z}getParameter(A,t){return t.set((A.x-this.min.x)/(this.max.x-this.min.x),(A.y-this.min.y)/(this.max.y-this.min.y),(A.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(A){return A.max.x>=this.min.x&&A.min.x<=this.max.x&&A.max.y>=this.min.y&&A.min.y<=this.max.y&&A.max.z>=this.min.z&&A.min.z<=this.max.z}intersectsSphere(A){return this.clampPoint(A.center,wc),wc.distanceToSquared(A.center)<=A.radius*A.radius}intersectsPlane(A){let t,i;return A.normal.x>0?(t=A.normal.x*this.min.x,i=A.normal.x*this.max.x):(t=A.normal.x*this.max.x,i=A.normal.x*this.min.x),A.normal.y>0?(t+=A.normal.y*this.min.y,i+=A.normal.y*this.max.y):(t+=A.normal.y*this.max.y,i+=A.normal.y*this.min.y),A.normal.z>0?(t+=A.normal.z*this.min.z,i+=A.normal.z*this.max.z):(t+=A.normal.z*this.max.z,i+=A.normal.z*this.min.z),t<=-A.constant&&i>=-A.constant}intersectsTriangle(A){if(this.isEmpty())return!1;this.getCenter(J0),sU.subVectors(this.max,J0),$y.subVectors(A.a,J0),AD.subVectors(A.b,J0),eD.subVectors(A.c,J0),KQ.subVectors(AD,$y),FQ.subVectors(eD,AD),hh.subVectors($y,eD);let t=[0,-KQ.z,KQ.y,0,-FQ.z,FQ.y,0,-hh.z,hh.y,KQ.z,0,-KQ.x,FQ.z,0,-FQ.x,hh.z,0,-hh.x,-KQ.y,KQ.x,0,-FQ.y,FQ.x,0,-hh.y,hh.x,0];return!nH(t,$y,AD,eD,sU)||(t=[1,0,0,0,1,0,0,0,1],!nH(t,$y,AD,eD,sU))?!1:(aU.crossVectors(KQ,FQ),t=[aU.x,aU.y,aU.z],nH(t,$y,AD,eD,sU))}clampPoint(A,t){return t.copy(A).clamp(this.min,this.max)}distanceToPoint(A){return this.clampPoint(A,wc).distanceTo(A)}getBoundingSphere(A){return this.isEmpty()?A.makeEmpty():(this.getCenter(A.center),A.radius=this.getSize(wc).length()*.5),A}intersect(A){return this.min.max(A.min),this.max.min(A.max),this.isEmpty()&&this.makeEmpty(),this}union(A){return this.min.min(A.min),this.max.max(A.max),this}applyMatrix4(A){return this.isEmpty()?this:(XB[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(A),XB[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(A),XB[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(A),XB[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(A),XB[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(A),XB[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(A),XB[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(A),XB[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(A),this.setFromPoints(XB),this)}translate(A){return this.min.add(A),this.max.add(A),this}equals(A){return A.min.equals(this.min)&&A.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(A){return this.min.fromArray(A.min),this.max.fromArray(A.max),this}}const XB=[new SA,new SA,new SA,new SA,new SA,new SA,new SA,new SA],wc=new SA,oU=new Ag,$y=new SA,AD=new SA,eD=new SA,KQ=new SA,FQ=new SA,hh=new SA,J0=new SA,sU=new SA,aU=new SA,ph=new SA;function nH(e,A,t,i,n){for(let g=0,o=e.length-3;g<=o;g+=3){ph.fromArray(e,g);const s=n.x*Math.abs(ph.x)+n.y*Math.abs(ph.y)+n.z*Math.abs(ph.z),a=A.dot(ph),r=t.dot(ph),I=i.dot(ph);if(Math.max(-Math.max(a,r,I),Math.min(a,r,I))>s)return!1}return!0}const bae=new Ag,L0=new SA,gH=new SA;class xs{constructor(A=new SA,t=-1){this.isSphere=!0,this.center=A,this.radius=t}set(A,t){return this.center.copy(A),this.radius=t,this}setFromPoints(A,t){const i=this.center;t!==void 0?i.copy(t):bae.setFromPoints(A).getCenter(i);let n=0;for(let g=0,o=A.length;g<o;g++)n=Math.max(n,i.distanceToSquared(A[g]));return this.radius=Math.sqrt(n),this}copy(A){return this.center.copy(A.center),this.radius=A.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(A){return A.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(A){return A.distanceTo(this.center)-this.radius}intersectsSphere(A){const t=this.radius+A.radius;return A.center.distanceToSquared(this.center)<=t*t}intersectsBox(A){return A.intersectsSphere(this)}intersectsPlane(A){return Math.abs(A.distanceToPoint(this.center))<=this.radius}clampPoint(A,t){const i=this.center.distanceToSquared(A);return t.copy(A),i>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(A){return this.isEmpty()?(A.makeEmpty(),A):(A.set(this.center,this.center),A.expandByScalar(this.radius),A)}applyMatrix4(A){return this.center.applyMatrix4(A),this.radius=this.radius*A.getMaxScaleOnAxis(),this}translate(A){return this.center.add(A),this}expandByPoint(A){if(this.isEmpty())return this.center.copy(A),this.radius=0,this;L0.subVectors(A,this.center);const t=L0.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),n=(i-this.radius)*.5;this.center.addScaledVector(L0,n/i),this.radius+=n}return this}union(A){return A.isEmpty()?this:this.isEmpty()?(this.copy(A),this):(this.center.equals(A.center)===!0?this.radius=Math.max(this.radius,A.radius):(gH.subVectors(A.center,this.center).setLength(A.radius),this.expandByPoint(L0.copy(A.center).add(gH)),this.expandByPoint(L0.copy(A.center).sub(gH))),this)}equals(A){return A.center.equals(this.center)&&A.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(A){return this.radius=A.radius,this.center.fromArray(A.center),this}}const $B=new SA,oH=new SA,rU=new SA,_Q=new SA,sH=new SA,IU=new SA,aH=new SA;class Fw{constructor(A=new SA,t=new SA(0,0,-1)){this.origin=A,this.direction=t}set(A,t){return this.origin.copy(A),this.direction.copy(t),this}copy(A){return this.origin.copy(A.origin),this.direction.copy(A.direction),this}at(A,t){return t.copy(this.origin).addScaledVector(this.direction,A)}lookAt(A){return this.direction.copy(A).sub(this.origin).normalize(),this}recast(A){return this.origin.copy(this.at(A,$B)),this}closestPointToPoint(A,t){t.subVectors(A,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(A){return Math.sqrt(this.distanceSqToPoint(A))}distanceSqToPoint(A){const t=$B.subVectors(A,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(A):($B.copy(this.origin).addScaledVector(this.direction,t),$B.distanceToSquared(A))}distanceSqToSegment(A,t,i,n){oH.copy(A).add(t).multiplyScalar(.5),rU.copy(t).sub(A).normalize(),_Q.copy(this.origin).sub(oH);const g=A.distanceTo(t)*.5,o=-this.direction.dot(rU),s=_Q.dot(this.direction),a=-_Q.dot(rU),r=_Q.lengthSq(),I=Math.abs(1-o*o);let c,l,B,Q;if(I>0)if(c=o*a-s,l=o*s-a,Q=g*I,c>=0)if(l>=-Q)if(l<=Q){const h=1/I;c*=h,l*=h,B=c*(c+o*l+2*s)+l*(o*c+l+2*a)+r}else l=g,c=Math.max(0,-(o*l+s)),B=-c*c+l*(l+2*a)+r;else l=-g,c=Math.max(0,-(o*l+s)),B=-c*c+l*(l+2*a)+r;else l<=-Q?(c=Math.max(0,-(-o*g+s)),l=c>0?-g:Math.min(Math.max(-g,-a),g),B=-c*c+l*(l+2*a)+r):l<=Q?(c=0,l=Math.min(Math.max(-g,-a),g),B=l*(l+2*a)+r):(c=Math.max(0,-(o*g+s)),l=c>0?g:Math.min(Math.max(-g,-a),g),B=-c*c+l*(l+2*a)+r);else l=o>0?-g:g,c=Math.max(0,-(o*l+s)),B=-c*c+l*(l+2*a)+r;return i&&i.copy(this.origin).addScaledVector(this.direction,c),n&&n.copy(oH).addScaledVector(rU,l),B}intersectSphere(A,t){$B.subVectors(A.center,this.origin);const i=$B.dot(this.direction),n=$B.dot($B)-i*i,g=A.radius*A.radius;if(n>g)return null;const o=Math.sqrt(g-n),s=i-o,a=i+o;return a<0?null:s<0?this.at(a,t):this.at(s,t)}intersectsSphere(A){return A.radius<0?!1:this.distanceSqToPoint(A.center)<=A.radius*A.radius}distanceToPlane(A){const t=A.normal.dot(this.direction);if(t===0)return A.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(A.normal)+A.constant)/t;return i>=0?i:null}intersectPlane(A,t){const i=this.distanceToPlane(A);return i===null?null:this.at(i,t)}intersectsPlane(A){const t=A.distanceToPoint(this.origin);return t===0||A.normal.dot(this.direction)*t<0}intersectBox(A,t){let i,n,g,o,s,a;const r=1/this.direction.x,I=1/this.direction.y,c=1/this.direction.z,l=this.origin;return r>=0?(i=(A.min.x-l.x)*r,n=(A.max.x-l.x)*r):(i=(A.max.x-l.x)*r,n=(A.min.x-l.x)*r),I>=0?(g=(A.min.y-l.y)*I,o=(A.max.y-l.y)*I):(g=(A.max.y-l.y)*I,o=(A.min.y-l.y)*I),i>o||g>n||((g>i||isNaN(i))&&(i=g),(o<n||isNaN(n))&&(n=o),c>=0?(s=(A.min.z-l.z)*c,a=(A.max.z-l.z)*c):(s=(A.max.z-l.z)*c,a=(A.min.z-l.z)*c),i>a||s>n)||((s>i||i!==i)&&(i=s),(a<n||n!==n)&&(n=a),n<0)?null:this.at(i>=0?i:n,t)}intersectsBox(A){return this.intersectBox(A,$B)!==null}intersectTriangle(A,t,i,n,g){sH.subVectors(t,A),IU.subVectors(i,A),aH.crossVectors(sH,IU);let o=this.direction.dot(aH),s;if(o>0){if(n)return null;s=1}else if(o<0)s=-1,o=-o;else return null;_Q.subVectors(this.origin,A);const a=s*this.direction.dot(IU.crossVectors(_Q,IU));if(a<0)return null;const r=s*this.direction.dot(sH.cross(_Q));if(r<0||a+r>o)return null;const I=-s*_Q.dot(aH);return I<0?null:this.at(I/o,g)}applyMatrix4(A){return this.origin.applyMatrix4(A),this.direction.transformDirection(A),this}equals(A){return A.origin.equals(this.origin)&&A.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class ni{constructor(A,t,i,n,g,o,s,a,r,I,c,l,B,Q,h,d){ni.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],A!==void 0&&this.set(A,t,i,n,g,o,s,a,r,I,c,l,B,Q,h,d)}set(A,t,i,n,g,o,s,a,r,I,c,l,B,Q,h,d){const p=this.elements;return p[0]=A,p[4]=t,p[8]=i,p[12]=n,p[1]=g,p[5]=o,p[9]=s,p[13]=a,p[2]=r,p[6]=I,p[10]=c,p[14]=l,p[3]=B,p[7]=Q,p[11]=h,p[15]=d,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new ni().fromArray(this.elements)}copy(A){const t=this.elements,i=A.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(A){const t=this.elements,i=A.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(A){const t=A.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(A,t,i){return A.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(A,t,i){return this.set(A.x,t.x,i.x,0,A.y,t.y,i.y,0,A.z,t.z,i.z,0,0,0,0,1),this}extractRotation(A){const t=this.elements,i=A.elements,n=1/tD.setFromMatrixColumn(A,0).length(),g=1/tD.setFromMatrixColumn(A,1).length(),o=1/tD.setFromMatrixColumn(A,2).length();return t[0]=i[0]*n,t[1]=i[1]*n,t[2]=i[2]*n,t[3]=0,t[4]=i[4]*g,t[5]=i[5]*g,t[6]=i[6]*g,t[7]=0,t[8]=i[8]*o,t[9]=i[9]*o,t[10]=i[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(A){const t=this.elements,i=A.x,n=A.y,g=A.z,o=Math.cos(i),s=Math.sin(i),a=Math.cos(n),r=Math.sin(n),I=Math.cos(g),c=Math.sin(g);if(A.order==="XYZ"){const l=o*I,B=o*c,Q=s*I,h=s*c;t[0]=a*I,t[4]=-a*c,t[8]=r,t[1]=B+Q*r,t[5]=l-h*r,t[9]=-s*a,t[2]=h-l*r,t[6]=Q+B*r,t[10]=o*a}else if(A.order==="YXZ"){const l=a*I,B=a*c,Q=r*I,h=r*c;t[0]=l+h*s,t[4]=Q*s-B,t[8]=o*r,t[1]=o*c,t[5]=o*I,t[9]=-s,t[2]=B*s-Q,t[6]=h+l*s,t[10]=o*a}else if(A.order==="ZXY"){const l=a*I,B=a*c,Q=r*I,h=r*c;t[0]=l-h*s,t[4]=-o*c,t[8]=Q+B*s,t[1]=B+Q*s,t[5]=o*I,t[9]=h-l*s,t[2]=-o*r,t[6]=s,t[10]=o*a}else if(A.order==="ZYX"){const l=o*I,B=o*c,Q=s*I,h=s*c;t[0]=a*I,t[4]=Q*r-B,t[8]=l*r+h,t[1]=a*c,t[5]=h*r+l,t[9]=B*r-Q,t[2]=-r,t[6]=s*a,t[10]=o*a}else if(A.order==="YZX"){const l=o*a,B=o*r,Q=s*a,h=s*r;t[0]=a*I,t[4]=h-l*c,t[8]=Q*c+B,t[1]=c,t[5]=o*I,t[9]=-s*I,t[2]=-r*I,t[6]=B*c+Q,t[10]=l-h*c}else if(A.order==="XZY"){const l=o*a,B=o*r,Q=s*a,h=s*r;t[0]=a*I,t[4]=-c,t[8]=r*I,t[1]=l*c+h,t[5]=o*I,t[9]=B*c-Q,t[2]=Q*c-B,t[6]=s*I,t[10]=h*c+l}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(A){return this.compose(Uae,A,vae)}lookAt(A,t,i){const n=this.elements;return bI.subVectors(A,t),bI.lengthSq()===0&&(bI.z=1),bI.normalize(),JQ.crossVectors(i,bI),JQ.lengthSq()===0&&(Math.abs(i.z)===1?bI.x+=1e-4:bI.z+=1e-4,bI.normalize(),JQ.crossVectors(i,bI)),JQ.normalize(),CU.crossVectors(bI,JQ),n[0]=JQ.x,n[4]=CU.x,n[8]=bI.x,n[1]=JQ.y,n[5]=CU.y,n[9]=bI.y,n[2]=JQ.z,n[6]=CU.z,n[10]=bI.z,this}multiply(A){return this.multiplyMatrices(this,A)}premultiply(A){return this.multiplyMatrices(A,this)}multiplyMatrices(A,t){const i=A.elements,n=t.elements,g=this.elements,o=i[0],s=i[4],a=i[8],r=i[12],I=i[1],c=i[5],l=i[9],B=i[13],Q=i[2],h=i[6],d=i[10],p=i[14],y=i[3],m=i[7],D=i[11],S=i[15],k=n[0],N=n[4],G=n[8],M=n[12],w=n[1],b=n[5],_=n[9],K=n[13],J=n[2],q=n[6],v=n[10],U=n[14],x=n[3],T=n[7],z=n[11],Z=n[15];return g[0]=o*k+s*w+a*J+r*x,g[4]=o*N+s*b+a*q+r*T,g[8]=o*G+s*_+a*v+r*z,g[12]=o*M+s*K+a*U+r*Z,g[1]=I*k+c*w+l*J+B*x,g[5]=I*N+c*b+l*q+B*T,g[9]=I*G+c*_+l*v+B*z,g[13]=I*M+c*K+l*U+B*Z,g[2]=Q*k+h*w+d*J+p*x,g[6]=Q*N+h*b+d*q+p*T,g[10]=Q*G+h*_+d*v+p*z,g[14]=Q*M+h*K+d*U+p*Z,g[3]=y*k+m*w+D*J+S*x,g[7]=y*N+m*b+D*q+S*T,g[11]=y*G+m*_+D*v+S*z,g[15]=y*M+m*K+D*U+S*Z,this}multiplyScalar(A){const t=this.elements;return t[0]*=A,t[4]*=A,t[8]*=A,t[12]*=A,t[1]*=A,t[5]*=A,t[9]*=A,t[13]*=A,t[2]*=A,t[6]*=A,t[10]*=A,t[14]*=A,t[3]*=A,t[7]*=A,t[11]*=A,t[15]*=A,this}determinant(){const A=this.elements,t=A[0],i=A[4],n=A[8],g=A[12],o=A[1],s=A[5],a=A[9],r=A[13],I=A[2],c=A[6],l=A[10],B=A[14],Q=A[3],h=A[7],d=A[11],p=A[15];return Q*(+g*a*c-n*r*c-g*s*l+i*r*l+n*s*B-i*a*B)+h*(+t*a*B-t*r*l+g*o*l-n*o*B+n*r*I-g*a*I)+d*(+t*r*c-t*s*B-g*o*c+i*o*B+g*s*I-i*r*I)+p*(-n*s*I-t*a*c+t*s*l+n*o*c-i*o*l+i*a*I)}transpose(){const A=this.elements;let t;return t=A[1],A[1]=A[4],A[4]=t,t=A[2],A[2]=A[8],A[8]=t,t=A[6],A[6]=A[9],A[9]=t,t=A[3],A[3]=A[12],A[12]=t,t=A[7],A[7]=A[13],A[13]=t,t=A[11],A[11]=A[14],A[14]=t,this}setPosition(A,t,i){const n=this.elements;return A.isVector3?(n[12]=A.x,n[13]=A.y,n[14]=A.z):(n[12]=A,n[13]=t,n[14]=i),this}invert(){const A=this.elements,t=A[0],i=A[1],n=A[2],g=A[3],o=A[4],s=A[5],a=A[6],r=A[7],I=A[8],c=A[9],l=A[10],B=A[11],Q=A[12],h=A[13],d=A[14],p=A[15],y=c*d*r-h*l*r+h*a*B-s*d*B-c*a*p+s*l*p,m=Q*l*r-I*d*r-Q*a*B+o*d*B+I*a*p-o*l*p,D=I*h*r-Q*c*r+Q*s*B-o*h*B-I*s*p+o*c*p,S=Q*c*a-I*h*a-Q*s*l+o*h*l+I*s*d-o*c*d,k=t*y+i*m+n*D+g*S;if(k===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const N=1/k;return A[0]=y*N,A[1]=(h*l*g-c*d*g-h*n*B+i*d*B+c*n*p-i*l*p)*N,A[2]=(s*d*g-h*a*g+h*n*r-i*d*r-s*n*p+i*a*p)*N,A[3]=(c*a*g-s*l*g-c*n*r+i*l*r+s*n*B-i*a*B)*N,A[4]=m*N,A[5]=(I*d*g-Q*l*g+Q*n*B-t*d*B-I*n*p+t*l*p)*N,A[6]=(Q*a*g-o*d*g-Q*n*r+t*d*r+o*n*p-t*a*p)*N,A[7]=(o*l*g-I*a*g+I*n*r-t*l*r-o*n*B+t*a*B)*N,A[8]=D*N,A[9]=(Q*c*g-I*h*g-Q*i*B+t*h*B+I*i*p-t*c*p)*N,A[10]=(o*h*g-Q*s*g+Q*i*r-t*h*r-o*i*p+t*s*p)*N,A[11]=(I*s*g-o*c*g-I*i*r+t*c*r+o*i*B-t*s*B)*N,A[12]=S*N,A[13]=(I*h*n-Q*c*n+Q*i*l-t*h*l-I*i*d+t*c*d)*N,A[14]=(Q*s*n-o*h*n-Q*i*a+t*h*a+o*i*d-t*s*d)*N,A[15]=(o*c*n-I*s*n+I*i*a-t*c*a-o*i*l+t*s*l)*N,this}scale(A){const t=this.elements,i=A.x,n=A.y,g=A.z;return t[0]*=i,t[4]*=n,t[8]*=g,t[1]*=i,t[5]*=n,t[9]*=g,t[2]*=i,t[6]*=n,t[10]*=g,t[3]*=i,t[7]*=n,t[11]*=g,this}getMaxScaleOnAxis(){const A=this.elements,t=A[0]*A[0]+A[1]*A[1]+A[2]*A[2],i=A[4]*A[4]+A[5]*A[5]+A[6]*A[6],n=A[8]*A[8]+A[9]*A[9]+A[10]*A[10];return Math.sqrt(Math.max(t,i,n))}makeTranslation(A,t,i){return A.isVector3?this.set(1,0,0,A.x,0,1,0,A.y,0,0,1,A.z,0,0,0,1):this.set(1,0,0,A,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(A){const t=Math.cos(A),i=Math.sin(A);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(A){const t=Math.cos(A),i=Math.sin(A);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(A){const t=Math.cos(A),i=Math.sin(A);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(A,t){const i=Math.cos(t),n=Math.sin(t),g=1-i,o=A.x,s=A.y,a=A.z,r=g*o,I=g*s;return this.set(r*o+i,r*s-n*a,r*a+n*s,0,r*s+n*a,I*s+i,I*a-n*o,0,r*a-n*s,I*a+n*o,g*a*a+i,0,0,0,0,1),this}makeScale(A,t,i){return this.set(A,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(A,t,i,n,g,o){return this.set(1,i,g,0,A,1,o,0,t,n,1,0,0,0,0,1),this}compose(A,t,i){const n=this.elements,g=t._x,o=t._y,s=t._z,a=t._w,r=g+g,I=o+o,c=s+s,l=g*r,B=g*I,Q=g*c,h=o*I,d=o*c,p=s*c,y=a*r,m=a*I,D=a*c,S=i.x,k=i.y,N=i.z;return n[0]=(1-(h+p))*S,n[1]=(B+D)*S,n[2]=(Q-m)*S,n[3]=0,n[4]=(B-D)*k,n[5]=(1-(l+p))*k,n[6]=(d+y)*k,n[7]=0,n[8]=(Q+m)*N,n[9]=(d-y)*N,n[10]=(1-(l+h))*N,n[11]=0,n[12]=A.x,n[13]=A.y,n[14]=A.z,n[15]=1,this}decompose(A,t,i){const n=this.elements;let g=tD.set(n[0],n[1],n[2]).length();const o=tD.set(n[4],n[5],n[6]).length(),s=tD.set(n[8],n[9],n[10]).length();this.determinant()<0&&(g=-g),A.x=n[12],A.y=n[13],A.z=n[14],kc.copy(this);const r=1/g,I=1/o,c=1/s;return kc.elements[0]*=r,kc.elements[1]*=r,kc.elements[2]*=r,kc.elements[4]*=I,kc.elements[5]*=I,kc.elements[6]*=I,kc.elements[8]*=c,kc.elements[9]*=c,kc.elements[10]*=c,t.setFromRotationMatrix(kc),i.x=g,i.y=o,i.z=s,this}makePerspective(A,t,i,n,g,o,s=jI,a=!1){const r=this.elements,I=2*g/(t-A),c=2*g/(i-n),l=(t+A)/(t-A),B=(i+n)/(i-n);let Q,h;if(a)Q=g/(o-g),h=o*g/(o-g);else if(s===jI)Q=-(o+g)/(o-g),h=-2*o*g/(o-g);else if(s===HS)Q=-o/(o-g),h=-o*g/(o-g);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+s);return r[0]=I,r[4]=0,r[8]=l,r[12]=0,r[1]=0,r[5]=c,r[9]=B,r[13]=0,r[2]=0,r[6]=0,r[10]=Q,r[14]=h,r[3]=0,r[7]=0,r[11]=-1,r[15]=0,this}makeOrthographic(A,t,i,n,g,o,s=jI,a=!1){const r=this.elements,I=2/(t-A),c=2/(i-n),l=-(t+A)/(t-A),B=-(i+n)/(i-n);let Q,h;if(a)Q=1/(o-g),h=o/(o-g);else if(s===jI)Q=-2/(o-g),h=-(o+g)/(o-g);else if(s===HS)Q=-1/(o-g),h=-g/(o-g);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+s);return r[0]=I,r[4]=0,r[8]=0,r[12]=l,r[1]=0,r[5]=c,r[9]=0,r[13]=B,r[2]=0,r[6]=0,r[10]=Q,r[14]=h,r[3]=0,r[7]=0,r[11]=0,r[15]=1,this}equals(A){const t=this.elements,i=A.elements;for(let n=0;n<16;n++)if(t[n]!==i[n])return!1;return!0}fromArray(A,t=0){for(let i=0;i<16;i++)this.elements[i]=A[i+t];return this}toArray(A=[],t=0){const i=this.elements;return A[t]=i[0],A[t+1]=i[1],A[t+2]=i[2],A[t+3]=i[3],A[t+4]=i[4],A[t+5]=i[5],A[t+6]=i[6],A[t+7]=i[7],A[t+8]=i[8],A[t+9]=i[9],A[t+10]=i[10],A[t+11]=i[11],A[t+12]=i[12],A[t+13]=i[13],A[t+14]=i[14],A[t+15]=i[15],A}}const tD=new SA,kc=new ni,Uae=new SA(0,0,0),vae=new SA(1,1,1),JQ=new SA,CU=new SA,bI=new SA,FiA=new ni,_iA=new oo;class ca{constructor(A=0,t=0,i=0,n=ca.DEFAULT_ORDER){this.isEuler=!0,this._x=A,this._y=t,this._z=i,this._order=n}get x(){return this._x}set x(A){this._x=A,this._onChangeCallback()}get y(){return this._y}set y(A){this._y=A,this._onChangeCallback()}get z(){return this._z}set z(A){this._z=A,this._onChangeCallback()}get order(){return this._order}set order(A){this._order=A,this._onChangeCallback()}set(A,t,i,n=this._order){return this._x=A,this._y=t,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(A){return this._x=A._x,this._y=A._y,this._z=A._z,this._order=A._order,this._onChangeCallback(),this}setFromRotationMatrix(A,t=this._order,i=!0){const n=A.elements,g=n[0],o=n[4],s=n[8],a=n[1],r=n[5],I=n[9],c=n[2],l=n[6],B=n[10];switch(t){case"XYZ":this._y=Math.asin(Fi(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-I,B),this._z=Math.atan2(-o,g)):(this._x=Math.atan2(l,r),this._z=0);break;case"YXZ":this._x=Math.asin(-Fi(I,-1,1)),Math.abs(I)<.9999999?(this._y=Math.atan2(s,B),this._z=Math.atan2(a,r)):(this._y=Math.atan2(-c,g),this._z=0);break;case"ZXY":this._x=Math.asin(Fi(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(-c,B),this._z=Math.atan2(-o,r)):(this._y=0,this._z=Math.atan2(a,g));break;case"ZYX":this._y=Math.asin(-Fi(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(l,B),this._z=Math.atan2(a,g)):(this._x=0,this._z=Math.atan2(-o,r));break;case"YZX":this._z=Math.asin(Fi(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-I,r),this._y=Math.atan2(-c,g)):(this._x=0,this._y=Math.atan2(s,B));break;case"XZY":this._z=Math.asin(-Fi(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(l,r),this._y=Math.atan2(s,g)):(this._x=Math.atan2(-I,B),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(A,t,i){return FiA.makeRotationFromQuaternion(A),this.setFromRotationMatrix(FiA,t,i)}setFromVector3(A,t=this._order){return this.set(A.x,A.y,A.z,t)}reorder(A){return _iA.setFromEuler(this),this.setFromQuaternion(_iA,A)}equals(A){return A._x===this._x&&A._y===this._y&&A._z===this._z&&A._order===this._order}fromArray(A){return this._x=A[0],this._y=A[1],this._z=A[2],A[3]!==void 0&&(this._order=A[3]),this._onChangeCallback(),this}toArray(A=[],t=0){return A[t]=this._x,A[t+1]=this._y,A[t+2]=this._z,A[t+3]=this._order,A}_onChange(A){return this._onChangeCallback=A,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}ca.DEFAULT_ORDER="XYZ";class PS{constructor(){this.mask=1}set(A){this.mask=(1<<A|0)>>>0}enable(A){this.mask|=1<<A|0}enableAll(){this.mask=-1}toggle(A){this.mask^=1<<A|0}disable(A){this.mask&=~(1<<A|0)}disableAll(){this.mask=0}test(A){return(this.mask&A.mask)!==0}isEnabled(A){return(this.mask&(1<<A|0))!==0}}let Kae=0;const JiA=new SA,iD=new oo,AE=new ni,cU=new SA,x0=new SA,Fae=new SA,_ae=new oo,LiA=new SA(1,0,0),xiA=new SA(0,1,0),TiA=new SA(0,0,1),qiA={type:"added"},Jae={type:"removed"},nD={type:"childadded",child:null},rH={type:"childremoved",child:null};class Bn extends bB{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Kae++}),this.uuid=$I(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Bn.DEFAULT_UP.clone();const A=new SA,t=new ca,i=new oo,n=new SA(1,1,1);function g(){i.setFromEuler(t,!1)}function o(){t.setFromQuaternion(i,void 0,!1)}t._onChange(g),i._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:A},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new ni},normalMatrix:{value:new An}}),this.matrix=new ni,this.matrixWorld=new ni,this.matrixAutoUpdate=Bn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Bn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new PS,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(A){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(A),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(A){return this.quaternion.premultiply(A),this}setRotationFromAxisAngle(A,t){this.quaternion.setFromAxisAngle(A,t)}setRotationFromEuler(A){this.quaternion.setFromEuler(A,!0)}setRotationFromMatrix(A){this.quaternion.setFromRotationMatrix(A)}setRotationFromQuaternion(A){this.quaternion.copy(A)}rotateOnAxis(A,t){return iD.setFromAxisAngle(A,t),this.quaternion.multiply(iD),this}rotateOnWorldAxis(A,t){return iD.setFromAxisAngle(A,t),this.quaternion.premultiply(iD),this}rotateX(A){return this.rotateOnAxis(LiA,A)}rotateY(A){return this.rotateOnAxis(xiA,A)}rotateZ(A){return this.rotateOnAxis(TiA,A)}translateOnAxis(A,t){return JiA.copy(A).applyQuaternion(this.quaternion),this.position.add(JiA.multiplyScalar(t)),this}translateX(A){return this.translateOnAxis(LiA,A)}translateY(A){return this.translateOnAxis(xiA,A)}translateZ(A){return this.translateOnAxis(TiA,A)}localToWorld(A){return this.updateWorldMatrix(!0,!1),A.applyMatrix4(this.matrixWorld)}worldToLocal(A){return this.updateWorldMatrix(!0,!1),A.applyMatrix4(AE.copy(this.matrixWorld).invert())}lookAt(A,t,i){A.isVector3?cU.copy(A):cU.set(A,t,i);const n=this.parent;this.updateWorldMatrix(!0,!1),x0.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?AE.lookAt(x0,cU,this.up):AE.lookAt(cU,x0,this.up),this.quaternion.setFromRotationMatrix(AE),n&&(AE.extractRotation(n.matrixWorld),iD.setFromRotationMatrix(AE),this.quaternion.premultiply(iD.invert()))}add(A){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return A===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",A),this):(A&&A.isObject3D?(A.removeFromParent(),A.parent=this,this.children.push(A),A.dispatchEvent(qiA),nD.child=A,this.dispatchEvent(nD),nD.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",A),this)}remove(A){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const t=this.children.indexOf(A);return t!==-1&&(A.parent=null,this.children.splice(t,1),A.dispatchEvent(Jae),rH.child=A,this.dispatchEvent(rH),rH.child=null),this}removeFromParent(){const A=this.parent;return A!==null&&A.remove(this),this}clear(){return this.remove(...this.children)}attach(A){return this.updateWorldMatrix(!0,!1),AE.copy(this.matrixWorld).invert(),A.parent!==null&&(A.parent.updateWorldMatrix(!0,!1),AE.multiply(A.parent.matrixWorld)),A.applyMatrix4(AE),A.removeFromParent(),A.parent=this,this.children.push(A),A.updateWorldMatrix(!1,!0),A.dispatchEvent(qiA),nD.child=A,this.dispatchEvent(nD),nD.child=null,this}getObjectById(A){return this.getObjectByProperty("id",A)}getObjectByName(A){return this.getObjectByProperty("name",A)}getObjectByProperty(A,t){if(this[A]===t)return this;for(let i=0,n=this.children.length;i<n;i++){const o=this.children[i].getObjectByProperty(A,t);if(o!==void 0)return o}}getObjectsByProperty(A,t,i=[]){this[A]===t&&i.push(this);const n=this.children;for(let g=0,o=n.length;g<o;g++)n[g].getObjectsByProperty(A,t,i);return i}getWorldPosition(A){return this.updateWorldMatrix(!0,!1),A.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(A){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(x0,A,Fae),A}getWorldScale(A){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(x0,_ae,A),A}getWorldDirection(A){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return A.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(A){A(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverse(A)}traverseVisible(A){if(this.visible===!1)return;A(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverseVisible(A)}traverseAncestors(A){const t=this.parent;t!==null&&(A(t),t.traverseAncestors(A))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(A){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||A)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,A=!0);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].updateMatrixWorld(A)}updateWorldMatrix(A,t){const i=this.parent;if(A===!0&&i!==null&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const n=this.children;for(let g=0,o=n.length;g<o;g++)n[g].updateWorldMatrix(!1,!0)}}toJSON(A){const t=A===void 0||typeof A=="string",i={};t&&(A={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.geometryInfo=this._geometryInfo.map(s=>({...s,boundingBox:s.boundingBox?s.boundingBox.toJSON():void 0,boundingSphere:s.boundingSphere?s.boundingSphere.toJSON():void 0})),n.instanceInfo=this._instanceInfo.map(s=>({...s})),n.availableInstanceIds=this._availableInstanceIds.slice(),n.availableGeometryIds=this._availableGeometryIds.slice(),n.nextIndexStart=this._nextIndexStart,n.nextVertexStart=this._nextVertexStart,n.geometryCount=this._geometryCount,n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.matricesTexture=this._matricesTexture.toJSON(A),n.indirectTexture=this._indirectTexture.toJSON(A),this._colorsTexture!==null&&(n.colorsTexture=this._colorsTexture.toJSON(A)),this.boundingSphere!==null&&(n.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(n.boundingBox=this.boundingBox.toJSON()));function g(s,a){return s[a.uuid]===void 0&&(s[a.uuid]=a.toJSON(A)),a.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(A).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(A).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=g(A.geometries,this.geometry);const s=this.geometry.parameters;if(s!==void 0&&s.shapes!==void 0){const a=s.shapes;if(Array.isArray(a))for(let r=0,I=a.length;r<I;r++){const c=a[r];g(A.shapes,c)}else g(A.shapes,a)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(g(A.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const s=[];for(let a=0,r=this.material.length;a<r;a++)s.push(g(A.materials,this.material[a]));n.material=s}else n.material=g(A.materials,this.material);if(this.children.length>0){n.children=[];for(let s=0;s<this.children.length;s++)n.children.push(this.children[s].toJSON(A).object)}if(this.animations.length>0){n.animations=[];for(let s=0;s<this.animations.length;s++){const a=this.animations[s];n.animations.push(g(A.animations,a))}}if(t){const s=o(A.geometries),a=o(A.materials),r=o(A.textures),I=o(A.images),c=o(A.shapes),l=o(A.skeletons),B=o(A.animations),Q=o(A.nodes);s.length>0&&(i.geometries=s),a.length>0&&(i.materials=a),r.length>0&&(i.textures=r),I.length>0&&(i.images=I),c.length>0&&(i.shapes=c),l.length>0&&(i.skeletons=l),B.length>0&&(i.animations=B),Q.length>0&&(i.nodes=Q)}return i.object=n,i;function o(s){const a=[];for(const r in s){const I=s[r];delete I.metadata,a.push(I)}return a}}clone(A){return new this.constructor().copy(this,A)}copy(A,t=!0){if(this.name=A.name,this.up.copy(A.up),this.position.copy(A.position),this.rotation.order=A.rotation.order,this.quaternion.copy(A.quaternion),this.scale.copy(A.scale),this.matrix.copy(A.matrix),this.matrixWorld.copy(A.matrixWorld),this.matrixAutoUpdate=A.matrixAutoUpdate,this.matrixWorldAutoUpdate=A.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=A.matrixWorldNeedsUpdate,this.layers.mask=A.layers.mask,this.visible=A.visible,this.castShadow=A.castShadow,this.receiveShadow=A.receiveShadow,this.frustumCulled=A.frustumCulled,this.renderOrder=A.renderOrder,this.animations=A.animations.slice(),this.userData=JSON.parse(JSON.stringify(A.userData)),t===!0)for(let i=0;i<A.children.length;i++){const n=A.children[i];this.add(n.clone())}return this}}Bn.DEFAULT_UP=new SA(0,1,0);Bn.DEFAULT_MATRIX_AUTO_UPDATE=!0;Bn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Mc=new SA,eE=new SA,IH=new SA,tE=new SA,gD=new SA,oD=new SA,YiA=new SA,CH=new SA,cH=new SA,lH=new SA,BH=new ig,EH=new ig,QH=new ig;class eI{constructor(A=new SA,t=new SA,i=new SA){this.a=A,this.b=t,this.c=i}static getNormal(A,t,i,n){n.subVectors(i,t),Mc.subVectors(A,t),n.cross(Mc);const g=n.lengthSq();return g>0?n.multiplyScalar(1/Math.sqrt(g)):n.set(0,0,0)}static getBarycoord(A,t,i,n,g){Mc.subVectors(n,t),eE.subVectors(i,t),IH.subVectors(A,t);const o=Mc.dot(Mc),s=Mc.dot(eE),a=Mc.dot(IH),r=eE.dot(eE),I=eE.dot(IH),c=o*r-s*s;if(c===0)return g.set(0,0,0),null;const l=1/c,B=(r*a-s*I)*l,Q=(o*I-s*a)*l;return g.set(1-B-Q,Q,B)}static containsPoint(A,t,i,n){return this.getBarycoord(A,t,i,n,tE)===null?!1:tE.x>=0&&tE.y>=0&&tE.x+tE.y<=1}static getInterpolation(A,t,i,n,g,o,s,a){return this.getBarycoord(A,t,i,n,tE)===null?(a.x=0,a.y=0,"z"in a&&(a.z=0),"w"in a&&(a.w=0),null):(a.setScalar(0),a.addScaledVector(g,tE.x),a.addScaledVector(o,tE.y),a.addScaledVector(s,tE.z),a)}static getInterpolatedAttribute(A,t,i,n,g,o){return BH.setScalar(0),EH.setScalar(0),QH.setScalar(0),BH.fromBufferAttribute(A,t),EH.fromBufferAttribute(A,i),QH.fromBufferAttribute(A,n),o.setScalar(0),o.addScaledVector(BH,g.x),o.addScaledVector(EH,g.y),o.addScaledVector(QH,g.z),o}static isFrontFacing(A,t,i,n){return Mc.subVectors(i,t),eE.subVectors(A,t),Mc.cross(eE).dot(n)<0}set(A,t,i){return this.a.copy(A),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(A,t,i,n){return this.a.copy(A[t]),this.b.copy(A[i]),this.c.copy(A[n]),this}setFromAttributeAndIndices(A,t,i,n){return this.a.fromBufferAttribute(A,t),this.b.fromBufferAttribute(A,i),this.c.fromBufferAttribute(A,n),this}clone(){return new this.constructor().copy(this)}copy(A){return this.a.copy(A.a),this.b.copy(A.b),this.c.copy(A.c),this}getArea(){return Mc.subVectors(this.c,this.b),eE.subVectors(this.a,this.b),Mc.cross(eE).length()*.5}getMidpoint(A){return A.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(A){return eI.getNormal(this.a,this.b,this.c,A)}getPlane(A){return A.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(A,t){return eI.getBarycoord(A,this.a,this.b,this.c,t)}getInterpolation(A,t,i,n,g){return eI.getInterpolation(A,this.a,this.b,this.c,t,i,n,g)}containsPoint(A){return eI.containsPoint(A,this.a,this.b,this.c)}isFrontFacing(A){return eI.isFrontFacing(this.a,this.b,this.c,A)}intersectsBox(A){return A.intersectsTriangle(this)}closestPointToPoint(A,t){const i=this.a,n=this.b,g=this.c;let o,s;gD.subVectors(n,i),oD.subVectors(g,i),CH.subVectors(A,i);const a=gD.dot(CH),r=oD.dot(CH);if(a<=0&&r<=0)return t.copy(i);cH.subVectors(A,n);const I=gD.dot(cH),c=oD.dot(cH);if(I>=0&&c<=I)return t.copy(n);const l=a*c-I*r;if(l<=0&&a>=0&&I<=0)return o=a/(a-I),t.copy(i).addScaledVector(gD,o);lH.subVectors(A,g);const B=gD.dot(lH),Q=oD.dot(lH);if(Q>=0&&B<=Q)return t.copy(g);const h=B*r-a*Q;if(h<=0&&r>=0&&Q<=0)return s=r/(r-Q),t.copy(i).addScaledVector(oD,s);const d=I*Q-B*c;if(d<=0&&c-I>=0&&B-Q>=0)return YiA.subVectors(g,n),s=(c-I)/(c-I+(B-Q)),t.copy(n).addScaledVector(YiA,s);const p=1/(d+h+l);return o=h*p,s=l*p,t.copy(i).addScaledVector(gD,o).addScaledVector(oD,s)}equals(A){return A.a.equals(this.a)&&A.b.equals(this.b)&&A.c.equals(this.c)}}const gyA={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},LQ={h:0,s:0,l:0},lU={h:0,s:0,l:0};function uH(e,A,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?e+(A-e)*6*t:t<1/2?A:t<2/3?e+(A-e)*6*(2/3-t):e}class Et{constructor(A,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(A,t,i)}set(A,t,i){if(t===void 0&&i===void 0){const n=A;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(A,t,i);return this}setScalar(A){return this.r=A,this.g=A,this.b=A,this}setHex(A,t=rn){return A=Math.floor(A),this.r=(A>>16&255)/255,this.g=(A>>8&255)/255,this.b=(A&255)/255,Un.colorSpaceToWorking(this,t),this}setRGB(A,t,i,n=Un.workingColorSpace){return this.r=A,this.g=t,this.b=i,Un.colorSpaceToWorking(this,n),this}setHSL(A,t,i,n=Un.workingColorSpace){if(A=JW(A,1),t=Fi(t,0,1),i=Fi(i,0,1),t===0)this.r=this.g=this.b=i;else{const g=i<=.5?i*(1+t):i+t-i*t,o=2*i-g;this.r=uH(o,g,A+1/3),this.g=uH(o,g,A),this.b=uH(o,g,A-1/3)}return Un.colorSpaceToWorking(this,n),this}setStyle(A,t=rn){function i(g){g!==void 0&&parseFloat(g)<1&&console.warn("THREE.Color: Alpha component of "+A+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(A)){let g;const o=n[1],s=n[2];switch(o){case"rgb":case"rgba":if(g=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(s))return i(g[4]),this.setRGB(Math.min(255,parseInt(g[1],10))/255,Math.min(255,parseInt(g[2],10))/255,Math.min(255,parseInt(g[3],10))/255,t);if(g=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(s))return i(g[4]),this.setRGB(Math.min(100,parseInt(g[1],10))/100,Math.min(100,parseInt(g[2],10))/100,Math.min(100,parseInt(g[3],10))/100,t);break;case"hsl":case"hsla":if(g=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(s))return i(g[4]),this.setHSL(parseFloat(g[1])/360,parseFloat(g[2])/100,parseFloat(g[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+A)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(A)){const g=n[1],o=g.length;if(o===3)return this.setRGB(parseInt(g.charAt(0),16)/15,parseInt(g.charAt(1),16)/15,parseInt(g.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(g,16),t);console.warn("THREE.Color: Invalid hex color "+A)}else if(A&&A.length>0)return this.setColorName(A,t);return this}setColorName(A,t=rn){const i=gyA[A.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+A),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(A){return this.r=A.r,this.g=A.g,this.b=A.b,this}copySRGBToLinear(A){return this.r=qE(A.r),this.g=qE(A.g),this.b=qE(A.b),this}copyLinearToSRGB(A){return this.r=jm(A.r),this.g=jm(A.g),this.b=jm(A.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(A=rn){return Un.workingToColorSpace(ja.copy(this),A),Math.round(Fi(ja.r*255,0,255))*65536+Math.round(Fi(ja.g*255,0,255))*256+Math.round(Fi(ja.b*255,0,255))}getHexString(A=rn){return("000000"+this.getHex(A).toString(16)).slice(-6)}getHSL(A,t=Un.workingColorSpace){Un.workingToColorSpace(ja.copy(this),t);const i=ja.r,n=ja.g,g=ja.b,o=Math.max(i,n,g),s=Math.min(i,n,g);let a,r;const I=(s+o)/2;if(s===o)a=0,r=0;else{const c=o-s;switch(r=I<=.5?c/(o+s):c/(2-o-s),o){case i:a=(n-g)/c+(n<g?6:0);break;case n:a=(g-i)/c+2;break;case g:a=(i-n)/c+4;break}a/=6}return A.h=a,A.s=r,A.l=I,A}getRGB(A,t=Un.workingColorSpace){return Un.workingToColorSpace(ja.copy(this),t),A.r=ja.r,A.g=ja.g,A.b=ja.b,A}getStyle(A=rn){Un.workingToColorSpace(ja.copy(this),A);const t=ja.r,i=ja.g,n=ja.b;return A!==rn?`color(${A} ${t.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(i*255)},${Math.round(n*255)})`}offsetHSL(A,t,i){return this.getHSL(LQ),this.setHSL(LQ.h+A,LQ.s+t,LQ.l+i)}add(A){return this.r+=A.r,this.g+=A.g,this.b+=A.b,this}addColors(A,t){return this.r=A.r+t.r,this.g=A.g+t.g,this.b=A.b+t.b,this}addScalar(A){return this.r+=A,this.g+=A,this.b+=A,this}sub(A){return this.r=Math.max(0,this.r-A.r),this.g=Math.max(0,this.g-A.g),this.b=Math.max(0,this.b-A.b),this}multiply(A){return this.r*=A.r,this.g*=A.g,this.b*=A.b,this}multiplyScalar(A){return this.r*=A,this.g*=A,this.b*=A,this}lerp(A,t){return this.r+=(A.r-this.r)*t,this.g+=(A.g-this.g)*t,this.b+=(A.b-this.b)*t,this}lerpColors(A,t,i){return this.r=A.r+(t.r-A.r)*i,this.g=A.g+(t.g-A.g)*i,this.b=A.b+(t.b-A.b)*i,this}lerpHSL(A,t){this.getHSL(LQ),A.getHSL(lU);const i=kM(LQ.h,lU.h,t),n=kM(LQ.s,lU.s,t),g=kM(LQ.l,lU.l,t);return this.setHSL(i,n,g),this}setFromVector3(A){return this.r=A.x,this.g=A.y,this.b=A.z,this}applyMatrix3(A){const t=this.r,i=this.g,n=this.b,g=A.elements;return this.r=g[0]*t+g[3]*i+g[6]*n,this.g=g[1]*t+g[4]*i+g[7]*n,this.b=g[2]*t+g[5]*i+g[8]*n,this}equals(A){return A.r===this.r&&A.g===this.g&&A.b===this.b}fromArray(A,t=0){return this.r=A[t],this.g=A[t+1],this.b=A[t+2],this}toArray(A=[],t=0){return A[t]=this.r,A[t+1]=this.g,A[t+2]=this.b,A}fromBufferAttribute(A,t){return this.r=A.getX(t),this.g=A.getY(t),this.b=A.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const ja=new Et;Et.NAMES=gyA;let Lae=0;class ho extends bB{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Lae++}),this.uuid=$I(),this.name="",this.type="Material",this.blending=Yp,this.side=tl,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=K_,this.blendDst=F_,this.blendEquation=ru,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Et(0,0,0),this.blendAlpha=0,this.depthFunc=pf,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=o4,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Xh,this.stencilZFail=Xh,this.stencilZPass=Xh,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(A){this._alphaTest>0!=A>0&&this.version++,this._alphaTest=A}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(A){if(A!==void 0)for(const t in A){const i=A[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const n=this[t];if(n===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}n&&n.isColor?n.set(i):n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[t]=i}}toJSON(A){const t=A===void 0||typeof A=="string";t&&(A={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(A).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(A).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(A).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(A).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(A).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(A).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(A).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(A).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(A).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(A).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(A).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(A).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(A).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(A).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(A).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(A).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(A).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(A).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(A).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(A).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(A).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(A).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(A).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(A).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(A).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(A).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==Yp&&(i.blending=this.blending),this.side!==tl&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==K_&&(i.blendSrc=this.blendSrc),this.blendDst!==F_&&(i.blendDst=this.blendDst),this.blendEquation!==ru&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==pf&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==o4&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Xh&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Xh&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Xh&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(g){const o=[];for(const s in g){const a=g[s];delete a.metadata,o.push(a)}return o}if(t){const g=n(A.textures),o=n(A.images);g.length>0&&(i.textures=g),o.length>0&&(i.images=o)}return i}clone(){return new this.constructor().copy(this)}copy(A){this.name=A.name,this.blending=A.blending,this.side=A.side,this.vertexColors=A.vertexColors,this.opacity=A.opacity,this.transparent=A.transparent,this.blendSrc=A.blendSrc,this.blendDst=A.blendDst,this.blendEquation=A.blendEquation,this.blendSrcAlpha=A.blendSrcAlpha,this.blendDstAlpha=A.blendDstAlpha,this.blendEquationAlpha=A.blendEquationAlpha,this.blendColor.copy(A.blendColor),this.blendAlpha=A.blendAlpha,this.depthFunc=A.depthFunc,this.depthTest=A.depthTest,this.depthWrite=A.depthWrite,this.stencilWriteMask=A.stencilWriteMask,this.stencilFunc=A.stencilFunc,this.stencilRef=A.stencilRef,this.stencilFuncMask=A.stencilFuncMask,this.stencilFail=A.stencilFail,this.stencilZFail=A.stencilZFail,this.stencilZPass=A.stencilZPass,this.stencilWrite=A.stencilWrite;const t=A.clippingPlanes;let i=null;if(t!==null){const n=t.length;i=new Array(n);for(let g=0;g!==n;++g)i[g]=t[g].clone()}return this.clippingPlanes=i,this.clipIntersection=A.clipIntersection,this.clipShadows=A.clipShadows,this.shadowSide=A.shadowSide,this.colorWrite=A.colorWrite,this.precision=A.precision,this.polygonOffset=A.polygonOffset,this.polygonOffsetFactor=A.polygonOffsetFactor,this.polygonOffsetUnits=A.polygonOffsetUnits,this.dithering=A.dithering,this.alphaTest=A.alphaTest,this.alphaHash=A.alphaHash,this.alphaToCoverage=A.alphaToCoverage,this.premultipliedAlpha=A.premultipliedAlpha,this.forceSinglePass=A.forceSinglePass,this.visible=A.visible,this.toneMapped=A.toneMapped,this.userData=JSON.parse(JSON.stringify(A.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(A){A===!0&&this.version++}}class kg extends ho{constructor(A){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Et(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ca,this.combine=iG,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.fog=A.fog,this}}const mE=xae();function xae(){const e=new ArrayBuffer(4),A=new Float32Array(e),t=new Uint32Array(e),i=new Uint32Array(512),n=new Uint32Array(512);for(let a=0;a<256;++a){const r=a-127;r<-27?(i[a]=0,i[a|256]=32768,n[a]=24,n[a|256]=24):r<-14?(i[a]=1024>>-r-14,i[a|256]=1024>>-r-14|32768,n[a]=-r-1,n[a|256]=-r-1):r<=15?(i[a]=r+15<<10,i[a|256]=r+15<<10|32768,n[a]=13,n[a|256]=13):r<128?(i[a]=31744,i[a|256]=64512,n[a]=24,n[a|256]=24):(i[a]=31744,i[a|256]=64512,n[a]=13,n[a|256]=13)}const g=new Uint32Array(2048),o=new Uint32Array(64),s=new Uint32Array(64);for(let a=1;a<1024;++a){let r=a<<13,I=0;for(;!(r&8388608);)r<<=1,I-=8388608;r&=-8388609,I+=947912704,g[a]=r|I}for(let a=1024;a<2048;++a)g[a]=939524096+(a-1024<<13);for(let a=1;a<31;++a)o[a]=a<<23;o[31]=1199570944,o[32]=2147483648;for(let a=33;a<63;++a)o[a]=2147483648+(a-32<<23);o[63]=3347054592;for(let a=1;a<64;++a)a!==32&&(s[a]=1024);return{floatView:A,uint32View:t,baseTable:i,shiftTable:n,mantissaTable:g,exponentTable:o,offsetTable:s}}function zr(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=Fi(e,-65504,65504),mE.floatView[0]=e;const A=mE.uint32View[0],t=A>>23&511;return mE.baseTable[t]+((A&8388607)>>mE.shiftTable[t])}function Nk(e){const A=e>>10;return mE.uint32View[0]=mE.mantissaTable[mE.offsetTable[A]+(e&1023)]+mE.exponentTable[A],mE.floatView[0]}class Tae{static toHalfFloat(A){return zr(A)}static fromHalfFloat(A){return Nk(A)}}const as=new SA,BU=new lt;let qae=0;class ji{constructor(A,t,i=!1){if(Array.isArray(A))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:qae++}),this.name="",this.array=A,this.itemSize=t,this.count=A!==void 0?A.length/t:0,this.normalized=i,this.usage=UN,this.updateRanges=[],this.gpuType=br,this.version=0}onUploadCallback(){}set needsUpdate(A){A===!0&&this.version++}setUsage(A){return this.usage=A,this}addUpdateRange(A,t){this.updateRanges.push({start:A,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(A){return this.name=A.name,this.array=new A.array.constructor(A.array),this.itemSize=A.itemSize,this.count=A.count,this.normalized=A.normalized,this.usage=A.usage,this.gpuType=A.gpuType,this}copyAt(A,t,i){A*=this.itemSize,i*=t.itemSize;for(let n=0,g=this.itemSize;n<g;n++)this.array[A+n]=t.array[i+n];return this}copyArray(A){return this.array.set(A),this}applyMatrix3(A){if(this.itemSize===2)for(let t=0,i=this.count;t<i;t++)BU.fromBufferAttribute(this,t),BU.applyMatrix3(A),this.setXY(t,BU.x,BU.y);else if(this.itemSize===3)for(let t=0,i=this.count;t<i;t++)as.fromBufferAttribute(this,t),as.applyMatrix3(A),this.setXYZ(t,as.x,as.y,as.z);return this}applyMatrix4(A){for(let t=0,i=this.count;t<i;t++)as.fromBufferAttribute(this,t),as.applyMatrix4(A),this.setXYZ(t,as.x,as.y,as.z);return this}applyNormalMatrix(A){for(let t=0,i=this.count;t<i;t++)as.fromBufferAttribute(this,t),as.applyNormalMatrix(A),this.setXYZ(t,as.x,as.y,as.z);return this}transformDirection(A){for(let t=0,i=this.count;t<i;t++)as.fromBufferAttribute(this,t),as.transformDirection(A),this.setXYZ(t,as.x,as.y,as.z);return this}set(A,t=0){return this.array.set(A,t),this}getComponent(A,t){let i=this.array[A*this.itemSize+t];return this.normalized&&(i=wr(i,this.array)),i}setComponent(A,t,i){return this.normalized&&(i=an(i,this.array)),this.array[A*this.itemSize+t]=i,this}getX(A){let t=this.array[A*this.itemSize];return this.normalized&&(t=wr(t,this.array)),t}setX(A,t){return this.normalized&&(t=an(t,this.array)),this.array[A*this.itemSize]=t,this}getY(A){let t=this.array[A*this.itemSize+1];return this.normalized&&(t=wr(t,this.array)),t}setY(A,t){return this.normalized&&(t=an(t,this.array)),this.array[A*this.itemSize+1]=t,this}getZ(A){let t=this.array[A*this.itemSize+2];return this.normalized&&(t=wr(t,this.array)),t}setZ(A,t){return this.normalized&&(t=an(t,this.array)),this.array[A*this.itemSize+2]=t,this}getW(A){let t=this.array[A*this.itemSize+3];return this.normalized&&(t=wr(t,this.array)),t}setW(A,t){return this.normalized&&(t=an(t,this.array)),this.array[A*this.itemSize+3]=t,this}setXY(A,t,i){return A*=this.itemSize,this.normalized&&(t=an(t,this.array),i=an(i,this.array)),this.array[A+0]=t,this.array[A+1]=i,this}setXYZ(A,t,i,n){return A*=this.itemSize,this.normalized&&(t=an(t,this.array),i=an(i,this.array),n=an(n,this.array)),this.array[A+0]=t,this.array[A+1]=i,this.array[A+2]=n,this}setXYZW(A,t,i,n,g){return A*=this.itemSize,this.normalized&&(t=an(t,this.array),i=an(i,this.array),n=an(n,this.array),g=an(g,this.array)),this.array[A+0]=t,this.array[A+1]=i,this.array[A+2]=n,this.array[A+3]=g,this}onUpload(A){return this.onUploadCallback=A,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const A={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(A.name=this.name),this.usage!==UN&&(A.usage=this.usage),A}}class Yae extends ji{constructor(A,t,i){super(new Int8Array(A),t,i)}}class Hae extends ji{constructor(A,t,i){super(new Uint8Array(A),t,i)}}class Oae extends ji{constructor(A,t,i){super(new Uint8ClampedArray(A),t,i)}}class Pae extends ji{constructor(A,t,i){super(new Int16Array(A),t,i)}}class xW extends ji{constructor(A,t,i){super(new Uint16Array(A),t,i)}}class jae extends ji{constructor(A,t,i){super(new Int32Array(A),t,i)}}class TW extends ji{constructor(A,t,i){super(new Uint32Array(A),t,i)}}class zae extends ji{constructor(A,t,i){super(new Uint16Array(A),t,i),this.isFloat16BufferAttribute=!0}getX(A){let t=Nk(this.array[A*this.itemSize]);return this.normalized&&(t=wr(t,this.array)),t}setX(A,t){return this.normalized&&(t=an(t,this.array)),this.array[A*this.itemSize]=zr(t),this}getY(A){let t=Nk(this.array[A*this.itemSize+1]);return this.normalized&&(t=wr(t,this.array)),t}setY(A,t){return this.normalized&&(t=an(t,this.array)),this.array[A*this.itemSize+1]=zr(t),this}getZ(A){let t=Nk(this.array[A*this.itemSize+2]);return this.normalized&&(t=wr(t,this.array)),t}setZ(A,t){return this.normalized&&(t=an(t,this.array)),this.array[A*this.itemSize+2]=zr(t),this}getW(A){let t=Nk(this.array[A*this.itemSize+3]);return this.normalized&&(t=wr(t,this.array)),t}setW(A,t){return this.normalized&&(t=an(t,this.array)),this.array[A*this.itemSize+3]=zr(t),this}setXY(A,t,i){return A*=this.itemSize,this.normalized&&(t=an(t,this.array),i=an(i,this.array)),this.array[A+0]=zr(t),this.array[A+1]=zr(i),this}setXYZ(A,t,i,n){return A*=this.itemSize,this.normalized&&(t=an(t,this.array),i=an(i,this.array),n=an(n,this.array)),this.array[A+0]=zr(t),this.array[A+1]=zr(i),this.array[A+2]=zr(n),this}setXYZW(A,t,i,n,g){return A*=this.itemSize,this.normalized&&(t=an(t,this.array),i=an(i,this.array),n=an(n,this.array),g=an(g,this.array)),this.array[A+0]=zr(t),this.array[A+1]=zr(i),this.array[A+2]=zr(n),this.array[A+3]=zr(g),this}}class $t extends ji{constructor(A,t,i){super(new Float32Array(A),t,i)}}let Zae=0;const mC=new ni,dH=new Bn,sD=new SA,UI=new Ag,T0=new Ag,Vs=new SA;class Ni extends bB{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Zae++}),this.uuid=$I(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(A){return Array.isArray(A)?this.index=new(tyA(A)?TW:xW)(A,1):this.index=A,this}setIndirect(A){return this.indirect=A,this}getIndirect(){return this.indirect}getAttribute(A){return this.attributes[A]}setAttribute(A,t){return this.attributes[A]=t,this}deleteAttribute(A){return delete this.attributes[A],this}hasAttribute(A){return this.attributes[A]!==void 0}addGroup(A,t,i=0){this.groups.push({start:A,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(A,t){this.drawRange.start=A,this.drawRange.count=t}applyMatrix4(A){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(A),t.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const g=new An().getNormalMatrix(A);i.applyNormalMatrix(g),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(A),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(A){return mC.makeRotationFromQuaternion(A),this.applyMatrix4(mC),this}rotateX(A){return mC.makeRotationX(A),this.applyMatrix4(mC),this}rotateY(A){return mC.makeRotationY(A),this.applyMatrix4(mC),this}rotateZ(A){return mC.makeRotationZ(A),this.applyMatrix4(mC),this}translate(A,t,i){return mC.makeTranslation(A,t,i),this.applyMatrix4(mC),this}scale(A,t,i){return mC.makeScale(A,t,i),this.applyMatrix4(mC),this}lookAt(A){return dH.lookAt(A),dH.updateMatrix(),this.applyMatrix4(dH.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(sD).negate(),this.translate(sD.x,sD.y,sD.z),this}setFromPoints(A){const t=this.getAttribute("position");if(t===void 0){const i=[];for(let n=0,g=A.length;n<g;n++){const o=A[n];i.push(o.x,o.y,o.z||0)}this.setAttribute("position",new $t(i,3))}else{const i=Math.min(A.length,t.count);for(let n=0;n<i;n++){const g=A[n];t.setXYZ(n,g.x,g.y,g.z||0)}A.length>t.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Ag);const A=this.attributes.position,t=this.morphAttributes.position;if(A&&A.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new SA(-1/0,-1/0,-1/0),new SA(1/0,1/0,1/0));return}if(A!==void 0){if(this.boundingBox.setFromBufferAttribute(A),t)for(let i=0,n=t.length;i<n;i++){const g=t[i];UI.setFromBufferAttribute(g),this.morphTargetsRelative?(Vs.addVectors(this.boundingBox.min,UI.min),this.boundingBox.expandByPoint(Vs),Vs.addVectors(this.boundingBox.max,UI.max),this.boundingBox.expandByPoint(Vs)):(this.boundingBox.expandByPoint(UI.min),this.boundingBox.expandByPoint(UI.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new xs);const A=this.attributes.position,t=this.morphAttributes.position;if(A&&A.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new SA,1/0);return}if(A){const i=this.boundingSphere.center;if(UI.setFromBufferAttribute(A),t)for(let g=0,o=t.length;g<o;g++){const s=t[g];T0.setFromBufferAttribute(s),this.morphTargetsRelative?(Vs.addVectors(UI.min,T0.min),UI.expandByPoint(Vs),Vs.addVectors(UI.max,T0.max),UI.expandByPoint(Vs)):(UI.expandByPoint(T0.min),UI.expandByPoint(T0.max))}UI.getCenter(i);let n=0;for(let g=0,o=A.count;g<o;g++)Vs.fromBufferAttribute(A,g),n=Math.max(n,i.distanceToSquared(Vs));if(t)for(let g=0,o=t.length;g<o;g++){const s=t[g],a=this.morphTargetsRelative;for(let r=0,I=s.count;r<I;r++)Vs.fromBufferAttribute(s,r),a&&(sD.fromBufferAttribute(A,r),Vs.add(sD)),n=Math.max(n,i.distanceToSquared(Vs))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const A=this.index,t=this.attributes;if(A===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=t.position,n=t.normal,g=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new ji(new Float32Array(4*i.count),4));const o=this.getAttribute("tangent"),s=[],a=[];for(let G=0;G<i.count;G++)s[G]=new SA,a[G]=new SA;const r=new SA,I=new SA,c=new SA,l=new lt,B=new lt,Q=new lt,h=new SA,d=new SA;function p(G,M,w){r.fromBufferAttribute(i,G),I.fromBufferAttribute(i,M),c.fromBufferAttribute(i,w),l.fromBufferAttribute(g,G),B.fromBufferAttribute(g,M),Q.fromBufferAttribute(g,w),I.sub(r),c.sub(r),B.sub(l),Q.sub(l);const b=1/(B.x*Q.y-Q.x*B.y);isFinite(b)&&(h.copy(I).multiplyScalar(Q.y).addScaledVector(c,-B.y).multiplyScalar(b),d.copy(c).multiplyScalar(B.x).addScaledVector(I,-Q.x).multiplyScalar(b),s[G].add(h),s[M].add(h),s[w].add(h),a[G].add(d),a[M].add(d),a[w].add(d))}let y=this.groups;y.length===0&&(y=[{start:0,count:A.count}]);for(let G=0,M=y.length;G<M;++G){const w=y[G],b=w.start,_=w.count;for(let K=b,J=b+_;K<J;K+=3)p(A.getX(K+0),A.getX(K+1),A.getX(K+2))}const m=new SA,D=new SA,S=new SA,k=new SA;function N(G){S.fromBufferAttribute(n,G),k.copy(S);const M=s[G];m.copy(M),m.sub(S.multiplyScalar(S.dot(M))).normalize(),D.crossVectors(k,M);const b=D.dot(a[G])<0?-1:1;o.setXYZW(G,m.x,m.y,m.z,b)}for(let G=0,M=y.length;G<M;++G){const w=y[G],b=w.start,_=w.count;for(let K=b,J=b+_;K<J;K+=3)N(A.getX(K+0)),N(A.getX(K+1)),N(A.getX(K+2))}}computeVertexNormals(){const A=this.index,t=this.getAttribute("position");if(t!==void 0){let i=this.getAttribute("normal");if(i===void 0)i=new ji(new Float32Array(t.count*3),3),this.setAttribute("normal",i);else for(let l=0,B=i.count;l<B;l++)i.setXYZ(l,0,0,0);const n=new SA,g=new SA,o=new SA,s=new SA,a=new SA,r=new SA,I=new SA,c=new SA;if(A)for(let l=0,B=A.count;l<B;l+=3){const Q=A.getX(l+0),h=A.getX(l+1),d=A.getX(l+2);n.fromBufferAttribute(t,Q),g.fromBufferAttribute(t,h),o.fromBufferAttribute(t,d),I.subVectors(o,g),c.subVectors(n,g),I.cross(c),s.fromBufferAttribute(i,Q),a.fromBufferAttribute(i,h),r.fromBufferAttribute(i,d),s.add(I),a.add(I),r.add(I),i.setXYZ(Q,s.x,s.y,s.z),i.setXYZ(h,a.x,a.y,a.z),i.setXYZ(d,r.x,r.y,r.z)}else for(let l=0,B=t.count;l<B;l+=3)n.fromBufferAttribute(t,l+0),g.fromBufferAttribute(t,l+1),o.fromBufferAttribute(t,l+2),I.subVectors(o,g),c.subVectors(n,g),I.cross(c),i.setXYZ(l+0,I.x,I.y,I.z),i.setXYZ(l+1,I.x,I.y,I.z),i.setXYZ(l+2,I.x,I.y,I.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const A=this.attributes.normal;for(let t=0,i=A.count;t<i;t++)Vs.fromBufferAttribute(A,t),Vs.normalize(),A.setXYZ(t,Vs.x,Vs.y,Vs.z)}toNonIndexed(){function A(s,a){const r=s.array,I=s.itemSize,c=s.normalized,l=new r.constructor(a.length*I);let B=0,Q=0;for(let h=0,d=a.length;h<d;h++){s.isInterleavedBufferAttribute?B=a[h]*s.data.stride+s.offset:B=a[h]*I;for(let p=0;p<I;p++)l[Q++]=r[B++]}return new ji(l,I,c)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Ni,i=this.index.array,n=this.attributes;for(const s in n){const a=n[s],r=A(a,i);t.setAttribute(s,r)}const g=this.morphAttributes;for(const s in g){const a=[],r=g[s];for(let I=0,c=r.length;I<c;I++){const l=r[I],B=A(l,i);a.push(B)}t.morphAttributes[s]=a}t.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let s=0,a=o.length;s<a;s++){const r=o[s];t.addGroup(r.start,r.count,r.materialIndex)}return t}toJSON(){const A={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(A.uuid=this.uuid,A.type=this.type,this.name!==""&&(A.name=this.name),Object.keys(this.userData).length>0&&(A.userData=this.userData),this.parameters!==void 0){const a=this.parameters;for(const r in a)a[r]!==void 0&&(A[r]=a[r]);return A}A.data={attributes:{}};const t=this.index;t!==null&&(A.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const a in i){const r=i[a];A.data.attributes[a]=r.toJSON(A.data)}const n={};let g=!1;for(const a in this.morphAttributes){const r=this.morphAttributes[a],I=[];for(let c=0,l=r.length;c<l;c++){const B=r[c];I.push(B.toJSON(A.data))}I.length>0&&(n[a]=I,g=!0)}g&&(A.data.morphAttributes=n,A.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(A.data.groups=JSON.parse(JSON.stringify(o)));const s=this.boundingSphere;return s!==null&&(A.data.boundingSphere=s.toJSON()),A}clone(){return new this.constructor().copy(this)}copy(A){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=A.name;const i=A.index;i!==null&&this.setIndex(i.clone());const n=A.attributes;for(const r in n){const I=n[r];this.setAttribute(r,I.clone(t))}const g=A.morphAttributes;for(const r in g){const I=[],c=g[r];for(let l=0,B=c.length;l<B;l++)I.push(c[l].clone(t));this.morphAttributes[r]=I}this.morphTargetsRelative=A.morphTargetsRelative;const o=A.groups;for(let r=0,I=o.length;r<I;r++){const c=o[r];this.addGroup(c.start,c.count,c.materialIndex)}const s=A.boundingBox;s!==null&&(this.boundingBox=s.clone());const a=A.boundingSphere;return a!==null&&(this.boundingSphere=a.clone()),this.drawRange.start=A.drawRange.start,this.drawRange.count=A.drawRange.count,this.userData=A.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const HiA=new ni,fh=new Fw,EU=new xs,OiA=new SA,QU=new SA,uU=new SA,dU=new SA,hH=new SA,hU=new SA,PiA=new SA,pU=new SA;class pn extends Bn{constructor(A=new Ni,t=new kg){super(),this.isMesh=!0,this.type="Mesh",this.geometry=A,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(A,t){return super.copy(A,t),A.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=A.morphTargetInfluences.slice()),A.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},A.morphTargetDictionary)),this.material=Array.isArray(A.material)?A.material.slice():A.material,this.geometry=A.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let g=0,o=n.length;g<o;g++){const s=n[g].name||String(g);this.morphTargetInfluences.push(0),this.morphTargetDictionary[s]=g}}}}getVertexPosition(A,t){const i=this.geometry,n=i.attributes.position,g=i.morphAttributes.position,o=i.morphTargetsRelative;t.fromBufferAttribute(n,A);const s=this.morphTargetInfluences;if(g&&s){hU.set(0,0,0);for(let a=0,r=g.length;a<r;a++){const I=s[a],c=g[a];I!==0&&(hH.fromBufferAttribute(c,A),o?hU.addScaledVector(hH,I):hU.addScaledVector(hH.sub(t),I))}t.add(hU)}return t}raycast(A,t){const i=this.geometry,n=this.material,g=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),EU.copy(i.boundingSphere),EU.applyMatrix4(g),fh.copy(A.ray).recast(A.near),!(EU.containsPoint(fh.origin)===!1&&(fh.intersectSphere(EU,OiA)===null||fh.origin.distanceToSquared(OiA)>(A.far-A.near)**2))&&(HiA.copy(g).invert(),fh.copy(A.ray).applyMatrix4(HiA),!(i.boundingBox!==null&&fh.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(A,t,fh)))}_computeIntersections(A,t,i){let n;const g=this.geometry,o=this.material,s=g.index,a=g.attributes.position,r=g.attributes.uv,I=g.attributes.uv1,c=g.attributes.normal,l=g.groups,B=g.drawRange;if(s!==null)if(Array.isArray(o))for(let Q=0,h=l.length;Q<h;Q++){const d=l[Q],p=o[d.materialIndex],y=Math.max(d.start,B.start),m=Math.min(s.count,Math.min(d.start+d.count,B.start+B.count));for(let D=y,S=m;D<S;D+=3){const k=s.getX(D),N=s.getX(D+1),G=s.getX(D+2);n=fU(this,p,A,i,r,I,c,k,N,G),n&&(n.faceIndex=Math.floor(D/3),n.face.materialIndex=d.materialIndex,t.push(n))}}else{const Q=Math.max(0,B.start),h=Math.min(s.count,B.start+B.count);for(let d=Q,p=h;d<p;d+=3){const y=s.getX(d),m=s.getX(d+1),D=s.getX(d+2);n=fU(this,o,A,i,r,I,c,y,m,D),n&&(n.faceIndex=Math.floor(d/3),t.push(n))}}else if(a!==void 0)if(Array.isArray(o))for(let Q=0,h=l.length;Q<h;Q++){const d=l[Q],p=o[d.materialIndex],y=Math.max(d.start,B.start),m=Math.min(a.count,Math.min(d.start+d.count,B.start+B.count));for(let D=y,S=m;D<S;D+=3){const k=D,N=D+1,G=D+2;n=fU(this,p,A,i,r,I,c,k,N,G),n&&(n.faceIndex=Math.floor(D/3),n.face.materialIndex=d.materialIndex,t.push(n))}}else{const Q=Math.max(0,B.start),h=Math.min(a.count,B.start+B.count);for(let d=Q,p=h;d<p;d+=3){const y=d,m=d+1,D=d+2;n=fU(this,o,A,i,r,I,c,y,m,D),n&&(n.faceIndex=Math.floor(d/3),t.push(n))}}}}function Wae(e,A,t,i,n,g,o,s){let a;if(A.side===Ua?a=i.intersectTriangle(o,g,n,!0,s):a=i.intersectTriangle(n,g,o,A.side===tl,s),a===null)return null;pU.copy(s),pU.applyMatrix4(e.matrixWorld);const r=t.ray.origin.distanceTo(pU);return r<t.near||r>t.far?null:{distance:r,point:pU.clone(),object:e}}function fU(e,A,t,i,n,g,o,s,a,r){e.getVertexPosition(s,QU),e.getVertexPosition(a,uU),e.getVertexPosition(r,dU);const I=Wae(e,A,t,i,QU,uU,dU,PiA);if(I){const c=new SA;eI.getBarycoord(PiA,QU,uU,dU,c),n&&(I.uv=eI.getInterpolatedAttribute(n,s,a,r,c,new lt)),g&&(I.uv1=eI.getInterpolatedAttribute(g,s,a,r,c,new lt)),o&&(I.normal=eI.getInterpolatedAttribute(o,s,a,r,c,new SA),I.normal.dot(i.direction)>0&&I.normal.multiplyScalar(-1));const l={a:s,b:a,c:r,normal:new SA,materialIndex:0};eI.getNormal(QU,uU,dU,l.normal),I.face=l,I.barycoord=c}return I}class sI extends Ni{constructor(A=1,t=1,i=1,n=1,g=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:A,height:t,depth:i,widthSegments:n,heightSegments:g,depthSegments:o};const s=this;n=Math.floor(n),g=Math.floor(g),o=Math.floor(o);const a=[],r=[],I=[],c=[];let l=0,B=0;Q("z","y","x",-1,-1,i,t,A,o,g,0),Q("z","y","x",1,-1,i,t,-A,o,g,1),Q("x","z","y",1,1,A,i,t,n,o,2),Q("x","z","y",1,-1,A,i,-t,n,o,3),Q("x","y","z",1,-1,A,t,i,n,g,4),Q("x","y","z",-1,-1,A,t,-i,n,g,5),this.setIndex(a),this.setAttribute("position",new $t(r,3)),this.setAttribute("normal",new $t(I,3)),this.setAttribute("uv",new $t(c,2));function Q(h,d,p,y,m,D,S,k,N,G,M){const w=D/N,b=S/G,_=D/2,K=S/2,J=k/2,q=N+1,v=G+1;let U=0,x=0;const T=new SA;for(let z=0;z<v;z++){const Z=z*b-K;for(let eA=0;eA<q;eA++){const aA=eA*w-_;T[h]=aA*y,T[d]=Z*m,T[p]=J,r.push(T.x,T.y,T.z),T[h]=0,T[d]=0,T[p]=k>0?1:-1,I.push(T.x,T.y,T.z),c.push(eA/N),c.push(1-z/G),U+=1}}for(let z=0;z<G;z++)for(let Z=0;Z<N;Z++){const eA=l+Z+q*z,aA=l+Z+q*(z+1),sA=l+(Z+1)+q*(z+1),pA=l+(Z+1)+q*z;a.push(eA,aA,pA),a.push(aA,sA,pA),x+=6}s.addGroup(B,x,M),B+=x,l+=U}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new sI(A.width,A.height,A.depth,A.widthSegments,A.heightSegments,A.depthSegments)}}function jS(e){const A={};for(const t in e){A[t]={};for(const i in e[t]){const n=e[t][i];n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)?n.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),A[t][i]=null):A[t][i]=n.clone():Array.isArray(n)?A[t][i]=n.slice():A[t][i]=n}}return A}function Er(e){const A={};for(let t=0;t<e.length;t++){const i=jS(e[t]);for(const n in i)A[n]=i[n]}return A}function Vae(e){const A=[];for(let t=0;t<e.length;t++)A.push(e[t].clone());return A}function oyA(e){const A=e.getRenderTarget();return A===null?e.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Un.workingColorSpace}const qW={clone:jS,merge:Er};var Xae=`void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,$ae=`void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;class Cc extends ho{constructor(A){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Xae,this.fragmentShader=$ae,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,A!==void 0&&this.setValues(A)}copy(A){return super.copy(A),this.fragmentShader=A.fragmentShader,this.vertexShader=A.vertexShader,this.uniforms=jS(A.uniforms),this.uniformsGroups=Vae(A.uniformsGroups),this.defines=Object.assign({},A.defines),this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.fog=A.fog,this.lights=A.lights,this.clipping=A.clipping,this.extensions=Object.assign({},A.extensions),this.glslVersion=A.glslVersion,this}toJSON(A){const t=super.toJSON(A);t.glslVersion=this.glslVersion,t.uniforms={};for(const n in this.uniforms){const o=this.uniforms[n].value;o&&o.isTexture?t.uniforms[n]={type:"t",value:o.toJSON(A).uuid}:o&&o.isColor?t.uniforms[n]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[n]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[n]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[n]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[n]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[n]={type:"m4",value:o.toArray()}:t.uniforms[n]={value:o}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const n in this.extensions)this.extensions[n]===!0&&(i[n]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class Ox extends Bn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ni,this.projectionMatrix=new ni,this.projectionMatrixInverse=new ni,this.coordinateSystem=jI,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(A,t){return super.copy(A,t),this.matrixWorldInverse.copy(A.matrixWorldInverse),this.projectionMatrix.copy(A.projectionMatrix),this.projectionMatrixInverse.copy(A.projectionMatrixInverse),this.coordinateSystem=A.coordinateSystem,this}getWorldDirection(A){return super.getWorldDirection(A).negate()}updateMatrixWorld(A){super.updateMatrixWorld(A),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(A,t){super.updateWorldMatrix(A,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const xQ=new SA,jiA=new lt,ziA=new lt;class Wo extends Ox{constructor(A=50,t=1,i=.1,n=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=A,this.zoom=1,this.near=i,this.far=n,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(A,t){return super.copy(A,t),this.fov=A.fov,this.zoom=A.zoom,this.near=A.near,this.far=A.far,this.focus=A.focus,this.aspect=A.aspect,this.view=A.view===null?null:Object.assign({},A.view),this.filmGauge=A.filmGauge,this.filmOffset=A.filmOffset,this}setFocalLength(A){const t=.5*this.getFilmHeight()/A;this.fov=OS*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const A=Math.tan(Op*.5*this.fov);return .5*this.getFilmHeight()/A}getEffectiveFOV(){return OS*2*Math.atan(Math.tan(Op*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(A,t,i){xQ.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(xQ.x,xQ.y).multiplyScalar(-A/xQ.z),xQ.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(xQ.x,xQ.y).multiplyScalar(-A/xQ.z)}getViewSize(A,t){return this.getViewBounds(A,jiA,ziA),t.subVectors(ziA,jiA)}setViewOffset(A,t,i,n,g,o){this.aspect=A/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=A,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=g,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const A=this.near;let t=A*Math.tan(Op*.5*this.fov)/this.zoom,i=2*t,n=this.aspect*i,g=-.5*n;const o=this.view;if(this.view!==null&&this.view.enabled){const a=o.fullWidth,r=o.fullHeight;g+=o.offsetX*n/a,t-=o.offsetY*i/r,n*=o.width/a,i*=o.height/r}const s=this.filmOffset;s!==0&&(g+=A*s/this.getFilmWidth()),this.projectionMatrix.makePerspective(g,g+n,t,t-i,A,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(A){const t=super.toJSON(A);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const aD=-90,rD=1;class syA extends Bn{constructor(A,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new Wo(aD,rD,A,t);n.layers=this.layers,this.add(n);const g=new Wo(aD,rD,A,t);g.layers=this.layers,this.add(g);const o=new Wo(aD,rD,A,t);o.layers=this.layers,this.add(o);const s=new Wo(aD,rD,A,t);s.layers=this.layers,this.add(s);const a=new Wo(aD,rD,A,t);a.layers=this.layers,this.add(a);const r=new Wo(aD,rD,A,t);r.layers=this.layers,this.add(r)}updateCoordinateSystem(){const A=this.coordinateSystem,t=this.children.concat(),[i,n,g,o,s,a]=t;for(const r of t)this.remove(r);if(A===jI)i.up.set(0,1,0),i.lookAt(1,0,0),n.up.set(0,1,0),n.lookAt(-1,0,0),g.up.set(0,0,-1),g.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),s.up.set(0,1,0),s.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else if(A===HS)i.up.set(0,-1,0),i.lookAt(-1,0,0),n.up.set(0,-1,0),n.lookAt(1,0,0),g.up.set(0,0,1),g.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),s.up.set(0,-1,0),s.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+A);for(const r of t)this.add(r),r.updateMatrixWorld()}update(A,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:n}=this;this.coordinateSystem!==A.coordinateSystem&&(this.coordinateSystem=A.coordinateSystem,this.updateCoordinateSystem());const[g,o,s,a,r,I]=this.children,c=A.getRenderTarget(),l=A.getActiveCubeFace(),B=A.getActiveMipmapLevel(),Q=A.xr.enabled;A.xr.enabled=!1;const h=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,A.setRenderTarget(i,0,n),A.render(t,g),A.setRenderTarget(i,1,n),A.render(t,o),A.setRenderTarget(i,2,n),A.render(t,s),A.setRenderTarget(i,3,n),A.render(t,a),A.setRenderTarget(i,4,n),A.render(t,r),i.texture.generateMipmaps=h,A.setRenderTarget(i,5,n),A.render(t,I),A.setRenderTarget(c,l,B),A.xr.enabled=Q,i.texture.needsPMREMUpdate=!0}}class sG extends Kg{constructor(A=[],t=rQ,i,n,g,o,s,a,r,I){super(A,t,i,n,g,o,s,a,r,I),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(A){this.image=A}}class ayA extends il{constructor(A=1,t={}){super(A,A,t),this.isWebGLCubeRenderTarget=!0;const i={width:A,height:A,depth:1},n=[i,i,i,i,i,i];this.texture=new sG(n),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(A,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:`

				varying vec3 vWorldDirection;

				vec3 transformDirection( in vec3 dir, in mat4 matrix ) {

					return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );

				}

				void main() {

					vWorldDirection = transformDirection( position, modelMatrix );

					#include <begin_vertex>
					#include <project_vertex>

				}
			`,fragmentShader:`

				uniform sampler2D tEquirect;

				varying vec3 vWorldDirection;

				#include <common>

				void main() {

					vec3 direction = normalize( vWorldDirection );

					vec2 sampleUV = equirectUv( direction );

					gl_FragColor = texture2D( tEquirect, sampleUV );

				}
			`},n=new sI(5,5,5),g=new Cc({name:"CubemapFromEquirect",uniforms:jS(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:Ua,blending:TE});g.uniforms.tEquirect.value=t;const o=new pn(n,g),s=t.minFilter;return t.minFilter===Gr&&(t.minFilter=qg),new syA(1,10,this).update(A,o),t.minFilter=s,o.geometry.dispose(),o.material.dispose(),this}clear(A,t=!0,i=!0,n=!0){const g=A.getRenderTarget();for(let o=0;o<6;o++)A.setRenderTarget(this,o),A.clear(t,i,n);A.setRenderTarget(g)}}class sa extends Bn{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Are={type:"move"};class vK{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new sa,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new sa,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new SA,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new SA),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new sa,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new SA,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new SA),this._grip}dispatchEvent(A){return this._targetRay!==null&&this._targetRay.dispatchEvent(A),this._grip!==null&&this._grip.dispatchEvent(A),this._hand!==null&&this._hand.dispatchEvent(A),this}connect(A){if(A&&A.hand){const t=this._hand;if(t)for(const i of A.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:A}),this}disconnect(A){return this.dispatchEvent({type:"disconnected",data:A}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(A,t,i){let n=null,g=null,o=null;const s=this._targetRay,a=this._grip,r=this._hand;if(A&&t.session.visibilityState!=="visible-blurred"){if(r&&A.hand){o=!0;for(const h of A.hand.values()){const d=t.getJointPose(h,i),p=this._getHandJoint(r,h);d!==null&&(p.matrix.fromArray(d.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=d.radius),p.visible=d!==null}const I=r.joints["index-finger-tip"],c=r.joints["thumb-tip"],l=I.position.distanceTo(c.position),B=.02,Q=.005;r.inputState.pinching&&l>B+Q?(r.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:A.handedness,target:this})):!r.inputState.pinching&&l<=B-Q&&(r.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:A.handedness,target:this}))}else a!==null&&A.gripSpace&&(g=t.getPose(A.gripSpace,i),g!==null&&(a.matrix.fromArray(g.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,g.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(g.linearVelocity)):a.hasLinearVelocity=!1,g.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(g.angularVelocity)):a.hasAngularVelocity=!1));s!==null&&(n=t.getPose(A.targetRaySpace,i),n===null&&g!==null&&(n=g),n!==null&&(s.matrix.fromArray(n.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,n.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(n.linearVelocity)):s.hasLinearVelocity=!1,n.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(n.angularVelocity)):s.hasAngularVelocity=!1,this.dispatchEvent(Are)))}return s!==null&&(s.visible=n!==null),a!==null&&(a.visible=g!==null),r!==null&&(r.visible=o!==null),this}_getHandJoint(A,t){if(A.joints[t.jointName]===void 0){const i=new sa;i.matrixAutoUpdate=!1,i.visible=!1,A.joints[t.jointName]=i,A.add(i)}return A.joints[t.jointName]}}class Px{constructor(A,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new Et(A),this.density=t}clone(){return new Px(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class aG{constructor(A,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new Et(A),this.near=t,this.far=i}clone(){return new aG(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}let rG=class extends Bn{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new ca,this.environmentIntensity=1,this.environmentRotation=new ca,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(A,t){return super.copy(A,t),A.background!==null&&(this.background=A.background.clone()),A.environment!==null&&(this.environment=A.environment.clone()),A.fog!==null&&(this.fog=A.fog.clone()),this.backgroundBlurriness=A.backgroundBlurriness,this.backgroundIntensity=A.backgroundIntensity,this.backgroundRotation.copy(A.backgroundRotation),this.environmentIntensity=A.environmentIntensity,this.environmentRotation.copy(A.environmentRotation),A.overrideMaterial!==null&&(this.overrideMaterial=A.overrideMaterial.clone()),this.matrixAutoUpdate=A.matrixAutoUpdate,this}toJSON(A){const t=super.toJSON(A);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}};class _w{constructor(A,t){this.isInterleavedBuffer=!0,this.array=A,this.stride=t,this.count=A!==void 0?A.length/t:0,this.usage=UN,this.updateRanges=[],this.version=0,this.uuid=$I()}onUploadCallback(){}set needsUpdate(A){A===!0&&this.version++}setUsage(A){return this.usage=A,this}addUpdateRange(A,t){this.updateRanges.push({start:A,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(A){return this.array=new A.array.constructor(A.array),this.count=A.count,this.stride=A.stride,this.usage=A.usage,this}copyAt(A,t,i){A*=this.stride,i*=t.stride;for(let n=0,g=this.stride;n<g;n++)this.array[A+n]=t.array[i+n];return this}set(A,t=0){return this.array.set(A,t),this}clone(A){A.arrayBuffers===void 0&&(A.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=$I()),A.arrayBuffers[this.array.buffer._uuid]===void 0&&(A.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(A.arrayBuffers[this.array.buffer._uuid]),i=new this.constructor(t,this.stride);return i.setUsage(this.usage),i}onUpload(A){return this.onUploadCallback=A,this}toJSON(A){return A.arrayBuffers===void 0&&(A.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=$I()),A.arrayBuffers[this.array.buffer._uuid]===void 0&&(A.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const Br=new SA;class CQ{constructor(A,t,i,n=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=A,this.itemSize=t,this.offset=i,this.normalized=n}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(A){this.data.needsUpdate=A}applyMatrix4(A){for(let t=0,i=this.data.count;t<i;t++)Br.fromBufferAttribute(this,t),Br.applyMatrix4(A),this.setXYZ(t,Br.x,Br.y,Br.z);return this}applyNormalMatrix(A){for(let t=0,i=this.count;t<i;t++)Br.fromBufferAttribute(this,t),Br.applyNormalMatrix(A),this.setXYZ(t,Br.x,Br.y,Br.z);return this}transformDirection(A){for(let t=0,i=this.count;t<i;t++)Br.fromBufferAttribute(this,t),Br.transformDirection(A),this.setXYZ(t,Br.x,Br.y,Br.z);return this}getComponent(A,t){let i=this.array[A*this.data.stride+this.offset+t];return this.normalized&&(i=wr(i,this.array)),i}setComponent(A,t,i){return this.normalized&&(i=an(i,this.array)),this.data.array[A*this.data.stride+this.offset+t]=i,this}setX(A,t){return this.normalized&&(t=an(t,this.array)),this.data.array[A*this.data.stride+this.offset]=t,this}setY(A,t){return this.normalized&&(t=an(t,this.array)),this.data.array[A*this.data.stride+this.offset+1]=t,this}setZ(A,t){return this.normalized&&(t=an(t,this.array)),this.data.array[A*this.data.stride+this.offset+2]=t,this}setW(A,t){return this.normalized&&(t=an(t,this.array)),this.data.array[A*this.data.stride+this.offset+3]=t,this}getX(A){let t=this.data.array[A*this.data.stride+this.offset];return this.normalized&&(t=wr(t,this.array)),t}getY(A){let t=this.data.array[A*this.data.stride+this.offset+1];return this.normalized&&(t=wr(t,this.array)),t}getZ(A){let t=this.data.array[A*this.data.stride+this.offset+2];return this.normalized&&(t=wr(t,this.array)),t}getW(A){let t=this.data.array[A*this.data.stride+this.offset+3];return this.normalized&&(t=wr(t,this.array)),t}setXY(A,t,i){return A=A*this.data.stride+this.offset,this.normalized&&(t=an(t,this.array),i=an(i,this.array)),this.data.array[A+0]=t,this.data.array[A+1]=i,this}setXYZ(A,t,i,n){return A=A*this.data.stride+this.offset,this.normalized&&(t=an(t,this.array),i=an(i,this.array),n=an(n,this.array)),this.data.array[A+0]=t,this.data.array[A+1]=i,this.data.array[A+2]=n,this}setXYZW(A,t,i,n,g){return A=A*this.data.stride+this.offset,this.normalized&&(t=an(t,this.array),i=an(i,this.array),n=an(n,this.array),g=an(g,this.array)),this.data.array[A+0]=t,this.data.array[A+1]=i,this.data.array[A+2]=n,this.data.array[A+3]=g,this}clone(A){if(A===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let g=0;g<this.itemSize;g++)t.push(this.data.array[n+g])}return new ji(new this.array.constructor(t),this.itemSize,this.normalized)}else return A.interleavedBuffers===void 0&&(A.interleavedBuffers={}),A.interleavedBuffers[this.data.uuid]===void 0&&(A.interleavedBuffers[this.data.uuid]=this.data.clone(A)),new CQ(A.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(A){if(A===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let g=0;g<this.itemSize;g++)t.push(this.data.array[n+g])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return A.interleavedBuffers===void 0&&(A.interleavedBuffers={}),A.interleavedBuffers[this.data.uuid]===void 0&&(A.interleavedBuffers[this.data.uuid]=this.data.toJSON(A)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}class FN extends ho{constructor(A){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Et(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.alphaMap=A.alphaMap,this.rotation=A.rotation,this.sizeAttenuation=A.sizeAttenuation,this.fog=A.fog,this}}let ID;const q0=new SA,CD=new SA,cD=new SA,lD=new lt,Y0=new lt,ryA=new ni,yU=new SA,H0=new SA,DU=new SA,ZiA=new lt,pH=new lt,WiA=new lt;class hJ extends Bn{constructor(A=new FN){if(super(),this.isSprite=!0,this.type="Sprite",ID===void 0){ID=new Ni;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new _w(t,5);ID.setIndex([0,1,2,0,2,3]),ID.setAttribute("position",new CQ(i,3,0,!1)),ID.setAttribute("uv",new CQ(i,2,3,!1))}this.geometry=ID,this.material=A,this.center=new lt(.5,.5),this.count=1}raycast(A,t){A.camera===null&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),CD.setFromMatrixScale(this.matrixWorld),ryA.copy(A.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(A.camera.matrixWorldInverse,this.matrixWorld),cD.setFromMatrixPosition(this.modelViewMatrix),A.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&CD.multiplyScalar(-cD.z);const i=this.material.rotation;let n,g;i!==0&&(g=Math.cos(i),n=Math.sin(i));const o=this.center;mU(yU.set(-.5,-.5,0),cD,o,CD,n,g),mU(H0.set(.5,-.5,0),cD,o,CD,n,g),mU(DU.set(.5,.5,0),cD,o,CD,n,g),ZiA.set(0,0),pH.set(1,0),WiA.set(1,1);let s=A.ray.intersectTriangle(yU,H0,DU,!1,q0);if(s===null&&(mU(H0.set(-.5,.5,0),cD,o,CD,n,g),pH.set(0,1),s=A.ray.intersectTriangle(yU,DU,H0,!1,q0),s===null))return;const a=A.ray.origin.distanceTo(q0);a<A.near||a>A.far||t.push({distance:a,point:q0.clone(),uv:eI.getInterpolation(q0,yU,H0,DU,ZiA,pH,WiA,new lt),face:null,object:this})}copy(A,t){return super.copy(A,t),A.center!==void 0&&this.center.copy(A.center),this.material=A.material,this}}function mU(e,A,t,i,n,g){lD.subVectors(e,t).addScalar(.5).multiply(i),n!==void 0?(Y0.x=g*lD.x-n*lD.y,Y0.y=n*lD.x+g*lD.y):Y0.copy(lD),e.copy(A),e.x+=Y0.x,e.y+=Y0.y,e.applyMatrix4(ryA)}const SU=new SA,ViA=new SA;class IyA extends Bn{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(A){super.copy(A,!1);const t=A.levels;for(let i=0,n=t.length;i<n;i++){const g=t[i];this.addLevel(g.object.clone(),g.distance,g.hysteresis)}return this.autoUpdate=A.autoUpdate,this}addLevel(A,t=0,i=0){t=Math.abs(t);const n=this.levels;let g;for(g=0;g<n.length&&!(t<n[g].distance);g++);return n.splice(g,0,{distance:t,hysteresis:i,object:A}),this.add(A),this}removeLevel(A){const t=this.levels;for(let i=0;i<t.length;i++)if(t[i].distance===A){const n=t.splice(i,1);return this.remove(n[0].object),!0}return!1}getCurrentLevel(){return this._currentLevel}getObjectForDistance(A){const t=this.levels;if(t.length>0){let i,n;for(i=1,n=t.length;i<n;i++){let g=t[i].distance;if(t[i].object.visible&&(g-=g*t[i].hysteresis),A<g)break}return t[i-1].object}return null}raycast(A,t){if(this.levels.length>0){SU.setFromMatrixPosition(this.matrixWorld);const n=A.ray.origin.distanceTo(SU);this.getObjectForDistance(n).raycast(A,t)}}update(A){const t=this.levels;if(t.length>1){SU.setFromMatrixPosition(A.matrixWorld),ViA.setFromMatrixPosition(this.matrixWorld);const i=SU.distanceTo(ViA)/A.zoom;t[0].object.visible=!0;let n,g;for(n=1,g=t.length;n<g;n++){let o=t[n].distance;if(t[n].object.visible&&(o-=o*t[n].hysteresis),i>=o)t[n-1].object.visible=!1,t[n].object.visible=!0;else break}for(this._currentLevel=n-1;n<g;n++)t[n].object.visible=!1}}toJSON(A){const t=super.toJSON(A);this.autoUpdate===!1&&(t.object.autoUpdate=!1),t.object.levels=[];const i=this.levels;for(let n=0,g=i.length;n<g;n++){const o=i[n];t.object.levels.push({object:o.object.uuid,distance:o.distance,hysteresis:o.hysteresis})}return t}}const XiA=new SA,$iA=new ig,AnA=new ig,ere=new SA,enA=new ni,wU=new SA,fH=new xs,tnA=new ni,yH=new Fw;class jx extends pn{constructor(A,t){super(A,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=g4,this.bindMatrix=new ni,this.bindMatrixInverse=new ni,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const A=this.geometry;this.boundingBox===null&&(this.boundingBox=new Ag),this.boundingBox.makeEmpty();const t=A.getAttribute("position");for(let i=0;i<t.count;i++)this.getVertexPosition(i,wU),this.boundingBox.expandByPoint(wU)}computeBoundingSphere(){const A=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new xs),this.boundingSphere.makeEmpty();const t=A.getAttribute("position");for(let i=0;i<t.count;i++)this.getVertexPosition(i,wU),this.boundingSphere.expandByPoint(wU)}copy(A,t){return super.copy(A,t),this.bindMode=A.bindMode,this.bindMatrix.copy(A.bindMatrix),this.bindMatrixInverse.copy(A.bindMatrixInverse),this.skeleton=A.skeleton,A.boundingBox!==null&&(this.boundingBox=A.boundingBox.clone()),A.boundingSphere!==null&&(this.boundingSphere=A.boundingSphere.clone()),this}raycast(A,t){const i=this.material,n=this.matrixWorld;i!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),fH.copy(this.boundingSphere),fH.applyMatrix4(n),A.ray.intersectsSphere(fH)!==!1&&(tnA.copy(n).invert(),yH.copy(A.ray).applyMatrix4(tnA),!(this.boundingBox!==null&&yH.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(A,t,yH)))}getVertexPosition(A,t){return super.getVertexPosition(A,t),this.applyBoneTransform(A,t),t}bind(A,t){this.skeleton=A,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const A=new ig,t=this.geometry.attributes.skinWeight;for(let i=0,n=t.count;i<n;i++){A.fromBufferAttribute(t,i);const g=1/A.manhattanLength();g!==1/0?A.multiplyScalar(g):A.set(1,0,0,0),t.setXYZW(i,A.x,A.y,A.z,A.w)}}updateMatrixWorld(A){super.updateMatrixWorld(A),this.bindMode===g4?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===YfA?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(A,t){const i=this.skeleton,n=this.geometry;$iA.fromBufferAttribute(n.attributes.skinIndex,A),AnA.fromBufferAttribute(n.attributes.skinWeight,A),XiA.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let g=0;g<4;g++){const o=AnA.getComponent(g);if(o!==0){const s=$iA.getComponent(g);enA.multiplyMatrices(i.bones[s].matrixWorld,i.boneInverses[s]),t.addScaledVector(ere.copy(XiA).applyMatrix4(enA),o)}}return t.applyMatrix4(this.bindMatrixInverse)}}class IG extends Bn{constructor(){super(),this.isBone=!0,this.type="Bone"}}class uB extends Kg{constructor(A=null,t=1,i=1,n,g,o,s,a,r=Ss,I=Ss,c,l){super(null,o,s,a,r,I,n,g,c,l),this.isDataTexture=!0,this.image={data:A,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const inA=new ni,tre=new ni;class Jw{constructor(A=[],t=[]){this.uuid=$I(),this.bones=A.slice(0),this.boneInverses=t,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){const A=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(A.length*16),t.length===0)this.calculateInverses();else if(A.length!==t.length){console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let i=0,n=this.bones.length;i<n;i++)this.boneInverses.push(new ni)}}calculateInverses(){this.boneInverses.length=0;for(let A=0,t=this.bones.length;A<t;A++){const i=new ni;this.bones[A]&&i.copy(this.bones[A].matrixWorld).invert(),this.boneInverses.push(i)}}pose(){for(let A=0,t=this.bones.length;A<t;A++){const i=this.bones[A];i&&i.matrixWorld.copy(this.boneInverses[A]).invert()}for(let A=0,t=this.bones.length;A<t;A++){const i=this.bones[A];i&&(i.parent&&i.parent.isBone?(i.matrix.copy(i.parent.matrixWorld).invert(),i.matrix.multiply(i.matrixWorld)):i.matrix.copy(i.matrixWorld),i.matrix.decompose(i.position,i.quaternion,i.scale))}}update(){const A=this.bones,t=this.boneInverses,i=this.boneMatrices,n=this.boneTexture;for(let g=0,o=A.length;g<o;g++){const s=A[g]?A[g].matrixWorld:tre;inA.multiplyMatrices(s,t[g]),inA.toArray(i,g*16)}n!==null&&(n.needsUpdate=!0)}clone(){return new Jw(this.bones,this.boneInverses)}computeBoneTexture(){let A=Math.sqrt(this.bones.length*4);A=Math.ceil(A/4)*4,A=Math.max(A,4);const t=new Float32Array(A*A*4);t.set(this.boneMatrices);const i=new uB(t,A,A,Ar,br);return i.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=i,this}getBoneByName(A){for(let t=0,i=this.bones.length;t<i;t++){const n=this.bones[t];if(n.name===A)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(A,t){this.uuid=A.uuid;for(let i=0,n=A.bones.length;i<n;i++){const g=A.bones[i];let o=t[g];o===void 0&&(console.warn("THREE.Skeleton: No bone found with UUID:",g),o=new IG),this.bones.push(o),this.boneInverses.push(new ni().fromArray(A.boneInverses[i]))}return this.init(),this}toJSON(){const A={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};A.uuid=this.uuid;const t=this.bones,i=this.boneInverses;for(let n=0,g=t.length;n<g;n++){const o=t[n];A.bones.push(o.uuid);const s=i[n];A.boneInverses.push(s.toArray())}return A}}class hd extends ji{constructor(A,t,i,n=1){super(A,t,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=n}copy(A){return super.copy(A),this.meshPerAttribute=A.meshPerAttribute,this}toJSON(){const A=super.toJSON();return A.meshPerAttribute=this.meshPerAttribute,A.isInstancedBufferAttribute=!0,A}}const BD=new ni,nnA=new ni,kU=[],gnA=new Ag,ire=new ni,O0=new pn,P0=new xs;class CG extends pn{constructor(A,t,i){super(A,t),this.isInstancedMesh=!0,this.instanceMatrix=new hd(new Float32Array(i*16),16),this.instanceColor=null,this.morphTexture=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let n=0;n<i;n++)this.setMatrixAt(n,ire)}computeBoundingBox(){const A=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Ag),A.boundingBox===null&&A.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,BD),gnA.copy(A.boundingBox).applyMatrix4(BD),this.boundingBox.union(gnA)}computeBoundingSphere(){const A=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new xs),A.boundingSphere===null&&A.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,BD),P0.copy(A.boundingSphere).applyMatrix4(BD),this.boundingSphere.union(P0)}copy(A,t){return super.copy(A,t),this.instanceMatrix.copy(A.instanceMatrix),A.morphTexture!==null&&(this.morphTexture=A.morphTexture.clone()),A.instanceColor!==null&&(this.instanceColor=A.instanceColor.clone()),this.count=A.count,A.boundingBox!==null&&(this.boundingBox=A.boundingBox.clone()),A.boundingSphere!==null&&(this.boundingSphere=A.boundingSphere.clone()),this}getColorAt(A,t){t.fromArray(this.instanceColor.array,A*3)}getMatrixAt(A,t){t.fromArray(this.instanceMatrix.array,A*16)}getMorphAt(A,t){const i=t.morphTargetInfluences,n=this.morphTexture.source.data.data,g=i.length+1,o=A*g+1;for(let s=0;s<i.length;s++)i[s]=n[o+s]}raycast(A,t){const i=this.matrixWorld,n=this.count;if(O0.geometry=this.geometry,O0.material=this.material,O0.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),P0.copy(this.boundingSphere),P0.applyMatrix4(i),A.ray.intersectsSphere(P0)!==!1))for(let g=0;g<n;g++){this.getMatrixAt(g,BD),nnA.multiplyMatrices(i,BD),O0.matrixWorld=nnA,O0.raycast(A,kU);for(let o=0,s=kU.length;o<s;o++){const a=kU[o];a.instanceId=g,a.object=this,t.push(a)}kU.length=0}}setColorAt(A,t){this.instanceColor===null&&(this.instanceColor=new hd(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,A*3)}setMatrixAt(A,t){t.toArray(this.instanceMatrix.array,A*16)}setMorphAt(A,t){const i=t.morphTargetInfluences,n=i.length+1;this.morphTexture===null&&(this.morphTexture=new uB(new Float32Array(n*this.count),n,this.count,Lx,br));const g=this.morphTexture.source.data.data;let o=0;for(let r=0;r<i.length;r++)o+=i[r];const s=this.geometry.morphTargetsRelative?1:1-o,a=n*A;g[a]=s,g.set(i,a+1)}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}}const DH=new SA,nre=new SA,gre=new An;class eu{constructor(A=new SA(1,0,0),t=0){this.isPlane=!0,this.normal=A,this.constant=t}set(A,t){return this.normal.copy(A),this.constant=t,this}setComponents(A,t,i,n){return this.normal.set(A,t,i),this.constant=n,this}setFromNormalAndCoplanarPoint(A,t){return this.normal.copy(A),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(A,t,i){const n=DH.subVectors(i,t).cross(nre.subVectors(A,t)).normalize();return this.setFromNormalAndCoplanarPoint(n,A),this}copy(A){return this.normal.copy(A.normal),this.constant=A.constant,this}normalize(){const A=1/this.normal.length();return this.normal.multiplyScalar(A),this.constant*=A,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(A){return this.normal.dot(A)+this.constant}distanceToSphere(A){return this.distanceToPoint(A.center)-A.radius}projectPoint(A,t){return t.copy(A).addScaledVector(this.normal,-this.distanceToPoint(A))}intersectLine(A,t){const i=A.delta(DH),n=this.normal.dot(i);if(n===0)return this.distanceToPoint(A.start)===0?t.copy(A.start):null;const g=-(A.start.dot(this.normal)+this.constant)/n;return g<0||g>1?null:t.copy(A.start).addScaledVector(i,g)}intersectsLine(A){const t=this.distanceToPoint(A.start),i=this.distanceToPoint(A.end);return t<0&&i>0||i<0&&t>0}intersectsBox(A){return A.intersectsPlane(this)}intersectsSphere(A){return A.intersectsPlane(this)}coplanarPoint(A){return A.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(A,t){const i=t||gre.getNormalMatrix(A),n=this.coplanarPoint(DH).applyMatrix4(A),g=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(g),this}translate(A){return this.constant-=A.dot(this.normal),this}equals(A){return A.normal.equals(this.normal)&&A.constant===this.constant}clone(){return new this.constructor().copy(this)}}const yh=new xs,ore=new lt(.5,.5),MU=new SA;class Lw{constructor(A=new eu,t=new eu,i=new eu,n=new eu,g=new eu,o=new eu){this.planes=[A,t,i,n,g,o]}set(A,t,i,n,g,o){const s=this.planes;return s[0].copy(A),s[1].copy(t),s[2].copy(i),s[3].copy(n),s[4].copy(g),s[5].copy(o),this}copy(A){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(A.planes[i]);return this}setFromProjectionMatrix(A,t=jI,i=!1){const n=this.planes,g=A.elements,o=g[0],s=g[1],a=g[2],r=g[3],I=g[4],c=g[5],l=g[6],B=g[7],Q=g[8],h=g[9],d=g[10],p=g[11],y=g[12],m=g[13],D=g[14],S=g[15];if(n[0].setComponents(r-o,B-I,p-Q,S-y).normalize(),n[1].setComponents(r+o,B+I,p+Q,S+y).normalize(),n[2].setComponents(r+s,B+c,p+h,S+m).normalize(),n[3].setComponents(r-s,B-c,p-h,S-m).normalize(),i)n[4].setComponents(a,l,d,D).normalize(),n[5].setComponents(r-a,B-l,p-d,S-D).normalize();else if(n[4].setComponents(r-a,B-l,p-d,S-D).normalize(),t===jI)n[5].setComponents(r+a,B+l,p+d,S+D).normalize();else if(t===HS)n[5].setComponents(a,l,d,D).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(A){if(A.boundingSphere!==void 0)A.boundingSphere===null&&A.computeBoundingSphere(),yh.copy(A.boundingSphere).applyMatrix4(A.matrixWorld);else{const t=A.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),yh.copy(t.boundingSphere).applyMatrix4(A.matrixWorld)}return this.intersectsSphere(yh)}intersectsSprite(A){yh.center.set(0,0,0);const t=ore.distanceTo(A.center);return yh.radius=.7071067811865476+t,yh.applyMatrix4(A.matrixWorld),this.intersectsSphere(yh)}intersectsSphere(A){const t=this.planes,i=A.center,n=-A.radius;for(let g=0;g<6;g++)if(t[g].distanceToPoint(i)<n)return!1;return!0}intersectsBox(A){const t=this.planes;for(let i=0;i<6;i++){const n=t[i];if(MU.x=n.normal.x>0?A.max.x:A.min.x,MU.y=n.normal.y>0?A.max.y:A.min.y,MU.z=n.normal.z>0?A.max.z:A.min.z,n.distanceToPoint(MU)<0)return!1}return!0}containsPoint(A){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(A)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const bl=new ni,Ul=new Lw;class zx{constructor(){this.coordinateSystem=jI}intersectsObject(A,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let i=0;i<t.cameras.length;i++){const n=t.cameras[i];if(bl.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),Ul.setFromProjectionMatrix(bl,n.coordinateSystem,n.reversedDepth),Ul.intersectsObject(A))return!0}return!1}intersectsSprite(A,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let i=0;i<t.cameras.length;i++){const n=t.cameras[i];if(bl.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),Ul.setFromProjectionMatrix(bl,n.coordinateSystem,n.reversedDepth),Ul.intersectsSprite(A))return!0}return!1}intersectsSphere(A,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let i=0;i<t.cameras.length;i++){const n=t.cameras[i];if(bl.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),Ul.setFromProjectionMatrix(bl,n.coordinateSystem,n.reversedDepth),Ul.intersectsSphere(A))return!0}return!1}intersectsBox(A,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let i=0;i<t.cameras.length;i++){const n=t.cameras[i];if(bl.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),Ul.setFromProjectionMatrix(bl,n.coordinateSystem,n.reversedDepth),Ul.intersectsBox(A))return!0}return!1}containsPoint(A,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let i=0;i<t.cameras.length;i++){const n=t.cameras[i];if(bl.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),Ul.setFromProjectionMatrix(bl,n.coordinateSystem,n.reversedDepth),Ul.containsPoint(A))return!0}return!1}clone(){return new zx}}function mH(e,A){return e-A}function sre(e,A){return e.z-A.z}function are(e,A){return A.z-e.z}class rre{constructor(){this.index=0,this.pool=[],this.list=[]}push(A,t,i,n){const g=this.pool,o=this.list;this.index>=g.length&&g.push({start:-1,count:-1,z:-1,index:-1});const s=g[this.index];o.push(s),this.index++,s.start=A,s.count=t,s.z=i,s.index=n}reset(){this.list.length=0,this.index=0}}const Or=new ni,Ire=new Et(1,1,1),onA=new Lw,Cre=new zx,NU=new Ag,Dh=new xs,j0=new SA,snA=new SA,cre=new SA,SH=new rre,za=new pn,RU=[];function lre(e,A,t=0){const i=A.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==A.array.constructor){const n=e.count;for(let g=0;g<n;g++)for(let o=0;o<i;o++)A.setComponent(g+t,o,e.getComponent(g,o))}else A.array.set(e.array,t*i);A.needsUpdate=!0}function mh(e,A){if(e.constructor!==A.constructor){const t=Math.min(e.length,A.length);for(let i=0;i<t;i++)A[i]=e[i]}else{const t=Math.min(e.length,A.length);A.set(new e.constructor(e.buffer,0,t))}}class CyA extends pn{constructor(A,t,i=t*2,n){super(new Ni,n),this.isBatchedMesh=!0,this.perObjectFrustumCulled=!0,this.sortObjects=!0,this.boundingBox=null,this.boundingSphere=null,this.customSort=null,this._instanceInfo=[],this._geometryInfo=[],this._availableInstanceIds=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._visibilityChanged=!0,this._geometryInitialized=!1,this._maxInstanceCount=A,this._maxVertexCount=t,this._maxIndexCount=i,this._multiDrawCounts=new Int32Array(A),this._multiDrawStarts=new Int32Array(A),this._multiDrawCount=0,this._multiDrawInstances=null,this._matricesTexture=null,this._indirectTexture=null,this._colorsTexture=null,this._initMatricesTexture(),this._initIndirectTexture()}get maxInstanceCount(){return this._maxInstanceCount}get instanceCount(){return this._instanceInfo.length-this._availableInstanceIds.length}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get unusedIndexCount(){return this._maxIndexCount-this._nextIndexStart}_initMatricesTexture(){let A=Math.sqrt(this._maxInstanceCount*4);A=Math.ceil(A/4)*4,A=Math.max(A,4);const t=new Float32Array(A*A*4),i=new uB(t,A,A,Ar,br);this._matricesTexture=i}_initIndirectTexture(){let A=Math.sqrt(this._maxInstanceCount);A=Math.ceil(A);const t=new Uint32Array(A*A),i=new uB(t,A,A,gG,IQ);this._indirectTexture=i}_initColorsTexture(){let A=Math.sqrt(this._maxInstanceCount);A=Math.ceil(A);const t=new Float32Array(A*A*4).fill(1),i=new uB(t,A,A,Ar,br);i.colorSpace=Un.workingColorSpace,this._colorsTexture=i}_initializeGeometry(A){const t=this.geometry,i=this._maxVertexCount,n=this._maxIndexCount;if(this._geometryInitialized===!1){for(const g in A.attributes){const o=A.getAttribute(g),{array:s,itemSize:a,normalized:r}=o,I=new s.constructor(i*a),c=new ji(I,a,r);t.setAttribute(g,c)}if(A.getIndex()!==null){const g=i>65535?new Uint32Array(n):new Uint16Array(n);t.setIndex(new ji(g,1))}this._geometryInitialized=!0}}_validateGeometry(A){const t=this.geometry;if(!!A.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!A.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const n=A.getAttribute(i),g=t.getAttribute(i);if(n.itemSize!==g.itemSize||n.normalized!==g.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(A){const t=this._instanceInfo;if(A<0||A>=t.length||t[A].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${A}. Instance is either out of range or has been deleted.`)}validateGeometryId(A){const t=this._geometryInfo;if(A<0||A>=t.length||t[A].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${A}. Geometry is either out of range or has been deleted.`)}setCustomSort(A){return this.customSort=A,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Ag);const A=this.boundingBox,t=this._instanceInfo;A.makeEmpty();for(let i=0,n=t.length;i<n;i++){if(t[i].active===!1)continue;const g=t[i].geometryIndex;this.getMatrixAt(i,Or),this.getBoundingBoxAt(g,NU).applyMatrix4(Or),A.union(NU)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new xs);const A=this.boundingSphere,t=this._instanceInfo;A.makeEmpty();for(let i=0,n=t.length;i<n;i++){if(t[i].active===!1)continue;const g=t[i].geometryIndex;this.getMatrixAt(i,Or),this.getBoundingSphereAt(g,Dh).applyMatrix4(Or),A.union(Dh)}}addInstance(A){if(this._instanceInfo.length>=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const i={visible:!0,active:!0,geometryIndex:A};let n=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(mH),n=this._availableInstanceIds.shift(),this._instanceInfo[n]=i):(n=this._instanceInfo.length,this._instanceInfo.push(i));const g=this._matricesTexture;Or.identity().toArray(g.image.data,n*16),g.needsUpdate=!0;const o=this._colorsTexture;return o&&(Ire.toArray(o.image.data,n*4),o.needsUpdate=!0),this._visibilityChanged=!0,n}addGeometry(A,t=-1,i=-1){this._initializeGeometry(A),this._validateGeometry(A);const n={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},g=this._geometryInfo;n.vertexStart=this._nextVertexStart,n.reservedVertexCount=t===-1?A.getAttribute("position").count:t;const o=A.getIndex();if(o!==null&&(n.indexStart=this._nextIndexStart,n.reservedIndexCount=i===-1?o.count:i),n.indexStart!==-1&&n.indexStart+n.reservedIndexCount>this._maxIndexCount||n.vertexStart+n.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let a;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(mH),a=this._availableGeometryIds.shift(),g[a]=n):(a=this._geometryCount,this._geometryCount++,g.push(n)),this.setGeometryAt(a,A),this._nextIndexStart=n.indexStart+n.reservedIndexCount,this._nextVertexStart=n.vertexStart+n.reservedVertexCount,a}setGeometryAt(A,t){if(A>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=i.getIndex()!==null,g=i.getIndex(),o=t.getIndex(),s=this._geometryInfo[A];if(n&&o.count>s.reservedIndexCount||t.attributes.position.count>s.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const a=s.vertexStart,r=s.reservedVertexCount;s.vertexCount=t.getAttribute("position").count;for(const I in i.attributes){const c=t.getAttribute(I),l=i.getAttribute(I);lre(c,l,a);const B=c.itemSize;for(let Q=c.count,h=r;Q<h;Q++){const d=a+Q;for(let p=0;p<B;p++)l.setComponent(d,p,0)}l.needsUpdate=!0,l.addUpdateRange(a*B,r*B)}if(n){const I=s.indexStart,c=s.reservedIndexCount;s.indexCount=t.getIndex().count;for(let l=0;l<o.count;l++)g.setX(I+l,a+o.getX(l));for(let l=o.count,B=c;l<B;l++)g.setX(I+l,a);g.needsUpdate=!0,g.addUpdateRange(I,s.reservedIndexCount)}return s.start=n?s.indexStart:s.vertexStart,s.count=n?s.indexCount:s.vertexCount,s.boundingBox=null,t.boundingBox!==null&&(s.boundingBox=t.boundingBox.clone()),s.boundingSphere=null,t.boundingSphere!==null&&(s.boundingSphere=t.boundingSphere.clone()),this._visibilityChanged=!0,A}deleteGeometry(A){const t=this._geometryInfo;if(A>=t.length||t[A].active===!1)return this;const i=this._instanceInfo;for(let n=0,g=i.length;n<g;n++)i[n].active&&i[n].geometryIndex===A&&this.deleteInstance(n);return t[A].active=!1,this._availableGeometryIds.push(A),this._visibilityChanged=!0,this}deleteInstance(A){return this.validateInstanceId(A),this._instanceInfo[A].active=!1,this._availableInstanceIds.push(A),this._visibilityChanged=!0,this}optimize(){let A=0,t=0;const i=this._geometryInfo,n=i.map((o,s)=>s).sort((o,s)=>i[o].vertexStart-i[s].vertexStart),g=this.geometry;for(let o=0,s=i.length;o<s;o++){const a=n[o],r=i[a];if(r.active!==!1){if(g.index!==null){if(r.indexStart!==t){const{indexStart:I,vertexStart:c,reservedIndexCount:l}=r,B=g.index,Q=B.array,h=A-c;for(let d=I;d<I+l;d++)Q[d]=Q[d]+h;B.array.copyWithin(t,I,I+l),B.addUpdateRange(t,l),r.indexStart=t}t+=r.reservedIndexCount}if(r.vertexStart!==A){const{vertexStart:I,reservedVertexCount:c}=r,l=g.attributes;for(const B in l){const Q=l[B],{array:h,itemSize:d}=Q;h.copyWithin(A*d,I*d,(I+c)*d),Q.addUpdateRange(A*d,c*d)}r.vertexStart=A}A+=r.reservedVertexCount,r.start=g.index?r.indexStart:r.vertexStart,this._nextIndexStart=g.index?r.indexStart+r.reservedIndexCount:0,this._nextVertexStart=r.vertexStart+r.reservedVertexCount}}return this}getBoundingBoxAt(A,t){if(A>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[A];if(n.boundingBox===null){const g=new Ag,o=i.index,s=i.attributes.position;for(let a=n.start,r=n.start+n.count;a<r;a++){let I=a;o&&(I=o.getX(I)),g.expandByPoint(j0.fromBufferAttribute(s,I))}n.boundingBox=g}return t.copy(n.boundingBox),t}getBoundingSphereAt(A,t){if(A>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[A];if(n.boundingSphere===null){const g=new xs;this.getBoundingBoxAt(A,NU),NU.getCenter(g.center);const o=i.index,s=i.attributes.position;let a=0;for(let r=n.start,I=n.start+n.count;r<I;r++){let c=r;o&&(c=o.getX(c)),j0.fromBufferAttribute(s,c),a=Math.max(a,g.center.distanceToSquared(j0))}g.radius=Math.sqrt(a),n.boundingSphere=g}return t.copy(n.boundingSphere),t}setMatrixAt(A,t){this.validateInstanceId(A);const i=this._matricesTexture,n=this._matricesTexture.image.data;return t.toArray(n,A*16),i.needsUpdate=!0,this}getMatrixAt(A,t){return this.validateInstanceId(A),t.fromArray(this._matricesTexture.image.data,A*16)}setColorAt(A,t){return this.validateInstanceId(A),this._colorsTexture===null&&this._initColorsTexture(),t.toArray(this._colorsTexture.image.data,A*4),this._colorsTexture.needsUpdate=!0,this}getColorAt(A,t){return this.validateInstanceId(A),t.fromArray(this._colorsTexture.image.data,A*4)}setVisibleAt(A,t){return this.validateInstanceId(A),this._instanceInfo[A].visible===t?this:(this._instanceInfo[A].visible=t,this._visibilityChanged=!0,this)}getVisibleAt(A){return this.validateInstanceId(A),this._instanceInfo[A].visible}setGeometryIdAt(A,t){return this.validateInstanceId(A),this.validateGeometryId(t),this._instanceInfo[A].geometryIndex=t,this}getGeometryIdAt(A){return this.validateInstanceId(A),this._instanceInfo[A].geometryIndex}getGeometryRangeAt(A,t={}){this.validateGeometryId(A);const i=this._geometryInfo[A];return t.vertexStart=i.vertexStart,t.vertexCount=i.vertexCount,t.reservedVertexCount=i.reservedVertexCount,t.indexStart=i.indexStart,t.indexCount=i.indexCount,t.reservedIndexCount=i.reservedIndexCount,t.start=i.start,t.count=i.count,t}setInstanceCount(A){const t=this._availableInstanceIds,i=this._instanceInfo;for(t.sort(mH);t[t.length-1]===i.length-1;)i.pop(),t.pop();if(A<i.length)throw new Error(`BatchedMesh: Instance ids outside the range ${A} are being used. Cannot shrink instance count.`);const n=new Int32Array(A),g=new Int32Array(A);mh(this._multiDrawCounts,n),mh(this._multiDrawStarts,g),this._multiDrawCounts=n,this._multiDrawStarts=g,this._maxInstanceCount=A;const o=this._indirectTexture,s=this._matricesTexture,a=this._colorsTexture;o.dispose(),this._initIndirectTexture(),mh(o.image.data,this._indirectTexture.image.data),s.dispose(),this._initMatricesTexture(),mh(s.image.data,this._matricesTexture.image.data),a&&(a.dispose(),this._initColorsTexture(),mh(a.image.data,this._colorsTexture.image.data))}setGeometrySize(A,t){const i=[...this._geometryInfo].filter(s=>s.active);if(Math.max(...i.map(s=>s.vertexStart+s.reservedVertexCount))>A)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...i.map(a=>a.indexStart+a.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);const g=this.geometry;g.dispose(),this._maxVertexCount=A,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Ni,this._initializeGeometry(g));const o=this.geometry;g.index&&mh(g.index.array,o.index.array);for(const s in g.attributes)mh(g.attributes[s].array,o.attributes[s].array)}raycast(A,t){const i=this._instanceInfo,n=this._geometryInfo,g=this.matrixWorld,o=this.geometry;za.material=this.material,za.geometry.index=o.index,za.geometry.attributes=o.attributes,za.geometry.boundingBox===null&&(za.geometry.boundingBox=new Ag),za.geometry.boundingSphere===null&&(za.geometry.boundingSphere=new xs);for(let s=0,a=i.length;s<a;s++){if(!i[s].visible||!i[s].active)continue;const r=i[s].geometryIndex,I=n[r];za.geometry.setDrawRange(I.start,I.count),this.getMatrixAt(s,za.matrixWorld).premultiply(g),this.getBoundingBoxAt(r,za.geometry.boundingBox),this.getBoundingSphereAt(r,za.geometry.boundingSphere),za.raycast(A,RU);for(let c=0,l=RU.length;c<l;c++){const B=RU[c];B.object=this,B.batchId=s,t.push(B)}RU.length=0}za.material=null,za.geometry.index=null,za.geometry.attributes={},za.geometry.setDrawRange(0,1/0)}copy(A){return super.copy(A),this.geometry=A.geometry.clone(),this.perObjectFrustumCulled=A.perObjectFrustumCulled,this.sortObjects=A.sortObjects,this.boundingBox=A.boundingBox!==null?A.boundingBox.clone():null,this.boundingSphere=A.boundingSphere!==null?A.boundingSphere.clone():null,this._geometryInfo=A._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=A._instanceInfo.map(t=>({...t})),this._availableInstanceIds=A._availableInstanceIds.slice(),this._availableGeometryIds=A._availableGeometryIds.slice(),this._nextIndexStart=A._nextIndexStart,this._nextVertexStart=A._nextVertexStart,this._geometryCount=A._geometryCount,this._maxInstanceCount=A._maxInstanceCount,this._maxVertexCount=A._maxVertexCount,this._maxIndexCount=A._maxIndexCount,this._geometryInitialized=A._geometryInitialized,this._multiDrawCounts=A._multiDrawCounts.slice(),this._multiDrawStarts=A._multiDrawStarts.slice(),this._indirectTexture=A._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=A._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=A._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(A,t,i,n,g){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const o=n.getIndex(),s=o===null?1:o.array.BYTES_PER_ELEMENT,a=this._instanceInfo,r=this._multiDrawStarts,I=this._multiDrawCounts,c=this._geometryInfo,l=this.perObjectFrustumCulled,B=this._indirectTexture,Q=B.image.data,h=i.isArrayCamera?Cre:onA;l&&!i.isArrayCamera&&(Or.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),onA.setFromProjectionMatrix(Or,i.coordinateSystem,i.reversedDepth));let d=0;if(this.sortObjects){Or.copy(this.matrixWorld).invert(),j0.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Or),snA.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Or);for(let m=0,D=a.length;m<D;m++)if(a[m].visible&&a[m].active){const S=a[m].geometryIndex;this.getMatrixAt(m,Or),this.getBoundingSphereAt(S,Dh).applyMatrix4(Or);let k=!1;if(l&&(k=!h.intersectsSphere(Dh,i)),!k){const N=c[S],G=cre.subVectors(Dh.center,j0).dot(snA);SH.push(N.start,N.count,G,m)}}const p=SH.list,y=this.customSort;y===null?p.sort(g.transparent?are:sre):y.call(this,p,i);for(let m=0,D=p.length;m<D;m++){const S=p[m];r[d]=S.start*s,I[d]=S.count,Q[d]=S.index,d++}SH.reset()}else for(let p=0,y=a.length;p<y;p++)if(a[p].visible&&a[p].active){const m=a[p].geometryIndex;let D=!1;if(l&&(this.getMatrixAt(p,Or),this.getBoundingSphereAt(m,Dh).applyMatrix4(Or),D=!h.intersectsSphere(Dh,i)),!D){const S=c[m];r[d]=S.start*s,I[d]=S.count,Q[d]=p,d++}}B.needsUpdate=!0,this._multiDrawCount=d,this._visibilityChanged=!1}onBeforeShadow(A,t,i,n,g,o){this.onBeforeRender(A,null,n,g,o)}}class es extends ho{constructor(A){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Et(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.linewidth=A.linewidth,this.linecap=A.linecap,this.linejoin=A.linejoin,this.fog=A.fog,this}}const pJ=new SA,fJ=new SA,anA=new ni,z0=new Fw,GU=new xs,wH=new SA,rnA=new SA;class yB extends Bn{constructor(A=new Ni,t=new es){super(),this.isLine=!0,this.type="Line",this.geometry=A,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(A,t){return super.copy(A,t),this.material=Array.isArray(A.material)?A.material.slice():A.material,this.geometry=A.geometry,this}computeLineDistances(){const A=this.geometry;if(A.index===null){const t=A.attributes.position,i=[0];for(let n=1,g=t.count;n<g;n++)pJ.fromBufferAttribute(t,n-1),fJ.fromBufferAttribute(t,n),i[n]=i[n-1],i[n]+=pJ.distanceTo(fJ);A.setAttribute("lineDistance",new $t(i,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(A,t){const i=this.geometry,n=this.matrixWorld,g=A.params.Line.threshold,o=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),GU.copy(i.boundingSphere),GU.applyMatrix4(n),GU.radius+=g,A.ray.intersectsSphere(GU)===!1)return;anA.copy(n).invert(),z0.copy(A.ray).applyMatrix4(anA);const s=g/((this.scale.x+this.scale.y+this.scale.z)/3),a=s*s,r=this.isLineSegments?2:1,I=i.index,l=i.attributes.position;if(I!==null){const B=Math.max(0,o.start),Q=Math.min(I.count,o.start+o.count);for(let h=B,d=Q-1;h<d;h+=r){const p=I.getX(h),y=I.getX(h+1),m=bU(this,A,z0,a,p,y,h);m&&t.push(m)}if(this.isLineLoop){const h=I.getX(Q-1),d=I.getX(B),p=bU(this,A,z0,a,h,d,Q-1);p&&t.push(p)}}else{const B=Math.max(0,o.start),Q=Math.min(l.count,o.start+o.count);for(let h=B,d=Q-1;h<d;h+=r){const p=bU(this,A,z0,a,h,h+1,h);p&&t.push(p)}if(this.isLineLoop){const h=bU(this,A,z0,a,Q-1,B,Q-1);h&&t.push(h)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let g=0,o=n.length;g<o;g++){const s=n[g].name||String(g);this.morphTargetInfluences.push(0),this.morphTargetDictionary[s]=g}}}}}function bU(e,A,t,i,n,g,o){const s=e.geometry.attributes.position;if(pJ.fromBufferAttribute(s,n),fJ.fromBufferAttribute(s,g),t.distanceSqToSegment(pJ,fJ,wH,rnA)>i)return;wH.applyMatrix4(e.matrixWorld);const r=A.ray.origin.distanceTo(wH);if(!(r<A.near||r>A.far))return{distance:r,point:rnA.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}const InA=new SA,CnA=new SA;class EI extends yB{constructor(A,t){super(A,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const A=this.geometry;if(A.index===null){const t=A.attributes.position,i=[];for(let n=0,g=t.count;n<g;n+=2)InA.fromBufferAttribute(t,n),CnA.fromBufferAttribute(t,n+1),i[n]=n===0?0:i[n-1],i[n+1]=i[n]+InA.distanceTo(CnA);A.setAttribute("lineDistance",new $t(i,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class Zx extends yB{constructor(A,t){super(A,t),this.isLineLoop=!0,this.type="LineLoop"}}class NE extends ho{constructor(A){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Et(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.alphaMap=A.alphaMap,this.size=A.size,this.sizeAttenuation=A.sizeAttenuation,this.fog=A.fog,this}}const cnA=new ni,a4=new Fw,UU=new xs,vU=new SA;class Pp extends Bn{constructor(A=new Ni,t=new NE){super(),this.isPoints=!0,this.type="Points",this.geometry=A,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(A,t){return super.copy(A,t),this.material=Array.isArray(A.material)?A.material.slice():A.material,this.geometry=A.geometry,this}raycast(A,t){const i=this.geometry,n=this.matrixWorld,g=A.params.Points.threshold,o=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),UU.copy(i.boundingSphere),UU.applyMatrix4(n),UU.radius+=g,A.ray.intersectsSphere(UU)===!1)return;cnA.copy(n).invert(),a4.copy(A.ray).applyMatrix4(cnA);const s=g/((this.scale.x+this.scale.y+this.scale.z)/3),a=s*s,r=i.index,c=i.attributes.position;if(r!==null){const l=Math.max(0,o.start),B=Math.min(r.count,o.start+o.count);for(let Q=l,h=B;Q<h;Q++){const d=r.getX(Q);vU.fromBufferAttribute(c,d),lnA(vU,d,a,n,A,t,this)}}else{const l=Math.max(0,o.start),B=Math.min(c.count,o.start+o.count);for(let Q=l,h=B;Q<h;Q++)vU.fromBufferAttribute(c,Q),lnA(vU,Q,a,n,A,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let g=0,o=n.length;g<o;g++){const s=n[g].name||String(g);this.morphTargetInfluences.push(0),this.morphTargetDictionary[s]=g}}}}}function lnA(e,A,t,i,n,g,o){const s=a4.distanceSqToPoint(e);if(s<t){const a=new SA;a4.closestPointToPoint(e,a),a.applyMatrix4(i);const r=n.ray.origin.distanceTo(a);if(r<n.near||r>n.far)return;g.push({distance:r,distanceToRay:Math.sqrt(s),point:a,index:A,face:null,faceIndex:null,barycoord:null,object:o})}}class cyA extends Kg{constructor(A,t,i,n,g=qg,o=qg,s,a,r){super(A,t,i,n,g,o,s,a,r),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const I=this;function c(){I.needsUpdate=!0,I._requestVideoFrameCallbackId=A.requestVideoFrameCallback(c)}"requestVideoFrameCallback"in A&&(this._requestVideoFrameCallbackId=A.requestVideoFrameCallback(c))}clone(){return new this.constructor(this.image).copy(this)}update(){const A=this.image;"requestVideoFrameCallback"in A===!1&&A.readyState>=A.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),super.dispose()}}class Bre extends cyA{constructor(A,t,i,n,g,o,s,a){super({},A,t,i,n,g,o,s,a),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(A){this.image=A,this.needsUpdate=!0}}class Ere extends Kg{constructor(A,t){super({width:A,height:t}),this.isFramebufferTexture=!0,this.magFilter=Ss,this.minFilter=Ss,this.generateMipmaps=!1,this.needsUpdate=!0}}class Wx extends Kg{constructor(A,t,i,n,g,o,s,a,r,I,c,l){super(null,o,s,a,r,I,n,g,c,l),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=A,this.flipY=!1,this.generateMipmaps=!1}}class Qre extends Wx{constructor(A,t,i,n,g,o){super(A,t,i,g,o),this.isCompressedArrayTexture=!0,this.image.depth=n,this.wrapR=oI,this.layerUpdates=new Set}addLayerUpdate(A){this.layerUpdates.add(A)}clearLayerUpdates(){this.layerUpdates.clear()}}class ure extends Wx{constructor(A,t,i){super(void 0,A[0].width,A[0].height,t,i,rQ),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=A}}class pd extends Kg{constructor(A,t,i,n,g,o,s,a,r){super(A,t,i,n,g,o,s,a,r),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Vx extends Kg{constructor(A,t,i=IQ,n,g,o,s=Ss,a=Ss,r,I=qS,c=1){if(I!==qS&&I!==YS)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const l={width:A,height:t,depth:c};super(l,n,g,o,s,a,I,i,r),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(A){return super.copy(A),this.source=new Ru(Object.assign({},A.image)),this.compareFunction=A.compareFunction,this}toJSON(A){const t=super.toJSON(A);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class YW extends Kg{constructor(A=null){super(),this.sourceTexture=A,this.isExternalTexture=!0}copy(A){return super.copy(A),this.sourceTexture=A.sourceTexture,this}}class Xx extends Ni{constructor(A=1,t=1,i=4,n=8,g=1){super(),this.type="CapsuleGeometry",this.parameters={radius:A,height:t,capSegments:i,radialSegments:n,heightSegments:g},t=Math.max(0,t),i=Math.max(1,Math.floor(i)),n=Math.max(3,Math.floor(n)),g=Math.max(1,Math.floor(g));const o=[],s=[],a=[],r=[],I=t/2,c=Math.PI/2*A,l=t,B=2*c+l,Q=i*2+g,h=n+1,d=new SA,p=new SA;for(let y=0;y<=Q;y++){let m=0,D=0,S=0,k=0;if(y<=i){const M=y/i,w=M*Math.PI/2;D=-I-A*Math.cos(w),S=A*Math.sin(w),k=-A*Math.cos(w),m=M*c}else if(y<=i+g){const M=(y-i)/g;D=-I+M*t,S=A,k=0,m=c+M*l}else{const M=(y-i-g)/i,w=M*Math.PI/2;D=I+A*Math.sin(w),S=A*Math.cos(w),k=A*Math.sin(w),m=c+l+M*c}const N=Math.max(0,Math.min(1,m/B));let G=0;y===0?G=.5/n:y===Q&&(G=-.5/n);for(let M=0;M<=n;M++){const w=M/n,b=w*Math.PI*2,_=Math.sin(b),K=Math.cos(b);p.x=-S*K,p.y=D,p.z=S*_,s.push(p.x,p.y,p.z),d.set(-S*K,k,S*_),d.normalize(),a.push(d.x,d.y,d.z),r.push(w+G,N)}if(y>0){const M=(y-1)*h;for(let w=0;w<n;w++){const b=M+w,_=M+w+1,K=y*h+w,J=y*h+w+1;o.push(b,_,K),o.push(_,J,K)}}}this.setIndex(o),this.setAttribute("position",new $t(s,3)),this.setAttribute("normal",new $t(a,3)),this.setAttribute("uv",new $t(r,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new Xx(A.radius,A.height,A.capSegments,A.radialSegments,A.heightSegments)}}class $x extends Ni{constructor(A=1,t=32,i=0,n=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:A,segments:t,thetaStart:i,thetaLength:n},t=Math.max(3,t);const g=[],o=[],s=[],a=[],r=new SA,I=new lt;o.push(0,0,0),s.push(0,0,1),a.push(.5,.5);for(let c=0,l=3;c<=t;c++,l+=3){const B=i+c/t*n;r.x=A*Math.cos(B),r.y=A*Math.sin(B),o.push(r.x,r.y,r.z),s.push(0,0,1),I.x=(o[l]/A+1)/2,I.y=(o[l+1]/A+1)/2,a.push(I.x,I.y)}for(let c=1;c<=t;c++)g.push(c,c+1,0);this.setIndex(g),this.setAttribute("position",new $t(o,3)),this.setAttribute("normal",new $t(s,3)),this.setAttribute("uv",new $t(a,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new $x(A.radius,A.segments,A.thetaStart,A.thetaLength)}}class gy extends Ni{constructor(A=1,t=1,i=1,n=32,g=1,o=!1,s=0,a=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:A,radiusBottom:t,height:i,radialSegments:n,heightSegments:g,openEnded:o,thetaStart:s,thetaLength:a};const r=this;n=Math.floor(n),g=Math.floor(g);const I=[],c=[],l=[],B=[];let Q=0;const h=[],d=i/2;let p=0;y(),o===!1&&(A>0&&m(!0),t>0&&m(!1)),this.setIndex(I),this.setAttribute("position",new $t(c,3)),this.setAttribute("normal",new $t(l,3)),this.setAttribute("uv",new $t(B,2));function y(){const D=new SA,S=new SA;let k=0;const N=(t-A)/i;for(let G=0;G<=g;G++){const M=[],w=G/g,b=w*(t-A)+A;for(let _=0;_<=n;_++){const K=_/n,J=K*a+s,q=Math.sin(J),v=Math.cos(J);S.x=b*q,S.y=-w*i+d,S.z=b*v,c.push(S.x,S.y,S.z),D.set(q,N,v).normalize(),l.push(D.x,D.y,D.z),B.push(K,1-w),M.push(Q++)}h.push(M)}for(let G=0;G<n;G++)for(let M=0;M<g;M++){const w=h[M][G],b=h[M+1][G],_=h[M+1][G+1],K=h[M][G+1];(A>0||M!==0)&&(I.push(w,b,K),k+=3),(t>0||M!==g-1)&&(I.push(b,_,K),k+=3)}r.addGroup(p,k,0),p+=k}function m(D){const S=Q,k=new lt,N=new SA;let G=0;const M=D===!0?A:t,w=D===!0?1:-1;for(let _=1;_<=n;_++)c.push(0,d*w,0),l.push(0,w,0),B.push(.5,.5),Q++;const b=Q;for(let _=0;_<=n;_++){const J=_/n*a+s,q=Math.cos(J),v=Math.sin(J);N.x=M*v,N.y=d*w,N.z=M*q,c.push(N.x,N.y,N.z),l.push(0,w,0),k.x=q*.5+.5,k.y=v*.5*w+.5,B.push(k.x,k.y),Q++}for(let _=0;_<n;_++){const K=S+_,J=b+_;D===!0?I.push(J,J+1,K):I.push(J+1,J,K),G+=3}r.addGroup(p,G,D===!0?1:2),p+=G}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new gy(A.radiusTop,A.radiusBottom,A.height,A.radialSegments,A.heightSegments,A.openEnded,A.thetaStart,A.thetaLength)}}class cG extends gy{constructor(A=1,t=1,i=32,n=1,g=!1,o=0,s=Math.PI*2){super(0,A,t,i,n,g,o,s),this.type="ConeGeometry",this.parameters={radius:A,height:t,radialSegments:i,heightSegments:n,openEnded:g,thetaStart:o,thetaLength:s}}static fromJSON(A){return new cG(A.radius,A.height,A.radialSegments,A.heightSegments,A.openEnded,A.thetaStart,A.thetaLength)}}class Td extends Ni{constructor(A=[],t=[],i=1,n=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:A,indices:t,radius:i,detail:n};const g=[],o=[];s(n),r(i),I(),this.setAttribute("position",new $t(g,3)),this.setAttribute("normal",new $t(g.slice(),3)),this.setAttribute("uv",new $t(o,2)),n===0?this.computeVertexNormals():this.normalizeNormals();function s(y){const m=new SA,D=new SA,S=new SA;for(let k=0;k<t.length;k+=3)B(t[k+0],m),B(t[k+1],D),B(t[k+2],S),a(m,D,S,y)}function a(y,m,D,S){const k=S+1,N=[];for(let G=0;G<=k;G++){N[G]=[];const M=y.clone().lerp(D,G/k),w=m.clone().lerp(D,G/k),b=k-G;for(let _=0;_<=b;_++)_===0&&G===k?N[G][_]=M:N[G][_]=M.clone().lerp(w,_/b)}for(let G=0;G<k;G++)for(let M=0;M<2*(k-G)-1;M++){const w=Math.floor(M/2);M%2===0?(l(N[G][w+1]),l(N[G+1][w]),l(N[G][w])):(l(N[G][w+1]),l(N[G+1][w+1]),l(N[G+1][w]))}}function r(y){const m=new SA;for(let D=0;D<g.length;D+=3)m.x=g[D+0],m.y=g[D+1],m.z=g[D+2],m.normalize().multiplyScalar(y),g[D+0]=m.x,g[D+1]=m.y,g[D+2]=m.z}function I(){const y=new SA;for(let m=0;m<g.length;m+=3){y.x=g[m+0],y.y=g[m+1],y.z=g[m+2];const D=d(y)/2/Math.PI+.5,S=p(y)/Math.PI+.5;o.push(D,1-S)}Q(),c()}function c(){for(let y=0;y<o.length;y+=6){const m=o[y+0],D=o[y+2],S=o[y+4],k=Math.max(m,D,S),N=Math.min(m,D,S);k>.9&&N<.1&&(m<.2&&(o[y+0]+=1),D<.2&&(o[y+2]+=1),S<.2&&(o[y+4]+=1))}}function l(y){g.push(y.x,y.y,y.z)}function B(y,m){const D=y*3;m.x=A[D+0],m.y=A[D+1],m.z=A[D+2]}function Q(){const y=new SA,m=new SA,D=new SA,S=new SA,k=new lt,N=new lt,G=new lt;for(let M=0,w=0;M<g.length;M+=9,w+=6){y.set(g[M+0],g[M+1],g[M+2]),m.set(g[M+3],g[M+4],g[M+5]),D.set(g[M+6],g[M+7],g[M+8]),k.set(o[w+0],o[w+1]),N.set(o[w+2],o[w+3]),G.set(o[w+4],o[w+5]),S.copy(y).add(m).add(D).divideScalar(3);const b=d(S);h(k,w+0,y,b),h(N,w+2,m,b),h(G,w+4,D,b)}}function h(y,m,D,S){S<0&&y.x===1&&(o[m]=y.x-1),D.x===0&&D.z===0&&(o[m]=S/2/Math.PI+.5)}function d(y){return Math.atan2(y.z,-y.x)}function p(y){return Math.atan2(-y.y,Math.sqrt(y.x*y.x+y.z*y.z))}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new Td(A.vertices,A.indices,A.radius,A.details)}}class AT extends Td{constructor(A=1,t=0){const i=(1+Math.sqrt(5))/2,n=1/i,g=[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-n,-i,0,-n,i,0,n,-i,0,n,i,-n,-i,0,-n,i,0,n,-i,0,n,i,0,-i,0,-n,i,0,-n,-i,0,n,i,0,n],o=[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9];super(g,o,A,t),this.type="DodecahedronGeometry",this.parameters={radius:A,detail:t}}static fromJSON(A){return new AT(A.radius,A.detail)}}const KU=new SA,FU=new SA,kH=new SA,_U=new eI;class lyA extends Ni{constructor(A=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:A,thresholdAngle:t},A!==null){const n=Math.pow(10,4),g=Math.cos(Op*t),o=A.getIndex(),s=A.getAttribute("position"),a=o?o.count:s.count,r=[0,0,0],I=["a","b","c"],c=new Array(3),l={},B=[];for(let Q=0;Q<a;Q+=3){o?(r[0]=o.getX(Q),r[1]=o.getX(Q+1),r[2]=o.getX(Q+2)):(r[0]=Q,r[1]=Q+1,r[2]=Q+2);const{a:h,b:d,c:p}=_U;if(h.fromBufferAttribute(s,r[0]),d.fromBufferAttribute(s,r[1]),p.fromBufferAttribute(s,r[2]),_U.getNormal(kH),c[0]=`${Math.round(h.x*n)},${Math.round(h.y*n)},${Math.round(h.z*n)}`,c[1]=`${Math.round(d.x*n)},${Math.round(d.y*n)},${Math.round(d.z*n)}`,c[2]=`${Math.round(p.x*n)},${Math.round(p.y*n)},${Math.round(p.z*n)}`,!(c[0]===c[1]||c[1]===c[2]||c[2]===c[0]))for(let y=0;y<3;y++){const m=(y+1)%3,D=c[y],S=c[m],k=_U[I[y]],N=_U[I[m]],G=`${D}_${S}`,M=`${S}_${D}`;M in l&&l[M]?(kH.dot(l[M].normal)<=g&&(B.push(k.x,k.y,k.z),B.push(N.x,N.y,N.z)),l[M]=null):G in l||(l[G]={index0:r[y],index1:r[m],normal:kH.clone()})}}for(const Q in l)if(l[Q]){const{index0:h,index1:d}=l[Q];KU.fromBufferAttribute(s,h),FU.fromBufferAttribute(s,d),B.push(KU.x,KU.y,KU.z),B.push(FU.x,FU.y,FU.z)}this.setAttribute("position",new $t(B,3))}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}}class Cl{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){console.warn("THREE.Curve: .getPoint() not implemented.")}getPointAt(A,t){const i=this.getUtoTmapping(A);return this.getPoint(i,t)}getPoints(A=5){const t=[];for(let i=0;i<=A;i++)t.push(this.getPoint(i/A));return t}getSpacedPoints(A=5){const t=[];for(let i=0;i<=A;i++)t.push(this.getPointAt(i/A));return t}getLength(){const A=this.getLengths();return A[A.length-1]}getLengths(A=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===A+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let i,n=this.getPoint(0),g=0;t.push(0);for(let o=1;o<=A;o++)i=this.getPoint(o/A),g+=i.distanceTo(n),t.push(g),n=i;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(A,t=null){const i=this.getLengths();let n=0;const g=i.length;let o;t?o=t:o=A*i[g-1];let s=0,a=g-1,r;for(;s<=a;)if(n=Math.floor(s+(a-s)/2),r=i[n]-o,r<0)s=n+1;else if(r>0)a=n-1;else{a=n;break}if(n=a,i[n]===o)return n/(g-1);const I=i[n],l=i[n+1]-I,B=(o-I)/l;return(n+B)/(g-1)}getTangent(A,t){let n=A-1e-4,g=A+1e-4;n<0&&(n=0),g>1&&(g=1);const o=this.getPoint(n),s=this.getPoint(g),a=t||(o.isVector2?new lt:new SA);return a.copy(s).sub(o).normalize(),a}getTangentAt(A,t){const i=this.getUtoTmapping(A);return this.getTangent(i,t)}computeFrenetFrames(A,t=!1){const i=new SA,n=[],g=[],o=[],s=new SA,a=new ni;for(let B=0;B<=A;B++){const Q=B/A;n[B]=this.getTangentAt(Q,new SA)}g[0]=new SA,o[0]=new SA;let r=Number.MAX_VALUE;const I=Math.abs(n[0].x),c=Math.abs(n[0].y),l=Math.abs(n[0].z);I<=r&&(r=I,i.set(1,0,0)),c<=r&&(r=c,i.set(0,1,0)),l<=r&&i.set(0,0,1),s.crossVectors(n[0],i).normalize(),g[0].crossVectors(n[0],s),o[0].crossVectors(n[0],g[0]);for(let B=1;B<=A;B++){if(g[B]=g[B-1].clone(),o[B]=o[B-1].clone(),s.crossVectors(n[B-1],n[B]),s.length()>Number.EPSILON){s.normalize();const Q=Math.acos(Fi(n[B-1].dot(n[B]),-1,1));g[B].applyMatrix4(a.makeRotationAxis(s,Q))}o[B].crossVectors(n[B],g[B])}if(t===!0){let B=Math.acos(Fi(g[0].dot(g[A]),-1,1));B/=A,n[0].dot(s.crossVectors(g[0],g[A]))>0&&(B=-B);for(let Q=1;Q<=A;Q++)g[Q].applyMatrix4(a.makeRotationAxis(n[Q],B*Q)),o[Q].crossVectors(n[Q],g[Q])}return{tangents:n,normals:g,binormals:o}}clone(){return new this.constructor().copy(this)}copy(A){return this.arcLengthDivisions=A.arcLengthDivisions,this}toJSON(){const A={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return A.arcLengthDivisions=this.arcLengthDivisions,A.type=this.type,A}fromJSON(A){return this.arcLengthDivisions=A.arcLengthDivisions,this}}class eT extends Cl{constructor(A=0,t=0,i=1,n=1,g=0,o=Math.PI*2,s=!1,a=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=A,this.aY=t,this.xRadius=i,this.yRadius=n,this.aStartAngle=g,this.aEndAngle=o,this.aClockwise=s,this.aRotation=a}getPoint(A,t=new lt){const i=t,n=Math.PI*2;let g=this.aEndAngle-this.aStartAngle;const o=Math.abs(g)<Number.EPSILON;for(;g<0;)g+=n;for(;g>n;)g-=n;g<Number.EPSILON&&(o?g=0:g=n),this.aClockwise===!0&&!o&&(g===n?g=-n:g=g-n);const s=this.aStartAngle+A*g;let a=this.aX+this.xRadius*Math.cos(s),r=this.aY+this.yRadius*Math.sin(s);if(this.aRotation!==0){const I=Math.cos(this.aRotation),c=Math.sin(this.aRotation),l=a-this.aX,B=r-this.aY;a=l*I-B*c+this.aX,r=l*c+B*I+this.aY}return i.set(a,r)}copy(A){return super.copy(A),this.aX=A.aX,this.aY=A.aY,this.xRadius=A.xRadius,this.yRadius=A.yRadius,this.aStartAngle=A.aStartAngle,this.aEndAngle=A.aEndAngle,this.aClockwise=A.aClockwise,this.aRotation=A.aRotation,this}toJSON(){const A=super.toJSON();return A.aX=this.aX,A.aY=this.aY,A.xRadius=this.xRadius,A.yRadius=this.yRadius,A.aStartAngle=this.aStartAngle,A.aEndAngle=this.aEndAngle,A.aClockwise=this.aClockwise,A.aRotation=this.aRotation,A}fromJSON(A){return super.fromJSON(A),this.aX=A.aX,this.aY=A.aY,this.xRadius=A.xRadius,this.yRadius=A.yRadius,this.aStartAngle=A.aStartAngle,this.aEndAngle=A.aEndAngle,this.aClockwise=A.aClockwise,this.aRotation=A.aRotation,this}}class ByA extends eT{constructor(A,t,i,n,g,o){super(A,t,i,i,n,g,o),this.isArcCurve=!0,this.type="ArcCurve"}}function HW(){let e=0,A=0,t=0,i=0;function n(g,o,s,a){e=g,A=s,t=-3*g+3*o-2*s-a,i=2*g-2*o+s+a}return{initCatmullRom:function(g,o,s,a,r){n(o,s,r*(s-g),r*(a-o))},initNonuniformCatmullRom:function(g,o,s,a,r,I,c){let l=(o-g)/r-(s-g)/(r+I)+(s-o)/I,B=(s-o)/I-(a-o)/(I+c)+(a-s)/c;l*=I,B*=I,n(o,s,l,B)},calc:function(g){const o=g*g,s=o*g;return e+A*g+t*o+i*s}}}const JU=new SA,MH=new HW,NH=new HW,RH=new HW;class OW extends Cl{constructor(A=[],t=!1,i="centripetal",n=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=A,this.closed=t,this.curveType=i,this.tension=n}getPoint(A,t=new SA){const i=t,n=this.points,g=n.length,o=(g-(this.closed?0:1))*A;let s=Math.floor(o),a=o-s;this.closed?s+=s>0?0:(Math.floor(Math.abs(s)/g)+1)*g:a===0&&s===g-1&&(s=g-2,a=1);let r,I;this.closed||s>0?r=n[(s-1)%g]:(JU.subVectors(n[0],n[1]).add(n[0]),r=JU);const c=n[s%g],l=n[(s+1)%g];if(this.closed||s+2<g?I=n[(s+2)%g]:(JU.subVectors(n[g-1],n[g-2]).add(n[g-1]),I=JU),this.curveType==="centripetal"||this.curveType==="chordal"){const B=this.curveType==="chordal"?.5:.25;let Q=Math.pow(r.distanceToSquared(c),B),h=Math.pow(c.distanceToSquared(l),B),d=Math.pow(l.distanceToSquared(I),B);h<1e-4&&(h=1),Q<1e-4&&(Q=h),d<1e-4&&(d=h),MH.initNonuniformCatmullRom(r.x,c.x,l.x,I.x,Q,h,d),NH.initNonuniformCatmullRom(r.y,c.y,l.y,I.y,Q,h,d),RH.initNonuniformCatmullRom(r.z,c.z,l.z,I.z,Q,h,d)}else this.curveType==="catmullrom"&&(MH.initCatmullRom(r.x,c.x,l.x,I.x,this.tension),NH.initCatmullRom(r.y,c.y,l.y,I.y,this.tension),RH.initCatmullRom(r.z,c.z,l.z,I.z,this.tension));return i.set(MH.calc(a),NH.calc(a),RH.calc(a)),i}copy(A){super.copy(A),this.points=[];for(let t=0,i=A.points.length;t<i;t++){const n=A.points[t];this.points.push(n.clone())}return this.closed=A.closed,this.curveType=A.curveType,this.tension=A.tension,this}toJSON(){const A=super.toJSON();A.points=[];for(let t=0,i=this.points.length;t<i;t++){const n=this.points[t];A.points.push(n.toArray())}return A.closed=this.closed,A.curveType=this.curveType,A.tension=this.tension,A}fromJSON(A){super.fromJSON(A),this.points=[];for(let t=0,i=A.points.length;t<i;t++){const n=A.points[t];this.points.push(new SA().fromArray(n))}return this.closed=A.closed,this.curveType=A.curveType,this.tension=A.tension,this}}function BnA(e,A,t,i,n){const g=(i-A)*.5,o=(n-t)*.5,s=e*e,a=e*s;return(2*t-2*i+g+o)*a+(-3*t+3*i-2*g-o)*s+g*e+t}function dre(e,A){const t=1-e;return t*t*A}function hre(e,A){return 2*(1-e)*e*A}function pre(e,A){return e*e*A}function MM(e,A,t,i){return dre(e,A)+hre(e,t)+pre(e,i)}function fre(e,A){const t=1-e;return t*t*t*A}function yre(e,A){const t=1-e;return 3*t*t*e*A}function Dre(e,A){return 3*(1-e)*e*e*A}function mre(e,A){return e*e*e*A}function NM(e,A,t,i,n){return fre(e,A)+yre(e,t)+Dre(e,i)+mre(e,n)}class PW extends Cl{constructor(A=new lt,t=new lt,i=new lt,n=new lt){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=A,this.v1=t,this.v2=i,this.v3=n}getPoint(A,t=new lt){const i=t,n=this.v0,g=this.v1,o=this.v2,s=this.v3;return i.set(NM(A,n.x,g.x,o.x,s.x),NM(A,n.y,g.y,o.y,s.y)),i}copy(A){return super.copy(A),this.v0.copy(A.v0),this.v1.copy(A.v1),this.v2.copy(A.v2),this.v3.copy(A.v3),this}toJSON(){const A=super.toJSON();return A.v0=this.v0.toArray(),A.v1=this.v1.toArray(),A.v2=this.v2.toArray(),A.v3=this.v3.toArray(),A}fromJSON(A){return super.fromJSON(A),this.v0.fromArray(A.v0),this.v1.fromArray(A.v1),this.v2.fromArray(A.v2),this.v3.fromArray(A.v3),this}}class EyA extends Cl{constructor(A=new SA,t=new SA,i=new SA,n=new SA){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=A,this.v1=t,this.v2=i,this.v3=n}getPoint(A,t=new SA){const i=t,n=this.v0,g=this.v1,o=this.v2,s=this.v3;return i.set(NM(A,n.x,g.x,o.x,s.x),NM(A,n.y,g.y,o.y,s.y),NM(A,n.z,g.z,o.z,s.z)),i}copy(A){return super.copy(A),this.v0.copy(A.v0),this.v1.copy(A.v1),this.v2.copy(A.v2),this.v3.copy(A.v3),this}toJSON(){const A=super.toJSON();return A.v0=this.v0.toArray(),A.v1=this.v1.toArray(),A.v2=this.v2.toArray(),A.v3=this.v3.toArray(),A}fromJSON(A){return super.fromJSON(A),this.v0.fromArray(A.v0),this.v1.fromArray(A.v1),this.v2.fromArray(A.v2),this.v3.fromArray(A.v3),this}}class jW extends Cl{constructor(A=new lt,t=new lt){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=A,this.v2=t}getPoint(A,t=new lt){const i=t;return A===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(A).add(this.v1)),i}getPointAt(A,t){return this.getPoint(A,t)}getTangent(A,t=new lt){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(A,t){return this.getTangent(A,t)}copy(A){return super.copy(A),this.v1.copy(A.v1),this.v2.copy(A.v2),this}toJSON(){const A=super.toJSON();return A.v1=this.v1.toArray(),A.v2=this.v2.toArray(),A}fromJSON(A){return super.fromJSON(A),this.v1.fromArray(A.v1),this.v2.fromArray(A.v2),this}}class QyA extends Cl{constructor(A=new SA,t=new SA){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=A,this.v2=t}getPoint(A,t=new SA){const i=t;return A===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(A).add(this.v1)),i}getPointAt(A,t){return this.getPoint(A,t)}getTangent(A,t=new SA){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(A,t){return this.getTangent(A,t)}copy(A){return super.copy(A),this.v1.copy(A.v1),this.v2.copy(A.v2),this}toJSON(){const A=super.toJSON();return A.v1=this.v1.toArray(),A.v2=this.v2.toArray(),A}fromJSON(A){return super.fromJSON(A),this.v1.fromArray(A.v1),this.v2.fromArray(A.v2),this}}class zW extends Cl{constructor(A=new lt,t=new lt,i=new lt){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=A,this.v1=t,this.v2=i}getPoint(A,t=new lt){const i=t,n=this.v0,g=this.v1,o=this.v2;return i.set(MM(A,n.x,g.x,o.x),MM(A,n.y,g.y,o.y)),i}copy(A){return super.copy(A),this.v0.copy(A.v0),this.v1.copy(A.v1),this.v2.copy(A.v2),this}toJSON(){const A=super.toJSON();return A.v0=this.v0.toArray(),A.v1=this.v1.toArray(),A.v2=this.v2.toArray(),A}fromJSON(A){return super.fromJSON(A),this.v0.fromArray(A.v0),this.v1.fromArray(A.v1),this.v2.fromArray(A.v2),this}}class ZW extends Cl{constructor(A=new SA,t=new SA,i=new SA){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=A,this.v1=t,this.v2=i}getPoint(A,t=new SA){const i=t,n=this.v0,g=this.v1,o=this.v2;return i.set(MM(A,n.x,g.x,o.x),MM(A,n.y,g.y,o.y),MM(A,n.z,g.z,o.z)),i}copy(A){return super.copy(A),this.v0.copy(A.v0),this.v1.copy(A.v1),this.v2.copy(A.v2),this}toJSON(){const A=super.toJSON();return A.v0=this.v0.toArray(),A.v1=this.v1.toArray(),A.v2=this.v2.toArray(),A}fromJSON(A){return super.fromJSON(A),this.v0.fromArray(A.v0),this.v1.fromArray(A.v1),this.v2.fromArray(A.v2),this}}class WW extends Cl{constructor(A=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=A}getPoint(A,t=new lt){const i=t,n=this.points,g=(n.length-1)*A,o=Math.floor(g),s=g-o,a=n[o===0?o:o-1],r=n[o],I=n[o>n.length-2?n.length-1:o+1],c=n[o>n.length-3?n.length-1:o+2];return i.set(BnA(s,a.x,r.x,I.x,c.x),BnA(s,a.y,r.y,I.y,c.y)),i}copy(A){super.copy(A),this.points=[];for(let t=0,i=A.points.length;t<i;t++){const n=A.points[t];this.points.push(n.clone())}return this}toJSON(){const A=super.toJSON();A.points=[];for(let t=0,i=this.points.length;t<i;t++){const n=this.points[t];A.points.push(n.toArray())}return A}fromJSON(A){super.fromJSON(A),this.points=[];for(let t=0,i=A.points.length;t<i;t++){const n=A.points[t];this.points.push(new lt().fromArray(n))}return this}}var yJ=Object.freeze({__proto__:null,ArcCurve:ByA,CatmullRomCurve3:OW,CubicBezierCurve:PW,CubicBezierCurve3:EyA,EllipseCurve:eT,LineCurve:jW,LineCurve3:QyA,QuadraticBezierCurve:zW,QuadraticBezierCurve3:ZW,SplineCurve:WW});class uyA extends Cl{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(A){this.curves.push(A)}closePath(){const A=this.curves[0].getPoint(0),t=this.curves[this.curves.length-1].getPoint(1);if(!A.equals(t)){const i=A.isVector2===!0?"LineCurve":"LineCurve3";this.curves.push(new yJ[i](t,A))}return this}getPoint(A,t){const i=A*this.getLength(),n=this.getCurveLengths();let g=0;for(;g<n.length;){if(n[g]>=i){const o=n[g]-i,s=this.curves[g],a=s.getLength(),r=a===0?0:1-o/a;return s.getPointAt(r,t)}g++}return null}getLength(){const A=this.getCurveLengths();return A[A.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const A=[];let t=0;for(let i=0,n=this.curves.length;i<n;i++)t+=this.curves[i].getLength(),A.push(t);return this.cacheLengths=A,A}getSpacedPoints(A=40){const t=[];for(let i=0;i<=A;i++)t.push(this.getPoint(i/A));return this.autoClose&&t.push(t[0]),t}getPoints(A=12){const t=[];let i;for(let n=0,g=this.curves;n<g.length;n++){const o=g[n],s=o.isEllipseCurve?A*2:o.isLineCurve||o.isLineCurve3?1:o.isSplineCurve?A*o.points.length:A,a=o.getPoints(s);for(let r=0;r<a.length;r++){const I=a[r];i&&i.equals(I)||(t.push(I),i=I)}}return this.autoClose&&t.length>1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(A){super.copy(A),this.curves=[];for(let t=0,i=A.curves.length;t<i;t++){const n=A.curves[t];this.curves.push(n.clone())}return this.autoClose=A.autoClose,this}toJSON(){const A=super.toJSON();A.autoClose=this.autoClose,A.curves=[];for(let t=0,i=this.curves.length;t<i;t++){const n=this.curves[t];A.curves.push(n.toJSON())}return A}fromJSON(A){super.fromJSON(A),this.autoClose=A.autoClose,this.curves=[];for(let t=0,i=A.curves.length;t<i;t++){const n=A.curves[t];this.curves.push(new yJ[n.type]().fromJSON(n))}return this}}class DJ extends uyA{constructor(A){super(),this.type="Path",this.currentPoint=new lt,A&&this.setFromPoints(A)}setFromPoints(A){this.moveTo(A[0].x,A[0].y);for(let t=1,i=A.length;t<i;t++)this.lineTo(A[t].x,A[t].y);return this}moveTo(A,t){return this.currentPoint.set(A,t),this}lineTo(A,t){const i=new jW(this.currentPoint.clone(),new lt(A,t));return this.curves.push(i),this.currentPoint.set(A,t),this}quadraticCurveTo(A,t,i,n){const g=new zW(this.currentPoint.clone(),new lt(A,t),new lt(i,n));return this.curves.push(g),this.currentPoint.set(i,n),this}bezierCurveTo(A,t,i,n,g,o){const s=new PW(this.currentPoint.clone(),new lt(A,t),new lt(i,n),new lt(g,o));return this.curves.push(s),this.currentPoint.set(g,o),this}splineThru(A){const t=[this.currentPoint.clone()].concat(A),i=new WW(t);return this.curves.push(i),this.currentPoint.copy(A[A.length-1]),this}arc(A,t,i,n,g,o){const s=this.currentPoint.x,a=this.currentPoint.y;return this.absarc(A+s,t+a,i,n,g,o),this}absarc(A,t,i,n,g,o){return this.absellipse(A,t,i,i,n,g,o),this}ellipse(A,t,i,n,g,o,s,a){const r=this.currentPoint.x,I=this.currentPoint.y;return this.absellipse(A+r,t+I,i,n,g,o,s,a),this}absellipse(A,t,i,n,g,o,s,a){const r=new eT(A,t,i,n,g,o,s,a);if(this.curves.length>0){const c=r.getPoint(0);c.equals(this.currentPoint)||this.lineTo(c.x,c.y)}this.curves.push(r);const I=r.getPoint(1);return this.currentPoint.copy(I),this}copy(A){return super.copy(A),this.currentPoint.copy(A.currentPoint),this}toJSON(){const A=super.toJSON();return A.currentPoint=this.currentPoint.toArray(),A}fromJSON(A){return super.fromJSON(A),this.currentPoint.fromArray(A.currentPoint),this}}class jp extends DJ{constructor(A){super(A),this.uuid=$I(),this.type="Shape",this.holes=[]}getPointsHoles(A){const t=[];for(let i=0,n=this.holes.length;i<n;i++)t[i]=this.holes[i].getPoints(A);return t}extractPoints(A){return{shape:this.getPoints(A),holes:this.getPointsHoles(A)}}copy(A){super.copy(A),this.holes=[];for(let t=0,i=A.holes.length;t<i;t++){const n=A.holes[t];this.holes.push(n.clone())}return this}toJSON(){const A=super.toJSON();A.uuid=this.uuid,A.holes=[];for(let t=0,i=this.holes.length;t<i;t++){const n=this.holes[t];A.holes.push(n.toJSON())}return A}fromJSON(A){super.fromJSON(A),this.uuid=A.uuid,this.holes=[];for(let t=0,i=A.holes.length;t<i;t++){const n=A.holes[t];this.holes.push(new DJ().fromJSON(n))}return this}}function Sre(e,A,t=2){const i=A&&A.length,n=i?A[0]*t:e.length;let g=dyA(e,0,n,t,!0);const o=[];if(!g||g.next===g.prev)return o;let s,a,r;if(i&&(g=Rre(e,A,g,t)),e.length>80*t){s=1/0,a=1/0;let I=-1/0,c=-1/0;for(let l=t;l<n;l+=t){const B=e[l],Q=e[l+1];B<s&&(s=B),Q<a&&(a=Q),B>I&&(I=B),Q>c&&(c=Q)}r=Math.max(I-s,c-a),r=r!==0?32767/r:0}return _N(g,o,t,s,a,r,0),o}function dyA(e,A,t,i,n){let g;if(n===Tre(e,A,t,i)>0)for(let o=A;o<t;o+=i)g=EnA(o/i|0,e[o],e[o+1],g);else for(let o=t-i;o>=A;o-=i)g=EnA(o/i|0,e[o],e[o+1],g);return g&&zS(g,g.next)&&(LN(g),g=g.next),g}function mf(e,A){if(!e)return e;A||(A=e);let t=e,i;do if(i=!1,!t.steiner&&(zS(t,t.next)||ko(t.prev,t,t.next)===0)){if(LN(t),t=A=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==A);return A}function _N(e,A,t,i,n,g,o){if(!e)return;!o&&g&&Kre(e,i,n,g);let s=e;for(;e.prev!==e.next;){const a=e.prev,r=e.next;if(g?kre(e,i,n,g):wre(e)){A.push(a.i,e.i,r.i),LN(e),e=r.next,s=r.next;continue}if(e=r,e===s){o?o===1?(e=Mre(mf(e),A),_N(e,A,t,i,n,g,2)):o===2&&Nre(e,A,t,i,n,g):_N(mf(e),A,t,i,n,g,1);break}}}function wre(e){const A=e.prev,t=e,i=e.next;if(ko(A,t,i)>=0)return!1;const n=A.x,g=t.x,o=i.x,s=A.y,a=t.y,r=i.y,I=Math.min(n,g,o),c=Math.min(s,a,r),l=Math.max(n,g,o),B=Math.max(s,a,r);let Q=i.next;for(;Q!==A;){if(Q.x>=I&&Q.x<=l&&Q.y>=c&&Q.y<=B&&Rk(n,s,g,a,o,r,Q.x,Q.y)&&ko(Q.prev,Q,Q.next)>=0)return!1;Q=Q.next}return!0}function kre(e,A,t,i){const n=e.prev,g=e,o=e.next;if(ko(n,g,o)>=0)return!1;const s=n.x,a=g.x,r=o.x,I=n.y,c=g.y,l=o.y,B=Math.min(s,a,r),Q=Math.min(I,c,l),h=Math.max(s,a,r),d=Math.max(I,c,l),p=r4(B,Q,A,t,i),y=r4(h,d,A,t,i);let m=e.prevZ,D=e.nextZ;for(;m&&m.z>=p&&D&&D.z<=y;){if(m.x>=B&&m.x<=h&&m.y>=Q&&m.y<=d&&m!==n&&m!==o&&Rk(s,I,a,c,r,l,m.x,m.y)&&ko(m.prev,m,m.next)>=0||(m=m.prevZ,D.x>=B&&D.x<=h&&D.y>=Q&&D.y<=d&&D!==n&&D!==o&&Rk(s,I,a,c,r,l,D.x,D.y)&&ko(D.prev,D,D.next)>=0))return!1;D=D.nextZ}for(;m&&m.z>=p;){if(m.x>=B&&m.x<=h&&m.y>=Q&&m.y<=d&&m!==n&&m!==o&&Rk(s,I,a,c,r,l,m.x,m.y)&&ko(m.prev,m,m.next)>=0)return!1;m=m.prevZ}for(;D&&D.z<=y;){if(D.x>=B&&D.x<=h&&D.y>=Q&&D.y<=d&&D!==n&&D!==o&&Rk(s,I,a,c,r,l,D.x,D.y)&&ko(D.prev,D,D.next)>=0)return!1;D=D.nextZ}return!0}function Mre(e,A){let t=e;do{const i=t.prev,n=t.next.next;!zS(i,n)&&pyA(i,t,t.next,n)&&JN(i,n)&&JN(n,i)&&(A.push(i.i,t.i,n.i),LN(t),LN(t.next),t=e=n),t=t.next}while(t!==e);return mf(t)}function Nre(e,A,t,i,n,g){let o=e;do{let s=o.next.next;for(;s!==o.prev;){if(o.i!==s.i&&Jre(o,s)){let a=fyA(o,s);o=mf(o,o.next),a=mf(a,a.next),_N(o,A,t,i,n,g,0),_N(a,A,t,i,n,g,0);return}s=s.next}o=o.next}while(o!==e)}function Rre(e,A,t,i){const n=[];for(let g=0,o=A.length;g<o;g++){const s=A[g]*i,a=g<o-1?A[g+1]*i:e.length,r=dyA(e,s,a,i,!1);r===r.next&&(r.steiner=!0),n.push(_re(r))}n.sort(Gre);for(let g=0;g<n.length;g++)t=bre(n[g],t);return t}function Gre(e,A){let t=e.x-A.x;if(t===0&&(t=e.y-A.y,t===0)){const i=(e.next.y-e.y)/(e.next.x-e.x),n=(A.next.y-A.y)/(A.next.x-A.x);t=i-n}return t}function bre(e,A){const t=Ure(e,A);if(!t)return A;const i=fyA(t,e);return mf(i,i.next),mf(t,t.next)}function Ure(e,A){let t=A;const i=e.x,n=e.y;let g=-1/0,o;if(zS(e,t))return t;do{if(zS(e,t.next))return t.next;if(n<=t.y&&n>=t.next.y&&t.next.y!==t.y){const c=t.x+(n-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(c<=i&&c>g&&(g=c,o=t.x<t.next.x?t:t.next,c===i))return o}t=t.next}while(t!==A);if(!o)return null;const s=o,a=o.x,r=o.y;let I=1/0;t=o;do{if(i>=t.x&&t.x>=a&&i!==t.x&&hyA(n<r?i:g,n,a,r,n<r?g:i,n,t.x,t.y)){const c=Math.abs(n-t.y)/(i-t.x);JN(t,e)&&(c<I||c===I&&(t.x>o.x||t.x===o.x&&vre(o,t)))&&(o=t,I=c)}t=t.next}while(t!==s);return o}function vre(e,A){return ko(e.prev,e,A.prev)<0&&ko(A.next,e,e.next)<0}function Kre(e,A,t,i){let n=e;do n.z===0&&(n.z=r4(n.x,n.y,A,t,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==e);n.prevZ.nextZ=null,n.prevZ=null,Fre(n)}function Fre(e){let A,t=1;do{let i=e,n;e=null;let g=null;for(A=0;i;){A++;let o=i,s=0;for(let r=0;r<t&&(s++,o=o.nextZ,!!o);r++);let a=t;for(;s>0||a>0&&o;)s!==0&&(a===0||!o||i.z<=o.z)?(n=i,i=i.nextZ,s--):(n=o,o=o.nextZ,a--),g?g.nextZ=n:e=n,n.prevZ=g,g=n;i=o}g.nextZ=null,t*=2}while(A>1);return e}function r4(e,A,t,i,n){return e=(e-t)*n|0,A=(A-i)*n|0,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,A=(A|A<<8)&16711935,A=(A|A<<4)&252645135,A=(A|A<<2)&858993459,A=(A|A<<1)&1431655765,e|A<<1}function _re(e){let A=e,t=e;do(A.x<t.x||A.x===t.x&&A.y<t.y)&&(t=A),A=A.next;while(A!==e);return t}function hyA(e,A,t,i,n,g,o,s){return(n-o)*(A-s)>=(e-o)*(g-s)&&(e-o)*(i-s)>=(t-o)*(A-s)&&(t-o)*(g-s)>=(n-o)*(i-s)}function Rk(e,A,t,i,n,g,o,s){return!(e===o&&A===s)&&hyA(e,A,t,i,n,g,o,s)}function Jre(e,A){return e.next.i!==A.i&&e.prev.i!==A.i&&!Lre(e,A)&&(JN(e,A)&&JN(A,e)&&xre(e,A)&&(ko(e.prev,e,A.prev)||ko(e,A.prev,A))||zS(e,A)&&ko(e.prev,e,e.next)>0&&ko(A.prev,A,A.next)>0)}function ko(e,A,t){return(A.y-e.y)*(t.x-A.x)-(A.x-e.x)*(t.y-A.y)}function zS(e,A){return e.x===A.x&&e.y===A.y}function pyA(e,A,t,i){const n=xU(ko(e,A,t)),g=xU(ko(e,A,i)),o=xU(ko(t,i,e)),s=xU(ko(t,i,A));return!!(n!==g&&o!==s||n===0&&LU(e,t,A)||g===0&&LU(e,i,A)||o===0&&LU(t,e,i)||s===0&&LU(t,A,i))}function LU(e,A,t){return A.x<=Math.max(e.x,t.x)&&A.x>=Math.min(e.x,t.x)&&A.y<=Math.max(e.y,t.y)&&A.y>=Math.min(e.y,t.y)}function xU(e){return e>0?1:e<0?-1:0}function Lre(e,A){let t=e;do{if(t.i!==e.i&&t.next.i!==e.i&&t.i!==A.i&&t.next.i!==A.i&&pyA(t,t.next,e,A))return!0;t=t.next}while(t!==e);return!1}function JN(e,A){return ko(e.prev,e,e.next)<0?ko(e,A,e.next)>=0&&ko(e,e.prev,A)>=0:ko(e,A,e.prev)<0||ko(e,e.next,A)<0}function xre(e,A){let t=e,i=!1;const n=(e.x+A.x)/2,g=(e.y+A.y)/2;do t.y>g!=t.next.y>g&&t.next.y!==t.y&&n<(t.next.x-t.x)*(g-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==e);return i}function fyA(e,A){const t=I4(e.i,e.x,e.y),i=I4(A.i,A.x,A.y),n=e.next,g=A.prev;return e.next=A,A.prev=e,t.next=n,n.prev=t,i.next=t,t.prev=i,g.next=i,i.prev=g,i}function EnA(e,A,t,i){const n=I4(e,A,t);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function LN(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function I4(e,A,t){return{i:e,x:A,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function Tre(e,A,t,i){let n=0;for(let g=A,o=t-i;g<t;g+=i)n+=(e[o]-e[g])*(e[g+1]+e[o+1]),o=g;return n}class qre{static triangulate(A,t,i=2){return Sre(A,t,i)}}class zc{static area(A){const t=A.length;let i=0;for(let n=t-1,g=0;g<t;n=g++)i+=A[n].x*A[g].y-A[g].x*A[n].y;return i*.5}static isClockWise(A){return zc.area(A)<0}static triangulateShape(A,t){const i=[],n=[],g=[];QnA(A),unA(i,A);let o=A.length;t.forEach(QnA);for(let a=0;a<t.length;a++)n.push(o),o+=t[a].length,unA(i,t[a]);const s=qre.triangulate(i,n);for(let a=0;a<s.length;a+=3)g.push(s.slice(a,a+3));return g}}function QnA(e){const A=e.length;A>2&&e[A-1].equals(e[0])&&e.pop()}function unA(e,A){for(let t=0;t<A.length;t++)e.push(A[t].x),e.push(A[t].y)}class tT extends Ni{constructor(A=new jp([new lt(.5,.5),new lt(-.5,.5),new lt(-.5,-.5),new lt(.5,-.5)]),t={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:A,options:t},A=Array.isArray(A)?A:[A];const i=this,n=[],g=[];for(let s=0,a=A.length;s<a;s++){const r=A[s];o(r)}this.setAttribute("position",new $t(n,3)),this.setAttribute("uv",new $t(g,2)),this.computeVertexNormals();function o(s){const a=[],r=t.curveSegments!==void 0?t.curveSegments:12,I=t.steps!==void 0?t.steps:1,c=t.depth!==void 0?t.depth:1;let l=t.bevelEnabled!==void 0?t.bevelEnabled:!0,B=t.bevelThickness!==void 0?t.bevelThickness:.2,Q=t.bevelSize!==void 0?t.bevelSize:B-.1,h=t.bevelOffset!==void 0?t.bevelOffset:0,d=t.bevelSegments!==void 0?t.bevelSegments:3;const p=t.extrudePath,y=t.UVGenerator!==void 0?t.UVGenerator:Yre;let m,D=!1,S,k,N,G;p&&(m=p.getSpacedPoints(I),D=!0,l=!1,S=p.computeFrenetFrames(I,!1),k=new SA,N=new SA,G=new SA),l||(d=0,B=0,Q=0,h=0);const M=s.extractPoints(r);let w=M.shape;const b=M.holes;if(!zc.isClockWise(w)){w=w.reverse();for(let H=0,P=b.length;H<P;H++){const tA=b[H];zc.isClockWise(tA)&&(b[H]=tA.reverse())}}function K(H){const tA=10000000000000001e-36;let iA=H[0];for(let oA=1;oA<=H.length;oA++){const IA=oA%H.length,CA=H[IA],_A=CA.x-iA.x,uA=CA.y-iA.y,X=_A*_A+uA*uA,O=Math.max(Math.abs(CA.x),Math.abs(CA.y),Math.abs(iA.x),Math.abs(iA.y)),cA=tA*O*O;if(X<=cA){H.splice(IA,1),oA--;continue}iA=CA}}K(w),b.forEach(K);const J=b.length,q=w;for(let H=0;H<J;H++){const P=b[H];w=w.concat(P)}function v(H,P,tA){return P||console.error("THREE.ExtrudeGeometry: vec does not exist"),H.clone().addScaledVector(P,tA)}const U=w.length;function x(H,P,tA){let iA,oA,IA;const CA=H.x-P.x,_A=H.y-P.y,uA=tA.x-H.x,X=tA.y-H.y,O=CA*CA+_A*_A,cA=CA*X-_A*uA;if(Math.abs(cA)>Number.EPSILON){const wA=Math.sqrt(O),xA=Math.sqrt(uA*uA+X*X),YA=P.x-_A/wA,jA=P.y+CA/wA,ie=tA.x-X/xA,he=tA.y+uA/xA,le=((ie-YA)*X-(he-jA)*uA)/(CA*X-_A*uA);iA=YA+CA*le-H.x,oA=jA+_A*le-H.y;const NA=iA*iA+oA*oA;if(NA<=2)return new lt(iA,oA);IA=Math.sqrt(NA/2)}else{let wA=!1;CA>Number.EPSILON?uA>Number.EPSILON&&(wA=!0):CA<-Number.EPSILON?uA<-Number.EPSILON&&(wA=!0):Math.sign(_A)===Math.sign(X)&&(wA=!0),wA?(iA=-_A,oA=CA,IA=Math.sqrt(O)):(iA=CA,oA=_A,IA=Math.sqrt(O/2))}return new lt(iA/IA,oA/IA)}const T=[];for(let H=0,P=q.length,tA=P-1,iA=H+1;H<P;H++,tA++,iA++)tA===P&&(tA=0),iA===P&&(iA=0),T[H]=x(q[H],q[tA],q[iA]);const z=[];let Z,eA=T.concat();for(let H=0,P=J;H<P;H++){const tA=b[H];Z=[];for(let iA=0,oA=tA.length,IA=oA-1,CA=iA+1;iA<oA;iA++,IA++,CA++)IA===oA&&(IA=0),CA===oA&&(CA=0),Z[iA]=x(tA[iA],tA[IA],tA[CA]);z.push(Z),eA=eA.concat(Z)}let aA;if(d===0)aA=zc.triangulateShape(q,b);else{const H=[],P=[];for(let tA=0;tA<d;tA++){const iA=tA/d,oA=B*Math.cos(iA*Math.PI/2),IA=Q*Math.sin(iA*Math.PI/2)+h;for(let CA=0,_A=q.length;CA<_A;CA++){const uA=v(q[CA],T[CA],IA);RA(uA.x,uA.y,-oA),iA===0&&H.push(uA)}for(let CA=0,_A=J;CA<_A;CA++){const uA=b[CA];Z=z[CA];const X=[];for(let O=0,cA=uA.length;O<cA;O++){const wA=v(uA[O],Z[O],IA);RA(wA.x,wA.y,-oA),iA===0&&X.push(wA)}iA===0&&P.push(X)}}aA=zc.triangulateShape(H,P)}const sA=aA.length,pA=Q+h;for(let H=0;H<U;H++){const P=l?v(w[H],eA[H],pA):w[H];D?(N.copy(S.normals[0]).multiplyScalar(P.x),k.copy(S.binormals[0]).multiplyScalar(P.y),G.copy(m[0]).add(N).add(k),RA(G.x,G.y,G.z)):RA(P.x,P.y,0)}for(let H=1;H<=I;H++)for(let P=0;P<U;P++){const tA=l?v(w[P],eA[P],pA):w[P];D?(N.copy(S.normals[H]).multiplyScalar(tA.x),k.copy(S.binormals[H]).multiplyScalar(tA.y),G.copy(m[H]).add(N).add(k),RA(G.x,G.y,G.z)):RA(tA.x,tA.y,c/I*H)}for(let H=d-1;H>=0;H--){const P=H/d,tA=B*Math.cos(P*Math.PI/2),iA=Q*Math.sin(P*Math.PI/2)+h;for(let oA=0,IA=q.length;oA<IA;oA++){const CA=v(q[oA],T[oA],iA);RA(CA.x,CA.y,c+tA)}for(let oA=0,IA=b.length;oA<IA;oA++){const CA=b[oA];Z=z[oA];for(let _A=0,uA=CA.length;_A<uA;_A++){const X=v(CA[_A],Z[_A],iA);D?RA(X.x,X.y+m[I-1].y,m[I-1].x+tA):RA(X.x,X.y,c+tA)}}}gA(),yA();function gA(){const H=n.length/3;if(l){let P=0,tA=U*P;for(let iA=0;iA<sA;iA++){const oA=aA[iA];qA(oA[2]+tA,oA[1]+tA,oA[0]+tA)}P=I+d*2,tA=U*P;for(let iA=0;iA<sA;iA++){const oA=aA[iA];qA(oA[0]+tA,oA[1]+tA,oA[2]+tA)}}else{for(let P=0;P<sA;P++){const tA=aA[P];qA(tA[2],tA[1],tA[0])}for(let P=0;P<sA;P++){const tA=aA[P];qA(tA[0]+U*I,tA[1]+U*I,tA[2]+U*I)}}i.addGroup(H,n.length/3-H,0)}function yA(){const H=n.length/3;let P=0;fA(q,P),P+=q.length;for(let tA=0,iA=b.length;tA<iA;tA++){const oA=b[tA];fA(oA,P),P+=oA.length}i.addGroup(H,n.length/3-H,1)}function fA(H,P){let tA=H.length;for(;--tA>=0;){const iA=tA;let oA=tA-1;oA<0&&(oA=H.length-1);for(let IA=0,CA=I+d*2;IA<CA;IA++){const _A=U*IA,uA=U*(IA+1),X=P+iA+_A,O=P+oA+_A,cA=P+oA+uA,wA=P+iA+uA;W(X,O,cA,wA)}}}function RA(H,P,tA){a.push(H),a.push(P),a.push(tA)}function qA(H,P,tA){$(H),$(P),$(tA);const iA=n.length/3,oA=y.generateTopUV(i,n,iA-3,iA-2,iA-1);L(oA[0]),L(oA[1]),L(oA[2])}function W(H,P,tA,iA){$(H),$(P),$(iA),$(P),$(tA),$(iA);const oA=n.length/3,IA=y.generateSideWallUV(i,n,oA-6,oA-3,oA-2,oA-1);L(IA[0]),L(IA[1]),L(IA[3]),L(IA[1]),L(IA[2]),L(IA[3])}function $(H){n.push(a[H*3+0]),n.push(a[H*3+1]),n.push(a[H*3+2])}function L(H){g.push(H.x),g.push(H.y)}}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}toJSON(){const A=super.toJSON(),t=this.parameters.shapes,i=this.parameters.options;return Hre(t,i,A)}static fromJSON(A,t){const i=[];for(let g=0,o=A.shapes.length;g<o;g++){const s=t[A.shapes[g]];i.push(s)}const n=A.options.extrudePath;return n!==void 0&&(A.options.extrudePath=new yJ[n.type]().fromJSON(n)),new tT(i,A.options)}}const Yre={generateTopUV:function(e,A,t,i,n){const g=A[t*3],o=A[t*3+1],s=A[i*3],a=A[i*3+1],r=A[n*3],I=A[n*3+1];return[new lt(g,o),new lt(s,a),new lt(r,I)]},generateSideWallUV:function(e,A,t,i,n,g){const o=A[t*3],s=A[t*3+1],a=A[t*3+2],r=A[i*3],I=A[i*3+1],c=A[i*3+2],l=A[n*3],B=A[n*3+1],Q=A[n*3+2],h=A[g*3],d=A[g*3+1],p=A[g*3+2];return Math.abs(s-I)<Math.abs(o-r)?[new lt(o,1-a),new lt(r,1-c),new lt(l,1-Q),new lt(h,1-p)]:[new lt(s,1-a),new lt(I,1-c),new lt(B,1-Q),new lt(d,1-p)]}};function Hre(e,A,t){if(t.shapes=[],Array.isArray(e))for(let i=0,n=e.length;i<n;i++){const g=e[i];t.shapes.push(g.uuid)}else t.shapes.push(e.uuid);return t.options=Object.assign({},A),A.extrudePath!==void 0&&(t.options.extrudePath=A.extrudePath.toJSON()),t}class iT extends Td{constructor(A=1,t=0){const i=(1+Math.sqrt(5))/2,n=[-1,i,0,1,i,0,-1,-i,0,1,-i,0,0,-1,i,0,1,i,0,-1,-i,0,1,-i,i,0,-1,i,0,1,-i,0,-1,-i,0,1],g=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(n,g,A,t),this.type="IcosahedronGeometry",this.parameters={radius:A,detail:t}}static fromJSON(A){return new iT(A.radius,A.detail)}}class nT extends Ni{constructor(A=[new lt(0,-.5),new lt(.5,0),new lt(0,.5)],t=12,i=0,n=Math.PI*2){super(),this.type="LatheGeometry",this.parameters={points:A,segments:t,phiStart:i,phiLength:n},t=Math.floor(t),n=Fi(n,0,Math.PI*2);const g=[],o=[],s=[],a=[],r=[],I=1/t,c=new SA,l=new lt,B=new SA,Q=new SA,h=new SA;let d=0,p=0;for(let y=0;y<=A.length-1;y++)switch(y){case 0:d=A[y+1].x-A[y].x,p=A[y+1].y-A[y].y,B.x=p*1,B.y=-d,B.z=p*0,h.copy(B),B.normalize(),a.push(B.x,B.y,B.z);break;case A.length-1:a.push(h.x,h.y,h.z);break;default:d=A[y+1].x-A[y].x,p=A[y+1].y-A[y].y,B.x=p*1,B.y=-d,B.z=p*0,Q.copy(B),B.x+=h.x,B.y+=h.y,B.z+=h.z,B.normalize(),a.push(B.x,B.y,B.z),h.copy(Q)}for(let y=0;y<=t;y++){const m=i+y*I*n,D=Math.sin(m),S=Math.cos(m);for(let k=0;k<=A.length-1;k++){c.x=A[k].x*D,c.y=A[k].y,c.z=A[k].x*S,o.push(c.x,c.y,c.z),l.x=y/t,l.y=k/(A.length-1),s.push(l.x,l.y);const N=a[3*k+0]*D,G=a[3*k+1],M=a[3*k+0]*S;r.push(N,G,M)}}for(let y=0;y<t;y++)for(let m=0;m<A.length-1;m++){const D=m+y*A.length,S=D,k=D+A.length,N=D+A.length+1,G=D+1;g.push(S,k,G),g.push(N,G,k)}this.setIndex(g),this.setAttribute("position",new $t(o,3)),this.setAttribute("uv",new $t(s,2)),this.setAttribute("normal",new $t(r,3))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new nT(A.points,A.segments,A.phiStart,A.phiLength)}}class lG extends Td{constructor(A=1,t=0){const i=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],n=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2];super(i,n,A,t),this.type="OctahedronGeometry",this.parameters={radius:A,detail:t}}static fromJSON(A){return new lG(A.radius,A.detail)}}class oB extends Ni{constructor(A=1,t=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:A,height:t,widthSegments:i,heightSegments:n};const g=A/2,o=t/2,s=Math.floor(i),a=Math.floor(n),r=s+1,I=a+1,c=A/s,l=t/a,B=[],Q=[],h=[],d=[];for(let p=0;p<I;p++){const y=p*l-o;for(let m=0;m<r;m++){const D=m*c-g;Q.push(D,-y,0),h.push(0,0,1),d.push(m/s),d.push(1-p/a)}}for(let p=0;p<a;p++)for(let y=0;y<s;y++){const m=y+r*p,D=y+r*(p+1),S=y+1+r*(p+1),k=y+1+r*p;B.push(m,D,k),B.push(D,S,k)}this.setIndex(B),this.setAttribute("position",new $t(Q,3)),this.setAttribute("normal",new $t(h,3)),this.setAttribute("uv",new $t(d,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new oB(A.width,A.height,A.widthSegments,A.heightSegments)}}class gT extends Ni{constructor(A=.5,t=1,i=32,n=1,g=0,o=Math.PI*2){super(),this.type="RingGeometry",this.parameters={innerRadius:A,outerRadius:t,thetaSegments:i,phiSegments:n,thetaStart:g,thetaLength:o},i=Math.max(3,i),n=Math.max(1,n);const s=[],a=[],r=[],I=[];let c=A;const l=(t-A)/n,B=new SA,Q=new lt;for(let h=0;h<=n;h++){for(let d=0;d<=i;d++){const p=g+d/i*o;B.x=c*Math.cos(p),B.y=c*Math.sin(p),a.push(B.x,B.y,B.z),r.push(0,0,1),Q.x=(B.x/t+1)/2,Q.y=(B.y/t+1)/2,I.push(Q.x,Q.y)}c+=l}for(let h=0;h<n;h++){const d=h*(i+1);for(let p=0;p<i;p++){const y=p+d,m=y,D=y+i+1,S=y+i+2,k=y+1;s.push(m,D,k),s.push(D,S,k)}}this.setIndex(s),this.setAttribute("position",new $t(a,3)),this.setAttribute("normal",new $t(r,3)),this.setAttribute("uv",new $t(I,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new gT(A.innerRadius,A.outerRadius,A.thetaSegments,A.phiSegments,A.thetaStart,A.thetaLength)}}class oT extends Ni{constructor(A=new jp([new lt(0,.5),new lt(-.5,-.5),new lt(.5,-.5)]),t=12){super(),this.type="ShapeGeometry",this.parameters={shapes:A,curveSegments:t};const i=[],n=[],g=[],o=[];let s=0,a=0;if(Array.isArray(A)===!1)r(A);else for(let I=0;I<A.length;I++)r(A[I]),this.addGroup(s,a,I),s+=a,a=0;this.setIndex(i),this.setAttribute("position",new $t(n,3)),this.setAttribute("normal",new $t(g,3)),this.setAttribute("uv",new $t(o,2));function r(I){const c=n.length/3,l=I.extractPoints(t);let B=l.shape;const Q=l.holes;zc.isClockWise(B)===!1&&(B=B.reverse());for(let d=0,p=Q.length;d<p;d++){const y=Q[d];zc.isClockWise(y)===!0&&(Q[d]=y.reverse())}const h=zc.triangulateShape(B,Q);for(let d=0,p=Q.length;d<p;d++){const y=Q[d];B=B.concat(y)}for(let d=0,p=B.length;d<p;d++){const y=B[d];n.push(y.x,y.y,0),g.push(0,0,1),o.push(y.x,y.y)}for(let d=0,p=h.length;d<p;d++){const y=h[d],m=y[0]+c,D=y[1]+c,S=y[2]+c;i.push(m,D,S),a+=3}}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}toJSON(){const A=super.toJSON(),t=this.parameters.shapes;return Ore(t,A)}static fromJSON(A,t){const i=[];for(let n=0,g=A.shapes.length;n<g;n++){const o=t[A.shapes[n]];i.push(o)}return new oT(i,A.curveSegments)}}function Ore(e,A){if(A.shapes=[],Array.isArray(e))for(let t=0,i=e.length;t<i;t++){const n=e[t];A.shapes.push(n.uuid)}else A.shapes.push(e.uuid);return A}class Sf extends Ni{constructor(A=1,t=32,i=16,n=0,g=Math.PI*2,o=0,s=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:A,widthSegments:t,heightSegments:i,phiStart:n,phiLength:g,thetaStart:o,thetaLength:s},t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));const a=Math.min(o+s,Math.PI);let r=0;const I=[],c=new SA,l=new SA,B=[],Q=[],h=[],d=[];for(let p=0;p<=i;p++){const y=[],m=p/i;let D=0;p===0&&o===0?D=.5/t:p===i&&a===Math.PI&&(D=-.5/t);for(let S=0;S<=t;S++){const k=S/t;c.x=-A*Math.cos(n+k*g)*Math.sin(o+m*s),c.y=A*Math.cos(o+m*s),c.z=A*Math.sin(n+k*g)*Math.sin(o+m*s),Q.push(c.x,c.y,c.z),l.copy(c).normalize(),h.push(l.x,l.y,l.z),d.push(k+D,1-m),y.push(r++)}I.push(y)}for(let p=0;p<i;p++)for(let y=0;y<t;y++){const m=I[p][y+1],D=I[p][y],S=I[p+1][y],k=I[p+1][y+1];(p!==0||o>0)&&B.push(m,D,k),(p!==i-1||a<Math.PI)&&B.push(D,S,k)}this.setIndex(B),this.setAttribute("position",new $t(Q,3)),this.setAttribute("normal",new $t(h,3)),this.setAttribute("uv",new $t(d,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new Sf(A.radius,A.widthSegments,A.heightSegments,A.phiStart,A.phiLength,A.thetaStart,A.thetaLength)}}class sT extends Td{constructor(A=1,t=0){const i=[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],n=[2,1,0,0,3,2,1,3,0,2,3,1];super(i,n,A,t),this.type="TetrahedronGeometry",this.parameters={radius:A,detail:t}}static fromJSON(A){return new sT(A.radius,A.detail)}}class aT extends Ni{constructor(A=1,t=.4,i=12,n=48,g=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:A,tube:t,radialSegments:i,tubularSegments:n,arc:g},i=Math.floor(i),n=Math.floor(n);const o=[],s=[],a=[],r=[],I=new SA,c=new SA,l=new SA;for(let B=0;B<=i;B++)for(let Q=0;Q<=n;Q++){const h=Q/n*g,d=B/i*Math.PI*2;c.x=(A+t*Math.cos(d))*Math.cos(h),c.y=(A+t*Math.cos(d))*Math.sin(h),c.z=t*Math.sin(d),s.push(c.x,c.y,c.z),I.x=A*Math.cos(h),I.y=A*Math.sin(h),l.subVectors(c,I).normalize(),a.push(l.x,l.y,l.z),r.push(Q/n),r.push(B/i)}for(let B=1;B<=i;B++)for(let Q=1;Q<=n;Q++){const h=(n+1)*B+Q-1,d=(n+1)*(B-1)+Q-1,p=(n+1)*(B-1)+Q,y=(n+1)*B+Q;o.push(h,d,y),o.push(d,p,y)}this.setIndex(o),this.setAttribute("position",new $t(s,3)),this.setAttribute("normal",new $t(a,3)),this.setAttribute("uv",new $t(r,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new aT(A.radius,A.tube,A.radialSegments,A.tubularSegments,A.arc)}}class rT extends Ni{constructor(A=1,t=.4,i=64,n=8,g=2,o=3){super(),this.type="TorusKnotGeometry",this.parameters={radius:A,tube:t,tubularSegments:i,radialSegments:n,p:g,q:o},i=Math.floor(i),n=Math.floor(n);const s=[],a=[],r=[],I=[],c=new SA,l=new SA,B=new SA,Q=new SA,h=new SA,d=new SA,p=new SA;for(let m=0;m<=i;++m){const D=m/i*g*Math.PI*2;y(D,g,o,A,B),y(D+.01,g,o,A,Q),d.subVectors(Q,B),p.addVectors(Q,B),h.crossVectors(d,p),p.crossVectors(h,d),h.normalize(),p.normalize();for(let S=0;S<=n;++S){const k=S/n*Math.PI*2,N=-t*Math.cos(k),G=t*Math.sin(k);c.x=B.x+(N*p.x+G*h.x),c.y=B.y+(N*p.y+G*h.y),c.z=B.z+(N*p.z+G*h.z),a.push(c.x,c.y,c.z),l.subVectors(c,B).normalize(),r.push(l.x,l.y,l.z),I.push(m/i),I.push(S/n)}}for(let m=1;m<=i;m++)for(let D=1;D<=n;D++){const S=(n+1)*(m-1)+(D-1),k=(n+1)*m+(D-1),N=(n+1)*m+D,G=(n+1)*(m-1)+D;s.push(S,k,G),s.push(k,N,G)}this.setIndex(s),this.setAttribute("position",new $t(a,3)),this.setAttribute("normal",new $t(r,3)),this.setAttribute("uv",new $t(I,2));function y(m,D,S,k,N){const G=Math.cos(m),M=Math.sin(m),w=S/D*m,b=Math.cos(w);N.x=k*(2+b)*.5*G,N.y=k*(2+b)*M*.5,N.z=k*Math.sin(w)*.5}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new rT(A.radius,A.tube,A.tubularSegments,A.radialSegments,A.p,A.q)}}class IT extends Ni{constructor(A=new ZW(new SA(-1,-1,0),new SA(-1,1,0),new SA(1,1,0)),t=64,i=1,n=8,g=!1){super(),this.type="TubeGeometry",this.parameters={path:A,tubularSegments:t,radius:i,radialSegments:n,closed:g};const o=A.computeFrenetFrames(t,g);this.tangents=o.tangents,this.normals=o.normals,this.binormals=o.binormals;const s=new SA,a=new SA,r=new lt;let I=new SA;const c=[],l=[],B=[],Q=[];h(),this.setIndex(Q),this.setAttribute("position",new $t(c,3)),this.setAttribute("normal",new $t(l,3)),this.setAttribute("uv",new $t(B,2));function h(){for(let m=0;m<t;m++)d(m);d(g===!1?t:0),y(),p()}function d(m){I=A.getPointAt(m/t,I);const D=o.normals[m],S=o.binormals[m];for(let k=0;k<=n;k++){const N=k/n*Math.PI*2,G=Math.sin(N),M=-Math.cos(N);a.x=M*D.x+G*S.x,a.y=M*D.y+G*S.y,a.z=M*D.z+G*S.z,a.normalize(),l.push(a.x,a.y,a.z),s.x=I.x+i*a.x,s.y=I.y+i*a.y,s.z=I.z+i*a.z,c.push(s.x,s.y,s.z)}}function p(){for(let m=1;m<=t;m++)for(let D=1;D<=n;D++){const S=(n+1)*(m-1)+(D-1),k=(n+1)*m+(D-1),N=(n+1)*m+D,G=(n+1)*(m-1)+D;Q.push(S,k,G),Q.push(k,N,G)}}function y(){for(let m=0;m<=t;m++)for(let D=0;D<=n;D++)r.x=m/t,r.y=D/n,B.push(r.x,r.y)}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}toJSON(){const A=super.toJSON();return A.path=this.parameters.path.toJSON(),A}static fromJSON(A){return new IT(new yJ[A.path.type]().fromJSON(A.path),A.tubularSegments,A.radius,A.radialSegments,A.closed)}}class yyA extends Ni{constructor(A=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:A},A!==null){const t=[],i=new Set,n=new SA,g=new SA;if(A.index!==null){const o=A.attributes.position,s=A.index;let a=A.groups;a.length===0&&(a=[{start:0,count:s.count,materialIndex:0}]);for(let r=0,I=a.length;r<I;++r){const c=a[r],l=c.start,B=c.count;for(let Q=l,h=l+B;Q<h;Q+=3)for(let d=0;d<3;d++){const p=s.getX(Q+d),y=s.getX(Q+(d+1)%3);n.fromBufferAttribute(o,p),g.fromBufferAttribute(o,y),dnA(n,g,i)===!0&&(t.push(n.x,n.y,n.z),t.push(g.x,g.y,g.z))}}}else{const o=A.attributes.position;for(let s=0,a=o.count/3;s<a;s++)for(let r=0;r<3;r++){const I=3*s+r,c=3*s+(r+1)%3;n.fromBufferAttribute(o,I),g.fromBufferAttribute(o,c),dnA(n,g,i)===!0&&(t.push(n.x,n.y,n.z),t.push(g.x,g.y,g.z))}}this.setAttribute("position",new $t(t,3))}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}}function dnA(e,A,t){const i=`${e.x},${e.y},${e.z}-${A.x},${A.y},${A.z}`,n=`${A.x},${A.y},${A.z}-${e.x},${e.y},${e.z}`;return t.has(i)===!0||t.has(n)===!0?!1:(t.add(i),t.add(n),!0)}var hnA=Object.freeze({__proto__:null,BoxGeometry:sI,CapsuleGeometry:Xx,CircleGeometry:$x,ConeGeometry:cG,CylinderGeometry:gy,DodecahedronGeometry:AT,EdgesGeometry:lyA,ExtrudeGeometry:tT,IcosahedronGeometry:iT,LatheGeometry:nT,OctahedronGeometry:lG,PlaneGeometry:oB,PolyhedronGeometry:Td,RingGeometry:gT,ShapeGeometry:oT,SphereGeometry:Sf,TetrahedronGeometry:sT,TorusGeometry:aT,TorusKnotGeometry:rT,TubeGeometry:IT,WireframeGeometry:yyA});class DyA extends ho{constructor(A){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Et(0),this.transparent=!0,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.fog=A.fog,this}}class myA extends Cc{constructor(A){super(A),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class xg extends ho{constructor(A){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Et(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Et(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xd,this.normalScale=new lt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ca,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.defines={STANDARD:""},this.color.copy(A.color),this.roughness=A.roughness,this.metalness=A.metalness,this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.emissive.copy(A.emissive),this.emissiveMap=A.emissiveMap,this.emissiveIntensity=A.emissiveIntensity,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.roughnessMap=A.roughnessMap,this.metalnessMap=A.metalnessMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.envMapIntensity=A.envMapIntensity,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.flatShading=A.flatShading,this.fog=A.fog,this}}class To extends xg{constructor(A){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new lt(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Fi(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Et(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new Et(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Et(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(A)}get anisotropy(){return this._anisotropy}set anisotropy(A){this._anisotropy>0!=A>0&&this.version++,this._anisotropy=A}get clearcoat(){return this._clearcoat}set clearcoat(A){this._clearcoat>0!=A>0&&this.version++,this._clearcoat=A}get iridescence(){return this._iridescence}set iridescence(A){this._iridescence>0!=A>0&&this.version++,this._iridescence=A}get dispersion(){return this._dispersion}set dispersion(A){this._dispersion>0!=A>0&&this.version++,this._dispersion=A}get sheen(){return this._sheen}set sheen(A){this._sheen>0!=A>0&&this.version++,this._sheen=A}get transmission(){return this._transmission}set transmission(A){this._transmission>0!=A>0&&this.version++,this._transmission=A}copy(A){return super.copy(A),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=A.anisotropy,this.anisotropyRotation=A.anisotropyRotation,this.anisotropyMap=A.anisotropyMap,this.clearcoat=A.clearcoat,this.clearcoatMap=A.clearcoatMap,this.clearcoatRoughness=A.clearcoatRoughness,this.clearcoatRoughnessMap=A.clearcoatRoughnessMap,this.clearcoatNormalMap=A.clearcoatNormalMap,this.clearcoatNormalScale.copy(A.clearcoatNormalScale),this.dispersion=A.dispersion,this.ior=A.ior,this.iridescence=A.iridescence,this.iridescenceMap=A.iridescenceMap,this.iridescenceIOR=A.iridescenceIOR,this.iridescenceThicknessRange=[...A.iridescenceThicknessRange],this.iridescenceThicknessMap=A.iridescenceThicknessMap,this.sheen=A.sheen,this.sheenColor.copy(A.sheenColor),this.sheenColorMap=A.sheenColorMap,this.sheenRoughness=A.sheenRoughness,this.sheenRoughnessMap=A.sheenRoughnessMap,this.transmission=A.transmission,this.transmissionMap=A.transmissionMap,this.thickness=A.thickness,this.thicknessMap=A.thicknessMap,this.attenuationDistance=A.attenuationDistance,this.attenuationColor.copy(A.attenuationColor),this.specularIntensity=A.specularIntensity,this.specularIntensityMap=A.specularIntensityMap,this.specularColor.copy(A.specularColor),this.specularColorMap=A.specularColorMap,this}}class VW extends ho{constructor(A){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Et(16777215),this.specular=new Et(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Et(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xd,this.normalScale=new lt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ca,this.combine=iG,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.specular.copy(A.specular),this.shininess=A.shininess,this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.emissive.copy(A.emissive),this.emissiveMap=A.emissiveMap,this.emissiveIntensity=A.emissiveIntensity,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.flatShading=A.flatShading,this.fog=A.fog,this}}class SyA extends ho{constructor(A){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Et(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Et(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xd,this.normalScale=new lt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.gradientMap=A.gradientMap,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.emissive.copy(A.emissive),this.emissiveMap=A.emissiveMap,this.emissiveIntensity=A.emissiveIntensity,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.alphaMap=A.alphaMap,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.fog=A.fog,this}}class wyA extends ho{constructor(A){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xd,this.normalScale=new lt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(A)}copy(A){return super.copy(A),this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.flatShading=A.flatShading,this}}class XW extends ho{constructor(A){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Et(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Et(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xd,this.normalScale=new lt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ca,this.combine=iG,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.emissive.copy(A.emissive),this.emissiveMap=A.emissiveMap,this.emissiveIntensity=A.emissiveIntensity,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.flatShading=A.flatShading,this.fog=A.fog,this}}class $W extends ho{constructor(A){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=OfA,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(A)}copy(A){return super.copy(A),this.depthPacking=A.depthPacking,this.map=A.map,this.alphaMap=A.alphaMap,this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this}}class AV extends ho{constructor(A){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(A)}copy(A){return super.copy(A),this.map=A.map,this.alphaMap=A.alphaMap,this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this}}class kyA extends ho{constructor(A){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Et(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xd,this.normalScale=new lt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.defines={MATCAP:""},this.color.copy(A.color),this.matcap=A.matcap,this.map=A.map,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.alphaMap=A.alphaMap,this.flatShading=A.flatShading,this.fog=A.fog,this}}class MyA extends es{constructor(A){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(A)}copy(A){return super.copy(A),this.scale=A.scale,this.dashSize=A.dashSize,this.gapSize=A.gapSize,this}}function Ep(e,A){return!e||e.constructor===A?e:typeof A.BYTES_PER_ELEMENT=="number"?new A(e):Array.prototype.slice.call(e)}function NyA(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function RyA(e){function A(n,g){return e[n]-e[g]}const t=e.length,i=new Array(t);for(let n=0;n!==t;++n)i[n]=n;return i.sort(A),i}function C4(e,A,t){const i=e.length,n=new e.constructor(i);for(let g=0,o=0;o!==i;++g){const s=t[g]*A;for(let a=0;a!==A;++a)n[o++]=e[s+a]}return n}function eV(e,A,t,i){let n=1,g=e[0];for(;g!==void 0&&g[i]===void 0;)g=e[n++];if(g===void 0)return;let o=g[i];if(o!==void 0)if(Array.isArray(o))do o=g[i],o!==void 0&&(A.push(g.time),t.push(...o)),g=e[n++];while(g!==void 0);else if(o.toArray!==void 0)do o=g[i],o!==void 0&&(A.push(g.time),o.toArray(t,t.length)),g=e[n++];while(g!==void 0);else do o=g[i],o!==void 0&&(A.push(g.time),t.push(o)),g=e[n++];while(g!==void 0)}function Pre(e,A,t,i,n=30){const g=e.clone();g.name=A;const o=[];for(let a=0;a<g.tracks.length;++a){const r=g.tracks[a],I=r.getValueSize(),c=[],l=[];for(let B=0;B<r.times.length;++B){const Q=r.times[B]*n;if(!(Q<t||Q>=i)){c.push(r.times[B]);for(let h=0;h<I;++h)l.push(r.values[B*I+h])}}c.length!==0&&(r.times=Ep(c,r.times.constructor),r.values=Ep(l,r.values.constructor),o.push(r))}g.tracks=o;let s=1/0;for(let a=0;a<g.tracks.length;++a)s>g.tracks[a].times[0]&&(s=g.tracks[a].times[0]);for(let a=0;a<g.tracks.length;++a)g.tracks[a].shift(-1*s);return g.resetDuration(),g}function jre(e,A=0,t=e,i=30){i<=0&&(i=30);const n=t.tracks.length,g=A/i;for(let o=0;o<n;++o){const s=t.tracks[o],a=s.ValueTypeName;if(a==="bool"||a==="string")continue;const r=e.tracks.find(function(p){return p.name===s.name&&p.ValueTypeName===a});if(r===void 0)continue;let I=0;const c=s.getValueSize();s.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(I=c/3);let l=0;const B=r.getValueSize();r.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(l=B/3);const Q=s.times.length-1;let h;if(g<=s.times[0]){const p=I,y=c-I;h=s.values.slice(p,y)}else if(g>=s.times[Q]){const p=Q*c+I,y=p+c-I;h=s.values.slice(p,y)}else{const p=s.createInterpolant(),y=I,m=c-I;p.evaluate(g),h=p.resultBuffer.slice(y,m)}a==="quaternion"&&new oo().fromArray(h).normalize().conjugate().toArray(h);const d=r.times.length;for(let p=0;p<d;++p){const y=p*B+l;if(a==="quaternion")oo.multiplyQuaternionsFlat(r.values,y,h,0,r.values,y);else{const m=B-l*2;for(let D=0;D<m;++D)r.values[y+D]-=h[D]}}}return e.blendMode=KW,e}class zre{static convertArray(A,t){return Ep(A,t)}static isTypedArray(A){return NyA(A)}static getKeyframeOrder(A){return RyA(A)}static sortedArray(A,t,i){return C4(A,t,i)}static flattenJSON(A,t,i,n){eV(A,t,i,n)}static subclip(A,t,i,n,g=30){return Pre(A,t,i,n,g)}static makeClipAdditive(A,t=0,i=A,n=30){return jre(A,t,i,n)}}class oy{constructor(A,t,i,n){this.parameterPositions=A,this._cachedIndex=0,this.resultBuffer=n!==void 0?n:new t.constructor(i),this.sampleValues=t,this.valueSize=i,this.settings=null,this.DefaultSettings_={}}evaluate(A){const t=this.parameterPositions;let i=this._cachedIndex,n=t[i],g=t[i-1];A:{e:{let o;t:{i:if(!(A<n)){for(let s=i+2;;){if(n===void 0){if(A<g)break i;return i=t.length,this._cachedIndex=i,this.copySampleValue_(i-1)}if(i===s)break;if(g=n,n=t[++i],A<n)break e}o=t.length;break t}if(!(A>=g)){const s=t[1];A<s&&(i=2,g=s);for(let a=i-2;;){if(g===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===a)break;if(n=g,g=t[--i-1],A>=g)break e}o=i,i=0;break t}break A}for(;i<o;){const s=i+o>>>1;A<t[s]?o=s:i=s+1}if(n=t[i],g=t[i-1],g===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===void 0)return i=t.length,this._cachedIndex=i,this.copySampleValue_(i-1)}this._cachedIndex=i,this.intervalChanged_(i,g,n)}return this.interpolate_(i,g,A,n)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(A){const t=this.resultBuffer,i=this.sampleValues,n=this.valueSize,g=A*n;for(let o=0;o!==n;++o)t[o]=i[g+o];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}class GyA extends oy{constructor(A,t,i,n){super(A,t,i,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:lp,endingEnd:lp}}intervalChanged_(A,t,i){const n=this.parameterPositions;let g=A-2,o=A+1,s=n[g],a=n[o];if(s===void 0)switch(this.getSettings_().endingStart){case Bp:g=A,s=2*t-i;break;case GN:g=n.length-2,s=t+n[g]-n[g+1];break;default:g=A,s=i}if(a===void 0)switch(this.getSettings_().endingEnd){case Bp:o=A,a=2*i-t;break;case GN:o=1,a=i+n[1]-n[0];break;default:o=A-1,a=t}const r=(i-t)*.5,I=this.valueSize;this._weightPrev=r/(t-s),this._weightNext=r/(a-i),this._offsetPrev=g*I,this._offsetNext=o*I}interpolate_(A,t,i,n){const g=this.resultBuffer,o=this.sampleValues,s=this.valueSize,a=A*s,r=a-s,I=this._offsetPrev,c=this._offsetNext,l=this._weightPrev,B=this._weightNext,Q=(i-t)/(n-t),h=Q*Q,d=h*Q,p=-l*d+2*l*h-l*Q,y=(1+l)*d+(-1.5-2*l)*h+(-.5+l)*Q+1,m=(-1-B)*d+(1.5+B)*h+.5*Q,D=B*d-B*h;for(let S=0;S!==s;++S)g[S]=p*o[I+S]+y*o[r+S]+m*o[a+S]+D*o[c+S];return g}}class tV extends oy{constructor(A,t,i,n){super(A,t,i,n)}interpolate_(A,t,i,n){const g=this.resultBuffer,o=this.sampleValues,s=this.valueSize,a=A*s,r=a-s,I=(i-t)/(n-t),c=1-I;for(let l=0;l!==s;++l)g[l]=o[r+l]*c+o[a+l]*I;return g}}class byA extends oy{constructor(A,t,i,n){super(A,t,i,n)}interpolate_(A){return this.copySampleValue_(A-1)}}class Ec{constructor(A,t,i,n){if(A===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+A);this.name=A,this.times=Ep(t,this.TimeBufferType),this.values=Ep(i,this.ValueBufferType),this.setInterpolation(n||this.DefaultInterpolation)}static toJSON(A){const t=A.constructor;let i;if(t.toJSON!==this.toJSON)i=t.toJSON(A);else{i={name:A.name,times:Ep(A.times,Array),values:Ep(A.values,Array)};const n=A.getInterpolation();n!==A.DefaultInterpolation&&(i.interpolation=n)}return i.type=A.ValueTypeName,i}InterpolantFactoryMethodDiscrete(A){return new byA(this.times,this.values,this.getValueSize(),A)}InterpolantFactoryMethodLinear(A){return new tV(this.times,this.values,this.getValueSize(),A)}InterpolantFactoryMethodSmooth(A){return new GyA(this.times,this.values,this.getValueSize(),A)}setInterpolation(A){let t;switch(A){case yf:t=this.InterpolantFactoryMethodDiscrete;break;case dd:t=this.InterpolantFactoryMethodLinear;break;case UK:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){const i="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(A!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(i);return console.warn("THREE.KeyframeTrack:",i),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return yf;case this.InterpolantFactoryMethodLinear:return dd;case this.InterpolantFactoryMethodSmooth:return UK}}getValueSize(){return this.values.length/this.times.length}shift(A){if(A!==0){const t=this.times;for(let i=0,n=t.length;i!==n;++i)t[i]+=A}return this}scale(A){if(A!==1){const t=this.times;for(let i=0,n=t.length;i!==n;++i)t[i]*=A}return this}trim(A,t){const i=this.times,n=i.length;let g=0,o=n-1;for(;g!==n&&i[g]<A;)++g;for(;o!==-1&&i[o]>t;)--o;if(++o,g!==0||o!==n){g>=o&&(o=Math.max(o,1),g=o-1);const s=this.getValueSize();this.times=i.slice(g,o),this.values=this.values.slice(g*s,o*s)}return this}validate(){let A=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),A=!1);const i=this.times,n=this.values,g=i.length;g===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),A=!1);let o=null;for(let s=0;s!==g;s++){const a=i[s];if(typeof a=="number"&&isNaN(a)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,s,a),A=!1;break}if(o!==null&&o>a){console.error("THREE.KeyframeTrack: Out of order keys.",this,s,a,o),A=!1;break}o=a}if(n!==void 0&&NyA(n))for(let s=0,a=n.length;s!==a;++s){const r=n[s];if(isNaN(r)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,s,r),A=!1;break}}return A}optimize(){const A=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),n=this.getInterpolation()===UK,g=A.length-1;let o=1;for(let s=1;s<g;++s){let a=!1;const r=A[s],I=A[s+1];if(r!==I&&(s!==1||r!==A[0]))if(n)a=!0;else{const c=s*i,l=c-i,B=c+i;for(let Q=0;Q!==i;++Q){const h=t[c+Q];if(h!==t[l+Q]||h!==t[B+Q]){a=!0;break}}}if(a){if(s!==o){A[o]=A[s];const c=s*i,l=o*i;for(let B=0;B!==i;++B)t[l+B]=t[c+B]}++o}}if(g>0){A[o]=A[g];for(let s=g*i,a=o*i,r=0;r!==i;++r)t[a+r]=t[s+r];++o}return o!==A.length?(this.times=A.slice(0,o),this.values=t.slice(0,o*i)):(this.times=A,this.values=t),this}clone(){const A=this.times.slice(),t=this.values.slice(),i=this.constructor,n=new i(this.name,A,t);return n.createInterpolant=this.createInterpolant,n}}Ec.prototype.ValueTypeName="";Ec.prototype.TimeBufferType=Float32Array;Ec.prototype.ValueBufferType=Float32Array;Ec.prototype.DefaultInterpolation=dd;class sy extends Ec{constructor(A,t,i){super(A,t,i)}}sy.prototype.ValueTypeName="bool";sy.prototype.ValueBufferType=Array;sy.prototype.DefaultInterpolation=yf;sy.prototype.InterpolantFactoryMethodLinear=void 0;sy.prototype.InterpolantFactoryMethodSmooth=void 0;class iV extends Ec{constructor(A,t,i,n){super(A,t,i,n)}}iV.prototype.ValueTypeName="color";class cQ extends Ec{constructor(A,t,i,n){super(A,t,i,n)}}cQ.prototype.ValueTypeName="number";class UyA extends oy{constructor(A,t,i,n){super(A,t,i,n)}interpolate_(A,t,i,n){const g=this.resultBuffer,o=this.sampleValues,s=this.valueSize,a=(i-t)/(n-t);let r=A*s;for(let I=r+s;r!==I;r+=4)oo.slerpFlat(g,0,o,r-s,o,r,a);return g}}class DB extends Ec{constructor(A,t,i,n){super(A,t,i,n)}InterpolantFactoryMethodLinear(A){return new UyA(this.times,this.values,this.getValueSize(),A)}}DB.prototype.ValueTypeName="quaternion";DB.prototype.InterpolantFactoryMethodSmooth=void 0;class ay extends Ec{constructor(A,t,i){super(A,t,i)}}ay.prototype.ValueTypeName="string";ay.prototype.ValueBufferType=Array;ay.prototype.DefaultInterpolation=yf;ay.prototype.InterpolantFactoryMethodLinear=void 0;ay.prototype.InterpolantFactoryMethodSmooth=void 0;class mB extends Ec{constructor(A,t,i,n){super(A,t,i,n)}}mB.prototype.ValueTypeName="vector";class fd{constructor(A="",t=-1,i=[],n=qx){this.name=A,this.tracks=i,this.duration=t,this.blendMode=n,this.uuid=$I(),this.userData={},this.duration<0&&this.resetDuration()}static parse(A){const t=[],i=A.tracks,n=1/(A.fps||1);for(let o=0,s=i.length;o!==s;++o)t.push(Wre(i[o]).scale(n));const g=new this(A.name,A.duration,t,A.blendMode);return g.uuid=A.uuid,g.userData=JSON.parse(A.userData||"{}"),g}static toJSON(A){const t=[],i=A.tracks,n={name:A.name,duration:A.duration,tracks:t,uuid:A.uuid,blendMode:A.blendMode,userData:JSON.stringify(A.userData)};for(let g=0,o=i.length;g!==o;++g)t.push(Ec.toJSON(i[g]));return n}static CreateFromMorphTargetSequence(A,t,i,n){const g=t.length,o=[];for(let s=0;s<g;s++){let a=[],r=[];a.push((s+g-1)%g,s,(s+1)%g),r.push(0,1,0);const I=RyA(a);a=C4(a,1,I),r=C4(r,1,I),!n&&a[0]===0&&(a.push(g),r.push(r[0])),o.push(new cQ(".morphTargetInfluences["+t[s].name+"]",a,r).scale(1/i))}return new this(A,-1,o)}static findByName(A,t){let i=A;if(!Array.isArray(A)){const n=A;i=n.geometry&&n.geometry.animations||n.animations}for(let n=0;n<i.length;n++)if(i[n].name===t)return i[n];return null}static CreateClipsFromMorphTargetSequences(A,t,i){const n={},g=/^([\w-]*?)([\d]+)$/;for(let s=0,a=A.length;s<a;s++){const r=A[s],I=r.name.match(g);if(I&&I.length>1){const c=I[1];let l=n[c];l||(n[c]=l=[]),l.push(r)}}const o=[];for(const s in n)o.push(this.CreateFromMorphTargetSequence(s,n[s],t,i));return o}static parseAnimation(A,t){if(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!A)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(c,l,B,Q,h){if(B.length!==0){const d=[],p=[];eV(B,d,p,Q),d.length!==0&&h.push(new c(l,d,p))}},n=[],g=A.name||"default",o=A.fps||30,s=A.blendMode;let a=A.length||-1;const r=A.hierarchy||[];for(let c=0;c<r.length;c++){const l=r[c].keys;if(!(!l||l.length===0))if(l[0].morphTargets){const B={};let Q;for(Q=0;Q<l.length;Q++)if(l[Q].morphTargets)for(let h=0;h<l[Q].morphTargets.length;h++)B[l[Q].morphTargets[h]]=-1;for(const h in B){const d=[],p=[];for(let y=0;y!==l[Q].morphTargets.length;++y){const m=l[Q];d.push(m.time),p.push(m.morphTarget===h?1:0)}n.push(new cQ(".morphTargetInfluence["+h+"]",d,p))}a=B.length*o}else{const B=".bones["+t[c].name+"]";i(mB,B+".position",l,"pos",n),i(DB,B+".quaternion",l,"rot",n),i(mB,B+".scale",l,"scl",n)}}return n.length===0?null:new this(g,a,n,s)}resetDuration(){const A=this.tracks;let t=0;for(let i=0,n=A.length;i!==n;++i){const g=this.tracks[i];t=Math.max(t,g.times[g.times.length-1])}return this.duration=t,this}trim(){for(let A=0;A<this.tracks.length;A++)this.tracks[A].trim(0,this.duration);return this}validate(){let A=!0;for(let t=0;t<this.tracks.length;t++)A=A&&this.tracks[t].validate();return A}optimize(){for(let A=0;A<this.tracks.length;A++)this.tracks[A].optimize();return this}clone(){const A=[];for(let i=0;i<this.tracks.length;i++)A.push(this.tracks[i].clone());const t=new this.constructor(this.name,this.duration,A,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}}function Zre(e){switch(e.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return cQ;case"vector":case"vector2":case"vector3":case"vector4":return mB;case"color":return iV;case"quaternion":return DB;case"bool":case"boolean":return sy;case"string":return ay}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}function Wre(e){if(e.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const A=Zre(e.type);if(e.times===void 0){const t=[],i=[];eV(e.keys,t,i,"value"),e.times=t,e.values=i}return A.parse!==void 0?A.parse(e):new A(e.name,e.times,e.values,e.interpolation)}const sB={enabled:!1,files:{},add:function(e,A){this.enabled!==!1&&(this.files[e]=A)},get:function(e){if(this.enabled!==!1)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class nV{constructor(A,t,i){const n=this;let g=!1,o=0,s=0,a;const r=[];this.onStart=void 0,this.onLoad=A,this.onProgress=t,this.onError=i,this.abortController=new AbortController,this.itemStart=function(I){s++,g===!1&&n.onStart!==void 0&&n.onStart(I,o,s),g=!0},this.itemEnd=function(I){o++,n.onProgress!==void 0&&n.onProgress(I,o,s),o===s&&(g=!1,n.onLoad!==void 0&&n.onLoad())},this.itemError=function(I){n.onError!==void 0&&n.onError(I)},this.resolveURL=function(I){return a?a(I):I},this.setURLModifier=function(I){return a=I,this},this.addHandler=function(I,c){return r.push(I,c),this},this.removeHandler=function(I){const c=r.indexOf(I);return c!==-1&&r.splice(c,2),this},this.getHandler=function(I){for(let c=0,l=r.length;c<l;c+=2){const B=r[c],Q=r[c+1];if(B.global&&(B.lastIndex=0),B.test(I))return Q}return null},this.abort=function(){return this.abortController.abort(),this.abortController=new AbortController,this}}}const vyA=new nV;class la{constructor(A){this.manager=A!==void 0?A:vyA,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(A,t){const i=this;return new Promise(function(n,g){i.load(A,n,t,g)})}parse(){}setCrossOrigin(A){return this.crossOrigin=A,this}setWithCredentials(A){return this.withCredentials=A,this}setPath(A){return this.path=A,this}setResourcePath(A){return this.resourcePath=A,this}setRequestHeader(A){return this.requestHeader=A,this}abort(){return this}}la.DEFAULT_MATERIAL_NAME="__DEFAULT";const iE={};class Vre extends Error{constructor(A,t){super(A),this.response=t}}class or extends la{constructor(A){super(A),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(A,t,i,n){A===void 0&&(A=""),this.path!==void 0&&(A=this.path+A),A=this.manager.resolveURL(A);const g=sB.get(`file:${A}`);if(g!==void 0)return this.manager.itemStart(A),setTimeout(()=>{t&&t(g),this.manager.itemEnd(A)},0),g;if(iE[A]!==void 0){iE[A].push({onLoad:t,onProgress:i,onError:n});return}iE[A]=[],iE[A].push({onLoad:t,onProgress:i,onError:n});const o=new Request(A,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),s=this.mimeType,a=this.responseType;fetch(o).then(r=>{if(r.status===200||r.status===0){if(r.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||r.body===void 0||r.body.getReader===void 0)return r;const I=iE[A],c=r.body.getReader(),l=r.headers.get("X-File-Size")||r.headers.get("Content-Length"),B=l?parseInt(l):0,Q=B!==0;let h=0;const d=new ReadableStream({start(p){y();function y(){c.read().then(({done:m,value:D})=>{if(m)p.close();else{h+=D.byteLength;const S=new ProgressEvent("progress",{lengthComputable:Q,loaded:h,total:B});for(let k=0,N=I.length;k<N;k++){const G=I[k];G.onProgress&&G.onProgress(S)}p.enqueue(D),y()}},m=>{p.error(m)})}}});return new Response(d)}else throw new Vre(`fetch for "${r.url}" responded with ${r.status}: ${r.statusText}`,r)}).then(r=>{switch(a){case"arraybuffer":return r.arrayBuffer();case"blob":return r.blob();case"document":return r.text().then(I=>new DOMParser().parseFromString(I,s));case"json":return r.json();default:if(s==="")return r.text();{const c=/charset="?([^;"\s]*)"?/i.exec(s),l=c&&c[1]?c[1].toLowerCase():void 0,B=new TextDecoder(l);return r.arrayBuffer().then(Q=>B.decode(Q))}}}).then(r=>{sB.add(`file:${A}`,r);const I=iE[A];delete iE[A];for(let c=0,l=I.length;c<l;c++){const B=I[c];B.onLoad&&B.onLoad(r)}}).catch(r=>{const I=iE[A];if(I===void 0)throw this.manager.itemError(A),r;delete iE[A];for(let c=0,l=I.length;c<l;c++){const B=I[c];B.onError&&B.onError(r)}this.manager.itemError(A)}).finally(()=>{this.manager.itemEnd(A)}),this.manager.itemStart(A)}setResponseType(A){return this.responseType=A,this}setMimeType(A){return this.mimeType=A,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class Xre extends la{constructor(A){super(A)}load(A,t,i,n){const g=this,o=new or(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(A,function(s){try{t(g.parse(JSON.parse(s)))}catch(a){n?n(a):console.error(a),g.manager.itemError(A)}},i,n)}parse(A){const t=[];for(let i=0;i<A.length;i++){const n=fd.parse(A[i]);t.push(n)}return t}}class $re extends la{constructor(A){super(A)}load(A,t,i,n){const g=this,o=[],s=new Wx,a=new or(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(g.withCredentials);let r=0;function I(c){a.load(A[c],function(l){const B=g.parse(l,!0);o[c]={width:B.width,height:B.height,format:B.format,mipmaps:B.mipmaps},r+=1,r===6&&(B.mipmapCount===1&&(s.minFilter=qg),s.image=o,s.format=B.format,s.needsUpdate=!0,t&&t(s))},i,n)}if(Array.isArray(A))for(let c=0,l=A.length;c<l;++c)I(c);else a.load(A,function(c){const l=g.parse(c,!0);if(l.isCubemap){const B=l.mipmaps.length/l.mipmapCount;for(let Q=0;Q<B;Q++){o[Q]={mipmaps:[]};for(let h=0;h<l.mipmapCount;h++)o[Q].mipmaps.push(l.mipmaps[Q*l.mipmapCount+h]),o[Q].format=l.format,o[Q].width=l.width,o[Q].height=l.height}s.image=o}else s.image.width=l.width,s.image.height=l.height,s.mipmaps=l.mipmaps;l.mipmapCount===1&&(s.minFilter=qg),s.format=l.format,s.needsUpdate=!0,t&&t(s)},i,n);return s}}const ED=new WeakMap;class xN extends la{constructor(A){super(A)}load(A,t,i,n){this.path!==void 0&&(A=this.path+A),A=this.manager.resolveURL(A);const g=this,o=sB.get(`image:${A}`);if(o!==void 0){if(o.complete===!0)g.manager.itemStart(A),setTimeout(function(){t&&t(o),g.manager.itemEnd(A)},0);else{let c=ED.get(o);c===void 0&&(c=[],ED.set(o,c)),c.push({onLoad:t,onError:n})}return o}const s=vN("img");function a(){I(),t&&t(this);const c=ED.get(this)||[];for(let l=0;l<c.length;l++){const B=c[l];B.onLoad&&B.onLoad(this)}ED.delete(this),g.manager.itemEnd(A)}function r(c){I(),n&&n(c),sB.remove(`image:${A}`);const l=ED.get(this)||[];for(let B=0;B<l.length;B++){const Q=l[B];Q.onError&&Q.onError(c)}ED.delete(this),g.manager.itemError(A),g.manager.itemEnd(A)}function I(){s.removeEventListener("load",a,!1),s.removeEventListener("error",r,!1)}return s.addEventListener("load",a,!1),s.addEventListener("error",r,!1),A.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(s.crossOrigin=this.crossOrigin),sB.add(`image:${A}`,s),g.manager.itemStart(A),s.src=A,s}}class AIe extends la{constructor(A){super(A)}load(A,t,i,n){const g=new sG;g.colorSpace=rn;const o=new xN(this.manager);o.setCrossOrigin(this.crossOrigin),o.setPath(this.path);let s=0;function a(r){o.load(A[r],function(I){g.images[r]=I,s++,s===6&&(g.needsUpdate=!0,t&&t(g))},void 0,n)}for(let r=0;r<A.length;++r)a(r);return g}}class eIe extends la{constructor(A){super(A)}load(A,t,i,n){const g=this,o=new uB,s=new or(this.manager);return s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setPath(this.path),s.setWithCredentials(g.withCredentials),s.load(A,function(a){let r;try{r=g.parse(a)}catch(I){if(n!==void 0)n(I);else{console.error(I);return}}r.image!==void 0?o.image=r.image:r.data!==void 0&&(o.image.width=r.width,o.image.height=r.height,o.image.data=r.data),o.wrapS=r.wrapS!==void 0?r.wrapS:oI,o.wrapT=r.wrapT!==void 0?r.wrapT:oI,o.magFilter=r.magFilter!==void 0?r.magFilter:qg,o.minFilter=r.minFilter!==void 0?r.minFilter:qg,o.anisotropy=r.anisotropy!==void 0?r.anisotropy:1,r.colorSpace!==void 0&&(o.colorSpace=r.colorSpace),r.flipY!==void 0&&(o.flipY=r.flipY),r.format!==void 0&&(o.format=r.format),r.type!==void 0&&(o.type=r.type),r.mipmaps!==void 0&&(o.mipmaps=r.mipmaps,o.minFilter=Gr),r.mipmapCount===1&&(o.minFilter=qg),r.generateMipmaps!==void 0&&(o.generateMipmaps=r.generateMipmaps),o.needsUpdate=!0,t&&t(o,r)},i,n),o}}class qd extends la{constructor(A){super(A)}load(A,t,i,n){const g=new Kg,o=new xN(this.manager);return o.setCrossOrigin(this.crossOrigin),o.setPath(this.path),o.load(A,function(s){g.image=s,g.needsUpdate=!0,t!==void 0&&t(g)},i,n),g}}class Yd extends Bn{constructor(A,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Et(A),this.intensity=t}dispose(){}copy(A,t){return super.copy(A,t),this.color.copy(A.color),this.intensity=A.intensity,this}toJSON(A){const t=super.toJSON(A);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}}class gV extends Yd{constructor(A,t,i){super(A,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Bn.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Et(t)}copy(A,t){return super.copy(A,t),this.groundColor.copy(A.groundColor),this}}const GH=new ni,pnA=new SA,fnA=new SA;class oV{constructor(A){this.camera=A,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new lt(512,512),this.mapType=Ic,this.map=null,this.mapPass=null,this.matrix=new ni,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Lw,this._frameExtents=new lt(1,1),this._viewportCount=1,this._viewports=[new ig(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(A){const t=this.camera,i=this.matrix;pnA.setFromMatrixPosition(A.matrixWorld),t.position.copy(pnA),fnA.setFromMatrixPosition(A.target.matrixWorld),t.lookAt(fnA),t.updateMatrixWorld(),GH.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(GH,t.coordinateSystem,t.reversedDepth),t.reversedDepth?i.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(GH)}getViewport(A){return this._viewports[A]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(A){return this.camera=A.camera.clone(),this.intensity=A.intensity,this.bias=A.bias,this.radius=A.radius,this.autoUpdate=A.autoUpdate,this.needsUpdate=A.needsUpdate,this.normalBias=A.normalBias,this.blurSamples=A.blurSamples,this.mapSize.copy(A.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const A={};return this.intensity!==1&&(A.intensity=this.intensity),this.bias!==0&&(A.bias=this.bias),this.normalBias!==0&&(A.normalBias=this.normalBias),this.radius!==1&&(A.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(A.mapSize=this.mapSize.toArray()),A.camera=this.camera.toJSON(!1).object,delete A.camera.matrix,A}}class tIe extends oV{constructor(){super(new Wo(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(A){const t=this.camera,i=OS*2*A.angle*this.focus,n=this.mapSize.width/this.mapSize.height*this.aspect,g=A.distance||t.far;(i!==t.fov||n!==t.aspect||g!==t.far)&&(t.fov=i,t.aspect=n,t.far=g,t.updateProjectionMatrix()),super.updateMatrices(A)}copy(A){return super.copy(A),this.focus=A.focus,this}}class CT extends Yd{constructor(A,t,i=0,n=Math.PI/3,g=0,o=2){super(A,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Bn.DEFAULT_UP),this.updateMatrix(),this.target=new Bn,this.distance=i,this.angle=n,this.penumbra=g,this.decay=o,this.map=null,this.shadow=new tIe}get power(){return this.intensity*Math.PI}set power(A){this.intensity=A/Math.PI}dispose(){this.shadow.dispose()}copy(A,t){return super.copy(A,t),this.distance=A.distance,this.angle=A.angle,this.penumbra=A.penumbra,this.decay=A.decay,this.target=A.target.clone(),this.shadow=A.shadow.clone(),this}}const ynA=new ni,Z0=new SA,bH=new SA;class iIe extends oV{constructor(){super(new Wo(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new lt(4,2),this._viewportCount=6,this._viewports=[new ig(2,1,1,1),new ig(0,1,1,1),new ig(3,1,1,1),new ig(1,1,1,1),new ig(3,0,1,1),new ig(1,0,1,1)],this._cubeDirections=[new SA(1,0,0),new SA(-1,0,0),new SA(0,0,1),new SA(0,0,-1),new SA(0,1,0),new SA(0,-1,0)],this._cubeUps=[new SA(0,1,0),new SA(0,1,0),new SA(0,1,0),new SA(0,1,0),new SA(0,0,1),new SA(0,0,-1)]}updateMatrices(A,t=0){const i=this.camera,n=this.matrix,g=A.distance||i.far;g!==i.far&&(i.far=g,i.updateProjectionMatrix()),Z0.setFromMatrixPosition(A.matrixWorld),i.position.copy(Z0),bH.copy(i.position),bH.add(this._cubeDirections[t]),i.up.copy(this._cubeUps[t]),i.lookAt(bH),i.updateMatrixWorld(),n.makeTranslation(-Z0.x,-Z0.y,-Z0.z),ynA.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),this._frustum.setFromProjectionMatrix(ynA,i.coordinateSystem,i.reversedDepth)}}class BG extends Yd{constructor(A,t,i=0,n=2){super(A,t),this.isPointLight=!0,this.type="PointLight",this.distance=i,this.decay=n,this.shadow=new iIe}get power(){return this.intensity*4*Math.PI}set power(A){this.intensity=A/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(A,t){return super.copy(A,t),this.distance=A.distance,this.decay=A.decay,this.shadow=A.shadow.clone(),this}}let Hd=class extends Ox{constructor(A=-1,t=1,i=1,n=-1,g=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=A,this.right=t,this.top=i,this.bottom=n,this.near=g,this.far=o,this.updateProjectionMatrix()}copy(A,t){return super.copy(A,t),this.left=A.left,this.right=A.right,this.top=A.top,this.bottom=A.bottom,this.near=A.near,this.far=A.far,this.zoom=A.zoom,this.view=A.view===null?null:Object.assign({},A.view),this}setViewOffset(A,t,i,n,g,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=A,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=g,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const A=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,n=(this.top+this.bottom)/2;let g=i-A,o=i+A,s=n+t,a=n-t;if(this.view!==null&&this.view.enabled){const r=(this.right-this.left)/this.view.fullWidth/this.zoom,I=(this.top-this.bottom)/this.view.fullHeight/this.zoom;g+=r*this.view.offsetX,o=g+r*this.view.width,s-=I*this.view.offsetY,a=s-I*this.view.height}this.projectionMatrix.makeOrthographic(g,o,s,a,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(A){const t=super.toJSON(A);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}};class nIe extends oV{constructor(){super(new Hd(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class zp extends Yd{constructor(A,t){super(A,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Bn.DEFAULT_UP),this.updateMatrix(),this.target=new Bn,this.shadow=new nIe}dispose(){this.shadow.dispose()}copy(A){return super.copy(A),this.target=A.target.clone(),this.shadow=A.shadow.clone(),this}}class sV extends Yd{constructor(A,t){super(A,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class KyA extends Yd{constructor(A,t,i=10,n=10){super(A,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=i,this.height=n}get power(){return this.intensity*this.width*this.height*Math.PI}set power(A){this.intensity=A/(this.width*this.height*Math.PI)}copy(A){return super.copy(A),this.width=A.width,this.height=A.height,this}toJSON(A){const t=super.toJSON(A);return t.object.width=this.width,t.object.height=this.height,t}}class FyA{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let A=0;A<9;A++)this.coefficients.push(new SA)}set(A){for(let t=0;t<9;t++)this.coefficients[t].copy(A[t]);return this}zero(){for(let A=0;A<9;A++)this.coefficients[A].set(0,0,0);return this}getAt(A,t){const i=A.x,n=A.y,g=A.z,o=this.coefficients;return t.copy(o[0]).multiplyScalar(.282095),t.addScaledVector(o[1],.488603*n),t.addScaledVector(o[2],.488603*g),t.addScaledVector(o[3],.488603*i),t.addScaledVector(o[4],1.092548*(i*n)),t.addScaledVector(o[5],1.092548*(n*g)),t.addScaledVector(o[6],.315392*(3*g*g-1)),t.addScaledVector(o[7],1.092548*(i*g)),t.addScaledVector(o[8],.546274*(i*i-n*n)),t}getIrradianceAt(A,t){const i=A.x,n=A.y,g=A.z,o=this.coefficients;return t.copy(o[0]).multiplyScalar(.886227),t.addScaledVector(o[1],2*.511664*n),t.addScaledVector(o[2],2*.511664*g),t.addScaledVector(o[3],2*.511664*i),t.addScaledVector(o[4],2*.429043*i*n),t.addScaledVector(o[5],2*.429043*n*g),t.addScaledVector(o[6],.743125*g*g-.247708),t.addScaledVector(o[7],2*.429043*i*g),t.addScaledVector(o[8],.429043*(i*i-n*n)),t}add(A){for(let t=0;t<9;t++)this.coefficients[t].add(A.coefficients[t]);return this}addScaledSH(A,t){for(let i=0;i<9;i++)this.coefficients[i].addScaledVector(A.coefficients[i],t);return this}scale(A){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(A);return this}lerp(A,t){for(let i=0;i<9;i++)this.coefficients[i].lerp(A.coefficients[i],t);return this}equals(A){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(A.coefficients[t]))return!1;return!0}copy(A){return this.set(A.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(A,t=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].fromArray(A,t+n*3);return this}toArray(A=[],t=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].toArray(A,t+n*3);return A}static getBasisAt(A,t){const i=A.x,n=A.y,g=A.z;t[0]=.282095,t[1]=.488603*n,t[2]=.488603*g,t[3]=.488603*i,t[4]=1.092548*i*n,t[5]=1.092548*n*g,t[6]=.315392*(3*g*g-1),t[7]=1.092548*i*g,t[8]=.546274*(i*i-n*n)}}class _yA extends Yd{constructor(A=new FyA,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=A}copy(A){return super.copy(A),this.sh.copy(A.sh),this}fromJSON(A){return this.intensity=A.intensity,this.sh.fromArray(A.sh),this}toJSON(A){const t=super.toJSON(A);return t.object.sh=this.sh.toArray(),t}}class cT extends la{constructor(A){super(A),this.textures={}}load(A,t,i,n){const g=this,o=new or(g.manager);o.setPath(g.path),o.setRequestHeader(g.requestHeader),o.setWithCredentials(g.withCredentials),o.load(A,function(s){try{t(g.parse(JSON.parse(s)))}catch(a){n?n(a):console.error(a),g.manager.itemError(A)}},i,n)}parse(A){const t=this.textures;function i(g){return t[g]===void 0&&console.warn("THREE.MaterialLoader: Undefined texture",g),t[g]}const n=this.createMaterialFromType(A.type);if(A.uuid!==void 0&&(n.uuid=A.uuid),A.name!==void 0&&(n.name=A.name),A.color!==void 0&&n.color!==void 0&&n.color.setHex(A.color),A.roughness!==void 0&&(n.roughness=A.roughness),A.metalness!==void 0&&(n.metalness=A.metalness),A.sheen!==void 0&&(n.sheen=A.sheen),A.sheenColor!==void 0&&(n.sheenColor=new Et().setHex(A.sheenColor)),A.sheenRoughness!==void 0&&(n.sheenRoughness=A.sheenRoughness),A.emissive!==void 0&&n.emissive!==void 0&&n.emissive.setHex(A.emissive),A.specular!==void 0&&n.specular!==void 0&&n.specular.setHex(A.specular),A.specularIntensity!==void 0&&(n.specularIntensity=A.specularIntensity),A.specularColor!==void 0&&n.specularColor!==void 0&&n.specularColor.setHex(A.specularColor),A.shininess!==void 0&&(n.shininess=A.shininess),A.clearcoat!==void 0&&(n.clearcoat=A.clearcoat),A.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=A.clearcoatRoughness),A.dispersion!==void 0&&(n.dispersion=A.dispersion),A.iridescence!==void 0&&(n.iridescence=A.iridescence),A.iridescenceIOR!==void 0&&(n.iridescenceIOR=A.iridescenceIOR),A.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=A.iridescenceThicknessRange),A.transmission!==void 0&&(n.transmission=A.transmission),A.thickness!==void 0&&(n.thickness=A.thickness),A.attenuationDistance!==void 0&&(n.attenuationDistance=A.attenuationDistance),A.attenuationColor!==void 0&&n.attenuationColor!==void 0&&n.attenuationColor.setHex(A.attenuationColor),A.anisotropy!==void 0&&(n.anisotropy=A.anisotropy),A.anisotropyRotation!==void 0&&(n.anisotropyRotation=A.anisotropyRotation),A.fog!==void 0&&(n.fog=A.fog),A.flatShading!==void 0&&(n.flatShading=A.flatShading),A.blending!==void 0&&(n.blending=A.blending),A.combine!==void 0&&(n.combine=A.combine),A.side!==void 0&&(n.side=A.side),A.shadowSide!==void 0&&(n.shadowSide=A.shadowSide),A.opacity!==void 0&&(n.opacity=A.opacity),A.transparent!==void 0&&(n.transparent=A.transparent),A.alphaTest!==void 0&&(n.alphaTest=A.alphaTest),A.alphaHash!==void 0&&(n.alphaHash=A.alphaHash),A.depthFunc!==void 0&&(n.depthFunc=A.depthFunc),A.depthTest!==void 0&&(n.depthTest=A.depthTest),A.depthWrite!==void 0&&(n.depthWrite=A.depthWrite),A.colorWrite!==void 0&&(n.colorWrite=A.colorWrite),A.blendSrc!==void 0&&(n.blendSrc=A.blendSrc),A.blendDst!==void 0&&(n.blendDst=A.blendDst),A.blendEquation!==void 0&&(n.blendEquation=A.blendEquation),A.blendSrcAlpha!==void 0&&(n.blendSrcAlpha=A.blendSrcAlpha),A.blendDstAlpha!==void 0&&(n.blendDstAlpha=A.blendDstAlpha),A.blendEquationAlpha!==void 0&&(n.blendEquationAlpha=A.blendEquationAlpha),A.blendColor!==void 0&&n.blendColor!==void 0&&n.blendColor.setHex(A.blendColor),A.blendAlpha!==void 0&&(n.blendAlpha=A.blendAlpha),A.stencilWriteMask!==void 0&&(n.stencilWriteMask=A.stencilWriteMask),A.stencilFunc!==void 0&&(n.stencilFunc=A.stencilFunc),A.stencilRef!==void 0&&(n.stencilRef=A.stencilRef),A.stencilFuncMask!==void 0&&(n.stencilFuncMask=A.stencilFuncMask),A.stencilFail!==void 0&&(n.stencilFail=A.stencilFail),A.stencilZFail!==void 0&&(n.stencilZFail=A.stencilZFail),A.stencilZPass!==void 0&&(n.stencilZPass=A.stencilZPass),A.stencilWrite!==void 0&&(n.stencilWrite=A.stencilWrite),A.wireframe!==void 0&&(n.wireframe=A.wireframe),A.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=A.wireframeLinewidth),A.wireframeLinecap!==void 0&&(n.wireframeLinecap=A.wireframeLinecap),A.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=A.wireframeLinejoin),A.rotation!==void 0&&(n.rotation=A.rotation),A.linewidth!==void 0&&(n.linewidth=A.linewidth),A.dashSize!==void 0&&(n.dashSize=A.dashSize),A.gapSize!==void 0&&(n.gapSize=A.gapSize),A.scale!==void 0&&(n.scale=A.scale),A.polygonOffset!==void 0&&(n.polygonOffset=A.polygonOffset),A.polygonOffsetFactor!==void 0&&(n.polygonOffsetFactor=A.polygonOffsetFactor),A.polygonOffsetUnits!==void 0&&(n.polygonOffsetUnits=A.polygonOffsetUnits),A.dithering!==void 0&&(n.dithering=A.dithering),A.alphaToCoverage!==void 0&&(n.alphaToCoverage=A.alphaToCoverage),A.premultipliedAlpha!==void 0&&(n.premultipliedAlpha=A.premultipliedAlpha),A.forceSinglePass!==void 0&&(n.forceSinglePass=A.forceSinglePass),A.visible!==void 0&&(n.visible=A.visible),A.toneMapped!==void 0&&(n.toneMapped=A.toneMapped),A.userData!==void 0&&(n.userData=A.userData),A.vertexColors!==void 0&&(typeof A.vertexColors=="number"?n.vertexColors=A.vertexColors>0:n.vertexColors=A.vertexColors),A.uniforms!==void 0)for(const g in A.uniforms){const o=A.uniforms[g];switch(n.uniforms[g]={},o.type){case"t":n.uniforms[g].value=i(o.value);break;case"c":n.uniforms[g].value=new Et().setHex(o.value);break;case"v2":n.uniforms[g].value=new lt().fromArray(o.value);break;case"v3":n.uniforms[g].value=new SA().fromArray(o.value);break;case"v4":n.uniforms[g].value=new ig().fromArray(o.value);break;case"m3":n.uniforms[g].value=new An().fromArray(o.value);break;case"m4":n.uniforms[g].value=new ni().fromArray(o.value);break;default:n.uniforms[g].value=o.value}}if(A.defines!==void 0&&(n.defines=A.defines),A.vertexShader!==void 0&&(n.vertexShader=A.vertexShader),A.fragmentShader!==void 0&&(n.fragmentShader=A.fragmentShader),A.glslVersion!==void 0&&(n.glslVersion=A.glslVersion),A.extensions!==void 0)for(const g in A.extensions)n.extensions[g]=A.extensions[g];if(A.lights!==void 0&&(n.lights=A.lights),A.clipping!==void 0&&(n.clipping=A.clipping),A.size!==void 0&&(n.size=A.size),A.sizeAttenuation!==void 0&&(n.sizeAttenuation=A.sizeAttenuation),A.map!==void 0&&(n.map=i(A.map)),A.matcap!==void 0&&(n.matcap=i(A.matcap)),A.alphaMap!==void 0&&(n.alphaMap=i(A.alphaMap)),A.bumpMap!==void 0&&(n.bumpMap=i(A.bumpMap)),A.bumpScale!==void 0&&(n.bumpScale=A.bumpScale),A.normalMap!==void 0&&(n.normalMap=i(A.normalMap)),A.normalMapType!==void 0&&(n.normalMapType=A.normalMapType),A.normalScale!==void 0){let g=A.normalScale;Array.isArray(g)===!1&&(g=[g,g]),n.normalScale=new lt().fromArray(g)}return A.displacementMap!==void 0&&(n.displacementMap=i(A.displacementMap)),A.displacementScale!==void 0&&(n.displacementScale=A.displacementScale),A.displacementBias!==void 0&&(n.displacementBias=A.displacementBias),A.roughnessMap!==void 0&&(n.roughnessMap=i(A.roughnessMap)),A.metalnessMap!==void 0&&(n.metalnessMap=i(A.metalnessMap)),A.emissiveMap!==void 0&&(n.emissiveMap=i(A.emissiveMap)),A.emissiveIntensity!==void 0&&(n.emissiveIntensity=A.emissiveIntensity),A.specularMap!==void 0&&(n.specularMap=i(A.specularMap)),A.specularIntensityMap!==void 0&&(n.specularIntensityMap=i(A.specularIntensityMap)),A.specularColorMap!==void 0&&(n.specularColorMap=i(A.specularColorMap)),A.envMap!==void 0&&(n.envMap=i(A.envMap)),A.envMapRotation!==void 0&&n.envMapRotation.fromArray(A.envMapRotation),A.envMapIntensity!==void 0&&(n.envMapIntensity=A.envMapIntensity),A.reflectivity!==void 0&&(n.reflectivity=A.reflectivity),A.refractionRatio!==void 0&&(n.refractionRatio=A.refractionRatio),A.lightMap!==void 0&&(n.lightMap=i(A.lightMap)),A.lightMapIntensity!==void 0&&(n.lightMapIntensity=A.lightMapIntensity),A.aoMap!==void 0&&(n.aoMap=i(A.aoMap)),A.aoMapIntensity!==void 0&&(n.aoMapIntensity=A.aoMapIntensity),A.gradientMap!==void 0&&(n.gradientMap=i(A.gradientMap)),A.clearcoatMap!==void 0&&(n.clearcoatMap=i(A.clearcoatMap)),A.clearcoatRoughnessMap!==void 0&&(n.clearcoatRoughnessMap=i(A.clearcoatRoughnessMap)),A.clearcoatNormalMap!==void 0&&(n.clearcoatNormalMap=i(A.clearcoatNormalMap)),A.clearcoatNormalScale!==void 0&&(n.clearcoatNormalScale=new lt().fromArray(A.clearcoatNormalScale)),A.iridescenceMap!==void 0&&(n.iridescenceMap=i(A.iridescenceMap)),A.iridescenceThicknessMap!==void 0&&(n.iridescenceThicknessMap=i(A.iridescenceThicknessMap)),A.transmissionMap!==void 0&&(n.transmissionMap=i(A.transmissionMap)),A.thicknessMap!==void 0&&(n.thicknessMap=i(A.thicknessMap)),A.anisotropyMap!==void 0&&(n.anisotropyMap=i(A.anisotropyMap)),A.sheenColorMap!==void 0&&(n.sheenColorMap=i(A.sheenColorMap)),A.sheenRoughnessMap!==void 0&&(n.sheenRoughnessMap=i(A.sheenRoughnessMap)),n}setTextures(A){return this.textures=A,this}createMaterialFromType(A){return cT.createMaterialFromType(A)}static createMaterialFromType(A){const t={ShadowMaterial:DyA,SpriteMaterial:FN,RawShaderMaterial:myA,ShaderMaterial:Cc,PointsMaterial:NE,MeshPhysicalMaterial:To,MeshStandardMaterial:xg,MeshPhongMaterial:VW,MeshToonMaterial:SyA,MeshNormalMaterial:wyA,MeshLambertMaterial:XW,MeshDepthMaterial:$W,MeshDistanceMaterial:AV,MeshBasicMaterial:kg,MeshMatcapMaterial:kyA,LineDashedMaterial:MyA,LineBasicMaterial:es,Material:ho};return new t[A]}}class AC{static extractUrlBase(A){const t=A.lastIndexOf("/");return t===-1?"./":A.slice(0,t+1)}static resolveURL(A,t){return typeof A!="string"||A===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(A)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(A)||/^data:.*,.*$/i.test(A)||/^blob:.*$/i.test(A)?A:t+A)}}class JyA extends Ni{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(A){return super.copy(A),this.instanceCount=A.instanceCount,this}toJSON(){const A=super.toJSON();return A.instanceCount=this.instanceCount,A.isInstancedBufferGeometry=!0,A}}class LyA extends la{constructor(A){super(A)}load(A,t,i,n){const g=this,o=new or(g.manager);o.setPath(g.path),o.setRequestHeader(g.requestHeader),o.setWithCredentials(g.withCredentials),o.load(A,function(s){try{t(g.parse(JSON.parse(s)))}catch(a){n?n(a):console.error(a),g.manager.itemError(A)}},i,n)}parse(A){const t={},i={};function n(B,Q){if(t[Q]!==void 0)return t[Q];const d=B.interleavedBuffers[Q],p=g(B,d.buffer),y=am(d.type,p),m=new _w(y,d.stride);return m.uuid=d.uuid,t[Q]=m,m}function g(B,Q){if(i[Q]!==void 0)return i[Q];const d=B.arrayBuffers[Q],p=new Uint32Array(d).buffer;return i[Q]=p,p}const o=A.isInstancedBufferGeometry?new JyA:new Ni,s=A.data.index;if(s!==void 0){const B=am(s.type,s.array);o.setIndex(new ji(B,1))}const a=A.data.attributes;for(const B in a){const Q=a[B];let h;if(Q.isInterleavedBufferAttribute){const d=n(A.data,Q.data);h=new CQ(d,Q.itemSize,Q.offset,Q.normalized)}else{const d=am(Q.type,Q.array),p=Q.isInstancedBufferAttribute?hd:ji;h=new p(d,Q.itemSize,Q.normalized)}Q.name!==void 0&&(h.name=Q.name),Q.usage!==void 0&&h.setUsage(Q.usage),o.setAttribute(B,h)}const r=A.data.morphAttributes;if(r)for(const B in r){const Q=r[B],h=[];for(let d=0,p=Q.length;d<p;d++){const y=Q[d];let m;if(y.isInterleavedBufferAttribute){const D=n(A.data,y.data);m=new CQ(D,y.itemSize,y.offset,y.normalized)}else{const D=am(y.type,y.array);m=new ji(D,y.itemSize,y.normalized)}y.name!==void 0&&(m.name=y.name),h.push(m)}o.morphAttributes[B]=h}A.data.morphTargetsRelative&&(o.morphTargetsRelative=!0);const c=A.data.groups||A.data.drawcalls||A.data.offsets;if(c!==void 0)for(let B=0,Q=c.length;B!==Q;++B){const h=c[B];o.addGroup(h.start,h.count,h.materialIndex)}const l=A.data.boundingSphere;return l!==void 0&&(o.boundingSphere=new xs().fromJSON(l)),A.name&&(o.name=A.name),A.userData&&(o.userData=A.userData),o}}class gIe extends la{constructor(A){super(A)}load(A,t,i,n){const g=this,o=this.path===""?AC.extractUrlBase(A):this.path;this.resourcePath=this.resourcePath||o;const s=new or(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(A,function(a){let r=null;try{r=JSON.parse(a)}catch(c){n!==void 0&&n(c),console.error("THREE:ObjectLoader: Can't parse "+A+".",c.message);return}const I=r.metadata;if(I===void 0||I.type===void 0||I.type.toLowerCase()==="geometry"){n!==void 0&&n(new Error("THREE.ObjectLoader: Can't load "+A)),console.error("THREE.ObjectLoader: Can't load "+A);return}g.parse(r,t)},i,n)}async loadAsync(A,t){const i=this,n=this.path===""?AC.extractUrlBase(A):this.path;this.resourcePath=this.resourcePath||n;const g=new or(this.manager);g.setPath(this.path),g.setRequestHeader(this.requestHeader),g.setWithCredentials(this.withCredentials);const o=await g.loadAsync(A,t),s=JSON.parse(o),a=s.metadata;if(a===void 0||a.type===void 0||a.type.toLowerCase()==="geometry")throw new Error("THREE.ObjectLoader: Can't load "+A);return await i.parseAsync(s)}parse(A,t){const i=this.parseAnimations(A.animations),n=this.parseShapes(A.shapes),g=this.parseGeometries(A.geometries,n),o=this.parseImages(A.images,function(){t!==void 0&&t(r)}),s=this.parseTextures(A.textures,o),a=this.parseMaterials(A.materials,s),r=this.parseObject(A.object,g,a,s,i),I=this.parseSkeletons(A.skeletons,r);if(this.bindSkeletons(r,I),this.bindLightTargets(r),t!==void 0){let c=!1;for(const l in o)if(o[l].data instanceof HTMLImageElement){c=!0;break}c===!1&&t(r)}return r}async parseAsync(A){const t=this.parseAnimations(A.animations),i=this.parseShapes(A.shapes),n=this.parseGeometries(A.geometries,i),g=await this.parseImagesAsync(A.images),o=this.parseTextures(A.textures,g),s=this.parseMaterials(A.materials,o),a=this.parseObject(A.object,n,s,o,t),r=this.parseSkeletons(A.skeletons,a);return this.bindSkeletons(a,r),this.bindLightTargets(a),a}parseShapes(A){const t={};if(A!==void 0)for(let i=0,n=A.length;i<n;i++){const g=new jp().fromJSON(A[i]);t[g.uuid]=g}return t}parseSkeletons(A,t){const i={},n={};if(t.traverse(function(g){g.isBone&&(n[g.uuid]=g)}),A!==void 0)for(let g=0,o=A.length;g<o;g++){const s=new Jw().fromJSON(A[g],n);i[s.uuid]=s}return i}parseGeometries(A,t){const i={};if(A!==void 0){const n=new LyA;for(let g=0,o=A.length;g<o;g++){let s;const a=A[g];switch(a.type){case"BufferGeometry":case"InstancedBufferGeometry":s=n.parse(a);break;default:a.type in hnA?s=hnA[a.type].fromJSON(a,t):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${a.type}"`)}s.uuid=a.uuid,a.name!==void 0&&(s.name=a.name),a.userData!==void 0&&(s.userData=a.userData),i[a.uuid]=s}}return i}parseMaterials(A,t){const i={},n={};if(A!==void 0){const g=new cT;g.setTextures(t);for(let o=0,s=A.length;o<s;o++){const a=A[o];i[a.uuid]===void 0&&(i[a.uuid]=g.parse(a)),n[a.uuid]=i[a.uuid]}}return n}parseAnimations(A){const t={};if(A!==void 0)for(let i=0;i<A.length;i++){const n=A[i],g=fd.parse(n);t[g.uuid]=g}return t}parseImages(A,t){const i=this,n={};let g;function o(a){return i.manager.itemStart(a),g.load(a,function(){i.manager.itemEnd(a)},void 0,function(){i.manager.itemError(a),i.manager.itemEnd(a)})}function s(a){if(typeof a=="string"){const r=a,I=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(r)?r:i.resourcePath+r;return o(I)}else return a.data?{data:am(a.type,a.data),width:a.width,height:a.height}:null}if(A!==void 0&&A.length>0){const a=new nV(t);g=new xN(a),g.setCrossOrigin(this.crossOrigin);for(let r=0,I=A.length;r<I;r++){const c=A[r],l=c.url;if(Array.isArray(l)){const B=[];for(let Q=0,h=l.length;Q<h;Q++){const d=l[Q],p=s(d);p!==null&&(p instanceof HTMLImageElement?B.push(p):B.push(new uB(p.data,p.width,p.height)))}n[c.uuid]=new Ru(B)}else{const B=s(c.url);n[c.uuid]=new Ru(B)}}}return n}async parseImagesAsync(A){const t=this,i={};let n;async function g(o){if(typeof o=="string"){const s=o,a=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(s)?s:t.resourcePath+s;return await n.loadAsync(a)}else return o.data?{data:am(o.type,o.data),width:o.width,height:o.height}:null}if(A!==void 0&&A.length>0){n=new xN(this.manager),n.setCrossOrigin(this.crossOrigin);for(let o=0,s=A.length;o<s;o++){const a=A[o],r=a.url;if(Array.isArray(r)){const I=[];for(let c=0,l=r.length;c<l;c++){const B=r[c],Q=await g(B);Q!==null&&(Q instanceof HTMLImageElement?I.push(Q):I.push(new uB(Q.data,Q.width,Q.height)))}i[a.uuid]=new Ru(I)}else{const I=await g(a.url);i[a.uuid]=new Ru(I)}}}return i}parseTextures(A,t){function i(g,o){return typeof g=="number"?g:(console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",g),o[g])}const n={};if(A!==void 0)for(let g=0,o=A.length;g<o;g++){const s=A[g];s.image===void 0&&console.warn('THREE.ObjectLoader: No "image" specified for',s.uuid),t[s.image]===void 0&&console.warn("THREE.ObjectLoader: Undefined image",s.image);const a=t[s.image],r=a.data;let I;Array.isArray(r)?(I=new sG,r.length===6&&(I.needsUpdate=!0)):(r&&r.data?I=new uB:I=new Kg,r&&(I.needsUpdate=!0)),I.source=a,I.uuid=s.uuid,s.name!==void 0&&(I.name=s.name),s.mapping!==void 0&&(I.mapping=i(s.mapping,oIe)),s.channel!==void 0&&(I.channel=s.channel),s.offset!==void 0&&I.offset.fromArray(s.offset),s.repeat!==void 0&&I.repeat.fromArray(s.repeat),s.center!==void 0&&I.center.fromArray(s.center),s.rotation!==void 0&&(I.rotation=s.rotation),s.wrap!==void 0&&(I.wrapS=i(s.wrap[0],DnA),I.wrapT=i(s.wrap[1],DnA)),s.format!==void 0&&(I.format=s.format),s.internalFormat!==void 0&&(I.internalFormat=s.internalFormat),s.type!==void 0&&(I.type=s.type),s.colorSpace!==void 0&&(I.colorSpace=s.colorSpace),s.minFilter!==void 0&&(I.minFilter=i(s.minFilter,mnA)),s.magFilter!==void 0&&(I.magFilter=i(s.magFilter,mnA)),s.anisotropy!==void 0&&(I.anisotropy=s.anisotropy),s.flipY!==void 0&&(I.flipY=s.flipY),s.generateMipmaps!==void 0&&(I.generateMipmaps=s.generateMipmaps),s.premultiplyAlpha!==void 0&&(I.premultiplyAlpha=s.premultiplyAlpha),s.unpackAlignment!==void 0&&(I.unpackAlignment=s.unpackAlignment),s.compareFunction!==void 0&&(I.compareFunction=s.compareFunction),s.userData!==void 0&&(I.userData=s.userData),n[s.uuid]=I}return n}parseObject(A,t,i,n,g){let o;function s(l){return t[l]===void 0&&console.warn("THREE.ObjectLoader: Undefined geometry",l),t[l]}function a(l){if(l!==void 0){if(Array.isArray(l)){const B=[];for(let Q=0,h=l.length;Q<h;Q++){const d=l[Q];i[d]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",d),B.push(i[d])}return B}return i[l]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",l),i[l]}}function r(l){return n[l]===void 0&&console.warn("THREE.ObjectLoader: Undefined texture",l),n[l]}let I,c;switch(A.type){case"Scene":o=new rG,A.background!==void 0&&(Number.isInteger(A.background)?o.background=new Et(A.background):o.background=r(A.background)),A.environment!==void 0&&(o.environment=r(A.environment)),A.fog!==void 0&&(A.fog.type==="Fog"?o.fog=new aG(A.fog.color,A.fog.near,A.fog.far):A.fog.type==="FogExp2"&&(o.fog=new Px(A.fog.color,A.fog.density)),A.fog.name!==""&&(o.fog.name=A.fog.name)),A.backgroundBlurriness!==void 0&&(o.backgroundBlurriness=A.backgroundBlurriness),A.backgroundIntensity!==void 0&&(o.backgroundIntensity=A.backgroundIntensity),A.backgroundRotation!==void 0&&o.backgroundRotation.fromArray(A.backgroundRotation),A.environmentIntensity!==void 0&&(o.environmentIntensity=A.environmentIntensity),A.environmentRotation!==void 0&&o.environmentRotation.fromArray(A.environmentRotation);break;case"PerspectiveCamera":o=new Wo(A.fov,A.aspect,A.near,A.far),A.focus!==void 0&&(o.focus=A.focus),A.zoom!==void 0&&(o.zoom=A.zoom),A.filmGauge!==void 0&&(o.filmGauge=A.filmGauge),A.filmOffset!==void 0&&(o.filmOffset=A.filmOffset),A.view!==void 0&&(o.view=Object.assign({},A.view));break;case"OrthographicCamera":o=new Hd(A.left,A.right,A.top,A.bottom,A.near,A.far),A.zoom!==void 0&&(o.zoom=A.zoom),A.view!==void 0&&(o.view=Object.assign({},A.view));break;case"AmbientLight":o=new sV(A.color,A.intensity);break;case"DirectionalLight":o=new zp(A.color,A.intensity),o.target=A.target||"";break;case"PointLight":o=new BG(A.color,A.intensity,A.distance,A.decay);break;case"RectAreaLight":o=new KyA(A.color,A.intensity,A.width,A.height);break;case"SpotLight":o=new CT(A.color,A.intensity,A.distance,A.angle,A.penumbra,A.decay),o.target=A.target||"";break;case"HemisphereLight":o=new gV(A.color,A.groundColor,A.intensity);break;case"LightProbe":o=new _yA().fromJSON(A);break;case"SkinnedMesh":I=s(A.geometry),c=a(A.material),o=new jx(I,c),A.bindMode!==void 0&&(o.bindMode=A.bindMode),A.bindMatrix!==void 0&&o.bindMatrix.fromArray(A.bindMatrix),A.skeleton!==void 0&&(o.skeleton=A.skeleton);break;case"Mesh":I=s(A.geometry),c=a(A.material),o=new pn(I,c);break;case"InstancedMesh":I=s(A.geometry),c=a(A.material);const l=A.count,B=A.instanceMatrix,Q=A.instanceColor;o=new CG(I,c,l),o.instanceMatrix=new hd(new Float32Array(B.array),16),Q!==void 0&&(o.instanceColor=new hd(new Float32Array(Q.array),Q.itemSize));break;case"BatchedMesh":I=s(A.geometry),c=a(A.material),o=new CyA(A.maxInstanceCount,A.maxVertexCount,A.maxIndexCount,c),o.geometry=I,o.perObjectFrustumCulled=A.perObjectFrustumCulled,o.sortObjects=A.sortObjects,o._drawRanges=A.drawRanges,o._reservedRanges=A.reservedRanges,o._geometryInfo=A.geometryInfo.map(h=>{let d=null,p=null;return h.boundingBox!==void 0&&(d=new Ag().fromJSON(h.boundingBox)),h.boundingSphere!==void 0&&(p=new xs().fromJSON(h.boundingSphere)),{...h,boundingBox:d,boundingSphere:p}}),o._instanceInfo=A.instanceInfo,o._availableInstanceIds=A._availableInstanceIds,o._availableGeometryIds=A._availableGeometryIds,o._nextIndexStart=A.nextIndexStart,o._nextVertexStart=A.nextVertexStart,o._geometryCount=A.geometryCount,o._maxInstanceCount=A.maxInstanceCount,o._maxVertexCount=A.maxVertexCount,o._maxIndexCount=A.maxIndexCount,o._geometryInitialized=A.geometryInitialized,o._matricesTexture=r(A.matricesTexture.uuid),o._indirectTexture=r(A.indirectTexture.uuid),A.colorsTexture!==void 0&&(o._colorsTexture=r(A.colorsTexture.uuid)),A.boundingSphere!==void 0&&(o.boundingSphere=new xs().fromJSON(A.boundingSphere)),A.boundingBox!==void 0&&(o.boundingBox=new Ag().fromJSON(A.boundingBox));break;case"LOD":o=new IyA;break;case"Line":o=new yB(s(A.geometry),a(A.material));break;case"LineLoop":o=new Zx(s(A.geometry),a(A.material));break;case"LineSegments":o=new EI(s(A.geometry),a(A.material));break;case"PointCloud":case"Points":o=new Pp(s(A.geometry),a(A.material));break;case"Sprite":o=new hJ(a(A.material));break;case"Group":o=new sa;break;case"Bone":o=new IG;break;default:o=new Bn}if(o.uuid=A.uuid,A.name!==void 0&&(o.name=A.name),A.matrix!==void 0?(o.matrix.fromArray(A.matrix),A.matrixAutoUpdate!==void 0&&(o.matrixAutoUpdate=A.matrixAutoUpdate),o.matrixAutoUpdate&&o.matrix.decompose(o.position,o.quaternion,o.scale)):(A.position!==void 0&&o.position.fromArray(A.position),A.rotation!==void 0&&o.rotation.fromArray(A.rotation),A.quaternion!==void 0&&o.quaternion.fromArray(A.quaternion),A.scale!==void 0&&o.scale.fromArray(A.scale)),A.up!==void 0&&o.up.fromArray(A.up),A.castShadow!==void 0&&(o.castShadow=A.castShadow),A.receiveShadow!==void 0&&(o.receiveShadow=A.receiveShadow),A.shadow&&(A.shadow.intensity!==void 0&&(o.shadow.intensity=A.shadow.intensity),A.shadow.bias!==void 0&&(o.shadow.bias=A.shadow.bias),A.shadow.normalBias!==void 0&&(o.shadow.normalBias=A.shadow.normalBias),A.shadow.radius!==void 0&&(o.shadow.radius=A.shadow.radius),A.shadow.mapSize!==void 0&&o.shadow.mapSize.fromArray(A.shadow.mapSize),A.shadow.camera!==void 0&&(o.shadow.camera=this.parseObject(A.shadow.camera))),A.visible!==void 0&&(o.visible=A.visible),A.frustumCulled!==void 0&&(o.frustumCulled=A.frustumCulled),A.renderOrder!==void 0&&(o.renderOrder=A.renderOrder),A.userData!==void 0&&(o.userData=A.userData),A.layers!==void 0&&(o.layers.mask=A.layers),A.children!==void 0){const l=A.children;for(let B=0;B<l.length;B++)o.add(this.parseObject(l[B],t,i,n,g))}if(A.animations!==void 0){const l=A.animations;for(let B=0;B<l.length;B++){const Q=l[B];o.animations.push(g[Q])}}if(A.type==="LOD"){A.autoUpdate!==void 0&&(o.autoUpdate=A.autoUpdate);const l=A.levels;for(let B=0;B<l.length;B++){const Q=l[B],h=o.getObjectByProperty("uuid",Q.object);h!==void 0&&o.addLevel(h,Q.distance,Q.hysteresis)}}return o}bindSkeletons(A,t){Object.keys(t).length!==0&&A.traverse(function(i){if(i.isSkinnedMesh===!0&&i.skeleton!==void 0){const n=t[i.skeleton];n===void 0?console.warn("THREE.ObjectLoader: No skeleton found with UUID:",i.skeleton):i.bind(n,i.bindMatrix)}})}bindLightTargets(A){A.traverse(function(t){if(t.isDirectionalLight||t.isSpotLight){const i=t.target,n=A.getObjectByProperty("uuid",i);n!==void 0?t.target=n:t.target=new Bn}})}}const oIe={UVMapping:Kx,CubeReflectionMapping:rQ,CubeRefractionMapping:ud,EquirectangularReflectionMapping:NN,EquirectangularRefractionMapping:RN,CubeUVReflectionMapping:Kw},DnA={RepeatWrapping:Fr,ClampToEdgeWrapping:oI,MirroredRepeatWrapping:ff},mnA={NearestFilter:Ss,NearestMipmapNearestFilter:nG,NearestMipmapLinearFilter:Nu,LinearFilter:qg,LinearMipmapNearestFilter:Hp,LinearMipmapLinearFilter:Gr},UH=new WeakMap;class aV extends la{constructor(A){super(A),this.isImageBitmapLoader=!0,typeof createImageBitmap>"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(A){return this.options=A,this}load(A,t,i,n){A===void 0&&(A=""),this.path!==void 0&&(A=this.path+A),A=this.manager.resolveURL(A);const g=this,o=sB.get(`image-bitmap:${A}`);if(o!==void 0){if(g.manager.itemStart(A),o.then){o.then(r=>{if(UH.has(o)===!0)n&&n(UH.get(o)),g.manager.itemError(A),g.manager.itemEnd(A);else return t&&t(r),g.manager.itemEnd(A),r});return}return setTimeout(function(){t&&t(o),g.manager.itemEnd(A)},0),o}const s={};s.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",s.headers=this.requestHeader,s.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const a=fetch(A,s).then(function(r){return r.blob()}).then(function(r){return createImageBitmap(r,Object.assign(g.options,{colorSpaceConversion:"none"}))}).then(function(r){return sB.add(`image-bitmap:${A}`,r),t&&t(r),g.manager.itemEnd(A),r}).catch(function(r){n&&n(r),UH.set(a,r),sB.remove(`image-bitmap:${A}`),g.manager.itemError(A),g.manager.itemEnd(A)});sB.add(`image-bitmap:${A}`,a),g.manager.itemStart(A)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let TU,rV=class{static getContext(){return TU===void 0&&(TU=new(window.AudioContext||window.webkitAudioContext)),TU}static setContext(A){TU=A}};class sIe extends la{constructor(A){super(A)}load(A,t,i,n){const g=this,o=new or(this.manager);o.setResponseType("arraybuffer"),o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(A,function(a){try{const r=a.slice(0);rV.getContext().decodeAudioData(r,function(c){t(c)}).catch(s)}catch(r){s(r)}},i,n);function s(a){n?n(a):console.error(a),g.manager.itemError(A)}}}const SnA=new ni,wnA=new ni,Sh=new ni;class aIe{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Wo,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Wo,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(A){const t=this._cache;if(t.focus!==A.focus||t.fov!==A.fov||t.aspect!==A.aspect*this.aspect||t.near!==A.near||t.far!==A.far||t.zoom!==A.zoom||t.eyeSep!==this.eyeSep){t.focus=A.focus,t.fov=A.fov,t.aspect=A.aspect*this.aspect,t.near=A.near,t.far=A.far,t.zoom=A.zoom,t.eyeSep=this.eyeSep,Sh.copy(A.projectionMatrix);const n=t.eyeSep/2,g=n*t.near/t.focus,o=t.near*Math.tan(Op*t.fov*.5)/t.zoom;let s,a;wnA.elements[12]=-n,SnA.elements[12]=n,s=-o*t.aspect+g,a=o*t.aspect+g,Sh.elements[0]=2*t.near/(a-s),Sh.elements[8]=(a+s)/(a-s),this.cameraL.projectionMatrix.copy(Sh),s=-o*t.aspect-g,a=o*t.aspect-g,Sh.elements[0]=2*t.near/(a-s),Sh.elements[8]=(a+s)/(a-s),this.cameraR.projectionMatrix.copy(Sh)}this.cameraL.matrixWorld.copy(A.matrixWorld).multiply(wnA),this.cameraR.matrixWorld.copy(A.matrixWorld).multiply(SnA)}}class xyA extends Wo{constructor(A=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=A}}class IV{constructor(A=!0){this.autoStart=A,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let A=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();A=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=A}return A}}const wh=new SA,vH=new oo,rIe=new SA,kh=new SA,Mh=new SA;class IIe extends Bn{constructor(){super(),this.type="AudioListener",this.context=rV.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new IV}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(A){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=A,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(A){return this.gain.gain.setTargetAtTime(A,this.context.currentTime,.01),this}updateMatrixWorld(A){super.updateMatrixWorld(A);const t=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(wh,vH,rIe),kh.set(0,0,-1).applyQuaternion(vH),Mh.set(0,1,0).applyQuaternion(vH),t.positionX){const i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(wh.x,i),t.positionY.linearRampToValueAtTime(wh.y,i),t.positionZ.linearRampToValueAtTime(wh.z,i),t.forwardX.linearRampToValueAtTime(kh.x,i),t.forwardY.linearRampToValueAtTime(kh.y,i),t.forwardZ.linearRampToValueAtTime(kh.z,i),t.upX.linearRampToValueAtTime(Mh.x,i),t.upY.linearRampToValueAtTime(Mh.y,i),t.upZ.linearRampToValueAtTime(Mh.z,i)}else t.setPosition(wh.x,wh.y,wh.z),t.setOrientation(kh.x,kh.y,kh.z,Mh.x,Mh.y,Mh.z)}}let TyA=class extends Bn{constructor(A){super(),this.type="Audio",this.listener=A,this.context=A.context,this.gain=this.context.createGain(),this.gain.connect(A.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(A){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=A,this.connect(),this}setMediaElementSource(A){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(A),this.connect(),this}setMediaStreamSource(A){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(A),this.connect(),this}setBuffer(A){return this.buffer=A,this.sourceType="buffer",this.autoplay&&this.play(),this}play(A=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+A;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(A=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+A),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let A=1,t=this.filters.length;A<t;A++)this.filters[A-1].connect(this.filters[A]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this._connected=!0,this}disconnect(){if(this._connected!==!1){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(let A=1,t=this.filters.length;A<t;A++)this.filters[A-1].disconnect(this.filters[A]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this._connected=!1,this}}getFilters(){return this.filters}setFilters(A){return A||(A=[]),this._connected===!0?(this.disconnect(),this.filters=A.slice(),this.connect()):this.filters=A.slice(),this}setDetune(A){return this.detune=A,this.isPlaying===!0&&this.source.detune!==void 0&&this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,.01),this}getDetune(){return this.detune}getFilter(){return this.getFilters()[0]}setFilter(A){return this.setFilters(A?[A]:[])}setPlaybackRate(A){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.playbackRate=A,this.isPlaying===!0&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1,this._progress=0}getLoop(){return this.hasPlaybackControl===!1?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop}setLoop(A){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.loop=A,this.isPlaying===!0&&(this.source.loop=this.loop),this}setLoopStart(A){return this.loopStart=A,this}setLoopEnd(A){return this.loopEnd=A,this}getVolume(){return this.gain.gain.value}setVolume(A){return this.gain.gain.setTargetAtTime(A,this.context.currentTime,.01),this}copy(A,t){return super.copy(A,t),A.sourceType!=="buffer"?(console.warn("THREE.Audio: Audio source type cannot be copied."),this):(this.autoplay=A.autoplay,this.buffer=A.buffer,this.detune=A.detune,this.loop=A.loop,this.loopStart=A.loopStart,this.loopEnd=A.loopEnd,this.offset=A.offset,this.duration=A.duration,this.playbackRate=A.playbackRate,this.hasPlaybackControl=A.hasPlaybackControl,this.sourceType=A.sourceType,this.filters=A.filters.slice(),this)}clone(A){return new this.constructor(this.listener).copy(this,A)}};const Nh=new SA,knA=new oo,CIe=new SA,Rh=new SA;class cIe extends TyA{constructor(A){super(A),this.panner=this.context.createPanner(),this.panner.panningModel="HRTF",this.panner.connect(this.gain)}connect(){return super.connect(),this.panner.connect(this.gain),this}disconnect(){return super.disconnect(),this.panner.disconnect(this.gain),this}getOutput(){return this.panner}getRefDistance(){return this.panner.refDistance}setRefDistance(A){return this.panner.refDistance=A,this}getRolloffFactor(){return this.panner.rolloffFactor}setRolloffFactor(A){return this.panner.rolloffFactor=A,this}getDistanceModel(){return this.panner.distanceModel}setDistanceModel(A){return this.panner.distanceModel=A,this}getMaxDistance(){return this.panner.maxDistance}setMaxDistance(A){return this.panner.maxDistance=A,this}setDirectionalCone(A,t,i){return this.panner.coneInnerAngle=A,this.panner.coneOuterAngle=t,this.panner.coneOuterGain=i,this}updateMatrixWorld(A){if(super.updateMatrixWorld(A),this.hasPlaybackControl===!0&&this.isPlaying===!1)return;this.matrixWorld.decompose(Nh,knA,CIe),Rh.set(0,0,1).applyQuaternion(knA);const t=this.panner;if(t.positionX){const i=this.context.currentTime+this.listener.timeDelta;t.positionX.linearRampToValueAtTime(Nh.x,i),t.positionY.linearRampToValueAtTime(Nh.y,i),t.positionZ.linearRampToValueAtTime(Nh.z,i),t.orientationX.linearRampToValueAtTime(Rh.x,i),t.orientationY.linearRampToValueAtTime(Rh.y,i),t.orientationZ.linearRampToValueAtTime(Rh.z,i)}else t.setPosition(Nh.x,Nh.y,Nh.z),t.setOrientation(Rh.x,Rh.y,Rh.z)}}class lIe{constructor(A,t=2048){this.analyser=A.context.createAnalyser(),this.analyser.fftSize=t,this.data=new Uint8Array(this.analyser.frequencyBinCount),A.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let A=0;const t=this.getFrequencyData();for(let i=0;i<t.length;i++)A+=t[i];return A/t.length}}class qyA{constructor(A,t,i){this.binding=A,this.valueSize=i;let n,g,o;switch(t){case"quaternion":n=this._slerp,g=this._slerpAdditive,o=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(i*6),this._workIndex=5;break;case"string":case"bool":n=this._select,g=this._select,o=this._setAdditiveIdentityOther,this.buffer=new Array(i*5);break;default:n=this._lerp,g=this._lerpAdditive,o=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(i*5)}this._mixBufferRegion=n,this._mixBufferRegionAdditive=g,this._setIdentity=o,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(A,t){const i=this.buffer,n=this.valueSize,g=A*n+n;let o=this.cumulativeWeight;if(o===0){for(let s=0;s!==n;++s)i[g+s]=i[s];o=t}else{o+=t;const s=t/o;this._mixBufferRegion(i,g,0,s,n)}this.cumulativeWeight=o}accumulateAdditive(A){const t=this.buffer,i=this.valueSize,n=i*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,n,0,A,i),this.cumulativeWeightAdditive+=A}apply(A){const t=this.valueSize,i=this.buffer,n=A*t+t,g=this.cumulativeWeight,o=this.cumulativeWeightAdditive,s=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,g<1){const a=t*this._origIndex;this._mixBufferRegion(i,n,a,1-g,t)}o>0&&this._mixBufferRegionAdditive(i,n,this._addIndex*t,1,t);for(let a=t,r=t+t;a!==r;++a)if(i[a]!==i[a+t]){s.setValue(i,n);break}}saveOriginalState(){const A=this.binding,t=this.buffer,i=this.valueSize,n=i*this._origIndex;A.getValue(t,n);for(let g=i,o=n;g!==o;++g)t[g]=t[n+g%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const A=this.valueSize*3;this.binding.setValue(this.buffer,A)}_setAdditiveIdentityNumeric(){const A=this._addIndex*this.valueSize,t=A+this.valueSize;for(let i=A;i<t;i++)this.buffer[i]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const A=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let i=0;i<this.valueSize;i++)this.buffer[t+i]=this.buffer[A+i]}_select(A,t,i,n,g){if(n>=.5)for(let o=0;o!==g;++o)A[t+o]=A[i+o]}_slerp(A,t,i,n){oo.slerpFlat(A,t,A,t,A,i,n)}_slerpAdditive(A,t,i,n,g){const o=this._workIndex*g;oo.multiplyQuaternionsFlat(A,o,A,t,A,i),oo.slerpFlat(A,t,A,t,A,o,n)}_lerp(A,t,i,n,g){const o=1-n;for(let s=0;s!==g;++s){const a=t+s;A[a]=A[a]*o+A[i+s]*n}}_lerpAdditive(A,t,i,n,g){for(let o=0;o!==g;++o){const s=t+o;A[s]=A[s]+A[i+o]*n}}}const CV="\\[\\]\\.:\\/",BIe=new RegExp("["+CV+"]","g"),cV="[^"+CV+"]",EIe="[^"+CV.replace("\\.","")+"]",QIe=/((?:WC+[\/:])*)/.source.replace("WC",cV),uIe=/(WCOD+)?/.source.replace("WCOD",EIe),dIe=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",cV),hIe=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",cV),pIe=new RegExp("^"+QIe+uIe+dIe+hIe+"$"),fIe=["material","materials","bones","map"];class yIe{constructor(A,t,i){const n=i||zn.parseTrackName(t);this._targetGroup=A,this._bindings=A.subscribe_(t,n)}getValue(A,t){this.bind();const i=this._targetGroup.nCachedObjects_,n=this._bindings[i];n!==void 0&&n.getValue(A,t)}setValue(A,t){const i=this._bindings;for(let n=this._targetGroup.nCachedObjects_,g=i.length;n!==g;++n)i[n].setValue(A,t)}bind(){const A=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=A.length;t!==i;++t)A[t].bind()}unbind(){const A=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=A.length;t!==i;++t)A[t].unbind()}}class zn{constructor(A,t,i){this.path=t,this.parsedPath=i||zn.parseTrackName(t),this.node=zn.findNode(A,this.parsedPath.nodeName),this.rootNode=A,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(A,t,i){return A&&A.isAnimationObjectGroup?new zn.Composite(A,t,i):new zn(A,t,i)}static sanitizeNodeName(A){return A.replace(/\s/g,"_").replace(BIe,"")}static parseTrackName(A){const t=pIe.exec(A);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+A);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},n=i.nodeName&&i.nodeName.lastIndexOf(".");if(n!==void 0&&n!==-1){const g=i.nodeName.substring(n+1);fIe.indexOf(g)!==-1&&(i.nodeName=i.nodeName.substring(0,n),i.objectName=g)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+A);return i}static findNode(A,t){if(t===void 0||t===""||t==="."||t===-1||t===A.name||t===A.uuid)return A;if(A.skeleton){const i=A.skeleton.getBoneByName(t);if(i!==void 0)return i}if(A.children){const i=function(g){for(let o=0;o<g.length;o++){const s=g[o];if(s.name===t||s.uuid===t)return s;const a=i(s.children);if(a)return a}return null},n=i(A.children);if(n)return n}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(A,t){A[t]=this.targetObject[this.propertyName]}_getValue_array(A,t){const i=this.resolvedProperty;for(let n=0,g=i.length;n!==g;++n)A[t++]=i[n]}_getValue_arrayElement(A,t){A[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(A,t){this.resolvedProperty.toArray(A,t)}_setValue_direct(A,t){this.targetObject[this.propertyName]=A[t]}_setValue_direct_setNeedsUpdate(A,t){this.targetObject[this.propertyName]=A[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(A,t){this.targetObject[this.propertyName]=A[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(A,t){const i=this.resolvedProperty;for(let n=0,g=i.length;n!==g;++n)i[n]=A[t++]}_setValue_array_setNeedsUpdate(A,t){const i=this.resolvedProperty;for(let n=0,g=i.length;n!==g;++n)i[n]=A[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(A,t){const i=this.resolvedProperty;for(let n=0,g=i.length;n!==g;++n)i[n]=A[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(A,t){this.resolvedProperty[this.propertyIndex]=A[t]}_setValue_arrayElement_setNeedsUpdate(A,t){this.resolvedProperty[this.propertyIndex]=A[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(A,t){this.resolvedProperty[this.propertyIndex]=A[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(A,t){this.resolvedProperty.fromArray(A,t)}_setValue_fromArray_setNeedsUpdate(A,t){this.resolvedProperty.fromArray(A,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(A,t){this.resolvedProperty.fromArray(A,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(A,t){this.bind(),this.getValue(A,t)}_setValue_unbound(A,t){this.bind(),this.setValue(A,t)}bind(){let A=this.node;const t=this.parsedPath,i=t.objectName,n=t.propertyName;let g=t.propertyIndex;if(A||(A=zn.findNode(this.rootNode,t.nodeName),this.node=A),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!A){console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");return}if(i){let r=t.objectIndex;switch(i){case"materials":if(!A.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!A.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}A=A.material.materials;break;case"bones":if(!A.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}A=A.skeleton.bones;for(let I=0;I<A.length;I++)if(A[I].name===r){r=I;break}break;case"map":if("map"in A){A=A.map;break}if(!A.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!A.material.map){console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}A=A.material.map;break;default:if(A[i]===void 0){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}A=A[i]}if(r!==void 0){if(A[r]===void 0){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,A);return}A=A[r]}}const o=A[n];if(o===void 0){const r=t.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+r+"."+n+" but it wasn't found.",A);return}let s=this.Versioning.None;this.targetObject=A,A.isMaterial===!0?s=this.Versioning.NeedsUpdate:A.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let a=this.BindingType.Direct;if(g!==void 0){if(n==="morphTargetInfluences"){if(!A.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!A.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}A.morphTargetDictionary[g]!==void 0&&(g=A.morphTargetDictionary[g])}a=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=g}else o.fromArray!==void 0&&o.toArray!==void 0?(a=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(a=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=n;this.getValue=this.GetterByBindingType[a],this.setValue=this.SetterByBindingTypeAndVersioning[a][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}zn.Composite=yIe;zn.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};zn.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};zn.prototype.GetterByBindingType=[zn.prototype._getValue_direct,zn.prototype._getValue_array,zn.prototype._getValue_arrayElement,zn.prototype._getValue_toArray];zn.prototype.SetterByBindingTypeAndVersioning=[[zn.prototype._setValue_direct,zn.prototype._setValue_direct_setNeedsUpdate,zn.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[zn.prototype._setValue_array,zn.prototype._setValue_array_setNeedsUpdate,zn.prototype._setValue_array_setMatrixWorldNeedsUpdate],[zn.prototype._setValue_arrayElement,zn.prototype._setValue_arrayElement_setNeedsUpdate,zn.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[zn.prototype._setValue_fromArray,zn.prototype._setValue_fromArray_setNeedsUpdate,zn.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class DIe{constructor(){this.isAnimationObjectGroup=!0,this.uuid=$I(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;const A={};this._indicesByUUID=A;for(let i=0,n=arguments.length;i!==n;++i)A[arguments[i].uuid]=i;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};const t=this;this.stats={objects:{get total(){return t._objects.length},get inUse(){return this.total-t.nCachedObjects_}},get bindingsPerObject(){return t._bindings.length}}}add(){const A=this._objects,t=this._indicesByUUID,i=this._paths,n=this._parsedPaths,g=this._bindings,o=g.length;let s,a=A.length,r=this.nCachedObjects_;for(let I=0,c=arguments.length;I!==c;++I){const l=arguments[I],B=l.uuid;let Q=t[B];if(Q===void 0){Q=a++,t[B]=Q,A.push(l);for(let h=0,d=o;h!==d;++h)g[h].push(new zn(l,i[h],n[h]))}else if(Q<r){s=A[Q];const h=--r,d=A[h];t[d.uuid]=Q,A[Q]=d,t[B]=h,A[h]=l;for(let p=0,y=o;p!==y;++p){const m=g[p],D=m[h];let S=m[Q];m[Q]=D,S===void 0&&(S=new zn(l,i[p],n[p])),m[h]=S}}else A[Q]!==s&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=r}remove(){const A=this._objects,t=this._indicesByUUID,i=this._bindings,n=i.length;let g=this.nCachedObjects_;for(let o=0,s=arguments.length;o!==s;++o){const a=arguments[o],r=a.uuid,I=t[r];if(I!==void 0&&I>=g){const c=g++,l=A[c];t[l.uuid]=I,A[I]=l,t[r]=c,A[c]=a;for(let B=0,Q=n;B!==Q;++B){const h=i[B],d=h[c],p=h[I];h[I]=d,h[c]=p}}}this.nCachedObjects_=g}uncache(){const A=this._objects,t=this._indicesByUUID,i=this._bindings,n=i.length;let g=this.nCachedObjects_,o=A.length;for(let s=0,a=arguments.length;s!==a;++s){const r=arguments[s],I=r.uuid,c=t[I];if(c!==void 0)if(delete t[I],c<g){const l=--g,B=A[l],Q=--o,h=A[Q];t[B.uuid]=c,A[c]=B,t[h.uuid]=l,A[l]=h,A.pop();for(let d=0,p=n;d!==p;++d){const y=i[d],m=y[l],D=y[Q];y[c]=m,y[l]=D,y.pop()}}else{const l=--o,B=A[l];l>0&&(t[B.uuid]=c),A[c]=B,A.pop();for(let Q=0,h=n;Q!==h;++Q){const d=i[Q];d[c]=d[l],d.pop()}}}this.nCachedObjects_=g}subscribe_(A,t){const i=this._bindingsIndicesByPath;let n=i[A];const g=this._bindings;if(n!==void 0)return g[n];const o=this._paths,s=this._parsedPaths,a=this._objects,r=a.length,I=this.nCachedObjects_,c=new Array(r);n=g.length,i[A]=n,o.push(A),s.push(t),g.push(c);for(let l=I,B=a.length;l!==B;++l){const Q=a[l];c[l]=new zn(Q,A,t)}return c}unsubscribe_(A){const t=this._bindingsIndicesByPath,i=t[A];if(i!==void 0){const n=this._paths,g=this._parsedPaths,o=this._bindings,s=o.length-1,a=o[s],r=A[s];t[r]=i,o[i]=a,o.pop(),g[i]=g[s],g.pop(),n[i]=n[s],n.pop()}}}class YyA{constructor(A,t,i=null,n=t.blendMode){this._mixer=A,this._clip=t,this._localRoot=i,this.blendMode=n;const g=t.tracks,o=g.length,s=new Array(o),a={endingStart:lp,endingEnd:lp};for(let r=0;r!==o;++r){const I=g[r].createInterpolant(null);s[r]=I,I.settings=a}this._interpolantSettings=a,this._interpolants=s,this._propertyBindings=new Array(o),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=dJ,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(A){return this._startTime=A,this}setLoop(A,t){return this.loop=A,this.repetitions=t,this}setEffectiveWeight(A){return this.weight=A,this._effectiveWeight=this.enabled?A:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(A){return this._scheduleFading(A,0,1)}fadeOut(A){return this._scheduleFading(A,1,0)}crossFadeFrom(A,t,i=!1){if(A.fadeOut(t),this.fadeIn(t),i===!0){const n=this._clip.duration,g=A._clip.duration,o=g/n,s=n/g;A.warp(1,o,t),this.warp(s,1,t)}return this}crossFadeTo(A,t,i=!1){return A.crossFadeFrom(this,t,i)}stopFading(){const A=this._weightInterpolant;return A!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(A)),this}setEffectiveTimeScale(A){return this.timeScale=A,this._effectiveTimeScale=this.paused?0:A,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(A){return this.timeScale=this._clip.duration/A,this.stopWarping()}syncWith(A){return this.time=A.time,this.timeScale=A.timeScale,this.stopWarping()}halt(A){return this.warp(this._effectiveTimeScale,0,A)}warp(A,t,i){const n=this._mixer,g=n.time,o=this.timeScale;let s=this._timeScaleInterpolant;s===null&&(s=n._lendControlInterpolant(),this._timeScaleInterpolant=s);const a=s.parameterPositions,r=s.sampleValues;return a[0]=g,a[1]=g+i,r[0]=A/o,r[1]=t/o,this}stopWarping(){const A=this._timeScaleInterpolant;return A!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(A)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(A,t,i,n){if(!this.enabled){this._updateWeight(A);return}const g=this._startTime;if(g!==null){const a=(A-g)*i;a<0||i===0?t=0:(this._startTime=null,t=i*a)}t*=this._updateTimeScale(A);const o=this._updateTime(t),s=this._updateWeight(A);if(s>0){const a=this._interpolants,r=this._propertyBindings;switch(this.blendMode){case KW:for(let I=0,c=a.length;I!==c;++I)a[I].evaluate(o),r[I].accumulateAdditive(s);break;case qx:default:for(let I=0,c=a.length;I!==c;++I)a[I].evaluate(o),r[I].accumulate(n,s)}}}_updateWeight(A){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const n=i.evaluate(A)[0];t*=n,A>i.parameterPositions[1]&&(this.stopFading(),n===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(A){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const n=i.evaluate(A)[0];t*=n,A>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(A){const t=this._clip.duration,i=this.loop;let n=this.time+A,g=this._loopCount;const o=i===HfA;if(A===0)return g===-1?n:o&&(g&1)===1?t-n:n;if(i===vW){g===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));A:{if(n>=t)n=t;else if(n<0)n=0;else{this.time=n;break A}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:A<0?-1:1})}}else{if(g===-1&&(A>=0?(g=0,this._setEndings(!0,this.repetitions===0,o)):this._setEndings(this.repetitions===0,!0,o)),n>=t||n<0){const s=Math.floor(n/t);n-=t*s,g+=Math.abs(s);const a=this.repetitions-g;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,n=A>0?t:0,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:A>0?1:-1});else{if(a===1){const r=A<0;this._setEndings(r,!r,o)}else this._setEndings(!1,!1,o);this._loopCount=g,this.time=n,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:s})}}else this.time=n;if(o&&(g&1)===1)return t-n}return n}_setEndings(A,t,i){const n=this._interpolantSettings;i?(n.endingStart=Bp,n.endingEnd=Bp):(A?n.endingStart=this.zeroSlopeAtStart?Bp:lp:n.endingStart=GN,t?n.endingEnd=this.zeroSlopeAtEnd?Bp:lp:n.endingEnd=GN)}_scheduleFading(A,t,i){const n=this._mixer,g=n.time;let o=this._weightInterpolant;o===null&&(o=n._lendControlInterpolant(),this._weightInterpolant=o);const s=o.parameterPositions,a=o.sampleValues;return s[0]=g,a[0]=t,s[1]=g+A,a[1]=i,this}}const mIe=new Float32Array(1);class lV extends bB{constructor(A){super(),this._root=A,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(A,t){const i=A._localRoot||this._root,n=A._clip.tracks,g=n.length,o=A._propertyBindings,s=A._interpolants,a=i.uuid,r=this._bindingsByRootAndName;let I=r[a];I===void 0&&(I={},r[a]=I);for(let c=0;c!==g;++c){const l=n[c],B=l.name;let Q=I[B];if(Q!==void 0)++Q.referenceCount,o[c]=Q;else{if(Q=o[c],Q!==void 0){Q._cacheIndex===null&&(++Q.referenceCount,this._addInactiveBinding(Q,a,B));continue}const h=t&&t._propertyBindings[c].binding.parsedPath;Q=new qyA(zn.create(i,B,h),l.ValueTypeName,l.getValueSize()),++Q.referenceCount,this._addInactiveBinding(Q,a,B),o[c]=Q}s[c].resultBuffer=Q.buffer}}_activateAction(A){if(!this._isActiveAction(A)){if(A._cacheIndex===null){const i=(A._localRoot||this._root).uuid,n=A._clip.uuid,g=this._actionsByClip[n];this._bindAction(A,g&&g.knownActions[0]),this._addInactiveAction(A,n,i)}const t=A._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const g=t[i];g.useCount++===0&&(this._lendBinding(g),g.saveOriginalState())}this._lendAction(A)}}_deactivateAction(A){if(this._isActiveAction(A)){const t=A._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const g=t[i];--g.useCount===0&&(g.restoreOriginalState(),this._takeBackBinding(g))}this._takeBackAction(A)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const A=this;this.stats={actions:{get total(){return A._actions.length},get inUse(){return A._nActiveActions}},bindings:{get total(){return A._bindings.length},get inUse(){return A._nActiveBindings}},controlInterpolants:{get total(){return A._controlInterpolants.length},get inUse(){return A._nActiveControlInterpolants}}}}_isActiveAction(A){const t=A._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(A,t,i){const n=this._actions,g=this._actionsByClip;let o=g[t];if(o===void 0)o={knownActions:[A],actionByRoot:{}},A._byClipCacheIndex=0,g[t]=o;else{const s=o.knownActions;A._byClipCacheIndex=s.length,s.push(A)}A._cacheIndex=n.length,n.push(A),o.actionByRoot[i]=A}_removeInactiveAction(A){const t=this._actions,i=t[t.length-1],n=A._cacheIndex;i._cacheIndex=n,t[n]=i,t.pop(),A._cacheIndex=null;const g=A._clip.uuid,o=this._actionsByClip,s=o[g],a=s.knownActions,r=a[a.length-1],I=A._byClipCacheIndex;r._byClipCacheIndex=I,a[I]=r,a.pop(),A._byClipCacheIndex=null;const c=s.actionByRoot,l=(A._localRoot||this._root).uuid;delete c[l],a.length===0&&delete o[g],this._removeInactiveBindingsForAction(A)}_removeInactiveBindingsForAction(A){const t=A._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const g=t[i];--g.referenceCount===0&&this._removeInactiveBinding(g)}}_lendAction(A){const t=this._actions,i=A._cacheIndex,n=this._nActiveActions++,g=t[n];A._cacheIndex=n,t[n]=A,g._cacheIndex=i,t[i]=g}_takeBackAction(A){const t=this._actions,i=A._cacheIndex,n=--this._nActiveActions,g=t[n];A._cacheIndex=n,t[n]=A,g._cacheIndex=i,t[i]=g}_addInactiveBinding(A,t,i){const n=this._bindingsByRootAndName,g=this._bindings;let o=n[t];o===void 0&&(o={},n[t]=o),o[i]=A,A._cacheIndex=g.length,g.push(A)}_removeInactiveBinding(A){const t=this._bindings,i=A.binding,n=i.rootNode.uuid,g=i.path,o=this._bindingsByRootAndName,s=o[n],a=t[t.length-1],r=A._cacheIndex;a._cacheIndex=r,t[r]=a,t.pop(),delete s[g],Object.keys(s).length===0&&delete o[n]}_lendBinding(A){const t=this._bindings,i=A._cacheIndex,n=this._nActiveBindings++,g=t[n];A._cacheIndex=n,t[n]=A,g._cacheIndex=i,t[i]=g}_takeBackBinding(A){const t=this._bindings,i=A._cacheIndex,n=--this._nActiveBindings,g=t[n];A._cacheIndex=n,t[n]=A,g._cacheIndex=i,t[i]=g}_lendControlInterpolant(){const A=this._controlInterpolants,t=this._nActiveControlInterpolants++;let i=A[t];return i===void 0&&(i=new tV(new Float32Array(2),new Float32Array(2),1,mIe),i.__cacheIndex=t,A[t]=i),i}_takeBackControlInterpolant(A){const t=this._controlInterpolants,i=A.__cacheIndex,n=--this._nActiveControlInterpolants,g=t[n];A.__cacheIndex=n,t[n]=A,g.__cacheIndex=i,t[i]=g}clipAction(A,t,i){const n=t||this._root,g=n.uuid;let o=typeof A=="string"?fd.findByName(n,A):A;const s=o!==null?o.uuid:A,a=this._actionsByClip[s];let r=null;if(i===void 0&&(o!==null?i=o.blendMode:i=qx),a!==void 0){const c=a.actionByRoot[g];if(c!==void 0&&c.blendMode===i)return c;r=a.knownActions[0],o===null&&(o=r._clip)}if(o===null)return null;const I=new YyA(this,o,t,i);return this._bindAction(I,r),this._addInactiveAction(I,s,g),I}existingAction(A,t){const i=t||this._root,n=i.uuid,g=typeof A=="string"?fd.findByName(i,A):A,o=g?g.uuid:A,s=this._actionsByClip[o];return s!==void 0&&s.actionByRoot[n]||null}stopAllAction(){const A=this._actions,t=this._nActiveActions;for(let i=t-1;i>=0;--i)A[i].stop();return this}update(A){A*=this.timeScale;const t=this._actions,i=this._nActiveActions,n=this.time+=A,g=Math.sign(A),o=this._accuIndex^=1;for(let r=0;r!==i;++r)t[r]._update(n,A,g,o);const s=this._bindings,a=this._nActiveBindings;for(let r=0;r!==a;++r)s[r].apply(o);return this}setTime(A){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(A)}getRoot(){return this._root}uncacheClip(A){const t=this._actions,i=A.uuid,n=this._actionsByClip,g=n[i];if(g!==void 0){const o=g.knownActions;for(let s=0,a=o.length;s!==a;++s){const r=o[s];this._deactivateAction(r);const I=r._cacheIndex,c=t[t.length-1];r._cacheIndex=null,r._byClipCacheIndex=null,c._cacheIndex=I,t[I]=c,t.pop(),this._removeInactiveBindingsForAction(r)}delete n[i]}}uncacheRoot(A){const t=A.uuid,i=this._actionsByClip;for(const o in i){const s=i[o].actionByRoot,a=s[t];a!==void 0&&(this._deactivateAction(a),this._removeInactiveAction(a))}const n=this._bindingsByRootAndName,g=n[t];if(g!==void 0)for(const o in g){const s=g[o];s.restoreOriginalState(),this._removeInactiveBinding(s)}}uncacheAction(A,t){const i=this.existingAction(A,t);i!==null&&(this._deactivateAction(i),this._removeInactiveAction(i))}}class SIe extends LW{constructor(A=1,t=1,i=1,n={}){super(A,t,n),this.isRenderTarget3D=!0,this.depth=i,this.texture=new Hx(null,A,t,i),this._setTextureOptions(n),this.texture.isRenderTargetTexture=!0}}class BV{constructor(A){this.value=A}clone(){return new BV(this.value.clone===void 0?this.value:this.value.clone())}}let wIe=0;class kIe extends bB{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:wIe++}),this.name="",this.usage=UN,this.uniforms=[]}add(A){return this.uniforms.push(A),this}remove(A){const t=this.uniforms.indexOf(A);return t!==-1&&this.uniforms.splice(t,1),this}setName(A){return this.name=A,this}setUsage(A){return this.usage=A,this}dispose(){this.dispatchEvent({type:"dispose"})}copy(A){this.name=A.name,this.usage=A.usage;const t=A.uniforms;this.uniforms.length=0;for(let i=0,n=t.length;i<n;i++){const g=Array.isArray(t[i])?t[i]:[t[i]];for(let o=0;o<g.length;o++)this.uniforms.push(g[o].clone())}return this}clone(){return new this.constructor().copy(this)}}class MIe extends _w{constructor(A,t,i=1){super(A,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=i}copy(A){return super.copy(A),this.meshPerAttribute=A.meshPerAttribute,this}clone(A){const t=super.clone(A);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(A){const t=super.toJSON(A);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}class NIe{constructor(A,t,i,n,g,o=!1){this.isGLBufferAttribute=!0,this.name="",this.buffer=A,this.type=t,this.itemSize=i,this.elementSize=n,this.count=g,this.normalized=o,this.version=0}set needsUpdate(A){A===!0&&this.version++}setBuffer(A){return this.buffer=A,this}setType(A,t){return this.type=A,this.elementSize=t,this}setItemSize(A){return this.itemSize=A,this}setCount(A){return this.count=A,this}}const MnA=new ni;class EV{constructor(A,t,i=0,n=1/0){this.ray=new Fw(A,t),this.near=i,this.far=n,this.camera=null,this.layers=new PS,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(A,t){this.ray.set(A,t)}setFromCamera(A,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(A.x,A.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(A.x,A.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):console.error("THREE.Raycaster: Unsupported camera type: "+t.type)}setFromXRController(A){return MnA.identity().extractRotation(A.matrixWorld),this.ray.origin.setFromMatrixPosition(A.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(MnA),this}intersectObject(A,t=!0,i=[]){return c4(A,this,i,t),i.sort(NnA),i}intersectObjects(A,t=!0,i=[]){for(let n=0,g=A.length;n<g;n++)c4(A[n],this,i,t);return i.sort(NnA),i}}function NnA(e,A){return e.distance-A.distance}function c4(e,A,t,i){let n=!0;if(e.layers.test(A.layers)&&e.raycast(A,t)===!1&&(n=!1),n===!0&&i===!0){const g=e.children;for(let o=0,s=g.length;o<s;o++)c4(g[o],A,t,!0)}}class RIe{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(A){this._document=A,A.hidden!==void 0&&(this._pageVisibilityHandler=GIe.bind(this),A.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(A){return this._timescale=A,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(A){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(A!==void 0?A:performance.now())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}}function GIe(){this._document.hidden===!1&&this.reset()}class bIe{constructor(A=1,t=0,i=0){this.radius=A,this.phi=t,this.theta=i}set(A,t,i){return this.radius=A,this.phi=t,this.theta=i,this}copy(A){return this.radius=A.radius,this.phi=A.phi,this.theta=A.theta,this}makeSafe(){return this.phi=Fi(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(A){return this.setFromCartesianCoords(A.x,A.y,A.z)}setFromCartesianCoords(A,t,i){return this.radius=Math.sqrt(A*A+t*t+i*i),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(A,i),this.phi=Math.acos(Fi(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}class UIe{constructor(A=1,t=0,i=0){this.radius=A,this.theta=t,this.y=i}set(A,t,i){return this.radius=A,this.theta=t,this.y=i,this}copy(A){return this.radius=A.radius,this.theta=A.theta,this.y=A.y,this}setFromVector3(A){return this.setFromCartesianCoords(A.x,A.y,A.z)}setFromCartesianCoords(A,t,i){return this.radius=Math.sqrt(A*A+i*i),this.theta=Math.atan2(A,i),this.y=t,this}clone(){return new this.constructor().copy(this)}}class QV{constructor(A,t,i,n){QV.prototype.isMatrix2=!0,this.elements=[1,0,0,1],A!==void 0&&this.set(A,t,i,n)}identity(){return this.set(1,0,0,1),this}fromArray(A,t=0){for(let i=0;i<4;i++)this.elements[i]=A[i+t];return this}set(A,t,i,n){const g=this.elements;return g[0]=A,g[2]=t,g[1]=i,g[3]=n,this}}const RnA=new lt;class vIe{constructor(A=new lt(1/0,1/0),t=new lt(-1/0,-1/0)){this.isBox2=!0,this.min=A,this.max=t}set(A,t){return this.min.copy(A),this.max.copy(t),this}setFromPoints(A){this.makeEmpty();for(let t=0,i=A.length;t<i;t++)this.expandByPoint(A[t]);return this}setFromCenterAndSize(A,t){const i=RnA.copy(t).multiplyScalar(.5);return this.min.copy(A).sub(i),this.max.copy(A).add(i),this}clone(){return new this.constructor().copy(this)}copy(A){return this.min.copy(A.min),this.max.copy(A.max),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y}getCenter(A){return this.isEmpty()?A.set(0,0):A.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(A){return this.isEmpty()?A.set(0,0):A.subVectors(this.max,this.min)}expandByPoint(A){return this.min.min(A),this.max.max(A),this}expandByVector(A){return this.min.sub(A),this.max.add(A),this}expandByScalar(A){return this.min.addScalar(-A),this.max.addScalar(A),this}containsPoint(A){return A.x>=this.min.x&&A.x<=this.max.x&&A.y>=this.min.y&&A.y<=this.max.y}containsBox(A){return this.min.x<=A.min.x&&A.max.x<=this.max.x&&this.min.y<=A.min.y&&A.max.y<=this.max.y}getParameter(A,t){return t.set((A.x-this.min.x)/(this.max.x-this.min.x),(A.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(A){return A.max.x>=this.min.x&&A.min.x<=this.max.x&&A.max.y>=this.min.y&&A.min.y<=this.max.y}clampPoint(A,t){return t.copy(A).clamp(this.min,this.max)}distanceToPoint(A){return this.clampPoint(A,RnA).distanceTo(A)}intersect(A){return this.min.max(A.min),this.max.min(A.max),this.isEmpty()&&this.makeEmpty(),this}union(A){return this.min.min(A.min),this.max.max(A.max),this}translate(A){return this.min.add(A),this.max.add(A),this}equals(A){return A.min.equals(this.min)&&A.max.equals(this.max)}}const GnA=new SA,qU=new SA,QD=new SA,uD=new SA,KH=new SA,KIe=new SA,FIe=new SA;class _Ie{constructor(A=new SA,t=new SA){this.start=A,this.end=t}set(A,t){return this.start.copy(A),this.end.copy(t),this}copy(A){return this.start.copy(A.start),this.end.copy(A.end),this}getCenter(A){return A.addVectors(this.start,this.end).multiplyScalar(.5)}delta(A){return A.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(A,t){return this.delta(t).multiplyScalar(A).add(this.start)}closestPointToPointParameter(A,t){GnA.subVectors(A,this.start),qU.subVectors(this.end,this.start);const i=qU.dot(qU);let g=qU.dot(GnA)/i;return t&&(g=Fi(g,0,1)),g}closestPointToPoint(A,t,i){const n=this.closestPointToPointParameter(A,t);return this.delta(i).multiplyScalar(n).add(this.start)}distanceSqToLine3(A,t=KIe,i=FIe){const n=10000000000000001e-32;let g,o;const s=this.start,a=A.start,r=this.end,I=A.end;QD.subVectors(r,s),uD.subVectors(I,a),KH.subVectors(s,a);const c=QD.dot(QD),l=uD.dot(uD),B=uD.dot(KH);if(c<=n&&l<=n)return t.copy(s),i.copy(a),t.sub(i),t.dot(t);if(c<=n)g=0,o=B/l,o=Fi(o,0,1);else{const Q=QD.dot(KH);if(l<=n)o=0,g=Fi(-Q/c,0,1);else{const h=QD.dot(uD),d=c*l-h*h;d!==0?g=Fi((h*B-Q*l)/d,0,1):g=0,o=(h*g+B)/l,o<0?(o=0,g=Fi(-Q/c,0,1)):o>1&&(o=1,g=Fi((h-Q)/c,0,1))}}return t.copy(s).add(QD.multiplyScalar(g)),i.copy(a).add(uD.multiplyScalar(o)),t.sub(i),t.dot(t)}applyMatrix4(A){return this.start.applyMatrix4(A),this.end.applyMatrix4(A),this}equals(A){return A.start.equals(this.start)&&A.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const bnA=new SA;class JIe extends Bn{constructor(A,t){super(),this.light=A,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new Ni,n=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let o=0,s=1,a=32;o<a;o++,s++){const r=o/a*Math.PI*2,I=s/a*Math.PI*2;n.push(Math.cos(r),Math.sin(r),1,Math.cos(I),Math.sin(I),1)}i.setAttribute("position",new $t(n,3));const g=new es({fog:!1,toneMapped:!1});this.cone=new EI(i,g),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),this.parent?(this.parent.updateWorldMatrix(!0),this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)):this.matrix.copy(this.light.matrixWorld),this.matrixWorld.copy(this.light.matrixWorld);const A=this.light.distance?this.light.distance:1e3,t=A*Math.tan(this.light.angle);this.cone.scale.set(t,t,A),bnA.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(bnA),this.color!==void 0?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}}const TQ=new SA,YU=new ni,FH=new ni;class HyA extends EI{constructor(A){const t=OyA(A),i=new Ni,n=[],g=[];for(let r=0;r<t.length;r++){const I=t[r];I.parent&&I.parent.isBone&&(n.push(0,0,0),n.push(0,0,0),g.push(0,0,0),g.push(0,0,0))}i.setAttribute("position",new $t(n,3)),i.setAttribute("color",new $t(g,3));const o=new es({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});super(i,o),this.isSkeletonHelper=!0,this.type="SkeletonHelper",this.root=A,this.bones=t,this.matrix=A.matrixWorld,this.matrixAutoUpdate=!1;const s=new Et(255),a=new Et(65280);this.setColors(s,a)}updateMatrixWorld(A){const t=this.bones,i=this.geometry,n=i.getAttribute("position");FH.copy(this.root.matrixWorld).invert();for(let g=0,o=0;g<t.length;g++){const s=t[g];s.parent&&s.parent.isBone&&(YU.multiplyMatrices(FH,s.matrixWorld),TQ.setFromMatrixPosition(YU),n.setXYZ(o,TQ.x,TQ.y,TQ.z),YU.multiplyMatrices(FH,s.parent.matrixWorld),TQ.setFromMatrixPosition(YU),n.setXYZ(o+1,TQ.x,TQ.y,TQ.z),o+=2)}i.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(A)}setColors(A,t){const n=this.geometry.getAttribute("color");for(let g=0;g<n.count;g+=2)n.setXYZ(g,A.r,A.g,A.b),n.setXYZ(g+1,t.r,t.g,t.b);return n.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}function OyA(e){const A=[];e.isBone===!0&&A.push(e);for(let t=0;t<e.children.length;t++)A.push(...OyA(e.children[t]));return A}class LIe extends pn{constructor(A,t,i){const n=new Sf(t,4,2),g=new kg({wireframe:!0,fog:!1,toneMapped:!1});super(n,g),this.light=A,this.color=i,this.type="PointLightHelper",this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1,this.update()}dispose(){this.geometry.dispose(),this.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.color!==void 0?this.material.color.set(this.color):this.material.color.copy(this.light.color)}}const xIe=new SA,UnA=new Et,vnA=new Et;class TIe extends Bn{constructor(A,t,i){super(),this.light=A,this.matrix=A.matrixWorld,this.matrixAutoUpdate=!1,this.color=i,this.type="HemisphereLightHelper";const n=new lG(t);n.rotateY(Math.PI*.5),this.material=new kg({wireframe:!0,fog:!1,toneMapped:!1}),this.color===void 0&&(this.material.vertexColors=!0);const g=n.getAttribute("position"),o=new Float32Array(g.count*3);n.setAttribute("color",new ji(o,3)),this.add(new pn(n,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){const A=this.children[0];if(this.color!==void 0)this.material.color.set(this.color);else{const t=A.geometry.getAttribute("color");UnA.copy(this.light.color),vnA.copy(this.light.groundColor);for(let i=0,n=t.count;i<n;i++){const g=i<n/2?UnA:vnA;t.setXYZ(i,g.r,g.g,g.b)}t.needsUpdate=!0}this.light.updateWorldMatrix(!0,!1),A.lookAt(xIe.setFromMatrixPosition(this.light.matrixWorld).negate())}}class qIe extends EI{constructor(A=10,t=10,i=4473924,n=8947848){i=new Et(i),n=new Et(n);const g=t/2,o=A/t,s=A/2,a=[],r=[];for(let l=0,B=0,Q=-s;l<=t;l++,Q+=o){a.push(-s,0,Q,s,0,Q),a.push(Q,0,-s,Q,0,s);const h=l===g?i:n;h.toArray(r,B),B+=3,h.toArray(r,B),B+=3,h.toArray(r,B),B+=3,h.toArray(r,B),B+=3}const I=new Ni;I.setAttribute("position",new $t(a,3)),I.setAttribute("color",new $t(r,3));const c=new es({vertexColors:!0,toneMapped:!1});super(I,c),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class YIe extends EI{constructor(A=10,t=16,i=8,n=64,g=4473924,o=8947848){g=new Et(g),o=new Et(o);const s=[],a=[];if(t>1)for(let c=0;c<t;c++){const l=c/t*(Math.PI*2),B=Math.sin(l)*A,Q=Math.cos(l)*A;s.push(0,0,0),s.push(B,0,Q);const h=c&1?g:o;a.push(h.r,h.g,h.b),a.push(h.r,h.g,h.b)}for(let c=0;c<i;c++){const l=c&1?g:o,B=A-A/i*c;for(let Q=0;Q<n;Q++){let h=Q/n*(Math.PI*2),d=Math.sin(h)*B,p=Math.cos(h)*B;s.push(d,0,p),a.push(l.r,l.g,l.b),h=(Q+1)/n*(Math.PI*2),d=Math.sin(h)*B,p=Math.cos(h)*B,s.push(d,0,p),a.push(l.r,l.g,l.b)}}const r=new Ni;r.setAttribute("position",new $t(s,3)),r.setAttribute("color",new $t(a,3));const I=new es({vertexColors:!0,toneMapped:!1});super(r,I),this.type="PolarGridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}const KnA=new SA,HU=new SA,FnA=new SA;class HIe extends Bn{constructor(A,t,i){super(),this.light=A,this.matrix=A.matrixWorld,this.matrixAutoUpdate=!1,this.color=i,this.type="DirectionalLightHelper",t===void 0&&(t=1);let n=new Ni;n.setAttribute("position",new $t([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));const g=new es({fog:!1,toneMapped:!1});this.lightPlane=new yB(n,g),this.add(this.lightPlane),n=new Ni,n.setAttribute("position",new $t([0,0,0,0,0,1],3)),this.targetLine=new yB(n,g),this.add(this.targetLine),this.update()}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),KnA.setFromMatrixPosition(this.light.matrixWorld),HU.setFromMatrixPosition(this.light.target.matrixWorld),FnA.subVectors(HU,KnA),this.lightPlane.lookAt(HU),this.color!==void 0?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color)),this.targetLine.lookAt(HU),this.targetLine.scale.z=FnA.length()}}const OU=new SA,bo=new Ox;class OIe extends EI{constructor(A){const t=new Ni,i=new es({color:16777215,vertexColors:!0,toneMapped:!1}),n=[],g=[],o={};s("n1","n2"),s("n2","n4"),s("n4","n3"),s("n3","n1"),s("f1","f2"),s("f2","f4"),s("f4","f3"),s("f3","f1"),s("n1","f1"),s("n2","f2"),s("n3","f3"),s("n4","f4"),s("p","n1"),s("p","n2"),s("p","n3"),s("p","n4"),s("u1","u2"),s("u2","u3"),s("u3","u1"),s("c","t"),s("p","c"),s("cn1","cn2"),s("cn3","cn4"),s("cf1","cf2"),s("cf3","cf4");function s(Q,h){a(Q),a(h)}function a(Q){n.push(0,0,0),g.push(0,0,0),o[Q]===void 0&&(o[Q]=[]),o[Q].push(n.length/3-1)}t.setAttribute("position",new $t(n,3)),t.setAttribute("color",new $t(g,3)),super(t,i),this.type="CameraHelper",this.camera=A,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=A.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=o,this.update();const r=new Et(16755200),I=new Et(16711680),c=new Et(43775),l=new Et(16777215),B=new Et(3355443);this.setColors(r,I,c,l,B)}setColors(A,t,i,n,g){const s=this.geometry.getAttribute("color");return s.setXYZ(0,A.r,A.g,A.b),s.setXYZ(1,A.r,A.g,A.b),s.setXYZ(2,A.r,A.g,A.b),s.setXYZ(3,A.r,A.g,A.b),s.setXYZ(4,A.r,A.g,A.b),s.setXYZ(5,A.r,A.g,A.b),s.setXYZ(6,A.r,A.g,A.b),s.setXYZ(7,A.r,A.g,A.b),s.setXYZ(8,A.r,A.g,A.b),s.setXYZ(9,A.r,A.g,A.b),s.setXYZ(10,A.r,A.g,A.b),s.setXYZ(11,A.r,A.g,A.b),s.setXYZ(12,A.r,A.g,A.b),s.setXYZ(13,A.r,A.g,A.b),s.setXYZ(14,A.r,A.g,A.b),s.setXYZ(15,A.r,A.g,A.b),s.setXYZ(16,A.r,A.g,A.b),s.setXYZ(17,A.r,A.g,A.b),s.setXYZ(18,A.r,A.g,A.b),s.setXYZ(19,A.r,A.g,A.b),s.setXYZ(20,A.r,A.g,A.b),s.setXYZ(21,A.r,A.g,A.b),s.setXYZ(22,A.r,A.g,A.b),s.setXYZ(23,A.r,A.g,A.b),s.setXYZ(24,t.r,t.g,t.b),s.setXYZ(25,t.r,t.g,t.b),s.setXYZ(26,t.r,t.g,t.b),s.setXYZ(27,t.r,t.g,t.b),s.setXYZ(28,t.r,t.g,t.b),s.setXYZ(29,t.r,t.g,t.b),s.setXYZ(30,t.r,t.g,t.b),s.setXYZ(31,t.r,t.g,t.b),s.setXYZ(32,i.r,i.g,i.b),s.setXYZ(33,i.r,i.g,i.b),s.setXYZ(34,i.r,i.g,i.b),s.setXYZ(35,i.r,i.g,i.b),s.setXYZ(36,i.r,i.g,i.b),s.setXYZ(37,i.r,i.g,i.b),s.setXYZ(38,n.r,n.g,n.b),s.setXYZ(39,n.r,n.g,n.b),s.setXYZ(40,g.r,g.g,g.b),s.setXYZ(41,g.r,g.g,g.b),s.setXYZ(42,g.r,g.g,g.b),s.setXYZ(43,g.r,g.g,g.b),s.setXYZ(44,g.r,g.g,g.b),s.setXYZ(45,g.r,g.g,g.b),s.setXYZ(46,g.r,g.g,g.b),s.setXYZ(47,g.r,g.g,g.b),s.setXYZ(48,g.r,g.g,g.b),s.setXYZ(49,g.r,g.g,g.b),s.needsUpdate=!0,this}update(){const A=this.geometry,t=this.pointMap,i=1,n=1;let g,o;if(bo.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),this.camera.reversedDepth===!0)g=1,o=0;else if(this.camera.coordinateSystem===jI)g=-1,o=1;else if(this.camera.coordinateSystem===HS)g=0,o=1;else throw new Error("THREE.CameraHelper.update(): Invalid coordinate system: "+this.camera.coordinateSystem);Oo("c",t,A,bo,0,0,g),Oo("t",t,A,bo,0,0,o),Oo("n1",t,A,bo,-i,-n,g),Oo("n2",t,A,bo,i,-n,g),Oo("n3",t,A,bo,-i,n,g),Oo("n4",t,A,bo,i,n,g),Oo("f1",t,A,bo,-i,-n,o),Oo("f2",t,A,bo,i,-n,o),Oo("f3",t,A,bo,-i,n,o),Oo("f4",t,A,bo,i,n,o),Oo("u1",t,A,bo,i*.7,n*1.1,g),Oo("u2",t,A,bo,-i*.7,n*1.1,g),Oo("u3",t,A,bo,0,n*2,g),Oo("cf1",t,A,bo,-i,0,o),Oo("cf2",t,A,bo,i,0,o),Oo("cf3",t,A,bo,0,-n,o),Oo("cf4",t,A,bo,0,n,o),Oo("cn1",t,A,bo,-i,0,g),Oo("cn2",t,A,bo,i,0,g),Oo("cn3",t,A,bo,0,-n,g),Oo("cn4",t,A,bo,0,n,g),A.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}}function Oo(e,A,t,i,n,g,o){OU.set(n,g,o).unproject(i);const s=A[e];if(s!==void 0){const a=t.getAttribute("position");for(let r=0,I=s.length;r<I;r++)a.setXYZ(s[r],OU.x,OU.y,OU.z)}}const PU=new Ag;class PIe extends EI{constructor(A,t=16776960){const i=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),n=new Float32Array(8*3),g=new Ni;g.setIndex(new ji(i,1)),g.setAttribute("position",new ji(n,3)),super(g,new es({color:t,toneMapped:!1})),this.object=A,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(){if(this.object!==void 0&&PU.setFromObject(this.object),PU.isEmpty())return;const A=PU.min,t=PU.max,i=this.geometry.attributes.position,n=i.array;n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=A.x,n[4]=t.y,n[5]=t.z,n[6]=A.x,n[7]=A.y,n[8]=t.z,n[9]=t.x,n[10]=A.y,n[11]=t.z,n[12]=t.x,n[13]=t.y,n[14]=A.z,n[15]=A.x,n[16]=t.y,n[17]=A.z,n[18]=A.x,n[19]=A.y,n[20]=A.z,n[21]=t.x,n[22]=A.y,n[23]=A.z,i.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(A){return this.object=A,this.update(),this}copy(A,t){return super.copy(A,t),this.object=A.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class jIe extends EI{constructor(A,t=16776960){const i=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),n=[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],g=new Ni;g.setIndex(new ji(i,1)),g.setAttribute("position",new $t(n,3)),super(g,new es({color:t,toneMapped:!1})),this.box=A,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(A){const t=this.box;t.isEmpty()||(t.getCenter(this.position),t.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(A))}dispose(){this.geometry.dispose(),this.material.dispose()}}class zIe extends yB{constructor(A,t=1,i=16776960){const n=i,g=[1,-1,0,-1,1,0,-1,-1,0,1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],o=new Ni;o.setAttribute("position",new $t(g,3)),o.computeBoundingSphere(),super(o,new es({color:n,toneMapped:!1})),this.type="PlaneHelper",this.plane=A,this.size=t;const s=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],a=new Ni;a.setAttribute("position",new $t(s,3)),a.computeBoundingSphere(),this.add(new pn(a,new kg({color:n,opacity:.2,transparent:!0,depthWrite:!1,toneMapped:!1})))}updateMatrixWorld(A){this.position.set(0,0,0),this.scale.set(.5*this.size,.5*this.size,1),this.lookAt(this.plane.normal),this.translateZ(-this.plane.constant),super.updateMatrixWorld(A)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}}const _nA=new SA;let jU,_H;class ZIe extends Bn{constructor(A=new SA(0,0,1),t=new SA(0,0,0),i=1,n=16776960,g=i*.2,o=g*.2){super(),this.type="ArrowHelper",jU===void 0&&(jU=new Ni,jU.setAttribute("position",new $t([0,0,0,0,1,0],3)),_H=new cG(.5,1,5,1),_H.translate(0,-.5,0)),this.position.copy(t),this.line=new yB(jU,new es({color:n,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new pn(_H,new kg({color:n,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(A),this.setLength(i,g,o)}setDirection(A){if(A.y>.99999)this.quaternion.set(0,0,0,1);else if(A.y<-.99999)this.quaternion.set(1,0,0,0);else{_nA.set(A.z,0,-A.x).normalize();const t=Math.acos(A.y);this.quaternion.setFromAxisAngle(_nA,t)}}setLength(A,t=A*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,A-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=A,this.cone.updateMatrix()}setColor(A){this.line.material.color.set(A),this.cone.material.color.set(A)}copy(A){return super.copy(A,!1),this.line.copy(A.line),this.cone.copy(A.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class WIe extends EI{constructor(A=1){const t=[0,0,0,A,0,0,0,0,0,0,A,0,0,0,0,0,0,A],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],n=new Ni;n.setAttribute("position",new $t(t,3)),n.setAttribute("color",new $t(i,3));const g=new es({vertexColors:!0,toneMapped:!1});super(n,g),this.type="AxesHelper"}setColors(A,t,i){const n=new Et,g=this.geometry.attributes.color.array;return n.set(A),n.toArray(g,0),n.toArray(g,3),n.set(t),n.toArray(g,6),n.toArray(g,9),n.set(i),n.toArray(g,12),n.toArray(g,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class VIe{constructor(){this.type="ShapePath",this.color=new Et,this.subPaths=[],this.currentPath=null}moveTo(A,t){return this.currentPath=new DJ,this.subPaths.push(this.currentPath),this.currentPath.moveTo(A,t),this}lineTo(A,t){return this.currentPath.lineTo(A,t),this}quadraticCurveTo(A,t,i,n){return this.currentPath.quadraticCurveTo(A,t,i,n),this}bezierCurveTo(A,t,i,n,g,o){return this.currentPath.bezierCurveTo(A,t,i,n,g,o),this}splineThru(A){return this.currentPath.splineThru(A),this}toShapes(A){function t(p){const y=[];for(let m=0,D=p.length;m<D;m++){const S=p[m],k=new jp;k.curves=S.curves,y.push(k)}return y}function i(p,y){const m=y.length;let D=!1;for(let S=m-1,k=0;k<m;S=k++){let N=y[S],G=y[k],M=G.x-N.x,w=G.y-N.y;if(Math.abs(w)>Number.EPSILON){if(w<0&&(N=y[k],M=-M,G=y[S],w=-w),p.y<N.y||p.y>G.y)continue;if(p.y===N.y){if(p.x===N.x)return!0}else{const b=w*(p.x-N.x)-M*(p.y-N.y);if(b===0)return!0;if(b<0)continue;D=!D}}else{if(p.y!==N.y)continue;if(G.x<=p.x&&p.x<=N.x||N.x<=p.x&&p.x<=G.x)return!0}}return D}const n=zc.isClockWise,g=this.subPaths;if(g.length===0)return[];let o,s,a;const r=[];if(g.length===1)return s=g[0],a=new jp,a.curves=s.curves,r.push(a),r;let I=!n(g[0].getPoints());I=A?!I:I;const c=[],l=[];let B=[],Q=0,h;l[Q]=void 0,B[Q]=[];for(let p=0,y=g.length;p<y;p++)s=g[p],h=s.getPoints(),o=n(h),o=A?!o:o,o?(!I&&l[Q]&&Q++,l[Q]={s:new jp,p:h},l[Q].s.curves=s.curves,I&&Q++,B[Q]=[]):B[Q].push({h:s,p:h[0]});if(!l[0])return t(g);if(l.length>1){let p=!1,y=0;for(let m=0,D=l.length;m<D;m++)c[m]=[];for(let m=0,D=l.length;m<D;m++){const S=B[m];for(let k=0;k<S.length;k++){const N=S[k];let G=!0;for(let M=0;M<l.length;M++)i(N.p,l[M].p)&&(m!==M&&y++,G?(G=!1,c[M].push(N)):p=!0);G&&c[m].push(N)}}y>0&&p===!1&&(B=c)}let d;for(let p=0,y=l.length;p<y;p++){a=l[p].s,r.push(a),d=B[p];for(let m=0,D=d.length;m<D;m++)a.holes.push(d[m].h)}return r}}class XIe extends bB{constructor(A,t=null){super(),this.object=A,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(A){if(A===void 0){console.warn("THREE.Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=A}disconnect(){}dispose(){}update(){}}function $Ie(e,A){const t=e.image&&e.image.width?e.image.width/e.image.height:1;return t>A?(e.repeat.x=1,e.repeat.y=t/A,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2):(e.repeat.x=A/t,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0),e}function ACe(e,A){const t=e.image&&e.image.width?e.image.width/e.image.height:1;return t>A?(e.repeat.x=A/t,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0):(e.repeat.x=1,e.repeat.y=t/A,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2),e}function eCe(e){return e.repeat.x=1,e.repeat.y=1,e.offset.x=0,e.offset.y=0,e}function l4(e,A,t,i){const n=tCe(i);switch(t){case GW:return e*A;case Lx:return e*A/n.components*n.byteLength;case gG:return e*A/n.components*n.byteLength;case UW:return e*A*2/n.components*n.byteLength;case xx:return e*A*2/n.components*n.byteLength;case bW:return e*A*3/n.components*n.byteLength;case Ar:return e*A*4/n.components*n.byteLength;case Tx:return e*A*4/n.components*n.byteLength;case DM:case mM:return Math.floor((e+3)/4)*Math.floor((A+3)/4)*8;case SM:case wM:return Math.floor((e+3)/4)*Math.floor((A+3)/4)*16;case O_:case j_:return Math.max(e,16)*Math.max(A,8)/4;case H_:case P_:return Math.max(e,8)*Math.max(A,8)/2;case z_:case Z_:return Math.floor((e+3)/4)*Math.floor((A+3)/4)*8;case W_:return Math.floor((e+3)/4)*Math.floor((A+3)/4)*16;case V_:return Math.floor((e+3)/4)*Math.floor((A+3)/4)*16;case X_:return Math.floor((e+4)/5)*Math.floor((A+3)/4)*16;case $_:return Math.floor((e+4)/5)*Math.floor((A+4)/5)*16;case AJ:return Math.floor((e+5)/6)*Math.floor((A+4)/5)*16;case eJ:return Math.floor((e+5)/6)*Math.floor((A+5)/6)*16;case tJ:return Math.floor((e+7)/8)*Math.floor((A+4)/5)*16;case iJ:return Math.floor((e+7)/8)*Math.floor((A+5)/6)*16;case nJ:return Math.floor((e+7)/8)*Math.floor((A+7)/8)*16;case gJ:return Math.floor((e+9)/10)*Math.floor((A+4)/5)*16;case oJ:return Math.floor((e+9)/10)*Math.floor((A+5)/6)*16;case sJ:return Math.floor((e+9)/10)*Math.floor((A+7)/8)*16;case aJ:return Math.floor((e+9)/10)*Math.floor((A+9)/10)*16;case rJ:return Math.floor((e+11)/12)*Math.floor((A+9)/10)*16;case IJ:return Math.floor((e+11)/12)*Math.floor((A+11)/12)*16;case CJ:case cJ:case lJ:return Math.ceil(e/4)*Math.ceil(A/4)*16;case BJ:case EJ:return Math.ceil(e/4)*Math.ceil(A/4)*8;case QJ:case uJ:return Math.ceil(e/4)*Math.ceil(A/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function tCe(e){switch(e){case Ic:case kW:return{byteLength:1,components:1};case xS:case MW:case ny:return{byteLength:2,components:1};case _x:case Jx:return{byteLength:2,components:4};case IQ:case Fx:case br:return{byteLength:4,components:1};case NW:case RW:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}class iCe{static contain(A,t){return $Ie(A,t)}static cover(A,t){return ACe(A,t)}static fill(A){return eCe(A)}static getByteLength(A,t,i,n){return l4(A,t,i,n)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:tG}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=tG);/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */function PyA(){let e=null,A=!1,t=null,i=null;function n(g,o){t(g,o),i=e.requestAnimationFrame(n)}return{start:function(){A!==!0&&t!==null&&(i=e.requestAnimationFrame(n),A=!0)},stop:function(){e.cancelAnimationFrame(i),A=!1},setAnimationLoop:function(g){t=g},setContext:function(g){e=g}}}function nCe(e){const A=new WeakMap;function t(s,a){const r=s.array,I=s.usage,c=r.byteLength,l=e.createBuffer();e.bindBuffer(a,l),e.bufferData(a,r,I),s.onUploadCallback();let B;if(r instanceof Float32Array)B=e.FLOAT;else if(typeof Float16Array<"u"&&r instanceof Float16Array)B=e.HALF_FLOAT;else if(r instanceof Uint16Array)s.isFloat16BufferAttribute?B=e.HALF_FLOAT:B=e.UNSIGNED_SHORT;else if(r instanceof Int16Array)B=e.SHORT;else if(r instanceof Uint32Array)B=e.UNSIGNED_INT;else if(r instanceof Int32Array)B=e.INT;else if(r instanceof Int8Array)B=e.BYTE;else if(r instanceof Uint8Array)B=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)B=e.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+r);return{buffer:l,type:B,bytesPerElement:r.BYTES_PER_ELEMENT,version:s.version,size:c}}function i(s,a,r){const I=a.array,c=a.updateRanges;if(e.bindBuffer(r,s),c.length===0)e.bufferSubData(r,0,I);else{c.sort((B,Q)=>B.start-Q.start);let l=0;for(let B=1;B<c.length;B++){const Q=c[l],h=c[B];h.start<=Q.start+Q.count+1?Q.count=Math.max(Q.count,h.start+h.count-Q.start):(++l,c[l]=h)}c.length=l+1;for(let B=0,Q=c.length;B<Q;B++){const h=c[B];e.bufferSubData(r,h.start*I.BYTES_PER_ELEMENT,I,h.start,h.count)}a.clearUpdateRanges()}a.onUploadCallback()}function n(s){return s.isInterleavedBufferAttribute&&(s=s.data),A.get(s)}function g(s){s.isInterleavedBufferAttribute&&(s=s.data);const a=A.get(s);a&&(e.deleteBuffer(a.buffer),A.delete(s))}function o(s,a){if(s.isInterleavedBufferAttribute&&(s=s.data),s.isGLBufferAttribute){const I=A.get(s);(!I||I.version<s.version)&&A.set(s,{buffer:s.buffer,type:s.type,bytesPerElement:s.elementSize,version:s.version});return}const r=A.get(s);if(r===void 0)A.set(s,t(s,a));else if(r.version<s.version){if(r.size!==s.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");i(r.buffer,s,a),r.version=s.version}}return{get:n,remove:g,update:o}}var gCe=`#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,oCe=`#ifdef USE_ALPHAHASH
	const float ALPHA_HASH_SCALE = 0.05;
	float hash2D( vec2 value ) {
		return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
	}
	float hash3D( vec3 value ) {
		return hash2D( vec2( hash2D( value.xy ), value.z ) );
	}
	float getAlphaHashThreshold( vec3 position ) {
		float maxDeriv = max(
			length( dFdx( position.xyz ) ),
			length( dFdy( position.xyz ) )
		);
		float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
		vec2 pixScales = vec2(
			exp2( floor( log2( pixScale ) ) ),
			exp2( ceil( log2( pixScale ) ) )
		);
		vec2 alpha = vec2(
			hash3D( floor( pixScales.x * position.xyz ) ),
			hash3D( floor( pixScales.y * position.xyz ) )
		);
		float lerpFactor = fract( log2( pixScale ) );
		float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
		float a = min( lerpFactor, 1.0 - lerpFactor );
		vec3 cases = vec3(
			x * x / ( 2.0 * a * ( 1.0 - a ) ),
			( x - 0.5 * a ) / ( 1.0 - a ),
			1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
		);
		float threshold = ( x < ( 1.0 - a ) )
			? ( ( x < a ) ? cases.x : cases.y )
			: cases.z;
		return clamp( threshold , 1.0e-6, 1.0 );
	}
#endif`,sCe=`#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`,aCe=`#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,rCe=`#ifdef USE_ALPHATEST
	#ifdef ALPHA_TO_COVERAGE
	diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
	if ( diffuseColor.a == 0.0 ) discard;
	#else
	if ( diffuseColor.a < alphaTest ) discard;
	#endif
#endif`,ICe=`#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`,CCe=`#ifdef USE_AOMAP
	float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
	reflectedLight.indirectDiffuse *= ambientOcclusion;
	#if defined( USE_CLEARCOAT ) 
		clearcoatSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_SHEEN ) 
		sheenSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD )
		float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
		reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
	#endif
#endif`,cCe=`#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`,lCe=`#ifdef USE_BATCHING
	#if ! defined( GL_ANGLE_multi_draw )
	#define gl_DrawID _gl_DrawID
	uniform int _gl_DrawID;
	#endif
	uniform highp sampler2D batchingTexture;
	uniform highp usampler2D batchingIdTexture;
	mat4 getBatchingMatrix( const in float i ) {
		int size = textureSize( batchingTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
	float getIndirectIndex( const in int i ) {
		int size = textureSize( batchingIdTexture, 0 ).x;
		int x = i % size;
		int y = i / size;
		return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
	}
#endif
#ifdef USE_BATCHING_COLOR
	uniform sampler2D batchingColorTexture;
	vec3 getBatchingColor( const in float i ) {
		int size = textureSize( batchingColorTexture, 0 ).x;
		int j = int( i );
		int x = j % size;
		int y = j / size;
		return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
	}
#endif`,BCe=`#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`,ECe=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`,QCe=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`,uCe=`float G_BlinnPhong_Implicit( ) {
	return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
	return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( specularColor, 1.0, dotVH );
	float G = G_BlinnPhong_Implicit( );
	float D = D_BlinnPhong( shininess, dotNH );
	return F * ( G * D );
} // validated`,dCe=`#ifdef USE_IRIDESCENCE
	const mat3 XYZ_TO_REC709 = mat3(
		 3.2404542, -0.9692660,  0.0556434,
		-1.5371385,  1.8760108, -0.2040259,
		-0.4985314,  0.0415560,  1.0572252
	);
	vec3 Fresnel0ToIor( vec3 fresnel0 ) {
		vec3 sqrtF0 = sqrt( fresnel0 );
		return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
	}
	vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
	}
	float IorToFresnel0( float transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
	}
	vec3 evalSensitivity( float OPD, vec3 shift ) {
		float phase = 2.0 * PI * OPD * 1.0e-9;
		vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
		vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
		vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
		vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
		xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
		xyz /= 1.0685e-7;
		vec3 rgb = XYZ_TO_REC709 * xyz;
		return rgb;
	}
	vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
		vec3 I;
		float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
		float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
		float cosTheta2Sq = 1.0 - sinTheta2Sq;
		if ( cosTheta2Sq < 0.0 ) {
			return vec3( 1.0 );
		}
		float cosTheta2 = sqrt( cosTheta2Sq );
		float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
		float R12 = F_Schlick( R0, 1.0, cosTheta1 );
		float T121 = 1.0 - R12;
		float phi12 = 0.0;
		if ( iridescenceIOR < outsideIOR ) phi12 = PI;
		float phi21 = PI - phi12;
		vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );		vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
		vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
		vec3 phi23 = vec3( 0.0 );
		if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
		if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
		if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
		float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
		vec3 phi = vec3( phi21 ) + phi23;
		vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
		vec3 r123 = sqrt( R123 );
		vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
		vec3 C0 = R12 + Rs;
		I = C0;
		vec3 Cm = Rs - T121;
		for ( int m = 1; m <= 2; ++ m ) {
			Cm *= r123;
			vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
			I += Cm * Sm;
		}
		return max( I, vec3( 0.0 ) );
	}
#endif`,hCe=`#ifdef USE_BUMPMAP
	uniform sampler2D bumpMap;
	uniform float bumpScale;
	vec2 dHdxy_fwd() {
		vec2 dSTdx = dFdx( vBumpMapUv );
		vec2 dSTdy = dFdy( vBumpMapUv );
		float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
		float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
		float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
		return vec2( dBx, dBy );
	}
	vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
		vec3 vN = surf_norm;
		vec3 R1 = cross( vSigmaY, vN );
		vec3 R2 = cross( vN, vSigmaX );
		float fDet = dot( vSigmaX, R1 ) * faceDirection;
		vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
		return normalize( abs( fDet ) * surf_norm - vGrad );
	}
#endif`,pCe=`#if NUM_CLIPPING_PLANES > 0
	vec4 plane;
	#ifdef ALPHA_TO_COVERAGE
		float distanceToPlane, distanceGradient;
		float clipOpacity = 1.0;
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
			distanceGradient = fwidth( distanceToPlane ) / 2.0;
			clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			if ( clipOpacity == 0.0 ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			float unionClipOpacity = 1.0;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
				distanceGradient = fwidth( distanceToPlane ) / 2.0;
				unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			}
			#pragma unroll_loop_end
			clipOpacity *= 1.0 - unionClipOpacity;
		#endif
		diffuseColor.a *= clipOpacity;
		if ( diffuseColor.a == 0.0 ) discard;
	#else
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			bool clipped = true;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
			}
			#pragma unroll_loop_end
			if ( clipped ) discard;
		#endif
	#endif
#endif`,fCe=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,yCe=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`,DCe=`#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`,mCe=`#if defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#elif defined( USE_COLOR )
	diffuseColor.rgb *= vColor;
#endif`,SCe=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR )
	varying vec3 vColor;
#endif`,wCe=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	varying vec3 vColor;
#endif`,kCe=`#if defined( USE_COLOR_ALPHA )
	vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	vColor = vec3( 1.0 );
#endif
#ifdef USE_COLOR
	vColor *= color;
#endif
#ifdef USE_INSTANCING_COLOR
	vColor.xyz *= instanceColor.xyz;
#endif
#ifdef USE_BATCHING_COLOR
	vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
	vColor.xyz *= batchingColor.xyz;
#endif`,MCe=`#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
	const highp float a = 12.9898, b = 78.233, c = 43758.5453;
	highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
	return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
	float precisionSafeLength( vec3 v ) { return length( v ); }
#else
	float precisionSafeLength( vec3 v ) {
		float maxComponent = max3( abs( v ) );
		return length( v / maxComponent ) * maxComponent;
	}
#endif
struct IncidentLight {
	vec3 color;
	vec3 direction;
	bool visible;
};
struct ReflectedLight {
	vec3 directDiffuse;
	vec3 directSpecular;
	vec3 indirectDiffuse;
	vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
	varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
mat3 transposeMat3( const in mat3 m ) {
	mat3 tmp;
	tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
	tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
	tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
	return tmp;
}
bool isPerspectiveMatrix( mat4 m ) {
	return m[ 2 ][ 3 ] == - 1.0;
}
vec2 equirectUv( in vec3 dir ) {
	float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
	float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
	return vec2( u, v );
}
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
	return RECIPROCAL_PI * diffuseColor;
}
vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
}
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
} // validated`,NCe=`#ifdef ENVMAP_TYPE_CUBE_UV
	#define cubeUV_minMipLevel 4.0
	#define cubeUV_minTileSize 16.0
	float getFace( vec3 direction ) {
		vec3 absDirection = abs( direction );
		float face = - 1.0;
		if ( absDirection.x > absDirection.z ) {
			if ( absDirection.x > absDirection.y )
				face = direction.x > 0.0 ? 0.0 : 3.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		} else {
			if ( absDirection.z > absDirection.y )
				face = direction.z > 0.0 ? 2.0 : 5.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		}
		return face;
	}
	vec2 getUV( vec3 direction, float face ) {
		vec2 uv;
		if ( face == 0.0 ) {
			uv = vec2( direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 1.0 ) {
			uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
		} else if ( face == 2.0 ) {
			uv = vec2( - direction.x, direction.y ) / abs( direction.z );
		} else if ( face == 3.0 ) {
			uv = vec2( - direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 4.0 ) {
			uv = vec2( - direction.x, direction.z ) / abs( direction.y );
		} else {
			uv = vec2( direction.x, direction.y ) / abs( direction.z );
		}
		return 0.5 * ( uv + 1.0 );
	}
	vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
		float face = getFace( direction );
		float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
		mipInt = max( mipInt, cubeUV_minMipLevel );
		float faceSize = exp2( mipInt );
		highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
		if ( face > 2.0 ) {
			uv.y += faceSize;
			face -= 3.0;
		}
		uv.x += face * faceSize;
		uv.x += filterInt * 3.0 * cubeUV_minTileSize;
		uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
		uv.x *= CUBEUV_TEXEL_WIDTH;
		uv.y *= CUBEUV_TEXEL_HEIGHT;
		#ifdef texture2DGradEXT
			return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
		#else
			return texture2D( envMap, uv ).rgb;
		#endif
	}
	#define cubeUV_r0 1.0
	#define cubeUV_m0 - 2.0
	#define cubeUV_r1 0.8
	#define cubeUV_m1 - 1.0
	#define cubeUV_r4 0.4
	#define cubeUV_m4 2.0
	#define cubeUV_r5 0.305
	#define cubeUV_m5 3.0
	#define cubeUV_r6 0.21
	#define cubeUV_m6 4.0
	float roughnessToMip( float roughness ) {
		float mip = 0.0;
		if ( roughness >= cubeUV_r1 ) {
			mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
		} else if ( roughness >= cubeUV_r4 ) {
			mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
		} else if ( roughness >= cubeUV_r5 ) {
			mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
		} else if ( roughness >= cubeUV_r6 ) {
			mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
		} else {
			mip = - 2.0 * log2( 1.16 * roughness );		}
		return mip;
	}
	vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
		float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
		float mipF = fract( mip );
		float mipInt = floor( mip );
		vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
		if ( mipF == 0.0 ) {
			return vec4( color0, 1.0 );
		} else {
			vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
			return vec4( mix( color0, color1, mipF ), 1.0 );
		}
	}
#endif`,RCe=`vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
	vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
	mat3 bm = mat3( batchingMatrix );
	transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
	transformedNormal = bm * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = bm * transformedTangent;
	#endif
#endif
#ifdef USE_INSTANCING
	mat3 im = mat3( instanceMatrix );
	transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
	transformedNormal = im * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = im * transformedTangent;
	#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
	transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
	transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
	#ifdef FLIP_SIDED
		transformedTangent = - transformedTangent;
	#endif
#endif`,GCe=`#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`,bCe=`#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,UCe=`#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
		emissiveColor = sRGBTransferEOTF( emissiveColor );
	#endif
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,vCe=`#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`,KCe="gl_FragColor = linearToOutputTexel( gl_FragColor );",FCe=`vec4 LinearTransferOETF( in vec4 value ) {
	return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
	return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
}
vec4 sRGBTransferOETF( in vec4 value ) {
	return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
}`,_Ce=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vec3 cameraToFrag;
		if ( isOrthographic ) {
			cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToFrag = normalize( vWorldPosition - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vec3 reflectVec = reflect( cameraToFrag, worldNormal );
		#else
			vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
		#endif
	#else
		vec3 reflectVec = vReflect;
	#endif
	#ifdef ENVMAP_TYPE_CUBE
		vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
	#else
		vec4 envColor = vec4( 0.0 );
	#endif
	#ifdef ENVMAP_BLENDING_MULTIPLY
		outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_MIX )
		outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_ADD )
		outgoingLight += envColor.xyz * specularStrength * reflectivity;
	#endif
#endif`,JCe=`#ifdef USE_ENVMAP
	uniform float envMapIntensity;
	uniform float flipEnvMap;
	uniform mat3 envMapRotation;
	#ifdef ENVMAP_TYPE_CUBE
		uniform samplerCube envMap;
	#else
		uniform sampler2D envMap;
	#endif
	
#endif`,LCe=`#ifdef USE_ENVMAP
	uniform float reflectivity;
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		varying vec3 vWorldPosition;
		uniform float refractionRatio;
	#else
		varying vec3 vReflect;
	#endif
#endif`,xCe=`#ifdef USE_ENVMAP
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		
		varying vec3 vWorldPosition;
	#else
		varying vec3 vReflect;
		uniform float refractionRatio;
	#endif
#endif`,TCe=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vWorldPosition = worldPosition.xyz;
	#else
		vec3 cameraToVertex;
		if ( isOrthographic ) {
			cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vReflect = reflect( cameraToVertex, worldNormal );
		#else
			vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
		#endif
	#endif
#endif`,qCe=`#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`,YCe=`#ifdef USE_FOG
	varying float vFogDepth;
#endif`,HCe=`#ifdef USE_FOG
	#ifdef FOG_EXP2
		float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
	#else
		float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
	#endif
	gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
#endif`,OCe=`#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`,PCe=`#ifdef USE_GRADIENTMAP
	uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
	float dotNL = dot( normal, lightDirection );
	vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
	#ifdef USE_GRADIENTMAP
		return vec3( texture2D( gradientMap, coord ).r );
	#else
		vec2 fw = fwidth( coord ) * 0.5;
		return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
	#endif
}`,jCe=`#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`,zCe=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,ZCe=`varying vec3 vViewPosition;
struct LambertMaterial {
	vec3 diffuseColor;
	float specularStrength;
};
void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Lambert
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Lambert`,WCe=`uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
	uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
	float x = normal.x, y = normal.y, z = normal.z;
	vec3 result = shCoefficients[ 0 ] * 0.886227;
	result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
	result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
	result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
	result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
	result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
	result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
	result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
	result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
	return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
	vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
	vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
	return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
	vec3 irradiance = ambientLightColor;
	return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
	float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
	if ( cutoffDistance > 0.0 ) {
		distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
	}
	return distanceFalloff;
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
	return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
	struct DirectionalLight {
		vec3 direction;
		vec3 color;
	};
	uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
	void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
		light.color = directionalLight.color;
		light.direction = directionalLight.direction;
		light.visible = true;
	}
#endif
#if NUM_POINT_LIGHTS > 0
	struct PointLight {
		vec3 position;
		vec3 color;
		float distance;
		float decay;
	};
	uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
	void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = pointLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float lightDistance = length( lVector );
		light.color = pointLight.color;
		light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
		light.visible = ( light.color != vec3( 0.0 ) );
	}
#endif
#if NUM_SPOT_LIGHTS > 0
	struct SpotLight {
		vec3 position;
		vec3 direction;
		vec3 color;
		float distance;
		float decay;
		float coneCos;
		float penumbraCos;
	};
	uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
	void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = spotLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float angleCos = dot( light.direction, spotLight.direction );
		float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
		if ( spotAttenuation > 0.0 ) {
			float lightDistance = length( lVector );
			light.color = spotLight.color * spotAttenuation;
			light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
			light.visible = ( light.color != vec3( 0.0 ) );
		} else {
			light.color = vec3( 0.0 );
			light.visible = false;
		}
	}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
	struct RectAreaLight {
		vec3 color;
		vec3 position;
		vec3 halfWidth;
		vec3 halfHeight;
	};
	uniform sampler2D ltc_1;	uniform sampler2D ltc_2;
	uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
	struct HemisphereLight {
		vec3 direction;
		vec3 skyColor;
		vec3 groundColor;
	};
	uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
	vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
		float dotNL = dot( normal, hemiLight.direction );
		float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
		vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
		return irradiance;
	}
#endif`,VCe=`#ifdef USE_ENVMAP
	vec3 getIBLIrradiance( const in vec3 normal ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
			return PI * envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 reflectVec = reflect( - viewDir, normal );
			reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
			reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
			return envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	#ifdef USE_ANISOTROPY
		vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
			#ifdef ENVMAP_TYPE_CUBE_UV
				vec3 bentNormal = cross( bitangent, viewDir );
				bentNormal = normalize( cross( bentNormal, bitangent ) );
				bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
				return getIBLRadiance( viewDir, bentNormal, roughness );
			#else
				return vec3( 0.0 );
			#endif
		}
	#endif
#endif`,XCe=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,$Ce=`varying vec3 vViewPosition;
struct ToonMaterial {
	vec3 diffuseColor;
};
void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Toon
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Toon`,Ace=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,ece=`varying vec3 vViewPosition;
struct BlinnPhongMaterial {
	vec3 diffuseColor;
	vec3 specularColor;
	float specularShininess;
	float specularStrength;
};
void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
	reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
}
void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_BlinnPhong
#define RE_IndirectDiffuse		RE_IndirectDiffuse_BlinnPhong`,tce=`PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
material.roughness = min( material.roughness, 1.0 );
#ifdef IOR
	material.ior = ior;
	#ifdef USE_SPECULAR
		float specularIntensityFactor = specularIntensity;
		vec3 specularColorFactor = specularColor;
		#ifdef USE_SPECULAR_COLORMAP
			specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
		#endif
		#ifdef USE_SPECULAR_INTENSITYMAP
			specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
		#endif
		material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
	#else
		float specularIntensityFactor = 1.0;
		vec3 specularColorFactor = vec3( 1.0 );
		material.specularF90 = 1.0;
	#endif
	material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
#else
	material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
	material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
	material.clearcoat = clearcoat;
	material.clearcoatRoughness = clearcoatRoughness;
	material.clearcoatF0 = vec3( 0.04 );
	material.clearcoatF90 = 1.0;
	#ifdef USE_CLEARCOATMAP
		material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
	#endif
	#ifdef USE_CLEARCOAT_ROUGHNESSMAP
		material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
	#endif
	material.clearcoat = saturate( material.clearcoat );	material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
	material.clearcoatRoughness += geometryRoughness;
	material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_DISPERSION
	material.dispersion = dispersion;
#endif
#ifdef USE_IRIDESCENCE
	material.iridescence = iridescence;
	material.iridescenceIOR = iridescenceIOR;
	#ifdef USE_IRIDESCENCEMAP
		material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
	#endif
	#ifdef USE_IRIDESCENCE_THICKNESSMAP
		material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
	#else
		material.iridescenceThickness = iridescenceThicknessMaximum;
	#endif
#endif
#ifdef USE_SHEEN
	material.sheenColor = sheenColor;
	#ifdef USE_SHEEN_COLORMAP
		material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
	#endif
	material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
	#ifdef USE_SHEEN_ROUGHNESSMAP
		material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
	#endif
#endif
#ifdef USE_ANISOTROPY
	#ifdef USE_ANISOTROPYMAP
		mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
		vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
		vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
	#else
		vec2 anisotropyV = anisotropyVector;
	#endif
	material.anisotropy = length( anisotropyV );
	if( material.anisotropy == 0.0 ) {
		anisotropyV = vec2( 1.0, 0.0 );
	} else {
		anisotropyV /= material.anisotropy;
		material.anisotropy = saturate( material.anisotropy );
	}
	material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
	material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
	material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
#endif`,ice=`struct PhysicalMaterial {
	vec3 diffuseColor;
	float roughness;
	vec3 specularColor;
	float specularF90;
	float dispersion;
	#ifdef USE_CLEARCOAT
		float clearcoat;
		float clearcoatRoughness;
		vec3 clearcoatF0;
		float clearcoatF90;
	#endif
	#ifdef USE_IRIDESCENCE
		float iridescence;
		float iridescenceIOR;
		float iridescenceThickness;
		vec3 iridescenceFresnel;
		vec3 iridescenceF0;
	#endif
	#ifdef USE_SHEEN
		vec3 sheenColor;
		float sheenRoughness;
	#endif
	#ifdef IOR
		float ior;
	#endif
	#ifdef USE_TRANSMISSION
		float transmission;
		float transmissionAlpha;
		float thickness;
		float attenuationDistance;
		vec3 attenuationColor;
	#endif
	#ifdef USE_ANISOTROPY
		float anisotropy;
		float alphaT;
		vec3 anisotropyT;
		vec3 anisotropyB;
	#endif
};
vec3 clearcoatSpecularDirect = vec3( 0.0 );
vec3 clearcoatSpecularIndirect = vec3( 0.0 );
vec3 sheenSpecularDirect = vec3( 0.0 );
vec3 sheenSpecularIndirect = vec3(0.0 );
vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
    float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
    float x2 = x * x;
    float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
    return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
}
float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
	float a2 = pow2( alpha );
	float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
	float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
	return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX( const in float alpha, const in float dotNH ) {
	float a2 = pow2( alpha );
	float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
	return RECIPROCAL_PI * a2 / pow2( denom );
}
#ifdef USE_ANISOTROPY
	float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
		float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
		float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
		float v = 0.5 / ( gv + gl );
		return saturate(v);
	}
	float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
		float a2 = alphaT * alphaB;
		highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
		highp float v2 = dot( v, v );
		float w2 = a2 / v2;
		return RECIPROCAL_PI * a2 * pow2 ( w2 );
	}
#endif
#ifdef USE_CLEARCOAT
	vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
		vec3 f0 = material.clearcoatF0;
		float f90 = material.clearcoatF90;
		float roughness = material.clearcoatRoughness;
		float alpha = pow2( roughness );
		vec3 halfDir = normalize( lightDir + viewDir );
		float dotNL = saturate( dot( normal, lightDir ) );
		float dotNV = saturate( dot( normal, viewDir ) );
		float dotNH = saturate( dot( normal, halfDir ) );
		float dotVH = saturate( dot( viewDir, halfDir ) );
		vec3 F = F_Schlick( f0, f90, dotVH );
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
		return F * ( V * D );
	}
#endif
vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
	vec3 f0 = material.specularColor;
	float f90 = material.specularF90;
	float roughness = material.roughness;
	float alpha = pow2( roughness );
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( f0, f90, dotVH );
	#ifdef USE_IRIDESCENCE
		F = mix( F, material.iridescenceFresnel, material.iridescence );
	#endif
	#ifdef USE_ANISOTROPY
		float dotTL = dot( material.anisotropyT, lightDir );
		float dotTV = dot( material.anisotropyT, viewDir );
		float dotTH = dot( material.anisotropyT, halfDir );
		float dotBL = dot( material.anisotropyB, lightDir );
		float dotBV = dot( material.anisotropyB, viewDir );
		float dotBH = dot( material.anisotropyB, halfDir );
		float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
		float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
	#else
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
	#endif
	return F * ( V * D );
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
	const float LUT_SIZE = 64.0;
	const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
	const float LUT_BIAS = 0.5 / LUT_SIZE;
	float dotNV = saturate( dot( N, V ) );
	vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
	uv = uv * LUT_SCALE + LUT_BIAS;
	return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
	float l = length( f );
	return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
	float x = dot( v1, v2 );
	float y = abs( x );
	float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
	float b = 3.4175940 + ( 4.1616724 + y ) * y;
	float v = a / b;
	float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
	return cross( v1, v2 ) * theta_sintheta;
}
vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
	vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
	vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
	vec3 lightNormal = cross( v1, v2 );
	if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
	vec3 T1, T2;
	T1 = normalize( V - N * dot( V, N ) );
	T2 = - cross( N, T1 );
	mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
	vec3 coords[ 4 ];
	coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
	coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
	coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
	coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
	coords[ 0 ] = normalize( coords[ 0 ] );
	coords[ 1 ] = normalize( coords[ 1 ] );
	coords[ 2 ] = normalize( coords[ 2 ] );
	coords[ 3 ] = normalize( coords[ 3 ] );
	vec3 vectorFormFactor = vec3( 0.0 );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
	float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
	return vec3( result );
}
#if defined( USE_SHEEN )
float D_Charlie( float roughness, float dotNH ) {
	float alpha = pow2( roughness );
	float invAlpha = 1.0 / alpha;
	float cos2h = dotNH * dotNH;
	float sin2h = max( 1.0 - cos2h, 0.0078125 );
	return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
}
float V_Neubelt( float dotNV, float dotNL ) {
	return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
}
vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float D = D_Charlie( sheenRoughness, dotNH );
	float V = V_Neubelt( dotNV, dotNL );
	return sheenColor * ( D * V );
}
#endif
float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	float r2 = roughness * roughness;
	float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
	float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
	float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
	return saturate( DG * RECIPROCAL_PI );
}
vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
	const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
	vec4 r = roughness * c0 + c1;
	float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
	vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
	return fab;
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	#ifdef USE_IRIDESCENCE
		vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
	#else
		vec3 Fr = specularColor;
	#endif
	vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
	float Ess = fab.x + fab.y;
	float Ems = 1.0 - Ess;
	vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;	vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
	singleScatter += FssEss;
	multiScatter += Fms * Ems;
}
#if NUM_RECT_AREA_LIGHTS > 0
	void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
		vec3 normal = geometryNormal;
		vec3 viewDir = geometryViewDir;
		vec3 position = geometryPosition;
		vec3 lightPos = rectAreaLight.position;
		vec3 halfWidth = rectAreaLight.halfWidth;
		vec3 halfHeight = rectAreaLight.halfHeight;
		vec3 lightColor = rectAreaLight.color;
		float roughness = material.roughness;
		vec3 rectCoords[ 4 ];
		rectCoords[ 0 ] = lightPos + halfWidth - halfHeight;		rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
		rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
		rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
		vec2 uv = LTC_Uv( normal, viewDir, roughness );
		vec4 t1 = texture2D( ltc_1, uv );
		vec4 t2 = texture2D( ltc_2, uv );
		mat3 mInv = mat3(
			vec3( t1.x, 0, t1.y ),
			vec3(    0, 1,    0 ),
			vec3( t1.z, 0, t1.w )
		);
		vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
		reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
	}
#endif
void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	#ifdef USE_CLEARCOAT
		float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
		vec3 ccIrradiance = dotNLcc * directLight.color;
		clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
	#endif
	reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
	#ifdef USE_CLEARCOAT
		clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
	#endif
	vec3 singleScattering = vec3( 0.0 );
	vec3 multiScattering = vec3( 0.0 );
	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
	#ifdef USE_IRIDESCENCE
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
	#else
		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
	#endif
	vec3 totalScattering = singleScattering + multiScattering;
	vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
	reflectedLight.indirectSpecular += radiance * singleScattering;
	reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
	reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
}
#define RE_Direct				RE_Direct_Physical
#define RE_Direct_RectArea		RE_Direct_RectArea_Physical
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Physical
#define RE_IndirectSpecular		RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
	return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
}`,nce=`
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
	geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
	float dotNVi = saturate( dot( normal, geometryViewDir ) );
	if ( material.iridescenceThickness == 0.0 ) {
		material.iridescence = 0.0;
	} else {
		material.iridescence = saturate( material.iridescence );
	}
	if ( material.iridescence > 0.0 ) {
		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
	}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
	PointLight pointLight;
	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
		pointLight = pointLights[ i ];
		getPointLightInfo( pointLight, geometryPosition, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
		pointLightShadow = pointLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
	SpotLight spotLight;
	vec4 spotColor;
	vec3 spotLightCoord;
	bool inSpotLightMap;
	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
		spotLight = spotLights[ i ];
		getSpotLightInfo( spotLight, geometryPosition, directLight );
		#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
		#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
		#else
		#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#endif
		#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
			spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
			inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
			spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
			directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
		#endif
		#undef SPOT_LIGHT_MAP_INDEX
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		spotLightShadow = spotLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
	DirectionalLight directionalLight;
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
		directionalLight = directionalLights[ i ];
		getDirectionalLightInfo( directionalLight, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
		directionalLightShadow = directionalLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
	RectAreaLight rectAreaLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
		rectAreaLight = rectAreaLights[ i ];
		RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
	vec3 iblIrradiance = vec3( 0.0 );
	vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
	#if defined( USE_LIGHT_PROBES )
		irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
	#endif
	#if ( NUM_HEMI_LIGHTS > 0 )
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
			irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
		}
		#pragma unroll_loop_end
	#endif
#endif
#if defined( RE_IndirectSpecular )
	vec3 radiance = vec3( 0.0 );
	vec3 clearcoatRadiance = vec3( 0.0 );
#endif`,gce=`#if defined( RE_IndirectDiffuse )
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
		irradiance += lightMapIrradiance;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
		iblIrradiance += getIBLIrradiance( geometryNormal );
	#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
	#ifdef USE_ANISOTROPY
		radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
	#else
		radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
	#endif
	#ifdef USE_CLEARCOAT
		clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
	#endif
#endif`,oce=`#if defined( RE_IndirectDiffuse )
	RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
	RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif`,sce=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,ace=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,rce=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,Ice=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,Cce=`#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`,cce=`#ifdef USE_MAP
	uniform sampler2D map;
#endif`,lce=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
	#if defined( USE_POINTS_UV )
		vec2 uv = vUv;
	#else
		vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
	#endif
#endif
#ifdef USE_MAP
	diffuseColor *= texture2D( map, uv );
#endif
#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, uv ).g;
#endif`,Bce=`#if defined( USE_POINTS_UV )
	varying vec2 vUv;
#else
	#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
		uniform mat3 uvTransform;
	#endif
#endif
#ifdef USE_MAP
	uniform sampler2D map;
#endif
#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,Ece=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`,Qce=`#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`,uce=`#ifdef USE_INSTANCING_MORPH
	float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		morphTargetInfluences[i] =  texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
	}
#endif`,dce=`#if defined( USE_MORPHCOLORS )
	vColor *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		#if defined( USE_COLOR_ALPHA )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
		#elif defined( USE_COLOR )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
		#endif
	}
#endif`,hce=`#ifdef USE_MORPHNORMALS
	objectNormal *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
	}
#endif`,pce=`#ifdef USE_MORPHTARGETS
	#ifndef USE_INSTANCING_MORPH
		uniform float morphTargetBaseInfluence;
		uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	#endif
	uniform sampler2DArray morphTargetsTexture;
	uniform ivec2 morphTargetsTextureSize;
	vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
		int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
		int y = texelIndex / morphTargetsTextureSize.x;
		int x = texelIndex - y * morphTargetsTextureSize.x;
		ivec3 morphUV = ivec3( x, y, morphTargetIndex );
		return texelFetch( morphTargetsTexture, morphUV, 0 );
	}
#endif`,fce=`#ifdef USE_MORPHTARGETS
	transformed *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
	}
#endif`,yce=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
	vec3 fdx = dFdx( vViewPosition );
	vec3 fdy = dFdy( vViewPosition );
	vec3 normal = normalize( cross( fdx, fdy ) );
#else
	vec3 normal = normalize( vNormal );
	#ifdef DOUBLE_SIDED
		normal *= faceDirection;
	#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
	#ifdef USE_TANGENT
		mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn = getTangentFrame( - vViewPosition, normal,
		#if defined( USE_NORMALMAP )
			vNormalMapUv
		#elif defined( USE_CLEARCOAT_NORMALMAP )
			vClearcoatNormalMapUv
		#else
			vUv
		#endif
		);
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn[0] *= faceDirection;
		tbn[1] *= faceDirection;
	#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	#ifdef USE_TANGENT
		mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn2[0] *= faceDirection;
		tbn2[1] *= faceDirection;
	#endif
#endif
vec3 nonPerturbedNormal = normal;`,Dce=`#ifdef USE_NORMALMAP_OBJECTSPACE
	normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	#ifdef FLIP_SIDED
		normal = - normal;
	#endif
	#ifdef DOUBLE_SIDED
		normal = normal * faceDirection;
	#endif
	normal = normalize( normalMatrix * normal );
#elif defined( USE_NORMALMAP_TANGENTSPACE )
	vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	mapN.xy *= normalScale;
	normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`,mce=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,Sce=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,wce=`#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`,kce=`#ifdef USE_NORMALMAP
	uniform sampler2D normalMap;
	uniform vec2 normalScale;
#endif
#ifdef USE_NORMALMAP_OBJECTSPACE
	uniform mat3 normalMatrix;
#endif
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
	mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
		vec3 q0 = dFdx( eye_pos.xyz );
		vec3 q1 = dFdy( eye_pos.xyz );
		vec2 st0 = dFdx( uv.st );
		vec2 st1 = dFdy( uv.st );
		vec3 N = surf_norm;
		vec3 q1perp = cross( q1, N );
		vec3 q0perp = cross( N, q0 );
		vec3 T = q1perp * st0.x + q0perp * st1.x;
		vec3 B = q1perp * st0.y + q0perp * st1.y;
		float det = max( dot( T, T ), dot( B, B ) );
		float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
		return mat3( T * scale, B * scale, N );
	}
#endif`,Mce=`#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,Nce=`#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,Rce=`#ifdef USE_CLEARCOATMAP
	uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform sampler2D clearcoatNormalMap;
	uniform vec2 clearcoatNormalScale;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform sampler2D clearcoatRoughnessMap;
#endif`,Gce=`#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`,bce=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Uce=`vec3 packNormalToRGB( const in vec3 normal ) {
	return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
	return 2.0 * rgb.xyz - 1.0;
}
const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
const float Inv255 = 1. / 255.;
const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
vec4 packDepthToRGBA( const in float v ) {
	if( v <= 0.0 )
		return vec4( 0., 0., 0., 0. );
	if( v >= 1.0 )
		return vec4( 1., 1., 1., 1. );
	float vuf;
	float af = modf( v * PackFactors.a, vuf );
	float bf = modf( vuf * ShiftRight8, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
}
vec3 packDepthToRGB( const in float v ) {
	if( v <= 0.0 )
		return vec3( 0., 0., 0. );
	if( v >= 1.0 )
		return vec3( 1., 1., 1. );
	float vuf;
	float bf = modf( v * PackFactors.b, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec3( vuf * Inv255, gf * PackUpscale, bf );
}
vec2 packDepthToRG( const in float v ) {
	if( v <= 0.0 )
		return vec2( 0., 0. );
	if( v >= 1.0 )
		return vec2( 1., 1. );
	float vuf;
	float gf = modf( v * 256., vuf );
	return vec2( vuf * Inv255, gf );
}
float unpackRGBAToDepth( const in vec4 v ) {
	return dot( v, UnpackFactors4 );
}
float unpackRGBToDepth( const in vec3 v ) {
	return dot( v, UnpackFactors3 );
}
float unpackRGToDepth( const in vec2 v ) {
	return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
}
vec4 pack2HalfToRGBA( const in vec2 v ) {
	vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
	return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
}
vec2 unpackRGBATo2Half( const in vec4 v ) {
	return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
}
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
	return ( viewZ + near ) / ( near - far );
}
float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return depth * ( near - far ) - near;
}
float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
	return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return ( near * far ) / ( ( far - near ) * depth - far );
}`,vce=`#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`,Kce=`vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
	mvPosition = batchingMatrix * mvPosition;
#endif
#ifdef USE_INSTANCING
	mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;`,Fce=`#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,_ce=`#ifdef DITHERING
	vec3 dithering( vec3 color ) {
		float grid_position = rand( gl_FragCoord.xy );
		vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
		dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
		return color + dither_shift_RGB;
	}
#endif`,Jce=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`,Lce=`#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`,xce=`#if NUM_SPOT_LIGHT_COORDS > 0
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
	uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
	float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
		float depth = unpackRGBAToDepth( texture2D( depths, uv ) );
		#ifdef USE_REVERSED_DEPTH_BUFFER
			return step( depth, compare );
		#else
			return step( compare, depth );
		#endif
	}
	vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
		return unpackRGBATo2Half( texture2D( shadow, uv ) );
	}
	float VSMShadow( sampler2D shadow, vec2 uv, float compare ) {
		float occlusion = 1.0;
		vec2 distribution = texture2DDistribution( shadow, uv );
		#ifdef USE_REVERSED_DEPTH_BUFFER
			float hard_shadow = step( distribution.x, compare );
		#else
			float hard_shadow = step( compare, distribution.x );
		#endif
		if ( hard_shadow != 1.0 ) {
			float distance = compare - distribution.x;
			float variance = max( 0.00000, distribution.y * distribution.y );
			float softness_probability = variance / (variance + distance * distance );			softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );			occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
		}
		return occlusion;
	}
	float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
		float shadow = 1.0;
		shadowCoord.xyz /= shadowCoord.w;
		shadowCoord.z += shadowBias;
		bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
		bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
		if ( frustumTest ) {
		#if defined( SHADOWMAP_TYPE_PCF )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx0 = - texelSize.x * shadowRadius;
			float dy0 = - texelSize.y * shadowRadius;
			float dx1 = + texelSize.x * shadowRadius;
			float dy1 = + texelSize.y * shadowRadius;
			float dx2 = dx0 / 2.0;
			float dy2 = dy0 / 2.0;
			float dx3 = dx1 / 2.0;
			float dy3 = dy1 / 2.0;
			shadow = (
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
			) * ( 1.0 / 17.0 );
		#elif defined( SHADOWMAP_TYPE_PCF_SOFT )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx = texelSize.x;
			float dy = texelSize.y;
			vec2 uv = shadowCoord.xy;
			vec2 f = fract( uv * shadowMapSize + 0.5 );
			uv -= f * texelSize;
			shadow = (
				texture2DCompare( shadowMap, uv, shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
						  f.x ),
					 mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
						  f.x ),
					 f.y )
			) * ( 1.0 / 9.0 );
		#elif defined( SHADOWMAP_TYPE_VSM )
			shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
		#else
			shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
		#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
	vec2 cubeToUV( vec3 v, float texelSizeY ) {
		vec3 absV = abs( v );
		float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
		absV *= scaleToCube;
		v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
		vec2 planar = v.xy;
		float almostATexel = 1.5 * texelSizeY;
		float almostOne = 1.0 - almostATexel;
		if ( absV.z >= almostOne ) {
			if ( v.z > 0.0 )
				planar.x = 4.0 - v.x;
		} else if ( absV.x >= almostOne ) {
			float signX = sign( v.x );
			planar.x = v.z * signX + 2.0 * signX;
		} else if ( absV.y >= almostOne ) {
			float signY = sign( v.y );
			planar.x = v.x + 2.0 * signY + 2.0;
			planar.y = v.z * signY - 2.0;
		}
		return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
	}
	float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		
		float lightToPositionLength = length( lightToPosition );
		if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
			float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );			dp += shadowBias;
			vec3 bd3D = normalize( lightToPosition );
			vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
			#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
				vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
				shadow = (
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
				) * ( 1.0 / 9.0 );
			#else
				shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
			#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
#endif`,Tce=`#if NUM_SPOT_LIGHT_COORDS > 0
	uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
#endif`,qce=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
	vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
	vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
	#if NUM_DIR_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
			vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
			vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
		shadowWorldPosition = worldPosition;
		#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
			shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
		#endif
		vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
	}
	#pragma unroll_loop_end
#endif`,Yce=`float getShadowMask() {
	float shadow = 1.0;
	#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
		directionalLight = directionalLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
		spotLight = spotLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
		pointLight = pointLightShadows[ i ];
		shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#endif
	return shadow;
}`,Hce=`#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,Oce=`#ifdef USE_SKINNING
	uniform mat4 bindMatrix;
	uniform mat4 bindMatrixInverse;
	uniform highp sampler2D boneTexture;
	mat4 getBoneMatrix( const in float i ) {
		int size = textureSize( boneTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
#endif`,Pce=`#ifdef USE_SKINNING
	vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
	vec4 skinned = vec4( 0.0 );
	skinned += boneMatX * skinVertex * skinWeight.x;
	skinned += boneMatY * skinVertex * skinWeight.y;
	skinned += boneMatZ * skinVertex * skinWeight.z;
	skinned += boneMatW * skinVertex * skinWeight.w;
	transformed = ( bindMatrixInverse * skinned ).xyz;
#endif`,jce=`#ifdef USE_SKINNING
	mat4 skinMatrix = mat4( 0.0 );
	skinMatrix += skinWeight.x * boneMatX;
	skinMatrix += skinWeight.y * boneMatY;
	skinMatrix += skinWeight.z * boneMatZ;
	skinMatrix += skinWeight.w * boneMatW;
	skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
	objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
	#ifdef USE_TANGENT
		objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
	#endif
#endif`,zce=`float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`,Zce=`#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`,Wce=`#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,Vce=`#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
vec3 LinearToneMapping( vec3 color ) {
	return saturate( toneMappingExposure * color );
}
vec3 ReinhardToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	return saturate( color / ( vec3( 1.0 ) + color ) );
}
vec3 CineonToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	color = max( vec3( 0.0 ), color - 0.004 );
	return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
}
vec3 RRTAndODTFit( vec3 v ) {
	vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
	vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
	return a / b;
}
vec3 ACESFilmicToneMapping( vec3 color ) {
	const mat3 ACESInputMat = mat3(
		vec3( 0.59719, 0.07600, 0.02840 ),		vec3( 0.35458, 0.90834, 0.13383 ),
		vec3( 0.04823, 0.01566, 0.83777 )
	);
	const mat3 ACESOutputMat = mat3(
		vec3(  1.60475, -0.10208, -0.00327 ),		vec3( -0.53108,  1.10813, -0.07276 ),
		vec3( -0.07367, -0.00605,  1.07602 )
	);
	color *= toneMappingExposure / 0.6;
	color = ACESInputMat * color;
	color = RRTAndODTFit( color );
	color = ACESOutputMat * color;
	return saturate( color );
}
const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
	vec3( 1.6605, - 0.1246, - 0.0182 ),
	vec3( - 0.5876, 1.1329, - 0.1006 ),
	vec3( - 0.0728, - 0.0083, 1.1187 )
);
const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
	vec3( 0.6274, 0.0691, 0.0164 ),
	vec3( 0.3293, 0.9195, 0.0880 ),
	vec3( 0.0433, 0.0113, 0.8956 )
);
vec3 agxDefaultContrastApprox( vec3 x ) {
	vec3 x2 = x * x;
	vec3 x4 = x2 * x2;
	return + 15.5 * x4 * x2
		- 40.14 * x4 * x
		+ 31.96 * x4
		- 6.868 * x2 * x
		+ 0.4298 * x2
		+ 0.1191 * x
		- 0.00232;
}
vec3 AgXToneMapping( vec3 color ) {
	const mat3 AgXInsetMatrix = mat3(
		vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
		vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
		vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
	);
	const mat3 AgXOutsetMatrix = mat3(
		vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
		vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
		vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
	);
	const float AgxMinEv = - 12.47393;	const float AgxMaxEv = 4.026069;
	color *= toneMappingExposure;
	color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
	color = AgXInsetMatrix * color;
	color = max( color, 1e-10 );	color = log2( color );
	color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
	color = clamp( color, 0.0, 1.0 );
	color = agxDefaultContrastApprox( color );
	color = AgXOutsetMatrix * color;
	color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
	color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
	color = clamp( color, 0.0, 1.0 );
	return color;
}
vec3 NeutralToneMapping( vec3 color ) {
	const float StartCompression = 0.8 - 0.04;
	const float Desaturation = 0.15;
	color *= toneMappingExposure;
	float x = min( color.r, min( color.g, color.b ) );
	float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
	color -= offset;
	float peak = max( color.r, max( color.g, color.b ) );
	if ( peak < StartCompression ) return color;
	float d = 1. - StartCompression;
	float newPeak = 1. - d * d / ( peak + d - StartCompression );
	color *= newPeak / peak;
	float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
	return mix( color, vec3( newPeak ), g );
}
vec3 CustomToneMapping( vec3 color ) { return color; }`,Xce=`#ifdef USE_TRANSMISSION
	material.transmission = transmission;
	material.transmissionAlpha = 1.0;
	material.thickness = thickness;
	material.attenuationDistance = attenuationDistance;
	material.attenuationColor = attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
	#endif
	#ifdef USE_THICKNESSMAP
		material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
	#endif
	vec3 pos = vWorldPosition;
	vec3 v = normalize( cameraPosition - pos );
	vec3 n = inverseTransformDirection( normal, viewMatrix );
	vec4 transmitted = getIBLVolumeRefraction(
		n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
		pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
		material.attenuationColor, material.attenuationDistance );
	material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
	totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
#endif`,$ce=`#ifdef USE_TRANSMISSION
	uniform float transmission;
	uniform float thickness;
	uniform float attenuationDistance;
	uniform vec3 attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		uniform sampler2D transmissionMap;
	#endif
	#ifdef USE_THICKNESSMAP
		uniform sampler2D thicknessMap;
	#endif
	uniform vec2 transmissionSamplerSize;
	uniform sampler2D transmissionSamplerMap;
	uniform mat4 modelMatrix;
	uniform mat4 projectionMatrix;
	varying vec3 vWorldPosition;
	float w0( float a ) {
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
	}
	float w1( float a ) {
		return ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );
	}
	float w2( float a ){
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
	}
	float w3( float a ) {
		return ( 1.0 / 6.0 ) * ( a * a * a );
	}
	float g0( float a ) {
		return w0( a ) + w1( a );
	}
	float g1( float a ) {
		return w2( a ) + w3( a );
	}
	float h0( float a ) {
		return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
	}
	float h1( float a ) {
		return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
	}
	vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
		uv = uv * texelSize.zw + 0.5;
		vec2 iuv = floor( uv );
		vec2 fuv = fract( uv );
		float g0x = g0( fuv.x );
		float g1x = g1( fuv.x );
		float h0x = h0( fuv.x );
		float h1x = h1( fuv.x );
		float h0y = h0( fuv.y );
		float h1y = h1( fuv.y );
		vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
			g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
	}
	vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
		vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
		vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
		vec2 fLodSizeInv = 1.0 / fLodSize;
		vec2 cLodSizeInv = 1.0 / cLodSize;
		vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
		vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
		return mix( fSample, cSample, fract( lod ) );
	}
	vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
		vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
		vec3 modelScale;
		modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
		modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
		modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
		return normalize( refractionVector ) * thickness * modelScale;
	}
	float applyIorToRoughness( const in float roughness, const in float ior ) {
		return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
	}
	vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
		float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
		return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
	}
	vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
		if ( isinf( attenuationDistance ) ) {
			return vec3( 1.0 );
		} else {
			vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
			vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );			return transmittance;
		}
	}
	vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
		const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
		const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
		const in vec3 attenuationColor, const in float attenuationDistance ) {
		vec4 transmittedLight;
		vec3 transmittance;
		#ifdef USE_DISPERSION
			float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
			vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
			for ( int i = 0; i < 3; i ++ ) {
				vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
				vec3 refractedRayExit = position + transmissionRay;
				vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
				vec2 refractionCoords = ndcPos.xy / ndcPos.w;
				refractionCoords += 1.0;
				refractionCoords /= 2.0;
				vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
				transmittedLight[ i ] = transmissionSample[ i ];
				transmittedLight.a += transmissionSample.a;
				transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
			}
			transmittedLight.a /= 3.0;
		#else
			vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
			vec3 refractedRayExit = position + transmissionRay;
			vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
			vec2 refractionCoords = ndcPos.xy / ndcPos.w;
			refractionCoords += 1.0;
			refractionCoords /= 2.0;
			transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
			transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
		#endif
		vec3 attenuatedColor = transmittance * transmittedLight.rgb;
		vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
		float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
		return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
	}
#endif`,Ale=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_SPECULARMAP
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`,ele=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	uniform mat3 mapTransform;
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	uniform mat3 alphaMapTransform;
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	uniform mat3 lightMapTransform;
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	uniform mat3 aoMapTransform;
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	uniform mat3 bumpMapTransform;
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	uniform mat3 normalMapTransform;
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_DISPLACEMENTMAP
	uniform mat3 displacementMapTransform;
	varying vec2 vDisplacementMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	uniform mat3 emissiveMapTransform;
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	uniform mat3 metalnessMapTransform;
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	uniform mat3 roughnessMapTransform;
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	uniform mat3 anisotropyMapTransform;
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	uniform mat3 clearcoatMapTransform;
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform mat3 clearcoatNormalMapTransform;
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform mat3 clearcoatRoughnessMapTransform;
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	uniform mat3 sheenColorMapTransform;
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	uniform mat3 sheenRoughnessMapTransform;
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	uniform mat3 iridescenceMapTransform;
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform mat3 iridescenceThicknessMapTransform;
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SPECULARMAP
	uniform mat3 specularMapTransform;
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	uniform mat3 specularColorMapTransform;
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	uniform mat3 specularIntensityMapTransform;
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`,tle=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
	vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ALPHAMAP
	vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_LIGHTMAP
	vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_AOMAP
	vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_BUMPMAP
	vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_NORMALMAP
	vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_DISPLACEMENTMAP
	vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_EMISSIVEMAP
	vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_METALNESSMAP
	vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ROUGHNESSMAP
	vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ANISOTROPYMAP
	vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOATMAP
	vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCEMAP
	vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_COLORMAP
	vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULARMAP
	vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_COLORMAP
	vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_TRANSMISSIONMAP
	vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_THICKNESSMAP
	vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
#endif`,ile=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
	vec4 worldPosition = vec4( transformed, 1.0 );
	#ifdef USE_BATCHING
		worldPosition = batchingMatrix * worldPosition;
	#endif
	#ifdef USE_INSTANCING
		worldPosition = instanceMatrix * worldPosition;
	#endif
	worldPosition = modelMatrix * worldPosition;
#endif`;const nle=`varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,gle=`uniform sampler2D t2D;
uniform float backgroundIntensity;
varying vec2 vUv;
void main() {
	vec4 texColor = texture2D( t2D, vUv );
	#ifdef DECODE_VIDEO_TEXTURE
		texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,ole=`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`,sle=`#ifdef ENVMAP_TYPE_CUBE
	uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
	uniform sampler2D envMap;
#endif
uniform float flipEnvMap;
uniform float backgroundBlurriness;
uniform float backgroundIntensity;
uniform mat3 backgroundRotation;
varying vec3 vWorldDirection;
#include <cube_uv_reflection_fragment>
void main() {
	#ifdef ENVMAP_TYPE_CUBE
		vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
	#elif defined( ENVMAP_TYPE_CUBE_UV )
		vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
	#else
		vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,ale=`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`,rle=`uniform samplerCube tCube;
uniform float tFlip;
uniform float opacity;
varying vec3 vWorldDirection;
void main() {
	vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
	gl_FragColor = texColor;
	gl_FragColor.a *= opacity;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,Ile=`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec2 vHighPrecisionZW;
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vHighPrecisionZW = gl_Position.zw;
}`,Cle=`#if DEPTH_PACKING == 3200
	uniform float opacity;
#endif
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec2 vHighPrecisionZW;
void main() {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#if DEPTH_PACKING == 3200
		diffuseColor.a = opacity;
	#endif
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <logdepthbuf_fragment>
	#ifdef USE_REVERSED_DEPTH_BUFFER
		float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
	#else
		float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
	#endif
	#if DEPTH_PACKING == 3200
		gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
	#elif DEPTH_PACKING == 3201
		gl_FragColor = packDepthToRGBA( fragCoordZ );
	#elif DEPTH_PACKING == 3202
		gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
	#elif DEPTH_PACKING == 3203
		gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
	#endif
}`,cle=`#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <worldpos_vertex>
	#include <clipping_planes_vertex>
	vWorldPosition = worldPosition.xyz;
}`,lle=`#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <clipping_planes_pars_fragment>
void main () {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	float dist = length( vWorldPosition - referencePosition );
	dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
	dist = saturate( dist );
	gl_FragColor = packDepthToRGBA( dist );
}`,Ble=`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
}`,Ele=`uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
	vec3 direction = normalize( vWorldDirection );
	vec2 sampleUV = equirectUv( direction );
	gl_FragColor = texture2D( tEquirect, sampleUV );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,Qle=`uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	vLineDistance = scale * lineDistance;
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`,ule=`uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
varying float vLineDistance;
#include <common>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	if ( mod( vLineDistance, totalSize ) > dashSize ) {
		discard;
	}
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`,dle=`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinbase_vertex>
		#include <skinnormal_vertex>
		#include <defaultnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <fog_vertex>
}`,hle=`uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
	varying vec3 vNormal;
#endif
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
	#else
		reflectedLight.indirectDiffuse += vec3( 1.0 );
	#endif
	#include <aomap_fragment>
	reflectedLight.indirectDiffuse *= diffuseColor.rgb;
	vec3 outgoingLight = reflectedLight.indirectDiffuse;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,ple=`#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,fle=`#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_lambert_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_lambert_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,yle=`#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <displacementmap_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
	vViewPosition = - mvPosition.xyz;
}`,Dle=`#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	vec3 viewDir = normalize( vViewPosition );
	vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
	vec3 y = cross( viewDir, x );
	vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
	#ifdef USE_MATCAP
		vec4 matcapColor = texture2D( matcap, uv );
	#else
		vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
	#endif
	vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,mle=`#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	vViewPosition = - mvPosition.xyz;
#endif
}`,Sle=`#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <packing>
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
	#ifdef OPAQUE
		gl_FragColor.a = 1.0;
	#endif
}`,wle=`#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,kle=`#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_phong_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,Mle=`#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
	varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
#ifdef USE_TRANSMISSION
	vWorldPosition = worldPosition.xyz;
#endif
}`,Nle=`#define STANDARD
#ifdef PHYSICAL
	#define IOR
	#define USE_SPECULAR
#endif
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float roughness;
uniform float metalness;
uniform float opacity;
#ifdef IOR
	uniform float ior;
#endif
#ifdef USE_SPECULAR
	uniform float specularIntensity;
	uniform vec3 specularColor;
	#ifdef USE_SPECULAR_COLORMAP
		uniform sampler2D specularColorMap;
	#endif
	#ifdef USE_SPECULAR_INTENSITYMAP
		uniform sampler2D specularIntensityMap;
	#endif
#endif
#ifdef USE_CLEARCOAT
	uniform float clearcoat;
	uniform float clearcoatRoughness;
#endif
#ifdef USE_DISPERSION
	uniform float dispersion;
#endif
#ifdef USE_IRIDESCENCE
	uniform float iridescence;
	uniform float iridescenceIOR;
	uniform float iridescenceThicknessMinimum;
	uniform float iridescenceThicknessMaximum;
#endif
#ifdef USE_SHEEN
	uniform vec3 sheenColor;
	uniform float sheenRoughness;
	#ifdef USE_SHEEN_COLORMAP
		uniform sampler2D sheenColorMap;
	#endif
	#ifdef USE_SHEEN_ROUGHNESSMAP
		uniform sampler2D sheenRoughnessMap;
	#endif
#endif
#ifdef USE_ANISOTROPY
	uniform vec2 anisotropyVector;
	#ifdef USE_ANISOTROPYMAP
		uniform sampler2D anisotropyMap;
	#endif
#endif
varying vec3 vViewPosition;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <roughnessmap_fragment>
	#include <metalnessmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <clearcoat_normal_fragment_begin>
	#include <clearcoat_normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_physical_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
	vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
	#include <transmission_fragment>
	vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
	#ifdef USE_SHEEN
		float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
		outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
	#endif
	#ifdef USE_CLEARCOAT
		float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
		vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
		outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
	#endif
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,Rle=`#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,Gle=`#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <gradientmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_toon_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_toon_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,ble=`uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#ifdef USE_POINTS_UV
	varying vec2 vUv;
	uniform mat3 uvTransform;
#endif
void main() {
	#ifdef USE_POINTS_UV
		vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	#endif
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	gl_PointSize = size;
	#ifdef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
	#endif
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <fog_vertex>
}`,Ule=`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
#include <map_particle_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_particle_fragment>
	#include <color_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`,vle=`#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <shadowmap_pars_vertex>
void main() {
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,Kle=`uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <logdepthbuf_pars_fragment>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
	#include <logdepthbuf_fragment>
	gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`,Fle=`uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	vec4 mvPosition = modelViewMatrix[ 3 ];
	vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
	#ifndef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) scale *= - mvPosition.z;
	#endif
	vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
	vec2 rotatedPosition;
	rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
	rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
	mvPosition.xy += rotatedPosition;
	gl_Position = projectionMatrix * mvPosition;
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`,_le=`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`,cn={alphahash_fragment:gCe,alphahash_pars_fragment:oCe,alphamap_fragment:sCe,alphamap_pars_fragment:aCe,alphatest_fragment:rCe,alphatest_pars_fragment:ICe,aomap_fragment:CCe,aomap_pars_fragment:cCe,batching_pars_vertex:lCe,batching_vertex:BCe,begin_vertex:ECe,beginnormal_vertex:QCe,bsdfs:uCe,iridescence_fragment:dCe,bumpmap_pars_fragment:hCe,clipping_planes_fragment:pCe,clipping_planes_pars_fragment:fCe,clipping_planes_pars_vertex:yCe,clipping_planes_vertex:DCe,color_fragment:mCe,color_pars_fragment:SCe,color_pars_vertex:wCe,color_vertex:kCe,common:MCe,cube_uv_reflection_fragment:NCe,defaultnormal_vertex:RCe,displacementmap_pars_vertex:GCe,displacementmap_vertex:bCe,emissivemap_fragment:UCe,emissivemap_pars_fragment:vCe,colorspace_fragment:KCe,colorspace_pars_fragment:FCe,envmap_fragment:_Ce,envmap_common_pars_fragment:JCe,envmap_pars_fragment:LCe,envmap_pars_vertex:xCe,envmap_physical_pars_fragment:VCe,envmap_vertex:TCe,fog_vertex:qCe,fog_pars_vertex:YCe,fog_fragment:HCe,fog_pars_fragment:OCe,gradientmap_pars_fragment:PCe,lightmap_pars_fragment:jCe,lights_lambert_fragment:zCe,lights_lambert_pars_fragment:ZCe,lights_pars_begin:WCe,lights_toon_fragment:XCe,lights_toon_pars_fragment:$Ce,lights_phong_fragment:Ace,lights_phong_pars_fragment:ece,lights_physical_fragment:tce,lights_physical_pars_fragment:ice,lights_fragment_begin:nce,lights_fragment_maps:gce,lights_fragment_end:oce,logdepthbuf_fragment:sce,logdepthbuf_pars_fragment:ace,logdepthbuf_pars_vertex:rce,logdepthbuf_vertex:Ice,map_fragment:Cce,map_pars_fragment:cce,map_particle_fragment:lce,map_particle_pars_fragment:Bce,metalnessmap_fragment:Ece,metalnessmap_pars_fragment:Qce,morphinstance_vertex:uce,morphcolor_vertex:dce,morphnormal_vertex:hce,morphtarget_pars_vertex:pce,morphtarget_vertex:fce,normal_fragment_begin:yce,normal_fragment_maps:Dce,normal_pars_fragment:mce,normal_pars_vertex:Sce,normal_vertex:wce,normalmap_pars_fragment:kce,clearcoat_normal_fragment_begin:Mce,clearcoat_normal_fragment_maps:Nce,clearcoat_pars_fragment:Rce,iridescence_pars_fragment:Gce,opaque_fragment:bce,packing:Uce,premultiplied_alpha_fragment:vce,project_vertex:Kce,dithering_fragment:Fce,dithering_pars_fragment:_ce,roughnessmap_fragment:Jce,roughnessmap_pars_fragment:Lce,shadowmap_pars_fragment:xce,shadowmap_pars_vertex:Tce,shadowmap_vertex:qce,shadowmask_pars_fragment:Yce,skinbase_vertex:Hce,skinning_pars_vertex:Oce,skinning_vertex:Pce,skinnormal_vertex:jce,specularmap_fragment:zce,specularmap_pars_fragment:Zce,tonemapping_fragment:Wce,tonemapping_pars_fragment:Vce,transmission_fragment:Xce,transmission_pars_fragment:$ce,uv_pars_fragment:Ale,uv_pars_vertex:ele,uv_vertex:tle,worldpos_vertex:ile,background_vert:nle,background_frag:gle,backgroundCube_vert:ole,backgroundCube_frag:sle,cube_vert:ale,cube_frag:rle,depth_vert:Ile,depth_frag:Cle,distanceRGBA_vert:cle,distanceRGBA_frag:lle,equirect_vert:Ble,equirect_frag:Ele,linedashed_vert:Qle,linedashed_frag:ule,meshbasic_vert:dle,meshbasic_frag:hle,meshlambert_vert:ple,meshlambert_frag:fle,meshmatcap_vert:yle,meshmatcap_frag:Dle,meshnormal_vert:mle,meshnormal_frag:Sle,meshphong_vert:wle,meshphong_frag:kle,meshphysical_vert:Mle,meshphysical_frag:Nle,meshtoon_vert:Rle,meshtoon_frag:Gle,points_vert:ble,points_frag:Ule,shadow_vert:vle,shadow_frag:Kle,sprite_vert:Fle,sprite_frag:_le},Pt={common:{diffuse:{value:new Et(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new An},alphaMap:{value:null},alphaMapTransform:{value:new An},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new An}},envmap:{envMap:{value:null},envMapRotation:{value:new An},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new An}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new An}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new An},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new An},normalScale:{value:new lt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new An},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new An}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new An}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new An}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Et(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Et(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new An},alphaTest:{value:0},uvTransform:{value:new An}},sprite:{diffuse:{value:new Et(16777215)},opacity:{value:1},center:{value:new lt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new An},alphaMap:{value:null},alphaMapTransform:{value:new An},alphaTest:{value:0}}},xc={basic:{uniforms:Er([Pt.common,Pt.specularmap,Pt.envmap,Pt.aomap,Pt.lightmap,Pt.fog]),vertexShader:cn.meshbasic_vert,fragmentShader:cn.meshbasic_frag},lambert:{uniforms:Er([Pt.common,Pt.specularmap,Pt.envmap,Pt.aomap,Pt.lightmap,Pt.emissivemap,Pt.bumpmap,Pt.normalmap,Pt.displacementmap,Pt.fog,Pt.lights,{emissive:{value:new Et(0)}}]),vertexShader:cn.meshlambert_vert,fragmentShader:cn.meshlambert_frag},phong:{uniforms:Er([Pt.common,Pt.specularmap,Pt.envmap,Pt.aomap,Pt.lightmap,Pt.emissivemap,Pt.bumpmap,Pt.normalmap,Pt.displacementmap,Pt.fog,Pt.lights,{emissive:{value:new Et(0)},specular:{value:new Et(1118481)},shininess:{value:30}}]),vertexShader:cn.meshphong_vert,fragmentShader:cn.meshphong_frag},standard:{uniforms:Er([Pt.common,Pt.envmap,Pt.aomap,Pt.lightmap,Pt.emissivemap,Pt.bumpmap,Pt.normalmap,Pt.displacementmap,Pt.roughnessmap,Pt.metalnessmap,Pt.fog,Pt.lights,{emissive:{value:new Et(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:cn.meshphysical_vert,fragmentShader:cn.meshphysical_frag},toon:{uniforms:Er([Pt.common,Pt.aomap,Pt.lightmap,Pt.emissivemap,Pt.bumpmap,Pt.normalmap,Pt.displacementmap,Pt.gradientmap,Pt.fog,Pt.lights,{emissive:{value:new Et(0)}}]),vertexShader:cn.meshtoon_vert,fragmentShader:cn.meshtoon_frag},matcap:{uniforms:Er([Pt.common,Pt.bumpmap,Pt.normalmap,Pt.displacementmap,Pt.fog,{matcap:{value:null}}]),vertexShader:cn.meshmatcap_vert,fragmentShader:cn.meshmatcap_frag},points:{uniforms:Er([Pt.points,Pt.fog]),vertexShader:cn.points_vert,fragmentShader:cn.points_frag},dashed:{uniforms:Er([Pt.common,Pt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:cn.linedashed_vert,fragmentShader:cn.linedashed_frag},depth:{uniforms:Er([Pt.common,Pt.displacementmap]),vertexShader:cn.depth_vert,fragmentShader:cn.depth_frag},normal:{uniforms:Er([Pt.common,Pt.bumpmap,Pt.normalmap,Pt.displacementmap,{opacity:{value:1}}]),vertexShader:cn.meshnormal_vert,fragmentShader:cn.meshnormal_frag},sprite:{uniforms:Er([Pt.sprite,Pt.fog]),vertexShader:cn.sprite_vert,fragmentShader:cn.sprite_frag},background:{uniforms:{uvTransform:{value:new An},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:cn.background_vert,fragmentShader:cn.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new An}},vertexShader:cn.backgroundCube_vert,fragmentShader:cn.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:cn.cube_vert,fragmentShader:cn.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:cn.equirect_vert,fragmentShader:cn.equirect_frag},distanceRGBA:{uniforms:Er([Pt.common,Pt.displacementmap,{referencePosition:{value:new SA},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:cn.distanceRGBA_vert,fragmentShader:cn.distanceRGBA_frag},shadow:{uniforms:Er([Pt.lights,Pt.fog,{color:{value:new Et(0)},opacity:{value:1}}]),vertexShader:cn.shadow_vert,fragmentShader:cn.shadow_frag}};xc.physical={uniforms:Er([xc.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new An},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new An},clearcoatNormalScale:{value:new lt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new An},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new An},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new An},sheen:{value:0},sheenColor:{value:new Et(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new An},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new An},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new An},transmissionSamplerSize:{value:new lt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new An},attenuationDistance:{value:0},attenuationColor:{value:new Et(0)},specularColor:{value:new Et(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new An},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new An},anisotropyVector:{value:new lt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new An}}]),vertexShader:cn.meshphysical_vert,fragmentShader:cn.meshphysical_frag};const zU={r:0,b:0,g:0},Gh=new ca,Jle=new ni;function Lle(e,A,t,i,n,g,o){const s=new Et(0);let a=g===!0?0:1,r,I,c=null,l=0,B=null;function Q(m){let D=m.isScene===!0?m.background:null;return D&&D.isTexture&&(D=(m.backgroundBlurriness>0?t:A).get(D)),D}function h(m){let D=!1;const S=Q(m);S===null?p(s,a):S&&S.isColor&&(p(S,1),D=!0);const k=e.xr.getEnvironmentBlendMode();k==="additive"?i.buffers.color.setClear(0,0,0,1,o):k==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,o),(e.autoClear||D)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function d(m,D){const S=Q(D);S&&(S.isCubeTexture||S.mapping===Kw)?(I===void 0&&(I=new pn(new sI(1,1,1),new Cc({name:"BackgroundCubeMaterial",uniforms:jS(xc.backgroundCube.uniforms),vertexShader:xc.backgroundCube.vertexShader,fragmentShader:xc.backgroundCube.fragmentShader,side:Ua,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),I.geometry.deleteAttribute("normal"),I.geometry.deleteAttribute("uv"),I.onBeforeRender=function(k,N,G){this.matrixWorld.copyPosition(G.matrixWorld)},Object.defineProperty(I.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(I)),Gh.copy(D.backgroundRotation),Gh.x*=-1,Gh.y*=-1,Gh.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(Gh.y*=-1,Gh.z*=-1),I.material.uniforms.envMap.value=S,I.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,I.material.uniforms.backgroundBlurriness.value=D.backgroundBlurriness,I.material.uniforms.backgroundIntensity.value=D.backgroundIntensity,I.material.uniforms.backgroundRotation.value.setFromMatrix4(Jle.makeRotationFromEuler(Gh)),I.material.toneMapped=Un.getTransfer(S.colorSpace)!==mg,(c!==S||l!==S.version||B!==e.toneMapping)&&(I.material.needsUpdate=!0,c=S,l=S.version,B=e.toneMapping),I.layers.enableAll(),m.unshift(I,I.geometry,I.material,0,0,null)):S&&S.isTexture&&(r===void 0&&(r=new pn(new oB(2,2),new Cc({name:"BackgroundMaterial",uniforms:jS(xc.background.uniforms),vertexShader:xc.background.vertexShader,fragmentShader:xc.background.fragmentShader,side:tl,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),r.geometry.deleteAttribute("normal"),Object.defineProperty(r.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(r)),r.material.uniforms.t2D.value=S,r.material.uniforms.backgroundIntensity.value=D.backgroundIntensity,r.material.toneMapped=Un.getTransfer(S.colorSpace)!==mg,S.matrixAutoUpdate===!0&&S.updateMatrix(),r.material.uniforms.uvTransform.value.copy(S.matrix),(c!==S||l!==S.version||B!==e.toneMapping)&&(r.material.needsUpdate=!0,c=S,l=S.version,B=e.toneMapping),r.layers.enableAll(),m.unshift(r,r.geometry,r.material,0,0,null))}function p(m,D){m.getRGB(zU,oyA(e)),i.buffers.color.setClear(zU.r,zU.g,zU.b,D,o)}function y(){I!==void 0&&(I.geometry.dispose(),I.material.dispose(),I=void 0),r!==void 0&&(r.geometry.dispose(),r.material.dispose(),r=void 0)}return{getClearColor:function(){return s},setClearColor:function(m,D=1){s.set(m),a=D,p(s,a)},getClearAlpha:function(){return a},setClearAlpha:function(m){a=m,p(s,a)},render:h,addToRenderList:d,dispose:y}}function xle(e,A){const t=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},n=l(null);let g=n,o=!1;function s(w,b,_,K,J){let q=!1;const v=c(K,_,b);g!==v&&(g=v,r(g.object)),q=B(w,K,_,J),q&&Q(w,K,_,J),J!==null&&A.update(J,e.ELEMENT_ARRAY_BUFFER),(q||o)&&(o=!1,D(w,b,_,K),J!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,A.get(J).buffer))}function a(){return e.createVertexArray()}function r(w){return e.bindVertexArray(w)}function I(w){return e.deleteVertexArray(w)}function c(w,b,_){const K=_.wireframe===!0;let J=i[w.id];J===void 0&&(J={},i[w.id]=J);let q=J[b.id];q===void 0&&(q={},J[b.id]=q);let v=q[K];return v===void 0&&(v=l(a()),q[K]=v),v}function l(w){const b=[],_=[],K=[];for(let J=0;J<t;J++)b[J]=0,_[J]=0,K[J]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:b,enabledAttributes:_,attributeDivisors:K,object:w,attributes:{},index:null}}function B(w,b,_,K){const J=g.attributes,q=b.attributes;let v=0;const U=_.getAttributes();for(const x in U)if(U[x].location>=0){const z=J[x];let Z=q[x];if(Z===void 0&&(x==="instanceMatrix"&&w.instanceMatrix&&(Z=w.instanceMatrix),x==="instanceColor"&&w.instanceColor&&(Z=w.instanceColor)),z===void 0||z.attribute!==Z||Z&&z.data!==Z.data)return!0;v++}return g.attributesNum!==v||g.index!==K}function Q(w,b,_,K){const J={},q=b.attributes;let v=0;const U=_.getAttributes();for(const x in U)if(U[x].location>=0){let z=q[x];z===void 0&&(x==="instanceMatrix"&&w.instanceMatrix&&(z=w.instanceMatrix),x==="instanceColor"&&w.instanceColor&&(z=w.instanceColor));const Z={};Z.attribute=z,z&&z.data&&(Z.data=z.data),J[x]=Z,v++}g.attributes=J,g.attributesNum=v,g.index=K}function h(){const w=g.newAttributes;for(let b=0,_=w.length;b<_;b++)w[b]=0}function d(w){p(w,0)}function p(w,b){const _=g.newAttributes,K=g.enabledAttributes,J=g.attributeDivisors;_[w]=1,K[w]===0&&(e.enableVertexAttribArray(w),K[w]=1),J[w]!==b&&(e.vertexAttribDivisor(w,b),J[w]=b)}function y(){const w=g.newAttributes,b=g.enabledAttributes;for(let _=0,K=b.length;_<K;_++)b[_]!==w[_]&&(e.disableVertexAttribArray(_),b[_]=0)}function m(w,b,_,K,J,q,v){v===!0?e.vertexAttribIPointer(w,b,_,J,q):e.vertexAttribPointer(w,b,_,K,J,q)}function D(w,b,_,K){h();const J=K.attributes,q=_.getAttributes(),v=b.defaultAttributeValues;for(const U in q){const x=q[U];if(x.location>=0){let T=J[U];if(T===void 0&&(U==="instanceMatrix"&&w.instanceMatrix&&(T=w.instanceMatrix),U==="instanceColor"&&w.instanceColor&&(T=w.instanceColor)),T!==void 0){const z=T.normalized,Z=T.itemSize,eA=A.get(T);if(eA===void 0)continue;const aA=eA.buffer,sA=eA.type,pA=eA.bytesPerElement,gA=sA===e.INT||sA===e.UNSIGNED_INT||T.gpuType===Fx;if(T.isInterleavedBufferAttribute){const yA=T.data,fA=yA.stride,RA=T.offset;if(yA.isInstancedInterleavedBuffer){for(let qA=0;qA<x.locationSize;qA++)p(x.location+qA,yA.meshPerAttribute);w.isInstancedMesh!==!0&&K._maxInstanceCount===void 0&&(K._maxInstanceCount=yA.meshPerAttribute*yA.count)}else for(let qA=0;qA<x.locationSize;qA++)d(x.location+qA);e.bindBuffer(e.ARRAY_BUFFER,aA);for(let qA=0;qA<x.locationSize;qA++)m(x.location+qA,Z/x.locationSize,sA,z,fA*pA,(RA+Z/x.locationSize*qA)*pA,gA)}else{if(T.isInstancedBufferAttribute){for(let yA=0;yA<x.locationSize;yA++)p(x.location+yA,T.meshPerAttribute);w.isInstancedMesh!==!0&&K._maxInstanceCount===void 0&&(K._maxInstanceCount=T.meshPerAttribute*T.count)}else for(let yA=0;yA<x.locationSize;yA++)d(x.location+yA);e.bindBuffer(e.ARRAY_BUFFER,aA);for(let yA=0;yA<x.locationSize;yA++)m(x.location+yA,Z/x.locationSize,sA,z,Z*pA,Z/x.locationSize*yA*pA,gA)}}else if(v!==void 0){const z=v[U];if(z!==void 0)switch(z.length){case 2:e.vertexAttrib2fv(x.location,z);break;case 3:e.vertexAttrib3fv(x.location,z);break;case 4:e.vertexAttrib4fv(x.location,z);break;default:e.vertexAttrib1fv(x.location,z)}}}}y()}function S(){G();for(const w in i){const b=i[w];for(const _ in b){const K=b[_];for(const J in K)I(K[J].object),delete K[J];delete b[_]}delete i[w]}}function k(w){if(i[w.id]===void 0)return;const b=i[w.id];for(const _ in b){const K=b[_];for(const J in K)I(K[J].object),delete K[J];delete b[_]}delete i[w.id]}function N(w){for(const b in i){const _=i[b];if(_[w.id]===void 0)continue;const K=_[w.id];for(const J in K)I(K[J].object),delete K[J];delete _[w.id]}}function G(){M(),o=!0,g!==n&&(g=n,r(g.object))}function M(){n.geometry=null,n.program=null,n.wireframe=!1}return{setup:s,reset:G,resetDefaultState:M,dispose:S,releaseStatesOfGeometry:k,releaseStatesOfProgram:N,initAttributes:h,enableAttribute:d,disableUnusedAttributes:y}}function Tle(e,A,t){let i;function n(r){i=r}function g(r,I){e.drawArrays(i,r,I),t.update(I,i,1)}function o(r,I,c){c!==0&&(e.drawArraysInstanced(i,r,I,c),t.update(I,i,c))}function s(r,I,c){if(c===0)return;A.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,r,0,I,0,c);let B=0;for(let Q=0;Q<c;Q++)B+=I[Q];t.update(B,i,1)}function a(r,I,c,l){if(c===0)return;const B=A.get("WEBGL_multi_draw");if(B===null)for(let Q=0;Q<r.length;Q++)o(r[Q],I[Q],l[Q]);else{B.multiDrawArraysInstancedWEBGL(i,r,0,I,0,l,0,c);let Q=0;for(let h=0;h<c;h++)Q+=I[h]*l[h];t.update(Q,i,1)}}this.setMode=n,this.render=g,this.renderInstances=o,this.renderMultiDraw=s,this.renderMultiDrawInstances=a}function qle(e,A,t,i){let n;function g(){if(n!==void 0)return n;if(A.has("EXT_texture_filter_anisotropic")===!0){const N=A.get("EXT_texture_filter_anisotropic");n=e.getParameter(N.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else n=0;return n}function o(N){return!(N!==Ar&&i.convert(N)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))}function s(N){const G=N===ny&&(A.has("EXT_color_buffer_half_float")||A.has("EXT_color_buffer_float"));return!(N!==Ic&&i.convert(N)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&N!==br&&!G)}function a(N){if(N==="highp"){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";N="mediump"}return N==="mediump"&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let r=t.precision!==void 0?t.precision:"highp";const I=a(r);I!==r&&(console.warn("THREE.WebGLRenderer:",r,"not supported, using",I,"instead."),r=I);const c=t.logarithmicDepthBuffer===!0,l=t.reversedDepthBuffer===!0&&A.has("EXT_clip_control"),B=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Q=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),d=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),p=e.getParameter(e.MAX_VERTEX_ATTRIBS),y=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),m=e.getParameter(e.MAX_VARYING_VECTORS),D=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),S=Q>0,k=e.getParameter(e.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:g,getMaxPrecision:a,textureFormatReadable:o,textureTypeReadable:s,precision:r,logarithmicDepthBuffer:c,reversedDepthBuffer:l,maxTextures:B,maxVertexTextures:Q,maxTextureSize:h,maxCubemapSize:d,maxAttributes:p,maxVertexUniforms:y,maxVaryings:m,maxFragmentUniforms:D,vertexTextures:S,maxSamples:k}}function Yle(e){const A=this;let t=null,i=0,n=!1,g=!1;const o=new eu,s=new An,a={value:null,needsUpdate:!1};this.uniform=a,this.numPlanes=0,this.numIntersection=0,this.init=function(c,l){const B=c.length!==0||l||i!==0||n;return n=l,i=c.length,B},this.beginShadows=function(){g=!0,I(null)},this.endShadows=function(){g=!1},this.setGlobalState=function(c,l){t=I(c,l,0)},this.setState=function(c,l,B){const Q=c.clippingPlanes,h=c.clipIntersection,d=c.clipShadows,p=e.get(c);if(!n||Q===null||Q.length===0||g&&!d)g?I(null):r();else{const y=g?0:i,m=y*4;let D=p.clippingState||null;a.value=D,D=I(Q,l,m,B);for(let S=0;S!==m;++S)D[S]=t[S];p.clippingState=D,this.numIntersection=h?this.numPlanes:0,this.numPlanes+=y}};function r(){a.value!==t&&(a.value=t,a.needsUpdate=i>0),A.numPlanes=i,A.numIntersection=0}function I(c,l,B,Q){const h=c!==null?c.length:0;let d=null;if(h!==0){if(d=a.value,Q!==!0||d===null){const p=B+h*4,y=l.matrixWorldInverse;s.getNormalMatrix(y),(d===null||d.length<p)&&(d=new Float32Array(p));for(let m=0,D=B;m!==h;++m,D+=4)o.copy(c[m]).applyMatrix4(y,s),o.normal.toArray(d,D),d[D+3]=o.constant}a.value=d,a.needsUpdate=!0}return A.numPlanes=h,A.numIntersection=0,d}}function Hle(e){let A=new WeakMap;function t(o,s){return s===NN?o.mapping=rQ:s===RN&&(o.mapping=ud),o}function i(o){if(o&&o.isTexture){const s=o.mapping;if(s===NN||s===RN)if(A.has(o)){const a=A.get(o).texture;return t(a,o.mapping)}else{const a=o.image;if(a&&a.height>0){const r=new ayA(a.height);return r.fromEquirectangularTexture(e,o),A.set(o,r),o.addEventListener("dispose",n),t(r.texture,o.mapping)}else return null}}return o}function n(o){const s=o.target;s.removeEventListener("dispose",n);const a=A.get(s);a!==void 0&&(A.delete(s),a.dispose())}function g(){A=new WeakMap}return{get:i,dispose:g}}const rm=4,JnA=[.125,.215,.35,.446,.526,.582],sp=20,JH=new Hd,LnA=new Et;let LH=null,xH=0,TH=0,qH=!1;const $h=(1+Math.sqrt(5))/2,dD=1/$h,xnA=[new SA(-$h,dD,0),new SA($h,dD,0),new SA(-dD,0,$h),new SA(dD,0,$h),new SA(0,$h,-dD),new SA(0,$h,dD),new SA(-1,1,-1),new SA(1,1,-1),new SA(-1,1,1),new SA(1,1,1)],Ole=new SA;class mJ{constructor(A){this._renderer=A,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(A,t=0,i=.1,n=100,g={}){const{size:o=256,position:s=Ole}=g;LH=this._renderer.getRenderTarget(),xH=this._renderer.getActiveCubeFace(),TH=this._renderer.getActiveMipmapLevel(),qH=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const a=this._allocateTargets();return a.depthBuffer=!0,this._sceneToCubeUV(A,i,n,a,s),t>0&&this._blur(a,0,0,t),this._applyPMREM(a),this._cleanup(a),a}fromEquirectangular(A,t=null){return this._fromTexture(A,t)}fromCubemap(A,t=null){return this._fromTexture(A,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=YnA(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=qnA(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(A){this._lodMax=Math.floor(Math.log2(A)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let A=0;A<this._lodPlanes.length;A++)this._lodPlanes[A].dispose()}_cleanup(A){this._renderer.setRenderTarget(LH,xH,TH),this._renderer.xr.enabled=qH,A.scissorTest=!1,ZU(A,0,0,A.width,A.height)}_fromTexture(A,t){A.mapping===rQ||A.mapping===ud?this._setSize(A.image.length===0?16:A.image[0].width||A.image[0].image.width):this._setSize(A.image.width/4),LH=this._renderer.getRenderTarget(),xH=this._renderer.getActiveCubeFace(),TH=this._renderer.getActiveMipmapLevel(),qH=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const i=t||this._allocateTargets();return this._textureToCubeUV(A,i),this._applyPMREM(i),this._cleanup(i),i}_allocateTargets(){const A=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,i={magFilter:qg,minFilter:qg,generateMipmaps:!1,type:ny,format:Ar,colorSpace:Ka,depthBuffer:!1},n=TnA(A,t,i);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==A||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=TnA(A,t,i);const{_lodMax:g}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=Ple(g)),this._blurMaterial=jle(g,A,t)}return n}_compileMaterial(A){const t=new pn(this._lodPlanes[0],A);this._renderer.compile(t,JH)}_sceneToCubeUV(A,t,i,n,g){const a=new Wo(90,1,t,i),r=[1,-1,1,1,1,1],I=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,B=c.toneMapping;c.getClearColor(LnA),c.toneMapping=QB,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(n),c.clearDepth(),c.setRenderTarget(null));const h=new kg({name:"PMREM.Background",side:Ua,depthWrite:!1,depthTest:!1}),d=new pn(new sI,h);let p=!1;const y=A.background;y?y.isColor&&(h.color.copy(y),A.background=null,p=!0):(h.color.copy(LnA),p=!0);for(let m=0;m<6;m++){const D=m%3;D===0?(a.up.set(0,r[m],0),a.position.set(g.x,g.y,g.z),a.lookAt(g.x+I[m],g.y,g.z)):D===1?(a.up.set(0,0,r[m]),a.position.set(g.x,g.y,g.z),a.lookAt(g.x,g.y+I[m],g.z)):(a.up.set(0,r[m],0),a.position.set(g.x,g.y,g.z),a.lookAt(g.x,g.y,g.z+I[m]));const S=this._cubeSize;ZU(n,D*S,m>2?S:0,S,S),c.setRenderTarget(n),p&&c.render(d,a),c.render(A,a)}d.geometry.dispose(),d.material.dispose(),c.toneMapping=B,c.autoClear=l,A.background=y}_textureToCubeUV(A,t){const i=this._renderer,n=A.mapping===rQ||A.mapping===ud;n?(this._cubemapMaterial===null&&(this._cubemapMaterial=YnA()),this._cubemapMaterial.uniforms.flipEnvMap.value=A.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=qnA());const g=n?this._cubemapMaterial:this._equirectMaterial,o=new pn(this._lodPlanes[0],g),s=g.uniforms;s.envMap.value=A;const a=this._cubeSize;ZU(t,0,0,3*a,2*a),i.setRenderTarget(t),i.render(o,JH)}_applyPMREM(A){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const n=this._lodPlanes.length;for(let g=1;g<n;g++){const o=Math.sqrt(this._sigmas[g]*this._sigmas[g]-this._sigmas[g-1]*this._sigmas[g-1]),s=xnA[(n-g-1)%xnA.length];this._blur(A,g-1,g,o,s)}t.autoClear=i}_blur(A,t,i,n,g){const o=this._pingPongRenderTarget;this._halfBlur(A,o,t,i,n,"latitudinal",g),this._halfBlur(o,A,i,i,n,"longitudinal",g)}_halfBlur(A,t,i,n,g,o,s){const a=this._renderer,r=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const I=3,c=new pn(this._lodPlanes[n],r),l=r.uniforms,B=this._sizeLods[i]-1,Q=isFinite(g)?Math.PI/(2*B):2*Math.PI/(2*sp-1),h=g/Q,d=isFinite(g)?1+Math.floor(I*h):sp;d>sp&&console.warn(`sigmaRadians, ${g}, is too large and will clip, as it requested ${d} samples when the maximum is set to ${sp}`);const p=[];let y=0;for(let N=0;N<sp;++N){const G=N/h,M=Math.exp(-G*G/2);p.push(M),N===0?y+=M:N<d&&(y+=2*M)}for(let N=0;N<p.length;N++)p[N]=p[N]/y;l.envMap.value=A.texture,l.samples.value=d,l.weights.value=p,l.latitudinal.value=o==="latitudinal",s&&(l.poleAxis.value=s);const{_lodMax:m}=this;l.dTheta.value=Q,l.mipInt.value=m-i;const D=this._sizeLods[n],S=3*D*(n>m-rm?n-m+rm:0),k=4*(this._cubeSize-D);ZU(t,S,k,3*D,2*D),a.setRenderTarget(t),a.render(c,JH)}}function Ple(e){const A=[],t=[],i=[];let n=e;const g=e-rm+1+JnA.length;for(let o=0;o<g;o++){const s=Math.pow(2,n);t.push(s);let a=1/s;o>e-rm?a=JnA[o-e+rm-1]:o===0&&(a=0),i.push(a);const r=1/(s-2),I=-r,c=1+r,l=[I,I,c,I,c,c,I,I,c,c,I,c],B=6,Q=6,h=3,d=2,p=1,y=new Float32Array(h*Q*B),m=new Float32Array(d*Q*B),D=new Float32Array(p*Q*B);for(let k=0;k<B;k++){const N=k%3*2/3-1,G=k>2?0:-1,M=[N,G,0,N+2/3,G,0,N+2/3,G+1,0,N,G,0,N+2/3,G+1,0,N,G+1,0];y.set(M,h*Q*k),m.set(l,d*Q*k);const w=[k,k,k,k,k,k];D.set(w,p*Q*k)}const S=new Ni;S.setAttribute("position",new ji(y,h)),S.setAttribute("uv",new ji(m,d)),S.setAttribute("faceIndex",new ji(D,p)),A.push(S),n>rm&&n--}return{lodPlanes:A,sizeLods:t,sigmas:i}}function TnA(e,A,t){const i=new il(e,A,t);return i.texture.mapping=Kw,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function ZU(e,A,t,i,n){e.viewport.set(A,t,i,n),e.scissor.set(A,t,i,n)}function jle(e,A,t){const i=new Float32Array(sp),n=new SA(0,1,0);return new Cc({name:"SphericalGaussianBlur",defines:{n:sp,CUBEUV_TEXEL_WIDTH:1/A,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:uV(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;
			uniform int samples;
			uniform float weights[ n ];
			uniform bool latitudinal;
			uniform float dTheta;
			uniform float mipInt;
			uniform vec3 poleAxis;

			#define ENVMAP_TYPE_CUBE_UV
			#include <cube_uv_reflection_fragment>

			vec3 getSample( float theta, vec3 axis ) {

				float cosTheta = cos( theta );
				// Rodrigues' axis-angle rotation
				vec3 sampleDirection = vOutputDirection * cosTheta
					+ cross( axis, vOutputDirection ) * sin( theta )
					+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );

				return bilinearCubeUV( envMap, sampleDirection, mipInt );

			}

			void main() {

				vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );

				if ( all( equal( axis, vec3( 0.0 ) ) ) ) {

					axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );

				}

				axis = normalize( axis );

				gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
				gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );

				for ( int i = 1; i < n; i++ ) {

					if ( i >= samples ) {

						break;

					}

					float theta = dTheta * float( i );
					gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
					gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );

				}

			}
		`,blending:TE,depthTest:!1,depthWrite:!1})}function qnA(){return new Cc({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:uV(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;

			#include <common>

			void main() {

				vec3 outputDirection = normalize( vOutputDirection );
				vec2 uv = equirectUv( outputDirection );

				gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );

			}
		`,blending:TE,depthTest:!1,depthWrite:!1})}function YnA(){return new Cc({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:uV(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			uniform float flipEnvMap;

			varying vec3 vOutputDirection;

			uniform samplerCube envMap;

			void main() {

				gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );

			}
		`,blending:TE,depthTest:!1,depthWrite:!1})}function uV(){return`

		precision mediump float;
		precision mediump int;

		attribute float faceIndex;

		varying vec3 vOutputDirection;

		// RH coordinate system; PMREM face-indexing convention
		vec3 getDirection( vec2 uv, float face ) {

			uv = 2.0 * uv - 1.0;

			vec3 direction = vec3( uv, 1.0 );

			if ( face == 0.0 ) {

				direction = direction.zyx; // ( 1, v, u ) pos x

			} else if ( face == 1.0 ) {

				direction = direction.xzy;
				direction.xz *= -1.0; // ( -u, 1, -v ) pos y

			} else if ( face == 2.0 ) {

				direction.x *= -1.0; // ( -u, v, 1 ) pos z

			} else if ( face == 3.0 ) {

				direction = direction.zyx;
				direction.xz *= -1.0; // ( -1, v, -u ) neg x

			} else if ( face == 4.0 ) {

				direction = direction.xzy;
				direction.xy *= -1.0; // ( -u, -1, v ) neg y

			} else if ( face == 5.0 ) {

				direction.z *= -1.0; // ( u, v, -1 ) neg z

			}

			return direction;

		}

		void main() {

			vOutputDirection = getDirection( uv, faceIndex );
			gl_Position = vec4( position, 1.0 );

		}
	`}function zle(e){let A=new WeakMap,t=null;function i(s){if(s&&s.isTexture){const a=s.mapping,r=a===NN||a===RN,I=a===rQ||a===ud;if(r||I){let c=A.get(s);const l=c!==void 0?c.texture.pmremVersion:0;if(s.isRenderTargetTexture&&s.pmremVersion!==l)return t===null&&(t=new mJ(e)),c=r?t.fromEquirectangular(s,c):t.fromCubemap(s,c),c.texture.pmremVersion=s.pmremVersion,A.set(s,c),c.texture;if(c!==void 0)return c.texture;{const B=s.image;return r&&B&&B.height>0||I&&B&&n(B)?(t===null&&(t=new mJ(e)),c=r?t.fromEquirectangular(s):t.fromCubemap(s),c.texture.pmremVersion=s.pmremVersion,A.set(s,c),s.addEventListener("dispose",g),c.texture):null}}}return s}function n(s){let a=0;const r=6;for(let I=0;I<r;I++)s[I]!==void 0&&a++;return a===r}function g(s){const a=s.target;a.removeEventListener("dispose",g);const r=A.get(a);r!==void 0&&(A.delete(a),r.dispose())}function o(){A=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:i,dispose:o}}function Zle(e){const A={};function t(i){if(A[i]!==void 0)return A[i];let n;switch(i){case"WEBGL_depth_texture":n=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=e.getExtension(i)}return A[i]=n,n}return{has:function(i){return t(i)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(i){const n=t(i);return n===null&&KN("THREE.WebGLRenderer: "+i+" extension not supported."),n}}}function Wle(e,A,t,i){const n={},g=new WeakMap;function o(c){const l=c.target;l.index!==null&&A.remove(l.index);for(const Q in l.attributes)A.remove(l.attributes[Q]);l.removeEventListener("dispose",o),delete n[l.id];const B=g.get(l);B&&(A.remove(B),g.delete(l)),i.releaseStatesOfGeometry(l),l.isInstancedBufferGeometry===!0&&delete l._maxInstanceCount,t.memory.geometries--}function s(c,l){return n[l.id]===!0||(l.addEventListener("dispose",o),n[l.id]=!0,t.memory.geometries++),l}function a(c){const l=c.attributes;for(const B in l)A.update(l[B],e.ARRAY_BUFFER)}function r(c){const l=[],B=c.index,Q=c.attributes.position;let h=0;if(B!==null){const y=B.array;h=B.version;for(let m=0,D=y.length;m<D;m+=3){const S=y[m+0],k=y[m+1],N=y[m+2];l.push(S,k,k,N,N,S)}}else if(Q!==void 0){const y=Q.array;h=Q.version;for(let m=0,D=y.length/3-1;m<D;m+=3){const S=m+0,k=m+1,N=m+2;l.push(S,k,k,N,N,S)}}else return;const d=new(tyA(l)?TW:xW)(l,1);d.version=h;const p=g.get(c);p&&A.remove(p),g.set(c,d)}function I(c){const l=g.get(c);if(l){const B=c.index;B!==null&&l.version<B.version&&r(c)}else r(c);return g.get(c)}return{get:s,update:a,getWireframeAttribute:I}}function Vle(e,A,t){let i;function n(l){i=l}let g,o;function s(l){g=l.type,o=l.bytesPerElement}function a(l,B){e.drawElements(i,B,g,l*o),t.update(B,i,1)}function r(l,B,Q){Q!==0&&(e.drawElementsInstanced(i,B,g,l*o,Q),t.update(B,i,Q))}function I(l,B,Q){if(Q===0)return;A.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,B,0,g,l,0,Q);let d=0;for(let p=0;p<Q;p++)d+=B[p];t.update(d,i,1)}function c(l,B,Q,h){if(Q===0)return;const d=A.get("WEBGL_multi_draw");if(d===null)for(let p=0;p<l.length;p++)r(l[p]/o,B[p],h[p]);else{d.multiDrawElementsInstancedWEBGL(i,B,0,g,l,0,h,0,Q);let p=0;for(let y=0;y<Q;y++)p+=B[y]*h[y];t.update(p,i,1)}}this.setMode=n,this.setIndex=s,this.render=a,this.renderInstances=r,this.renderMultiDraw=I,this.renderMultiDrawInstances=c}function Xle(e){const A={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function i(g,o,s){switch(t.calls++,o){case e.TRIANGLES:t.triangles+=s*(g/3);break;case e.LINES:t.lines+=s*(g/2);break;case e.LINE_STRIP:t.lines+=s*(g-1);break;case e.LINE_LOOP:t.lines+=s*g;break;case e.POINTS:t.points+=s*g;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",o);break}}function n(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:A,render:t,programs:null,autoReset:!0,reset:n,update:i}}function $le(e,A,t){const i=new WeakMap,n=new ig;function g(o,s,a){const r=o.morphTargetInfluences,I=s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color,c=I!==void 0?I.length:0;let l=i.get(s);if(l===void 0||l.count!==c){let M=function(){N.dispose(),i.delete(s),s.removeEventListener("dispose",M)};l!==void 0&&l.texture.dispose();const B=s.morphAttributes.position!==void 0,Q=s.morphAttributes.normal!==void 0,h=s.morphAttributes.color!==void 0,d=s.morphAttributes.position||[],p=s.morphAttributes.normal||[],y=s.morphAttributes.color||[];let m=0;B===!0&&(m=1),Q===!0&&(m=2),h===!0&&(m=3);let D=s.attributes.position.count*m,S=1;D>A.maxTextureSize&&(S=Math.ceil(D/A.maxTextureSize),D=A.maxTextureSize);const k=new Float32Array(D*S*4*c),N=new Yx(k,D,S,c);N.type=br,N.needsUpdate=!0;const G=m*4;for(let w=0;w<c;w++){const b=d[w],_=p[w],K=y[w],J=D*S*4*w;for(let q=0;q<b.count;q++){const v=q*G;B===!0&&(n.fromBufferAttribute(b,q),k[J+v+0]=n.x,k[J+v+1]=n.y,k[J+v+2]=n.z,k[J+v+3]=0),Q===!0&&(n.fromBufferAttribute(_,q),k[J+v+4]=n.x,k[J+v+5]=n.y,k[J+v+6]=n.z,k[J+v+7]=0),h===!0&&(n.fromBufferAttribute(K,q),k[J+v+8]=n.x,k[J+v+9]=n.y,k[J+v+10]=n.z,k[J+v+11]=K.itemSize===4?n.w:1)}}l={count:c,texture:N,size:new lt(D,S)},i.set(s,l),s.addEventListener("dispose",M)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)a.getUniforms().setValue(e,"morphTexture",o.morphTexture,t);else{let B=0;for(let h=0;h<r.length;h++)B+=r[h];const Q=s.morphTargetsRelative?1:1-B;a.getUniforms().setValue(e,"morphTargetBaseInfluence",Q),a.getUniforms().setValue(e,"morphTargetInfluences",r)}a.getUniforms().setValue(e,"morphTargetsTexture",l.texture,t),a.getUniforms().setValue(e,"morphTargetsTextureSize",l.size)}return{update:g}}function ABe(e,A,t,i){let n=new WeakMap;function g(a){const r=i.render.frame,I=a.geometry,c=A.get(a,I);if(n.get(c)!==r&&(A.update(c),n.set(c,r)),a.isInstancedMesh&&(a.hasEventListener("dispose",s)===!1&&a.addEventListener("dispose",s),n.get(a)!==r&&(t.update(a.instanceMatrix,e.ARRAY_BUFFER),a.instanceColor!==null&&t.update(a.instanceColor,e.ARRAY_BUFFER),n.set(a,r))),a.isSkinnedMesh){const l=a.skeleton;n.get(l)!==r&&(l.update(),n.set(l,r))}return c}function o(){n=new WeakMap}function s(a){const r=a.target;r.removeEventListener("dispose",s),t.remove(r.instanceMatrix),r.instanceColor!==null&&t.remove(r.instanceColor)}return{update:g,dispose:o}}const jyA=new Kg,HnA=new Vx(1,1),zyA=new Yx,ZyA=new Hx,WyA=new sG,OnA=[],PnA=[],jnA=new Float32Array(16),znA=new Float32Array(9),ZnA=new Float32Array(4);function xw(e,A,t){const i=e[0];if(i<=0||i>0)return e;const n=A*t;let g=OnA[n];if(g===void 0&&(g=new Float32Array(n),OnA[n]=g),A!==0){i.toArray(g,0);for(let o=1,s=0;o!==A;++o)s+=t,e[o].toArray(g,s)}return g}function Ys(e,A){if(e.length!==A.length)return!1;for(let t=0,i=e.length;t<i;t++)if(e[t]!==A[t])return!1;return!0}function Hs(e,A){for(let t=0,i=A.length;t<i;t++)e[t]=A[t]}function lT(e,A){let t=PnA[A];t===void 0&&(t=new Int32Array(A),PnA[A]=t);for(let i=0;i!==A;++i)t[i]=e.allocateTextureUnit();return t}function eBe(e,A){const t=this.cache;t[0]!==A&&(e.uniform1f(this.addr,A),t[0]=A)}function tBe(e,A){const t=this.cache;if(A.x!==void 0)(t[0]!==A.x||t[1]!==A.y)&&(e.uniform2f(this.addr,A.x,A.y),t[0]=A.x,t[1]=A.y);else{if(Ys(t,A))return;e.uniform2fv(this.addr,A),Hs(t,A)}}function iBe(e,A){const t=this.cache;if(A.x!==void 0)(t[0]!==A.x||t[1]!==A.y||t[2]!==A.z)&&(e.uniform3f(this.addr,A.x,A.y,A.z),t[0]=A.x,t[1]=A.y,t[2]=A.z);else if(A.r!==void 0)(t[0]!==A.r||t[1]!==A.g||t[2]!==A.b)&&(e.uniform3f(this.addr,A.r,A.g,A.b),t[0]=A.r,t[1]=A.g,t[2]=A.b);else{if(Ys(t,A))return;e.uniform3fv(this.addr,A),Hs(t,A)}}function nBe(e,A){const t=this.cache;if(A.x!==void 0)(t[0]!==A.x||t[1]!==A.y||t[2]!==A.z||t[3]!==A.w)&&(e.uniform4f(this.addr,A.x,A.y,A.z,A.w),t[0]=A.x,t[1]=A.y,t[2]=A.z,t[3]=A.w);else{if(Ys(t,A))return;e.uniform4fv(this.addr,A),Hs(t,A)}}function gBe(e,A){const t=this.cache,i=A.elements;if(i===void 0){if(Ys(t,A))return;e.uniformMatrix2fv(this.addr,!1,A),Hs(t,A)}else{if(Ys(t,i))return;ZnA.set(i),e.uniformMatrix2fv(this.addr,!1,ZnA),Hs(t,i)}}function oBe(e,A){const t=this.cache,i=A.elements;if(i===void 0){if(Ys(t,A))return;e.uniformMatrix3fv(this.addr,!1,A),Hs(t,A)}else{if(Ys(t,i))return;znA.set(i),e.uniformMatrix3fv(this.addr,!1,znA),Hs(t,i)}}function sBe(e,A){const t=this.cache,i=A.elements;if(i===void 0){if(Ys(t,A))return;e.uniformMatrix4fv(this.addr,!1,A),Hs(t,A)}else{if(Ys(t,i))return;jnA.set(i),e.uniformMatrix4fv(this.addr,!1,jnA),Hs(t,i)}}function aBe(e,A){const t=this.cache;t[0]!==A&&(e.uniform1i(this.addr,A),t[0]=A)}function rBe(e,A){const t=this.cache;if(A.x!==void 0)(t[0]!==A.x||t[1]!==A.y)&&(e.uniform2i(this.addr,A.x,A.y),t[0]=A.x,t[1]=A.y);else{if(Ys(t,A))return;e.uniform2iv(this.addr,A),Hs(t,A)}}function IBe(e,A){const t=this.cache;if(A.x!==void 0)(t[0]!==A.x||t[1]!==A.y||t[2]!==A.z)&&(e.uniform3i(this.addr,A.x,A.y,A.z),t[0]=A.x,t[1]=A.y,t[2]=A.z);else{if(Ys(t,A))return;e.uniform3iv(this.addr,A),Hs(t,A)}}function CBe(e,A){const t=this.cache;if(A.x!==void 0)(t[0]!==A.x||t[1]!==A.y||t[2]!==A.z||t[3]!==A.w)&&(e.uniform4i(this.addr,A.x,A.y,A.z,A.w),t[0]=A.x,t[1]=A.y,t[2]=A.z,t[3]=A.w);else{if(Ys(t,A))return;e.uniform4iv(this.addr,A),Hs(t,A)}}function cBe(e,A){const t=this.cache;t[0]!==A&&(e.uniform1ui(this.addr,A),t[0]=A)}function lBe(e,A){const t=this.cache;if(A.x!==void 0)(t[0]!==A.x||t[1]!==A.y)&&(e.uniform2ui(this.addr,A.x,A.y),t[0]=A.x,t[1]=A.y);else{if(Ys(t,A))return;e.uniform2uiv(this.addr,A),Hs(t,A)}}function BBe(e,A){const t=this.cache;if(A.x!==void 0)(t[0]!==A.x||t[1]!==A.y||t[2]!==A.z)&&(e.uniform3ui(this.addr,A.x,A.y,A.z),t[0]=A.x,t[1]=A.y,t[2]=A.z);else{if(Ys(t,A))return;e.uniform3uiv(this.addr,A),Hs(t,A)}}function EBe(e,A){const t=this.cache;if(A.x!==void 0)(t[0]!==A.x||t[1]!==A.y||t[2]!==A.z||t[3]!==A.w)&&(e.uniform4ui(this.addr,A.x,A.y,A.z,A.w),t[0]=A.x,t[1]=A.y,t[2]=A.z,t[3]=A.w);else{if(Ys(t,A))return;e.uniform4uiv(this.addr,A),Hs(t,A)}}function QBe(e,A,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n);let g;this.type===e.SAMPLER_2D_SHADOW?(HnA.compareFunction=_W,g=HnA):g=jyA,t.setTexture2D(A||g,n)}function uBe(e,A,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),t.setTexture3D(A||ZyA,n)}function dBe(e,A,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),t.setTextureCube(A||WyA,n)}function hBe(e,A,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),t.setTexture2DArray(A||zyA,n)}function pBe(e){switch(e){case 5126:return eBe;case 35664:return tBe;case 35665:return iBe;case 35666:return nBe;case 35674:return gBe;case 35675:return oBe;case 35676:return sBe;case 5124:case 35670:return aBe;case 35667:case 35671:return rBe;case 35668:case 35672:return IBe;case 35669:case 35673:return CBe;case 5125:return cBe;case 36294:return lBe;case 36295:return BBe;case 36296:return EBe;case 35678:case 36198:case 36298:case 36306:case 35682:return QBe;case 35679:case 36299:case 36307:return uBe;case 35680:case 36300:case 36308:case 36293:return dBe;case 36289:case 36303:case 36311:case 36292:return hBe}}function fBe(e,A){e.uniform1fv(this.addr,A)}function yBe(e,A){const t=xw(A,this.size,2);e.uniform2fv(this.addr,t)}function DBe(e,A){const t=xw(A,this.size,3);e.uniform3fv(this.addr,t)}function mBe(e,A){const t=xw(A,this.size,4);e.uniform4fv(this.addr,t)}function SBe(e,A){const t=xw(A,this.size,4);e.uniformMatrix2fv(this.addr,!1,t)}function wBe(e,A){const t=xw(A,this.size,9);e.uniformMatrix3fv(this.addr,!1,t)}function kBe(e,A){const t=xw(A,this.size,16);e.uniformMatrix4fv(this.addr,!1,t)}function MBe(e,A){e.uniform1iv(this.addr,A)}function NBe(e,A){e.uniform2iv(this.addr,A)}function RBe(e,A){e.uniform3iv(this.addr,A)}function GBe(e,A){e.uniform4iv(this.addr,A)}function bBe(e,A){e.uniform1uiv(this.addr,A)}function UBe(e,A){e.uniform2uiv(this.addr,A)}function vBe(e,A){e.uniform3uiv(this.addr,A)}function KBe(e,A){e.uniform4uiv(this.addr,A)}function FBe(e,A,t){const i=this.cache,n=A.length,g=lT(t,n);Ys(i,g)||(e.uniform1iv(this.addr,g),Hs(i,g));for(let o=0;o!==n;++o)t.setTexture2D(A[o]||jyA,g[o])}function _Be(e,A,t){const i=this.cache,n=A.length,g=lT(t,n);Ys(i,g)||(e.uniform1iv(this.addr,g),Hs(i,g));for(let o=0;o!==n;++o)t.setTexture3D(A[o]||ZyA,g[o])}function JBe(e,A,t){const i=this.cache,n=A.length,g=lT(t,n);Ys(i,g)||(e.uniform1iv(this.addr,g),Hs(i,g));for(let o=0;o!==n;++o)t.setTextureCube(A[o]||WyA,g[o])}function LBe(e,A,t){const i=this.cache,n=A.length,g=lT(t,n);Ys(i,g)||(e.uniform1iv(this.addr,g),Hs(i,g));for(let o=0;o!==n;++o)t.setTexture2DArray(A[o]||zyA,g[o])}function xBe(e){switch(e){case 5126:return fBe;case 35664:return yBe;case 35665:return DBe;case 35666:return mBe;case 35674:return SBe;case 35675:return wBe;case 35676:return kBe;case 5124:case 35670:return MBe;case 35667:case 35671:return NBe;case 35668:case 35672:return RBe;case 35669:case 35673:return GBe;case 5125:return bBe;case 36294:return UBe;case 36295:return vBe;case 36296:return KBe;case 35678:case 36198:case 36298:case 36306:case 35682:return FBe;case 35679:case 36299:case 36307:return _Be;case 35680:case 36300:case 36308:case 36293:return JBe;case 36289:case 36303:case 36311:case 36292:return LBe}}class TBe{constructor(A,t,i){this.id=A,this.addr=i,this.cache=[],this.type=t.type,this.setValue=pBe(t.type)}}class qBe{constructor(A,t,i){this.id=A,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=xBe(t.type)}}class YBe{constructor(A){this.id=A,this.seq=[],this.map={}}setValue(A,t,i){const n=this.seq;for(let g=0,o=n.length;g!==o;++g){const s=n[g];s.setValue(A,t[s.id],i)}}}const YH=/(\w+)(\])?(\[|\.)?/g;function WnA(e,A){e.seq.push(A),e.map[A.id]=A}function HBe(e,A,t){const i=e.name,n=i.length;for(YH.lastIndex=0;;){const g=YH.exec(i),o=YH.lastIndex;let s=g[1];const a=g[2]==="]",r=g[3];if(a&&(s=s|0),r===void 0||r==="["&&o+2===n){WnA(t,r===void 0?new TBe(s,e,A):new qBe(s,e,A));break}else{let c=t.map[s];c===void 0&&(c=new YBe(s),WnA(t,c)),t=c}}}class KK{constructor(A,t){this.seq=[],this.map={};const i=A.getProgramParameter(t,A.ACTIVE_UNIFORMS);for(let n=0;n<i;++n){const g=A.getActiveUniform(t,n),o=A.getUniformLocation(t,g.name);HBe(g,o,this)}}setValue(A,t,i,n){const g=this.map[t];g!==void 0&&g.setValue(A,i,n)}setOptional(A,t,i){const n=t[i];n!==void 0&&this.setValue(A,i,n)}static upload(A,t,i,n){for(let g=0,o=t.length;g!==o;++g){const s=t[g],a=i[s.id];a.needsUpdate!==!1&&s.setValue(A,a.value,n)}}static seqWithValue(A,t){const i=[];for(let n=0,g=A.length;n!==g;++n){const o=A[n];o.id in t&&i.push(o)}return i}}function VnA(e,A,t){const i=e.createShader(A);return e.shaderSource(i,t),e.compileShader(i),i}const OBe=37297;let PBe=0;function jBe(e,A){const t=e.split(`
`),i=[],n=Math.max(A-6,0),g=Math.min(A+6,t.length);for(let o=n;o<g;o++){const s=o+1;i.push(`${s===A?">":" "} ${s}: ${t[o]}`)}return i.join(`
`)}const XnA=new An;function zBe(e){Un._getMatrix(XnA,Un.workingColorSpace,e);const A=`mat3( ${XnA.elements.map(t=>t.toFixed(4))} )`;switch(Un.getTransfer(e)){case bN:return[A,"LinearTransferOETF"];case mg:return[A,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",e),[A,"LinearTransferOETF"]}}function $nA(e,A,t){const i=e.getShaderParameter(A,e.COMPILE_STATUS),g=(e.getShaderInfoLog(A)||"").trim();if(i&&g==="")return"";const o=/ERROR: 0:(\d+)/.exec(g);if(o){const s=parseInt(o[1]);return t.toUpperCase()+`

`+g+`

`+jBe(e.getShaderSource(A),s)}else return g}function ZBe(e,A){const t=zBe(A);return[`vec4 ${e}( vec4 value ) {`,`	return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(`
`)}function WBe(e,A){let t;switch(A){case _fA:t="Linear";break;case JfA:t="Reinhard";break;case LfA:t="Cineon";break;case iy:t="ACESFilmic";break;case TfA:t="AgX";break;case qfA:t="Neutral";break;case xfA:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",A),t="Linear"}return"vec3 "+e+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const WU=new SA;function VBe(){Un.getLuminanceCoefficients(WU);const e=WU.x.toFixed(4),A=WU.y.toFixed(4),t=WU.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",`	const vec3 weights = vec3( ${e}, ${A}, ${t} );`,"	return dot( weights, rgb );","}"].join(`
`)}function XBe(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Gk).join(`
`)}function $Be(e){const A=[];for(const t in e){const i=e[t];i!==!1&&A.push("#define "+t+" "+i)}return A.join(`
`)}function AEe(e,A){const t={},i=e.getProgramParameter(A,e.ACTIVE_ATTRIBUTES);for(let n=0;n<i;n++){const g=e.getActiveAttrib(A,n),o=g.name;let s=1;g.type===e.FLOAT_MAT2&&(s=2),g.type===e.FLOAT_MAT3&&(s=3),g.type===e.FLOAT_MAT4&&(s=4),t[o]={type:g.type,location:e.getAttribLocation(A,o),locationSize:s}}return t}function Gk(e){return e!==""}function AgA(e,A){const t=A.numSpotLightShadows+A.numSpotLightMaps-A.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,A.numDirLights).replace(/NUM_SPOT_LIGHTS/g,A.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,A.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,A.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,A.numPointLights).replace(/NUM_HEMI_LIGHTS/g,A.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,A.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,A.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,A.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,A.numPointLightShadows)}function egA(e,A){return e.replace(/NUM_CLIPPING_PLANES/g,A.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,A.numClippingPlanes-A.numClipIntersection)}const eEe=/^[ \t]*#include +<([\w\d./]+)>/gm;function B4(e){return e.replace(eEe,iEe)}const tEe=new Map;function iEe(e,A){let t=cn[A];if(t===void 0){const i=tEe.get(A);if(i!==void 0)t=cn[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',A,i);else throw new Error("Can not resolve #include <"+A+">")}return B4(t)}const nEe=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function tgA(e){return e.replace(nEe,gEe)}function gEe(e,A,t,i){let n="";for(let g=parseInt(A);g<parseInt(t);g++)n+=i.replace(/\[\s*i\s*\]/g,"[ "+g+" ]").replace(/UNROLLED_LOOP_INDEX/g,g);return n}function igA(e){let A=`precision ${e.precision} float;
	precision ${e.precision} int;
	precision ${e.precision} sampler2D;
	precision ${e.precision} samplerCube;
	precision ${e.precision} sampler3D;
	precision ${e.precision} sampler2DArray;
	precision ${e.precision} sampler2DShadow;
	precision ${e.precision} samplerCubeShadow;
	precision ${e.precision} sampler2DArrayShadow;
	precision ${e.precision} isampler2D;
	precision ${e.precision} isampler3D;
	precision ${e.precision} isamplerCube;
	precision ${e.precision} isampler2DArray;
	precision ${e.precision} usampler2D;
	precision ${e.precision} usampler3D;
	precision ${e.precision} usamplerCube;
	precision ${e.precision} usampler2DArray;
	`;return e.precision==="highp"?A+=`
#define HIGH_PRECISION`:e.precision==="mediump"?A+=`
#define MEDIUM_PRECISION`:e.precision==="lowp"&&(A+=`
#define LOW_PRECISION`),A}function oEe(e){let A="SHADOWMAP_TYPE_BASIC";return e.shadowMapType===vx?A="SHADOWMAP_TYPE_PCF":e.shadowMapType===yM?A="SHADOWMAP_TYPE_PCF_SOFT":e.shadowMapType===Gc&&(A="SHADOWMAP_TYPE_VSM"),A}function sEe(e){let A="ENVMAP_TYPE_CUBE";if(e.envMap)switch(e.envMapMode){case rQ:case ud:A="ENVMAP_TYPE_CUBE";break;case Kw:A="ENVMAP_TYPE_CUBE_UV";break}return A}function aEe(e){let A="ENVMAP_MODE_REFLECTION";if(e.envMap)switch(e.envMapMode){case ud:A="ENVMAP_MODE_REFRACTION";break}return A}function rEe(e){let A="ENVMAP_BLENDING_NONE";if(e.envMap)switch(e.combine){case iG:A="ENVMAP_BLENDING_MULTIPLY";break;case KfA:A="ENVMAP_BLENDING_MIX";break;case FfA:A="ENVMAP_BLENDING_ADD";break}return A}function IEe(e){const A=e.envMapCubeUVHeight;if(A===null)return null;const t=Math.log2(A)-2,i=1/A;return{texelWidth:1/(3*Math.max(Math.pow(2,t),7*16)),texelHeight:i,maxMip:t}}function CEe(e,A,t,i){const n=e.getContext(),g=t.defines;let o=t.vertexShader,s=t.fragmentShader;const a=oEe(t),r=sEe(t),I=aEe(t),c=rEe(t),l=IEe(t),B=XBe(t),Q=$Be(g),h=n.createProgram();let d,p,y=t.glslVersion?"#version "+t.glslVersion+`
`:"";t.isRawShaderMaterial?(d=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,Q].filter(Gk).join(`
`),d.length>0&&(d+=`
`),p=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,Q].filter(Gk).join(`
`),p.length>0&&(p+=`
`)):(d=[igA(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,Q,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+I:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+a:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","	attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","	attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","	uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","	attribute vec2 uv1;","#endif","#ifdef USE_UV2","	attribute vec2 uv2;","#endif","#ifdef USE_UV3","	attribute vec2 uv3;","#endif","#ifdef USE_TANGENT","	attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","	attribute vec4 color;","#elif defined( USE_COLOR )","	attribute vec3 color;","#endif","#ifdef USE_SKINNING","	attribute vec4 skinIndex;","	attribute vec4 skinWeight;","#endif",`
`].filter(Gk).join(`
`),p=[igA(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,Q,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+r:"",t.envMap?"#define "+I:"",t.envMap?"#define "+c:"",l?"#define CUBEUV_TEXEL_WIDTH "+l.texelWidth:"",l?"#define CUBEUV_TEXEL_HEIGHT "+l.texelHeight:"",l?"#define CUBEUV_MAX_MIP "+l.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+a:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==QB?"#define TONE_MAPPING":"",t.toneMapping!==QB?cn.tonemapping_pars_fragment:"",t.toneMapping!==QB?WBe("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",cn.colorspace_pars_fragment,ZBe("linearToOutputTexel",t.outputColorSpace),VBe(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
`].filter(Gk).join(`
`)),o=B4(o),o=AgA(o,t),o=egA(o,t),s=B4(s),s=AgA(s,t),s=egA(s,t),o=tgA(o),s=tgA(s),t.isRawShaderMaterial!==!0&&(y=`#version 300 es
`,d=[B,"#define attribute in","#define varying out","#define texture2D texture"].join(`
`)+`
`+d,p=["#define varying in",t.glslVersion===s4?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===s4?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
`)+`
`+p);const m=y+d+o,D=y+p+s,S=VnA(n,n.VERTEX_SHADER,m),k=VnA(n,n.FRAGMENT_SHADER,D);n.attachShader(h,S),n.attachShader(h,k),t.index0AttributeName!==void 0?n.bindAttribLocation(h,0,t.index0AttributeName):t.morphTargets===!0&&n.bindAttribLocation(h,0,"position"),n.linkProgram(h);function N(b){if(e.debug.checkShaderErrors){const _=n.getProgramInfoLog(h)||"",K=n.getShaderInfoLog(S)||"",J=n.getShaderInfoLog(k)||"",q=_.trim(),v=K.trim(),U=J.trim();let x=!0,T=!0;if(n.getProgramParameter(h,n.LINK_STATUS)===!1)if(x=!1,typeof e.debug.onShaderError=="function")e.debug.onShaderError(n,h,S,k);else{const z=$nA(n,S,"vertex"),Z=$nA(n,k,"fragment");console.error("THREE.WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(h,n.VALIDATE_STATUS)+`

Material Name: `+b.name+`
Material Type: `+b.type+`

Program Info Log: `+q+`
`+z+`
`+Z)}else q!==""?console.warn("THREE.WebGLProgram: Program Info Log:",q):(v===""||U==="")&&(T=!1);T&&(b.diagnostics={runnable:x,programLog:q,vertexShader:{log:v,prefix:d},fragmentShader:{log:U,prefix:p}})}n.deleteShader(S),n.deleteShader(k),G=new KK(n,h),M=AEe(n,h)}let G;this.getUniforms=function(){return G===void 0&&N(this),G};let M;this.getAttributes=function(){return M===void 0&&N(this),M};let w=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return w===!1&&(w=n.getProgramParameter(h,OBe)),w},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(h),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=PBe++,this.cacheKey=A,this.usedTimes=1,this.program=h,this.vertexShader=S,this.fragmentShader=k,this}let cEe=0;class lEe{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(A){const t=A.vertexShader,i=A.fragmentShader,n=this._getShaderStage(t),g=this._getShaderStage(i),o=this._getShaderCacheForMaterial(A);return o.has(n)===!1&&(o.add(n),n.usedTimes++),o.has(g)===!1&&(o.add(g),g.usedTimes++),this}remove(A){const t=this.materialCache.get(A);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(A),this}getVertexShaderID(A){return this._getShaderStage(A.vertexShader).id}getFragmentShaderID(A){return this._getShaderStage(A.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(A){const t=this.materialCache;let i=t.get(A);return i===void 0&&(i=new Set,t.set(A,i)),i}_getShaderStage(A){const t=this.shaderCache;let i=t.get(A);return i===void 0&&(i=new BEe(A),t.set(A,i)),i}}class BEe{constructor(A){this.id=cEe++,this.code=A,this.usedTimes=0}}function EEe(e,A,t,i,n,g,o){const s=new PS,a=new lEe,r=new Set,I=[],c=n.logarithmicDepthBuffer,l=n.vertexTextures;let B=n.precision;const Q={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function h(M){return r.add(M),M===0?"uv":`uv${M}`}function d(M,w,b,_,K){const J=_.fog,q=K.geometry,v=M.isMeshStandardMaterial?_.environment:null,U=(M.isMeshStandardMaterial?t:A).get(M.envMap||v),x=U&&U.mapping===Kw?U.image.height:null,T=Q[M.type];M.precision!==null&&(B=n.getMaxPrecision(M.precision),B!==M.precision&&console.warn("THREE.WebGLProgram.getParameters:",M.precision,"not supported, using",B,"instead."));const z=q.morphAttributes.position||q.morphAttributes.normal||q.morphAttributes.color,Z=z!==void 0?z.length:0;let eA=0;q.morphAttributes.position!==void 0&&(eA=1),q.morphAttributes.normal!==void 0&&(eA=2),q.morphAttributes.color!==void 0&&(eA=3);let aA,sA,pA,gA;if(T){const me=xc[T];aA=me.vertexShader,sA=me.fragmentShader}else aA=M.vertexShader,sA=M.fragmentShader,a.update(M),pA=a.getVertexShaderID(M),gA=a.getFragmentShaderID(M);const yA=e.getRenderTarget(),fA=e.state.buffers.depth.getReversed(),RA=K.isInstancedMesh===!0,qA=K.isBatchedMesh===!0,W=!!M.map,$=!!M.matcap,L=!!U,H=!!M.aoMap,P=!!M.lightMap,tA=!!M.bumpMap,iA=!!M.normalMap,oA=!!M.displacementMap,IA=!!M.emissiveMap,CA=!!M.metalnessMap,_A=!!M.roughnessMap,uA=M.anisotropy>0,X=M.clearcoat>0,O=M.dispersion>0,cA=M.iridescence>0,wA=M.sheen>0,xA=M.transmission>0,YA=uA&&!!M.anisotropyMap,jA=X&&!!M.clearcoatMap,ie=X&&!!M.clearcoatNormalMap,he=X&&!!M.clearcoatRoughnessMap,le=cA&&!!M.iridescenceMap,NA=cA&&!!M.iridescenceThicknessMap,EA=wA&&!!M.sheenColorMap,PA=wA&&!!M.sheenRoughnessMap,ZA=!!M.specularMap,FA=!!M.specularColorMap,Ie=!!M.specularIntensityMap,DA=xA&&!!M.transmissionMap,rA=xA&&!!M.thicknessMap,BA=!!M.gradientMap,j=!!M.alphaMap,QA=M.alphaTest>0,dA=!!M.alphaHash,UA=!!M.extensions;let TA=QB;M.toneMapped&&(yA===null||yA.isXRRenderTarget===!0)&&(TA=e.toneMapping);const oe={shaderID:T,shaderType:M.type,shaderName:M.name,vertexShader:aA,fragmentShader:sA,defines:M.defines,customVertexShaderID:pA,customFragmentShaderID:gA,isRawShaderMaterial:M.isRawShaderMaterial===!0,glslVersion:M.glslVersion,precision:B,batching:qA,batchingColor:qA&&K._colorsTexture!==null,instancing:RA,instancingColor:RA&&K.instanceColor!==null,instancingMorph:RA&&K.morphTexture!==null,supportsVertexTextures:l,outputColorSpace:yA===null?e.outputColorSpace:yA.isXRRenderTarget===!0?yA.texture.colorSpace:Ka,alphaToCoverage:!!M.alphaToCoverage,map:W,matcap:$,envMap:L,envMapMode:L&&U.mapping,envMapCubeUVHeight:x,aoMap:H,lightMap:P,bumpMap:tA,normalMap:iA,displacementMap:l&&oA,emissiveMap:IA,normalMapObjectSpace:iA&&M.normalMapType===jfA,normalMapTangentSpace:iA&&M.normalMapType===xd,metalnessMap:CA,roughnessMap:_A,anisotropy:uA,anisotropyMap:YA,clearcoat:X,clearcoatMap:jA,clearcoatNormalMap:ie,clearcoatRoughnessMap:he,dispersion:O,iridescence:cA,iridescenceMap:le,iridescenceThicknessMap:NA,sheen:wA,sheenColorMap:EA,sheenRoughnessMap:PA,specularMap:ZA,specularColorMap:FA,specularIntensityMap:Ie,transmission:xA,transmissionMap:DA,thicknessMap:rA,gradientMap:BA,opaque:M.transparent===!1&&M.blending===Yp&&M.alphaToCoverage===!1,alphaMap:j,alphaTest:QA,alphaHash:dA,combine:M.combine,mapUv:W&&h(M.map.channel),aoMapUv:H&&h(M.aoMap.channel),lightMapUv:P&&h(M.lightMap.channel),bumpMapUv:tA&&h(M.bumpMap.channel),normalMapUv:iA&&h(M.normalMap.channel),displacementMapUv:oA&&h(M.displacementMap.channel),emissiveMapUv:IA&&h(M.emissiveMap.channel),metalnessMapUv:CA&&h(M.metalnessMap.channel),roughnessMapUv:_A&&h(M.roughnessMap.channel),anisotropyMapUv:YA&&h(M.anisotropyMap.channel),clearcoatMapUv:jA&&h(M.clearcoatMap.channel),clearcoatNormalMapUv:ie&&h(M.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:he&&h(M.clearcoatRoughnessMap.channel),iridescenceMapUv:le&&h(M.iridescenceMap.channel),iridescenceThicknessMapUv:NA&&h(M.iridescenceThicknessMap.channel),sheenColorMapUv:EA&&h(M.sheenColorMap.channel),sheenRoughnessMapUv:PA&&h(M.sheenRoughnessMap.channel),specularMapUv:ZA&&h(M.specularMap.channel),specularColorMapUv:FA&&h(M.specularColorMap.channel),specularIntensityMapUv:Ie&&h(M.specularIntensityMap.channel),transmissionMapUv:DA&&h(M.transmissionMap.channel),thicknessMapUv:rA&&h(M.thicknessMap.channel),alphaMapUv:j&&h(M.alphaMap.channel),vertexTangents:!!q.attributes.tangent&&(iA||uA),vertexColors:M.vertexColors,vertexAlphas:M.vertexColors===!0&&!!q.attributes.color&&q.attributes.color.itemSize===4,pointsUvs:K.isPoints===!0&&!!q.attributes.uv&&(W||j),fog:!!J,useFog:M.fog===!0,fogExp2:!!J&&J.isFogExp2,flatShading:M.flatShading===!0&&M.wireframe===!1,sizeAttenuation:M.sizeAttenuation===!0,logarithmicDepthBuffer:c,reversedDepthBuffer:fA,skinning:K.isSkinnedMesh===!0,morphTargets:q.morphAttributes.position!==void 0,morphNormals:q.morphAttributes.normal!==void 0,morphColors:q.morphAttributes.color!==void 0,morphTargetsCount:Z,morphTextureStride:eA,numDirLights:w.directional.length,numPointLights:w.point.length,numSpotLights:w.spot.length,numSpotLightMaps:w.spotLightMap.length,numRectAreaLights:w.rectArea.length,numHemiLights:w.hemi.length,numDirLightShadows:w.directionalShadowMap.length,numPointLightShadows:w.pointShadowMap.length,numSpotLightShadows:w.spotShadowMap.length,numSpotLightShadowsWithMaps:w.numSpotLightShadowsWithMaps,numLightProbes:w.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:M.dithering,shadowMapEnabled:e.shadowMap.enabled&&b.length>0,shadowMapType:e.shadowMap.type,toneMapping:TA,decodeVideoTexture:W&&M.map.isVideoTexture===!0&&Un.getTransfer(M.map.colorSpace)===mg,decodeVideoTextureEmissive:IA&&M.emissiveMap.isVideoTexture===!0&&Un.getTransfer(M.emissiveMap.colorSpace)===mg,premultipliedAlpha:M.premultipliedAlpha,doubleSided:M.side===AI,flipSided:M.side===Ua,useDepthPacking:M.depthPacking>=0,depthPacking:M.depthPacking||0,index0AttributeName:M.index0AttributeName,extensionClipCullDistance:UA&&M.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(UA&&M.extensions.multiDraw===!0||qA)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:M.customProgramCacheKey()};return oe.vertexUv1s=r.has(1),oe.vertexUv2s=r.has(2),oe.vertexUv3s=r.has(3),r.clear(),oe}function p(M){const w=[];if(M.shaderID?w.push(M.shaderID):(w.push(M.customVertexShaderID),w.push(M.customFragmentShaderID)),M.defines!==void 0)for(const b in M.defines)w.push(b),w.push(M.defines[b]);return M.isRawShaderMaterial===!1&&(y(w,M),m(w,M),w.push(e.outputColorSpace)),w.push(M.customProgramCacheKey),w.join()}function y(M,w){M.push(w.precision),M.push(w.outputColorSpace),M.push(w.envMapMode),M.push(w.envMapCubeUVHeight),M.push(w.mapUv),M.push(w.alphaMapUv),M.push(w.lightMapUv),M.push(w.aoMapUv),M.push(w.bumpMapUv),M.push(w.normalMapUv),M.push(w.displacementMapUv),M.push(w.emissiveMapUv),M.push(w.metalnessMapUv),M.push(w.roughnessMapUv),M.push(w.anisotropyMapUv),M.push(w.clearcoatMapUv),M.push(w.clearcoatNormalMapUv),M.push(w.clearcoatRoughnessMapUv),M.push(w.iridescenceMapUv),M.push(w.iridescenceThicknessMapUv),M.push(w.sheenColorMapUv),M.push(w.sheenRoughnessMapUv),M.push(w.specularMapUv),M.push(w.specularColorMapUv),M.push(w.specularIntensityMapUv),M.push(w.transmissionMapUv),M.push(w.thicknessMapUv),M.push(w.combine),M.push(w.fogExp2),M.push(w.sizeAttenuation),M.push(w.morphTargetsCount),M.push(w.morphAttributeCount),M.push(w.numDirLights),M.push(w.numPointLights),M.push(w.numSpotLights),M.push(w.numSpotLightMaps),M.push(w.numHemiLights),M.push(w.numRectAreaLights),M.push(w.numDirLightShadows),M.push(w.numPointLightShadows),M.push(w.numSpotLightShadows),M.push(w.numSpotLightShadowsWithMaps),M.push(w.numLightProbes),M.push(w.shadowMapType),M.push(w.toneMapping),M.push(w.numClippingPlanes),M.push(w.numClipIntersection),M.push(w.depthPacking)}function m(M,w){s.disableAll(),w.supportsVertexTextures&&s.enable(0),w.instancing&&s.enable(1),w.instancingColor&&s.enable(2),w.instancingMorph&&s.enable(3),w.matcap&&s.enable(4),w.envMap&&s.enable(5),w.normalMapObjectSpace&&s.enable(6),w.normalMapTangentSpace&&s.enable(7),w.clearcoat&&s.enable(8),w.iridescence&&s.enable(9),w.alphaTest&&s.enable(10),w.vertexColors&&s.enable(11),w.vertexAlphas&&s.enable(12),w.vertexUv1s&&s.enable(13),w.vertexUv2s&&s.enable(14),w.vertexUv3s&&s.enable(15),w.vertexTangents&&s.enable(16),w.anisotropy&&s.enable(17),w.alphaHash&&s.enable(18),w.batching&&s.enable(19),w.dispersion&&s.enable(20),w.batchingColor&&s.enable(21),w.gradientMap&&s.enable(22),M.push(s.mask),s.disableAll(),w.fog&&s.enable(0),w.useFog&&s.enable(1),w.flatShading&&s.enable(2),w.logarithmicDepthBuffer&&s.enable(3),w.reversedDepthBuffer&&s.enable(4),w.skinning&&s.enable(5),w.morphTargets&&s.enable(6),w.morphNormals&&s.enable(7),w.morphColors&&s.enable(8),w.premultipliedAlpha&&s.enable(9),w.shadowMapEnabled&&s.enable(10),w.doubleSided&&s.enable(11),w.flipSided&&s.enable(12),w.useDepthPacking&&s.enable(13),w.dithering&&s.enable(14),w.transmission&&s.enable(15),w.sheen&&s.enable(16),w.opaque&&s.enable(17),w.pointsUvs&&s.enable(18),w.decodeVideoTexture&&s.enable(19),w.decodeVideoTextureEmissive&&s.enable(20),w.alphaToCoverage&&s.enable(21),M.push(s.mask)}function D(M){const w=Q[M.type];let b;if(w){const _=xc[w];b=qW.clone(_.uniforms)}else b=M.uniforms;return b}function S(M,w){let b;for(let _=0,K=I.length;_<K;_++){const J=I[_];if(J.cacheKey===w){b=J,++b.usedTimes;break}}return b===void 0&&(b=new CEe(e,w,M,g),I.push(b)),b}function k(M){if(--M.usedTimes===0){const w=I.indexOf(M);I[w]=I[I.length-1],I.pop(),M.destroy()}}function N(M){a.remove(M)}function G(){a.dispose()}return{getParameters:d,getProgramCacheKey:p,getUniforms:D,acquireProgram:S,releaseProgram:k,releaseShaderCache:N,programs:I,dispose:G}}function QEe(){let e=new WeakMap;function A(o){return e.has(o)}function t(o){let s=e.get(o);return s===void 0&&(s={},e.set(o,s)),s}function i(o){e.delete(o)}function n(o,s,a){e.get(o)[s]=a}function g(){e=new WeakMap}return{has:A,get:t,remove:i,update:n,dispose:g}}function uEe(e,A){return e.groupOrder!==A.groupOrder?e.groupOrder-A.groupOrder:e.renderOrder!==A.renderOrder?e.renderOrder-A.renderOrder:e.material.id!==A.material.id?e.material.id-A.material.id:e.z!==A.z?e.z-A.z:e.id-A.id}function ngA(e,A){return e.groupOrder!==A.groupOrder?e.groupOrder-A.groupOrder:e.renderOrder!==A.renderOrder?e.renderOrder-A.renderOrder:e.z!==A.z?A.z-e.z:e.id-A.id}function ggA(){const e=[];let A=0;const t=[],i=[],n=[];function g(){A=0,t.length=0,i.length=0,n.length=0}function o(c,l,B,Q,h,d){let p=e[A];return p===void 0?(p={id:c.id,object:c,geometry:l,material:B,groupOrder:Q,renderOrder:c.renderOrder,z:h,group:d},e[A]=p):(p.id=c.id,p.object=c,p.geometry=l,p.material=B,p.groupOrder=Q,p.renderOrder=c.renderOrder,p.z=h,p.group=d),A++,p}function s(c,l,B,Q,h,d){const p=o(c,l,B,Q,h,d);B.transmission>0?i.push(p):B.transparent===!0?n.push(p):t.push(p)}function a(c,l,B,Q,h,d){const p=o(c,l,B,Q,h,d);B.transmission>0?i.unshift(p):B.transparent===!0?n.unshift(p):t.unshift(p)}function r(c,l){t.length>1&&t.sort(c||uEe),i.length>1&&i.sort(l||ngA),n.length>1&&n.sort(l||ngA)}function I(){for(let c=A,l=e.length;c<l;c++){const B=e[c];if(B.id===null)break;B.id=null,B.object=null,B.geometry=null,B.material=null,B.group=null}}return{opaque:t,transmissive:i,transparent:n,init:g,push:s,unshift:a,finish:I,sort:r}}function dEe(){let e=new WeakMap;function A(i,n){const g=e.get(i);let o;return g===void 0?(o=new ggA,e.set(i,[o])):n>=g.length?(o=new ggA,g.push(o)):o=g[n],o}function t(){e=new WeakMap}return{get:A,dispose:t}}function hEe(){const e={};return{get:function(A){if(e[A.id]!==void 0)return e[A.id];let t;switch(A.type){case"DirectionalLight":t={direction:new SA,color:new Et};break;case"SpotLight":t={position:new SA,direction:new SA,color:new Et,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new SA,color:new Et,distance:0,decay:0};break;case"HemisphereLight":t={direction:new SA,skyColor:new Et,groundColor:new Et};break;case"RectAreaLight":t={color:new Et,position:new SA,halfWidth:new SA,halfHeight:new SA};break}return e[A.id]=t,t}}}function pEe(){const e={};return{get:function(A){if(e[A.id]!==void 0)return e[A.id];let t;switch(A.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new lt};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new lt};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new lt,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[A.id]=t,t}}}let fEe=0;function yEe(e,A){return(A.castShadow?2:0)-(e.castShadow?2:0)+(A.map?1:0)-(e.map?1:0)}function DEe(e){const A=new hEe,t=pEe(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let r=0;r<9;r++)i.probe.push(new SA);const n=new SA,g=new ni,o=new ni;function s(r){let I=0,c=0,l=0;for(let M=0;M<9;M++)i.probe[M].set(0,0,0);let B=0,Q=0,h=0,d=0,p=0,y=0,m=0,D=0,S=0,k=0,N=0;r.sort(yEe);for(let M=0,w=r.length;M<w;M++){const b=r[M],_=b.color,K=b.intensity,J=b.distance,q=b.shadow&&b.shadow.map?b.shadow.map.texture:null;if(b.isAmbientLight)I+=_.r*K,c+=_.g*K,l+=_.b*K;else if(b.isLightProbe){for(let v=0;v<9;v++)i.probe[v].addScaledVector(b.sh.coefficients[v],K);N++}else if(b.isDirectionalLight){const v=A.get(b);if(v.color.copy(b.color).multiplyScalar(b.intensity),b.castShadow){const U=b.shadow,x=t.get(b);x.shadowIntensity=U.intensity,x.shadowBias=U.bias,x.shadowNormalBias=U.normalBias,x.shadowRadius=U.radius,x.shadowMapSize=U.mapSize,i.directionalShadow[B]=x,i.directionalShadowMap[B]=q,i.directionalShadowMatrix[B]=b.shadow.matrix,y++}i.directional[B]=v,B++}else if(b.isSpotLight){const v=A.get(b);v.position.setFromMatrixPosition(b.matrixWorld),v.color.copy(_).multiplyScalar(K),v.distance=J,v.coneCos=Math.cos(b.angle),v.penumbraCos=Math.cos(b.angle*(1-b.penumbra)),v.decay=b.decay,i.spot[h]=v;const U=b.shadow;if(b.map&&(i.spotLightMap[S]=b.map,S++,U.updateMatrices(b),b.castShadow&&k++),i.spotLightMatrix[h]=U.matrix,b.castShadow){const x=t.get(b);x.shadowIntensity=U.intensity,x.shadowBias=U.bias,x.shadowNormalBias=U.normalBias,x.shadowRadius=U.radius,x.shadowMapSize=U.mapSize,i.spotShadow[h]=x,i.spotShadowMap[h]=q,D++}h++}else if(b.isRectAreaLight){const v=A.get(b);v.color.copy(_).multiplyScalar(K),v.halfWidth.set(b.width*.5,0,0),v.halfHeight.set(0,b.height*.5,0),i.rectArea[d]=v,d++}else if(b.isPointLight){const v=A.get(b);if(v.color.copy(b.color).multiplyScalar(b.intensity),v.distance=b.distance,v.decay=b.decay,b.castShadow){const U=b.shadow,x=t.get(b);x.shadowIntensity=U.intensity,x.shadowBias=U.bias,x.shadowNormalBias=U.normalBias,x.shadowRadius=U.radius,x.shadowMapSize=U.mapSize,x.shadowCameraNear=U.camera.near,x.shadowCameraFar=U.camera.far,i.pointShadow[Q]=x,i.pointShadowMap[Q]=q,i.pointShadowMatrix[Q]=b.shadow.matrix,m++}i.point[Q]=v,Q++}else if(b.isHemisphereLight){const v=A.get(b);v.skyColor.copy(b.color).multiplyScalar(K),v.groundColor.copy(b.groundColor).multiplyScalar(K),i.hemi[p]=v,p++}}d>0&&(e.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Pt.LTC_FLOAT_1,i.rectAreaLTC2=Pt.LTC_FLOAT_2):(i.rectAreaLTC1=Pt.LTC_HALF_1,i.rectAreaLTC2=Pt.LTC_HALF_2)),i.ambient[0]=I,i.ambient[1]=c,i.ambient[2]=l;const G=i.hash;(G.directionalLength!==B||G.pointLength!==Q||G.spotLength!==h||G.rectAreaLength!==d||G.hemiLength!==p||G.numDirectionalShadows!==y||G.numPointShadows!==m||G.numSpotShadows!==D||G.numSpotMaps!==S||G.numLightProbes!==N)&&(i.directional.length=B,i.spot.length=h,i.rectArea.length=d,i.point.length=Q,i.hemi.length=p,i.directionalShadow.length=y,i.directionalShadowMap.length=y,i.pointShadow.length=m,i.pointShadowMap.length=m,i.spotShadow.length=D,i.spotShadowMap.length=D,i.directionalShadowMatrix.length=y,i.pointShadowMatrix.length=m,i.spotLightMatrix.length=D+S-k,i.spotLightMap.length=S,i.numSpotLightShadowsWithMaps=k,i.numLightProbes=N,G.directionalLength=B,G.pointLength=Q,G.spotLength=h,G.rectAreaLength=d,G.hemiLength=p,G.numDirectionalShadows=y,G.numPointShadows=m,G.numSpotShadows=D,G.numSpotMaps=S,G.numLightProbes=N,i.version=fEe++)}function a(r,I){let c=0,l=0,B=0,Q=0,h=0;const d=I.matrixWorldInverse;for(let p=0,y=r.length;p<y;p++){const m=r[p];if(m.isDirectionalLight){const D=i.directional[c];D.direction.setFromMatrixPosition(m.matrixWorld),n.setFromMatrixPosition(m.target.matrixWorld),D.direction.sub(n),D.direction.transformDirection(d),c++}else if(m.isSpotLight){const D=i.spot[B];D.position.setFromMatrixPosition(m.matrixWorld),D.position.applyMatrix4(d),D.direction.setFromMatrixPosition(m.matrixWorld),n.setFromMatrixPosition(m.target.matrixWorld),D.direction.sub(n),D.direction.transformDirection(d),B++}else if(m.isRectAreaLight){const D=i.rectArea[Q];D.position.setFromMatrixPosition(m.matrixWorld),D.position.applyMatrix4(d),o.identity(),g.copy(m.matrixWorld),g.premultiply(d),o.extractRotation(g),D.halfWidth.set(m.width*.5,0,0),D.halfHeight.set(0,m.height*.5,0),D.halfWidth.applyMatrix4(o),D.halfHeight.applyMatrix4(o),Q++}else if(m.isPointLight){const D=i.point[l];D.position.setFromMatrixPosition(m.matrixWorld),D.position.applyMatrix4(d),l++}else if(m.isHemisphereLight){const D=i.hemi[h];D.direction.setFromMatrixPosition(m.matrixWorld),D.direction.transformDirection(d),h++}}}return{setup:s,setupView:a,state:i}}function ogA(e){const A=new DEe(e),t=[],i=[];function n(I){r.camera=I,t.length=0,i.length=0}function g(I){t.push(I)}function o(I){i.push(I)}function s(){A.setup(t)}function a(I){A.setupView(t,I)}const r={lightsArray:t,shadowsArray:i,camera:null,lights:A,transmissionRenderTarget:{}};return{init:n,state:r,setupLights:s,setupLightsView:a,pushLight:g,pushShadow:o}}function mEe(e){let A=new WeakMap;function t(n,g=0){const o=A.get(n);let s;return o===void 0?(s=new ogA(e),A.set(n,[s])):g>=o.length?(s=new ogA(e),o.push(s)):s=o[g],s}function i(){A=new WeakMap}return{get:t,dispose:i}}const SEe=`void main() {
	gl_Position = vec4( position, 1.0 );
}`,wEe=`uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
#include <packing>
void main() {
	const float samples = float( VSM_SAMPLES );
	float mean = 0.0;
	float squared_mean = 0.0;
	float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
	float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
	for ( float i = 0.0; i < samples; i ++ ) {
		float uvOffset = uvStart + i * uvStride;
		#ifdef HORIZONTAL_PASS
			vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
			mean += distribution.x;
			squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
		#else
			float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
			mean += depth;
			squared_mean += depth * depth;
		#endif
	}
	mean = mean / samples;
	squared_mean = squared_mean / samples;
	float std_dev = sqrt( squared_mean - mean * mean );
	gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
}`;function kEe(e,A,t){let i=new Lw;const n=new lt,g=new lt,o=new ig,s=new $W({depthPacking:PfA}),a=new AV,r={},I=t.maxTextureSize,c={[tl]:Ua,[Ua]:tl,[AI]:AI},l=new Cc({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new lt},radius:{value:4}},vertexShader:SEe,fragmentShader:wEe}),B=l.clone();B.defines.HORIZONTAL_PASS=1;const Q=new Ni;Q.setAttribute("position",new ji(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const h=new pn(Q,l),d=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=vx;let p=this.type;this.render=function(k,N,G){if(d.enabled===!1||d.autoUpdate===!1&&d.needsUpdate===!1||k.length===0)return;const M=e.getRenderTarget(),w=e.getActiveCubeFace(),b=e.getActiveMipmapLevel(),_=e.state;_.setBlending(TE),_.buffers.depth.getReversed()===!0?_.buffers.color.setClear(0,0,0,0):_.buffers.color.setClear(1,1,1,1),_.buffers.depth.setTest(!0),_.setScissorTest(!1);const K=p!==Gc&&this.type===Gc,J=p===Gc&&this.type!==Gc;for(let q=0,v=k.length;q<v;q++){const U=k[q],x=U.shadow;if(x===void 0){console.warn("THREE.WebGLShadowMap:",U,"has no shadow.");continue}if(x.autoUpdate===!1&&x.needsUpdate===!1)continue;n.copy(x.mapSize);const T=x.getFrameExtents();if(n.multiply(T),g.copy(x.mapSize),(n.x>I||n.y>I)&&(n.x>I&&(g.x=Math.floor(I/T.x),n.x=g.x*T.x,x.mapSize.x=g.x),n.y>I&&(g.y=Math.floor(I/T.y),n.y=g.y*T.y,x.mapSize.y=g.y)),x.map===null||K===!0||J===!0){const Z=this.type!==Gc?{minFilter:Ss,magFilter:Ss}:{};x.map!==null&&x.map.dispose(),x.map=new il(n.x,n.y,Z),x.map.texture.name=U.name+".shadowMap",x.camera.updateProjectionMatrix()}e.setRenderTarget(x.map),e.clear();const z=x.getViewportCount();for(let Z=0;Z<z;Z++){const eA=x.getViewport(Z);o.set(g.x*eA.x,g.y*eA.y,g.x*eA.z,g.y*eA.w),_.viewport(o),x.updateMatrices(U,Z),i=x.getFrustum(),D(N,G,x.camera,U,this.type)}x.isPointLightShadow!==!0&&this.type===Gc&&y(x,G),x.needsUpdate=!1}p=this.type,d.needsUpdate=!1,e.setRenderTarget(M,w,b)};function y(k,N){const G=A.update(h);l.defines.VSM_SAMPLES!==k.blurSamples&&(l.defines.VSM_SAMPLES=k.blurSamples,B.defines.VSM_SAMPLES=k.blurSamples,l.needsUpdate=!0,B.needsUpdate=!0),k.mapPass===null&&(k.mapPass=new il(n.x,n.y)),l.uniforms.shadow_pass.value=k.map.texture,l.uniforms.resolution.value=k.mapSize,l.uniforms.radius.value=k.radius,e.setRenderTarget(k.mapPass),e.clear(),e.renderBufferDirect(N,null,G,l,h,null),B.uniforms.shadow_pass.value=k.mapPass.texture,B.uniforms.resolution.value=k.mapSize,B.uniforms.radius.value=k.radius,e.setRenderTarget(k.map),e.clear(),e.renderBufferDirect(N,null,G,B,h,null)}function m(k,N,G,M){let w=null;const b=G.isPointLight===!0?k.customDistanceMaterial:k.customDepthMaterial;if(b!==void 0)w=b;else if(w=G.isPointLight===!0?a:s,e.localClippingEnabled&&N.clipShadows===!0&&Array.isArray(N.clippingPlanes)&&N.clippingPlanes.length!==0||N.displacementMap&&N.displacementScale!==0||N.alphaMap&&N.alphaTest>0||N.map&&N.alphaTest>0||N.alphaToCoverage===!0){const _=w.uuid,K=N.uuid;let J=r[_];J===void 0&&(J={},r[_]=J);let q=J[K];q===void 0&&(q=w.clone(),J[K]=q,N.addEventListener("dispose",S)),w=q}if(w.visible=N.visible,w.wireframe=N.wireframe,M===Gc?w.side=N.shadowSide!==null?N.shadowSide:N.side:w.side=N.shadowSide!==null?N.shadowSide:c[N.side],w.alphaMap=N.alphaMap,w.alphaTest=N.alphaToCoverage===!0?.5:N.alphaTest,w.map=N.map,w.clipShadows=N.clipShadows,w.clippingPlanes=N.clippingPlanes,w.clipIntersection=N.clipIntersection,w.displacementMap=N.displacementMap,w.displacementScale=N.displacementScale,w.displacementBias=N.displacementBias,w.wireframeLinewidth=N.wireframeLinewidth,w.linewidth=N.linewidth,G.isPointLight===!0&&w.isMeshDistanceMaterial===!0){const _=e.properties.get(w);_.light=G}return w}function D(k,N,G,M,w){if(k.visible===!1)return;if(k.layers.test(N.layers)&&(k.isMesh||k.isLine||k.isPoints)&&(k.castShadow||k.receiveShadow&&w===Gc)&&(!k.frustumCulled||i.intersectsObject(k))){k.modelViewMatrix.multiplyMatrices(G.matrixWorldInverse,k.matrixWorld);const K=A.update(k),J=k.material;if(Array.isArray(J)){const q=K.groups;for(let v=0,U=q.length;v<U;v++){const x=q[v],T=J[x.materialIndex];if(T&&T.visible){const z=m(k,T,M,w);k.onBeforeShadow(e,k,N,G,K,z,x),e.renderBufferDirect(G,null,K,z,k,x),k.onAfterShadow(e,k,N,G,K,z,x)}}}else if(J.visible){const q=m(k,J,M,w);k.onBeforeShadow(e,k,N,G,K,q,null),e.renderBufferDirect(G,null,K,q,k,null),k.onAfterShadow(e,k,N,G,K,q,null)}}const _=k.children;for(let K=0,J=_.length;K<J;K++)D(_[K],N,G,M,w)}function S(k){k.target.removeEventListener("dispose",S);for(const G in r){const M=r[G],w=k.target.uuid;w in M&&(M[w].dispose(),delete M[w])}}}const MEe={[__]:J_,[L_]:q_,[x_]:Y_,[pf]:T_,[J_]:__,[q_]:L_,[Y_]:x_,[T_]:pf};function NEe(e,A){function t(){let DA=!1;const rA=new ig;let BA=null;const j=new ig(0,0,0,0);return{setMask:function(QA){BA!==QA&&!DA&&(e.colorMask(QA,QA,QA,QA),BA=QA)},setLocked:function(QA){DA=QA},setClear:function(QA,dA,UA,TA,oe){oe===!0&&(QA*=TA,dA*=TA,UA*=TA),rA.set(QA,dA,UA,TA),j.equals(rA)===!1&&(e.clearColor(QA,dA,UA,TA),j.copy(rA))},reset:function(){DA=!1,BA=null,j.set(-1,0,0,0)}}}function i(){let DA=!1,rA=!1,BA=null,j=null,QA=null;return{setReversed:function(dA){if(rA!==dA){const UA=A.get("EXT_clip_control");dA?UA.clipControlEXT(UA.LOWER_LEFT_EXT,UA.ZERO_TO_ONE_EXT):UA.clipControlEXT(UA.LOWER_LEFT_EXT,UA.NEGATIVE_ONE_TO_ONE_EXT),rA=dA;const TA=QA;QA=null,this.setClear(TA)}},getReversed:function(){return rA},setTest:function(dA){dA?yA(e.DEPTH_TEST):fA(e.DEPTH_TEST)},setMask:function(dA){BA!==dA&&!DA&&(e.depthMask(dA),BA=dA)},setFunc:function(dA){if(rA&&(dA=MEe[dA]),j!==dA){switch(dA){case __:e.depthFunc(e.NEVER);break;case J_:e.depthFunc(e.ALWAYS);break;case L_:e.depthFunc(e.LESS);break;case pf:e.depthFunc(e.LEQUAL);break;case x_:e.depthFunc(e.EQUAL);break;case T_:e.depthFunc(e.GEQUAL);break;case q_:e.depthFunc(e.GREATER);break;case Y_:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}j=dA}},setLocked:function(dA){DA=dA},setClear:function(dA){QA!==dA&&(rA&&(dA=1-dA),e.clearDepth(dA),QA=dA)},reset:function(){DA=!1,BA=null,j=null,QA=null,rA=!1}}}function n(){let DA=!1,rA=null,BA=null,j=null,QA=null,dA=null,UA=null,TA=null,oe=null;return{setTest:function(me){DA||(me?yA(e.STENCIL_TEST):fA(e.STENCIL_TEST))},setMask:function(me){rA!==me&&!DA&&(e.stencilMask(me),rA=me)},setFunc:function(me,be,$e){(BA!==me||j!==be||QA!==$e)&&(e.stencilFunc(me,be,$e),BA=me,j=be,QA=$e)},setOp:function(me,be,$e){(dA!==me||UA!==be||TA!==$e)&&(e.stencilOp(me,be,$e),dA=me,UA=be,TA=$e)},setLocked:function(me){DA=me},setClear:function(me){oe!==me&&(e.clearStencil(me),oe=me)},reset:function(){DA=!1,rA=null,BA=null,j=null,QA=null,dA=null,UA=null,TA=null,oe=null}}}const g=new t,o=new i,s=new n,a=new WeakMap,r=new WeakMap;let I={},c={},l=new WeakMap,B=[],Q=null,h=!1,d=null,p=null,y=null,m=null,D=null,S=null,k=null,N=new Et(0,0,0),G=0,M=!1,w=null,b=null,_=null,K=null,J=null;const q=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let v=!1,U=0;const x=e.getParameter(e.VERSION);x.indexOf("WebGL")!==-1?(U=parseFloat(/^WebGL (\d)/.exec(x)[1]),v=U>=1):x.indexOf("OpenGL ES")!==-1&&(U=parseFloat(/^OpenGL ES (\d)/.exec(x)[1]),v=U>=2);let T=null,z={};const Z=e.getParameter(e.SCISSOR_BOX),eA=e.getParameter(e.VIEWPORT),aA=new ig().fromArray(Z),sA=new ig().fromArray(eA);function pA(DA,rA,BA,j){const QA=new Uint8Array(4),dA=e.createTexture();e.bindTexture(DA,dA),e.texParameteri(DA,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(DA,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let UA=0;UA<BA;UA++)DA===e.TEXTURE_3D||DA===e.TEXTURE_2D_ARRAY?e.texImage3D(rA,0,e.RGBA,1,1,j,0,e.RGBA,e.UNSIGNED_BYTE,QA):e.texImage2D(rA+UA,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,QA);return dA}const gA={};gA[e.TEXTURE_2D]=pA(e.TEXTURE_2D,e.TEXTURE_2D,1),gA[e.TEXTURE_CUBE_MAP]=pA(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),gA[e.TEXTURE_2D_ARRAY]=pA(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),gA[e.TEXTURE_3D]=pA(e.TEXTURE_3D,e.TEXTURE_3D,1,1),g.setClear(0,0,0,1),o.setClear(1),s.setClear(0),yA(e.DEPTH_TEST),o.setFunc(pf),tA(!1),iA(t4),yA(e.CULL_FACE),H(TE);function yA(DA){I[DA]!==!0&&(e.enable(DA),I[DA]=!0)}function fA(DA){I[DA]!==!1&&(e.disable(DA),I[DA]=!1)}function RA(DA,rA){return c[DA]!==rA?(e.bindFramebuffer(DA,rA),c[DA]=rA,DA===e.DRAW_FRAMEBUFFER&&(c[e.FRAMEBUFFER]=rA),DA===e.FRAMEBUFFER&&(c[e.DRAW_FRAMEBUFFER]=rA),!0):!1}function qA(DA,rA){let BA=B,j=!1;if(DA){BA=l.get(rA),BA===void 0&&(BA=[],l.set(rA,BA));const QA=DA.textures;if(BA.length!==QA.length||BA[0]!==e.COLOR_ATTACHMENT0){for(let dA=0,UA=QA.length;dA<UA;dA++)BA[dA]=e.COLOR_ATTACHMENT0+dA;BA.length=QA.length,j=!0}}else BA[0]!==e.BACK&&(BA[0]=e.BACK,j=!0);j&&e.drawBuffers(BA)}function W(DA){return Q!==DA?(e.useProgram(DA),Q=DA,!0):!1}const $={[ru]:e.FUNC_ADD,[dfA]:e.FUNC_SUBTRACT,[hfA]:e.FUNC_REVERSE_SUBTRACT};$[pfA]=e.MIN,$[ffA]=e.MAX;const L={[yfA]:e.ZERO,[DfA]:e.ONE,[mfA]:e.SRC_COLOR,[K_]:e.SRC_ALPHA,[RfA]:e.SRC_ALPHA_SATURATE,[MfA]:e.DST_COLOR,[wfA]:e.DST_ALPHA,[SfA]:e.ONE_MINUS_SRC_COLOR,[F_]:e.ONE_MINUS_SRC_ALPHA,[NfA]:e.ONE_MINUS_DST_COLOR,[kfA]:e.ONE_MINUS_DST_ALPHA,[GfA]:e.CONSTANT_COLOR,[bfA]:e.ONE_MINUS_CONSTANT_COLOR,[UfA]:e.CONSTANT_ALPHA,[vfA]:e.ONE_MINUS_CONSTANT_ALPHA};function H(DA,rA,BA,j,QA,dA,UA,TA,oe,me){if(DA===TE){h===!0&&(fA(e.BLEND),h=!1);return}if(h===!1&&(yA(e.BLEND),h=!0),DA!==ufA){if(DA!==d||me!==M){if((p!==ru||D!==ru)&&(e.blendEquation(e.FUNC_ADD),p=ru,D=ru),me)switch(DA){case Yp:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case io:e.blendFunc(e.ONE,e.ONE);break;case i4:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case n4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:console.error("THREE.WebGLState: Invalid blending: ",DA);break}else switch(DA){case Yp:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case io:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case i4:console.error("THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case n4:console.error("THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:console.error("THREE.WebGLState: Invalid blending: ",DA);break}y=null,m=null,S=null,k=null,N.set(0,0,0),G=0,d=DA,M=me}return}QA=QA||rA,dA=dA||BA,UA=UA||j,(rA!==p||QA!==D)&&(e.blendEquationSeparate($[rA],$[QA]),p=rA,D=QA),(BA!==y||j!==m||dA!==S||UA!==k)&&(e.blendFuncSeparate(L[BA],L[j],L[dA],L[UA]),y=BA,m=j,S=dA,k=UA),(TA.equals(N)===!1||oe!==G)&&(e.blendColor(TA.r,TA.g,TA.b,oe),N.copy(TA),G=oe),d=DA,M=!1}function P(DA,rA){DA.side===AI?fA(e.CULL_FACE):yA(e.CULL_FACE);let BA=DA.side===Ua;rA&&(BA=!BA),tA(BA),DA.blending===Yp&&DA.transparent===!1?H(TE):H(DA.blending,DA.blendEquation,DA.blendSrc,DA.blendDst,DA.blendEquationAlpha,DA.blendSrcAlpha,DA.blendDstAlpha,DA.blendColor,DA.blendAlpha,DA.premultipliedAlpha),o.setFunc(DA.depthFunc),o.setTest(DA.depthTest),o.setMask(DA.depthWrite),g.setMask(DA.colorWrite);const j=DA.stencilWrite;s.setTest(j),j&&(s.setMask(DA.stencilWriteMask),s.setFunc(DA.stencilFunc,DA.stencilRef,DA.stencilFuncMask),s.setOp(DA.stencilFail,DA.stencilZFail,DA.stencilZPass)),IA(DA.polygonOffset,DA.polygonOffsetFactor,DA.polygonOffsetUnits),DA.alphaToCoverage===!0?yA(e.SAMPLE_ALPHA_TO_COVERAGE):fA(e.SAMPLE_ALPHA_TO_COVERAGE)}function tA(DA){w!==DA&&(DA?e.frontFace(e.CW):e.frontFace(e.CCW),w=DA)}function iA(DA){DA!==BfA?(yA(e.CULL_FACE),DA!==b&&(DA===t4?e.cullFace(e.BACK):DA===EfA?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))):fA(e.CULL_FACE),b=DA}function oA(DA){DA!==_&&(v&&e.lineWidth(DA),_=DA)}function IA(DA,rA,BA){DA?(yA(e.POLYGON_OFFSET_FILL),(K!==rA||J!==BA)&&(e.polygonOffset(rA,BA),K=rA,J=BA)):fA(e.POLYGON_OFFSET_FILL)}function CA(DA){DA?yA(e.SCISSOR_TEST):fA(e.SCISSOR_TEST)}function _A(DA){DA===void 0&&(DA=e.TEXTURE0+q-1),T!==DA&&(e.activeTexture(DA),T=DA)}function uA(DA,rA,BA){BA===void 0&&(T===null?BA=e.TEXTURE0+q-1:BA=T);let j=z[BA];j===void 0&&(j={type:void 0,texture:void 0},z[BA]=j),(j.type!==DA||j.texture!==rA)&&(T!==BA&&(e.activeTexture(BA),T=BA),e.bindTexture(DA,rA||gA[DA]),j.type=DA,j.texture=rA)}function X(){const DA=z[T];DA!==void 0&&DA.type!==void 0&&(e.bindTexture(DA.type,null),DA.type=void 0,DA.texture=void 0)}function O(){try{e.compressedTexImage2D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function cA(){try{e.compressedTexImage3D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function wA(){try{e.texSubImage2D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function xA(){try{e.texSubImage3D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function YA(){try{e.compressedTexSubImage2D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function jA(){try{e.compressedTexSubImage3D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function ie(){try{e.texStorage2D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function he(){try{e.texStorage3D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function le(){try{e.texImage2D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function NA(){try{e.texImage3D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function EA(DA){aA.equals(DA)===!1&&(e.scissor(DA.x,DA.y,DA.z,DA.w),aA.copy(DA))}function PA(DA){sA.equals(DA)===!1&&(e.viewport(DA.x,DA.y,DA.z,DA.w),sA.copy(DA))}function ZA(DA,rA){let BA=r.get(rA);BA===void 0&&(BA=new WeakMap,r.set(rA,BA));let j=BA.get(DA);j===void 0&&(j=e.getUniformBlockIndex(rA,DA.name),BA.set(DA,j))}function FA(DA,rA){const j=r.get(rA).get(DA);a.get(rA)!==j&&(e.uniformBlockBinding(rA,j,DA.__bindingPointIndex),a.set(rA,j))}function Ie(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),I={},T=null,z={},c={},l=new WeakMap,B=[],Q=null,h=!1,d=null,p=null,y=null,m=null,D=null,S=null,k=null,N=new Et(0,0,0),G=0,M=!1,w=null,b=null,_=null,K=null,J=null,aA.set(0,0,e.canvas.width,e.canvas.height),sA.set(0,0,e.canvas.width,e.canvas.height),g.reset(),o.reset(),s.reset()}return{buffers:{color:g,depth:o,stencil:s},enable:yA,disable:fA,bindFramebuffer:RA,drawBuffers:qA,useProgram:W,setBlending:H,setMaterial:P,setFlipSided:tA,setCullFace:iA,setLineWidth:oA,setPolygonOffset:IA,setScissorTest:CA,activeTexture:_A,bindTexture:uA,unbindTexture:X,compressedTexImage2D:O,compressedTexImage3D:cA,texImage2D:le,texImage3D:NA,updateUBOMapping:ZA,uniformBlockBinding:FA,texStorage2D:ie,texStorage3D:he,texSubImage2D:wA,texSubImage3D:xA,compressedTexSubImage2D:YA,compressedTexSubImage3D:jA,scissor:EA,viewport:PA,reset:Ie}}function REe(e,A,t,i,n,g,o){const s=A.has("WEBGL_multisampled_render_to_texture")?A.get("WEBGL_multisampled_render_to_texture"):null,a=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),r=new lt,I=new WeakMap;let c;const l=new WeakMap;let B=!1;try{B=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function Q(X,O){return B?new OffscreenCanvas(X,O):vN("canvas")}function h(X,O,cA){let wA=1;const xA=uA(X);if((xA.width>cA||xA.height>cA)&&(wA=cA/Math.max(xA.width,xA.height)),wA<1)if(typeof HTMLImageElement<"u"&&X instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&X instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&X instanceof ImageBitmap||typeof VideoFrame<"u"&&X instanceof VideoFrame){const YA=Math.floor(wA*xA.width),jA=Math.floor(wA*xA.height);c===void 0&&(c=Q(YA,jA));const ie=O?Q(YA,jA):c;return ie.width=YA,ie.height=jA,ie.getContext("2d").drawImage(X,0,0,YA,jA),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+xA.width+"x"+xA.height+") to ("+YA+"x"+jA+")."),ie}else return"data"in X&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+xA.width+"x"+xA.height+")."),X;return X}function d(X){return X.generateMipmaps}function p(X){e.generateMipmap(X)}function y(X){return X.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:X.isWebGL3DRenderTarget?e.TEXTURE_3D:X.isWebGLArrayRenderTarget||X.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function m(X,O,cA,wA,xA=!1){if(X!==null){if(e[X]!==void 0)return e[X];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+X+"'")}let YA=O;if(O===e.RED&&(cA===e.FLOAT&&(YA=e.R32F),cA===e.HALF_FLOAT&&(YA=e.R16F),cA===e.UNSIGNED_BYTE&&(YA=e.R8)),O===e.RED_INTEGER&&(cA===e.UNSIGNED_BYTE&&(YA=e.R8UI),cA===e.UNSIGNED_SHORT&&(YA=e.R16UI),cA===e.UNSIGNED_INT&&(YA=e.R32UI),cA===e.BYTE&&(YA=e.R8I),cA===e.SHORT&&(YA=e.R16I),cA===e.INT&&(YA=e.R32I)),O===e.RG&&(cA===e.FLOAT&&(YA=e.RG32F),cA===e.HALF_FLOAT&&(YA=e.RG16F),cA===e.UNSIGNED_BYTE&&(YA=e.RG8)),O===e.RG_INTEGER&&(cA===e.UNSIGNED_BYTE&&(YA=e.RG8UI),cA===e.UNSIGNED_SHORT&&(YA=e.RG16UI),cA===e.UNSIGNED_INT&&(YA=e.RG32UI),cA===e.BYTE&&(YA=e.RG8I),cA===e.SHORT&&(YA=e.RG16I),cA===e.INT&&(YA=e.RG32I)),O===e.RGB_INTEGER&&(cA===e.UNSIGNED_BYTE&&(YA=e.RGB8UI),cA===e.UNSIGNED_SHORT&&(YA=e.RGB16UI),cA===e.UNSIGNED_INT&&(YA=e.RGB32UI),cA===e.BYTE&&(YA=e.RGB8I),cA===e.SHORT&&(YA=e.RGB16I),cA===e.INT&&(YA=e.RGB32I)),O===e.RGBA_INTEGER&&(cA===e.UNSIGNED_BYTE&&(YA=e.RGBA8UI),cA===e.UNSIGNED_SHORT&&(YA=e.RGBA16UI),cA===e.UNSIGNED_INT&&(YA=e.RGBA32UI),cA===e.BYTE&&(YA=e.RGBA8I),cA===e.SHORT&&(YA=e.RGBA16I),cA===e.INT&&(YA=e.RGBA32I)),O===e.RGB&&(cA===e.UNSIGNED_INT_5_9_9_9_REV&&(YA=e.RGB9_E5),cA===e.UNSIGNED_INT_10F_11F_11F_REV&&(YA=e.R11F_G11F_B10F)),O===e.RGBA){const jA=xA?bN:Un.getTransfer(wA);cA===e.FLOAT&&(YA=e.RGBA32F),cA===e.HALF_FLOAT&&(YA=e.RGBA16F),cA===e.UNSIGNED_BYTE&&(YA=jA===mg?e.SRGB8_ALPHA8:e.RGBA8),cA===e.UNSIGNED_SHORT_4_4_4_4&&(YA=e.RGBA4),cA===e.UNSIGNED_SHORT_5_5_5_1&&(YA=e.RGB5_A1)}return(YA===e.R16F||YA===e.R32F||YA===e.RG16F||YA===e.RG32F||YA===e.RGBA16F||YA===e.RGBA32F)&&A.get("EXT_color_buffer_float"),YA}function D(X,O){let cA;return X?O===null||O===IQ||O===TS?cA=e.DEPTH24_STENCIL8:O===br?cA=e.DEPTH32F_STENCIL8:O===xS&&(cA=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):O===null||O===IQ||O===TS?cA=e.DEPTH_COMPONENT24:O===br?cA=e.DEPTH_COMPONENT32F:O===xS&&(cA=e.DEPTH_COMPONENT16),cA}function S(X,O){return d(X)===!0||X.isFramebufferTexture&&X.minFilter!==Ss&&X.minFilter!==qg?Math.log2(Math.max(O.width,O.height))+1:X.mipmaps!==void 0&&X.mipmaps.length>0?X.mipmaps.length:X.isCompressedTexture&&Array.isArray(X.image)?O.mipmaps.length:1}function k(X){const O=X.target;O.removeEventListener("dispose",k),G(O),O.isVideoTexture&&I.delete(O)}function N(X){const O=X.target;O.removeEventListener("dispose",N),w(O)}function G(X){const O=i.get(X);if(O.__webglInit===void 0)return;const cA=X.source,wA=l.get(cA);if(wA){const xA=wA[O.__cacheKey];xA.usedTimes--,xA.usedTimes===0&&M(X),Object.keys(wA).length===0&&l.delete(cA)}i.remove(X)}function M(X){const O=i.get(X);e.deleteTexture(O.__webglTexture);const cA=X.source,wA=l.get(cA);delete wA[O.__cacheKey],o.memory.textures--}function w(X){const O=i.get(X);if(X.depthTexture&&(X.depthTexture.dispose(),i.remove(X.depthTexture)),X.isWebGLCubeRenderTarget)for(let wA=0;wA<6;wA++){if(Array.isArray(O.__webglFramebuffer[wA]))for(let xA=0;xA<O.__webglFramebuffer[wA].length;xA++)e.deleteFramebuffer(O.__webglFramebuffer[wA][xA]);else e.deleteFramebuffer(O.__webglFramebuffer[wA]);O.__webglDepthbuffer&&e.deleteRenderbuffer(O.__webglDepthbuffer[wA])}else{if(Array.isArray(O.__webglFramebuffer))for(let wA=0;wA<O.__webglFramebuffer.length;wA++)e.deleteFramebuffer(O.__webglFramebuffer[wA]);else e.deleteFramebuffer(O.__webglFramebuffer);if(O.__webglDepthbuffer&&e.deleteRenderbuffer(O.__webglDepthbuffer),O.__webglMultisampledFramebuffer&&e.deleteFramebuffer(O.__webglMultisampledFramebuffer),O.__webglColorRenderbuffer)for(let wA=0;wA<O.__webglColorRenderbuffer.length;wA++)O.__webglColorRenderbuffer[wA]&&e.deleteRenderbuffer(O.__webglColorRenderbuffer[wA]);O.__webglDepthRenderbuffer&&e.deleteRenderbuffer(O.__webglDepthRenderbuffer)}const cA=X.textures;for(let wA=0,xA=cA.length;wA<xA;wA++){const YA=i.get(cA[wA]);YA.__webglTexture&&(e.deleteTexture(YA.__webglTexture),o.memory.textures--),i.remove(cA[wA])}i.remove(X)}let b=0;function _(){b=0}function K(){const X=b;return X>=n.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+X+" texture units while this GPU supports only "+n.maxTextures),b+=1,X}function J(X){const O=[];return O.push(X.wrapS),O.push(X.wrapT),O.push(X.wrapR||0),O.push(X.magFilter),O.push(X.minFilter),O.push(X.anisotropy),O.push(X.internalFormat),O.push(X.format),O.push(X.type),O.push(X.generateMipmaps),O.push(X.premultiplyAlpha),O.push(X.flipY),O.push(X.unpackAlignment),O.push(X.colorSpace),O.join()}function q(X,O){const cA=i.get(X);if(X.isVideoTexture&&CA(X),X.isRenderTargetTexture===!1&&X.isExternalTexture!==!0&&X.version>0&&cA.__version!==X.version){const wA=X.image;if(wA===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(wA.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{gA(cA,X,O);return}}else X.isExternalTexture&&(cA.__webglTexture=X.sourceTexture?X.sourceTexture:null);t.bindTexture(e.TEXTURE_2D,cA.__webglTexture,e.TEXTURE0+O)}function v(X,O){const cA=i.get(X);if(X.isRenderTargetTexture===!1&&X.version>0&&cA.__version!==X.version){gA(cA,X,O);return}t.bindTexture(e.TEXTURE_2D_ARRAY,cA.__webglTexture,e.TEXTURE0+O)}function U(X,O){const cA=i.get(X);if(X.isRenderTargetTexture===!1&&X.version>0&&cA.__version!==X.version){gA(cA,X,O);return}t.bindTexture(e.TEXTURE_3D,cA.__webglTexture,e.TEXTURE0+O)}function x(X,O){const cA=i.get(X);if(X.version>0&&cA.__version!==X.version){yA(cA,X,O);return}t.bindTexture(e.TEXTURE_CUBE_MAP,cA.__webglTexture,e.TEXTURE0+O)}const T={[Fr]:e.REPEAT,[oI]:e.CLAMP_TO_EDGE,[ff]:e.MIRRORED_REPEAT},z={[Ss]:e.NEAREST,[nG]:e.NEAREST_MIPMAP_NEAREST,[Nu]:e.NEAREST_MIPMAP_LINEAR,[qg]:e.LINEAR,[Hp]:e.LINEAR_MIPMAP_NEAREST,[Gr]:e.LINEAR_MIPMAP_LINEAR},Z={[zfA]:e.NEVER,[AyA]:e.ALWAYS,[ZfA]:e.LESS,[_W]:e.LEQUAL,[WfA]:e.EQUAL,[$fA]:e.GEQUAL,[VfA]:e.GREATER,[XfA]:e.NOTEQUAL};function eA(X,O){if(O.type===br&&A.has("OES_texture_float_linear")===!1&&(O.magFilter===qg||O.magFilter===Hp||O.magFilter===Nu||O.magFilter===Gr||O.minFilter===qg||O.minFilter===Hp||O.minFilter===Nu||O.minFilter===Gr)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(X,e.TEXTURE_WRAP_S,T[O.wrapS]),e.texParameteri(X,e.TEXTURE_WRAP_T,T[O.wrapT]),(X===e.TEXTURE_3D||X===e.TEXTURE_2D_ARRAY)&&e.texParameteri(X,e.TEXTURE_WRAP_R,T[O.wrapR]),e.texParameteri(X,e.TEXTURE_MAG_FILTER,z[O.magFilter]),e.texParameteri(X,e.TEXTURE_MIN_FILTER,z[O.minFilter]),O.compareFunction&&(e.texParameteri(X,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(X,e.TEXTURE_COMPARE_FUNC,Z[O.compareFunction])),A.has("EXT_texture_filter_anisotropic")===!0){if(O.magFilter===Ss||O.minFilter!==Nu&&O.minFilter!==Gr||O.type===br&&A.has("OES_texture_float_linear")===!1)return;if(O.anisotropy>1||i.get(O).__currentAnisotropy){const cA=A.get("EXT_texture_filter_anisotropic");e.texParameterf(X,cA.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(O.anisotropy,n.getMaxAnisotropy())),i.get(O).__currentAnisotropy=O.anisotropy}}}function aA(X,O){let cA=!1;X.__webglInit===void 0&&(X.__webglInit=!0,O.addEventListener("dispose",k));const wA=O.source;let xA=l.get(wA);xA===void 0&&(xA={},l.set(wA,xA));const YA=J(O);if(YA!==X.__cacheKey){xA[YA]===void 0&&(xA[YA]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,cA=!0),xA[YA].usedTimes++;const jA=xA[X.__cacheKey];jA!==void 0&&(xA[X.__cacheKey].usedTimes--,jA.usedTimes===0&&M(O)),X.__cacheKey=YA,X.__webglTexture=xA[YA].texture}return cA}function sA(X,O,cA){return Math.floor(Math.floor(X/cA)/O)}function pA(X,O,cA,wA){const YA=X.updateRanges;if(YA.length===0)t.texSubImage2D(e.TEXTURE_2D,0,0,0,O.width,O.height,cA,wA,O.data);else{YA.sort((NA,EA)=>NA.start-EA.start);let jA=0;for(let NA=1;NA<YA.length;NA++){const EA=YA[jA],PA=YA[NA],ZA=EA.start+EA.count,FA=sA(PA.start,O.width,4),Ie=sA(EA.start,O.width,4);PA.start<=ZA+1&&FA===Ie&&sA(PA.start+PA.count-1,O.width,4)===FA?EA.count=Math.max(EA.count,PA.start+PA.count-EA.start):(++jA,YA[jA]=PA)}YA.length=jA+1;const ie=e.getParameter(e.UNPACK_ROW_LENGTH),he=e.getParameter(e.UNPACK_SKIP_PIXELS),le=e.getParameter(e.UNPACK_SKIP_ROWS);e.pixelStorei(e.UNPACK_ROW_LENGTH,O.width);for(let NA=0,EA=YA.length;NA<EA;NA++){const PA=YA[NA],ZA=Math.floor(PA.start/4),FA=Math.ceil(PA.count/4),Ie=ZA%O.width,DA=Math.floor(ZA/O.width),rA=FA,BA=1;e.pixelStorei(e.UNPACK_SKIP_PIXELS,Ie),e.pixelStorei(e.UNPACK_SKIP_ROWS,DA),t.texSubImage2D(e.TEXTURE_2D,0,Ie,DA,rA,BA,cA,wA,O.data)}X.clearUpdateRanges(),e.pixelStorei(e.UNPACK_ROW_LENGTH,ie),e.pixelStorei(e.UNPACK_SKIP_PIXELS,he),e.pixelStorei(e.UNPACK_SKIP_ROWS,le)}}function gA(X,O,cA){let wA=e.TEXTURE_2D;(O.isDataArrayTexture||O.isCompressedArrayTexture)&&(wA=e.TEXTURE_2D_ARRAY),O.isData3DTexture&&(wA=e.TEXTURE_3D);const xA=aA(X,O),YA=O.source;t.bindTexture(wA,X.__webglTexture,e.TEXTURE0+cA);const jA=i.get(YA);if(YA.version!==jA.__version||xA===!0){t.activeTexture(e.TEXTURE0+cA);const ie=Un.getPrimaries(Un.workingColorSpace),he=O.colorSpace===DE?null:Un.getPrimaries(O.colorSpace),le=O.colorSpace===DE||ie===he?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,O.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,O.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,O.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,le);let NA=h(O.image,!1,n.maxTextureSize);NA=_A(O,NA);const EA=g.convert(O.format,O.colorSpace),PA=g.convert(O.type);let ZA=m(O.internalFormat,EA,PA,O.colorSpace,O.isVideoTexture);eA(wA,O);let FA;const Ie=O.mipmaps,DA=O.isVideoTexture!==!0,rA=jA.__version===void 0||xA===!0,BA=YA.dataReady,j=S(O,NA);if(O.isDepthTexture)ZA=D(O.format===YS,O.type),rA&&(DA?t.texStorage2D(e.TEXTURE_2D,1,ZA,NA.width,NA.height):t.texImage2D(e.TEXTURE_2D,0,ZA,NA.width,NA.height,0,EA,PA,null));else if(O.isDataTexture)if(Ie.length>0){DA&&rA&&t.texStorage2D(e.TEXTURE_2D,j,ZA,Ie[0].width,Ie[0].height);for(let QA=0,dA=Ie.length;QA<dA;QA++)FA=Ie[QA],DA?BA&&t.texSubImage2D(e.TEXTURE_2D,QA,0,0,FA.width,FA.height,EA,PA,FA.data):t.texImage2D(e.TEXTURE_2D,QA,ZA,FA.width,FA.height,0,EA,PA,FA.data);O.generateMipmaps=!1}else DA?(rA&&t.texStorage2D(e.TEXTURE_2D,j,ZA,NA.width,NA.height),BA&&pA(O,NA,EA,PA)):t.texImage2D(e.TEXTURE_2D,0,ZA,NA.width,NA.height,0,EA,PA,NA.data);else if(O.isCompressedTexture)if(O.isCompressedArrayTexture){DA&&rA&&t.texStorage3D(e.TEXTURE_2D_ARRAY,j,ZA,Ie[0].width,Ie[0].height,NA.depth);for(let QA=0,dA=Ie.length;QA<dA;QA++)if(FA=Ie[QA],O.format!==Ar)if(EA!==null)if(DA){if(BA)if(O.layerUpdates.size>0){const UA=l4(FA.width,FA.height,O.format,O.type);for(const TA of O.layerUpdates){const oe=FA.data.subarray(TA*UA/FA.data.BYTES_PER_ELEMENT,(TA+1)*UA/FA.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,QA,0,0,TA,FA.width,FA.height,1,EA,oe)}O.clearLayerUpdates()}else t.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,QA,0,0,0,FA.width,FA.height,NA.depth,EA,FA.data)}else t.compressedTexImage3D(e.TEXTURE_2D_ARRAY,QA,ZA,FA.width,FA.height,NA.depth,0,FA.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else DA?BA&&t.texSubImage3D(e.TEXTURE_2D_ARRAY,QA,0,0,0,FA.width,FA.height,NA.depth,EA,PA,FA.data):t.texImage3D(e.TEXTURE_2D_ARRAY,QA,ZA,FA.width,FA.height,NA.depth,0,EA,PA,FA.data)}else{DA&&rA&&t.texStorage2D(e.TEXTURE_2D,j,ZA,Ie[0].width,Ie[0].height);for(let QA=0,dA=Ie.length;QA<dA;QA++)FA=Ie[QA],O.format!==Ar?EA!==null?DA?BA&&t.compressedTexSubImage2D(e.TEXTURE_2D,QA,0,0,FA.width,FA.height,EA,FA.data):t.compressedTexImage2D(e.TEXTURE_2D,QA,ZA,FA.width,FA.height,0,FA.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):DA?BA&&t.texSubImage2D(e.TEXTURE_2D,QA,0,0,FA.width,FA.height,EA,PA,FA.data):t.texImage2D(e.TEXTURE_2D,QA,ZA,FA.width,FA.height,0,EA,PA,FA.data)}else if(O.isDataArrayTexture)if(DA){if(rA&&t.texStorage3D(e.TEXTURE_2D_ARRAY,j,ZA,NA.width,NA.height,NA.depth),BA)if(O.layerUpdates.size>0){const QA=l4(NA.width,NA.height,O.format,O.type);for(const dA of O.layerUpdates){const UA=NA.data.subarray(dA*QA/NA.data.BYTES_PER_ELEMENT,(dA+1)*QA/NA.data.BYTES_PER_ELEMENT);t.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,dA,NA.width,NA.height,1,EA,PA,UA)}O.clearLayerUpdates()}else t.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,NA.width,NA.height,NA.depth,EA,PA,NA.data)}else t.texImage3D(e.TEXTURE_2D_ARRAY,0,ZA,NA.width,NA.height,NA.depth,0,EA,PA,NA.data);else if(O.isData3DTexture)DA?(rA&&t.texStorage3D(e.TEXTURE_3D,j,ZA,NA.width,NA.height,NA.depth),BA&&t.texSubImage3D(e.TEXTURE_3D,0,0,0,0,NA.width,NA.height,NA.depth,EA,PA,NA.data)):t.texImage3D(e.TEXTURE_3D,0,ZA,NA.width,NA.height,NA.depth,0,EA,PA,NA.data);else if(O.isFramebufferTexture){if(rA)if(DA)t.texStorage2D(e.TEXTURE_2D,j,ZA,NA.width,NA.height);else{let QA=NA.width,dA=NA.height;for(let UA=0;UA<j;UA++)t.texImage2D(e.TEXTURE_2D,UA,ZA,QA,dA,0,EA,PA,null),QA>>=1,dA>>=1}}else if(Ie.length>0){if(DA&&rA){const QA=uA(Ie[0]);t.texStorage2D(e.TEXTURE_2D,j,ZA,QA.width,QA.height)}for(let QA=0,dA=Ie.length;QA<dA;QA++)FA=Ie[QA],DA?BA&&t.texSubImage2D(e.TEXTURE_2D,QA,0,0,EA,PA,FA):t.texImage2D(e.TEXTURE_2D,QA,ZA,EA,PA,FA);O.generateMipmaps=!1}else if(DA){if(rA){const QA=uA(NA);t.texStorage2D(e.TEXTURE_2D,j,ZA,QA.width,QA.height)}BA&&t.texSubImage2D(e.TEXTURE_2D,0,0,0,EA,PA,NA)}else t.texImage2D(e.TEXTURE_2D,0,ZA,EA,PA,NA);d(O)&&p(wA),jA.__version=YA.version,O.onUpdate&&O.onUpdate(O)}X.__version=O.version}function yA(X,O,cA){if(O.image.length!==6)return;const wA=aA(X,O),xA=O.source;t.bindTexture(e.TEXTURE_CUBE_MAP,X.__webglTexture,e.TEXTURE0+cA);const YA=i.get(xA);if(xA.version!==YA.__version||wA===!0){t.activeTexture(e.TEXTURE0+cA);const jA=Un.getPrimaries(Un.workingColorSpace),ie=O.colorSpace===DE?null:Un.getPrimaries(O.colorSpace),he=O.colorSpace===DE||jA===ie?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,O.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,O.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,O.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,he);const le=O.isCompressedTexture||O.image[0].isCompressedTexture,NA=O.image[0]&&O.image[0].isDataTexture,EA=[];for(let dA=0;dA<6;dA++)!le&&!NA?EA[dA]=h(O.image[dA],!0,n.maxCubemapSize):EA[dA]=NA?O.image[dA].image:O.image[dA],EA[dA]=_A(O,EA[dA]);const PA=EA[0],ZA=g.convert(O.format,O.colorSpace),FA=g.convert(O.type),Ie=m(O.internalFormat,ZA,FA,O.colorSpace),DA=O.isVideoTexture!==!0,rA=YA.__version===void 0||wA===!0,BA=xA.dataReady;let j=S(O,PA);eA(e.TEXTURE_CUBE_MAP,O);let QA;if(le){DA&&rA&&t.texStorage2D(e.TEXTURE_CUBE_MAP,j,Ie,PA.width,PA.height);for(let dA=0;dA<6;dA++){QA=EA[dA].mipmaps;for(let UA=0;UA<QA.length;UA++){const TA=QA[UA];O.format!==Ar?ZA!==null?DA?BA&&t.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,UA,0,0,TA.width,TA.height,ZA,TA.data):t.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,UA,Ie,TA.width,TA.height,0,TA.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):DA?BA&&t.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,UA,0,0,TA.width,TA.height,ZA,FA,TA.data):t.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,UA,Ie,TA.width,TA.height,0,ZA,FA,TA.data)}}}else{if(QA=O.mipmaps,DA&&rA){QA.length>0&&j++;const dA=uA(EA[0]);t.texStorage2D(e.TEXTURE_CUBE_MAP,j,Ie,dA.width,dA.height)}for(let dA=0;dA<6;dA++)if(NA){DA?BA&&t.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,0,0,0,EA[dA].width,EA[dA].height,ZA,FA,EA[dA].data):t.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,0,Ie,EA[dA].width,EA[dA].height,0,ZA,FA,EA[dA].data);for(let UA=0;UA<QA.length;UA++){const oe=QA[UA].image[dA].image;DA?BA&&t.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,UA+1,0,0,oe.width,oe.height,ZA,FA,oe.data):t.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,UA+1,Ie,oe.width,oe.height,0,ZA,FA,oe.data)}}else{DA?BA&&t.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,0,0,0,ZA,FA,EA[dA]):t.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,0,Ie,ZA,FA,EA[dA]);for(let UA=0;UA<QA.length;UA++){const TA=QA[UA];DA?BA&&t.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,UA+1,0,0,ZA,FA,TA.image[dA]):t.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+dA,UA+1,Ie,ZA,FA,TA.image[dA])}}}d(O)&&p(e.TEXTURE_CUBE_MAP),YA.__version=xA.version,O.onUpdate&&O.onUpdate(O)}X.__version=O.version}function fA(X,O,cA,wA,xA,YA){const jA=g.convert(cA.format,cA.colorSpace),ie=g.convert(cA.type),he=m(cA.internalFormat,jA,ie,cA.colorSpace),le=i.get(O),NA=i.get(cA);if(NA.__renderTarget=O,!le.__hasExternalTextures){const EA=Math.max(1,O.width>>YA),PA=Math.max(1,O.height>>YA);xA===e.TEXTURE_3D||xA===e.TEXTURE_2D_ARRAY?t.texImage3D(xA,YA,he,EA,PA,O.depth,0,jA,ie,null):t.texImage2D(xA,YA,he,EA,PA,0,jA,ie,null)}t.bindFramebuffer(e.FRAMEBUFFER,X),IA(O)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,wA,xA,NA.__webglTexture,0,oA(O)):(xA===e.TEXTURE_2D||xA>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&xA<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,wA,xA,NA.__webglTexture,YA),t.bindFramebuffer(e.FRAMEBUFFER,null)}function RA(X,O,cA){if(e.bindRenderbuffer(e.RENDERBUFFER,X),O.depthBuffer){const wA=O.depthTexture,xA=wA&&wA.isDepthTexture?wA.type:null,YA=D(O.stencilBuffer,xA),jA=O.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ie=oA(O);IA(O)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,ie,YA,O.width,O.height):cA?e.renderbufferStorageMultisample(e.RENDERBUFFER,ie,YA,O.width,O.height):e.renderbufferStorage(e.RENDERBUFFER,YA,O.width,O.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,jA,e.RENDERBUFFER,X)}else{const wA=O.textures;for(let xA=0;xA<wA.length;xA++){const YA=wA[xA],jA=g.convert(YA.format,YA.colorSpace),ie=g.convert(YA.type),he=m(YA.internalFormat,jA,ie,YA.colorSpace),le=oA(O);cA&&IA(O)===!1?e.renderbufferStorageMultisample(e.RENDERBUFFER,le,he,O.width,O.height):IA(O)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,le,he,O.width,O.height):e.renderbufferStorage(e.RENDERBUFFER,he,O.width,O.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function qA(X,O){if(O&&O.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(e.FRAMEBUFFER,X),!(O.depthTexture&&O.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const wA=i.get(O.depthTexture);wA.__renderTarget=O,(!wA.__webglTexture||O.depthTexture.image.width!==O.width||O.depthTexture.image.height!==O.height)&&(O.depthTexture.image.width=O.width,O.depthTexture.image.height=O.height,O.depthTexture.needsUpdate=!0),q(O.depthTexture,0);const xA=wA.__webglTexture,YA=oA(O);if(O.depthTexture.format===qS)IA(O)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,xA,0,YA):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,xA,0);else if(O.depthTexture.format===YS)IA(O)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,xA,0,YA):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,xA,0);else throw new Error("Unknown depthTexture format")}function W(X){const O=i.get(X),cA=X.isWebGLCubeRenderTarget===!0;if(O.__boundDepthTexture!==X.depthTexture){const wA=X.depthTexture;if(O.__depthDisposeCallback&&O.__depthDisposeCallback(),wA){const xA=()=>{delete O.__boundDepthTexture,delete O.__depthDisposeCallback,wA.removeEventListener("dispose",xA)};wA.addEventListener("dispose",xA),O.__depthDisposeCallback=xA}O.__boundDepthTexture=wA}if(X.depthTexture&&!O.__autoAllocateDepthBuffer){if(cA)throw new Error("target.depthTexture not supported in Cube render targets");const wA=X.texture.mipmaps;wA&&wA.length>0?qA(O.__webglFramebuffer[0],X):qA(O.__webglFramebuffer,X)}else if(cA){O.__webglDepthbuffer=[];for(let wA=0;wA<6;wA++)if(t.bindFramebuffer(e.FRAMEBUFFER,O.__webglFramebuffer[wA]),O.__webglDepthbuffer[wA]===void 0)O.__webglDepthbuffer[wA]=e.createRenderbuffer(),RA(O.__webglDepthbuffer[wA],X,!1);else{const xA=X.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,YA=O.__webglDepthbuffer[wA];e.bindRenderbuffer(e.RENDERBUFFER,YA),e.framebufferRenderbuffer(e.FRAMEBUFFER,xA,e.RENDERBUFFER,YA)}}else{const wA=X.texture.mipmaps;if(wA&&wA.length>0?t.bindFramebuffer(e.FRAMEBUFFER,O.__webglFramebuffer[0]):t.bindFramebuffer(e.FRAMEBUFFER,O.__webglFramebuffer),O.__webglDepthbuffer===void 0)O.__webglDepthbuffer=e.createRenderbuffer(),RA(O.__webglDepthbuffer,X,!1);else{const xA=X.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,YA=O.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,YA),e.framebufferRenderbuffer(e.FRAMEBUFFER,xA,e.RENDERBUFFER,YA)}}t.bindFramebuffer(e.FRAMEBUFFER,null)}function $(X,O,cA){const wA=i.get(X);O!==void 0&&fA(wA.__webglFramebuffer,X,X.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),cA!==void 0&&W(X)}function L(X){const O=X.texture,cA=i.get(X),wA=i.get(O);X.addEventListener("dispose",N);const xA=X.textures,YA=X.isWebGLCubeRenderTarget===!0,jA=xA.length>1;if(jA||(wA.__webglTexture===void 0&&(wA.__webglTexture=e.createTexture()),wA.__version=O.version,o.memory.textures++),YA){cA.__webglFramebuffer=[];for(let ie=0;ie<6;ie++)if(O.mipmaps&&O.mipmaps.length>0){cA.__webglFramebuffer[ie]=[];for(let he=0;he<O.mipmaps.length;he++)cA.__webglFramebuffer[ie][he]=e.createFramebuffer()}else cA.__webglFramebuffer[ie]=e.createFramebuffer()}else{if(O.mipmaps&&O.mipmaps.length>0){cA.__webglFramebuffer=[];for(let ie=0;ie<O.mipmaps.length;ie++)cA.__webglFramebuffer[ie]=e.createFramebuffer()}else cA.__webglFramebuffer=e.createFramebuffer();if(jA)for(let ie=0,he=xA.length;ie<he;ie++){const le=i.get(xA[ie]);le.__webglTexture===void 0&&(le.__webglTexture=e.createTexture(),o.memory.textures++)}if(X.samples>0&&IA(X)===!1){cA.__webglMultisampledFramebuffer=e.createFramebuffer(),cA.__webglColorRenderbuffer=[],t.bindFramebuffer(e.FRAMEBUFFER,cA.__webglMultisampledFramebuffer);for(let ie=0;ie<xA.length;ie++){const he=xA[ie];cA.__webglColorRenderbuffer[ie]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,cA.__webglColorRenderbuffer[ie]);const le=g.convert(he.format,he.colorSpace),NA=g.convert(he.type),EA=m(he.internalFormat,le,NA,he.colorSpace,X.isXRRenderTarget===!0),PA=oA(X);e.renderbufferStorageMultisample(e.RENDERBUFFER,PA,EA,X.width,X.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+ie,e.RENDERBUFFER,cA.__webglColorRenderbuffer[ie])}e.bindRenderbuffer(e.RENDERBUFFER,null),X.depthBuffer&&(cA.__webglDepthRenderbuffer=e.createRenderbuffer(),RA(cA.__webglDepthRenderbuffer,X,!0)),t.bindFramebuffer(e.FRAMEBUFFER,null)}}if(YA){t.bindTexture(e.TEXTURE_CUBE_MAP,wA.__webglTexture),eA(e.TEXTURE_CUBE_MAP,O);for(let ie=0;ie<6;ie++)if(O.mipmaps&&O.mipmaps.length>0)for(let he=0;he<O.mipmaps.length;he++)fA(cA.__webglFramebuffer[ie][he],X,O,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+ie,he);else fA(cA.__webglFramebuffer[ie],X,O,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+ie,0);d(O)&&p(e.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(jA){for(let ie=0,he=xA.length;ie<he;ie++){const le=xA[ie],NA=i.get(le);let EA=e.TEXTURE_2D;(X.isWebGL3DRenderTarget||X.isWebGLArrayRenderTarget)&&(EA=X.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),t.bindTexture(EA,NA.__webglTexture),eA(EA,le),fA(cA.__webglFramebuffer,X,le,e.COLOR_ATTACHMENT0+ie,EA,0),d(le)&&p(EA)}t.unbindTexture()}else{let ie=e.TEXTURE_2D;if((X.isWebGL3DRenderTarget||X.isWebGLArrayRenderTarget)&&(ie=X.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),t.bindTexture(ie,wA.__webglTexture),eA(ie,O),O.mipmaps&&O.mipmaps.length>0)for(let he=0;he<O.mipmaps.length;he++)fA(cA.__webglFramebuffer[he],X,O,e.COLOR_ATTACHMENT0,ie,he);else fA(cA.__webglFramebuffer,X,O,e.COLOR_ATTACHMENT0,ie,0);d(O)&&p(ie),t.unbindTexture()}X.depthBuffer&&W(X)}function H(X){const O=X.textures;for(let cA=0,wA=O.length;cA<wA;cA++){const xA=O[cA];if(d(xA)){const YA=y(X),jA=i.get(xA).__webglTexture;t.bindTexture(YA,jA),p(YA),t.unbindTexture()}}}const P=[],tA=[];function iA(X){if(X.samples>0){if(IA(X)===!1){const O=X.textures,cA=X.width,wA=X.height;let xA=e.COLOR_BUFFER_BIT;const YA=X.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,jA=i.get(X),ie=O.length>1;if(ie)for(let le=0;le<O.length;le++)t.bindFramebuffer(e.FRAMEBUFFER,jA.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+le,e.RENDERBUFFER,null),t.bindFramebuffer(e.FRAMEBUFFER,jA.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+le,e.TEXTURE_2D,null,0);t.bindFramebuffer(e.READ_FRAMEBUFFER,jA.__webglMultisampledFramebuffer);const he=X.texture.mipmaps;he&&he.length>0?t.bindFramebuffer(e.DRAW_FRAMEBUFFER,jA.__webglFramebuffer[0]):t.bindFramebuffer(e.DRAW_FRAMEBUFFER,jA.__webglFramebuffer);for(let le=0;le<O.length;le++){if(X.resolveDepthBuffer&&(X.depthBuffer&&(xA|=e.DEPTH_BUFFER_BIT),X.stencilBuffer&&X.resolveStencilBuffer&&(xA|=e.STENCIL_BUFFER_BIT)),ie){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,jA.__webglColorRenderbuffer[le]);const NA=i.get(O[le]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,NA,0)}e.blitFramebuffer(0,0,cA,wA,0,0,cA,wA,xA,e.NEAREST),a===!0&&(P.length=0,tA.length=0,P.push(e.COLOR_ATTACHMENT0+le),X.depthBuffer&&X.resolveDepthBuffer===!1&&(P.push(YA),tA.push(YA),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,tA)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,P))}if(t.bindFramebuffer(e.READ_FRAMEBUFFER,null),t.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),ie)for(let le=0;le<O.length;le++){t.bindFramebuffer(e.FRAMEBUFFER,jA.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+le,e.RENDERBUFFER,jA.__webglColorRenderbuffer[le]);const NA=i.get(O[le]).__webglTexture;t.bindFramebuffer(e.FRAMEBUFFER,jA.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+le,e.TEXTURE_2D,NA,0)}t.bindFramebuffer(e.DRAW_FRAMEBUFFER,jA.__webglMultisampledFramebuffer)}else if(X.depthBuffer&&X.resolveDepthBuffer===!1&&a){const O=X.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[O])}}}function oA(X){return Math.min(n.maxSamples,X.samples)}function IA(X){const O=i.get(X);return X.samples>0&&A.has("WEBGL_multisampled_render_to_texture")===!0&&O.__useRenderToTexture!==!1}function CA(X){const O=o.render.frame;I.get(X)!==O&&(I.set(X,O),X.update())}function _A(X,O){const cA=X.colorSpace,wA=X.format,xA=X.type;return X.isCompressedTexture===!0||X.isVideoTexture===!0||cA!==Ka&&cA!==DE&&(Un.getTransfer(cA)===mg?(wA!==Ar||xA!==Ic)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",cA)),O}function uA(X){return typeof HTMLImageElement<"u"&&X instanceof HTMLImageElement?(r.width=X.naturalWidth||X.width,r.height=X.naturalHeight||X.height):typeof VideoFrame<"u"&&X instanceof VideoFrame?(r.width=X.displayWidth,r.height=X.displayHeight):(r.width=X.width,r.height=X.height),r}this.allocateTextureUnit=K,this.resetTextureUnits=_,this.setTexture2D=q,this.setTexture2DArray=v,this.setTexture3D=U,this.setTextureCube=x,this.rebindTextures=$,this.setupRenderTarget=L,this.updateRenderTargetMipmap=H,this.updateMultisampleRenderTarget=iA,this.setupDepthRenderbuffer=W,this.setupFrameBufferTexture=fA,this.useMultisampledRTT=IA}function VyA(e,A){function t(i,n=DE){let g;const o=Un.getTransfer(n);if(i===Ic)return e.UNSIGNED_BYTE;if(i===_x)return e.UNSIGNED_SHORT_4_4_4_4;if(i===Jx)return e.UNSIGNED_SHORT_5_5_5_1;if(i===NW)return e.UNSIGNED_INT_5_9_9_9_REV;if(i===RW)return e.UNSIGNED_INT_10F_11F_11F_REV;if(i===kW)return e.BYTE;if(i===MW)return e.SHORT;if(i===xS)return e.UNSIGNED_SHORT;if(i===Fx)return e.INT;if(i===IQ)return e.UNSIGNED_INT;if(i===br)return e.FLOAT;if(i===ny)return e.HALF_FLOAT;if(i===GW)return e.ALPHA;if(i===bW)return e.RGB;if(i===Ar)return e.RGBA;if(i===qS)return e.DEPTH_COMPONENT;if(i===YS)return e.DEPTH_STENCIL;if(i===Lx)return e.RED;if(i===gG)return e.RED_INTEGER;if(i===UW)return e.RG;if(i===xx)return e.RG_INTEGER;if(i===Tx)return e.RGBA_INTEGER;if(i===DM||i===mM||i===SM||i===wM)if(o===mg)if(g=A.get("WEBGL_compressed_texture_s3tc_srgb"),g!==null){if(i===DM)return g.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===mM)return g.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===SM)return g.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===wM)return g.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(g=A.get("WEBGL_compressed_texture_s3tc"),g!==null){if(i===DM)return g.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===mM)return g.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===SM)return g.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===wM)return g.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===H_||i===O_||i===P_||i===j_)if(g=A.get("WEBGL_compressed_texture_pvrtc"),g!==null){if(i===H_)return g.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===O_)return g.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===P_)return g.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===j_)return g.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===z_||i===Z_||i===W_)if(g=A.get("WEBGL_compressed_texture_etc"),g!==null){if(i===z_||i===Z_)return o===mg?g.COMPRESSED_SRGB8_ETC2:g.COMPRESSED_RGB8_ETC2;if(i===W_)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:g.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===V_||i===X_||i===$_||i===AJ||i===eJ||i===tJ||i===iJ||i===nJ||i===gJ||i===oJ||i===sJ||i===aJ||i===rJ||i===IJ)if(g=A.get("WEBGL_compressed_texture_astc"),g!==null){if(i===V_)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:g.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===X_)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:g.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===$_)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:g.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===AJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:g.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===eJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:g.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===tJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:g.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===iJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:g.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===nJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:g.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===gJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:g.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===oJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:g.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===sJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:g.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===aJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:g.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===rJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:g.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===IJ)return o===mg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:g.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===CJ||i===cJ||i===lJ)if(g=A.get("EXT_texture_compression_bptc"),g!==null){if(i===CJ)return o===mg?g.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:g.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===cJ)return g.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===lJ)return g.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===BJ||i===EJ||i===QJ||i===uJ)if(g=A.get("EXT_texture_compression_rgtc"),g!==null){if(i===BJ)return g.COMPRESSED_RED_RGTC1_EXT;if(i===EJ)return g.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===QJ)return g.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===uJ)return g.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===TS?e.UNSIGNED_INT_24_8:e[i]!==void 0?e[i]:null}return{convert:t}}const GEe=`
void main() {

	gl_Position = vec4( position, 1.0 );

}`,bEe=`
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;

void main() {

	vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );

	if ( coord.x >= 1.0 ) {

		gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;

	} else {

		gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;

	}

}`;class UEe{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(A,t){if(this.texture===null){const i=new YW(A.texture);(A.depthNear!==t.depthNear||A.depthFar!==t.depthFar)&&(this.depthNear=A.depthNear,this.depthFar=A.depthFar),this.texture=i}}getMesh(A){if(this.texture!==null&&this.mesh===null){const t=A.cameras[0].viewport,i=new Cc({vertexShader:GEe,fragmentShader:bEe,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new pn(new oB(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class vEe extends bB{constructor(A,t){super();const i=this;let n=null,g=1,o=null,s="local-floor",a=1,r=null,I=null,c=null,l=null,B=null,Q=null;const h=typeof XRWebGLBinding<"u",d=new UEe,p={},y=t.getContextAttributes();let m=null,D=null;const S=[],k=[],N=new lt;let G=null;const M=new Wo;M.viewport=new ig;const w=new Wo;w.viewport=new ig;const b=[M,w],_=new xyA;let K=null,J=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(gA){let yA=S[gA];return yA===void 0&&(yA=new vK,S[gA]=yA),yA.getTargetRaySpace()},this.getControllerGrip=function(gA){let yA=S[gA];return yA===void 0&&(yA=new vK,S[gA]=yA),yA.getGripSpace()},this.getHand=function(gA){let yA=S[gA];return yA===void 0&&(yA=new vK,S[gA]=yA),yA.getHandSpace()};function q(gA){const yA=k.indexOf(gA.inputSource);if(yA===-1)return;const fA=S[yA];fA!==void 0&&(fA.update(gA.inputSource,gA.frame,r||o),fA.dispatchEvent({type:gA.type,data:gA.inputSource}))}function v(){n.removeEventListener("select",q),n.removeEventListener("selectstart",q),n.removeEventListener("selectend",q),n.removeEventListener("squeeze",q),n.removeEventListener("squeezestart",q),n.removeEventListener("squeezeend",q),n.removeEventListener("end",v),n.removeEventListener("inputsourceschange",U);for(let gA=0;gA<S.length;gA++){const yA=k[gA];yA!==null&&(k[gA]=null,S[gA].disconnect(yA))}K=null,J=null,d.reset();for(const gA in p)delete p[gA];A.setRenderTarget(m),B=null,l=null,c=null,n=null,D=null,pA.stop(),i.isPresenting=!1,A.setPixelRatio(G),A.setSize(N.width,N.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(gA){g=gA,i.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(gA){s=gA,i.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return r||o},this.setReferenceSpace=function(gA){r=gA},this.getBaseLayer=function(){return l!==null?l:B},this.getBinding=function(){return c===null&&h&&(c=new XRWebGLBinding(n,t)),c},this.getFrame=function(){return Q},this.getSession=function(){return n},this.setSession=async function(gA){if(n=gA,n!==null){if(m=A.getRenderTarget(),n.addEventListener("select",q),n.addEventListener("selectstart",q),n.addEventListener("selectend",q),n.addEventListener("squeeze",q),n.addEventListener("squeezestart",q),n.addEventListener("squeezeend",q),n.addEventListener("end",v),n.addEventListener("inputsourceschange",U),y.xrCompatible!==!0&&await t.makeXRCompatible(),G=A.getPixelRatio(),A.getSize(N),h&&"createProjectionLayer"in XRWebGLBinding.prototype){let fA=null,RA=null,qA=null;y.depth&&(qA=y.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,fA=y.stencil?YS:qS,RA=y.stencil?TS:IQ);const W={colorFormat:t.RGBA8,depthFormat:qA,scaleFactor:g};c=this.getBinding(),l=c.createProjectionLayer(W),n.updateRenderState({layers:[l]}),A.setPixelRatio(1),A.setSize(l.textureWidth,l.textureHeight,!1),D=new il(l.textureWidth,l.textureHeight,{format:Ar,type:Ic,depthTexture:new Vx(l.textureWidth,l.textureHeight,RA,void 0,void 0,void 0,void 0,void 0,void 0,fA),stencilBuffer:y.stencil,colorSpace:A.outputColorSpace,samples:y.antialias?4:0,resolveDepthBuffer:l.ignoreDepthValues===!1,resolveStencilBuffer:l.ignoreDepthValues===!1})}else{const fA={antialias:y.antialias,alpha:!0,depth:y.depth,stencil:y.stencil,framebufferScaleFactor:g};B=new XRWebGLLayer(n,t,fA),n.updateRenderState({baseLayer:B}),A.setPixelRatio(1),A.setSize(B.framebufferWidth,B.framebufferHeight,!1),D=new il(B.framebufferWidth,B.framebufferHeight,{format:Ar,type:Ic,colorSpace:A.outputColorSpace,stencilBuffer:y.stencil,resolveDepthBuffer:B.ignoreDepthValues===!1,resolveStencilBuffer:B.ignoreDepthValues===!1})}D.isXRRenderTarget=!0,this.setFoveation(a),r=null,o=await n.requestReferenceSpace(s),pA.setContext(n),pA.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode},this.getDepthTexture=function(){return d.getDepthTexture()};function U(gA){for(let yA=0;yA<gA.removed.length;yA++){const fA=gA.removed[yA],RA=k.indexOf(fA);RA>=0&&(k[RA]=null,S[RA].disconnect(fA))}for(let yA=0;yA<gA.added.length;yA++){const fA=gA.added[yA];let RA=k.indexOf(fA);if(RA===-1){for(let W=0;W<S.length;W++)if(W>=k.length){k.push(fA),RA=W;break}else if(k[W]===null){k[W]=fA,RA=W;break}if(RA===-1)break}const qA=S[RA];qA&&qA.connect(fA)}}const x=new SA,T=new SA;function z(gA,yA,fA){x.setFromMatrixPosition(yA.matrixWorld),T.setFromMatrixPosition(fA.matrixWorld);const RA=x.distanceTo(T),qA=yA.projectionMatrix.elements,W=fA.projectionMatrix.elements,$=qA[14]/(qA[10]-1),L=qA[14]/(qA[10]+1),H=(qA[9]+1)/qA[5],P=(qA[9]-1)/qA[5],tA=(qA[8]-1)/qA[0],iA=(W[8]+1)/W[0],oA=$*tA,IA=$*iA,CA=RA/(-tA+iA),_A=CA*-tA;if(yA.matrixWorld.decompose(gA.position,gA.quaternion,gA.scale),gA.translateX(_A),gA.translateZ(CA),gA.matrixWorld.compose(gA.position,gA.quaternion,gA.scale),gA.matrixWorldInverse.copy(gA.matrixWorld).invert(),qA[10]===-1)gA.projectionMatrix.copy(yA.projectionMatrix),gA.projectionMatrixInverse.copy(yA.projectionMatrixInverse);else{const uA=$+CA,X=L+CA,O=oA-_A,cA=IA+(RA-_A),wA=H*L/X*uA,xA=P*L/X*uA;gA.projectionMatrix.makePerspective(O,cA,wA,xA,uA,X),gA.projectionMatrixInverse.copy(gA.projectionMatrix).invert()}}function Z(gA,yA){yA===null?gA.matrixWorld.copy(gA.matrix):gA.matrixWorld.multiplyMatrices(yA.matrixWorld,gA.matrix),gA.matrixWorldInverse.copy(gA.matrixWorld).invert()}this.updateCamera=function(gA){if(n===null)return;let yA=gA.near,fA=gA.far;d.texture!==null&&(d.depthNear>0&&(yA=d.depthNear),d.depthFar>0&&(fA=d.depthFar)),_.near=w.near=M.near=yA,_.far=w.far=M.far=fA,(K!==_.near||J!==_.far)&&(n.updateRenderState({depthNear:_.near,depthFar:_.far}),K=_.near,J=_.far),_.layers.mask=gA.layers.mask|6,M.layers.mask=_.layers.mask&3,w.layers.mask=_.layers.mask&5;const RA=gA.parent,qA=_.cameras;Z(_,RA);for(let W=0;W<qA.length;W++)Z(qA[W],RA);qA.length===2?z(_,M,w):_.projectionMatrix.copy(M.projectionMatrix),eA(gA,_,RA)};function eA(gA,yA,fA){fA===null?gA.matrix.copy(yA.matrixWorld):(gA.matrix.copy(fA.matrixWorld),gA.matrix.invert(),gA.matrix.multiply(yA.matrixWorld)),gA.matrix.decompose(gA.position,gA.quaternion,gA.scale),gA.updateMatrixWorld(!0),gA.projectionMatrix.copy(yA.projectionMatrix),gA.projectionMatrixInverse.copy(yA.projectionMatrixInverse),gA.isPerspectiveCamera&&(gA.fov=OS*2*Math.atan(1/gA.projectionMatrix.elements[5]),gA.zoom=1)}this.getCamera=function(){return _},this.getFoveation=function(){if(!(l===null&&B===null))return a},this.setFoveation=function(gA){a=gA,l!==null&&(l.fixedFoveation=gA),B!==null&&B.fixedFoveation!==void 0&&(B.fixedFoveation=gA)},this.hasDepthSensing=function(){return d.texture!==null},this.getDepthSensingMesh=function(){return d.getMesh(_)},this.getCameraTexture=function(gA){return p[gA]};let aA=null;function sA(gA,yA){if(I=yA.getViewerPose(r||o),Q=yA,I!==null){const fA=I.views;B!==null&&(A.setRenderTargetFramebuffer(D,B.framebuffer),A.setRenderTarget(D));let RA=!1;fA.length!==_.cameras.length&&(_.cameras.length=0,RA=!0);for(let L=0;L<fA.length;L++){const H=fA[L];let P=null;if(B!==null)P=B.getViewport(H);else{const iA=c.getViewSubImage(l,H);P=iA.viewport,L===0&&(A.setRenderTargetTextures(D,iA.colorTexture,iA.depthStencilTexture),A.setRenderTarget(D))}let tA=b[L];tA===void 0&&(tA=new Wo,tA.layers.enable(L),tA.viewport=new ig,b[L]=tA),tA.matrix.fromArray(H.transform.matrix),tA.matrix.decompose(tA.position,tA.quaternion,tA.scale),tA.projectionMatrix.fromArray(H.projectionMatrix),tA.projectionMatrixInverse.copy(tA.projectionMatrix).invert(),tA.viewport.set(P.x,P.y,P.width,P.height),L===0&&(_.matrix.copy(tA.matrix),_.matrix.decompose(_.position,_.quaternion,_.scale)),RA===!0&&_.cameras.push(tA)}const qA=n.enabledFeatures;if(qA&&qA.includes("depth-sensing")&&n.depthUsage=="gpu-optimized"&&h){c=i.getBinding();const L=c.getDepthInformation(fA[0]);L&&L.isValid&&L.texture&&d.init(L,n.renderState)}if(qA&&qA.includes("camera-access")&&h){A.state.unbindTexture(),c=i.getBinding();for(let L=0;L<fA.length;L++){const H=fA[L].camera;if(H){let P=p[H];P||(P=new YW,p[H]=P);const tA=c.getCameraImage(H);P.sourceTexture=tA}}}}for(let fA=0;fA<S.length;fA++){const RA=k[fA],qA=S[fA];RA!==null&&qA!==void 0&&qA.update(RA,yA,r||o)}aA&&aA(gA,yA),yA.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:yA}),Q=null}const pA=new PyA;pA.setAnimationLoop(sA),this.setAnimationLoop=function(gA){aA=gA},this.dispose=function(){}}}const bh=new ca,KEe=new ni;function FEe(e,A){function t(d,p){d.matrixAutoUpdate===!0&&d.updateMatrix(),p.value.copy(d.matrix)}function i(d,p){p.color.getRGB(d.fogColor.value,oyA(e)),p.isFog?(d.fogNear.value=p.near,d.fogFar.value=p.far):p.isFogExp2&&(d.fogDensity.value=p.density)}function n(d,p,y,m,D){p.isMeshBasicMaterial||p.isMeshLambertMaterial?g(d,p):p.isMeshToonMaterial?(g(d,p),c(d,p)):p.isMeshPhongMaterial?(g(d,p),I(d,p)):p.isMeshStandardMaterial?(g(d,p),l(d,p),p.isMeshPhysicalMaterial&&B(d,p,D)):p.isMeshMatcapMaterial?(g(d,p),Q(d,p)):p.isMeshDepthMaterial?g(d,p):p.isMeshDistanceMaterial?(g(d,p),h(d,p)):p.isMeshNormalMaterial?g(d,p):p.isLineBasicMaterial?(o(d,p),p.isLineDashedMaterial&&s(d,p)):p.isPointsMaterial?a(d,p,y,m):p.isSpriteMaterial?r(d,p):p.isShadowMaterial?(d.color.value.copy(p.color),d.opacity.value=p.opacity):p.isShaderMaterial&&(p.uniformsNeedUpdate=!1)}function g(d,p){d.opacity.value=p.opacity,p.color&&d.diffuse.value.copy(p.color),p.emissive&&d.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity),p.map&&(d.map.value=p.map,t(p.map,d.mapTransform)),p.alphaMap&&(d.alphaMap.value=p.alphaMap,t(p.alphaMap,d.alphaMapTransform)),p.bumpMap&&(d.bumpMap.value=p.bumpMap,t(p.bumpMap,d.bumpMapTransform),d.bumpScale.value=p.bumpScale,p.side===Ua&&(d.bumpScale.value*=-1)),p.normalMap&&(d.normalMap.value=p.normalMap,t(p.normalMap,d.normalMapTransform),d.normalScale.value.copy(p.normalScale),p.side===Ua&&d.normalScale.value.negate()),p.displacementMap&&(d.displacementMap.value=p.displacementMap,t(p.displacementMap,d.displacementMapTransform),d.displacementScale.value=p.displacementScale,d.displacementBias.value=p.displacementBias),p.emissiveMap&&(d.emissiveMap.value=p.emissiveMap,t(p.emissiveMap,d.emissiveMapTransform)),p.specularMap&&(d.specularMap.value=p.specularMap,t(p.specularMap,d.specularMapTransform)),p.alphaTest>0&&(d.alphaTest.value=p.alphaTest);const y=A.get(p),m=y.envMap,D=y.envMapRotation;m&&(d.envMap.value=m,bh.copy(D),bh.x*=-1,bh.y*=-1,bh.z*=-1,m.isCubeTexture&&m.isRenderTargetTexture===!1&&(bh.y*=-1,bh.z*=-1),d.envMapRotation.value.setFromMatrix4(KEe.makeRotationFromEuler(bh)),d.flipEnvMap.value=m.isCubeTexture&&m.isRenderTargetTexture===!1?-1:1,d.reflectivity.value=p.reflectivity,d.ior.value=p.ior,d.refractionRatio.value=p.refractionRatio),p.lightMap&&(d.lightMap.value=p.lightMap,d.lightMapIntensity.value=p.lightMapIntensity,t(p.lightMap,d.lightMapTransform)),p.aoMap&&(d.aoMap.value=p.aoMap,d.aoMapIntensity.value=p.aoMapIntensity,t(p.aoMap,d.aoMapTransform))}function o(d,p){d.diffuse.value.copy(p.color),d.opacity.value=p.opacity,p.map&&(d.map.value=p.map,t(p.map,d.mapTransform))}function s(d,p){d.dashSize.value=p.dashSize,d.totalSize.value=p.dashSize+p.gapSize,d.scale.value=p.scale}function a(d,p,y,m){d.diffuse.value.copy(p.color),d.opacity.value=p.opacity,d.size.value=p.size*y,d.scale.value=m*.5,p.map&&(d.map.value=p.map,t(p.map,d.uvTransform)),p.alphaMap&&(d.alphaMap.value=p.alphaMap,t(p.alphaMap,d.alphaMapTransform)),p.alphaTest>0&&(d.alphaTest.value=p.alphaTest)}function r(d,p){d.diffuse.value.copy(p.color),d.opacity.value=p.opacity,d.rotation.value=p.rotation,p.map&&(d.map.value=p.map,t(p.map,d.mapTransform)),p.alphaMap&&(d.alphaMap.value=p.alphaMap,t(p.alphaMap,d.alphaMapTransform)),p.alphaTest>0&&(d.alphaTest.value=p.alphaTest)}function I(d,p){d.specular.value.copy(p.specular),d.shininess.value=Math.max(p.shininess,1e-4)}function c(d,p){p.gradientMap&&(d.gradientMap.value=p.gradientMap)}function l(d,p){d.metalness.value=p.metalness,p.metalnessMap&&(d.metalnessMap.value=p.metalnessMap,t(p.metalnessMap,d.metalnessMapTransform)),d.roughness.value=p.roughness,p.roughnessMap&&(d.roughnessMap.value=p.roughnessMap,t(p.roughnessMap,d.roughnessMapTransform)),p.envMap&&(d.envMapIntensity.value=p.envMapIntensity)}function B(d,p,y){d.ior.value=p.ior,p.sheen>0&&(d.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen),d.sheenRoughness.value=p.sheenRoughness,p.sheenColorMap&&(d.sheenColorMap.value=p.sheenColorMap,t(p.sheenColorMap,d.sheenColorMapTransform)),p.sheenRoughnessMap&&(d.sheenRoughnessMap.value=p.sheenRoughnessMap,t(p.sheenRoughnessMap,d.sheenRoughnessMapTransform))),p.clearcoat>0&&(d.clearcoat.value=p.clearcoat,d.clearcoatRoughness.value=p.clearcoatRoughness,p.clearcoatMap&&(d.clearcoatMap.value=p.clearcoatMap,t(p.clearcoatMap,d.clearcoatMapTransform)),p.clearcoatRoughnessMap&&(d.clearcoatRoughnessMap.value=p.clearcoatRoughnessMap,t(p.clearcoatRoughnessMap,d.clearcoatRoughnessMapTransform)),p.clearcoatNormalMap&&(d.clearcoatNormalMap.value=p.clearcoatNormalMap,t(p.clearcoatNormalMap,d.clearcoatNormalMapTransform),d.clearcoatNormalScale.value.copy(p.clearcoatNormalScale),p.side===Ua&&d.clearcoatNormalScale.value.negate())),p.dispersion>0&&(d.dispersion.value=p.dispersion),p.iridescence>0&&(d.iridescence.value=p.iridescence,d.iridescenceIOR.value=p.iridescenceIOR,d.iridescenceThicknessMinimum.value=p.iridescenceThicknessRange[0],d.iridescenceThicknessMaximum.value=p.iridescenceThicknessRange[1],p.iridescenceMap&&(d.iridescenceMap.value=p.iridescenceMap,t(p.iridescenceMap,d.iridescenceMapTransform)),p.iridescenceThicknessMap&&(d.iridescenceThicknessMap.value=p.iridescenceThicknessMap,t(p.iridescenceThicknessMap,d.iridescenceThicknessMapTransform))),p.transmission>0&&(d.transmission.value=p.transmission,d.transmissionSamplerMap.value=y.texture,d.transmissionSamplerSize.value.set(y.width,y.height),p.transmissionMap&&(d.transmissionMap.value=p.transmissionMap,t(p.transmissionMap,d.transmissionMapTransform)),d.thickness.value=p.thickness,p.thicknessMap&&(d.thicknessMap.value=p.thicknessMap,t(p.thicknessMap,d.thicknessMapTransform)),d.attenuationDistance.value=p.attenuationDistance,d.attenuationColor.value.copy(p.attenuationColor)),p.anisotropy>0&&(d.anisotropyVector.value.set(p.anisotropy*Math.cos(p.anisotropyRotation),p.anisotropy*Math.sin(p.anisotropyRotation)),p.anisotropyMap&&(d.anisotropyMap.value=p.anisotropyMap,t(p.anisotropyMap,d.anisotropyMapTransform))),d.specularIntensity.value=p.specularIntensity,d.specularColor.value.copy(p.specularColor),p.specularColorMap&&(d.specularColorMap.value=p.specularColorMap,t(p.specularColorMap,d.specularColorMapTransform)),p.specularIntensityMap&&(d.specularIntensityMap.value=p.specularIntensityMap,t(p.specularIntensityMap,d.specularIntensityMapTransform))}function Q(d,p){p.matcap&&(d.matcap.value=p.matcap)}function h(d,p){const y=A.get(p).light;d.referencePosition.value.setFromMatrixPosition(y.matrixWorld),d.nearDistance.value=y.shadow.camera.near,d.farDistance.value=y.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function _Ee(e,A,t,i){let n={},g={},o=[];const s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function a(y,m){const D=m.program;i.uniformBlockBinding(y,D)}function r(y,m){let D=n[y.id];D===void 0&&(Q(y),D=I(y),n[y.id]=D,y.addEventListener("dispose",d));const S=m.program;i.updateUBOMapping(y,S);const k=A.render.frame;g[y.id]!==k&&(l(y),g[y.id]=k)}function I(y){const m=c();y.__bindingPointIndex=m;const D=e.createBuffer(),S=y.__size,k=y.usage;return e.bindBuffer(e.UNIFORM_BUFFER,D),e.bufferData(e.UNIFORM_BUFFER,S,k),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,m,D),D}function c(){for(let y=0;y<s;y++)if(o.indexOf(y)===-1)return o.push(y),y;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function l(y){const m=n[y.id],D=y.uniforms,S=y.__cache;e.bindBuffer(e.UNIFORM_BUFFER,m);for(let k=0,N=D.length;k<N;k++){const G=Array.isArray(D[k])?D[k]:[D[k]];for(let M=0,w=G.length;M<w;M++){const b=G[M];if(B(b,k,M,S)===!0){const _=b.__offset,K=Array.isArray(b.value)?b.value:[b.value];let J=0;for(let q=0;q<K.length;q++){const v=K[q],U=h(v);typeof v=="number"||typeof v=="boolean"?(b.__data[0]=v,e.bufferSubData(e.UNIFORM_BUFFER,_+J,b.__data)):v.isMatrix3?(b.__data[0]=v.elements[0],b.__data[1]=v.elements[1],b.__data[2]=v.elements[2],b.__data[3]=0,b.__data[4]=v.elements[3],b.__data[5]=v.elements[4],b.__data[6]=v.elements[5],b.__data[7]=0,b.__data[8]=v.elements[6],b.__data[9]=v.elements[7],b.__data[10]=v.elements[8],b.__data[11]=0):(v.toArray(b.__data,J),J+=U.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,_,b.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}function B(y,m,D,S){const k=y.value,N=m+"_"+D;if(S[N]===void 0)return typeof k=="number"||typeof k=="boolean"?S[N]=k:S[N]=k.clone(),!0;{const G=S[N];if(typeof k=="number"||typeof k=="boolean"){if(G!==k)return S[N]=k,!0}else if(G.equals(k)===!1)return G.copy(k),!0}return!1}function Q(y){const m=y.uniforms;let D=0;const S=16;for(let N=0,G=m.length;N<G;N++){const M=Array.isArray(m[N])?m[N]:[m[N]];for(let w=0,b=M.length;w<b;w++){const _=M[w],K=Array.isArray(_.value)?_.value:[_.value];for(let J=0,q=K.length;J<q;J++){const v=K[J],U=h(v),x=D%S,T=x%U.boundary,z=x+T;D+=T,z!==0&&S-z<U.storage&&(D+=S-z),_.__data=new Float32Array(U.storage/Float32Array.BYTES_PER_ELEMENT),_.__offset=D,D+=U.storage}}}const k=D%S;return k>0&&(D+=S-k),y.__size=D,y.__cache={},this}function h(y){const m={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(m.boundary=4,m.storage=4):y.isVector2?(m.boundary=8,m.storage=8):y.isVector3||y.isColor?(m.boundary=16,m.storage=12):y.isVector4?(m.boundary=16,m.storage=16):y.isMatrix3?(m.boundary=48,m.storage=48):y.isMatrix4?(m.boundary=64,m.storage=64):y.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",y),m}function d(y){const m=y.target;m.removeEventListener("dispose",d);const D=o.indexOf(m.__bindingPointIndex);o.splice(D,1),e.deleteBuffer(n[m.id]),delete n[m.id],delete g[m.id]}function p(){for(const y in n)e.deleteBuffer(n[y]);o=[],n={},g={}}return{bind:a,update:r,dispose:p}}class dV{constructor(A={}){const{canvas:t=iyA(),context:i=null,depth:n=!0,stencil:g=!1,alpha:o=!1,antialias:s=!1,premultipliedAlpha:a=!0,preserveDrawingBuffer:r=!1,powerPreference:I="default",failIfMajorPerformanceCaveat:c=!1,reversedDepthBuffer:l=!1}=A;this.isWebGLRenderer=!0;let B;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");B=i.getContextAttributes().alpha}else B=o;const Q=new Uint32Array(4),h=new Int32Array(4);let d=null,p=null;const y=[],m=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=QB,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const D=this;let S=!1;this._outputColorSpace=rn;let k=0,N=0,G=null,M=-1,w=null;const b=new ig,_=new ig;let K=null;const J=new Et(0);let q=0,v=t.width,U=t.height,x=1,T=null,z=null;const Z=new ig(0,0,v,U),eA=new ig(0,0,v,U);let aA=!1;const sA=new Lw;let pA=!1,gA=!1;const yA=new ni,fA=new SA,RA=new ig,qA={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let W=!1;function $(){return G===null?x:1}let L=i;function H(nA,vA){return t.getContext(nA,vA)}try{const nA={alpha:!0,depth:n,stencil:g,antialias:s,premultipliedAlpha:a,preserveDrawingBuffer:r,powerPreference:I,failIfMajorPerformanceCaveat:c};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${tG}`),t.addEventListener("webglcontextlost",BA,!1),t.addEventListener("webglcontextrestored",j,!1),t.addEventListener("webglcontextcreationerror",QA,!1),L===null){const vA="webgl2";if(L=H(vA,nA),L===null)throw H(vA)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(nA){throw console.error("THREE.WebGLRenderer: "+nA.message),nA}let P,tA,iA,oA,IA,CA,_A,uA,X,O,cA,wA,xA,YA,jA,ie,he,le,NA,EA,PA,ZA,FA,Ie;function DA(){P=new Zle(L),P.init(),ZA=new VyA(L,P),tA=new qle(L,P,A,ZA),iA=new NEe(L,P),tA.reversedDepthBuffer&&l&&iA.buffers.depth.setReversed(!0),oA=new Xle(L),IA=new QEe,CA=new REe(L,P,iA,IA,tA,ZA,oA),_A=new Hle(D),uA=new zle(D),X=new nCe(L),FA=new xle(L,X),O=new Wle(L,X,oA,FA),cA=new ABe(L,O,X,oA),NA=new $le(L,tA,CA),ie=new Yle(IA),wA=new EEe(D,_A,uA,P,tA,FA,ie),xA=new FEe(D,IA),YA=new dEe,jA=new mEe(P),le=new Lle(D,_A,uA,iA,cA,B,a),he=new kEe(D,cA,tA),Ie=new _Ee(L,oA,tA,iA),EA=new Tle(L,P,oA),PA=new Vle(L,P,oA),oA.programs=wA.programs,D.capabilities=tA,D.extensions=P,D.properties=IA,D.renderLists=YA,D.shadowMap=he,D.state=iA,D.info=oA}DA();const rA=new vEe(D,L);this.xr=rA,this.getContext=function(){return L},this.getContextAttributes=function(){return L.getContextAttributes()},this.forceContextLoss=function(){const nA=P.get("WEBGL_lose_context");nA&&nA.loseContext()},this.forceContextRestore=function(){const nA=P.get("WEBGL_lose_context");nA&&nA.restoreContext()},this.getPixelRatio=function(){return x},this.setPixelRatio=function(nA){nA!==void 0&&(x=nA,this.setSize(v,U,!1))},this.getSize=function(nA){return nA.set(v,U)},this.setSize=function(nA,vA,KA=!0){if(rA.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}v=nA,U=vA,t.width=Math.floor(nA*x),t.height=Math.floor(vA*x),KA===!0&&(t.style.width=nA+"px",t.style.height=vA+"px"),this.setViewport(0,0,nA,vA)},this.getDrawingBufferSize=function(nA){return nA.set(v*x,U*x).floor()},this.setDrawingBufferSize=function(nA,vA,KA){v=nA,U=vA,x=KA,t.width=Math.floor(nA*KA),t.height=Math.floor(vA*KA),this.setViewport(0,0,nA,vA)},this.getCurrentViewport=function(nA){return nA.copy(b)},this.getViewport=function(nA){return nA.copy(Z)},this.setViewport=function(nA,vA,KA,WA){nA.isVector4?Z.set(nA.x,nA.y,nA.z,nA.w):Z.set(nA,vA,KA,WA),iA.viewport(b.copy(Z).multiplyScalar(x).round())},this.getScissor=function(nA){return nA.copy(eA)},this.setScissor=function(nA,vA,KA,WA){nA.isVector4?eA.set(nA.x,nA.y,nA.z,nA.w):eA.set(nA,vA,KA,WA),iA.scissor(_.copy(eA).multiplyScalar(x).round())},this.getScissorTest=function(){return aA},this.setScissorTest=function(nA){iA.setScissorTest(aA=nA)},this.setOpaqueSort=function(nA){T=nA},this.setTransparentSort=function(nA){z=nA},this.getClearColor=function(nA){return nA.copy(le.getClearColor())},this.setClearColor=function(){le.setClearColor(...arguments)},this.getClearAlpha=function(){return le.getClearAlpha()},this.setClearAlpha=function(){le.setClearAlpha(...arguments)},this.clear=function(nA=!0,vA=!0,KA=!0){let WA=0;if(nA){let bA=!1;if(G!==null){const pe=G.texture.format;bA=pe===Tx||pe===xx||pe===gG}if(bA){const pe=G.texture.type,xe=pe===Ic||pe===IQ||pe===xS||pe===TS||pe===_x||pe===Jx,it=le.getClearColor(),ve=le.getClearAlpha(),re=it.r,Qe=it.g,HA=it.b;xe?(Q[0]=re,Q[1]=Qe,Q[2]=HA,Q[3]=ve,L.clearBufferuiv(L.COLOR,0,Q)):(h[0]=re,h[1]=Qe,h[2]=HA,h[3]=ve,L.clearBufferiv(L.COLOR,0,h))}else WA|=L.COLOR_BUFFER_BIT}vA&&(WA|=L.DEPTH_BUFFER_BIT),KA&&(WA|=L.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),L.clear(WA)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",BA,!1),t.removeEventListener("webglcontextrestored",j,!1),t.removeEventListener("webglcontextcreationerror",QA,!1),le.dispose(),YA.dispose(),jA.dispose(),IA.dispose(),_A.dispose(),uA.dispose(),cA.dispose(),FA.dispose(),Ie.dispose(),wA.dispose(),rA.dispose(),rA.removeEventListener("sessionstart",$e),rA.removeEventListener("sessionend",ci),ke.stop()};function BA(nA){nA.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),S=!0}function j(){console.log("THREE.WebGLRenderer: Context Restored."),S=!1;const nA=oA.autoReset,vA=he.enabled,KA=he.autoUpdate,WA=he.needsUpdate,bA=he.type;DA(),oA.autoReset=nA,he.enabled=vA,he.autoUpdate=KA,he.needsUpdate=WA,he.type=bA}function QA(nA){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",nA.statusMessage)}function dA(nA){const vA=nA.target;vA.removeEventListener("dispose",dA),UA(vA)}function UA(nA){TA(nA),IA.remove(nA)}function TA(nA){const vA=IA.get(nA).programs;vA!==void 0&&(vA.forEach(function(KA){wA.releaseProgram(KA)}),nA.isShaderMaterial&&wA.releaseShaderCache(nA))}this.renderBufferDirect=function(nA,vA,KA,WA,bA,pe){vA===null&&(vA=qA);const xe=bA.isMesh&&bA.matrixWorld.determinant()<0,it=Xe(nA,vA,KA,WA,bA);iA.setMaterial(WA,xe);let ve=KA.index,re=1;if(WA.wireframe===!0){if(ve=O.getWireframeAttribute(KA),ve===void 0)return;re=2}const Qe=KA.drawRange,HA=KA.attributes.position;let ge=Qe.start*re,ye=(Qe.start+Qe.count)*re;pe!==null&&(ge=Math.max(ge,pe.start*re),ye=Math.min(ye,(pe.start+pe.count)*re)),ve!==null?(ge=Math.max(ge,0),ye=Math.min(ye,ve.count)):HA!=null&&(ge=Math.max(ge,0),ye=Math.min(ye,HA.count));const Te=ye-ge;if(Te<0||Te===1/0)return;FA.setup(bA,WA,it,KA,ve);let gt,Qt=EA;if(ve!==null&&(gt=X.get(ve),Qt=PA,Qt.setIndex(gt)),bA.isMesh)WA.wireframe===!0?(iA.setLineWidth(WA.wireframeLinewidth*$()),Qt.setMode(L.LINES)):Qt.setMode(L.TRIANGLES);else if(bA.isLine){let _e=WA.linewidth;_e===void 0&&(_e=1),iA.setLineWidth(_e*$()),bA.isLineSegments?Qt.setMode(L.LINES):bA.isLineLoop?Qt.setMode(L.LINE_LOOP):Qt.setMode(L.LINE_STRIP)}else bA.isPoints?Qt.setMode(L.POINTS):bA.isSprite&&Qt.setMode(L.TRIANGLES);if(bA.isBatchedMesh)if(bA._multiDrawInstances!==null)KN("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Qt.renderMultiDrawInstances(bA._multiDrawStarts,bA._multiDrawCounts,bA._multiDrawCount,bA._multiDrawInstances);else if(P.get("WEBGL_multi_draw"))Qt.renderMultiDraw(bA._multiDrawStarts,bA._multiDrawCounts,bA._multiDrawCount);else{const _e=bA._multiDrawStarts,Ze=bA._multiDrawCounts,at=bA._multiDrawCount,Ai=ve?X.get(ve).bytesPerElement:1,Bi=IA.get(WA).currentProgram.getUniforms();for(let yi=0;yi<at;yi++)Bi.setValue(L,"_gl_DrawID",yi),Qt.render(_e[yi]/Ai,Ze[yi])}else if(bA.isInstancedMesh)Qt.renderInstances(ge,Te,bA.count);else if(KA.isInstancedBufferGeometry){const _e=KA._maxInstanceCount!==void 0?KA._maxInstanceCount:1/0,Ze=Math.min(KA.instanceCount,_e);Qt.renderInstances(ge,Te,Ze)}else Qt.render(ge,Te)};function oe(nA,vA,KA){nA.transparent===!0&&nA.side===AI&&nA.forceSinglePass===!1?(nA.side=Ua,nA.needsUpdate=!0,Jt(nA,vA,KA),nA.side=tl,nA.needsUpdate=!0,Jt(nA,vA,KA),nA.side=AI):Jt(nA,vA,KA)}this.compile=function(nA,vA,KA=null){KA===null&&(KA=nA),p=jA.get(KA),p.init(vA),m.push(p),KA.traverseVisible(function(bA){bA.isLight&&bA.layers.test(vA.layers)&&(p.pushLight(bA),bA.castShadow&&p.pushShadow(bA))}),nA!==KA&&nA.traverseVisible(function(bA){bA.isLight&&bA.layers.test(vA.layers)&&(p.pushLight(bA),bA.castShadow&&p.pushShadow(bA))}),p.setupLights();const WA=new Set;return nA.traverse(function(bA){if(!(bA.isMesh||bA.isPoints||bA.isLine||bA.isSprite))return;const pe=bA.material;if(pe)if(Array.isArray(pe))for(let xe=0;xe<pe.length;xe++){const it=pe[xe];oe(it,KA,bA),WA.add(it)}else oe(pe,KA,bA),WA.add(pe)}),p=m.pop(),WA},this.compileAsync=function(nA,vA,KA=null){const WA=this.compile(nA,vA,KA);return new Promise(bA=>{function pe(){if(WA.forEach(function(xe){IA.get(xe).currentProgram.isReady()&&WA.delete(xe)}),WA.size===0){bA(nA);return}setTimeout(pe,10)}P.get("KHR_parallel_shader_compile")!==null?pe():setTimeout(pe,10)})};let me=null;function be(nA){me&&me(nA)}function $e(){ke.stop()}function ci(){ke.start()}const ke=new PyA;ke.setAnimationLoop(be),typeof self<"u"&&ke.setContext(self),this.setAnimationLoop=function(nA){me=nA,rA.setAnimationLoop(nA),nA===null?ke.stop():ke.start()},rA.addEventListener("sessionstart",$e),rA.addEventListener("sessionend",ci),this.render=function(nA,vA){if(vA!==void 0&&vA.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(S===!0)return;if(nA.matrixWorldAutoUpdate===!0&&nA.updateMatrixWorld(),vA.parent===null&&vA.matrixWorldAutoUpdate===!0&&vA.updateMatrixWorld(),rA.enabled===!0&&rA.isPresenting===!0&&(rA.cameraAutoUpdate===!0&&rA.updateCamera(vA),vA=rA.getCamera()),nA.isScene===!0&&nA.onBeforeRender(D,nA,vA,G),p=jA.get(nA,m.length),p.init(vA),m.push(p),yA.multiplyMatrices(vA.projectionMatrix,vA.matrixWorldInverse),sA.setFromProjectionMatrix(yA,jI,vA.reversedDepth),gA=this.localClippingEnabled,pA=ie.init(this.clippingPlanes,gA),d=YA.get(nA,y.length),d.init(),y.push(d),rA.enabled===!0&&rA.isPresenting===!0){const pe=D.xr.getDepthSensingMesh();pe!==null&&nt(pe,vA,-1/0,D.sortObjects)}nt(nA,vA,0,D.sortObjects),d.finish(),D.sortObjects===!0&&d.sort(T,z),W=rA.enabled===!1||rA.isPresenting===!1||rA.hasDepthSensing()===!1,W&&le.addToRenderList(d,nA),this.info.render.frame++,pA===!0&&ie.beginShadows();const KA=p.state.shadowsArray;he.render(KA,nA,vA),pA===!0&&ie.endShadows(),this.info.autoReset===!0&&this.info.reset();const WA=d.opaque,bA=d.transmissive;if(p.setupLights(),vA.isArrayCamera){const pe=vA.cameras;if(bA.length>0)for(let xe=0,it=pe.length;xe<it;xe++){const ve=pe[xe];dt(WA,bA,nA,ve)}W&&le.render(nA);for(let xe=0,it=pe.length;xe<it;xe++){const ve=pe[xe];Ut(d,nA,ve,ve.viewport)}}else bA.length>0&&dt(WA,bA,nA,vA),W&&le.render(nA),Ut(d,nA,vA);G!==null&&N===0&&(CA.updateMultisampleRenderTarget(G),CA.updateRenderTargetMipmap(G)),nA.isScene===!0&&nA.onAfterRender(D,nA,vA),FA.resetDefaultState(),M=-1,w=null,m.pop(),m.length>0?(p=m[m.length-1],pA===!0&&ie.setGlobalState(D.clippingPlanes,p.state.camera)):p=null,y.pop(),y.length>0?d=y[y.length-1]:d=null};function nt(nA,vA,KA,WA){if(nA.visible===!1)return;if(nA.layers.test(vA.layers)){if(nA.isGroup)KA=nA.renderOrder;else if(nA.isLOD)nA.autoUpdate===!0&&nA.update(vA);else if(nA.isLight)p.pushLight(nA),nA.castShadow&&p.pushShadow(nA);else if(nA.isSprite){if(!nA.frustumCulled||sA.intersectsSprite(nA)){WA&&RA.setFromMatrixPosition(nA.matrixWorld).applyMatrix4(yA);const xe=cA.update(nA),it=nA.material;it.visible&&d.push(nA,xe,it,KA,RA.z,null)}}else if((nA.isMesh||nA.isLine||nA.isPoints)&&(!nA.frustumCulled||sA.intersectsObject(nA))){const xe=cA.update(nA),it=nA.material;if(WA&&(nA.boundingSphere!==void 0?(nA.boundingSphere===null&&nA.computeBoundingSphere(),RA.copy(nA.boundingSphere.center)):(xe.boundingSphere===null&&xe.computeBoundingSphere(),RA.copy(xe.boundingSphere.center)),RA.applyMatrix4(nA.matrixWorld).applyMatrix4(yA)),Array.isArray(it)){const ve=xe.groups;for(let re=0,Qe=ve.length;re<Qe;re++){const HA=ve[re],ge=it[HA.materialIndex];ge&&ge.visible&&d.push(nA,xe,ge,KA,RA.z,HA)}}else it.visible&&d.push(nA,xe,it,KA,RA.z,null)}}const pe=nA.children;for(let xe=0,it=pe.length;xe<it;xe++)nt(pe[xe],vA,KA,WA)}function Ut(nA,vA,KA,WA){const bA=nA.opaque,pe=nA.transmissive,xe=nA.transparent;p.setupLightsView(KA),pA===!0&&ie.setGlobalState(D.clippingPlanes,KA),WA&&iA.viewport(b.copy(WA)),bA.length>0&&Ht(bA,vA,KA),pe.length>0&&Ht(pe,vA,KA),xe.length>0&&Ht(xe,vA,KA),iA.buffers.depth.setTest(!0),iA.buffers.depth.setMask(!0),iA.buffers.color.setMask(!0),iA.setPolygonOffset(!1)}function dt(nA,vA,KA,WA){if((KA.isScene===!0?KA.overrideMaterial:null)!==null)return;p.state.transmissionRenderTarget[WA.id]===void 0&&(p.state.transmissionRenderTarget[WA.id]=new il(1,1,{generateMipmaps:!0,type:P.has("EXT_color_buffer_half_float")||P.has("EXT_color_buffer_float")?ny:Ic,minFilter:Gr,samples:4,stencilBuffer:g,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Un.workingColorSpace}));const pe=p.state.transmissionRenderTarget[WA.id],xe=WA.viewport||b;pe.setSize(xe.z*D.transmissionResolutionScale,xe.w*D.transmissionResolutionScale);const it=D.getRenderTarget(),ve=D.getActiveCubeFace(),re=D.getActiveMipmapLevel();D.setRenderTarget(pe),D.getClearColor(J),q=D.getClearAlpha(),q<1&&D.setClearColor(16777215,.5),D.clear(),W&&le.render(KA);const Qe=D.toneMapping;D.toneMapping=QB;const HA=WA.viewport;if(WA.viewport!==void 0&&(WA.viewport=void 0),p.setupLightsView(WA),pA===!0&&ie.setGlobalState(D.clippingPlanes,WA),Ht(nA,KA,WA),CA.updateMultisampleRenderTarget(pe),CA.updateRenderTargetMipmap(pe),P.has("WEBGL_multisampled_render_to_texture")===!1){let ge=!1;for(let ye=0,Te=vA.length;ye<Te;ye++){const gt=vA[ye],Qt=gt.object,_e=gt.geometry,Ze=gt.material,at=gt.group;if(Ze.side===AI&&Qt.layers.test(WA.layers)){const Ai=Ze.side;Ze.side=Ua,Ze.needsUpdate=!0,Ft(Qt,KA,WA,_e,Ze,at),Ze.side=Ai,Ze.needsUpdate=!0,ge=!0}}ge===!0&&(CA.updateMultisampleRenderTarget(pe),CA.updateRenderTargetMipmap(pe))}D.setRenderTarget(it,ve,re),D.setClearColor(J,q),HA!==void 0&&(WA.viewport=HA),D.toneMapping=Qe}function Ht(nA,vA,KA){const WA=vA.isScene===!0?vA.overrideMaterial:null;for(let bA=0,pe=nA.length;bA<pe;bA++){const xe=nA[bA],it=xe.object,ve=xe.geometry,re=xe.group;let Qe=xe.material;Qe.allowOverride===!0&&WA!==null&&(Qe=WA),it.layers.test(KA.layers)&&Ft(it,vA,KA,ve,Qe,re)}}function Ft(nA,vA,KA,WA,bA,pe){nA.onBeforeRender(D,vA,KA,WA,bA,pe),nA.modelViewMatrix.multiplyMatrices(KA.matrixWorldInverse,nA.matrixWorld),nA.normalMatrix.getNormalMatrix(nA.modelViewMatrix),bA.onBeforeRender(D,vA,KA,WA,nA,pe),bA.transparent===!0&&bA.side===AI&&bA.forceSinglePass===!1?(bA.side=Ua,bA.needsUpdate=!0,D.renderBufferDirect(KA,vA,WA,bA,nA,pe),bA.side=tl,bA.needsUpdate=!0,D.renderBufferDirect(KA,vA,WA,bA,nA,pe),bA.side=AI):D.renderBufferDirect(KA,vA,WA,bA,nA,pe),nA.onAfterRender(D,vA,KA,WA,bA,pe)}function Jt(nA,vA,KA){vA.isScene!==!0&&(vA=qA);const WA=IA.get(nA),bA=p.state.lights,pe=p.state.shadowsArray,xe=bA.state.version,it=wA.getParameters(nA,bA.state,pe,vA,KA),ve=wA.getProgramCacheKey(it);let re=WA.programs;WA.environment=nA.isMeshStandardMaterial?vA.environment:null,WA.fog=vA.fog,WA.envMap=(nA.isMeshStandardMaterial?uA:_A).get(nA.envMap||WA.environment),WA.envMapRotation=WA.environment!==null&&nA.envMap===null?vA.environmentRotation:nA.envMapRotation,re===void 0&&(nA.addEventListener("dispose",dA),re=new Map,WA.programs=re);let Qe=re.get(ve);if(Qe!==void 0){if(WA.currentProgram===Qe&&WA.lightsStateVersion===xe)return He(nA,it),Qe}else it.uniforms=wA.getUniforms(nA),nA.onBeforeCompile(it,D),Qe=wA.acquireProgram(it,ve),re.set(ve,Qe),WA.uniforms=it.uniforms;const HA=WA.uniforms;return(!nA.isShaderMaterial&&!nA.isRawShaderMaterial||nA.clipping===!0)&&(HA.clippingPlanes=ie.uniform),He(nA,it),WA.needsLights=kA(nA),WA.lightsStateVersion=xe,WA.needsLights&&(HA.ambientLightColor.value=bA.state.ambient,HA.lightProbe.value=bA.state.probe,HA.directionalLights.value=bA.state.directional,HA.directionalLightShadows.value=bA.state.directionalShadow,HA.spotLights.value=bA.state.spot,HA.spotLightShadows.value=bA.state.spotShadow,HA.rectAreaLights.value=bA.state.rectArea,HA.ltc_1.value=bA.state.rectAreaLTC1,HA.ltc_2.value=bA.state.rectAreaLTC2,HA.pointLights.value=bA.state.point,HA.pointLightShadows.value=bA.state.pointShadow,HA.hemisphereLights.value=bA.state.hemi,HA.directionalShadowMap.value=bA.state.directionalShadowMap,HA.directionalShadowMatrix.value=bA.state.directionalShadowMatrix,HA.spotShadowMap.value=bA.state.spotShadowMap,HA.spotLightMatrix.value=bA.state.spotLightMatrix,HA.spotLightMap.value=bA.state.spotLightMap,HA.pointShadowMap.value=bA.state.pointShadowMap,HA.pointShadowMatrix.value=bA.state.pointShadowMatrix),WA.currentProgram=Qe,WA.uniformsList=null,Qe}function $A(nA){if(nA.uniformsList===null){const vA=nA.currentProgram.getUniforms();nA.uniformsList=KK.seqWithValue(vA.seq,nA.uniforms)}return nA.uniformsList}function He(nA,vA){const KA=IA.get(nA);KA.outputColorSpace=vA.outputColorSpace,KA.batching=vA.batching,KA.batchingColor=vA.batchingColor,KA.instancing=vA.instancing,KA.instancingColor=vA.instancingColor,KA.instancingMorph=vA.instancingMorph,KA.skinning=vA.skinning,KA.morphTargets=vA.morphTargets,KA.morphNormals=vA.morphNormals,KA.morphColors=vA.morphColors,KA.morphTargetsCount=vA.morphTargetsCount,KA.numClippingPlanes=vA.numClippingPlanes,KA.numIntersection=vA.numClipIntersection,KA.vertexAlphas=vA.vertexAlphas,KA.vertexTangents=vA.vertexTangents,KA.toneMapping=vA.toneMapping}function Xe(nA,vA,KA,WA,bA){vA.isScene!==!0&&(vA=qA),CA.resetTextureUnits();const pe=vA.fog,xe=WA.isMeshStandardMaterial?vA.environment:null,it=G===null?D.outputColorSpace:G.isXRRenderTarget===!0?G.texture.colorSpace:Ka,ve=(WA.isMeshStandardMaterial?uA:_A).get(WA.envMap||xe),re=WA.vertexColors===!0&&!!KA.attributes.color&&KA.attributes.color.itemSize===4,Qe=!!KA.attributes.tangent&&(!!WA.normalMap||WA.anisotropy>0),HA=!!KA.morphAttributes.position,ge=!!KA.morphAttributes.normal,ye=!!KA.morphAttributes.color;let Te=QB;WA.toneMapped&&(G===null||G.isXRRenderTarget===!0)&&(Te=D.toneMapping);const gt=KA.morphAttributes.position||KA.morphAttributes.normal||KA.morphAttributes.color,Qt=gt!==void 0?gt.length:0,_e=IA.get(WA),Ze=p.state.lights;if(pA===!0&&(gA===!0||nA!==w)){const si=nA===w&&WA.id===M;ie.setState(WA,nA,si)}let at=!1;WA.version===_e.__version?(_e.needsLights&&_e.lightsStateVersion!==Ze.state.version||_e.outputColorSpace!==it||bA.isBatchedMesh&&_e.batching===!1||!bA.isBatchedMesh&&_e.batching===!0||bA.isBatchedMesh&&_e.batchingColor===!0&&bA.colorTexture===null||bA.isBatchedMesh&&_e.batchingColor===!1&&bA.colorTexture!==null||bA.isInstancedMesh&&_e.instancing===!1||!bA.isInstancedMesh&&_e.instancing===!0||bA.isSkinnedMesh&&_e.skinning===!1||!bA.isSkinnedMesh&&_e.skinning===!0||bA.isInstancedMesh&&_e.instancingColor===!0&&bA.instanceColor===null||bA.isInstancedMesh&&_e.instancingColor===!1&&bA.instanceColor!==null||bA.isInstancedMesh&&_e.instancingMorph===!0&&bA.morphTexture===null||bA.isInstancedMesh&&_e.instancingMorph===!1&&bA.morphTexture!==null||_e.envMap!==ve||WA.fog===!0&&_e.fog!==pe||_e.numClippingPlanes!==void 0&&(_e.numClippingPlanes!==ie.numPlanes||_e.numIntersection!==ie.numIntersection)||_e.vertexAlphas!==re||_e.vertexTangents!==Qe||_e.morphTargets!==HA||_e.morphNormals!==ge||_e.morphColors!==ye||_e.toneMapping!==Te||_e.morphTargetsCount!==Qt)&&(at=!0):(at=!0,_e.__version=WA.version);let Ai=_e.currentProgram;at===!0&&(Ai=Jt(WA,vA,bA));let Bi=!1,yi=!1,mt=!1;const ct=Ai.getUniforms(),fi=_e.uniforms;if(iA.useProgram(Ai.program)&&(Bi=!0,yi=!0,mt=!0),WA.id!==M&&(M=WA.id,yi=!0),Bi||w!==nA){iA.buffers.depth.getReversed()&&nA.reversedDepth!==!0&&(nA._reversedDepth=!0,nA.updateProjectionMatrix()),ct.setValue(L,"projectionMatrix",nA.projectionMatrix),ct.setValue(L,"viewMatrix",nA.matrixWorldInverse);const jt=ct.map.cameraPosition;jt!==void 0&&jt.setValue(L,fA.setFromMatrixPosition(nA.matrixWorld)),tA.logarithmicDepthBuffer&&ct.setValue(L,"logDepthBufFC",2/(Math.log(nA.far+1)/Math.LN2)),(WA.isMeshPhongMaterial||WA.isMeshToonMaterial||WA.isMeshLambertMaterial||WA.isMeshBasicMaterial||WA.isMeshStandardMaterial||WA.isShaderMaterial)&&ct.setValue(L,"isOrthographic",nA.isOrthographicCamera===!0),w!==nA&&(w=nA,yi=!0,mt=!0)}if(bA.isSkinnedMesh){ct.setOptional(L,bA,"bindMatrix"),ct.setOptional(L,bA,"bindMatrixInverse");const si=bA.skeleton;si&&(si.boneTexture===null&&si.computeBoneTexture(),ct.setValue(L,"boneTexture",si.boneTexture,CA))}bA.isBatchedMesh&&(ct.setOptional(L,bA,"batchingTexture"),ct.setValue(L,"batchingTexture",bA._matricesTexture,CA),ct.setOptional(L,bA,"batchingIdTexture"),ct.setValue(L,"batchingIdTexture",bA._indirectTexture,CA),ct.setOptional(L,bA,"batchingColorTexture"),bA._colorsTexture!==null&&ct.setValue(L,"batchingColorTexture",bA._colorsTexture,CA));const Yi=KA.morphAttributes;if((Yi.position!==void 0||Yi.normal!==void 0||Yi.color!==void 0)&&NA.update(bA,KA,Ai),(yi||_e.receiveShadow!==bA.receiveShadow)&&(_e.receiveShadow=bA.receiveShadow,ct.setValue(L,"receiveShadow",bA.receiveShadow)),WA.isMeshGouraudMaterial&&WA.envMap!==null&&(fi.envMap.value=ve,fi.flipEnvMap.value=ve.isCubeTexture&&ve.isRenderTargetTexture===!1?-1:1),WA.isMeshStandardMaterial&&WA.envMap===null&&vA.environment!==null&&(fi.envMapIntensity.value=vA.environmentIntensity),yi&&(ct.setValue(L,"toneMappingExposure",D.toneMappingExposure),_e.needsLights&&St(fi,mt),pe&&WA.fog===!0&&xA.refreshFogUniforms(fi,pe),xA.refreshMaterialUniforms(fi,WA,x,U,p.state.transmissionRenderTarget[nA.id]),KK.upload(L,$A(_e),fi,CA)),WA.isShaderMaterial&&WA.uniformsNeedUpdate===!0&&(KK.upload(L,$A(_e),fi,CA),WA.uniformsNeedUpdate=!1),WA.isSpriteMaterial&&ct.setValue(L,"center",bA.center),ct.setValue(L,"modelViewMatrix",bA.modelViewMatrix),ct.setValue(L,"normalMatrix",bA.normalMatrix),ct.setValue(L,"modelMatrix",bA.matrixWorld),WA.isShaderMaterial||WA.isRawShaderMaterial){const si=WA.uniformsGroups;for(let jt=0,Zt=si.length;jt<Zt;jt++){const vi=si[jt];Ie.update(vi,Ai),Ie.bind(vi,Ai)}}return Ai}function St(nA,vA){nA.ambientLightColor.needsUpdate=vA,nA.lightProbe.needsUpdate=vA,nA.directionalLights.needsUpdate=vA,nA.directionalLightShadows.needsUpdate=vA,nA.pointLights.needsUpdate=vA,nA.pointLightShadows.needsUpdate=vA,nA.spotLights.needsUpdate=vA,nA.spotLightShadows.needsUpdate=vA,nA.rectAreaLights.needsUpdate=vA,nA.hemisphereLights.needsUpdate=vA}function kA(nA){return nA.isMeshLambertMaterial||nA.isMeshToonMaterial||nA.isMeshPhongMaterial||nA.isMeshStandardMaterial||nA.isShadowMaterial||nA.isShaderMaterial&&nA.lights===!0}this.getActiveCubeFace=function(){return k},this.getActiveMipmapLevel=function(){return N},this.getRenderTarget=function(){return G},this.setRenderTargetTextures=function(nA,vA,KA){const WA=IA.get(nA);WA.__autoAllocateDepthBuffer=nA.resolveDepthBuffer===!1,WA.__autoAllocateDepthBuffer===!1&&(WA.__useRenderToTexture=!1),IA.get(nA.texture).__webglTexture=vA,IA.get(nA.depthTexture).__webglTexture=WA.__autoAllocateDepthBuffer?void 0:KA,WA.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(nA,vA){const KA=IA.get(nA);KA.__webglFramebuffer=vA,KA.__useDefaultFramebuffer=vA===void 0};const se=L.createFramebuffer();this.setRenderTarget=function(nA,vA=0,KA=0){G=nA,k=vA,N=KA;let WA=!0,bA=null,pe=!1,xe=!1;if(nA){const ve=IA.get(nA);if(ve.__useDefaultFramebuffer!==void 0)iA.bindFramebuffer(L.FRAMEBUFFER,null),WA=!1;else if(ve.__webglFramebuffer===void 0)CA.setupRenderTarget(nA);else if(ve.__hasExternalTextures)CA.rebindTextures(nA,IA.get(nA.texture).__webglTexture,IA.get(nA.depthTexture).__webglTexture);else if(nA.depthBuffer){const HA=nA.depthTexture;if(ve.__boundDepthTexture!==HA){if(HA!==null&&IA.has(HA)&&(nA.width!==HA.image.width||nA.height!==HA.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");CA.setupDepthRenderbuffer(nA)}}const re=nA.texture;(re.isData3DTexture||re.isDataArrayTexture||re.isCompressedArrayTexture)&&(xe=!0);const Qe=IA.get(nA).__webglFramebuffer;nA.isWebGLCubeRenderTarget?(Array.isArray(Qe[vA])?bA=Qe[vA][KA]:bA=Qe[vA],pe=!0):nA.samples>0&&CA.useMultisampledRTT(nA)===!1?bA=IA.get(nA).__webglMultisampledFramebuffer:Array.isArray(Qe)?bA=Qe[KA]:bA=Qe,b.copy(nA.viewport),_.copy(nA.scissor),K=nA.scissorTest}else b.copy(Z).multiplyScalar(x).floor(),_.copy(eA).multiplyScalar(x).floor(),K=aA;if(KA!==0&&(bA=se),iA.bindFramebuffer(L.FRAMEBUFFER,bA)&&WA&&iA.drawBuffers(nA,bA),iA.viewport(b),iA.scissor(_),iA.setScissorTest(K),pe){const ve=IA.get(nA.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+vA,ve.__webglTexture,KA)}else if(xe){const ve=vA;for(let re=0;re<nA.textures.length;re++){const Qe=IA.get(nA.textures[re]);L.framebufferTextureLayer(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0+re,Qe.__webglTexture,KA,ve)}}else if(nA!==null&&KA!==0){const ve=IA.get(nA.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,ve.__webglTexture,KA)}M=-1},this.readRenderTargetPixels=function(nA,vA,KA,WA,bA,pe,xe,it=0){if(!(nA&&nA.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let ve=IA.get(nA).__webglFramebuffer;if(nA.isWebGLCubeRenderTarget&&xe!==void 0&&(ve=ve[xe]),ve){iA.bindFramebuffer(L.FRAMEBUFFER,ve);try{const re=nA.textures[it],Qe=re.format,HA=re.type;if(!tA.textureFormatReadable(Qe)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!tA.textureTypeReadable(HA)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}vA>=0&&vA<=nA.width-WA&&KA>=0&&KA<=nA.height-bA&&(nA.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+it),L.readPixels(vA,KA,WA,bA,ZA.convert(Qe),ZA.convert(HA),pe))}finally{const re=G!==null?IA.get(G).__webglFramebuffer:null;iA.bindFramebuffer(L.FRAMEBUFFER,re)}}},this.readRenderTargetPixelsAsync=async function(nA,vA,KA,WA,bA,pe,xe,it=0){if(!(nA&&nA.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let ve=IA.get(nA).__webglFramebuffer;if(nA.isWebGLCubeRenderTarget&&xe!==void 0&&(ve=ve[xe]),ve)if(vA>=0&&vA<=nA.width-WA&&KA>=0&&KA<=nA.height-bA){iA.bindFramebuffer(L.FRAMEBUFFER,ve);const re=nA.textures[it],Qe=re.format,HA=re.type;if(!tA.textureFormatReadable(Qe))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!tA.textureTypeReadable(HA))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const ge=L.createBuffer();L.bindBuffer(L.PIXEL_PACK_BUFFER,ge),L.bufferData(L.PIXEL_PACK_BUFFER,pe.byteLength,L.STREAM_READ),nA.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+it),L.readPixels(vA,KA,WA,bA,ZA.convert(Qe),ZA.convert(HA),0);const ye=G!==null?IA.get(G).__webglFramebuffer:null;iA.bindFramebuffer(L.FRAMEBUFFER,ye);const Te=L.fenceSync(L.SYNC_GPU_COMMANDS_COMPLETE,0);return L.flush(),await wae(L,Te,4),L.bindBuffer(L.PIXEL_PACK_BUFFER,ge),L.getBufferSubData(L.PIXEL_PACK_BUFFER,0,pe),L.deleteBuffer(ge),L.deleteSync(Te),pe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(nA,vA=null,KA=0){const WA=Math.pow(2,-KA),bA=Math.floor(nA.image.width*WA),pe=Math.floor(nA.image.height*WA),xe=vA!==null?vA.x:0,it=vA!==null?vA.y:0;CA.setTexture2D(nA,0),L.copyTexSubImage2D(L.TEXTURE_2D,KA,0,0,xe,it,bA,pe),iA.unbindTexture()};const Ce=L.createFramebuffer(),VA=L.createFramebuffer();this.copyTextureToTexture=function(nA,vA,KA=null,WA=null,bA=0,pe=null){pe===null&&(bA!==0?(KN("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),pe=bA,bA=0):pe=0);let xe,it,ve,re,Qe,HA,ge,ye,Te;const gt=nA.isCompressedTexture?nA.mipmaps[pe]:nA.image;if(KA!==null)xe=KA.max.x-KA.min.x,it=KA.max.y-KA.min.y,ve=KA.isBox3?KA.max.z-KA.min.z:1,re=KA.min.x,Qe=KA.min.y,HA=KA.isBox3?KA.min.z:0;else{const Yi=Math.pow(2,-bA);xe=Math.floor(gt.width*Yi),it=Math.floor(gt.height*Yi),nA.isDataArrayTexture?ve=gt.depth:nA.isData3DTexture?ve=Math.floor(gt.depth*Yi):ve=1,re=0,Qe=0,HA=0}WA!==null?(ge=WA.x,ye=WA.y,Te=WA.z):(ge=0,ye=0,Te=0);const Qt=ZA.convert(vA.format),_e=ZA.convert(vA.type);let Ze;vA.isData3DTexture?(CA.setTexture3D(vA,0),Ze=L.TEXTURE_3D):vA.isDataArrayTexture||vA.isCompressedArrayTexture?(CA.setTexture2DArray(vA,0),Ze=L.TEXTURE_2D_ARRAY):(CA.setTexture2D(vA,0),Ze=L.TEXTURE_2D),L.pixelStorei(L.UNPACK_FLIP_Y_WEBGL,vA.flipY),L.pixelStorei(L.UNPACK_PREMULTIPLY_ALPHA_WEBGL,vA.premultiplyAlpha),L.pixelStorei(L.UNPACK_ALIGNMENT,vA.unpackAlignment);const at=L.getParameter(L.UNPACK_ROW_LENGTH),Ai=L.getParameter(L.UNPACK_IMAGE_HEIGHT),Bi=L.getParameter(L.UNPACK_SKIP_PIXELS),yi=L.getParameter(L.UNPACK_SKIP_ROWS),mt=L.getParameter(L.UNPACK_SKIP_IMAGES);L.pixelStorei(L.UNPACK_ROW_LENGTH,gt.width),L.pixelStorei(L.UNPACK_IMAGE_HEIGHT,gt.height),L.pixelStorei(L.UNPACK_SKIP_PIXELS,re),L.pixelStorei(L.UNPACK_SKIP_ROWS,Qe),L.pixelStorei(L.UNPACK_SKIP_IMAGES,HA);const ct=nA.isDataArrayTexture||nA.isData3DTexture,fi=vA.isDataArrayTexture||vA.isData3DTexture;if(nA.isDepthTexture){const Yi=IA.get(nA),si=IA.get(vA),jt=IA.get(Yi.__renderTarget),Zt=IA.get(si.__renderTarget);iA.bindFramebuffer(L.READ_FRAMEBUFFER,jt.__webglFramebuffer),iA.bindFramebuffer(L.DRAW_FRAMEBUFFER,Zt.__webglFramebuffer);for(let vi=0;vi<ve;vi++)ct&&(L.framebufferTextureLayer(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,IA.get(nA).__webglTexture,bA,HA+vi),L.framebufferTextureLayer(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,IA.get(vA).__webglTexture,pe,Te+vi)),L.blitFramebuffer(re,Qe,xe,it,ge,ye,xe,it,L.DEPTH_BUFFER_BIT,L.NEAREST);iA.bindFramebuffer(L.READ_FRAMEBUFFER,null),iA.bindFramebuffer(L.DRAW_FRAMEBUFFER,null)}else if(bA!==0||nA.isRenderTargetTexture||IA.has(nA)){const Yi=IA.get(nA),si=IA.get(vA);iA.bindFramebuffer(L.READ_FRAMEBUFFER,Ce),iA.bindFramebuffer(L.DRAW_FRAMEBUFFER,VA);for(let jt=0;jt<ve;jt++)ct?L.framebufferTextureLayer(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,Yi.__webglTexture,bA,HA+jt):L.framebufferTexture2D(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,Yi.__webglTexture,bA),fi?L.framebufferTextureLayer(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,si.__webglTexture,pe,Te+jt):L.framebufferTexture2D(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,si.__webglTexture,pe),bA!==0?L.blitFramebuffer(re,Qe,xe,it,ge,ye,xe,it,L.COLOR_BUFFER_BIT,L.NEAREST):fi?L.copyTexSubImage3D(Ze,pe,ge,ye,Te+jt,re,Qe,xe,it):L.copyTexSubImage2D(Ze,pe,ge,ye,re,Qe,xe,it);iA.bindFramebuffer(L.READ_FRAMEBUFFER,null),iA.bindFramebuffer(L.DRAW_FRAMEBUFFER,null)}else fi?nA.isDataTexture||nA.isData3DTexture?L.texSubImage3D(Ze,pe,ge,ye,Te,xe,it,ve,Qt,_e,gt.data):vA.isCompressedArrayTexture?L.compressedTexSubImage3D(Ze,pe,ge,ye,Te,xe,it,ve,Qt,gt.data):L.texSubImage3D(Ze,pe,ge,ye,Te,xe,it,ve,Qt,_e,gt):nA.isDataTexture?L.texSubImage2D(L.TEXTURE_2D,pe,ge,ye,xe,it,Qt,_e,gt.data):nA.isCompressedTexture?L.compressedTexSubImage2D(L.TEXTURE_2D,pe,ge,ye,gt.width,gt.height,Qt,gt.data):L.texSubImage2D(L.TEXTURE_2D,pe,ge,ye,xe,it,Qt,_e,gt);L.pixelStorei(L.UNPACK_ROW_LENGTH,at),L.pixelStorei(L.UNPACK_IMAGE_HEIGHT,Ai),L.pixelStorei(L.UNPACK_SKIP_PIXELS,Bi),L.pixelStorei(L.UNPACK_SKIP_ROWS,yi),L.pixelStorei(L.UNPACK_SKIP_IMAGES,mt),pe===0&&vA.generateMipmaps&&L.generateMipmap(Ze),iA.unbindTexture()},this.initRenderTarget=function(nA){IA.get(nA).__webglFramebuffer===void 0&&CA.setupRenderTarget(nA)},this.initTexture=function(nA){nA.isCubeTexture?CA.setTextureCube(nA,0):nA.isData3DTexture?CA.setTexture3D(nA,0):nA.isDataArrayTexture||nA.isCompressedArrayTexture?CA.setTexture2DArray(nA,0):CA.setTexture2D(nA,0),iA.unbindTexture()},this.resetState=function(){k=0,N=0,G=null,iA.reset(),FA.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return jI}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(A){this._outputColorSpace=A;const t=this.getContext();t.drawingBufferColorSpace=Un._getDrawingBufferColorSpace(A),t.unpackColorSpace=Un._getUnpackColorSpace()}}const JEe=Object.freeze(Object.defineProperty({__proto__:null,ACESFilmicToneMapping:iy,AddEquation:ru,AddOperation:FfA,AdditiveAnimationBlendMode:KW,AdditiveBlending:io,AgXToneMapping:TfA,AlphaFormat:GW,AlwaysCompare:AyA,AlwaysDepth:J_,AlwaysStencilFunc:o4,AmbientLight:sV,AnimationAction:YyA,AnimationClip:fd,AnimationLoader:Xre,AnimationMixer:lV,AnimationObjectGroup:DIe,AnimationUtils:zre,ArcCurve:ByA,ArrayCamera:xyA,ArrowHelper:ZIe,AttachedBindMode:g4,Audio:TyA,AudioAnalyser:lIe,AudioContext:rV,AudioListener:IIe,AudioLoader:sIe,AxesHelper:WIe,BackSide:Ua,BasicDepthPacking:OfA,BasicShadowMap:QfA,BatchedMesh:CyA,Bone:IG,BooleanKeyframeTrack:sy,Box2:vIe,Box3:Ag,Box3Helper:jIe,BoxGeometry:sI,BoxHelper:PIe,BufferAttribute:ji,BufferGeometry:Ni,BufferGeometryLoader:LyA,ByteType:kW,Cache:sB,Camera:Ox,CameraHelper:OIe,CanvasTexture:pd,CapsuleGeometry:Xx,CatmullRomCurve3:OW,CineonToneMapping:LfA,CircleGeometry:$x,ClampToEdgeWrapping:oI,Clock:IV,Color:Et,ColorKeyframeTrack:iV,ColorManagement:Un,CompressedArrayTexture:Qre,CompressedCubeTexture:ure,CompressedTexture:Wx,CompressedTextureLoader:$re,ConeGeometry:cG,ConstantAlphaFactor:UfA,ConstantColorFactor:GfA,Controls:XIe,CubeCamera:syA,CubeReflectionMapping:rQ,CubeRefractionMapping:ud,CubeTexture:sG,CubeTextureLoader:AIe,CubeUVReflectionMapping:Kw,CubicBezierCurve:PW,CubicBezierCurve3:EyA,CubicInterpolant:GyA,CullFaceBack:t4,CullFaceFront:EfA,CullFaceFrontBack:Rse,CullFaceNone:BfA,Curve:Cl,CurvePath:uyA,CustomBlending:ufA,CustomToneMapping:xfA,CylinderGeometry:gy,Cylindrical:UIe,Data3DTexture:Hx,DataArrayTexture:Yx,DataTexture:uB,DataTextureLoader:eIe,DataUtils:Tae,DecrementStencilOp:Tse,DecrementWrapStencilOp:Yse,DefaultLoadingManager:vyA,DepthFormat:qS,DepthStencilFormat:YS,DepthTexture:Vx,DetachedBindMode:YfA,DirectionalLight:zp,DirectionalLightHelper:HIe,DiscreteInterpolant:byA,DodecahedronGeometry:AT,DoubleSide:AI,DstAlphaFactor:wfA,DstColorFactor:MfA,DynamicCopyUsage:iae,DynamicDrawUsage:eyA,DynamicReadUsage:Aae,EdgesGeometry:lyA,EllipseCurve:eT,EqualCompare:WfA,EqualDepth:x_,EqualStencilFunc:jse,EquirectangularReflectionMapping:NN,EquirectangularRefractionMapping:RN,Euler:ca,EventDispatcher:bB,ExternalTexture:YW,ExtrudeGeometry:tT,FileLoader:or,Float16BufferAttribute:zae,Float32BufferAttribute:$t,FloatType:br,Fog:aG,FogExp2:Px,FramebufferTexture:Ere,FrontSide:tl,Frustum:Lw,FrustumArray:zx,GLBufferAttribute:NIe,GLSL1:gae,GLSL3:s4,GreaterCompare:VfA,GreaterDepth:q_,GreaterEqualCompare:$fA,GreaterEqualDepth:T_,GreaterEqualStencilFunc:Vse,GreaterStencilFunc:Zse,GridHelper:qIe,Group:sa,HalfFloatType:ny,HemisphereLight:gV,HemisphereLightHelper:TIe,IcosahedronGeometry:iT,ImageBitmapLoader:aV,ImageLoader:xN,ImageUtils:nyA,IncrementStencilOp:xse,IncrementWrapStencilOp:qse,InstancedBufferAttribute:hd,InstancedBufferGeometry:JyA,InstancedInterleavedBuffer:MIe,InstancedMesh:CG,Int16BufferAttribute:Pae,Int32BufferAttribute:jae,Int8BufferAttribute:Yae,IntType:Fx,InterleavedBuffer:_w,InterleavedBufferAttribute:CQ,Interpolant:oy,InterpolateDiscrete:yf,InterpolateLinear:dd,InterpolateSmooth:UK,InterpolationSamplingMode:aae,InterpolationSamplingType:sae,InvertStencilOp:Hse,KeepStencilOp:Xh,KeyframeTrack:Ec,LOD:IyA,LatheGeometry:nT,Layers:PS,LessCompare:ZfA,LessDepth:L_,LessEqualCompare:_W,LessEqualDepth:pf,LessEqualStencilFunc:zse,LessStencilFunc:Pse,Light:Yd,LightProbe:_yA,Line:yB,Line3:_Ie,LineBasicMaterial:es,LineCurve:jW,LineCurve3:QyA,LineDashedMaterial:MyA,LineLoop:Zx,LineSegments:EI,LinearFilter:qg,LinearInterpolant:tV,LinearMipMapLinearFilter:vse,LinearMipMapNearestFilter:Use,LinearMipmapLinearFilter:Gr,LinearMipmapNearestFilter:Hp,LinearSRGBColorSpace:Ka,LinearToneMapping:_fA,LinearTransfer:bN,Loader:la,LoaderUtils:AC,LoadingManager:nV,LoopOnce:vW,LoopPingPong:HfA,LoopRepeat:dJ,MOUSE:Mse,Material:ho,MaterialLoader:cT,MathUtils:VC,Matrix2:QV,Matrix3:An,Matrix4:ni,MaxEquation:ffA,Mesh:pn,MeshBasicMaterial:kg,MeshDepthMaterial:$W,MeshDistanceMaterial:AV,MeshLambertMaterial:XW,MeshMatcapMaterial:kyA,MeshNormalMaterial:wyA,MeshPhongMaterial:VW,MeshPhysicalMaterial:To,MeshStandardMaterial:xg,MeshToonMaterial:SyA,MinEquation:pfA,MirroredRepeatWrapping:ff,MixOperation:KfA,MultiplyBlending:n4,MultiplyOperation:iG,NearestFilter:Ss,NearestMipMapLinearFilter:bse,NearestMipMapNearestFilter:Gse,NearestMipmapLinearFilter:Nu,NearestMipmapNearestFilter:nG,NeutralToneMapping:qfA,NeverCompare:zfA,NeverDepth:__,NeverStencilFunc:Ose,NoBlending:TE,NoColorSpace:DE,NoToneMapping:QB,NormalAnimationBlendMode:qx,NormalBlending:Yp,NotEqualCompare:XfA,NotEqualDepth:Y_,NotEqualStencilFunc:Wse,NumberKeyframeTrack:cQ,Object3D:Bn,ObjectLoader:gIe,ObjectSpaceNormalMap:jfA,OctahedronGeometry:lG,OneFactor:DfA,OneMinusConstantAlphaFactor:vfA,OneMinusConstantColorFactor:bfA,OneMinusDstAlphaFactor:kfA,OneMinusDstColorFactor:NfA,OneMinusSrcAlphaFactor:F_,OneMinusSrcColorFactor:SfA,OrthographicCamera:Hd,PCFShadowMap:vx,PCFSoftShadowMap:yM,PMREMGenerator:mJ,Path:DJ,PerspectiveCamera:Wo,Plane:eu,PlaneGeometry:oB,PlaneHelper:zIe,PointLight:BG,PointLightHelper:LIe,Points:Pp,PointsMaterial:NE,PolarGridHelper:YIe,PolyhedronGeometry:Td,PositionalAudio:cIe,PropertyBinding:zn,PropertyMixer:qyA,QuadraticBezierCurve:zW,QuadraticBezierCurve3:ZW,Quaternion:oo,QuaternionKeyframeTrack:DB,QuaternionLinearInterpolant:UyA,RED_GREEN_RGTC2_Format:QJ,RED_RGTC1_Format:BJ,REVISION:tG,RGBADepthPacking:PfA,RGBAFormat:Ar,RGBAIntegerFormat:Tx,RGBA_ASTC_10x10_Format:aJ,RGBA_ASTC_10x5_Format:gJ,RGBA_ASTC_10x6_Format:oJ,RGBA_ASTC_10x8_Format:sJ,RGBA_ASTC_12x10_Format:rJ,RGBA_ASTC_12x12_Format:IJ,RGBA_ASTC_4x4_Format:V_,RGBA_ASTC_5x4_Format:X_,RGBA_ASTC_5x5_Format:$_,RGBA_ASTC_6x5_Format:AJ,RGBA_ASTC_6x6_Format:eJ,RGBA_ASTC_8x5_Format:tJ,RGBA_ASTC_8x6_Format:iJ,RGBA_ASTC_8x8_Format:nJ,RGBA_BPTC_Format:CJ,RGBA_ETC2_EAC_Format:W_,RGBA_PVRTC_2BPPV1_Format:j_,RGBA_PVRTC_4BPPV1_Format:P_,RGBA_S3TC_DXT1_Format:mM,RGBA_S3TC_DXT3_Format:SM,RGBA_S3TC_DXT5_Format:wM,RGBDepthPacking:Fse,RGBFormat:bW,RGBIntegerFormat:Kse,RGB_BPTC_SIGNED_Format:cJ,RGB_BPTC_UNSIGNED_Format:lJ,RGB_ETC1_Format:z_,RGB_ETC2_Format:Z_,RGB_PVRTC_2BPPV1_Format:O_,RGB_PVRTC_4BPPV1_Format:H_,RGB_S3TC_DXT1_Format:DM,RGDepthPacking:_se,RGFormat:UW,RGIntegerFormat:xx,RawShaderMaterial:myA,Ray:Fw,Raycaster:EV,RectAreaLight:KyA,RedFormat:Lx,RedIntegerFormat:gG,ReinhardToneMapping:JfA,RenderTarget:LW,RenderTarget3D:SIe,RepeatWrapping:Fr,ReplaceStencilOp:Lse,ReverseSubtractEquation:hfA,RingGeometry:gT,SIGNED_RED_GREEN_RGTC2_Format:uJ,SIGNED_RED_RGTC1_Format:EJ,SRGBColorSpace:rn,SRGBTransfer:mg,Scene:rG,ShaderChunk:cn,ShaderLib:xc,ShaderMaterial:Cc,ShadowMaterial:DyA,Shape:jp,ShapeGeometry:oT,ShapePath:VIe,ShapeUtils:zc,ShortType:MW,Skeleton:Jw,SkeletonHelper:HyA,SkinnedMesh:jx,Source:Ru,Sphere:xs,SphereGeometry:Sf,Spherical:bIe,SphericalHarmonics3:FyA,SplineCurve:WW,SpotLight:CT,SpotLightHelper:JIe,Sprite:hJ,SpriteMaterial:FN,SrcAlphaFactor:K_,SrcAlphaSaturateFactor:RfA,SrcColorFactor:mfA,StaticCopyUsage:tae,StaticDrawUsage:UN,StaticReadUsage:$se,StereoCamera:aIe,StreamCopyUsage:nae,StreamDrawUsage:Xse,StreamReadUsage:eae,StringKeyframeTrack:ay,SubtractEquation:dfA,SubtractiveBlending:i4,TOUCH:Nse,TangentSpaceNormalMap:xd,TetrahedronGeometry:sT,Texture:Kg,TextureLoader:qd,TextureUtils:iCe,Timer:RIe,TimestampQuery:oae,TorusGeometry:aT,TorusKnotGeometry:rT,Triangle:eI,TriangleFanDrawMode:Df,TriangleStripDrawMode:oG,TrianglesDrawMode:FW,TubeGeometry:IT,UVMapping:Kx,Uint16BufferAttribute:xW,Uint32BufferAttribute:TW,Uint8BufferAttribute:Hae,Uint8ClampedBufferAttribute:Oae,Uniform:BV,UniformsGroup:kIe,UniformsLib:Pt,UniformsUtils:qW,UnsignedByteType:Ic,UnsignedInt101111Type:RW,UnsignedInt248Type:TS,UnsignedInt5999Type:NW,UnsignedIntType:IQ,UnsignedShort4444Type:_x,UnsignedShort5551Type:Jx,UnsignedShortType:xS,VSMShadowMap:Gc,Vector2:lt,Vector3:SA,Vector4:ig,VectorKeyframeTrack:mB,VideoFrameTexture:Bre,VideoTexture:cyA,WebGL3DRenderTarget:Gae,WebGLArrayRenderTarget:Rae,WebGLCoordinateSystem:jI,WebGLCubeRenderTarget:ayA,WebGLRenderTarget:il,WebGLRenderer:dV,WebGLUtils:VyA,WebGPUCoordinateSystem:HS,WebXRController:vK,WireframeGeometry:yyA,WrapAroundEnding:GN,ZeroCurvatureEnding:lp,ZeroFactor:yfA,ZeroSlopeEnding:Bp,ZeroStencilOp:Jse,createCanvasElement:iyA},Symbol.toStringTag,{value:"Module"}));var XyA={exports:{}},$yA={},ADA={exports:{}},eDA={};/**
 * @license React
 * use-sync-external-store-shim.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var ZS=E;function LEe(e,A){return e===A&&(e!==0||1/e===1/A)||e!==e&&A!==A}var xEe=typeof Object.is=="function"?Object.is:LEe,TEe=ZS.useState,qEe=ZS.useEffect,YEe=ZS.useLayoutEffect,HEe=ZS.useDebugValue;function OEe(e,A){var t=A(),i=TEe({inst:{value:t,getSnapshot:A}}),n=i[0].inst,g=i[1];return YEe(function(){n.value=t,n.getSnapshot=A,HH(n)&&g({inst:n})},[e,t,A]),qEe(function(){return HH(n)&&g({inst:n}),e(function(){HH(n)&&g({inst:n})})},[e]),HEe(t),t}function HH(e){var A=e.getSnapshot;e=e.value;try{var t=A();return!xEe(e,t)}catch{return!0}}function PEe(e,A){return A()}var jEe=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?PEe:OEe;eDA.useSyncExternalStore=ZS.useSyncExternalStore!==void 0?ZS.useSyncExternalStore:jEe;ADA.exports=eDA;var zEe=ADA.exports;/**
 * @license React
 * use-sync-external-store-shim/with-selector.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var BT=E,ZEe=zEe;function WEe(e,A){return e===A&&(e!==0||1/e===1/A)||e!==e&&A!==A}var VEe=typeof Object.is=="function"?Object.is:WEe,XEe=ZEe.useSyncExternalStore,$Ee=BT.useRef,AQe=BT.useEffect,eQe=BT.useMemo,tQe=BT.useDebugValue;$yA.useSyncExternalStoreWithSelector=function(e,A,t,i,n){var g=$Ee(null);if(g.current===null){var o={hasValue:!1,value:null};g.current=o}else o=g.current;g=eQe(function(){function a(B){if(!r){if(r=!0,I=B,B=i(B),n!==void 0&&o.hasValue){var Q=o.value;if(n(Q,B))return c=Q}return c=B}if(Q=c,VEe(I,B))return Q;var h=i(B);return n!==void 0&&n(Q,h)?(I=B,Q):(I=B,c=h)}var r=!1,I,c,l=t===void 0?null:t;return[function(){return a(A())},l===null?void 0:function(){return a(l())}]},[A,t,i,n]);var s=XEe(e,g[0],g[1]);return AQe(function(){o.hasValue=!0,o.value=s},[s]),tQe(s),s};XyA.exports=$yA;var iQe=XyA.exports;const nQe=nw(iQe),sgA=e=>{let A;const t=new Set,i=(r,I)=>{const c=typeof r=="function"?r(A):r;if(!Object.is(c,A)){const l=A;A=I??(typeof c!="object"||c===null)?c:Object.assign({},A,c),t.forEach(B=>B(A,l))}},n=()=>A,s={setState:i,getState:n,getInitialState:()=>a,subscribe:r=>(t.add(r),()=>t.delete(r))},a=A=e(i,n,s);return s},tDA=e=>e?sgA(e):sgA,{useSyncExternalStoreWithSelector:gQe}=nQe,oQe=e=>e;function sQe(e,A=oQe,t){const i=gQe(e.subscribe,e.getState,e.getInitialState,A,t);return ue.useDebugValue(i),i}const agA=(e,A)=>{const t=tDA(e),i=(n,g=A)=>sQe(t,n,g);return Object.assign(i,t),i},iDA=(e,A)=>e?agA(e,A):agA,aQe=e=>typeof e=="object"&&typeof e.then=="function",Qp=[];function nDA(e,A,t=(i,n)=>i===n){if(e===A)return!0;if(!e||!A)return!1;const i=e.length;if(A.length!==i)return!1;for(let n=0;n<i;n++)if(!t(e[n],A[n]))return!1;return!0}function gDA(e,A=null,t=!1,i={}){A===null&&(A=[e]);for(const g of Qp)if(nDA(A,g.keys,g.equal)){if(t)return;if(Object.prototype.hasOwnProperty.call(g,"error"))throw g.error;if(Object.prototype.hasOwnProperty.call(g,"response"))return i.lifespan&&i.lifespan>0&&(g.timeout&&clearTimeout(g.timeout),g.timeout=setTimeout(g.remove,i.lifespan)),g.response;if(!t)throw g.promise}const n={keys:A,equal:i.equal,remove:()=>{const g=Qp.indexOf(n);g!==-1&&Qp.splice(g,1)},promise:(aQe(e)?e:e(...A)).then(g=>{n.response=g,i.lifespan&&i.lifespan>0&&(n.timeout=setTimeout(n.remove,i.lifespan))}).catch(g=>n.error=g)};if(Qp.push(n),!t)throw n.promise}const oDA=(e,A,t)=>gDA(e,A,!1,t),rQe=(e,A,t)=>void gDA(e,A,!0,t),IQe=e=>{if(e===void 0||e.length===0)Qp.splice(0,Qp.length);else{const A=Qp.find(t=>nDA(e,t.keys,t.equal));A&&A.remove()}};var sDA={exports:{}},aDA={exports:{}},OH={exports:{}},PH={};/**
 * @license React
 * scheduler.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var rgA;function CQe(){return rgA||(rgA=1,function(e){function A(v,U){var x=v.length;v.push(U);A:for(;0<x;){var T=x-1>>>1,z=v[T];if(0<n(z,U))v[T]=U,v[x]=z,x=T;else break A}}function t(v){return v.length===0?null:v[0]}function i(v){if(v.length===0)return null;var U=v[0],x=v.pop();if(x!==U){v[0]=x;A:for(var T=0,z=v.length,Z=z>>>1;T<Z;){var eA=2*(T+1)-1,aA=v[eA],sA=eA+1,pA=v[sA];if(0>n(aA,x))sA<z&&0>n(pA,aA)?(v[T]=pA,v[sA]=x,T=sA):(v[T]=aA,v[eA]=x,T=eA);else if(sA<z&&0>n(pA,x))v[T]=pA,v[sA]=x,T=sA;else break A}}return U}function n(v,U){var x=v.sortIndex-U.sortIndex;return x!==0?x:v.id-U.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var g=performance;e.unstable_now=function(){return g.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var a=[],r=[],I=1,c=null,l=3,B=!1,Q=!1,h=!1,d=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;function m(v){for(var U=t(r);U!==null;){if(U.callback===null)i(r);else if(U.startTime<=v)i(r),U.sortIndex=U.expirationTime,A(a,U);else break;U=t(r)}}function D(v){if(h=!1,m(v),!Q)if(t(a)!==null)Q=!0,J();else{var U=t(r);U!==null&&q(D,U.startTime-v)}}var S=!1,k=-1,N=5,G=-1;function M(){return!(e.unstable_now()-G<N)}function w(){if(S){var v=e.unstable_now();G=v;var U=!0;try{A:{Q=!1,h&&(h=!1,p(k),k=-1),B=!0;var x=l;try{e:{for(m(v),c=t(a);c!==null&&!(c.expirationTime>v&&M());){var T=c.callback;if(typeof T=="function"){c.callback=null,l=c.priorityLevel;var z=T(c.expirationTime<=v);if(v=e.unstable_now(),typeof z=="function"){c.callback=z,m(v),U=!0;break e}c===t(a)&&i(a),m(v)}else i(a);c=t(a)}if(c!==null)U=!0;else{var Z=t(r);Z!==null&&q(D,Z.startTime-v),U=!1}}break A}finally{c=null,l=x,B=!1}U=void 0}}finally{U?b():S=!1}}}var b;if(typeof y=="function")b=function(){y(w)};else if(typeof MessageChannel<"u"){var _=new MessageChannel,K=_.port2;_.port1.onmessage=w,b=function(){K.postMessage(null)}}else b=function(){d(w,0)};function J(){S||(S=!0,b())}function q(v,U){k=d(function(){v(e.unstable_now())},U)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(v){v.callback=null},e.unstable_continueExecution=function(){Q||B||(Q=!0,J())},e.unstable_forceFrameRate=function(v){0>v||125<v?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):N=0<v?Math.floor(1e3/v):5},e.unstable_getCurrentPriorityLevel=function(){return l},e.unstable_getFirstCallbackNode=function(){return t(a)},e.unstable_next=function(v){switch(l){case 1:case 2:case 3:var U=3;break;default:U=l}var x=l;l=U;try{return v()}finally{l=x}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(v,U){switch(v){case 1:case 2:case 3:case 4:case 5:break;default:v=3}var x=l;l=v;try{return U()}finally{l=x}},e.unstable_scheduleCallback=function(v,U,x){var T=e.unstable_now();switch(typeof x=="object"&&x!==null?(x=x.delay,x=typeof x=="number"&&0<x?T+x:T):x=T,v){case 1:var z=-1;break;case 2:z=250;break;case 5:z=1073741823;break;case 4:z=1e4;break;default:z=5e3}return z=x+z,v={id:I++,callback:U,priorityLevel:v,startTime:x,expirationTime:z,sortIndex:-1},x>T?(v.sortIndex=x,A(r,v),t(a)===null&&v===t(r)&&(h?(p(k),k=-1):h=!0,q(D,x-T))):(v.sortIndex=z,A(a,v),Q||B||(Q=!0,J())),v},e.unstable_shouldYield=M,e.unstable_wrapCallback=function(v){var U=l;return function(){var x=l;l=U;try{return v.apply(this,arguments)}finally{l=x}}}}(PH)),PH}var IgA;function cQe(){return IgA||(IgA=1,OH.exports=CQe()),OH.exports}/**
 * @license React
 * react-reconciler.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */(function(e){e.exports=function(A){function t(u,f,R,F){return new VSA(u,f,R,F)}function i(){}function n(u){var f="https://react.dev/errors/"+u;if(1<arguments.length){f+="?args[]="+encodeURIComponent(arguments[1]);for(var R=2;R<arguments.length;R++)f+="&args[]="+encodeURIComponent(arguments[R])}return"Minified React error #"+u+"; visit "+f+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function g(u){return u===null||typeof u!="object"?null:(u=n9&&u[n9]||u["@@iterator"],typeof u=="function"?u:null)}function o(u){if(u==null)return null;if(typeof u=="function")return u.$$typeof===iwA?null:u.displayName||u.name||null;if(typeof u=="string")return u;switch(u){case By:return"Fragment";case ly:return"Portal";case GT:return"Profiler";case e9:return"StrictMode";case UT:return"Suspense";case vT:return"SuspenseList"}if(typeof u=="object")switch(u.$$typeof){case fQ:return(u.displayName||"Context")+".Provider";case t9:return(u._context.displayName||"Context")+".Consumer";case bT:var f=u.render;return u=u.displayName,u||(u=f.displayName||f.name||"",u=u!==""?"ForwardRef("+u+")":"ForwardRef"),u;case KT:return f=u.displayName||null,f!==null?f:o(u.type)||"Memo";case yQ:f=u._payload,u=u._init;try{return o(u(f))}catch{}}return null}function s(u){if(FT===void 0)try{throw Error()}catch(R){var f=R.stack.trim().match(/\n( *(at )?)/);FT=f&&f[1]||"",g9=-1<R.stack.indexOf(`
    at`)?" (<anonymous>)":-1<R.stack.indexOf("@")?"@unknown:0:0":""}return`
`+FT+u+g9}function a(u,f){if(!u||_T)return"";_T=!0;var R=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var F={DetermineComponentFrameRoot:function(){try{if(f){var Wt=function(){throw Error()};if(Object.defineProperty(Wt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Wt,[])}catch(on){var Xt=on}Reflect.construct(u,[],Wt)}else{try{Wt.call()}catch(on){Xt=on}u.call(Wt.prototype)}}else{try{throw Error()}catch(on){Xt=on}(Wt=u())&&typeof Wt.catch=="function"&&Wt.catch(function(){})}}catch(on){if(on&&Xt&&typeof on.stack=="string")return[on.stack,Xt.stack]}return[null,null]}};F.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var Y=Object.getOwnPropertyDescriptor(F.DetermineComponentFrameRoot,"name");Y&&Y.configurable&&Object.defineProperty(F.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var AA=F.DetermineComponentFrameRoot(),GA=AA[0],ne=AA[1];if(GA&&ne){var Me=GA.split(`
`),tt=ne.split(`
`);for(Y=F=0;F<Me.length&&!Me[F].includes("DetermineComponentFrameRoot");)F++;for(;Y<tt.length&&!tt[Y].includes("DetermineComponentFrameRoot");)Y++;if(F===Me.length||Y===tt.length)for(F=Me.length-1,Y=tt.length-1;1<=F&&0<=Y&&Me[F]!==tt[Y];)Y--;for(;1<=F&&0<=Y;F--,Y--)if(Me[F]!==tt[Y]){if(F!==1||Y!==1)do if(F--,Y--,0>Y||Me[F]!==tt[Y]){var bt=`
`+Me[F].replace(" at new "," at ");return u.displayName&&bt.includes("<anonymous>")&&(bt=bt.replace("<anonymous>",u.displayName)),bt}while(1<=F&&0<=Y);break}}}finally{_T=!1,Error.prepareStackTrace=R}return(R=u?u.displayName||u.name:"")?s(R):""}function r(u){switch(u.tag){case 26:case 27:case 5:return s(u.type);case 16:return s("Lazy");case 13:return s("Suspense");case 19:return s("SuspenseList");case 0:case 15:return u=a(u.type,!1),u;case 11:return u=a(u.type.render,!1),u;case 1:return u=a(u.type,!0),u;default:return""}}function I(u){try{var f="";do f+=r(u),u=u.return;while(u);return f}catch(R){return`
Error generating stack: `+R.message+`
`+R.stack}}function c(u){var f=u,R=u;if(u.alternate)for(;f.return;)f=f.return;else{u=f;do f=u,f.flags&4098&&(R=f.return),u=f.return;while(u)}return f.tag===3?R:null}function l(u){if(c(u)!==u)throw Error(n(188))}function B(u){var f=u.alternate;if(!f){if(f=c(u),f===null)throw Error(n(188));return f!==u?null:u}for(var R=u,F=f;;){var Y=R.return;if(Y===null)break;var AA=Y.alternate;if(AA===null){if(F=Y.return,F!==null){R=F;continue}break}if(Y.child===AA.child){for(AA=Y.child;AA;){if(AA===R)return l(Y),u;if(AA===F)return l(Y),f;AA=AA.sibling}throw Error(n(188))}if(R.return!==F.return)R=Y,F=AA;else{for(var GA=!1,ne=Y.child;ne;){if(ne===R){GA=!0,R=Y,F=AA;break}if(ne===F){GA=!0,F=Y,R=AA;break}ne=ne.sibling}if(!GA){for(ne=AA.child;ne;){if(ne===R){GA=!0,R=AA,F=Y;break}if(ne===F){GA=!0,F=AA,R=Y;break}ne=ne.sibling}if(!GA)throw Error(n(189))}}if(R.alternate!==F)throw Error(n(190))}if(R.tag!==3)throw Error(n(188));return R.stateNode.current===R?u:f}function Q(u){var f=u.tag;if(f===5||f===26||f===27||f===6)return u;for(u=u.child;u!==null;){if(f=Q(u),f!==null)return f;u=u.sibling}return null}function h(u){var f=u.tag;if(f===5||f===26||f===27||f===6)return u;for(u=u.child;u!==null;){if(u.tag!==4&&(f=h(u),f!==null))return f;u=u.sibling}return null}function d(u){return{current:u}}function p(u){0>Qy||(u.current=YT[Qy],YT[Qy]=null,Qy--)}function y(u,f){Qy++,YT[Qy]=u.current,u.current=f}function m(u){return u>>>=0,u===0?32:31-(d0A(u)/h0A|0)|0}function D(u){var f=u&42;if(f!==0)return f;switch(u&-u){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128: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 u&4194176;case 4194304:case 8388608:case 16777216:case 33554432:return u&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return u}}function S(u,f){var R=u.pendingLanes;if(R===0)return 0;var F=0,Y=u.suspendedLanes,AA=u.pingedLanes,GA=u.warmLanes;u=u.finishedLanes!==0;var ne=R&134217727;return ne!==0?(R=ne&~Y,R!==0?F=D(R):(AA&=ne,AA!==0?F=D(AA):u||(GA=ne&~GA,GA!==0&&(F=D(GA))))):(ne=R&~Y,ne!==0?F=D(ne):AA!==0?F=D(AA):u||(GA=R&~GA,GA!==0&&(F=D(GA)))),F===0?0:f!==0&&f!==F&&!(f&Y)&&(Y=F&-F,GA=f&-f,Y>=GA||Y===32&&(GA&4194176)!==0)?f:F}function k(u,f){return(u.pendingLanes&~(u.suspendedLanes&~u.pingedLanes)&f)===0}function N(u,f){switch(u){case 1:case 2:case 4:case 8:return f+250;case 16:case 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 f+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function G(){var u=MG;return MG<<=1,!(MG&4194176)&&(MG=128),u}function M(){var u=NG;return NG<<=1,!(NG&62914560)&&(NG=4194304),u}function w(u){for(var f=[],R=0;31>R;R++)f.push(u);return f}function b(u,f){u.pendingLanes|=f,f!==268435456&&(u.suspendedLanes=0,u.pingedLanes=0,u.warmLanes=0)}function _(u,f,R,F,Y,AA){var GA=u.pendingLanes;u.pendingLanes=R,u.suspendedLanes=0,u.pingedLanes=0,u.warmLanes=0,u.expiredLanes&=R,u.entangledLanes&=R,u.errorRecoveryDisabledLanes&=R,u.shellSuspendCounter=0;var ne=u.entanglements,Me=u.expirationTimes,tt=u.hiddenUpdates;for(R=GA&~R;0<R;){var bt=31-kI(R),Wt=1<<bt;ne[bt]=0,Me[bt]=-1;var Xt=tt[bt];if(Xt!==null)for(tt[bt]=null,bt=0;bt<Xt.length;bt++){var on=Xt[bt];on!==null&&(on.lane&=-536870913)}R&=~Wt}F!==0&&K(u,F,0),AA!==0&&Y===0&&u.tag!==0&&(u.suspendedLanes|=AA&~(GA&~f))}function K(u,f,R){u.pendingLanes|=f,u.suspendedLanes&=~f;var F=31-kI(f);u.entangledLanes|=f,u.entanglements[F]=u.entanglements[F]|1073741824|R&4194218}function J(u,f){var R=u.entangledLanes|=f;for(u=u.entanglements;R;){var F=31-kI(R),Y=1<<F;Y&f|u[F]&f&&(u[F]|=f),R&=~Y}}function q(u){return u&=-u,2<u?8<u?u&134217727?32:268435456:8:2}function v(u){if(MI&&typeof MI.onCommitFiberRoot=="function")try{MI.onCommitFiberRoot($w,u,void 0,(u.current.flags&128)===128)}catch{}}function U(u){if(typeof m0A=="function"&&S0A(u),MI&&typeof MI.setStrictMode=="function")try{MI.setStrictMode($w,u)}catch{}}function x(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}function T(u,f){if(typeof u=="object"&&u!==null){var R=G9.get(u);return R!==void 0?R:(f={value:u,source:f,stack:I(f)},G9.set(u,f),f)}return{value:u,source:f,stack:I(f)}}function z(u,f){dy[hy++]=bG,dy[hy++]=GG,GG=u,bG=f}function Z(u,f,R){uC[dC++]=xB,uC[dC++]=TB,uC[dC++]=eh,eh=u;var F=xB;u=TB;var Y=32-kI(F)-1;F&=~(1<<Y),R+=1;var AA=32-kI(f)+Y;if(30<AA){var GA=Y-Y%5;AA=(F&(1<<GA)-1).toString(32),F>>=GA,Y-=GA,xB=1<<32-kI(f)+Y|R<<Y|F,TB=AA+u}else xB=1<<AA|R<<Y|F,TB=u}function eA(u){u.return!==null&&(z(u,1),Z(u,1,0))}function aA(u){for(;u===GG;)GG=dy[--hy],dy[hy]=null,bG=dy[--hy],dy[hy]=null;for(;u===eh;)eh=uC[--dC],uC[dC]=null,TB=uC[--dC],uC[dC]=null,xB=uC[--dC],uC[dC]=null}function sA(u,f){y(mQ,f),y(A0,u),y(Qa,null),u=owA(f),p(Qa),y(Qa,u)}function pA(){p(Qa),p(A0),p(mQ)}function gA(u){u.memoizedState!==null&&y(UG,u);var f=Qa.current,R=swA(f,u.type);f!==R&&(y(A0,u),y(Qa,R))}function yA(u){A0.current===u&&(p(Qa),p(A0)),UG.current===u&&(p(UG),LB?Ah._currentValue=Ey:Ah._currentValue2=Ey)}function fA(u){var f=Error(n(418,""));throw L(T(f,u)),PT}function RA(u,f){if(!EC)throw Error(n(175));A0A(u.stateNode,u.type,u.memoizedProps,f,u)||fA(u)}function qA(u){for(lr=u.return;lr;)switch(lr.tag){case 3:case 27:ul=!0;return;case 5:case 13:ul=!1;return;default:lr=lr.return}}function W(u){if(!EC||u!==lr)return!1;if(!og)return qA(u),og=!0,!1;var f=!1;if(qa?u.tag!==3&&u.tag!==27&&(u.tag!==5||p9(u.type)&&!kG(u.type,u.memoizedProps))&&(f=!0):u.tag!==3&&(u.tag!==5||p9(u.type)&&!kG(u.type,u.memoizedProps))&&(f=!0),f&&Ya&&fA(u),qA(u),u.tag===13){if(!EC)throw Error(n(316));if(u=u.memoizedState,u=u!==null?u.dehydrated:null,!u)throw Error(n(317));Ya=i0A(u)}else Ya=lr?d9(u.stateNode):null;return!0}function $(){EC&&(Ya=lr=null,og=!1)}function L(u){fc===null?fc=[u]:fc.push(u)}function H(){for(var u=py,f=jT=py=0;f<u;){var R=hC[f];hC[f++]=null;var F=hC[f];hC[f++]=null;var Y=hC[f];hC[f++]=null;var AA=hC[f];if(hC[f++]=null,F!==null&&Y!==null){var GA=F.pending;GA===null?Y.next=Y:(Y.next=GA.next,GA.next=Y),F.pending=Y}AA!==0&&oA(R,Y,AA)}}function P(u,f,R,F){hC[py++]=u,hC[py++]=f,hC[py++]=R,hC[py++]=F,jT|=F,u.lanes|=F,u=u.alternate,u!==null&&(u.lanes|=F)}function tA(u,f,R,F){return P(u,f,R,F),IA(u)}function iA(u,f){return P(u,null,null,f),IA(u)}function oA(u,f,R){u.lanes|=R;var F=u.alternate;F!==null&&(F.lanes|=R);for(var Y=!1,AA=u.return;AA!==null;)AA.childLanes|=R,F=AA.alternate,F!==null&&(F.childLanes|=R),AA.tag===22&&(u=AA.stateNode,u===null||u._visibility&1||(Y=!0)),u=AA,AA=AA.return;Y&&f!==null&&u.tag===3&&(AA=u.stateNode,Y=31-kI(R),AA=AA.hiddenUpdates,u=AA[Y],u===null?AA[Y]=[f]:u.push(f),f.lane=R|536870912)}function IA(u){if(50<r0)throw r0=0,rq=null,Error(n(185));for(var f=u.return;f!==null;)u=f,f=u.return;return u.tag===3?u.stateNode:null}function CA(u){u!==fy&&u.next===null&&(fy===null?vG=fy=u:fy=fy.next=u),KG=!0,zT||(zT=!0,wA(uA))}function _A(u,f){if(!ZT&&KG){ZT=!0;do for(var R=!1,F=vG;F!==null;){if(u!==0){var Y=F.pendingLanes;if(Y===0)var AA=0;else{var GA=F.suspendedLanes,ne=F.pingedLanes;AA=(1<<31-kI(42|u)+1)-1,AA&=Y&~(GA&~ne),AA=AA&201326677?AA&201326677|1:AA?AA|2:0}AA!==0&&(R=!0,cA(F,AA))}else AA=Vn,AA=S(F,F===Og?AA:0),!(AA&3)||k(F,AA)||(R=!0,cA(F,AA));F=F.next}while(R);ZT=!1}}function uA(){KG=zT=!1;var u=0;yy!==0&&(EwA()&&(u=yy),yy=0);for(var f=pc(),R=null,F=vG;F!==null;){var Y=F.next,AA=X(F,f);AA===0?(F.next=null,R===null?vG=Y:R.next=Y,Y===null&&(fy=R)):(R=F,(u!==0||AA&3)&&(KG=!0)),F=Y}_A(u)}function X(u,f){for(var R=u.suspendedLanes,F=u.pingedLanes,Y=u.expirationTimes,AA=u.pendingLanes&-62914561;0<AA;){var GA=31-kI(AA),ne=1<<GA,Me=Y[GA];Me===-1?(!(ne&R)||ne&F)&&(Y[GA]=N(ne,f)):Me<=f&&(u.expiredLanes|=ne),AA&=~ne}if(f=Og,R=Vn,R=S(u,u===f?R:0),F=u.callbackNode,R===0||u===f&&Pg===2||u.cancelPendingCommit!==null)return F!==null&&F!==null&&HT(F),u.callbackNode=null,u.callbackPriority=0;if(!(R&3)||k(u,R)){if(f=R&-R,f===u.callbackPriority)return f;switch(F!==null&&HT(F),q(R)){case 2:case 8:R=y0A;break;case 32:R=OT;break;case 268435456:R=D0A;break;default:R=OT}return F=O.bind(null,u),R=RG(R,F),u.callbackPriority=f,u.callbackNode=R,f}return F!==null&&F!==null&&HT(F),u.callbackPriority=2,u.callbackNode=null,2}function O(u,f){var R=u.callbackNode;if(Vd()&&u.callbackNode!==R)return null;var F=Vn;return F=S(u,u===Og?F:0),F===0?null:(cr(u,F,f),X(u,pc()),u.callbackNode!=null&&u.callbackNode===R?O.bind(null,u):null)}function cA(u,f){if(Vd())return null;cr(u,f,!0)}function wA(u){fwA?ywA(function(){Gg&6?RG(R9,u):u()}):RG(R9,u)}function xA(){return yy===0&&(yy=G()),yy}function YA(u,f){if(e0===null){var R=e0=[];WT=0,Dy=xA(),my={status:"pending",value:void 0,then:function(F){R.push(F)}}}return WT++,f.then(jA,jA),f}function jA(){if(--WT===0&&e0!==null){my!==null&&(my.status="fulfilled");var u=e0;e0=null,Dy=0,my=null;for(var f=0;f<u.length;f++)(0,u[f])()}}function ie(u,f){var R=[],F={status:"pending",value:null,reason:null,then:function(Y){R.push(Y)}};return u.then(function(){F.status="fulfilled",F.value=f;for(var Y=0;Y<R.length;Y++)(0,R[Y])(f)},function(Y){for(F.status="rejected",F.reason=Y,Y=0;Y<R.length;Y++)(0,R[Y])(void 0)}),F}function he(u){u.updateQueue={baseState:u.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function le(u,f){u=u.updateQueue,f.updateQueue===u&&(f.updateQueue={baseState:u.baseState,firstBaseUpdate:u.firstBaseUpdate,lastBaseUpdate:u.lastBaseUpdate,shared:u.shared,callbacks:null})}function NA(u){return{lane:u,tag:0,payload:null,callback:null,next:null}}function EA(u,f,R){var F=u.updateQueue;if(F===null)return null;if(F=F.shared,Gg&2){var Y=F.pending;return Y===null?f.next=f:(f.next=Y.next,Y.next=f),F.pending=f,f=IA(u),oA(u,null,R),f}return P(u,F,f,R),IA(u)}function PA(u,f,R){if(f=f.updateQueue,f!==null&&(f=f.shared,(R&4194176)!==0)){var F=f.lanes;F&=u.pendingLanes,R|=F,f.lanes=R,J(u,R)}}function ZA(u,f){var R=u.updateQueue,F=u.alternate;if(F!==null&&(F=F.updateQueue,R===F)){var Y=null,AA=null;if(R=R.firstBaseUpdate,R!==null){do{var GA={lane:R.lane,tag:R.tag,payload:R.payload,callback:null,next:null};AA===null?Y=AA=GA:AA=AA.next=GA,R=R.next}while(R!==null);AA===null?Y=AA=f:AA=AA.next=f}else Y=AA=f;R={baseState:F.baseState,firstBaseUpdate:Y,lastBaseUpdate:AA,shared:F.shared,callbacks:F.callbacks},u.updateQueue=R;return}u=R.lastBaseUpdate,u===null?R.firstBaseUpdate=f:u.next=f,R.lastBaseUpdate=f}function FA(){if(VT){var u=my;if(u!==null)throw u}}function Ie(u,f,R,F){VT=!1;var Y=u.updateQueue;SQ=!1;var AA=Y.firstBaseUpdate,GA=Y.lastBaseUpdate,ne=Y.shared.pending;if(ne!==null){Y.shared.pending=null;var Me=ne,tt=Me.next;Me.next=null,GA===null?AA=tt:GA.next=tt,GA=Me;var bt=u.alternate;bt!==null&&(bt=bt.updateQueue,ne=bt.lastBaseUpdate,ne!==GA&&(ne===null?bt.firstBaseUpdate=tt:ne.next=tt,bt.lastBaseUpdate=Me))}if(AA!==null){var Wt=Y.baseState;GA=0,bt=tt=Me=null,ne=AA;do{var Xt=ne.lane&-536870913,on=Xt!==ne.lane;if(on?(Vn&Xt)===Xt:(F&Xt)===Xt){Xt!==0&&Xt===Dy&&(VT=!0),bt!==null&&(bt=bt.next={lane:0,tag:ne.tag,payload:ne.payload,callback:null,next:null});A:{var yC=u,I0=ne;Xt=f;var Ih=R;switch(I0.tag){case 1:if(yC=I0.payload,typeof yC=="function"){Wt=yC.call(Ih,Wt,Xt);break A}Wt=yC;break A;case 3:yC.flags=yC.flags&-65537|128;case 0:if(yC=I0.payload,Xt=typeof yC=="function"?yC.call(Ih,Wt,Xt):yC,Xt==null)break A;Wt=RT({},Wt,Xt);break A;case 2:SQ=!0}}Xt=ne.callback,Xt!==null&&(u.flags|=64,on&&(u.flags|=8192),on=Y.callbacks,on===null?Y.callbacks=[Xt]:on.push(Xt))}else on={lane:Xt,tag:ne.tag,payload:ne.payload,callback:ne.callback,next:null},bt===null?(tt=bt=on,Me=Wt):bt=bt.next=on,GA|=Xt;if(ne=ne.next,ne===null){if(ne=Y.shared.pending,ne===null)break;on=ne,ne=on.next,on.next=null,Y.lastBaseUpdate=on,Y.shared.pending=null}}while(!0);bt===null&&(Me=Wt),Y.baseState=Me,Y.firstBaseUpdate=tt,Y.lastBaseUpdate=bt,AA===null&&(Y.shared.lanes=0),MQ|=GA,u.lanes=GA,u.memoizedState=Wt}}function DA(u,f){if(typeof u!="function")throw Error(n(191,u));u.call(f)}function rA(u,f){var R=u.callbacks;if(R!==null)for(u.callbacks=null,u=0;u<R.length;u++)DA(R[u],f)}function BA(u,f){if(NI(u,f))return!0;if(typeof u!="object"||u===null||typeof f!="object"||f===null)return!1;var R=Object.keys(u),F=Object.keys(f);if(R.length!==F.length)return!1;for(F=0;F<R.length;F++){var Y=R[F];if(!w0A.call(f,Y)||!NI(u[Y],f[Y]))return!1}return!0}function j(u){return u=u.status,u==="fulfilled"||u==="rejected"}function QA(){}function dA(u,f,R){switch(R=u[R],R===void 0?u.push(f):R!==f&&(f.then(QA,QA),f=R),f.status){case"fulfilled":return f.value;case"rejected":throw u=f.reason,u===t0?Error(n(483)):u;default:if(typeof f.status=="string")f.then(QA,QA);else{if(u=Og,u!==null&&100<u.shellSuspendCounter)throw Error(n(482));u=f,u.status="pending",u.then(function(F){if(f.status==="pending"){var Y=f;Y.status="fulfilled",Y.value=F}},function(F){if(f.status==="pending"){var Y=f;Y.status="rejected",Y.reason=F}})}switch(f.status){case"fulfilled":return f.value;case"rejected":throw u=f.reason,u===t0?Error(n(483)):u}throw Sy=f,t0}}function UA(){if(Sy===null)throw Error(n(459));var u=Sy;return Sy=null,u}function TA(u){var f=i0;return i0+=1,wy===null&&(wy=[]),dA(wy,u,f)}function oe(u,f){f=f.props.ref,u.ref=f!==void 0?f:null}function me(u,f){throw f.$$typeof===AwA?Error(n(525)):(u=Object.prototype.toString.call(f),Error(n(31,u==="[object Object]"?"object with keys {"+Object.keys(f).join(", ")+"}":u)))}function be(u){var f=u._init;return f(u._payload)}function $e(u){function f(Ue,we){if(u){var Ye=Ue.deletions;Ye===null?(Ue.deletions=[we],Ue.flags|=16):Ye.push(we)}}function R(Ue,we){if(!u)return null;for(;we!==null;)f(Ue,we),we=we.sibling;return null}function F(Ue){for(var we=new Map;Ue!==null;)Ue.key!==null?we.set(Ue.key,Ue):we.set(Ue.index,Ue),Ue=Ue.sibling;return we}function Y(Ue,we){return Ue=pQ(Ue,we),Ue.index=0,Ue.sibling=null,Ue}function AA(Ue,we,Ye){return Ue.index=Ye,u?(Ye=Ue.alternate,Ye!==null?(Ye=Ye.index,Ye<we?(Ue.flags|=33554434,we):Ye):(Ue.flags|=33554434,we)):(Ue.flags|=1048576,we)}function GA(Ue){return u&&Ue.alternate===null&&(Ue.flags|=33554434),Ue}function ne(Ue,we,Ye,Mt){return we===null||we.tag!==6?(we=kT(Ye,Ue.mode,Mt),we.return=Ue,we):(we=Y(we,Ye),we.return=Ue,we)}function Me(Ue,we,Ye,Mt){var ui=Ye.type;return ui===By?bt(Ue,we,Ye.props.children,Mt,Ye.key):we!==null&&(we.elementType===ui||typeof ui=="object"&&ui!==null&&ui.$$typeof===yQ&&be(ui)===we.type)?(we=Y(we,Ye.props),oe(we,Ye),we.return=Ue,we):(we=mG(Ye.type,Ye.key,Ye.props,null,Ue.mode,Mt),oe(we,Ye),we.return=Ue,we)}function tt(Ue,we,Ye,Mt){return we===null||we.tag!==4||we.stateNode.containerInfo!==Ye.containerInfo||we.stateNode.implementation!==Ye.implementation?(we=MT(Ye,Ue.mode,Mt),we.return=Ue,we):(we=Y(we,Ye.children||[]),we.return=Ue,we)}function bt(Ue,we,Ye,Mt,ui){return we===null||we.tag!==7?(we=Xd(Ye,Ue.mode,Mt,ui),we.return=Ue,we):(we=Y(we,Ye),we.return=Ue,we)}function Wt(Ue,we,Ye){if(typeof we=="string"&&we!==""||typeof we=="number"||typeof we=="bigint")return we=kT(""+we,Ue.mode,Ye),we.return=Ue,we;if(typeof we=="object"&&we!==null){switch(we.$$typeof){case SG:return Ye=mG(we.type,we.key,we.props,null,Ue.mode,Ye),oe(Ye,we),Ye.return=Ue,Ye;case ly:return we=MT(we,Ue.mode,Ye),we.return=Ue,we;case yQ:var Mt=we._init;return we=Mt(we._payload),Wt(Ue,we,Ye)}if(wG(we)||g(we))return we=Xd(we,Ue.mode,Ye,null),we.return=Ue,we;if(typeof we.then=="function")return Wt(Ue,TA(we),Ye);if(we.$$typeof===fQ)return Wt(Ue,ae(Ue,we),Ye);me(Ue,we)}return null}function Xt(Ue,we,Ye,Mt){var ui=we!==null?we.key:null;if(typeof Ye=="string"&&Ye!==""||typeof Ye=="number"||typeof Ye=="bigint")return ui!==null?null:ne(Ue,we,""+Ye,Mt);if(typeof Ye=="object"&&Ye!==null){switch(Ye.$$typeof){case SG:return Ye.key===ui?Me(Ue,we,Ye,Mt):null;case ly:return Ye.key===ui?tt(Ue,we,Ye,Mt):null;case yQ:return ui=Ye._init,Ye=ui(Ye._payload),Xt(Ue,we,Ye,Mt)}if(wG(Ye)||g(Ye))return ui!==null?null:bt(Ue,we,Ye,Mt,null);if(typeof Ye.then=="function")return Xt(Ue,we,TA(Ye),Mt);if(Ye.$$typeof===fQ)return Xt(Ue,we,ae(Ue,Ye),Mt);me(Ue,Ye)}return null}function on(Ue,we,Ye,Mt,ui){if(typeof Mt=="string"&&Mt!==""||typeof Mt=="number"||typeof Mt=="bigint")return Ue=Ue.get(Ye)||null,ne(we,Ue,""+Mt,ui);if(typeof Mt=="object"&&Mt!==null){switch(Mt.$$typeof){case SG:return Ue=Ue.get(Mt.key===null?Ye:Mt.key)||null,Me(we,Ue,Mt,ui);case ly:return Ue=Ue.get(Mt.key===null?Ye:Mt.key)||null,tt(we,Ue,Mt,ui);case yQ:var $g=Mt._init;return Mt=$g(Mt._payload),on(Ue,we,Ye,Mt,ui)}if(wG(Mt)||g(Mt))return Ue=Ue.get(Ye)||null,bt(we,Ue,Mt,ui,null);if(typeof Mt.then=="function")return on(Ue,we,Ye,TA(Mt),ui);if(Mt.$$typeof===fQ)return on(Ue,we,Ye,ae(we,Mt),ui);me(we,Mt)}return null}function yC(Ue,we,Ye,Mt){for(var ui=null,$g=null,Ti=we,sg=we=0,Ws=null;Ti!==null&&sg<Ye.length;sg++){Ti.index>sg?(Ws=Ti,Ti=null):Ws=Ti.sibling;var ag=Xt(Ue,Ti,Ye[sg],Mt);if(ag===null){Ti===null&&(Ti=Ws);break}u&&Ti&&ag.alternate===null&&f(Ue,Ti),we=AA(ag,we,sg),$g===null?ui=ag:$g.sibling=ag,$g=ag,Ti=Ws}if(sg===Ye.length)return R(Ue,Ti),og&&z(Ue,sg),ui;if(Ti===null){for(;sg<Ye.length;sg++)Ti=Wt(Ue,Ye[sg],Mt),Ti!==null&&(we=AA(Ti,we,sg),$g===null?ui=Ti:$g.sibling=Ti,$g=Ti);return og&&z(Ue,sg),ui}for(Ti=F(Ti);sg<Ye.length;sg++)Ws=on(Ti,Ue,sg,Ye[sg],Mt),Ws!==null&&(u&&Ws.alternate!==null&&Ti.delete(Ws.key===null?sg:Ws.key),we=AA(Ws,we,sg),$g===null?ui=Ws:$g.sibling=Ws,$g=Ws);return u&&Ti.forEach(function(RQ){return f(Ue,RQ)}),og&&z(Ue,sg),ui}function I0(Ue,we,Ye,Mt){if(Ye==null)throw Error(n(151));for(var ui=null,$g=null,Ti=we,sg=we=0,Ws=null,ag=Ye.next();Ti!==null&&!ag.done;sg++,ag=Ye.next()){Ti.index>sg?(Ws=Ti,Ti=null):Ws=Ti.sibling;var RQ=Xt(Ue,Ti,ag.value,Mt);if(RQ===null){Ti===null&&(Ti=Ws);break}u&&Ti&&RQ.alternate===null&&f(Ue,Ti),we=AA(RQ,we,sg),$g===null?ui=RQ:$g.sibling=RQ,$g=RQ,Ti=Ws}if(ag.done)return R(Ue,Ti),og&&z(Ue,sg),ui;if(Ti===null){for(;!ag.done;sg++,ag=Ye.next())ag=Wt(Ue,ag.value,Mt),ag!==null&&(we=AA(ag,we,sg),$g===null?ui=ag:$g.sibling=ag,$g=ag);return og&&z(Ue,sg),ui}for(Ti=F(Ti);!ag.done;sg++,ag=Ye.next())ag=on(Ti,Ue,sg,ag.value,Mt),ag!==null&&(u&&ag.alternate!==null&&Ti.delete(ag.key===null?sg:ag.key),we=AA(ag,we,sg),$g===null?ui=ag:$g.sibling=ag,$g=ag);return u&&Ti.forEach(function(U0A){return f(Ue,U0A)}),og&&z(Ue,sg),ui}function Ih(Ue,we,Ye,Mt){if(typeof Ye=="object"&&Ye!==null&&Ye.type===By&&Ye.key===null&&(Ye=Ye.props.children),typeof Ye=="object"&&Ye!==null){switch(Ye.$$typeof){case SG:A:{for(var ui=Ye.key;we!==null;){if(we.key===ui){if(ui=Ye.type,ui===By){if(we.tag===7){R(Ue,we.sibling),Mt=Y(we,Ye.props.children),Mt.return=Ue,Ue=Mt;break A}}else if(we.elementType===ui||typeof ui=="object"&&ui!==null&&ui.$$typeof===yQ&&be(ui)===we.type){R(Ue,we.sibling),Mt=Y(we,Ye.props),oe(Mt,Ye),Mt.return=Ue,Ue=Mt;break A}R(Ue,we);break}else f(Ue,we);we=we.sibling}Ye.type===By?(Mt=Xd(Ye.props.children,Ue.mode,Mt,Ye.key),Mt.return=Ue,Ue=Mt):(Mt=mG(Ye.type,Ye.key,Ye.props,null,Ue.mode,Mt),oe(Mt,Ye),Mt.return=Ue,Ue=Mt)}return GA(Ue);case ly:A:{for(ui=Ye.key;we!==null;){if(we.key===ui)if(we.tag===4&&we.stateNode.containerInfo===Ye.containerInfo&&we.stateNode.implementation===Ye.implementation){R(Ue,we.sibling),Mt=Y(we,Ye.children||[]),Mt.return=Ue,Ue=Mt;break A}else{R(Ue,we);break}else f(Ue,we);we=we.sibling}Mt=MT(Ye,Ue.mode,Mt),Mt.return=Ue,Ue=Mt}return GA(Ue);case yQ:return ui=Ye._init,Ye=ui(Ye._payload),Ih(Ue,we,Ye,Mt)}if(wG(Ye))return yC(Ue,we,Ye,Mt);if(g(Ye)){if(ui=g(Ye),typeof ui!="function")throw Error(n(150));return Ye=ui.call(Ye),I0(Ue,we,Ye,Mt)}if(typeof Ye.then=="function")return Ih(Ue,we,TA(Ye),Mt);if(Ye.$$typeof===fQ)return Ih(Ue,we,ae(Ue,Ye),Mt);me(Ue,Ye)}return typeof Ye=="string"&&Ye!==""||typeof Ye=="number"||typeof Ye=="bigint"?(Ye=""+Ye,we!==null&&we.tag===6?(R(Ue,we.sibling),Mt=Y(we,Ye),Mt.return=Ue,Ue=Mt):(R(Ue,we),Mt=kT(Ye,Ue.mode,Mt),Mt.return=Ue,Ue=Mt),GA(Ue)):R(Ue,we)}return function(Ue,we,Ye,Mt){try{i0=0;var ui=Ih(Ue,we,Ye,Mt);return wy=null,ui}catch(Ti){if(Ti===t0)throw Ti;var $g=t(29,Ti,null,Ue.mode);return $g.lanes=Mt,$g.return=Ue,$g}finally{}}}function ci(u,f){u=OB,y(_G,u),y(ky,f),OB=u|f.baseLanes}function ke(){y(_G,OB),y(ky,ky.current)}function nt(){OB=_G.current,p(ky),p(_G)}function Ut(u){var f=u.alternate;y(vs,vs.current&1),y(pC,u),dl===null&&(f===null||ky.current!==null||f.memoizedState!==null)&&(dl=u)}function dt(u){if(u.tag===22){if(y(vs,vs.current),y(pC,u),dl===null){var f=u.alternate;f!==null&&f.memoizedState!==null&&(dl=u)}}else Ht()}function Ht(){y(vs,vs.current),y(pC,pC.current)}function Ft(u){p(pC),dl===u&&(dl=null),p(vs)}function Jt(u){for(var f=u;f!==null;){if(f.tag===13){var R=f.memoizedState;if(R!==null&&(R=R.dehydrated,R===null||xT(R)||TT(R)))return f}else if(f.tag===19&&f.memoizedProps.revealOrder!==void 0){if(f.flags&128)return f}else if(f.child!==null){f.child.return=f,f=f.child;continue}if(f===u)break;for(;f.sibling===null;){if(f.return===null||f.return===u)return null;f=f.return}f.sibling.return=f.return,f=f.sibling}return null}function $A(){throw Error(n(321))}function He(u,f){if(f===null)return!1;for(var R=0;R<f.length&&R<u.length;R++)if(!NI(u[R],f[R]))return!1;return!0}function Xe(u,f,R,F,Y,AA){return wQ=AA,Dn=f,f.memoizedState=null,f.updateQueue=null,f.lanes=0,zi.H=u===null||u.memoizedState===null?nh:kQ,ih=!1,AA=R(F,Y),ih=!1,My&&(AA=kA(f,R,F,Y)),St(u),AA}function St(u){zi.H=hl;var f=Rg!==null&&Rg.next!==null;if(wQ=0,os=Rg=Dn=null,JG=!1,n0=0,Ny=null,f)throw Error(n(300));u===null||zs||(u=u.dependencies,u!==null&&IC(u)&&(zs=!0))}function kA(u,f,R,F){Dn=u;var Y=0;do{if(My&&(Ny=null),n0=0,My=!1,25<=Y)throw Error(n(301));if(Y+=1,os=Rg=null,u.updateQueue!=null){var AA=u.updateQueue;AA.lastEffect=null,AA.events=null,AA.stores=null,AA.memoCache!=null&&(AA.memoCache.index=0)}zi.H=gh,AA=f(R,F)}while(My);return AA}function se(){var u=zi.H,f=u.useState()[0];return f=typeof f.then=="function"?WA(f):f,u=u.useState()[0],(Rg!==null?Rg.memoizedState:null)!==u&&(Dn.flags|=1024),f}function Ce(){var u=LG!==0;return LG=0,u}function VA(u,f,R){f.updateQueue=u.updateQueue,f.flags&=-2053,u.lanes&=~R}function nA(u){if(JG){for(u=u.memoizedState;u!==null;){var f=u.queue;f!==null&&(f.pending=null),u=u.next}JG=!1}wQ=0,os=Rg=Dn=null,My=!1,n0=LG=0,Ny=null}function vA(){var u={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return os===null?Dn.memoizedState=os=u:os=os.next=u,os}function KA(){if(Rg===null){var u=Dn.alternate;u=u!==null?u.memoizedState:null}else u=Rg.next;var f=os===null?Dn.memoizedState:os.next;if(f!==null)os=f,Rg=u;else{if(u===null)throw Dn.alternate===null?Error(n(467)):Error(n(310));Rg=u,u={memoizedState:Rg.memoizedState,baseState:Rg.baseState,baseQueue:Rg.baseQueue,queue:Rg.queue,next:null},os===null?Dn.memoizedState=os=u:os=os.next=u}return os}function WA(u){var f=n0;return n0+=1,Ny===null&&(Ny=[]),u=dA(Ny,u,f),f=Dn,(os===null?f.memoizedState:os.next)===null&&(f=f.alternate,zi.H=f===null||f.memoizedState===null?nh:kQ),u}function bA(u){if(u!==null&&typeof u=="object"){if(typeof u.then=="function")return WA(u);if(u.$$typeof===fQ)return LA(u)}throw Error(n(438,String(u)))}function pe(u){var f=null,R=Dn.updateQueue;if(R!==null&&(f=R.memoCache),f==null){var F=Dn.alternate;F!==null&&(F=F.updateQueue,F!==null&&(F=F.memoCache,F!=null&&(f={data:F.data.map(function(Y){return Y.slice()}),index:0})))}if(f==null&&(f={data:[],index:0}),R===null&&(R=$T(),Dn.updateQueue=R),R.memoCache=f,R=f.data[f.index],R===void 0)for(R=f.data[f.index]=Array(u),F=0;F<u;F++)R[F]=twA;return f.index++,R}function xe(u,f){return typeof f=="function"?f(u):f}function it(u){var f=KA();return ve(f,Rg,u)}function ve(u,f,R){var F=u.queue;if(F===null)throw Error(n(311));F.lastRenderedReducer=R;var Y=u.baseQueue,AA=F.pending;if(AA!==null){if(Y!==null){var GA=Y.next;Y.next=AA.next,AA.next=GA}f.baseQueue=Y=AA,F.pending=null}if(AA=u.baseState,Y===null)u.memoizedState=AA;else{f=Y.next;var ne=GA=null,Me=null,tt=f,bt=!1;do{var Wt=tt.lane&-536870913;if(Wt!==tt.lane?(Vn&Wt)===Wt:(wQ&Wt)===Wt){var Xt=tt.revertLane;if(Xt===0)Me!==null&&(Me=Me.next={lane:0,revertLane:0,action:tt.action,hasEagerState:tt.hasEagerState,eagerState:tt.eagerState,next:null}),Wt===Dy&&(bt=!0);else if((wQ&Xt)===Xt){tt=tt.next,Xt===Dy&&(bt=!0);continue}else Wt={lane:0,revertLane:tt.revertLane,action:tt.action,hasEagerState:tt.hasEagerState,eagerState:tt.eagerState,next:null},Me===null?(ne=Me=Wt,GA=AA):Me=Me.next=Wt,Dn.lanes|=Xt,MQ|=Xt;Wt=tt.action,ih&&R(AA,Wt),AA=tt.hasEagerState?tt.eagerState:R(AA,Wt)}else Xt={lane:Wt,revertLane:tt.revertLane,action:tt.action,hasEagerState:tt.hasEagerState,eagerState:tt.eagerState,next:null},Me===null?(ne=Me=Xt,GA=AA):Me=Me.next=Xt,Dn.lanes|=Wt,MQ|=Wt;tt=tt.next}while(tt!==null&&tt!==f);if(Me===null?GA=AA:Me.next=ne,!NI(AA,u.memoizedState)&&(zs=!0,bt&&(R=my,R!==null)))throw R;u.memoizedState=AA,u.baseState=GA,u.baseQueue=Me,F.lastRenderedState=AA}return Y===null&&(F.lanes=0),[u.memoizedState,F.dispatch]}function re(u){var f=KA(),R=f.queue;if(R===null)throw Error(n(311));R.lastRenderedReducer=u;var F=R.dispatch,Y=R.pending,AA=f.memoizedState;if(Y!==null){R.pending=null;var GA=Y=Y.next;do AA=u(AA,GA.action),GA=GA.next;while(GA!==Y);NI(AA,f.memoizedState)||(zs=!0),f.memoizedState=AA,f.baseQueue===null&&(f.baseState=AA),R.lastRenderedState=AA}return[AA,F]}function Qe(u,f,R){var F=Dn,Y=KA(),AA=og;if(AA){if(R===void 0)throw Error(n(407));R=R()}else R=f();var GA=!NI((Rg||Y).memoizedState,R);if(GA&&(Y.memoizedState=R,zs=!0),Y=Y.queue,fg(ye.bind(null,F,Y,u),[u]),Y.getSnapshot!==f||GA||os!==null&&os.memoizedState.tag&1){if(F.flags|=2048,vi(9,ge.bind(null,F,Y,R,f),{destroy:void 0},null),Og===null)throw Error(n(349));AA||wQ&60||HA(F,f,R)}return R}function HA(u,f,R){u.flags|=16384,u={getSnapshot:f,value:R},f=Dn.updateQueue,f===null?(f=$T(),Dn.updateQueue=f,f.stores=[u]):(R=f.stores,R===null?f.stores=[u]:R.push(u))}function ge(u,f,R,F){f.value=R,f.getSnapshot=F,Te(f)&&gt(u)}function ye(u,f,R){return R(function(){Te(f)&&gt(u)})}function Te(u){var f=u.getSnapshot;u=u.value;try{var R=f();return!NI(u,R)}catch{return!0}}function gt(u){var f=iA(u,2);f!==null&&fo(f,u,2)}function Qt(u){var f=vA();if(typeof u=="function"){var R=u;if(u=R(),ih){U(!0);try{R()}finally{U(!1)}}}return f.memoizedState=f.baseState=u,f.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:xe,lastRenderedState:u},f}function _e(u,f,R,F){return u.baseState=R,ve(u,Rg,typeof F=="function"?F:xe)}function Ze(u,f,R,F,Y){if(ot(u))throw Error(n(485));if(u=f.action,u!==null){var AA={payload:Y,action:u,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(GA){AA.listeners.push(GA)}};zi.T!==null?R(!0):AA.isTransition=!1,F(AA),R=f.pending,R===null?(AA.next=f.pending=AA,at(f,AA)):(AA.next=R.next,f.pending=R.next=AA)}}function at(u,f){var R=f.action,F=f.payload,Y=u.state;if(f.isTransition){var AA=zi.T,GA={};zi.T=GA;try{var ne=R(Y,F),Me=zi.S;Me!==null&&Me(GA,ne),Ai(u,f,ne)}catch(tt){yi(u,f,tt)}finally{zi.T=AA}}else try{AA=R(Y,F),Ai(u,f,AA)}catch(tt){yi(u,f,tt)}}function Ai(u,f,R){R!==null&&typeof R=="object"&&typeof R.then=="function"?R.then(function(F){Bi(u,f,F)},function(F){return yi(u,f,F)}):Bi(u,f,R)}function Bi(u,f,R){f.status="fulfilled",f.value=R,mt(f),u.state=R,f=u.pending,f!==null&&(R=f.next,R===f?u.pending=null:(R=R.next,f.next=R,at(u,R)))}function yi(u,f,R){var F=u.pending;if(u.pending=null,F!==null){F=F.next;do f.status="rejected",f.reason=R,mt(f),f=f.next;while(f!==F)}u.action=null}function mt(u){u=u.listeners;for(var f=0;f<u.length;f++)(0,u[f])()}function ct(u,f){return f}function fi(u,f){if(og){var R=Og.formState;if(R!==null){A:{var F=Dn;if(og){if(Ya){var Y=jwA(Ya,ul);if(Y){Ya=d9(Y),F=zwA(Y);break A}}fA(F)}F=!1}F&&(f=R[0])}}R=vA(),R.memoizedState=R.baseState=f,F={pending:null,lanes:0,dispatch:null,lastRenderedReducer:ct,lastRenderedState:f},R.queue=F,R=Vt.bind(null,Dn,F),F.dispatch=R,F=Qt(!1);var AA=Re.bind(null,Dn,!1,F.queue);return F=vA(),Y={state:f,dispatch:null,action:u,pending:null},F.queue=Y,R=Ze.bind(null,Dn,Y,AA,R),Y.dispatch=R,F.memoizedState=u,[f,R,!1]}function Yi(u){var f=KA();return si(f,Rg,u)}function si(u,f,R){f=ve(u,f,ct)[0],u=it(xe)[0],f=typeof f=="object"&&f!==null&&typeof f.then=="function"?WA(f):f;var F=KA(),Y=F.queue,AA=Y.dispatch;return R!==F.memoizedState&&(Dn.flags|=2048,vi(9,jt.bind(null,Y,R),{destroy:void 0},null)),[f,AA,u]}function jt(u,f){u.action=f}function Zt(u){var f=KA(),R=Rg;if(R!==null)return si(f,R,u);KA(),f=f.memoizedState,R=KA();var F=R.queue.dispatch;return R.memoizedState=u,[f,F,!1]}function vi(u,f,R,F){return u={tag:u,create:f,inst:R,deps:F,next:null},f=Dn.updateQueue,f===null&&(f=$T(),Dn.updateQueue=f),R=f.lastEffect,R===null?f.lastEffect=u.next=u:(F=R.next,R.next=u,u.next=F,f.lastEffect=u),u}function kn(){return KA().memoizedState}function gn(u,f,R,F){var Y=vA();Dn.flags|=u,Y.memoizedState=vi(1|f,R,{destroy:void 0},F===void 0?null:F)}function Ki(u,f,R,F){var Y=KA();F=F===void 0?null:F;var AA=Y.memoizedState.inst;Rg!==null&&F!==null&&He(F,Rg.memoizedState.deps)?Y.memoizedState=vi(f,R,AA,F):(Dn.flags|=u,Y.memoizedState=vi(1|f,R,AA,F))}function Tn(u,f){gn(8390656,8,u,f)}function fg(u,f){Ki(2048,8,u,f)}function Zi(u,f){return Ki(4,2,u,f)}function te(u,f){return Ki(4,4,u,f)}function Eg(u,f){if(typeof f=="function"){u=u();var R=f(u);return function(){typeof R=="function"?R():f(null)}}if(f!=null)return u=u(),f.current=u,function(){f.current=null}}function gi(u,f,R){R=R!=null?R.concat([u]):null,Ki(4,4,Eg.bind(null,f,u),R)}function Mg(){}function Hg(u,f){var R=KA();f=f===void 0?null:f;var F=R.memoizedState;return f!==null&&He(f,F[1])?F[0]:(R.memoizedState=[u,f],u)}function de(u,f){var R=KA();f=f===void 0?null:f;var F=R.memoizedState;if(f!==null&&He(f,F[1]))return F[0];if(F=u(),ih){U(!0);try{u()}finally{U(!1)}}return R.memoizedState=[F,f],F}function qe(u,f,R){return R===void 0||wQ&1073741824?u.memoizedState=f:(u.memoizedState=R,u=Ql(),Dn.lanes|=u,MQ|=u,R)}function OA(u,f,R,F){return NI(R,f)?R:ky.current!==null?(u=qe(u,R,F),NI(u,f)||(zs=!0),u):wQ&42?(u=Ql(),Dn.lanes|=u,MQ|=u,f):(zs=!0,u.memoizedState=R)}function Ae(u,f,R,F,Y){var AA=$d();qr(AA!==0&&8>AA?AA:8);var GA=zi.T,ne={};zi.T=ne,Re(u,!1,f,R);try{var Me=Y(),tt=zi.S;if(tt!==null&&tt(ne,Me),Me!==null&&typeof Me=="object"&&typeof Me.then=="function"){var bt=ie(Me,F);hA(u,f,bt,Xg(u))}else hA(u,f,F,Xg(u))}catch(Wt){hA(u,f,{then:function(){},status:"rejected",reason:Wt},Xg())}finally{qr(AA),zi.T=GA}}function Ke(u){var f=u.memoizedState;if(f!==null)return f;f={memoizedState:Ey,baseState:Ey,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:xe,lastRenderedState:Ey},next:null};var R={};return f.next={memoizedState:R,baseState:R,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:xe,lastRenderedState:R},next:null},u.memoizedState=f,u=u.alternate,u!==null&&(u.memoizedState=f),f}function Je(){return LA(Ah)}function pt(){return KA().memoizedState}function Tt(){return KA().memoizedState}function vt(u){for(var f=u.return;f!==null;){switch(f.tag){case 24:case 3:var R=Xg();u=NA(R);var F=EA(f,u,R);F!==null&&(fo(F,f,R),PA(F,f,R)),f={cache:Be()},u.payload=f;return}f=f.return}}function ei(u,f,R){var F=Xg();R={lane:F,revertLane:0,action:R,hasEagerState:!1,eagerState:null,next:null},ot(u)?kt(f,R):(R=tA(u,f,R,F),R!==null&&(fo(R,u,F),ht(R,f,F)))}function Vt(u,f,R){var F=Xg();hA(u,f,R,F)}function hA(u,f,R,F){var Y={lane:F,revertLane:0,action:R,hasEagerState:!1,eagerState:null,next:null};if(ot(u))kt(f,Y);else{var AA=u.alternate;if(u.lanes===0&&(AA===null||AA.lanes===0)&&(AA=f.lastRenderedReducer,AA!==null))try{var GA=f.lastRenderedState,ne=AA(GA,R);if(Y.hasEagerState=!0,Y.eagerState=ne,NI(ne,GA))return P(u,f,Y,0),Og===null&&H(),!1}catch{}finally{}if(R=tA(u,f,Y,F),R!==null)return fo(R,u,F),ht(R,f,F),!0}return!1}function Re(u,f,R,F){if(F={lane:2,revertLane:xA(),action:F,hasEagerState:!1,eagerState:null,next:null},ot(u)){if(f)throw Error(n(479))}else f=tA(u,R,F,2),f!==null&&fo(f,u,2)}function ot(u){var f=u.alternate;return u===Dn||f!==null&&f===Dn}function kt(u,f){My=JG=!0;var R=u.pending;R===null?f.next=f:(f.next=R.next,R.next=f),u.pending=f}function ht(u,f,R){if(R&4194176){var F=f.lanes;F&=u.pendingLanes,R|=F,f.lanes=R,J(u,R)}}function ee(u,f,R,F){f=u.memoizedState,R=R(F,f),R=R==null?f:RT({},f,R),u.memoizedState=R,u.lanes===0&&(u.updateQueue.baseState=R)}function je(u,f,R,F,Y,AA,GA){return u=u.stateNode,typeof u.shouldComponentUpdate=="function"?u.shouldComponentUpdate(F,AA,GA):f.prototype&&f.prototype.isPureReactComponent?!BA(R,F)||!BA(Y,AA):!0}function Ct(u,f,R,F){u=f.state,typeof f.componentWillReceiveProps=="function"&&f.componentWillReceiveProps(R,F),typeof f.UNSAFE_componentWillReceiveProps=="function"&&f.UNSAFE_componentWillReceiveProps(R,F),f.state!==u&&Aq.enqueueReplaceState(f,f.state,null)}function At(u,f){var R=f;if("ref"in f){R={};for(var F in f)F!=="ref"&&(R[F]=f[F])}if(u=u.defaultProps){R===f&&(R=RT({},R));for(var Y in u)R[Y]===void 0&&(R[Y]=u[Y])}return R}function zt(u,f){try{var R=u.onUncaughtError;R(f.value,{componentStack:f.stack})}catch(F){setTimeout(function(){throw F})}}function li(u,f,R){try{var F=u.onCaughtError;F(R.value,{componentStack:R.stack,errorBoundary:f.tag===1?f.stateNode:null})}catch(Y){setTimeout(function(){throw Y})}}function Ei(u,f,R){return R=NA(R),R.tag=3,R.payload={element:null},R.callback=function(){zt(u,f)},R}function ai(u){return u=NA(u),u.tag=3,u}function Hi(u,f,R,F){var Y=R.type.getDerivedStateFromError;if(typeof Y=="function"){var AA=F.value;u.payload=function(){return Y(AA)},u.callback=function(){li(f,R,F)}}var GA=R.stateNode;GA!==null&&typeof GA.componentDidCatch=="function"&&(u.callback=function(){li(f,R,F),typeof Y!="function"&&(NQ===null?NQ=new Set([this]):NQ.add(this));var ne=F.stack;this.componentDidCatch(F.value,{componentStack:ne!==null?ne:""})})}function gg(u,f,R,F,Y){if(R.flags|=32768,F!==null&&typeof F=="object"&&typeof F.then=="function"){if(f=R.alternate,f!==null&&Qc(f,R,Y,!0),R=pC.current,R!==null){switch(R.tag){case 13:return dl===null?DT():R.alternate===null&&Go===0&&(Go=3),R.flags&=-257,R.flags|=65536,R.lanes=Y,F===FG?R.flags|=16384:(f=R.updateQueue,f===null?R.updateQueue=new Set([F]):f.add(F),ST(u,F,Y)),!1;case 22:return R.flags|=65536,F===FG?R.flags|=16384:(f=R.updateQueue,f===null?(f={transitions:null,markerInstances:null,retryQueue:new Set([F])},R.updateQueue=f):(R=f.retryQueue,R===null?f.retryQueue=new Set([F]):R.add(F)),ST(u,F,Y)),!1}throw Error(n(435,R.tag))}return ST(u,F,Y),DT(),!1}if(og)return f=pC.current,f!==null?(!(f.flags&65536)&&(f.flags|=256),f.flags|=65536,f.lanes=Y,F!==PT&&(u=Error(n(422),{cause:F}),L(T(u,R)))):(F!==PT&&(f=Error(n(423),{cause:F}),L(T(f,R))),u=u.current.alternate,u.flags|=65536,Y&=-Y,u.lanes|=Y,F=T(F,R),Y=Ei(u.stateNode,F,Y),ZA(u,Y),Go!==4&&(Go=2)),!1;var AA=Error(n(520),{cause:F});if(AA=T(AA,R),o0===null?o0=[AA]:o0.push(AA),Go!==4&&(Go=2),f===null)return!0;F=T(F,R),R=f;do{switch(R.tag){case 3:return R.flags|=65536,u=Y&-Y,R.lanes|=u,u=Ei(R.stateNode,F,u),ZA(R,u),!1;case 1:if(f=R.type,AA=R.stateNode,(R.flags&128)===0&&(typeof f.getDerivedStateFromError=="function"||AA!==null&&typeof AA.componentDidCatch=="function"&&(NQ===null||!NQ.has(AA))))return R.flags|=65536,Y&=-Y,R.lanes|=Y,Y=ai(Y),Hi(Y,u,R,F),ZA(R,Y),!1}R=R.return}while(R!==null);return!1}function yn(u,f,R,F){f.child=u===null?b9(f,null,R,F):th(f,u.child,R,F)}function Rs(u,f,R,F,Y){R=R.render;var AA=f.ref;if("ref"in F){var GA={};for(var ne in F)ne!=="ref"&&(GA[ne]=F[ne])}else GA=F;return lA(f),F=Xe(u,f,R,GA,AA,Y),ne=Ce(),u!==null&&!zs?(VA(u,f,Y),Yo(u,f,Y)):(og&&ne&&eA(f),f.flags|=1,yn(u,f,F,Y),f.child)}function qo(u,f,R,F,Y){if(u===null){var AA=R.type;return typeof AA=="function"&&!wT(AA)&&AA.defaultProps===void 0&&R.compare===null?(f.tag=15,f.type=AA,eg(u,f,AA,F,Y)):(u=mG(R.type,null,F,f,f.mode,Y),u.ref=f.ref,u.return=f,f.child=u)}if(AA=u.child,!yI(u,Y)){var GA=AA.memoizedProps;if(R=R.compare,R=R!==null?R:BA,R(GA,F)&&u.ref===f.ref)return Yo(u,f,Y)}return f.flags|=1,u=pQ(AA,F),u.ref=f.ref,u.return=f,f.child=u}function eg(u,f,R,F,Y){if(u!==null){var AA=u.memoizedProps;if(BA(AA,F)&&u.ref===f.ref)if(zs=!1,f.pendingProps=F=AA,yI(u,Y))u.flags&131072&&(zs=!0);else return f.lanes=u.lanes,Yo(u,f,Y)}return Vg(u,f,R,F,Y)}function Gs(u,f,R){var F=f.pendingProps,Y=F.children,AA=(f.stateNode._pendingVisibility&2)!==0,GA=u!==null?u.memoizedState:null;if(Wg(u,f),F.mode==="hidden"||AA){if(f.flags&128){if(F=GA!==null?GA.baseLanes|R:R,u!==null){for(Y=f.child=u.child,AA=0;Y!==null;)AA=AA|Y.lanes|Y.childLanes,Y=Y.sibling;f.childLanes=AA&~F}else f.childLanes=0,f.child=null;return bs(u,f,F,R)}if(R&536870912)f.memoizedState={baseLanes:0,cachePool:null},u!==null&&rt(f,GA!==null?GA.cachePool:null),GA!==null?ci(f,GA):ke(),dt(f);else return f.lanes=f.childLanes=536870912,bs(u,f,GA!==null?GA.baseLanes|R:R,R)}else GA!==null?(rt(f,GA.cachePool),ci(f,GA),Ht(),f.memoizedState=null):(u!==null&&rt(f,null),ke(),Ht());return yn(u,f,Y,R),f.child}function bs(u,f,R,F){var Y=Le();return Y=Y===null?null:{parent:LB?No._currentValue:No._currentValue2,pool:Y},f.memoizedState={baseLanes:R,cachePool:Y},u!==null&&rt(f,null),ke(),dt(f),u!==null&&Qc(u,f,F,!0),null}function Wg(u,f){var R=f.ref;if(R===null)u!==null&&u.ref!==null&&(f.flags|=2097664);else{if(typeof R!="function"&&typeof R!="object")throw Error(n(284));(u===null||u.ref!==R)&&(f.flags|=2097664)}}function Vg(u,f,R,F,Y){return lA(f),R=Xe(u,f,R,F,void 0,Y),F=Ce(),u!==null&&!zs?(VA(u,f,Y),Yo(u,f,Y)):(og&&F&&eA(f),f.flags|=1,yn(u,f,R,Y),f.child)}function rC(u,f,R,F,Y,AA){return lA(f),f.updateQueue=null,R=kA(f,F,R,Y),St(u),F=Ce(),u!==null&&!zs?(VA(u,f,AA),Yo(u,f,AA)):(og&&F&&eA(f),f.flags|=1,yn(u,f,R,AA),f.child)}function sr(u,f,R,F,Y){if(lA(f),f.stateNode===null){var AA=uy,GA=R.contextType;typeof GA=="object"&&GA!==null&&(AA=LA(GA)),AA=new R(F,AA),f.memoizedState=AA.state!==null&&AA.state!==void 0?AA.state:null,AA.updater=Aq,f.stateNode=AA,AA._reactInternals=f,AA=f.stateNode,AA.props=F,AA.state=f.memoizedState,AA.refs={},he(f),GA=R.contextType,AA.context=typeof GA=="object"&&GA!==null?LA(GA):uy,AA.state=f.memoizedState,GA=R.getDerivedStateFromProps,typeof GA=="function"&&(ee(f,R,GA,F),AA.state=f.memoizedState),typeof R.getDerivedStateFromProps=="function"||typeof AA.getSnapshotBeforeUpdate=="function"||typeof AA.UNSAFE_componentWillMount!="function"&&typeof AA.componentWillMount!="function"||(GA=AA.state,typeof AA.componentWillMount=="function"&&AA.componentWillMount(),typeof AA.UNSAFE_componentWillMount=="function"&&AA.UNSAFE_componentWillMount(),GA!==AA.state&&Aq.enqueueReplaceState(AA,AA.state,null),Ie(f,F,AA,Y),FA(),AA.state=f.memoizedState),typeof AA.componentDidMount=="function"&&(f.flags|=4194308),F=!0}else if(u===null){AA=f.stateNode;var ne=f.memoizedProps,Me=At(R,ne);AA.props=Me;var tt=AA.context,bt=R.contextType;GA=uy,typeof bt=="object"&&bt!==null&&(GA=LA(bt));var Wt=R.getDerivedStateFromProps;bt=typeof Wt=="function"||typeof AA.getSnapshotBeforeUpdate=="function",ne=f.pendingProps!==ne,bt||typeof AA.UNSAFE_componentWillReceiveProps!="function"&&typeof AA.componentWillReceiveProps!="function"||(ne||tt!==GA)&&Ct(f,AA,F,GA),SQ=!1;var Xt=f.memoizedState;AA.state=Xt,Ie(f,F,AA,Y),FA(),tt=f.memoizedState,ne||Xt!==tt||SQ?(typeof Wt=="function"&&(ee(f,R,Wt,F),tt=f.memoizedState),(Me=SQ||je(f,R,Me,F,Xt,tt,GA))?(bt||typeof AA.UNSAFE_componentWillMount!="function"&&typeof AA.componentWillMount!="function"||(typeof AA.componentWillMount=="function"&&AA.componentWillMount(),typeof AA.UNSAFE_componentWillMount=="function"&&AA.UNSAFE_componentWillMount()),typeof AA.componentDidMount=="function"&&(f.flags|=4194308)):(typeof AA.componentDidMount=="function"&&(f.flags|=4194308),f.memoizedProps=F,f.memoizedState=tt),AA.props=F,AA.state=tt,AA.context=GA,F=Me):(typeof AA.componentDidMount=="function"&&(f.flags|=4194308),F=!1)}else{AA=f.stateNode,le(u,f),GA=f.memoizedProps,bt=At(R,GA),AA.props=bt,Wt=f.pendingProps,Xt=AA.context,tt=R.contextType,Me=uy,typeof tt=="object"&&tt!==null&&(Me=LA(tt)),ne=R.getDerivedStateFromProps,(tt=typeof ne=="function"||typeof AA.getSnapshotBeforeUpdate=="function")||typeof AA.UNSAFE_componentWillReceiveProps!="function"&&typeof AA.componentWillReceiveProps!="function"||(GA!==Wt||Xt!==Me)&&Ct(f,AA,F,Me),SQ=!1,Xt=f.memoizedState,AA.state=Xt,Ie(f,F,AA,Y),FA();var on=f.memoizedState;GA!==Wt||Xt!==on||SQ||u!==null&&u.dependencies!==null&&IC(u.dependencies)?(typeof ne=="function"&&(ee(f,R,ne,F),on=f.memoizedState),(bt=SQ||je(f,R,bt,F,Xt,on,Me)||u!==null&&u.dependencies!==null&&IC(u.dependencies))?(tt||typeof AA.UNSAFE_componentWillUpdate!="function"&&typeof AA.componentWillUpdate!="function"||(typeof AA.componentWillUpdate=="function"&&AA.componentWillUpdate(F,on,Me),typeof AA.UNSAFE_componentWillUpdate=="function"&&AA.UNSAFE_componentWillUpdate(F,on,Me)),typeof AA.componentDidUpdate=="function"&&(f.flags|=4),typeof AA.getSnapshotBeforeUpdate=="function"&&(f.flags|=1024)):(typeof AA.componentDidUpdate!="function"||GA===u.memoizedProps&&Xt===u.memoizedState||(f.flags|=4),typeof AA.getSnapshotBeforeUpdate!="function"||GA===u.memoizedProps&&Xt===u.memoizedState||(f.flags|=1024),f.memoizedProps=F,f.memoizedState=on),AA.props=F,AA.state=on,AA.context=Me,F=bt):(typeof AA.componentDidUpdate!="function"||GA===u.memoizedProps&&Xt===u.memoizedState||(f.flags|=4),typeof AA.getSnapshotBeforeUpdate!="function"||GA===u.memoizedProps&&Xt===u.memoizedState||(f.flags|=1024),F=!1)}return AA=F,Wg(u,f),F=(f.flags&128)!==0,AA||F?(AA=f.stateNode,R=F&&typeof R.getDerivedStateFromError!="function"?null:AA.render(),f.flags|=1,u!==null&&F?(f.child=th(f,u.child,null,Y),f.child=th(f,null,R,Y)):yn(u,f,R,Y),f.memoizedState=AA.state,u=f.child):u=Yo(u,f,Y),u}function UB(u,f,R,F){return $(),f.flags|=256,yn(u,f,R,F),f.child}function pI(u){return{baseLanes:u,cachePool:ft()}}function fI(u,f,R){return u=u!==null?u.childLanes&~R:0,f&&(u|=fC),u}function vB(u,f,R){var F=f.pendingProps,Y=!1,AA=(f.flags&128)!==0,GA;if((GA=AA)||(GA=u!==null&&u.memoizedState===null?!1:(vs.current&2)!==0),GA&&(Y=!0,f.flags&=-129),GA=(f.flags&32)!==0,f.flags&=-33,u===null){if(og){if(Y?Ut(f):Ht(),og){var ne=Ya,Me;(Me=ne)&&(ne=$wA(ne,ul),ne!==null?(f.memoizedState={dehydrated:ne,treeContext:eh!==null?{id:xB,overflow:TB}:null,retryLane:536870912},Me=t(18,null,null,0),Me.stateNode=ne,Me.return=f,f.child=Me,lr=f,Ya=null,Me=!0):Me=!1),Me||fA(f)}if(ne=f.memoizedState,ne!==null&&(ne=ne.dehydrated,ne!==null))return TT(ne)?f.lanes=16:f.lanes=536870912,null;Ft(f)}return ne=F.children,F=F.fallback,Y?(Ht(),Y=f.mode,ne=ll({mode:"hidden",children:ne},Y),F=Xd(F,Y,R,null),ne.return=f,F.return=f,ne.sibling=F,f.child=ne,Y=f.child,Y.memoizedState=pI(R),Y.childLanes=fI(u,GA,R),f.memoizedState=eq,F):(Ut(f),Ps(f,ne))}if(Me=u.memoizedState,Me!==null&&(ne=Me.dehydrated,ne!==null)){if(AA)f.flags&256?(Ut(f),f.flags&=-257,f=Pd(u,f,R)):f.memoizedState!==null?(Ht(),f.child=u.child,f.flags|=128,f=null):(Ht(),Y=F.fallback,ne=f.mode,F=ll({mode:"visible",children:F.children},ne),Y=Xd(Y,ne,R,null),Y.flags|=2,F.return=f,Y.return=f,F.sibling=Y,f.child=F,th(f,u.child,null,R),F=f.child,F.memoizedState=pI(R),F.childLanes=fI(u,GA,R),f.memoizedState=eq,f=Y);else if(Ut(f),TT(ne))GA=OwA(ne).digest,F=Error(n(419)),F.stack="",F.digest=GA,L({value:F,source:null,stack:null}),f=Pd(u,f,R);else if(zs||Qc(u,f,R,!1),GA=(R&u.childLanes)!==0,zs||GA){if(GA=Og,GA!==null){if(F=R&-R,F&42)F=1;else switch(F){case 2:F=1;break;case 8:F=4;break;case 32:F=16;break;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:case 4194304:case 8388608:case 16777216:case 33554432:F=64;break;case 268435456:F=134217728;break;default:F=0}if(F=F&(GA.suspendedLanes|R)?0:F,F!==0&&F!==Me.retryLane)throw Me.retryLane=F,iA(u,F),fo(GA,u,F),v9}xT(ne)||DT(),f=Pd(u,f,R)}else xT(ne)?(f.flags|=128,f.child=u.child,f=zSA.bind(null,u),PwA(ne,f),f=null):(u=Me.treeContext,EC&&(Ya=WwA(ne),lr=f,og=!0,fc=null,ul=!1,u!==null&&(uC[dC++]=xB,uC[dC++]=TB,uC[dC++]=eh,xB=u.id,TB=u.overflow,eh=f)),f=Ps(f,F.children),f.flags|=4096);return f}return Y?(Ht(),Y=F.fallback,ne=f.mode,Me=u.child,AA=Me.sibling,F=pQ(Me,{mode:"hidden",children:F.children}),F.subtreeFlags=Me.subtreeFlags&31457280,AA!==null?Y=pQ(AA,Y):(Y=Xd(Y,ne,R,null),Y.flags|=2),Y.return=f,F.return=f,F.sibling=Y,f.child=F,F=Y,Y=f.child,ne=u.child.memoizedState,ne===null?ne=pI(R):(Me=ne.cachePool,Me!==null?(AA=LB?No._currentValue:No._currentValue2,Me=Me.parent!==AA?{parent:AA,pool:AA}:Me):Me=ft(),ne={baseLanes:ne.baseLanes|R,cachePool:Me}),Y.memoizedState=ne,Y.childLanes=fI(u,GA,R),f.memoizedState=eq,F):(Ut(f),R=u.child,u=R.sibling,R=pQ(R,{mode:"visible",children:F.children}),R.return=f,R.sibling=null,u!==null&&(GA=f.deletions,GA===null?(f.deletions=[u],f.flags|=16):GA.push(u)),f.child=R,f.memoizedState=null,R)}function Ps(u,f){return f=ll({mode:"visible",children:f},u.mode),f.return=u,u.child=f}function ll(u,f){return ZV(u,f,0,null)}function Pd(u,f,R){return th(f,u.child,null,R),u=Ps(f,f.pendingProps.children),u.flags|=2,f.memoizedState=null,u}function KB(u,f,R){u.lanes|=f;var F=u.alternate;F!==null&&(F.lanes|=f),rr(u.return,f,R)}function jd(u,f,R,F,Y){var AA=u.memoizedState;AA===null?u.memoizedState={isBackwards:f,rendering:null,renderingStartTime:0,last:F,tail:R,tailMode:Y}:(AA.isBackwards=f,AA.rendering=null,AA.renderingStartTime=0,AA.last=F,AA.tail=R,AA.tailMode=Y)}function ry(u,f,R){var F=f.pendingProps,Y=F.revealOrder,AA=F.tail;if(yn(u,f,F.children,R),F=vs.current,F&2)F=F&1|2,f.flags|=128;else{if(u!==null&&u.flags&128)A:for(u=f.child;u!==null;){if(u.tag===13)u.memoizedState!==null&&KB(u,R,f);else if(u.tag===19)KB(u,R,f);else if(u.child!==null){u.child.return=u,u=u.child;continue}if(u===f)break A;for(;u.sibling===null;){if(u.return===null||u.return===f)break A;u=u.return}u.sibling.return=u.return,u=u.sibling}F&=1}switch(y(vs,F),Y){case"forwards":for(R=f.child,Y=null;R!==null;)u=R.alternate,u!==null&&Jt(u)===null&&(Y=R),R=R.sibling;R=Y,R===null?(Y=f.child,f.child=null):(Y=R.sibling,R.sibling=null),jd(f,!1,Y,R,AA);break;case"backwards":for(R=null,Y=f.child,f.child=null;Y!==null;){if(u=Y.alternate,u!==null&&Jt(u)===null){f.child=Y;break}u=Y.sibling,Y.sibling=R,R=Y,Y=u}jd(f,!0,R,null,AA);break;case"together":jd(f,!1,null,null,void 0);break;default:f.memoizedState=null}return f.child}function Yo(u,f,R){if(u!==null&&(f.dependencies=u.dependencies),MQ|=f.lanes,!(R&f.childLanes))if(u!==null){if(Qc(u,f,R,!1),(R&f.childLanes)===0)return null}else return null;if(u!==null&&f.child!==u.child)throw Error(n(153));if(f.child!==null){for(u=f.child,R=pQ(u,u.pendingProps),f.child=R,R.return=f;u.sibling!==null;)u=u.sibling,R=R.sibling=pQ(u,u.pendingProps),R.return=f;R.sibling=null}return f.child}function yI(u,f){return u.lanes&f?!0:(u=u.dependencies,!!(u!==null&&IC(u)))}function Hw(u,f,R){switch(f.tag){case 3:sA(f,f.stateNode.containerInfo),ar(f,No,u.memoizedState.cache),$();break;case 27:case 5:gA(f);break;case 4:sA(f,f.stateNode.containerInfo);break;case 10:ar(f,f.type,f.memoizedProps.value);break;case 13:var F=f.memoizedState;if(F!==null)return F.dehydrated!==null?(Ut(f),f.flags|=128,null):R&f.child.childLanes?vB(u,f,R):(Ut(f),u=Yo(u,f,R),u!==null?u.sibling:null);Ut(f);break;case 19:var Y=(u.flags&128)!==0;if(F=(R&f.childLanes)!==0,F||(Qc(u,f,R,!1),F=(R&f.childLanes)!==0),Y){if(F)return ry(u,f,R);f.flags|=128}if(Y=f.memoizedState,Y!==null&&(Y.rendering=null,Y.tail=null,Y.lastEffect=null),y(vs,vs.current),F)break;return null;case 22:case 23:return f.lanes=0,Gs(u,f,R);case 24:ar(f,No,u.memoizedState.cache)}return Yo(u,f,R)}function DI(u,f,R){if(u!==null)if(u.memoizedProps!==f.pendingProps)zs=!0;else{if(!yI(u,R)&&!(f.flags&128))return zs=!1,Hw(u,f,R);zs=!!(u.flags&131072)}else zs=!1,og&&f.flags&1048576&&Z(f,bG,f.index);switch(f.lanes=0,f.tag){case 16:A:{u=f.pendingProps;var F=f.elementType,Y=F._init;if(F=Y(F._payload),f.type=F,typeof F=="function")wT(F)?(u=At(F,u),f.tag=1,f=sr(null,f,F,u,R)):(f.tag=0,f=Vg(null,f,F,u,R));else{if(F!=null){if(Y=F.$$typeof,Y===bT){f.tag=11,f=Rs(null,f,F,u,R);break A}else if(Y===KT){f.tag=14,f=qo(null,f,F,u,R);break A}}throw f=o(F)||F,Error(n(306,f,""))}}return f;case 0:return Vg(u,f,f.type,f.pendingProps,R);case 1:return F=f.type,Y=At(F,f.pendingProps),sr(u,f,F,Y,R);case 3:A:{if(sA(f,f.stateNode.containerInfo),u===null)throw Error(n(387));var AA=f.pendingProps;Y=f.memoizedState,F=Y.element,le(u,f),Ie(f,AA,null,R);var GA=f.memoizedState;if(AA=GA.cache,ar(f,No,AA),AA!==Y.cache&&mI(f,[No],R,!0),FA(),AA=GA.element,EC&&Y.isDehydrated)if(Y={element:AA,isDehydrated:!1,cache:GA.cache},f.updateQueue.baseState=Y,f.memoizedState=Y,f.flags&256){f=UB(u,f,AA,R);break A}else if(AA!==F){F=T(Error(n(424)),f),L(F),f=UB(u,f,AA,R);break A}else for(EC&&(Ya=ZwA(f.stateNode.containerInfo),lr=f,og=!0,fc=null,ul=!0),R=b9(f,null,AA,R),f.child=R;R;)R.flags=R.flags&-3|4096,R=R.sibling;else{if($(),AA===F){f=Yo(u,f,R);break A}yn(u,f,AA,R)}f=f.child}return f;case 26:if(QC)return Wg(u,f),u===null?(R=y9(f.type,null,f.pendingProps,null))?f.memoizedState=R:og||(f.stateNode=C0A(f.type,f.pendingProps,mQ.current,f)):f.memoizedState=y9(f.type,u.memoizedProps,f.pendingProps,u.memoizedState),null;case 27:if(qa)return gA(f),u===null&&qa&&og&&(F=f.stateNode=M9(f.type,f.pendingProps,mQ.current,Qa.current,!1),lr=f,ul=!0,Ya=h9(F)),F=f.pendingProps.children,u!==null||og?yn(u,f,F,R):f.child=th(f,null,F,R),Wg(u,f),f.child;case 5:return u===null&&og&&(a0A(f.type,f.pendingProps,Qa.current),(Y=F=Ya)&&(F=VwA(F,f.type,f.pendingProps,ul),F!==null?(f.stateNode=F,lr=f,Ya=h9(F),ul=!1,Y=!0):Y=!1),Y||fA(f)),gA(f),Y=f.type,AA=f.pendingProps,GA=u!==null?u.memoizedProps:null,F=AA.children,kG(Y,AA)?F=null:GA!==null&&kG(Y,GA)&&(f.flags|=32),f.memoizedState!==null&&(Y=Xe(u,f,se,null,null,R),LB?Ah._currentValue=Y:Ah._currentValue2=Y),Wg(u,f),yn(u,f,F,R),f.child;case 6:return u===null&&og&&(r0A(f.pendingProps,Qa.current),(u=R=Ya)&&(R=XwA(R,f.pendingProps,ul),R!==null?(f.stateNode=R,lr=f,Ya=null,u=!0):u=!1),u||fA(f)),null;case 13:return vB(u,f,R);case 4:return sA(f,f.stateNode.containerInfo),F=f.pendingProps,u===null?f.child=th(f,null,F,R):yn(u,f,F,R),f.child;case 11:return Rs(u,f,f.type,f.pendingProps,R);case 7:return yn(u,f,f.pendingProps,R),f.child;case 8:return yn(u,f,f.pendingProps.children,R),f.child;case 12:return yn(u,f,f.pendingProps.children,R),f.child;case 10:return F=f.pendingProps,ar(f,f.type,F.value),yn(u,f,F.children,R),f.child;case 9:return Y=f.type._context,F=f.pendingProps.children,lA(f),Y=LA(Y),F=F(Y),f.flags|=1,yn(u,f,F,R),f.child;case 14:return qo(u,f,f.type,f.pendingProps,R);case 15:return eg(u,f,f.type,f.pendingProps,R);case 19:return ry(u,f,R);case 22:return Gs(u,f,R);case 24:return lA(f),F=LA(No),u===null?(Y=Le(),Y===null&&(Y=Og,AA=Be(),Y.pooledCache=AA,AA.refCount++,AA!==null&&(Y.pooledCacheLanes|=R),Y=AA),f.memoizedState={parent:F,cache:Y},he(f),ar(f,No,Y)):(u.lanes&R&&(le(u,f),Ie(f,null,null,R),FA()),Y=u.memoizedState,AA=f.memoizedState,Y.parent!==F?(Y={parent:F,cache:F},f.memoizedState=Y,f.lanes===0&&(f.memoizedState=f.updateQueue.baseState=Y),ar(f,No,F)):(F=AA.cache,ar(f,No,F),F!==Y.cache&&mI(f,[No],R,!0))),yn(u,f,f.pendingProps.children,R),f.child;case 29:throw f.pendingProps}throw Error(n(156,f.tag))}function ar(u,f,R){LB?(y(xG,f._currentValue),f._currentValue=R):(y(xG,f._currentValue2),f._currentValue2=R)}function Fa(u){var f=xG.current;LB?u._currentValue=f:u._currentValue2=f,p(xG)}function rr(u,f,R){for(;u!==null;){var F=u.alternate;if((u.childLanes&f)!==f?(u.childLanes|=f,F!==null&&(F.childLanes|=f)):F!==null&&(F.childLanes&f)!==f&&(F.childLanes|=f),u===R)break;u=u.return}}function mI(u,f,R,F){var Y=u.child;for(Y!==null&&(Y.return=u);Y!==null;){var AA=Y.dependencies;if(AA!==null){var GA=Y.child;AA=AA.firstContext;A:for(;AA!==null;){var ne=AA;AA=Y;for(var Me=0;Me<f.length;Me++)if(ne.context===f[Me]){AA.lanes|=R,ne=AA.alternate,ne!==null&&(ne.lanes|=R),rr(AA.return,R,u),F||(GA=null);break A}AA=ne.next}}else if(Y.tag===18){if(GA=Y.return,GA===null)throw Error(n(341));GA.lanes|=R,AA=GA.alternate,AA!==null&&(AA.lanes|=R),rr(GA,R,u),GA=null}else GA=Y.child;if(GA!==null)GA.return=Y;else for(GA=Y;GA!==null;){if(GA===u){GA=null;break}if(Y=GA.sibling,Y!==null){Y.return=GA.return,GA=Y;break}GA=GA.return}Y=GA}}function Qc(u,f,R,F){u=null;for(var Y=f,AA=!1;Y!==null;){if(!AA){if(Y.flags&524288)AA=!0;else if(Y.flags&262144)break}if(Y.tag===10){var GA=Y.alternate;if(GA===null)throw Error(n(387));if(GA=GA.memoizedProps,GA!==null){var ne=Y.type;NI(Y.pendingProps.value,GA.value)||(u!==null?u.push(ne):u=[ne])}}else if(Y===UG.current){if(GA=Y.alternate,GA===null)throw Error(n(387));GA.memoizedState.memoizedState!==Y.memoizedState.memoizedState&&(u!==null?u.push(Ah):u=[Ah])}Y=Y.return}u!==null&&mI(f,u,R,F),f.flags|=262144}function IC(u){for(u=u.firstContext;u!==null;){var f=u.context;if(!NI(LB?f._currentValue:f._currentValue2,u.memoizedValue))return!0;u=u.next}return!1}function lA(u){oh=u,qB=null,u=u.dependencies,u!==null&&(u.firstContext=null)}function LA(u){return De(oh,u)}function ae(u,f){return oh===null&&lA(u),De(u,f)}function De(u,f){var R=LB?f._currentValue:f._currentValue2;if(f={context:f,memoizedValue:R,next:null},qB===null){if(u===null)throw Error(n(308));qB=f,u.dependencies={lanes:0,firstContext:f},u.flags|=524288}else qB=qB.next=f;return R}function Be(){return{controller:new M0A,data:new Map,refCount:0}}function Fe(u){u.refCount--,u.refCount===0&&N0A(R0A,function(){u.controller.abort()})}function Le(){var u=sh.current;return u!==null?u:Og.pooledCache}function rt(u,f){f===null?y(sh,sh.current):y(sh,f.pool)}function ft(){var u=Le();return u===null?null:{parent:LB?No._currentValue:No._currentValue2,pool:u}}function En(u){u.flags|=4}function rg(u,f){if(u!==null&&u.child===f.child)return!1;if(f.flags&16)return!0;for(u=f.child;u!==null;){if(u.flags&13878||u.subtreeFlags&13878)return!0;u=u.sibling}return!1}function qn(u,f,R,F){if(Ta)for(R=f.child;R!==null;){if(R.tag===5||R.tag===6)JT(u,R.stateNode);else if(!(R.tag===4||qa&&R.tag===27)&&R.child!==null){R.child.return=R,R=R.child;continue}if(R===f)break;for(;R.sibling===null;){if(R.return===null||R.return===f)return;R=R.return}R.sibling.return=R.return,R=R.sibling}else if(DQ)for(var Y=f.child;Y!==null;){if(Y.tag===5){var AA=Y.stateNode;R&&F&&(AA=Q9(AA,Y.type,Y.memoizedProps)),JT(u,AA)}else if(Y.tag===6)AA=Y.stateNode,R&&F&&(AA=u9(AA,Y.memoizedProps)),JT(u,AA);else if(Y.tag!==4){if(Y.tag===22&&Y.memoizedState!==null)AA=Y.child,AA!==null&&(AA.return=Y),qn(u,Y,!0,!0);else if(Y.child!==null){Y.child.return=Y,Y=Y.child;continue}}if(Y===f)break;for(;Y.sibling===null;){if(Y.return===null||Y.return===f)return;Y=Y.return}Y.sibling.return=Y.return,Y=Y.sibling}}function Ig(u,f,R,F){if(DQ)for(var Y=f.child;Y!==null;){if(Y.tag===5){var AA=Y.stateNode;R&&F&&(AA=Q9(AA,Y.type,Y.memoizedProps)),B9(u,AA)}else if(Y.tag===6)AA=Y.stateNode,R&&F&&(AA=u9(AA,Y.memoizedProps)),B9(u,AA);else if(Y.tag!==4){if(Y.tag===22&&Y.memoizedState!==null)AA=Y.child,AA!==null&&(AA.return=Y),Ig(u,Y,!(Y.memoizedProps!==null&&Y.memoizedProps.mode==="manual"),!0);else if(Y.child!==null){Y.child.return=Y,Y=Y.child;continue}}if(Y===f)break;for(;Y.sibling===null;){if(Y.return===null||Y.return===f)return;Y=Y.return}Y.sibling.return=Y.return,Y=Y.sibling}}function Us(u,f){if(DQ&&rg(u,f)){u=f.stateNode;var R=u.containerInfo,F=l9();Ig(F,f,!1,!1),u.pendingChildren=F,En(f),HwA(R,F)}}function ao(u,f,R,F){if(Ta)u.memoizedProps!==F&&En(f);else if(DQ){var Y=u.stateNode,AA=u.memoizedProps;if((u=rg(u,f))||AA!==F){var GA=Qa.current;AA=YwA(Y,R,AA,F,!u,null),AA===Y?f.stateNode=Y:(s9(AA,R,F,GA)&&En(f),f.stateNode=AA,u?qn(AA,f,!1,!1):En(f))}else f.stateNode=Y}}function Yn(u,f,R){if(uwA(f,R)){if(u.flags|=16777216,!I9(f,R))if(hQ())u.flags|=8192;else throw Sy=FG,XT}else u.flags&=-16777217}function Qn(u,f){if(l0A(f)){if(u.flags|=16777216,!k9(f))if(hQ())u.flags|=8192;else throw Sy=FG,XT}else u.flags&=-16777217}function Ng(u,f){f!==null&&(u.flags|=4),u.flags&16384&&(f=u.tag!==22?M():536870912,u.lanes|=f,by|=f)}function po(u,f){if(!og)switch(u.tailMode){case"hidden":f=u.tail;for(var R=null;f!==null;)f.alternate!==null&&(R=f),f=f.sibling;R===null?u.tail=null:R.sibling=null;break;case"collapsed":R=u.tail;for(var F=null;R!==null;)R.alternate!==null&&(F=R),R=R.sibling;F===null?f||u.tail===null?u.tail=null:u.tail.sibling=null:F.sibling=null}}function mi(u){var f=u.alternate!==null&&u.alternate.child===u.child,R=0,F=0;if(f)for(var Y=u.child;Y!==null;)R|=Y.lanes|Y.childLanes,F|=Y.subtreeFlags&31457280,F|=Y.flags&31457280,Y.return=u,Y=Y.sibling;else for(Y=u.child;Y!==null;)R|=Y.lanes|Y.childLanes,F|=Y.subtreeFlags,F|=Y.flags,Y.return=u,Y=Y.sibling;return u.subtreeFlags|=F,u.childLanes=R,f}function Di(u,f,R){var F=f.pendingProps;switch(aA(f),f.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return mi(f),null;case 1:return mi(f),null;case 3:return R=f.stateNode,F=null,u!==null&&(F=u.memoizedState.cache),f.memoizedState.cache!==F&&(f.flags|=2048),Fa(No),pA(),R.pendingContext&&(R.context=R.pendingContext,R.pendingContext=null),(u===null||u.child===null)&&(W(f)?En(f):u===null||u.memoizedState.isDehydrated&&!(f.flags&256)||(f.flags|=1024,fc!==null&&(lC(fc),fc=null))),Us(u,f),mi(f),null;case 26:if(QC){R=f.type;var Y=f.memoizedState;return u===null?(En(f),Y!==null?(mi(f),Qn(f,Y)):(mi(f),Yn(f,R,F))):Y?Y!==u.memoizedState?(En(f),mi(f),Qn(f,Y)):(mi(f),f.flags&=-16777217):(Ta?u.memoizedProps!==F&&En(f):ao(u,f,R,F),mi(f),Yn(f,R,F)),null}case 27:if(qa){if(yA(f),R=mQ.current,Y=f.type,u!==null&&f.stateNode!=null)Ta?u.memoizedProps!==F&&En(f):ao(u,f,Y,F);else{if(!F){if(f.stateNode===null)throw Error(n(166));return mi(f),null}u=Qa.current,W(f)?RA(f,u):(u=M9(Y,F,R,u,!0),f.stateNode=u,En(f))}return mi(f),null}case 5:if(yA(f),R=f.type,u!==null&&f.stateNode!=null)ao(u,f,R,F);else{if(!F){if(f.stateNode===null)throw Error(n(166));return mi(f),null}u=Qa.current,W(f)?RA(f,u):(Y=IwA(R,F,mQ.current,u,f),qn(Y,f,!1,!1),f.stateNode=Y,s9(Y,R,F,u)&&En(f))}return mi(f),Yn(f,f.type,f.pendingProps),null;case 6:if(u&&f.stateNode!=null)R=u.memoizedProps,Ta?R!==F&&En(f):DQ&&(R!==F?(f.stateNode=a9(F,mQ.current,Qa.current,f),En(f)):f.stateNode=u.stateNode);else{if(typeof F!="string"&&f.stateNode===null)throw Error(n(166));if(u=mQ.current,R=Qa.current,W(f)){if(!EC)throw Error(n(176));if(u=f.stateNode,R=f.memoizedProps,F=null,Y=lr,Y!==null)switch(Y.tag){case 27:case 5:F=Y.memoizedProps}e0A(u,R,f,F)||fA(f)}else f.stateNode=a9(F,u,R,f)}return mi(f),null;case 13:if(F=f.memoizedState,u===null||u.memoizedState!==null&&u.memoizedState.dehydrated!==null){if(Y=W(f),F!==null&&F.dehydrated!==null){if(u===null){if(!Y)throw Error(n(318));if(!EC)throw Error(n(344));if(Y=f.memoizedState,Y=Y!==null?Y.dehydrated:null,!Y)throw Error(n(317));t0A(Y,f)}else $(),!(f.flags&128)&&(f.memoizedState=null),f.flags|=4;mi(f),Y=!1}else fc!==null&&(lC(fc),fc=null),Y=!0;if(!Y)return f.flags&256?(Ft(f),f):(Ft(f),null)}if(Ft(f),f.flags&128)return f.lanes=R,f;if(R=F!==null,u=u!==null&&u.memoizedState!==null,R){F=f.child,Y=null,F.alternate!==null&&F.alternate.memoizedState!==null&&F.alternate.memoizedState.cachePool!==null&&(Y=F.alternate.memoizedState.cachePool.pool);var AA=null;F.memoizedState!==null&&F.memoizedState.cachePool!==null&&(AA=F.memoizedState.cachePool.pool),AA!==Y&&(F.flags|=2048)}return R!==u&&R&&(f.child.flags|=8192),Ng(f,f.updateQueue),mi(f),null;case 4:return pA(),Us(u,f),u===null&&lwA(f.stateNode.containerInfo),mi(f),null;case 10:return Fa(f.type),mi(f),null;case 19:if(p(vs),Y=f.memoizedState,Y===null)return mi(f),null;if(F=(f.flags&128)!==0,AA=Y.rendering,AA===null)if(F)po(Y,!1);else{if(Go!==0||u!==null&&u.flags&128)for(u=f.child;u!==null;){if(AA=Jt(u),AA!==null){for(f.flags|=128,po(Y,!1),u=AA.updateQueue,f.updateQueue=u,Ng(f,u),f.subtreeFlags=0,u=R,R=f.child;R!==null;)zV(R,u),R=R.sibling;return y(vs,vs.current&1|2),f.child}u=u.sibling}Y.tail!==null&&pc()>s0&&(f.flags|=128,F=!0,po(Y,!1),f.lanes=4194304)}else{if(!F)if(u=Jt(AA),u!==null){if(f.flags|=128,F=!0,u=u.updateQueue,f.updateQueue=u,Ng(f,u),po(Y,!0),Y.tail===null&&Y.tailMode==="hidden"&&!AA.alternate&&!og)return mi(f),null}else 2*pc()-Y.renderingStartTime>s0&&R!==536870912&&(f.flags|=128,F=!0,po(Y,!1),f.lanes=4194304);Y.isBackwards?(AA.sibling=f.child,f.child=AA):(u=Y.last,u!==null?u.sibling=AA:f.child=AA,Y.last=AA)}return Y.tail!==null?(f=Y.tail,Y.rendering=f,Y.tail=f.sibling,Y.renderingStartTime=pc(),f.sibling=null,u=vs.current,y(vs,F?u&1|2:u&1),f):(mi(f),null);case 22:case 23:return Ft(f),nt(),F=f.memoizedState!==null,u!==null?u.memoizedState!==null!==F&&(f.flags|=8192):F&&(f.flags|=8192),F?R&536870912&&!(f.flags&128)&&(mi(f),f.subtreeFlags&6&&(f.flags|=8192)):mi(f),R=f.updateQueue,R!==null&&Ng(f,R.retryQueue),R=null,u!==null&&u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(R=u.memoizedState.cachePool.pool),F=null,f.memoizedState!==null&&f.memoizedState.cachePool!==null&&(F=f.memoizedState.cachePool.pool),F!==R&&(f.flags|=2048),u!==null&&p(sh),null;case 24:return R=null,u!==null&&(R=u.memoizedState.cache),f.memoizedState.cache!==R&&(f.flags|=2048),Fa(No),mi(f),null;case 25:return null}throw Error(n(156,f.tag))}function Si(u,f){switch(aA(f),f.tag){case 1:return u=f.flags,u&65536?(f.flags=u&-65537|128,f):null;case 3:return Fa(No),pA(),u=f.flags,u&65536&&!(u&128)?(f.flags=u&-65537|128,f):null;case 26:case 27:case 5:return yA(f),null;case 13:if(Ft(f),u=f.memoizedState,u!==null&&u.dehydrated!==null){if(f.alternate===null)throw Error(n(340));$()}return u=f.flags,u&65536?(f.flags=u&-65537|128,f):null;case 19:return p(vs),null;case 4:return pA(),null;case 10:return Fa(f.type),null;case 22:case 23:return Ft(f),nt(),u!==null&&p(sh),u=f.flags,u&65536?(f.flags=u&-65537|128,f):null;case 24:return Fa(No),null;case 25:return null;default:return null}}function un(u,f){switch(aA(f),f.tag){case 3:Fa(No),pA();break;case 26:case 27:case 5:yA(f);break;case 4:pA();break;case 13:Ft(f);break;case 19:p(vs);break;case 10:Fa(f.type);break;case 22:case 23:Ft(f),nt(),u!==null&&p(sh);break;case 24:Fa(No)}}function xi(u,f){try{var R=f.updateQueue,F=R!==null?R.lastEffect:null;if(F!==null){var Y=F.next;R=Y;do{if((R.tag&u)===u){F=void 0;var AA=R.create,GA=R.inst;F=AA(),GA.destroy=F}R=R.next}while(R!==Y)}}catch(ne){yg(f,f.return,ne)}}function Ho(u,f,R){try{var F=f.updateQueue,Y=F!==null?F.lastEffect:null;if(Y!==null){var AA=Y.next;F=AA;do{if((F.tag&u)===u){var GA=F.inst,ne=GA.destroy;if(ne!==void 0){GA.destroy=void 0,Y=f;var Me=R;try{ne()}catch(tt){yg(Y,Me,tt)}}}F=F.next}while(F!==AA)}}catch(tt){yg(f,f.return,tt)}}function uc(u){var f=u.updateQueue;if(f!==null){var R=u.stateNode;try{rA(f,R)}catch(F){yg(u,u.return,F)}}}function Ea(u,f,R){R.props=At(u.type,u.memoizedProps),R.state=u.memoizedState;try{R.componentWillUnmount()}catch(F){yg(u,f,F)}}function CC(u,f){try{var R=u.ref;if(R!==null){var F=u.stateNode;switch(u.tag){case 26:case 27:case 5:var Y=Ww(F);break;default:Y=F}typeof R=="function"?u.refCleanup=R(Y):R.current=Y}}catch(AA){yg(u,f,AA)}}function _a(u,f){var R=u.ref,F=u.refCleanup;if(R!==null)if(typeof F=="function")try{F()}catch(Y){yg(u,f,Y)}finally{u.refCleanup=null,u=u.alternate,u!=null&&(u.refCleanup=null)}else if(typeof R=="function")try{R(null)}catch(Y){yg(u,f,Y)}else R.current=null}function ro(u){var f=u.type,R=u.memoizedProps,F=u.stateNode;try{bwA(F,f,R,u)}catch(Y){yg(u,u.return,Y)}}function Bl(u,f,R){try{UwA(u.stateNode,u.type,R,f,u)}catch(F){yg(u,u.return,F)}}function EQ(u){return u.tag===5||u.tag===3||(QC?u.tag===26:!1)||(qa?u.tag===27:!1)||u.tag===4}function Ir(u){A:for(;;){for(;u.sibling===null;){if(u.return===null||EQ(u.return))return null;u=u.return}for(u.sibling.return=u.return,u=u.sibling;u.tag!==5&&u.tag!==6&&(!qa||u.tag!==27)&&u.tag!==18;){if(u.flags&2||u.child===null||u.tag===4)continue A;u.child.return=u,u=u.child}if(!(u.flags&2))return u.stateNode}}function El(u,f,R){var F=u.tag;if(F===5||F===6)u=u.stateNode,f?KwA(R,u,f):RwA(R,u);else if(!(F===4||qa&&F===27)&&(u=u.child,u!==null))for(El(u,f,R),u=u.sibling;u!==null;)El(u,f,R),u=u.sibling}function zd(u,f,R){var F=u.tag;if(F===5||F===6)u=u.stateNode,f?vwA(R,u,f):NwA(R,u);else if(!(F===4||qa&&F===27)&&(u=u.child,u!==null))for(zd(u,f,R),u=u.sibling;u!==null;)zd(u,f,R),u=u.sibling}function dG(u,f,R){u=u.containerInfo;try{E9(u,R)}catch(F){yg(f,f.return,F)}}function Ow(u,f){for(awA(u.containerInfo),Zs=f;Zs!==null;)if(u=Zs,f=u.child,(u.subtreeFlags&1028)!==0&&f!==null)f.return=u,Zs=f;else for(;Zs!==null;){u=Zs;var R=u.alternate;switch(f=u.flags,u.tag){case 0:break;case 11:case 15:break;case 1:if(f&1024&&R!==null){f=void 0;var F=u,Y=R.memoizedProps;R=R.memoizedState;var AA=F.stateNode;try{var GA=At(F.type,Y,F.elementType===F.type);f=AA.getSnapshotBeforeUpdate(GA,R),AA.__reactInternalSnapshotBeforeUpdate=f}catch(ne){yg(F,F.return,ne)}}break;case 3:f&1024&&Ta&&qwA(u.stateNode.containerInfo);break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if(f&1024)throw Error(n(163))}if(f=u.sibling,f!==null){f.return=u.return,Zs=f;break}Zs=u.return}return GA=_9,_9=!1,GA}function Pw(u,f,R){var F=R.flags;switch(R.tag){case 0:case 11:case 15:cC(u,R),F&4&&xi(5,R);break;case 1:if(cC(u,R),F&4)if(u=R.stateNode,f===null)try{u.componentDidMount()}catch(ne){yg(R,R.return,ne)}else{var Y=At(R.type,f.memoizedProps);f=f.memoizedState;try{u.componentDidUpdate(Y,f,u.__reactInternalSnapshotBeforeUpdate)}catch(ne){yg(R,R.return,ne)}}F&64&&uc(R),F&512&&CC(R,R.return);break;case 3:if(cC(u,R),F&64&&(F=R.updateQueue,F!==null)){if(u=null,R.child!==null)switch(R.child.tag){case 27:case 5:u=Ww(R.child.stateNode);break;case 1:u=R.child.stateNode}try{rA(F,u)}catch(ne){yg(R,R.return,ne)}}break;case 26:if(QC){cC(u,R),F&512&&CC(R,R.return);break}case 27:case 5:cC(u,R),f===null&&F&4&&ro(R),F&512&&CC(R,R.return);break;case 12:cC(u,R);break;case 13:cC(u,R),F&4&&jw(u,R);break;case 22:if(Y=R.memoizedState!==null||YB,!Y){f=f!==null&&f.memoizedState!==null||Ro;var AA=YB,GA=Ro;YB=Y,(Ro=f)&&!GA?dc(u,R,(R.subtreeFlags&8772)!==0):cC(u,R),YB=AA,Ro=GA}F&512&&(R.memoizedProps.mode==="manual"?CC(R,R.return):_a(R,R.return));break;default:cC(u,R)}}function Zd(u){var f=u.alternate;f!==null&&(u.alternate=null,Zd(f)),u.child=null,u.deletions=null,u.sibling=null,u.tag===5&&(f=u.stateNode,f!==null&&QwA(f)),u.stateNode=null,u.return=null,u.dependencies=null,u.memoizedProps=null,u.memoizedState=null,u.pendingProps=null,u.stateNode=null,u.updateQueue=null}function SI(u,f,R){for(R=R.child;R!==null;)QQ(u,f,R),R=R.sibling}function QQ(u,f,R){if(MI&&typeof MI.onCommitFiberUnmount=="function")try{MI.onCommitFiberUnmount($w,R)}catch{}switch(R.tag){case 26:if(QC){Ro||_a(R,f),SI(u,f,R),R.memoizedState?m9(R.memoizedState):R.stateNode&&w9(R.stateNode);break}case 27:if(qa){Ro||_a(R,f);var F=ss,Y=RI;ss=R.stateNode,SI(u,f,R),u0A(R.stateNode),ss=F,RI=Y;break}case 5:Ro||_a(R,f);case 6:if(Ta){if(F=ss,Y=RI,ss=null,SI(u,f,R),ss=F,RI=Y,ss!==null)if(RI)try{_wA(ss,R.stateNode)}catch(AA){yg(R,f,AA)}else try{FwA(ss,R.stateNode)}catch(AA){yg(R,f,AA)}}else SI(u,f,R);break;case 18:Ta&&ss!==null&&(RI?s0A(ss,R.stateNode):o0A(ss,R.stateNode));break;case 4:Ta?(F=ss,Y=RI,ss=R.stateNode.containerInfo,RI=!0,SI(u,f,R),ss=F,RI=Y):(DQ&&dG(R.stateNode,R,l9()),SI(u,f,R));break;case 0:case 11:case 14:case 15:Ro||Ho(2,R,f),Ro||Ho(4,R,f),SI(u,f,R);break;case 1:Ro||(_a(R,f),F=R.stateNode,typeof F.componentWillUnmount=="function"&&Ea(R,f,F)),SI(u,f,R);break;case 21:SI(u,f,R);break;case 22:Ro||_a(R,f),Ro=(F=Ro)||R.memoizedState!==null,SI(u,f,R),Ro=F;break;default:SI(u,f,R)}}function jw(u,f){if(EC&&f.memoizedState===null&&(u=f.alternate,u!==null&&(u=u.memoizedState,u!==null&&(u=u.dehydrated,u!==null))))try{g0A(u)}catch(R){yg(f,f.return,R)}}function hG(u){switch(u.tag){case 13:case 19:var f=u.stateNode;return f===null&&(f=u.stateNode=new F9),f;case 22:return u=u.stateNode,f=u._retryCache,f===null&&(f=u._retryCache=new F9),f;default:throw Error(n(435,u.tag))}}function Cr(u,f){var R=hG(u);f.forEach(function(F){var Y=ZSA.bind(null,u,F);R.has(F)||(R.add(F),F.then(Y,Y))})}function Ja(u,f){var R=f.deletions;if(R!==null)for(var F=0;F<R.length;F++){var Y=R[F],AA=u,GA=f;if(Ta){var ne=GA;A:for(;ne!==null;){switch(ne.tag){case 27:case 5:ss=ne.stateNode,RI=!1;break A;case 3:ss=ne.stateNode.containerInfo,RI=!0;break A;case 4:ss=ne.stateNode.containerInfo,RI=!0;break A}ne=ne.return}if(ss===null)throw Error(n(160));QQ(AA,GA,Y),ss=null,RI=!1}else QQ(AA,GA,Y);AA=Y.alternate,AA!==null&&(AA.return=null),Y.return=null}if(f.subtreeFlags&13878)for(f=f.child;f!==null;)pG(f,u),f=f.sibling}function pG(u,f){var R=u.alternate,F=u.flags;switch(u.tag){case 0:case 11:case 14:case 15:Ja(f,u),Tr(u),F&4&&(Ho(3,u,u.return),xi(3,u),Ho(5,u,u.return));break;case 1:Ja(f,u),Tr(u),F&512&&(Ro||R===null||_a(R,R.return)),F&64&&YB&&(u=u.updateQueue,u!==null&&(F=u.callbacks,F!==null&&(R=u.shared.hiddenCallbacks,u.shared.hiddenCallbacks=R===null?F:R.concat(F))));break;case 26:if(QC){var Y=yc;Ja(f,u),Tr(u),F&512&&(Ro||R===null||_a(R,R.return)),F&4&&(F=R!==null?R.memoizedState:null,f=u.memoizedState,R===null?f===null?u.stateNode===null?u.stateNode=I0A(Y,u.type,u.memoizedProps,u):S9(Y,u.type,u.stateNode):u.stateNode=D9(Y,f,u.memoizedProps):F!==f?(F===null?R.stateNode!==null&&w9(R.stateNode):m9(F),f===null?S9(Y,u.type,u.stateNode):D9(Y,f,u.memoizedProps)):f===null&&u.stateNode!==null&&Bl(u,u.memoizedProps,R.memoizedProps));break}case 27:if(qa&&F&4&&u.alternate===null){Y=u.stateNode;var AA=u.memoizedProps;try{E0A(Y),Q0A(u.type,AA,Y,u)}catch(bt){yg(u,u.return,bt)}}case 5:if(Ja(f,u),Tr(u),F&512&&(Ro||R===null||_a(R,R.return)),Ta){if(u.flags&32){f=u.stateNode;try{c9(f)}catch(bt){yg(u,u.return,bt)}}F&4&&u.stateNode!=null&&(f=u.memoizedProps,Bl(u,f,R!==null?R.memoizedProps:f)),F&1024&&(tq=!0)}break;case 6:if(Ja(f,u),Tr(u),F&4&&Ta){if(u.stateNode===null)throw Error(n(162));F=u.memoizedProps,R=R!==null?R.memoizedProps:F,f=u.stateNode;try{GwA(f,R,F)}catch(bt){yg(u,u.return,bt)}}break;case 3:if(QC?(c0A(),Y=yc,yc=qT(f.containerInfo),Ja(f,u),yc=Y):Ja(f,u),Tr(u),F&4){if(Ta&&EC&&R!==null&&R.memoizedState.isDehydrated)try{n0A(f.containerInfo)}catch(bt){yg(u,u.return,bt)}if(DQ){F=f.containerInfo,R=f.pendingChildren;try{E9(F,R)}catch(bt){yg(u,u.return,bt)}}}tq&&(tq=!1,zw(u));break;case 4:QC?(R=yc,yc=qT(u.stateNode.containerInfo),Ja(f,u),Tr(u),yc=R):(Ja(f,u),Tr(u)),F&4&&DQ&&dG(u.stateNode,u,u.stateNode.pendingChildren);break;case 12:Ja(f,u),Tr(u);break;case 13:Ja(f,u),Tr(u),u.child.flags&8192&&u.memoizedState!==null!=(R!==null&&R.memoizedState!==null)&&(oq=pc()),F&4&&(F=u.updateQueue,F!==null&&(u.updateQueue=null,Cr(u,F)));break;case 22:F&512&&(Ro||R===null||_a(R,R.return)),Y=u.memoizedState!==null;var GA=R!==null&&R.memoizedState!==null,ne=YB,Me=Ro;if(YB=ne||Y,Ro=Me||GA,Ja(f,u),Ro=Me,YB=ne,Tr(u),f=u.stateNode,f._current=u,f._visibility&=-3,f._visibility|=f._pendingVisibility&2,F&8192&&(f._visibility=Y?f._visibility&-2:f._visibility|1,Y&&(f=YB||Ro,R===null||GA||f||FB(u)),Ta&&(u.memoizedProps===null||u.memoizedProps.mode!=="manual"))){A:if(R=null,Ta)for(f=u;;){if(f.tag===5||QC&&f.tag===26||qa&&f.tag===27){if(R===null){GA=R=f;try{AA=GA.stateNode,Y?JwA(AA):xwA(GA.stateNode,GA.memoizedProps)}catch(bt){yg(GA,GA.return,bt)}}}else if(f.tag===6){if(R===null){GA=f;try{var tt=GA.stateNode;Y?LwA(tt):TwA(tt,GA.memoizedProps)}catch(bt){yg(GA,GA.return,bt)}}}else if((f.tag!==22&&f.tag!==23||f.memoizedState===null||f===u)&&f.child!==null){f.child.return=f,f=f.child;continue}if(f===u)break A;for(;f.sibling===null;){if(f.return===null||f.return===u)break A;R===f&&(R=null),f=f.return}R===f&&(R=null),f.sibling.return=f.return,f=f.sibling}}F&4&&(F=u.updateQueue,F!==null&&(R=F.retryQueue,R!==null&&(F.retryQueue=null,Cr(u,R))));break;case 19:Ja(f,u),Tr(u),F&4&&(F=u.updateQueue,F!==null&&(u.updateQueue=null,Cr(u,F)));break;case 21:break;default:Ja(f,u),Tr(u)}}function Tr(u){var f=u.flags;if(f&2){try{if(Ta&&(!qa||u.tag!==27)){A:{for(var R=u.return;R!==null;){if(EQ(R)){var F=R;break A}R=R.return}throw Error(n(160))}switch(F.tag){case 27:if(qa){var Y=F.stateNode,AA=Ir(u);zd(u,AA,Y);break}case 5:var GA=F.stateNode;F.flags&32&&(c9(GA),F.flags&=-33);var ne=Ir(u);zd(u,ne,GA);break;case 3:case 4:var Me=F.stateNode.containerInfo,tt=Ir(u);El(u,tt,Me);break;default:throw Error(n(161))}}}catch(bt){yg(u,u.return,bt)}u.flags&=-3}f&4096&&(u.flags&=-4097)}function zw(u){if(u.subtreeFlags&1024)for(u=u.child;u!==null;){var f=u;zw(f),f.tag===5&&f.flags&1024&&pwA(f.stateNode),u=u.sibling}}function cC(u,f){if(f.subtreeFlags&8772)for(f=f.child;f!==null;)Pw(u,f.alternate,f),f=f.sibling}function FB(u){for(u=u.child;u!==null;){var f=u;switch(f.tag){case 0:case 11:case 14:case 15:Ho(4,f,f.return),FB(f);break;case 1:_a(f,f.return);var R=f.stateNode;typeof R.componentWillUnmount=="function"&&Ea(f,f.return,R),FB(f);break;case 26:case 27:case 5:_a(f,f.return),FB(f);break;case 22:_a(f,f.return),f.memoizedState===null&&FB(f);break;default:FB(f)}u=u.sibling}}function dc(u,f,R){for(R=R&&(f.subtreeFlags&8772)!==0,f=f.child;f!==null;){var F=f.alternate,Y=u,AA=f,GA=AA.flags;switch(AA.tag){case 0:case 11:case 15:dc(Y,AA,R),xi(4,AA);break;case 1:if(dc(Y,AA,R),F=AA,Y=F.stateNode,typeof Y.componentDidMount=="function")try{Y.componentDidMount()}catch(tt){yg(F,F.return,tt)}if(F=AA,Y=F.updateQueue,Y!==null){var ne=F.stateNode;try{var Me=Y.shared.hiddenCallbacks;if(Me!==null)for(Y.shared.hiddenCallbacks=null,Y=0;Y<Me.length;Y++)DA(Me[Y],ne)}catch(tt){yg(F,F.return,tt)}}R&&GA&64&&uc(AA),CC(AA,AA.return);break;case 26:case 27:case 5:dc(Y,AA,R),R&&F===null&&GA&4&&ro(AA),CC(AA,AA.return);break;case 12:dc(Y,AA,R);break;case 13:dc(Y,AA,R),R&&GA&4&&jw(Y,AA);break;case 22:AA.memoizedState===null&&dc(Y,AA,R),CC(AA,AA.return);break;default:dc(Y,AA,R)}f=f.sibling}}function Iy(u,f){var R=null;u!==null&&u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(R=u.memoizedState.cachePool.pool),u=null,f.memoizedState!==null&&f.memoizedState.cachePool!==null&&(u=f.memoizedState.cachePool.pool),u!==R&&(u!=null&&u.refCount++,R!=null&&Fe(R))}function Cy(u,f){u=null,f.alternate!==null&&(u=f.alternate.memoizedState.cache),f=f.memoizedState.cache,f!==u&&(f.refCount++,u!=null&&Fe(u))}function hc(u,f,R,F){if(f.subtreeFlags&10256)for(f=f.child;f!==null;)Zw(u,f,R,F),f=f.sibling}function Zw(u,f,R,F){var Y=f.flags;switch(f.tag){case 0:case 11:case 15:hc(u,f,R,F),Y&2048&&xi(9,f);break;case 3:hc(u,f,R,F),Y&2048&&(u=null,f.alternate!==null&&(u=f.alternate.memoizedState.cache),f=f.memoizedState.cache,f!==u&&(f.refCount++,u!=null&&Fe(u)));break;case 12:if(Y&2048){hc(u,f,R,F),u=f.stateNode;try{var AA=f.memoizedProps,GA=AA.id,ne=AA.onPostCommit;typeof ne=="function"&&ne(GA,f.alternate===null?"mount":"update",u.passiveEffectDuration,-0)}catch(Me){yg(f,f.return,Me)}}else hc(u,f,R,F);break;case 23:break;case 22:AA=f.stateNode,f.memoizedState!==null?AA._visibility&4?hc(u,f,R,F):mA(u,f):AA._visibility&4?hc(u,f,R,F):(AA._visibility|=4,_B(u,f,R,F,(f.subtreeFlags&10256)!==0)),Y&2048&&Iy(f.alternate,f);break;case 24:hc(u,f,R,F),Y&2048&&Cy(f.alternate,f);break;default:hc(u,f,R,F)}}function _B(u,f,R,F,Y){for(Y=Y&&(f.subtreeFlags&10256)!==0,f=f.child;f!==null;){var AA=u,GA=f,ne=R,Me=F,tt=GA.flags;switch(GA.tag){case 0:case 11:case 15:_B(AA,GA,ne,Me,Y),xi(8,GA);break;case 23:break;case 22:var bt=GA.stateNode;GA.memoizedState!==null?bt._visibility&4?_B(AA,GA,ne,Me,Y):mA(AA,GA):(bt._visibility|=4,_B(AA,GA,ne,Me,Y)),Y&&tt&2048&&Iy(GA.alternate,GA);break;case 24:_B(AA,GA,ne,Me,Y),Y&&tt&2048&&Cy(GA.alternate,GA);break;default:_B(AA,GA,ne,Me,Y)}f=f.sibling}}function mA(u,f){if(f.subtreeFlags&10256)for(f=f.child;f!==null;){var R=u,F=f,Y=F.flags;switch(F.tag){case 22:mA(R,F),Y&2048&&Iy(F.alternate,F);break;case 24:mA(R,F),Y&2048&&Cy(F.alternate,F);break;default:mA(R,F)}f=f.sibling}}function JA(u){if(u.subtreeFlags&Ry)for(u=u.child;u!==null;)Se(u),u=u.sibling}function Se(u){switch(u.tag){case 26:JA(u),u.flags&Ry&&(u.memoizedState!==null?B0A(yc,u.memoizedState,u.memoizedProps):C9(u.type,u.memoizedProps));break;case 5:JA(u),u.flags&Ry&&C9(u.type,u.memoizedProps);break;case 3:case 4:if(QC){var f=yc;yc=qT(u.stateNode.containerInfo),JA(u),yc=f}else JA(u);break;case 22:u.memoizedState===null&&(f=u.alternate,f!==null&&f.memoizedState!==null?(f=Ry,Ry=16777216,JA(u),Ry=f):JA(u));break;default:JA(u)}}function Oe(u){var f=u.alternate;if(f!==null&&(u=f.child,u!==null)){f.child=null;do f=u.sibling,u.sibling=null,u=f;while(u!==null)}}function Pe(u){var f=u.deletions;if(u.flags&16){if(f!==null)for(var R=0;R<f.length;R++){var F=f[R];Zs=F,wi(F,u)}Oe(u)}if(u.subtreeFlags&10256)for(u=u.child;u!==null;)We(u),u=u.sibling}function We(u){switch(u.tag){case 0:case 11:case 15:Pe(u),u.flags&2048&&Ho(9,u,u.return);break;case 3:Pe(u);break;case 12:Pe(u);break;case 22:var f=u.stateNode;u.memoizedState!==null&&f._visibility&4&&(u.return===null||u.return.tag!==13)?(f._visibility&=-5,Dt(u)):Pe(u);break;default:Pe(u)}}function Dt(u){var f=u.deletions;if(u.flags&16){if(f!==null)for(var R=0;R<f.length;R++){var F=f[R];Zs=F,wi(F,u)}Oe(u)}for(u=u.child;u!==null;){switch(f=u,f.tag){case 0:case 11:case 15:Ho(8,f,f.return),Dt(f);break;case 22:R=f.stateNode,R._visibility&4&&(R._visibility&=-5,Dt(f));break;default:Dt(f)}u=u.sibling}}function wi(u,f){for(;Zs!==null;){var R=Zs;switch(R.tag){case 0:case 11:case 15:Ho(8,R,f);break;case 23:case 22:if(R.memoizedState!==null&&R.memoizedState.cachePool!==null){var F=R.memoizedState.cachePool.pool;F!=null&&F.refCount++}break;case 24:Fe(R.memoizedState.cache)}if(F=R.child,F!==null)F.return=R,Zs=F;else A:for(R=u;Zs!==null;){F=Zs;var Y=F.sibling,AA=F.return;if(Zd(F),F===R){Zs=null;break A}if(Y!==null){Y.return=AA,Zs=Y;break A}Zs=AA}}}function Wi(u){var f=r9(u);if(f!=null){if(typeof f.memoizedProps["data-testname"]!="string")throw Error(n(364));return f}if(u=DwA(u),u===null)throw Error(n(362));return u.stateNode.current}function gs(u,f){var R=u.tag;switch(f.$$typeof){case TG:if(u.type===f.value)return!0;break;case qG:A:{for(f=f.value,u=[u,0],R=0;R<u.length;){var F=u[R++],Y=F.tag,AA=u[R++],GA=f[AA];if(Y!==5&&Y!==26&&Y!==27||!Xw(F)){for(;GA!=null&&gs(F,GA);)AA++,GA=f[AA];if(AA===f.length){f=!0;break A}else for(F=F.child;F!==null;)u.push(F,AA),F=F.sibling}}f=!1}return f;case YG:if((R===5||R===26||R===27)&&wwA(u.stateNode,f.value))return!0;break;case OG:if((R===5||R===6||R===26||R===27)&&(u=SwA(u),u!==null&&0<=u.indexOf(f.value)))return!0;break;case HG:if((R===5||R===26||R===27)&&(u=u.memoizedProps["data-testname"],typeof u=="string"&&u.toLowerCase()===f.value.toLowerCase()))return!0;break;default:throw Error(n(365))}return!1}function Io(u){switch(u.$$typeof){case TG:return"<"+(o(u.value)||"Unknown")+">";case qG:return":has("+(Io(u)||"")+")";case YG:return'[role="'+u.value+'"]';case OG:return'"'+u.value+'"';case HG:return'[data-testname="'+u.value+'"]';default:throw Error(n(365))}}function La(u,f){var R=[];u=[u,0];for(var F=0;F<u.length;){var Y=u[F++],AA=Y.tag,GA=u[F++],ne=f[GA];if(AA!==5&&AA!==26&&AA!==27||!Xw(Y)){for(;ne!=null&&gs(Y,ne);)GA++,ne=f[GA];if(GA===f.length)R.push(Y);else for(Y=Y.child;Y!==null;)u.push(Y,GA),Y=Y.sibling}}return R}function js(u,f){if(!Vw)throw Error(n(363));u=Wi(u),u=La(u,f),f=[],u=Array.from(u);for(var R=0;R<u.length;){var F=u[R++],Y=F.tag;if(Y===5||Y===26||Y===27)Xw(F)||f.push(F.stateNode);else for(F=F.child;F!==null;)u.push(F),F=F.sibling}return f}function Xg(){if(Gg&2&&Vn!==0)return Vn&-Vn;if(zi.T!==null){var u=Dy;return u!==0?u:xA()}return BwA()}function Ql(){fC===0&&(fC=!(Vn&536870912)||og?G():536870912);var u=pC.current;return u!==null&&(u.flags|=32),fC}function fo(u,f,R){(u===Og&&Pg===2||u.cancelPendingCommit!==null)&&(dQ(u,0),xa(u,Vn,fC,!1)),b(u,R),(!(Gg&2)||u!==Og)&&(u===Og&&(!(Gg&2)&&(ah|=R),Go===4&&xa(u,Vn,fC,!1)),CA(u))}function cr(u,f,R){if(Gg&6)throw Error(n(327));var F=!R&&(f&60)===0&&(f&u.expiredLanes)===0||k(u,f),Y=F?HSA(u,f):mT(u,f,!0),AA=F;do{if(Y===0){Gy&&!F&&xa(u,f,0,!1);break}else if(Y===6)xa(u,f,0,!HB);else{if(R=u.current.alternate,AA&&!uQ(R)){Y=mT(u,f,!1),AA=!1;continue}if(Y===2){if(AA=f,u.errorRecoveryDisabledLanes&AA)var GA=0;else GA=u.pendingLanes&-536870913,GA=GA!==0?GA:GA&536870912?536870912:0;if(GA!==0){f=GA;A:{var ne=u;Y=o0;var Me=EC&&ne.current.memoizedState.isDehydrated;if(Me&&(dQ(ne,GA).flags|=256),GA=mT(ne,GA,!1),GA!==2){if(iq&&!Me){ne.errorRecoveryDisabledLanes|=AA,ah|=AA,Y=4;break A}AA=pl,pl=Y,AA!==null&&lC(AA)}Y=GA}if(AA=!1,Y!==2)continue}}if(Y===1){dQ(u,0),xa(u,f,0,!0);break}A:{switch(F=u,Y){case 0:case 1:throw Error(n(345));case 4:if((f&4194176)===f){xa(F,f,fC,!HB);break A}break;case 2:pl=null;break;case 3:case 5:break;default:throw Error(n(329))}if(F.finishedWork=R,F.finishedLanes=f,(f&62914560)===f&&(AA=oq+300-pc(),10<AA)){if(xa(F,f,fC,!HB),S(F,0)!==0)break A;F.timeoutHandle=CwA(BC.bind(null,F,R,pl,PG,gq,f,fC,ah,by,HB,2,-0,0),AA);break A}BC(F,R,pl,PG,gq,f,fC,ah,by,HB,0,-0,0)}}break}while(!0);CA(u)}function lC(u){pl===null?pl=u:pl.push.apply(pl,u)}function BC(u,f,R,F,Y,AA,GA,ne,Me,tt,bt,Wt,Xt){var on=f.subtreeFlags;if((on&8192||(on&16785408)===16785408)&&(dwA(),Se(f),f=hwA(),f!==null)){u.cancelPendingCommit=f(HV.bind(null,u,R,F,Y,GA,ne,Me,1,Wt,Xt)),xa(u,AA,GA,!tt);return}HV(u,R,F,Y,GA,ne,Me,bt,Wt,Xt)}function uQ(u){for(var f=u;;){var R=f.tag;if((R===0||R===11||R===15)&&f.flags&16384&&(R=f.updateQueue,R!==null&&(R=R.stores,R!==null)))for(var F=0;F<R.length;F++){var Y=R[F],AA=Y.getSnapshot;Y=Y.value;try{if(!NI(AA(),Y))return!1}catch{return!1}}if(R=f.child,f.subtreeFlags&16384&&R!==null)R.return=f,f=R;else{if(f===u)break;for(;f.sibling===null;){if(f.return===null||f.return===u)return!0;f=f.return}f.sibling.return=f.return,f=f.sibling}}return!0}function xa(u,f,R,F){f&=~nq,f&=~ah,u.suspendedLanes|=f,u.pingedLanes&=~f,F&&(u.warmLanes|=f),F=u.expirationTimes;for(var Y=f;0<Y;){var AA=31-kI(Y),GA=1<<AA;F[AA]=-1,Y&=~GA}R!==0&&K(u,R,f)}function Wd(){return Gg&6?!0:(_A(0),!1)}function JB(){if(Rn!==null){if(Pg===0)var u=Rn.return;else u=Rn,qB=oh=null,nA(u),wy=null,i0=0,u=Rn;for(;u!==null;)un(u.alternate,u),u=u.return;Rn=null}}function dQ(u,f){u.finishedWork=null,u.finishedLanes=0;var R=u.timeoutHandle;R!==LT&&(u.timeoutHandle=LT,cwA(R)),R=u.cancelPendingCommit,R!==null&&(u.cancelPendingCommit=null,R()),JB(),Og=u,Rn=R=pQ(u.current,null),Vn=f,Pg=0,GI=null,HB=!1,Gy=k(u,f),iq=!1,by=fC=nq=ah=MQ=Go=0,pl=o0=null,gq=!1,f&8&&(f|=f&32);var F=u.entangledLanes;if(F!==0)for(u=u.entanglements,F&=f;0<F;){var Y=31-kI(F),AA=1<<Y;f|=u[Y],F&=~AA}return OB=f,H(),R}function fG(u,f){Dn=null,zi.H=hl,f===t0?(f=UA(),Pg=3):f===XT?(f=UA(),Pg=4):Pg=f===v9?8:f!==null&&typeof f=="object"&&typeof f.then=="function"?6:1,GI=f,Rn===null&&(Go=1,zt(u,T(f,u.current)))}function hQ(){var u=pC.current;return u===null?!0:(Vn&4194176)===Vn?dl===null:(Vn&62914560)===Vn||Vn&536870912?u===dl:!1}function yG(){var u=zi.H;return zi.H=hl,u===null?hl:u}function xV(){var u=zi.A;return zi.A=G0A,u}function DT(){Go=4,HB||(Vn&4194176)!==Vn&&pC.current!==null||(Gy=!0),!(MQ&134217727)&&!(ah&134217727)||Og===null||xa(Og,Vn,fC,!1)}function mT(u,f,R){var F=Gg;Gg|=2;var Y=yG(),AA=xV();(Og!==u||Vn!==f)&&(PG=null,dQ(u,f)),f=!1;var GA=Go;A:do try{if(Pg!==0&&Rn!==null){var ne=Rn,Me=GI;switch(Pg){case 8:JB(),GA=6;break A;case 3:case 2:case 6:pC.current===null&&(f=!0);var tt=Pg;if(Pg=0,GI=null,cy(u,ne,Me,tt),R&&Gy){GA=0;break A}break;default:tt=Pg,Pg=0,GI=null,cy(u,ne,Me,tt)}}YSA(),GA=Go;break}catch(bt){fG(u,bt)}while(!0);return f&&u.shellSuspendCounter++,qB=oh=null,Gg=F,zi.H=Y,zi.A=AA,Rn===null&&(Og=null,Vn=0,H()),GA}function YSA(){for(;Rn!==null;)TV(Rn)}function HSA(u,f){var R=Gg;Gg|=2;var F=yG(),Y=xV();Og!==u||Vn!==f?(PG=null,s0=pc()+500,dQ(u,f)):Gy=k(u,f);A:do try{if(Pg!==0&&Rn!==null){f=Rn;var AA=GI;e:switch(Pg){case 1:Pg=0,GI=null,cy(u,f,AA,1);break;case 2:if(j(AA)){Pg=0,GI=null,qV(f);break}f=function(){Pg===2&&Og===u&&(Pg=7),CA(u)},AA.then(f,f);break A;case 3:Pg=7;break A;case 4:Pg=5;break A;case 7:j(AA)?(Pg=0,GI=null,qV(f)):(Pg=0,GI=null,cy(u,f,AA,7));break;case 5:var GA=null;switch(Rn.tag){case 26:GA=Rn.memoizedState;case 5:case 27:var ne=Rn,Me=ne.type,tt=ne.pendingProps;if(GA?k9(GA):I9(Me,tt)){Pg=0,GI=null;var bt=ne.sibling;if(bt!==null)Rn=bt;else{var Wt=ne.return;Wt!==null?(Rn=Wt,DG(Wt)):Rn=null}break e}}Pg=0,GI=null,cy(u,f,AA,5);break;case 6:Pg=0,GI=null,cy(u,f,AA,6);break;case 8:JB(),Go=6;break A;default:throw Error(n(462))}}OSA();break}catch(Xt){fG(u,Xt)}while(!0);return qB=oh=null,zi.H=F,zi.A=Y,Gg=R,Rn!==null?0:(Og=null,Vn=0,H(),Go)}function OSA(){for(;Rn!==null&&!p0A();)TV(Rn)}function TV(u){var f=DI(u.alternate,u,OB);u.memoizedProps=u.pendingProps,f===null?DG(u):Rn=f}function qV(u){var f=u,R=f.alternate;switch(f.tag){case 15:case 0:f=rC(R,f,f.pendingProps,f.type,void 0,Vn);break;case 11:f=rC(R,f,f.pendingProps,f.type.render,f.ref,Vn);break;case 5:nA(f);default:un(R,f),f=Rn=zV(f,OB),f=DI(R,f,OB)}u.memoizedProps=u.pendingProps,f===null?DG(u):Rn=f}function cy(u,f,R,F){qB=oh=null,nA(f),wy=null,i0=0;var Y=f.return;try{if(gg(u,Y,f,R,Vn)){Go=1,zt(u,T(R,u.current)),Rn=null;return}}catch(AA){if(Y!==null)throw Rn=Y,AA;Go=1,zt(u,T(R,u.current)),Rn=null;return}f.flags&32768?(og||F===1?u=!0:Gy||Vn&536870912?u=!1:(HB=u=!0,(F===2||F===3||F===6)&&(F=pC.current,F!==null&&F.tag===13&&(F.flags|=16384))),YV(f,u)):DG(f)}function DG(u){var f=u;do{if(f.flags&32768){YV(f,HB);return}u=f.return;var R=Di(f.alternate,f,OB);if(R!==null){Rn=R;return}if(f=f.sibling,f!==null){Rn=f;return}Rn=f=u}while(f!==null);Go===0&&(Go=5)}function YV(u,f){do{var R=Si(u.alternate,u);if(R!==null){R.flags&=32767,Rn=R;return}if(R=u.return,R!==null&&(R.flags|=32768,R.subtreeFlags=0,R.deletions=null),!f&&(u=u.sibling,u!==null)){Rn=u;return}Rn=u=R}while(u!==null);Go=6,Rn=null}function HV(u,f,R,F,Y,AA,GA,ne,Me,tt){var bt=zi.T,Wt=$d();try{qr(2),zi.T=null,PSA(u,f,R,F,Wt,Y,AA,GA,ne,Me,tt)}finally{zi.T=bt,qr(Wt)}}function PSA(u,f,R,F,Y,AA,GA,ne){do Vd();while(rh!==null);if(Gg&6)throw Error(n(327));var Me=u.finishedWork;if(F=u.finishedLanes,Me===null)return null;if(u.finishedWork=null,u.finishedLanes=0,Me===u.current)throw Error(n(177));u.callbackNode=null,u.callbackPriority=0,u.cancelPendingCommit=null;var tt=Me.lanes|Me.childLanes;if(tt|=jT,_(u,F,tt,AA,GA,ne),u===Og&&(Rn=Og=null,Vn=0),!(Me.subtreeFlags&10256)&&!(Me.flags&10256)||jG||(jG=!0,sq=tt,aq=R,WSA(OT,function(){return Vd(),null})),R=(Me.flags&15990)!==0,Me.subtreeFlags&15990||R?(R=zi.T,zi.T=null,AA=$d(),qr(2),GA=Gg,Gg|=4,Ow(u,Me),pG(Me,u),rwA(u.containerInfo),u.current=Me,Pw(u,Me.alternate,Me),f0A(),Gg=GA,qr(AA),zi.T=R):u.current=Me,jG?(jG=!1,rh=u,a0=F):OV(u,tt),tt=u.pendingLanes,tt===0&&(NQ=null),v(Me.stateNode),CA(u),f!==null)for(Y=u.onRecoverableError,Me=0;Me<f.length;Me++)tt=f[Me],Y(tt.value,{componentStack:tt.stack});return a0&3&&Vd(),tt=u.pendingLanes,F&4194218&&tt&42?u===rq?r0++:(r0=0,rq=u):r0=0,_A(0),null}function OV(u,f){(u.pooledCacheLanes&=f)===0&&(f=u.pooledCache,f!=null&&(u.pooledCache=null,Fe(f)))}function Vd(){if(rh!==null){var u=rh,f=sq;sq=0;var R=q(a0),F=32>R?32:R;R=zi.T;var Y=$d();try{if(qr(F),zi.T=null,rh===null)var AA=!1;else{F=aq,aq=null;var GA=rh,ne=a0;if(rh=null,a0=0,Gg&6)throw Error(n(331));var Me=Gg;if(Gg|=4,We(GA.current),Zw(GA,GA.current,ne,F),Gg=Me,_A(0,!1),MI&&typeof MI.onPostCommitFiberRoot=="function")try{MI.onPostCommitFiberRoot($w,GA)}catch{}AA=!0}return AA}finally{qr(Y),zi.T=R,OV(u,f)}}return!1}function PV(u,f,R){f=T(R,f),f=Ei(u.stateNode,f,2),u=EA(u,f,2),u!==null&&(b(u,2),CA(u))}function yg(u,f,R){if(u.tag===3)PV(u,u,R);else for(;f!==null;){if(f.tag===3){PV(f,u,R);break}else if(f.tag===1){var F=f.stateNode;if(typeof f.type.getDerivedStateFromError=="function"||typeof F.componentDidCatch=="function"&&(NQ===null||!NQ.has(F))){u=T(R,u),R=ai(2),F=EA(f,R,2),F!==null&&(Hi(R,F,f,u),b(F,2),CA(F));break}}f=f.return}}function ST(u,f,R){var F=u.pingCache;if(F===null){F=u.pingCache=new b0A;var Y=new Set;F.set(f,Y)}else Y=F.get(f),Y===void 0&&(Y=new Set,F.set(f,Y));Y.has(R)||(iq=!0,Y.add(R),u=jSA.bind(null,u,f,R),f.then(u,u))}function jSA(u,f,R){var F=u.pingCache;F!==null&&F.delete(f),u.pingedLanes|=u.suspendedLanes&R,u.warmLanes&=~R,Og===u&&(Vn&R)===R&&(Go===4||Go===3&&(Vn&62914560)===Vn&&300>pc()-oq?!(Gg&2)&&dQ(u,0):nq|=R,by===Vn&&(by=0)),CA(u)}function jV(u,f){f===0&&(f=M()),u=iA(u,f),u!==null&&(b(u,f),CA(u))}function zSA(u){var f=u.memoizedState,R=0;f!==null&&(R=f.retryLane),jV(u,R)}function ZSA(u,f){var R=0;switch(u.tag){case 13:var F=u.stateNode,Y=u.memoizedState;Y!==null&&(R=Y.retryLane);break;case 19:F=u.stateNode;break;case 22:F=u.stateNode._retryCache;break;default:throw Error(n(314))}F!==null&&F.delete(f),jV(u,R)}function WSA(u,f){return RG(u,f)}function VSA(u,f,R,F){this.tag=u,this.key=R,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=f,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=F,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function wT(u){return u=u.prototype,!(!u||!u.isReactComponent)}function pQ(u,f){var R=u.alternate;return R===null?(R=t(u.tag,f,u.key,u.mode),R.elementType=u.elementType,R.type=u.type,R.stateNode=u.stateNode,R.alternate=u,u.alternate=R):(R.pendingProps=f,R.type=u.type,R.flags=0,R.subtreeFlags=0,R.deletions=null),R.flags=u.flags&31457280,R.childLanes=u.childLanes,R.lanes=u.lanes,R.child=u.child,R.memoizedProps=u.memoizedProps,R.memoizedState=u.memoizedState,R.updateQueue=u.updateQueue,f=u.dependencies,R.dependencies=f===null?null:{lanes:f.lanes,firstContext:f.firstContext},R.sibling=u.sibling,R.index=u.index,R.ref=u.ref,R.refCleanup=u.refCleanup,R}function zV(u,f){u.flags&=31457282;var R=u.alternate;return R===null?(u.childLanes=0,u.lanes=f,u.child=null,u.subtreeFlags=0,u.memoizedProps=null,u.memoizedState=null,u.updateQueue=null,u.dependencies=null,u.stateNode=null):(u.childLanes=R.childLanes,u.lanes=R.lanes,u.child=R.child,u.subtreeFlags=0,u.deletions=null,u.memoizedProps=R.memoizedProps,u.memoizedState=R.memoizedState,u.updateQueue=R.updateQueue,u.type=R.type,f=R.dependencies,u.dependencies=f===null?null:{lanes:f.lanes,firstContext:f.firstContext}),u}function mG(u,f,R,F,Y,AA){var GA=0;if(F=u,typeof u=="function")wT(u)&&(GA=1);else if(typeof u=="string")GA=QC&&qa?f9(u,R,Qa.current)?26:N9(u)?27:5:QC?f9(u,R,Qa.current)?26:5:qa&&N9(u)?27:5;else A:switch(u){case By:return Xd(R.children,Y,AA,f);case e9:GA=8,Y|=24;break;case GT:return u=t(12,R,f,Y|2),u.elementType=GT,u.lanes=AA,u;case UT:return u=t(13,R,f,Y),u.elementType=UT,u.lanes=AA,u;case vT:return u=t(19,R,f,Y),u.elementType=vT,u.lanes=AA,u;case i9:return ZV(R,Y,AA,f);default:if(typeof u=="object"&&u!==null)switch(u.$$typeof){case ewA:case fQ:GA=10;break A;case t9:GA=9;break A;case bT:GA=11;break A;case KT:GA=14;break A;case yQ:GA=16,F=null;break A}GA=29,R=Error(n(130,u===null?"null":typeof u,"")),F=null}return f=t(GA,R,f,Y),f.elementType=u,f.type=F,f.lanes=AA,f}function Xd(u,f,R,F){return u=t(7,u,F,f),u.lanes=R,u}function ZV(u,f,R,F){u=t(22,u,F,f),u.elementType=i9,u.lanes=R;var Y={_visibility:1,_pendingVisibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null,_current:null,detach:function(){var AA=Y._current;if(AA===null)throw Error(n(456));if(!(Y._pendingVisibility&2)){var GA=iA(AA,2);GA!==null&&(Y._pendingVisibility|=2,fo(GA,AA,2))}},attach:function(){var AA=Y._current;if(AA===null)throw Error(n(456));if(Y._pendingVisibility&2){var GA=iA(AA,2);GA!==null&&(Y._pendingVisibility&=-3,fo(GA,AA,2))}}};return u.stateNode=Y,u}function kT(u,f,R){return u=t(6,u,null,f),u.lanes=R,u}function MT(u,f,R){return f=t(4,u.children!==null?u.children:[],u.key,f),f.lanes=R,f.stateNode={containerInfo:u.containerInfo,pendingChildren:null,implementation:u.implementation},f}function XSA(u,f,R,F,Y,AA,GA,ne){this.tag=1,this.containerInfo=u,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=LT,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=w(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.finishedLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=w(0),this.hiddenUpdates=w(null),this.identifierPrefix=F,this.onUncaughtError=Y,this.onCaughtError=AA,this.onRecoverableError=GA,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=ne,this.incompleteTransitions=new Map}function WV(u,f,R,F,Y,AA,GA,ne,Me,tt,bt,Wt){return u=new XSA(u,f,R,GA,ne,Me,tt,Wt),f=1,AA===!0&&(f|=24),AA=t(3,null,null,f),u.current=AA,AA.stateNode=u,f=Be(),f.refCount++,u.pooledCache=f,f.refCount++,AA.memoizedState={element:F,isDehydrated:R,cache:f},he(AA),u}function VV(u){return u?(u=uy,u):uy}function XV(u){var f=u._reactInternals;if(f===void 0)throw typeof u.render=="function"?Error(n(188)):(u=Object.keys(u).join(","),Error(n(268,u)));return u=B(f),u=u!==null?Q(u):null,u===null?null:Ww(u.stateNode)}function $V(u,f,R,F,Y,AA){Y=VV(Y),F.context===null?F.context=Y:F.pendingContext=Y,F=NA(f),F.payload={element:R},AA=AA===void 0?null:AA,AA!==null&&(F.callback=AA),R=EA(u,F,f),R!==null&&(fo(R,u,f),PA(R,u,f))}function A9(u,f){if(u=u.memoizedState,u!==null&&u.dehydrated!==null){var R=u.retryLane;u.retryLane=R!==0&&R<f?R:f}}function NT(u,f){A9(u,f),(u=u.alternate)&&A9(u,f)}var Nn={},$SA=E,wI=cQe(),RT=Object.assign,AwA=Symbol.for("react.element"),SG=Symbol.for("react.transitional.element"),ly=Symbol.for("react.portal"),By=Symbol.for("react.fragment"),e9=Symbol.for("react.strict_mode"),GT=Symbol.for("react.profiler"),ewA=Symbol.for("react.provider"),t9=Symbol.for("react.consumer"),fQ=Symbol.for("react.context"),bT=Symbol.for("react.forward_ref"),UT=Symbol.for("react.suspense"),vT=Symbol.for("react.suspense_list"),KT=Symbol.for("react.memo"),yQ=Symbol.for("react.lazy"),i9=Symbol.for("react.offscreen"),twA=Symbol.for("react.memo_cache_sentinel"),n9=Symbol.iterator,iwA=Symbol.for("react.client.reference"),zi=$SA.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,FT,g9,_T=!1,wG=Array.isArray,nwA=A.rendererVersion,gwA=A.rendererPackageName,o9=A.extraDevToolsConfig,Ww=A.getPublicInstance,owA=A.getRootHostContext,swA=A.getChildHostContext,awA=A.prepareForCommit,rwA=A.resetAfterCommit,IwA=A.createInstance,JT=A.appendInitialChild,s9=A.finalizeInitialChildren,kG=A.shouldSetTextContent,a9=A.createTextInstance,CwA=A.scheduleTimeout,cwA=A.cancelTimeout,LT=A.noTimeout,LB=A.isPrimaryRenderer;A.warnsIfNotActing;var Ta=A.supportsMutation,DQ=A.supportsPersistence,EC=A.supportsHydration,r9=A.getInstanceFromNode;A.beforeActiveInstanceBlur,A.afterActiveInstanceBlur;var lwA=A.preparePortalMount;A.prepareScopeUpdate,A.getInstanceFromScope;var qr=A.setCurrentUpdatePriority,$d=A.getCurrentUpdatePriority,BwA=A.resolveUpdatePriority;A.resolveEventType,A.resolveEventTimeStamp;var EwA=A.shouldAttemptEagerTransition,QwA=A.detachDeletedInstance;A.requestPostPaintCallback;var uwA=A.maySuspendCommit,I9=A.preloadInstance,dwA=A.startSuspendingCommit,C9=A.suspendInstance,hwA=A.waitForCommitToBeReady,Ey=A.NotPendingTransition,Ah=A.HostTransitionContext,pwA=A.resetFormInstance;A.bindToConsole;var fwA=A.supportsMicrotasks,ywA=A.scheduleMicrotask,Vw=A.supportsTestSelectors,DwA=A.findFiberRoot,mwA=A.getBoundingRect,SwA=A.getTextContent,Xw=A.isHiddenSubtree,wwA=A.matchAccessibilityRole,kwA=A.setFocusIfFocusable,MwA=A.setupIntersectionObserver,NwA=A.appendChild,RwA=A.appendChildToContainer,GwA=A.commitTextUpdate,bwA=A.commitMount,UwA=A.commitUpdate,vwA=A.insertBefore,KwA=A.insertInContainerBefore,FwA=A.removeChild,_wA=A.removeChildFromContainer,c9=A.resetTextContent,JwA=A.hideInstance,LwA=A.hideTextInstance,xwA=A.unhideInstance,TwA=A.unhideTextInstance,qwA=A.clearContainer,YwA=A.cloneInstance,l9=A.createContainerChildSet,B9=A.appendChildToContainerChildSet,HwA=A.finalizeContainerChildren,E9=A.replaceContainerChildren,Q9=A.cloneHiddenInstance,u9=A.cloneHiddenTextInstance,xT=A.isSuspenseInstancePending,TT=A.isSuspenseInstanceFallback,OwA=A.getSuspenseInstanceFallbackErrorDetails,PwA=A.registerSuspenseInstanceRetry,jwA=A.canHydrateFormStateMarker,zwA=A.isFormStateMarkerMatching,d9=A.getNextHydratableSibling,h9=A.getFirstHydratableChild,ZwA=A.getFirstHydratableChildWithinContainer,WwA=A.getFirstHydratableChildWithinSuspenseInstance,VwA=A.canHydrateInstance,XwA=A.canHydrateTextInstance,$wA=A.canHydrateSuspenseInstance,A0A=A.hydrateInstance,e0A=A.hydrateTextInstance,t0A=A.hydrateSuspenseInstance,i0A=A.getNextHydratableInstanceAfterSuspenseInstance,n0A=A.commitHydratedContainer,g0A=A.commitHydratedSuspenseInstance,o0A=A.clearSuspenseBoundary,s0A=A.clearSuspenseBoundaryFromContainer,p9=A.shouldDeleteUnhydratedTailInstances;A.diffHydratedPropsForDevWarnings,A.diffHydratedTextForDevWarnings,A.describeHydratableInstanceForDevWarnings;var a0A=A.validateHydratableInstance,r0A=A.validateHydratableTextInstance,QC=A.supportsResources,f9=A.isHostHoistableType,qT=A.getHoistableRoot,y9=A.getResource,D9=A.acquireResource,m9=A.releaseResource,I0A=A.hydrateHoistable,S9=A.mountHoistable,w9=A.unmountHoistable,C0A=A.createHoistableInstance,c0A=A.prepareToCommitHoistables,l0A=A.mayResourceSuspendCommit,k9=A.preloadResource,B0A=A.suspendResource,qa=A.supportsSingletons,M9=A.resolveSingletonInstance,E0A=A.clearSingleton,Q0A=A.acquireSingletonInstance,u0A=A.releaseSingletonInstance,N9=A.isHostSingletonType,YT=[],Qy=-1,uy={},kI=Math.clz32?Math.clz32:m,d0A=Math.log,h0A=Math.LN2,MG=128,NG=4194304,RG=wI.unstable_scheduleCallback,HT=wI.unstable_cancelCallback,p0A=wI.unstable_shouldYield,f0A=wI.unstable_requestPaint,pc=wI.unstable_now,R9=wI.unstable_ImmediatePriority,y0A=wI.unstable_UserBlockingPriority,OT=wI.unstable_NormalPriority,D0A=wI.unstable_IdlePriority,m0A=wI.log,S0A=wI.unstable_setDisableYieldValue,$w=null,MI=null,NI=typeof Object.is=="function"?Object.is:x,G9=new WeakMap,dy=[],hy=0,GG=null,bG=0,uC=[],dC=0,eh=null,xB=1,TB="",Qa=d(null),A0=d(null),mQ=d(null),UG=d(null),lr=null,Ya=null,og=!1,fc=null,ul=!1,PT=Error(n(519)),hC=[],py=0,jT=0,vG=null,fy=null,zT=!1,KG=!1,ZT=!1,yy=0,e0=null,WT=0,Dy=0,my=null,SQ=!1,VT=!1,w0A=Object.prototype.hasOwnProperty,t0=Error(n(460)),XT=Error(n(474)),FG={then:function(){}},Sy=null,wy=null,i0=0,th=$e(!0),b9=$e(!1),ky=d(null),_G=d(0),pC=d(null),dl=null,vs=d(0),wQ=0,Dn=null,Rg=null,os=null,JG=!1,My=!1,ih=!1,LG=0,n0=0,Ny=null,k0A=0,$T=function(){return{lastEffect:null,events:null,stores:null,memoCache:null}},hl={readContext:LA,use:bA,useCallback:$A,useContext:$A,useEffect:$A,useImperativeHandle:$A,useLayoutEffect:$A,useInsertionEffect:$A,useMemo:$A,useReducer:$A,useRef:$A,useState:$A,useDebugValue:$A,useDeferredValue:$A,useTransition:$A,useSyncExternalStore:$A,useId:$A};hl.useCacheRefresh=$A,hl.useMemoCache=$A,hl.useHostTransitionStatus=$A,hl.useFormState=$A,hl.useActionState=$A,hl.useOptimistic=$A;var nh={readContext:LA,use:bA,useCallback:function(u,f){return vA().memoizedState=[u,f===void 0?null:f],u},useContext:LA,useEffect:Tn,useImperativeHandle:function(u,f,R){R=R!=null?R.concat([u]):null,gn(4194308,4,Eg.bind(null,f,u),R)},useLayoutEffect:function(u,f){return gn(4194308,4,u,f)},useInsertionEffect:function(u,f){gn(4,2,u,f)},useMemo:function(u,f){var R=vA();f=f===void 0?null:f;var F=u();if(ih){U(!0);try{u()}finally{U(!1)}}return R.memoizedState=[F,f],F},useReducer:function(u,f,R){var F=vA();if(R!==void 0){var Y=R(f);if(ih){U(!0);try{R(f)}finally{U(!1)}}}else Y=f;return F.memoizedState=F.baseState=Y,u={pending:null,lanes:0,dispatch:null,lastRenderedReducer:u,lastRenderedState:Y},F.queue=u,u=u.dispatch=ei.bind(null,Dn,u),[F.memoizedState,u]},useRef:function(u){var f=vA();return u={current:u},f.memoizedState=u},useState:function(u){u=Qt(u);var f=u.queue,R=Vt.bind(null,Dn,f);return f.dispatch=R,[u.memoizedState,R]},useDebugValue:Mg,useDeferredValue:function(u,f){var R=vA();return qe(R,u,f)},useTransition:function(){var u=Qt(!1);return u=Ae.bind(null,Dn,u.queue,!0,!1),vA().memoizedState=u,[!1,u]},useSyncExternalStore:function(u,f,R){var F=Dn,Y=vA();if(og){if(R===void 0)throw Error(n(407));R=R()}else{if(R=f(),Og===null)throw Error(n(349));Vn&60||HA(F,f,R)}Y.memoizedState=R;var AA={value:R,getSnapshot:f};return Y.queue=AA,Tn(ye.bind(null,F,AA,u),[u]),F.flags|=2048,vi(9,ge.bind(null,F,AA,R,f),{destroy:void 0},null),R},useId:function(){var u=vA(),f=Og.identifierPrefix;if(og){var R=TB,F=xB;R=(F&~(1<<32-kI(F)-1)).toString(32)+R,f=":"+f+"R"+R,R=LG++,0<R&&(f+="H"+R.toString(32)),f+=":"}else R=k0A++,f=":"+f+"r"+R.toString(32)+":";return u.memoizedState=f},useCacheRefresh:function(){return vA().memoizedState=vt.bind(null,Dn)}};nh.useMemoCache=pe,nh.useHostTransitionStatus=Je,nh.useFormState=fi,nh.useActionState=fi,nh.useOptimistic=function(u){var f=vA();f.memoizedState=f.baseState=u;var R={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return f.queue=R,f=Re.bind(null,Dn,!0,R),R.dispatch=f,[u,f]};var kQ={readContext:LA,use:bA,useCallback:Hg,useContext:LA,useEffect:fg,useImperativeHandle:gi,useInsertionEffect:Zi,useLayoutEffect:te,useMemo:de,useReducer:it,useRef:kn,useState:function(){return it(xe)},useDebugValue:Mg,useDeferredValue:function(u,f){var R=KA();return OA(R,Rg.memoizedState,u,f)},useTransition:function(){var u=it(xe)[0],f=KA().memoizedState;return[typeof u=="boolean"?u:WA(u),f]},useSyncExternalStore:Qe,useId:pt};kQ.useCacheRefresh=Tt,kQ.useMemoCache=pe,kQ.useHostTransitionStatus=Je,kQ.useFormState=Yi,kQ.useActionState=Yi,kQ.useOptimistic=function(u,f){var R=KA();return _e(R,Rg,u,f)};var gh={readContext:LA,use:bA,useCallback:Hg,useContext:LA,useEffect:fg,useImperativeHandle:gi,useInsertionEffect:Zi,useLayoutEffect:te,useMemo:de,useReducer:re,useRef:kn,useState:function(){return re(xe)},useDebugValue:Mg,useDeferredValue:function(u,f){var R=KA();return Rg===null?qe(R,u,f):OA(R,Rg.memoizedState,u,f)},useTransition:function(){var u=re(xe)[0],f=KA().memoizedState;return[typeof u=="boolean"?u:WA(u),f]},useSyncExternalStore:Qe,useId:pt};gh.useCacheRefresh=Tt,gh.useMemoCache=pe,gh.useHostTransitionStatus=Je,gh.useFormState=Zt,gh.useActionState=Zt,gh.useOptimistic=function(u,f){var R=KA();return Rg!==null?_e(R,Rg,u,f):(R.baseState=u,[u,R.queue.dispatch])};var Aq={isMounted:function(u){return(u=u._reactInternals)?c(u)===u:!1},enqueueSetState:function(u,f,R){u=u._reactInternals;var F=Xg(),Y=NA(F);Y.payload=f,R!=null&&(Y.callback=R),f=EA(u,Y,F),f!==null&&(fo(f,u,F),PA(f,u,F))},enqueueReplaceState:function(u,f,R){u=u._reactInternals;var F=Xg(),Y=NA(F);Y.tag=1,Y.payload=f,R!=null&&(Y.callback=R),f=EA(u,Y,F),f!==null&&(fo(f,u,F),PA(f,u,F))},enqueueForceUpdate:function(u,f){u=u._reactInternals;var R=Xg(),F=NA(R);F.tag=2,f!=null&&(F.callback=f),f=EA(u,F,R),f!==null&&(fo(f,u,R),PA(f,u,R))}},U9=typeof reportError=="function"?reportError:function(u){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var f=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof u=="object"&&u!==null&&typeof u.message=="string"?String(u.message):String(u),error:u});if(!window.dispatchEvent(f))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",u);return}console.error(u)},v9=Error(n(461)),zs=!1,eq={dehydrated:null,treeContext:null,retryLane:0},xG=d(null),oh=null,qB=null,M0A=typeof AbortController<"u"?AbortController:function(){var u=[],f=this.signal={aborted:!1,addEventListener:function(R,F){u.push(F)}};this.abort=function(){f.aborted=!0,u.forEach(function(R){return R()})}},N0A=wI.unstable_scheduleCallback,R0A=wI.unstable_NormalPriority,No={$$typeof:fQ,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0},K9=zi.S;zi.S=function(u,f){typeof f=="object"&&f!==null&&typeof f.then=="function"&&YA(u,f),K9!==null&&K9(u,f)};var sh=d(null),YB=!1,Ro=!1,tq=!1,F9=typeof WeakSet=="function"?WeakSet:Set,Zs=null,_9=!1,ss=null,RI=!1,yc=null,Ry=8192,G0A={getCacheForType:function(u){var f=LA(No),R=f.data.get(u);return R===void 0&&(R=u(),f.data.set(u,R)),R}},TG=0,qG=1,YG=2,HG=3,OG=4;if(typeof Symbol=="function"&&Symbol.for){var g0=Symbol.for;TG=g0("selector.component"),qG=g0("selector.has_pseudo_class"),YG=g0("selector.role"),HG=g0("selector.test_id"),OG=g0("selector.text")}var b0A=typeof WeakMap=="function"?WeakMap:Map,Gg=0,Og=null,Rn=null,Vn=0,Pg=0,GI=null,HB=!1,Gy=!1,iq=!1,OB=0,Go=0,MQ=0,ah=0,nq=0,fC=0,by=0,o0=null,pl=null,gq=!1,oq=0,s0=1/0,PG=null,NQ=null,jG=!1,rh=null,a0=0,sq=0,aq=null,r0=0,rq=null;return Nn.attemptContinuousHydration=function(u){if(u.tag===13){var f=iA(u,67108864);f!==null&&fo(f,u,67108864),NT(u,67108864)}},Nn.attemptHydrationAtCurrentPriority=function(u){if(u.tag===13){var f=Xg(),R=iA(u,f);R!==null&&fo(R,u,f),NT(u,f)}},Nn.attemptSynchronousHydration=function(u){switch(u.tag){case 3:if(u=u.stateNode,u.current.memoizedState.isDehydrated){var f=D(u.pendingLanes);if(f!==0){for(u.pendingLanes|=2,u.entangledLanes|=2;f;){var R=1<<31-kI(f);u.entanglements[1]|=R,f&=~R}CA(u),!(Gg&6)&&(s0=pc()+500,_A(0))}}break;case 13:f=iA(u,2),f!==null&&fo(f,u,2),Wd(),NT(u,2)}},Nn.batchedUpdates=function(u,f){return u(f)},Nn.createComponentSelector=function(u){return{$$typeof:TG,value:u}},Nn.createContainer=function(u,f,R,F,Y,AA,GA,ne,Me,tt){return WV(u,f,!1,null,R,F,AA,GA,ne,Me,tt,null)},Nn.createHasPseudoClassSelector=function(u){return{$$typeof:qG,value:u}},Nn.createHydrationContainer=function(u,f,R,F,Y,AA,GA,ne,Me,tt,bt,Wt,Xt){return u=WV(R,F,!0,u,Y,AA,ne,Me,tt,bt,Wt,Xt),u.context=VV(null),R=u.current,F=Xg(),Y=NA(F),Y.callback=f??null,EA(R,Y,F),u.current.lanes=F,b(u,F),CA(u),u},Nn.createPortal=function(u,f,R){var F=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:ly,key:F==null?null:""+F,children:u,containerInfo:f,implementation:R}},Nn.createRoleSelector=function(u){return{$$typeof:YG,value:u}},Nn.createTestNameSelector=function(u){return{$$typeof:HG,value:u}},Nn.createTextSelector=function(u){return{$$typeof:OG,value:u}},Nn.defaultOnCaughtError=function(u){console.error(u)},Nn.defaultOnRecoverableError=function(u){U9(u)},Nn.defaultOnUncaughtError=function(u){U9(u)},Nn.deferredUpdates=function(u){var f=zi.T,R=$d();try{return qr(32),zi.T=null,u()}finally{qr(R),zi.T=f}},Nn.discreteUpdates=function(u,f,R,F,Y){var AA=zi.T,GA=$d();try{return qr(2),zi.T=null,u(f,R,F,Y)}finally{qr(GA),zi.T=AA,Gg===0&&(s0=pc()+500)}},Nn.findAllNodes=js,Nn.findBoundingRects=function(u,f){if(!Vw)throw Error(n(363));f=js(u,f),u=[];for(var R=0;R<f.length;R++)u.push(mwA(f[R]));for(f=u.length-1;0<f;f--){R=u[f];for(var F=R.x,Y=F+R.width,AA=R.y,GA=AA+R.height,ne=f-1;0<=ne;ne--)if(f!==ne){var Me=u[ne],tt=Me.x,bt=tt+Me.width,Wt=Me.y,Xt=Wt+Me.height;if(F>=tt&&AA>=Wt&&Y<=bt&&GA<=Xt){u.splice(f,1);break}else if(F!==tt||R.width!==Me.width||Xt<AA||Wt>GA){if(!(AA!==Wt||R.height!==Me.height||bt<F||tt>Y)){tt>F&&(Me.width+=tt-F,Me.x=F),bt<Y&&(Me.width=Y-tt),u.splice(f,1);break}}else{Wt>AA&&(Me.height+=Wt-AA,Me.y=AA),Xt<GA&&(Me.height=GA-Wt),u.splice(f,1);break}}}return u},Nn.findHostInstance=XV,Nn.findHostInstanceWithNoPortals=function(u){return u=B(u),u=u!==null?h(u):null,u===null?null:Ww(u.stateNode)},Nn.findHostInstanceWithWarning=function(u){return XV(u)},Nn.flushPassiveEffects=Vd,Nn.flushSyncFromReconciler=function(u){var f=Gg;Gg|=1;var R=zi.T,F=$d();try{if(qr(2),zi.T=null,u)return u()}finally{qr(F),zi.T=R,Gg=f,!(Gg&6)&&_A(0)}},Nn.flushSyncWork=Wd,Nn.focusWithin=function(u,f){if(!Vw)throw Error(n(363));for(u=Wi(u),f=La(u,f),f=Array.from(f),u=0;u<f.length;){var R=f[u++],F=R.tag;if(!Xw(R)){if((F===5||F===26||F===27)&&kwA(R.stateNode))return!0;for(R=R.child;R!==null;)f.push(R),R=R.sibling}}return!1},Nn.getFindAllNodesFailureDescription=function(u,f){if(!Vw)throw Error(n(363));var R=0,F=[];u=[Wi(u),0];for(var Y=0;Y<u.length;){var AA=u[Y++],GA=AA.tag,ne=u[Y++],Me=f[ne];if((GA!==5&&GA!==26&&GA!==27||!Xw(AA))&&(gs(AA,Me)&&(F.push(Io(Me)),ne++,ne>R&&(R=ne)),ne<f.length))for(AA=AA.child;AA!==null;)u.push(AA,ne),AA=AA.sibling}if(R<f.length){for(u=[];R<f.length;R++)u.push(Io(f[R]));return`findAllNodes was able to match part of the selector:
  `+(F.join(" > ")+`

No matching component was found for:
  `)+u.join(" > ")}return null},Nn.getPublicRootInstance=function(u){if(u=u.current,!u.child)return null;switch(u.child.tag){case 27:case 5:return Ww(u.child.stateNode);default:return u.child.stateNode}},Nn.injectIntoDevTools=function(){var u={bundleType:0,version:nwA,rendererPackageName:gwA,currentDispatcherRef:zi,findFiberByHostInstance:r9,reconcilerVersion:"19.0.0"};if(o9!==null&&(u.rendererConfig=o9),typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")u=!1;else{var f=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(f.isDisabled||!f.supportsFiber)u=!0;else{try{$w=f.inject(u),MI=f}catch{}u=!!f.checkDCE}}return u},Nn.isAlreadyRendering=function(){return!1},Nn.observeVisibleRects=function(u,f,R,F){if(!Vw)throw Error(n(363));u=js(u,f);var Y=MwA(u,R,F).disconnect;return{disconnect:function(){Y()}}},Nn.shouldError=function(){return null},Nn.shouldSuspend=function(){return!1},Nn.startHostTransition=function(u,f,R,F){if(u.tag!==5)throw Error(n(476));var Y=Ke(u).queue;Ae(u,Y,f,Ey,R===null?i:function(){var AA=Ke(u).next.queue;return hA(u,AA,{},Xg()),R(F)})},Nn.updateContainer=function(u,f,R,F){var Y=f.current,AA=Xg();return $V(Y,AA,u,f,R,F),AA},Nn.updateContainerSync=function(u,f,R,F){return f.tag===0&&Vd(),$V(f.current,2,u,f,R,F),2},Nn},e.exports.default=e.exports,Object.defineProperty(e.exports,"__esModule",{value:!0})})(aDA);var lQe=aDA.exports;sDA.exports=lQe;var BQe=sDA.exports;const EQe=nw(BQe);var rDA={exports:{}},IDA={};/**
 * @license React
 * scheduler.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */(function(e){function A(v,U){var x=v.length;v.push(U);A:for(;0<x;){var T=x-1>>>1,z=v[T];if(0<n(z,U))v[T]=U,v[x]=z,x=T;else break A}}function t(v){return v.length===0?null:v[0]}function i(v){if(v.length===0)return null;var U=v[0],x=v.pop();if(x!==U){v[0]=x;A:for(var T=0,z=v.length,Z=z>>>1;T<Z;){var eA=2*(T+1)-1,aA=v[eA],sA=eA+1,pA=v[sA];if(0>n(aA,x))sA<z&&0>n(pA,aA)?(v[T]=pA,v[sA]=x,T=sA):(v[T]=aA,v[eA]=x,T=eA);else if(sA<z&&0>n(pA,x))v[T]=pA,v[sA]=x,T=sA;else break A}}return U}function n(v,U){var x=v.sortIndex-U.sortIndex;return x!==0?x:v.id-U.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var g=performance;e.unstable_now=function(){return g.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var a=[],r=[],I=1,c=null,l=3,B=!1,Q=!1,h=!1,d=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;function m(v){for(var U=t(r);U!==null;){if(U.callback===null)i(r);else if(U.startTime<=v)i(r),U.sortIndex=U.expirationTime,A(a,U);else break;U=t(r)}}function D(v){if(h=!1,m(v),!Q)if(t(a)!==null)Q=!0,J();else{var U=t(r);U!==null&&q(D,U.startTime-v)}}var S=!1,k=-1,N=5,G=-1;function M(){return!(e.unstable_now()-G<N)}function w(){if(S){var v=e.unstable_now();G=v;var U=!0;try{A:{Q=!1,h&&(h=!1,p(k),k=-1),B=!0;var x=l;try{e:{for(m(v),c=t(a);c!==null&&!(c.expirationTime>v&&M());){var T=c.callback;if(typeof T=="function"){c.callback=null,l=c.priorityLevel;var z=T(c.expirationTime<=v);if(v=e.unstable_now(),typeof z=="function"){c.callback=z,m(v),U=!0;break e}c===t(a)&&i(a),m(v)}else i(a);c=t(a)}if(c!==null)U=!0;else{var Z=t(r);Z!==null&&q(D,Z.startTime-v),U=!1}}break A}finally{c=null,l=x,B=!1}U=void 0}}finally{U?b():S=!1}}}var b;if(typeof y=="function")b=function(){y(w)};else if(typeof MessageChannel<"u"){var _=new MessageChannel,K=_.port2;_.port1.onmessage=w,b=function(){K.postMessage(null)}}else b=function(){d(w,0)};function J(){S||(S=!0,b())}function q(v,U){k=d(function(){v(e.unstable_now())},U)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(v){v.callback=null},e.unstable_continueExecution=function(){Q||B||(Q=!0,J())},e.unstable_forceFrameRate=function(v){0>v||125<v?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):N=0<v?Math.floor(1e3/v):5},e.unstable_getCurrentPriorityLevel=function(){return l},e.unstable_getFirstCallbackNode=function(){return t(a)},e.unstable_next=function(v){switch(l){case 1:case 2:case 3:var U=3;break;default:U=l}var x=l;l=U;try{return v()}finally{l=x}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(v,U){switch(v){case 1:case 2:case 3:case 4:case 5:break;default:v=3}var x=l;l=v;try{return U()}finally{l=x}},e.unstable_scheduleCallback=function(v,U,x){var T=e.unstable_now();switch(typeof x=="object"&&x!==null?(x=x.delay,x=typeof x=="number"&&0<x?T+x:T):x=T,v){case 1:var z=-1;break;case 2:z=250;break;case 5:z=1073741823;break;case 4:z=1e4;break;default:z=5e3}return z=x+z,v={id:I++,callback:U,priorityLevel:v,startTime:x,expirationTime:z,sortIndex:-1},x>T?(v.sortIndex=x,A(r,v),t(a)===null&&v===t(r)&&(h?(p(k),k=-1):h=!0,q(D,x-T))):(v.sortIndex=z,A(a,v),Q||B||(Q=!0,J())),v},e.unstable_shouldYield=M,e.unstable_wrapCallback=function(v){var U=l;return function(){var x=l;l=U;try{return v.apply(this,arguments)}finally{l=x}}}})(IDA);rDA.exports=IDA;var CgA=rDA.exports;function hV(e,A,t){if(!e)return;if(t(e)===!0)return e;let i=A?e.return:e.child;for(;i;){const n=hV(i,A,t);if(n)return n;i=A?null:i.sibling}}function CDA(e){try{return Object.defineProperties(e,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return e}}const pV=CDA(E.createContext(null));class cDA extends E.Component{render(){return E.createElement(pV.Provider,{value:this._reactInternals},this.props.children)}}function lDA(){const e=E.useContext(pV);if(e===null)throw new Error("its-fine: useFiber must be called within a <FiberProvider />!");const A=E.useId();return E.useMemo(()=>{for(const t of[e,e==null?void 0:e.alternate]){if(!t)continue;const i=hV(t,!1,n=>{let g=n.memoizedState;for(;g;){if(g.memoizedState===A)return!0;g=g.next}});if(i)return i}},[e,A])}const QQe=Symbol.for("react.context"),uQe=e=>e!==null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===QQe;function dQe(){const e=lDA(),[A]=E.useState(()=>new Map);A.clear();let t=e;for(;t;){const i=t.type;uQe(i)&&i!==pV&&!A.has(i)&&A.set(i,E.use(CDA(i))),t=t.return}return A}function hQe(){const e=dQe();return E.useMemo(()=>Array.from(e.keys()).reduce((A,t)=>i=>E.createElement(A,null,E.createElement(t.Provider,{...i,value:e.get(t)})),A=>E.createElement(cDA,{...A})),[e])}function BDA(e){let A=e.root;for(;A.getState().previousRoot;)A=A.getState().previousRoot;return A}const EDA=e=>e&&e.isOrthographicCamera,pQe=e=>e&&e.hasOwnProperty("current"),fQe=e=>e!=null&&(typeof e=="string"||typeof e=="number"||e.isColor),EG=((e,A)=>typeof window<"u"&&(((e=window.document)==null?void 0:e.createElement)||((A=window.navigator)==null?void 0:A.product)==="ReactNative"))()?E.useLayoutEffect:E.useEffect;function fV(e){const A=E.useRef(e);return EG(()=>void(A.current=e),[e]),A}function yQe(){const e=lDA(),A=hQe();return E.useMemo(()=>({children:t})=>{const n=!!hV(e,!0,g=>g.type===E.StrictMode)?E.StrictMode:E.Fragment;return C.jsx(n,{children:C.jsx(A,{children:t})})},[e,A])}function DQe({set:e}){return EG(()=>(e(new Promise(()=>null)),()=>e(!1)),[e]),null}const mQe=(e=>(e=class extends E.Component{constructor(...t){super(...t),this.state={error:!1}}componentDidCatch(t){this.props.set(t)}render(){return this.state.error?null:this.props.children}},e.getDerivedStateFromError=()=>({error:!0}),e))();function QDA(e){var A;const t=typeof window<"u"?(A=window.devicePixelRatio)!=null?A:2:1;return Array.isArray(e)?Math.min(Math.max(e[0],t),e[1]):e}function hD(e){var A;return(A=e.__r3f)==null?void 0:A.root.getState()}const lo={obj:e=>e===Object(e)&&!lo.arr(e)&&typeof e!="function",fun:e=>typeof e=="function",str:e=>typeof e=="string",num:e=>typeof e=="number",boo:e=>typeof e=="boolean",und:e=>e===void 0,nul:e=>e===null,arr:e=>Array.isArray(e),equ(e,A,{arrays:t="shallow",objects:i="reference",strict:n=!0}={}){if(typeof e!=typeof A||!!e!=!!A)return!1;if(lo.str(e)||lo.num(e)||lo.boo(e))return e===A;const g=lo.obj(e);if(g&&i==="reference")return e===A;const o=lo.arr(e);if(o&&t==="reference")return e===A;if((o||g)&&e===A)return!0;let s;for(s in e)if(!(s in A))return!1;if(g&&t==="shallow"&&i==="shallow"){for(s in n?A:e)if(!lo.equ(e[s],A[s],{strict:n,objects:"reference"}))return!1}else for(s in n?A:e)if(e[s]!==A[s])return!1;if(lo.und(s)){if(o&&e.length===0&&A.length===0||g&&Object.keys(e).length===0&&Object.keys(A).length===0)return!0;if(e!==A)return!1}return!0}};function SQe(e){const A={nodes:{},materials:{},meshes:{}};return e&&e.traverse(t=>{t.name&&(A.nodes[t.name]=t),t.material&&!A.materials[t.material.name]&&(A.materials[t.material.name]=t.material),t.isMesh&&!A.meshes[t.name]&&(A.meshes[t.name]=t)}),A}function wQe(e){e.type!=="Scene"&&(e.dispose==null||e.dispose());for(const A in e){const t=e[A];(t==null?void 0:t.type)!=="Scene"&&(t==null||t.dispose==null||t.dispose())}}const uDA=["children","key","ref"];function kQe(e){const A={};for(const t in e)uDA.includes(t)||(A[t]=e[t]);return A}function SJ(e,A,t,i){const n=e;let g=n==null?void 0:n.__r3f;return g||(g={root:A,type:t,parent:null,children:[],props:kQe(i),object:n,eventCount:0,handlers:{},isHidden:!1},n&&(n.__r3f=g)),g}function TN(e,A){let t=e[A];if(!A.includes("-"))return{root:e,key:A,target:t};t=e;for(const n of A.split("-")){var i;A=n,e=t,t=(i=t)==null?void 0:i[A]}return{root:e,key:A,target:t}}const cgA=/-\d+$/;function wJ(e,A){if(lo.str(A.props.attach)){if(cgA.test(A.props.attach)){const n=A.props.attach.replace(cgA,""),{root:g,key:o}=TN(e.object,n);Array.isArray(g[o])||(g[o]=[])}const{root:t,key:i}=TN(e.object,A.props.attach);A.previousAttach=t[i],t[i]=A.object}else lo.fun(A.props.attach)&&(A.previousAttach=A.props.attach(e.object,A.object))}function kJ(e,A){if(lo.str(A.props.attach)){const{root:t,key:i}=TN(e.object,A.props.attach),n=A.previousAttach;n===void 0?delete t[i]:t[i]=n}else A.previousAttach==null||A.previousAttach(e.object,A.object);delete A.previousAttach}const E4=[...uDA,"args","dispose","attach","object","onUpdate","dispose"],lgA=new Map;function MQe(e){let A=lgA.get(e.constructor);try{A||(A=new e.constructor,lgA.set(e.constructor,A))}catch{}return A}function NQe(e,A){const t={};for(const i in A)if(!E4.includes(i)&&!lo.equ(A[i],e.props[i])){t[i]=A[i];for(const n in A)n.startsWith(`${i}-`)&&(t[n]=A[n])}for(const i in e.props){if(E4.includes(i)||A.hasOwnProperty(i))continue;const{root:n,key:g}=TN(e.object,i);if(n.constructor&&n.constructor.length===0){const o=MQe(n);lo.und(o)||(t[g]=o[g])}else t[g]=0}return t}const RQe=["map","emissiveMap","sheenColorMap","specularColorMap","envMap"],GQe=/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/;function Iu(e,A){var t;const i=e.__r3f,n=i&&BDA(i).getState(),g=i==null?void 0:i.eventCount;for(const s in A){let a=A[s];if(E4.includes(s))continue;if(i&&GQe.test(s)){typeof a=="function"?i.handlers[s]=a:delete i.handlers[s],i.eventCount=Object.keys(i.handlers).length;continue}if(a===void 0)continue;let{root:r,key:I,target:c}=TN(e,s);if(c instanceof PS&&a instanceof PS)c.mask=a.mask;else if(c instanceof Et&&fQe(a))c.set(a);else if(c!==null&&typeof c=="object"&&typeof c.set=="function"&&typeof c.copy=="function"&&a!=null&&a.constructor&&c.constructor===a.constructor)c.copy(a);else if(c!==null&&typeof c=="object"&&typeof c.set=="function"&&Array.isArray(a))typeof c.fromArray=="function"?c.fromArray(a):c.set(...a);else if(c!==null&&typeof c=="object"&&typeof c.set=="function"&&typeof a=="number")typeof c.setScalar=="function"?c.setScalar(a):c.set(a);else{var o;r[I]=a,n&&!n.linear&&RQe.includes(I)&&(o=r[I])!=null&&o.isTexture&&r[I].format===Ar&&r[I].type===Ic&&(r[I].colorSpace=rn)}}if(i!=null&&i.parent&&n!=null&&n.internal&&(t=i.object)!=null&&t.isObject3D&&g!==i.eventCount){const s=i.object,a=n.internal.interaction.indexOf(s);a>-1&&n.internal.interaction.splice(a,1),i.eventCount&&s.raycast!==null&&n.internal.interaction.push(s)}return i&&i.props.attach===void 0&&(i.object.isBufferGeometry?i.props.attach="geometry":i.object.isMaterial&&(i.props.attach="material")),i&&Tw(i),e}function Tw(e){var A;if(!e.parent)return;e.props.onUpdate==null||e.props.onUpdate(e.object);const t=(A=e.root)==null||A.getState==null?void 0:A.getState();t&&t.internal.frames===0&&t.invalidate()}function dDA(e,A){e.manual||(EDA(e)?(e.left=A.width/-2,e.right=A.width/2,e.top=A.height/2,e.bottom=A.height/-2):e.aspect=A.width/A.height,e.updateProjectionMatrix())}const pr=e=>e==null?void 0:e.isObject3D;function VU(e){return(e.eventObject||e.object).uuid+"/"+e.index+e.instanceId}function hDA(e,A,t,i){const n=t.get(A);n&&(t.delete(A),t.size===0&&(e.delete(i),n.target.releasePointerCapture(i)))}function bQe(e,A){const{internal:t}=e.getState();t.interaction=t.interaction.filter(i=>i!==A),t.initialHits=t.initialHits.filter(i=>i!==A),t.hovered.forEach((i,n)=>{(i.eventObject===A||i.object===A)&&t.hovered.delete(n)}),t.capturedMap.forEach((i,n)=>{hDA(t.capturedMap,A,i,n)})}function UQe(e){function A(a){const{internal:r}=e.getState(),I=a.offsetX-r.initialClick[0],c=a.offsetY-r.initialClick[1];return Math.round(Math.sqrt(I*I+c*c))}function t(a){return a.filter(r=>["Move","Over","Enter","Out","Leave"].some(I=>{var c;return(c=r.__r3f)==null?void 0:c.handlers["onPointer"+I]}))}function i(a,r){const I=e.getState(),c=new Set,l=[],B=r?r(I.internal.interaction):I.internal.interaction;for(let p=0;p<B.length;p++){const y=hD(B[p]);y&&(y.raycaster.camera=void 0)}I.previousRoot||I.events.compute==null||I.events.compute(a,I);function Q(p){const y=hD(p);if(!y||!y.events.enabled||y.raycaster.camera===null)return[];if(y.raycaster.camera===void 0){var m;y.events.compute==null||y.events.compute(a,y,(m=y.previousRoot)==null?void 0:m.getState()),y.raycaster.camera===void 0&&(y.raycaster.camera=null)}return y.raycaster.camera?y.raycaster.intersectObject(p,!0):[]}let h=B.flatMap(Q).sort((p,y)=>{const m=hD(p.object),D=hD(y.object);return!m||!D?p.distance-y.distance:D.events.priority-m.events.priority||p.distance-y.distance}).filter(p=>{const y=VU(p);return c.has(y)?!1:(c.add(y),!0)});I.events.filter&&(h=I.events.filter(h,I));for(const p of h){let y=p.object;for(;y;){var d;(d=y.__r3f)!=null&&d.eventCount&&l.push({...p,eventObject:y}),y=y.parent}}if("pointerId"in a&&I.internal.capturedMap.has(a.pointerId))for(let p of I.internal.capturedMap.get(a.pointerId).values())c.has(VU(p.intersection))||l.push(p.intersection);return l}function n(a,r,I,c){if(a.length){const l={stopped:!1};for(const B of a){let Q=hD(B.object);if(Q||B.object.traverseAncestors(h=>{const d=hD(h);if(d)return Q=d,!1}),Q){const{raycaster:h,pointer:d,camera:p,internal:y}=Q,m=new SA(d.x,d.y,0).unproject(p),D=M=>{var w,b;return(w=(b=y.capturedMap.get(M))==null?void 0:b.has(B.eventObject))!=null?w:!1},S=M=>{const w={intersection:B,target:r.target};y.capturedMap.has(M)?y.capturedMap.get(M).set(B.eventObject,w):y.capturedMap.set(M,new Map([[B.eventObject,w]])),r.target.setPointerCapture(M)},k=M=>{const w=y.capturedMap.get(M);w&&hDA(y.capturedMap,B.eventObject,w,M)};let N={};for(let M in r){let w=r[M];typeof w!="function"&&(N[M]=w)}let G={...B,...N,pointer:d,intersections:a,stopped:l.stopped,delta:I,unprojectedPoint:m,ray:h.ray,camera:p,stopPropagation(){const M="pointerId"in r&&y.capturedMap.get(r.pointerId);if((!M||M.has(B.eventObject))&&(G.stopped=l.stopped=!0,y.hovered.size&&Array.from(y.hovered.values()).find(w=>w.eventObject===B.eventObject))){const w=a.slice(0,a.indexOf(B));g([...w,B])}},target:{hasPointerCapture:D,setPointerCapture:S,releasePointerCapture:k},currentTarget:{hasPointerCapture:D,setPointerCapture:S,releasePointerCapture:k},nativeEvent:r};if(c(G),l.stopped===!0)break}}}return a}function g(a){const{internal:r}=e.getState();for(const I of r.hovered.values())if(!a.length||!a.find(c=>c.object===I.object&&c.index===I.index&&c.instanceId===I.instanceId)){const l=I.eventObject.__r3f;if(r.hovered.delete(VU(I)),l!=null&&l.eventCount){const B=l.handlers,Q={...I,intersections:a};B.onPointerOut==null||B.onPointerOut(Q),B.onPointerLeave==null||B.onPointerLeave(Q)}}}function o(a,r){for(let I=0;I<r.length;I++){const c=r[I].__r3f;c==null||c.handlers.onPointerMissed==null||c.handlers.onPointerMissed(a)}}function s(a){switch(a){case"onPointerLeave":case"onPointerCancel":return()=>g([]);case"onLostPointerCapture":return r=>{const{internal:I}=e.getState();"pointerId"in r&&I.capturedMap.has(r.pointerId)&&requestAnimationFrame(()=>{I.capturedMap.has(r.pointerId)&&(I.capturedMap.delete(r.pointerId),g([]))})}}return function(I){const{onPointerMissed:c,internal:l}=e.getState();l.lastEvent.current=I;const B=a==="onPointerMove",Q=a==="onClick"||a==="onContextMenu"||a==="onDoubleClick",d=i(I,B?t:void 0),p=Q?A(I):0;a==="onPointerDown"&&(l.initialClick=[I.offsetX,I.offsetY],l.initialHits=d.map(m=>m.eventObject)),Q&&!d.length&&p<=2&&(o(I,l.interaction),c&&c(I)),B&&g(d);function y(m){const D=m.eventObject,S=D.__r3f;if(!(S!=null&&S.eventCount))return;const k=S.handlers;if(B){if(k.onPointerOver||k.onPointerEnter||k.onPointerOut||k.onPointerLeave){const N=VU(m),G=l.hovered.get(N);G?G.stopped&&m.stopPropagation():(l.hovered.set(N,m),k.onPointerOver==null||k.onPointerOver(m),k.onPointerEnter==null||k.onPointerEnter(m))}k.onPointerMove==null||k.onPointerMove(m)}else{const N=k[a];N?(!Q||l.initialHits.includes(D))&&(o(I,l.interaction.filter(G=>!l.initialHits.includes(G))),N(m)):Q&&l.initialHits.includes(D)&&o(I,l.interaction.filter(G=>!l.initialHits.includes(G)))}}n(d,I,p,y)}}return{handlePointer:s}}const BgA=e=>!!(e!=null&&e.render),yV=E.createContext(null),vQe=(e,A)=>{const t=iDA((s,a)=>{const r=new SA,I=new SA,c=new SA;function l(p=a().camera,y=I,m=a().size){const{width:D,height:S,top:k,left:N}=m,G=D/S;y.isVector3?c.copy(y):c.set(...y);const M=p.getWorldPosition(r).distanceTo(c);if(EDA(p))return{width:D/p.zoom,height:S/p.zoom,top:k,left:N,factor:1,distance:M,aspect:G};{const w=p.fov*Math.PI/180,b=2*Math.tan(w/2)*M,_=b*(D/S);return{width:_,height:b,top:k,left:N,factor:D/_,distance:M,aspect:G}}}let B;const Q=p=>s(y=>({performance:{...y.performance,current:p}})),h=new lt;return{set:s,get:a,gl:null,camera:null,raycaster:null,events:{priority:1,enabled:!0,connected:!1},scene:null,xr:null,invalidate:(p=1)=>e(a(),p),advance:(p,y)=>A(p,y,a()),legacy:!1,linear:!1,flat:!1,controls:null,clock:new IV,pointer:h,mouse:h,frameloop:"always",onPointerMissed:void 0,performance:{current:1,min:.5,max:1,debounce:200,regress:()=>{const p=a();B&&clearTimeout(B),p.performance.current!==p.performance.min&&Q(p.performance.min),B=setTimeout(()=>Q(a().performance.max),p.performance.debounce)}},size:{width:0,height:0,top:0,left:0},viewport:{initialDpr:0,dpr:0,width:0,height:0,top:0,left:0,aspect:0,distance:0,factor:0,getCurrentViewport:l},setEvents:p=>s(y=>({...y,events:{...y.events,...p}})),setSize:(p,y,m=0,D=0)=>{const S=a().camera,k={width:p,height:y,top:m,left:D};s(N=>({size:k,viewport:{...N.viewport,...l(S,I,k)}}))},setDpr:p=>s(y=>{const m=QDA(p);return{viewport:{...y.viewport,dpr:m,initialDpr:y.viewport.initialDpr||m}}}),setFrameloop:(p="always")=>{const y=a().clock;y.stop(),y.elapsedTime=0,p!=="never"&&(y.start(),y.elapsedTime=0),s(()=>({frameloop:p}))},previousRoot:void 0,internal:{interaction:[],hovered:new Map,subscribers:[],initialClick:[0,0],initialHits:[],capturedMap:new Map,lastEvent:E.createRef(),active:!1,frames:0,priority:0,subscribe:(p,y,m)=>{const D=a().internal;return D.priority=D.priority+(y>0?1:0),D.subscribers.push({ref:p,priority:y,store:m}),D.subscribers=D.subscribers.sort((S,k)=>S.priority-k.priority),()=>{const S=a().internal;S!=null&&S.subscribers&&(S.priority=S.priority-(y>0?1:0),S.subscribers=S.subscribers.filter(k=>k.ref!==p))}}}}}),i=t.getState();let n=i.size,g=i.viewport.dpr,o=i.camera;return t.subscribe(()=>{const{camera:s,size:a,viewport:r,gl:I,set:c}=t.getState();if(a.width!==n.width||a.height!==n.height||r.dpr!==g){n=a,g=r.dpr,dDA(s,a),r.dpr>0&&I.setPixelRatio(r.dpr);const l=typeof HTMLCanvasElement<"u"&&I.domElement instanceof HTMLCanvasElement;I.setSize(a.width,a.height,l)}s!==o&&(o=s,c(l=>({viewport:{...l.viewport,...l.viewport.getCurrentViewport(s)}})))}),t.subscribe(s=>e(s)),t};function DV(){const e=E.useContext(yV);if(!e)throw new Error("R3F: Hooks can only be used within the Canvas component!");return e}function ic(e=t=>t,A){return DV()(e,A)}function Ba(e,A=0){const t=DV(),i=t.getState().internal.subscribe,n=fV(e);return EG(()=>i(n,A,t),[A,i,t]),null}const EgA=new WeakMap,KQe=e=>{var A;return typeof e=="function"&&(e==null||(A=e.prototype)==null?void 0:A.constructor)===e};function pDA(e,A){return function(t,...i){let n;return KQe(t)?(n=EgA.get(t),n||(n=new t,EgA.set(t,n))):n=t,e&&e(n),Promise.all(i.map(g=>new Promise((o,s)=>n.load(g,a=>{pr(a==null?void 0:a.scene)&&Object.assign(a,SQe(a.scene)),o(a)},A,a=>s(new Error(`Could not load ${g}: ${a==null?void 0:a.message}`))))))}}function Od(e,A,t,i){const n=Array.isArray(A)?A:[A],g=oDA(pDA(t,i),[e,...n],{equal:lo.equ});return Array.isArray(A)?g:g[0]}Od.preload=function(e,A,t){const i=Array.isArray(A)?A:[A];return rQe(pDA(t),[e,...i])};Od.clear=function(e,A){const t=Array.isArray(A)?A:[A];return IQe([e,...t])};function FQe(e){const A=EQe(e);return A.injectIntoDevTools({bundleType:0,rendererPackageName:"@react-three/fiber",version:E.version}),A}const fDA=0,WS={},_Qe=/^three(?=[A-Z])/,ET=e=>`${e[0].toUpperCase()}${e.slice(1)}`;let JQe=0;const LQe=e=>typeof e=="function";function xQe(e){if(LQe(e)){const A=`${JQe++}`;return WS[A]=e,A}else Object.assign(WS,e)}function yDA(e,A){const t=ET(e),i=WS[t];if(e!=="primitive"&&!i)throw new Error(`R3F: ${t} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`);if(e==="primitive"&&!A.object)throw new Error("R3F: Primitives without 'object' are invalid!");if(A.args!==void 0&&!Array.isArray(A.args))throw new Error("R3F: The args prop must be an array!")}function TQe(e,A,t){var i;return e=ET(e)in WS?e:e.replace(_Qe,""),yDA(e,A),e==="primitive"&&(i=A.object)!=null&&i.__r3f&&delete A.object.__r3f,SJ(A.object,t,e,A)}function qQe(e){if(!e.isHidden){var A;e.props.attach&&(A=e.parent)!=null&&A.object?kJ(e.parent,e):pr(e.object)&&(e.object.visible=!1),e.isHidden=!0,Tw(e)}}function DDA(e){if(e.isHidden){var A;e.props.attach&&(A=e.parent)!=null&&A.object?wJ(e.parent,e):pr(e.object)&&e.props.visible!==!1&&(e.object.visible=!0),e.isHidden=!1,Tw(e)}}function mV(e,A,t){const i=A.root.getState();if(!(!e.parent&&e.object!==i.scene)){if(!A.object){var n,g;const o=WS[ET(A.type)];A.object=(n=A.props.object)!=null?n:new o(...(g=A.props.args)!=null?g:[]),A.object.__r3f=A}if(Iu(A.object,A.props),A.props.attach)wJ(e,A);else if(pr(A.object)&&pr(e.object)){const o=e.object.children.indexOf(t==null?void 0:t.object);if(t&&o!==-1){const s=e.object.children.indexOf(A.object);if(s!==-1){e.object.children.splice(s,1);const a=s<o?o-1:o;e.object.children.splice(a,0,A.object)}else A.object.parent=e.object,e.object.children.splice(o,0,A.object),A.object.dispatchEvent({type:"added"}),e.object.dispatchEvent({type:"childadded",child:A.object})}else e.object.add(A.object)}for(const o of A.children)mV(A,o);Tw(A)}}function jH(e,A){A&&(A.parent=e,e.children.push(A),mV(e,A))}function QgA(e,A,t){if(!A||!t)return;A.parent=e;const i=e.children.indexOf(t);i!==-1?e.children.splice(i,0,A):e.children.push(A),mV(e,A,t)}function mDA(e){if(typeof e.dispose=="function"){const A=()=>{try{e.dispose()}catch{}};typeof IS_REACT_ACT_ENVIRONMENT<"u"?A():CgA.unstable_scheduleCallback(CgA.unstable_IdlePriority,A)}}function Q4(e,A,t){if(!A)return;A.parent=null;const i=e.children.indexOf(A);i!==-1&&e.children.splice(i,1),A.props.attach?kJ(e,A):pr(A.object)&&pr(e.object)&&(e.object.remove(A.object),bQe(BDA(A),A.object));const n=A.props.dispose!==null&&t!==!1;for(let g=A.children.length-1;g>=0;g--){const o=A.children[g];Q4(A,o,n)}A.children.length=0,delete A.object.__r3f,n&&A.type!=="primitive"&&A.object.type!=="Scene"&&mDA(A.object),t===void 0&&Tw(A)}function YQe(e,A){for(const t of[e,e.alternate])if(t!==null)if(typeof t.ref=="function"){t.refCleanup==null||t.refCleanup();const i=t.ref(A);typeof i=="function"&&(t.refCleanup=i)}else t.ref&&(t.ref.current=A)}const FK=[];function HQe(){for(const[t]of FK){const i=t.parent;if(i){t.props.attach?kJ(i,t):pr(t.object)&&pr(i.object)&&i.object.remove(t.object);for(const n of t.children)n.props.attach?kJ(t,n):pr(n.object)&&pr(t.object)&&t.object.remove(n.object)}t.isHidden&&DDA(t),t.object.__r3f&&delete t.object.__r3f,t.type!=="primitive"&&mDA(t.object)}for(const[t,i,n]of FK){t.props=i;const g=t.parent;if(g){var e,A;const o=WS[ET(t.type)];t.object=(e=t.props.object)!=null?e:new o(...(A=t.props.args)!=null?A:[]),t.object.__r3f=t,YQe(n,t.object),Iu(t.object,t.props),t.props.attach?wJ(g,t):pr(t.object)&&pr(g.object)&&g.object.add(t.object);for(const s of t.children)s.props.attach?wJ(t,s):pr(s.object)&&pr(t.object)&&t.object.add(s.object);Tw(t)}}FK.length=0}const zH=()=>{},ugA={};let XU=fDA;const OQe=0,PQe=4,MJ=FQe({isPrimaryRenderer:!1,warnsIfNotActing:!1,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,createInstance:TQe,removeChild:Q4,appendChild:jH,appendInitialChild:jH,insertBefore:QgA,appendChildToContainer(e,A){const t=e.getState().scene.__r3f;!A||!t||jH(t,A)},removeChildFromContainer(e,A){const t=e.getState().scene.__r3f;!A||!t||Q4(t,A)},insertInContainerBefore(e,A,t){const i=e.getState().scene.__r3f;!A||!t||!i||QgA(i,A,t)},getRootHostContext:()=>ugA,getChildHostContext:()=>ugA,commitUpdate(e,A,t,i,n){var g,o,s;yDA(A,i);let a=!1;if((e.type==="primitive"&&t.object!==i.object||((g=i.args)==null?void 0:g.length)!==((o=t.args)==null?void 0:o.length)||(s=i.args)!=null&&s.some((I,c)=>{var l;return I!==((l=t.args)==null?void 0:l[c])}))&&(a=!0),a)FK.push([e,{...i},n]);else{const I=NQe(e,i);Object.keys(I).length&&(Object.assign(e.props,I),Iu(e.object,I))}(n.sibling===null||(n.flags&PQe)===OQe)&&HQe()},finalizeInitialChildren:()=>!1,commitMount(){},getPublicInstance:e=>e==null?void 0:e.object,prepareForCommit:()=>null,preparePortalMount:e=>SJ(e.getState().scene,e,"",{}),resetAfterCommit:()=>{},shouldSetTextContent:()=>!1,clearContainer:()=>!1,hideInstance:qQe,unhideInstance:DDA,createTextInstance:zH,hideTextInstance:zH,unhideTextInstance:zH,scheduleTimeout:typeof setTimeout=="function"?setTimeout:void 0,cancelTimeout:typeof clearTimeout=="function"?clearTimeout:void 0,noTimeout:-1,getInstanceFromNode:()=>null,beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},detachDeletedInstance(){},prepareScopeUpdate(){},getInstanceFromScope:()=>null,shouldAttemptEagerTransition:()=>!1,trackSchedulerEvent:()=>{},resolveEventType:()=>null,resolveEventTimeStamp:()=>-1.1,requestPostPaintCallback(){},maySuspendCommit:()=>!1,preloadInstance:()=>!0,startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady:()=>null,NotPendingTransition:null,HostTransitionContext:E.createContext(null),setCurrentUpdatePriority(e){XU=e},getCurrentUpdatePriority(){return XU},resolveUpdatePriority(){var e;if(XU!==fDA)return XU;switch(typeof window<"u"&&((e=window.event)==null?void 0:e.type)){case"click":case"contextmenu":case"dblclick":case"pointercancel":case"pointerdown":case"pointerup":return bK.DiscreteEventPriority;case"pointermove":case"pointerout":case"pointerover":case"pointerenter":case"pointerleave":case"wheel":return bK.ContinuousEventPriority;default:return bK.DefaultEventPriority}},resetFormInstance(){}}),wf=new Map,pD={objects:"shallow",strict:!1};function jQe(e,A){if(!A&&typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&e.parentElement){const{width:t,height:i,top:n,left:g}=e.parentElement.getBoundingClientRect();return{width:t,height:i,top:n,left:g}}else if(!A&&typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return{width:e.width,height:e.height,top:0,left:0};return{width:0,height:0,top:0,left:0,...A}}function zQe(e){const A=wf.get(e),t=A==null?void 0:A.fiber,i=A==null?void 0:A.store;A&&console.warn("R3F.createRoot should only be called once!");const n=typeof reportError=="function"?reportError:console.error,g=i||vQe(h4,hgA),o=t||MJ.createContainer(g,bK.ConcurrentRoot,null,!1,null,"",n,n,n,null);A||wf.set(e,{fiber:o,store:g});let s,a,r=!1,I=null;return{async configure(c={}){let l;I=new Promise(Z=>l=Z);let{gl:B,size:Q,scene:h,events:d,onCreated:p,shadows:y=!1,linear:m=!1,flat:D=!1,legacy:S=!1,orthographic:k=!1,frameloop:N="always",dpr:G=[1,2],performance:M,raycaster:w,camera:b,onPointerMissed:_}=c,K=g.getState(),J=K.gl;if(!K.gl){const Z={canvas:e,powerPreference:"high-performance",antialias:!0,alpha:!0},eA=typeof B=="function"?await B(Z):B;BgA(eA)?J=eA:J=new dV({...Z,...B}),K.set({gl:J})}let q=K.raycaster;q||K.set({raycaster:q=new EV});const{params:v,...U}=w||{};if(lo.equ(U,q,pD)||Iu(q,{...U}),lo.equ(v,q.params,pD)||Iu(q,{params:{...q.params,...v}}),!K.camera||K.camera===a&&!lo.equ(a,b,pD)){a=b;const Z=b==null?void 0:b.isCamera,eA=Z?b:k?new Hd(0,0,0,0,.1,1e3):new Wo(75,0,.1,1e3);Z||(eA.position.z=5,b&&(Iu(eA,b),eA.manual||("aspect"in b||"left"in b||"right"in b||"bottom"in b||"top"in b)&&(eA.manual=!0,eA.updateProjectionMatrix())),!K.camera&&!(b!=null&&b.rotation)&&eA.lookAt(0,0,0)),K.set({camera:eA}),q.camera=eA}if(!K.scene){let Z;h!=null&&h.isScene?(Z=h,SJ(Z,g,"",{})):(Z=new rG,SJ(Z,g,"",{}),h&&Iu(Z,h)),K.set({scene:Z})}d&&!K.events.handlers&&K.set({events:d(g)});const x=jQe(e,Q);if(lo.equ(x,K.size,pD)||K.setSize(x.width,x.height,x.top,x.left),G&&K.viewport.dpr!==QDA(G)&&K.setDpr(G),K.frameloop!==N&&K.setFrameloop(N),K.onPointerMissed||K.set({onPointerMissed:_}),M&&!lo.equ(M,K.performance,pD)&&K.set(Z=>({performance:{...Z.performance,...M}})),!K.xr){var T;const Z=(sA,pA)=>{const gA=g.getState();gA.frameloop!=="never"&&hgA(sA,!0,gA,pA)},eA=()=>{const sA=g.getState();sA.gl.xr.enabled=sA.gl.xr.isPresenting,sA.gl.xr.setAnimationLoop(sA.gl.xr.isPresenting?Z:null),sA.gl.xr.isPresenting||h4(sA)},aA={connect(){const sA=g.getState().gl;sA.xr.addEventListener("sessionstart",eA),sA.xr.addEventListener("sessionend",eA)},disconnect(){const sA=g.getState().gl;sA.xr.removeEventListener("sessionstart",eA),sA.xr.removeEventListener("sessionend",eA)}};typeof((T=J.xr)==null?void 0:T.addEventListener)=="function"&&aA.connect(),K.set({xr:aA})}if(J.shadowMap){const Z=J.shadowMap.enabled,eA=J.shadowMap.type;if(J.shadowMap.enabled=!!y,lo.boo(y))J.shadowMap.type=yM;else if(lo.str(y)){var z;const aA={basic:QfA,percentage:vx,soft:yM,variance:Gc};J.shadowMap.type=(z=aA[y])!=null?z:yM}else lo.obj(y)&&Object.assign(J.shadowMap,y);(Z!==J.shadowMap.enabled||eA!==J.shadowMap.type)&&(J.shadowMap.needsUpdate=!0)}return Un.enabled=!S,r||(J.outputColorSpace=m?Ka:rn,J.toneMapping=D?QB:iy),K.legacy!==S&&K.set(()=>({legacy:S})),K.linear!==m&&K.set(()=>({linear:m})),K.flat!==D&&K.set(()=>({flat:D})),B&&!lo.fun(B)&&!BgA(B)&&!lo.equ(B,J,pD)&&Iu(J,B),s=p,r=!0,l(),this},render(c){return!r&&!I&&this.configure(),I.then(()=>{MJ.updateContainer(C.jsx(ZQe,{store:g,children:c,onCreated:s,rootElement:e}),o,null,()=>{})}),g},unmount(){SDA(e)}}}function ZQe({store:e,children:A,onCreated:t,rootElement:i}){return EG(()=>{const n=e.getState();n.set(g=>({internal:{...g.internal,active:!0}})),t&&t(n),e.getState().events.connected||n.events.connect==null||n.events.connect(i)},[]),C.jsx(yV.Provider,{value:e,children:A})}function SDA(e,A){const t=wf.get(e),i=t==null?void 0:t.fiber;if(i){const n=t==null?void 0:t.store.getState();n&&(n.internal.active=!1),MJ.updateContainer(null,i,null,()=>{n&&setTimeout(()=>{try{var g,o,s,a;n.events.disconnect==null||n.events.disconnect(),(g=n.gl)==null||(o=g.renderLists)==null||o.dispose==null||o.dispose(),(s=n.gl)==null||s.forceContextLoss==null||s.forceContextLoss(),(a=n.gl)!=null&&a.xr&&n.xr.disconnect(),wQe(n.scene),wf.delete(e)}catch{}},500)})}}function lGe(e,A,t){return C.jsx(WQe,{children:e,container:A,state:t})}function WQe({state:e={},children:A,container:t}){const{events:i,size:n,...g}=e,o=DV(),[s]=E.useState(()=>new EV),[a]=E.useState(()=>new lt),r=fV((c,l)=>{let B;if(l.camera&&n){const Q=l.camera;B=c.viewport.getCurrentViewport(Q,new SA,n),Q!==c.camera&&dDA(Q,n)}return{...c,...l,scene:t,raycaster:s,pointer:a,mouse:a,previousRoot:o,events:{...c.events,...l.events,...i},size:{...c.size,...n},viewport:{...c.viewport,...B},setEvents:Q=>l.set(h=>({...h,events:{...h.events,...Q}}))}}),I=E.useMemo(()=>{const c=iDA((B,Q)=>({...g,set:B,get:Q})),l=B=>c.setState(Q=>r.current(B,Q));return l(o.getState()),o.subscribe(l),c},[o,t]);return C.jsx(C.Fragment,{children:MJ.createPortal(C.jsx(yV.Provider,{value:I,children:A}),I,null)})}const VQe=new Set,XQe=new Set,$Qe=new Set;function ZH(e,A){if(e.size)for(const{callback:t}of e.values())t(A)}function RM(e,A){switch(e){case"before":return ZH(VQe,A);case"after":return ZH(XQe,A);case"tail":return ZH($Qe,A)}}let WH,VH;function u4(e,A,t){let i=A.clock.getDelta();A.frameloop==="never"&&typeof e=="number"&&(i=e-A.clock.elapsedTime,A.clock.oldTime=A.clock.elapsedTime,A.clock.elapsedTime=e),WH=A.internal.subscribers;for(let n=0;n<WH.length;n++)VH=WH[n],VH.ref.current(VH.store.getState(),i,t);return!A.internal.priority&&A.gl.render&&A.gl.render(A.scene,A.camera),A.internal.frames=Math.max(0,A.internal.frames-1),A.frameloop==="always"?1:A.internal.frames}let NJ=!1,d4=!1,XH,dgA,fD;function wDA(e){dgA=requestAnimationFrame(wDA),NJ=!0,XH=0,RM("before",e),d4=!0;for(const t of wf.values()){var A;fD=t.store.getState(),fD.internal.active&&(fD.frameloop==="always"||fD.internal.frames>0)&&!((A=fD.gl.xr)!=null&&A.isPresenting)&&(XH+=u4(e,fD))}if(d4=!1,RM("after",e),XH===0)return RM("tail",e),NJ=!1,cancelAnimationFrame(dgA)}function h4(e,A=1){var t;if(!e)return wf.forEach(i=>h4(i.store.getState(),A));(t=e.gl.xr)!=null&&t.isPresenting||!e.internal.active||e.frameloop==="never"||(A>1?e.internal.frames=Math.min(60,e.internal.frames+A):d4?e.internal.frames=2:e.internal.frames=1,NJ||(NJ=!0,requestAnimationFrame(wDA)))}function hgA(e,A=!0,t,i){if(A&&RM("before",e),t)u4(e,t,i);else for(const n of wf.values())u4(e,n.store.getState());A&&RM("after",e)}const $H={onClick:["click",!1],onContextMenu:["contextmenu",!1],onDoubleClick:["dblclick",!1],onWheel:["wheel",!0],onPointerDown:["pointerdown",!0],onPointerUp:["pointerup",!0],onPointerLeave:["pointerleave",!0],onPointerMove:["pointermove",!0],onPointerCancel:["pointercancel",!0],onLostPointerCapture:["lostpointercapture",!0]};function Aue(e){const{handlePointer:A}=UQe(e);return{priority:1,enabled:!0,compute(t,i,n){i.pointer.set(t.offsetX/i.size.width*2-1,-(t.offsetY/i.size.height)*2+1),i.raycaster.setFromCamera(i.pointer,i.camera)},connected:void 0,handlers:Object.keys($H).reduce((t,i)=>({...t,[i]:A(i)}),{}),update:()=>{var t;const{events:i,internal:n}=e.getState();(t=n.lastEvent)!=null&&t.current&&i.handlers&&i.handlers.onPointerMove(n.lastEvent.current)},connect:t=>{const{set:i,events:n}=e.getState();if(n.disconnect==null||n.disconnect(),i(g=>({events:{...g.events,connected:t}})),n.handlers)for(const g in n.handlers){const o=n.handlers[g],[s,a]=$H[g];t.addEventListener(s,o,{passive:a})}},disconnect:()=>{const{set:t,events:i}=e.getState();if(i.connected){if(i.handlers)for(const n in i.handlers){const g=i.handlers[n],[o]=$H[n];i.connected.removeEventListener(o,g)}t(n=>({events:{...n.events,connected:void 0}}))}}}}function pgA(e,A){let t;return(...i)=>{window.clearTimeout(t),t=window.setTimeout(()=>e(...i),A)}}function eue({debounce:e,scroll:A,polyfill:t,offsetSize:i}={debounce:0,scroll:!1,offsetSize:!1}){const n=t||(typeof window>"u"?class{}:window.ResizeObserver);if(!n)throw new Error("This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills");const[g,o]=E.useState({left:0,top:0,width:0,height:0,bottom:0,right:0,x:0,y:0}),s=E.useRef({element:null,scrollContainers:null,resizeObserver:null,lastBounds:g,orientationHandler:null}),a=e?typeof e=="number"?e:e.scroll:null,r=e?typeof e=="number"?e:e.resize:null,I=E.useRef(!1);E.useEffect(()=>(I.current=!0,()=>void(I.current=!1)));const[c,l,B]=E.useMemo(()=>{const p=()=>{if(!s.current.element)return;const{left:y,top:m,width:D,height:S,bottom:k,right:N,x:G,y:M}=s.current.element.getBoundingClientRect(),w={left:y,top:m,width:D,height:S,bottom:k,right:N,x:G,y:M};s.current.element instanceof HTMLElement&&i&&(w.height=s.current.element.offsetHeight,w.width=s.current.element.offsetWidth),Object.freeze(w),I.current&&!gue(s.current.lastBounds,w)&&o(s.current.lastBounds=w)};return[p,r?pgA(p,r):p,a?pgA(p,a):p]},[o,i,a,r]);function Q(){s.current.scrollContainers&&(s.current.scrollContainers.forEach(p=>p.removeEventListener("scroll",B,!0)),s.current.scrollContainers=null),s.current.resizeObserver&&(s.current.resizeObserver.disconnect(),s.current.resizeObserver=null),s.current.orientationHandler&&("orientation"in screen&&"removeEventListener"in screen.orientation?screen.orientation.removeEventListener("change",s.current.orientationHandler):"onorientationchange"in window&&window.removeEventListener("orientationchange",s.current.orientationHandler))}function h(){s.current.element&&(s.current.resizeObserver=new n(B),s.current.resizeObserver.observe(s.current.element),A&&s.current.scrollContainers&&s.current.scrollContainers.forEach(p=>p.addEventListener("scroll",B,{capture:!0,passive:!0})),s.current.orientationHandler=()=>{B()},"orientation"in screen&&"addEventListener"in screen.orientation?screen.orientation.addEventListener("change",s.current.orientationHandler):"onorientationchange"in window&&window.addEventListener("orientationchange",s.current.orientationHandler))}const d=p=>{!p||p===s.current.element||(Q(),s.current.element=p,s.current.scrollContainers=kDA(p),h())};return iue(B,!!A),tue(l),E.useEffect(()=>{Q(),h()},[A,B,l]),E.useEffect(()=>Q,[]),[d,g,c]}function tue(e){E.useEffect(()=>{const A=e;return window.addEventListener("resize",A),()=>void window.removeEventListener("resize",A)},[e])}function iue(e,A){E.useEffect(()=>{if(A){const t=e;return window.addEventListener("scroll",t,{capture:!0,passive:!0}),()=>void window.removeEventListener("scroll",t,!0)}},[e,A])}function kDA(e){const A=[];if(!e||e===document.body)return A;const{overflow:t,overflowX:i,overflowY:n}=window.getComputedStyle(e);return[t,i,n].some(g=>g==="auto"||g==="scroll")&&A.push(e),[...A,...kDA(e.parentElement)]}const nue=["x","y","top","bottom","left","right","width","height"],gue=(e,A)=>nue.every(t=>e[t]===A[t]);function oue({ref:e,children:A,fallback:t,resize:i,style:n,gl:g,events:o=Aue,eventSource:s,eventPrefix:a,shadows:r,linear:I,flat:c,legacy:l,orthographic:B,frameloop:Q,dpr:h,performance:d,raycaster:p,camera:y,scene:m,onPointerMissed:D,onCreated:S,...k}){E.useMemo(()=>xQe(JEe),[]);const N=yQe(),[G,M]=eue({scroll:!0,debounce:{scroll:50,resize:0},...i}),w=E.useRef(null),b=E.useRef(null);E.useImperativeHandle(e,()=>w.current);const _=fV(D),[K,J]=E.useState(!1),[q,v]=E.useState(!1);if(K)throw K;if(q)throw q;const U=E.useRef(null);EG(()=>{const T=w.current;if(M.width>0&&M.height>0&&T){U.current||(U.current=zQe(T));async function z(){await U.current.configure({gl:g,scene:m,events:o,shadows:r,linear:I,flat:c,legacy:l,orthographic:B,frameloop:Q,dpr:h,performance:d,raycaster:p,camera:y,size:M,onPointerMissed:(...Z)=>_.current==null?void 0:_.current(...Z),onCreated:Z=>{Z.events.connect==null||Z.events.connect(s?pQe(s)?s.current:s:b.current),a&&Z.setEvents({compute:(eA,aA)=>{const sA=eA[a+"X"],pA=eA[a+"Y"];aA.pointer.set(sA/aA.size.width*2-1,-(pA/aA.size.height)*2+1),aA.raycaster.setFromCamera(aA.pointer,aA.camera)}}),S==null||S(Z)}}),U.current.render(C.jsx(N,{children:C.jsx(mQe,{set:v,children:C.jsx(E.Suspense,{fallback:C.jsx(DQe,{set:J}),children:A??null})})}))}z()}}),E.useEffect(()=>{const T=w.current;if(T)return()=>SDA(T)},[]);const x=s?"none":"auto";return C.jsx("div",{ref:b,style:{position:"relative",width:"100%",height:"100%",overflow:"hidden",pointerEvents:x,...n},...k,children:C.jsx("div",{ref:G,style:{width:"100%",height:"100%"},children:C.jsx("canvas",{ref:w,style:{display:"block"},children:t})})})}function QG(e){return C.jsx(cDA,{children:C.jsx(oue,{...e})})}const sue=parseInt(tG.replace(/\D+/g,""));function aue(e,A=1e-4){A=Math.max(A,Number.EPSILON);const t={},i=e.getIndex(),n=e.getAttribute("position"),g=i?i.count:n.count;let o=0;const s=Object.keys(e.attributes),a={},r={},I=[],c=["getX","getY","getZ","getW"];for(let h=0,d=s.length;h<d;h++){const p=s[h];a[p]=[];const y=e.morphAttributes[p];y&&(r[p]=new Array(y.length).fill(0).map(()=>[]))}const l=Math.log10(1/A),B=Math.pow(10,l);for(let h=0;h<g;h++){const d=i?i.getX(h):h;let p="";for(let y=0,m=s.length;y<m;y++){const D=s[y],S=e.getAttribute(D),k=S.itemSize;for(let N=0;N<k;N++)p+=`${~~(S[c[N]](d)*B)},`}if(p in t)I.push(t[p]);else{for(let y=0,m=s.length;y<m;y++){const D=s[y],S=e.getAttribute(D),k=e.morphAttributes[D],N=S.itemSize,G=a[D],M=r[D];for(let w=0;w<N;w++){const b=c[w];if(G.push(S[b](d)),k)for(let _=0,K=k.length;_<K;_++)M[_].push(k[_][b](d))}}t[p]=o,I.push(o),o++}}const Q=e.clone();for(let h=0,d=s.length;h<d;h++){const p=s[h],y=e.getAttribute(p),m=new y.array.constructor(a[p]),D=new ji(m,y.itemSize,y.normalized);if(Q.setAttribute(p,D),p in r)for(let S=0;S<r[p].length;S++){const k=e.morphAttributes[p][S],N=new k.array.constructor(r[p][S]),G=new ji(N,k.itemSize,k.normalized);Q.morphAttributes[p][S]=G}}return Q.setIndex(I),Q}function fgA(e,A){if(A===FW)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(A===Df||A===oG){let t=e.getIndex();if(t===null){const o=[],s=e.getAttribute("position");if(s!==void 0){for(let a=0;a<s.count;a++)o.push(a);e.setIndex(o),t=e.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),e}const i=t.count-2,n=[];if(t)if(A===Df)for(let o=1;o<=i;o++)n.push(t.getX(0)),n.push(t.getX(o)),n.push(t.getX(o+1));else for(let o=0;o<i;o++)o%2===0?(n.push(t.getX(o)),n.push(t.getX(o+1)),n.push(t.getX(o+2))):(n.push(t.getX(o+2)),n.push(t.getX(o+1)),n.push(t.getX(o)));n.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const g=e.clone();return g.setIndex(n),g.clearGroups(),g}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",A),e}function MDA(e,A,t={}){const i=new SA,n=new oo,g=new SA,o=new ni,s=new ni,a=new ni;t.preserveMatrix=t.preserveMatrix!==void 0?t.preserveMatrix:!0,t.preservePosition=t.preservePosition!==void 0?t.preservePosition:!0,t.preserveHipPosition=t.preserveHipPosition!==void 0?t.preserveHipPosition:!1,t.useTargetMatrix=t.useTargetMatrix!==void 0?t.useTargetMatrix:!1,t.hip=t.hip!==void 0?t.hip:"hip",t.names=t.names||{};const r=A.isObject3D?A.skeleton.bones:RJ(A),I=e.isObject3D?e.skeleton.bones:RJ(e);let c,l,B,Q,h;if(e.isObject3D?e.skeleton.pose():(t.useTargetMatrix=!0,t.preserveMatrix=!1),t.preservePosition){h=[];for(let d=0;d<I.length;d++)h.push(I[d].position.clone())}if(t.preserveMatrix){e.updateMatrixWorld(),e.matrixWorld.identity();for(let d=0;d<e.children.length;++d)e.children[d].updateMatrixWorld(!0)}if(t.offsets){c=[];for(let d=0;d<I.length;++d)l=I[d],B=t.names[l.name]||l.name,t.offsets[B]&&(l.matrix.multiply(t.offsets[B]),l.matrix.decompose(l.position,l.quaternion,l.scale),l.updateMatrixWorld()),c.push(l.matrixWorld.clone())}for(let d=0;d<I.length;++d){if(l=I[d],B=t.names[l.name]||l.name,Q=NDA(B,r),a.copy(l.matrixWorld),Q){if(Q.updateMatrixWorld(),t.useTargetMatrix?s.copy(Q.matrixWorld):(s.copy(e.matrixWorld).invert(),s.multiply(Q.matrixWorld)),g.setFromMatrixScale(s),s.scale(g.set(1/g.x,1/g.y,1/g.z)),a.makeRotationFromQuaternion(n.setFromRotationMatrix(s)),e.isObject3D){const p=I.indexOf(l),y=c?c[p]:o.copy(e.skeleton.boneInverses[p]).invert();a.multiply(y)}a.copyPosition(s)}l.parent&&l.parent.isBone?(l.matrix.copy(l.parent.matrixWorld).invert(),l.matrix.multiply(a)):l.matrix.copy(a),t.preserveHipPosition&&B===t.hip&&l.matrix.setPosition(i.set(0,l.position.y,0)),l.matrix.decompose(l.position,l.quaternion,l.scale),l.updateMatrixWorld()}if(t.preservePosition)for(let d=0;d<I.length;++d)l=I[d],B=t.names[l.name]||l.name,B!==t.hip&&l.position.copy(h[d]);t.preserveMatrix&&e.updateMatrixWorld(!0)}function rue(e,A,t,i={}){i.useFirstFramePosition=i.useFirstFramePosition!==void 0?i.useFirstFramePosition:!1,i.fps=i.fps!==void 0?i.fps:30,i.names=i.names||[],A.isObject3D||(A=Cue(A));const n=Math.round(t.duration*(i.fps/1e3)*1e3),g=1/i.fps,o=[],s=new lV(A),a=RJ(e.skeleton),r=[];let I,c,l,B,Q;s.clipAction(t).play(),s.update(0),A.updateMatrixWorld();for(let h=0;h<n;++h){const d=h*g;MDA(e,A,i);for(let p=0;p<a.length;++p)Q=i.names[a[p].name]||a[p].name,l=NDA(Q,A.skeleton),l&&(c=a[p],B=r[p]=r[p]||{bone:c},i.hip===Q&&(B.pos||(B.pos={times:new Float32Array(n),values:new Float32Array(n*3)}),i.useFirstFramePosition&&(h===0&&(I=c.position.clone()),c.position.sub(I)),B.pos.times[h]=d,c.position.toArray(B.pos.values,h*3)),B.quat||(B.quat={times:new Float32Array(n),values:new Float32Array(n*4)}),B.quat.times[h]=d,c.quaternion.toArray(B.quat.values,h*4));s.update(g),A.updateMatrixWorld()}for(let h=0;h<r.length;++h)B=r[h],B&&(B.pos&&o.push(new mB(".bones["+B.bone.name+"].position",B.pos.times,B.pos.values)),o.push(new DB(".bones["+B.bone.name+"].quaternion",B.quat.times,B.quat.values)));return s.uncacheAction(t),new fd(t.name,-1,o)}function Iue(e){const A=new Map,t=new Map,i=e.clone();return RDA(e,i,function(n,g){A.set(g,n),t.set(n,g)}),i.traverse(function(n){if(!n.isSkinnedMesh)return;const g=n,o=A.get(n),s=o.skeleton.bones;g.skeleton=o.skeleton.clone(),g.bindMatrix.copy(o.bindMatrix),g.skeleton.bones=s.map(function(a){return t.get(a)}),g.bind(g.skeleton,g.bindMatrix)}),i}function NDA(e,A){for(let t=0,i=RJ(A);t<i.length;t++)if(e===i[t].name)return i[t]}function RJ(e){return Array.isArray(e)?e:e.bones}function Cue(e){const A=new HyA(e.bones[0]);return A.skeleton=e,A}function RDA(e,A,t){t(e,A);for(let i=0;i<e.children.length;i++)RDA(e.children[i],A.children[i],t)}const cue={retarget:MDA,retargetClip:rue,clone:Iue};function GJ(e){if(typeof TextDecoder<"u")return new TextDecoder().decode(e);let A="";for(let t=0,i=e.length;t<i;t++)A+=String.fromCharCode(e[t]);try{return decodeURIComponent(escape(A))}catch{return A}}const up="srgb",YE="srgb-linear",ygA=3001,lue=3e3;let SV=class extends la{constructor(A){super(A),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new due(t)}),this.register(function(t){return new hue(t)}),this.register(function(t){return new Mue(t)}),this.register(function(t){return new Nue(t)}),this.register(function(t){return new Rue(t)}),this.register(function(t){return new fue(t)}),this.register(function(t){return new yue(t)}),this.register(function(t){return new Due(t)}),this.register(function(t){return new mue(t)}),this.register(function(t){return new uue(t)}),this.register(function(t){return new Sue(t)}),this.register(function(t){return new pue(t)}),this.register(function(t){return new kue(t)}),this.register(function(t){return new wue(t)}),this.register(function(t){return new Eue(t)}),this.register(function(t){return new Gue(t)}),this.register(function(t){return new bue(t)})}load(A,t,i,n){const g=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const r=AC.extractUrlBase(A);o=AC.resolveURL(r,this.path)}else o=AC.extractUrlBase(A);this.manager.itemStart(A);const s=function(r){n?n(r):console.error(r),g.manager.itemError(A),g.manager.itemEnd(A)},a=new or(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(A,function(r){try{g.parse(r,o,function(I){t(I),g.manager.itemEnd(A)},s)}catch(I){s(I)}},i,s)}setDRACOLoader(A){return this.dracoLoader=A,this}setDDSLoader(){throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')}setKTX2Loader(A){return this.ktx2Loader=A,this}setMeshoptDecoder(A){return this.meshoptDecoder=A,this}register(A){return this.pluginCallbacks.indexOf(A)===-1&&this.pluginCallbacks.push(A),this}unregister(A){return this.pluginCallbacks.indexOf(A)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(A),1),this}parse(A,t,i,n){let g;const o={},s={};if(typeof A=="string")g=JSON.parse(A);else if(A instanceof ArrayBuffer)if(GJ(new Uint8Array(A.slice(0,4)))===GDA){try{o[Kn.KHR_BINARY_GLTF]=new Uue(A)}catch(I){n&&n(I);return}g=JSON.parse(o[Kn.KHR_BINARY_GLTF].content)}else g=JSON.parse(GJ(new Uint8Array(A)));else g=A;if(g.asset===void 0||g.asset.version[0]<2){n&&n(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const a=new Pue(g,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});a.fileLoader.setRequestHeader(this.requestHeader);for(let r=0;r<this.pluginCallbacks.length;r++){const I=this.pluginCallbacks[r](a);I.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),s[I.name]=I,o[I.name]=!0}if(g.extensionsUsed)for(let r=0;r<g.extensionsUsed.length;++r){const I=g.extensionsUsed[r],c=g.extensionsRequired||[];switch(I){case Kn.KHR_MATERIALS_UNLIT:o[I]=new Que;break;case Kn.KHR_DRACO_MESH_COMPRESSION:o[I]=new vue(g,this.dracoLoader);break;case Kn.KHR_TEXTURE_TRANSFORM:o[I]=new Kue;break;case Kn.KHR_MESH_QUANTIZATION:o[I]=new Fue;break;default:c.indexOf(I)>=0&&s[I]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+I+'".')}}a.setExtensions(o),a.setPlugins(s),a.parse(i,n)}parseAsync(A,t){const i=this;return new Promise(function(n,g){i.parse(A,t,n,g)})}};function Bue(){let e={};return{get:function(A){return e[A]},add:function(A,t){e[A]=t},remove:function(A){delete e[A]},removeAll:function(){e={}}}}const Kn={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};let Eue=class{constructor(A){this.parser=A,this.name=Kn.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const A=this.parser,t=this.parser.json.nodes||[];for(let i=0,n=t.length;i<n;i++){const g=t[i];g.extensions&&g.extensions[this.name]&&g.extensions[this.name].light!==void 0&&A._addNodeRef(this.cache,g.extensions[this.name].light)}}_loadLight(A){const t=this.parser,i="light:"+A;let n=t.cache.get(i);if(n)return n;const g=t.json,a=((g.extensions&&g.extensions[this.name]||{}).lights||[])[A];let r;const I=new Et(16777215);a.color!==void 0&&I.setRGB(a.color[0],a.color[1],a.color[2],YE);const c=a.range!==void 0?a.range:0;switch(a.type){case"directional":r=new zp(I),r.target.position.set(0,0,-1),r.add(r.target);break;case"point":r=new BG(I),r.distance=c;break;case"spot":r=new CT(I),r.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,r.angle=a.spot.outerConeAngle,r.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,r.target.position.set(0,0,-1),r.add(r.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return r.position.set(0,0,0),r.decay=2,IE(r,a),a.intensity!==void 0&&(r.intensity=a.intensity),r.name=t.createUniqueName(a.name||"light_"+A),n=Promise.resolve(r),t.cache.add(i,n),n}getDependency(A,t){if(A==="light")return this._loadLight(t)}createNodeAttachment(A){const t=this,i=this.parser,g=i.json.nodes[A],s=(g.extensions&&g.extensions[this.name]||{}).light;return s===void 0?null:this._loadLight(s).then(function(a){return i._getNodeRef(t.cache,s,a)})}},Que=class{constructor(){this.name=Kn.KHR_MATERIALS_UNLIT}getMaterialType(){return kg}extendParams(A,t,i){const n=[];A.color=new Et(1,1,1),A.opacity=1;const g=t.pbrMetallicRoughness;if(g){if(Array.isArray(g.baseColorFactor)){const o=g.baseColorFactor;A.color.setRGB(o[0],o[1],o[2],YE),A.opacity=o[3]}g.baseColorTexture!==void 0&&n.push(i.assignTexture(A,"map",g.baseColorTexture,up))}return Promise.all(n)}},uue=class{constructor(A){this.parser=A,this.name=Kn.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(A,t){const n=this.parser.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=n.extensions[this.name].emissiveStrength;return g!==void 0&&(t.emissiveIntensity=g),Promise.resolve()}},due=class{constructor(A){this.parser=A,this.name=Kn.KHR_MATERIALS_CLEARCOAT}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];if(o.clearcoatFactor!==void 0&&(t.clearcoat=o.clearcoatFactor),o.clearcoatTexture!==void 0&&g.push(i.assignTexture(t,"clearcoatMap",o.clearcoatTexture)),o.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=o.clearcoatRoughnessFactor),o.clearcoatRoughnessTexture!==void 0&&g.push(i.assignTexture(t,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),o.clearcoatNormalTexture!==void 0&&(g.push(i.assignTexture(t,"clearcoatNormalMap",o.clearcoatNormalTexture)),o.clearcoatNormalTexture.scale!==void 0)){const s=o.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new lt(s,s)}return Promise.all(g)}},hue=class{constructor(A){this.parser=A,this.name=Kn.KHR_MATERIALS_DISPERSION}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const n=this.parser.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=n.extensions[this.name];return t.dispersion=g.dispersion!==void 0?g.dispersion:0,Promise.resolve()}},pue=class{constructor(A){this.parser=A,this.name=Kn.KHR_MATERIALS_IRIDESCENCE}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];return o.iridescenceFactor!==void 0&&(t.iridescence=o.iridescenceFactor),o.iridescenceTexture!==void 0&&g.push(i.assignTexture(t,"iridescenceMap",o.iridescenceTexture)),o.iridescenceIor!==void 0&&(t.iridescenceIOR=o.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),o.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=o.iridescenceThicknessMinimum),o.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=o.iridescenceThicknessMaximum),o.iridescenceThicknessTexture!==void 0&&g.push(i.assignTexture(t,"iridescenceThicknessMap",o.iridescenceThicknessTexture)),Promise.all(g)}},fue=class{constructor(A){this.parser=A,this.name=Kn.KHR_MATERIALS_SHEEN}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[];t.sheenColor=new Et(0,0,0),t.sheenRoughness=0,t.sheen=1;const o=n.extensions[this.name];if(o.sheenColorFactor!==void 0){const s=o.sheenColorFactor;t.sheenColor.setRGB(s[0],s[1],s[2],YE)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&g.push(i.assignTexture(t,"sheenColorMap",o.sheenColorTexture,up)),o.sheenRoughnessTexture!==void 0&&g.push(i.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(g)}},yue=class{constructor(A){this.parser=A,this.name=Kn.KHR_MATERIALS_TRANSMISSION}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];return o.transmissionFactor!==void 0&&(t.transmission=o.transmissionFactor),o.transmissionTexture!==void 0&&g.push(i.assignTexture(t,"transmissionMap",o.transmissionTexture)),Promise.all(g)}},Due=class{constructor(A){this.parser=A,this.name=Kn.KHR_MATERIALS_VOLUME}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];t.thickness=o.thicknessFactor!==void 0?o.thicknessFactor:0,o.thicknessTexture!==void 0&&g.push(i.assignTexture(t,"thicknessMap",o.thicknessTexture)),t.attenuationDistance=o.attenuationDistance||1/0;const s=o.attenuationColor||[1,1,1];return t.attenuationColor=new Et().setRGB(s[0],s[1],s[2],YE),Promise.all(g)}},mue=class{constructor(A){this.parser=A,this.name=Kn.KHR_MATERIALS_IOR}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const n=this.parser.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=n.extensions[this.name];return t.ior=g.ior!==void 0?g.ior:1.5,Promise.resolve()}},Sue=class{constructor(A){this.parser=A,this.name=Kn.KHR_MATERIALS_SPECULAR}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];t.specularIntensity=o.specularFactor!==void 0?o.specularFactor:1,o.specularTexture!==void 0&&g.push(i.assignTexture(t,"specularIntensityMap",o.specularTexture));const s=o.specularColorFactor||[1,1,1];return t.specularColor=new Et().setRGB(s[0],s[1],s[2],YE),o.specularColorTexture!==void 0&&g.push(i.assignTexture(t,"specularColorMap",o.specularColorTexture,up)),Promise.all(g)}},wue=class{constructor(A){this.parser=A,this.name=Kn.EXT_MATERIALS_BUMP}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];return t.bumpScale=o.bumpFactor!==void 0?o.bumpFactor:1,o.bumpTexture!==void 0&&g.push(i.assignTexture(t,"bumpMap",o.bumpTexture)),Promise.all(g)}},kue=class{constructor(A){this.parser=A,this.name=Kn.KHR_MATERIALS_ANISOTROPY}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];return o.anisotropyStrength!==void 0&&(t.anisotropy=o.anisotropyStrength),o.anisotropyRotation!==void 0&&(t.anisotropyRotation=o.anisotropyRotation),o.anisotropyTexture!==void 0&&g.push(i.assignTexture(t,"anisotropyMap",o.anisotropyTexture)),Promise.all(g)}},Mue=class{constructor(A){this.parser=A,this.name=Kn.KHR_TEXTURE_BASISU}loadTexture(A){const t=this.parser,i=t.json,n=i.textures[A];if(!n.extensions||!n.extensions[this.name])return null;const g=n.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(i.extensionsRequired&&i.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(A,g.source,o)}},Nue=class{constructor(A){this.parser=A,this.name=Kn.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(A){const t=this.name,i=this.parser,n=i.json,g=n.textures[A];if(!g.extensions||!g.extensions[t])return null;const o=g.extensions[t],s=n.images[o.source];let a=i.textureLoader;if(s.uri){const r=i.options.manager.getHandler(s.uri);r!==null&&(a=r)}return this.detectSupport().then(function(r){if(r)return i.loadTextureImage(A,o.source,a);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return i.loadTexture(A)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(A){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){A(t.height===1)}})),this.isSupported}},Rue=class{constructor(A){this.parser=A,this.name=Kn.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(A){const t=this.name,i=this.parser,n=i.json,g=n.textures[A];if(!g.extensions||!g.extensions[t])return null;const o=g.extensions[t],s=n.images[o.source];let a=i.textureLoader;if(s.uri){const r=i.options.manager.getHandler(s.uri);r!==null&&(a=r)}return this.detectSupport().then(function(r){if(r)return i.loadTextureImage(A,o.source,a);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return i.loadTexture(A)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(A){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){A(t.height===1)}})),this.isSupported}},Gue=class{constructor(A){this.name=Kn.EXT_MESHOPT_COMPRESSION,this.parser=A}loadBufferView(A){const t=this.parser.json,i=t.bufferViews[A];if(i.extensions&&i.extensions[this.name]){const n=i.extensions[this.name],g=this.parser.getDependency("buffer",n.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return g.then(function(s){const a=n.byteOffset||0,r=n.byteLength||0,I=n.count,c=n.byteStride,l=new Uint8Array(s,a,r);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(I,c,l,n.mode,n.filter).then(function(B){return B.buffer}):o.ready.then(function(){const B=new ArrayBuffer(I*c);return o.decodeGltfBuffer(new Uint8Array(B),I,c,l,n.mode,n.filter),B})})}else return null}},bue=class{constructor(A){this.name=Kn.EXT_MESH_GPU_INSTANCING,this.parser=A}createNodeMesh(A){const t=this.parser.json,i=t.nodes[A];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const n=t.meshes[i.mesh];for(const r of n.primitives)if(r.mode!==bC.TRIANGLES&&r.mode!==bC.TRIANGLE_STRIP&&r.mode!==bC.TRIANGLE_FAN&&r.mode!==void 0)return null;const o=i.extensions[this.name].attributes,s=[],a={};for(const r in o)s.push(this.parser.getDependency("accessor",o[r]).then(I=>(a[r]=I,a[r])));return s.length<1?null:(s.push(this.parser.createNodeMesh(A)),Promise.all(s).then(r=>{const I=r.pop(),c=I.isGroup?I.children:[I],l=r[0].count,B=[];for(const Q of c){const h=new ni,d=new SA,p=new oo,y=new SA(1,1,1),m=new CG(Q.geometry,Q.material,l);for(let D=0;D<l;D++)a.TRANSLATION&&d.fromBufferAttribute(a.TRANSLATION,D),a.ROTATION&&p.fromBufferAttribute(a.ROTATION,D),a.SCALE&&y.fromBufferAttribute(a.SCALE,D),m.setMatrixAt(D,h.compose(d,p,y));for(const D in a)if(D==="_COLOR_0"){const S=a[D];m.instanceColor=new hd(S.array,S.itemSize,S.normalized)}else D!=="TRANSLATION"&&D!=="ROTATION"&&D!=="SCALE"&&Q.geometry.setAttribute(D,a[D]);Bn.prototype.copy.call(m,Q),this.parser.assignFinalMaterial(m),B.push(m)}return I.isGroup?(I.clear(),I.add(...B),I):B[0]}))}};const GDA="glTF",W0=12,DgA={JSON:1313821514,BIN:5130562};let Uue=class{constructor(A){this.name=Kn.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(A,0,W0);if(this.header={magic:GJ(new Uint8Array(A.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==GDA)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-W0,n=new DataView(A,W0);let g=0;for(;g<i;){const o=n.getUint32(g,!0);g+=4;const s=n.getUint32(g,!0);if(g+=4,s===DgA.JSON){const a=new Uint8Array(A,W0+g,o);this.content=GJ(a)}else if(s===DgA.BIN){const a=W0+g;this.body=A.slice(a,a+o)}g+=o}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}},vue=class{constructor(A,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Kn.KHR_DRACO_MESH_COMPRESSION,this.json=A,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(A,t){const i=this.json,n=this.dracoLoader,g=A.extensions[this.name].bufferView,o=A.extensions[this.name].attributes,s={},a={},r={};for(const I in o){const c=p4[I]||I.toLowerCase();s[c]=o[I]}for(const I in A.attributes){const c=p4[I]||I.toLowerCase();if(o[I]!==void 0){const l=i.accessors[A.attributes[I]],B=zm[l.componentType];r[c]=B.name,a[c]=l.normalized===!0}}return t.getDependency("bufferView",g).then(function(I){return new Promise(function(c,l){n.decodeDracoFile(I,function(B){for(const Q in B.attributes){const h=B.attributes[Q],d=a[Q];d!==void 0&&(h.normalized=d)}c(B)},s,r,YE,l)})})}},Kue=class{constructor(){this.name=Kn.KHR_TEXTURE_TRANSFORM}extendTexture(A,t){return(t.texCoord===void 0||t.texCoord===A.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(A=A.clone(),t.texCoord!==void 0&&(A.channel=t.texCoord),t.offset!==void 0&&A.offset.fromArray(t.offset),t.rotation!==void 0&&(A.rotation=t.rotation),t.scale!==void 0&&A.repeat.fromArray(t.scale),A.needsUpdate=!0),A}},Fue=class{constructor(){this.name=Kn.KHR_MESH_QUANTIZATION}},bDA=class extends oy{constructor(A,t,i,n){super(A,t,i,n)}copySampleValue_(A){const t=this.resultBuffer,i=this.sampleValues,n=this.valueSize,g=A*n*3+n;for(let o=0;o!==n;o++)t[o]=i[g+o];return t}interpolate_(A,t,i,n){const g=this.resultBuffer,o=this.sampleValues,s=this.valueSize,a=s*2,r=s*3,I=n-t,c=(i-t)/I,l=c*c,B=l*c,Q=A*r,h=Q-r,d=-2*B+3*l,p=B-l,y=1-d,m=p-l+c;for(let D=0;D!==s;D++){const S=o[h+D+s],k=o[h+D+a]*I,N=o[Q+D+s],G=o[Q+D]*I;g[D]=y*S+m*k+d*N+p*G}return g}};const _ue=new oo;let Jue=class extends bDA{interpolate_(A,t,i,n){const g=super.interpolate_(A,t,i,n);return _ue.fromArray(g).normalize().toArray(g),g}};const bC={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},zm={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},mgA={9728:Ss,9729:qg,9984:nG,9985:Hp,9986:Nu,9987:Gr},SgA={33071:oI,33648:ff,10497:Fr},AO={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},p4={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",...sue>=152?{TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3"}:{TEXCOORD_0:"uv",TEXCOORD_1:"uv2"},COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},qQ={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Lue={CUBICSPLINE:void 0,LINEAR:dd,STEP:yf},eO={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function xue(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new xg({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:tl})),e.DefaultMaterial}function Uh(e,A,t){for(const i in t.extensions)e[i]===void 0&&(A.userData.gltfExtensions=A.userData.gltfExtensions||{},A.userData.gltfExtensions[i]=t.extensions[i])}function IE(e,A){A.extras!==void 0&&(typeof A.extras=="object"?Object.assign(e.userData,A.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+A.extras))}function Tue(e,A,t){let i=!1,n=!1,g=!1;for(let r=0,I=A.length;r<I;r++){const c=A[r];if(c.POSITION!==void 0&&(i=!0),c.NORMAL!==void 0&&(n=!0),c.COLOR_0!==void 0&&(g=!0),i&&n&&g)break}if(!i&&!n&&!g)return Promise.resolve(e);const o=[],s=[],a=[];for(let r=0,I=A.length;r<I;r++){const c=A[r];if(i){const l=c.POSITION!==void 0?t.getDependency("accessor",c.POSITION):e.attributes.position;o.push(l)}if(n){const l=c.NORMAL!==void 0?t.getDependency("accessor",c.NORMAL):e.attributes.normal;s.push(l)}if(g){const l=c.COLOR_0!==void 0?t.getDependency("accessor",c.COLOR_0):e.attributes.color;a.push(l)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(a)]).then(function(r){const I=r[0],c=r[1],l=r[2];return i&&(e.morphAttributes.position=I),n&&(e.morphAttributes.normal=c),g&&(e.morphAttributes.color=l),e.morphTargetsRelative=!0,e})}function que(e,A){if(e.updateMorphTargets(),A.weights!==void 0)for(let t=0,i=A.weights.length;t<i;t++)e.morphTargetInfluences[t]=A.weights[t];if(A.extras&&Array.isArray(A.extras.targetNames)){const t=A.extras.targetNames;if(e.morphTargetInfluences.length===t.length){e.morphTargetDictionary={};for(let i=0,n=t.length;i<n;i++)e.morphTargetDictionary[t[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Yue(e){let A;const t=e.extensions&&e.extensions[Kn.KHR_DRACO_MESH_COMPRESSION];if(t?A="draco:"+t.bufferView+":"+t.indices+":"+tO(t.attributes):A=e.indices+":"+tO(e.attributes)+":"+e.mode,e.targets!==void 0)for(let i=0,n=e.targets.length;i<n;i++)A+=":"+tO(e.targets[i]);return A}function tO(e){let A="";const t=Object.keys(e).sort();for(let i=0,n=t.length;i<n;i++)A+=t[i]+":"+e[t[i]]+";";return A}function f4(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function Hue(e){return e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0?"image/jpeg":e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?"image/webp":"image/png"}const Oue=new ni;let Pue=class{constructor(A={},t={}){this.json=A,this.extensions={},this.plugins={},this.options=t,this.cache=new Bue,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,n=!1,g=-1;typeof navigator<"u"&&typeof navigator.userAgent<"u"&&(i=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)===!0,n=navigator.userAgent.indexOf("Firefox")>-1,g=n?navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]:-1),typeof createImageBitmap>"u"||i||n&&g<98?this.textureLoader=new qd(this.options.manager):this.textureLoader=new aV(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new or(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(A){this.extensions=A}setPlugins(A){this.plugins=A}parse(A,t){const i=this,n=this.json,g=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(o){const s={scene:o[0][n.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:n.asset,parser:i,userData:{}};return Uh(g,s,n),IE(s,n),Promise.all(i._invokeAll(function(a){return a.afterRoot&&a.afterRoot(s)})).then(function(){for(const a of s.scenes)a.updateMatrixWorld();A(s)})}).catch(t)}_markDefs(){const A=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let n=0,g=t.length;n<g;n++){const o=t[n].joints;for(let s=0,a=o.length;s<a;s++)A[o[s]].isBone=!0}for(let n=0,g=A.length;n<g;n++){const o=A[n];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(i[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(A,t){t!==void 0&&(A.refs[t]===void 0&&(A.refs[t]=A.uses[t]=0),A.refs[t]++)}_getNodeRef(A,t,i){if(A.refs[t]<=1)return i;const n=i.clone(),g=(o,s)=>{const a=this.associations.get(o);a!=null&&this.associations.set(s,a);for(const[r,I]of o.children.entries())g(I,s.children[r])};return g(i,n),n.name+="_instance_"+A.uses[t]++,n}_invokeOne(A){const t=Object.values(this.plugins);t.push(this);for(let i=0;i<t.length;i++){const n=A(t[i]);if(n)return n}return null}_invokeAll(A){const t=Object.values(this.plugins);t.unshift(this);const i=[];for(let n=0;n<t.length;n++){const g=A(t[n]);g&&i.push(g)}return i}getDependency(A,t){const i=A+":"+t;let n=this.cache.get(i);if(!n){switch(A){case"scene":n=this.loadScene(t);break;case"node":n=this._invokeOne(function(g){return g.loadNode&&g.loadNode(t)});break;case"mesh":n=this._invokeOne(function(g){return g.loadMesh&&g.loadMesh(t)});break;case"accessor":n=this.loadAccessor(t);break;case"bufferView":n=this._invokeOne(function(g){return g.loadBufferView&&g.loadBufferView(t)});break;case"buffer":n=this.loadBuffer(t);break;case"material":n=this._invokeOne(function(g){return g.loadMaterial&&g.loadMaterial(t)});break;case"texture":n=this._invokeOne(function(g){return g.loadTexture&&g.loadTexture(t)});break;case"skin":n=this.loadSkin(t);break;case"animation":n=this._invokeOne(function(g){return g.loadAnimation&&g.loadAnimation(t)});break;case"camera":n=this.loadCamera(t);break;default:if(n=this._invokeOne(function(g){return g!=this&&g.getDependency&&g.getDependency(A,t)}),!n)throw new Error("Unknown type: "+A);break}this.cache.add(i,n)}return n}getDependencies(A){let t=this.cache.get(A);if(!t){const i=this,n=this.json[A+(A==="mesh"?"es":"s")]||[];t=Promise.all(n.map(function(g,o){return i.getDependency(A,o)})),this.cache.add(A,t)}return t}loadBuffer(A){const t=this.json.buffers[A],i=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&A===0)return Promise.resolve(this.extensions[Kn.KHR_BINARY_GLTF].body);const n=this.options;return new Promise(function(g,o){i.load(AC.resolveURL(t.uri,n.path),g,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(A){const t=this.json.bufferViews[A];return this.getDependency("buffer",t.buffer).then(function(i){const n=t.byteLength||0,g=t.byteOffset||0;return i.slice(g,g+n)})}loadAccessor(A){const t=this,i=this.json,n=this.json.accessors[A];if(n.bufferView===void 0&&n.sparse===void 0){const o=AO[n.type],s=zm[n.componentType],a=n.normalized===!0,r=new s(n.count*o);return Promise.resolve(new ji(r,o,a))}const g=[];return n.bufferView!==void 0?g.push(this.getDependency("bufferView",n.bufferView)):g.push(null),n.sparse!==void 0&&(g.push(this.getDependency("bufferView",n.sparse.indices.bufferView)),g.push(this.getDependency("bufferView",n.sparse.values.bufferView))),Promise.all(g).then(function(o){const s=o[0],a=AO[n.type],r=zm[n.componentType],I=r.BYTES_PER_ELEMENT,c=I*a,l=n.byteOffset||0,B=n.bufferView!==void 0?i.bufferViews[n.bufferView].byteStride:void 0,Q=n.normalized===!0;let h,d;if(B&&B!==c){const p=Math.floor(l/B),y="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+p+":"+n.count;let m=t.cache.get(y);m||(h=new r(s,p*B,n.count*B/I),m=new _w(h,B/I),t.cache.add(y,m)),d=new CQ(m,a,l%B/I,Q)}else s===null?h=new r(n.count*a):h=new r(s,l,n.count*a),d=new ji(h,a,Q);if(n.sparse!==void 0){const p=AO.SCALAR,y=zm[n.sparse.indices.componentType],m=n.sparse.indices.byteOffset||0,D=n.sparse.values.byteOffset||0,S=new y(o[1],m,n.sparse.count*p),k=new r(o[2],D,n.sparse.count*a);s!==null&&(d=new ji(d.array.slice(),d.itemSize,d.normalized));for(let N=0,G=S.length;N<G;N++){const M=S[N];if(d.setX(M,k[N*a]),a>=2&&d.setY(M,k[N*a+1]),a>=3&&d.setZ(M,k[N*a+2]),a>=4&&d.setW(M,k[N*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return d})}loadTexture(A){const t=this.json,i=this.options,g=t.textures[A].source,o=t.images[g];let s=this.textureLoader;if(o.uri){const a=i.manager.getHandler(o.uri);a!==null&&(s=a)}return this.loadTextureImage(A,g,s)}loadTextureImage(A,t,i){const n=this,g=this.json,o=g.textures[A],s=g.images[t],a=(s.uri||s.bufferView)+":"+o.sampler;if(this.textureCache[a])return this.textureCache[a];const r=this.loadImageSource(t,i).then(function(I){I.flipY=!1,I.name=o.name||s.name||"",I.name===""&&typeof s.uri=="string"&&s.uri.startsWith("data:image/")===!1&&(I.name=s.uri);const l=(g.samplers||{})[o.sampler]||{};return I.magFilter=mgA[l.magFilter]||qg,I.minFilter=mgA[l.minFilter]||Gr,I.wrapS=SgA[l.wrapS]||Fr,I.wrapT=SgA[l.wrapT]||Fr,n.associations.set(I,{textures:A}),I}).catch(function(){return null});return this.textureCache[a]=r,r}loadImageSource(A,t){const i=this,n=this.json,g=this.options;if(this.sourceCache[A]!==void 0)return this.sourceCache[A].then(c=>c.clone());const o=n.images[A],s=self.URL||self.webkitURL;let a=o.uri||"",r=!1;if(o.bufferView!==void 0)a=i.getDependency("bufferView",o.bufferView).then(function(c){r=!0;const l=new Blob([c],{type:o.mimeType});return a=s.createObjectURL(l),a});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+A+" is missing URI and bufferView");const I=Promise.resolve(a).then(function(c){return new Promise(function(l,B){let Q=l;t.isImageBitmapLoader===!0&&(Q=function(h){const d=new Kg(h);d.needsUpdate=!0,l(d)}),t.load(AC.resolveURL(c,g.path),Q,void 0,B)})}).then(function(c){return r===!0&&s.revokeObjectURL(a),IE(c,o),c.userData.mimeType=o.mimeType||Hue(o.uri),c}).catch(function(c){throw console.error("THREE.GLTFLoader: Couldn't load texture",a),c});return this.sourceCache[A]=I,I}assignTexture(A,t,i,n){const g=this;return this.getDependency("texture",i.index).then(function(o){if(!o)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(o=o.clone(),o.channel=i.texCoord),g.extensions[Kn.KHR_TEXTURE_TRANSFORM]){const s=i.extensions!==void 0?i.extensions[Kn.KHR_TEXTURE_TRANSFORM]:void 0;if(s){const a=g.associations.get(o);o=g.extensions[Kn.KHR_TEXTURE_TRANSFORM].extendTexture(o,s),g.associations.set(o,a)}}return n!==void 0&&(typeof n=="number"&&(n=n===ygA?up:YE),"colorSpace"in o?o.colorSpace=n:o.encoding=n===up?ygA:lue),A[t]=o,o})}assignFinalMaterial(A){const t=A.geometry;let i=A.material;const n=t.attributes.tangent===void 0,g=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(A.isPoints){const s="PointsMaterial:"+i.uuid;let a=this.cache.get(s);a||(a=new NE,ho.prototype.copy.call(a,i),a.color.copy(i.color),a.map=i.map,a.sizeAttenuation=!1,this.cache.add(s,a)),i=a}else if(A.isLine){const s="LineBasicMaterial:"+i.uuid;let a=this.cache.get(s);a||(a=new es,ho.prototype.copy.call(a,i),a.color.copy(i.color),a.map=i.map,this.cache.add(s,a)),i=a}if(n||g||o){let s="ClonedMaterial:"+i.uuid+":";n&&(s+="derivative-tangents:"),g&&(s+="vertex-colors:"),o&&(s+="flat-shading:");let a=this.cache.get(s);a||(a=i.clone(),g&&(a.vertexColors=!0),o&&(a.flatShading=!0),n&&(a.normalScale&&(a.normalScale.y*=-1),a.clearcoatNormalScale&&(a.clearcoatNormalScale.y*=-1)),this.cache.add(s,a),this.associations.set(a,this.associations.get(i))),i=a}A.material=i}getMaterialType(){return xg}loadMaterial(A){const t=this,i=this.json,n=this.extensions,g=i.materials[A];let o;const s={},a=g.extensions||{},r=[];if(a[Kn.KHR_MATERIALS_UNLIT]){const c=n[Kn.KHR_MATERIALS_UNLIT];o=c.getMaterialType(),r.push(c.extendParams(s,g,t))}else{const c=g.pbrMetallicRoughness||{};if(s.color=new Et(1,1,1),s.opacity=1,Array.isArray(c.baseColorFactor)){const l=c.baseColorFactor;s.color.setRGB(l[0],l[1],l[2],YE),s.opacity=l[3]}c.baseColorTexture!==void 0&&r.push(t.assignTexture(s,"map",c.baseColorTexture,up)),s.metalness=c.metallicFactor!==void 0?c.metallicFactor:1,s.roughness=c.roughnessFactor!==void 0?c.roughnessFactor:1,c.metallicRoughnessTexture!==void 0&&(r.push(t.assignTexture(s,"metalnessMap",c.metallicRoughnessTexture)),r.push(t.assignTexture(s,"roughnessMap",c.metallicRoughnessTexture))),o=this._invokeOne(function(l){return l.getMaterialType&&l.getMaterialType(A)}),r.push(Promise.all(this._invokeAll(function(l){return l.extendMaterialParams&&l.extendMaterialParams(A,s)})))}g.doubleSided===!0&&(s.side=AI);const I=g.alphaMode||eO.OPAQUE;if(I===eO.BLEND?(s.transparent=!0,s.depthWrite=!1):(s.transparent=!1,I===eO.MASK&&(s.alphaTest=g.alphaCutoff!==void 0?g.alphaCutoff:.5)),g.normalTexture!==void 0&&o!==kg&&(r.push(t.assignTexture(s,"normalMap",g.normalTexture)),s.normalScale=new lt(1,1),g.normalTexture.scale!==void 0)){const c=g.normalTexture.scale;s.normalScale.set(c,c)}if(g.occlusionTexture!==void 0&&o!==kg&&(r.push(t.assignTexture(s,"aoMap",g.occlusionTexture)),g.occlusionTexture.strength!==void 0&&(s.aoMapIntensity=g.occlusionTexture.strength)),g.emissiveFactor!==void 0&&o!==kg){const c=g.emissiveFactor;s.emissive=new Et().setRGB(c[0],c[1],c[2],YE)}return g.emissiveTexture!==void 0&&o!==kg&&r.push(t.assignTexture(s,"emissiveMap",g.emissiveTexture,up)),Promise.all(r).then(function(){const c=new o(s);return g.name&&(c.name=g.name),IE(c,g),t.associations.set(c,{materials:A}),g.extensions&&Uh(n,c,g),c})}createUniqueName(A){const t=zn.sanitizeNodeName(A||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(A){const t=this,i=this.extensions,n=this.primitiveCache;function g(s){return i[Kn.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(s,t).then(function(a){return wgA(a,s,t)})}const o=[];for(let s=0,a=A.length;s<a;s++){const r=A[s],I=Yue(r),c=n[I];if(c)o.push(c.promise);else{let l;r.extensions&&r.extensions[Kn.KHR_DRACO_MESH_COMPRESSION]?l=g(r):l=wgA(new Ni,r,t),n[I]={primitive:r,promise:l},o.push(l)}}return Promise.all(o)}loadMesh(A){const t=this,i=this.json,n=this.extensions,g=i.meshes[A],o=g.primitives,s=[];for(let a=0,r=o.length;a<r;a++){const I=o[a].material===void 0?xue(this.cache):this.getDependency("material",o[a].material);s.push(I)}return s.push(t.loadGeometries(o)),Promise.all(s).then(function(a){const r=a.slice(0,a.length-1),I=a[a.length-1],c=[];for(let B=0,Q=I.length;B<Q;B++){const h=I[B],d=o[B];let p;const y=r[B];if(d.mode===bC.TRIANGLES||d.mode===bC.TRIANGLE_STRIP||d.mode===bC.TRIANGLE_FAN||d.mode===void 0)p=g.isSkinnedMesh===!0?new jx(h,y):new pn(h,y),p.isSkinnedMesh===!0&&p.normalizeSkinWeights(),d.mode===bC.TRIANGLE_STRIP?p.geometry=fgA(p.geometry,oG):d.mode===bC.TRIANGLE_FAN&&(p.geometry=fgA(p.geometry,Df));else if(d.mode===bC.LINES)p=new EI(h,y);else if(d.mode===bC.LINE_STRIP)p=new yB(h,y);else if(d.mode===bC.LINE_LOOP)p=new Zx(h,y);else if(d.mode===bC.POINTS)p=new Pp(h,y);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+d.mode);Object.keys(p.geometry.morphAttributes).length>0&&que(p,g),p.name=t.createUniqueName(g.name||"mesh_"+A),IE(p,g),d.extensions&&Uh(n,p,d),t.assignFinalMaterial(p),c.push(p)}for(let B=0,Q=c.length;B<Q;B++)t.associations.set(c[B],{meshes:A,primitives:B});if(c.length===1)return g.extensions&&Uh(n,c[0],g),c[0];const l=new sa;g.extensions&&Uh(n,l,g),t.associations.set(l,{meshes:A});for(let B=0,Q=c.length;B<Q;B++)l.add(c[B]);return l})}loadCamera(A){let t;const i=this.json.cameras[A],n=i[i.type];if(!n){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return i.type==="perspective"?t=new Wo(VC.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):i.type==="orthographic"&&(t=new Hd(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),IE(t,i),Promise.resolve(t)}loadSkin(A){const t=this.json.skins[A],i=[];for(let n=0,g=t.joints.length;n<g;n++)i.push(this._loadNodeShallow(t.joints[n]));return t.inverseBindMatrices!==void 0?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(n){const g=n.pop(),o=n,s=[],a=[];for(let r=0,I=o.length;r<I;r++){const c=o[r];if(c){s.push(c);const l=new ni;g!==null&&l.fromArray(g.array,r*16),a.push(l)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[r])}return new Jw(s,a)})}loadAnimation(A){const t=this.json,i=this,n=t.animations[A],g=n.name?n.name:"animation_"+A,o=[],s=[],a=[],r=[],I=[];for(let c=0,l=n.channels.length;c<l;c++){const B=n.channels[c],Q=n.samplers[B.sampler],h=B.target,d=h.node,p=n.parameters!==void 0?n.parameters[Q.input]:Q.input,y=n.parameters!==void 0?n.parameters[Q.output]:Q.output;h.node!==void 0&&(o.push(this.getDependency("node",d)),s.push(this.getDependency("accessor",p)),a.push(this.getDependency("accessor",y)),r.push(Q),I.push(h))}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(a),Promise.all(r),Promise.all(I)]).then(function(c){const l=c[0],B=c[1],Q=c[2],h=c[3],d=c[4],p=[];for(let y=0,m=l.length;y<m;y++){const D=l[y],S=B[y],k=Q[y],N=h[y],G=d[y];if(D===void 0)continue;D.updateMatrix&&D.updateMatrix();const M=i._createAnimationTracks(D,S,k,N,G);if(M)for(let w=0;w<M.length;w++)p.push(M[w])}return new fd(g,void 0,p)})}createNodeMesh(A){const t=this.json,i=this,n=t.nodes[A];return n.mesh===void 0?null:i.getDependency("mesh",n.mesh).then(function(g){const o=i._getNodeRef(i.meshCache,n.mesh,g);return n.weights!==void 0&&o.traverse(function(s){if(s.isMesh)for(let a=0,r=n.weights.length;a<r;a++)s.morphTargetInfluences[a]=n.weights[a]}),o})}loadNode(A){const t=this.json,i=this,n=t.nodes[A],g=i._loadNodeShallow(A),o=[],s=n.children||[];for(let r=0,I=s.length;r<I;r++)o.push(i.getDependency("node",s[r]));const a=n.skin===void 0?Promise.resolve(null):i.getDependency("skin",n.skin);return Promise.all([g,Promise.all(o),a]).then(function(r){const I=r[0],c=r[1],l=r[2];l!==null&&I.traverse(function(B){B.isSkinnedMesh&&B.bind(l,Oue)});for(let B=0,Q=c.length;B<Q;B++)I.add(c[B]);return I})}_loadNodeShallow(A){const t=this.json,i=this.extensions,n=this;if(this.nodeCache[A]!==void 0)return this.nodeCache[A];const g=t.nodes[A],o=g.name?n.createUniqueName(g.name):"",s=[],a=n._invokeOne(function(r){return r.createNodeMesh&&r.createNodeMesh(A)});return a&&s.push(a),g.camera!==void 0&&s.push(n.getDependency("camera",g.camera).then(function(r){return n._getNodeRef(n.cameraCache,g.camera,r)})),n._invokeAll(function(r){return r.createNodeAttachment&&r.createNodeAttachment(A)}).forEach(function(r){s.push(r)}),this.nodeCache[A]=Promise.all(s).then(function(r){let I;if(g.isBone===!0?I=new IG:r.length>1?I=new sa:r.length===1?I=r[0]:I=new Bn,I!==r[0])for(let c=0,l=r.length;c<l;c++)I.add(r[c]);if(g.name&&(I.userData.name=g.name,I.name=o),IE(I,g),g.extensions&&Uh(i,I,g),g.matrix!==void 0){const c=new ni;c.fromArray(g.matrix),I.applyMatrix4(c)}else g.translation!==void 0&&I.position.fromArray(g.translation),g.rotation!==void 0&&I.quaternion.fromArray(g.rotation),g.scale!==void 0&&I.scale.fromArray(g.scale);return n.associations.has(I)||n.associations.set(I,{}),n.associations.get(I).nodes=A,I}),this.nodeCache[A]}loadScene(A){const t=this.extensions,i=this.json.scenes[A],n=this,g=new sa;i.name&&(g.name=n.createUniqueName(i.name)),IE(g,i),i.extensions&&Uh(t,g,i);const o=i.nodes||[],s=[];for(let a=0,r=o.length;a<r;a++)s.push(n.getDependency("node",o[a]));return Promise.all(s).then(function(a){for(let I=0,c=a.length;I<c;I++)g.add(a[I]);const r=I=>{const c=new Map;for(const[l,B]of n.associations)(l instanceof ho||l instanceof Kg)&&c.set(l,B);return I.traverse(l=>{const B=n.associations.get(l);B!=null&&c.set(l,B)}),c};return n.associations=r(g),g})}_createAnimationTracks(A,t,i,n,g){const o=[],s=A.name?A.name:A.uuid,a=[];qQ[g.path]===qQ.weights?A.traverse(function(l){l.morphTargetInfluences&&a.push(l.name?l.name:l.uuid)}):a.push(s);let r;switch(qQ[g.path]){case qQ.weights:r=cQ;break;case qQ.rotation:r=DB;break;case qQ.position:case qQ.scale:r=mB;break;default:switch(i.itemSize){case 1:r=cQ;break;case 2:case 3:default:r=mB;break}break}const I=n.interpolation!==void 0?Lue[n.interpolation]:dd,c=this._getArrayFromAccessor(i);for(let l=0,B=a.length;l<B;l++){const Q=new r(a[l]+"."+qQ[g.path],t.array,c,I);n.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(Q),o.push(Q)}return o}_getArrayFromAccessor(A){let t=A.array;if(A.normalized){const i=f4(t.constructor),n=new Float32Array(t.length);for(let g=0,o=t.length;g<o;g++)n[g]=t[g]*i;t=n}return t}_createCubicSplineTrackInterpolant(A){A.createInterpolant=function(i){const n=this instanceof DB?Jue:bDA;return new n(this.times,this.values,this.getValueSize()/3,i)},A.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function jue(e,A,t){const i=A.attributes,n=new Ag;if(i.POSITION!==void 0){const s=t.json.accessors[i.POSITION],a=s.min,r=s.max;if(a!==void 0&&r!==void 0){if(n.set(new SA(a[0],a[1],a[2]),new SA(r[0],r[1],r[2])),s.normalized){const I=f4(zm[s.componentType]);n.min.multiplyScalar(I),n.max.multiplyScalar(I)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const g=A.targets;if(g!==void 0){const s=new SA,a=new SA;for(let r=0,I=g.length;r<I;r++){const c=g[r];if(c.POSITION!==void 0){const l=t.json.accessors[c.POSITION],B=l.min,Q=l.max;if(B!==void 0&&Q!==void 0){if(a.setX(Math.max(Math.abs(B[0]),Math.abs(Q[0]))),a.setY(Math.max(Math.abs(B[1]),Math.abs(Q[1]))),a.setZ(Math.max(Math.abs(B[2]),Math.abs(Q[2]))),l.normalized){const h=f4(zm[l.componentType]);a.multiplyScalar(h)}s.max(a)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(s)}e.boundingBox=n;const o=new xs;n.getCenter(o.center),o.radius=n.min.distanceTo(n.max)/2,e.boundingSphere=o}function wgA(e,A,t){const i=A.attributes,n=[];function g(o,s){return t.getDependency("accessor",o).then(function(a){e.setAttribute(s,a)})}for(const o in i){const s=p4[o]||o.toLowerCase();s in e.attributes||n.push(g(i[o],s))}if(A.indices!==void 0&&!e.index){const o=t.getDependency("accessor",A.indices).then(function(s){e.setIndex(s)});n.push(o)}return IE(e,A),jue(e,A,t),Promise.all(n).then(function(){return A.targets!==void 0?Tue(e,A.targets,t):e})}const iO=new WeakMap;class zue extends la{constructor(A){super(A),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(A){return this.decoderPath=A,this}setDecoderConfig(A){return this.decoderConfig=A,this}setWorkerLimit(A){return this.workerLimit=A,this}load(A,t,i,n){const g=new or(this.manager);g.setPath(this.path),g.setResponseType("arraybuffer"),g.setRequestHeader(this.requestHeader),g.setWithCredentials(this.withCredentials),g.load(A,o=>{const s={attributeIDs:this.defaultAttributeIDs,attributeTypes:this.defaultAttributeTypes,useUniqueIDs:!1};this.decodeGeometry(o,s).then(t).catch(n)},i,n)}decodeDracoFile(A,t,i,n){const g={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:n||this.defaultAttributeTypes,useUniqueIDs:!!i};this.decodeGeometry(A,g).then(t)}decodeGeometry(A,t){for(const a in t.attributeTypes){const r=t.attributeTypes[a];r.BYTES_PER_ELEMENT!==void 0&&(t.attributeTypes[a]=r.name)}const i=JSON.stringify(t);if(iO.has(A)){const a=iO.get(A);if(a.key===i)return a.promise;if(A.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let n;const g=this.workerNextTaskID++,o=A.byteLength,s=this._getWorker(g,o).then(a=>(n=a,new Promise((r,I)=>{n._callbacks[g]={resolve:r,reject:I},n.postMessage({type:"decode",id:g,taskConfig:t,buffer:A},[A])}))).then(a=>this._createGeometry(a.geometry));return s.catch(()=>!0).then(()=>{n&&g&&this._releaseTask(n,g)}),iO.set(A,{key:i,promise:s}),s}_createGeometry(A){const t=new Ni;A.index&&t.setIndex(new ji(A.index.array,1));for(let i=0;i<A.attributes.length;i++){const n=A.attributes[i],g=n.name,o=n.array,s=n.itemSize;t.setAttribute(g,new ji(o,s))}return t}_loadLibrary(A,t){const i=new or(this.manager);return i.setPath(this.decoderPath),i.setResponseType(t),i.setWithCredentials(this.withCredentials),new Promise((n,g)=>{i.load(A,n,void 0,g)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const A=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return A?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const n=i[0];A||(this.decoderConfig.wasmBinary=i[1]);const g=Zue.toString(),o=["/* draco decoder */",n,"","/* worker */",g.substring(g.indexOf("{")+1,g.lastIndexOf("}"))].join(`
`);this.workerSourceURL=URL.createObjectURL(new Blob([o]))}),this.decoderPending}_getWorker(A,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const n=new Worker(this.workerSourceURL);n._callbacks={},n._taskCosts={},n._taskLoad=0,n.postMessage({type:"init",decoderConfig:this.decoderConfig}),n.onmessage=function(g){const o=g.data;switch(o.type){case"decode":n._callbacks[o.id].resolve(o);break;case"error":n._callbacks[o.id].reject(o);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+o.type+'"')}},this.workerPool.push(n)}else this.workerPool.sort(function(n,g){return n._taskLoad>g._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[A]=t,i._taskLoad+=t,i})}_releaseTask(A,t){A._taskLoad-=A._taskCosts[t],delete A._callbacks[t],delete A._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(A=>A._taskLoad))}dispose(){for(let A=0;A<this.workerPool.length;++A)this.workerPool[A].terminate();return this.workerPool.length=0,this}}function Zue(){let e,A;onmessage=function(o){const s=o.data;switch(s.type){case"init":e=s.decoderConfig,A=new Promise(function(I){e.onModuleLoaded=function(c){I({draco:c})},DracoDecoderModule(e)});break;case"decode":const a=s.buffer,r=s.taskConfig;A.then(I=>{const c=I.draco,l=new c.Decoder,B=new c.DecoderBuffer;B.Init(new Int8Array(a),a.byteLength);try{const Q=t(c,l,B,r),h=Q.attributes.map(d=>d.array.buffer);Q.index&&h.push(Q.index.array.buffer),self.postMessage({type:"decode",id:s.id,geometry:Q},h)}catch(Q){console.error(Q),self.postMessage({type:"error",id:s.id,error:Q.message})}finally{c.destroy(B),c.destroy(l)}});break}};function t(o,s,a,r){const I=r.attributeIDs,c=r.attributeTypes;let l,B;const Q=s.GetEncodedGeometryType(a);if(Q===o.TRIANGULAR_MESH)l=new o.Mesh,B=s.DecodeBufferToMesh(a,l);else if(Q===o.POINT_CLOUD)l=new o.PointCloud,B=s.DecodeBufferToPointCloud(a,l);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!B.ok()||l.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+B.error_msg());const h={index:null,attributes:[]};for(const d in I){const p=self[c[d]];let y,m;if(r.useUniqueIDs)m=I[d],y=s.GetAttributeByUniqueId(l,m);else{if(m=s.GetAttributeId(l,o[I[d]]),m===-1)continue;y=s.GetAttribute(l,m)}h.attributes.push(n(o,s,l,d,p,y))}return Q===o.TRIANGULAR_MESH&&(h.index=i(o,s,l)),o.destroy(l),h}function i(o,s,a){const I=a.num_faces()*3,c=I*4,l=o._malloc(c);s.GetTrianglesUInt32Array(a,c,l);const B=new Uint32Array(o.HEAPF32.buffer,l,I).slice();return o._free(l),{array:B,itemSize:1}}function n(o,s,a,r,I,c){const l=c.num_components(),Q=a.num_points()*l,h=Q*I.BYTES_PER_ELEMENT,d=g(o,I),p=o._malloc(h);s.GetAttributeDataArrayForAllPoints(a,c,d,h,p);const y=new I(o.HEAPF32.buffer,p,Q).slice();return o._free(p),{name:r,array:y,itemSize:l}}function g(o,s){switch(s){case Float32Array:return o.DT_FLOAT32;case Int8Array:return o.DT_INT8;case Int16Array:return o.DT_INT16;case Int32Array:return o.DT_INT32;case Uint8Array:return o.DT_UINT8;case Uint16Array:return o.DT_UINT16;case Uint32Array:return o.DT_UINT32}}}let $U;const nO=()=>{if($U)return $U;const e=" ",A=" ",t=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),i=new Uint8Array([32,0,65,253,3,1,2,34,4,106,6,5,11,8,7,20,13,33,12,16,128,9,116,64,19,113,127,15,10,21,22,14,255,66,24,54,136,107,18,23,192,26,114,118,132,17,77,101,130,144,27,87,131,44,45,74,156,154,70,167]);if(typeof WebAssembly!="object")return{supported:!1};let n=e;WebAssembly.validate(t)&&(n=A);let g;const o=WebAssembly.instantiate(s(n),{}).then(c=>{g=c.instance,g.exports.__wasm_call_ctors()});function s(c){const l=new Uint8Array(c.length);for(let Q=0;Q<c.length;++Q){const h=c.charCodeAt(Q);l[Q]=h>96?h-71:h>64?h-65:h>47?h+4:h>46?63:62}let B=0;for(let Q=0;Q<c.length;++Q)l[B++]=l[Q]<60?i[l[Q]]:(l[Q]-60)*64+l[++Q];return l.buffer.slice(0,B)}function a(c,l,B,Q,h,d){const p=g.exports.sbrk,y=B+3&-4,m=p(y*Q),D=p(h.length),S=new Uint8Array(g.exports.memory.buffer);S.set(h,D);const k=c(m,B,Q,D,h.length);if(k===0&&d&&d(m,y,Q),l.set(S.subarray(m,m+B*Q)),p(m-p(0)),k!==0)throw new Error(`Malformed buffer data: ${k}`)}const r={0:"",1:"meshopt_decodeFilterOct",2:"meshopt_decodeFilterQuat",3:"meshopt_decodeFilterExp",NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},I={0:"meshopt_decodeVertexBuffer",1:"meshopt_decodeIndexBuffer",2:"meshopt_decodeIndexSequence",ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return $U={ready:o,supported:!0,decodeVertexBuffer(c,l,B,Q,h){a(g.exports.meshopt_decodeVertexBuffer,c,l,B,Q,g.exports[r[h]])},decodeIndexBuffer(c,l,B,Q){a(g.exports.meshopt_decodeIndexBuffer,c,l,B,Q)},decodeIndexSequence(c,l,B,Q){a(g.exports.meshopt_decodeIndexSequence,c,l,B,Q)},decodeGltfBuffer(c,l,B,Q,h,d){a(g.exports[I[h]],c,l,B,Q,g.exports[r[d]])}},$U};function Wue(e,A){if(typeof e!="object"||!e)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var i=t.call(e,A);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(A==="string"?String:Number)(e)}function Vue(e){var A=Wue(e,"string");return typeof A=="symbol"?A:A+""}function Xue(e,A,t){return(A=Vue(A))in e?Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[A]=t,e}function kgA(e,A){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);A&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),t.push.apply(t,i)}return t}function hg(e){for(var A=1;A<arguments.length;A++){var t=arguments[A]!=null?arguments[A]:{};A%2?kgA(Object(t),!0).forEach(function(i){Xue(e,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):kgA(Object(t)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(t,i))})}return e}const $ue=new oo;new ca;const Ade=new SA;new Bn;const Xu=new ni,ma=new SA,Zc=new oo,kf=new SA,ede=e=>{const[A,t,i]=e;return new SA(A,t,i)},MgA=({x:e,y:A,z:t,w:i})=>$ue.set(e,A,t,i),tde=e=>{if(Array.isArray(e))return new Pm(e[0],e[1],e[2]);if(typeof e=="number")return new Pm(e,e,e);{const A=e;return new Pm(A.x,A.y,A.z)}},ide={fixed:1,dynamic:0,kinematicPosition:2,kinematicVelocity:3},UDA=e=>ide[e],nde=(e,A)=>{const t=Array.from(e);for(let i=0;i<e.length/3;i++)t[i*3]*=A.x,t[i*3+1]*=A.y,t[i*3+2]*=A.z;return t},vDA=e=>e?e instanceof oo?[e.x,e.y,e.z,e.w]:e instanceof SA||e instanceof ca?[e.x,e.y,e.z]:Array.isArray(e)?e:[e]:[0];function YQ(e){const A=E.useRef(void 0);return A.current===void 0&&(A.current={value:typeof e=="function"?e():e}),A.current.value}const gde=e=>{const A=E.useRef(e),t=E.useRef(0),i=E.useRef(0);E.useEffect(()=>{A.current=e},[e]),E.useEffect(()=>{const n=()=>{const g=performance.now(),o=g-i.current;t.current=requestAnimationFrame(n),A.current(o/1e3),i.current=g};return t.current=requestAnimationFrame(n),()=>cancelAnimationFrame(t.current)},[])},ode=({onStep:e,updatePriority:A})=>(Ba((t,i)=>{e(i)},A),null),sde=({onStep:e})=>(gde(A=>{e(A)}),null),ade=({onStep:e,type:A,updatePriority:t})=>A==="independent"?ue.createElement(sde,{onStep:e}):ue.createElement(ode,{onStep:e,updatePriority:t});var rde=E.memo(ade);function Ide(e,A){if(e==null)return{};var t={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(A.indexOf(i)!==-1)continue;t[i]=e[i]}return t}function bJ(e,A){if(e==null)return{};var t,i,n=Ide(e,A);if(Object.getOwnPropertySymbols){var g=Object.getOwnPropertySymbols(e);for(i=0;i<g.length;i++)t=g[i],A.indexOf(t)===-1&&{}.propertyIsEnumerable.call(e,t)&&(n[t]=e[t])}return n}const Cde=["mass","linearDamping","angularDamping","type","onCollisionEnter","onCollisionExit","onIntersectionEnter","onIntersectionExit","onContactForce","children","canSleep","ccd","gravityScale","softCcdPrediction","ref"],cde=(e,A,t)=>{const i=A.slice();if(e==="heightfield"){const g=i[3];return g.x*=t.x,g.x*=t.y,g.x*=t.z,i}if(e==="trimesh"||e==="convexHull")return i[0]=nde(i[0],t),i;const n=[t.x,t.y,t.z,t.x,t.x];return i.map((g,o)=>n[o]*g)},lde=(e,A,t,i)=>{const n=cde(e.shape,e.args,t),g=Ko[e.shape](...n);return A.createCollider(g,i==null?void 0:i())},Bde=["shape","args"],NgA="Please pick ONLY ONE of the `density`, `mass` and `massProperties` options.",Ede=(e,A)=>{if(A.density!==void 0){if(A.mass!==void 0||A.massProperties!==void 0)throw new Error(NgA);e.setDensity(A.density);return}if(A.mass!==void 0){if(A.massProperties!==void 0)throw new Error(NgA);e.setMass(A.mass);return}A.massProperties!==void 0&&e.setMassProperties(A.massProperties.mass,A.massProperties.centerOfMass,A.massProperties.principalAngularInertia,A.massProperties.angularInertiaLocalFrame)},KDA={sensor:(e,A)=>{e.setSensor(A)},collisionGroups:(e,A)=>{e.setCollisionGroups(A)},solverGroups:(e,A)=>{e.setSolverGroups(A)},friction:(e,A)=>{e.setFriction(A)},frictionCombineRule:(e,A)=>{e.setFrictionCombineRule(A)},restitution:(e,A)=>{e.setRestitution(A)},restitutionCombineRule:(e,A)=>{e.setRestitutionCombineRule(A)},activeCollisionTypes:(e,A)=>{e.setActiveCollisionTypes(A)},contactSkin:(e,A)=>{e.setContactSkin(A)},quaternion:()=>{},position:()=>{},rotation:()=>{},scale:()=>{}},FDA=Object.keys(KDA),Qde=(e,A,t)=>{const i=t.get(e.handle);if(i){var n;const g=i.object.parent.getWorldScale(Ade),o=(n=i.worldParent)===null||n===void 0?void 0:n.matrixWorld.clone().invert();i.object.updateWorldMatrix(!0,!1),Xu.copy(i.object.matrixWorld),o&&Xu.premultiply(o),Xu.decompose(ma,Zc,kf),e.parent()?(e.setTranslationWrtParent({x:ma.x*g.x,y:ma.y*g.y,z:ma.z*g.z}),e.setRotationWrtParent(Zc)):(e.setTranslation({x:ma.x*g.x,y:ma.y*g.y,z:ma.z*g.z}),e.setRotation(Zc)),FDA.forEach(s=>{if(s in A){const a=A[s];KDA[s](e,a,A)}}),Ede(e,A)}},ude=(e,A,t)=>{const i=E.useMemo(()=>FDA.flatMap(n=>vDA(A[n])),[A]);E.useEffect(()=>{const n=e();Qde(n,A,t)},[...i,e])},dde=e=>{let A=!1;return e.traverseAncestors(t=>{t.userData.r3RapierType==="MeshCollider"&&(A=!0)}),A},hde=(e,A,t)=>({collider:e,worldParent:t||void 0,object:A}),pde={cuboid:"cuboid",ball:"ball",hull:"convexHull",trimesh:"trimesh"},fde=({object:e,ignoreMeshColliders:A=!0,options:t})=>{const i=[];e.updateWorldMatrix(!0,!1);const n=e.matrixWorld.clone().invert(),g=o=>{if("isMesh"in o){if(A&&dde(o))return;const s=o.getWorldScale(kf),a=pde[t.colliders||"cuboid"];o.updateWorldMatrix(!0,!1),Xu.copy(o.matrixWorld).premultiply(n).decompose(ma,Zc,kf);const r=new ca().setFromQuaternion(Zc,"XYZ"),{geometry:I}=o,{args:c,offset:l}=yde(I,t.colliders||"cuboid"),B=hg(hg({},JDA(t)),{},{args:c,shape:a,rotation:[r.x,r.y,r.z],position:[ma.x+l.x*s.x,ma.y+l.y*s.y,ma.z+l.z*s.z],scale:[s.x,s.y,s.z]});i.push(B)}};return t.includeInvisible?e.traverse(g):e.traverseVisible(g),i},yde=(e,A)=>{switch(A){case"cuboid":{e.computeBoundingBox();const{boundingBox:i}=e,n=i.getSize(new SA);return{args:[n.x/2,n.y/2,n.z/2],offset:i.getCenter(new SA)}}case"ball":{e.computeBoundingSphere();const{boundingSphere:i}=e;return{args:[i.radius],offset:i.center}}case"trimesh":{var t;const i=e.index?e.clone():aue(e);return{args:[i.attributes.position.array,(t=i.index)===null||t===void 0?void 0:t.array],offset:new SA}}case"hull":return{args:[e.clone().attributes.position.array],offset:new SA}}return{args:[],offset:new SA}},_DA=e=>({collision:!!(e!=null&&e.onCollisionEnter||e!=null&&e.onCollisionExit||e!=null&&e.onIntersectionEnter||e!=null&&e.onIntersectionExit),contactForce:!!(e!=null&&e.onContactForce)}),Dde=(e,A,t,i={})=>{const{onCollisionEnter:n,onCollisionExit:g,onIntersectionEnter:o,onIntersectionExit:s,onContactForce:a}=A;E.useEffect(()=>{const r=e();if(r){const{collision:I,contactForce:c}=_DA(A),l=I||i.collision,B=c||i.contactForce;l&&B?r.setActiveEvents(ME.COLLISION_EVENTS|ME.CONTACT_FORCE_EVENTS):l?r.setActiveEvents(ME.COLLISION_EVENTS):B&&r.setActiveEvents(ME.CONTACT_FORCE_EVENTS),t.set(r.handle,{onCollisionEnter:n,onCollisionExit:g,onIntersectionEnter:o,onIntersectionExit:s,onContactForce:a})}return()=>{r&&t.delete(r.handle)}},[n,g,o,s,a,i])},JDA=(e={})=>bJ(e,Cde),QT=()=>{const e=E.useContext(LDA);if(!e)throw new Error("react-three-rapier: useRapier must be used within <Physics />!");return e},wV=(e,A,t=!0)=>{const[i,n]=E.useState([]);return E.useEffect(()=>{e.current&&A.colliders!==!1&&n(fde({object:e.current,options:A,ignoreMeshColliders:t}))},[A.colliders]),i},mde=E.memo(()=>{const{world:e}=QT(),A=E.useRef(null);return Ba(()=>{const t=A.current;if(!t)return;const i=e.debugRender(),n=new Ni;n.setAttribute("position",new ji(i.vertices,3)),n.setAttribute("color",new ji(i.colors,4)),t.geometry.dispose(),t.geometry=n}),ue.createElement("group",null,ue.createElement("lineSegments",{ref:A,frustumCulled:!1},ue.createElement("lineBasicMaterial",{color:16777215,vertexColors:!0}),ue.createElement("bufferGeometry",null)))}),Sde=e=>{let A;const t={get(o,s){return A||(A=e()),Reflect.get(A,s)},set(o,s,a){return A||(A=e()),Reflect.set(A,s,a)}};return{proxy:new Proxy({},t),reset:()=>{A=void 0},set:o=>{A=o}}},LDA=E.createContext(void 0),Av=(e,A)=>{var t,i,n,g,o,s;return{target:{rigidBody:e.rigidBody.object,collider:e.collider.object,colliderObject:(t=e.collider.state)===null||t===void 0?void 0:t.object,rigidBodyObject:(i=e.rigidBody.state)===null||i===void 0?void 0:i.object},other:{rigidBody:A.rigidBody.object,collider:A.collider.object,colliderObject:(n=A.collider.state)===null||n===void 0?void 0:n.object,rigidBodyObject:(g=A.rigidBody.state)===null||g===void 0?void 0:g.object},rigidBody:A.rigidBody.object,collider:A.collider.object,colliderObject:(o=A.collider.state)===null||o===void 0?void 0:o.object,rigidBodyObject:(s=A.rigidBody.state)===null||s===void 0?void 0:s.object}},RgA=async()=>{let e=await Qi(()=>Promise.resolve().then(()=>kse),void 0);return await e.init(),e},wde=e=>{const{colliders:A="cuboid",children:t,timeStep:i=1/60,paused:n=!1,interpolate:g=!0,updatePriority:o,updateLoop:s="follow",debug:a=!1,gravity:r=[0,-9.81,0],allowedLinearError:I=.001,predictionDistance:c=.002,numSolverIterations:l=4,numAdditionalFrictionIterations:B=4,numInternalPgsIterations:Q=1,minIslandSize:h=128,maxCcdSubsteps:d=1,contactNaturalFrequency:p=30,lengthUnit:y=1}=e,m=oDA(RgA,["@react-thee/rapier",RgA]),{invalidate:D}=ic(),S=YQ(()=>new Map),k=YQ(()=>new Map),N=YQ(()=>new Map),G=YQ(()=>new Map),M=YQ(()=>new SW(!1)),w=YQ(()=>new Set),b=YQ(()=>new Set),{proxy:_,reset:K,set:J}=YQ(()=>Sde(()=>new m.World(ede(r))));E.useEffect(()=>()=>{_.free(),K()},[]),E.useEffect(()=>{_.gravity=tde(r),_.integrationParameters.numSolverIterations=l,_.integrationParameters.numAdditionalFrictionIterations=B,_.integrationParameters.numInternalPgsIterations=Q,_.integrationParameters.normalizedAllowedLinearError=I,_.integrationParameters.minIslandSize=h,_.integrationParameters.maxCcdSubsteps=d,_.integrationParameters.normalizedPredictionDistance=c,_.lengthUnit=y,_.integrationParameters.contact_natural_frequency=p},[_,...r,l,B,Q,I,h,d,c,y,p]);const q=E.useCallback(z=>{var Z;const eA=_.getCollider(z),aA=G.get(z),sA=k.get(z),pA=eA==null||(Z=eA.parent())===null||Z===void 0?void 0:Z.handle,gA=pA!==void 0?_.getRigidBody(pA):void 0,yA=gA&&pA!==void 0?N.get(pA):void 0,fA=pA!==void 0?S.get(pA):void 0;return{collider:{object:eA,events:aA,state:sA},rigidBody:{object:gA,events:yA,state:fA}}},[]),[v]=E.useState({previousState:{},accumulator:0}),U=E.useCallback(z=>{const Z=_,eA=i==="vary",aA=VC.clamp(z,0,.5),sA=gA=>{w.forEach(yA=>{yA.current(Z)}),Z.timestep=gA,Z.step(M),b.forEach(yA=>{yA.current(Z)})};if(eA)sA(aA);else for(v.accumulator+=aA;v.accumulator>=i;)g&&(v.previousState={},Z.forEachRigidBody(gA=>{v.previousState[gA.handle]={position:gA.translation(),rotation:gA.rotation()}})),sA(i),v.accumulator-=i;const pA=eA||!g||n?1:v.accumulator/i;S.forEach((gA,yA)=>{const fA=Z.getRigidBody(yA),RA=N.get(yA);if(RA!=null&&RA.onSleep||RA!=null&&RA.onWake){if(fA.isSleeping()&&!gA.isSleeping){var qA;RA==null||(qA=RA.onSleep)===null||qA===void 0||qA.call(RA)}if(!fA.isSleeping()&&gA.isSleeping){var W;RA==null||(W=RA.onWake)===null||W===void 0||W.call(RA)}gA.isSleeping=fA.isSleeping()}if(!fA||fA.isSleeping()&&!("isInstancedMesh"in gA.object)||!gA.setMatrix)return;let $=fA.translation(),L=fA.rotation(),H=v.previousState[yA];H&&(Xu.compose(H.position,MgA(H.rotation),gA.scale).premultiply(gA.invertedWorldMatrix).decompose(ma,Zc,kf),gA.meshType=="mesh"&&(gA.object.position.copy(ma),gA.object.quaternion.copy(Zc))),Xu.compose($,MgA(L),gA.scale).premultiply(gA.invertedWorldMatrix).decompose(ma,Zc,kf),gA.meshType=="instancedMesh"?gA.setMatrix(Xu):(gA.object.position.lerp(ma,pA),gA.object.quaternion.slerp(Zc,pA))}),M.drainCollisionEvents((gA,yA,fA)=>{const RA=q(gA),qA=q(yA);if(!(RA!=null&&RA.collider.object)||!(qA!=null&&qA.collider.object))return;const W=Av(RA,qA),$=Av(qA,RA);if(fA)Z.contactPair(RA.collider.object,qA.collider.object,(FA,Ie)=>{var DA,rA,BA,j,QA,dA,UA,TA;(DA=RA.rigidBody.events)===null||DA===void 0||(rA=DA.onCollisionEnter)===null||rA===void 0||rA.call(DA,hg(hg({},W),{},{manifold:FA,flipped:Ie})),(BA=qA.rigidBody.events)===null||BA===void 0||(j=BA.onCollisionEnter)===null||j===void 0||j.call(BA,hg(hg({},$),{},{manifold:FA,flipped:Ie})),(QA=RA.collider.events)===null||QA===void 0||(dA=QA.onCollisionEnter)===null||dA===void 0||dA.call(QA,hg(hg({},W),{},{manifold:FA,flipped:Ie})),(UA=qA.collider.events)===null||UA===void 0||(TA=UA.onCollisionEnter)===null||TA===void 0||TA.call(UA,hg(hg({},$),{},{manifold:FA,flipped:Ie}))});else{var L,H,P,tA,iA,oA,IA,CA;(L=RA.rigidBody.events)===null||L===void 0||(H=L.onCollisionExit)===null||H===void 0||H.call(L,W),(P=qA.rigidBody.events)===null||P===void 0||(tA=P.onCollisionExit)===null||tA===void 0||tA.call(P,$),(iA=RA.collider.events)===null||iA===void 0||(oA=iA.onCollisionExit)===null||oA===void 0||oA.call(iA,W),(IA=qA.collider.events)===null||IA===void 0||(CA=IA.onCollisionExit)===null||CA===void 0||CA.call(IA,$)}if(fA){if(Z.intersectionPair(RA.collider.object,qA.collider.object)){var _A,uA,X,O,cA,wA,xA,YA;(_A=RA.rigidBody.events)===null||_A===void 0||(uA=_A.onIntersectionEnter)===null||uA===void 0||uA.call(_A,W),(X=qA.rigidBody.events)===null||X===void 0||(O=X.onIntersectionEnter)===null||O===void 0||O.call(X,$),(cA=RA.collider.events)===null||cA===void 0||(wA=cA.onIntersectionEnter)===null||wA===void 0||wA.call(cA,W),(xA=qA.collider.events)===null||xA===void 0||(YA=xA.onIntersectionEnter)===null||YA===void 0||YA.call(xA,$)}}else{var jA,ie,he,le,NA,EA,PA,ZA;(jA=RA.rigidBody.events)===null||jA===void 0||(ie=jA.onIntersectionExit)===null||ie===void 0||ie.call(jA,W),(he=qA.rigidBody.events)===null||he===void 0||(le=he.onIntersectionExit)===null||le===void 0||le.call(he,$),(NA=RA.collider.events)===null||NA===void 0||(EA=NA.onIntersectionExit)===null||EA===void 0||EA.call(NA,W),(PA=qA.collider.events)===null||PA===void 0||(ZA=PA.onIntersectionExit)===null||ZA===void 0||ZA.call(PA,$)}}),M.drainContactForceEvents(gA=>{var yA,fA,RA,qA,W,$,L,H;const P=q(gA.collider1()),tA=q(gA.collider2());if(!(P!=null&&P.collider.object)||!(tA!=null&&tA.collider.object))return;const iA=Av(P,tA),oA=Av(tA,P);(yA=P.rigidBody.events)===null||yA===void 0||(fA=yA.onContactForce)===null||fA===void 0||fA.call(yA,hg(hg({},iA),{},{totalForce:gA.totalForce(),totalForceMagnitude:gA.totalForceMagnitude(),maxForceDirection:gA.maxForceDirection(),maxForceMagnitude:gA.maxForceMagnitude()})),(RA=tA.rigidBody.events)===null||RA===void 0||(qA=RA.onContactForce)===null||qA===void 0||qA.call(RA,hg(hg({},oA),{},{totalForce:gA.totalForce(),totalForceMagnitude:gA.totalForceMagnitude(),maxForceDirection:gA.maxForceDirection(),maxForceMagnitude:gA.maxForceMagnitude()})),(W=P.collider.events)===null||W===void 0||($=W.onContactForce)===null||$===void 0||$.call(W,hg(hg({},iA),{},{totalForce:gA.totalForce(),totalForceMagnitude:gA.totalForceMagnitude(),maxForceDirection:gA.maxForceDirection(),maxForceMagnitude:gA.maxForceMagnitude()})),(L=tA.collider.events)===null||L===void 0||(H=L.onContactForce)===null||H===void 0||H.call(L,hg(hg({},oA),{},{totalForce:gA.totalForce(),totalForceMagnitude:gA.totalForceMagnitude(),maxForceDirection:gA.maxForceDirection(),maxForceMagnitude:gA.maxForceMagnitude()}))}),Z.forEachActiveRigidBody(()=>{D()})},[n,i,g,_]),x=E.useMemo(()=>({rapier:m,world:_,setWorld:z=>{J(z)},physicsOptions:{colliders:A,gravity:r},rigidBodyStates:S,colliderStates:k,rigidBodyEvents:N,colliderEvents:G,beforeStepCallbacks:w,afterStepCallbacks:b,isPaused:n,isDebug:a,step:U}),[n,U,a,A,r]),T=E.useCallback(z=>{n||U(z)},[n,U]);return ue.createElement(LDA.Provider,{value:x},ue.createElement(rde,{onStep:T,type:s,updatePriority:o}),a&&ue.createElement(mde,null),t)};function ra(){return ra=Object.assign?Object.assign.bind():function(e){for(var A=1;A<arguments.length;A++){var t=arguments[A];for(var i in t)({}).hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},ra.apply(null,arguments)}const kV=(e,A=null)=>{const t=E.useRef(A);return e&&typeof e!="function"?(e.current||(e.current=t.current),e):t},xDA=(e,A,t)=>{const i=E.useRef(void 0),n=E.useCallback(()=>(i.current||(i.current=e()),i.current),t);return E.useEffect(()=>{const g=n(),o=()=>A(g);return()=>{o(),i.current=void 0}},[n]),n},kde=e=>{var A;const t=UDA((e==null?void 0:e.type)||"dynamic"),i=new TC(t);return i.canSleep=(A=e==null?void 0:e.canSleep)!==null&&A!==void 0?A:!0,i},Mde=({rigidBody:e,object:A,setMatrix:t,getMatrix:i,worldScale:n,meshType:g="mesh"})=>{A.updateWorldMatrix(!0,!1);const o=A.parent.matrixWorld.clone().invert();return{object:A,rigidBody:e,invertedWorldMatrix:o,setMatrix:t||(s=>{A.matrix.copy(s)}),getMatrix:i||(s=>s.copy(A.matrix)),scale:n||A.getWorldScale(kf).clone(),isSleeping:!1,meshType:g}},Nde=["args","colliders","canSleep"],TDA={gravityScale:(e,A)=>{e.setGravityScale(A,!0)},additionalSolverIterations(e,A){e.setAdditionalSolverIterations(A)},linearDamping:(e,A)=>{e.setLinearDamping(A)},angularDamping:(e,A)=>{e.setAngularDamping(A)},dominanceGroup:(e,A)=>{e.setDominanceGroup(A)},enabledRotations:(e,[A,t,i])=>{e.setEnabledRotations(A,t,i,!0)},enabledTranslations:(e,[A,t,i])=>{e.setEnabledTranslations(A,t,i,!0)},lockRotations:(e,A)=>{e.lockRotations(A,!0)},lockTranslations:(e,A)=>{e.lockTranslations(A,!0)},angularVelocity:(e,[A,t,i])=>{e.setAngvel({x:A,y:t,z:i},!0)},linearVelocity:(e,[A,t,i])=>{e.setLinvel({x:A,y:t,z:i},!0)},ccd:(e,A)=>{e.enableCcd(A)},softCcdPrediction:(e,A)=>{e.setSoftCcdPrediction(A)},userData:(e,A)=>{e.userData=A},type(e,A){e.setBodyType(UDA(A),!0)},position:()=>{},rotation:()=>{},quaternion:()=>{},scale:()=>{}},qDA=Object.keys(TDA),Rde=(e,A,t,i=!0)=>{if(!e)return;const n=t.get(e.handle);n&&(i&&(n.object.updateWorldMatrix(!0,!1),Xu.copy(n.object.matrixWorld).decompose(ma,Zc,kf),e.setTranslation(ma,!1),e.setRotation(Zc,!1)),qDA.forEach(g=>{g in A&&TDA[g](e,A[g])}))},Gde=(e,A,t,i=!0)=>{const n=E.useMemo(()=>qDA.flatMap(g=>vDA(A[g])),[A]);E.useEffect(()=>{const g=e();Rde(g,A,t,i)},n)},bde=(e,A,t)=>{const{onWake:i,onSleep:n,onCollisionEnter:g,onCollisionExit:o,onIntersectionEnter:s,onIntersectionExit:a,onContactForce:r}=A,I={onWake:i,onSleep:n,onCollisionEnter:g,onCollisionExit:o,onIntersectionEnter:s,onIntersectionExit:a,onContactForce:r};E.useEffect(()=>{const c=e();return t.set(c.handle,I),()=>{t.delete(c.handle)}},[i,n,g,o,s,a,r])},Ude=({x:e,y:A,z:t}={x:0,y:0,z:0})=>new SA(e,A,t),oC=E.memo(e=>{const{children:A,position:t,rotation:i,quaternion:n,scale:g,name:o}=e,{world:s,colliderEvents:a,colliderStates:r}=QT(),I=ODA(),c=kV(e.ref),l=E.useRef(null),B=Bde.flatMap(d=>Array.isArray(e[d])?e[d]:[e[d]]),Q=xDA(()=>{const d=l.current.getWorldScale(Ude()),p=lde(e,s,d,I==null?void 0:I.getRigidBody);return typeof e.ref=="function"&&e.ref(p),c.current=p,p},d=>{s.getCollider(d.handle)&&s.removeCollider(d,!0)},[...B,I]);E.useEffect(()=>{const d=Q();return r.set(d.handle,hde(d,l.current,I==null?void 0:I.ref.current)),()=>{r.delete(d.handle)}},[Q]);const h=E.useMemo(()=>hg(hg({},JDA(I==null?void 0:I.options)),e),[e,I==null?void 0:I.options]);return ude(Q,h,r),Dde(Q,h,a,_DA(I==null?void 0:I.options)),ue.createElement("object3D",{position:t,rotation:i,quaternion:n,scale:g,ref:l,name:o},A)}),vde=ue.forwardRef((e,A)=>ue.createElement(oC,ra({},e,{shape:"cuboid",ref:A})));vde.displayName="CuboidCollider";const Kde=ue.forwardRef((e,A)=>ue.createElement(oC,ra({},e,{shape:"roundCuboid",ref:A})));Kde.displayName="RoundCuboidCollider";const Fde=ue.forwardRef((e,A)=>ue.createElement(oC,ra({},e,{shape:"ball",ref:A})));Fde.displayName="BallCollider";const _de=ue.forwardRef((e,A)=>ue.createElement(oC,ra({},e,{shape:"capsule",ref:A})));_de.displayName="CapsuleCollider";const Jde=ue.forwardRef((e,A)=>ue.createElement(oC,ra({},e,{shape:"heightfield",ref:A})));Jde.displayName="HeightfieldCollider";const Lde=ue.forwardRef((e,A)=>ue.createElement(oC,ra({},e,{shape:"trimesh",ref:A})));Lde.displayName="TrimeshCollider";const xde=ue.forwardRef((e,A)=>ue.createElement(oC,ra({},e,{shape:"cone",ref:A})));xde.displayName="ConeCollider";const Tde=ue.forwardRef((e,A)=>ue.createElement(oC,ra({},e,{shape:"roundCone",ref:A})));Tde.displayName="RoundConeCollider";const YDA=ue.forwardRef((e,A)=>ue.createElement(oC,ra({},e,{shape:"cylinder",ref:A})));YDA.displayName="CylinderCollider";YDA.displayName="RoundCylinderCollider";const qde=ue.forwardRef((e,A)=>ue.createElement(oC,ra({},e,{shape:"convexHull",ref:A})));qde.displayName="ConvexHullCollider";const Yde=["ref","children","type","position","rotation","scale","quaternion","transformState"],HDA=E.createContext(void 0),ODA=()=>E.useContext(HDA),RE=E.memo(e=>{const{ref:A,children:t,type:i,position:n,rotation:g,scale:o,quaternion:s,transformState:a}=e,r=bJ(e,Yde),I=E.useRef(null),c=kV(A),{world:l,rigidBodyStates:B,physicsOptions:Q,rigidBodyEvents:h}=QT(),d=E.useMemo(()=>hg(hg(hg({},Q),e),{},{children:void 0}),[Q,e]),p=Nde.flatMap(S=>Array.isArray(d[S])?[...d[S]]:d[S]),y=wV(I,d),m=xDA(()=>{const S=kde(d),k=l.createRigidBody(S);return typeof A=="function"&&A(k),c.current=k,k},S=>{l.getRigidBody(S.handle)&&l.removeRigidBody(S)},p);E.useEffect(()=>{const S=m(),k=Mde({rigidBody:S,object:I.current});return B.set(S.handle,e.transformState?e.transformState(k):k),()=>{B.delete(S.handle)}},[m]),Gde(m,d,B),bde(m,d,h);const D=E.useMemo(()=>({ref:I,getRigidBody:m,options:d}),[m]);return ue.createElement(HDA.Provider,{value:D},ue.createElement("object3D",ra({ref:I},r,{position:n,rotation:g,quaternion:s,scale:o}),t,y.map((S,k)=>ue.createElement(oC,ra({key:k},S)))))});RE.displayName="RigidBody";const Hde=E.memo(e=>{const{children:A,type:t}=e,{physicsOptions:i}=QT(),n=E.useRef(null),{options:g}=ODA(),o=E.useMemo(()=>hg(hg(hg({},i),g),{},{children:void 0,colliders:t}),[i,g]),s=wV(n,o,!1);return ue.createElement("object3D",{ref:n,userData:{r3RapierType:"MeshCollider"}},A,s.map((a,r)=>ue.createElement(oC,ra({key:r},a))))});Hde.displayName="MeshCollider";const Ode=["ref"],Pde=["children","instances","colliderNodes","position","rotation","quaternion","scale"],jde=E.memo(e=>{let{ref:A}=e,t=bJ(e,Ode);const i=kV(A,[]),n=E.useRef(null),g=E.useRef(null),{children:o,instances:s,colliderNodes:a=[],position:r,rotation:I,quaternion:c,scale:l}=t,B=bJ(t,Pde),Q=wV(n,hg(hg({},t),{},{children:void 0})),h=()=>{const p=g.current.children[0];if(p&&"isInstancedMesh"in p)return p};E.useEffect(()=>{const p=h();p?p.instanceMatrix.setUsage(eyA):console.warn("InstancedRigidBodies expects exactly one child, which must be an InstancedMesh")},[]);const d=(p,y)=>{const m=h();return m?hg(hg({},p),{},{getMatrix:D=>(m.getMatrixAt(y,D),D),setMatrix:D=>{m.setMatrixAt(y,D),m.instanceMatrix.needsUpdate=!0},meshType:"instancedMesh"}):p};return ue.createElement("object3D",ra({ref:n},B,{position:r,rotation:I,quaternion:c,scale:l}),ue.createElement("object3D",{ref:g},o),s==null?void 0:s.map((p,y)=>ue.createElement(RE,ra({},B,p,{ref:m=>{i.current[y]=m},transformState:m=>d(m,y)}),ue.createElement(ue.Fragment,null,a.map((m,D)=>ue.createElement(E.Fragment,{key:D},m)),Q.map((m,D)=>ue.createElement(oC,ra({key:D},m)))))))});jde.displayName="InstancedRigidBodies";function y4(){return y4=Object.assign?Object.assign.bind():function(e){for(var A=1;A<arguments.length;A++){var t=arguments[A];for(var i in t)({}).hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},y4.apply(null,arguments)}const zde=e=>e;function Zde(e,A=zde){const t=ue.useSyncExternalStore(e.subscribe,ue.useCallback(()=>A(e.getState()),[e,A]),ue.useCallback(()=>A(e.getInitialState()),[e,A]));return ue.useDebugValue(t),t}const GgA=e=>{const A=tDA(e),t=i=>Zde(A,i);return Object.assign(t,A),t},Wde=e=>e?GgA(e):GgA,gO=e=>e===Object(e)&&!Array.isArray(e)&&typeof e!="function";function qw(e,A){const t=ic(g=>g.gl),i=Od(qd,gO(e)?Object.values(e):e);return E.useLayoutEffect(()=>{A==null||A(i)},[A]),E.useEffect(()=>{if("initTexture"in t){let g=[];Array.isArray(i)?g=i:i instanceof Kg?g=[i]:gO(i)&&(g=Object.values(i)),g.forEach(o=>{o instanceof Kg&&t.initTexture(o)})}},[t,i]),E.useMemo(()=>{if(gO(e)){const g={};let o=0;for(const s in e)g[s]=i[o++];return g}else return i},[e,i])}qw.preload=e=>Od.preload(qd,e);qw.clear=e=>Od.clear(qd,e);let ev=null,PDA="https://www.gstatic.com/draco/versioned/decoders/1.5.5/";function jDA(e=!0,A=!0,t){return i=>{t&&t(i),e&&(ev||(ev=new zue),ev.setDecoderPath(typeof e=="string"?e:PDA),i.setDRACOLoader(ev)),A&&i.setMeshoptDecoder(typeof nO=="function"?nO():nO)}}const Ur=(e,A,t,i)=>Od(SV,e,jDA(A,t,i));Ur.preload=(e,A,t,i)=>Od.preload(SV,e,jDA(A,t,i));Ur.clear=e=>Od.clear(SV,e);Ur.setDecoderPath=e=>{PDA=e};function Vde(e,A,t){const i=ic(B=>B.size),n=ic(B=>B.viewport),g=typeof e=="number"?e:i.width*n.dpr,o=i.height*n.dpr,s=(typeof e=="number"?t:e)||{},{samples:a=0,depth:r,...I}=s,c=r??s.depthBuffer,l=E.useMemo(()=>{const B=new il(g,o,{minFilter:qg,magFilter:qg,type:ny,...I});return c&&(B.depthTexture=new Vx(g,o,br)),B.samples=a,B},[]);return E.useLayoutEffect(()=>{l.setSize(g,o),a&&(l.samples=a)},[a,l,g,o]),E.useEffect(()=>()=>l.dispose(),[]),l}const Xde=e=>typeof e=="function",$de=E.forwardRef(({envMap:e,resolution:A=256,frames:t=1/0,children:i,makeDefault:n,...g},o)=>{const s=ic(({set:d})=>d),a=ic(({camera:d})=>d),r=ic(({size:d})=>d),I=E.useRef(null);E.useImperativeHandle(o,()=>I.current,[]);const c=E.useRef(null),l=Vde(A);E.useLayoutEffect(()=>{g.manual||I.current.updateProjectionMatrix()},[r,g]),E.useLayoutEffect(()=>{I.current.updateProjectionMatrix()}),E.useLayoutEffect(()=>{if(n){const d=a;return s(()=>({camera:I.current})),()=>s(()=>({camera:d}))}},[I,n,s]);let B=0,Q=null;const h=Xde(i);return Ba(d=>{h&&(t===1/0||B<t)&&(c.current.visible=!1,d.gl.setRenderTarget(l),Q=d.scene.background,e&&(d.scene.background=e),d.gl.render(d.scene,I.current),d.scene.background=Q,d.gl.setRenderTarget(null),c.current.visible=!0,B++)}),E.createElement(E.Fragment,null,E.createElement("orthographicCamera",y4({left:r.width/-2,right:r.width/2,top:r.height/2,bottom:r.height/-2,ref:I},g),!h&&i),E.createElement("group",{ref:c},h&&i(l.texture)))});function Ahe(e,A){const t=E.useRef(null),[i]=E.useState(()=>A?A instanceof Bn?{current:A}:A:t),[n]=E.useState(()=>new lV(void 0));E.useLayoutEffect(()=>{A&&(i.current=A instanceof Bn?A:A.current),n._root=i.current});const g=E.useRef({}),o=E.useMemo(()=>{const s={};return e.forEach(a=>Object.defineProperty(s,a.name,{enumerable:!0,get(){if(i.current)return g.current[a.name]||(g.current[a.name]=n.clipAction(a,i.current))},configurable:!0})),{ref:i,clips:e,actions:s,names:e.map(a=>a.name),mixer:n}},[e]);return Ba((s,a)=>n.update(a)),E.useEffect(()=>{const s=i.current;return()=>{g.current={},n.stopAllAction(),Object.values(o.actions).forEach(a=>{s&&n.uncacheAction(a,s)})}},[e]),o}const ehe=2e3,the=5e3,bgA=.08,Ap="/models/dice.glb",UgA=new URL("/assets/dice-GytAQsgt.glb",import.meta.url).href;function tv(e){if(/^(?:[a-z]+:)?\/\//i.test(e)||e.startsWith("data:")||e.startsWith("blob:"))return e;const[A,t=""]=e.split("?");if(A.replace(/^\.?\//,"/")===Ap)return t?`${UgA}?${t}`:UgA;const n="/";return`${n.endsWith("/")?n:`${n}/`}${e.replace(/^\.?\//,"")}`}function vgA({result:e,position:A,rollTrigger:t,noAnimation:i=!1,active:n=!0,chargeLevel:g=0,modelOverride:o}){const[s,a]=E.useState(tv(o||Ap)),r=E.useMemo(()=>{try{const z=(o||s).split("?")[1];if(!z)return null;const eA=new URLSearchParams(z).get("tint");return eA&&/^#[0-9a-f]{3,8}$/i.test(eA)?eA:null}catch{return null}},[o,s]);E.useEffect(()=>{var T;try{(T=Ur.preload)==null||T.call(Ur,tv(Ap))}catch{}},[]),E.useEffect(()=>{if(o){a(tv(o));return}let T=!1;return(async()=>{try{const z=await Xo();let Z=Ap;(z==null?void 0:z.diceColorTheme)==="dice_red_white"?Z=`${Ap}?tint=%23c81e1e`:(z==null?void 0:z.diceColorTheme)==="dice_green_gold"?Z=`${Ap}?tint=%2316a34a`:(z==null?void 0:z.diceColorTheme)==="dice_blue_silver"&&(Z=`${Ap}?tint=%232563eb`),T||a(tv(Z))}catch{}})(),()=>{T=!0}},[o]);const I=E.useMemo(()=>s.split("?")[0],[s]),c=Ur(I),l=E.useMemo(()=>{const T=c.scene.clone(!0),z=r?new Et(r):null;return T.traverse(Z=>{var eA;if(Z!=null&&Z.isMesh&&Z.material){const aA=Array.isArray(Z.material)?Z.material:[Z.material];for(const sA of aA){for(const pA of["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap","bumpMap","displacementMap","alphaMap","envMap"]){const gA=sA==null?void 0:sA[pA];if(gA&&typeof gA=="object"&&"needsUpdate"in gA)try{gA.needsUpdate=!0}catch{}}if(sA&&typeof sA.name=="string"&&sA.name.startsWith("pips_")){try{(eA=sA.color)==null||eA.set("#0a0a0a")}catch{}try{sA.metalness=.15}catch{}try{sA.roughness=.7}catch{}if("envMapIntensity"in sA)try{sA.envMapIntensity=.6}catch{}continue}if(z&&sA&&sA.color)try{sA.color.copy(z)}catch{}if(sA&&"envMapIntensity"in sA)try{sA.envMapIntensity=Math.max(1,Number(sA.envMapIntensity||.9))}catch{}if(sA&&"metalness"in sA)try{sA.metalness=Math.min(.9,Math.max(.2,Number(sA.metalness||.5)))}catch{}if(sA&&"roughness"in sA)try{sA.roughness=Math.min(.9,Math.max(.2,Number(sA.roughness||.55)))}catch{}}}}),T},[c.scene,r]),B=E.useRef(null),Q=E.useRef(null),h=E.useRef(null),d=E.useRef(!1),p=E.useRef(!1),y=E.useRef(null),m=E.useRef(!1),D=E.useRef(0),S=E.useRef({x:0,y:0,z:0}),k=E.useRef({x:0,y:0,z:0}),N=E.useRef(new ca),G=E.useRef(new oo),M=E.useRef(null),w=E.useRef(0);w.current=g;const b=E.useCallback(T=>{var fA,RA;if(!A)return;const z=B.current;if(!z)return;(fA=z.wakeUp)==null||fA.call(z),z.setLinvel({x:0,y:0,z:0},!0),z.setAngvel({x:0,y:0,z:0},!0),z.setRotation({x:0,y:0,z:0,w:1},!0);const Z=.3+T*.7,eA=S.current,aA=k.current,sA=-A[0],pA=-A[2],gA=Math.sqrt(sA*sA+pA*pA)||1,yA=25*Z;eA.x=sA/gA*yA+(Math.random()-.5)*8*Z,eA.y=8+10*Z,eA.z=pA/gA*yA+(Math.random()-.5)*8*Z,aA.x=(Math.random()-.5)*120*Z,aA.y=(Math.random()-.5)*120*Z,aA.z=(Math.random()-.5)*120*Z,z.setTranslation({x:A[0],y:2.6,z:A[2]},!0),z.setLinvel(eA,!0),z.setAngvel(aA,!0),(RA=z.wakeUp)==null||RA.call(z)},[A]);E.useCallback(()=>{b(.6)},[b]),E.useEffect(()=>{var z,Z;const T=B.current;if(T)if(n)(Z=T.wakeUp)==null||Z.call(T);else{d.current=!1;try{T.setLinvel({x:0,y:0,z:0},!0),T.setAngvel({x:0,y:0,z:0},!0),(z=T.sleep)==null||z.call(T)}catch{}if(p.current){p.current=!1,y.current&&(window.clearTimeout(y.current),y.current=null);try{RC()}catch{}}}},[n]),E.useEffect(()=>()=>{try{y.current&&(window.clearTimeout(y.current),y.current=null),RC()}catch{}},[]);const _=E.useRef(b);_.current=b,E.useEffect(()=>{var z;if(i||!A||!n||typeof t!="number"||t<=0)return;h.current&&(window.clearTimeout(h.current),h.current=null),Q.current=Date.now(),d.current=!0,D.current=0,M.current=null;const T=B.current;if(T)try{(z=T.wakeUp)==null||z.call(T),T.setLinvel({x:0,y:0,z:0},!0),T.setAngvel({x:0,y:0,z:0},!0)}catch{}if(m.current=!0,!p.current){p.current=!0;try{pvA({volume:.075,playbackRate:1})}catch{}y.current&&window.clearTimeout(y.current),y.current=window.setTimeout(()=>{if(p.current){p.current=!1;try{RC()}catch{}}y.current&&(window.clearTimeout(y.current),y.current=null)},5e3)}},[t,n,i,A]),E.useEffect(()=>{if(!(t>0)&&(d.current&&(d.current=!1),p.current)){p.current=!1,y.current&&(window.clearTimeout(y.current),y.current=null);try{RC()}catch{}}},[t]),E.useEffect(()=>{var Z;if(i||!A||!n)return;if(!Q.current||!d.current){const eA=B.current;if(!eA)return;try{eA.setLinvel({x:0,y:0,z:0},!0),eA.setAngvel({x:0,y:0,z:0},!0)}catch{}if(e){const aA=Wb[e];if(aA){const sA=N.current,pA=G.current;sA.set(aA[0],aA[1],aA[2]),pA.setFromEuler(sA);try{eA.setRotation(pA,!0)}catch{}try{eA.setTranslation({x:A[0],y:2,z:A[2]},!0)}catch{}}}try{(Z=eA.sleep)==null||Z.call(eA)}catch{}return}if(!e)return;const T=Date.now()-(Q.current??Date.now()),z=Math.max(0,ehe-T);return h.current&&(window.clearTimeout(h.current),h.current=null),h.current=window.setTimeout(()=>{var pA;if(d.current=!1,p.current){p.current=!1,y.current&&(window.clearTimeout(y.current),y.current=null);try{RC()}catch{}}const eA=B.current;if(!eA)return;try{const gA=eA.translation(),yA=4.2,fA=gA.x,RA=gA.z,qA=Math.sqrt(fA*fA+RA*RA);if(qA>yA){const W=yA/qA;M.current={x:fA*W,z:RA*W}}else M.current={x:fA,z:RA}}catch{M.current={x:A[0],z:A[2]}}const aA=M.current.x,sA=M.current.z;try{eA.setLinvel({x:0,y:0,z:0},!0),eA.setAngvel({x:0,y:0,z:0},!0),eA.setTranslation({x:aA,y:2,z:sA},!0)}catch{}if(e){const gA=Wb[e];if(gA){const yA=N.current,fA=G.current;yA.set(gA[0],gA[1],gA[2]),fA.setFromEuler(yA);try{eA.setRotation(fA,!0)}catch{}}}if(Q.current=null,p.current){p.current=!1,y.current&&(window.clearTimeout(y.current),y.current=null);try{RC()}catch{}}try{(pA=eA.sleep)==null||pA.call(eA)}catch{}},z),()=>{h.current&&(window.clearTimeout(h.current),h.current=null)}},[t,e,A,i,n]);const K=E.useRef(0),J=E.useRef(!1),q=E.useRef(!1),v=E.useRef(0),U=10,x=E.useRef(0);return Ba((T,z)=>{var gA,yA,fA,RA,qA,W;const Z=B.current;if(!Z)return;const eA=5,aA=1,sA=4;try{const $=Z.translation(),L=$.x,H=$.z,P=Math.sqrt(L*L+H*H);let tA=!1,iA=$.x,oA=$.y,IA=$.z;if(P>eA){const CA=(eA-.3)/P;iA=L*CA,IA=H*CA,tA=!0;const _A=Z.linvel(),uA=(_A.x*L+_A.z*H)/(P*P);uA>0&&Z.setLinvel({x:_A.x-2*uA*L,y:_A.y,z:_A.z-2*uA*H},!0)}if(oA<aA){oA=.5,tA=!0;const CA=Z.linvel();Z.setLinvel({x:CA.x,y:Math.abs(CA.y)+2,z:CA.z},!0)}if(oA>sA){oA=sA-.5,tA=!0;const CA=Z.linvel();Z.setLinvel({x:CA.x,y:-Math.abs(CA.y)*.5,z:CA.z},!0)}tA&&Z.setTranslation({x:iA,y:oA,z:IA},!0)}catch{}const pA=w.current;if(pA>0&&!d.current&&n){(gA=Z.wakeUp)==null||gA.call(Z),x.current+=z;const $=x.current,L=.15+pA*.6,H=18+pA*30,P=Math.sin($*H)*L,tA=Math.cos($*H*1.3)*L,iA=(A==null?void 0:A[0])??0,oA=(A==null?void 0:A[2])??0;Z.setTranslation({x:iA+P,y:2,z:oA+tA},!0);const IA=.3+pA*1.2;Z.setAngvel({x:Math.sin($*H*.7)*IA,y:0,z:Math.cos($*H*.9)*IA},!0);return}if(pA===0&&x.current>0&&!d.current&&(x.current=0),d.current&&n){if(Q.current&&Date.now()-Q.current>the){if(d.current=!1,p.current){p.current=!1,y.current&&(window.clearTimeout(y.current),y.current=null);try{RC()}catch{}}try{Z.setLinvel({x:0,y:0,z:0},!0),Z.setAngvel({x:0,y:0,z:0},!0),Z.setTranslation({x:(A==null?void 0:A[0])??0,y:2,z:(A==null?void 0:A[2])??0},!0)}catch{}if(e){const IA=Wb[e];if(IA){const CA=N.current,_A=G.current;CA.set(IA[0],IA[1],IA[2]),_A.setFromEuler(CA);try{Z.setRotation(_A,!0)}catch{}}}Q.current=null;try{(yA=Z.sleep)==null||yA.call(Z)}catch{}return}K.current+=z,D.current++,J.current=!1,q.current=!1,v.current=0;try{(fA=Z.wakeUp)==null||fA.call(Z)}catch{}if(m.current){m.current=!1;try{_.current(w.current)}catch{}}const $=D.current<=15,L=Z.angvel(),H=Math.sqrt(L.x*L.x+L.y*L.y+L.z*L.z),P=$?40:25;if(H<P){const IA=P-H+15;Z.setAngvel({x:L.x+(Math.random()-.5)*IA,y:L.y+(Math.random()-.5)*IA,z:L.z+(Math.random()-.5)*IA},!0)}const tA=Z.linvel();if(Math.sqrt(tA.x*tA.x+tA.y*tA.y+tA.z*tA.z)<($?8:4)&&Z.setLinvel({x:(Math.random()-.5)*12,y:Math.max(tA.y,6),z:(Math.random()-.5)*12},!0),K.current>=.15){const IA={x:(Math.random()-.5)*10,y:4,z:(Math.random()-.5)*10};Z.applyImpulse(IA,!0),Z.applyTorqueImpulse({x:(Math.random()-.5)*15,y:(Math.random()-.5)*15,z:(Math.random()-.5)*15},!0),K.current=0}return}if(n&&!d.current&&e)try{const $=Z.linvel(),L=Z.angvel(),H=Math.abs($.x)+Math.abs($.y)+Math.abs($.z),P=Math.abs(L.x)+Math.abs(L.y)+Math.abs(L.z);Z.setLinvel({x:0,y:0,z:0},!0),Z.setAngvel({x:0,y:0,z:0},!0);const tA=Wb[e];if(tA){const IA=N.current,CA=G.current;IA.set(tA[0],tA[1],tA[2]),CA.setFromEuler(IA),Z.setRotation(CA,!0)}const iA=((RA=M.current)==null?void 0:RA.x)??(A==null?void 0:A[0])??0,oA=((qA=M.current)==null?void 0:qA.z)??(A==null?void 0:A[2])??0;Z.setTranslation({x:iA,y:2,z:oA},!0),J.current=!0,H<bgA&&P<bgA?(v.current++,v.current>=U&&(q.current=!0)):v.current=0,(W=Z.sleep)==null||W.call(Z)}catch{}}),E.useEffect(()=>()=>{if(d.current=!1,h.current&&window.clearTimeout(h.current),Q.current=null,p.current){p.current=!1,y.current&&(window.clearTimeout(y.current),y.current=null);try{RC()}catch{}}},[]),E.useEffect(()=>{const T=()=>{try{p.current&&(p.current=!1,y.current&&(window.clearTimeout(y.current),y.current=null),RC())}catch{}},z=()=>{document.visibilityState==="hidden"&&T()},Z=()=>T(),eA=()=>T();return document.addEventListener("visibilitychange",z),window.addEventListener("pagehide",Z),window.addEventListener("beforeunload",eA),()=>{document.removeEventListener("visibilitychange",z),window.removeEventListener("pagehide",Z),window.removeEventListener("beforeunload",eA)}},[]),C.jsx(RE,{ref:B,position:A,colliders:"cuboid",mass:1,linearDamping:.3,angularDamping:.3,restitution:.8,friction:.5,ccd:!0,children:C.jsx("primitive",{object:l,scale:31.25,visible:n})})}const Wr=6.5,ihe=Wr+.65,KgA=[[3,1,0],[-1.5,1,2.6],[-1.5,1,-2.6]],FgA=[[-3,1,0],[3,1,0]],Zm=24,UJ=3,nhe=1.2,ghe=1,vJ=Wr-ghe,ohe=2*vJ*Math.sin(Math.PI/Zm),she=Array.from({length:Zm},(e,A)=>{const t=A*2*Math.PI/Zm;return{position:[Math.cos(t)*vJ,UJ/2,Math.sin(t)*vJ],rotation:[0,-t+Math.PI/2,0],width:ohe,height:UJ,thickness:nhe}}),oO=5,ahe=Wr,rhe=1,Ihe=1.4,zDA=[];for(let e=0;e<oO;e++){const A=e/oO,t=(e+1)/oO,i=(A+t)/2,n=UJ+i*(ahe-UJ),g=Math.max(.5,vJ*Math.cos(i*(Math.PI/2))),o=2*g*Math.sin(Math.PI/Zm),s=i*(Math.PI/2);for(let a=0;a<Zm;a++){const r=a*2*Math.PI/Zm;zDA.push({position:[Math.cos(r)*g,n,Math.sin(r)*g],rotation:[s,-r+Math.PI/2,0],width:o,height:Ihe,thickness:rhe})}}function _gA(){return C.jsxs(C.Fragment,{children:[she.map((e,A)=>C.jsx(RE,{type:"fixed",colliders:"cuboid",position:e.position,rotation:e.rotation,restitution:.85,friction:.3,children:C.jsxs("mesh",{visible:!1,children:[C.jsx("boxGeometry",{args:[e.width,e.height,e.thickness]}),C.jsx("meshStandardMaterial",{transparent:!0,opacity:0})]})},`bwall-${A}`)),zDA.map((e,A)=>C.jsx(RE,{type:"fixed",colliders:"cuboid",position:e.position,rotation:e.rotation,restitution:.85,friction:.3,children:C.jsxs("mesh",{visible:!1,children:[C.jsx("boxGeometry",{args:[e.width,e.height,e.thickness]}),C.jsx("meshStandardMaterial",{transparent:!0,opacity:0})]})},`dome-${A}`))]})}const Che={uTime:{value:0},uShimmerColor:{value:new SA(1,1,1)}},che=`
    varying vec2 vUv;
    void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
`,lhe=`
    varying vec2 vUv;
    uniform float uTime;
    uniform vec3 uShimmerColor;

    void main() {
        vec2 uv = vUv - 0.5;          // centre-relative (-0.5 to 0.5)
        float d = length(uv) * 2.0;   // 0 at centre, 1 at edge

        // Discard outside the dome circle
        if (d > 1.0) discard;

        // ── 1. Glass thickness profile (hemisphere cross-section) ─────
        float thickness = 1.0 - sqrt(max(1.0 - d * d, 0.0));

        // ── 2. Fresnel rim — sharp bright edge (real glass is brightest at glancing angles) ─
        // Tight inner ramp gives a crisp, defined ring rather than a fuzzy glow
        float fresnel = pow(d, 6.0) * 0.75;
        // Directional lighting bias — upper-left is brightest
        float rimAngle = atan(uv.y, uv.x);
        float rimLit = 0.50 + 0.50 * sin(rimAngle + 0.8);
        float rimHighlight = smoothstep(0.82, 0.95, d) * rimLit * 0.90;
        // Hard outer cutoff at glass edge
        float edgeFade = 1.0 - smoothstep(0.96, 1.0, d);
        float rim = (fresnel + rimHighlight) * edgeFade;

        // ── 3. Gold-rim contact ring — thin bright line right at the base ─
        float contactRing = smoothstep(0.92, 0.96, d) * (1.0 - smoothstep(0.96, 0.98, d)) * 0.60;

        // ── 4. Primary specular — crisp window reflection ───────────────
        // Upper-left crescent: tight, bright reflection like a studio softbox
        vec2 specCenter = vec2(-0.10, 0.14);
        vec2 specUV = (uv - specCenter) * vec2(1.0, 1.5);
        float specD = length(specUV);
        // Use pow for a tighter, more concentrated highlight
        float spec = pow(max(1.0 - specD / 0.22, 0.0), 3.0) * 0.55;
        // Strengthen near the rim (curved glass concentrates reflections at edges)
        spec *= 0.3 + 0.7 * smoothstep(0.15, 0.65, d);

        // ── 5. Secondary specular — smaller opposite kick ──────────────
        vec2 spec2Center = vec2(0.14, -0.10);
        float spec2D = length(uv - spec2Center);
        float spec2 = pow(max(1.0 - spec2D / 0.14, 0.0), 3.0) * 0.22;
        spec2 *= smoothstep(0.10, 0.45, d);

        // ── 6. Shadow vignette — keep extremely faint so center stays clear ─
        float shadow = smoothstep(0.72, 1.0, d) * 0.02;
        // Directional: darker opposite the light
        shadow *= 0.6 + 0.4 * (1.0 - rimLit);

        // ── 7. Glass body tint — very faint aqua/green ─────────────────
        float tintStrength = thickness * 0.0012;
        vec3 glassTint = vec3(0.80, 0.96, 0.90);

        // ── 8. Animated caustic shimmer — large rectangular sweep ───────
        // One large orbiting rectangular glint
        float a1 = uTime * 0.50;
        vec2 shimP1 = vec2(cos(a1) * 0.28, sin(a1) * 0.24);
        vec2 shimDelta = uv - shimP1;
        // Rectangular falloff: wide horizontally, narrow vertically
        float shimRx = max(1.0 - abs(shimDelta.x) / 0.12, 0.0);
        float shimRy = max(1.0 - abs(shimDelta.y) / 0.12, 0.0);
        float shim1 = shimRx * shimRy * 0.90;
        shim1 *= smoothstep(0.62, 0.95, d);

        // Top-edge arc shimmer — bright wide band hugging upper rim
        float topBias = smoothstep(-0.10, 0.35, uv.y);
        float rimProx = smoothstep(0.55, 0.93, d);
        float topShim = topBias * rimProx * 1.15;
        topShim *= 0.72 + 0.28 * sin(uTime * 0.90);

        // Moving rim glint: a bright narrow sweep orbiting the ring so shimmer is readable.
        float sweepAngle = atan(uv.y, uv.x);
        float sweepCore = pow(max(0.0, cos(sweepAngle - (uTime * 1.9))), 14.0);
        float sweepBand = smoothstep(0.80, 0.90, d) * (1.0 - smoothstep(0.94, 0.99, d));
        float rimSweep = sweepCore * sweepBand * 2.4;

        // Interior caustic shimmer: subtle moving light inside the glass body.
        vec2 inP1 = vec2(cos(uTime * 0.85) * 0.16, sin(uTime * 0.72) * 0.14);
        vec2 inP2 = vec2(cos(uTime * -0.64 + 1.2) * 0.11, sin(uTime * -0.93 + 0.4) * 0.10);
        float inBlob1 = pow(max(1.0 - length((uv - inP1) * vec2(0.95, 1.25)) / 0.46, 0.0), 2.0);
        float inBlob2 = pow(max(1.0 - length((uv - inP2) * vec2(1.1, 0.95)) / 0.37, 0.0), 2.1);
        float inWave = 0.5 + 0.5 * sin((uv.x * 10.0) + (uv.y * 7.5) + (uTime * 3.1));
        float interiorMask = 1.0 - smoothstep(0.70, 0.98, d);
        float interiorShimmer = ((inBlob1 * 1.05) + (inBlob2 * 0.95) + (inWave * 0.62)) * interiorMask;

        float shimmer = (shim1 * 1.85) + (topShim * 1.55) + rimSweep;

        // ── Composite ─────────────────────────────────────────────────
        // Keep highlights near edges for a true glass-only look.
        float edgeMask = smoothstep(0.58, 0.96, d);
        float shimmerEdge = shimmer * smoothstep(0.50, 0.93, d);
        float baseHighlight = rim + contactRing + (spec * edgeMask) + (spec2 * edgeMask);
        float highlight = baseHighlight + (shimmerEdge * edgeMask);

        // Glass colour: very faint tint with bright highlights (tinted by uShimmerColor)
        vec3 col = mix(glassTint * tintStrength, uShimmerColor, highlight * 0.9);
        col += uShimmerColor * (rimSweep * 0.12);
        col += uShimmerColor * (interiorShimmer * 0.28);

        // Alpha: highlights are opaque-ish, base glass is very transparent
        // Keep the dome body highly transparent; preserve only subtle reflections.
        float alpha = (baseHighlight * 0.16) + ((shimmerEdge * edgeMask) * 0.46) + (shadow * 0.15) + (tintStrength * 0.25);
        // Keep rim sheen, but allow subtle interior shimmer visibility.
        alpha *= smoothstep(0.52, 0.9, d);
        alpha += interiorShimmer * 0.22;
        alpha = clamp(alpha, 0.0, 0.28);

        gl_FragColor = vec4(col, alpha);
    }
`;function JgA({shimmerColor:e}){const A=E.useMemo(()=>new Cc({uniforms:qW.clone(Che),vertexShader:che,fragmentShader:lhe,transparent:!0,depthWrite:!1}),[]);return E.useEffect(()=>{if(e){const t=new Et(e);A.uniforms.uShimmerColor.value.set(t.r,t.g,t.b)}else A.uniforms.uShimmerColor.value.set(1,1,1)},[e,A]),Ba((t,i)=>{A.uniforms.uTime.value+=i}),C.jsxs("mesh",{rotation:[-Math.PI/2,0,0],position:[0,.012,0],children:[C.jsx("circleGeometry",{args:[ihe,128]}),C.jsx("primitive",{object:A,attach:"material"})]})}function Bhe({results:e,rollTrigger:A,preRollTrigger:t,showDice:i,gameMode:n="cee-lo",gameState:g,noAnimation:o=!1,chargeLevel:s=0,feltColor:a,shimmerColor:r,numberOfDice:I,diceModels:c}){const{scheduleReveal:l}=kB(),B=t??0,Q=E.useMemo(()=>{if(!a)return!1;const k=a.trim().toLowerCase();return k==="transparent"||k==="rgba(0,0,0,0)"||k==="rgba(0, 0, 0, 0)"},[a]),h=I?KgA.slice(0,I):KgA,d=I?FgA.slice(0,I):FgA,p=E.useMemo(()=>{try{const k=navigator.userAgent;return/iPad|iPhone|iPod/.test(k)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}catch{return!1}},[]);E.useEffect(()=>{A>0&&l(2e3)},[A,l]);const y=ic(),m=E.useMemo(()=>({felt:new xg({color:Q?"#0e3a20":a??"#0e3a20",roughness:.95,metalness:.02,transparent:Q,opacity:Q?0:1,depthWrite:!Q}),rim:new xg({color:"gold",roughness:.4,metalness:.85,envMapIntensity:.6})}),[a,Q]),D=()=>(E.useEffect(()=>{var K;if(!p)return;const{gl:k,scene:N}=y;let G=Date.now();const M=15e3;function w(){try{N.traverse(J=>{const q=J.material;q&&(Array.isArray(q)?q.forEach(v=>{v.needsUpdate=!0,v.map&&(v.map.needsUpdate=!0)}):(q.needsUpdate=!0,q.map&&(q.map.needsUpdate=!0)))});try{k.outputColorSpace=rn}catch{}try{k.toneMapping=iy}catch{}k.setClearColor("#000000",0)}catch{}}function b(){document.visibilityState==="visible"?Date.now()-G>M&&w():G=Date.now()}function _(){w()}document.addEventListener("visibilitychange",b);try{(K=k==null?void 0:k.domElement)==null||K.addEventListener("webglcontextrestored",_,!1)}catch{}return()=>{var J;document.removeEventListener("visibilitychange",b);try{(J=k==null?void 0:k.domElement)==null||J.removeEventListener("webglcontextrestored",_,!1)}catch{}}},[p]),null),S=()=>C.jsxs(C.Fragment,{children:[C.jsx("ambientLight",{intensity:.8}),C.jsx("hemisphereLight",{args:["#ffffff",Q?"#0e3a20":a??"#0e3a20",.45],position:[0,6,0]})]});if(n==="craps"){const k=e==null?void 0:e[0],N=e==null?void 0:e[1];return C.jsx(RE,{type:"fixed",children:C.jsxs("group",{children:[C.jsx(D,{}),C.jsx(S,{}),C.jsxs("mesh",{rotation:[-Math.PI/2,0,0],position:[0,-.001,0],children:[C.jsx("circleGeometry",{args:[Wr,128]}),C.jsx("primitive",{object:m.felt,attach:"material"})]}),C.jsxs("mesh",{rotation:[-Math.PI/2,0,0],position:[0,0,0],castShadow:!0,children:[C.jsx("ringGeometry",{args:[Wr-.15,Wr+.2,128]}),C.jsx("primitive",{object:m.rim,attach:"material"})]}),C.jsx(JgA,{shimmerColor:r}),C.jsx(RE,{type:"fixed",colliders:"cuboid",position:[0,-.5,0],friction:.9,restitution:.15,children:C.jsxs("mesh",{visible:!1,children:[C.jsx("boxGeometry",{args:[Wr*2,1,Wr*2]}),C.jsx("meshStandardMaterial",{transparent:!0,opacity:0})]})}),C.jsx(_gA,{}),i&&d.map((G,M)=>C.jsx(vgA,{position:G,result:M===0?k:N,rollTrigger:A,spinTrigger:B,noAnimation:o,active:!o,chargeLevel:s,modelOverride:c==null?void 0:c[M]},M))]})})}return C.jsx(RE,{type:"fixed",children:C.jsxs("group",{children:[C.jsx(D,{}),C.jsx(S,{}),C.jsxs("mesh",{rotation:[-Math.PI/2,0,0],position:[0,-.001,0],children:[C.jsx("circleGeometry",{args:[Wr,128]}),C.jsx("primitive",{object:m.felt,attach:"material"})]}),C.jsx(RE,{type:"fixed",colliders:"cuboid",position:[0,-.5,0],friction:.9,restitution:.15,children:C.jsxs("mesh",{visible:!1,children:[C.jsx("boxGeometry",{args:[Wr*2,1,Wr*2]}),C.jsx("meshStandardMaterial",{transparent:!0,opacity:0})]})}),C.jsxs("mesh",{rotation:[-Math.PI/2,0,0],position:[0,0,0],castShadow:!0,children:[C.jsx("ringGeometry",{args:[Wr-.15,Wr+.2,128]}),C.jsx("primitive",{object:m.rim,attach:"material"})]}),C.jsx(JgA,{shimmerColor:r}),C.jsx(_gA,{}),i&&h.map((k,N)=>C.jsx(vgA,{position:k,result:e==null?void 0:e[N],rollTrigger:A,spinTrigger:B,noAnimation:o,active:!o,chargeLevel:s,modelOverride:c==null?void 0:c[N]},N))]})})}let _K=null,JK=null;function LgA(e){_K=e}function xgA(e){JK=e}function sO(){try{_K==null||_K()}catch{}}function TgA(){try{JK==null||JK()}catch{}}let Im=null;const uT=typeof navigator<"u"&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1),Ehe=uT?[1,1]:[1,1.5],Qhe=!uT,ZDA={alpha:!0,antialias:!uT,powerPreference:"high-performance"};function WDA(e){if(!e)return!1;try{if(typeof e.isContextLost=="function"&&e.isContextLost())return!1;const A=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT),t=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT);return!!(A&&t&&typeof A.precision=="number"&&typeof t.precision=="number")}catch{return!1}}function uhe(){if(typeof document>"u")return!1;try{const e=document.createElement("canvas");e.width=16,e.height=16;const A=ZDA,t=e.getContext("webgl2",A)||e.getContext("webgl",A)||e.getContext("experimental-webgl",A);return WDA(t)}catch{return!1}}const Jl=()=>{var A,t;const e=Im;if(Im=null,e){try{(t=(A=e.renderLists)==null?void 0:A.dispose)==null||t.call(A)}catch{}try{e.dispose()}catch{}}};function VDA(){Jl()}class dhe extends ue.Component{constructor(){super(...arguments);Oi(this,"state",{hasError:!1})}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t,i){var g;JI.error("CanvasErrorBoundary caught",{message:t==null?void 0:t.message,stack:(g=t==null?void 0:t.stack)==null?void 0:g.slice(0,500)}),console.error("[DiceBoard] Canvas error boundary caught:",t,i);const n=(t==null?void 0:t.message)||"";(n.includes("autoReset")||n.includes("undefined is not an object")||n.includes("precision")||n.includes("reading null")||n.includes("getShaderPrecisionFormat")||n.includes("WebGL")||n.includes("reading 'precision'"))&&this.props.onError()}reset(){this.setState({hasError:!1})}render(){return this.state.hasError?null:this.props.children}}function hhe(){const{size:e,camera:A}=ic();return ue.useEffect(()=>{const t=Math.min(e.width,e.height)/2,i=Wr+.75,n=A.position,g=Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z),o=g>.1&&n.y>.1?n.y/g:1,s=o<.95?1+(1-o)*.6:1,a=t/(i*s),r=A;r.zoom=a,r.updateProjectionMatrix()},[e.width,e.height,A]),null}function XDA({isWaiting:e,rollTrigger:A,results:t,preRollTrigger:i,gameMode:n="cee-lo",gameState:g,diceSettled:o,chargeLevel:s=0,cameraAngle:a=0,feltColor:r,shimmerColor:I,numberOfDice:c,diceModels:l,rollEnabled:B=!1,onRollRequest:Q}){const h=n==="craps",[d,p]=ue.useState(!0),[y,m]=ue.useState(null),D=ue.useRef(null),[S,k]=ue.useState(0),[N,G]=ue.useState(!1),[M,w]=ue.useState(!1),[b,_]=ue.useState(0),K=ue.useRef(0),J=ue.useRef(!0),q=ue.useRef(null),v=ue.useRef(null),U=uT?8:2,x=ue.useCallback(()=>{J.current&&(Jl(),G(!0))},[]),T=ue.useCallback(()=>{K.current=Math.min(K.current+1,U+1),_(K.current)},[]),z=ue.useCallback(()=>{K.current=0,_(0)},[]),Z=ue.useCallback(()=>{q.current!=null&&(window.clearTimeout(q.current),q.current=null)},[]),eA=ue.useCallback(()=>{v.current!=null&&(window.clearTimeout(v.current),v.current=null)},[]),aA=ue.useCallback(uA=>{J.current&&(Z(),w(!1),q.current=window.setTimeout(()=>{q.current=null,J.current&&k(X=>X+1)},Math.max(16,uA)))},[Z]),sA=ue.useCallback(()=>{J.current&&(Z(),Jl(),z(),G(!1),w(!1),aA(50))},[Z,z,aA]);ue.useEffect(()=>(J.current=!0,LgA(Jl),xgA(sA),()=>{J.current=!1,LgA(null),xgA(null),Z(),eA(),Jl()}),[eA,Z,sA]),ue.useEffect(()=>{if(N)return;let uA=!1;eA();const X=()=>{var cA;if(uA||!J.current)return;if(uhe()){w(!0),K.current>0&&z();return}w(!1);const O=K.current;try{(cA=JI.warn)==null||cA.call(JI,"DiceBoard WebGL preflight failed",{attempt:O,max:U})}catch{}if(O<U){T();const wA=Math.min(2200,350*Math.pow(1.55,O));v.current=window.setTimeout(X,wA)}else x()};return X(),()=>{uA=!0,eA()}},[T,S,eA,x,z,N]),ue.useEffect(()=>{let uA=!1;const X=YA=>{var he,le;if(uA)return;const jA=Im;if(!jA)return;let ie=!1;try{const NA=(he=jA.getContext)==null?void 0:he.call(jA);ie=!!(NA&&typeof NA.isContextLost=="function"&&NA.isContextLost())}catch{ie=!0}if(ie){try{(le=JI.warn)==null||le.call(JI,"DiceBoard probe detected lost WebGL context, forcing fresh remount",{source:YA})}catch{}Jl(),z(),aA(250)}},O=()=>{document.visibilityState==="visible"&&X("visibilitychange")},cA=()=>X("pageshow"),wA=YA=>{var he,le;const jA=YA.reason,ie=jA&&(jA.message||String(jA))||"";if(!uA&&(ie.includes("reading 'precision'")||ie.includes("getShaderPrecisionFormat")||ie.includes("WebGLRenderer")||ie.includes("WebGLCapabilities")||ie.includes("initGLContext"))){try{(he=JI.warn)==null||he.call(JI,"DiceBoard caught WebGL init rejection, scheduling remount",{msg:ie.slice(0,200)})}catch{}Jl();const NA=K.current,EA=Math.min(1600,400*Math.pow(2,NA));NA<U?(T(),aA(EA)):!uA&&J.current&&x();try{(le=YA.preventDefault)==null||le.call(YA)}catch{}}};document.addEventListener("visibilitychange",O),window.addEventListener("pageshow",cA),window.addEventListener("unhandledrejection",wA);let xA=null;return(async()=>{var YA;try{const{App:jA}=await Qi(async()=>{const{App:ie}=await Promise.resolve().then(()=>GR);return{App:ie}},void 0);if(uA)return;if(xA=await jA.addListener("resume",()=>X("capacitor-resume")),uA){try{await((YA=xA==null?void 0:xA.remove)==null?void 0:YA.call(xA))}catch{}xA=null}}catch{}})(),()=>{var YA;uA=!0;try{document.removeEventListener("visibilitychange",O)}catch{}try{window.removeEventListener("pageshow",cA)}catch{}try{window.removeEventListener("unhandledrejection",wA)}catch{}try{(YA=xA==null?void 0:xA.remove)==null||YA.call(xA)}catch{}xA=null}},[T,x,z,aA]),ue.useEffect(()=>{let uA=!0;return(async()=>{try{const X=await Xo();if(!uA)return;p(X.showAnimations!==!1)}catch{}})(),()=>{uA=!1}},[]),ue.useCallback(async()=>{const uA=!d;p(uA);try{const X=await Xo();await JE({...X,showAnimations:uA})}catch{}},[d]);const pA=ue.useMemo(()=>{if(d&&!N)return null;const uA=Array.isArray(t)?t:void 0;if(!uA)return null;const X=(h?uA.slice(0,2):uA).filter(O=>typeof O=="number"&&O>=1&&O<=6);return X.length===0?null:X},[t,d,h,N]),gA=Il(),yA=gA==null?void 0:gA.throttleVideoForAnimation,fA=ue.useRef(A);ue.useEffect(()=>{yA&&(A>fA.current&&yA(!0).catch(()=>{}),fA.current=A)},[A,yA]),ue.useEffect(()=>{if(yA&&o&&t){const uA=setTimeout(()=>{yA(!1).catch(()=>{})},500);return()=>clearTimeout(uA)}},[o,t,yA]);const[RA,qA]=ue.useState(0);ue.useEffect(()=>{if(!h)return;const uA=X=>{var wA;const O=((wA=X.detail)==null?void 0:wA.streak)??0;let cA=0;O>=7?cA=5:O>=5?cA=4:O>=4?cA=3:O>=3?cA=2:O>=2&&(cA=1),qA(cA)};return window.addEventListener("craps:streak",uA),()=>window.removeEventListener("craps:streak",uA)},[h]);const W=RA>0?`dice-halo dice-halo--active dice-halo--level-${RA}`:"dice-halo";ue.useEffect(()=>{var Ie;if(!h){m(null);return}const uA=g==null?void 0:g.lastRoll;if(!uA||!Array.isArray(uA.dice))return;const X=String(uA.timestamp??`${uA.dice.join("-")}-${uA.total}-${((Ie=uA.events)==null?void 0:Ie.join("|"))??""}`);if(D.current===X)return;D.current=X;const O=Number(uA.total??uA.dice[0]+uA.dice[1]),cA=new Set((uA.events??[]).map(DA=>String(DA).toUpperCase())),wA=uA.resolutions??{},xA=Number(uA.point??(g==null?void 0:g.crapsPoint)??0)||null,YA=cA.has("POINT_MADE")||[...cA].some(DA=>DA.startsWith("POINTMADE:")),jA=cA.has("SEVEN_OUT")||cA.has("SEVENOUT")||O===7&&!!wA.passLineLosses,ie=cA.has("POINT_SET"),he=!xA&&(O===7||O===11)&&!!wA.passLineWins,le=uA.dice[0]===uA.dice[1]&&[4,6,8,10].includes(O);let NA=`Rolled ${O}`,EA=`${uA.dice[0]} + ${uA.dice[1]}`,PA="neutral";YA?(NA="Point Made",EA=`${O} hits clean`,PA="win"):he?(NA=O===11?"Yo Eleven":"Natural Seven",EA="Come-out winner",PA="win"):jA?(NA="Seven Out",EA="Dice pass to the next shooter",PA="loss"):ie?(NA=`Point Is ${xA??O}`,EA="Hit it again before seven",PA="point"):le&&(NA=`Hard ${O}`,EA=`${uA.dice[0]} the hard way`,PA="win");const ZA=window.setTimeout(()=>{m({key:X,total:O,title:NA,detail:EA,tone:PA})},650),FA=window.setTimeout(()=>{m(DA=>(DA==null?void 0:DA.key)===X?null:DA)},2450);return()=>{window.clearTimeout(ZA),window.clearTimeout(FA)}},[g==null?void 0:g.lastRoll,h]);const[$,L]=ue.useState(null),H=ue.useRef(0),[P,tA]=ue.useState(0);ue.useEffect(()=>{if(h)return;const uA=X=>{var cA;const O=(cA=X.detail)==null?void 0:cA.result;(O==="win"||O==="lose")&&(H.current+=1,L(O),tA(wA=>O==="win"?wA+1:0))};return window.addEventListener("ceelo:result",uA),()=>window.removeEventListener("ceelo:result",uA)},[h]),ue.useEffect(()=>{if(!$)return;const uA=setTimeout(()=>L(null),1900);return()=>clearTimeout(uA)},[$,H.current]);const iA=$?`dice-halo dice-halo--ceelo dice-halo--ceelo-${$}`:"",oA=ue.useMemo(()=>P>=7?5:P>=5?4:P>=4?3:P>=3?2:P>=2?1:0,[P]),IA=oA>0?`dice-halo dice-halo--active dice-halo--level-${oA}`:"dice-halo",CA=ue.useCallback(()=>{!B||e||!Q||Q()},[e,Q,B]),_A=ue.useCallback(uA=>{!B||e||uA.key!=="Enter"&&uA.key!==" "||(uA.preventDefault(),CA())},[CA,e,B]);return C.jsxs("div",{className:`dice-board-wrap${B&&!e?" dice-board-wrap--rollable":""}${y?` dice-board-wrap--craps-impact dice-board-wrap--${y.tone}`:""}`,role:B&&!e?"button":void 0,tabIndex:B&&!e?0:void 0,"aria-label":B&&!e?"Roll dice":void 0,onClick:CA,onKeyDown:_A,children:[h&&C.jsx("div",{className:W,"aria-hidden":!0}),y&&C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"craps-roll-impact-ring","aria-hidden":!0},`pulse-${y.key}`),C.jsxs("div",{className:"craps-roll-moment",role:"status","aria-live":"polite",children:[C.jsx("span",{className:"craps-roll-moment__total",children:y.total}),C.jsxs("span",{className:"craps-roll-moment__copy",children:[C.jsx("strong",{children:y.title}),C.jsx("small",{children:y.detail})]})]},`moment-${y.key}`)]}),!h&&oA>0&&C.jsx("div",{className:IA,"aria-hidden":!0}),!h&&$&&C.jsx("div",{className:iA,"aria-hidden":!0},H.current),C.jsxs("div",{className:"dice-board-canvas","data-testid":"dice-board",children:[N?C.jsxs("div",{className:"dice-board-canvas__error",role:"alert",children:[C.jsx("p",{children:"3D rendering unavailable"}),C.jsx("p",{className:"dice-board-canvas__error-hint",children:"Dice results will show as static images"}),C.jsx("button",{className:"dice-board-canvas__retry",type:"button",onClick:sA,children:"Retry 3D"})]}):!M||b>0&&b<=U?C.jsx("div",{className:"dice-board-canvas__recovering",role:"status","aria-live":"polite",children:C.jsxs("p",{children:["Restoring 3D graphics... (attempt ",b,"/",U,")"]})}):C.jsx(dhe,{onError:()=>{console.warn("[DiceBoard] Error boundary triggered, attempting recovery"),Jl(),setTimeout(()=>{K.current<U?(T(),aA(0)):x()},300)},children:C.jsxs(QG,{shadows:Qhe,orthographic:!0,dpr:Ehe,gl:ZDA,style:{background:"transparent"},onCreated:({gl:uA})=>{var wA;if(Jl(),!uA||!uA.getContext){if(console.error("[DiceBoard] WebGL context creation failed"),K.current<U){console.warn(`[DiceBoard] Attempting context recovery (attempt ${K.current+1}/${U})`),T(),aA(300);return}console.error("[DiceBoard] Max retry attempts reached, falling back to static"),x();return}let X;try{if(X=uA.getContext(),!WDA(X))throw new Error("Context missing required methods")}catch(xA){console.error("[DiceBoard] WebGL context test failed:",xA),K.current>=U?(console.error("[DiceBoard] Max retry attempts reached, falling back to static"),x()):(T(),aA(300));return}Im=uA,K.current>0&&(console.log("[DiceBoard] Context restored successfully after retries"),z());try{uA.setClearColor(0,0)}catch(xA){console.error("[DiceBoard] setClearColor failed:",xA)}try{uA.outputColorSpace=rn}catch{}try{rn!=null&&(uA.outputEncoding=rn)}catch{}try{uA.toneMapping=iy}catch{}try{uA.toneMappingExposure=1}catch{}try{uA.physicallyCorrectLights=!0}catch{}const O=uA==null?void 0:uA.domElement,cA=xA=>{var YA;try{(YA=xA.preventDefault)==null||YA.call(xA)}catch{}JI.error("DiceBoard WebGL context LOST",{retries:K.current}),console.warn("[DiceBoard] WebGL context lost event detected"),Jl(),z(),aA(300)};try{O==null||O.addEventListener("webglcontextlost",cA,!1)}catch{}try{const xA=()=>{try{O==null||O.removeEventListener("webglcontextlost",cA,!1)}catch{}Im===uA&&(Im=null)},YA=(wA=uA.dispose)==null?void 0:wA.bind(uA);uA.dispose=()=>{try{xA()}catch{}YA&&YA()}}catch{}},children:[C.jsx($de,{makeDefault:!0,position:[0,20*Math.cos(a),20*Math.sin(a)],near:.1,far:100,zoom:16,rotation:[-(Math.PI/2-a),0,0]}),C.jsx(hhe,{}),C.jsx("ambientLight",{intensity:.7}),C.jsx("directionalLight",{position:[6,12,6],intensity:1.1,castShadow:!0}),C.jsx(wde,{gravity:[0,-9.8,0],children:C.jsx(Bhe,{rollTrigger:A,results:t,preRollTrigger:i,showDice:d,gameMode:n,gameState:g,noAnimation:!d,chargeLevel:s,feltColor:r,shimmerColor:I,numberOfDice:c,diceModels:l})})]},S)},`eb-${S}`),pA&&pA.length>0&&C.jsx("div",{className:"dice-board-canvas__faces","aria-label":"Dice faces","aria-live":"polite",children:C.jsx(EpA,{dice:pA})})]})]})}const phe=Object.freeze(Object.defineProperty({__proto__:null,default:XDA,disposeDiceBoardRenderer:VDA},Symbol.toStringTag,{value:"Module"})),$DA=50,iv=$DA/1200,fhe=({disabled:e,busy:A=!1,onClick:t,onPressStart:i,onChargeChange:n,label:g="ROLL"})=>{const o=e||A,s=E.useRef(!1),a=E.useRef(0),r=E.useRef(null),I=E.useRef(n);I.current=n,E.useEffect(()=>()=>{r.current&&clearInterval(r.current)},[]);const c=E.useCallback(()=>{var m;a.current=0,(m=I.current)==null||m.call(I,0),r.current&&clearInterval(r.current),r.current=window.setInterval(()=>{var D;a.current=Math.min(1,a.current+iv),(D=I.current)==null||D.call(I,a.current),a.current>=.25&&a.current<.25+iv*1.5?So("Light"):a.current>=.6&&a.current<.6+iv*1.5?So("Medium"):a.current>=.95&&a.current<.95+iv*1.5&&So("Heavy")},$DA)},[]),l=E.useCallback(()=>{var m;r.current&&(clearInterval(r.current),r.current=null),(m=I.current)==null||m.call(I,0)},[]),B=E.useRef(0),Q=E.useCallback(()=>{try{window.dispatchEvent(new CustomEvent("ui:roll-interaction"))}catch{}},[]),h=E.useCallback(m=>{o||s.current||(m.preventDefault(),m.stopPropagation(),m.currentTarget.setPointerCapture(m.pointerId),s.current=!0,Q(),On(),i==null||i(),c())},[o,Q,i,c]),d=E.useCallback(async m=>{if(m.preventDefault(),m.stopPropagation(),!!s.current){s.current=!1,m.currentTarget.hasPointerCapture(m.pointerId)&&m.currentTarget.releasePointerCapture(m.pointerId),l(),B.current=Date.now()+400,Q(),t();try{window.dispatchEvent(new CustomEvent("ui:roll"))}catch{}await So("Heavy")}},[Q,t,l]),p=E.useCallback(m=>{m.stopPropagation(),s.current&&(s.current=!1,m.currentTarget.hasPointerCapture(m.pointerId)&&m.currentTarget.releasePointerCapture(m.pointerId),l())},[l]),y=E.useCallback(async m=>{var D,S;if(m.stopPropagation(),s.current||Date.now()<B.current){m.preventDefault();return}if(!o){Q(),i==null||i(),(D=I.current)==null||D.call(I,1),t(),(S=I.current)==null||S.call(I,0);try{window.dispatchEvent(new CustomEvent("ui:roll"))}catch{}await So("Heavy")}},[o,Q,t,i]);return C.jsx("div",{className:"zentara-roll-wrapper",children:C.jsxs("button",{type:"button",className:"zentara-roll-btn",onClick:y,onPointerDown:h,onPointerUp:d,onPointerCancel:p,disabled:o,"aria-label":A?"Rolling dice":"Roll dice","aria-busy":A||void 0,children:[A&&C.jsx("span",{className:"zentara-roll-spinner","aria-hidden":"true"}),C.jsx("span",{className:"zentara-roll-halo","aria-hidden":"true"}),C.jsx("span",{className:"zentara-roll-label","aria-live":"polite",children:A?"...":g})]})})},qgA=ue.memo(fhe),yhe=420,YgA=e=>C.jsxs("span",{className:"zentara-balance-pill",children:["Balance: ",e]}),Dhe=({phase:e,pendingEffect:A,isMyTurn:t,inJail:i,onRoll:n,onRollPressStart:g,onRollChargeChange:o,onBuy:s,onSkipBuy:a,onPayRent:r,onHeroClashRoll:I,onPayTax:c,onResolveCard:l,onPayBail:B,onPlantSpy:Q,plantSpyEligibleGroup:h=null,plantSpyCost:d=1e3,suppressBuyPrompt:p=!1,buyInProgress:y=!1,tileOwnedByMe:m=!1,credits:D,upgradeableCount:S=0,armableCount:k=0,onArmPlanets:N,clashPhase:G="idle",children:M})=>{const w=G!=="idle",b=E.useRef(null),_=E.useRef(e);return E.useEffect(()=>{if(e!==_.current){_.current=e;const K=b.current;if(!K)return;K.style.pointerEvents="none";const J=setTimeout(()=>{K.style.pointerEvents=""},yhe);return()=>{clearTimeout(J),K.style.pointerEvents=""}}},[e]),t?C.jsxs("div",{className:"zentara-action-bar",ref:b,children:[C.jsxs("div",{className:"zentara-action-bar__left",children:[!w&&e==="pre-roll"&&!i&&C.jsxs(C.Fragment,{children:[C.jsx(qgA,{onClick:n,onPressStart:g,onChargeChange:o,label:"ROLL DICE"}),k>0&&N&&C.jsxs("button",{className:"zentara-btn zentara-btn--secondary zentara-btn--arm",onClick:N,title:S>0?"Arm planets":"Not enough credits to arm",disabled:S===0,children:[C.jsx("span",{className:"zentara-btn--arm__full",children:"🔫 Arm Planets"}),C.jsx("span",{className:"zentara-btn--arm__short",children:"🔫 Arm"})]})]}),!w&&e==="pre-roll"&&i&&C.jsxs(C.Fragment,{children:[C.jsx(qgA,{onClick:n,onPressStart:g,onChargeChange:o,label:"ROLL"}),C.jsx("button",{className:"zentara-btn zentara-btn--secondary",onClick:B,children:"Wake Up"}),YgA(D)]}),!w&&e==="rolling"&&C.jsx("span",{className:"zentara-action-bar__waiting",children:"Rolling…"}),e==="action"&&(A==null?void 0:A.action)==="buy-prompt"&&!p&&C.jsxs(C.Fragment,{children:[C.jsx("button",{className:"zentara-btn zentara-btn--secondary zentara-btn--prompt-pulse",onClick:a,disabled:y||m,children:"Pass"}),YgA(D)]}),e==="action"&&(A==null?void 0:A.action)==="draw-card"&&A.cardText&&C.jsx("span",{className:"zentara-card-prompt__text",children:A.cardText})]}),(e==="action"||M||h)&&!w&&C.jsxs("div",{className:"zentara-action-bar__right",children:[e==="action"&&(A==null?void 0:A.action)==="buy-prompt"&&!p&&C.jsxs("button",{className:"zentara-btn zentara-btn--primary zentara-btn--prompt-pulse",onClick:s,disabled:y||m||D<(A.amount??0),children:["Capture (",A.amount,")"]}),e==="action"&&(A==null?void 0:A.action)==="draw-card"&&C.jsx("span",{className:"zentara-action-bar__waiting",children:A.cardMoveTo!==void 0||A.cardGoToJail?"Warping…":(A.amount??0)>=0?`Looting +${A.amount} credits…`:`Energy draining… (-${Math.abs(A.amount??0)})`}),e==="action"&&(A==null?void 0:A.action)==="energy-toll"&&C.jsxs("span",{className:"zentara-action-bar__waiting",children:["Taking damage… (-",A.amount," credits)"]}),e==="action"&&(A==null?void 0:A.action)==="hero-clash"&&!w&&C.jsx("button",{className:"zentara-btn zentara-btn--primary",onClick:I,children:"⚔️ Hero Clash! Roll"}),e==="action"&&(A==null?void 0:A.action)==="spy-clash"&&!w&&C.jsx("span",{className:"zentara-action-bar__waiting",children:"🕵️ Spy Strike in progress…"}),t&&h&&!A&&!w&&(e==="action"||e==="pre-roll"||e==="done")&&C.jsxs("button",{className:"zentara-btn zentara-btn--secondary",onClick:()=>Q==null?void 0:Q(h),disabled:D<d,title:`Plant a spy on the ${h} group`,children:["🕵️ Plant Spy (",d,")"]}),e==="action"&&(A==null?void 0:A.action)==="void-drain"&&C.jsxs("span",{className:"zentara-action-bar__waiting",children:["Energy draining to the cosmos… (-",A.amount," credits)"]}),M]})]}):M?C.jsx("div",{className:"zentara-action-bar",children:C.jsx("div",{className:"zentara-action-bar__right",children:M})}):null},mhe=ue.memo(Dhe),She={start:PpA,planet:jpA,station:ZpA,asteroid:qZ,nebula:YZ,wormhole:zpA,tax:$3,"void-drain":$3,jail:WpA,"go-to-jail":VpA,"free-parking":XpA},whe={start:"Launch Gate",jail:"Cryosleep Chamber","go-to-jail":"Black Hole","free-parking":"Rest Stop",wormhole:"Wormhole",asteroid:"Asteroid Field",nebula:"Nebula",tax:"Void Drain","void-drain":"Void Drain",station:"Space Station"},khe={start:"Collect ✦200 energy each time you pass.",planet:"Capture this planet and upgrade its defenses to collect an energy toll from rivals.",station:"Space station — energy toll scales with the number of outposts you control.",asteroid:"Incoming asteroid! Draw a card — fortune or disaster awaits.",nebula:"Drifting through a nebula… draw a card to see what you find.",wormhole:"A rift in space — teleport to the paired wormhole.",tax:"The cosmos claims its due. Your energy drains into the void.","void-drain":"The cosmos claims its due. Your energy drains into the void.",jail:"Cryosleep Chamber — just visiting, unless you've been frozen.","go-to-jail":"Gravitational pull drags you straight into cryosleep.","free-parking":"A quiet sector of space. Rest here — nothing happens."},yo={0:"The last jump gate still standing from the Old Federation. Every fleet musters here.",1:"The closest star system to Sol — 4.37 light-years away. A prized first colony.",2:"Sensor ghosts dance in the ionised gas. Some say lost ships broadcast here forever.",3:"Tidally locked to its red dwarf star — one side in perpetual daylight, the other frozen.",4:"Galactic customs checkpoint. All cargo is taxed at ✦200 before passage.",5:"First-ring relay outpost. Provides fuel, repairs and encrypted comms to passing fleets.",6:"An ocean world with twice Earth's gravity — ideal for submarine fleet bases.",7:"A dense belt of iron-nickel asteroids. Rich salvage, but collisions are frequent.",8:"Slightly larger than Earth with a 112-day year. Its amber skies hide ancient ruins.",9:"Located in the habitable zone of Kepler-62. Thick clouds shroud a lush surface.",10:"Maximum-security cryosleep facility. Triple-layered stasis fields prevent any escape.",11:"One of seven known TRAPPIST worlds. Volcanic vents power its geothermal forges.",12:"A stable spatial rift linked to Wormhole β — instantaneous travel across the sector.",13:"Mild surface temperature and low radiation make this a premium colony world.",14:"The outermost habitable TRAPPIST planet. Ice-capped but mineral-rich beneath.",15:"Mid-range waystation with rotating habitat ring. Popular with mercenary crews.",16:"Orbits a quiet red dwarf only 11 light-years from Sol. A strategic forward base.",17:"Violent electromagnetic storms scramble navigation — tread carefully.",18:"A super-Earth candidate with a 168-day orbit. Its twin moons light the night sky.",19:"The furthest Tau Ceti colony — harsh winters but vast tundra mining operations.",20:"Neutral territory by treaty. All fleets stand down inside the beacon perimeter.",21:"Orbits within a triple-star system. Three sunsets paint the sky every evening.",22:"A rogue asteroid storm — fragment impacts can cripple shields in seconds.",23:"Slightly smaller than Earth. Underground cavern cities shelter millions from solar flares.",24:"Tidally heated, with surface geysers erupting every few hours. Rich in rare isotopes.",25:"Deep-space listening post. Its long-range arrays detect fleet movements sectors away.",26:"A diamond-core super-Earth. Surface temperatures melt hull plating — orbit only.",27:"The cooler sibling of 55e. Automated mining drones extract carbon nanomaterials.",28:"Exit point of the spatial rift from Wormhole α. Gravitational tides can be rough.",29:"A massive super-Earth with 8× Earth's mass. High gravity breeds tough colonists.",30:"Singularity detected — gravitational pull is inescapable. Straight to cryosleep.",31:"Orbits one of the oldest known stars — 11 billion years old. Ancient relics abound.",32:"The outer companion to Kapteyn b. Frozen methane lakes cover its dark surface.",33:"A shimmering gateway nebula — the gas refracts light into dazzling prismatic arcs.",34:"A rocky world just 14 light-years away. Its thin atmosphere crackles with static.",35:"The final frontier outpost before deep void. Last chance to resupply or repair.",36:"A sudden meteor shower — Loss or fortune depends on your shield configuration.",37:"A mythical jungle world. Bio-luminescent flora and apex predators rule the canopy.",38:"War-effort contribution. All empires pay ✦100 to fund the galactic defense grid.",39:"The legendary throne world at the galaxy's heart. Whoever holds Zentara rules all."},Mhe={"Alpha Centauri":yo[1],"Proxima B":yo[3],"Kepler-22b":yo[6],"Kepler-442b":yo[8],"Kepler-62f":yo[9],"Trappist-1d":yo[11],"Trappist-1e":yo[13],"Trappist-1f":yo[14],"Ross 128b":yo[16],"Tau Ceti e":yo[18],"Tau Ceti f":yo[19],"Gliese 667Cc":yo[21],"Gliese 581d":yo[23],"Gliese 581g":yo[24],"Cancri 55e":yo[26],"Cancri 55f":yo[27],"HD 40307g":yo[29],"Kapteyn b":yo[31],"Kapteyn c":yo[32],"Wolf 1061c":yo[34],Pandora:yo[37],Zentara:yo[39]},Nhe=({tile:e,property:A,ownerName:t,ownerColor:i,planetContent:n,onClick:g})=>{var p;if(!e)return C.jsx("div",{className:"zentara-tile-card zentara-tile-card--empty",children:C.jsx("span",{className:"zentara-tile-card__hint",children:"Tap a tile for info"})});const o=e.group?Bs[e.group]:"#1e3a5f",s=(n==null?void 0:n.imageUrl)??She[e.type],a=khe[e.type]??"",r=(n==null?void 0:n.lore)??(e.type==="planet"?Mhe[e.name]:yo[e.id])??"",I=A!=null,c=(A==null?void 0:A.upgradeLevel)??0,l=(p=e.rent)==null?void 0:p[c],Q=I?["Unfortified","Shield I","Shield II","Shield III","Shield IV","Fortress"][c]??"Unfortified":null,h=I?"⬢".repeat(c)+"⬡".repeat(5-c):null,d=I&&Q?`${Q}  ${h}`:a;return C.jsxs("div",{className:"zentara-tile-card",onClick:g,style:{cursor:g?"pointer":void 0},children:[C.jsx("div",{className:"zentara-tile-card__accent",style:{background:o}}),C.jsxs("div",{className:"zentara-tile-card__body",children:[C.jsxs("div",{className:"zentara-tile-card__header",children:[s&&C.jsx("img",{className:"zentara-tile-card__img",src:s,alt:e.type}),C.jsx("span",{className:"zentara-tile-card__name",children:e.name})]}),d&&C.jsx("div",{className:`zentara-tile-card__desc${["station","asteroid","nebula","wormhole"].includes(e.type)&&!I?" zentara-tile-card__desc--breach":""}`,children:d}),r&&C.jsx("div",{className:"zentara-tile-card__fact",children:r}),C.jsx("div",{className:"zentara-tile-card__status",style:I&&i?{color:i}:void 0,children:I?`Controlled by ${t??"Unknown"}`:e.cost!=null?"Uncontrolled":whe[e.type]??e.type.replace(/-/g," ")}),e.cost!=null&&C.jsx("div",{className:"zentara-tile-card__stats",children:I?l!=null?C.jsxs(C.Fragment,{children:["Damage ✦",l]}):null:C.jsxs(C.Fragment,{children:["Capture ✦",e.cost,l!=null&&C.jsxs(C.Fragment,{children:[" · Damage ✦",l]})]})})]})]})},Rhe=ue.memo(Nhe),Ghe={start:"Launch Gate",jail:"Cryosleep Chamber","go-to-jail":"Black Hole","free-parking":"Rest Stop",wormhole:"Wormhole",asteroid:"Asteroid Field",nebula:"Nebula",tax:"Void Drain","void-drain":"Void Drain",station:"Space Station"},bhe=({tile:e,property:A,ownerName:t,isOwnedByMe:i,canAffordUpgrade:n,onClose:g,onUpgrade:o,onMortgage:s,onSell:a,onSabotage:r,sabotageCost:I,credits:c,groupOwned:l,groupTotal:B,planetContent:Q})=>{if(!e)return null;const h=e.group?Bs[e.group]:"#1e3a5f",d=c!=null&&I!=null&&c>=I;return C.jsx("div",{className:"zentara-tmodal-overlay",onClick:g,children:C.jsxs("div",{className:"zentara-tmodal-card",onClick:p=>p.stopPropagation(),children:[C.jsx("div",{className:"zentara-tmodal__strip",style:{background:h}}),C.jsx("h3",{className:"zentara-tmodal__name",children:e.name}),(Q==null?void 0:Q.imageUrl)&&C.jsx("img",{className:"zentara-tmodal__planet-image",src:Q.imageUrl,alt:""}),C.jsx("p",{className:"zentara-tmodal__type",children:Ghe[e.type]??e.type.replace(/-/g," ")}),(Q==null?void 0:Q.lore)&&C.jsx("p",{className:"zentara-tmodal__lore",children:Q.lore}),e.cost!=null&&C.jsxs("p",{className:"zentara-tmodal__cost",children:["Capture Cost: ",C.jsx("strong",{children:e.cost})," energy",c!=null&&C.jsxs("span",{className:"zentara-tmodal__balance-pill",children:["Balance: ",c]})]}),e.rent&&C.jsxs("div",{className:"zentara-tmodal__rent",children:[C.jsxs("div",{children:["Damage: ",e.rent[0]]}),e.rent.slice(1).map((p,y)=>C.jsxs("div",{children:["Arms Lv.",y+1,": ",p]},y))]}),A&&C.jsxs("div",{className:"zentara-tmodal__owner-section",children:[C.jsxs("div",{children:["Commander: ",t??"Unknown"]}),C.jsxs("div",{children:["Arms Level: ",A.upgradeLevel]}),A.dormant&&C.jsx("div",{className:"zentara-tmodal__mortgaged",children:"Decommissioned"})]}),e.group&&B!=null&&B>1&&i&&C.jsxs("div",{className:"zentara-tmodal__sector-box",children:[C.jsxs("div",{className:"zentara-tmodal__sector-row",children:[C.jsx("span",{className:"zentara-tmodal__sector-label",style:{color:h},children:"Sector Control"}),C.jsxs("span",{className:"zentara-tmodal__sector-count","data-full":l===B?"true":void 0,children:[l,"/",B]})]}),C.jsx("div",{className:"zentara-tmodal__sector-bars",children:Array.from({length:B}).map((p,y)=>C.jsx("div",{className:"zentara-tmodal__sector-bar",style:{background:y<(l??0)?h:"rgba(255,255,255,0.12)"}},y))}),l!=null&&l<B&&C.jsxs("div",{className:"zentara-tmodal__sector-warn",children:["⚠ Capture all ",B," planets in this sector to unlock arming"]}),l===B&&A&&A.upgradeLevel<5&&C.jsx("div",{className:"zentara-tmodal__sector-ok",children:"✓ Full sector control — arming unlocked"})]}),i&&A&&!A.dormant&&C.jsxs("div",{className:"zentara-tmodal__actions",children:[A.upgradeLevel<5&&e.upgradeCost!=null&&C.jsxs("button",{onClick:()=>o==null?void 0:o(e.id),disabled:!n,className:"zentara-tmodal__action-btn zentara-tmodal__action-btn--arm",children:["Arm (",e.upgradeCost,")"]}),A.upgradeLevel===0&&C.jsx("button",{onClick:()=>s==null?void 0:s(e.id),className:"zentara-tmodal__action-btn zentara-tmodal__action-btn--decommission",children:"Decommission"}),A.upgradeLevel===0&&C.jsxs("button",{onClick:()=>a==null?void 0:a(e.id),className:"zentara-tmodal__action-btn zentara-tmodal__action-btn--sell",children:["Sell (",Math.floor((e.cost??0)/2),")"]})]}),i&&(A==null?void 0:A.dormant)&&C.jsxs("button",{onClick:()=>s==null?void 0:s(e.id),className:"zentara-tmodal__action-btn--recommission",children:["Recommission (",Math.floor((e.cost??0)*.3),")"]}),!i&&A&&A.upgradeLevel>0&&I!=null&&C.jsxs("button",{onClick:()=>r==null?void 0:r(e.id),disabled:!d,className:"zentara-tmodal__action-btn--sabotage",children:["Sabotage Arms (",I,")"]}),C.jsx("button",{onClick:g,className:"zentara-tmodal__close-btn",children:"Close"})]})})},Uhe=ue.memo(bhe),AmA=({playerId:e,credits:A,properties:t,board:i,onUpgrade:n,onClose:g})=>{const o=E.useMemo(()=>{const s=[];for(const a of t){if(a.ownerId!==e||a.dormant)continue;const r=i[a.tileId];if(!(r!=null&&r.upgradeCost))continue;const I=Hm(e,a.tileId,i,t);a.upgradeLevel>=I||r.upgradeCost>A||s.push({property:a,tile:r,maxLevel:I})}return s.sort((a,r)=>(a.tile.group??"").localeCompare(r.tile.group??"")||a.tile.id-r.tile.id),s},[e,A,t,i]);return er.createPortal(C.jsx("div",{className:"zentara-arm-overlay",onClick:g,children:C.jsxs("div",{className:"zentara-arm-card",onClick:s=>s.stopPropagation(),children:[C.jsx("h3",{className:"zentara-arm-title",children:"Arm Properties"}),o.length===0?C.jsx("p",{className:"zentara-arm-empty",children:"No properties available to arm."}):C.jsx("ul",{className:"zentara-arm-list",children:o.map(({property:s,tile:a})=>{const r=a.group?Bs[a.group]:"#1e3a5f";return C.jsxs("li",{className:"zentara-arm-row",onClick:()=>n(s.tileId),children:[C.jsx("span",{className:"zentara-arm-row__color",style:{background:r}}),C.jsx("span",{className:"zentara-arm-row__name",children:a.name}),C.jsxs("span",{className:"zentara-arm-row__level",children:["Lv ",s.upgradeLevel," → ",s.upgradeLevel+1]}),C.jsxs("span",{className:"zentara-arm-row__cost",children:["⚡",a.upgradeCost]})]},s.tileId)})}),C.jsx("button",{className:"zentara-arm-close",onClick:g,children:"Close"})]})}),document.body)},vhe={"crimson-dominion":cz,"silver-pact":lz,"azure-sovereignty":Bz,"golden-imperium":Ez,"emerald-collective":Qz,"void-enclave":uz};function Khe({playerId:e,properties:A,tiles:t}){const i=E.useMemo(()=>{const n=[];for(const g of A){if(g.ownerId!==e)continue;const o=t[g.tileId];o!=null&&o.group&&n.push({color:Bs[o.group]??"#1e3a5f",dormant:g.dormant})}return n.sort((g,o)=>g.color.localeCompare(o.color)),n},[e,A,t]);return i.length===0?null:C.jsx("div",{className:"property-dots",children:i.map((n,g)=>C.jsx("span",{className:`property-dot${n.dormant?" property-dot--dormant":""}`,style:{background:n.color}},g))})}function Fhe({track:e,stream:A}){const t=E.useRef(null);return E.useEffect(()=>{const i=t.current;if(i){if(e!=null&&e.attach)return e.attach(i),()=>{e.detach(i)};if(A){i.srcObject!==A&&(i.srcObject=A);let n=0;const g=()=>{i.play().catch(()=>{n<3&&(n++,setTimeout(g,150+n*200))})};g(),i.onloadedmetadata=g;const o=()=>{const a=A.getVideoTracks()[0];a&&a.readyState==="live"&&g()},s=()=>{document.hidden||g()};return i.addEventListener("pause",o),document.addEventListener("visibilitychange",s),()=>{i.removeEventListener("pause",o),document.removeEventListener("visibilitychange",s),i.onloadedmetadata=null,i.srcObject=null}}}},[e,A]),C.jsx("video",{ref:t,autoPlay:!0,playsInline:!0,muted:!0,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",borderRadius:"50%",zIndex:1}})}const HgA={type:"spring",stiffness:420,damping:38,mass:.6},_he=({players:e,properties:A,tiles:t,currentPlayerId:i,localPlayerId:n,onSaveAndExit:g,onAvatarClick:o,roomId:s,onUpgradeProperty:a,upgradeableCount:r})=>{const I=qi(),{user:c}=tn(),{remoteStreams:l,myVideo:B,remoteVideoFlags:Q}=Il(),{onBuyChips:h}=Sw(),d=(()=>{try{return(c==null?void 0:c.isGuest)===!0}catch{return!1}})(),p=E.useRef(null),[y,m]=E.useState(!1),D=e.find(G=>G.id===n);D!=null&&D.depleted||D==null||D.credits;const S=E.useCallback(G=>()=>{try{ti("Light")}catch{}try{}catch{}G()},[]),k=E.useCallback(()=>{if(g){g();return}I(-1)},[g,I]);E.useCallback(()=>{d||h()},[d,h]);const N=E.useMemo(()=>e.map(G=>G.id),[e]);return C.jsxs("div",{className:"card zentara-player-panel zentara-landscape-panel",children:[C.jsx("div",{className:"card-header card-header--two-rows",children:C.jsxs("div",{className:"card-header-row",children:[C.jsx("div",{className:"header-slot header-slot--left",children:C.jsx("a",{className:"gold-link white-link",onClick:S(k),"aria-label":"Back",style:{display:"flex"},children:C.jsx(tc,{className:"icon",style:{color:"var(--gold, #caa64d)"}})})}),C.jsx("div",{className:"header-slot header-slot--center",children:C.jsx("div",{className:"chip-fly-container",children:C.jsx(XI.ul,{className:"players players--avatars",role:"list",ref:p,layout:!0,transition:HgA,children:N.map(G=>{const M=e.find(_=>_.id===G);if(!M)return null;const w=M.depleted?0:M.credits,b=G===i;return C.jsxs(XI.li,{layout:!0,transition:HgA,className:["player","player--avatar",b?"is-rolling":"",G===n?"is-me":""].join(" "),"data-player-id":G,onClick:()=>o==null?void 0:o(G),style:{cursor:"pointer"},children:[C.jsxs("div",{className:`avatar-ring${b?" is-rolling":""}`,style:{position:"relative"},children:[(()=>{const _=G===n?B:l[G];return((Q==null?void 0:Q[G])??!1)&&_?C.jsx(Fhe,{stream:_}):null})(),C.jsx("img",{src:vhe[M.piece],alt:M.piece,className:"zentara-piece-avatar",style:{width:"100%",height:"100%",objectFit:"contain",borderRadius:"50%"}}),C.jsxs("div",{className:"avatar-balance-pill",children:[C.jsx("span",{children:"Power"}),C.jsx("strong",{children:CB.formatMoney(w,"",0)})]})]}),C.jsx(Khe,{playerId:G,properties:A,tiles:t}),G===n&&b&&(r??0)>0&&C.jsx("button",{className:"zentara-arm-btn",onClick:_=>{_.stopPropagation(),m(!0)},title:"Arm properties",children:"🔫"}),C.jsxs("div",{className:"player-mini",children:[C.jsx("div",{className:"player-name",children:C.jsx("span",{className:"player-name__text",children:Xi(M.piece)})}),(M.armorLevel>0||M.weaponLevel>0||M.heroId)&&C.jsxs("div",{className:"zentara-ship-badges",children:[M.heroId&&ms[M.heroId]&&C.jsxs("span",{className:"zentara-ship-badge zentara-ship-badge--hero",title:`${ms[M.heroId].name} (${pQA[ms[M.heroId].tier]})`,children:["🦸",ms[M.heroId].tier]}),M.armorLevel>0&&C.jsxs("span",{className:"zentara-ship-badge zentara-ship-badge--armor",title:`Armor ${M.armorLevel}`,children:["🛡",M.armorLevel]}),M.weaponLevel>0&&C.jsxs("span",{className:"zentara-ship-badge zentara-ship-badge--weapon",title:`Weapons ${M.weaponLevel}`,children:["⚔",M.weaponLevel]})]})]})]},G)})})})}),C.jsx("div",{className:"header-slot header-slot--right"})]})}),y&&a&&C.jsx(AmA,{playerId:n,credits:(D==null?void 0:D.credits)??0,properties:A,board:t,onUpgrade:a,onClose:()=>m(!1)})]})},Jhe=ue.memo(_he),D4=40,emA=50,tmA=50,Cm=44,cm=39.5,Lhe=41.75,nv=3.8,OgA=hB.MINIMAP_STEP_MS,PgA={cursor:"pointer",pointerEvents:"auto"},xhe={"crimson-dominion":"#ff3a3a","silver-pact":"#b0c4de","azure-sovereignty":"#4488ff","golden-imperium":"#ffaa00","emerald-collective":"#39ff14","void-enclave":"#cc44ff"},The={purple:"#7b2ff2",cyan:"#00e5ff",orange:"#ff9100",red:"#ff1744",yellow:"#ffd600",green:"#00e676",blue:"#2979ff",magenta:"#e040fb"};function bk(e,A){const t=A*Math.PI/180;return{x:emA+e*Math.cos(t),y:tmA+e*Math.sin(t)}}function qhe(e,A){const t=Math.min(.55,A*.08),i=e-A/2+t,n=e+A/2-t,g=bk(Cm,i),o=bk(Cm,n),s=bk(cm,n),a=bk(cm,i),r=n-i>180?1:0;return[`M ${g.x.toFixed(3)} ${g.y.toFixed(3)}`,`A ${Cm} ${Cm} 0 ${r} 1 ${o.x.toFixed(3)} ${o.y.toFixed(3)}`,`L ${s.x.toFixed(3)} ${s.y.toFixed(3)}`,`A ${cm} ${cm} 0 ${r} 0 ${a.x.toFixed(3)} ${a.y.toFixed(3)}`,"Z"].join(" ")}function imA(e){const A=360/e;return Array.from({length:e},(t,i)=>{const n=-90+i*A;return{...bk(Lhe,n),angleDeg:n,path:qhe(n,A)}})}const Yhe=imA(D4),Hhe=({players:e,currentPlayerId:A,properties:t=[],tiles:i=[],onTileClick:n})=>{const g=i.length||D4,o=g===D4?Yhe:imA(g),s=E.useMemo(()=>{const B=new Map;for(const Q of t){if(!Q.ownerId)continue;const h=e.find(d=>d.id===Q.ownerId);h&&B.set(Q.tileId,h.pieceColor)}return B},[t,e]),a=E.useMemo(()=>e.filter(B=>!B.depleted),[e]),[r,I]=E.useState(()=>{const B={};for(const Q of e)B[Q.id]=Q.tileIndex;return B}),c=E.useRef({}),l=E.useRef({});return E.useEffect(()=>{const B=new Set(a.map(Q=>Q.id));for(const Q of Object.keys(l.current))B.has(Q)||(clearTimeout(l.current[Q]),delete l.current[Q])},[a]),E.useEffect(()=>{for(const B of a){const Q=B.tileIndex,h=c.current[B.id];if(h===void 0){c.current[B.id]=Q,I(k=>({...k,[B.id]:Q}));continue}if(h===Q)continue;c.current[B.id]=Q,clearTimeout(l.current[B.id]);const d=(Q-h+g)%g,p=d>g/2,y=p?-1:1,m=p?g-d:d;let D=0;const S=()=>{D++,I(k=>{const N=k[B.id]??h;return{...k,[B.id]:(N+y+g)%g}}),D<m&&(l.current[B.id]=setTimeout(S,OgA))};m>0&&(l.current[B.id]=setTimeout(S,OgA))}},[a]),E.useEffect(()=>()=>{for(const B of Object.values(l.current))clearTimeout(B)},[]),C.jsxs("svg",{viewBox:"0 0 100 100",className:"zentara-minimap","aria-label":"Board minimap",children:[C.jsx("circle",{cx:emA,cy:tmA,r:(Cm+cm)/2,fill:"none",stroke:"rgba(0,229,255,0.18)",strokeWidth:Cm-cm+1.2,opacity:.52}),o.map((B,Q)=>{const h=i[Q],p=(h!=null&&h.group?The[h.group]:void 0)??"rgba(86, 98, 116, 0.92)",y=s.get(Q);return C.jsx("path",{d:B.path,fill:y??p,stroke:y?"rgba(255,255,255,0.88)":"rgba(2,8,18,0.9)",strokeWidth:y?.52:.38,opacity:y?1:.94,style:n?PgA:void 0,onClick:n?()=>n(Q):void 0},Q)}),a.map(B=>{const Q=r[B.id]??B.tileIndex,h=o[Q];if(!h)return null;const d=B.id===A;return C.jsx("rect",{x:h.x-nv/2,y:h.y-nv/2,width:nv,height:nv,rx:.8,fill:xhe[B.piece]??B.pieceColor,stroke:d?"#eaffff":"rgba(0,0,0,0.76)",strokeWidth:d?1.8:1,opacity:1,transform:`rotate(${h.angleDeg+45} ${h.x} ${h.y})`,className:d?"zentara-minimap-current-player":void 0,filter:d?"drop-shadow(0 0 3px rgba(0,229,255,0.8))":"drop-shadow(0 0 2px rgba(0,0,0,0.6))",style:n?PgA:void 0,onClick:n?()=>n(B.tileIndex):void 0},B.id)})]})},Ohe=ue.memo(Hhe),Phe=({localPlayer:e,otherPlayers:A,properties:t,tiles:i,onPropose:n,onClose:g})=>{var N,G;const[o,s]=E.useState(((N=A[0])==null?void 0:N.id)??""),[a,r]=E.useState([]),[I,c]=E.useState(0),[l,B]=E.useState([]),[Q,h]=E.useState(0),d=E.useMemo(()=>t.filter(M=>M.ownerId===e.id&&M.upgradeLevel===0),[t,e.id]),p=E.useMemo(()=>t.filter(M=>M.ownerId===o&&M.upgradeLevel===0),[t,o]),y=(M,w,b)=>w(_=>_.includes(b)?_.filter(K=>K!==b):[..._,b]),m=M=>{var w;return((w=i[M])==null?void 0:w.name)??`#${M}`},D=M=>{var w;return(w=i[M])==null?void 0:w.group},S=o&&(a.length>0||I>0||l.length>0||Q>0),k=M=>{s(M),B([]),h(0)};return C.jsxs(C.Fragment,{children:[C.jsx("h3",{className:"zentara-trade-card__title",children:"Propose Trade"}),C.jsx("div",{className:"zentara-trade-card__section-title",children:"Trade With"}),C.jsx("div",{className:"zentara-trade-card__chip-row",children:A.map(M=>C.jsxs("button",{onClick:()=>k(M.id),className:"zentara-trade-chip",style:{background:o===M.id?"#1e3a5f":"transparent",color:o===M.id?"#fff":"#6b7fa3"},children:[Xi(M.piece)," (",M.credits,"cr)"]},M.id))}),C.jsx("div",{className:"zentara-trade-card__section-title",children:"You Give"}),d.length===0?C.jsx("div",{className:"zentara-trade-card__empty",children:"No properties to offer"}):C.jsx("div",{className:"zentara-trade-card__chip-row zentara-trade-card__chip-row--tight",children:d.map(M=>{const w=a.includes(M.tileId),b=D(M.tileId);return C.jsx("button",{onClick:()=>y(a,r,M.tileId),className:"zentara-trade-chip",style:{background:w?b?Bs[b]:"#1e3a5f":"transparent",color:w?"#fff":"#c0d0e8",borderColor:b?Bs[b]:"#1e3a5f",opacity:M.dormant?.4:1},children:m(M.tileId)},M.tileId)})}),C.jsxs("div",{className:"zentara-trade-card__credits-row",children:[C.jsx("label",{className:"zentara-trade-card__credits-label",children:"Credits:"}),C.jsx("input",{type:"range",min:0,max:e.credits,value:I,onChange:M=>c(Number(M.target.value)),className:"zentara-trade-card__credits-slider"}),C.jsx("span",{className:"zentara-trade-card__credits-value",children:I})]}),C.jsx("div",{className:"zentara-trade-card__section-title",children:"You Receive"}),p.length===0?C.jsx("div",{className:"zentara-trade-card__empty",children:"They have no properties"}):C.jsx("div",{className:"zentara-trade-card__chip-row zentara-trade-card__chip-row--tight",children:p.map(M=>{const w=l.includes(M.tileId),b=D(M.tileId);return C.jsx("button",{onClick:()=>y(l,B,M.tileId),className:"zentara-trade-chip",style:{background:w?b?Bs[b]:"#1e3a5f":"transparent",color:w?"#fff":"#c0d0e8",borderColor:b?Bs[b]:"#1e3a5f",opacity:M.dormant?.4:1},children:m(M.tileId)},M.tileId)})}),C.jsxs("div",{className:"zentara-trade-card__credits-row",children:[C.jsx("label",{className:"zentara-trade-card__credits-label",children:"Credits:"}),C.jsx("input",{type:"range",min:0,max:((G=A.find(M=>M.id===o))==null?void 0:G.credits)??0,value:Q,onChange:M=>h(Number(M.target.value)),className:"zentara-trade-card__credits-slider"}),C.jsx("span",{className:"zentara-trade-card__credits-value",children:Q})]}),C.jsxs("div",{className:"zentara-trade-card__btn-row",children:[C.jsx("button",{onClick:g,className:"zentara-trade-btn zentara-trade-btn--cancel",children:"Cancel"}),C.jsx("button",{disabled:!S,onClick:()=>S&&n(o,a,I,l,Q),className:"zentara-trade-btn zentara-trade-btn--propose",children:"Send Offer"})]})]})},jhe=({trade:e,players:A,tiles:t,onAccept:i,onDecline:n})=>{const g=(()=>{const r=A.find(I=>I.id===e.offerer.playerId);return r?Xi(r.piece):"Unknown Fleet"})(),o=r=>{var I;return((I=t[r])==null?void 0:I.name)??`#${r}`},s=r=>{var I;return(I=t[r])==null?void 0:I.group},a=({propIds:r})=>C.jsx("div",{className:"zentara-trade-card__chip-row zentara-trade-card__chip-row--tight",style:{marginTop:4},children:r.map(I=>{const c=s(I);return C.jsx("span",{className:"zentara-trade-chip zentara-trade-chip--default",style:{background:c?Bs[c]:"#1e3a5f",color:"#fff"},children:o(I)},I)})});return C.jsxs(C.Fragment,{children:[C.jsxs("h3",{className:"zentara-trade-card__title",children:["Trade Offer from ",g]}),C.jsx("div",{className:"zentara-trade-card__section-title",children:"They Give"}),e.offerer.propertyIds.length>0&&C.jsx(a,{propIds:e.offerer.propertyIds}),e.offerer.credits>0&&C.jsxs("div",{className:"zentara-trade-card__credits-info",children:["+",e.offerer.credits," credits"]}),e.offerer.propertyIds.length===0&&e.offerer.credits===0&&C.jsx("div",{className:"zentara-trade-card__nothing",children:"Nothing"}),C.jsx("div",{className:"zentara-trade-card__section-title",children:"You Give"}),e.recipient.propertyIds.length>0&&C.jsx(a,{propIds:e.recipient.propertyIds}),e.recipient.credits>0&&C.jsxs("div",{className:"zentara-trade-card__credits-info",children:["+",e.recipient.credits," credits"]}),e.recipient.propertyIds.length===0&&e.recipient.credits===0&&C.jsx("div",{className:"zentara-trade-card__nothing",children:"Nothing"}),C.jsxs("div",{className:"zentara-trade-card__btn-row",children:[C.jsx("button",{onClick:n,className:"zentara-trade-btn zentara-trade-btn--decline",children:"Decline"}),C.jsx("button",{onClick:i,className:"zentara-trade-btn zentara-trade-btn--accept",children:"Accept"})]})]})},zhe=({open:e,mode:A,localPlayer:t,players:i,properties:n,tiles:g,pendingTrade:o,onPropose:s,onAccept:a,onDecline:r,onClose:I})=>{if(!e)return null;const c=i.filter(l=>l.id!==t.id&&!l.depleted);return C.jsx("div",{className:"zentara-trade-overlay",onClick:I,children:C.jsx("div",{className:"zentara-trade-card",onClick:l=>l.stopPropagation(),children:A==="propose"?C.jsx(Phe,{localPlayer:t,otherPlayers:c,properties:n,tiles:g,onPropose:s,onClose:I}):o?C.jsx(jhe,{trade:o,players:i,tiles:g,onAccept:a,onDecline:r}):null})})},Zhe=ue.memo(zhe),Whe=({players:e,properties:A,tiles:t,currentPlayerId:i,open:n,onClose:g})=>C.jsxs(C.Fragment,{children:[n&&C.jsx("div",{onClick:g,className:"zentara-drawer-backdrop"}),C.jsxs("div",{className:`zentara-drawer${n?" zentara-drawer--open":""}`,children:[C.jsxs("div",{className:"zentara-drawer__header",children:[C.jsx("h3",{className:"zentara-drawer__title",children:"Players"}),C.jsx("button",{onClick:g,className:"zentara-drawer__close",children:"✕"})]}),e.map(o=>{const s=A.filter(I=>I.ownerId===o.id).sort((I,c)=>{var l,B;return(((l=t[I.tileId])==null?void 0:l.group)??"").localeCompare(((B=t[c.tileId])==null?void 0:B.group)??"")}),a=o.maxHp>0?Math.round(o.hp/o.maxHp*100):0,r=o.hp>o.maxHp*.6?"#00e676":o.hp>o.maxHp*.25?"#ffab00":"#ff1744";return C.jsxs("div",{className:`zentara-drawer__player${o.depleted?" zentara-drawer__player--bankrupt":""}`,children:[C.jsxs("div",{className:"zentara-drawer__player-row",children:[C.jsx("span",{className:"zentara-drawer__color-swatch",style:{background:o.pieceColor,boxShadow:o.id===i?`0 0 6px ${o.pieceColor}`:"none"}}),C.jsx("strong",{className:"zentara-drawer__player-name",children:Xi(o.piece)}),o.depleted&&C.jsx("span",{className:"zentara-drawer__status--destroyed",children:"(Destroyed)"}),o.inJail&&C.jsx("span",{className:"zentara-drawer__status--detained",children:"(Cryosleep)"})]}),C.jsxs("div",{className:"zentara-drawer__credits",children:["Credits: ",C.jsx("strong",{children:o.credits})]}),C.jsxs("div",{className:"zentara-drawer__hp-track",children:[C.jsx("div",{className:"zentara-drawer__hp-fill",style:{width:`${a}%`,background:r,boxShadow:`0 0 6px ${r}`}}),C.jsxs("span",{className:"zentara-drawer__hp-label",children:["♥ ",o.hp,"/",o.maxHp]})]}),s.length>0&&C.jsx("div",{className:"zentara-drawer__props",children:s.map(I=>{const c=t[I.tileId],l=c!=null&&c.group?Bs[c.group]:"#1e3a5f";return C.jsx("span",{className:"zentara-drawer__prop-chip",style:{background:l,opacity:I.dormant?.4:1},children:(c==null?void 0:c.name)??`#${I.tileId}`},I.tileId)})})]},o.id)})]})]}),Vhe=ue.memo(Whe),Xhe=({open:e,onClose:A,roomId:t,localPlayerId:i,players:n,injectedMessages:g,onLocalSend:o})=>{const s=OR(),[a,r]=E.useState([]),[I,c]=E.useState(""),l=E.useRef(null),B=E.useRef(null),Q=!!t,h=E.useMemo(()=>{if(Q)return s.getRoomMessages(t);if(!g||g.length===0)return a;const D=new Map;for(const S of a)D.set(S.id,S);for(const S of g)D.has(S.id)||D.set(S.id,S);return Array.from(D.values()).sort((S,k)=>S.ts-k.ts||S.id.localeCompare(k.id))},[Q,s,t,a,g]);E.useEffect(()=>{e&&l.current&&(l.current.scrollTop=l.current.scrollHeight)},[e,h.length]),E.useEffect(()=>{e&&setTimeout(()=>{var D;return(D=B.current)==null?void 0:D.focus()},350)},[e]);const d=E.useCallback(D=>{const S=n.find(k=>k.id===D);return S?Xi(S.piece):"Unknown"},[n]),p=E.useCallback(D=>{const S=n.find(k=>k.id===D);return(S==null?void 0:S.pieceColor)??"#6b7fa3"},[n]),y=E.useCallback(()=>{const D=I.trim();if(D){if(Q)s.sendRoomMessage(t,D);else{const S={id:`local-${Date.now()}-${Math.random()}`,ts:Date.now(),senderId:i,text:D,roomId:"local"};r(k=>[...k,S]);try{o==null||o(S)}catch{}}c("")}},[I,Q,t,s,i,o]),m=E.useCallback(D=>{D.key==="Enter"&&!D.shiftKey&&(D.preventDefault(),y())},[y]);return C.jsxs(C.Fragment,{children:[e&&C.jsx("div",{onClick:A,className:"zentara-drawer-backdrop"}),C.jsxs("div",{className:`zentara-chat-drawer${e?" zentara-chat-drawer--open":""}`,children:[C.jsxs("div",{className:"zentara-drawer__header",children:[C.jsx("h3",{className:"zentara-drawer__title",children:"Chat"}),C.jsx("button",{onClick:A,className:"zentara-drawer__close",children:"✕"})]}),C.jsxs("div",{className:"zentara-chat-messages",ref:l,children:[h.length===0&&C.jsx("p",{className:"zentara-chat-empty",children:"No messages yet. Say something!"}),h.map(D=>{const S=D.senderId===i;return C.jsxs("div",{className:`zentara-chat-bubble${S?" zentara-chat-bubble--me":""}`,children:[!S&&C.jsx("span",{className:"zentara-chat-sender",style:{color:p(D.senderId)},children:d(D.senderId)}),C.jsx("span",{className:"zentara-chat-text",children:D.text}),D.pending&&C.jsx("span",{className:"zentara-chat-pending",children:"…"})]},D.id)})]}),C.jsxs("div",{className:"zentara-chat-input-row",children:[C.jsx("input",{ref:B,type:"text",className:"zentara-chat-input",placeholder:"Type a message…",value:I,onChange:D=>c(D.target.value),onKeyDown:m,maxLength:200}),C.jsx("button",{className:"zentara-btn zentara-btn--primary zentara-chat-send",onClick:y,disabled:!I.trim(),children:"Send"})]})]})]})},$he=ue.memo(Xhe),Ape=4500,epe=({latest:e,players:A,onOpen:t,hidden:i})=>{const[n,g]=E.useState(null);if(E.useEffect(()=>{if(!e||i)return;g(e);const r=setTimeout(()=>g(null),Ape);return()=>clearTimeout(r)},[e,i]),!n||i)return null;const o=A.find(r=>r.id===n.senderId),s=o?Xi(o.piece):"Bot",a=(o==null?void 0:o.pieceColor)??"#6b7fa3";return C.jsxs("div",{role:"button","aria-label":"Open chat",onClick:t,style:{position:"fixed",top:14,left:"50%",transform:"translateX(-50%)",zIndex:10010,maxWidth:"88vw",minWidth:220,background:"rgba(8,14,32,0.92)",color:"#e8efff",padding:"10px 14px",borderRadius:14,border:`1px solid ${a}`,boxShadow:"0 8px 24px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.05) inset",fontFamily:"system-ui, sans-serif",fontSize:14,lineHeight:1.3,cursor:"pointer",animation:"zentara-chat-toast-in 220ms ease-out",pointerEvents:"auto"},children:[C.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[C.jsx("span",{style:{color:a,fontWeight:700,fontSize:12,letterSpacing:.3},children:s}),C.jsx("span",{style:{opacity:.5,fontSize:11},children:"· tap to open chat"})]}),C.jsx("div",{style:{marginTop:2},children:n.text}),C.jsx("style",{children:`
                @keyframes zentara-chat-toast-in {
                    from { opacity: 0; transform: translate(-50%, -8px); }
                    to   { opacity: 1; transform: translate(-50%, 0); }
                }
            `})]})},tpe=15e3,ipe=5e3,npe=22e3,gpe=8e3,jgA=7e3,ope=900,spe=700,ape=700,rpe=900,LK=globalThis.__zentaraActiveBotChatSessions||new Set;globalThis.__zentaraActiveBotChatSessions=LK;const Po=(...e)=>{console.log("[autoplay-bot-chat]",...e)},Ipe=[/\b(stop|quit|enough|no more)\s+(chat|chatting|talking|messaging)/i,/\b(shut\s*up|be\s*quiet|leave\s+me\s+alone|don'?t\s+(chat|talk|message))\b/i,/\bno\s+(chat|chit-?chat|talking)\b/i,/\bplease\s+stop\b/i];function Cpe(e){return Ipe.some(A=>A.test(e))}function cpe({enabled:e,gameMode:A,bots:t,localPlayerId:i,requireHumanEngagement:n=!0,getSituation:g,onMessage:o,getHistory:s,controlsRef:a}){const r=E.useRef(o),I=E.useRef(g),c=E.useRef(s),l=E.useRef(i);r.current=o,I.current=g,c.current=s,l.current=i;const B=E.useRef(a);B.current=a,E.useEffect(()=>{if(!e||t.length===0){Po("skip mount",{enabled:e,botCount:t.length});return}const Q=[A,n?"quickmatch":"autoplay",...t.map(K=>K.id).sort()].join(":");if(LK.has(Q)){Po("skip duplicate session",{sessionKey:Q});return}LK.add(Q),Po("mount",{enabled:e,gameMode:A,bots:t.map(K=>K.name),mode:n?"quickmatch":"autoplay"});let h=!1,d=null;const p=new Set,y=Ca(),m=()=>{LK.delete(Q)};if(!n){const K=dpe({apiBase:y,gameMode:A,bots:t,onMessageRef:r,getSituationRef:I,getHistoryRef:c,isCancelled:()=>h,scheduleNext:q=>{h||(d=setTimeout(K,q))}}),J=1500+Math.random()*1e3;return Po(`[autoplay] first tick in ${Math.round(J)}ms`),d=setTimeout(K,J),()=>{h=!0,d&&clearTimeout(d);for(const q of p)clearTimeout(q);p.clear(),m(),Po("unmount (autoplay)")}}let D=0,S=!1,k=!1;const N=[...t].sort(()=>Math.random()-.5),G=()=>{var q;if(k)return!0;const K=((q=c.current)==null?void 0:q.call(c))??[],J=l.current;return J&&K.some(v=>v.senderId===J&&Cpe(v.text))?(k=!0,Po("human asked bots to stop — silencing chat"),!0):!1},M=async(K,J,q,v,U)=>{var Z,eA;if(h||G())return;if(S){Po(`[${K}] suppressed - request already in flight`);return}const x=Date.now();if(U&&x-D<jgA){Po(`[${K}] suppressed — within ${jgA}ms of previous line`);return}D=x;const T=(Z=c.current)==null?void 0:Z.call(c);Po(`[${K}] POST /api/bot-chat/one-liner`,{gameMode:A,style:J,speakerId:q,bots:t.length,situation:v,historyLen:(T==null?void 0:T.length)??0});const z=performance.now();S=!0;try{const aA=await fetch(`${y}/api/bot-chat/one-liner`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({gameMode:A,style:J,speakerId:q,bots:t,situation:v,history:T})});if(h)return;const sA=Math.round(performance.now()-z);if(!aA.ok){Po(`[${K}] ✗ HTTP ${aA.status} in ${sA}ms`);return}const pA=await aA.json();if(h)return;if(pA!=null&&pA.ok&&((eA=pA.message)!=null&&eA.text)){const gA=pA.message;Po(`[${K}] ✓ message in ${sA}ms`,{senderId:gA.senderId,text:gA.text,fallback:!!pA.fallback}),r.current({id:gA.id,senderId:gA.senderId,text:gA.text,ts:gA.ts,roomId:"autoplay"})}else Po(`[${K}] ∅ no message in ${sA}ms`,{reason:pA==null?void 0:pA.reason})}catch(aA){Po(`[${K}] ✗ network error`,aA)}finally{S=!1}},w=async()=>{if(h||G())return;const K=N.shift();if(!K){Po("intro round complete — switching to event-driven mode");return}if(await M("intro","intro",K.id,void 0,!1),h||N.length===0)return;const J=npe+Math.random()*gpe;Po(`next intro in ${Math.round(J/1e3)}s (${N.length} remaining)`),d=setTimeout(w,J)},b=tpe+Math.random()*ipe;Po(`first intro in ${Math.round(b/1e3)}s`),d=setTimeout(w,b);const _={notifyGameEvent:K=>{if(h||G())return;const J=ope+Math.random()*spe,q=setTimeout(()=>{p.delete(q),M("event","game",void 0,K,!0)},J);p.add(q)},notifyHumanMessage:K=>{if(h||G())return;const J=ape+Math.random()*rpe,q=setTimeout(()=>{p.delete(q),M("human-reply","converse",void 0,void 0,!1)},J);p.add(q)}};return B.current&&(B.current.current=_),()=>{h=!0,d&&clearTimeout(d);for(const K of p)clearTimeout(K);p.clear(),B.current&&B.current.current===_&&(B.current.current=null),m(),Po("unmount (quickmatch)")}},[e,A,n,JSON.stringify(t.map(Q=>Q.id))])}const lpe=12e3,Bpe=8e3,Epe=15e3,Qpe=12e3;function upe(e,A){var i;const t=e.toLowerCase();for(const n of A){const g=(i=(n.name||"").split(/\s+/)[0])==null?void 0:i.toLowerCase();if(!g)continue;if(new RegExp(`(^|[^a-z0-9])@?${g}\\b`,"i").test(t))return n}return null}function dpe(e){const{apiBase:A,gameMode:t,bots:i,onMessageRef:n,getSituationRef:g,getHistoryRef:o,isCancelled:s,scheduleNext:a}=e;let r=0,I=0,c;const l=[...i].sort(()=>Math.random()-.5),B=.55,Q=.15,h=.25,d=()=>{const m=Math.random();return m<B?"converse":m<B+Q?"game":m<B+Q+h?"smalltalk":"trending"},p=m=>{const D=m[m.length-1];if(D){const N=upe(D.text,i);if(N&&N.id!==D.senderId)return N}const S=i.filter(N=>N.id!==c),k=S.length>0?S:i;return k[Math.floor(Math.random()*k.length)]};return async()=>{var G,M,w,b;if(s())return;r+=1;const m=r;let D,S;if(l.length>0){const _=l.shift();D="intro",S=_.id,c=_.id}else{const _=((G=o.current)==null?void 0:G.call(o))??[],K=p(_);S=K.id,c=K.id,D=d()}const k=(M=o.current)==null?void 0:M.call(o),N=D==="converse"||D==="game"?(w=g.current)==null?void 0:w.call(g):void 0;Po(`[autoplay] tick ${m} → ${D} (speaker=${S})`);try{const _=await fetch(`${A}/api/bot-chat/one-liner`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({gameMode:t,style:D,speakerId:S,bots:i,situation:N,history:k})});if(s())return;if(_.ok){const K=await _.json();if(K!=null&&K.ok&&((b=K.message)!=null&&b.text)){const J=K.message;Po(`[autoplay] tick ${m} ✓`,{senderId:J.senderId,text:J.text,fallback:!!K.fallback}),n.current({id:J.id,senderId:J.senderId,text:J.text,ts:J.ts,roomId:"autoplay"}),I+=1}else Po(`[autoplay] tick ${m} ∅`,{reason:K==null?void 0:K.reason})}}catch(_){Po(`[autoplay] tick ${m} ✗ network error`,_)}finally{if(!s()){const _=l.length>0?lpe+Math.random()*Bpe:Epe+Math.random()*Qpe;a(_)}}}}const hpe={"crimson-dominion":cz,"silver-pact":lz,"azure-sovereignty":Bz,"golden-imperium":Ez,"emerald-collective":Qz,"void-enclave":uz},ppe=({player:e,properties:A,tiles:t,isCurrentPlayer:i,onClose:n,onTileClick:g})=>{var s;if(!e)return null;const o=A.filter(a=>a.ownerId===e.id).sort((a,r)=>{var I,c;return(((I=t[a.tileId])==null?void 0:I.group)??"").localeCompare(((c=t[r.tileId])==null?void 0:c.group)??"")});return C.jsx("div",{className:"zentara-pinfo-overlay",onClick:n,children:C.jsxs("div",{className:"zentara-pinfo-card",onClick:a=>a.stopPropagation(),children:[C.jsxs("div",{className:"zentara-pinfo__header",children:[C.jsx("div",{className:"zentara-pinfo__avatar",style:{border:`2px solid ${e.pieceColor}`,boxShadow:i?`0 0 10px ${e.pieceColor}`:"none",background:e.pieceColor+"22"},children:C.jsx("img",{src:hpe[e.piece],alt:e.piece,className:"zentara-pinfo__avatar-img"})}),C.jsxs("div",{children:[C.jsx("h3",{className:"zentara-pinfo__name",children:Xi(e.piece)}),C.jsxs("div",{className:"zentara-pinfo__badges",children:[i&&C.jsx("span",{className:"zentara-pinfo__badge zentara-pinfo__badge--current",children:"Current Turn"}),e.depleted&&C.jsx("span",{className:"zentara-pinfo__badge zentara-pinfo__badge--destroyed",children:"Destroyed"}),e.inJail&&C.jsx("span",{className:"zentara-pinfo__badge zentara-pinfo__badge--detained",children:"In Cryosleep"})]})]})]}),gB[e.piece]&&C.jsxs("div",{className:"zentara-pinfo__lore",children:[C.jsx("div",{className:"zentara-pinfo__lore-name",children:gB[e.piece].name}),C.jsxs("div",{className:"zentara-pinfo__lore-motto",children:['"',gB[e.piece].motto,'"']}),C.jsx("p",{className:"zentara-pinfo__lore-text",children:gB[e.piece].lore})]}),C.jsxs("div",{className:"zentara-pinfo__credits",children:["Credits: ",C.jsx("strong",{children:e.credits})]}),C.jsxs("div",{className:"zentara-pinfo__position",children:["Position: ",((s=t[e.tileIndex])==null?void 0:s.name)??`Tile ${e.tileIndex}`]}),o.length>0&&C.jsxs("div",{className:"zentara-pinfo__colonies",children:[C.jsxs("div",{className:"zentara-pinfo__colonies-label",children:["Colonies (",o.length,")"]}),C.jsx("div",{className:"zentara-pinfo__colony-list",children:o.map(a=>{const r=t[a.tileId],I=r!=null&&r.group?Bs[r.group]:"#1e3a5f";return C.jsxs("span",{className:"zentara-pinfo__colony-chip",onClick:()=>g==null?void 0:g(a.tileId),style:{background:I,opacity:a.dormant?.4:1,cursor:g?"pointer":void 0},children:[(r==null?void 0:r.name)??`#${a.tileId}`,a.upgradeLevel>0&&` ★${a.upgradeLevel}`]},a.tileId)})})]}),o.length===0&&C.jsx("div",{className:"zentara-pinfo__no-colonies",children:"No colonies captured"}),C.jsx("button",{onClick:n,className:"zentara-pinfo__close-btn",children:"Close"})]})})},fpe=ue.memo(ppe);function ype(e,A){const t=E.useRef(0);return E.useCallback((...i)=>{const n=Date.now();n-t.current>=A&&(t.current=n,e(...i))},[e,A])}const Dpe=["/videos/space-conquest-1.mp4","/videos/space-conquest-2.mp4","/videos/zentara_game_intro.mp4","/videos/planet-capture.mp4","/videos/team-destroyed-1.mp4","/videos/team-destroyed-2.mp4","/videos/team-destroyed-3.mp4","/videos/fleet-ambush.mp4","/videos/empire-strike.mp4","/videos/broadside-salvo.mp4","/videos/jail-detention.mp4"],mpe={"/videos/zentara_game_intro.mp4":"/videos/zentara_game_intro.mp4","/videos/capture-planet.mp4":"/videos/planet-capture.mp4","/videos/resource-strike.mp4":"/videos/empire-strike.mp4","/videos/board-movement.mp4":"/videos/space-conquest-2.mp4","/videos/social-friends.mp4":"/videos/space-conquest-2.mp4","/videos/social.mp4":"/videos/space-conquest-2.mp4","/videos/trade.mp4":"/videos/space-conquest-2.mp4"};let m4=!1;const S4=new Map,xK=new Set,zgA=new Set;let TK=0;async function Spe(e){if(!(S4.has(e)||xK.has(e))){xK.add(e);try{const A=await fetch(e,{cache:"force-cache"});if(!A.ok)return;const t=await A.blob(),i=URL.createObjectURL(t);S4.set(e,i)}catch{}finally{xK.delete(e)}}}function nmA(e){return mpe[e]??e}function wpe(e){const A=nmA(e);return S4.get(A)??A}function ZgA(e){const A=nmA(e);zgA.has(A)||(zgA.add(A),TK+=1,Spe(A).finally(()=>{TK=Math.max(0,TK-1)}))}function WgA(){return TK===0&&xK.size===0}async function kpe(e=5e3){return!m4||WgA()?!0:new Promise(A=>{const t=Date.now(),i=window.setInterval(()=>{if(WgA()){window.clearInterval(i),A(!0);return}Date.now()-t>=Math.max(250,e)&&(window.clearInterval(i),A(!1))},50)})}function Mpe(e=[]){if(!(Ui.isNativePlatform()&&Ui.getPlatform()==="ios")){if(!m4){m4=!0;let A=0;for(const t of Dpe)window.setTimeout(()=>{ZgA(t)},A*50),A+=1}for(const A of e)queueMicrotask(()=>{ZgA(A)})}}const Npe=2,Rpe=2500,Gpe=({src:e,onEnd:A,coatOfArms:t,caption:i})=>{const n=E.useMemo(()=>{try{return Ui.getPlatform()}catch{return"web"}},[]),g=E.useRef(Ui.isNativePlatform()).current,o=g&&n==="ios",s=E.useMemo(()=>wpe(e),[e]),a=E.useRef(!1),[r,I]=E.useState(!1),c=E.useRef(null),[l,B]=E.useState("loading"),Q=E.useRef(l);Q.current=l,E.useEffect(()=>{a.current=!1,I(!1),B("loading")},[e]);const h=E.useRef(A);h.current=A;const d=E.useCallback(()=>{a.current||(a.current=!0,h.current())},[]);E.useEffect(()=>{if(l==="failed"){const D=setTimeout(()=>I(!0),400),S=setTimeout(d,Rpe);return()=>{clearTimeout(D),clearTimeout(S)}}if(l==="loading"){const D=c.current;if(!D)return;let S=!1,k=0;const G=setTimeout(()=>{S||Q.current!=="loading"||(console.warn("[ZENTARA] Cutscene load timeout, falling back",{src:e}),B("failed"))},o?7e3:3500),M=()=>{S||Q.current!=="loading"||D.play().then(()=>{},()=>{S||Q.current!=="loading"||(k<3?(k++,setTimeout(M,300*k)):B("failed"))})};try{D.pause(),D.currentTime=0,g&&D.load()}catch{}if(D.readyState<2){const w=()=>{D.removeEventListener("canplay",w),M()};return D.addEventListener("canplay",w),setTimeout(M,100),()=>{S=!0,clearTimeout(G),D.removeEventListener("canplay",w)}}return M(),()=>{S=!0,clearTimeout(G)}}if(l==="playing"){const D=c.current,S=D==null?void 0:D.duration,N=(typeof S=="number"&&Number.isFinite(S)&&S>0?S:4)*1e3,G=setTimeout(d,Math.min(N+1e3,12e3)),M=setTimeout(()=>I(!0),Math.max(0,N-2e3));let w=(D==null?void 0:D.currentTime)??0,b=0;const _=setInterval(()=>{const K=c.current;if(!K||K.ended||K.paused){clearInterval(_);return}K.currentTime===w?(b++,b>=2&&(console.warn("[ZENTARA] Cutscene stalled, force-dismissing"),clearInterval(_),d())):(b=0,w=K.currentTime)},2e3);return()=>{clearTimeout(G),clearTimeout(M),clearInterval(_)}}},[l,d,g,o,e]),E.useEffect(()=>{if(l==="failed")return;const D=()=>{if(document.hidden)return;const S=c.current;if(!(!S||S.ended)&&S.paused){let k=0;const N=()=>{S.play().catch(()=>{k<2?(k++,setTimeout(N,300)):(console.warn("[ZENTARA] Failed to resume video on foreground"),d())})};N()}};return document.addEventListener("visibilitychange",D),()=>document.removeEventListener("visibilitychange",D)},[l,d]);const p=E.useCallback(()=>{const D=c.current;!D||!t||r||D.duration&&D.currentTime>=D.duration-Npe&&I(!0)},[t,r]),y=ype(p,200);if(l==="failed")return C.jsxs("div",{className:"zentara-cutscene-overlay",children:[C.jsx("div",{className:"zentara-cutscene-flash"}),C.jsx("div",{className:"zentara-cutscene-ring"}),t&&r&&C.jsx("img",{src:t,alt:"",className:"zentara-cutscene-emblem"}),i&&C.jsx("div",{className:"zentara-cutscene-caption",children:i})]});const m=l==="playing";return C.jsxs("div",{className:"zentara-cutscene-overlay",children:[C.jsx("video",{ref:c,src:s,autoPlay:!0,muted:!0,playsInline:!0,preload:"auto",onEnded:d,onError:()=>B("failed"),onCanPlay:()=>{var D;(D=c.current)==null||D.play().catch(()=>{})},onPlaying:()=>{l==="loading"&&B("playing")},onTimeUpdate:y,className:"zentara-cutscene-video",style:m?void 0:{opacity:0}},s),t&&r&&C.jsx("img",{src:t,alt:"",className:"zentara-cutscene-emblem"}),i&&C.jsx("div",{className:"zentara-cutscene-caption",children:i})]})},MV={"crimson-dominion":{pack:"CosmicShark",skinColor:"Red",accentColor:"#ff3344",emissionSuffix:"Emission",tierVariants:{1:"02",2:"06",3:"10",4:"13",5:"14",6:"16"}},"silver-pact":{pack:"CosmicShark",skinColor:"White",accentColor:"#c0d8ff",emissionSuffix:"Emission",tierVariants:{1:"02",2:"06",3:"10",4:"13",5:"14",6:"16"}},"azure-sovereignty":{pack:"CosmicShark",skinColor:"Blue",accentColor:"#3399ff",emissionSuffix:"Emission",tierVariants:{1:"02",2:"06",3:"10",4:"13",5:"14",6:"16"}},"golden-imperium":{pack:"CosmicShark",skinColor:"Yellow",accentColor:"#ffcc33",emissionSuffix:"Emission",tierVariants:{1:"02",2:"06",3:"10",4:"13",5:"14",6:"16"}},"emerald-collective":{pack:"CosmicShark",skinColor:"Green",accentColor:"#33ff88",emissionSuffix:"Emission",tierVariants:{1:"02",2:"06",3:"10",4:"13",5:"14",6:"16"}},"void-enclave":{pack:"CosmicShark",skinColor:"Purple",accentColor:"#aa55ff",emissionSuffix:"Emission",tierVariants:{1:"02",2:"06",3:"10",4:"13",5:"14",6:"16"}}},NV="/models/zentara/ships",bpe=`${NV}/CosmicShark`,Upe={"crimson-dominion":"18","silver-pact":"16","azure-sovereignty":"02","golden-imperium":"01","emerald-collective":"06","void-enclave":"17"};function gmA(e,A){const t=MV[e],i=t.tierVariants[A];return`${NV}/${t.pack}/${t.pack}${i}.glb`}function vpe(e){return`${bpe}/CosmicShark${Upe[e]}.obj`}function omA(e,A){const t=MV[e],i=`${NV}/${t.pack}/Textures/${t.pack}`;return{diffuse:`${i}_${t.skinColor}.webp`,normal:`${i}_Normal.webp`,metallic:`${i}_Metallic.webp`,roughness:`${i}_Roughness.webp`,emission:`${i}_${t.emissionSuffix}.webp`}}const smA={"spy-plant":4300,"hero-clash":4700,wormhole:4200,"raid-victory":4400},dT="#41d8ff";function Kpe(e){return e*e*(3-2*e)}function Fpe(e){return Math.max(0,Math.min(1,e))}function w4(e,A=dT){return e!=null&&e.pieceColor&&/^#[0-9a-f]{3,8}$/i.test(e.pieceColor)?e.pieceColor:A}function _pe(e){var A;return(e.heroId?(A=ms[e.heroId])==null?void 0:A.tier:void 0)??1}function Jpe(){const e=E.useRef(null),A=E.useMemo(()=>{const i=new Float32Array(2280);let n=13933;const g=()=>(n=n*16807%2147483647,(n-1)/2147483646);for(let s=0;s<760;s+=1)i[s*3]=(g()-.5)*54,i[s*3+1]=(g()-.5)*28,i[s*3+2]=-g()*55+10;const o=new Ni;return o.setAttribute("position",new ji(i,3)),o},[]);return E.useEffect(()=>()=>A.dispose(),[A]),Ba((t,i)=>{e.current&&(e.current.position.z+=i*1.2,e.current.position.z>10&&(e.current.position.z=0))}),C.jsx("points",{ref:e,geometry:A,children:C.jsx("pointsMaterial",{color:"#d9f6ff",size:.055,transparent:!0,opacity:.82,sizeAttenuation:!0})})}function Lpe({color:e=dT}){return C.jsx("group",{children:C.jsx("pointLight",{color:e,intensity:1.7,distance:2.8})})}function xpe({color:e,tailZ:A,hullWidth:t}){const i=E.useMemo(()=>{const o=document.createElement("canvas");o.width=128,o.height=128;const s=o.getContext("2d");if(s){const r=s.createRadialGradient(64,64,0,64,64,64);r.addColorStop(0,"rgba(255,255,255,0.9)"),r.addColorStop(.18,"rgba(255,255,255,0.38)"),r.addColorStop(.55,"rgba(255,255,255,0.1)"),r.addColorStop(1,"rgba(255,255,255,0)"),s.fillStyle=r,s.fillRect(0,0,128,128)}const a=new pd(o);return a.colorSpace=rn,a},[]),n=E.useRef(null),g=VC.clamp(t*.38,.44,.9);return E.useEffect(()=>()=>i.dispose(),[i]),Ba(({clock:o})=>{var a;const s=.96+Math.sin(o.elapsedTime*9)*.06;(a=n.current)==null||a.scale.set(g*s,g*s,1)}),C.jsxs("group",{position:[0,0,A+.18],children:[C.jsx("pointLight",{color:e,intensity:1.8,distance:2.4,decay:2}),C.jsx("sprite",{ref:n,scale:[g,g,1],renderOrder:20,children:C.jsx("spriteMaterial",{map:i,color:e,transparent:!0,opacity:.7,blending:io,depthWrite:!1,depthTest:!1,toneMapped:!1})})]})}function Tpe({piece:e,tier:A,color:t}){const i=gmA(e,A),n=Ur(i),g=omA(e),o=qw([g.diffuse,g.normal,g.metallic,g.roughness,g.emission]),s=E.useMemo(()=>new Et(t),[t]),a=E.useMemo(()=>{const[r,I,c,l,B]=o;r.colorSpace=rn,B.colorSpace=rn;for(const k of o)k.flipY=!1,k.anisotropy=4,k.needsUpdate=!0;const Q=n.scene.clone(!0);Q.traverse(k=>{const N=k;!N.isMesh||!N.material||(N.material=new xg({map:r,normalMap:I,metalnessMap:c,roughnessMap:l,emissiveMap:B,emissive:s,emissiveIntensity:.72,metalness:.74,roughness:.44,envMapIntensity:1.25}))});const d=new Ag().setFromObject(Q).getSize(new SA),p=Math.max(d.x,d.y,d.z)||1;Q.scale.setScalar(1.65/p),Q.updateMatrixWorld(!0);const m=new Ag().setFromObject(Q).getCenter(new SA);Q.position.sub(m),Q.updateMatrixWorld(!0);const D=new Ag().setFromObject(Q),S=D.getSize(new SA);return{object:Q,tailZ:D.max.z,hullWidth:Math.max(S.x,S.y)}},[s,n.scene,o]);return C.jsxs("group",{rotation:[-.08,0,0],children:[C.jsx("primitive",{object:a.object,dispose:null}),C.jsx(xpe,{color:`#${s.getHexString()}`,tailZ:a.tailZ,hullWidth:a.hullWidth})]})}function KJ({player:e,color:A}){const t=(e==null?void 0:e.piece)??"azure-sovereignty",i=e?_pe(e):1,n=e?w4(e,A):A;return C.jsx(E.Suspense,{fallback:C.jsx(Lpe,{color:n}),children:C.jsx(Tpe,{piece:t,tier:i,color:n})})}function VgA({color:e,progress:A}){const t=.7+A*4.2,i=Math.max(0,1-A);return C.jsxs("mesh",{rotation:[Math.PI/2,0,0],scale:[t,t,t],children:[C.jsx("torusGeometry",{args:[1,.015,8,96]}),C.jsx("meshBasicMaterial",{color:e,transparent:!0,opacity:i*.82,blending:io,depthWrite:!1})]})}function qpe({player:e,color:A}){return C.jsx("group",{scale:.24,rotation:[.35,Math.PI*.56,.2],children:C.jsx(KJ,{player:e,color:A})})}function XgA({player:e,color:A,side:t}){const i=t==="left"?-1:1,n=t==="left"?0:Math.PI,g=[{position:[0,.08,0],scale:.48},{position:[i*.6,.34,.36],scale:.42},{position:[i*.62,-.2,.42],scale:.42},{position:[i*1.18,.48,.85],scale:.36},{position:[i*1.2,-.36,.92],scale:.36}];return C.jsx("group",{children:g.map((o,s)=>C.jsx("group",{position:o.position,rotation:[0,n,0],scale:o.scale,children:C.jsx(KJ,{player:e,color:A})},s))})}function yD({color:e,start:A,end:t,opacity:i}){const n=E.useMemo(()=>new OW([new SA(...A),new SA((A[0]+t[0])/2,(A[1]+t[1])/2+.18,(A[2]+t[2])/2),new SA(...t)]),[A,t]);return C.jsxs("mesh",{children:[C.jsx("tubeGeometry",{args:[n,16,.025,8,!1]}),C.jsx("meshBasicMaterial",{color:e,transparent:!0,opacity:i,blending:io,toneMapped:!1})]})}function Ype({kind:e,attacker:A,defender:t,groupColor:i=dT}){const n=E.useRef(null),g=w4(A,"#41d8ff"),o=w4(t,"#ff4d6d"),s=i||g,a=E.useRef(null),r=E.useRef(null),I=E.useRef(null),c=E.useRef(null),l=E.useRef(null),B=E.useRef(null),{camera:Q}=ic(),h=qw("/zentara/planets/zentara.webp");E.useMemo(()=>(h.colorSpace=rn,h.anisotropy=4,h.needsUpdate=!0,h),[h]),Ba(({clock:S})=>{n.current===null&&(n.current=S.elapsedTime);const k=S.elapsedTime-n.current,N=smA[e]/1e3,G=Fpe(k/N),M=Kpe(G);if(Q.position.set(Math.sin(G*Math.PI*.75)*1.3,2+Math.sin(G*Math.PI)*.42,6.5-M*2.1),Q.lookAt(0,.25,-1.2),c.current&&(c.current.rotation.y+=.18/60,c.current.rotation.x=-.18),I.current&&I.current.position.set(-2.2+M*2.15,1.35-M*.95,-1.25-M*.5),a.current&&(a.current.position.x=e==="hero-clash"?-3.35+M*1.7:-2.8+M*1.25,a.current.position.y=.25+Math.sin(k*2)*.05,a.current.rotation.y=e==="hero-clash"?-.1+Math.sin(k*.9)*.025:-.18+Math.sin(k*.9)*.04),r.current&&(r.current.position.x=e==="hero-clash"?3.35-M*1.7:2.75-M*.8,r.current.position.y=.2+Math.cos(k*1.8)*.05,r.current.rotation.y=e==="hero-clash"?.1:Math.PI+.22),l.current&&(l.current.rotation.z=k*1.6,l.current.scale.setScalar(.8+Math.sin(k*5)*.025+M*.75)),B.current){const w=e==="hero-clash"?Math.max(0,1-Math.abs(G-.58)/.16):Math.max(0,1-Math.abs(G-.72)/.22);B.current.intensity=.5+w*7}});const d=e==="hero-clash"||e==="raid-victory",p=e==="spy-plant",y=e==="wormhole",m=e==="hero-clash",D=e==="spy-plant"?.35:.7;return C.jsxs(C.Fragment,{children:[C.jsx("color",{attach:"background",args:["#020611"]}),C.jsx("ambientLight",{intensity:1.05}),C.jsx("hemisphereLight",{args:["#d7ecff","#172038",1.25]}),C.jsx("directionalLight",{position:[4,6,5],intensity:2.35,color:"#dceeff"}),C.jsx("directionalLight",{position:[-4,2.8,3],intensity:.9,color:g}),C.jsx("pointLight",{ref:B,position:[0,.8,-1.8],color:s,intensity:1.2,distance:8}),C.jsx(Jpe,{}),C.jsxs("group",{ref:a,position:[-2.8,.25,-1.3],rotation:[.22,-.18,-.08],scale:.82,children:[C.jsx("pointLight",{position:[.1,.65,1.1],color:"#ffffff",intensity:1.9,distance:3.2,decay:1.6}),C.jsx("pointLight",{position:[-.8,-.25,.35],color:g,intensity:2,distance:2.8,decay:1.6}),m?C.jsx(XgA,{player:A,color:g,side:"left"}):C.jsx(KJ,{player:A,color:g})]}),(e==="hero-clash"||e==="raid-victory")&&C.jsxs("group",{ref:r,position:[2.75,.2,-2.15],rotation:[.12,Math.PI+.22,.04],scale:.95,children:[C.jsx("pointLight",{position:[.1,.65,1.1],color:"#ffffff",intensity:1.8,distance:3.2,decay:1.6}),C.jsx("pointLight",{position:[.8,-.25,.35],color:o,intensity:1.8,distance:2.8,decay:1.6}),m?C.jsx(XgA,{player:t,color:o,side:"right"}):C.jsx(KJ,{player:t,color:o})]}),C.jsxs("mesh",{ref:c,position:[.75,-1,-2.65],scale:e==="wormhole"?.62:1,children:[C.jsx("sphereGeometry",{args:[1.05,48,32]}),C.jsx("meshStandardMaterial",{map:h,color:e==="wormhole"?"#9bb8ff":"#ffffff",roughness:.78,metalness:.04,emissive:s,emissiveIntensity:.08})]}),C.jsxs("mesh",{position:[.75,-1,-2.65],rotation:[Math.PI/2,0,0],children:[C.jsx("torusGeometry",{args:[1.24,.012,8,120]}),C.jsx("meshBasicMaterial",{color:s,transparent:!0,opacity:.35,blending:io})]}),p&&C.jsxs(C.Fragment,{children:[C.jsxs("group",{ref:I,children:[C.jsx("pointLight",{position:[0,.45,.7],color:"#ffffff",intensity:2.6,distance:2.1,decay:1.4}),C.jsx("pointLight",{position:[.35,-.15,.1],color:g,intensity:2.4,distance:1.8,decay:1.4}),C.jsx(qpe,{player:A,color:g})]}),C.jsx(VgA,{color:s,progress:D}),C.jsx(VgA,{color:s,progress:.64})]}),d&&C.jsx(C.Fragment,{children:m?C.jsxs(C.Fragment,{children:[C.jsx(yD,{color:g,start:[-1.5,.42,-1.35],end:[1.45,.2,-2.02],opacity:.82}),C.jsx(yD,{color:g,start:[-1.85,-.02,-1.12],end:[1.18,-.22,-1.78],opacity:.62}),C.jsx(yD,{color:o,start:[1.58,.34,-1.9],end:[-1.08,.08,-1.28],opacity:.72}),C.jsx(yD,{color:"#ffffff",start:[-1.5,.45,-1.35],end:[1.45,.22,-2.02],opacity:.28})]}):C.jsxs(C.Fragment,{children:[C.jsx(yD,{color:g,start:[-1.2,.2,-1.35],end:[1.78,.18,-2],opacity:.88}),C.jsx(yD,{color:"#ffffff",start:[-1.2,.22,-1.35],end:[1.78,.18,-2],opacity:.4})]})}),y&&C.jsx("group",{ref:l,position:[0,.2,-2.7],children:Array.from({length:8}).map((S,k)=>C.jsxs("mesh",{rotation:[0,0,k/8*Math.PI],children:[C.jsx("torusGeometry",{args:[.82+k*.12,.012,8,96]}),C.jsx("meshBasicMaterial",{color:k%2?"#8ee8ff":s,transparent:!0,opacity:.6-k*.045,blending:io})]},k))})]})}function Hpe(e){switch(e){case"spy-plant":return"Covert asset deployed";case"hero-clash":return"Fleet engagement";case"wormhole":return"Wormhole transit";case"raid-victory":return"Raid victory";default:return"Cutscene"}}function Ope({kind:e,attacker:A,defender:t,groupColor:i=dT,caption:n,onEnd:g}){const o=E.useRef(!1);E.useEffect(()=>{o.current=!1;const a=window.setTimeout(()=>{o.current||(o.current=!0,g())},smA[e]);return()=>window.clearTimeout(a)},[e,g]);const s=()=>{o.current||(o.current=!0,g())};return C.jsxs("div",{className:"zentara-realtime-cutscene",role:"dialog","aria-label":"Zentara cinematic cutscene",children:[C.jsx(QG,{gl:{antialias:!0,alpha:!1,powerPreference:"high-performance"},dpr:[1,1.5],camera:{position:[0,2.15,6.5],fov:46,near:.1,far:80},children:C.jsx(Ype,{kind:e,attacker:A,defender:t,groupColor:i})}),C.jsx("div",{className:"zentara-realtime-cutscene__vignette"}),C.jsx("div",{className:"zentara-realtime-cutscene__bars","aria-hidden":"true"}),C.jsxs("div",{className:"zentara-realtime-cutscene__copy",children:[C.jsx("span",{children:e.replace("-"," ").toUpperCase()}),C.jsx("strong",{children:n??Hpe(e)})]}),C.jsx("button",{className:"zentara-realtime-cutscene__skip",type:"button",onClick:s,children:"Skip"})]})}const Ppe=7600,jpe=4,$gA=[[0,.5,-1.5],[-4.2,2.5,-4.2],[4.1,2.65,-4.8],[.15,4.4,-7]];function zpe(e){var A;return(e.heroId?(A=ms[e.heroId])==null?void 0:A.tier:void 0)??1}function Zpe(){const e=E.useRef(null),A=E.useMemo(()=>{const i=new Float32Array(2700);let n=21791;const g=()=>(n=n*16807%2147483647,(n-1)/2147483646);for(let s=0;s<900;s+=1)i[s*3]=(g()-.5)*55,i[s*3+1]=(g()-.5)*32,i[s*3+2]=-g()*48+8;const o=new Ni;return o.setAttribute("position",new ji(i,3)),o},[]);return Ba((t,i)=>{e.current&&(e.current.position.z+=i*1.35,e.current.position.z>12&&(e.current.position.z=0))}),C.jsx("points",{ref:e,geometry:A,children:C.jsx("pointsMaterial",{color:"#d8efff",size:.065,transparent:!0,opacity:.88,sizeAttenuation:!0})})}function Wpe({color:e,tailZ:A,hullWidth:t}){const i=E.useRef(null),n=E.useRef(null),g=E.useRef(null),o=E.useMemo(()=>{const I=document.createElement("canvas");I.width=128,I.height=128;const c=I.getContext("2d");if(c){const B=c.createRadialGradient(64,64,0,64,64,64);B.addColorStop(0,"rgba(255,255,255,0.85)"),B.addColorStop(.14,"rgba(255,255,255,0.42)"),B.addColorStop(.42,"rgba(255,255,255,0.12)"),B.addColorStop(1,"rgba(255,255,255,0)"),c.fillStyle=B,c.fillRect(0,0,128,128)}const l=new pd(I);return l.colorSpace=rn,l},[]),s=VC.clamp(t*.42,.52,1.05),a=s*.28,r=VC.clamp(t*.16,.13,.34);return E.useEffect(()=>()=>o.dispose(),[o]),Ba(({clock:I})=>{var l,B,Q;const c=.96+Math.sin(I.elapsedTime*8)*.045;(l=i.current)==null||l.scale.set(s*c,s*c,1),(B=n.current)==null||B.scale.set(a*c,a*c,1),(Q=g.current)==null||Q.scale.set(a*c,a*c,1)}),C.jsxs("group",{position:[0,0,A+.34],children:[C.jsx("pointLight",{color:e,intensity:2.4,distance:2.2,decay:2}),C.jsx("sprite",{ref:i,scale:[s,s,1],renderOrder:20,children:C.jsx("spriteMaterial",{map:o,color:e,transparent:!0,opacity:.62,blending:io,depthWrite:!1,depthTest:!1,toneMapped:!1})}),C.jsx("sprite",{ref:n,position:[-r,0,.03],scale:[a,a,1],renderOrder:21,children:C.jsx("spriteMaterial",{map:o,color:"#f5fdff",transparent:!0,opacity:.95,blending:io,depthWrite:!1,depthTest:!1,toneMapped:!1})}),C.jsx("sprite",{ref:g,position:[r,0,.03],scale:[a,a,1],renderOrder:21,children:C.jsx("spriteMaterial",{map:o,color:"#f5fdff",transparent:!0,opacity:.95,blending:io,depthWrite:!1,depthTest:!1,toneMapped:!1})})]})}function Vpe({player:e,index:A}){const t=E.useRef(null),i=zpe(e),n=gmA(e.piece,i),g=Ur(n),o=omA(e.piece),s=qw([o.diffuse,o.normal,o.metallic,o.roughness,o.emission]),a=E.useMemo(()=>new Et(e.pieceColor||"#8fe9ff"),[e.pieceColor]),r=E.useMemo(()=>{const[I,c,l,B,Q]=s;I.colorSpace=rn,Q.colorSpace=rn;for(const k of s)k.flipY=!1,k.anisotropy=4,k.needsUpdate=!0;const h=g.scene.clone(!0);h.traverse(k=>{const N=k;!N.isMesh||!N.material||(N.material=new xg({map:I,normalMap:c,metalnessMap:l,roughnessMap:B,emissiveMap:Q,emissive:a,emissiveIntensity:.65,metalness:.72,roughness:.46,envMapIntensity:1.35}))});const p=new Ag().setFromObject(h).getSize(new SA),y=Math.max(p.x,p.y,p.z)||1;h.scale.setScalar(4.6/y),h.updateMatrixWorld(!0);const m=new Ag().setFromObject(h).getCenter(new SA);h.position.sub(m),h.updateMatrixWorld(!0);const D=new Ag().setFromObject(h),S=D.getSize(new SA);return{object:h,tailZ:D.max.z,hullWidth:Math.max(S.x,S.y)}},[a,g.scene,s]);return Ba(({clock:I})=>{if(!t.current)return;const c=I.elapsedTime,l=VC.smoothstep(c,A*.22,2.4+A*.2),B=$gA[A]??$gA[0];t.current.position.set(B[0]+(1-l)*(A%2===0?11:-11),B[1]-(1-l)*5+Math.sin(c*.7+A)*.1,B[2]-(1-l)*24-c*.15),t.current.rotation.set(-.12+Math.sin(c*.5+A)*.035,Math.sin(c*.34+A)*.08,(1-l)*(A%2===0?-.7:.7)+Math.sin(c*.45+A)*.04);const Q=A===0?1.5:.9-A*.06;t.current.scale.setScalar(Q*Math.max(.01,l))}),C.jsxs("group",{ref:t,rotation:[-.12,0,0],children:[C.jsx("primitive",{object:r.object,dispose:null}),C.jsx(Wpe,{color:`#${a.getHexString()}`,tailZ:r.tailZ,hullWidth:r.hullWidth})]})}function Xpe(){const{camera:e}=ic();return Ba(({clock:A})=>{const t=A.elapsedTime,i=VC.smoothstep(t,0,6.8);e.position.set(VC.lerp(7.2,.4,i),VC.lerp(5.8,3.2,i),VC.lerp(17,12.2,i)),e.lookAt(0,1.7,-3.4)}),null}function $pe(){const e=qw("/zentara/planets/zentara.webp");return E.useEffect(()=>{e.colorSpace=rn,e.anisotropy=4,e.needsUpdate=!0},[e]),C.jsxs("group",{position:[0,-12.5,-11],scale:[1.55,1,1.2],rotation:[-.06,-.28,.02],children:[C.jsxs("mesh",{children:[C.jsx("sphereGeometry",{args:[10,96,48]}),C.jsx("meshStandardMaterial",{map:e,color:"#ffffff",emissive:"#081329",emissiveIntensity:.12,roughness:.88,metalness:.02})]}),C.jsxs("mesh",{scale:[1.012,1.012,1.012],children:[C.jsx("sphereGeometry",{args:[10.05,96,48]}),C.jsx("meshBasicMaterial",{color:"#74d8ff",transparent:!0,opacity:.13,blending:io,side:Ua,depthWrite:!1})]})]})}function Afe({players:e}){return C.jsxs(C.Fragment,{children:[C.jsx("color",{attach:"background",args:["#01030b"]}),C.jsx("fog",{attach:"fog",args:["#03081b",18,48]}),C.jsx("hemisphereLight",{args:["#d9eeff","#11152b",2.4]}),C.jsx("ambientLight",{intensity:1.25,color:"#d8eaff"}),C.jsx("directionalLight",{position:[7,10,12],intensity:6.5,color:"#fff4dd"}),C.jsx("directionalLight",{position:[-9,4,6],intensity:4.2,color:"#72cfff"}),C.jsx("directionalLight",{position:[3,-2,-12],intensity:3.8,color:"#b178ff"}),C.jsx("pointLight",{position:[0,3,8],intensity:42,distance:32,decay:1.6,color:"#ffffff"}),C.jsx(Zpe,{}),C.jsxs(E.Suspense,{fallback:null,children:[C.jsx($pe,{}),e.slice(0,jpe).map((A,t)=>C.jsx(Vpe,{player:A,index:t},A.id))]}),C.jsx(Xpe,{})]})}const efe=({players:e,skipEnabled:A,onComplete:t})=>{const i=E.useRef(!1),n=()=>{i.current||(i.current=!0,t())};return E.useEffect(()=>{const g=window.setTimeout(n,Ppe);return()=>window.clearTimeout(g)},[]),C.jsxs("div",{className:"zentara-fleet-intro",onClick:A?n:void 0,role:"presentation",children:[C.jsx(QG,{camera:{position:[7.2,5.8,17],fov:38,near:.1,far:100},dpr:[1,1.5],gl:{antialias:!0,alpha:!1,powerPreference:"high-performance",toneMapping:iy,toneMappingExposure:1.35},children:C.jsx(Afe,{players:e})}),C.jsx("div",{className:"zentara-fleet-intro__grade"}),C.jsx("div",{className:"zentara-fleet-intro__flare"}),C.jsxs("div",{className:"zentara-fleet-intro__copy",children:[C.jsx("div",{className:"zentara-fleet-intro__eyebrow",children:"The frontier is unclaimed"}),C.jsx("div",{className:"zentara-fleet-intro__title",children:"ZENTARA"}),C.jsx("div",{className:"zentara-fleet-intro__rule"}),C.jsx("div",{className:"zentara-fleet-intro__subtitle",children:"Conquer the galaxy. Command your empire."})]}),C.jsx("div",{className:"zentara-fleet-intro__status",children:A?"Tap to deploy":"Fleet approaching"})]})},tfe={asteroid:qZ,nebula:YZ},ife=({deck:e,text:A,amount:t,rollerName:i,rollerColor:n,onDismiss:g,autoDismissMs:o})=>{const s=e==="asteroid"?"Asteroid Event":"Nebula Intel",a=ue.useRef(g);return ue.useEffect(()=>{a.current=g},[g]),ue.useEffect(()=>{if(!o||o<=0)return;const r=window.setTimeout(()=>{var I;(I=a.current)==null||I.call(a)},o);return()=>window.clearTimeout(r)},[o]),C.jsx("div",{className:"zentara-card-backdrop",onClick:g,children:C.jsxs("div",{className:"zentara-card","data-deck":e,onClick:r=>r.stopPropagation(),children:[C.jsx("div",{className:"zentara-card-art-wrap",children:C.jsx("img",{className:"zentara-card-art",src:tfe[e],alt:s})}),C.jsx("div",{className:"zentara-card-title",children:s}),C.jsxs("div",{className:"zentara-card-roller",children:[C.jsx("span",{className:"zentara-card-roller-dot",style:{background:n}}),C.jsx("span",{className:"zentara-card-roller-name",children:i})]}),C.jsx("div",{className:"zentara-card-divider"}),C.jsx("div",{className:"zentara-card-text",children:A}),t!==0&&C.jsxs("div",{className:`zentara-card-amount ${t>=0?"positive":"negative"}`,children:[t>=0?"+":"",t," energy"]}),C.jsx("button",{className:"zentara-card-dismiss",onClick:g,children:"Dismiss ✕"})]})})},amA="/assets/mission-briefing-BujJMjA8.webp",nfe=({factionName:e,factionColor:A,group:t,groupColor:i,cost:n,onConfirm:g,onCancel:o,autoDismissMs:s})=>{const a=ue.useRef(o);ue.useEffect(()=>{a.current=o},[o]),ue.useEffect(()=>{if(!s||s<=0)return;const c=window.setTimeout(()=>a.current(),s);return()=>window.clearTimeout(c)},[s]);const r=t.toUpperCase(),I=n>=1e3?"MONOPOLY INFILTRATION":"FOOTHOLD INFILTRATION";return C.jsx("div",{className:"zentara-spy-deploy-backdrop",children:C.jsxs("section",{className:"zentara-spy-deploy-card",style:{"--spy-faction":A,"--spy-group":i},role:"dialog","aria-modal":"true","aria-labelledby":"zentara-spy-deploy-title",children:[C.jsxs("div",{className:"zentara-spy-deploy-art",children:[C.jsx("img",{src:amA,alt:""}),C.jsx("div",{className:"zentara-spy-deploy-classified",children:"CLASSIFIED // SPY STRIKE"})]}),C.jsx("button",{type:"button",className:"zentara-spy-deploy-cancel",onClick:o,"aria-label":"Cancel spy deployment",children:"Cancel"}),C.jsxs("div",{className:"zentara-spy-deploy-body",children:[C.jsx("div",{className:"zentara-spy-deploy-kicker",children:I}),C.jsx("h2",{id:"zentara-spy-deploy-title",children:"Deploy Covert Asset?"}),C.jsxs("p",{className:"zentara-spy-deploy-lore",children:[e," intelligence is prepared to embed a sleeper cell inside the"," ",C.jsxs("strong",{children:[r," sector"]}),". Once deployed, the operative will remain hidden, feeding false coordinates and waiting for your fleet to return."]}),C.jsxs("div",{className:"zentara-spy-deploy-sequence",children:[C.jsxs("div",{children:[C.jsx("span",{children:"Trigger"}),"Your fleet next lands on any ",r," planet."]}),C.jsxs("div",{children:[C.jsx("span",{children:"Phase A"}),"Soldier Strike: breach the ground defenses."]}),C.jsxs("div",{children:[C.jsx("span",{children:"Phase B"}),"Sniper: eliminate the defending hero."]})]}),C.jsxs("div",{className:"zentara-spy-deploy-outcome success",children:[C.jsx("strong",{children:"Mission success"}),"Vanquish the defender's hero and seize the entire ",r," group."]}),C.jsxs("div",{className:"zentara-spy-deploy-outcome failure",children:[C.jsx("strong",{children:"Mission failure"}),"The spy is exposed. Lose ",xpA.toLocaleString()," energy against a partial holding or ",LpA.toLocaleString()," against a full monopoly, then face normal rent and any hero clash."]}),C.jsxs("p",{className:"zentara-spy-deploy-footnote",children:["Confirm to spend ",n.toLocaleString()," energy and deploy the asset. A change in control may invalidate the mission before activation."]}),C.jsx("button",{type:"button",onClick:g,children:"Acknowledge & Deploy"})]})]})})},rmA=17e3,ImA=700,CmA=2500,k4=3,cmA=5,AoA=30,eoA=8,gfe=.12;function ofe(){return Math.floor((rmA-CmA)/ImA)}function sfe(e=Math.random){const A=ofe();let t=0;for(let i=0;i<A;i+=1)t+=k4+Math.floor(e()*(cmA-k4+1));return Math.max(1,t)}function FJ(e,A,t,i){const n=Math.max(1,Math.floor(A)),g=Math.max(0,Math.min(n,Math.floor(e))),o=n-g,s=Math.ceil(n*gfe),a=Math.max(0,s+i.weaponLevel-t.weaponLevel),r=g>=a,I=g+t.weaponLevel,c=o+i.weaponLevel,l=r?Math.min(AoA+g*eoA,i.credits):Math.min(AoA+Math.floor(g*eoA*.5),t.credits);return{attackerRoll:g,defenderRoll:o,attackerTotal:I,defenderTotal:c,winnerId:r?t.id:i.id,creditsStolen:Math.max(0,l),finalHits:g,totalSpawned:n}}const afe="/assets/fps_soundtrack-DPaQcdtT.m4a",Wm="/assets/zentara_bg_planet-D7XktRqs.webp",rfe="/assets/bogies_intro-CcVJ01Lv.webp",Ife="/assets/raid_torpedo-uTmsDgFP.webp",Cfe="/assets/enemy_crimson_bank2-BT7rb74W.webp",cfe="/assets/enemy_crimson_bank4-BCMi3o3A.webp",lfe="/assets/enemy_crimson_bank6-CXlmAW_2.webp",Bfe="/assets/enemy_silver_bank2-DvdISIck.webp",Efe="/assets/enemy_silver_bank4-C8sYDjrv.webp",Qfe="/assets/enemy_silver_bank6-LEedzbJQ.webp",ufe="/assets/enemy_azure_bank2-CB0VkvKZ.webp",dfe="/assets/enemy_azure_bank4-Bz4T-snu.webp",hfe="/assets/enemy_azure_bank6-Covwy4o4.webp",pfe="/assets/enemy_golden_bank2-D0C8kMEZ.webp",ffe="/assets/enemy_golden_bank4-Dc5WWR8O.webp",yfe="/assets/enemy_golden_bank6-LOlFOFuT.webp",Dfe="/assets/enemy_emerald_bank2-5IgU95Qn.webp",mfe="/assets/enemy_emerald_bank4-BG8NH3Zr.webp",Sfe="/assets/enemy_emerald_bank6-C0p50Ap6.webp",wfe="/assets/enemy_void_bank2-BOmN2a0s.webp",kfe="/assets/enemy_void_bank4-dsAjcFRS.webp",Mfe="/assets/enemy_void_bank6-D3jYjyIh.webp",Nfe="data:image/webp;base64, ",Rfe="data:image/webp;base64, ",Gfe="data:image/webp;base64, ",bfe="data:image/webp;base64, ",Ufe="data:image/webp;base64, ",vfe="data:image/webp;base64, ",Kfe="data:image/webp;base64, ",Ffe="data:image/webp;base64, ",_fe="data:image/webp;base64, ",Jfe="data:image/webp;base64, ",Lfe="data:image/webp;base64, ",xfe="data:image/webp;base64, ",Tfe="data:image/webp;base64, ",qfe="data:image/webp;base64, ",Yfe="data:image/webp;base64, ",Hfe="data:image/webp;base64, ",Ofe="data:image/webp;base64, ",Pfe="data:image/webp;base64, ",jfe="data:image/webp;base64, ",zfe="data:image/webp;base64, ",Zfe="data:image/webp;base64, ",Wfe="data:image/webp;base64, ",Vfe="data:image/webp;base64, ",Xfe="data:image/webp;base64,UklGRqAJAABXRUJQVlA4WAoAAAAQAAAA/wEA/wAAQUxQSFwCAAABoFtbmyRJ+Q35DUnxM6SN+XwZFRn1syPYIdkJdoiD9gmZlZWbUMEWETEBMfw//D/8P/w//D/8P/w//D/8P/w//D/8P/z/z0GQlCTbkkh0NdLL1upqa63ZltDFQNmqdS5PznNrtoXeRdvv13dl57nZFnoWbddy6Nxso1vRdi17zvP8qJRqG52Kdi1b57nW2ppX2/yoVNtdirbfK+sffvLNT356Q6k2OxTsVtY/+eSL77xjm+d5gzqU7Hntky+++9W7t3kupdjuT7JrWa1/+eDWqq3uBLuVUkr1WU+TOWVkZi+p1ecVjsnMjMzMeJ6UhB5Bu/nk3CFzysycMmN/eNkrzq8HmZmRmW8gVuNQSWR0SF7Cysgp30AAIBD9lr6sAMQVAXQF+MpCnBYgScnr7Am6lC0cA5CUvFUiEV0Rvjz3AEjJT0okokfqeuYDgKTkp0US0TF9hyIl7yiSiE6ZU2ZkRgRu4XmRRPTIzCkjc3oDCYJEBO9FJBHdMXPKzJzyDQQAArFVNyGSiM6YOWVkThmrAGLfm9CSq3j1ZeRyyoyT0rf78js9fIuMAAAC0V3hW1T0WICk5Nt88ZHEaQCSku/3pQcvcQxAUvItkwTitc8FY1eQpOT9JXF5JSK6IBDbQVLyzpJIEhRioy5DRFcESMo7SiJJALFOLzcFr8HohiApPymRJIB4nvSS8RAkqQsQ0Qspr0skCSCOlW2LjHX6kiSiJ2IZ5wUQmx9JJKETiER0ZZIEYiNAaSeRRPRyAOBWADH8P/w//D/8P/w//D/8P/w//D/8P/w//D/8PwwOVlA4IB4HAACwOwCdASoAAgABPhkMhUIhBCpnCgQAYS0t34+TPJeSIML3d6z6G+aL6Y+f1so7/K4I7/EPwz8F/8J4d+M33L7Ocj75nvf+EuHf8l+LV0LwdPqH+etnGNH/nepD/rfcd7hvor/nf474Cf5j/Tf9L+ZHey9Fz9ZAgmQXPECgyC54gUGQXPECgyC54gUGQXPECgyC54gUGQXPECgyC54gUGQXPECgyC54gUGQXPECgyC54gUGQXPECgyC54gUGQXPECgyC54gUGQXPECgyC54gUGQXOba3bxfLvBBOyE8cuL8hdzfiszMXsgnmZi9j1VOqDLpldbq2gRc3/+1G/Yi3TG4L0NitG0BxAaOR90sOqeWZwNZfjt/2iy2elH/j4QIkquwxiZi9kE8zMXoU+6ihSBYtTW86IEyELLkAVSds3etdaVBisP9Cklz/f3lWmAs5v+QVM+NCFYlJUCnXD4jpSOzC+3OTWz5J6ulXbXw9p4rMzF7IJ5l0lkF4DAYDXspPQinbl+P+8NT7AGVxAoMgueIFBkFzxAoMgueIFBkFzxAoMgueIFBkFzxAoMgueIFBkFzxAoMgueIFBkFzxAoMgueIFBkFzxAoMgueIFBkFzxAoMgueIFBkFzxAoMgueIFBkFzxAn/AAA/v/9IsAAAAAAAAAAGF/UGcrjeGUmznfjVi4pLO5GYPXYffy/9sXaAfxoLlqP/DP2O19R2Z//Fuc6RbZ0/5sZ95OZ/ZOuq/8oYhs+79YD8ijjHyBFSEMuwWs9jLbDZA2HzoMGu9nzRt1p0teCML/ExGRpo8eYqGPr/wPhSkttcZcx4Q1YWZbTh9smK2uetAmjOhRA/+1/X+fb3iKlaTNUUbcQ2/4YS+JZ3qoxCJIDE/koKgKpEofw+qI3Lv00uK87peZJmcpTHUa8RX9ZpS1b1f/mLMdVjASsT7jbtXSa4hnMsS/u4vzVr/NBj1guF1lT+vKcvU5nmjoEIOkgGa2cXyFC/9RLeUHTeJCzC2+Kyxw1/AY2WvRKbuUaYicwdwVKLRxl+Iz3tX01+P0Df/WmKjuEwIDCdNOkOsjTyP2zhj9hBjn4VSsYpFonAGhT8q2qO1WEd6vdAnxHbZDVs8bcUerVIbNdIJrWM8KoDF1bBmkN2Ymh2xcQX8cEoOub/5KAy9HFzIAXeCy7vaqVuZk0LRGgcmkzUlnFwTk2gNBf6OuptbWUsu1S+QLvu7DGAMYtJL1CmFxnDSCmwMqoEFqQvf08+uxa3FhhQOSeCWxw9J1RiHXUZXA/9Xp731GTIHewvVupKLUbzhHcGNwvZNvZ6fXMwis6rv8akHvr6gkSoe03EVehYb5hQCkNXR5YL3Co9RjAtxH2Xu99o4Y6d9O0OhvUb092VvXlvBndEZd4QrY4u/aqowW0E+Lr6ML2xli/5p1i6CtGuXJjUb01Asuv8zbYzmofjL7VGK6XNnmGJIXxSN1mkuy6bZFiPJjiAax5xNR9IlU7Gzn2sPxaDWrbSISDlsl3q0vmnHjN4IlHtaqdPUODMfzBXhx4ZIhdaMPiMWSas4EA+rQwRbvn+YGco47wyuKt89NV5+GU3G5AgDVbTszkMYaMyrlzwjD+nZQd2bQ441w958PaDY41j80CJVeDAUfKuTG5Crfa1XnmSAwGeUDzQaNm80VfD/AAOA08j94+/4yMfFkBVewyULxcFuDI7i1aMfjphEW9b8NGUgVsoYid25r9KfesZckwXkCIJqUSJbFcjatoXYslShtuVya+Y2TEEqSi0tIusXtc78sj/LIFqhqSHaYOSkFB3hhez36dufCD+anWY5/TFu+Gp3bHJ9uztPeXlbVmON/e610l0RCDB+0JS6mG1SzYE5VfmXvDmJUtGpnx4lTT80DLY7SSftbvfeEQN8h0bgSCeRWmNwQ63Ru65Jc/qgnGoA6UVwlkpnVdrF9Wepn+mU9PtBNSTljx1SuOMiaFrLjxMX7FFQWPRs591dwc0dsKqYaPd9go0wj5grePAs4PKPR3Y+wlBywBejOV7zu4NQR0K01wC3KyySxGrVUSbODazCiVYrU0TKR1Mwm01rsr3MV13x+VQIP9JlAGhIyhr2BFnMVeJLPSlmmsfOxENcyh7eFNtJB/Z5xUlDClU1C33J9x6ZC1nZgR4tsvla5Z04H/dU5AOcLpdM/xs7mbcIhNz4VQsVOsE8J+Z9+x6DXuar5prZmTeXOUaNIv0IiNr3k5npFl/0VWfnm4Z++suiOuQI/dtrCUjon9yysyTb412pUswX8CrKpj/Vj8+iWHATJGsQnfXef7wclVLWxvomxpIx1SSPxX5qO7Lz9KnBpeIAAACIA/w87H5xkfFgowNAGpym+NJXYEiM+0gPIdLKB+QmhTJoaA0IR0y2DtiIGdP6gcK9iaQzgWhoQgpwLg0BnaBZXnoDOhAAAA",$fe="data:image/webp;base64, ",Aye="data:image/webp;base64, ",eye="/assets/enemy_azure_headon_bank5-i9H_e-T1.webp",tye="/assets/enemy_golden_headon_bank3-BAwmOiOE.webp",iye="data:image/webp;base64, ",nye="data:image/webp;base64, ",gye="data:image/webp;base64, ",oye="data:image/webp;base64, ",sye="data:image/webp;base64,UklGRv4KAABXRUJQVlA4WAoAAAAQAAAA/wEA/wAAQUxQSFECAAABBrqRbTuSnGdKmXJNGVPKl1UhQ312LCfgQIEDFdCeUNXVRVqYD/bviYgJcPd/93/3f/d/93/3f/d/93/3f/d/93/3f/f/Pwc1QtouO21QU4NazkyrAGWn1cQ0Zjknf/HyTpgpO9W6xrI/n1683PmLuexUyxrLnl4e+sVctprVWPb0cs8v4JY9la1GNZanl1u/YLJnapUvbnkqu0mNZX/2cv31u29+qrs3eCqPDUrl+eX6Oz59VzvOX8CGbFBZZu3dp+9+rd3nL3hpl92esjy9XJ3+qoNnpnI2J5V5aXuqs55mQATQSibXeVPHDIABfP9I2moRlGeffNxhQACG2F+1bBXnzxsDYOBJo1fj0LQhGiSXcA6BeNJo29jRbqnLpuy4ouymoLpyKk4rA6RrnZaQl7JTx8hAuramQdEUVZdnDxnSdWcaFC0yr2duyEC67k5A0TDrESbYtWMCikY5CAJs6yHcnyMoWuSACNCTRozBYR5LAormOCAA86TRtrFjaz6IBBSNcUAEiFiVHfs+iFyOq3ruG8xSECcd6+E++51e9RAJyzZ2NFfVQ8xosTKQrof5zAfoNDKQrsf7rKda6hgZSNdDBuR43mdB7CqAdO2fNssroWiCcmwXkK6d0wYQqdiYl0HRFGUga8e0AWTHOrXcZK5BNEMBWXemAWTH/VBL4qYA8gIoWiFZ62kA2XFslu2EWKcuCYqWqGWcV3ZsvpUGlCdIUDRlADk2yqR3SkDRymWbrbaj+7/7v/u/+7/7v/u/+7/7v/u/+7/7v/u/+78bHABWUDgghggAAFBAAJ0BKgACAAE+GQyFQiEEFrsNBABhLS3fj5M5HXuKcypzv39eu30Lpp8/0HeJj/afVX6Ov5N/tfUB/GP7H/yvbs9G/oAf07+wdYZ6AHlqftP8H/7d/ux7Qv/5ziL+d/g1+nPkz/XvC/xm+7vaqrHeG+SP+8ea7EvXK/Qv9J+ZFyXxc+gl/r+ZL6M/5PuDfy7+o/6r+0/uX3tPRr/XIGldTwBMYhdO6ngCYxC6d1PAExiF07qeAJjELp3U8ATGIXTup4AmMQundTwBMYhdO6ngCYxC6d1PAExiF07qeAJjELp3U8ATGIXTup4AmMQundTwBMYhdO6ngCXjlodCMHVA0aLiSYApRoH1QundTwBMYhdO6nf/9YU4VpeNy1TBhxfRZJpzdWsIGgkz0yqFs/0gKHLOBskV0kx1ovi3fzzuJNTqdSXMn0KLIRNUkFzieXiF07pyE4CEqe7MWqODSAT3SCfpV7ZrROU8FC8kLCCnXUYDjAfC20ZhnhXKBhfZHxcMaTep7gZnAAWKgY+JcuN5qWOMQc31PAExiF06Rpnq0y1YFXLmZLvtN23bdryvqnLxC6d1PAExiF07qeAJjELp3U8ATGIXTup4AmMQundTwBMYhdO6ngCYxC6d1PAExiF07qeAJjELp3U8ATGIXTup4AmMQundTwBMYhdO6ngCYxC6d1PAExiF0qAA/v/6RYAAAAAAAhPU2769DQbeVPfZ2YBeyGLpm0RitdpFKxg+a/ifUpeY/mX/GFvwOjksTomBitASHtU7Rve7HnqV7FDJtTz4eD/+7YDbTUb87igTvXge8k+H1ngbEG8FMqG0jQWVJiZrmioAeDtl1L/zoX50pHVfm1eU3y8j+cXkSEJo1P/NDR+8HE15P15G/OVwsfcZj7GUsX3M3/pZnrYv5P9gv/2coOpr0BqRh8AOx8pkjcV1SIphig+HQRxlGj83RUhtJgt0eSi/7aCf//tLigp8s4liwNoxpFnzMS+ZQa/nEYgw6nEBmKAc+6jlcM9Tr7fyX/+LVF8hsv8IBKIzFt1h9QKhdSmYiervI42NtCGbI/WvfVUSZrufK075uqSvXoq/dLG+xrbsP/aKFmZv6XlVTQo/9qbVLHpOEjv2ZgyWVH5Ob7DBjtM/8EkguOs1iejZ9+bDoJ0H/v8oP/rTK936rIwAB0psSodjw/9yCM/2Mf+TJXqjXipJwRylF0uE7h2hWbpVJifdqHlL3c1Ov4+IFXx4wSrFsqQbHigBmAtDfsblTP7m6nMVXPjUhfQG+YnZaUUqK2A2V1LHyesY4dFieONIHT40RZtBfempR3snglzZB8GrNcovq5DDtWjOMwEZWoawU87yEflruo3Cluw/8VTk5axX4YWNdUup3tvlQN4HpAfAmdxSVVS41FIrCqnMEBdn0l/Tylw63hOzhdhzEofuz3s2nh6rfxRRnjOIF/JQvgQ1mpqQTBiio1pjZy3Jnw64TCWOtE94D9sz3HiCtIu6AZJTT8inBJZpLr5Pmn6GpcmSZ9I87/U+Qy28wvj5Qsg6gTRIeRQmyuPPJmqnPIcaSI0xhN9m1E/rvbFVilBwPLB/diXFQDMtuJrBFvQj2xQ3BVL8Owlxj2rHS5AuG8R9ys7XlOf6t1O6MnXNA9z1V9oyhcNnOn8j1bxiHqd797l/aklaWBB3Ypspa5jCZKNw+S6WbeOslByOG8Q5suaFwT+DmMp6Y8Yscc6bJzf6p5pjaW8xvJBWJtBoJ+gK2YBcU9QttRteIA2B40OneH9876p/dHYN71+lXqoy29aKfn6cxcPDfEPzRCn4gILbq5hP20bgZZKw4RBf/wYf+rKQzaaJiPXrenkf2gn5UAyvjkS+2iC+HYbqZ4xmazIMAtcmEnPIH74cdmj/TXBBWHbKXU4sgVdm9S6r44GEx63ShIzKiAkdAnR0Z5hPX+/f2OmuXtxEhpa47vW9DxFaeulEuf0MQheawJmzwwO3g/iSRrus3LjcIIARQFiofZu+uI/xKRoOAk3jbKsDHpD+ja0zx1SP+0PSIRJbLOpXwBnZsbESpchmUmJqSZ4uy37VirH2t39tzXPf/G5ntCMYAY0+OXccu/YWCtkR/pI3z2mWmhyVKbT+mxGBMTfVb9dshq0NNBZWBS7yiKKTdzr/NYLt/iBs3ArsCQm2T1DAvE0+XqaR3m4/Ijd7gKWt6ytn1TefVaJHGDMymIjEeKXxfvHBga2DpL5OOoTPtVFK9S6tHQ2p+CuoyfXaL2bqlF8Y/aA0S74afP445e2NEuRlpB59nDHwNQWL6pba8RukJMPw3qWquifzie+eIg+9/zpHTzpDgL7gXoBgNWUtNcxY+jh9Rmx59M+c7C8Jo/4nXXhsBsqo6C7vO4FFNzBR++ehrnbom/UFnEsKRlknDau/Id+sKU2qxxojQCL2QXoXwLCj7ewINp0l1H4nnr7KCkd96SOK94eJiURjhSrBr4Jbb2AqnvchxwWk6aQpulcjTqBmafnHWkYGZYOdECS5LHu2E+HddPWeHGDEkdNd7epCuHDFPKPxHCuUrqOohvgPXIuvH6QbOvXgjunCCLq9btveqQzEZs1Ohh8yx0sXy22BQ32PywaapsYjDsqI4twfJhpYkgUI+2FdhEPzJBdcqudKtFKWZftc1WQA7AV8tvPqHpliYrhzI5K1J9/9WNyFvvViv3cTz7qHS2pNCrf1psoe1TTamt9doEUT+xaLkkk3m3tb/FQoWskDUdg8KEf19SX3exZ6TE1/+7sjNfwOjBU/VLR2659ZfPHj2bYvulTnANSvTMdD83evUZUmuCy1spVYRTawAACjUZTavPfQVFJdTW2yH+wdrZbKVyr/4z7VlxGyNv41g5IB6AsPJ7Ist1vN3OAar/B8+EhAGqQAAAAAAAAAAAA=",aye="data:image/webp;base64, ",rye="data:image/webp;base64, ",Iye="/assets/enemy_void_headon_bank5-uqlOncyY.webp",Cye="/assets/cockpit_red-D9Z7CCYz.webp",cye="/assets/cockpit_silver-CYcc-KqK.webp",lye="/assets/cockpit_blue-JbBctwkd.webp",Bye="/assets/cockpit_gold-OYjriaOU.webp",Eye="/assets/cockpit_green-Bh4QHBHC.webp",Qye="/assets/cockpit_black-DplLg93u.webp",uye="/assets/cockpit_legacy_crimson_turret_1-DrDnrMz8.png",dye="/assets/cockpit_legacy_crimson_turret_2-VkMAD65W.png",hye="/assets/cockpit_legacy_crimson_turret_3-BW1HBR1o.png",pye="/assets/cockpit_legacy_crimson_turret_4-BRDgMiwJ.png",fye="/assets/cockpit_legacy_crimson_turret_5-BAf9UZqT.png",yye="/assets/cockpit_legacy_crimson_turret_6-Bdt8rLXS.png",Dye="/assets/cockpit_legacy_silver_turret_1-DSOfodaj.png",mye="/assets/cockpit_legacy_silver_turret_2-tAnK_626.png",Sye="/assets/cockpit_legacy_silver_turret_3-BMtF9R9P.png",wye="/assets/cockpit_legacy_silver_turret_4-pPzY36b0.png",kye="/assets/cockpit_legacy_silver_turret_5-C8OJNHF7.png",Mye="/assets/cockpit_legacy_silver_turret_6-CyE7D_WC.png",Nye="/assets/cockpit_legacy_gold_turret_1-AxxZC0ic.png",Rye="/assets/cockpit_legacy_gold_turret_2-BZsPbqyX.png",Gye="/assets/cockpit_legacy_gold_turret_3-CbpKpXzT.png",bye="/assets/cockpit_legacy_gold_turret_4-B2JEPHJw.png",Uye="/assets/cockpit_legacy_gold_turret_5-B8Secc75.png",vye="/assets/cockpit_legacy_gold_turret_6-Cv44-Nbd.png",Kye="/assets/cockpit_legacy_azzure_turret_1-KU89WC9_.png",Fye="/assets/cockpit_legacy_azzure_turret_2-CC7hQ0xE.png",_ye="/assets/cockpit_legacy_azzure_turret_3-Bjzduy1w.png",Jye="/assets/cockpit_legacy_azzure_turret_4-BcUI99jC.png",Lye="/assets/cockpit_legacy_azzure_turret_5-Cv2ra0mr.png",xye="/assets/cockpit_legacy_azzure_turret_6-CiNSaI5P.png",Tye="/assets/cockpit_legacy_void_turret_1-DhGgm8Nz.png",qye="/assets/cockpit_legacy_void_turret_2-DCCuuayW.png",Yye="/assets/cockpit_legacy_void_turret_3-CX2YTDou.png",Hye="/assets/cockpit_legacy_void_turret_4-D_mbGRwe.png",Oye="/assets/cockpit_legacy_void_turret_5-Bktw9bbQ.png",Pye="/assets/cockpit_legacy_void_turret_6-B_CLoEvm.png",jye="/assets/cockpit_legacy_emerald_turret_1-BqJwnLMP.png",zye="/assets/cockpit_legacy_emerald_turret_2-CpcpGDUL.png",Zye="/assets/cockpit_legacy_emerald_turret_3-DgrTzw2E.png",Wye="/assets/cockpit_legacy_emerald_turret_4-ChFGDzar.png",Vye="/assets/cockpit_legacy_emerald_turret_5-CQQYvOlj.png",Xye="/assets/cockpit_legacy_emerald_turret_6-BA7NzSGw.png",$ye="/assets/battleship_crimson-BP8YBbHm.webp",ADe="/assets/battleship_silver-Bny1kROS.webp",eDe="/assets/battleship_azure-Bq1rJGy2.webp",tDe="/assets/battleship_golden-Aq15Jmcg.webp",iDe="/assets/battleship_emerald-CE5hNTxV.webp",nDe="/assets/battleship_void-y7zwWNtK.webp",lmA=afe,gDe=rfe,yd=e=>{if(typeof Image>"u")return null;const A=new Image;return A.src=e,A},oDe={"crimson-dominion":[Cfe,cfe,lfe],"silver-pact":[Bfe,Efe,Qfe],"azure-sovereignty":[ufe,dfe,hfe],"golden-imperium":[pfe,ffe,yfe],"emerald-collective":[Dfe,mfe,Sfe],"void-enclave":[wfe,kfe,Mfe]},sDe={"crimson-dominion":[Nfe,Rfe,Gfe],"silver-pact":[bfe,Ufe,vfe],"azure-sovereignty":[Kfe,Ffe,_fe],"golden-imperium":[Jfe,Lfe,xfe],"emerald-collective":[Tfe,qfe,Yfe],"void-enclave":[Hfe,Ofe,Pfe]},aDe={"crimson-dominion":[jfe,zfe,Zfe],"silver-pact":[Wfe,Vfe,Xfe],"azure-sovereignty":[$fe,Aye,eye],"golden-imperium":[tye,iye,nye],"emerald-collective":[gye,oye,sye],"void-enclave":[aye,rye,Iye]},rDe={"crimson-dominion":Cye,"silver-pact":cye,"azure-sovereignty":lye,"golden-imperium":Bye,"emerald-collective":Eye,"void-enclave":Qye},BmA={"crimson-dominion":"#ff1744","silver-pact":"#b0bec5","azure-sovereignty":"#448aff","golden-imperium":"#ffc400","emerald-collective":"#69f0ae","void-enclave":"#d500f9"},vl=yd(HZ),V0=yd(Ife),IDe=yd(Wm),EmA={};for(const[e,A]of Object.entries(rDe)){const t=yd(A);t&&(EmA[e]=t)}const CDe={"crimson-dominion":[uye,dye,hye,pye,fye,yye],"silver-pact":[Dye,mye,Sye,wye,kye,Mye],"azure-sovereignty":[Kye,Fye,_ye,Jye,Lye,xye],"golden-imperium":[Nye,Rye,Gye,bye,Uye,vye],"emerald-collective":[jye,zye,Zye,Wye,Vye,Xye],"void-enclave":[Tye,qye,Yye,Hye,Oye,Pye]},RV={};for(const[e,A]of Object.entries(CDe))RV[e]=A.map(t=>yd(t));const cDe=RV["crimson-dominion"],lDe={"crimson-dominion":$ye,"silver-pact":ADe,"azure-sovereignty":eDe,"golden-imperium":tDe,"emerald-collective":iDe,"void-enclave":nDe},QmA={};for(const[e,A]of Object.entries(lDe))QmA[e]=yd(A);const BDe=()=>{try{return Ui.getPlatform()}catch{return"web"}},_J=BDe(),umA=_J==="android",GV=_J==="ios",sC=_J==="ios"||_J==="android",EDe=GV?1:sC?1.25:2,toA=GV?22:sC?16:0,QDe=()=>{var e;if(typeof window>"u"||typeof navigator>"u")return!1;try{if(navigator.maxTouchPoints>0||(e=window.matchMedia)!=null&&e.call(window,"(pointer: coarse)").matches)return!0}catch{}return!1},uDe=()=>{var e,A;if(typeof window>"u")return!1;try{return!!((e=window.matchMedia)!=null&&e.call(window,"(pointer: fine)").matches||(A=window.matchMedia)!=null&&A.call(window,"(hover: hover)").matches)}catch{return!1}},dDe=QDe(),hDe=uDe(),ioA=!sC||hDe||!dDe;function DD(e,A){let t=0;for(let i=0;i<e.length;i+=1){const n=e[i];A(n)&&(e[t]=n,t+=1)}e.length=t}const mD=128,dp=48;let aO=null,gv=null,rO=null;function pDe(){if(aO)return aO;const e=document.createElement("canvas");e.width=mD,e.height=mD;const A=e.getContext("2d"),t=mD/2,i=A.createRadialGradient(t,t,0,t,t,t);i.addColorStop(0,"rgba(255,180,60,0.3)"),i.addColorStop(.5,"rgba(255,100,20,0.15)"),i.addColorStop(1,"rgba(255,40,0,0)"),A.fillStyle=i,A.fillRect(0,0,mD,mD);const n=mD*.2,g=A.createRadialGradient(t,t,0,t,t,n);return g.addColorStop(0,"rgba(255,255,220,0.7)"),g.addColorStop(.5,"rgba(255,200,80,0.4)"),g.addColorStop(1,"rgba(255,120,20,0)"),A.fillStyle=g,A.beginPath(),A.arc(t,t,n,0,Math.PI*2),A.fill(),aO=e,e}function fDe(){if(gv)return gv;const e=(A,t)=>{const i=document.createElement("canvas");i.width=dp,i.height=dp;const n=i.getContext("2d"),g=dp/2,o=dp/2,s=n.createRadialGradient(g,g,0,g,g,o);return s.addColorStop(0,"#ffffff"),s.addColorStop(.4,t),s.addColorStop(1,A),n.fillStyle=s,n.beginPath(),n.arc(g,g,o,0,Math.PI*2),n.fill(),i};return gv={hit:e("rgba(0,255,170,0)","#00ffaa"),miss:e("rgba(255,68,68,0)","#ff4444")},gv}function yDe(){if(rO)return rO;const e=document.createElement("canvas");e.width=dp,e.height=dp;const A=e.getContext("2d"),t=dp/2,i=A.createRadialGradient(t,t,0,t,t,t);return i.addColorStop(0,"#ffffff"),i.addColorStop(.35,"#aaffcc"),i.addColorStop(1,"rgba(0,255,102,0)"),A.fillStyle=i,A.beginPath(),A.arc(t,t,t,0,Math.PI*2),A.fill(),rO=e,e}const noA={};function DDe(e,A){const t=noA[e];if(t&&Math.abs(t.cachedR-A)<5)return t.canvas;const i=Math.ceil(A*2),n=document.createElement("canvas");n.width=i,n.height=i;const g=n.getContext("2d"),o=i/2,s=g.createRadialGradient(o,o,0,o,o,A);return s.addColorStop(0,`${BmA[e]}44`),s.addColorStop(1,"transparent"),g.fillStyle=s,g.fillRect(0,0,i,i),noA[e]={canvas:n,cachedR:A},n}const dmA=1,goA=.012,mDe=5.6,IO=e=>{const A=1-Math.max(e.z,0)/dmA,t=A*A;return(goA+(mDe-goA)*t+(e.z<0?Math.abs(e.z)*3:0))*e.sizeScale},SDe=(e,A,t)=>{const i=A*.5,n=t*.5,g=e.x-i,o=e.y-n,s=1-Math.max(0,Math.min(1,e.z/dmA)),a=Math.sign(e.visualVx),r=Math.sign(g),I=a!==0&&a===r?g*s*.025:0,c=e.visualVx+I,l=e.spriteIndex%3;let B=l;const Q=90,h=30;l===1?c<-Q?B=0:c>Q&&(B=2):l===0?c>-h&&(B=1):c<h&&(B=1);const d=-o/(t*.5),p=-e.visualVy/280,m=d+p*.3>.05;return e.z<.34&&!m?B+6:m?B+3:B},wDe=e=>{const t=Math.max(-1,Math.min(1,e.visualVx/380)),i=Math.max(-1,Math.min(1,e.visualVy/520));return t*.26+i*.06};class hmA{constructor(A){Oi(this,"audio",null);Oi(this,"fadeTimer",null);Oi(this,"volume");Oi(this,"fadeMs");Oi(this,"fadeSteps");Oi(this,"src");this.src=A.src,this.volume=A.volume??.1875,this.fadeMs=A.fadeMs??800,this.fadeSteps=A.fadeSteps??16}play(){if(this.audio)return;const A=new Audio(this.src);A.loop=!0,A.volume=this.volume,A.play().catch(()=>{}),this.audio=A}stop(){const A=this.audio;if(!A)return;this.clearFade();const t=this.fadeMs/this.fadeSteps,i=A.volume;let n=0;this.fadeTimer=window.setInterval(()=>{n+=1,A.volume=Math.max(0,i*(1-n/this.fadeSteps)),n>=this.fadeSteps&&(this.clearFade(),A.pause(),this.audio=null)},t)}dispose(){this.clearFade(),this.audio&&(this.audio.pause(),this.audio=null)}clearFade(){this.fadeTimer!==null&&(window.clearInterval(this.fadeTimer),this.fadeTimer=null)}}function kDe(e){const A=e.rng??Math.random,t=e.width,i=e.height,n=t/2,g=i/2,o=A(),s=o<.1?"bankout":o<.25?"attack":o<.75?"strafe":"weave",a=s==="bankout"?.05:s==="attack"?.7:s==="strafe"?1.2:.95,r=A()<.5?-1:1,I=A()<.7?-1:1,c=A(),l=c<.18?"vertical":c<.5?"horizontal":"lateral";let B=(.45+A()*.55)*a,Q=(.45+A()*.6)*a*.85;l==="vertical"?(B*=.1+A()*.15,Q=(.85+A()*.5)*a):l==="horizontal"&&(Q*=.1+A()*.15,B=(.85+A()*.5)*a);let h=n+r*t*B,d=g+I*i*Q;const p=Math.min(t,i)*(s==="bankout"?.22:l==="lateral"?.38:.24),y=h-n,m=d-g,D=Math.hypot(y,m);if(D<p){const J=D>.001?y/D:r,q=D>.001?m/D:-.4*I;h=n+J*p,d=g+q*p}let S,k;if(e.overrideZ!==void 0)S=t*(.08+A()*.84),k=i*(.08+A()*.64);else if(l==="horizontal"){const J=-r;S=n+J*t*(.55+A()*.25),k=g+(A()-.5)*i*.55}else{const J=t*e.battleshipAnchorX,q=i*e.battleshipAnchorY,v=Math.min(t,i)*.2,U=A()*Math.PI*2,x=A()*v;S=J+Math.cos(U)*x,k=q+Math.sin(U)*x*.75}const N=e.zSpeedMin+A()*(e.zSpeedMax-e.zSpeedMin),G=s==="strafe"?N*1.25:s==="bankout"?N*1.3:s==="attack"?N*.92:N,M=e.overrideZ??e.zFar,w=Math.max(.1,M/G),b=e.overrideZ!==void 0?.55:.35,_=(h-S)/w*b,K=(d-k)/w*b;return{id:e.allocId(),x:S,y:k,vx:_,vy:K,z:M,zSpeed:G,alive:!0,spawnTime:e.now,color:e.factionColor,pieceKey:e.faction,sizeScale:.7+A()*.7,wobblePhase:A()*Math.PI*2,wobbleAmp:s==="weave"?6+A()*6:2+A()*4,wobbleFreq:.8+A()*1.4,flybyPlayed:!1,prevY:k,visualVy:0,spriteIndex:1,prevSpriteIndex:1,spriteFadeStart:0,targetX:h,targetY:d,visualVx:_,bankVx:_,profile:s,weavePhase:A()*Math.PI*2,renderScale:0,renderCosR:0,renderSinR:0,spinRate:A()<.1?(A()<.5?-1:1)*(.9+A()*.6):0}}const ooA=(e,A)=>{const t=Math.hypot(e,A);return t<.001?null:{x:e/t,y:A/t}},MDe=(e,A,t)=>{const i=Math.hypot(e.vx,e.vy);return i>=24?{x:e.vx/i,y:e.vy/i}:ooA(e.targetX-e.x,e.targetY-e.y)??ooA(e.targetX-A,e.targetY-t)??{x:0,y:-1}},NDe=(e,A,t,i,n,g)=>{const o=t-e,s=i-A,a=Math.hypot(o,s),r=Math.max(0,n*g);if(a<=r||a<.001)return{vx:t,vy:i};const I=r/a;return{vx:e+o*I,vy:A+s*I}},RDe=(e,A,t,i,n)=>{const g=e*t.x+A*t.y,o=e-t.x*g,s=A-t.y*g,a=Math.exp(-5*i*n),r=g+380*i*n;return{vx:t.x*r+o*a,vy:t.y*r+s*a}},JJ=1e3,pmA=1800,fmA=.8,GDe=umA?0:sC?24:50,bDe=sC?4:7,soA=["#4a148c","#0d47a1","#004d40","#b71c1c","#1a237e","#311b92","#01579b","#1b5e20"],UDe=sC?36:100,LJ=50,ymA=160,DmA=.75,vDe=sC?130:80,KDe=sC?900:500,vh=(e,A)=>e+Math.random()*(A-e);function FDe(){const e=Math.random()*Math.PI*2;return{angle:e,cosAngle:Math.cos(e),sinAngle:Math.sin(e),dist:Math.random()*.15,speed:JJ+Math.random()*(pmA-JJ),brightness:.3+Math.random()*.7,length:.5+Math.random()*1.5}}function _De(){return Array.from({length:GDe},()=>{const e=FDe();return e.dist=Math.random()*fmA,e})}function JDe(){return Array.from({length:bDe},()=>({x:Math.random(),y:Math.random(),radius:.1+Math.random()*.18,color:soA[Math.floor(Math.random()*soA.length)],alpha:.04+Math.random()*.06,driftX:(Math.random()-.5)*.006,driftY:(Math.random()-.5)*.006}))}function LDe(){return Array.from({length:UDe},()=>({angle:Math.random()*Math.PI*2,dist:Math.random()*DmA,speed:LJ+Math.random()*(ymA-LJ),size:.4+Math.random()*1.2,alpha:.12+Math.random()*.3}))}const aoA=sC?4:6,roA=400;function xDe(e,A){const t=[];for(let i=0;i<aoA;i+=1){const n=Math.PI*2*i/aoA+Math.random()*.5,g=80+Math.random()*120;t.push({x:e,y:A,vx:Math.cos(n)*g,vy:Math.sin(n)*g,life:roA,maxLife:roA})}return t}const TDe=/^[og]\s*(.+)?/,qDe=/^mtllib /,YDe=/^usemtl /,HDe=/^usemap /,IoA=/\s+/,CoA=new SA,CO=new SA,coA=new SA,loA=new SA,SC=new SA,ov=new Et;function ODe(){const e={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(A,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=A,this.object.fromDeclaration=t!==!1;return}const i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:A||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(n,g){const o=this._finalize(!1);o&&(o.inherited||o.groupCount<=0)&&this.materials.splice(o.index,1);const s={index:this.materials.length,name:n||"",mtllib:Array.isArray(g)&&g.length>0?g[g.length-1]:"",smooth:o!==void 0?o.smooth:this.smooth,groupStart:o!==void 0?o.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(a){const r={index:typeof a=="number"?a:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return r.clone=this.clone.bind(r),r}};return this.materials.push(s),s},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(n){const g=this.currentMaterial();if(g&&g.groupEnd===-1&&(g.groupEnd=this.geometry.vertices.length/3,g.groupCount=g.groupEnd-g.groupStart,g.inherited=!1),n&&this.materials.length>1)for(let o=this.materials.length-1;o>=0;o--)this.materials[o].groupCount<=0&&this.materials.splice(o,1);return n&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),g}},i&&i.name&&typeof i.clone=="function"){const n=i.clone(0);n.inherited=!0,this.object.materials.push(n)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(A,t){const i=parseInt(A,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(A,t){const i=parseInt(A,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(A,t){const i=parseInt(A,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(A,t,i){const n=this.vertices,g=this.object.geometry.vertices;g.push(n[A+0],n[A+1],n[A+2]),g.push(n[t+0],n[t+1],n[t+2]),g.push(n[i+0],n[i+1],n[i+2])},addVertexPoint:function(A){const t=this.vertices;this.object.geometry.vertices.push(t[A+0],t[A+1],t[A+2])},addVertexLine:function(A){const t=this.vertices;this.object.geometry.vertices.push(t[A+0],t[A+1],t[A+2])},addNormal:function(A,t,i){const n=this.normals,g=this.object.geometry.normals;g.push(n[A+0],n[A+1],n[A+2]),g.push(n[t+0],n[t+1],n[t+2]),g.push(n[i+0],n[i+1],n[i+2])},addFaceNormal:function(A,t,i){const n=this.vertices,g=this.object.geometry.normals;CoA.fromArray(n,A),CO.fromArray(n,t),coA.fromArray(n,i),SC.subVectors(coA,CO),loA.subVectors(CoA,CO),SC.cross(loA),SC.normalize(),g.push(SC.x,SC.y,SC.z),g.push(SC.x,SC.y,SC.z),g.push(SC.x,SC.y,SC.z)},addColor:function(A,t,i){const n=this.colors,g=this.object.geometry.colors;n[A]!==void 0&&g.push(n[A+0],n[A+1],n[A+2]),n[t]!==void 0&&g.push(n[t+0],n[t+1],n[t+2]),n[i]!==void 0&&g.push(n[i+0],n[i+1],n[i+2])},addUV:function(A,t,i){const n=this.uvs,g=this.object.geometry.uvs;g.push(n[A+0],n[A+1]),g.push(n[t+0],n[t+1]),g.push(n[i+0],n[i+1])},addDefaultUV:function(){const A=this.object.geometry.uvs;A.push(0,0),A.push(0,0),A.push(0,0)},addUVLine:function(A){const t=this.uvs;this.object.geometry.uvs.push(t[A+0],t[A+1])},addFace:function(A,t,i,n,g,o,s,a,r){const I=this.vertices.length;let c=this.parseVertexIndex(A,I),l=this.parseVertexIndex(t,I),B=this.parseVertexIndex(i,I);if(this.addVertex(c,l,B),this.addColor(c,l,B),s!==void 0&&s!==""){const Q=this.normals.length;c=this.parseNormalIndex(s,Q),l=this.parseNormalIndex(a,Q),B=this.parseNormalIndex(r,Q),this.addNormal(c,l,B)}else this.addFaceNormal(c,l,B);if(n!==void 0&&n!==""){const Q=this.uvs.length;c=this.parseUVIndex(n,Q),l=this.parseUVIndex(g,Q),B=this.parseUVIndex(o,Q),this.addUV(c,l,B),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(A){this.object.geometry.type="Points";const t=this.vertices.length;for(let i=0,n=A.length;i<n;i++){const g=this.parseVertexIndex(A[i],t);this.addVertexPoint(g),this.addColor(g)}},addLineGeometry:function(A,t){this.object.geometry.type="Line";const i=this.vertices.length,n=this.uvs.length;for(let g=0,o=A.length;g<o;g++)this.addVertexLine(this.parseVertexIndex(A[g],i));for(let g=0,o=t.length;g<o;g++)this.addUVLine(this.parseUVIndex(t[g],n))}};return e.startObject("",!1),e}class PDe extends la{constructor(A){super(A),this.materials=null}load(A,t,i,n){const g=this,o=new or(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(A,function(s){try{t(g.parse(s))}catch(a){n?n(a):console.error(a),g.manager.itemError(A)}},i,n)}setMaterials(A){return this.materials=A,this}parse(A){const t=new ODe;A.indexOf(`\r
`)!==-1&&(A=A.replace(/\r\n/g,`
`)),A.indexOf(`\\
`)!==-1&&(A=A.replace(/\\\n/g,""));const i=A.split(`
`);let n=[];for(let s=0,a=i.length;s<a;s++){const r=i[s].trimStart();if(r.length===0)continue;const I=r.charAt(0);if(I!=="#")if(I==="v"){const c=r.split(IoA);switch(c[0]){case"v":t.vertices.push(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3])),c.length>=7?(ov.setRGB(parseFloat(c[4]),parseFloat(c[5]),parseFloat(c[6]),rn),t.colors.push(ov.r,ov.g,ov.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3]));break;case"vt":t.uvs.push(parseFloat(c[1]),parseFloat(c[2]));break}}else if(I==="f"){const l=r.slice(1).trim().split(IoA),B=[];for(let h=0,d=l.length;h<d;h++){const p=l[h];if(p.length>0){const y=p.split("/");B.push(y)}}const Q=B[0];for(let h=1,d=B.length-1;h<d;h++){const p=B[h],y=B[h+1];t.addFace(Q[0],p[0],y[0],Q[1],p[1],y[1],Q[2],p[2],y[2])}}else if(I==="l"){const c=r.substring(1).trim().split(" ");let l=[];const B=[];if(r.indexOf("/")===-1)l=c;else for(let Q=0,h=c.length;Q<h;Q++){const d=c[Q].split("/");d[0]!==""&&l.push(d[0]),d[1]!==""&&B.push(d[1])}t.addLineGeometry(l,B)}else if(I==="p"){const l=r.slice(1).trim().split(" ");t.addPointGeometry(l)}else if((n=TDe.exec(r))!==null){const c=(" "+n[0].slice(1).trim()).slice(1);t.startObject(c)}else if(YDe.test(r))t.object.startMaterial(r.substring(7).trim(),t.materialLibraries);else if(qDe.test(r))t.materialLibraries.push(r.substring(7).trim());else if(HDe.test(r))console.warn('THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');else if(I==="s"){if(n=r.split(" "),n.length>1){const l=n[1].trim().toLowerCase();t.object.smooth=l!=="0"&&l!=="off"}else t.object.smooth=!0;const c=t.object.currentMaterial();c&&(c.smooth=t.object.smooth)}else{if(r==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+r+'"')}}t.finalize();const g=new sa;if(g.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let s=0,a=t.objects.length;s<a;s++){const r=t.objects[s],I=r.geometry,c=r.materials,l=I.type==="Line",B=I.type==="Points";let Q=!1;if(I.vertices.length===0)continue;const h=new Ni;h.setAttribute("position",new $t(I.vertices,3)),I.normals.length>0&&h.setAttribute("normal",new $t(I.normals,3)),I.colors.length>0&&(Q=!0,h.setAttribute("color",new $t(I.colors,3))),I.hasUVIndices===!0&&h.setAttribute("uv",new $t(I.uvs,2));const d=[];for(let y=0,m=c.length;y<m;y++){const D=c[y],S=D.name+"_"+D.smooth+"_"+Q;let k=t.materials[S];if(this.materials!==null){if(k=this.materials.create(D.name),l&&k&&!(k instanceof es)){const N=new es;ho.prototype.copy.call(N,k),N.color.copy(k.color),k=N}else if(B&&k&&!(k instanceof NE)){const N=new NE({size:10,sizeAttenuation:!1});ho.prototype.copy.call(N,k),N.color.copy(k.color),N.map=k.map,k=N}}k===void 0&&(l?k=new es:B?k=new NE({size:1,sizeAttenuation:!1}):k=new VW,k.name=D.name,k.flatShading=!D.smooth,k.vertexColors=Q,t.materials[S]=k),d.push(k)}let p;if(d.length>1){for(let y=0,m=c.length;y<m;y++){const D=c[y];h.addGroup(D.groupStart,D.groupCount,y)}l?p=new EI(h,d):B?p=new Pp(h,d):p=new pn(h,d)}else l?p=new EI(h,d[0]):B?p=new Pp(h,d[0]):p=new pn(h,d[0]);p.name=r.name,g.add(p)}else if(t.vertices.length>0){const s=new NE({size:1,sizeAttenuation:!1}),a=new Ni;a.setAttribute("position",new $t(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(a.setAttribute("color",new $t(t.colors,3)),s.vertexColors=!0);const r=new Pp(a,s);g.add(r)}return g}}function BoA(e,A){if(A===FW)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(A===Df||A===oG){let t=e.getIndex();if(t===null){const o=[],s=e.getAttribute("position");if(s!==void 0){for(let a=0;a<s.count;a++)o.push(a);e.setIndex(o),t=e.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),e}const i=t.count-2,n=[];if(A===Df)for(let o=1;o<=i;o++)n.push(t.getX(0)),n.push(t.getX(o)),n.push(t.getX(o+1));else for(let o=0;o<i;o++)o%2===0?(n.push(t.getX(o)),n.push(t.getX(o+1)),n.push(t.getX(o+2))):(n.push(t.getX(o+2)),n.push(t.getX(o+1)),n.push(t.getX(o)));n.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const g=e.clone();return g.setIndex(n),g.clearGroups(),g}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",A),e}class jDe extends la{constructor(A){super(A),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new XDe(t)}),this.register(function(t){return new $De(t)}),this.register(function(t){return new ame(t)}),this.register(function(t){return new rme(t)}),this.register(function(t){return new Ime(t)}),this.register(function(t){return new eme(t)}),this.register(function(t){return new tme(t)}),this.register(function(t){return new ime(t)}),this.register(function(t){return new nme(t)}),this.register(function(t){return new VDe(t)}),this.register(function(t){return new gme(t)}),this.register(function(t){return new Ame(t)}),this.register(function(t){return new sme(t)}),this.register(function(t){return new ome(t)}),this.register(function(t){return new ZDe(t)}),this.register(function(t){return new Cme(t)}),this.register(function(t){return new cme(t)})}load(A,t,i,n){const g=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const r=AC.extractUrlBase(A);o=AC.resolveURL(r,this.path)}else o=AC.extractUrlBase(A);this.manager.itemStart(A);const s=function(r){n?n(r):console.error(r),g.manager.itemError(A),g.manager.itemEnd(A)},a=new or(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(A,function(r){try{g.parse(r,o,function(I){t(I),g.manager.itemEnd(A)},s)}catch(I){s(I)}},i,s)}setDRACOLoader(A){return this.dracoLoader=A,this}setKTX2Loader(A){return this.ktx2Loader=A,this}setMeshoptDecoder(A){return this.meshoptDecoder=A,this}register(A){return this.pluginCallbacks.indexOf(A)===-1&&this.pluginCallbacks.push(A),this}unregister(A){return this.pluginCallbacks.indexOf(A)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(A),1),this}parse(A,t,i,n){let g;const o={},s={},a=new TextDecoder;if(typeof A=="string")g=JSON.parse(A);else if(A instanceof ArrayBuffer)if(a.decode(new Uint8Array(A,0,4))===mmA){try{o[Fn.KHR_BINARY_GLTF]=new lme(A)}catch(c){n&&n(c);return}g=JSON.parse(o[Fn.KHR_BINARY_GLTF].content)}else g=JSON.parse(a.decode(A));else g=A;if(g.asset===void 0||g.asset.version[0]<2){n&&n(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const r=new wme(g,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});r.fileLoader.setRequestHeader(this.requestHeader);for(let I=0;I<this.pluginCallbacks.length;I++){const c=this.pluginCallbacks[I](r);c.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),s[c.name]=c,o[c.name]=!0}if(g.extensionsUsed)for(let I=0;I<g.extensionsUsed.length;++I){const c=g.extensionsUsed[I],l=g.extensionsRequired||[];switch(c){case Fn.KHR_MATERIALS_UNLIT:o[c]=new WDe;break;case Fn.KHR_DRACO_MESH_COMPRESSION:o[c]=new Bme(g,this.dracoLoader);break;case Fn.KHR_TEXTURE_TRANSFORM:o[c]=new Eme;break;case Fn.KHR_MESH_QUANTIZATION:o[c]=new Qme;break;default:l.indexOf(c)>=0&&s[c]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+c+'".')}}r.setExtensions(o),r.setPlugins(s),r.parse(i,n)}parseAsync(A,t){const i=this;return new Promise(function(n,g){i.parse(A,t,n,g)})}}function zDe(){let e={};return{get:function(A){return e[A]},add:function(A,t){e[A]=t},remove:function(A){delete e[A]},removeAll:function(){e={}}}}const Fn={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class ZDe{constructor(A){this.parser=A,this.name=Fn.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const A=this.parser,t=this.parser.json.nodes||[];for(let i=0,n=t.length;i<n;i++){const g=t[i];g.extensions&&g.extensions[this.name]&&g.extensions[this.name].light!==void 0&&A._addNodeRef(this.cache,g.extensions[this.name].light)}}_loadLight(A){const t=this.parser,i="light:"+A;let n=t.cache.get(i);if(n)return n;const g=t.json,a=((g.extensions&&g.extensions[this.name]||{}).lights||[])[A];let r;const I=new Et(16777215);a.color!==void 0&&I.setRGB(a.color[0],a.color[1],a.color[2],Ka);const c=a.range!==void 0?a.range:0;switch(a.type){case"directional":r=new zp(I),r.target.position.set(0,0,-1),r.add(r.target);break;case"point":r=new BG(I),r.distance=c;break;case"spot":r=new CT(I),r.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,r.angle=a.spot.outerConeAngle,r.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,r.target.position.set(0,0,-1),r.add(r.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return r.position.set(0,0,0),Tl(r,a),a.intensity!==void 0&&(r.intensity=a.intensity),r.name=t.createUniqueName(a.name||"light_"+A),n=Promise.resolve(r),t.cache.add(i,n),n}getDependency(A,t){if(A==="light")return this._loadLight(t)}createNodeAttachment(A){const t=this,i=this.parser,g=i.json.nodes[A],s=(g.extensions&&g.extensions[this.name]||{}).light;return s===void 0?null:this._loadLight(s).then(function(a){return i._getNodeRef(t.cache,s,a)})}}class WDe{constructor(){this.name=Fn.KHR_MATERIALS_UNLIT}getMaterialType(){return kg}extendParams(A,t,i){const n=[];A.color=new Et(1,1,1),A.opacity=1;const g=t.pbrMetallicRoughness;if(g){if(Array.isArray(g.baseColorFactor)){const o=g.baseColorFactor;A.color.setRGB(o[0],o[1],o[2],Ka),A.opacity=o[3]}g.baseColorTexture!==void 0&&n.push(i.assignTexture(A,"map",g.baseColorTexture,rn))}return Promise.all(n)}}class VDe{constructor(A){this.parser=A,this.name=Fn.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(A,t){const n=this.parser.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=n.extensions[this.name].emissiveStrength;return g!==void 0&&(t.emissiveIntensity=g),Promise.resolve()}}class XDe{constructor(A){this.parser=A,this.name=Fn.KHR_MATERIALS_CLEARCOAT}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];if(o.clearcoatFactor!==void 0&&(t.clearcoat=o.clearcoatFactor),o.clearcoatTexture!==void 0&&g.push(i.assignTexture(t,"clearcoatMap",o.clearcoatTexture)),o.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=o.clearcoatRoughnessFactor),o.clearcoatRoughnessTexture!==void 0&&g.push(i.assignTexture(t,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),o.clearcoatNormalTexture!==void 0&&(g.push(i.assignTexture(t,"clearcoatNormalMap",o.clearcoatNormalTexture)),o.clearcoatNormalTexture.scale!==void 0)){const s=o.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new lt(s,s)}return Promise.all(g)}}class $De{constructor(A){this.parser=A,this.name=Fn.KHR_MATERIALS_DISPERSION}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const n=this.parser.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=n.extensions[this.name];return t.dispersion=g.dispersion!==void 0?g.dispersion:0,Promise.resolve()}}class Ame{constructor(A){this.parser=A,this.name=Fn.KHR_MATERIALS_IRIDESCENCE}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];return o.iridescenceFactor!==void 0&&(t.iridescence=o.iridescenceFactor),o.iridescenceTexture!==void 0&&g.push(i.assignTexture(t,"iridescenceMap",o.iridescenceTexture)),o.iridescenceIor!==void 0&&(t.iridescenceIOR=o.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),o.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=o.iridescenceThicknessMinimum),o.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=o.iridescenceThicknessMaximum),o.iridescenceThicknessTexture!==void 0&&g.push(i.assignTexture(t,"iridescenceThicknessMap",o.iridescenceThicknessTexture)),Promise.all(g)}}class eme{constructor(A){this.parser=A,this.name=Fn.KHR_MATERIALS_SHEEN}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[];t.sheenColor=new Et(0,0,0),t.sheenRoughness=0,t.sheen=1;const o=n.extensions[this.name];if(o.sheenColorFactor!==void 0){const s=o.sheenColorFactor;t.sheenColor.setRGB(s[0],s[1],s[2],Ka)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&g.push(i.assignTexture(t,"sheenColorMap",o.sheenColorTexture,rn)),o.sheenRoughnessTexture!==void 0&&g.push(i.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(g)}}class tme{constructor(A){this.parser=A,this.name=Fn.KHR_MATERIALS_TRANSMISSION}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];return o.transmissionFactor!==void 0&&(t.transmission=o.transmissionFactor),o.transmissionTexture!==void 0&&g.push(i.assignTexture(t,"transmissionMap",o.transmissionTexture)),Promise.all(g)}}class ime{constructor(A){this.parser=A,this.name=Fn.KHR_MATERIALS_VOLUME}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];t.thickness=o.thicknessFactor!==void 0?o.thicknessFactor:0,o.thicknessTexture!==void 0&&g.push(i.assignTexture(t,"thicknessMap",o.thicknessTexture)),t.attenuationDistance=o.attenuationDistance||1/0;const s=o.attenuationColor||[1,1,1];return t.attenuationColor=new Et().setRGB(s[0],s[1],s[2],Ka),Promise.all(g)}}class nme{constructor(A){this.parser=A,this.name=Fn.KHR_MATERIALS_IOR}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const n=this.parser.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=n.extensions[this.name];return t.ior=g.ior!==void 0?g.ior:1.5,Promise.resolve()}}class gme{constructor(A){this.parser=A,this.name=Fn.KHR_MATERIALS_SPECULAR}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];t.specularIntensity=o.specularFactor!==void 0?o.specularFactor:1,o.specularTexture!==void 0&&g.push(i.assignTexture(t,"specularIntensityMap",o.specularTexture));const s=o.specularColorFactor||[1,1,1];return t.specularColor=new Et().setRGB(s[0],s[1],s[2],Ka),o.specularColorTexture!==void 0&&g.push(i.assignTexture(t,"specularColorMap",o.specularColorTexture,rn)),Promise.all(g)}}class ome{constructor(A){this.parser=A,this.name=Fn.EXT_MATERIALS_BUMP}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];return t.bumpScale=o.bumpFactor!==void 0?o.bumpFactor:1,o.bumpTexture!==void 0&&g.push(i.assignTexture(t,"bumpMap",o.bumpTexture)),Promise.all(g)}}class sme{constructor(A){this.parser=A,this.name=Fn.KHR_MATERIALS_ANISOTROPY}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:To}extendMaterialParams(A,t){const i=this.parser,n=i.json.materials[A];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const g=[],o=n.extensions[this.name];return o.anisotropyStrength!==void 0&&(t.anisotropy=o.anisotropyStrength),o.anisotropyRotation!==void 0&&(t.anisotropyRotation=o.anisotropyRotation),o.anisotropyTexture!==void 0&&g.push(i.assignTexture(t,"anisotropyMap",o.anisotropyTexture)),Promise.all(g)}}class ame{constructor(A){this.parser=A,this.name=Fn.KHR_TEXTURE_BASISU}loadTexture(A){const t=this.parser,i=t.json,n=i.textures[A];if(!n.extensions||!n.extensions[this.name])return null;const g=n.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(i.extensionsRequired&&i.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(A,g.source,o)}}class rme{constructor(A){this.parser=A,this.name=Fn.EXT_TEXTURE_WEBP}loadTexture(A){const t=this.name,i=this.parser,n=i.json,g=n.textures[A];if(!g.extensions||!g.extensions[t])return null;const o=g.extensions[t],s=n.images[o.source];let a=i.textureLoader;if(s.uri){const r=i.options.manager.getHandler(s.uri);r!==null&&(a=r)}return i.loadTextureImage(A,o.source,a)}}class Ime{constructor(A){this.parser=A,this.name=Fn.EXT_TEXTURE_AVIF}loadTexture(A){const t=this.name,i=this.parser,n=i.json,g=n.textures[A];if(!g.extensions||!g.extensions[t])return null;const o=g.extensions[t],s=n.images[o.source];let a=i.textureLoader;if(s.uri){const r=i.options.manager.getHandler(s.uri);r!==null&&(a=r)}return i.loadTextureImage(A,o.source,a)}}class Cme{constructor(A){this.name=Fn.EXT_MESHOPT_COMPRESSION,this.parser=A}loadBufferView(A){const t=this.parser.json,i=t.bufferViews[A];if(i.extensions&&i.extensions[this.name]){const n=i.extensions[this.name],g=this.parser.getDependency("buffer",n.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return g.then(function(s){const a=n.byteOffset||0,r=n.byteLength||0,I=n.count,c=n.byteStride,l=new Uint8Array(s,a,r);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(I,c,l,n.mode,n.filter).then(function(B){return B.buffer}):o.ready.then(function(){const B=new ArrayBuffer(I*c);return o.decodeGltfBuffer(new Uint8Array(B),I,c,l,n.mode,n.filter),B})})}else return null}}class cme{constructor(A){this.name=Fn.EXT_MESH_GPU_INSTANCING,this.parser=A}createNodeMesh(A){const t=this.parser.json,i=t.nodes[A];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const n=t.meshes[i.mesh];for(const r of n.primitives)if(r.mode!==UC.TRIANGLES&&r.mode!==UC.TRIANGLE_STRIP&&r.mode!==UC.TRIANGLE_FAN&&r.mode!==void 0)return null;const o=i.extensions[this.name].attributes,s=[],a={};for(const r in o)s.push(this.parser.getDependency("accessor",o[r]).then(I=>(a[r]=I,a[r])));return s.length<1?null:(s.push(this.parser.createNodeMesh(A)),Promise.all(s).then(r=>{const I=r.pop(),c=I.isGroup?I.children:[I],l=r[0].count,B=[];for(const Q of c){const h=new ni,d=new SA,p=new oo,y=new SA(1,1,1),m=new CG(Q.geometry,Q.material,l);for(let D=0;D<l;D++)a.TRANSLATION&&d.fromBufferAttribute(a.TRANSLATION,D),a.ROTATION&&p.fromBufferAttribute(a.ROTATION,D),a.SCALE&&y.fromBufferAttribute(a.SCALE,D),m.setMatrixAt(D,h.compose(d,p,y));for(const D in a)if(D==="_COLOR_0"){const S=a[D];m.instanceColor=new hd(S.array,S.itemSize,S.normalized)}else D!=="TRANSLATION"&&D!=="ROTATION"&&D!=="SCALE"&&Q.geometry.setAttribute(D,a[D]);Bn.prototype.copy.call(m,Q),this.parser.assignFinalMaterial(m),B.push(m)}return I.isGroup?(I.clear(),I.add(...B),I):B[0]}))}}const mmA="glTF",X0=12,EoA={JSON:1313821514,BIN:5130562};class lme{constructor(A){this.name=Fn.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(A,0,X0),i=new TextDecoder;if(this.header={magic:i.decode(new Uint8Array(A.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==mmA)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const n=this.header.length-X0,g=new DataView(A,X0);let o=0;for(;o<n;){const s=g.getUint32(o,!0);o+=4;const a=g.getUint32(o,!0);if(o+=4,a===EoA.JSON){const r=new Uint8Array(A,X0+o,s);this.content=i.decode(r)}else if(a===EoA.BIN){const r=X0+o;this.body=A.slice(r,r+s)}o+=s}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Bme{constructor(A,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Fn.KHR_DRACO_MESH_COMPRESSION,this.json=A,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(A,t){const i=this.json,n=this.dracoLoader,g=A.extensions[this.name].bufferView,o=A.extensions[this.name].attributes,s={},a={},r={};for(const I in o){const c=M4[I]||I.toLowerCase();s[c]=o[I]}for(const I in A.attributes){const c=M4[I]||I.toLowerCase();if(o[I]!==void 0){const l=i.accessors[A.attributes[I]],B=Vm[l.componentType];r[c]=B.name,a[c]=l.normalized===!0}}return t.getDependency("bufferView",g).then(function(I){return new Promise(function(c,l){n.decodeDracoFile(I,function(B){for(const Q in B.attributes){const h=B.attributes[Q],d=a[Q];d!==void 0&&(h.normalized=d)}c(B)},s,r,Ka,l)})})}}class Eme{constructor(){this.name=Fn.KHR_TEXTURE_TRANSFORM}extendTexture(A,t){return(t.texCoord===void 0||t.texCoord===A.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(A=A.clone(),t.texCoord!==void 0&&(A.channel=t.texCoord),t.offset!==void 0&&A.offset.fromArray(t.offset),t.rotation!==void 0&&(A.rotation=t.rotation),t.scale!==void 0&&A.repeat.fromArray(t.scale),A.needsUpdate=!0),A}}class Qme{constructor(){this.name=Fn.KHR_MESH_QUANTIZATION}}class SmA extends oy{constructor(A,t,i,n){super(A,t,i,n)}copySampleValue_(A){const t=this.resultBuffer,i=this.sampleValues,n=this.valueSize,g=A*n*3+n;for(let o=0;o!==n;o++)t[o]=i[g+o];return t}interpolate_(A,t,i,n){const g=this.resultBuffer,o=this.sampleValues,s=this.valueSize,a=s*2,r=s*3,I=n-t,c=(i-t)/I,l=c*c,B=l*c,Q=A*r,h=Q-r,d=-2*B+3*l,p=B-l,y=1-d,m=p-l+c;for(let D=0;D!==s;D++){const S=o[h+D+s],k=o[h+D+a]*I,N=o[Q+D+s],G=o[Q+D]*I;g[D]=y*S+m*k+d*N+p*G}return g}}const ume=new oo;class dme extends SmA{interpolate_(A,t,i,n){const g=super.interpolate_(A,t,i,n);return ume.fromArray(g).normalize().toArray(g),g}}const UC={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Vm={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},QoA={9728:Ss,9729:qg,9984:nG,9985:Hp,9986:Nu,9987:Gr},uoA={33071:oI,33648:ff,10497:Fr},cO={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},M4={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},HQ={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},hme={CUBICSPLINE:void 0,LINEAR:dd,STEP:yf},lO={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function pme(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new xg({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:tl})),e.DefaultMaterial}function Kh(e,A,t){for(const i in t.extensions)e[i]===void 0&&(A.userData.gltfExtensions=A.userData.gltfExtensions||{},A.userData.gltfExtensions[i]=t.extensions[i])}function Tl(e,A){A.extras!==void 0&&(typeof A.extras=="object"?Object.assign(e.userData,A.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+A.extras))}function fme(e,A,t){let i=!1,n=!1,g=!1;for(let r=0,I=A.length;r<I;r++){const c=A[r];if(c.POSITION!==void 0&&(i=!0),c.NORMAL!==void 0&&(n=!0),c.COLOR_0!==void 0&&(g=!0),i&&n&&g)break}if(!i&&!n&&!g)return Promise.resolve(e);const o=[],s=[],a=[];for(let r=0,I=A.length;r<I;r++){const c=A[r];if(i){const l=c.POSITION!==void 0?t.getDependency("accessor",c.POSITION):e.attributes.position;o.push(l)}if(n){const l=c.NORMAL!==void 0?t.getDependency("accessor",c.NORMAL):e.attributes.normal;s.push(l)}if(g){const l=c.COLOR_0!==void 0?t.getDependency("accessor",c.COLOR_0):e.attributes.color;a.push(l)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(a)]).then(function(r){const I=r[0],c=r[1],l=r[2];return i&&(e.morphAttributes.position=I),n&&(e.morphAttributes.normal=c),g&&(e.morphAttributes.color=l),e.morphTargetsRelative=!0,e})}function yme(e,A){if(e.updateMorphTargets(),A.weights!==void 0)for(let t=0,i=A.weights.length;t<i;t++)e.morphTargetInfluences[t]=A.weights[t];if(A.extras&&Array.isArray(A.extras.targetNames)){const t=A.extras.targetNames;if(e.morphTargetInfluences.length===t.length){e.morphTargetDictionary={};for(let i=0,n=t.length;i<n;i++)e.morphTargetDictionary[t[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Dme(e){let A;const t=e.extensions&&e.extensions[Fn.KHR_DRACO_MESH_COMPRESSION];if(t?A="draco:"+t.bufferView+":"+t.indices+":"+BO(t.attributes):A=e.indices+":"+BO(e.attributes)+":"+e.mode,e.targets!==void 0)for(let i=0,n=e.targets.length;i<n;i++)A+=":"+BO(e.targets[i]);return A}function BO(e){let A="";const t=Object.keys(e).sort();for(let i=0,n=t.length;i<n;i++)A+=t[i]+":"+e[t[i]]+";";return A}function N4(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function mme(e){return e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0?"image/jpeg":e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?"image/webp":e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Sme=new ni;class wme{constructor(A={},t={}){this.json=A,this.extensions={},this.plugins={},this.options=t,this.cache=new zDe,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,n=-1,g=!1,o=-1;if(typeof navigator<"u"){const s=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(s)===!0;const a=s.match(/Version\/(\d+)/);n=i&&a?parseInt(a[1],10):-1,g=s.indexOf("Firefox")>-1,o=g?s.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&n<17||g&&o<98?this.textureLoader=new qd(this.options.manager):this.textureLoader=new aV(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new or(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(A){this.extensions=A}setPlugins(A){this.plugins=A}parse(A,t){const i=this,n=this.json,g=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(o){const s={scene:o[0][n.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:n.asset,parser:i,userData:{}};return Kh(g,s,n),Tl(s,n),Promise.all(i._invokeAll(function(a){return a.afterRoot&&a.afterRoot(s)})).then(function(){for(const a of s.scenes)a.updateMatrixWorld();A(s)})}).catch(t)}_markDefs(){const A=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let n=0,g=t.length;n<g;n++){const o=t[n].joints;for(let s=0,a=o.length;s<a;s++)A[o[s]].isBone=!0}for(let n=0,g=A.length;n<g;n++){const o=A[n];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(i[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(A,t){t!==void 0&&(A.refs[t]===void 0&&(A.refs[t]=A.uses[t]=0),A.refs[t]++)}_getNodeRef(A,t,i){if(A.refs[t]<=1)return i;const n=i.clone(),g=(o,s)=>{const a=this.associations.get(o);a!=null&&this.associations.set(s,a);for(const[r,I]of o.children.entries())g(I,s.children[r])};return g(i,n),n.name+="_instance_"+A.uses[t]++,n}_invokeOne(A){const t=Object.values(this.plugins);t.push(this);for(let i=0;i<t.length;i++){const n=A(t[i]);if(n)return n}return null}_invokeAll(A){const t=Object.values(this.plugins);t.unshift(this);const i=[];for(let n=0;n<t.length;n++){const g=A(t[n]);g&&i.push(g)}return i}getDependency(A,t){const i=A+":"+t;let n=this.cache.get(i);if(!n){switch(A){case"scene":n=this.loadScene(t);break;case"node":n=this._invokeOne(function(g){return g.loadNode&&g.loadNode(t)});break;case"mesh":n=this._invokeOne(function(g){return g.loadMesh&&g.loadMesh(t)});break;case"accessor":n=this.loadAccessor(t);break;case"bufferView":n=this._invokeOne(function(g){return g.loadBufferView&&g.loadBufferView(t)});break;case"buffer":n=this.loadBuffer(t);break;case"material":n=this._invokeOne(function(g){return g.loadMaterial&&g.loadMaterial(t)});break;case"texture":n=this._invokeOne(function(g){return g.loadTexture&&g.loadTexture(t)});break;case"skin":n=this.loadSkin(t);break;case"animation":n=this._invokeOne(function(g){return g.loadAnimation&&g.loadAnimation(t)});break;case"camera":n=this.loadCamera(t);break;default:if(n=this._invokeOne(function(g){return g!=this&&g.getDependency&&g.getDependency(A,t)}),!n)throw new Error("Unknown type: "+A);break}this.cache.add(i,n)}return n}getDependencies(A){let t=this.cache.get(A);if(!t){const i=this,n=this.json[A+(A==="mesh"?"es":"s")]||[];t=Promise.all(n.map(function(g,o){return i.getDependency(A,o)})),this.cache.add(A,t)}return t}loadBuffer(A){const t=this.json.buffers[A],i=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&A===0)return Promise.resolve(this.extensions[Fn.KHR_BINARY_GLTF].body);const n=this.options;return new Promise(function(g,o){i.load(AC.resolveURL(t.uri,n.path),g,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(A){const t=this.json.bufferViews[A];return this.getDependency("buffer",t.buffer).then(function(i){const n=t.byteLength||0,g=t.byteOffset||0;return i.slice(g,g+n)})}loadAccessor(A){const t=this,i=this.json,n=this.json.accessors[A];if(n.bufferView===void 0&&n.sparse===void 0){const o=cO[n.type],s=Vm[n.componentType],a=n.normalized===!0,r=new s(n.count*o);return Promise.resolve(new ji(r,o,a))}const g=[];return n.bufferView!==void 0?g.push(this.getDependency("bufferView",n.bufferView)):g.push(null),n.sparse!==void 0&&(g.push(this.getDependency("bufferView",n.sparse.indices.bufferView)),g.push(this.getDependency("bufferView",n.sparse.values.bufferView))),Promise.all(g).then(function(o){const s=o[0],a=cO[n.type],r=Vm[n.componentType],I=r.BYTES_PER_ELEMENT,c=I*a,l=n.byteOffset||0,B=n.bufferView!==void 0?i.bufferViews[n.bufferView].byteStride:void 0,Q=n.normalized===!0;let h,d;if(B&&B!==c){const p=Math.floor(l/B),y="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+p+":"+n.count;let m=t.cache.get(y);m||(h=new r(s,p*B,n.count*B/I),m=new _w(h,B/I),t.cache.add(y,m)),d=new CQ(m,a,l%B/I,Q)}else s===null?h=new r(n.count*a):h=new r(s,l,n.count*a),d=new ji(h,a,Q);if(n.sparse!==void 0){const p=cO.SCALAR,y=Vm[n.sparse.indices.componentType],m=n.sparse.indices.byteOffset||0,D=n.sparse.values.byteOffset||0,S=new y(o[1],m,n.sparse.count*p),k=new r(o[2],D,n.sparse.count*a);s!==null&&(d=new ji(d.array.slice(),d.itemSize,d.normalized)),d.normalized=!1;for(let N=0,G=S.length;N<G;N++){const M=S[N];if(d.setX(M,k[N*a]),a>=2&&d.setY(M,k[N*a+1]),a>=3&&d.setZ(M,k[N*a+2]),a>=4&&d.setW(M,k[N*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}d.normalized=Q}return d})}loadTexture(A){const t=this.json,i=this.options,g=t.textures[A].source,o=t.images[g];let s=this.textureLoader;if(o.uri){const a=i.manager.getHandler(o.uri);a!==null&&(s=a)}return this.loadTextureImage(A,g,s)}loadTextureImage(A,t,i){const n=this,g=this.json,o=g.textures[A],s=g.images[t],a=(s.uri||s.bufferView)+":"+o.sampler;if(this.textureCache[a])return this.textureCache[a];const r=this.loadImageSource(t,i).then(function(I){I.flipY=!1,I.name=o.name||s.name||"",I.name===""&&typeof s.uri=="string"&&s.uri.startsWith("data:image/")===!1&&(I.name=s.uri);const l=(g.samplers||{})[o.sampler]||{};return I.magFilter=QoA[l.magFilter]||qg,I.minFilter=QoA[l.minFilter]||Gr,I.wrapS=uoA[l.wrapS]||Fr,I.wrapT=uoA[l.wrapT]||Fr,I.generateMipmaps=!I.isCompressedTexture&&I.minFilter!==Ss&&I.minFilter!==qg,n.associations.set(I,{textures:A}),I}).catch(function(){return null});return this.textureCache[a]=r,r}loadImageSource(A,t){const i=this,n=this.json,g=this.options;if(this.sourceCache[A]!==void 0)return this.sourceCache[A].then(c=>c.clone());const o=n.images[A],s=self.URL||self.webkitURL;let a=o.uri||"",r=!1;if(o.bufferView!==void 0)a=i.getDependency("bufferView",o.bufferView).then(function(c){r=!0;const l=new Blob([c],{type:o.mimeType});return a=s.createObjectURL(l),a});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+A+" is missing URI and bufferView");const I=Promise.resolve(a).then(function(c){return new Promise(function(l,B){let Q=l;t.isImageBitmapLoader===!0&&(Q=function(h){const d=new Kg(h);d.needsUpdate=!0,l(d)}),t.load(AC.resolveURL(c,g.path),Q,void 0,B)})}).then(function(c){return r===!0&&s.revokeObjectURL(a),Tl(c,o),c.userData.mimeType=o.mimeType||mme(o.uri),c}).catch(function(c){throw console.error("THREE.GLTFLoader: Couldn't load texture",a),c});return this.sourceCache[A]=I,I}assignTexture(A,t,i,n){const g=this;return this.getDependency("texture",i.index).then(function(o){if(!o)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(o=o.clone(),o.channel=i.texCoord),g.extensions[Fn.KHR_TEXTURE_TRANSFORM]){const s=i.extensions!==void 0?i.extensions[Fn.KHR_TEXTURE_TRANSFORM]:void 0;if(s){const a=g.associations.get(o);o=g.extensions[Fn.KHR_TEXTURE_TRANSFORM].extendTexture(o,s),g.associations.set(o,a)}}return n!==void 0&&(o.colorSpace=n),A[t]=o,o})}assignFinalMaterial(A){const t=A.geometry;let i=A.material;const n=t.attributes.tangent===void 0,g=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(A.isPoints){const s="PointsMaterial:"+i.uuid;let a=this.cache.get(s);a||(a=new NE,ho.prototype.copy.call(a,i),a.color.copy(i.color),a.map=i.map,a.sizeAttenuation=!1,this.cache.add(s,a)),i=a}else if(A.isLine){const s="LineBasicMaterial:"+i.uuid;let a=this.cache.get(s);a||(a=new es,ho.prototype.copy.call(a,i),a.color.copy(i.color),a.map=i.map,this.cache.add(s,a)),i=a}if(n||g||o){let s="ClonedMaterial:"+i.uuid+":";n&&(s+="derivative-tangents:"),g&&(s+="vertex-colors:"),o&&(s+="flat-shading:");let a=this.cache.get(s);a||(a=i.clone(),g&&(a.vertexColors=!0),o&&(a.flatShading=!0),n&&(a.normalScale&&(a.normalScale.y*=-1),a.clearcoatNormalScale&&(a.clearcoatNormalScale.y*=-1)),this.cache.add(s,a),this.associations.set(a,this.associations.get(i))),i=a}A.material=i}getMaterialType(){return xg}loadMaterial(A){const t=this,i=this.json,n=this.extensions,g=i.materials[A];let o;const s={},a=g.extensions||{},r=[];if(a[Fn.KHR_MATERIALS_UNLIT]){const c=n[Fn.KHR_MATERIALS_UNLIT];o=c.getMaterialType(),r.push(c.extendParams(s,g,t))}else{const c=g.pbrMetallicRoughness||{};if(s.color=new Et(1,1,1),s.opacity=1,Array.isArray(c.baseColorFactor)){const l=c.baseColorFactor;s.color.setRGB(l[0],l[1],l[2],Ka),s.opacity=l[3]}c.baseColorTexture!==void 0&&r.push(t.assignTexture(s,"map",c.baseColorTexture,rn)),s.metalness=c.metallicFactor!==void 0?c.metallicFactor:1,s.roughness=c.roughnessFactor!==void 0?c.roughnessFactor:1,c.metallicRoughnessTexture!==void 0&&(r.push(t.assignTexture(s,"metalnessMap",c.metallicRoughnessTexture)),r.push(t.assignTexture(s,"roughnessMap",c.metallicRoughnessTexture))),o=this._invokeOne(function(l){return l.getMaterialType&&l.getMaterialType(A)}),r.push(Promise.all(this._invokeAll(function(l){return l.extendMaterialParams&&l.extendMaterialParams(A,s)})))}g.doubleSided===!0&&(s.side=AI);const I=g.alphaMode||lO.OPAQUE;if(I===lO.BLEND?(s.transparent=!0,s.depthWrite=!1):(s.transparent=!1,I===lO.MASK&&(s.alphaTest=g.alphaCutoff!==void 0?g.alphaCutoff:.5)),g.normalTexture!==void 0&&o!==kg&&(r.push(t.assignTexture(s,"normalMap",g.normalTexture)),s.normalScale=new lt(1,1),g.normalTexture.scale!==void 0)){const c=g.normalTexture.scale;s.normalScale.set(c,c)}if(g.occlusionTexture!==void 0&&o!==kg&&(r.push(t.assignTexture(s,"aoMap",g.occlusionTexture)),g.occlusionTexture.strength!==void 0&&(s.aoMapIntensity=g.occlusionTexture.strength)),g.emissiveFactor!==void 0&&o!==kg){const c=g.emissiveFactor;s.emissive=new Et().setRGB(c[0],c[1],c[2],Ka)}return g.emissiveTexture!==void 0&&o!==kg&&r.push(t.assignTexture(s,"emissiveMap",g.emissiveTexture,rn)),Promise.all(r).then(function(){const c=new o(s);return g.name&&(c.name=g.name),Tl(c,g),t.associations.set(c,{materials:A}),g.extensions&&Kh(n,c,g),c})}createUniqueName(A){const t=zn.sanitizeNodeName(A||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(A){const t=this,i=this.extensions,n=this.primitiveCache;function g(s){return i[Fn.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(s,t).then(function(a){return doA(a,s,t)})}const o=[];for(let s=0,a=A.length;s<a;s++){const r=A[s],I=Dme(r),c=n[I];if(c)o.push(c.promise);else{let l;r.extensions&&r.extensions[Fn.KHR_DRACO_MESH_COMPRESSION]?l=g(r):l=doA(new Ni,r,t),n[I]={primitive:r,promise:l},o.push(l)}}return Promise.all(o)}loadMesh(A){const t=this,i=this.json,n=this.extensions,g=i.meshes[A],o=g.primitives,s=[];for(let a=0,r=o.length;a<r;a++){const I=o[a].material===void 0?pme(this.cache):this.getDependency("material",o[a].material);s.push(I)}return s.push(t.loadGeometries(o)),Promise.all(s).then(function(a){const r=a.slice(0,a.length-1),I=a[a.length-1],c=[];for(let B=0,Q=I.length;B<Q;B++){const h=I[B],d=o[B];let p;const y=r[B];if(d.mode===UC.TRIANGLES||d.mode===UC.TRIANGLE_STRIP||d.mode===UC.TRIANGLE_FAN||d.mode===void 0)p=g.isSkinnedMesh===!0?new jx(h,y):new pn(h,y),p.isSkinnedMesh===!0&&p.normalizeSkinWeights(),d.mode===UC.TRIANGLE_STRIP?p.geometry=BoA(p.geometry,oG):d.mode===UC.TRIANGLE_FAN&&(p.geometry=BoA(p.geometry,Df));else if(d.mode===UC.LINES)p=new EI(h,y);else if(d.mode===UC.LINE_STRIP)p=new yB(h,y);else if(d.mode===UC.LINE_LOOP)p=new Zx(h,y);else if(d.mode===UC.POINTS)p=new Pp(h,y);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+d.mode);Object.keys(p.geometry.morphAttributes).length>0&&yme(p,g),p.name=t.createUniqueName(g.name||"mesh_"+A),Tl(p,g),d.extensions&&Kh(n,p,d),t.assignFinalMaterial(p),c.push(p)}for(let B=0,Q=c.length;B<Q;B++)t.associations.set(c[B],{meshes:A,primitives:B});if(c.length===1)return g.extensions&&Kh(n,c[0],g),c[0];const l=new sa;g.extensions&&Kh(n,l,g),t.associations.set(l,{meshes:A});for(let B=0,Q=c.length;B<Q;B++)l.add(c[B]);return l})}loadCamera(A){let t;const i=this.json.cameras[A],n=i[i.type];if(!n){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return i.type==="perspective"?t=new Wo(VC.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):i.type==="orthographic"&&(t=new Hd(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),Tl(t,i),Promise.resolve(t)}loadSkin(A){const t=this.json.skins[A],i=[];for(let n=0,g=t.joints.length;n<g;n++)i.push(this._loadNodeShallow(t.joints[n]));return t.inverseBindMatrices!==void 0?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(n){const g=n.pop(),o=n,s=[],a=[];for(let r=0,I=o.length;r<I;r++){const c=o[r];if(c){s.push(c);const l=new ni;g!==null&&l.fromArray(g.array,r*16),a.push(l)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[r])}return new Jw(s,a)})}loadAnimation(A){const t=this.json,i=this,n=t.animations[A],g=n.name?n.name:"animation_"+A,o=[],s=[],a=[],r=[],I=[];for(let c=0,l=n.channels.length;c<l;c++){const B=n.channels[c],Q=n.samplers[B.sampler],h=B.target,d=h.node,p=n.parameters!==void 0?n.parameters[Q.input]:Q.input,y=n.parameters!==void 0?n.parameters[Q.output]:Q.output;h.node!==void 0&&(o.push(this.getDependency("node",d)),s.push(this.getDependency("accessor",p)),a.push(this.getDependency("accessor",y)),r.push(Q),I.push(h))}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(a),Promise.all(r),Promise.all(I)]).then(function(c){const l=c[0],B=c[1],Q=c[2],h=c[3],d=c[4],p=[];for(let m=0,D=l.length;m<D;m++){const S=l[m],k=B[m],N=Q[m],G=h[m],M=d[m];if(S===void 0)continue;S.updateMatrix&&S.updateMatrix();const w=i._createAnimationTracks(S,k,N,G,M);if(w)for(let b=0;b<w.length;b++)p.push(w[b])}const y=new fd(g,void 0,p);return Tl(y,n),y})}createNodeMesh(A){const t=this.json,i=this,n=t.nodes[A];return n.mesh===void 0?null:i.getDependency("mesh",n.mesh).then(function(g){const o=i._getNodeRef(i.meshCache,n.mesh,g);return n.weights!==void 0&&o.traverse(function(s){if(s.isMesh)for(let a=0,r=n.weights.length;a<r;a++)s.morphTargetInfluences[a]=n.weights[a]}),o})}loadNode(A){const t=this.json,i=this,n=t.nodes[A],g=i._loadNodeShallow(A),o=[],s=n.children||[];for(let r=0,I=s.length;r<I;r++)o.push(i.getDependency("node",s[r]));const a=n.skin===void 0?Promise.resolve(null):i.getDependency("skin",n.skin);return Promise.all([g,Promise.all(o),a]).then(function(r){const I=r[0],c=r[1],l=r[2];l!==null&&I.traverse(function(B){B.isSkinnedMesh&&B.bind(l,Sme)});for(let B=0,Q=c.length;B<Q;B++)I.add(c[B]);return I})}_loadNodeShallow(A){const t=this.json,i=this.extensions,n=this;if(this.nodeCache[A]!==void 0)return this.nodeCache[A];const g=t.nodes[A],o=g.name?n.createUniqueName(g.name):"",s=[],a=n._invokeOne(function(r){return r.createNodeMesh&&r.createNodeMesh(A)});return a&&s.push(a),g.camera!==void 0&&s.push(n.getDependency("camera",g.camera).then(function(r){return n._getNodeRef(n.cameraCache,g.camera,r)})),n._invokeAll(function(r){return r.createNodeAttachment&&r.createNodeAttachment(A)}).forEach(function(r){s.push(r)}),this.nodeCache[A]=Promise.all(s).then(function(r){let I;if(g.isBone===!0?I=new IG:r.length>1?I=new sa:r.length===1?I=r[0]:I=new Bn,I!==r[0])for(let c=0,l=r.length;c<l;c++)I.add(r[c]);if(g.name&&(I.userData.name=g.name,I.name=o),Tl(I,g),g.extensions&&Kh(i,I,g),g.matrix!==void 0){const c=new ni;c.fromArray(g.matrix),I.applyMatrix4(c)}else g.translation!==void 0&&I.position.fromArray(g.translation),g.rotation!==void 0&&I.quaternion.fromArray(g.rotation),g.scale!==void 0&&I.scale.fromArray(g.scale);if(!n.associations.has(I))n.associations.set(I,{});else if(g.mesh!==void 0&&n.meshCache.refs[g.mesh]>1){const c=n.associations.get(I);n.associations.set(I,{...c})}return n.associations.get(I).nodes=A,I}),this.nodeCache[A]}loadScene(A){const t=this.extensions,i=this.json.scenes[A],n=this,g=new sa;i.name&&(g.name=n.createUniqueName(i.name)),Tl(g,i),i.extensions&&Kh(t,g,i);const o=i.nodes||[],s=[];for(let a=0,r=o.length;a<r;a++)s.push(n.getDependency("node",o[a]));return Promise.all(s).then(function(a){for(let I=0,c=a.length;I<c;I++)g.add(a[I]);const r=I=>{const c=new Map;for(const[l,B]of n.associations)(l instanceof ho||l instanceof Kg)&&c.set(l,B);return I.traverse(l=>{const B=n.associations.get(l);B!=null&&c.set(l,B)}),c};return n.associations=r(g),g})}_createAnimationTracks(A,t,i,n,g){const o=[],s=A.name?A.name:A.uuid,a=[];HQ[g.path]===HQ.weights?A.traverse(function(l){l.morphTargetInfluences&&a.push(l.name?l.name:l.uuid)}):a.push(s);let r;switch(HQ[g.path]){case HQ.weights:r=cQ;break;case HQ.rotation:r=DB;break;case HQ.translation:case HQ.scale:r=mB;break;default:switch(i.itemSize){case 1:r=cQ;break;case 2:case 3:default:r=mB;break}break}const I=n.interpolation!==void 0?hme[n.interpolation]:dd,c=this._getArrayFromAccessor(i);for(let l=0,B=a.length;l<B;l++){const Q=new r(a[l]+"."+HQ[g.path],t.array,c,I);n.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(Q),o.push(Q)}return o}_getArrayFromAccessor(A){let t=A.array;if(A.normalized){const i=N4(t.constructor),n=new Float32Array(t.length);for(let g=0,o=t.length;g<o;g++)n[g]=t[g]*i;t=n}return t}_createCubicSplineTrackInterpolant(A){A.createInterpolant=function(i){const n=this instanceof DB?dme:SmA;return new n(this.times,this.values,this.getValueSize()/3,i)},A.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function kme(e,A,t){const i=A.attributes,n=new Ag;if(i.POSITION!==void 0){const s=t.json.accessors[i.POSITION],a=s.min,r=s.max;if(a!==void 0&&r!==void 0){if(n.set(new SA(a[0],a[1],a[2]),new SA(r[0],r[1],r[2])),s.normalized){const I=N4(Vm[s.componentType]);n.min.multiplyScalar(I),n.max.multiplyScalar(I)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const g=A.targets;if(g!==void 0){const s=new SA,a=new SA;for(let r=0,I=g.length;r<I;r++){const c=g[r];if(c.POSITION!==void 0){const l=t.json.accessors[c.POSITION],B=l.min,Q=l.max;if(B!==void 0&&Q!==void 0){if(a.setX(Math.max(Math.abs(B[0]),Math.abs(Q[0]))),a.setY(Math.max(Math.abs(B[1]),Math.abs(Q[1]))),a.setZ(Math.max(Math.abs(B[2]),Math.abs(Q[2]))),l.normalized){const h=N4(Vm[l.componentType]);a.multiplyScalar(h)}s.max(a)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(s)}e.boundingBox=n;const o=new xs;n.getCenter(o.center),o.radius=n.min.distanceTo(n.max)/2,e.boundingSphere=o}function doA(e,A,t){const i=A.attributes,n=[];function g(o,s){return t.getDependency("accessor",o).then(function(a){e.setAttribute(s,a)})}for(const o in i){const s=M4[o]||o.toLowerCase();s in e.attributes||n.push(g(i[o],s))}if(A.indices!==void 0&&!e.index){const o=t.getDependency("accessor",A.indices).then(function(s){e.setIndex(s)});n.push(o)}return Un.workingColorSpace!==Ka&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Un.workingColorSpace}" not supported.`),Tl(e,A),kme(e,A,t),Promise.all(n).then(function(){return A.targets!==void 0?fme(e,A.targets,t):e})}class Mme extends rG{constructor(){super();const A=new sI;A.deleteAttribute("uv");const t=new xg({side:Ua}),i=new xg,n=new BG(16777215,900,28,2);n.position.set(.418,16.199,.3),this.add(n);const g=new pn(A,t);g.position.set(-.757,13.219,.717),g.scale.set(31.713,28.305,28.591),this.add(g);const o=new CG(A,i,6),s=new Bn;s.position.set(-10.906,2.009,1.846),s.rotation.set(0,-.195,0),s.scale.set(2.328,7.905,4.651),s.updateMatrix(),o.setMatrixAt(0,s.matrix),s.position.set(-5.607,-.754,-.758),s.rotation.set(0,.994,0),s.scale.set(1.97,1.534,3.955),s.updateMatrix(),o.setMatrixAt(1,s.matrix),s.position.set(6.167,.857,7.803),s.rotation.set(0,.561,0),s.scale.set(3.927,6.285,3.687),s.updateMatrix(),o.setMatrixAt(2,s.matrix),s.position.set(-2.017,.018,6.124),s.rotation.set(0,.333,0),s.scale.set(2.002,4.566,2.064),s.updateMatrix(),o.setMatrixAt(3,s.matrix),s.position.set(2.291,-.756,-2.621),s.rotation.set(0,-.286,0),s.scale.set(1.546,1.552,1.496),s.updateMatrix(),o.setMatrixAt(4,s.matrix),s.position.set(-2.193,-.369,-5.547),s.rotation.set(0,.516,0),s.scale.set(3.875,3.487,2.986),s.updateMatrix(),o.setMatrixAt(5,s.matrix),this.add(o);const a=new pn(A,SD(50));a.position.set(-16.116,14.37,8.208),a.scale.set(.1,2.428,2.739),this.add(a);const r=new pn(A,SD(50));r.position.set(-16.109,18.021,-8.207),r.scale.set(.1,2.425,2.751),this.add(r);const I=new pn(A,SD(17));I.position.set(14.904,12.198,-1.832),I.scale.set(.15,4.265,6.331),this.add(I);const c=new pn(A,SD(43));c.position.set(-.462,8.89,14.52),c.scale.set(4.38,5.441,.088),this.add(c);const l=new pn(A,SD(20));l.position.set(3.235,11.486,-12.541),l.scale.set(2.5,2,.1),this.add(l);const B=new pn(A,SD(100));B.position.set(0,20,0),B.scale.set(1,.1,1),this.add(B)}dispose(){const A=new Set;this.traverse(t=>{t.isMesh&&(A.add(t.geometry),A.add(t.material))});for(const t of A)t.dispose()}}function SD(e){return new XW({color:0,emissive:16777215,emissiveIntensity:e})}const Nme=1,xJ={"crimson-dominion":{body:9047834,accent:16720440,emissive:5570568,metalness:.3,roughness:.7,flame:16724770},"silver-pact":{body:13161180,accent:6976640,emissive:2107440,metalness:.55,roughness:.55,flame:12571903},"azure-sovereignty":{body:1063562,accent:5154303,emissive:662602,metalness:.4,roughness:.65,flame:3386111},"golden-imperium":{body:12093466,accent:16766515,emissive:4861960,metalness:.6,roughness:.55,flame:16763972},"emerald-collective":{body:1006128,accent:5635994,emissive:665624,metalness:.3,roughness:.7,flame:6750122},"void-enclave":{body:1707818,accent:12796159,emissive:2754628,metalness:.45,roughness:.65,flame:12607743}},Rme=.62,Gme=320,bme=.18,Ume=260,vme=.55,hoA=.18,Kme=.75;class Fme{constructor(){Oi(this,"renderer",null);Oi(this,"scene");Oi(this,"camera");Oi(this,"ambient");Oi(this,"keyLight");Oi(this,"rimLight");Oi(this,"shipTemplate",null);Oi(this,"shipPool",[]);Oi(this,"shipMeshById",new Map);Oi(this,"freeShipMeshes",[]);Oi(this,"modelReady",!1);Oi(this,"modelPromise",null);Oi(this,"widthCss",0);Oi(this,"heightCss",0);Oi(this,"mountedCanvas",null);Oi(this,"shipMaterials",[]);Oi(this,"thrusterGlowMat",null);Oi(this,"cockpitMat",null);Oi(this,"currentScheme",xJ["crimson-dominion"]);Oi(this,"currentFaction","crimson-dominion");Oi(this,"contextLost",!1);Oi(this,"onContextLost",null);Oi(this,"onContextRestored",null);Oi(this,"_loggedFirstRender",!1);this.scene=new rG,this.camera=new Hd(-1,1,1,-1,.1,2e3),this.camera.position.set(0,0,500),this.camera.lookAt(0,0,0),this.ambient=new sV(6977704,.32),this.keyLight=new zp(16773588,1.95),this.keyLight.position.set(2,4,6),this.rimLight=new zp(7129343,1.05),this.rimLight.position.set(-3,-1,-2);const A=new zp(16751962,.45);A.position.set(0,-5,2);const t=new gV(6983360,1053208,.65);this.scene.add(this.ambient,this.keyLight,this.rimLight,A,t),this.scene.fog=new aG(329485,500.55,501.05)}mount(A,t){return this.mountedCanvas===A&&this.renderer?this.modelPromise??Promise.resolve():(this.renderer&&this.renderer.dispose(),this.renderer=new dV({canvas:A,alpha:!0,antialias:!0,premultipliedAlpha:!0,powerPreference:"high-performance"}),this.renderer.setClearColor(0,0),this.renderer.toneMapping=iy,this.renderer.toneMappingExposure=1.18,this.renderer.outputColorSpace=rn,this.mountedCanvas=A,this.contextLost=!1,this.onContextLost=i=>{i.preventDefault(),this.contextLost=!0},this.onContextRestored=()=>{this.contextLost=!1},A.addEventListener("webglcontextlost",this.onContextLost,!1),A.addEventListener("webglcontextrestored",this.onContextRestored,!1),this.modelPromise||(this.modelPromise=this.loadModel(t)),this.modelPromise)}resize(A,t,i){this.renderer&&(A<=0||t<=0||(console.log("[Raid3D] resize",{widthCss:A,heightCss:t,dpr:i}),this.widthCss=A,this.heightCss=t,this.renderer.setPixelRatio(i),this.renderer.setSize(A,t,!1),this.camera.left=-A/2,this.camera.right=A/2,this.camera.top=t/2,this.camera.bottom=-t/2,this.camera.updateProjectionMatrix()))}setShipPoses(A){if(!this.modelReady||!this.shipTemplate)return;const t=new Set(A.map(i=>i.id));for(const[i,n]of this.shipMeshById)t.has(i)||(this.shipMeshById.delete(i),n.visible=!1,this.freeShipMeshes.push(n));for(const i of A){if(this.shipMeshById.has(i.id))continue;let n=this.freeShipMeshes.pop();n||(n=this.shipTemplate.clone(!0),this.shipPool.push(n),this.scene.add(n)),this.shipMeshById.set(i.id,n)}for(let i=0;i<A.length;i++){const n=A[i],g=this.shipMeshById.get(n.id);if(!g)continue;const o=200,s=n.x<-o||n.x>this.widthCss+o,a=n.y<-o||n.y>this.heightCss+o;if(s||a){g.visible=!1;continue}g.visible=!0,g.position.x=n.x-this.widthCss/2,g.position.y=-(n.y-this.heightCss/2),g.position.z=-n.z;const r=performance.now()*.001,I=i*1.731,c=Math.max(0,Math.min(1,1-n.z/Nme)),l=Math.min(c,.85),B=l*l*l,h=(.04+(8.4-.04)*B)*n.sizeScale*Kme;g.scale.setScalar(h);const d=poA(n.bankVx/Gme,-1,1)*Rme,p=.012*c,y=.04*c,m=c>.55?-((c-.55)/.45)*.22:0,D=poA(n.visualVy/Ume,-1,1)*bme+Math.sin(r*1.7+I)*p+m,S=d*vme+Math.sin(r*1.3+I*.7)*p;let k=d+Math.sin(r*.9+I*1.2)*y;if(n.spinRate&&n.spawnTime){const G=(performance.now()-n.spawnTime)/1e3,M=Math.PI*2.5,w=n.spinRate*G,b=Math.sign(w)*Math.min(Math.abs(w),M);k+=b}const N=g.userData;if(N.spawnTime!==n.spawnTime&&(N.spawnTime=n.spawnTime,N.rot&&(N.rot.init=!1)),!N.rot||!N.rot.init)N.rot={p:D,y:S,r:k,init:!0};else{const M=n.visualVx*n.bankVx<0&&Math.abs(n.bankVx)>70?.38:hoA;N.rot.p+=(D-N.rot.p)*hoA,N.rot.y+=(S-N.rot.y)*M,N.rot.r+=(k-N.rot.r)*M}g.rotation.set(N.rot.p,N.rot.y,N.rot.r,"YXZ")}}setShipPose(A){this.setShipPoses([A])}setVisible(A){for(const t of this.shipPool)t.visible=A}setFactionScheme(A){const t=xJ[A];t&&(this.currentScheme=t,this.currentFaction=A,this.applyFactionColor())}applyFactionColor(){const A=this.currentScheme,t=new Et(A.body),i=new Et(A.accent),n=new Et(A.emissive);if(this.shipMaterials.length===1&&!!this.shipMaterials[0].map){const o=new Et(A.accent);this.shipMaterials[0].emissive.copy(o),this.shipMaterials[0].needsUpdate=!0}else for(let o=0;o<this.shipMaterials.length;o++){const s=this.shipMaterials[o],a=this.shipMaterials.length>1&&o%2===1,r=a?i:t,I=r.clone().lerp(new Et(16777215),a?.22:.16);I.multiplyScalar(a?1.28:1.2),s.color.copy(I),s.emissive.copy(n).lerp(r,a?.5:.35),s.emissiveIntensity=a?.42:.28,s.metalness=A.metalness,s.roughness=Math.max(.32,A.roughness*.82),s.envMapIntensity=Math.max(s.envMapIntensity,a?1.05:.9),s.needsUpdate=!0}if(this.thrusterGlowMat&&(this.thrusterGlowMat.color.set(A.flame),this.thrusterGlowMat.needsUpdate=!0),this.cockpitMat){const o=new Et(A.accent);this.cockpitMat.color.copy(o).lerp(new Et(16777215),.2).multiplyScalar(.42),this.cockpitMat.emissive.copy(o),this.cockpitMat.emissiveIntensity=.8,this.cockpitMat.envMapIntensity=Math.max(this.cockpitMat.envMapIntensity,1.1),this.cockpitMat.needsUpdate=!0}}render(){if(this.renderer&&!this.contextLost&&!(this.widthCss<=0||this.heightCss<=0)){if(this._loggedFirstRender||(this._loggedFirstRender=!0,console.log("[Raid3D] first render",{w:this.widthCss,h:this.heightCss,sceneChildren:this.scene.children.length,poolSize:this.shipPool.length})),this.thrusterGlowMat){const A=performance.now()*.001,t=.88+.12*Math.sin(A*28)*Math.sin(A*11),i=.88+.12*Math.sin(A*4.2)*Math.cos(A*2.1);this.thrusterGlowMat.opacity=.82*t*i}try{this.renderer.render(this.scene,this.camera)}catch(A){this.contextLost=!0,console.warn("[Raid3D] render aborted (context likely lost)",A)}}}dispose(){for(const A of this.shipPool)this.scene.remove(A),A.traverse(t=>{var n,g,o;const i=t;if(i.isMesh){(g=(n=i.geometry)==null?void 0:n.dispose)==null||g.call(n);const s=i.material;Array.isArray(s)?s.forEach(a=>{var r;return(r=a.dispose)==null?void 0:r.call(a)}):(o=s==null?void 0:s.dispose)==null||o.call(s)}});if(this.shipPool=[],this.shipMeshById.clear(),this.freeShipMeshes=[],this.shipTemplate=null,this.mountedCanvas&&(this.onContextLost&&this.mountedCanvas.removeEventListener("webglcontextlost",this.onContextLost,!1),this.onContextRestored&&this.mountedCanvas.removeEventListener("webglcontextrestored",this.onContextRestored,!1)),this.onContextLost=null,this.onContextRestored=null,this.renderer){try{const A=this.renderer.getContext().getExtension("WEBGL_lose_context");A==null||A.loseContext()}catch{}this.renderer.dispose()}this.renderer=null,this.modelReady=!1,this.modelPromise=null,this.mountedCanvas=null}async loadModel(A){if(/\.glb($|\?)/i.test(A))return this.loadGLBModel(A);const t=new PDe;let i;try{try{const x=await fetch(A,{method:"HEAD"});x.ok||console.warn("[Raid3D] HEAD probe failed",A,x.status,x.statusText)}catch(x){console.warn("[Raid3D] HEAD probe threw",A,x)}i=await t.loadAsync(A),console.log("[Raid3D] OBJ loaded",A)}catch(x){console.warn("[Raid3D] OBJ load failed, using fallback box",A,x);const T=new pn(new sI(.2,.2,.2),new xg({color:16711935,emissive:4456516})),z=new sa;z.add(T),this.shipTemplate=z,this.modelReady=!0;return}const n=new Ag().setFromObject(i),g=new SA;n.getSize(g);const o=150,s=Math.max(g.x,g.y,g.z),a=s>0?o/s:1;i.scale.set(a*.7,a*1.25,a);const r=new Ag().setFromObject(i),I=new SA;r.getCenter(I),i.position.sub(I),i.rotation.x=0;const c=new sa;c.add(i),this.shipMaterials=[];const l=0,B=1,Q=2,h=3,d=new xg({color:12700640,metalness:.42,roughness:.52,emissive:1185831,emissiveIntensity:.28,envMapIntensity:.9}),p=new xg({color:1778224,metalness:.42,roughness:.16,emissive:791072,emissiveIntensity:.8,envMapIntensity:1.1}),y=new xg({color:10398659,metalness:.38,roughness:.56,emissive:1054506,emissiveIntensity:.42,envMapIntensity:1.05}),m=new xg({color:5858420,metalness:.55,roughness:.42,emissive:4856325,emissiveIntensity:1,envMapIntensity:.95}),D=_me().albedo;EO(d,D,.03,.62),EO(y,D,.03,.56),EO(m,D,.038,.52);const S=[d,p,y,m];this.shipMaterials.push(d,y,m),this.cockpitMat=p;let k=0;c.traverse(x=>{if(x.type!=="Mesh")return;const T=x,z=T.geometry,Z=z.getAttribute("position");if(!Z)return;z.computeBoundingBox();const eA=z.boundingBox,aA=(eA.min.x+eA.max.x)/2,sA=eA.max.x-eA.min.x||1,pA=eA.max.y-eA.min.y||1,gA=eA.max.z-eA.min.z||1,yA=Z.count/3,fA=[[],[],[],[]];for(let W=0;W<yA;W++){const $=W*3,L=Z.getX($),H=Z.getY($),P=Z.getZ($),tA=Z.getX($+1),iA=Z.getY($+1),oA=Z.getZ($+1),IA=Z.getX($+2),CA=Z.getY($+2),_A=Z.getZ($+2),uA=(L+tA+IA)/3,X=(H+iA+CA)/3,O=(P+oA+_A)/3,cA=(uA-aA)/(sA*.5),wA=(X-eA.min.y)/pA,xA=(O-eA.min.z)/gA;let YA;xA<.22?YA=h:wA>.7&&xA>.3&&xA<.78&&Math.abs(cA)<.35?YA=B:Math.abs(cA)>.55&&wA<.55?YA=Q:YA=l,fA[YA].push($,$+1,$+2)}const RA=[],qA=[];for(let W=0;W<4;W++)if(fA[W].length!==0){qA.push({start:RA.length,count:fA[W].length,matIndex:W});for(const $ of fA[W])RA.push($)}z.setIndex(new ji(new Uint32Array(RA),1)),z.clearGroups();for(const W of qA)z.addGroup(W.start,W.count,W.matIndex);z.computeVertexNormals(),T.material=S,T.frustumCulled=!1,k++}),this.applyFactionColor(),console.log("[Raid3D] OBJ segmented meshCount",k);const N=new Ag().setFromObject(c),G=Math.max(.1,N.max.z-N.min.z),M=N.min.z,w=G*.85,b=document.createElement("canvas");b.width=128,b.height=128;const _=b.getContext("2d");if(_){const x=_.createRadialGradient(64,64,0,64,64,64);x.addColorStop(0,"rgba(255,200,140,1)"),x.addColorStop(.35,"rgba(255,140,60,0.55)"),x.addColorStop(1,"rgba(255,80,20,0)"),_.fillStyle=x,_.fillRect(0,0,128,128)}const K=new pd(b);K.colorSpace=rn;const J=new FN({map:K,color:16755268,transparent:!0,blending:io,depthWrite:!1,fog:!1});this.thrusterGlowMat=J;const q=new hJ(J),v=w*1.6;q.scale.set(v,v,1),q.position.set(0,0,M-w*.15),q.renderOrder=0,c.add(q),this.shipTemplate=c,this.modelReady=!0;const U=new Ag().setFromObject(c);console.log("[Raid3D] mesh added",{children:this.scene.children.length,bbox:{min:U.min.toArray(),max:U.max.toArray()}})}async loadGLBModel(A){if(!this.renderer)throw new Error("renderer not mounted");const t=MV[this.currentFaction],i=A.match(/\/ships\/([^/]+)\//),n=i?i[1]:t.pack,g=`/models/zentara/ships/${n}/Textures/${n}`,o={diffuse:`${g}_${t.skinColor}.webp`,normal:`${g}_Normal.webp`,metallic:`${g}_Metallic.webp`,roughness:`${g}_Roughness.webp`,emission:`${g}_${t.emissionSuffix}.webp`},s=new jDe,a=new qd,r=(x,T)=>new Promise((z,Z)=>{a.load(x,eA=>{T&&(eA.colorSpace=rn),eA.flipY=!1,eA.anisotropy=8,eA.minFilter=Gr,eA.magFilter=qg,eA.generateMipmaps=!0,z(eA)},void 0,Z)});let I,c;try{const[x,T,z,Z,eA,aA]=await Promise.all([s.loadAsync(A),r(o.diffuse,!0),r(o.normal,!1),r(o.metallic,!1),r(o.roughness,!1),r(o.emission,!0)]);I=x.scene,c={diffuse:T,normal:z,metallic:Z,roughness:eA,emission:aA},console.log("[Raid3D] GLB loaded",A,"faction",this.currentFaction)}catch(x){console.warn("[Raid3D] GLB load failed, using fallback box",A,x);const T=new pn(new sI(.2,.2,.2),new xg({color:16711935,emissive:4456516})),z=new sa;z.add(T),this.shipTemplate=z,this.modelReady=!0;return}const l=new Et(this.currentScheme.accent),B=new xg({map:c.diffuse,normalMap:c.normal,metalnessMap:c.metallic,roughnessMap:c.roughness,emissiveMap:c.emission,emissive:l,emissiveIntensity:1.2,metalness:1,roughness:1,envMapIntensity:1});this.shipMaterials=[B],this.cockpitMat=null,I.traverse(x=>{const T=x;T.isMesh&&(T.material=B,T.frustumCulled=!1)});const Q=new mJ(this.renderer);Q.compileEquirectangularShader();const h=Q.fromScene(new Mme,.04).texture;this.scene.environment=h,Q.dispose();const d=new Ag().setFromObject(I),p=new SA;d.getSize(p);const y=Math.max(p.x,p.y,p.z),m=y>0?150/y:1;I.scale.setScalar(m),I.rotation.set(0,0,0),I.updateMatrixWorld(!0);const D=new Ag().setFromObject(I),S=new SA;D.getCenter(S),I.position.sub(S);const k=new sa;k.add(I);const N=new Ag().setFromObject(k),G=Math.max(.1,N.max.z-N.min.z),M=N.min.z,w=G*.85,b=document.createElement("canvas");b.width=128,b.height=128;const _=b.getContext("2d");if(_){const x=_.createRadialGradient(64,64,0,64,64,64);x.addColorStop(0,"rgba(255,200,140,1)"),x.addColorStop(.35,"rgba(255,140,60,0.55)"),x.addColorStop(1,"rgba(255,80,20,0)"),_.fillStyle=x,_.fillRect(0,0,128,128)}const K=new pd(b);K.colorSpace=rn;const J=new FN({map:K,color:this.currentScheme.flame,transparent:!0,blending:io,depthWrite:!1,fog:!1});this.thrusterGlowMat=J;const q=new hJ(J),v=w*1.6;q.scale.set(v,v,1),q.position.set(0,0,M-w*.15),k.add(q),this.shipTemplate=k,this.modelReady=!0;const U=new Ag().setFromObject(k);console.log("[Raid3D] GLB mesh added",{bbox:{min:U.min.toArray(),max:U.max.toArray()}})}}function poA(e,A,t){return e<A?A:e>t?t:e}function EO(e,A,t,i){A.wrapS=A.wrapT=Fr,e.onBeforeCompile=n=>{n.uniforms.uPlatingTex={value:A},n.uniforms.uPlatingScale={value:t},n.uniforms.uPlatingStrength={value:i},n.vertexShader=n.vertexShader.replace("#include <common>",`#include <common>
varying vec3 vLocalPos;
varying vec3 vLocalNormal;`).replace("#include <begin_vertex>",`#include <begin_vertex>
vLocalPos = position;
vLocalNormal = normal;`),n.fragmentShader=n.fragmentShader.replace("#include <common>",`#include <common>
varying vec3 vLocalPos;
varying vec3 vLocalNormal;
uniform sampler2D uPlatingTex;
uniform float uPlatingScale;
uniform float uPlatingStrength;`).replace("#include <map_fragment>",`
                vec3 tn = abs(normalize(vLocalNormal));
                tn = pow(tn, vec3(4.0));
                tn /= (tn.x + tn.y + tn.z);
                vec3 p = vLocalPos * uPlatingScale;
                vec3 sx = texture2D(uPlatingTex, p.yz).rgb;
                vec3 sy = texture2D(uPlatingTex, p.xz).rgb;
                vec3 sz = texture2D(uPlatingTex, p.xy).rgb;
                vec3 plating = sx * tn.x + sy * tn.y + sz * tn.z;
                float lum = dot(plating, vec3(0.299, 0.587, 0.114));
                // Blend: 1.0 = no change, lum near 0 darkens (panel seams).
                float modAmt = mix(1.0, lum * 1.4, uPlatingStrength);
                diffuseColor.rgb *= modAmt;
                `)},e.needsUpdate=!0}function _me(){const A=document.createElement("canvas");A.width=A.height=512;const t=A.getContext("2d"),i=t.createImageData(512,512);for(let o=0;o<i.data.length;o+=4){const s=160+(Math.random()*80|0);i.data[o]=s,i.data[o+1]=s,i.data[o+2]=s,i.data[o+3]=255}t.putImageData(i,0,0);for(let o=0;o<18;o++){const s=Math.random()*512,a=Math.random()*512,r=30+Math.random()*80,I=t.createRadialGradient(s,a,0,s,a,r);I.addColorStop(0,`rgba(${30+Math.random()*30|0}, ${30+Math.random()*30|0}, ${30+Math.random()*30|0}, 0.30)`),I.addColorStop(1,"rgba(0,0,0,0)"),t.fillStyle=I,t.fillRect(s-r,a-r,r*2,r*2)}t.globalAlpha=.18;for(let o=0;o<60;o++){const s=Math.random()*512,a=1+Math.random()*4,r=t.createLinearGradient(s,0,s,512);r.addColorStop(0,"rgba(30,30,40,0)"),r.addColorStop(.4,"rgba(30,30,40,1)"),r.addColorStop(1,"rgba(10,10,20,0)"),t.fillStyle=r,t.fillRect(s,0,a,512)}t.globalAlpha=1,t.lineCap="butt";const n=[[4,3,"rgba(15,17,22,0.95)"],[6,2,"rgba(20,22,28,0.85)"],[10,1.5,"rgba(25,27,34,0.7)"],[16,1,"rgba(30,32,38,0.55)"]];for(const[o,s,a]of n){t.strokeStyle=a,t.lineWidth=s;const r=512/o;for(let I=0;I<=o;I++){const c=Math.round(I*r)+.5;t.beginPath(),t.moveTo(c,0),t.lineTo(c,512),t.stroke(),t.beginPath(),t.moveTo(0,c),t.lineTo(512,c),t.stroke()}}t.strokeStyle="rgba(15,17,22,0.85)",t.lineWidth=2;for(let o=0;o<6;o++){const s=Math.random()*512,a=Math.random()*512,r=60+Math.random()*200,I=(Math.random()<.5?0:Math.PI/2)+(Math.random()-.5)*.5;t.beginPath(),t.moveTo(s,a),t.lineTo(s+Math.cos(I)*r,a+Math.sin(I)*r),t.stroke()}for(let o=0;o<200;o++){const s=Math.random()*512,a=Math.random()*512,r=1+Math.random()*1.4;t.fillStyle=`rgba(${15+Math.random()*25|0},${15+Math.random()*25|0},${20+Math.random()*25|0},0.85)`,t.beginPath(),t.arc(s,a,r,0,Math.PI*2),t.fill()}t.strokeStyle="rgba(220,225,235,0.35)",t.lineWidth=.8;for(let o=0;o<24;o++){const s=Math.random()*512,a=Math.random()*512,r=8+Math.random()*30,I=Math.random()*Math.PI*2;t.beginPath(),t.moveTo(s,a),t.lineTo(s+Math.cos(I)*r,a+Math.sin(I)*r),t.stroke()}const g=new pd(A);return g.wrapS=g.wrapT=Fr,g.repeat.set(4,4),g.anisotropy=4,g.colorSpace=rn,{albedo:g}}const nE=rmA,Jme=ImA,foA=k4,Lme=cmA,xme=.84,Tme=.8,qme=.28,yoA=.62,DoA=.34,moA=.08,Yme=.2,Hme=20,QO=900,Ome=180,Pme=90,wD=20,SoA=30,sv=200,kD=800,uO=800,jme=.65,zme=.012,woA=[1500,6e3,10500],Zme=.375,Wme=56,koA=26,dO=2,hO=60,Vme=8,MoA=450,NoA=560,av=1,Xme=.36,$me=.9,ASe=2.4,eSe=1.1,tSe=.6,iSe=1.6,nSe=.6,gSe=1100,oSe=.68,sSe=320,aSe=.5,rSe=.5,ISe=2.4,CSe=1.8,cSe=1.3,lSe=.4,BSe=3.2,ESe=CmA,RoA=40,QSe=1500,uSe=252,GoA=6,dSe=5,hSe=105,pSe=600,fSe=640,ySe=140,boA=380,UoA=1200,DSe=320,mSe=820,rv=sC?11:16,Iv=18,Cv=.07,SSe=1400,wSe=Math.PI*1.1,voA=sC?12:18,kSe=900,KoA=.028,MSe=.38,NSe=18,RSe=200,FoA=e=>{const A=(e??"").match(/t(\d)$/);return A?Math.min(6,Math.max(1,parseInt(A[1],10))):null},wmA=({attacker:e,defender:A,onComplete:t,tileBackgroundImage:i,onProgress:n,isSpectator:g=!1,botPilot:o=!1,isLocalDefender:s=!1,confirmedResult:a=null})=>{const r=e.piece,I=A.piece,c=E.useRef(null),l=E.useRef(null),B=E.useRef(null),Q=E.useRef(null),h=E.useRef(null),d=E.useRef(!1),p=E.useRef(1),[y,m]=E.useState("countdown"),[D,S]=E.useState(3),[k,N]=E.useState(0),[G,M]=E.useState(nE),[w,b]=E.useState(null),[_,K]=E.useState(!1),[J,q]=E.useState(!1),v=E.useMemo(()=>i?yd(i):IDe,[i]),U=i??Wm,[x,T]=E.useState(0),z=E.useRef([]),Z=E.useRef([]),eA=E.useRef([]),aA=E.useRef([]),sA=E.useRef([]),pA=E.useRef([]),gA=E.useRef(0),yA=E.useRef(0),fA=E.useRef(0),RA=E.useRef([]),qA=E.useRef([]),W=E.useRef([]),$=E.useRef([[],[],[]]),L=E.useRef([[],[],[]]),H=E.useRef(0),P=E.useRef({x:0,y:0}),tA=E.useRef(null),iA=E.useRef({x:0,y:0}),oA=E.useRef({dx:0,dy:0}),IA=E.useRef(null),CA=E.useRef({up:!1,down:!1,left:!1,right:!1}),_A=E.useRef(0),uA=E.useRef(0),[X,O]=E.useState(0),cA=E.useRef(0),wA=E.useRef(0),xA=E.useRef(0),YA=E.useRef(0),jA=E.useRef(0),ie=E.useRef(0),he=E.useRef(0),le=E.useRef({x:0,y:0,untilTs:0,nextBurstTs:0,tilt:0,targetTilt:0}),NA=E.useRef({initialized:!1,prevX:0,prevY:0,bankVel:0,pitchVel:0}),EA=E.useRef(null),PA=E.useRef([]),ZA=E.useRef(null),FA=E.useRef(!1),Ie=E.useRef(-1),DA=E.useRef(-1e3),rA=E.useRef(0),BA=E.useRef(0),j=E.useRef(0),QA=E.useRef({w:0,h:0}),dA=E.useRef(0),UA=E.useRef(_),TA=E.useRef(g),oe=E.useRef(n),me=E.useRef(r);E.useRef(0),E.useRef(0),UA.current=_,TA.current=g,oe.current=n,me.current=r;const be=E.useRef(1);be.current=FoA(e.heroId)??1;const $e=E.useRef(0),ci=E.useRef(0),ke=E.useRef(0),nt=E.useRef(null),Ut=E.useRef(0),dt=E.useRef({w:0,h:0}),Ht=E.useRef(null),Ft=E.useRef({w:0,h:0}),Jt=E.useRef(null),$A=E.useRef(0),He=E.useRef({w:0,h:0}),Xe=E.useRef([]);E.useEffect(()=>{const HA=[...oDe[I],...sDe[I],...aDe[I]];Xe.current=HA.map(ge=>yd(ge)).filter(ge=>!!ge)},[I]);const St=E.useCallback(()=>{var Ai;const HA=l.current;if(!HA)return;const ge=Math.min(window.devicePixelRatio||1,EDe),ye=HA.clientWidth,Te=HA.clientHeight;if(ye<=0||Te<=0)return;const gt=Math.round(ye*ge),Qt=Math.round(Te*ge),_e=HA.width!==gt||HA.height!==Qt;if(_e&&(HA.width=gt,HA.height=Qt),p.current=ge,QA.current={w:ye,h:Te},dA.current=Math.sqrt(ye/2*(ye/2)+Te/2*(Te/2)),(Ai=h.current)==null||Ai.resize(ye,Te,ge),B.current&&!_e){B.current.setTransform(ge,0,0,ge,0,0);return}const at=typeof navigator<"u"&&/Android/i.test(navigator.userAgent)?HA.getContext("2d"):HA.getContext("2d",{desynchronized:!0});at&&(at.setTransform(ge,0,0,ge,0,0),B.current=at)},[]),kA=E.useCallback((HA,ge)=>{const ye=xDe(HA,ge);for(let Te=0;Te<ye.length;Te+=1)Z.current.push(ye[Te])},[]),se=E.useCallback((HA,ge)=>{const{w:ye,h:Te}=QA.current;!ye||!Te||z.current.push(kDe({width:ye,height:Te,faction:I,factionColor:BmA[I],allocId:()=>cA.current++,now:HA,overrideZ:ge,battleshipAnchorX:yoA,battleshipAnchorY:DoA,zSpeedMin:Xme,zSpeedMax:$me,zFar:av}))},[I]),Ce=E.useCallback(HA=>FJ(HA,uA.current,e,A),[e,A]),VA=E.useCallback(HA=>{if(y!=="playing"||g)return;const ge=performance.now();if(ge-wA.current>=nE)return;const{x:Te,y:gt}=P.current;if(Te<=0||gt<=0)return;HA==="bot"&&Tc({volume:.12}),j.current=ge;const{w:Qt,h:_e}=QA.current;let Ze=!1;const Ai=.6+(be.current-1)*.28,Bi=Qt*.06,yi=_e*.3,mt=jt=>{const Zt=Math.atan2(gt-_e,Te-jt);return{bx:jt+Math.cos(Zt)*yi,by:_e+Math.sin(Zt)*yi}},{bx:ct,by:fi}=mt(Qt/2-Bi),{bx:Yi,by:si}=mt(Qt/2+Bi);for(const jt of z.current){if(!jt.alive)continue;const Zt=jt.renderScale>0?jt.renderScale:IO(jt),vi=Math.sqrt(Math.max(.5,Zt)),kn=SoA*vi*Ai,gn=kn*kn,Ki=jt.x-Te,Tn=jt.y-gt;if(Ki*Ki+Tn*Tn>gn)continue;jt.alive=!1,_A.current+=1,N(_A.current),kA(jt.x,jt.y);const fg=1-Math.max(jt.z,0)/av,Zi=1+fg*fg*4,te=Math.max(Zt,jme);aA.current.push({x:jt.x,y:jt.y,vx:jt.vx*Zi,vy:jt.vy*Zi,life:kD,maxLife:kD,color:jt.color,maxRadius:uO*te*Ai}),pa({volume:.03}),Ze=!0;break}if(!Ze)for(const jt of pA.current){if(!jt.alive)continue;const Zt=Math.max(0,1-jt.z),vi=koA+(Wme-koA)*Zt,kn=vi*vi*Ai,gn=jt.x-Te,Ki=jt.y-gt;if(!(gn*gn+Ki*Ki>kn)){jt.alive=!1,kA(jt.x,jt.y),aA.current.push({x:jt.x,y:jt.y,vx:0,vy:0,life:kD*.7,maxLife:kD*.7,color:"#ff5530",maxRadius:uO*.55*Ai}),pa({volume:.04}),Ze=!0;break}}eA.current.push({x1:ct,y1:fi,x2:Te-GoA,y2:gt,life:sv,maxLife:sv,hit:Ze,width:Ai},{x1:Yi,y1:si,x2:Te+GoA,y2:gt,life:sv,maxLife:sv,hit:Ze,width:Ai})},[g,y,kA]),nA=E.useCallback(()=>{for(const HA of PA.current)clearTimeout(HA);PA.current=[]},[]),vA=E.useCallback(()=>{if(y!=="playing"||g)return;const HA=performance.now();if(!(HA-ie.current<pSe)){ie.current=HA,dvA({volume:.22}),nA(),VA("player");for(let ge=1;ge<dSe;ge+=1){const ye=setTimeout(()=>{PA.current=PA.current.filter(Te=>Te!==ye),VA("player")},ge*hSe);PA.current.push(ye)}}},[nA,VA,g,y]),KA=E.useCallback(()=>{if(o){const HA=performance.now();if(HA-jA.current<RoA)return;jA.current=HA,VA("bot");return}vA()},[o,VA,vA]),WA=E.useCallback(()=>{FA.current=!1,ZA.current&&(ZA.current(),ZA.current=null),EA.current&&(clearInterval(EA.current),EA.current=null)},[]),bA=E.useCallback(()=>{if(!(y!=="playing"||g)){if(!FA.current){FA.current=!0;const HA=()=>WA();window.addEventListener("pointerup",HA,!0),window.addEventListener("pointercancel",HA,!0),window.addEventListener("mouseup",HA,!0),window.addEventListener("touchend",HA,!0),window.addEventListener("touchcancel",HA,!0),ZA.current=()=>{window.removeEventListener("pointerup",HA,!0),window.removeEventListener("pointercancel",HA,!0),window.removeEventListener("mouseup",HA,!0),window.removeEventListener("touchend",HA,!0),window.removeEventListener("touchcancel",HA,!0)}}KA(),!EA.current&&(EA.current=setInterval(()=>{KA()},fSe))}},[KA,g,y]);E.useEffect(()=>{y!=="playing"&&(WA(),nA())},[nA,y,WA]),E.useEffect(()=>()=>nA(),[nA]),E.useEffect(()=>{if(g||o)return;const HA=gt=>{const Qt=gt,_e=Qt==null?void 0:Qt.tagName;return _e==="INPUT"||_e==="TEXTAREA"||_e==="SELECT"||!!(Qt!=null&&Qt.isContentEditable)},ge=(gt,Qt)=>{const _e=CA.current;switch(gt){case"KeyW":case"ArrowUp":return _e.up=Qt,!0;case"KeyS":case"ArrowDown":return _e.down=Qt,!0;case"KeyA":case"ArrowLeft":return _e.left=Qt,!0;case"KeyD":case"ArrowRight":return _e.right=Qt,!0;default:return!1}},ye=gt=>{if(!HA(gt.target)){if(ge(gt.code,!0)){gt.preventDefault();return}if(gt.code==="Space"||gt.code==="KeyF"){gt.preventDefault(),gt.repeat||bA();return}gt.code==="Enter"&&(gt.preventDefault(),gt.repeat||KA())}},Te=gt=>{if(ge(gt.code,!1)){gt.preventDefault();return}(gt.code==="Space"||gt.code==="KeyF")&&(gt.preventDefault(),WA())};return window.addEventListener("keydown",ye),window.addEventListener("keyup",Te),()=>{window.removeEventListener("keydown",ye),window.removeEventListener("keyup",Te),CA.current={up:!1,down:!1,left:!1,right:!1},WA()}},[o,KA,g,bA,WA]),E.useEffect(()=>{const HA=()=>WA(),ge=()=>{document.visibilityState!=="visible"&&WA()};return window.addEventListener("blur",HA),document.addEventListener("visibilitychange",ge),()=>{window.removeEventListener("blur",HA),document.removeEventListener("visibilitychange",ge),WA()}},[WA]),E.useEffect(()=>{if(y!=="countdown")return;const HA=performance.now(),ge=D*1e3,ye=HA+ge;let Te=0,gt=D,Qt=!1;const _e=()=>{Qt||(Qt=!0,S(0),m("playing"))},Ze=()=>{if(Qt)return;const Ai=Math.max(0,ye-performance.now()),Bi=Math.ceil(Ai/1e3);if(Bi!==gt){if(gt=Bi,Bi<=0){_e();return}S(Bi)}Te=requestAnimationFrame(Ze)};Te=requestAnimationFrame(Ze);const at=window.setTimeout(_e,ge+750);return()=>{cancelAnimationFrame(Te),window.clearTimeout(at)}},[y,g]);const pe=E.useRef(null);E.useEffect(()=>{pe.current||(pe.current=new hmA({src:lmA}));const HA=pe.current;if(y==="countdown")HA.play();else if(y==="result")return HA.stop(),()=>HA.dispose()},[y]),E.useEffect(()=>()=>{var HA;(HA=pe.current)==null||HA.dispose()},[]),E.useEffect(()=>()=>{const HA=ge=>{if(ge)try{ge.width=0,ge.height=0}catch{}};HA(l.current),HA(Q.current),HA(nt.current),HA(Ht.current),HA(Jt.current),nt.current=null,Ht.current=null,Jt.current=null},[]),E.useEffect(()=>{const HA=[l.current,Q.current].filter(Te=>!!Te);if(HA.length===0)return;const ge=Te=>{Te.preventDefault(),q(!0)},ye=()=>q(!1);for(const Te of HA)Te.addEventListener("webglcontextlost",ge,!1),Te.addEventListener("webglcontextrestored",ye,!1),Te.addEventListener("contextlost",ge,!1),Te.addEventListener("contextrestored",ye,!1);return()=>{for(const Te of HA)Te.removeEventListener("webglcontextlost",ge,!1),Te.removeEventListener("webglcontextrestored",ye,!1),Te.removeEventListener("contextlost",ge,!1),Te.removeEventListener("contextrestored",ye,!1)}},[]),E.useEffect(()=>{if(y!=="playing")return;const HA=Q.current;if(!HA)return;console.log("[Raid3D] mount effect canvas",{client:[HA.clientWidth,HA.clientHeight],offset:[HA.offsetWidth,HA.offsetHeight]});const ge=new Fme;ge.setFactionScheme(I),h.current=ge,d.current=!1;let ye=!1;return ge.mount(HA,vpe(I)).then(()=>{if(ye)return;d.current=!0;let{w:Te,h:gt}=QA.current;(Te<=0||gt<=0)&&(Te=HA.clientWidth,gt=HA.clientHeight),ge.resize(Te,gt,p.current||window.devicePixelRatio||1),console.log("[Raid3D] scene ready",{w:Te,h:gt})}).catch(Te=>{console.warn("[Raid3D] failed to load ship model",Te)}),()=>{ye=!0,d.current=!1,ge.dispose(),h.current===ge&&(h.current=null)}},[y,I]),E.useEffect(()=>{if(g||o)return;const HA=c.current,ge=l.current;if(!HA||!ge)return;const ye=_e=>{const Ze=ge.getBoundingClientRect();return{x:_e.clientX-Ze.left,y:_e.clientY-Ze.top}},Te=_e=>{P.current=ye(_e)},gt=_e=>{const Ze=_e.target;Ze instanceof Element&&(Ze.closest(".raid-fps-fire-btn")||Ze.closest(".raid-fps-pad-zone"))||(_e.preventDefault(),P.current=ye(_e),KA())},Qt=_e=>{const Ze=_e.changedTouches[0],at=ye(Ze),{h:Ai}=QA.current;at.y>Ai-uSe||(_e.preventDefault(),P.current=at,KA())};return HA.addEventListener("touchstart",Qt,{passive:!1}),ioA&&(HA.addEventListener("mousemove",Te),HA.addEventListener("mousedown",gt)),()=>{HA.removeEventListener("touchstart",Qt),ioA&&(HA.removeEventListener("mousemove",Te),HA.removeEventListener("mousedown",gt))}},[KA,g,o]),E.useEffect(()=>{if(!o||y!=="playing")return;let HA=0,ge=performance.now();const ye=window.setInterval(()=>{KA()},RoA);let Te=-1,gt=0,Qt=0,_e=0,Ze=0,at=0,Ai=0,Bi=0,yi=Math.random()*Math.PI*2,mt=Math.random()*Math.PI*2;const ct=Yi=>{const si=!Yi&&Math.random()<.25,jt=Yi?5:si?70:22;gt=(Math.random()-.5)*jt,Qt=(Math.random()-.5)*jt;const Zt=Yi?60+Math.random()*60:110+Math.random()*110;_e=performance.now()+Zt,Ze=0,at=0},fi=()=>{const Yi=performance.now(),si=Math.min(.08,(Yi-ge)/1e3);ge=Yi,yi+=si*1.8,Ai=Math.sin(yi)*1.8+Math.sin(yi*2.3)*.8,Bi=Math.cos(yi*.9)*1.5+Math.cos(yi*2.7)*.6,mt+=si*5.2;const jt=Math.sin(mt)*16+Math.sin(mt*.37)*9,Zt=Math.cos(mt*.83)*12+Math.sin(mt*1.7)*6,{w:vi,h:kn}=QA.current;if(vi>0&&kn>0){P.current.x<=0&&P.current.y<=0&&(P.current={x:vi/2,y:kn/2});let gn=null,Ki=1/0;const Tn=P.current.x,fg=P.current.y;for(const Zi of pA.current){if(!Zi.alive)continue;const te=Zi.x-Tn,Eg=Zi.y-fg,gi=te*te+Eg*Eg;gi<Ki&&(Ki=gi,gn={x:Zi.x,y:Zi.y,id:-1e3-Zi.id})}if(!gn)for(const Zi of z.current){if(!Zi.alive||Zi.z>.85)continue;const te=Zi.x-Tn,Eg=Zi.y-fg,gi=te*te+Eg*Eg;gi<Ki&&(Ki=gi,gn={x:Zi.x,y:Zi.y,id:Zi.id})}if(gn)if(gn.id!==Te&&(Te=gn.id,ct(gn.id<=-1e3)),Yi<_e)P.current.x+=Ai*si*.4,P.current.y+=Bi*si*.4;else{const Zi=gn.id<=-1e3,te=gn.x+gt+Ai+(Zi?0:jt),Eg=gn.y+Qt+Bi+(Zi?0:Zt),gi=te-Tn,Mg=Eg-fg,Hg=Math.sqrt(gi*gi+Mg*Mg),qe=Math.min(Zi?1400:1100,Hg*6),OA=Hg>.1?gi/Hg*qe:0,Ae=Hg>.1?Mg/Hg*qe:0,Ke=Math.min(1,(Zi?12:9)*si);Ze+=(OA-Ze)*Ke,at+=(Ae-at)*Ke,P.current.x=Tn+Ze*si,P.current.y=fg+at*si}else Te=-1,Ze*=Math.max(0,1-3*si),at*=Math.max(0,1-3*si),P.current.x=Math.max(24,Math.min(vi-24,P.current.x+Ze*si+jt*si*5)),P.current.y=Math.max(24,Math.min(kn-24,P.current.y+at*si+Zt*si*4))}HA=requestAnimationFrame(fi)};return HA=requestAnimationFrame(fi),()=>{cancelAnimationFrame(HA),window.clearInterval(ye)}},[o,y,KA]),E.useEffect(()=>{if(y!=="playing")return;St();let HA=0;const ge=()=>{HA||(HA=requestAnimationFrame(()=>{HA=0,St()}))};window.addEventListener("resize",ge);const ye=typeof window<"u"?window.visualViewport:null;ye==null||ye.addEventListener("resize",ge),wA.current=performance.now(),xA.current=0,Ie.current=-1,uA.current=0,O(0),_A.current=0,N(0),H.current=0,b(null),le.current={x:0,y:0,untilTs:0,nextBurstTs:performance.now()+vh(boA,UoA),tilt:0,targetTilt:0},NA.current={initialized:!1,prevX:0,prevY:0,bankVel:0,pitchVel:0},z.current=[],Z.current=[],eA.current=[],aA.current=[],sA.current=[],pA.current=[],gA.current=0,yA.current=0,T(0),fA.current=0,RA.current=_De(),qA.current=JDe(),W.current=LDe();const{w:Te,h:gt}=QA.current;P.current.x<=0&&P.current.y<=0&&(P.current={x:Te/2,y:gt/2});let Qt=performance.now();BA.current=0;const _e=Ze=>{const at=Math.min((Ze-Qt)/1e3,.05);Qt=Ze;const Ai=Ze-wA.current;oe.current&&Ai-DA.current>=500&&(DA.current=Ai,oe.current({hits:_A.current,totalSpawned:uA.current,elapsedMs:Math.round(Ai),durationMs:nE,status:"active"}));const Bi=Math.max(0,nE-Ai),yi=Math.ceil(Bi/1e3);if(yi!==Ie.current&&(Ie.current=yi,M(Bi)),Ai>=nE+QSe&&(z.current=[]),Bi<=0&&z.current.length===0){m("result");return}if(Ai<100&&uA.current===0){const hA=6+Math.floor(Math.random()*3);for(let Re=0;Re<hA;Re++)se(Ze,.35+Math.random()*.5),uA.current+=1;O(uA.current)}if(Bi>ESe&&Ai-xA.current>=Jme){const hA=foA+Math.floor(Math.random()*(Lme-foA+1));for(let Re=0;Re<hA;Re+=1)se(Ze),uA.current+=1;O(uA.current),xA.current=Ai}const{w:mt,h:ct}=QA.current;if(!g&&Bi>0)for(;gA.current<woA.length&&Ai>=woA[gA.current];){const hA=mt*(.15+Math.random()*.7),Re=ct*(.1+Math.random()*.35),ot=mt*.5+(Math.random()-.5)*mt*.12,kt=ct*.78;fA.current+=1,pA.current.push({id:fA.current,x:hA,y:Re,z:1,originX:hA,originY:Re,targetX:ot,targetY:kt,spawnMs:Ze,alive:!0}),gA.current+=1}DD(pA.current,hA=>{if(!hA.alive)return!1;if(hA.z-=Zme*at,hA.z<=0){yA.current+=1,T(yA.current);const ot=le.current;return ot.untilTs=Ze+700,ot.targetTilt=vh(-Cv*2,Cv*2),sA.current.push({x1:hA.targetX,y1:hA.targetY,x2:hA.targetX,y2:hA.targetY,life:380,maxLife:380,color:"#ff3344"}),kA(hA.targetX,hA.targetY),aA.current.push({x:hA.targetX,y:hA.targetY,vx:0,vy:0,life:kD,maxLife:kD,color:"#ff5522",maxRadius:uO*1.2}),pa({volume:.06}),!1}const Re=1-hA.z;return hA.x=hA.originX+(hA.targetX-hA.originX)*Re,hA.y=hA.originY+(hA.targetY-hA.originY)*Re,!0});const{dx:fi,dy:Yi}=oA.current,si=Math.sqrt(fi*fi+Yi*Yi);if(si>Vme){const hA=Math.min(si/hO,1);P.current.x+=fi/si*hA*MoA*at,P.current.y+=Yi/si*hA*MoA*at}const jt=CA.current,Zt=(jt.right?1:0)-(jt.left?1:0),vi=(jt.down?1:0)-(jt.up?1:0);if(Zt!==0||vi!==0){const hA=Math.sqrt(Zt*Zt+vi*vi)||1;P.current.x+=Zt/hA*NoA*at,P.current.y+=vi/hA*NoA*at}P.current.x=Math.max(0,Math.min(mt,P.current.x)),P.current.y=Math.max(0,Math.min(ct,P.current.y));{const hA=NA.current;if(hA.initialized){const Re=(P.current.x-hA.prevX)/Math.max(at,.001),ot=(P.current.y-hA.prevY)/Math.max(at,.001);hA.bankVel=hA.bankVel*.94+Re*.06,hA.pitchVel=hA.pitchVel*.94+ot*.06}hA.prevX=P.current.x,hA.prevY=P.current.y,hA.initialized=!0}const kn=NA.current.bankVel/SSe*wSe,gn=Math.cos(kn),Ki=Math.sin(kn),Tn=mt/2*(1-gn)+ct/2*Ki,fg=ct/2*(1-gn)-mt/2*Ki;DD(z.current,hA=>{if(!hA.alive)return!1;const Re=hA.x,ot=hA.y,kt=1-Math.max(hA.z,0)/av,ht=1+kt*.75+(hA.z<0?Math.abs(hA.z)*2:0);hA.z-=hA.zSpeed*ht*at;const ee=hA.z<=oSe,je=ee?0:1,Ct=ee?1:0;let At=hA.vx;if(ee&&(hA.commitDirX===void 0||hA.commitDirY===void 0)){const eg=MDe(hA,mt/2,ct/2);hA.commitDirX=eg.x,hA.commitDirY=eg.y}if(je>0){const eg=hA.targetX-hA.x,Gs=hA.targetY-hA.y,bs=Math.max(.25,hA.z/hA.zSpeed);let Wg=eg/bs,Vg=Gs/bs;if(hA.profile==="weave"){const vB=(Ze-hA.spawnTime)/1e3,Ps=sSe*(aSe+kt*rSe);Wg+=Math.sin(vB*ISe+hA.weavePhase)*Ps,Vg+=Math.cos(vB*CSe+hA.weavePhase*cSe)*Ps*lSe}At=Wg;let rC=ASe;hA.profile==="strafe"?rC=eSe-kt*tSe:hA.profile==="weave"?rC=iSe:hA.profile==="bankout"&&(rC=nSe);const sr=1-Math.exp(-rC*at),UB=hA.vx+(Wg-hA.vx)*sr,pI=hA.vy+(Vg-hA.vy)*sr,fI=NDe(hA.vx,hA.vy,UB,pI,gSe,at);hA.vx=fI.vx,hA.vy=fI.vy}if(Ct>0&&hA.commitDirX!==void 0&&hA.commitDirY!==void 0){const eg=RDe(hA.vx,hA.vy,{x:hA.commitDirX,y:hA.commitDirY},Ct,at);hA.vx=eg.vx,hA.vy=eg.vy,At=hA.commitDirX*Math.max(160,Math.hypot(hA.vx,hA.vy))}const zt=1+kt*kt*BSe,li=hA.z<0?Math.abs(hA.z)*14:0,Ei=zt+li;if(hA.x+=hA.vx*Ei*at,hA.y+=hA.vy*Ei*at,hA.z>0&&hA.profile!=="weave"){const eg=(Ze-hA.spawnTime)/1e3,Gs=Math.sin(eg*hA.wobbleFreq*Math.PI*2+hA.wobblePhase)*hA.wobbleAmp*kt,bs=Math.cos(eg*hA.wobbleFreq*Math.PI*2+hA.wobblePhase*1.3)*hA.wobbleAmp*.6*kt;hA.x+=Gs*at*1.2,hA.y+=bs*at*1.2}const ai=(hA.x-Re)/Math.max(at,1e-4),Hi=(hA.y-ot)/Math.max(at,1e-4);hA.visualVx=hA.visualVx*.72+ai*.28,hA.visualVy=hA.visualVy*.72+Hi*.28;const gg=1-Math.exp(-10*at);hA.bankVx+=(At-hA.bankVx)*gg,hA.prevY=hA.y;{const eg=SDe(hA,mt,ct);eg!==hA.spriteIndex&&(hA.prevSpriteIndex=hA.spriteIndex,hA.spriteFadeStart=Ze,hA.spriteIndex=eg)}hA.renderScale=IO(hA);const yn=wDe(hA);if(hA.renderCosR=Math.cos(yn)*hA.renderScale,hA.renderSinR=Math.sin(yn)*hA.renderScale,!hA.flybyPlayed&&hA.z<.12&&(hA.flybyPlayed=!0,Ze-YA.current>300&&(YA.current=Ze)),hA.z>.05&&hA.z<.7&&Math.random()<zme&&sA.current.length<12&&(sA.current.push({x1:hA.x,y1:hA.y,x2:mt/2+(Math.random()-.5)*mt*.4,y2:ct*(.7+Math.random()*.3),life:75+Math.random()*50,maxLife:125,color:"#00ff66"}),Ze-he.current>ySe&&(he.current=Ze,Tc({volume:.012}))),hA.z>av*.3)return!0;const Rs=Ome*hA.renderScale/2,qo=Pme*hA.renderScale/2;return hA.x>-Rs&&hA.x<mt+Rs&&hA.y>-qo&&hA.y<ct+qo}),DD(Z.current,hA=>(hA.life-=at*1e3,hA.life<=0?!1:(hA.x+=hA.vx*at,hA.y+=hA.vy*at,!0))),DD(eA.current,hA=>(hA.life-=at*1e3,hA.life>0)),DD(aA.current,hA=>{if(hA.life-=at*1e3,hA.life<=0)return!1;const ot=2+(1-hA.life/hA.maxLife)*6;return hA.x+=hA.vx*ot*at,hA.y+=hA.vy*ot*at,!0}),DD(sA.current,hA=>(hA.life-=at*1e3,hA.life>0)),ci.current+=1,Ze-ke.current>=1e3&&($e.current=ci.current,ci.current=0,ke.current=Ze);const Zi=l.current,te=B.current??(Zi==null?void 0:Zi.getContext("2d"))??null;if(!Zi||!te){rA.current=requestAnimationFrame(_e);return}if(B.current=te,!(toA<=0||Ze-BA.current>=toA)){rA.current=requestAnimationFrame(_e);return}BA.current=Ze;const gi=p.current;if(te.setTransform(gi*gn,gi*Ki,gi*-Ki,gi*gn,gi*Tn,gi*fg),v!=null&&v.complete&&v.naturalWidth>0){const hA=Ze-wA.current,Re=Math.min(1,Math.max(0,hA/nE)),ot=1+qme*(.45+Re*.55),kt=Math.hypot(mt,ct)/Math.min(mt,ct)+.08,ht=kt*ot,ee=mt*xme,je=ct*Tme,Ct=(1-kt)*mt/2,At=(1-kt)*ct/2,zt=ee+ot*(Ct-ee),li=je+ot*(At-je),Ei=(P.current.x-mt/2)/mt*mt*KoA,ai=(P.current.y-ct/2)/ct*ct*(KoA*.6);te.drawImage(v,zt+Ei,li+ai,ht*mt,ht*ct)}else te.fillStyle="#0a0a1a",te.fillRect(0,0,mt,ct);if(Ze-Ut.current>KDe||dt.current.w!==mt||dt.current.h!==ct){for(const Re of qA.current){const ot=Ut.current===0?0:(Ze-Ut.current)/1e3;Re.x+=Re.driftX*ot,Re.y+=Re.driftY*ot,Re.x<-.25&&(Re.x+=1.5),Re.x>1.25&&(Re.x-=1.5),Re.y<-.25&&(Re.y+=1.5),Re.y>1.25&&(Re.y-=1.5)}if(!nt.current||dt.current.w!==mt||dt.current.h!==ct){const Re=document.createElement("canvas");Re.width=mt,Re.height=ct,nt.current=Re,dt.current={w:mt,h:ct}}const hA=nt.current.getContext("2d");hA.clearRect(0,0,mt,ct);for(const Re of qA.current){const ot=Re.x*mt,kt=Re.y*ct,ht=Re.radius*Math.max(mt,ct),ee=hA.createRadialGradient(ot,kt,0,ot,kt,ht);ee.addColorStop(0,Re.color),ee.addColorStop(1,"transparent"),hA.globalAlpha=Re.alpha,hA.fillStyle=ee,hA.fillRect(ot-ht,kt-ht,ht*2,ht*2)}hA.globalAlpha=1,Ut.current=Ze}nt.current&&te.drawImage(nt.current,0,0);const Hg=mt/2,de=ct/2,qe=dA.current;if(!umA&&qe>0){for(const Re of RA.current)Re.dist+=Re.speed/qe*at,Re.dist>fmA&&(Re.angle=Math.random()*Math.PI*2,Re.cosAngle=Math.cos(Re.angle),Re.sinAngle=Math.sin(Re.angle),Re.speed=JJ+Math.random()*(pmA-JJ),Re.brightness=.3+Math.random()*.7,Re.length=.5+Math.random()*1.5,Re.dist=.01);for(const Re of W.current)Re.dist+=Re.speed/qe*at,Re.dist>DmA&&(Re.angle=Math.random()*Math.PI*2,Re.speed=LJ+Math.random()*(ymA-LJ),Re.size=.4+Math.random()*1.2,Re.alpha=.12+Math.random()*.3,Re.dist=.01);if(Ze-$A.current>vDe||He.current.w!==mt||He.current.h!==ct){if(!Jt.current||He.current.w!==mt||He.current.h!==ct){const ht=document.createElement("canvas");ht.width=mt,ht.height=ct,Jt.current=ht,He.current={w:mt,h:ct}}const Re=Jt.current.getContext("2d");Re.clearRect(0,0,mt,ct);const ot=$.current;ot[0].length=0,ot[1].length=0,ot[2].length=0;for(const ht of RA.current){const ee=ht.dist*qe,je=ht.cosAngle,Ct=ht.sinAngle,At=Hg+je*ee,zt=de+Ct*ee,li=ht.length*(3+8*ht.dist),Ei=ht.brightness*Math.min(ht.dist/.2,1)*.6,ai=ht.dist<.3?0:ht.dist<.6?1:2;ot[ai].push([At,zt,At-je*li,zt-Ct*li,Ei])}Re.strokeStyle="#cce0ff",Re.globalAlpha=.5,[.8,1.3,2].forEach((ht,ee)=>{if(ot[ee].length){Re.lineWidth=ht,Re.beginPath();for(const[je,Ct,At,zt]of ot[ee])Re.moveTo(je,Ct),Re.lineTo(At,zt);Re.stroke()}}),Re.globalAlpha=1;const kt=L.current;kt[0].length=0,kt[1].length=0,kt[2].length=0;for(const ht of W.current){const ee=ht.dist*qe,je=Hg+Math.cos(ht.angle)*ee,Ct=de+Math.sin(ht.angle)*ee,At=ht.alpha*Math.min(ht.dist/.08,1),zt=At<.15?0:At<.3?1:2;kt[zt].push([je,Ct,ht.size])}Re.fillStyle="#8899bb",[.1,.22,.38].forEach((ht,ee)=>{if(kt[ee].length){Re.globalAlpha=ht,Re.beginPath();for(const[je,Ct,At]of kt[ee])Re.moveTo(je+At,Ct),Re.arc(je,Ct,At,0,Math.PI*2);Re.fill()}}),Re.globalAlpha=1,$A.current=Ze}Jt.current&&te.drawImage(Jt.current,0,0)}{const hA=QmA[I];if(hA!=null&&hA.complete&&hA.naturalWidth>0){const Re=Math.min(1,Math.max(0,Ai/nE)),ot=Re*Re,kt=ct*(moA+(Yme-moA)*ot),ht=hA.naturalWidth/hA.naturalHeight,ee=kt*ht,je=mt*yoA,Ct=ct*DoA;if(H.current===0){const At=kt*1.4,zt=DDe(I,At);te.drawImage(zt,je-At,Ct-At,At*2,At*2)}if(te.globalAlpha=.82+ot*.18,te.drawImage(hA,je-ee/2,Ct-kt/2,ee,kt),te.globalAlpha=1,H.current===0&&_A.current>=Hme&&(H.current=Ze),H.current>0&&(vl!=null&&vl.complete)&&vl.naturalWidth>0){const At=Ze-H.current;for(let zt=0;zt<3;zt++){const li=(At+zt*(QO/3))%QO/QO,Ei=kt*(.5+li*2.1),ai=(1-li)*(zt===0?.9:.65);te.globalAlpha=ai,te.drawImage(vl,je-Ei/2,Ct-Ei/2,Ei,Ei)}te.globalAlpha=1}}}const OA=z.current;for(let hA=1;hA<OA.length;hA++){const Re=OA[hA];let ot=hA-1;for(;ot>=0&&OA[ot].z<Re.z;)OA[ot+1]=OA[ot],ot--;OA[ot+1]=Re}const Ae=h.current,Ke=d.current&&Ae!==null;Ae&&Ke&&Ae.setShipPoses(OA.map(hA=>({id:hA.id,x:hA.x,y:hA.y,z:hA.z,visualVx:hA.visualVx,bankVx:hA.bankVx,visualVy:hA.visualVy,sizeScale:hA.sizeScale,spinRate:hA.spinRate,spawnTime:hA.spawnTime}))),Ae&&Ae.render(),pDe(),Math.max(Xe.current.length,1),te.globalCompositeOperation="source-over";for(const hA of OA);te.setTransform(gi*gn,gi*Ki,gi*-Ki,gi*gn,gi*Tn,gi*fg),te.globalAlpha=1,te.globalAlpha=.7,te.fillStyle="#ff8c00",te.beginPath();for(const hA of Z.current){const Re=3*(hA.life/hA.maxLife)+1;te.moveTo(hA.x+Re,hA.y),te.arc(hA.x,hA.y,Re,0,Math.PI*2)}te.fill(),te.globalAlpha=1;const Je=fDe();for(const hA of eA.current){const Re=1-hA.life/hA.maxLife,ot=hA.x1+(hA.x2-hA.x1)*Re,kt=hA.y1+(hA.y2-hA.y1)*Re,ht=hA.life>hA.maxLife*.2?1:hA.life/(hA.maxLife*.2),ee=hA.hit?"#00ffaa":"#ff4444",je=(hA.hit?18:13)*(hA.width??1),Ct=Math.max(Re-.15,0),At=hA.x1+(hA.x2-hA.x1)*Ct,zt=hA.y1+(hA.y2-hA.y1)*Ct;te.globalAlpha=ht*.3,te.strokeStyle=ee,te.lineWidth=je*.8,te.lineCap="round",te.beginPath(),te.moveTo(At,zt),te.lineTo(ot,kt),te.stroke(),te.globalAlpha=ht*.25,te.fillStyle=ee,te.beginPath(),te.arc(ot,kt,je*2.5,0,Math.PI*2),te.fill(),te.globalAlpha=ht;const li=hA.hit?Je.hit:Je.miss;te.drawImage(li,ot-je,kt-je,je*2,je*2)}te.globalAlpha=1;for(const hA of aA.current){const Re=1-hA.life/hA.maxLife,ot=1-(1-Re)*(1-Re)*(1-Re),kt=hA.maxRadius*2*(.01+ot*.99);te.globalAlpha=.7*(Re<.5?1:1-(Re-.5)/.5),vl!=null&&vl.complete&&vl.naturalWidth>0?te.drawImage(vl,hA.x-kt/2,hA.y-kt/2,kt,kt):(te.fillStyle=hA.color,te.beginPath(),te.arc(hA.x,hA.y,kt/2,0,Math.PI*2),te.fill())}te.globalAlpha=1;const pt=yDe();for(const hA of pA.current){if(!hA.alive)continue;const Re=Math.max(0,1-hA.z),ot=8+Re*34,kt=.55+.45*Math.sin((Ze-hA.spawnMs)*.018),ht=hA.x-hA.originX,ee=hA.y-hA.originY,je=Math.hypot(ht,ee)||1,Ct=ht/je,At=ee/je,zt=-At,li=Ct,Ei=ot*2.7,ai=ot*.72,Hi=hA.x-Ct*Ei,gg=hA.y-At*Ei,yn=ot*(3.8+kt*1.2),Rs=Hi-Ct*yn,qo=gg-At*yn,eg=te.createLinearGradient(hA.originX,hA.originY,hA.x,hA.y);if(eg.addColorStop(0,"rgba(255, 102, 51, 0)"),eg.addColorStop(.65,"rgba(255, 55, 22, 0.48)"),eg.addColorStop(1,"rgba(255, 214, 105, 0.92)"),te.globalAlpha=.45+Re*.5,te.fillStyle=eg,te.beginPath(),te.moveTo(hA.originX,hA.originY),te.lineTo(Hi+zt*ai,gg+li*ai),te.lineTo(Hi-zt*ai,gg-li*ai),te.closePath(),te.fill(),te.globalAlpha=.72+kt*.22,te.fillStyle="#ff4a1f",te.beginPath(),te.moveTo(Hi+zt*ai*.55,gg+li*ai*.55),te.lineTo(Rs,qo),te.lineTo(Hi-zt*ai*.55,gg-li*ai*.55),te.closePath(),te.fill(),te.globalAlpha=.92,te.strokeStyle="#fff2b0",te.lineWidth=Math.max(1.5,ot*.18),te.beginPath(),te.moveTo(Hi,gg),te.lineTo(Hi-Ct*yn*.72,gg-At*yn*.72),te.stroke(),te.globalAlpha=1,V0!=null&&V0.complete&&V0.naturalWidth>0){const Gs=ot*5,bs=ot*2.5;te.save(),te.translate(hA.x-Ct*ot*.9,hA.y-At*ot*.9),te.rotate(Math.atan2(At,Ct)+Math.PI),te.drawImage(V0,-Gs/2,-bs/2,Gs,bs),te.restore()}else te.fillStyle="#4a1015",te.strokeStyle="#ff6b39",te.lineWidth=Math.max(1.5,ot*.12),te.beginPath(),te.moveTo(hA.x+Ct*ot*.9,hA.y+At*ot*.9),te.lineTo(hA.x-Ct*Ei*.78+zt*ai,hA.y-At*Ei*.78+li*ai),te.lineTo(Hi+zt*ai*1.65,gg+li*ai*1.65),te.lineTo(Hi-zt*ai*1.65,gg-li*ai*1.65),te.lineTo(hA.x-Ct*Ei*.78-zt*ai,hA.y-At*Ei*.78-li*ai),te.closePath(),te.fill(),te.stroke();te.globalAlpha=.95,te.fillStyle="#fff4c2",te.beginPath(),te.arc(hA.x+Ct*ot*.35,hA.y+At*ot*.35,ot*.42,0,Math.PI*2),te.fill(),te.globalAlpha=(.25+Re*.35)*kt,te.strokeStyle="#ff3028",te.lineWidth=Math.max(1.5,ot*.08),te.beginPath(),te.arc(hA.x,hA.y,ot*(1.5+kt*.45),0,Math.PI*2),te.stroke(),te.globalAlpha*=.55,te.beginPath(),te.arc(hA.x,hA.y,ot*(2.5+kt*.7),0,Math.PI*2),te.stroke()}te.globalAlpha=1;for(const hA of sA.current){const Re=1-hA.life/hA.maxLife,ot=hA.x1+(hA.x2-hA.x1)*Re,kt=hA.y1+(hA.y2-hA.y1)*Re,ht=hA.life>hA.maxLife*.2?1:hA.life/(hA.maxLife*.2),ee=14,je=Math.max(Re-.12,0),Ct=hA.x1+(hA.x2-hA.x1)*je,At=hA.y1+(hA.y2-hA.y1)*je;te.globalAlpha=ht*.3,te.strokeStyle=hA.color,te.lineWidth=ee*.7,te.lineCap="round",te.beginPath(),te.moveTo(Ct,At),te.lineTo(ot,kt),te.stroke(),te.globalAlpha=ht*.2,te.fillStyle=hA.color,te.beginPath(),te.arc(ot,kt,ee*3,0,Math.PI*2),te.fill(),te.globalAlpha=ht,te.drawImage(pt,ot-ee,kt-ee,ee*2,ee*2)}if(te.globalAlpha=1,sA.current.length>0){let hA=0;for(const ot of sA.current){const kt=ot.life/ot.maxLife;kt>hA&&(hA=kt)}const Re=hA*(sC?.18:.35);te.globalAlpha=Re,te.fillStyle="#00ff50",te.fillRect(0,0,mt,ct),te.globalAlpha=1}if(te.setTransform(gi,0,0,gi,0,0),!Ht.current||Ft.current.w!==mt||Ft.current.h!==ct){const hA=document.createElement("canvas");hA.width=mt,hA.height=ct;const Re=hA.getContext("2d"),ot=Re.createRadialGradient(mt/2,ct/2,Math.min(mt,ct)*.35,mt/2,ct/2,Math.max(mt,ct)*.75);ot.addColorStop(0,"transparent"),ot.addColorStop(1,"rgba(0,0,0,0.45)"),Re.fillStyle=ot,Re.fillRect(0,0,mt,ct),Ht.current=hA,Ft.current={w:mt,h:ct}}te.drawImage(Ht.current,0,0);const{x:Tt,y:vt}=P.current;if(Tt>0&&vt>0&&!TA.current){te.globalAlpha=.25,te.strokeStyle="#00ffaa",te.lineWidth=6,te.beginPath(),te.arc(Tt,vt,wD,0,Math.PI*2),te.stroke(),te.globalAlpha=1,te.lineWidth=1.5,te.beginPath(),te.arc(Tt,vt,wD,0,Math.PI*2),te.stroke();const hA=6;te.beginPath(),te.moveTo(Tt-wD-hA,vt),te.lineTo(Tt-hA,vt),te.moveTo(Tt+hA,vt),te.lineTo(Tt+wD+hA,vt),te.moveTo(Tt,vt-wD-hA),te.lineTo(Tt,vt-hA),te.moveTo(Tt,vt+hA),te.lineTo(Tt,vt+wD+hA),te.stroke(),te.fillStyle="#00ffaa",te.beginPath(),te.arc(Tt,vt,2,0,Math.PI*2),te.fill()}if(tA.current!==null){const{x:hA,y:Re}=iA.current,{dx:ot,dy:kt}=oA.current,ht=Math.min(Math.sqrt(ot*ot+kt*kt),hO),ee=Math.atan2(kt,ot);te.save(),te.globalAlpha=.25,te.strokeStyle="#00ffaa",te.lineWidth=2,te.beginPath(),te.arc(hA,Re,hO,0,Math.PI*2),te.stroke(),te.globalAlpha=.5,te.fillStyle="#00ffaa",te.beginPath(),te.arc(hA+Math.cos(ee)*ht,Re+Math.sin(ee)*ht,16,0,Math.PI*2),te.fill(),te.restore()}const ei=EmA[me.current];if(ei!=null&&ei.complete&&ei.naturalWidth>0){const hA=le.current;Ze>=hA.nextBurstTs&&(hA.untilTs=Ze+vh(DSe,mSe),hA.nextBurstTs=Ze+vh(boA,UoA),hA.targetTilt=vh(-Cv,Cv)),Ze<=hA.untilTs?(hA.x=vh(-rv,rv),hA.y=vh(-rv,rv)):(hA.x=0,hA.y=0,hA.targetTilt=0),hA.tilt+=(hA.targetTilt-hA.tilt)*Math.min(1,at*3);const Re=NA.current,ot=Math.max(-voA,Math.min(voA,Re.pitchVel/kSe)),kt=hA.tilt,ht=Math.cos(kt),ee=Math.sin(kt),je=mt/2,Ct=ct/2;te.setTransform(gi*ht,gi*ee,gi*-ee,gi*ht,gi*(je*(1-ht)+Ct*ee),gi*(Ct*(1-ht)-je*ee)),te.globalAlpha=.35,te.drawImage(ei,-Iv+hA.x,-Iv+hA.y+ot,mt+Iv*2,ct+Iv*2),te.setTransform(gi,0,0,gi,0,0),te.globalAlpha=1}{const hA=ct*.3,Re=mt*.06,kt=(RV[me.current]??cDe)[be.current-1];if(kt!=null&&kt.complete&&kt.naturalWidth>0){const ht=Ze-j.current,ee=Math.max(0,1-ht/RSe),je=Math.sin(ee*Math.PI)*NSe,Ct=hA*(kt.naturalWidth/kt.naturalHeight),{x:At,y:zt}=P.current,li=ct,Ei=mt/2-Re,ai=Math.atan2(zt-li,At-Ei)+Math.PI/2,Hi=Math.cos(ai),gg=Math.sin(ai);te.setTransform(gi*Hi,gi*gg,gi*-gg,gi*Hi,gi*(Ei-gg*je),gi*(li+Hi*je)),te.globalAlpha=MSe,te.drawImage(kt,-Ct/2,-hA,Ct,hA);const yn=mt/2+Re,Rs=Math.atan2(zt-li,At-yn)+Math.PI/2,qo=Math.cos(Rs),eg=Math.sin(Rs);te.setTransform(gi*-qo,gi*-eg,gi*-eg,gi*qo,gi*(yn-eg*je),gi*(li+qo*je)),te.drawImage(kt,-Ct/2,-hA,Ct,hA),te.setTransform(gi,0,0,gi,0,0),te.globalAlpha=1}}if(UA.current){te.save(),te.strokeStyle="rgba(255,255,0,0.35)",te.lineWidth=1;for(const hA of z.current)te.beginPath(),te.arc(hA.x,hA.y,SoA*IO(hA),0,Math.PI*2),te.stroke();te.fillStyle="rgba(0,0,0,0.7)",te.fillRect(8,ct-110,220,100),te.font="12px monospace",te.fillStyle="#0f0",te.fillText(`FPS: ${$e.current}`,16,ct-90),te.fillText(`Ships: ${z.current.length}`,16,ct-74),te.fillText(`Spawned: ${uA.current}`,16,ct-58),te.fillText(`Lasers: ${eA.current.length}`,16,ct-42),te.fillText(`Hits: ${_A.current}`,16,ct-26),te.restore()}const Vt=1500;Bi<Vt&&(te.fillStyle=`rgba(0,0,0,${1-Bi/Vt})`,te.fillRect(0,0,mt,ct)),rA.current=requestAnimationFrame(_e)};return rA.current=requestAnimationFrame(_e),()=>{var Ze;cancelAnimationFrame(rA.current),HA&&cancelAnimationFrame(HA),window.removeEventListener("resize",ge),ye==null||ye.removeEventListener("resize",ge),(Ze=IA.current)==null||Ze.call(IA)}},[y,St,se,v]),E.useEffect(()=>{var ye;if(y!=="result")return;const HA=Ce(_A.current);(ye=oe.current)==null||ye.call(oe,{hits:_A.current,totalSpawned:uA.current,elapsedMs:nE,durationMs:nE,status:"complete"}),b(s?a?{...HA,winnerId:a.winnerId,creditsStolen:a.creditsStolen}:null:HA);const ge=window.setTimeout(()=>{t({...HA,finalHits:_A.current,totalSpawned:uA.current})},3e3);return()=>window.clearTimeout(ge)},[Ce,t,y,s,a,g,e.id]);const xe=E.useMemo(()=>Xi(I),[I]),it=E.useMemo(()=>Xi(r),[r]),ve=E.useMemo(()=>FoA(e.heroId),[e.heroId]),re=w?Math.max(1,w.attackerRoll+w.defenderRoll):Math.max(1,X),Qe=y==="result"&&!!w&&w.winnerId===e.id;return C.jsxs("div",{ref:c,className:"raid-fps-overlay",children:[C.jsx("canvas",{ref:l,className:"raid-fps-canvas"}),C.jsx("canvas",{ref:Q,className:"raid-fps-3d-canvas"}),J&&C.jsx("img",{src:U,alt:"","aria-hidden":"true",className:"raid-fps-context-lost-bg",draggable:!1}),C.jsxs("div",{className:"raid-fps-hud",children:[C.jsxs("div",{className:"raid-fps-hud-left",children:[C.jsx("span",{className:"raid-fps-label",children:s?"COVER FIRE":"HITS"}),C.jsx("span",{className:"raid-fps-value",children:k})]}),C.jsxs("div",{className:"raid-fps-hud-center",children:[C.jsx("span",{className:"raid-fps-title",children:s?`Defending against ${it}`:`Raid on ${xe}`}),ve&&C.jsxs("span",{className:"raid-fps-subtitle",children:["Hero Level ",ve]}),!s&&!g&&C.jsx("span",{className:"raid-fps-hull-pips","aria-label":`Hull integrity: ${dO-x} of ${dO}`,children:Array.from({length:dO}).map((HA,ge)=>C.jsx("span",{className:`raid-fps-hull-pip${ge<x?" raid-fps-hull-pip--lost":""}`},ge))})]}),C.jsxs("div",{className:"raid-fps-hud-right",children:[C.jsx("span",{className:"raid-fps-label",children:"TIME"}),C.jsxs("span",{className:"raid-fps-value",children:[Math.ceil(G/1e3),"s"]})]})]}),!1,y==="countdown"&&C.jsxs("div",{className:"raid-fps-countdown",children:[C.jsx("img",{src:gDe,alt:"","aria-hidden":"true",className:"raid-fps-countdown-video",draggable:!1}),C.jsx("div",{className:"raid-fps-countdown-overlay"}),C.jsx("div",{className:"raid-fps-countdown-alert",children:"Enemy fighters detected"}),C.jsx("div",{className:"raid-fps-countdown-label",children:"Prepare to defend"}),ve&&C.jsxs("div",{className:"raid-fps-countdown-hero",children:[it," Hero Level ",ve]}),C.jsx("div",{className:"raid-fps-countdown-num",children:D||"GO!"})]}),y==="result"&&!w&&s&&C.jsxs("div",{className:"raid-fps-result",children:[C.jsx("div",{className:"raid-fps-result-title",children:"Calculating outcome…"}),C.jsx("div",{className:"raid-fps-result-stats",children:"Awaiting battle report"})]}),y==="result"&&w&&(()=>{const HA=!g,ge=HA&&s?!Qe:Qe,ye=HA?ge?s?`${xe} defended!`:`${it} wins the raid!`:s?`${it} broke through!`:`${xe} defended!`:Qe?`${it} wins the raid!`:`${xe} defended!`,Te=HA?ge?"+":"-":Qe?"+":"-",gt=!s;return C.jsxs("div",{className:"raid-fps-result",children:[C.jsx("div",{className:`raid-fps-result-title ${ge?"win":"lose"}`,children:ye}),gt&&C.jsxs("div",{className:"raid-fps-result-stats",children:[k," / ",re," ships destroyed"]}),C.jsxs("div",{className:"raid-fps-result-credits",children:[Te,w.creditsStolen," energy"]})]})})(),g&&y!=="result"&&C.jsx("div",{className:"raid-fps-spectator-badge",children:"SPECTATING"}),(y==="countdown"||y==="playing"&&!g)&&C.jsxs(C.Fragment,{children:[C.jsx("div",{"data-no-global-haptic":!0,className:`raid-fps-pad-zone${y==="countdown"?" raid-fps-control-preview":""}`,onTouchStart:HA=>{HA.stopPropagation();const ge=HA.changedTouches[0];tA.current=ge.identifier;const ye=l.current;if(ye){const _e=ye.getBoundingClientRect();iA.current={x:ge.clientX-_e.left,y:ge.clientY-_e.top}}oA.current={dx:0,dy:0};const Te=_e=>{for(let Ze=0;Ze<_e.changedTouches.length;Ze+=1){const at=_e.changedTouches[Ze];if(at.identifier!==tA.current)continue;const Ai=l.current;if(!Ai)return;const Bi=Ai.getBoundingClientRect();oA.current={dx:at.clientX-Bi.left-iA.current.x,dy:at.clientY-Bi.top-iA.current.y}}},gt=()=>{tA.current=null,oA.current={dx:0,dy:0},document.removeEventListener("touchmove",Te),document.removeEventListener("touchend",Qt),document.removeEventListener("touchcancel",Qt),IA.current=null},Qt=_e=>{for(let Ze=0;Ze<_e.changedTouches.length;Ze+=1)if(_e.changedTouches[Ze].identifier===tA.current){gt();break}};IA.current=gt,document.addEventListener("touchmove",Te,{passive:!0}),document.addEventListener("touchend",Qt),document.addEventListener("touchcancel",Qt)},onMouseDown:HA=>{HA.stopPropagation(),HA.preventDefault(),tA.current=-1;const ge=l.current;if(ge){const Qt=ge.getBoundingClientRect();iA.current={x:HA.clientX-Qt.left,y:HA.clientY-Qt.top}}oA.current={dx:0,dy:0};const ye=Qt=>{const _e=l.current;if(!_e)return;const Ze=_e.getBoundingClientRect();oA.current={dx:Qt.clientX-Ze.left-iA.current.x,dy:Qt.clientY-Ze.top-iA.current.y}},Te=()=>{tA.current=null,oA.current={dx:0,dy:0},document.removeEventListener("mousemove",ye),document.removeEventListener("mouseup",gt),IA.current=null},gt=()=>Te();IA.current=Te,document.addEventListener("mousemove",ye),document.addEventListener("mouseup",gt)},children:C.jsxs("div",{className:"raid-fps-pad-icon",children:[C.jsxs("svg",{width:"56",height:"56",viewBox:"0 0 48 48",fill:"none",children:[C.jsx("circle",{cx:"24",cy:"24",r:"22",stroke:"rgba(0,255,170,0.5)",strokeWidth:"2.5"}),C.jsx("circle",{cx:"24",cy:"24",r:"8",fill:"rgba(0,255,170,0.35)"}),C.jsx("path",{d:"M24 6 L24 14 M24 34 L24 42 M6 24 L14 24 M34 24 L42 24",stroke:"rgba(0,255,170,0.5)",strokeWidth:"2.5",strokeLinecap:"round"})]}),C.jsx("span",{className:"raid-fps-pad-label",children:"AIM"})]})}),C.jsx("button",{"data-no-global-haptic":!0,className:`raid-fps-fire-btn${y==="countdown"?" raid-fps-control-preview":""}`,onPointerDown:HA=>{HA.stopPropagation(),HA.preventDefault();try{HA.currentTarget.setPointerCapture(HA.pointerId)}catch{}bA()},onPointerUp:HA=>{HA.stopPropagation();try{HA.currentTarget.releasePointerCapture(HA.pointerId)}catch{}WA()},onPointerCancel:HA=>{HA.stopPropagation();try{HA.currentTarget.releasePointerCapture(HA.pointerId)}catch{}WA()},onClick:HA=>{HA.stopPropagation(),y==="playing"&&!EA.current&&KA()},children:"FIRE"})]})]})},GSe=["⬡","◈","✦","⬢","◉","⧫","Δ","Ψ","Σ"],Uk=[3,4,5],pO=Uk.reduce((e,A)=>e+A,0),bSe=[350,260,190],USe=90,vSe=2200,cv=900,_oA=1800,$0=5e3,kmA=({attacker:e,defender:A,onComplete:t,isSpectator:i=!1})=>{const[n,g]=E.useState("intro"),[o,s]=E.useState(3),[a,r]=E.useState(0),[I,c]=E.useState([]),[l,B]=E.useState(null),[Q,h]=E.useState([]),[d,p]=E.useState(!1),[y,m]=E.useState(null),[D,S]=E.useState(null),[k,N]=E.useState($0/1e3),G=E.useRef(0),M=E.useRef(t);M.current=t;const w=E.useRef([]),b=E.useCallback(()=>{w.current.forEach(clearTimeout),w.current=[]},[]),_=E.useCallback((z,Z)=>{const eA=setTimeout(z,Z);w.current.push(eA)},[]);E.useEffect(()=>b,[b]);const K=E.useCallback(z=>{b();const Z=Uk[z],eA=Array.from({length:Z},()=>Math.floor(Math.random()*9));r(z),c(eA),h([]),B(null),g("reveal")},[b]);E.useEffect(()=>{if(n!=="intro")return;G.current=0;const z=setTimeout(()=>{s(3),g("countdown")},vSe);return()=>clearTimeout(z)},[n]),E.useEffect(()=>{n==="countdown"&&(b(),_(()=>s(2),cv),_(()=>s(1),cv*2),_(()=>s("GO!"),cv*3),_(()=>K(0),cv*3+600))},[n,b,_,K]),E.useEffect(()=>{if(n!=="reveal"||I.length===0)return;N($0/1e3),b();const z=bSe[a];let Z=500;for(let eA=0;eA<I.length;eA++){const aA=I[eA];_(()=>B(aA),Z),Z+=z,_(()=>B(null),Z),Z+=USe}_(()=>g("input"),Z+100)},[n,a,I,b,_]);const J=E.useRef([]);E.useEffect(()=>{J.current=Q},[Q]),E.useEffect(()=>{if(n!=="input"||i)return;N($0/1e3);const z=Date.now(),Z=window.setInterval(()=>{const aA=Date.now()-z,sA=Math.max(0,Math.ceil(($0-aA)/1e3));N(sA)},200),eA=window.setTimeout(()=>{g(aA=>{if(aA!=="input")return aA;const sA=J.current;let pA=0;for(let yA=0;yA<sA.length&&sA[yA]===I[yA];yA++)pA++;G.current+=pA,p(!1);const gA=a+1;return _(()=>{if(gA>=Uk.length){const yA=FJ(G.current,pO,e,A);S(yA),g("result"),M.current(yA)}else K(gA)},_oA),"roundResult"})},$0);return()=>{window.clearInterval(Z),window.clearTimeout(eA)}},[n,i,I,a,e,A,_,K]);const q=E.useCallback(z=>{if(n!=="input"||i)return;const Z=[...Q,z],eA=Z.length-1,aA=I[eA]===z;if(So(aA?"Light":"Medium").catch(()=>{}),m({cell:z,ok:aA}),_(()=>m(null),250),!aA||Z.length===I.length){let sA=0;for(let yA=0;yA<Z.length&&Z[yA]===I[yA];yA++)sA++;G.current+=sA;const pA=aA&&Z.length===I.length;p(pA),h(Z),g("roundResult"),So(pA?"Heavy":"Medium").catch(()=>{});const gA=a+1;_(()=>{if(gA>=Uk.length){const yA=FJ(G.current,pO,e,A);S(yA),g("result"),So(yA.winnerId===e.id?"Heavy":"Medium").catch(()=>{}),M.current(yA)}else K(gA)},_oA)}else h(Z)},[n,i,Q,I,a,e,A,_,K]),v=z=>z.piece.replace(/-/g," ").replace(/\b\w/g,Z=>Z.toUpperCase()),U=v(e),x=v(A),T=(D==null?void 0:D.winnerId)===e.id;return C.jsxs("div",{className:"zcb-overlay",children:[n==="intro"&&C.jsxs("div",{className:"zcb-intro",children:[C.jsx("div",{className:"zcb-intro-alert",children:"⚠ INTRUSION DETECTED ⚠"}),C.jsxs("div",{className:"zcb-intro-title",children:["DECRYPTION",C.jsx("br",{}),"BREACH"]}),C.jsxs("div",{className:"zcb-intro-vs",children:[C.jsx("span",{className:"zcb-intro-atk",children:U}),C.jsx("span",{className:"zcb-intro-arrow",children:"⟶"}),C.jsx("span",{className:"zcb-intro-def",children:x})]}),C.jsx("div",{className:"zcb-intro-rule"}),C.jsx("div",{className:"zcb-intro-body",children:C.jsx("span",{className:"zcb-intro-body-line",children:"Memorize the flashing sequence — then tap it back, in order."})}),C.jsx("div",{className:"zcb-intro-blink",children:"INITIALIZING ENCRYPTION BREACH…"})]}),n==="countdown"&&C.jsxs("div",{className:"zcb-countdown",children:[C.jsx("div",{className:"zcb-countdown-label",children:"DECRYPTION BREACH"}),C.jsx("div",{className:`zcb-countdown-num${o==="GO!"?" zcb-countdown-go":""}`,children:o},String(o)),C.jsx("div",{className:"zcb-countdown-sub",children:o==="GO!"?"MEMORIZE THE SEQUENCE":"PREPARE"})]}),(n==="reveal"||n==="input"||n==="roundResult")&&C.jsxs("div",{className:"zcb-game",children:[C.jsxs("div",{className:"zcb-game-left",children:[C.jsxs("div",{className:"zcb-game-header",children:[C.jsx("div",{className:"zcb-game-title",children:"DECRYPTION BREACH"}),C.jsxs("div",{className:"zcb-game-round",children:["LAYER ",a+1," / ",Uk.length]})]}),C.jsxs("div",{className:`zcb-status-bar${n==="roundResult"?d?" zcb-status-pass":" zcb-status-fail":""}`,children:[n==="reveal"&&"OBSERVE…",n==="input"&&!i&&`${Q.length} / ${I.length} — ${k}s`,n==="input"&&i&&"DECRYPTING…",n==="roundResult"&&(d?"✓ CRACKED":"✗ FAILED")]}),n==="input"&&!i&&C.jsx("div",{className:"zcb-progress",children:I.map((z,Z)=>C.jsx("span",{className:`zcb-pip${Z<Q.length?" zcb-pip-done":""}`},Z))})]}),C.jsx("div",{className:"zcb-grid",children:GSe.map((z,Z)=>{const eA=l===Z,aA=(y==null?void 0:y.cell)===Z,sA=aA&&(y==null?void 0:y.ok),pA=aA&&!(y!=null&&y.ok),gA=["zcb-cell",eA?"zcb-cell--lit":"",sA?"zcb-cell--ok":"",pA?"zcb-cell--bad":"",n==="input"&&!i?"zcb-cell--active":""].filter(Boolean).join(" ");return C.jsx("button",{className:gA,onPointerDown:()=>q(Z),disabled:n!=="input"||i,children:z},Z)})})]}),n==="result"&&D&&C.jsxs("div",{className:"zcb-result",children:[C.jsx("div",{className:`zcb-result-verdict${T?" zcb-result-win":" zcb-result-lose"}`,children:T?`BREACH
SUCCESSFUL`:`ENCRYPTION
HELD`}),C.jsxs("div",{className:"zcb-result-score",children:[G.current," / ",pO," sequences cracked"]}),C.jsx("div",{className:"zcb-result-credits",children:T?`${U} extracted ✦${D.creditsStolen}`:`${x} repelled the breach`})]})]})},JoA="/assets/zentara_bg_station-CAwho_RD.webp",KSe="/assets/zentara_bg_asteroid-JpVBwON4.webp",FSe="/assets/zentara_bg_wormhole-ByrGMZDT.webp",LoA="/assets/zentara_bg_tax-D9cuUCQx.webp",_Se="/assets/zentara_bg_jail-CSIhqvMO.webp",JSe="/assets/zentara_bg_go-to-jail-Cn-gffQl.webp",LSe="/assets/zentara_bg_free-parking-BZgv5fD7.webp",xSe="/assets/galaxy_bg-EkKFwwxn.webp",TSe=9e4,qSe=1800,YSe=2400,HSe=900,MmA=200,Xm=120,OSe=240,xoA=1200,PSe=2400,jSe=1.4,NmA=1200,VS=2e3,hp=5,zSe=9,ZSe=-14,WSe=-26,lv=2.2,VSe=4,XSe=9,$Se=-1.5,Awe=-7,ToA=55,ewe=7,twe=2200,iwe=800,fO=110,nwe=18,gwe=3,owe=380,swe=950,awe=14,rwe=.32,Iwe=3.2,Cwe=.62,cwe=18,lwe=24,yO=.08,qoA=-3.4,YoA=3.4,HoA=-50,OoA=3,Bv=100,Bwe=GV?1:sC?1.25:1.75;function PoA(e,A,t,i){const n=t?e.id:A.id,o=i?Math.min(MmA,(t?A:e).credits):0;return{attackerRoll:t?1:0,defenderRoll:t?0:1,attackerTotal:t?1:0,defenderTotal:t?0:1,winnerId:n,creditsStolen:Math.max(0,o),finalHits:t?1:0,totalSpawned:1}}const Ev={muzzle:{x:0,y:40,z:0},weapon:{x:0,y:0,z:0,tiltX:-.08,tiltY:0,tiltZ:0},forceMuzzle:!1},RmA="/zentara/soldier/enemy-soldier.glb?v=7";Ur.preload(RmA);const Ewe=({enemy:e,empireId:A})=>{const t=E.useRef(null),i=E.useRef(null),n=E.useRef(null),g=E.useRef(null),o=E.useRef(null),s=E.useRef(null),a=E.useRef(null),r=E.useRef({x:0,y:0,leanZ:0}),I=E.useRef(null),c=E.useMemo(()=>{const _=new Et(e.color).multiplyScalar(2.6);return new kg({color:_,transparent:!0,opacity:0,blending:io,depthWrite:!1,toneMapped:!1})},[e.color]),{scene:l,animations:B}=Ur(RmA),Q=E.useMemo(()=>cue.clone(l),[l]);E.useLayoutEffect(()=>{Q.traverse(_=>{const K=_;if(!K.isSkinnedMesh||!K.skeleton)return;const J=new Set;if(K.skeleton.bones.forEach((z,Z)=>{/head|neck/i.test(z.name)&&J.add(Z)}),J.size===0)return;const q=K.geometry,v=q.getAttribute("skinIndex"),U=q.getAttribute("skinWeight");if(!v||!U)return;const x=q.getAttribute("position").count,T=new Float32Array(x*3);for(let z=0;z<x;z++){let Z=0;for(let aA=0;aA<4;aA++){const sA=v.getComponent(z,aA);J.has(sA)&&(Z+=U.getComponent(z,aA))}const eA=Z>.5;T[z*3+0]=eA?0:1,T[z*3+1]=eA?0:1,T[z*3+2]=eA?0:1}q.setAttribute("color",new ji(T,3))})},[Q]),E.useLayoutEffect(()=>{const _=new Sf(3.5,12,8),K=new kg({color:16734746,toneMapped:!1}),J=[];return Q.traverse(q=>{if(/shoulder/i.test(q.name)&&!/end/i.test(q.name)){const v=new pn(_,K);v.position.set(0,0,4),v.renderOrder=5,q.add(v),J.push(v)}}),()=>{J.forEach(q=>{var v;return(v=q.parent)==null?void 0:v.remove(q)}),_.dispose(),K.dispose()}},[Q]);const h=E.useRef(null);E.useLayoutEffect(()=>{Q.traverse(_=>{!h.current&&/hips$/i.test(_.name)&&(h.current=_)})},[Q]);const d=E.useMemo(()=>B.map(_=>{const K=_.clone();return K.tracks=K.tracks.filter(J=>!/Hips\.position/i.test(J.name)),K}),[B]);E.useLayoutEffect(()=>{if(Q.traverse(J=>{(J.isSkinnedMesh||J.isMesh)&&(J.frustumCulled=!1)}),!t.current)return;t.current.updateWorldMatrix(!0,!0);let _=1/0;const K=new SA;if(Q.traverse(J=>{J.isBone&&(J.getWorldPosition(K),K.y<_&&(_=K.y))}),isFinite(_)){const J=t.current.position.y,q=t.current.scale.y||1,v=(J-_)/q;Q.position.y+=v}else Q.position.y+=1},[Q]);const{actions:p,names:y}=Ahe(d,Q),m=E.useMemo(()=>{const _=new Et(e.color),K=[];return Q.traverse(J=>{const q=J;if(!q.isMesh)return;const v=x=>{const T=x.clone();T.color&&(T.color.lerp(_,.45),T.color.multiplyScalar(.55)),T.emissive||(T.emissive=new Et(0)),T.emissive.copy(_).multiplyScalar(.22),T.emissiveIntensity=.1,T.metalness=Math.min(1,(T.metalness??0)+.25),T.roughness=Math.max(.25,(T.roughness??.6)-.1),T.vertexColors=!0;const z={value:_.clone()};return T.onBeforeCompile=Z=>{Z.uniforms.uFaction=z,Z.vertexShader=Z.vertexShader.replace("void main() {",`varying vec3 vBindPos;
void main() {`).replace("#include <begin_vertex>",`#include <begin_vertex>
vBindPos = position;`),Z.fragmentShader=Z.fragmentShader.replace("void main() {",`uniform vec3 uFaction;
varying vec3 vBindPos;
void main() {`).replace("#include <emissivemap_fragment>",`#include <emissivemap_fragment>
                             // Per-vertex head/body mask (1 = body, 0 = head).
                             vec3 vMask = vec3(1.0);
                             #ifdef USE_COLOR
                                vMask = vColor;
                             #endif
                             // Gate the base faction emissive by the head mask.
                             totalEmissiveRadiance *= vMask;

                             // ── Procedural emissive armor strips ─────
                             // Two thin horizontal bands at chest and waist
                             // height in object space (un-skinned position).
                             // Bind-pose Y values measured from GLB inspect:
                             //   chest ≈ 1.45m, waist ≈ 1.00m (model is ~1.79 tall).
                             float chestBand = exp(-pow((vBindPos.y - 1.45) * 26.0, 2.0));
                             float waistBand = exp(-pow((vBindPos.y - 1.00) * 32.0, 2.0));
                             float stripGlow = chestBand * 1.2 + waistBand * 0.7;
                             totalEmissiveRadiance += stripGlow * uFaction * vMask;

                             // ── Crisper fresnel rim ──────────────────
                             // Boosted slightly now that the base armor is
                             // darker — rim lighting carries the silhouette.
                             vec3 rimViewDir = normalize(vViewPosition);
                             float rim = pow(1.0 - clamp(dot(rimViewDir, normal), 0.0, 1.0), 2.2);
                             totalEmissiveRadiance += rim * uFaction * 1.25 * vMask;
                            `)},T.needsUpdate=!0,K.push(T),T},U=q.material;q.material=Array.isArray(U)?U.map(v):v(U)}),K},[Q,e.color]),D=_=>y.includes(_),S=E.useMemo(()=>y.filter(_=>_==="die"||_.startsWith("die-")||_.startsWith("die_")||/^die\d+$/.test(_)),[y]),k=(_,K,J,q)=>{if(_==="dead")return S.length===0?null:((!a.current||!S.includes(a.current))&&(a.current=S[Math.random()*S.length|0]),a.current);a.current&&(a.current=null);const v=K*Math.cos(q),U=.22;return v>U&&D("walk-right")?"walk-right":v<-U&&D("walk-left")?"walk-left":J?D("run")?"run":D("walk")?"walk":D("idle")?"idle":null:D("aim")?"aim":D("idle")?"idle":null},N=_=>{const K=s.current;if(_===K)return;const J=K?p[K]:null,q=_?p[_]:null;if(!(_!==null&&!q)){if(s.current=_,q){q.enabled=!0;const v=q.time,U=q.getClip();q.reset();const x=!!_&&(_==="die"||_.startsWith("die-")||_.startsWith("die_")||/^die\d+$/.test(_));v>0&&U.duration>0&&!x&&(q.time=v%U.duration),x?(q.setLoop(vW,1),q.clampWhenFinished=!0,q.timeScale=1):(q.setLoop(dJ,1/0),q.clampWhenFinished=!1,_==="walk-left"||_==="walk-right"?q.timeScale=U.duration>0?U.duration/.68:2.5:_==="run"?q.timeScale=.8:_==="walk"?q.timeScale=1.05:q.timeScale=1),q.fadeIn(.22).play()}J&&J!==q&&J.fadeOut(.22)}};E.useEffect(()=>{if(y.length===0)return;const _=["aim","idle","run","walk"].find(J=>y.includes(J));if(!_)return;const K=p[_];K&&(K.isRunning()||(K.reset(),K.setLoop(dJ,1/0),K.fadeIn(.05).play(),s.current=_))},[y,p]);const G=E.useMemo(()=>new kg({color:1114112,transparent:!0,opacity:.75,depthTest:!1}),[]),M=E.useMemo(()=>new kg({color:16729173,transparent:!0,opacity:.95,depthTest:!1}),[]),w=E.useMemo(()=>GmA(),[]),b=E.useMemo(()=>new kg({color:16767078,transparent:!0,opacity:0,blending:io,depthWrite:!1}),[]);return E.useLayoutEffect(()=>{const _=[],K=new sa;K.name="enemy-weapon",K.frustumCulled=!1,o.current=K;const J=new xg({color:1710621,metalness:.7,roughness:.45,emissive:0}),q=new xg({color:2763312,metalness:.6,roughness:.55}),v=new sI(5,22,5.5),U=new pn(v,J);U.position.set(0,12,0),K.add(U);const x=new gy(1.3,1.3,18,10),T=new pn(x,J);T.position.set(0,30,.5),K.add(T);const z=new sI(4,11,5),Z=new pn(z,q);Z.position.set(0,-5,.2),K.add(Z);const eA=new sI(3.6,5,9),aA=new pn(eA,q);aA.position.set(0,8,-6),K.add(aA);const sA=new sI(3.4,3.4,7),pA=new pn(sA,q);pA.position.set(0,0,-4.2),K.add(pA),K.rotation.x=Ev.weapon.tiltX,_.push(()=>{v.dispose(),x.dispose(),z.dispose(),eA.dispose(),sA.dispose(),J.dispose(),q.dispose()});const gA=new Sf(1.2,12,10),yA=new pn(gA,b);yA.position.set(0,40,0),yA.renderOrder=6,yA.frustumCulled=!1,K.add(yA),g.current=yA,_.push(()=>{gA.dispose(),g.current===yA&&(g.current=null)});let fA=null;return Q.traverse(RA=>{fA||/righthand$/i.test(RA.name)&&(fA=RA)}),fA||Q.traverse(RA=>{fA||/right(forearm|arm)$/i.test(RA.name)&&(fA=RA)}),fA&&(fA.add(K),_.push(()=>{var RA;(RA=K.parent)==null||RA.remove(K)})),()=>{_.forEach(RA=>RA()),o.current===K&&(o.current=null)}},[Q,b]),E.useLayoutEffect(()=>{var _;(_=t.current)==null||_.position.set(e.pos[0],e.pos[1],e.pos[2])},[]),E.useEffect(()=>()=>{m.forEach(_=>_.dispose()),G.dispose(),M.dispose(),b.dispose(),c.dispose()},[m,G,M,b,c]),Ba((_,K)=>{const J=t.current;if(!J)return;const q=performance.now(),v=e.spawnedAt?q-e.spawnedAt:1/0,U=v<VS,x=U?Math.max(0,Math.min(1,v/VS)):1;if(I.current)if(U){I.current.visible=!0;const iA=Math.sin(x*Math.PI),oA=.85+.15*Math.sin(q*.05);c.opacity=Math.min(.5,(iA*oA+.15)*.5);const IA=Math.min(1,x*2);I.current.scale.y=IA,I.current.position.y=3+(1-IA)*3}else I.current.visible&&(I.current.visible=!1);const T=.9,z=U?x<T?0:Math.min(1,(x-T)/(1-T)):1;for(let iA=0;iA<m.length;iA++){const oA=m[iA];U?(oA.transparent=!0,oA.opacity=z):oA.opacity!==1&&(oA.transparent=!1,oA.opacity=1)}const Z=!U||x>=T;Q.visible!==Z&&(Q.visible=Z),N(k(e.state,e.strafeDirX??0,e.isAdvancing??!1,e.yaw??0));const aA=e.state==="aim"||e.state==="fire"?Math.max(-1,Math.min(1,e.strafeDirX??0)):0,sA=Math.abs(aA),pA=q*.006,gA=-aA*.08,yA=Math.sin(pA*8)*.012*sA,fA=Math.sin(pA*6)*.012*sA,RA=1-Math.exp(-10*K);r.current.leanZ+=(gA-r.current.leanZ)*RA,r.current.y+=(yA-r.current.y)*RA,r.current.x+=(fA-r.current.x)*RA;const qA=e.pos[0]+r.current.x,W=e.pos[1]+r.current.y,$=e.pos[2];if(J.position.x=qA,J.position.y=W,J.position.z=$,e.state!=="dead"){let oA=(e.yaw??0)-J.rotation.y;oA-=Math.round(oA/(2*Math.PI))*(2*Math.PI),J.rotation.y+=oA*Math.min(1,16*K),J.rotation.z+=(r.current.leanZ-J.rotation.z)*RA}e.state==="dead"&&(J.position.y=-.95);const L=!!(e.flashUntilAt&&e.flashUntilAt>q),H=e.color;for(let iA=0;iA<m.length;iA++){const oA=m[iA];L?(oA.emissive.setRGB(1,1,1),oA.emissiveIntensity=1.4):(oA.emissive.set(H).multiplyScalar(.35),oA.emissiveIntensity=.25)}if(g.current){const oA=!!(e.muzzleUntilAt&&e.muzzleUntilAt>q)||Ev.forceMuzzle;b.opacity=oA?.95:0;const IA=oA?1+Math.sin(q*.08)*.2:.001;g.current.scale.setScalar(IA);const CA=Ev.muzzle;g.current.position.set(CA.x,CA.y,CA.z)}if(o.current){const iA=Ev.weapon;o.current.position.set(iA.x,iA.y,iA.z),o.current.rotation.set(iA.tiltX,iA.tiltY,iA.tiltZ)}const P=e.maxHp||100,tA=Math.max(0,Math.min(1,e.hp/P));i.current&&(i.current.scale.x=tA,i.current.position.x=-.3*(1-tA),M.color.setHex(tA>.5?6750106:tA>.25?16766515:16724804)),n.current&&(n.current.visible=!1)}),C.jsxs("group",{ref:t,scale:1.45,children:[C.jsx("mesh",{position:[0,.012,0],rotation:[-Math.PI/2,0,0],scale:[1.1,.7,1],material:w,renderOrder:-1,children:C.jsx("planeGeometry",{args:[1,1]})}),C.jsx("primitive",{object:Q}),C.jsx("mesh",{ref:I,material:c,position:[0,3,0],renderOrder:500,visible:!1,children:C.jsx("cylinderGeometry",{args:[.55,.4,6,24,1,!0]})}),C.jsxs("group",{ref:n,position:[0,2.05,0],children:[C.jsx("mesh",{material:G,renderOrder:999,children:C.jsx("planeGeometry",{args:[.62,.09]})}),C.jsx("mesh",{ref:i,material:M,position:[0,0,.001],renderOrder:1e3,children:C.jsx("planeGeometry",{args:[.6,.07]})})]})]})},DO=[-3,-1.5,0,1.5,3],Qwe=.35,uwe=.35,dwe=.4,hwe=1,Qv=160,joA=280,zoA=600,pwe=1400,fwe=1400,ywe=200;function ZoA(e,A){return e*(1+(Math.random()*2-1)*A)}function WoA(e){return Math.max(0,Math.min(1,e))}function VoA(e,A,t){return e<A?Math.min(A,e+t):e>A?Math.max(A,e-t):A}const XoA=2.2,Dwe=3.2,mwe=7.5,Swe=10,wwe=6.5,kwe=9,Mwe=.9,Nwe=1.8,$oA=-6,Rwe=2.6,Gwe=1.2,AsA=.45,bwe=.35;function Uwe(e,A){if(A.length!==0)for(const t of A){const i=t.hx+AsA,n=bwe+AsA,g=e[0]-t.x,o=e[2]-t.z;if(Math.abs(g)>=i||Math.abs(o)>=n)continue;const s=i-Math.abs(g),a=n-Math.abs(o);s<a?e[0]=t.x+(g>=0?i:-i):e[2]=t.z+(o>=0?n:-n)}}class esA{constructor(){Oi(this,"nextLaneSwapAt",0);Oi(this,"firstShotArmedAt",0);Oi(this,"targetX",0);Oi(this,"engageZ",$oA);Oi(this,"velX",0);Oi(this,"velZ",0);Oi(this,"burstRemaining",0)}init(A){const t=A+VS;this.firstShotArmedAt=t+OSe+ywe+Math.random()*fwe,this.nextLaneSwapAt=A,this.targetX=Number.NaN,this.engageZ=$oA+(Math.random()-.5)*2*Rwe,this.velX=0,this.velZ=0,this.burstRemaining=0}tick({now:A,dt:t,camera:i,self:n,combatants:g,cover:o}){if(n.state==="dead")return null;if(n.spawnedAt&&A-n.spawnedAt<VS)return this.velX=0,this.velZ=0,n.strafeDirX=0,n.isAdvancing=!1,null;const s=n.team==="ally",a=s||n.pos[2]>=this.engageZ-.05;if(s)this.velX=0,this.velZ=0,n.strafeDirX=0,n.isAdvancing=!1;else{if(Number.isNaN(this.targetX)&&(this.targetX=n.pos[0]),A>=this.nextLaneSwapAt){const G=g.filter(b=>b!==n&&b.team===n.team&&b.state!=="dead"),M=DO.filter(b=>{if(Math.abs(b-n.pos[0])<=.5)return!1;for(const _ of G)if(Math.abs(b-_.pos[0])<Gwe)return!1;return!0});let w;if(M.length>0)w=M[Math.floor(Math.random()*M.length)]??0;else{let b=DO[0]??0,_=-1/0;for(const K of DO){if(Math.abs(K-n.pos[0])<=.5)continue;let J=1/0;for(const q of G){const v=Math.abs(K-q.pos[0]);v<J&&(J=v)}J>_&&(_=J,b=K)}w=b}this.targetX=w,this.nextLaneSwapAt=A+xoA+Math.random()*(PSe-xoA)}const p=this.engageZ-n.pos[2],y=p>.03?Dwe*WoA(p/Nwe):0,m=Math.abs(y)>Math.abs(this.velZ)?wwe:kwe;this.velZ=VoA(this.velZ,y,m*t),Math.abs(this.velZ)<.02&&(this.velZ=0),n.pos[2]=Math.min(this.engageZ,n.pos[2]+this.velZ*t),n.pos[2]>=this.engageZ-.01&&(n.pos[2]=Math.min(n.pos[2],this.engageZ),this.velZ=0),n.isAdvancing=this.velZ>.16||!a&&p>.35;const D=this.targetX-n.pos[0],S=Math.abs(D)>.03?Math.sign(D)*XoA*WoA(Math.abs(D)/Mwe):0,k=Math.abs(S)>Math.abs(this.velX)?mwe:Swe;this.velX=VoA(this.velX,S,k*t),Math.abs(this.velX)<.02&&(this.velX=0);const N=n.pos[0]+this.velX*t;D>0&&N>=this.targetX||D<0&&N<=this.targetX?(n.pos[0]=this.targetX,this.velX=0):n.pos[0]=N,n.strafeDirX=Math.max(-1,Math.min(1,this.velX/XoA))}if(o&&o.length>0){const p=n.pos[0],y=n.pos[2];Uwe(n.pos,o),Math.abs(n.pos[0]-p)>.001&&(this.velX=0),Math.abs(n.pos[2]-y)>.001&&(this.velZ=0,n.isAdvancing=!1)}if(A<this.firstShotArmedAt)return null;let r=null,I=null,c=1/0;const l=n.pos[0],B=n.pos[2];if(s)for(const p of g){if(p.team!=="enemy"||p.state==="dead")continue;const y=p.pos[0]-l,m=p.pos[2]-B,D=y*y+m*m;D<c&&(c=D,r=p.id,I=new SA(p.pos[0],p.pos[1]+1.05,p.pos[2]))}else{const p=i.position.x-l,y=i.position.z-B;c=(p*p+y*y)*rwe,r=null,I=i.position.clone();for(const D of g){if(D.team!=="ally"||D.state==="dead")continue;const S=D.pos[0]-l,k=D.pos[2]-B,N=S*S+k*k;N<c&&(c=N,r=D.id,I=new SA(D.pos[0],D.pos[1]+1.05,D.pos[2]))}}if(!I)return null;const Q=s?iwe:owe,h=s?twe:swe,d=s?ewe:awe;if(n.state==="patrol"&&A>=n.nextActionAt){n.state="aim";const y=this.burstRemaining>0?Q*.25:Q;return n.aimEndsAt=A+ZoA(y,Qwe),null}if(n.state==="aim"&&A>=n.aimEndsAt){n.state="fire",n.muzzleUntilAt=A+90;let p;this.burstRemaining>0?(this.burstRemaining-=1,p=Qv+Math.random()*(joA-Qv)):Math.random()<dwe?(this.burstRemaining=1+Math.floor(Math.random()*hwe),p=Qv+Math.random()*(joA-Qv)):p=ZoA(h,uwe),n.nextActionAt=A+p;const y=new SA(n.pos[0]+.18,n.pos[1]+1.05,n.pos[2]+(s?-.6:.6)),m=I.clone(),D=jSe*Math.PI/180;return m.x+=(Math.random()-.5)*2*Math.tan(D)*6,m.y+=(Math.random()-.5)*2*Math.tan(D)*6,{muzzle:y,aimEnd:m,damage:d,targetId:r}}return n.state==="fire"&&A>=n.nextActionAt&&(n.state="patrol",this.burstRemaining===0&&A-(n.muzzleUntilAt??0)<h*.5&&Math.random()<.7?n.nextActionAt=A+zoA+Math.random()*(pwe-zoA):n.nextActionAt=A+300+Math.random()*500),null}}const vwe=Math.cos(gwe*Math.PI/180),mO=2.4,tsA=1.4,isA=new SA,nsA=new SA,Kwe=900,Fwe=140,Ak=140,OQ=16,gsA=2200,SO=16;let ek=null;function _we(){if(ek)return ek;const e=128,A=document.createElement("canvas");A.width=A.height=e;const t=A.getContext("2d"),i=t.createRadialGradient(e/2,e/2,0,e/2,e/2,e/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.18,"rgba(255,140,140,0.95)"),i.addColorStop(.45,"rgba(255,60,80,0.55)"),i.addColorStop(.75,"rgba(120,20,40,0.18)"),i.addColorStop(1,"rgba(0,0,0,0)"),t.fillStyle=i,t.fillRect(0,0,e,e),ek=new pd(A),ek.colorSpace=rn,ek}let uv=null;function Jwe(){if(uv)return uv;const e=128,A=document.createElement("canvas");A.width=A.height=e;const t=A.getContext("2d"),i=t.createRadialGradient(e/2,e/2,0,e/2,e/2,e/2);return i.addColorStop(0,"rgba(0,0,0,0.85)"),i.addColorStop(.35,"rgba(0,0,0,0.55)"),i.addColorStop(.7,"rgba(0,0,0,0.18)"),i.addColorStop(1,"rgba(0,0,0,0)"),t.fillStyle=i,t.fillRect(0,0,e,e),uv=new pd(A),uv}let dv=null;function GmA(){return dv||(dv=new kg({map:Jwe(),color:0,transparent:!0,opacity:.65,depthWrite:!1,toneMapped:!1,fog:!1}),dv)}const bmA=new qd,UmA="/zentara/soldier";function Lwe(e,A){const t=bmA.load(`${UmA}/${e}`);return t.wrapS=Fr,t.wrapT=Fr,t.repeat.set(A[0],A[1]),t.anisotropy=4,t.colorSpace=rn,t}function xwe({position:e}){const A=E.useRef(null);return Ba(()=>{const t=A.current;if(!t)return;const i=performance.now()*.0026;t.intensity=1.3+1.1*Math.sin(i)}),C.jsx("pointLight",{ref:A,position:e,color:16767053,distance:14,decay:1.7,intensity:1.3})}const Twe=E.forwardRef(function({yawRef:A,pitchRef:t,killsRef:i,totalSpawnedRef:n,playerHpRef:g,botHpRef:o,enemyAccent:s,allyAccent:a,enemyEmpire:r,allyEmpire:I,activeRef:c,moveRef:l,adsRef:B,onPlayerDied:Q,onShotFired:h,onEnemyFired:d,onCombatantFired:p,onEnemyKilled:y,onLockChange:m,botPilot:D=!1},S){const{camera:k,scene:N,gl:G}=ic(),M=E.useMemo(()=>{const FA=new Et(s),Ie={h:0,s:0,l:0};return FA.getHSL(Ie),FA.setHSL(Ie.h,Math.min(.55,Ie.s*.7),.04),FA},[s]);E.useEffect(()=>{},[N,M]);const w=E.useRef([]),b=E.useRef([]),[,_]=ue.useReducer(FA=>FA+1,0),K=E.useRef(1),J=E.useRef(0),q=E.useRef(!1);E.useRef(null);const v=E.useRef(new Map),U=E.useRef(null),x=E.useRef(!1),T=E.useRef(!1),z=E.useRef({x:0,z:0}),Z=E.useRef(0),eA=E.useRef(0),aA=E.useRef(0),sA=E.useRef(0),pA=E.useCallback((FA,Ie)=>{const DA=performance.now(),rA=Math.max(0,aA.current+sA.current-DA);FA>=eA.current*(rA/Math.max(1,sA.current))&&(eA.current=FA,aA.current=DA,sA.current=Ie)},[]),gA=E.useRef([]),yA=E.useRef(null),fA=E.useRef(new Float32Array(OQ*6)),RA=E.useRef(new Float32Array(OQ*6));if(!yA.current){const FA=new Ni;FA.setAttribute("position",new ji(fA.current,3)),FA.setAttribute("color",new ji(RA.current,3)),FA.setDrawRange(0,OQ*2),yA.current=FA}const qA=E.useMemo(()=>new es({vertexColors:!0,transparent:!0,opacity:1,blending:io,depthWrite:!1,linewidth:2}),[]),W=E.useRef(null),$=E.useMemo(()=>{const FA=new gy(1,1,1,8,1,!0);return FA.translate(0,.5,0),FA},[]),L=E.useMemo(()=>new kg({transparent:!0,opacity:1,blending:io,depthWrite:!1,toneMapped:!1,fog:!1}),[]);function H(FA,Ie,DA,rA=Ak,BA=null){const j=performance.now(),QA={a:FA.clone(),aLocal:BA?BA.clone():null,b:Ie.clone(),length:Math.max(.5,FA.distanceTo(Ie)),color:new Et(DA),bornAt:j,untilAt:j+rA},dA=gA.current;dA.length<OQ?dA.push(QA):dA[K.current++%OQ]=QA}const P=E.useRef([]),tA=E.useRef(null),iA=E.useRef(0),oA=E.useMemo(()=>new oB(1,1),[]),IA=E.useMemo(()=>new kg({map:_we(),transparent:!0,depthWrite:!1,blending:io,toneMapped:!1}),[]);function CA(FA,Ie){const DA=iA.current++%SO;P.current[DA]={pos:FA.clone(),bornAt:performance.now(),color:new Et(Ie)}}function _A(FA,Ie,DA=80){if(Ie.y>=-1e-4)return null;const rA=-FA.y/Ie.y;return rA<=0||rA>DA?null:FA.clone().add(Ie.clone().multiplyScalar(rA))}const uA=E.useMemo(()=>Lwe("corridor-floor.webp",[6,40]),[]),X=E.useMemo(()=>new xg({color:16777215,map:uA,metalness:.35,roughness:.7,emissive:2238513,emissiveIntensity:.12}),[uA]),O=E.useMemo(()=>new xg({color:2106930,metalness:.5,roughness:.5,emissive:s,emissiveIntensity:.06}),[s]),cA=E.useMemo(()=>new xg({color:1448483,metalness:.45,roughness:.55,emissive:10466559,emissiveIntensity:.1}),[]),wA=E.useMemo(()=>new kg({color:s,transparent:!0,opacity:.9,blending:io,depthWrite:!1,toneMapped:!1}),[s]),xA=E.useMemo(()=>new xg({color:1185312,metalness:.55,roughness:.35,emissive:s,emissiveIntensity:.55}),[s]),YA=E.useMemo(()=>new kg({color:s,transparent:!0,opacity:.55,blending:io,depthWrite:!1,toneMapped:!1,fog:!1}),[s]),jA=E.useMemo(()=>{const FA=bmA.load(`${UmA}/cover/cover-barricade-low.webp`);return FA.anisotropy=4,FA.colorSpace=rn,FA},[]),ie=E.useMemo(()=>new xg({map:jA,transparent:!0,alphaTest:.12,depthWrite:!0,side:AI,metalness:.55,roughness:.6,emissive:1711914,emissiveIntensity:.45}),[jA]),he=E.useMemo(()=>new oB(mO,tsA),[]),le=E.useMemo(()=>new oB(mO*.92,.06),[]),NA=E.useMemo(()=>new kg({color:10478847,transparent:!0,opacity:.85,blending:io,depthWrite:!1,toneMapped:!1,side:AI}),[]),EA=E.useMemo(()=>new oB(1,1),[]),PA=E.useMemo(()=>GmA(),[]);E.useEffect(()=>()=>{ie.dispose(),jA.dispose(),he.dispose(),le.dispose(),NA.dispose(),EA.dispose()},[ie,jA,he,le,NA,EA]);const ZA=E.useCallback((FA,Ie)=>{const DA=b.current;if(!DA.length)return null;const rA=Ie.z-FA.z;if(Math.abs(rA)<1e-4)return null;let BA=1/0,j=null;for(let QA=0;QA<DA.length;QA++){const dA=DA[QA],UA=(dA.z-FA.z)/rA;if(UA<=.001||UA>=.999)continue;const TA=FA.x+(Ie.x-FA.x)*UA,oe=FA.y+(Ie.y-FA.y)*UA;TA<dA.x-dA.hx||TA>dA.x+dA.hx||oe<0||oe>2*dA.hy||UA<BA&&(BA=UA,j=new SA(TA,oe,dA.z))}return j},[]);return E.useEffect(()=>(k.position.set(0,1.6,0),k.rotation.order="YXZ",J.current=performance.now(),()=>{X.dispose(),uA.dispose(),O.dispose(),cA.dispose(),wA.dispose(),xA.dispose(),YA.dispose()}),[k,X,O,cA,wA,xA,YA,uA]),E.useImperativeHandle(S,()=>({fire:()=>{if(!c.current||x.current)return;const FA=performance.now(),Ie=B.current?.006:.014;Z.current=Math.min(.05,Z.current+Ie);const DA=new SA(0,0,-1).applyQuaternion(k.quaternion).normalize(),rA=k.position,BA=[[.55,.45],[1.05,.55],[1.65,.38]];let QA=80,dA=null;for(const $A of w.current)if(!($A.state==="dead"||$A.team!=="enemy")&&!($A.spawnedAt&&FA-$A.spawnedAt<VS))for(let He=0;He<BA.length;He++){const[Xe,St]=BA[He],kA=$A.pos[0]-rA.x,se=$A.pos[1]+Xe-rA.y,Ce=$A.pos[2]-rA.z,VA=DA.x*kA+DA.y*se+DA.z*Ce;if(VA<=0||VA>=QA)continue;const nA=kA-DA.x*VA,vA=se-DA.y*VA,KA=Ce-DA.z*VA;nA*nA+vA*vA+KA*KA>St*St||(QA=VA,dA=$A)}const UA=new SA(0,0,-1).applyQuaternion(k.quaternion),TA=!!B.current;let oe=TA?0:.55,me=TA?-.08:-.2;const be=G.domElement,$e=be==null?void 0:be.getBoundingClientRect();if(!TA&&$e&&$e.width>0&&$e.height>0){const $A=document.querySelector(".soldier-weapon-wrap");if($A){const He=$A.getBoundingClientRect();if(He.width>0&&He.height>0){const Xe=He.right-.97*He.width,St=He.bottom-.875*He.height;oe=(Xe-$e.left)/$e.width*2-1,me=-((St-$e.top)/$e.height*2-1)}}}const ke=new SA(oe,me,-1).unproject(k).sub(k.position).normalize(),nt=k.position.clone().add(ke.multiplyScalar(1.2)),Ut=nt.clone().sub(k.position).applyQuaternion(k.quaternion.clone().invert()),dt=UA.clone().normalize(),Ht=$A=>{const He=Math.max(.5,$A.x*dt.x+$A.y*dt.y+$A.z*dt.z-(k.position.x*dt.x+k.position.y*dt.y+k.position.z*dt.z));return nt.clone().add(dt.clone().multiplyScalar(He))};if(!dA){const $A=_A(k.position,dt,80),He=$A||k.position.clone().add(dt.clone().multiplyScalar(40)),Xe=ZA(k.position,He);Xe?(H(nt,Ht(Xe),a,Ak,Ut),CA(Xe,a)):(H(nt,Ht(He),a,Ak,Ut),$A&&CA($A,a)),h==null||h(!1);return}const Ft=new SA(dA.pos[0],dA.pos[1]+1.05,dA.pos[2]),Jt=ZA(rA,Ft);if(Jt){H(nt,Ht(Jt),a,Ak,Ut),CA(Jt,a),h==null||h(!1);return}H(nt,Ht(Ft),a,Ak,Ut),dA.hp-=nwe,dA.flashUntilAt=FA+Fwe,dA.hp<=0&&(dA.state="dead",dA.nextActionAt=FA+Kwe,i.current+=1,U.current=null,v.current.delete(dA.id),y==null||y()),h==null||h(!0),_()}}),[c,k,i,h,y,ZA]),Ba((FA,Ie)=>{if(!c.current||x.current){for(const Ce of w.current)Ce.state!=="dead"&&(Ce.strafeDirX!==0&&(Ce.strafeDirX=0),Ce.isAdvancing&&(Ce.isAdvancing=!1));z.current.x=0,z.current.z=0;return}const DA=Math.min(Ie,.05),rA=performance.now(),BA=rA-J.current;if(!q.current&&BA>=NmA){q.current=!0;const Ce=[],VA=(HA,ge,ye,Te=[])=>{const Qt=Math.min(ge,ye),_e=Math.max(ge,ye);let Ze=[0,(Qt+_e)*.5];for(let at=0;at<24;at++){const Ai=(Math.random()*2-1)*HA,Bi=Qt+Math.random()*(_e-Qt);Ze=[Ai,Bi];let yi=!0;for(let mt=0;mt<Ce.length;mt++){const ct=Ce[mt][0]-Ai,fi=Ce[mt][1]-Bi;if(ct*ct+fi*fi<lv*lv){yi=!1;break}}if(yi)for(let mt=0;mt<Te.length;mt++){const ct=Te[mt][0]-Ai,fi=Te[mt][1]-Bi;if(ct*ct+fi*fi<lv*lv){yi=!1;break}}if(yi)break}return Ce.push(Ze),Ze},nA=4,vA=-9,KA=-13,WA=8.5,bA=3.2,pe=[],xe=[];for(let HA=0;HA<nA;HA++){let ge=0,ye=(vA+KA)*.5;for(let Te=0;Te<24;Te++){const gt=(Math.random()*2-1)*WA,Qt=KA+Math.random()*(vA-KA);let _e=!0;for(let Ze=0;Ze<pe.length;Ze++){const at=pe[Ze][0]-gt,Ai=pe[Ze][1]-Qt;if(at*at+Ai*Ai<bA*bA){_e=!1;break}}if(ge=gt,ye=Qt,_e)break}pe.push([ge,ye]),xe.push({x:ge,z:ye,hx:mO*.5,hy:tsA*.5})}b.current=xe;const it=xe.map(HA=>[HA.x,HA.z]);for(let HA=0;HA<hp;HA++){const[ge,ye]=VA(zSe,ZSe,WSe,it),Te={id:K.current++,pos:[ge,0,ye],hp:Xm,maxHp:Xm,state:"patrol",aimEndsAt:0,nextActionAt:rA+600+Math.random()*2400,color:s,lane:0,spawnedAt:rA,team:"enemy"};w.current.push(Te);const gt=new esA;gt.init(rA),v.current.set(Te.id,gt)}const ve=k.position.x,re=k.position.z,Qe=[[ve,re],...it];Ce.length=0;for(let HA=0;HA<VSe;HA++){const[ge,ye]=VA(XSe,$Se,Awe,Qe),Te={id:K.current++,pos:[ve+ge,0,re+ye],hp:ToA,maxHp:ToA,state:"patrol",aimEndsAt:0,nextActionAt:rA+800+Math.random()*2600,color:a,lane:0,spawnedAt:rA,team:"ally"};w.current.push(Te);const gt=new esA;gt.init(rA),v.current.set(Te.id,gt)}n.current=hp,o.current=hp*Xm,_()}const j=w.current;let QA=0;for(const Ce of j){if(Ce.state==="dead")continue;const VA=v.current.get(Ce.id);if(!VA)continue;const nA=VA.tick({now:rA,dt:DA,camera:k,self:Ce,combatants:j,cover:b.current});if(nA){const vA=Ce.team==="ally";p==null||p(vA);const KA=vA?6750105:6741503,WA=ZA(nA.muzzle,nA.aimEnd);if(WA){H(nA.muzzle,WA,KA,80),CA(WA,vA?4521864:5623039);continue}if(H(nA.muzzle,nA.aimEnd,KA,80),nA.targetId===null){const pe=nA.aimEnd.clone().sub(nA.muzzle),xe=pe.length()||1;pe.divideScalar(xe);const ve=k.position.clone().sub(nA.muzzle).dot(pe);nA.muzzle.clone().add(pe.multiplyScalar(ve)).distanceTo(k.position)<=.55&&ve>0&&ve<=xe+.5&&(g.current=Math.max(0,g.current-nA.damage),pA(.05,220),d==null||d(),g.current<=0&&!x.current&&(x.current=!0,Q()))}else{const bA=j.find(pe=>pe.id===nA.targetId);bA&&bA.state!=="dead"&&(bA.hp-=nA.damage,bA.flashUntilAt=rA+110,bA.hp<=0&&(bA.state="dead",bA.nextActionAt=rA+9999e3,v.current.delete(bA.id),bA.team==="enemy"&&(i.current+=1,U.current===bA.id&&(U.current=null),y==null||y())))}}if(Ce.team==="ally"){let vA=1/0,KA=Ce.pos[0],WA=Ce.pos[2]-1;for(const bA of j){if(bA.team!=="enemy"||bA.state==="dead")continue;const pe=bA.pos[0]-Ce.pos[0],xe=bA.pos[2]-Ce.pos[2],it=pe*pe+xe*xe;it<vA&&(vA=it,KA=bA.pos[0],WA=bA.pos[2])}Ce.yaw=Math.atan2(KA-Ce.pos[0],WA-Ce.pos[2])}else Ce.yaw=Math.atan2(k.position.x-Ce.pos[0],k.position.z-Ce.pos[2]);Ce.team==="enemy"&&(QA+=Math.max(0,Ce.hp))}if(q.current&&(o.current=QA),Z.current*=Math.exp(-14*DA),D){let Ce=null,VA=1/0;for(const nA of w.current){if(nA.team!=="enemy"||nA.state==="dead")continue;const vA=nA.pos[0]-k.position.x,KA=nA.pos[2]-k.position.z,WA=vA*vA+KA*KA;WA<VA&&(VA=WA,Ce=nA)}if(Ce){const nA=Ce.pos[0],vA=(Ce.pos[1]??0)+1.5,KA=Ce.pos[2],WA=nA-k.position.x,bA=vA-k.position.y,pe=KA-k.position.z,xe=Math.sqrt(WA*WA+pe*pe),it=Math.atan2(-WA,-pe),ve=Math.atan2(bA,Math.max(.001,xe)),re=1-Math.exp(-14*DA);let Qe=it-A.current;for(;Qe>Math.PI;)Qe-=2*Math.PI;for(;Qe<-Math.PI;)Qe+=2*Math.PI;Math.abs(Qe)<.018&&Math.abs(ve-t.current)<.018?(A.current=it,t.current=ve):(A.current=A.current+Qe*re,t.current=t.current+(ve-t.current)*re)}}let dA=0,UA=0;if(sA.current>0){const Ce=(rA-aA.current)/sA.current;if(Ce<1){const VA=eA.current*(1-Ce);dA=(Math.random()-.5)*VA,UA=(Math.random()-.5)*VA}else sA.current=0,eA.current=0}if(k.rotation.y=A.current+UA,k.rotation.x=t.current+Z.current+dA,k instanceof Wo){const Ce=B.current?45:70,VA=1-Math.exp(-8*DA),nA=k.fov+(Ce-k.fov)*VA;Math.abs(nA-k.fov)>.01&&(k.fov=nA,k.updateProjectionMatrix())}const TA=l.current,oe=z.current;let me=0,be=0;if(TA&&(TA.x!==0||TA.z!==0)){const Ce=A.current,VA=-Math.sin(Ce),nA=-Math.cos(Ce),vA=Math.cos(Ce),KA=-Math.sin(Ce),WA=Math.hypot(TA.x,TA.z),bA=WA<=yO?0:Math.min(1,(WA-yO)/(1-yO)),pe=WA||1,xe=TA.x/pe,it=TA.z/pe,ve=Iwe*(B.current?Cwe:1)*bA;me=(VA*it+vA*xe)*ve,be=(nA*it+KA*xe)*ve}const $e=me-oe.x,ci=be-oe.z,ke=Math.hypot($e,ci),nt=(me===0&&be===0?lwe:cwe)*DA;if(ke<=nt||ke<1e-4)oe.x=me,oe.z=be;else{const Ce=nt/ke;oe.x+=$e*Ce,oe.z+=ci*Ce}(Math.abs(oe.x)>1e-4||Math.abs(oe.z)>1e-4)&&(k.position.x+=oe.x*DA,k.position.z+=oe.z*DA,k.position.x=Math.max(qoA,Math.min(YoA,k.position.x)),k.position.z=Math.max(HoA,Math.min(OoA,k.position.z)),(k.position.x<=qoA&&oe.x<0||k.position.x>=YoA&&oe.x>0)&&(oe.x=0),(k.position.z<=HoA&&oe.z<0||k.position.z>=OoA&&oe.z>0)&&(oe.z=0));const Ut=new SA(0,0,-1).applyQuaternion(k.quaternion);let dt=null,Ht=vwe;const Ft=k.position;for(const Ce of w.current){if(Ce.state==="dead"||Ce.team==="ally"||Ce.spawnedAt&&rA-Ce.spawnedAt<VS)continue;const VA=Ce.pos[0]-Ft.x,nA=Ce.pos[1]+1-Ft.y,vA=Ce.pos[2]-Ft.z,KA=Math.hypot(VA,nA,vA)||1,WA=(Ut.x*VA+Ut.y*nA+Ut.z*vA)/KA;if(WA>Ht){if(isA.copy(Ft),nsA.set(Ce.pos[0],Ce.pos[1]+1,Ce.pos[2]),ZA(isA,nsA))continue;Ht=WA,dt=Ce.id}}U.current=dt;const Jt=dt!==null;Jt!==T.current&&(T.current=Jt,m==null||m(Jt));const $A=fA.current,He=RA.current,Xe=gA.current;for(let Ce=0;Ce<OQ;Ce++){const VA=Xe[Ce],nA=Ce*6;VA&&VA.untilAt>rA?($A[nA+0]=VA.a.x,$A[nA+1]=VA.a.y,$A[nA+2]=VA.a.z,$A[nA+3]=VA.b.x,$A[nA+4]=VA.b.y,$A[nA+5]=VA.b.z,He[nA+0]=VA.color.r,He[nA+1]=VA.color.g,He[nA+2]=VA.color.b,He[nA+3]=VA.color.r,He[nA+4]=VA.color.g,He[nA+5]=VA.color.b):($A[nA+0]=0,$A[nA+1]=-1e3,$A[nA+2]=0,$A[nA+3]=0,$A[nA+4]=-1e3,$A[nA+5]=0,He[nA+0]=0,He[nA+1]=0,He[nA+2]=0,He[nA+3]=0,He[nA+4]=0,He[nA+5]=0)}const St=yA.current;St&&(St.getAttribute("position").needsUpdate=!0,St.getAttribute("color").needsUpdate=!0);const kA=W.current;if(kA){const Ce=new SA,VA=new oo,nA=new SA(0,1,0),vA=new Et,KA=new ni().makeTranslation(0,-1e4,0);for(let WA=0;WA<OQ;WA++){const bA=Xe[WA];if(!bA||bA.untilAt<=rA){kA.setMatrixAt(WA,KA),kA.instanceColor&&vA.setRGB(0,0,0).toArray(kA.instanceColor.array,WA*3);continue}const pe=Math.max(1,bA.untilAt-bA.bornAt),xe=Math.min(1,(rA-bA.bornAt)/pe);bA.aLocal&&(bA.a.copy(bA.aLocal).applyQuaternion(k.quaternion).add(k.position),bA.b.set(0,0,-1).applyQuaternion(k.quaternion).multiplyScalar(bA.length).add(bA.a)),Ce.subVectors(bA.b,bA.a);const it=Ce.length()||1e-4;Ce.divideScalar(it);const ve=Math.min(it,1.2),re=Math.min(it,xe*(it+ve)),Qe=Math.max(0,re-ve),HA=bA.a.clone().add(Ce.clone().multiplyScalar(Qe)),ge=Math.max(1e-4,re-Qe);VA.setFromUnitVectors(nA,Ce);const ye=.02,Te=new ni().compose(HA,VA,new SA(ye,ge,ye));kA.setMatrixAt(WA,Te);const gt=1-xe*xe;kA.setColorAt(WA,vA.copy(bA.color).multiplyScalar(gt))}kA.instanceMatrix.needsUpdate=!0,kA.instanceColor&&(kA.instanceColor.needsUpdate=!0)}const se=tA.current;if(se){const Ce=new ni,VA=new Et,nA=new ni().makeTranslation(0,-1e4,0);for(let vA=0;vA<SO;vA++){const KA=P.current[vA],WA=KA?rA-KA.bornAt:1/0;if(!KA||WA>gsA){se.setMatrixAt(vA,nA),se.instanceColor&&VA.setRGB(0,0,0).toArray(se.instanceColor.array,vA*3);continue}const bA=WA/gsA,pe=.05+bA*.07;Ce.makeRotationX(-Math.PI/2).setPosition(KA.pos.x,.02,KA.pos.z).scale(new SA(pe,pe,pe));const xe=new ni().compose(new SA(KA.pos.x,.02,KA.pos.z),new oo().setFromEuler(new ca(-Math.PI/2,0,0)),new SA(pe,pe,pe));se.setMatrixAt(vA,xe);const it=1-bA;se.setColorAt(vA,VA.copy(KA.color).multiplyScalar(it))}se.instanceMatrix.needsUpdate=!0,se.instanceColor&&(se.instanceColor.needsUpdate=!0)}}),E.useEffect(()=>()=>{var FA;w.current=[],gA.current=[],P.current=[],qA.dispose(),(FA=yA.current)==null||FA.dispose(),L.dispose(),$.dispose(),IA.dispose(),oA.dispose()},[qA,IA,oA,L,$]),C.jsxs(C.Fragment,{children:[C.jsx("fogExp2",{attach:"fog",args:[M.getHex(),.022]}),C.jsx("ambientLight",{intensity:1.6}),C.jsx("hemisphereLight",{color:15397375,groundColor:4864552,intensity:.95}),C.jsx("directionalLight",{position:[3,8,2],intensity:1.7,castShadow:!1}),C.jsx("directionalLight",{position:[-3,6,-8],intensity:.85}),C.jsx("pointLight",{position:[0,3.7,-3],distance:11,color:16777215,intensity:1.4,decay:1.6}),C.jsx("pointLight",{position:[0,3.7,-9],distance:11,color:16777215,intensity:1.3,decay:1.6}),C.jsx("pointLight",{position:[0,3.7,-15],distance:11,color:16777215,intensity:1.2,decay:1.6}),C.jsx("pointLight",{position:[0,3.7,-21],distance:11,color:16777215,intensity:1.1,decay:1.6}),C.jsx("pointLight",{position:[0,3.2,-30],distance:20,color:s,intensity:1.2}),C.jsx("pointLight",{position:[0,2.2,2],distance:9,color:16773336,intensity:.7}),C.jsx(xwe,{position:[0,3.4,-12]}),C.jsx("mesh",{rotation:[-Math.PI/2,0,0],position:[0,0,-78],material:X,children:C.jsx("planeGeometry",{args:[24,160]})}),w.current.map(FA=>C.jsx(Ewe,{enemy:FA,empireId:FA.team==="ally"?I:r},FA.id)),b.current.map((FA,Ie)=>C.jsxs("group",{children:[C.jsx("mesh",{position:[FA.x,.015,FA.z+.02],rotation:[-Math.PI/2,0,0],geometry:EA,material:PA,scale:[FA.hx*2*1.35,FA.hy*1.2,1],renderOrder:-1}),C.jsx("mesh",{position:[FA.x,FA.hy,FA.z],geometry:he,material:ie}),C.jsx("mesh",{position:[FA.x,FA.hy*2-.04,FA.z+.01],geometry:le,material:NA})]},`cover-${Ie}`)),C.jsx("instancedMesh",{ref:W,args:[$,L,OQ],frustumCulled:!1}),C.jsx("instancedMesh",{ref:tA,args:[oA,IA,SO],frustumCulled:!1})]})}),qwe=new URL("/assets/rifle-viewmodel-C29ujLaF.webp",import.meta.url).href,Ywe=new URL("/assets/rifle-muzzle-flash-B8EJ_3SY.webp",import.meta.url).href,Hwe=new URL("/assets/blood-burst-DiPNfQU_.webp",import.meta.url).href,osA=.0042,ssA=.0034,hv=.55,pv=.85,vmA=({attacker:e,defender:A,onComplete:t,botPilot:i=!1,previewMode:n=!1,tileBackgroundImage:g,skipBonus:o=!1})=>{const[s,a]=E.useState(n?"playing":"intro"),[r,I]=E.useState({playerHp:Bv,botHp:Xm*hp,kills:0}),[c,l]=E.useState(null),B=E.useRef(null),Q=E.useRef(null),h=E.useRef(0),d=E.useRef(0),p=E.useRef(0),y=E.useRef(0),m=E.useRef(Bv),D=E.useRef(Xm*hp),S=E.useRef(!1),k=E.useRef(0),N=E.useRef(t);N.current=t;const G=E.useRef(!1),M=E.useRef(0),[,w]=E.useState(0),b=E.useRef(Bv),_=E.useRef(0),[,K]=E.useState(0),J=E.useRef(null),[q,v]=E.useState(!1),U=E.useRef(0),[,x]=E.useState(0),T=E.useRef(0),[,z]=E.useState(0),[Z,eA]=E.useState([]),aA=E.useRef(0),[sA,pA]=E.useState(!1),gA=E.useRef(!1),yA=E.useCallback($A=>{gA.current=$A,pA($A)},[]),fA=E.useRef(null),RA=E.useRef(null),qA=E.useRef(new Set),W=E.useCallback(($A,He)=>{const Xe=window.setTimeout(()=>{qA.current.delete(Xe),$A()},He);return qA.current.add(Xe),Xe},[]);E.useEffect(()=>()=>{for(const Xe of qA.current)window.clearTimeout(Xe);qA.current.clear(),J.current!=null&&(window.clearInterval(J.current),J.current=null);const $A=RA.current;if($A)for($A.traverse(Xe=>{const St=Xe;if(St.geometry&&typeof St.geometry.dispose=="function")try{St.geometry.dispose()}catch{}const kA=St.material;if(kA){const se=Array.isArray(kA)?kA:[kA];for(const Ce of se)try{Ce.dispose()}catch{}}});$A.children.length;)$A.remove($A.children[0]);const He=fA.current;if(He){try{He.dispose()}catch{}try{const St=He.getContext();St&&!St.isContextLost()&&He.forceContextLoss()}catch{}const Xe=He.domElement;Xe&&Xe.parentElement&&(Xe.width=1,Xe.height=1),fA.current=null}RA.current=null},[]);const $=E.useRef(null);E.useEffect(()=>{var He;if(n){(He=$.current)==null||He.stop();return}$.current||($.current=new hmA({src:lmA}));const $A=$.current;s==="intro"||s==="playing"?$A.play():s==="result"&&$A.stop()},[s,n]),E.useEffect(()=>()=>{var $A;($A=$.current)==null||$A.dispose(),$.current=null},[]);const L=E.useRef({x:0,z:0}),H=E.useRef({w:!1,a:!1,s:!1,d:!1}),P=E.useRef(!1),[tA,iA]=E.useState(!1),oA=.5,IA=E.useRef(null),[CA,_A]=E.useState(0),[uA,X]=E.useState(!1),O=E.useCallback(()=>{const $A=H.current,He=($A.d?1:0)+($A.a?-1:0),Xe=($A.w?1:0)+($A.s?-1:0);L.current={x:He,z:Xe}},[]);E.useEffect(()=>{if(s!=="playing"||tA){_A(0);return}const $A=.97,He=.875,Xe=-137,St=()=>{const Ce=IA.current;if(!Ce)return;const VA=Ce.getBoundingClientRect();if(VA.width<=0||VA.height<=0)return;const nA=VA.right-$A*VA.width,vA=VA.bottom-He*VA.height,KA=window.innerWidth*.5,WA=window.innerHeight*.5,bA=Math.atan2(WA-vA,KA-nA)*(180/Math.PI);_A(bA-Xe)},kA=window.requestAnimationFrame(St),se=new ResizeObserver(St);return IA.current&&se.observe(IA.current),window.addEventListener("resize",St),window.addEventListener("orientationchange",St),()=>{window.cancelAnimationFrame(kA),se.disconnect(),window.removeEventListener("resize",St),window.removeEventListener("orientationchange",St)}},[s,tA]);const[cA,wA]=E.useState({active:!1,baseX:0,baseY:0,knobX:0,knobY:0}),xA=E.useRef(null),YA=E.useMemo(()=>{const $A=xJ[A.piece];return($A==null?void 0:$A.accent)??16724804},[A.piece]),jA=E.useMemo(()=>{const $A=xJ[e.piece];return($A==null?void 0:$A.accent)??6750105},[e.piece]),ie=E.useCallback($A=>{if(!G.current){G.current=!0,S.current=!1,l($A),a("result");try{pa({volume:.5})}catch{}W(()=>N.current($A),YSe)}},[e,W]),he=E.useCallback(()=>{ie(PoA(e,A,!1,!0))},[e,A,ie]),le=E.useCallback($A=>{ie(PoA(e,A,!0,$A))},[e,A,ie]),NA=E.useCallback($A=>{B.current===null&&(B.current=$A,S.current=!1,a("kill-cam"),W(()=>{$A?o||i?le(i?Math.random()<.6:!0):a("codebreaker"):he()},HSe))},[he,le,W,o,i]);E.useCallback($A=>{G.current||B.current!==null||NA($A)},[NA]),E.useEffect(()=>{if(!i||s!=="playing")return;L.current={x:0,z:0};const $A=window.setInterval(()=>{var He;if(S.current&&gA.current){(He=Q.current)==null||He.fire();try{Tc({volume:.22})}catch{}}},fO);return()=>{window.clearInterval($A),L.current={x:0,z:0}}},[i,s]),E.useEffect(()=>{if(n){k.current=performance.now(),S.current=!0;return}if(s!=="intro")return;const $A=window.setTimeout(()=>{k.current=performance.now(),S.current=!0,a("playing")},qSe);return()=>window.clearTimeout($A)},[s,n]),E.useEffect(()=>{if(s!=="playing")return;let $A=0;const He=()=>{const Xe=m.current,St=D.current;Xe<b.current&&(_.current=performance.now()+280,K(vA=>vA+1)),b.current=Xe,I({playerHp:Xe,botHp:St,kills:p.current});const kA=L.current,se=!!(kA&&(kA.x!==0||kA.z!==0));X(vA=>vA!==se?se:vA);const Ce=performance.now()-k.current,VA=NmA+200;if(!n&&Ce>=VA&&St<=0&&B.current===null){NA(!0);return}const nA=performance.now()-k.current;if(!n&&nA>=TSe&&B.current===null){NA(Xe>=St);return}$A=requestAnimationFrame(He)};return $A=requestAnimationFrame(He),()=>cancelAnimationFrame($A)},[s,NA]);const EA=E.useRef({active:!1,lastX:0,lastY:0}),PA=E.useCallback($A=>{var He,Xe;S.current&&(EA.current={active:!0,lastX:$A.clientX,lastY:$A.clientY},(Xe=(He=$A.target).setPointerCapture)==null||Xe.call(He,$A.pointerId))},[]),ZA=E.useCallback($A=>{const He=EA.current;if(!He.active)return;const Xe=$A.clientX-He.lastX,St=$A.clientY-He.lastY;He.lastX=$A.clientX,He.lastY=$A.clientY;const kA=P.current?oA:1;h.current=Math.max(-pv,Math.min(pv,h.current-Xe*osA*kA)),d.current=Math.max(-hv,Math.min(hv,d.current-St*ssA*kA))},[]),FA=E.useCallback(()=>{EA.current.active=!1},[]),Ie=E.useCallback(()=>{var $A;if(S.current){($A=Q.current)==null||$A.fire();try{Tc({volume:.28})}catch{}}},[]),DA=E.useRef(null),rA=E.useCallback($A=>{var He,Xe;if($A.preventDefault(),!!S.current){Ie(),v(!0),J.current!=null&&window.clearInterval(J.current),J.current=window.setInterval(Ie,fO);try{(Xe=(He=$A.target).setPointerCapture)==null||Xe.call(He,$A.pointerId)}catch{}DA.current={id:$A.pointerId,lastX:$A.clientX,lastY:$A.clientY}}},[Ie]),BA=E.useCallback($A=>{const He=DA.current;if(!He||He.id!==$A.pointerId)return;const Xe=$A.clientX-He.lastX,St=$A.clientY-He.lastY;He.lastX=$A.clientX,He.lastY=$A.clientY;const kA=P.current?oA:1;h.current=Math.max(-pv,Math.min(pv,h.current-Xe*osA*kA)),d.current=Math.max(-hv,Math.min(hv,d.current-St*ssA*kA))},[]),j=E.useCallback(()=>{v(!1),J.current!=null&&(window.clearInterval(J.current),J.current=null),DA.current=null},[]);E.useEffect(()=>()=>{J.current!=null&&window.clearInterval(J.current)},[]);const QA=E.useCallback(()=>{if(!S.current)return;const $A=!P.current;P.current=$A,iA($A)},[]),dA=E.useCallback($A=>{!S.current&&$A||P.current!==$A&&(P.current=$A,iA($A))},[]);E.useEffect(()=>{const $A=St=>{St.button===2&&dA(!0)},He=St=>{St.button===2&&dA(!1)},Xe=St=>{St.preventDefault()};return window.addEventListener("mousedown",$A),window.addEventListener("mouseup",He),window.addEventListener("contextmenu",Xe),()=>{window.removeEventListener("mousedown",$A),window.removeEventListener("mouseup",He),window.removeEventListener("contextmenu",Xe)}},[dA]),E.useEffect(()=>{const $A=kA=>{const se=kA,Ce=se==null?void 0:se.tagName;return Ce==="INPUT"||Ce==="TEXTAREA"||Ce==="SELECT"||!!(se!=null&&se.isContentEditable)},He=(kA,se)=>{const Ce=H.current;switch(kA){case"KeyW":case"ArrowUp":Ce.w=se;break;case"KeyS":case"ArrowDown":Ce.s=se;break;case"KeyA":case"ArrowLeft":Ce.a=se;break;case"KeyD":case"ArrowRight":Ce.d=se;break;default:return}return O(),!0},Xe=kA=>{if(!S.current||$A(kA.target))return;if(He(kA.code,!0)){kA.preventDefault();return}if(kA.code==="Space"||kA.code==="KeyF"){if(kA.preventDefault(),kA.repeat)return;v(!0),Ie(),J.current!=null&&window.clearInterval(J.current),J.current=window.setInterval(Ie,fO);return}(kA.code==="ShiftLeft"||kA.code==="ShiftRight")&&(kA.preventDefault(),dA(!0))},St=kA=>{if(He(kA.code,!1)){kA.preventDefault();return}if(kA.code==="Space"||kA.code==="KeyF"){kA.preventDefault(),j();return}(kA.code==="ShiftLeft"||kA.code==="ShiftRight")&&(kA.preventDefault(),dA(!1))};return window.addEventListener("keydown",Xe),window.addEventListener("keyup",St),()=>{window.removeEventListener("keydown",Xe),window.removeEventListener("keyup",St),j(),dA(!1)}},[Ie,j,O,dA]);const UA=56,TA=E.useCallback($A=>{var He,Xe;S.current&&xA.current==null&&(xA.current=$A.pointerId,(Xe=(He=$A.target).setPointerCapture)==null||Xe.call(He,$A.pointerId),wA({active:!0,baseX:$A.clientX,baseY:$A.clientY,knobX:$A.clientX,knobY:$A.clientY}),L.current={x:0,z:0})},[]),oe=E.useCallback($A=>{xA.current===$A.pointerId&&wA(He=>{if(!He.active)return He;const Xe=$A.clientX-He.baseX,St=$A.clientY-He.baseY,kA=Math.hypot(Xe,St),se=Math.min(kA,UA),Ce=kA>0?Xe/kA:0,VA=kA>0?St/kA:0,nA=se/UA;return L.current={x:Ce*nA,z:-VA*nA},{...He,knobX:He.baseX+Ce*se,knobY:He.baseY+VA*se}})},[]),me=E.useCallback($A=>{xA.current===$A.pointerId&&(xA.current=null,wA({active:!1,baseX:0,baseY:0,knobX:0,knobY:0}),O())},[O]),be=(c==null?void 0:c.winnerId)===e.id,$e=performance.now(),ci=M.current>$e,ke=_.current>$e,nt=U.current>$e,Ut=T.current>$e,dt="/zentara/soldier/intro-key-art.webp",Ht=be?"/zentara/soldier/result-win.webp":"/zentara/soldier/result-loss.webp",Ft=`#${jA.toString(16).padStart(6,"0")}`,Jt=`#${YA.toString(16).padStart(6,"0")}`;return C.jsxs("div",{className:`soldier-raid-root${tA?" ads":""}`,style:{"--soldier-ally":Ft,"--soldier-enemy":Jt},role:"dialog","aria-modal":"true","aria-label":"Ground Assault",children:[C.jsxs("div",{className:"soldier-raid-canvas-wrap",style:g?{backgroundImage:`url(${g})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"}:void 0,children:[C.jsx(QG,{dpr:[1,Bwe],camera:{fov:70,near:.1,far:80,position:[0,1.6,0]},gl:{antialias:!1,powerPreference:"low-power",alpha:!0},onCreated:({gl:$A,scene:He})=>{fA.current=$A,RA.current=He,$A.setClearColor(new Et(0),0),$A.shadowMap.enabled=!1},children:C.jsx(Twe,{ref:Q,yawRef:h,pitchRef:d,killsRef:p,totalSpawnedRef:y,playerHpRef:m,botHpRef:D,activeRef:S,moveRef:L,adsRef:P,enemyAccent:YA,allyAccent:jA,allyEmpire:e.piece,enemyEmpire:A.piece,botPilot:i,onPlayerDied:()=>{n||NA(!1)},onShotFired:$A=>{M.current=performance.now()+90,w(He=>He+1),$A&&(T.current=performance.now()+180,z(He=>He+1))},onEnemyFired:()=>{_.current=performance.now()+200,K($A=>$A+1)},onCombatantFired:$A=>{try{Tc({volume:$A?.14:.18})}catch{}},onEnemyKilled:()=>{U.current=performance.now()+320,x(Xe=>Xe+1);const $A=++aA.current,He=performance.now();eA(Xe=>[...Xe,{id:$A,bornAt:He}]),W(()=>{eA(Xe=>Xe.filter(St=>St.id!==$A))},900)},onLockChange:yA})}),C.jsx("div",{className:"soldier-vignette","aria-hidden":"true"}),C.jsx("div",{className:"soldier-color-grade","aria-hidden":"true"}),s==="playing"&&C.jsxs(C.Fragment,{children:[C.jsx("div",{className:`soldier-weapon-wrap${tA?" ads":""}`,"aria-hidden":"true",ref:IA,children:C.jsxs("div",{className:`soldier-weapon-pivot${tA?" ads":""}`,style:{transform:tA?"none":`rotate(${CA.toFixed(3)}deg)`},children:[C.jsx("img",{src:qwe,alt:"","aria-hidden":"true",className:`soldier-viewmodel${tA?" ads":""}${q?" firing":""}${ci?" recoil":""}${uA?" walking":""}`,draggable:!1}),ci&&!tA&&C.jsx("img",{src:Ywe,alt:"","aria-hidden":"true",className:"soldier-muzzle-flash",draggable:!1})]})}),nt&&C.jsx("img",{src:Hwe,alt:"","aria-hidden":"true",className:"soldier-blood-burst",draggable:!1})]}),ke&&C.jsx("div",{className:"soldier-damage-vignette"})]}),!i&&C.jsx("div",{className:"soldier-look-pad",onPointerDown:PA,onPointerMove:ZA,onPointerUp:FA,onPointerCancel:FA}),!i&&C.jsx("div",{className:"soldier-move-pad",onPointerDown:TA,onPointerMove:oe,onPointerUp:me,onPointerCancel:me,children:cA.active&&C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"soldier-move-stick-base",style:{left:cA.baseX,top:cA.baseY}}),C.jsx("div",{className:"soldier-move-stick-knob",style:{left:cA.knobX,top:cA.knobY}})]})}),!n&&C.jsxs("div",{className:"soldier-hud",children:[C.jsx("div",{className:"soldier-hud-top duel",children:C.jsxs("div",{className:"soldier-duel-portrait enemy",children:[C.jsx("span",{className:"soldier-duel-role",children:"Hostile force"}),C.jsx("span",{className:"soldier-duel-name",children:Xi(A.piece)}),C.jsx("div",{className:"soldier-duel-hp-bar enemy",children:C.jsx("div",{className:"soldier-duel-hp-fill enemy",style:{width:`${Math.max(0,Math.min(100,r.botHp/(Xm*hp)*100))}%`}})}),C.jsx("span",{className:"soldier-duel-hp-value",children:Math.max(0,Math.ceil(r.botHp))})]})}),s==="playing"&&C.jsx("div",{className:`soldier-reticle${sA?" locked":""}`}),s==="playing"&&Ut&&C.jsx("div",{className:"soldier-hit-marker","aria-hidden":"true"}),s==="playing"&&C.jsxs("div",{className:"soldier-kill-counter","aria-label":"Enemies down",children:[C.jsx("span",{className:"soldier-kill-counter-value",children:r.kills}),C.jsx("span",{className:"soldier-kill-counter-sep",children:"/"}),C.jsx("span",{className:"soldier-kill-counter-total",children:hp})]}),s==="playing"&&Z.length>0&&C.jsx("div",{className:"soldier-kill-toast-stack","aria-hidden":"true",children:Z.map($A=>C.jsx("span",{className:"soldier-kill-toast",children:"ENEMY DOWN"},$A.id))}),C.jsxs("div",{className:"soldier-duel-portrait player",children:[C.jsx("span",{className:"soldier-duel-role",children:"Strike team"}),C.jsx("span",{className:"soldier-duel-name",children:Xi(e.piece)}),C.jsx("div",{className:"soldier-hp-bar",children:C.jsx("div",{className:"soldier-hp-bar-fill",style:{width:`${Math.max(0,Math.min(100,r.playerHp/Bv*100))}%`}})}),C.jsx("span",{className:"soldier-duel-hp-value",children:Math.max(0,Math.ceil(r.playerHp))})]})]}),s==="playing"&&!i&&C.jsxs("button",{type:"button",className:`soldier-fire-btn${q?" active":""}`,onPointerDown:rA,onPointerMove:BA,onPointerUp:j,onPointerCancel:j,"aria-label":"Fire",children:[C.jsx("span",{className:"soldier-fire-btn-icon","aria-hidden":"true"}),C.jsx("span",{className:"soldier-fire-btn-label",children:"FIRE"})]}),s==="playing"&&!i&&C.jsxs("button",{type:"button",className:`soldier-ads-btn${tA?" active":""}`,onPointerDown:$A=>{$A.preventDefault(),QA()},"aria-label":"Aim Down Sights","aria-pressed":tA,children:[C.jsx("span",{className:"soldier-ads-btn-icon","aria-hidden":"true"}),C.jsx("span",{className:"soldier-ads-btn-label",children:"ADS"})]}),!n&&s==="intro"&&C.jsxs("div",{className:"soldier-splash",style:{backgroundImage:`linear-gradient(180deg, rgba(2,5,10,0.28), rgba(2,5,10,0.82)), url(${dt})`},children:[C.jsx("span",{className:"soldier-splash-kicker",children:"Tactical encounter"}),C.jsx("h2",{children:"Faction Duel"}),C.jsxs("p",{children:[Xi(e.piece)," vs. ",Xi(A.piece)]}),C.jsxs("p",{children:["1v1 — eliminate your opponent to claim ",MmA," energy."]})]}),s==="kill-cam"&&C.jsx("div",{className:`soldier-kill-cam ${B.current?"win":"loss"}`,children:C.jsx("span",{className:"soldier-kill-cam-text",children:B.current?"ENEMY DOWN":"ELIMINATED"})}),s==="codebreaker"&&C.jsx(kmA,{attacker:e,defender:A,onComplete:$A=>le($A.winnerId===e.id)}),s==="result"&&c&&C.jsxs("div",{className:`soldier-splash ${be?"win":"loss"}`,style:{backgroundImage:`linear-gradient(180deg, rgba(2,5,10,0.24), rgba(2,5,10,0.82)), url(${Ht})`},children:[C.jsx("span",{className:"soldier-splash-kicker",children:"Combat report"}),C.jsx("h2",{children:be?"Duel Won":"Duel Lost"}),c.creditsStolen>0&&C.jsxs("p",{children:["✦ ",c.creditsStolen.toLocaleString()," energy ",be?"seized":"forfeited"]})]})]})},Owe=Object.freeze(Object.defineProperty({__proto__:null,default:vmA},Symbol.toStringTag,{value:"Module"})),KmA="/models/zentara_ship.glb",wO=2.4,Pwe=.4,jwe=6;function zwe({tint:e}){const A=E.useRef(null),t=E.useRef(performance.now()),i=Ur(KmA),n=E.useMemo(()=>{const g=i.scene.clone(!0),o=new Ag().setFromObject(g),s=new SA;o.getSize(s);const r=2/(Math.max(s.x,s.y,s.z)||1);g.scale.setScalar(r);const I=new Ag().setFromObject(g),c=new SA;if(I.getCenter(c),g.position.sub(c),e){const l=new Et(e);g.traverse(B=>{const Q=B;if(Q.isMesh&&Q.material){const h=Q.material.clone();"color"in h&&h.color.lerp(l,.55),Q.material=h}})}return g},[i.scene,e]);return Ba(()=>{if(!A.current)return;const g=(performance.now()-t.current)/1e3,o=Math.min(1,g/jwe),s=1-Math.pow(1-o,3),a=wO+(Pwe-wO)*s;A.current.scale.setScalar(a);const r=g,I=Math.sin(r*.55)*.55+Math.sin(r*1.7)*.12;A.current.rotation.z=I,A.current.rotation.y=Math.PI+Math.sin(r*.45)*.18,A.current.position.y=Math.sin(r*.6)*.08,A.current.position.x=Math.sin(r*.33)*.18+I*.12}),C.jsxs("group",{ref:A,rotation:[-.18,Math.PI,0],scale:wO,children:[C.jsx("primitive",{object:n}),C.jsx(asA,{tint:e,offsetX:-.35}),C.jsx(asA,{tint:e,offsetX:.35})]})}function asA({tint:e,offsetX:A}){const t=E.useRef(null),i=E.useRef(null),n=E.useRef(null),g=E.useRef(null),o=E.useRef(null),s=E.useRef(null),a=E.useMemo(()=>new Et("#e6f4ff"),[]),r=E.useMemo(()=>{const I=new Et("#6cb8ff");return e&&I.lerp(new Et(e),.5),I},[e]);return Ba(()=>{const I=performance.now()*.001,c=.82+.18*Math.sin(I*33+A*5)*Math.sin(I*11),l=.88+.12*Math.sin(I*4.2),B=c*l;if(i.current&&t.current){i.current.opacity=Math.min(1,1.4*B);const Q=1+.12*Math.sin(I*9+A*7);t.current.scale.set(Q,Q*1.4,1)}if(g.current&&n.current){g.current.opacity=.95*B;const Q=1+.22*Math.sin(I*6+A*3);n.current.scale.set(Q,Q*1.15,1)}if(s.current&&o.current){s.current.opacity=.7*B;const Q=1+.45*Math.sin(I*7+A*2);o.current.scale.set(.95,Q,1)}}),C.jsxs("group",{position:[A,-.05,-1],children:[C.jsxs("mesh",{ref:n,children:[C.jsx("planeGeometry",{args:[1.6,1.6]}),C.jsx("meshBasicMaterial",{ref:g,color:r,transparent:!0,opacity:.95,blending:io,depthWrite:!1,toneMapped:!1})]}),C.jsxs("mesh",{ref:t,children:[C.jsx("planeGeometry",{args:[.8,.8]}),C.jsx("meshBasicMaterial",{ref:i,color:a,transparent:!0,opacity:1,blending:io,depthWrite:!1,toneMapped:!1})]}),C.jsxs("mesh",{ref:o,position:[0,-.7,-.05],children:[C.jsx("planeGeometry",{args:[.55,2.2]}),C.jsx("meshBasicMaterial",{ref:s,color:r,transparent:!0,opacity:.7,blending:io,depthWrite:!1,toneMapped:!1})]})]})}const FmA=({tint:e,size:A=140})=>C.jsx("div",{style:{width:A,height:A,pointerEvents:"none"},children:C.jsxs(QG,{orthographic:!0,camera:{position:[0,0,5],zoom:32,near:.1,far:100},gl:{alpha:!0,antialias:!0,powerPreference:"high-performance"},style:{background:"transparent"},children:[C.jsx("ambientLight",{intensity:.55}),C.jsx("directionalLight",{position:[3,4,5],intensity:1.3,color:"#fff1d4"}),C.jsx("directionalLight",{position:[-3,-1,-2],intensity:.7,color:"#6cc8ff"}),C.jsx(E.Suspense,{fallback:null,children:C.jsx(zwe,{tint:e})})]})});var caA;try{(caA=Ur.preload)==null||caA.call(Ur,KmA)}catch{}const qN=18,fv=26,yv=3,rsA=1100,IsA=3500,Dv=22,Zwe=.16,Wwe=.24,Vwe={1:1,2:1.2,3:1.4,4:1.6,5:1.8,6:2},mv=1e4,kO=2,CsA=5e3,Sv=2e3,Xwe=600,PQ=["READY","3","2","1","FIRE"],csA="zentara.sniper.coachmark.v1",$we=Ym.bullseye*qN,A0e=Ym.hit*qN,MO=Ym.graze*qN,_mA=({defender:e,onComplete:A,groupColor:t="#9d4edd",botPilot:i=!1})=>{const[n,g]=E.useState(!1),[o,s]=E.useState(null),[a,r]=E.useState(!1),[I,c]=E.useState(null),[l,B]=E.useState(!1),[Q,h]=E.useState(kO),d=E.useRef("miss"),p=E.useMemo(()=>{const jA=e.heroId?ms[e.heroId]:void 0,ie=(jA==null?void 0:jA.tier)??1;return Zwe*Vwe[ie]},[e.heroId]),[y,m]=E.useState(null),[D,S]=E.useState(0),k=E.useRef(!1),[N,G]=E.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(csA)!=="seen"}catch{return!1}}),M=E.useRef(typeof window<"u"&&window.__sniperDebug===!0),w=E.useRef(null),b=E.useRef(null),_=E.useRef(null),K=E.useRef(null),J=E.useRef(null),q=E.useRef(null),v=E.useRef(null),U=E.useRef(null),x=E.useRef(performance.now()),T=E.useRef({x:0,y:0}),z=E.useRef({x:0,y:0}),Z=E.useRef(0),eA=E.useRef((Math.random()-.5)*Dv),aA=E.useRef({x:0,y:0}),sA=E.useRef({up:!1,down:!1,left:!1,right:!1}),pA=E.useRef(null),gA=E.useRef("none"),yA=1,fA=220,RA=260,qA=E.useCallback((jA,ie)=>{const he=Math.sqrt(jA*jA+ie*ie);if(he>fA){const le=fA/he;aA.current={x:jA*le,y:ie*le}}else aA.current={x:jA,y:ie}},[]);E.useEffect(()=>{if(M.current){k.current=!0,S(PQ.length-1);return}let jA=0;S(jA);const ie=window.setInterval(()=>{if(jA+=1,jA>=PQ.length){window.clearInterval(ie),k.current=!0,x.current=performance.now(),S(PQ.length);return}S(jA),So("Light").catch(()=>{})},Xwe);return()=>window.clearInterval(ie)},[]),E.useEffect(()=>{AM({volume:.35})},[]),E.useEffect(()=>{let jA=0;const ie=()=>{const he=performance.now(),le=(he-x.current)/1e3,NA=J.current;if(!NA){jA=requestAnimationFrame(ie);return}const EA=NA.clientWidth,PA=NA.clientHeight,ZA=EA/2+Math.sin(le*Math.PI*2*p)*EA*Wwe,FA=PA/2+Math.cos(le*Math.PI*2*p*.6)*30;T.current={x:ZA,y:FA};const Ie=_.current;Ie&&(Ie.style.left=`${ZA}px`,Ie.style.top=`${FA}px`);const DA=K.current;if(DA){const dt=ZA-Z.current,Ht=Math.max(-18,Math.min(18,dt*1.2));DA.style.transform=`rotate(${Ht}deg)`}Z.current=ZA;let rA=fv;if(o!==null){const dt=he-o;dt<=rsA?rA=fv-(fv-yv)*(dt/rsA):dt<=IsA?rA=yv:rA=yv+(fv-yv)*Math.min(1,(dt-IsA)/600)}const BA=Math.sin(le*1.7)*rA+Math.cos(le*.9)*rA*.4+eA.current,j=Math.cos(le*1.3)*rA+Math.sin(le*2.1)*rA*.3,QA=aA.current,dA=BA+QA.x,UA=j+QA.y;z.current={x:EA/2+dA,y:PA/2+UA};const TA=w.current;TA&&(TA.style.transform=`translate(calc(-50% + ${dA}px), calc(-50% + ${UA}px))`);const oe=b.current;if(oe){const dt=Math.max(20,rA*4);oe.style.width=`${dt}px`,oe.style.height=`${dt}px`}const me=z.current.x-ZA,be=z.current.y-FA,$e=Math.sqrt(me*me+be*be);let ci="none";if($e<=$we?ci="bullseye":$e<=A0e?ci="hit":$e<=MO&&(ci="graze"),ci!==gA.current){const dt=gA.current;gA.current=ci,TA&&(TA.classList.toggle("locked-graze",ci==="graze"),TA.classList.toggle("locked-hit",ci==="hit"),TA.classList.toggle("locked-bullseye",ci==="bullseye")),a||(ci==="bullseye"&&dt!=="bullseye"?So("Medium").catch(()=>{}):ci==="hit"&&(dt==="none"||dt==="graze")&&So("Light").catch(()=>{}))}const ke=U.current;ke&&(ke.textContent=`RANGE ▸ ${($e/qN).toFixed(1)}°`);const nt=k.current?Math.max(0,mv-(he-x.current)):mv,Ut=v.current;if(Ut){Ut.textContent=`⏱ ${(nt/1e3).toFixed(1)}s`;const dt=nt<Sv;Ut.classList.toggle("zentara-sniper-hud-block--urgent",dt)}if(NA){let dt=0;nt<Sv?dt=1:nt<CsA&&(dt=.5*(1-(nt-Sv)/(CsA-Sv))),NA.style.setProperty("--pressure",dt.toFixed(3))}a||(jA=requestAnimationFrame(ie))};return jA=requestAnimationFrame(ie),()=>cancelAnimationFrame(jA)},[o,a,p]);const W=E.useCallback(()=>{a||(g(!0),s(performance.now()),So("Light").catch(()=>{}))},[a]),$=E.useCallback(()=>{g(!1),setTimeout(()=>s(null),50)},[]),L=E.useCallback(jA=>{pA.current={x:jA.clientX,y:jA.clientY,ax:aA.current.x,ay:aA.current.y};try{jA.currentTarget.setPointerCapture(jA.pointerId)}catch{}},[]),H=E.useCallback(jA=>{const ie=pA.current;if(!ie)return;const he=ie.ax+(jA.clientX-ie.x)*yA,le=ie.ay+(jA.clientY-ie.y)*yA;qA(he,le)},[qA]),P=E.useCallback(jA=>{pA.current=null;try{jA.currentTarget.releasePointerCapture(jA.pointerId)}catch{}},[]),tA=E.useCallback(jA=>{a||jA.target.closest(".zentara-sniper-btn, .zentara-sniper-controls, .zentara-sniper-pad-zone, .zentara-sniper-fire-btn")||L(jA)},[a,L]),iA=H,oA=P,IA=E.useCallback(jA=>{a||(jA.stopPropagation(),W(),L(jA))},[a,W,L]),CA=E.useCallback(jA=>{pA.current&&(jA.stopPropagation(),H(jA))},[H]),_A=E.useCallback(jA=>{!pA.current&&!n||(jA.stopPropagation(),P(jA),$())},[n,P,$]),uA=E.useCallback(()=>{const jA=q.current;jA&&jA.classList.remove("active");const ie=J.current;ie&&ie.classList.remove("zentara-sniper-overlay--slowmo");const he=_.current;he&&he.classList.remove("zentara-sniper-target--hit"),aA.current={x:0,y:0},pA.current=null,eA.current=(Math.random()-.5)*Dv,x.current=performance.now(),d.current="miss",h(kO),g(!1),s(null),B(!1),c(null),r(!1),m(null)},[]),X={miss:0,graze:1,hit:2,bullseye:3},O=E.useCallback(()=>{const jA=q.current;jA&&jA.classList.remove("active");const ie=J.current;ie&&ie.classList.remove("zentara-sniper-overlay--slowmo");const he=_.current;he&&he.classList.remove("zentara-sniper-target--hit"),aA.current={x:0,y:0},pA.current=null,eA.current=(Math.random()-.5)*Dv,x.current=performance.now(),g(!1),s(null),B(!1),c(null),r(!1),m(null)},[]),cA=E.useCallback(()=>{if(a||!k.current&&!M.current)return;r(!0),B(!0),So("Heavy").catch(()=>{}),Tc({volume:.8}),setTimeout(()=>B(!1),120);const jA=z.current.x-T.current.x,ie=z.current.y-T.current.y,le=Math.sqrt(jA*jA+ie*ie)/qN;let NA="miss";le<=Ym.bullseye?NA="bullseye":le<=Ym.hit?NA="hit":le<=Ym.graze&&(NA="graze");const EA=q.current,PA=J.current;if(EA&&PA){const ZA=PA.getBoundingClientRect(),FA=ZA.width/2,Ie=ZA.height-8,DA=T.current.x,rA=T.current.y;EA.setAttribute("x1",String(FA)),EA.setAttribute("y1",String(Ie)),EA.setAttribute("x2",String(DA)),EA.setAttribute("y2",String(rA));const BA=NA==="miss"?"#ff4d4d":NA==="graze"?"#ffa500":NA==="hit"?"#41e077":"#ffd700";EA.setAttribute("stroke",BA),EA.classList.add("active")}X[NA]>X[d.current]&&(d.current=NA),setTimeout(()=>{if(c(NA),NA!=="miss"){pa({volume:.7});const Ie=J.current;Ie&&Ie.classList.add("zentara-sniper-overlay--slowmo");const DA=_.current;DA&&DA.classList.add("zentara-sniper-target--hit"),m({id:performance.now(),x:T.current.x,y:T.current.y})}const ZA=Q-1;h(ZA);const FA=ZA<=0||NA!=="miss";M.current?FA||setTimeout(O,1200):FA?setTimeout(()=>A(d.current),NA==="miss"?1500:2e3):setTimeout(O,1200)},250)},[a,A,Q,O,X]),wA=E.useRef(null),xA=E.useRef(cA);xA.current=cA,E.useEffect(()=>{if(!i||a||!k.current)return;const jA=String(Q);if(wA.current===jA)return;wA.current=jA;const ie=setTimeout(()=>{const le=T.current,NA=z.current,EA=(Math.random()-.5)*MO*1.8,PA=(Math.random()-.5)*MO*1.8;aA.current.x+=le.x-NA.x+EA,aA.current.y+=le.y-NA.y+PA},500),he=setTimeout(()=>xA.current(),1400);return()=>{clearTimeout(ie),clearTimeout(he)}},[i,a,D,Q]),E.useEffect(()=>{let jA=0,ie=performance.now();const he=ZA=>{const FA=ZA,Ie=FA==null?void 0:FA.tagName;return Ie==="INPUT"||Ie==="TEXTAREA"||Ie==="SELECT"||!!(FA!=null&&FA.isContentEditable)},le=(ZA,FA)=>{const Ie=sA.current;switch(ZA){case"KeyW":case"ArrowUp":return Ie.up=FA,!0;case"KeyS":case"ArrowDown":return Ie.down=FA,!0;case"KeyA":case"ArrowLeft":return Ie.left=FA,!0;case"KeyD":case"ArrowRight":return Ie.right=FA,!0;default:return!1}},NA=()=>{const ZA=performance.now(),FA=Math.min(.05,Math.max(0,(ZA-ie)/1e3));if(ie=ZA,!a){const Ie=sA.current,DA=(Ie.right?1:0)-(Ie.left?1:0),rA=(Ie.down?1:0)-(Ie.up?1:0);if(DA!==0||rA!==0){const BA=Math.sqrt(DA*DA+rA*rA)||1,j=aA.current;qA(j.x+DA/BA*RA*FA,j.y+rA/BA*RA*FA)}}jA=requestAnimationFrame(NA)},EA=ZA=>{if(!he(ZA.target)){if(le(ZA.code,!0)){ZA.preventDefault();return}if(ZA.code==="ShiftLeft"||ZA.code==="ShiftRight"){ZA.preventDefault(),ZA.repeat||W();return}(ZA.code==="Space"||ZA.code==="Enter"||ZA.code==="KeyF")&&(ZA.preventDefault(),!ZA.repeat&&!a&&cA())}},PA=ZA=>{if(le(ZA.code,!1)){ZA.preventDefault();return}(ZA.code==="ShiftLeft"||ZA.code==="ShiftRight")&&(ZA.preventDefault(),$())};return jA=requestAnimationFrame(NA),window.addEventListener("keydown",EA),window.addEventListener("keyup",PA),()=>{cancelAnimationFrame(jA),window.removeEventListener("keydown",EA),window.removeEventListener("keyup",PA),sA.current={up:!1,down:!1,left:!1,right:!1},$()}},[$,cA,a,qA,W]),E.useEffect(()=>{if(a||M.current)return;const jA=window.setInterval(()=>{if(k.current&&performance.now()-x.current>=mv&&(window.clearInterval(jA),!a)){r(!0),c("miss");const ie=Q-1;h(ie),ie<=0?setTimeout(()=>A(d.current),1500):setTimeout(O,1200)}},100);return()=>window.clearInterval(jA)},[a,A,Q,O]);const YA=E.useCallback(()=>{G(!1);try{window.localStorage.setItem(csA,"seen")}catch{}},[]);return E.useEffect(()=>{if(!N||D<PQ.length)return;const jA=window.setTimeout(YA,2e3);return()=>window.clearTimeout(jA)},[N,YA,D]),C.jsxs("div",{className:"zentara-sniper-overlay",ref:J,onPointerDown:tA,onPointerMove:iA,onPointerUp:oA,onPointerCancel:oA,style:{touchAction:"none",cursor:a?"default":"crosshair"},children:[C.jsx("div",{className:"zentara-sniper-stars zentara-sniper-stars--back"}),C.jsx("div",{className:"zentara-sniper-stars zentara-sniper-stars--front"}),C.jsx("div",{className:"zentara-sniper-target",ref:_,children:C.jsx("div",{className:"zentara-sniper-target-bank",ref:K,children:C.jsx(FmA,{tint:e.pieceColor,size:140})})}),C.jsx("div",{className:"zentara-sniper-scope"}),C.jsx("svg",{className:"zentara-sniper-tracer-svg",overflow:"visible","aria-hidden":"true",children:C.jsx("line",{ref:q,x1:"0",y1:"0",x2:"0",y2:"0"})}),y&&C.jsx("img",{src:HZ,alt:"","aria-hidden":"true",className:"zentara-sniper-impact-explosion zentara-blast-explosion",style:{left:y.x,top:y.y}},y.id),C.jsxs("div",{className:"zentara-sniper-reticle",ref:w,children:[C.jsx("div",{className:"zentara-sniper-stability-ring",ref:b}),C.jsx("div",{className:"zentara-sniper-dot"}),C.jsx("div",{className:"zentara-sniper-wind-arrow",style:{"--wind-mag":`${Math.abs(eA.current)/Dv}`,"--wind-dir":eA.current>=0?"1":"-1"},"aria-hidden":"true"})]}),C.jsx("div",{className:"zentara-sniper-pressure-vignette"}),C.jsx("div",{className:"zentara-sniper-hud zentara-sniper-hud--top-left",children:C.jsxs("div",{className:"zentara-sniper-hud-block",children:["TARGET ▸ ",e.displayName.toUpperCase()]})}),C.jsxs("div",{className:"zentara-sniper-hud zentara-sniper-hud--top-right",children:[C.jsxs("div",{className:"zentara-sniper-hud-block",style:{color:t,borderColor:t},children:["🔫 ",Q,"/",kO]}),C.jsxs("div",{className:"zentara-sniper-hud-block",ref:v,style:{color:t,borderColor:t},children:["⏱ ",(mv/1e3).toFixed(1),"s"]})]}),C.jsx("div",{className:"zentara-sniper-hud zentara-sniper-hud--bottom-center",children:C.jsx("div",{className:"zentara-sniper-hud-block zentara-sniper-hud-block--range",ref:U,children:"RANGE ▸ —"})}),!a&&C.jsxs(C.Fragment,{children:[C.jsx("div",{"data-no-global-haptic":!0,className:`zentara-sniper-pad-zone${n?" active":""}`,onPointerDown:IA,onPointerMove:CA,onPointerUp:_A,onPointerCancel:_A,children:C.jsxs("div",{className:"zentara-sniper-pad-icon",children:[C.jsxs("svg",{width:"56",height:"56",viewBox:"0 0 48 48",fill:"none",children:[C.jsx("circle",{cx:"24",cy:"24",r:"22",stroke:"rgba(0,255,200,0.55)",strokeWidth:"2.5"}),C.jsx("circle",{cx:"24",cy:"24",r:"8",fill:"rgba(0,255,200,0.4)"}),C.jsx("path",{d:"M24 6 L24 14 M24 34 L24 42 M6 24 L14 24 M34 24 L42 24",stroke:"rgba(0,255,200,0.55)",strokeWidth:"2.5",strokeLinecap:"round"})]}),C.jsx("span",{className:"zentara-sniper-pad-label",children:n?"STEADY":"AIM"})]})}),C.jsx("button",{"data-no-global-haptic":!0,className:"zentara-sniper-fire-btn",onClick:jA=>{jA.stopPropagation(),cA()},children:"FIRE"})]}),a&&M.current&&I&&C.jsxs("div",{className:"zentara-sniper-controls zentara-sniper-controls--debug",children:[C.jsx("button",{className:"zentara-sniper-btn zentara-sniper-btn--fire",onClick:uA,children:"🔁 RESET (DEBUG)"}),C.jsx("button",{className:"zentara-sniper-btn zentara-sniper-btn--aim",onClick:()=>A(I),children:"✓ RESOLVE"})]}),l&&C.jsx("div",{className:"zentara-sniper-flash"}),!k.current&&D<PQ.length&&!M.current&&C.jsx("div",{className:"zentara-sniper-ready-overlay","aria-hidden":"true",children:C.jsx("div",{className:`zentara-sniper-ready-step zentara-sniper-ready-step--${PQ[D].toLowerCase()}`,children:PQ[D]},D)}),N&&D>=PQ.length&&C.jsxs("div",{className:"zentara-sniper-coachmark",onClick:jA=>{jA.stopPropagation(),YA()},children:[C.jsx("div",{className:"zentara-sniper-coachmark-line",children:"DRAG anywhere to aim"}),C.jsx("div",{className:"zentara-sniper-coachmark-line",children:"HOLD the AIM pad to steady"}),C.jsx("div",{className:"zentara-sniper-coachmark-line",children:"TAP FIRE to shoot"})]}),I&&C.jsxs("div",{className:`zentara-sniper-result ${I}`,children:[I==="bullseye"&&"🎯 BULLSEYE",I==="hit"&&"✅ HIT",I==="graze"&&"↘ GRAZE",I==="miss"&&"❌ MISS"]})]})},e0e=2400,t0e=({attacker:e,defender:A,groupColor:t="#9d4edd",onComplete:i})=>{const[n,g]=E.useState(null),o=E.useRef(!1),s=E.useRef(null);E.useEffect(()=>{let r=!1;return fetch("/zentara/spy-strike/sniper-intro.mp4",{method:"HEAD"}).then(I=>{r||g(I.ok)}).catch(()=>{r||g(!1)}),()=>{r=!0}},[]),E.useEffect(()=>{AM({volume:.5})},[]);const a=()=>{o.current||(o.current=!0,i())};return E.useEffect(()=>{if(n)return;const r=window.setTimeout(a,e0e);return()=>window.clearTimeout(r)},[n]),C.jsx("div",{className:"zentara-sniper-intro",style:{"--group-color":t},onClick:a,children:n?C.jsx("video",{ref:s,className:"zentara-sniper-intro-video",src:"/zentara/spy-strike/sniper-intro.mp4",autoPlay:!0,muted:!0,playsInline:!0,onEnded:a,onError:()=>g(!1)}):C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"zentara-sniper-intro-stars zentara-sniper-intro-stars--back"}),C.jsx("div",{className:"zentara-sniper-intro-stars zentara-sniper-intro-stars--mid"}),C.jsx("div",{className:"zentara-sniper-intro-stars zentara-sniper-intro-stars--front"}),C.jsx("div",{className:"zentara-sniper-intro-nebula"}),C.jsx("div",{className:"zentara-sniper-intro-target",children:C.jsx(FmA,{tint:A.pieceColor,size:120})}),C.jsx("div",{className:"zentara-sniper-intro-iris"}),C.jsxs("div",{className:"zentara-sniper-intro-reticle",children:[C.jsx("div",{className:"zentara-sniper-intro-crosshair zentara-sniper-intro-crosshair--v"}),C.jsx("div",{className:"zentara-sniper-intro-crosshair zentara-sniper-intro-crosshair--h"}),C.jsx("div",{className:"zentara-sniper-intro-tickring"})]}),C.jsxs("div",{className:"zentara-sniper-intro-hud",children:[C.jsx("div",{className:"zentara-sniper-intro-hud-line",children:"SCOPE ACQUIRING…"}),C.jsxs("div",{className:"zentara-sniper-intro-hud-line zentara-sniper-intro-hud-line--target",children:["TARGET ▸ ",A.displayName.toUpperCase()]}),C.jsxs("div",{className:"zentara-sniper-intro-hud-line zentara-sniper-intro-hud-line--shooter",children:["SHOOTER ▸ ",e.displayName.toUpperCase()]})]}),C.jsx("div",{className:"zentara-sniper-intro-skip",children:"TAP TO SKIP"})]})})},i0e="/assets/breach-success-B5KvPAf1.webp",n0e="/assets/spy-exposed-j5AkCokU.webp",g0e=Object.assign({"../../assets/heroes/azure-sovereignty-t1.webp":M5,"../../assets/heroes/azure-sovereignty-t2.webp":N5,"../../assets/heroes/azure-sovereignty-t3.webp":R5,"../../assets/heroes/azure-sovereignty-t4.webp":G5,"../../assets/heroes/azure-sovereignty-t5.webp":b5,"../../assets/heroes/azure-sovereignty-t6.webp":U5,"../../assets/heroes/crimson-dominion-t1.webp":v5,"../../assets/heroes/crimson-dominion-t2.webp":K5,"../../assets/heroes/crimson-dominion-t3.webp":F5,"../../assets/heroes/crimson-dominion-t4.webp":_5,"../../assets/heroes/crimson-dominion-t5.webp":J5,"../../assets/heroes/crimson-dominion-t6.webp":L5,"../../assets/heroes/emerald-collective-t1.webp":x5,"../../assets/heroes/emerald-collective-t2.webp":T5,"../../assets/heroes/emerald-collective-t3.webp":q5,"../../assets/heroes/emerald-collective-t4.webp":Y5,"../../assets/heroes/emerald-collective-t5.webp":H5,"../../assets/heroes/emerald-collective-t6.webp":O5,"../../assets/heroes/golden-imperium-t1.webp":P5,"../../assets/heroes/golden-imperium-t2.webp":j5,"../../assets/heroes/golden-imperium-t3.webp":z5,"../../assets/heroes/golden-imperium-t4.webp":Z5,"../../assets/heroes/golden-imperium-t5.webp":W5,"../../assets/heroes/golden-imperium-t6.webp":V5,"../../assets/heroes/silver-pact-t1.webp":X5,"../../assets/heroes/silver-pact-t2.webp":$5,"../../assets/heroes/silver-pact-t3.webp":Az,"../../assets/heroes/silver-pact-t4.webp":ez,"../../assets/heroes/silver-pact-t5.webp":tz,"../../assets/heroes/silver-pact-t6.webp":iz,"../../assets/heroes/void-enclave-t1.webp":nz,"../../assets/heroes/void-enclave-t2.webp":gz,"../../assets/heroes/void-enclave-t3.webp":oz,"../../assets/heroes/void-enclave-t4.webp":sz,"../../assets/heroes/void-enclave-t5.webp":az,"../../assets/heroes/void-enclave-t6.webp":rz}),JmA={};var laA;for(const[e,A]of Object.entries(g0e)){const t=(laA=e.split("/").pop())==null?void 0:laA.replace(".webp","");t&&(JmA[t]=A.default)}const bV=e=>e.trim().toLowerCase()==="you";function o0e(e,A=!0){return bV(e)?A?"You":"you":e}function s0e(e,A){return bV(e)?C.jsxs(C.Fragment,{children:["You close in on ",C.jsx("strong",{children:A}),"."]}):C.jsxs(C.Fragment,{children:[C.jsx("strong",{children:e})," closes in on ",C.jsx("strong",{children:A}),"."]})}function lsA(e){return bV(e)?"your":/s$/i.test(e)?`${e}'`:`${e}'s`}function a0e(e){return e.charAt(0).toUpperCase()+e.slice(1)}const r0e=1500,I0e=2200;function BsA({player:e,role:A,align:t}){const i=e.heroId?JmA[e.heroId]:void 0;return C.jsxs("div",{className:`zentara-spystrike-combatant zentara-spystrike-combatant--${t}`,style:{"--combatant-color":e.pieceColor},children:[i?C.jsx("img",{src:i,alt:"",className:"zentara-spystrike-combatant__portrait"}):C.jsx("span",{className:"zentara-spystrike-combatant__fallback","aria-hidden":"true",children:e.displayName.slice(0,1).toUpperCase()}),C.jsxs("span",{className:"zentara-spystrike-combatant__copy",children:[C.jsx("small",{children:A}),C.jsx("strong",{children:e.displayName})]})]})}function EsA({attacker:e,defender:A}){return C.jsxs(C.Fragment,{children:[C.jsx(BsA,{player:e,role:"Operative",align:"left"}),C.jsx(BsA,{player:A,role:"Target",align:"right"})]})}const QsA=({pendingEffect:e,attacker:A,defender:t,groupColor:i="#9d4edd",onPuzzleResult:n,onShotResult:g,botPilot:o=!1})=>{var d,p;const s=e.step??"puzzle",[a,r]=E.useState(s==="shot"?"sniper-intro":"intro"),[I,c]=E.useState(null),[l,B]=E.useState(null),Q=E.useRef(!1),h=E.useRef(!1);if(E.useEffect(()=>{s==="shot"&&a==="puzzle-result"&&I&&r("sniper-intro")},[s,a,I]),E.useEffect(()=>{if(a!=="puzzle-result"||I===null||Q.current)return;const y=setTimeout(()=>{Q.current=!0,n(I)},r0e);return()=>clearTimeout(y)},[a,I,n]),E.useEffect(()=>{if(a!=="shot-result"||l===null||h.current)return;const y=setTimeout(()=>{h.current=!0,g(l)},I0e);return()=>clearTimeout(y)},[a,l,g]),E.useEffect(()=>{if(!o)return;let y=!1;const m=D=>new Promise(S=>setTimeout(S,D));return(async()=>{if(a==="intro"){if(await m(1800),y)return;r("puzzle");return}})(),()=>{y=!0}},[o,a]),a==="intro")return C.jsx("div",{className:"zentara-spystrike-overlay",children:C.jsxs("div",{className:"zentara-spystrike-card zentara-spystrike-scene",style:{borderColor:i,"--spystrike-scene":`url("${amA}")`},children:[C.jsxs("div",{className:"zentara-spystrike-eyebrow",children:["SPY STRIKE — ",(d=e.group)==null?void 0:d.toUpperCase()]}),C.jsx("h2",{className:"zentara-spystrike-title",children:"🕵️ Operation Authorized"}),C.jsx("h3",{children:"Proceed with mission."}),C.jsx(EsA,{attacker:A,defender:t}),C.jsxs("div",{className:"zentara-spystrike-body",children:[C.jsx("p",{children:s0e(A.displayName,t.displayName)}),C.jsxs("ol",{className:"zentara-spystrike-objectives",children:[C.jsxs("li",{children:[C.jsx("strong",{children:"Phase A — Soldier Strike"}),": breach the defended station."]}),C.jsxs("li",{children:[C.jsx("strong",{children:"Phase B — Sniper"}),": line up the target."]})]}),C.jsxs("p",{className:"zentara-spystrike-warning",children:["Failure at either phase: ",C.jsx("strong",{children:"1,000c penalty"})," + planet rent + hero clash."]}),C.jsxs("p",{className:"zentara-spystrike-reward",children:["Success: ",C.jsxs("strong",{children:["vanquish ",lsA(t.displayName)," hero"]})," + seize the entire group."]})]}),C.jsx("button",{className:"zentara-spystrike-cta",style:{background:i},onClick:()=>r("puzzle"),children:"BEGIN SOLDIER STRIKE →"})]})});if(a==="puzzle")return C.jsx(vmA,{attacker:A,defender:t,botPilot:o,skipBonus:!0,onComplete:y=>{const m=y.winnerId===A.id;c(m),r("puzzle-result")}});if(a==="puzzle-result"){const y=I===!0;return C.jsx("div",{className:"zentara-spystrike-overlay",children:C.jsxs("div",{className:"zentara-spystrike-card zentara-spystrike-scene",style:{borderColor:y?"#41e077":"#ff4d4d","--spystrike-scene":`url("${y?i0e:n0e}")`},children:[C.jsxs("div",{className:"zentara-spystrike-eyebrow",children:["PHASE A ",y?"COMPLETE":"FAILED"]}),C.jsx("h2",{className:"zentara-spystrike-title",children:y?"⚔️ Station Breached":"🛡️ Strike Repelled"}),C.jsx(EsA,{attacker:A,defender:t}),y?C.jsx("p",{className:"zentara-spystrike-body",children:"Soldier Strike successful. Stand by for the sniper phase."}):C.jsx("p",{className:"zentara-spystrike-body",children:"The strike team is defeated. Penalties applied — stand your ground for the rent & hero clash."})]})})}if(a==="sniper-intro")return C.jsx(t0e,{attacker:A,defender:t,groupColor:i,onComplete:()=>r("sniper")});if(a==="sniper")return C.jsx(_mA,{defender:t,groupColor:i,botPilot:o,onComplete:y=>{B(y),r("shot-result")}});if(a==="shot-result"){const y=l!==null&&l!=="miss",m=y?"#41e077":"#ff4d4d",D={bullseye:"BULLSEYE",hit:"CLEAN HIT",graze:"GRAZING SHOT",miss:"SHOT MISSED"};return C.jsx("div",{className:"zentara-spystrike-overlay",children:C.jsxs("div",{className:"zentara-spystrike-card",style:{borderColor:m},children:[C.jsxs("div",{className:"zentara-spystrike-eyebrow",children:["PHASE B ",y?"COMPLETE":"FAILED"]}),C.jsx("h2",{className:"zentara-spystrike-title",children:y?"🎯 Target Down":"💨 Target Escaped"}),C.jsxs("div",{className:"zentara-spystrike-body",children:[C.jsx("p",{style:{fontSize:18,fontWeight:600,color:m,margin:"4px 0 12px"},children:l?D[l]:""}),y?C.jsx(C.Fragment,{children:C.jsxs("p",{className:"zentara-spystrike-reward",children:[C.jsx("strong",{children:a0e(lsA(t.displayName))})," hero is vanquished. The entire",C.jsxs("strong",{children:[" ",(p=e.group)==null?void 0:p.toUpperCase()]})," group falls to ",C.jsx("strong",{children:o0e(A.displayName,!1)}),"."]})}):C.jsx(C.Fragment,{children:C.jsxs("p",{className:"zentara-spystrike-warning",children:["The spy is exposed. ",C.jsx("strong",{children:"1,000c penalty"})," applied — and you still owe planet rent and a hero clash on landing."]})})]})]})})}return null},C0e=(()=>{try{return Ui.isNativePlatform()}catch{return!1}})(),R4="onb_zentara_v4",NO=[{title:"Welcome, Commander",body:"Zentara is a galactic conquest board game. Command your empire across 40 star systems — capture planets, arm them with defenses, and destroy your rivals.",video:"/videos/planet-capture.mp4",details:["2–6 players — last empire standing wins","Starting credits: 1,500 · Starting HP: 1,500"]},{title:"Capture Planets",body:"Land on an unowned planet and capture it for your empire. Own all planets in a color group to unlock arming — boosting energy toll up to 5 levels.",video:"/videos/space-conquest-1.mp4",details:["22 capturable planets across 8 color groups","Arm evenly — no planet can be 2+ levels ahead"]},{title:"Fleet Combat",body:"When you land on an enemy planet, their turrets deal HP damage to your fleet. Heavy damage triggers a devastating fleet ambush!",video:"/videos/fleet-ambush.mp4",details:["Damage scales with arming level","Opponent earns credits from the damage dealt"]},{title:"Ship Upgrades",body:"Upgrade your flagship with armor to reduce incoming damage and weapons to auto-strike enemy defenses when you roll doubles.",video:"/videos/empire-strike.mp4",details:["🛡️ Armor — 200c per level (15% reduction each)","⚔️ Weapons — 250c per level (destroy enemy arms)"]},{title:"Spy Strike",body:"When an enemy completes a color group, plant a covert spy on it for 1,000 credits. The next time the spy’s owner lands on that group, a Spy Strike triggers — hijack the group on success, lose big on failure.",video:"/videos/empire-strike.mp4",details:["Plant cost: 1,000c · Failure penalty: 1,000c (on top of plant cost)","Phase A — Soldier Strike: breach the defended station","Phase B — Sniper: 7 seconds to hit the target","Win: take ownership of the entire color group","Lose: pay penalty + normal rent + any hero clash"]},{title:"Galactic Conquest",body:"Trade planets, form alliances, navigate wormholes, and survive cryosleep. The last empire standing claims victory over Zentara!",video:"/videos/space-conquest-2.mp4",details:["Trade properties and credits with rivals","Rolling doubles grants an extra roll","Three doubles → forced into cryosleep!"]}],c0e=({open:e,onClose:A})=>{const[t,i]=E.useState(0),[n,g]=E.useState(!1),[o,s]=E.useState(!1),a=E.useRef(null),r=NO.length,I=E.useCallback(()=>{Ia.set({key:R4,value:"1"}),i(0),A()},[A]),c=E.useCallback(p=>{p===t||n||(g(!0),setTimeout(()=>{i(p),g(!1)},300))},[t,n]),l=E.useCallback(()=>{t<r-1?c(t+1):I()},[t,r,c,I]),B=E.useCallback(()=>{t>0&&c(t-1)},[t,c]);if(E.useEffect(()=>{e&&(i(0),g(!1),s(!1))},[e]),E.useEffect(()=>{if(!e)return;const p=y=>{y.key==="Escape"&&I(),(y.key==="ArrowRight"||y.key==="Enter")&&l(),y.key==="ArrowLeft"&&B()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,I,l,B]),E.useEffect(()=>{if(!e)return;const p=a.current;if(!p)return;let y=!1;s(!1),p.currentTime=0;let m=0;const D=()=>{y||p.play().catch(()=>{y||m<3&&(m++,setTimeout(D,200*m))})};if(p.readyState<2){const S=()=>{p.removeEventListener("canplay",S),D()};return p.addEventListener("canplay",S),setTimeout(D,100),()=>{y=!0,p.removeEventListener("canplay",S)}}return D(),()=>{y=!0}},[e,t]),E.useEffect(()=>{if(!e||o)return;const p=setTimeout(()=>s(!0),1500);return()=>clearTimeout(p)},[e,t,o]),E.useEffect(()=>{var p,y,m;if(e)try{(window.__E2E===!0||((y=(p=window.location)==null?void 0:p.search)==null?void 0:y.includes("e2e=1"))||((m=window.sessionStorage)==null?void 0:m.getItem("e2e"))==="1")&&(Ia.set({key:R4,value:"1"}),setTimeout(A,0))}catch{}},[e,A]),!e)return null;const Q=NO[t],h=t===r-1,d=(t+1)/r*100;return C.jsxs("div",{className:"z-onb-vid",role:"dialog","aria-modal":"true","aria-label":"Zentara Tutorial",onClick:()=>{var p;(p=a.current)==null||p.play().catch(()=>{})},children:[C.jsx("video",{ref:a,className:"z-onb-vid__bg",src:Q.video,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"auto",controls:!1,onCanPlay:()=>{var p;(p=a.current)==null||p.play().catch(()=>{})},onError:()=>s(!0),onPlaying:()=>{setTimeout(()=>s(!0),C0e?500:0)},style:o?void 0:{opacity:0}},Q.video),C.jsx("div",{className:"z-onb-vid__overlay"}),C.jsx("div",{className:"z-onb-vid__progress",children:C.jsx("div",{className:"z-onb-vid__progress-fill",style:{width:`${d}%`}})}),C.jsx("button",{className:"z-onb-vid__skip",onClick:I,children:"Skip"}),C.jsxs("div",{className:`z-onb-vid__content${n?" z-onb-vid__content--out":""}`,children:[C.jsxs("div",{className:"z-onb-vid__step-num",children:[t+1," / ",r]}),C.jsx("h2",{className:"z-onb-vid__title",children:Q.title}),C.jsx("p",{className:"z-onb-vid__body",children:Q.body}),Q.details&&C.jsx("ul",{className:"z-onb-vid__details",children:Q.details.map((p,y)=>C.jsx("li",{children:p},y))})]}),C.jsx("div",{className:"z-onb-vid__dots",children:NO.map((p,y)=>C.jsx("button",{className:`z-onb-vid__dot${y===t?" z-onb-vid__dot--active":""}`,onClick:()=>c(y),"aria-label":`Go to step ${y+1}`},y))}),C.jsxs("div",{className:"z-onb-vid__nav",children:[t>0?C.jsx("button",{className:"z-onb-vid__btn z-onb-vid__btn--ghost",onClick:B,children:"Back"}):C.jsx("span",{}),C.jsx("button",{className:"z-onb-vid__btn z-onb-vid__btn--primary",onClick:l,children:h?"Begin Conquest":"Next"})]})]})};function l0e(){const[e,A]=E.useState(!1),[t,i]=E.useState(!1);return E.useEffect(()=>{(async()=>{try{const{value:n}=await Ia.get({key:R4});A(n!=="1")}catch{A(!0)}i(!0)})()},[]),{showOnboardingVideo:e&&t,onboardingReady:t,dismissOnboardingVideo:()=>A(!1)}}const B0e="/assets/logo-Ds4ViVZo.webp",LmA={version:1,generatedAt:null,planets:{}};let pp=null,wv=null;function tk(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function E0e(){const e="".trim();return e?e.endsWith(".json")?e:`${e.replace(/\/$/,"")}/manifest.json`:"/zentara/planets/manifest.json"}function Q0e(e){if(/^(https?:|data:|blob:)/i.test(e))return e;const A="".trim();if(!A)return e;const t=A.endsWith(".json")?A.slice(0,A.lastIndexOf("/")):A.replace(/\/$/,""),i=e.split("/").pop();return i?`${t}/${i}`:e}async function u0e(){return pp||(wv||(wv=fetch(E0e(),{cache:"no-cache"}).then(async e=>{if(!e.ok)throw new Error(`planet manifest ${e.status}`);const A=await e.json(),t=Object.fromEntries(Object.entries(A.planets??{}).map(([i,n])=>[i,{...n,imageUrl:Q0e(n.imageUrl)}]));return pp={...A,planets:t},pp}).catch(()=>LmA).finally(()=>{wv=null})),wv)}function d0e(){const[e,A]=E.useState((pp==null?void 0:pp.planets)??LmA.planets);return E.useEffect(()=>{let t=!0;return u0e().then(i=>{t&&A(i.planets)}),()=>{t=!1}},[]),e}const xmA=/^#[0-9a-f]{3,8}$/i,RO=(e,A)=>e&&xmA.test(e)?e:A,usA="/models/dice.glb";function h0e(e){const A=e!=null&&e.pieceColor&&xmA.test(e.pieceColor)?e.pieceColor:null;return A?`${usA}?tint=${encodeURIComponent(A)}`:usA}const kv={start:JoA,planet:Wm,station:JoA,asteroid:KSe,nebula:xSe,wormhole:FSe,tax:LoA,"void-drain":LoA,jail:_Se,"go-to-jail":JSe,"free-parking":LSe},p0e=ue.lazy(()=>Qi(()=>Promise.resolve().then(()=>Owe),void 0)),f0e=new Set(["start","jail","go-to-jail","free-parking"]),y0e=3e3,D0e=1200,m0e=450,S0e=2400,w0e=700,GO=hB.FLIGHT_DURATION_MS/4,k0e=650,Fh=["/videos/space-conquest-1.mp4","/videos/space-conquest-2.mp4","/videos/planet-capture.mp4"],dsA=["/videos/team-destroyed-2.mp4","/videos/team-destroyed-1.mp4","/videos/team-destroyed-3.mp4"],M0e=20,G4=({players:e,localPlayerId:A,savedState:t,onSaveAndExit:i,multiplayerActions:n,multiplayerEvents:g,multiplayerPendingEffect:o,multiplayerPendingTrade:s,multiplayerRollTrigger:a,multiplayerRaidActivity:r,roomId:I,boardSize:c,autoplay:l=!1,botChatEnabled:B=!1,gameRules:Q})=>{var zw,cC,FB,dc,Iy,Cy,hc,Zw,_B;const h=qi(),d=E.useRef(new Set),p=E.useRef((mA,JA)=>{const Se=globalThis.setTimeout(()=>{d.current.delete(Se),mA()},JA);return d.current.add(Se),Se}),y=E.useRef(mA=>{mA!==void 0&&(globalThis.clearTimeout(mA),d.current.delete(mA))});E.useEffect(()=>()=>{d.current.forEach(mA=>globalThis.clearTimeout(mA)),d.current.clear()},[]);const m=Jge(e,t,c,Q,l),D=!!n,S=D?t:m.gameState,k=D?g??[]:m.events,N=D?o??null:m.pendingEffect,G=D?s??null:m.pendingTrade,M=D?a??0:m.rollTrigger,w=D?n:m.actions,b=E.useRef(w);b.current=w;const _=d0e(),{showAdNow:K,onZentaraTurnEnd:J,isAdShowing:q}=Yf(),v=E.useRef(q);v.current=q;const U=Jr(),{showOnboardingVideo:x,onboardingReady:T,dismissOnboardingVideo:z}=l0e(),[Z,eA]=E.useState(null),[aA,sA]=E.useState(null),pA=E.useRef(null),gA=E.useCallback(()=>{try{ti("Light")}catch{}},[]),yA=Ix();E.useEffect(()=>(yA.acquire(),()=>{yA.release()}),[yA]),E.useEffect(()=>()=>{try{VDA()}catch{}},[]),E.useEffect(()=>{var Oe;const mA=fA.current,JA=mA==null?void 0:mA.matchId;if(!JA)return;const Se=Yge(k,mA,(mA==null?void 0:mA.board)??[],{roundNumber:mA==null?void 0:mA.roundNumber,phase:((Oe=mA==null?void 0:mA.currentTurn)==null?void 0:Oe.phase)??null});Lge(JA,"zentara",Se)},[k]),E.useEffect(()=>{var JA,Se;if(D)return;const mA=S==null?void 0:S.matchId;if(mA)return xge(mA,"zentara",{name:"Zentara · SP",playerCount:((JA=S==null?void 0:S.players)==null?void 0:JA.length)??1,phase:((Se=S==null?void 0:S.currentTurn)==null?void 0:Se.phase)??null}),()=>{Tge(mA)}},[D,S==null?void 0:S.matchId,(zw=S==null?void 0:S.players)==null?void 0:zw.length,(cC=S==null?void 0:S.currentTurn)==null?void 0:cC.phase]);const fA=E.useRef(S);fA.current=S,E.useEffect(()=>{if(D)return;const mA=()=>{const Oe=fA.current;Oe&&!Oe.finished&&uQA(Oe)},JA=()=>{document.visibilityState==="hidden"&&mA()};document.addEventListener("visibilitychange",JA);let Se;return(async()=>{try{const{App:Oe}=await Qi(async()=>{const{App:We}=await Promise.resolve().then(()=>GR);return{App:We}},void 0),Pe=await Oe.addListener("appStateChange",We=>{We.isActive||mA()});Se=()=>{try{Pe.remove()}catch{}}}catch{}})(),()=>{mA(),document.removeEventListener("visibilitychange",JA),Se==null||Se()}},[D]),E.useEffect(()=>(uvA(),()=>{tN()}),[]),E.useEffect(()=>(document.body.classList.add("page-zentara"),()=>{document.body.classList.remove("page-zentara")}),[]);const[RA,qA]=E.useState(null),[W,$]=E.useState(!1),[L,H]=E.useState(!1),[P,tA]=E.useState(!1),[iA,oA]=E.useState(!1),[IA,CA]=E.useState([]),[_A,uA]=E.useState(0),[X,O]=E.useState(null),cA=B&&!l&&!D,wA=E.useMemo(()=>cA?e.filter(mA=>mA.id!==A).map(mA=>({id:mA.id,name:mA.name})):[],[cA,e,A]),xA=E.useRef(!1),YA=E.useRef(null);cpe({enabled:cA,gameMode:"zentara",bots:wA,localPlayerId:A,requireHumanEngagement:!0,controlsRef:YA,getSituation:()=>{var Se,Oe;const mA=(Se=S==null?void 0:S.players)==null?void 0:Se.find(Pe=>{var We;return Pe.id===((We=S==null?void 0:S.currentTurn)==null?void 0:We.playerId)}),JA=((Oe=S==null?void 0:S.currentTurn)==null?void 0:Oe.phase)??"pre-roll";return mA?`It's ${mA.displayName}'s turn (phase: ${JA}) in a Zentara match. React briefly in character.`:"It's a chill moment in a Zentara match."},getHistory:()=>IA.slice(-8).map(mA=>{var JA;return{author:((JA=e.find(Se=>Se.id===mA.senderId))==null?void 0:JA.name)||"Bot",text:mA.text,senderId:mA.senderId}}),onMessage:mA=>{CA(JA=>{var Pe;if(JA.some(We=>We.id===mA.id))return console.log("[zentara-autoplay-chat] dropped duplicate id",mA.id),JA;const Se=8e3;return JA.some(We=>We.senderId===mA.senderId&&We.text===mA.text&&Math.abs(We.ts-mA.ts)<Se)?(console.log("[zentara-autoplay-chat] dropped near-duplicate text",{senderId:mA.senderId,text:mA.text}),JA):(console.log("[zentara-autoplay-chat] message received",{id:mA.id,from:((Pe=e.find(We=>We.id===mA.senderId))==null?void 0:Pe.name)||mA.senderId,text:mA.text,drawerOpen:xA.current,total:JA.length+1}),[...JA,mA])}),xA.current||(O(mA),uA(JA=>JA+1))}}),xA.current=P,E.useEffect(()=>{P&&(uA(0),O(null))},[P]);const jA=E.useRef(0);E.useEffect(()=>{if(!cA){jA.current=k.length;return}if(k.length<=jA.current){jA.current=k.length;return}const mA=k.slice(jA.current);jA.current=k.length;const JA=YA.current;if(!JA)return;const Se=Pe=>{var We;return Pe&&((We=S.players.find(Dt=>Dt.id===Pe))==null?void 0:We.displayName)||"someone"},Oe=Pe=>{var We;return((We=S.board[Pe])==null?void 0:We.name)??`planet ${Pe}`};for(const Pe of mA){let We=null;switch(Pe.type){case"buy":{const Dt=Pe.cost??0;Dt>=200&&(We=`${Se(Pe.playerId)} just captured ${Oe(Pe.tileId)} for ${Dt} energy — a high-value pickup.`);break}case"upgrade":{const Dt=Pe.level??0;Dt>=3&&(We=`${Se(Pe.playerId)} just armed ${Oe(Pe.tileId)} to Arms Level ${Dt}.`);break}case"strike":We=`${Se(Pe.playerId)} struck ${Oe(Pe.tileId)}.`;break;case"seizure":We=`${Se(Pe.attackerId)} seized ${Oe(Pe.tileId)} from ${Se(Pe.defenderId)}.`;break;case"hero-clash":{const Dt=Pe.finalDamage??0;Dt>=30&&(We=`Hero clash between ${Se(Pe.attackerId)} and ${Se(Pe.defenderId)} — ${Dt} damage dealt.`);break}case"hero-vanquished":We=`${Se(Pe.vanquisherId)} vanquished ${Se(Pe.victimId)}'s hero!`;break;case"hero-restored":We=`${Se(Pe.playerId)}'s hero rejoined the fleet.`;break;case"raid":{const Dt=Pe.creditsStolen??0;We=`Raid: ${Se(Pe.winnerId)} took ${Dt} energy.`;break}case"spy-shot-result":{const Dt=Pe.outcome,wi=Se(Pe.spyOwnerId),Wi=Se(Pe.defenderId);Dt==="bullseye"?We=`${wi}'s spy bullseyed ${Wi}.`:Dt==="hit"?We=`${wi}'s spy hit ${Wi}.`:Dt==="graze"?We=`${wi}'s spy grazed ${Wi}.`:Dt==="miss"&&(We=`${wi}'s spy missed ${Wi}.`);break}case"bankrupt":We=`${Se(Pe.playerId)} just went bankrupt.`;break;case"win":We=`${Se(Pe.playerId)} just won the match!`;break}if(We){JA.notifyGameEvent(We);break}}},[k,cA,l,S.players,S.board]);const[ie,he]=E.useState(!1),[le,NA]=E.useState(null),[EA,PA]=E.useState(!1),ZA=E.useRef(0),FA=E.useRef(void 0),[Ie,DA]=E.useState(null),[rA,BA]=E.useState(void 0),j=E.useCallback(mA=>{BA(mA),b.current.upgradeProperty(mA)},[]),[QA,dA]=E.useState(!1),[UA,TA]=E.useState(null),[oe,me]=E.useState(0),[be,$e]=E.useState(50),ci=E.useRef(void 0),ke=E.useCallback((mA,JA=1400)=>{TA(mA),me(Se=>Se+1),y.current(ci.current),ci.current=p.current(()=>TA(null),JA)},[]),[nt,Ut]=E.useState("idle"),[dt,Ht]=E.useState(void 0),[Ft,Jt]=E.useState(0),[$A,He]=E.useState(""),[Xe,St]=E.useState(null),kA=E.useRef(void 0),se=E.useRef(void 0),Ce=E.useRef(void 0),[VA,nA]=E.useState(!1),[vA,KA]=E.useState(!1),[WA,bA]=E.useState(!1),[pe,xe]=E.useState(!1),it=E.useRef(!1),[ve,re]=E.useState(null),[Qe,HA]=E.useState(null),[ge,ye]=E.useState(null),[Te,gt]=E.useState(null),[Qt,_e]=E.useState(null),Ze=E.useRef([]),at=E.useRef(Math.floor(Math.random()*Fh.length)),Ai=200,Bi=1800,yi=400,mt=E.useCallback((mA,JA=k0e)=>{mA&&p.current(mA,JA)},[]),ct=E.useCallback(mA=>{y.current(se.current),y.current(Ce.current),HA(null),nA(!1),KA(!1),it.current=!1,xe(!1),Ut("attack"),He(`⚔️ ${mA.attackerName} — Attack`),Ht([mA.attackDice[0],mA.attackDice[1],0]),Jt(JA=>JA+1),y.current(kA.current),kA.current=p.current(()=>{Ut("defense"),He(`🛡 ${mA.defenderName} — Defense`),Ht([mA.defenseDice[0],mA.defenseDice[1],0]),Jt(JA=>JA+1),kA.current=p.current(()=>{Ut("result"),He(""),Ht(void 0),re({attackerName:mA.attackerName,defenderName:mA.defenderName,attackDice:mA.attackDice,defenseDice:mA.defenseDice,attackBoostPct:mA.attackBoostPct,defenseReducePct:mA.defenseReducePct,baseDamage:mA.baseDamage,finalDamage:mA.finalDamage,tileId:mA.tileId,attackHeroId:mA.attackHeroId,defendHeroId:mA.defendHeroId})},2500)},2500)},[]),fi=E.useCallback((mA,JA,Se)=>{const Oe=mA.filter(Boolean);if(Oe.length){if(ge){Ze.current.push(...Oe),mt(Se);return}Ze.current=Oe.slice(1),gt(JA??null),ye(Oe[0]),mt(Se)}},[ge,mt]),Yi=E.useCallback(()=>{if(!ve||it.current)return;it.current=!0,Ut("idle"),re(null),xe(!1),St(null);const mA=ve.finalDamage;$e(mA),mA<Ai&&dA(!0),ke(ve.tileId,1200),Tc(),p.current(()=>pa(),400),mA>=100&&p.current(()=>pa(),700),mA>=250&&p.current(()=>pa(),1e3),mA>=400&&p.current(()=>pa(),1300),mA>=Ai&&(y.current(Wg.current),Wg.current=p.current(()=>{const JA=(ve==null?void 0:ve.attackerName)??"Attacker",Se=(ve==null?void 0:ve.defenderName)??"Defender",Oe=`${JA} dealt ${mA} damage to ${Se}`;fi(["/videos/fleet-ambush.mp4"],Oe)},1200))},[ve,fi]);E.useEffect(()=>{if(!l||nt!=="result"||!ve)return;const mA=p.current(()=>{Yi()},3500);return()=>y.current(mA)},[l,nt,ve,Yi]);const si=E.useCallback((mA,JA,Se)=>{const Oe=!!(Se!=null&&Se.manualRoll);if(St(mA),Ut("intro"),nA(!1),KA(Oe),re(null),Ht(void 0),He(""),HA(JA),y.current(kA.current),y.current(se.current),y.current(Ce.current),Oe){se.current=p.current(()=>{nA(!0)},Bi);return}se.current=p.current(()=>{ct({...JA,attackHeroId:mA.atk.heroId,defendHeroId:mA.def.heroId})},Bi+yi)},[Bi,yi,ct]),jt=E.useCallback(()=>{!vA||!VA||!Qe||!Xe||(y.current(se.current),bA(!0),p.current(()=>{ct({...Qe,attackHeroId:Xe.atk.heroId,defendHeroId:Xe.def.heroId}),bA(!1)},300))},[vA,VA,Qe,Xe,ct]),[Zt,vi]=E.useState(null),[kn,gn]=E.useState(null),[Ki,Tn]=E.useState(null),[fg,Zi]=E.useState(!1),te=E.useRef(!1),Eg=E.useRef(!1),gi=E.useRef(void 0),Mg=E.useRef(void 0),[Hg,de]=E.useState(!1),[qe,OA]=E.useState(null);E.useEffect(()=>{const mA=()=>{ZA.current=Date.now()};return window.addEventListener("ui:roll",mA),window.addEventListener("ui:roll-interaction",mA),()=>{window.removeEventListener("ui:roll",mA),window.removeEventListener("ui:roll-interaction",mA)}},[]);const Ae=E.useCallback(()=>Date.now()-ZA.current<m0e,[]),Ke=E.useCallback(()=>{Ae()||i==null||i()},[i,Ae]);E.useEffect(()=>(window.__explode=(mA=(Se=>(Se=S.players[S.currentPlayerIndex])==null?void 0:Se.tileIndex)()??0,JA=100)=>{console.log("[EXPLOSION] 💥 tile",mA,"damage",JA),$e(JA),ke(mA,1400)},window.__fireLasers=window.__explode,window.__debugBlast=()=>de(mA=>!mA),window.__testLasers=mA=>{const JA=S.properties,Se=JA.filter(wi=>wi.upgradeLevel>0);if(Se.length===0){console.warn("[LASERS] No upgraded turrets on the board — buy & upgrade a property first");return}const Oe=mA??(new Set(Se.map(Wi=>Wi.ownerId)),Se[0].tileId),Pe=JA.find(wi=>wi.tileId===Oe),We=Pe==null?void 0:Pe.ownerId,Dt=We?Se.filter(wi=>wi.ownerId===We).length:0;console.log(`[LASERS] 🔫 Firing ${Dt} turret beam(s) at tile ${Oe}`+(We?` (owner has ${Dt} armed properties)`:" (unowned — no beams will render)")),$e(200),ke(Oe,2e3)},window.__raid=mA=>{var Dt;const JA=S.players[S.currentPlayerIndex],Se=mA??(S.currentPlayerIndex+1)%S.players.length,Oe=S.players[Se];if(!JA||!Oe){console.warn("[RAID] invalid player indices");return}console.log(`[RAID] 🎯 ${Xi(JA.piece)} → ${Xi(Oe.piece)}`);const Pe=S.board[JA.tileIndex],We=(Pe==null?void 0:Pe.type)==="planet"?((Dt=_[tk(Pe.name)])==null?void 0:Dt.imageUrl)??Wm:kv[(Pe==null?void 0:Pe.type)??"start"];vi({attacker:JA,defender:Oe,miniGame:"fps",tileImage:We})},window.__codebreaker=mA=>{const JA=S.players[S.currentPlayerIndex],Se=mA??(S.currentPlayerIndex+1)%S.players.length,Oe=S.players[Se];if(!JA||!Oe){console.warn("[CODEBREAKER] invalid player indices");return}console.log(`[CODEBREAKER] 🔓 ${Xi(JA.piece)} → ${Xi(Oe.piece)}`),vi({attacker:JA,defender:Oe,miniGame:"codebreaker"})},window.__soldier=(mA,JA,Se)=>{const Oe=S.players[S.currentPlayerIndex],Pe=mA??(S.currentPlayerIndex+1)%S.players.length,We=S.players[Pe];if(!Oe||!We){console.warn("[SOLDIER FPS] invalid player indices");return}const Dt=S.board[Oe.tileIndex],wi=JA??(Dt&&Dt.type!=="planet"?Dt.type:"station"),Wi=kv[wi];console.log(`[SOLDIER FPS] 🪖 ${Xi(Oe.piece)} → ${Xi(We.piece)} (bg=${wi}${Se?", no codebreaker":""})`),vi({attacker:Oe,defender:We,miniGame:"soldier-fps",tileImage:Wi,skipBonus:!!Se})},window.__spystrike=(mA,JA,Se="puzzle")=>{var wi;const Oe=S.players[S.currentPlayerIndex],Pe=mA??(S.currentPlayerIndex+1)%S.players.length,We=S.players[Pe];if(!Oe||!We){console.warn("[SPY STRIKE] invalid player indices");return}const Dt=JA??((wi=S.board.find(Wi=>Wi.type==="planet"&&Wi.group))==null?void 0:wi.group)??"orion";console.log(`[SPY STRIKE] 🕵️ ${Xi(Oe.piece)} → ${Xi(We.piece)} (group: ${Dt}, step: ${Se})`),gn({attacker:Oe,defender:We,group:Dt,step:Se})},window.__sniper=(mA,JA)=>{var wi;const Se=S.players[S.currentPlayerIndex],Oe=mA??(S.currentPlayerIndex+1)%S.players.length,Pe=S.players[Oe];if(!Se||!Pe){console.warn("[SNIPER] invalid player indices");return}const We=JA??((wi=S.board.find(Wi=>Wi.type==="planet"&&Wi.group))==null?void 0:wi.group),Dt=We&&Bs[We]||"#9d4edd";window.__sniperDebug!==!1&&(window.__sniperDebug=!0),console.log(`[SNIPER] 🎯 ${Xi(Se.piece)} → ${Xi(Pe.piece)} (color: ${Dt}, debug: ${!!window.__sniperDebug})`),Tn({attacker:Se,defender:Pe,groupColor:Dt,runKey:0})},window.__testHeroClash=(mA,JA,Se)=>{const Oe=mA??S.currentPlayerIndex,Pe=JA??(Oe+1)%S.players.length,We=S.players[Oe],Dt=S.players[Pe];if(!We||!Dt){console.warn("[HERO CLASH] invalid player indices");return}const wi=We.heroId?ms[We.heroId]:null,Wi=Dt.heroId?ms[Dt.heroId]:null,gs=Math.ceil(Math.random()*6),Io=Math.ceil(Math.random()*6),La=gs+Io,js=Math.ceil(Math.random()*6),Xg=Math.ceil(Math.random()*6),Ql=js+Xg,fo=wi?mu(wi.empire,wi.tier):{attack:0},cr=Wi?mu(Wi.empire,Wi.tier):{defense:0},lC=Math.min(fo.attack*La,3),BC=Math.min(cr.defense*Ql,.9),uQ=100,xa=Math.round(uQ*(1+lC)),Wd=Math.max(1,Math.round(xa*(1-BC))),JB=Se??We.tileIndex;console.log(`[HERO CLASH] ⚔️ ${Xi(We.piece)} (${(wi==null?void 0:wi.name)??"no hero"} T${(wi==null?void 0:wi.tier)??0}) 🎲${gs}+${Io}=${La} → atk ${(lC*100).toFixed(0)}% vs ${Xi(Dt.piece)} (${(Wi==null?void 0:Wi.name)??"no hero"} T${(Wi==null?void 0:Wi.tier)??0}) 🎲${js}+${Xg}=${Ql} → def ${(BC*100).toFixed(0)}% | base ${uQ} → boosted ${xa} → final ${Wd}`),si({atk:We,def:Dt},{attackerName:Xi(We.piece),defenderName:Xi(Dt.piece),attackDice:[gs,Io],defenseDice:[js,Xg],attackBoostPct:Math.round(lC*100),defenseReducePct:Math.round(BC*100),baseDamage:uQ,finalDamage:Wd,tileId:JB},{manualRoll:!0})},window.__cutscene=(mA="victory",JA)=>{const Se=JA??null;if(mA==="destroyed"){fi(dsA,Se??"Fleet destroyed!");return}if(mA==="ambush"){fi(["/videos/fleet-ambush.mp4"],Se??"Fleet ambush!");return}if(mA==="conquest"||mA==="victory"){fi(Fh,Se??"Victory!");return}if(mA.startsWith("/videos/")){fi([mA],Se);return}console.warn("[ZENTARA] Unknown cutscene kind. Use victory, conquest, destroyed, ambush, or a /videos/*.mp4 path.")},window.__cutscene3d=(mA="spy-plant",JA)=>{if(!["spy-plant","hero-clash","wormhole","raid-victory"].includes(mA)){console.warn("[ZENTARA] Unknown realtime cutscene kind. Use spy-plant, hero-clash, wormhole, or raid-victory.");return}const Oe=S.players[S.currentPlayerIndex]??null,Pe=S.players.find(Dt=>Dt.id!==(Oe==null?void 0:Oe.id)&&!Dt.depleted)??null,We=Oe?S.board[Oe.tileIndex]:null;_e({kind:mA,caption:JA??void 0,attacker:Oe,defender:Pe,groupColor:We!=null&&We.group?Bs[We.group]??(Oe==null?void 0:Oe.pieceColor):Oe==null?void 0:Oe.pieceColor})},()=>{delete window.__explode,delete window.__fireLasers,delete window.__debugBlast,delete window.__testLasers,delete window.__raid,delete window.__codebreaker,delete window.__soldier,delete window.__spystrike,delete window.__sniper,delete window.__testHeroClash,delete window.__cutscene,delete window.__cutscene3d}),[S.players,S.currentPlayerIndex,S.board,si,fi]);const[Je,pt]=E.useState(!1),[Tt,vt]=E.useState(!1),[ei,Vt]=E.useState("idle"),[hA,Re]=E.useState(null),[ot,kt]=E.useState(null),ht=E.useRef(!1);E.useEffect(()=>()=>y.current(ee.current),[]);const ee=E.useRef(void 0),[je,Ct]=E.useState(!1),At=E.useRef(!1);E.useEffect(()=>{if(rA!=null){const mA=p.current(()=>BA(void 0),400);return()=>y.current(mA)}},[rA]);const zt=E.useRef(void 0),li=E.useRef(0),Ei=E.useRef(null);E.useEffect(()=>{if(!S.finished||Ei.current===S.matchId||ge||Qt)return;const mA=p.current(()=>{Ei.current!==S.matchId&&(Ei.current=S.matchId,K({ignoreMinInterval:!0}).catch(()=>{}))},400);return()=>y.current(mA)},[S.matchId,S.finished,ge,Qt,K]),E.useEffect(()=>{if(!l||!S.finished)return;const mA=p.current(()=>{try{X1()}catch{}const JA=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID().slice(0,8):Math.random().toString(36).slice(2,10),Oe=new URLSearchParams(window.location.search).get("bots"),Pe=Oe?`?autoplay=1&bots=${encodeURIComponent(Oe)}`:"?autoplay=1";h(`/zentara/match/${JA}${Pe}`,{replace:!0})},12e3);return()=>y.current(mA)},[l,S.finished,h]);const ai=E.useCallback(mA=>{const JA=S.players.find(Se=>Se.id===mA);return JA?Xi(JA.piece):"Unknown Fleet"},[S.players]),Hi=E.useCallback(mA=>{var JA;return((JA=S.board[mA])==null?void 0:JA.name)??`Tile ${mA}`},[S.board]);E.useEffect(()=>{if(k.length<=li.current){li.current=k.length;return}const mA=k.slice(li.current);li.current=k.length;for(const JA of mA){const Se="playerId"in JA?JA.playerId:"payerId"in JA?JA.payerId:null,Oe=Se?ai(Se):"Player",Pe=!ge;switch(JA.type){case"move":"passedStart"in JA&&JA.passedStart&&Pe&&U.info(`${Oe} passed Command Base`,"+200 energy");break;case"buy":if(Se!==A&&!ge){z6(),at.current=(at.current+1)%Fh.length;const We=S.board[JA.tileId],Dt=We!=null&&We.group?Bs[We.group]:void 0;gt(C.jsxs(C.Fragment,{children:[C.jsx("span",{style:Dt?{color:Dt}:void 0,children:Hi(JA.tileId)})," captured by ",Oe]})),ye(Fh[at.current])}else Pe&&U.info(`${Oe} captured ${Hi(JA.tileId)}`,`-${JA.cost} energy`);break;case"energy-toll":{const We=ai(JA.ownerId);Pe&&U.info(`${Oe} took damage!`,`-${JA.amount} energy · ${We} gained ✦${JA.amount}`);break}case"void-drain":Pe&&U.info(`${Oe} paid supply levy`,`-${JA.amount} energy`);break;case"card":Pe&&U.info(`${Oe} received intel`,JA.text),AM();break;case"jail":Pe&&U.info(`${Oe} entered cryosleep!`,JA.reason==="triple-doubles"?"Triple doubles":""),y8();break;case"jail-free":Pe&&U.info(`${Oe} woke from cryosleep`,JA.method==="pay"?"Paid wake-up fee":JA.method==="roll-doubles"?"Rolled doubles":"Used intel");break;case"upgrade":BA(JA.tileId),Pe&&U.info(`${Oe} armed ${Hi(JA.tileId)}`,`Arms Level ${JA.level}`);break;case"depleted":fi(dsA,`${Oe}'s fleet destroyed!`),pa();break;case"repossess":Pe&&U.info(`${Oe} lost ${Hi(JA.tileId)}`,`+${JA.amount} energy (seized by command)`);break;case"sell":Pe&&U.info(`${Oe} sold ${Hi(JA.tileId)}`,`+${JA.amount} energy`);break;case"debt-sell":Pe&&U.info(`${Oe} evacuated ${Hi(JA.tileId)}`,`+${JA.amount} energy (debt recovery)`);break;case"debt-liquidate-arm":Pe&&U.info(`${Oe} liquidated arms at ${Hi(JA.tileId)}`,`Arms Level ${JA.level} (+${JA.refund} energy)`);break;case"trade":{const We=ai(JA.offererId),Dt=ai(JA.recipientId);Pe&&(JA.offererId===A?U.info("Trade accepted",`${Dt} accepted your offer`):JA.recipientId===A?U.info("Trade completed",`You accepted ${We}'s offer`):U.info(`${We} traded with ${Dt}`));break}case"trade-declined":{const We=ai(JA.offererId),Dt=ai(JA.recipientId);Pe&&(JA.offererId===A?U.info("Trade declined",`${Dt} declined your offer`):JA.recipientId===A&&U.info("Trade declined",`You declined ${We}'s offer`));break}case"upgrade-armor":Pe&&U.info(`${Oe} reinforced armor`,`Shield Level ${JA.level} (-${JA.cost} energy)`);break;case"upgrade-weapon":Pe&&U.info(`${Oe} upgraded weapons`,`Weapon Level ${JA.level} (-${JA.cost} energy)`),Tc();break;case"liquidate-armor":Pe&&Se!==A&&U.info(`${Oe} sold armor`,`Shield Level ${JA.level} (+${JA.refund} energy)`);break;case"liquidate-weapon":Pe&&Se!==A&&U.info(`${Oe} sold weapons`,`Weapon Level ${JA.level} (+${JA.refund} energy)`);break;case"strike":Pe&&U.info(`${Oe} struck ${Hi(JA.tileId)}!`,`Arms reduced to Level ${JA.newLevel}`),Tc(),p.current(()=>pa(),300);break;case"hero-clash":{const We=ai(JA.attackerId),Dt=ai(JA.defenderId),wi=JA.attackDice[0]+JA.attackDice[1],Wi=JA.defenseDice[0]+JA.defenseDice[1],gs=ms[JA.attackHeroId],Io=ms[JA.defenseHeroId],La=gs?mu(gs.empire,gs.tier).attack:0,js=Io?mu(Io.empire,Io.tier).defense:0,Xg=Math.round(Math.min(La*wi/7,3)*100),Ql=Math.round(Math.min(js*Wi/7,.9)*100),fo=S.players.find(BC=>BC.id===JA.attackerId)??null,cr=S.players.find(BC=>BC.id===JA.defenderId)??null,lC=JA.attackerId===A||JA.defenderId===A;fo&&cr&&si({atk:fo,def:cr},{attackerName:We,defenderName:Dt,attackDice:JA.attackDice,defenseDice:JA.defenseDice,attackBoostPct:Xg,defenseReducePct:Ql,baseDamage:JA.baseDamage,finalDamage:JA.finalDamage,tileId:JA.tileId},{manualRoll:lC});break}case"raid":{const We=ai(JA.attackerId),Dt=ai(JA.defenderId),wi=ai(JA.winnerId);Pe&&U.info(`${wi} won the raid!`,`Stole ✦${JA.creditsStolen} from ${JA.winnerId===JA.attackerId?Dt:We}`);break}case"spy-shot-result":{const We=ai(JA.spyOwnerId),Dt=ai(JA.defenderId),wi=(JA.group??"").toUpperCase();if(Pe)switch(JA.outcome){case"bullseye":U.info(`🎯 ${We}'s sniper — BULLSEYE`,`${Dt}'s hero down · ${wi} group seized`);break;case"hit":U.info(`✅ ${We}'s sniper — CLEAN HIT`,`${Dt}'s hero down · ${wi} group seized`);break;case"graze":U.info(`↘ ${We}'s sniper — GRAZING SHOT`,`${Dt}'s hero down · ${wi} group seized`);break;case"miss":U.info(`❌ ${We}'s sniper — MISSED`,"Spy exposed · penalty + rent + hero clash");break}break}case"spy-plant":{const We=S.players.find(Dt=>Dt.id===JA.playerId)??null;_e({kind:"spy-plant",attacker:We,groupColor:Bs[JA.group]??(We==null?void 0:We.pieceColor),caption:`${We?Xi(We.piece):ai(JA.playerId)} deployed a covert asset`}),AM();break}case"win":{const We=S.players.find(Dt=>Dt.id===JA.playerId)??null;hvA(),fi(Fh,`${We?Xi(We.piece):ai(JA.playerId)} claims victory!`);break}}}},[k,A,ai,Hi,U,ge,si,fi,S.players]),E.useEffect(()=>()=>{y.current(kA.current),y.current(se.current),y.current(Ce.current)},[]);const gg=E.useRef(!1);E.useEffect(()=>{if(S.currentTurn.phase!=="done"){gg.current=!1;return}if(!(S.finished||!Je||Zt)&&!gg.current){gg.current=!0;try{J()}catch{}}},[S.currentTurn.phase,S.finished,Je,Zt,J]),E.useEffect(()=>{if(S.currentTurn.phase==="done"&&!S.finished&&Je&&!Zt&&!q&&!aA){if(y.current(zt.current),Eg.current){zt.current=p.current(()=>{Eg.current=!1,b.current.endTurn()},2e3);return}zt.current=p.current(()=>{b.current.endTurn()},y0e)}return()=>{y.current(zt.current)}},[S.currentTurn.phase,S.finished,Je,Zt,q,aA]);const yn=E.useRef(void 0);E.useEffect(()=>{if(!(!Je||!S.pendingTeleport))return y.current(yn.current),yn.current=p.current(()=>{At.current=!1,pt(!1),b.current.applyTeleport()},600),()=>{y.current(yn.current)}},[Je,S.pendingTeleport]);const Rs=E.useRef(void 0),qo=E.useRef(void 0);E.useEffect(()=>(Je||(y.current(qo.current),qo.current=p.current(()=>{At.current=!0,pt(!0)},M0e*300+800)),()=>{y.current(qo.current)}),[Je]),E.useEffect(()=>{if(Zt){y.current(Mg.current),Zi(!0);return}Zi(!1)},[Zt]),E.useEffect(()=>()=>{y.current(Mg.current)},[]);const eg=E.useRef(!1),Gs=["Unfortified","Shield I","Shield II","Shield III","Shield IV","Fortress"];E.useEffect(()=>{var We;if(!Je){eg.current=!1;return}if(eg.current)return;eg.current=!0;const mA=S.players[S.currentPlayerIndex];if(!mA)return;const JA=S.board[mA.tileIndex];if(!JA||JA.type==="jail"||JA.type==="go-to-jail"||N)return;const Se=S.properties.find(Dt=>Dt.tileId===JA.id),Oe=Se!=null&&Se.ownerId?S.players.find(Dt=>Dt.id===Se.ownerId):null;let Pe;if(Oe&&Oe.id===mA.id){const Dt=Se.upgradeLevel,wi=Gs[Dt]??"Unfortified",Wi="⬢".repeat(Dt)+"⬡".repeat(5-Dt);Pe=`Your Territory · ${wi} ${Wi}`}else if(Oe){const Dt=Se.upgradeLevel,wi=Gs[Dt]??"Unfortified",Wi="⬢".repeat(Dt)+"⬡".repeat(5-Dt),gs=(We=JA.rent)==null?void 0:We[Dt];Pe=`Captured by ${Xi(Oe.piece)} · ${wi} ${Wi}`+(gs!=null?` · Damage ✦${gs}`:"")+(Se.dormant?" · Decommissioned":"")}else JA.cost!=null?Pe=`Uncontrolled · Capture ✦${JA.cost}`:Pe={start:"Collect energy",tax:"Supply levy",jail:"Cryosleep chamber","go-to-jail":"Forced cryosleep","free-parking":"Rest stop",wormhole:"Wormhole jump",asteroid:"Random event",nebula:"Intel briefing",station:"Space station"}[JA.type]??JA.type.replace("-"," ");ge||U.info(`Landed on ${JA.name}!`,Pe)},[Je,S.players,S.currentPlayerIndex,S.board,S.properties,N,ge]),E.useEffect(()=>{te.current=!1},[M]),E.useEffect(()=>{var La,js,Xg,Ql,fo;if(Zt||te.current||!Je||S.finished||N)return;const mA=S.currentTurn.phase;if(mA!=="done"&&mA!=="pre-roll"||(te.current=!0,(La=S.gameRules)!=null&&La.disableRaid))return;const JA=S.players[S.currentPlayerIndex];if(!JA||JA.depleted||JA.inJail)return;const Se=S.board[JA.tileIndex];if(!Se||f0e.has(Se.type))return;const Oe=S.players.find(cr=>cr.id!==JA.id&&!cr.depleted&&!cr.inJail&&cr.tileIndex===JA.tileIndex);if(!Oe)return;const Pe=S.players.find(cr=>cr.id===A),We=Pe==null?void 0:Pe.piece,Dt=JA.id===A||JA.id.startsWith("zentara_bot_")&&S.botControllerId===A;if(D&&!Dt)return;if(l?!0:!!We&&We!==JA.piece&&We!==Oe.piece){if(l&&!D){const hQ=Se.type==="planet"?"fps":"soldier-fps",yG=Se.type==="planet"?((js=_[tk(Se.name)])==null?void 0:js.imageUrl)??Wm:kv[Se.type];vi({attacker:JA,defender:Oe,miniGame:hQ,botPilot:!0,tileImage:yG});return}const lC=sfe(),BC=Math.floor(Math.random()*(lC+1)),uQ=FJ(BC,lC,JA,Oe),xa=uQ.winnerId,Wd=xa===JA.id?Oe.id:JA.id,JB=uQ.creditsStolen;y.current(Mg.current),Zi(!0),Mg.current=p.current(()=>Zi(!1),S0e),JB>0&&(!D||Dt)&&b.current.resolveRaid({attackerId:JA.id,defenderId:Oe.id,winnerId:xa,creditsStolen:JB});const dQ=Xi(((Xg=S.players.find(hQ=>hQ.id===xa))==null?void 0:Xg.piece)??"crimson-dominion"),fG=Xi(((Ql=S.players.find(hQ=>hQ.id===Wd))==null?void 0:Ql.piece)??"crimson-dominion");U.info(`${dQ} won the raid!`,`Stole ✦${JB} from ${fG}`),Eg.current=!0,y.current(gi.current),gi.current=p.current(()=>{Eg.current=!1},2e3);return}const Wi=Se.type==="planet"?"fps":"soldier-fps",gs=Se.type==="planet"?((fo=_[tk(Se.name)])==null?void 0:fo.imageUrl)??Wm:kv[Se.type],Io=Oe.id===A;vi(Io?{attacker:Oe,defender:JA,miniGame:Wi,tileImage:gs}:{attacker:JA,defender:Oe,miniGame:Wi,tileImage:gs})},[Je,N,S.currentTurn.phase,S.finished,Zt,S.players,S.currentPlayerIndex,S.board,S.botControllerId,A,U,l,D,_]);const bs=E.useCallback(mA=>{var Oe,Pe;if(!Zt)return;const JA=(Oe=S.players[S.currentPlayerIndex])==null?void 0:Oe.id,Se=JA===A||!!(JA!=null&&JA.startsWith("zentara_bot_"))&&S.botControllerId===A;if(!D||Se){const We=(Pe=S.players[S.currentPlayerIndex])==null?void 0:Pe.id,Dt=We?Zt.attacker.id===We?Zt.defender.id:Zt.attacker.id:Zt.defender.id;b.current.resolveRaid({attackerId:We,defenderId:Dt,winnerId:mA.winnerId,creditsStolen:mA.creditsStolen,finalHits:mA.finalHits,totalSpawned:mA.totalSpawned,mode:Zt.miniGame==="soldier-fps"?"soldier":"space"})}p.current(()=>pa(),300),vi(null),Eg.current=!0,y.current(gi.current),gi.current=p.current(()=>{Eg.current=!1},2e3)},[Zt,S.players,S.currentPlayerIndex,S.botControllerId,A,D]),Wg=E.useRef(void 0);E.useEffect(()=>{var mA;if(!(S.currentTurn.phase!=="action"||!N||!Je||!At.current)){if(N.action==="energy-toll"){const JA=N.amount??50,Se=S.players[S.currentPlayerIndex];return(()=>{console.log("[BLAST] Firing turret beams at tile",N.tileId,"damage",JA),$e(JA),ke(N.tileId,1200),JA<Ai&&dA(!0),Tc(),p.current(()=>pa(),400),JA>=100&&p.current(()=>pa(),700),JA>=250&&p.current(()=>pa(),1e3),JA>=400&&p.current(()=>pa(),1300),JA>=Ai?(y.current(Wg.current),Wg.current=p.current(()=>{const Pe=S.properties.find(Wi=>Wi.tileId===N.tileId),We=Pe!=null&&Pe.ownerId?S.players.find(Wi=>Wi.id===Pe.ownerId):null,Dt=We?Xi(We.piece):"Enemy",wi=Se?Xi(Se.piece):"Fleet";gt(`${Dt} dealt ${JA} damage to ${wi}`),ye("/videos/fleet-ambush.mp4"),mt(()=>b.current.payRent())},1200)):(y.current(Wg.current),Wg.current=p.current(()=>{b.current.payRent()},1400))})(),()=>{y.current(Wg.current),y.current(ci.current)}}else if(N.action==="void-drain")dA(!0),y.current(Rs.current),Rs.current=p.current(()=>b.current.payTax(),D0e);else if(N.action==="draw-card"){const JA=(mA=S.board[N.tileId])==null?void 0:mA.type;eA({deck:JA==="asteroid"?"asteroid":"nebula",text:N.cardText??"",amount:N.amount??0,autoDismissMs:3e3})}return()=>{y.current(Rs.current),y.current(Wg.current)}}},[S.currentTurn.phase,N,Je]);const[Vg,rC]=E.useState(S),sr=E.useRef(M),[UB,pI]=E.useState(void 0),[fI,vB]=E.useState(1),[Ps,ll]=E.useState(!1),[Pd,KB]=E.useState(!1),[jd,ry]=E.useState(0),Yo=E.useRef(!1),yI=E.useRef(!1),Hw=E.useCallback(()=>{Yo.current=!0,yI.current=!0,ll(!1)},[]);E.useEffect(()=>(window.__intro=()=>{console.log("[ZENTARA] Replaying fleet intro"),Yo.current=!1,yI.current=!0,KB(!1),ry(mA=>mA+1),ll(!0)},()=>{delete window.__intro}),[]),E.useEffect(()=>{if(T){if(x){Ps&&ll(!1);return}l||Yo.current||yI.current||Ps||ll(!0)}},[T,x,l,Ps]),E.useEffect(()=>{if(!Ps){KB(!1);return}yI.current=!0,KB(!1);const mA=p.current(()=>KB(!0),700);return()=>y.current(mA)},[Ps]),E.useEffect(()=>{if(Ps||!l&&!yI.current)return;Yo.current||(Yo.current=!0,BA(0),pI(2));const mA=p.current(()=>pI(void 0),3500);return()=>y.current(mA)},[Ps,l]);const{reveal:DI}=kB(),[ar,Fa]=E.useState(0),[rr,mI]=E.useState("idle"),Qc=E.useRef(M),IC=E.useRef(setTimeout(()=>{})),lA=E.useCallback(()=>{mI("charging"),AM({volume:.12})},[]),LA=E.useCallback(mA=>{Fa(mA),mA===0&&mI(JA=>JA==="charging"?"idle":JA)},[]),ae=E.useCallback(()=>{Fa(0),mI("launch"),b.current.roll()},[]),De=E.useRef(null),Be=E.useRef(!1);if(M!==sr.current){sr.current=M,Be.current=!0,De.current=S,pt(!1),vt(!1),Ct(!0),y.current(ee.current);const mA=Vg.players[Vg.currentPlayerIndex],JA=mA?Vg.board[mA.tileIndex]:void 0;Re((mA==null?void 0:mA.tileIndex)??null);const Se=mA?S.players.find(Oe=>Oe.id===mA.id):S.players[S.currentPlayerIndex];kt((Se==null?void 0:Se.tileIndex)??null),ht.current=(mA==null?void 0:mA.inJail)===!0||(JA==null?void 0:JA.type)==="jail",ht.current?Vt("idle"):Vt("liftoff")}E.useEffect(()=>{if(M!==sr.current){sr.current=M,pt(!1),vt(!1),Ct(!0);const mA=Vg.players[Vg.currentPlayerIndex];mA&&(BA(mA.tileIndex),Re(mA.tileIndex)),De.current=S}else De.current?De.current=S:rC(S)},[S,M]),E.useEffect(()=>{if(DI&&De.current){const mA=De.current,JA=p.current(()=>{De.current=null,Be.current=!1,rC(mA)},1e3);return()=>y.current(JA)}},[DI]),E.useEffect(()=>{M!==Qc.current&&(Qc.current=M,y.current(IC.current),Fa(0),mI("launch"))},[M]);const Fe=S.players[S.currentPlayerIndex],Le=(Fe==null?void 0:Fe.id)===A,rt=le!=null&&(N==null?void 0:N.action)==="buy-prompt"&&N.tileId===le;E.useEffect(()=>{le!=null&&((N==null?void 0:N.action)!=="buy-prompt"||N.tileId!==le)&&NA(null)},[N,le]);const ft=S.players.find(mA=>mA.id===A),En=E.useMemo(()=>ft?S.properties.filter(mA=>mA.ownerId===A&&!mA.dormant&&mA.upgradeLevel<Hm(A,mA.tileId,S.board,S.properties)).length:0,[S.properties,S.board,ft,A]),rg=E.useMemo(()=>ft?S.properties.filter(mA=>{var JA;return mA.ownerId===A&&!mA.dormant&&mA.upgradeLevel<Hm(A,mA.tileId,S.board,S.properties)&&(((JA=S.board[mA.tileId])==null?void 0:JA.upgradeCost)??1/0)<=ft.credits}).length:0,[S.properties,S.board,ft,A]),qn=E.useMemo(()=>{var Wi,gs;if(!Le||!ft||ft.depleted||(Wi=S.gameRules)!=null&&Wi.disableSpyStrike||N||S.currentTurn.phase==="in-debt"||(ft.heroLockoutTurnsRemaining??0)>0)return null;const mA=S.board[ft.tileIndex];if(!mA||mA.type!=="planet"||!mA.group)return null;const JA=mA.group,Se=S.spies;if(Se!=null&&Se[JA])return null;const Oe=S.siegeCooldowns,Pe=(Oe==null?void 0:Oe[JA])??0;if(S.roundNumber<Pe)return null;const We=S.board.filter(Io=>Io.group===JA).map(Io=>Io.id);if(We.length===0)return null;let Dt=0;const wi=[];for(const Io of We){const La=S.properties.find(js=>js.tileId===Io);if(!(La!=null&&La.ownerId))return null;La.ownerId===A?Dt+=1:wi.push(Io)}if(Dt===0){const Io=(gs=S.properties.find(js=>js.tileId===We[0]))==null?void 0:gs.ownerId;return!Io||Io===A||!We.every(js=>S.properties.some(Xg=>Xg.tileId===js&&Xg.ownerId===Io))||ft.credits<Tp?null:{group:JA,cost:Tp}}return wi.length===0||ft.credits<qp?null:{group:JA,cost:qp}},[D,Le,ft,A,N,S]),Ig=(qn==null?void 0:qn.group)??null,Us=(qn==null?void 0:qn.cost)??Tp,ao=E.useCallback(mA=>{!ft||(qn==null?void 0:qn.group)!==mA||sA({factionName:Xi(ft.piece),factionColor:RO(ft.pieceColor,"#9d4edd"),group:mA,groupColor:Bs[mA]??"#9d4edd",cost:qn.cost})},[ft,qn]),Yn=E.useMemo(()=>S.players.filter(mA=>!mA.depleted&&(D?mA.isBot||mA.id.startsWith("zentara_bot_"):mA.id!==A)).map(mA=>mA.id),[S.players,D,A]),Qn=E.useMemo(()=>S.winnerId?S.players.find(mA=>mA.id===S.winnerId)??null:null,[S.players,S.winnerId]),Ng=E.useMemo(()=>{if(!Qn)return null;let mA=0;for(const Oe of S.properties.filter(Pe=>Pe.ownerId===Qn.id)){const Pe=S.board[Oe.tileId];mA+=(Pe==null?void 0:Pe.cost)??0,Oe.upgradeLevel>0&&(Pe!=null&&Pe.upgradeCost)&&(mA+=Oe.upgradeLevel*Pe.upgradeCost)}const JA=Qn.weaponLevel*dn.weaponUpgradeCost,Se=Qn.armorLevel*dn.armorUpgradeCost;return{credits:Qn.credits,propertyValue:mA,weaponValue:JA,armorValue:Se,total:Math.max(0,Qn.credits+mA+JA+Se)}},[Qn,S.properties,S.board]);Zge({isMyTurn:Le,phase:S.currentTurn.phase,pendingEffect:N,pendingTrade:G,inJail:(Fe==null?void 0:Fe.inJail)??!1,credits:(Fe==null?void 0:Fe.credits)??0,botPlayerIds:Yn,currentPlayerId:(Fe==null?void 0:Fe.id)??"",properties:S.properties,board:S.board,actions:w,gameFinished:S.finished,players:S.players,spies:S.spies,siegeCooldowns:S.siegeCooldowns,roundNumber:S.roundNumber,autoplay:l});const po=E.useCallback(mA=>{const JA=S.board[mA]??null;qA(JA)},[S.board]),mi=DI&&!Be.current,Di=mi?S:Vg,Si=Di.players[Di.currentPlayerIndex],un=RA??Di.board[(Si==null?void 0:Si.tileIndex)??0]??null,xi=un?Di.properties.find(mA=>mA.tileId===un.id)??null:null,Ho=xi?Di.players.find(mA=>mA.id===xi.ownerId)??null:null,uc=Ho?Xi(Ho.piece):null,Ea=Ho?RO(Ho.pieceColor,"#fff"):null,CC=E.useCallback(()=>{if(!N||ie)return;he(!0),NA(N.tileId),FA.current&&y.current(FA.current),FA.current=p.current(()=>{he(!1),FA.current=void 0},5e3),at.current=(at.current+1)%Fh.length;const mA=Fh[at.current],JA=S.players[S.currentPlayerIndex],Se=S.board[N.tileId],Oe=(Se==null?void 0:Se.name)??`Tile ${N.tileId}`,Pe=Se!=null&&Se.group?Bs[Se.group]:void 0;gt(JA?C.jsxs(C.Fragment,{children:[C.jsx("span",{style:Pe?{color:Pe}:void 0,children:Oe})," captured by ",Xi(JA.piece)]}):null),ye(mA),mt(()=>b.current.buyProperty(N.tileId)),z6()},[N,S.players,S.currentPlayerIndex,ie,mt]);E.useEffect(()=>{(S.currentTurn.phase!=="action"||(N==null?void 0:N.action)!=="buy-prompt")&&(he(!1),FA.current&&(y.current(FA.current),FA.current=void 0))},[S.currentTurn.phase,N]);const _a=E.useCallback(()=>{ie||((N==null?void 0:N.action)==="buy-prompt"&&NA(N.tileId),b.current.skipBuy())},[ie,N]),[ro,Bl]=E.useState(void 0),EQ=E.useRef(M);E.useEffect(()=>{M!==EQ.current&&(EQ.current=M,Bl(void 0))},[M]),E.useEffect(()=>{const mA=S.currentTurn.diceValues;mA&&Bl([mA[0],mA[1],0])},[S.currentTurn.diceValues]);const Ir=ro;E.useEffect(()=>{!DI||!ro||rr!=="launch"||(mI("impact"),Vl({volume:.05,rate:.85}),y.current(IC.current),IC.current=p.current(()=>{mI("idle"),IC.current=setTimeout(()=>{})},1400))},[DI,ro,rr]);const El=nt==="attack"||nt==="defense",zd=El?Ft:M,dG=El?dt:Ir,Ow=ei!=="idle"&&ot!=null?ot:Si==null?void 0:Si.tileIndex,Pw=Ow!=null?Di.board[Ow]??S.board[Ow]??null:null,Zd=ei==="liftoff"&&hA!=null?Di.board[hA]??Pw:Pw,SI=(Zd==null?void 0:Zd.type)??"start",QQ=Zd,jw=(QQ==null?void 0:QQ.type)==="planet"?_[tk(QQ.name)]??null:null,hG=(un==null?void 0:un.type)==="planet"?_[tk(un.name)]??null:null,Cr=RA?S.properties.find(mA=>mA.tileId===RA.id)??null:null,Ja=Cr?(()=>{const mA=S.players.find(JA=>JA.id===Cr.ownerId);return mA?Xi(mA.piece):null})():null,pG=!l&&!x&&!Yo.current&&!yI.current;if(T&&Ps&&!x||!T&&pG){const mA=T&&Ps;return C.jsx("div",{className:"zentara-screen","data-intro-active":"true",children:mA&&C.jsx(efe,{players:S.players,skipEnabled:Pd,onComplete:Hw},jd)})}return C.jsxs("div",{className:"zentara-screen","data-tile-type":SI,"data-pieces-moving":je&&!Je||void 0,"data-ship-bg-phase":ei,"data-cutscene-active":ge||Qt?"true":void 0,"data-raid-active":fg?"true":void 0,"data-raid-mini":Zt?"true":void 0,style:jw?{"--zentara-tile-bg":`url("${jw.imageUrl}")`}:void 0,children:[C.jsx("div",{className:"zentara-warp-background zentara-warp-background--forward","aria-hidden":"true"}),C.jsx("div",{className:"zentara-warp-background zentara-warp-background--reverse","aria-hidden":"true"}),C.jsxs("div",{className:"zentara-ambient-scene","aria-hidden":"true",children:[C.jsx("div",{className:"zentara-space-dust"}),C.jsx("div",{className:"zentara-ambient-light"}),C.jsxs("div",{className:"zentara-fleet-traffic",children:[C.jsx("i",{}),C.jsx("i",{}),C.jsx("i",{})]})]}),fg&&!Zt&&!ge&&!Qt&&C.jsx("video",{className:"zentara-raid-bg-video",src:"/videos/empire-strike.mp4",autoPlay:!0,muted:!0,playsInline:!0,loop:!0,preload:"auto"}),r&&!Zt&&C.jsxs("div",{className:"zentara-raid-live",role:"status","aria-live":"polite",children:[C.jsx("div",{className:"zentara-raid-live__label",children:r.status==="complete"?"RAID COMPLETE":"LIVE RAID"}),C.jsxs("strong",{children:[((FB=S.players.find(mA=>mA.id===r.attackerId))==null?void 0:FB.displayName)??"Attacker"," vs ",((dc=S.players.find(mA=>mA.id===r.defenderId))==null?void 0:dc.displayName)??"Defender"]}),C.jsxs("span",{children:[r.hits," hits · ",r.totalSpawned>0?Math.round(r.hits/r.totalSpawned*100):0,"% accuracy"]}),C.jsx("div",{className:"zentara-raid-live__track",children:C.jsx("i",{style:{width:`${Math.min(100,r.elapsedMs/r.durationMs*100)}%`}})})]}),ge&&C.jsx(Gpe,{src:ge,onEnd:()=>{const mA=Ze.current.shift();if(mA){ye(mA);return}ye(null),gt(null)}}),ge&&Te&&C.jsx("div",{className:"zentara-cutscene-caption zentara-cutscene-caption--top",children:Te}),Qt&&er.createPortal(C.jsx(Ope,{...Qt,onEnd:()=>_e(null)}),document.body),C.jsx("img",{src:B0e,alt:"Zentara",className:"zentara-game-logo"}),C.jsxs("div",{className:"zentara-main-row",children:[C.jsx("div",{className:"zentara-player-col",children:C.jsx(Jhe,{players:S.players,properties:S.properties,tiles:S.board,currentPlayerId:(Fe==null?void 0:Fe.id)??"",localPlayerId:A,onSaveAndExit:i?Ke:void 0,roomId:I,onAvatarClick:mA=>{DA(mA);const JA=S.players.find(Se=>Se.id===mA);JA&&BA(JA.tileIndex)},onUpgradeProperty:j,upgradeableCount:rg})}),C.jsx("div",{className:"zentara-board-col",children:C.jsxs("div",{className:"zentara-board-area",children:[C.jsx(Cse,{gameState:Vg,onTileClick:po,zoomOverride:UB,onPieceArrival:()=>{if(At.current=!0,pt(!0),vt(!1),Re(null),y.current(ee.current),ht.current?Vt("idle"):(Vt("landing"),ee.current=p.current(()=>{Vt("idle"),kt(null)},w0e)),typeof window<"u"&&new URLSearchParams(window.location.search).get("debugTurrets")==="1"){const mA=["crimson-dominion","silver-pact","azure-sovereignty","golden-imperium","emerald-collective","void-enclave"],JA=fA.current.players[fA.current.currentPlayerIndex];if(JA){const Se=JA.tileIndex;mA[Se%mA.length]!==JA.piece&&($e(80),Tc(),p.current(()=>pa(),200),ke(Se,1400))}}},onPieceMoveStart:()=>{vt(!0),y.current(ee.current);const mA=Vg.players[Vg.currentPlayerIndex];mA&&kt(mA.tileIndex),ht.current?Vt("idle"):(Vt("liftoff"),ee.current=p.current(()=>{Vt("warp"),ee.current=p.current(()=>{Vt("warp-exit"),ee.current=p.current(()=>{Re(null),Vt("landing")},GO)},GO)},GO))},onZoomChange:vB,focusTileIndex:rA,toggleZoomRef:pA,laserBeamTile:UA,laserBeamSeq:oe,blastDamage:be,suppressDarkOverlay:!!ge||!!Qt||fg}),C.jsx("div",{className:"zentara-top-hud",children:C.jsxs("div",{className:"zentara-dice-miniboard","aria-label":"Dice and board overview",children:[C.jsx("div",{className:"zentara-minimap-wrapper zentara-minimap-wrapper--around-dice",children:C.jsx(Ohe,{players:Vg.players,currentPlayerId:((Iy=Vg.players[Vg.currentPlayerIndex])==null?void 0:Iy.id)??"",properties:Vg.properties,tiles:Vg.board,onTileClick:BA})}),C.jsxs("div",{className:`zentara-dice-center zentara-dice-center--${rr}`,"data-roll-phase":rr,style:{"--player-color":RO(Fe==null?void 0:Fe.pieceColor,"#fff"),"--roll-charge":ar},children:[C.jsxs("div",{className:"zentara-roll-console","aria-hidden":"true",children:[C.jsx("span",{className:"zentara-roll-console__ring zentara-roll-console__ring--outer"}),C.jsx("span",{className:"zentara-roll-console__ring zentara-roll-console__ring--inner"}),C.jsx("span",{className:"zentara-roll-console__scan"}),C.jsx("span",{className:"zentara-roll-console__impact"})]}),(()=>{const mA=nt==="attack"&&Xe?Xe.atk:nt==="defense"&&Xe?Xe.def:Fe,JA=h0e(mA);return C.jsx(XDA,{isWaiting:!1,rollTrigger:zd,results:dG,chargeLevel:El?0:ar,gameMode:"craps",feltColor:"transparent",shimmerColor:"#7ec8f0",diceModels:[JA,JA]})})(),!El&&Le&&(rr==="charging"||rr==="launch")&&C.jsxs("div",{className:"zentara-roll-status","aria-live":"polite",children:[C.jsx("span",{className:"zentara-roll-status__eyebrow",children:rr==="charging"?"COMMAND LINK":"VECTOR CAST"}),C.jsx("strong",{children:rr==="charging"?`${Math.max(1,Math.round(ar*100))}%`:"ROLLING"})]}),(nt==="attack"||nt==="defense")&&$A&&C.jsx("div",{className:"zentara-clash-roll-label",children:$A})]})]})}),nt==="intro"&&Xe&&er.createPortal(C.jsxs("div",{className:`zentara-clash-intro-overlay${vA?" zentara-clash-intro-overlay--manual-roll":""}${WA?" zentara-clash-intro-overlay--closing":""}`,children:[C.jsxs("div",{className:"zentara-clash-intro-side zentara-clash-intro-side--left",style:{"--clash-faction-color":zu[Xe.atk.piece]},children:[Xe.atk.heroId&&BE[Xe.atk.heroId]?C.jsx("img",{className:"zentara-clash-intro-portrait",src:BE[Xe.atk.heroId],alt:""}):C.jsx("div",{className:"zentara-clash-intro-portrait zentara-clash-intro-portrait--fallback"}),C.jsx("div",{className:"zentara-clash-intro-label",children:Xi(Xe.atk.piece)})]}),C.jsxs("div",{className:"zentara-clash-intro-vs",children:["⚔️",C.jsx("br",{}),"HERO",C.jsx("br",{}),"CLASH"]}),C.jsxs("div",{className:"zentara-clash-intro-side zentara-clash-intro-side--right",style:{"--clash-faction-color":zu[Xe.def.piece]},children:[Xe.def.heroId&&BE[Xe.def.heroId]?C.jsx("img",{className:"zentara-clash-intro-portrait zentara-clash-intro-portrait--flip",src:BE[Xe.def.heroId],alt:""}):C.jsx("div",{className:"zentara-clash-intro-portrait zentara-clash-intro-portrait--fallback zentara-clash-intro-portrait--flip"}),C.jsx("div",{className:"zentara-clash-intro-label",children:Xi(Xe.def.piece)})]}),vA&&C.jsx("button",{className:"zentara-btn zentara-btn--primary zentara-clash-intro-roll-btn",onClick:jt,disabled:!VA,children:VA?"⚔️ Hero Roll Dice":"⚔️ Preparing Clash..."})]}),document.body),nt==="result"&&ve&&(()=>{const mA=ve.attackDice[0]+ve.attackDice[1],JA=ve.defenseDice[0]+ve.defenseDice[1],Se=mA>JA,Oe=Se?ve.attackHeroId:ve.defendHeroId,Pe=Se?ve.attackBoostPct:ve.defenseReducePct,We=Se?"Attack Boost":"Defense Reduction";return C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"zentara-clash-result-backdrop"}),C.jsx("div",{className:"zentara-clash-result-overlay",onClick:Yi,children:C.jsxs("div",{className:"zentara-clash-result-panel",onClick:Dt=>Dt.stopPropagation(),children:[C.jsx("div",{className:"zentara-clash-result-title",children:"⚔️ Hero Clash Result"}),Oe&&BE[Oe]&&C.jsxs("div",{className:"zentara-clash-result-hero-display",children:[C.jsx("img",{className:"zentara-clash-result-hero-image",src:BE[Oe],alt:"Winner Hero"}),C.jsxs("div",{className:"zentara-clash-result-hero-impact",children:[C.jsx("div",{className:"zentara-clash-result-hero-impact-label",children:We}),C.jsxs("div",{className:"zentara-clash-result-hero-impact-value",children:["+",Pe,"%"]})]})]}),C.jsxs("div",{className:`zentara-clash-result-row zentara-clash-result-row--attack ${Se?"active":"inactive"}`,children:[C.jsx("span",{className:"zentara-clash-result-icon",children:"⚔️"}),C.jsxs("span",{className:"zentara-clash-result-name",children:[ve.attackerName,Se?" 🏆":""]}),C.jsxs("span",{className:"zentara-clash-result-dice",children:["🎲 ",ve.attackDice[0]," + ",ve.attackDice[1]," = ",mA]}),C.jsxs("span",{className:"zentara-clash-result-pct",children:["+",ve.attackBoostPct,"% boost"]})]}),C.jsxs("div",{className:`zentara-clash-result-row zentara-clash-result-row--defense ${Se?"inactive":"active"}`,children:[C.jsx("span",{className:"zentara-clash-result-icon",children:"🛡"}),C.jsxs("span",{className:"zentara-clash-result-name",children:[ve.defenderName,Se?"":" 🏆"]}),C.jsxs("span",{className:"zentara-clash-result-dice",children:["🎲 ",ve.defenseDice[0]," + ",ve.defenseDice[1]," = ",JA]}),C.jsxs("span",{className:"zentara-clash-result-pct",children:["−",ve.defenseReducePct,"% block"]})]}),C.jsxs("div",{className:"zentara-clash-result-damage",children:[C.jsx("span",{className:"zentara-clash-result-damage-label",children:"Damage"}),C.jsxs("span",{className:"zentara-clash-result-damage-value",children:["✦",ve.finalDamage]}),C.jsx("button",{className:"zentara-clash-calc-toggle",onClick:Dt=>{Dt.stopPropagation(),xe(!pe)},children:"i"}),pe&&C.jsx("div",{className:"zentara-clash-calculation-floating",children:C.jsxs("div",{className:"zentara-clash-calculation-card zentara-clash-calculation-tooltip",children:[C.jsx("div",{className:"zentara-clash-calculation-header",children:"Calculation"}),C.jsxs("div",{className:"zentara-clash-calculation-rows",children:[C.jsxs("div",{className:"zentara-clash-calculation-row",children:[C.jsx("span",{children:"Base Damage"}),C.jsxs("span",{style:{color:"#fff"},children:["✦",ve.baseDamage]})]}),C.jsxs("div",{className:"zentara-clash-calculation-row zentara-clash-calculation-row--boost",children:[C.jsxs("span",{children:["+ Attack Boost (",ve.attackBoostPct,"%)"]}),C.jsxs("span",{children:["+✦",Math.round(ve.baseDamage*ve.attackBoostPct/100)]})]}),C.jsxs("div",{className:"zentara-clash-calculation-row zentara-clash-calculation-row--block",children:[C.jsxs("span",{children:["- Defense Block (",ve.defenseReducePct,"%)"]}),C.jsxs("span",{children:["−✦",Math.round(ve.baseDamage*ve.defenseReducePct/100)]})]}),C.jsxs("div",{className:"zentara-clash-calculation-row zentara-clash-calculation-row--final",children:[C.jsx("span",{children:"= Final Damage"}),C.jsxs("span",{children:["✦",ve.finalDamage]})]})]})]})})]}),C.jsx("div",{className:"zentara-clash-result-continue",onClick:Yi,children:"Click to continue…"})]})})]})})(),Hg&&C.jsxs("div",{style:{position:"absolute",top:8,left:8,zIndex:999,background:"rgba(0,0,0,0.85)",color:"#fff",padding:"10px 14px",borderRadius:8,fontSize:12,fontFamily:"monospace",display:"flex",flexDirection:"column",gap:6,minWidth:200},children:[C.jsx("div",{style:{fontWeight:700,fontSize:13,marginBottom:2},children:"Blast Debug"}),C.jsxs("label",{children:["Damage: ",be," ",C.jsxs("span",{style:{opacity:.5},children:["(scale ",Math.min(3,Math.max(.35,be/100)).toFixed(2),"×)"]}),C.jsx("input",{type:"range",min:2,max:1500,step:1,value:be,onChange:mA=>$e(Number(mA.target.value)),style:{width:"100%"}})]}),C.jsxs("label",{children:["Tile:",C.jsx("input",{type:"number",min:0,max:39,defaultValue:0,id:"__blast-tile",style:{width:50,marginLeft:6,background:"#222",color:"#fff",border:"1px solid #555",borderRadius:4,padding:"2px 4px"}})]}),C.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:[2,10,50,100,300,800,1500].map(mA=>C.jsx("button",{onClick:()=>{var Se;$e(mA);const JA=Number(((Se=document.getElementById("__blast-tile"))==null?void 0:Se.value)??0);ke(JA,1200)},style:{padding:"3px 8px",fontSize:11,background:"#333",color:"#fff",border:"1px solid #666",borderRadius:4,cursor:"pointer"},children:mA},mA))}),C.jsx("button",{onClick:()=>{var JA;const mA=Number(((JA=document.getElementById("__blast-tile"))==null?void 0:JA.value)??0);ke(mA,1200)},style:{padding:"4px 10px",fontSize:12,background:"#2563eb",color:"#fff",border:"none",borderRadius:4,cursor:"pointer"},children:"Fire 💥"}),C.jsx("button",{onClick:()=>de(!1),style:{padding:"2px 8px",fontSize:11,background:"transparent",color:"#888",border:"1px solid #444",borderRadius:4,cursor:"pointer",alignSelf:"flex-end"},children:"Close"})]})]})}),C.jsx("div",{className:"zentara-floating-controls",children:C.jsx(hpA,{roomId:I,singlePlayer:!I})}),C.jsxs("div",{className:`zentara-sidebar ${EA?"zentara-sidebar--folded":""}`,"data-moving":!Je||void 0,children:[C.jsxs("div",{className:"zentara-command-strip","aria-label":"Game commands",children:[C.jsx("button",{onClick:()=>{gA(),H(!0)},children:"Players"}),C.jsx("button",{disabled:!ft||ft.depleted,onClick:()=>{gA(),$(!0)},children:"Trade"}),C.jsxs("button",{onClick:()=>{Ae()||(gA(),tA(!0))},children:["Chat",_A>0&&C.jsx("span",{children:_A>9?"9+":_A})]}),!D&&C.jsx("button",{onClick:mA=>{mA.preventDefault(),mA.stopPropagation(),!Ae()&&(gA(),w.saveGame(),Ke())},children:"Save & Exit"})]}),C.jsx("button",{type:"button",className:"zentara-sidebar__toggle",onClick:()=>{gA(),PA(!EA)},title:EA?"Expand":"Fold","aria-label":EA?"Expand sidebar":"Fold sidebar",children:EA?"◀":"▶"}),Le&&C.jsx("div",{className:"zentara-your-turn",children:"Your Turn"}),Je&&C.jsx(Rhe,{tile:un,property:xi,ownerName:uc,ownerColor:Ea,planetContent:hG,onClick:()=>{gA(),un&&qA(un)}}),Le&&S.currentTurn.phase==="pre-roll"&&ft&&C.jsxs("div",{className:"zentara-ship-upgrade-row",children:[C.jsxs("button",{className:"zentara-menu-btn zentara-menu-btn--ship",disabled:ft.armorLevel>=dn.maxArmorLevel||ft.credits<dn.armorUpgradeCost,onClick:()=>{gA(),OA("armor")},children:[C.jsx("span",{className:"ship-btn__icon",children:"🛡"}),C.jsxs("span",{className:"ship-btn__label",children:["Armor ",ft.armorLevel,"/",dn.maxArmorLevel]}),C.jsxs("span",{className:"ship-btn__cost",children:[dn.armorUpgradeCost,"c"]})]}),C.jsxs("button",{className:"zentara-menu-btn zentara-menu-btn--ship",disabled:ft.weaponLevel>=dn.maxWeaponLevel||ft.credits<dn.weaponUpgradeCost,onClick:()=>{gA(),OA("weapon")},children:[C.jsx("span",{className:"ship-btn__icon",children:"🚀"}),C.jsxs("span",{className:"ship-btn__label",children:["Weapons ",ft.weaponLevel,"/",dn.maxWeaponLevel]}),C.jsxs("span",{className:"ship-btn__cost",children:[dn.weaponUpgradeCost,"c"]})]}),ft.armorLevel>0&&C.jsxs("button",{className:"zentara-menu-btn zentara-menu-btn--ship zentara-menu-btn--liquidate",onClick:()=>{gA(),OA("liquidate-armor")},children:[C.jsx("span",{className:"ship-btn__icon",children:"🛡"}),C.jsx("span",{className:"ship-btn__label",children:"Sell Armor"}),C.jsxs("span",{className:"ship-btn__cost",children:["+",Math.floor(dn.armorUpgradeCost/2),"c"]})]}),ft.weaponLevel>0&&C.jsxs("button",{className:"zentara-menu-btn zentara-menu-btn--ship zentara-menu-btn--liquidate",onClick:()=>{gA(),OA("liquidate-weapon")},children:[C.jsx("span",{className:"ship-btn__icon",children:"🚀"}),C.jsx("span",{className:"ship-btn__label",children:"Sell Weapons"}),C.jsxs("span",{className:"ship-btn__cost",children:["+",Math.floor(dn.weaponUpgradeCost/2),"c"]})]})]}),qe&&ft&&C.jsx("div",{className:"zentara-ship-confirm-overlay",onClick:()=>OA(null),children:C.jsxs("div",{className:"zentara-ship-confirm-card",onClick:mA=>mA.stopPropagation(),children:[qe==="armor"?C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"zentara-ship-confirm__icon",children:"🛡"}),C.jsx("h4",{className:"zentara-ship-confirm__title",children:"Upgrade Ship Armor"}),C.jsxs("p",{className:"zentara-ship-confirm__level",children:["Level ",ft.armorLevel," → ",ft.armorLevel+1]}),C.jsxs("p",{className:"zentara-ship-confirm__desc",children:["Each armor level reduces incoming hull damage by 15%. At level ",ft.armorLevel+1,", you'll absorb ",C.jsxs("strong",{children:[(ft.armorLevel+1)*15,"%"]})," of all damage when landing on enemy planets."]}),C.jsxs("p",{className:"zentara-ship-confirm__cost",children:["Cost: ",C.jsxs("strong",{children:[dn.armorUpgradeCost," energy"]})]}),C.jsxs("p",{className:"zentara-ship-confirm__balance",children:["Balance after: ",ft.credits-dn.armorUpgradeCost," energy"]})]}):qe==="weapon"?C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"zentara-ship-confirm__icon",children:"🚀"}),C.jsx("h4",{className:"zentara-ship-confirm__title",children:"Upgrade Ship Weapons"}),C.jsxs("p",{className:"zentara-ship-confirm__level",children:["Level ",ft.weaponLevel," → ",ft.weaponLevel+1]}),C.jsx("p",{className:"zentara-ship-confirm__desc",children:ft.weaponLevel===0?"Unlocks Strike — when you roll doubles and land on an enemy planet, automatically destroy one arms level on that property.":"Increases your strike power for Resource Raids. Higher weapon levels give you a dice bonus during raid roll-offs."}),C.jsxs("p",{className:"zentara-ship-confirm__cost",children:["Cost: ",C.jsxs("strong",{children:[dn.weaponUpgradeCost," energy"]})]}),C.jsxs("p",{className:"zentara-ship-confirm__balance",children:["Balance after: ",ft.credits-dn.weaponUpgradeCost," energy"]})]}):qe==="liquidate-armor"?C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"zentara-ship-confirm__icon",children:"🛡"}),C.jsx("h4",{className:"zentara-ship-confirm__title",children:"Sell Ship Armor"}),C.jsxs("p",{className:"zentara-ship-confirm__level",children:["Level ",ft.armorLevel," → ",ft.armorLevel-1]}),C.jsxs("p",{className:"zentara-ship-confirm__desc",children:["Downgrade armor by one level. You'll lose 15% damage reduction (",ft.armorLevel*15,"% → ",(ft.armorLevel-1)*15,"%)."]}),C.jsxs("p",{className:"zentara-ship-confirm__cost",children:["Refund: ",C.jsxs("strong",{children:[Math.floor(dn.armorUpgradeCost/2)," energy"]})]}),C.jsxs("p",{className:"zentara-ship-confirm__balance",children:["Balance after: ",ft.credits+Math.floor(dn.armorUpgradeCost/2)," energy"]})]}):C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"zentara-ship-confirm__icon",children:"🚀"}),C.jsx("h4",{className:"zentara-ship-confirm__title",children:"Sell Ship Weapons"}),C.jsxs("p",{className:"zentara-ship-confirm__level",children:["Level ",ft.weaponLevel," → ",ft.weaponLevel-1]}),C.jsx("p",{className:"zentara-ship-confirm__desc",children:ft.weaponLevel===1?"You will lose Strike ability entirely — no more automatic hits on enemy planets when rolling doubles.":"Downgrade weapons by one level. Your strike power for Resource Raids will decrease."}),C.jsxs("p",{className:"zentara-ship-confirm__cost",children:["Refund: ",C.jsxs("strong",{children:[Math.floor(dn.weaponUpgradeCost/2)," energy"]})]}),C.jsxs("p",{className:"zentara-ship-confirm__balance",children:["Balance after: ",ft.credits+Math.floor(dn.weaponUpgradeCost/2)," energy"]})]}),C.jsxs("div",{className:"zentara-ship-confirm__buttons",children:[C.jsx("button",{className:"zentara-ship-confirm__btn zentara-ship-confirm__btn--cancel",onClick:()=>{gA(),OA(null)},children:"Cancel"}),C.jsx("button",{className:`zentara-ship-confirm__btn ${qe.startsWith("liquidate")?"zentara-ship-confirm__btn--sell":"zentara-ship-confirm__btn--confirm"}`,onClick:()=>{gA(),qe==="armor"?w.upgradeArmor():qe==="weapon"?w.upgradeWeapon():qe==="liquidate-armor"?(w.liquidateArmor(),U.info(`${ai(A)} sold armor`,`Shield Level ${ft.armorLevel-1} (+${Math.floor(dn.armorUpgradeCost/2)} energy)`)):(w.liquidateWeapon(),U.info(`${ai(A)} sold weapons`,`Weapon Level ${ft.weaponLevel-1} (+${Math.floor(dn.weaponUpgradeCost/2)} energy)`)),OA(null)},children:qe.startsWith("liquidate")?"Confirm Sale":"Confirm Upgrade"})]})]})}),C.jsx("div",{className:"zentara-sidebar-spacer"}),C.jsx(mhe,{phase:mi&&Je?S.currentTurn.phase:mi?"landed":"rolling",pendingEffect:mi&&Je?N:null,suppressBuyPrompt:rt,buyInProgress:ie,tileOwnedByMe:!!((N==null?void 0:N.tileId)!=null&&S.properties.some(mA=>mA.tileId===N.tileId&&mA.ownerId===A)),isMyTurn:Le,inJail:(Fe==null?void 0:Fe.inJail)??!1,onRoll:ae,onRollPressStart:lA,onRollChargeChange:LA,onBuy:CC,onSkipBuy:_a,onPayRent:w.payRent,onHeroClashRoll:w.heroClashRoll,onPayTax:w.payTax,onResolveCard:w.resolveCard,onPayBail:w.payBailAction,onPlantSpy:ao,plantSpyEligibleGroup:Ig,plantSpyCost:Us,onArmPlanets:()=>oA(!0),credits:((Cy=S.players.find(mA=>mA.id===A))==null?void 0:Cy.credits)??0,upgradeableCount:rg,armableCount:En})]})]}),C.jsx(Uhe,{tile:RA,property:Cr,ownerName:Ja,isOwnedByMe:(Cr==null?void 0:Cr.ownerId)===A,canAffordUpgrade:!!((RA==null?void 0:RA.upgradeCost)!=null&&Cr&&(((hc=S.players.find(mA=>mA.id===A))==null?void 0:hc.credits)??0)>=RA.upgradeCost&&Cr.upgradeLevel<Hm(A,RA.id,S.board,S.properties)),onClose:()=>qA(null),onUpgrade:j,onMortgage:mA=>w.mortgageProperty(mA),onSell:mA=>w.sellProperty(mA),onSabotage:mA=>w.sabotageProperty(mA),sabotageCost:(()=>{if(!(RA!=null&&RA.group)||!RA.upgradeCost||!Cr||Cr.ownerId===A||Cr.upgradeLevel<=0)return null;const mA=S.board.filter(Se=>Se.group===RA.group).map(Se=>Se.id),JA=S.properties.filter(Se=>mA.includes(Se.tileId)&&Se.ownerId===A&&!Se.dormant).length;return JA<=0?null:RA.upgradeCost*(mA.length-JA+1)})(),credits:((Zw=S.players.find(mA=>mA.id===A))==null?void 0:Zw.credits)??0,groupOwned:(()=>{if(!(RA!=null&&RA.group))return;const mA=S.board.filter(JA=>JA.group===RA.group).map(JA=>JA.id);return S.properties.filter(JA=>mA.includes(JA.tileId)&&JA.ownerId===A).length})(),groupTotal:(()=>{if(RA!=null&&RA.group)return S.board.filter(mA=>mA.group===RA.group).length})(),planetContent:hG}),C.jsx(fpe,{player:Ie?S.players.find(mA=>mA.id===Ie)??null:null,properties:S.properties,tiles:S.board,isCurrentPlayer:Ie===(Fe==null?void 0:Fe.id),onClose:()=>DA(null),onTileClick:mA=>{qA(S.board[mA]??null),DA(null)}}),iA&&C.jsx(AmA,{playerId:A,credits:((_B=S.players.find(mA=>mA.id===A))==null?void 0:_B.credits)??0,properties:S.properties,board:S.board,onUpgrade:j,onClose:()=>oA(!1)}),C.jsx(Zhe,{open:W&&!!ft||!!G&&G.recipient.playerId===A,mode:G&&G.recipient.playerId===A?"review":"propose",localPlayer:ft??Fe,players:S.players,properties:S.properties,tiles:S.board,pendingTrade:G,onPropose:(mA,JA,Se,Oe,Pe)=>{var Dt;const We=((Dt=ft??Fe)==null?void 0:Dt.id)??A;w.proposeTrade(We,mA,JA,Se,Oe,Pe),$(!1)},onAccept:()=>{w.acceptTrade(),$(!1)},onDecline:()=>{w.declineTrade(),$(!1)},onClose:()=>$(!1)}),S.currentTurn.phase==="in-debt"&&Le&&C.jsx("div",{className:"zentara-debt-overlay",children:C.jsxs("div",{className:"zentara-debt-modal",children:[C.jsx("h2",{className:"zentara-debt-title",children:"⚠️ Fleet in Crisis"}),C.jsx("p",{className:"zentara-debt-subtitle",children:"Your energy is depleted! Sell properties to recover, or accept your fate."}),C.jsxs("p",{className:"zentara-debt-credits",children:["Energy: ",C.jsxs("span",{className:"zentara-debt-player-credits",children:["✦",(Fe==null?void 0:Fe.credits)??0]})]}),C.jsx("div",{className:"zentara-debt-props",children:S.properties.filter(mA=>mA.ownerId===A).map(mA=>{const JA=S.board[mA.tileId];if(!(JA!=null&&JA.cost))return null;const Se=Math.floor(JA.cost/2),Oe=JA.upgradeCost?Math.floor(JA.upgradeCost/2):0,Pe=JA.group?Bs[JA.group]:void 0;return C.jsxs("div",{className:"zentara-debt-prop-row",children:[C.jsxs("div",{className:"zentara-debt-prop-info",children:[Pe&&C.jsx("span",{className:"zentara-debt-prop-dot",style:{"--prop-color":Pe}}),C.jsx("span",{className:"zentara-debt-prop-name",children:JA.name}),mA.upgradeLevel>0&&C.jsxs("span",{className:"zentara-debt-prop-level",children:["Lv",mA.upgradeLevel]})]}),C.jsxs("div",{className:"zentara-debt-actions",children:[mA.upgradeLevel>0&&C.jsxs("button",{className:"zentara-debt-sell-btn zentara-debt-sell-btn--liquidate",onClick:()=>w.debtLiquidateArm(mA.tileId),children:["Liquidate Arm +✦",Oe]}),C.jsxs("button",{className:"zentara-debt-sell-btn",onClick:()=>w.debtSell(mA.tileId),disabled:mA.upgradeLevel>0,children:["Sell Planet +✦",Se]})]})]},mA.tileId)})}),C.jsx("button",{className:"zentara-debt-done-btn",onClick:()=>w.debtResolve(),disabled:((Fe==null?void 0:Fe.credits)??0)<=0&&S.properties.some(mA=>mA.ownerId===A),children:S.properties.filter(mA=>mA.ownerId===A).length===0?"Accept Fate":"Done Selling"})]})}),S.finished&&!ge&&!Qt&&C.jsxs("div",{className:"zentara-win-overlay",children:[C.jsx("div",{className:"zentara-win-title",children:"⚔️ War Over"}),C.jsxs("div",{className:"zentara-win-name",children:[Qn?Xi(Qn.piece):"Unknown"," claims victory!"]}),C.jsxs("div",{className:"zentara-win-total",children:["Total Net Worth: ✦",(Ng==null?void 0:Ng.total)??(Qn==null?void 0:Qn.credits)??0]}),Ng&&C.jsxs("div",{className:"zentara-win-breakdown",children:[C.jsxs("span",{children:["⚡ Energy: ✦",Ng.credits]}),Ng.propertyValue>0&&C.jsxs("span",{children:["🌍 Planets: ✦",Ng.propertyValue]}),Ng.weaponValue>0&&C.jsxs("span",{children:["🚀 Weapons: ✦",Ng.weaponValue]}),Ng.armorValue>0&&C.jsxs("span",{children:["🛡 Armor: ✦",Ng.armorValue]})]}),C.jsxs("div",{className:"zentara-win-actions",children:[C.jsx("button",{className:"zentara-win-btn zentara-win-btn--primary",onClick:()=>{X1();const mA=crypto.randomUUID().slice(0,8);h(`/zentara/match/${mA}`)},children:"Play Again"}),C.jsx("button",{className:"zentara-win-btn zentara-win-btn--secondary",onClick:()=>{h("/lobby")},children:"Back to Lobby"})]}),C.jsx("div",{style:{marginTop:12,display:"flex",justifyContent:"center"},children:C.jsx(nEA,{gameMode:"zentara"})})]}),Z&&C.jsx(ife,{deck:Z.deck,text:Z.text,amount:Z.amount,rollerName:Fe?Xi(Fe.piece):"Unknown Fleet",rollerColor:(Fe==null?void 0:Fe.pieceColor)??"#888",onDismiss:()=>{eA(null),b.current.resolveCard()},autoDismissMs:Z.autoDismissMs}),aA&&C.jsx(nfe,{...aA,onConfirm:()=>{b.current.plantSpy(aA.group),sA(null)},onCancel:()=>sA(null)}),Zt&&Zt.miniGame==="fps"&&C.jsx(wmA,{attacker:Zt.attacker,defender:Zt.defender,onComplete:bs,tileBackgroundImage:Zt.tileImage,botPilot:!!Zt.botPilot,onProgress:D?mA=>{var JA,Se;return(Se=(JA=b.current).reportRaidProgress)==null?void 0:Se.call(JA,{attackerId:Zt.attacker.id,defenderId:Zt.defender.id,...mA})}:void 0}),Zt&&Zt.miniGame==="codebreaker"&&C.jsx(kmA,{attacker:Zt.attacker,defender:Zt.defender,onComplete:bs}),Zt&&Zt.miniGame==="soldier-fps"&&C.jsx(ue.Suspense,{fallback:null,children:C.jsx(p0e,{attacker:Zt.attacker,defender:Zt.defender,onComplete:bs,botPilot:!!Zt.botPilot,tileBackgroundImage:Zt.tileImage,skipBonus:!!Zt.skipBonus})}),(N==null?void 0:N.action)==="spy-clash"&&(Je||l)&&(N.spyOwnerId===A||l)&&(()=>{const mA=S.players.find(Pe=>Pe.id===N.spyOwnerId),JA=S.players.find(Pe=>Pe.id===N.defenderId);if(!mA||!JA)return null;const Se=S.board[N.tileId],Oe=l&&N.spyOwnerId!==A;return er.createPortal(C.jsx(QsA,{pendingEffect:N,attacker:mA,defender:JA,groupColor:Se!=null&&Se.group?Bs[Se.group]??"#9d4edd":"#9d4edd",onPuzzleResult:Pe=>{var We;return(We=w.spyPuzzleResult)==null?void 0:We.call(w,Pe)},onShotResult:Pe=>{var We;return(We=w.spyShotResult)==null?void 0:We.call(w,Pe)},botPilot:Oe}),document.body)})(),kn&&(()=>{var JA;const mA={tileId:((JA=S.board.find(Se=>Se.group===kn.group))==null?void 0:JA.id)??0,action:"spy-clash",group:kn.group,spyOwnerId:kn.attacker.id,defenderId:kn.defender.id,step:kn.step};return C.jsx(QsA,{pendingEffect:mA,attacker:kn.attacker,defender:kn.defender,groupColor:Bs[kn.group]??"#9d4edd",onPuzzleResult:Se=>{console.log(`[SPY STRIKE DEBUG] puzzle result: ${Se?"PASS → advancing to shot":"FAIL"}`),Se?gn(Oe=>Oe&&{...Oe,step:"shot"}):p.current(()=>gn(null),1800)},onShotResult:Se=>{console.log(`[SPY STRIKE DEBUG] shot result: ${Se}`),p.current(()=>gn(null),1800)}})})(),Ki&&C.jsxs(C.Fragment,{children:[C.jsx(_mA,{defender:Ki.defender,groupColor:Ki.groupColor,onComplete:mA=>{console.log(`[SNIPER DEBUG] outcome: ${mA}`),p.current(()=>Tn(null),1500)}},Ki.runKey),C.jsxs("div",{className:"zentara-sniper-debug-toolbar",children:[C.jsx("button",{type:"button",className:"zentara-sniper-debug-btn",onClick:()=>Tn(mA=>mA&&{...mA,runKey:mA.runKey+1}),children:"🔁 RESTART"}),C.jsx("button",{type:"button",className:"zentara-sniper-debug-btn zentara-sniper-debug-btn--close",onClick:()=>Tn(null),children:"✕ CLOSE"})]})]}),C.jsx(c0e,{open:x,onClose:z}),QA&&!ge&&!Qt&&C.jsx("div",{className:"zentara-laser-flash",onAnimationEnd:()=>dA(!1)}),C.jsx(Vhe,{players:S.players,properties:S.properties,tiles:S.board,currentPlayerId:(Fe==null?void 0:Fe.id)??"",open:L,onClose:()=>H(!1)}),C.jsx($he,{open:P,onClose:()=>tA(!1),roomId:I,localPlayerId:A,players:S.players,injectedMessages:cA?IA:void 0,onLocalSend:cA&&!l?mA=>{var JA;CA(Se=>Se.some(Oe=>Oe.id===mA.id)?Se:[...Se,mA]),(JA=YA.current)==null||JA.notifyHumanMessage(mA.text)}:void 0}),cA&&C.jsx(epe,{latest:X,players:S.players,onOpen:()=>tA(!0),hidden:P})]})},Vi={ROLL:"zentara:roll",BUY:"zentara:buy",SKIP_BUY:"zentara:skip-buy",PAY_RENT:"zentara:pay-rent",HERO_CLASH_ROLL:"zentara:hero-clash-roll",PAY_TAX:"zentara:pay-tax",RESOLVE_CARD:"zentara:resolve-card",PAY_BAIL:"zentara:pay-bail",APPLY_TELEPORT:"zentara:apply-teleport",END_TURN:"zentara:end-turn",UPGRADE:"zentara:upgrade",MORTGAGE:"zentara:mortgage",SELL:"zentara:sell",SABOTAGE:"zentara:sabotage",UPGRADE_ARMOR:"zentara:upgrade-armor",UPGRADE_WEAPON:"zentara:upgrade-weapon",LIQUIDATE_ARMOR:"zentara:liquidate-armor",LIQUIDATE_WEAPON:"zentara:liquidate-weapon",RESOLVE_RAID:"zentara:resolve-raid",RAID_PROGRESS:"zentara:raid-progress",DEBT_SELL:"zentara:debt-sell",DEBT_LIQUIDATE_ARM:"zentara:debt-liquidate-arm",DEBT_RESOLVE:"zentara:debt-resolve",PLANT_SPY:"zentara:plant-spy",SPY_PUZZLE_RESULT:"zentara:spy-puzzle-result",SPY_SHOT_RESULT:"zentara:spy-shot-result",PROPOSE_TRADE:"zentara:propose-trade",ACCEPT_TRADE:"zentara:accept-trade",DECLINE_TRADE:"zentara:decline-trade",SELECT_PIECE:"zentara:select-piece",START_MATCH:"zentara:start-match",GET_STATE:"zentara:get-state",STATE_UPDATE:"zentara:state-update",PIECE_SELECTED:"zentara:piece-selected",TRADE_PROPOSED:"zentara:trade-proposed",TRADE_RESOLVED:"zentara:trade-resolved",GAME_OVER:"zentara:game-over"};function Mv(){return crypto.randomUUID()}function hsA(e,A,t,i=1e4){return new Promise(n=>{const g=setTimeout(()=>n(null),i);e.emit(A,t,o=>{clearTimeout(g),n(o)})})}function psA(e){if(!e)return null;const A=String(e.action??"");return A==="pay-rent"?{...e,action:"energy-toll"}:A==="pay-tax"?{...e,action:"void-drain"}:e}function N0e(e){const A=Ms(),{meId:t,user:i}=tn(),n=t??(i==null?void 0:i.id),{info:g}=JL(),[o,s]=E.useState(null),[a,r]=E.useState([]),[I,c]=E.useState(null),[l,B]=E.useState(0),[Q,h]=E.useState(null),[d,p]=E.useState(!!(A!=null&&A.connected)),y=E.useRef(null),[m,D]=E.useState({}),S=Object.values(m);E.useEffect(()=>{if(!A)return;const CA=()=>{if(!A.connected){console.warn("[Zentara] requestState: socket not connected");return}console.log("[Zentara] Requesting game state for room",e),hsA(A,Vi.GET_STATE,{roomId:e,eventId:Mv()}).then(X=>{if(X!=null&&X.ok&&X.state){console.log("[Zentara] GET_STATE response OK, phase:",X.state.currentTurn.phase);const O={...X.state,pendingEffect:psA(X.state.pendingEffect),board:XF(X.state.boardSize).tiles};for(const cA of O.players)cA.armorLevel==null&&(cA.armorLevel=0),cA.weaponLevel==null&&(cA.weaponLevel=0);s(O)}else console.warn("[Zentara] GET_STATE response not OK",X)}).catch(X=>{console.warn("[Zentara] GET_STATE error:",X.message)})},_A=()=>{console.log("[Zentara] Socket connected"),p(!0),CA()},uA=()=>{console.warn("[Zentara] Socket disconnected"),p(!1)};return A.on("connect",_A),A.on("disconnect",uA),p(A.connected),A.connected&&CA(),()=>{A.off("connect",_A),A.off("disconnect",uA)}},[A,e]),E.useEffect(()=>{if(!A)return;const CA=wA=>{var YA,jA;console.log("[Zentara] STATE_UPDATE received",{phase:wA.state.currentTurn.phase,currentPlayerIdx:wA.state.currentPlayerIndex,pendingEffect:(YA=wA.state.pendingEffect)==null?void 0:YA.action,playersCount:wA.state.players.length});const xA={...wA.state,pendingEffect:psA(wA.state.pendingEffect),board:XF(wA.state.boardSize).tiles};for(const ie of xA.players)ie.armorLevel==null&&(ie.armorLevel=0),ie.weaponLevel==null&&(ie.weaponLevel=0);s(xA),(jA=wA.events)!=null&&jA.length&&(r(ie=>[...ie,...wA.events]),wA.events.some(ie=>ie.type==="roll")&&B(ie=>ie+1))},_A=wA=>{c(wA.trade),y.current=wA.trade},uA=wA=>{const xA=y.current,YA=!!xA&&xA.id===wA.tradeId,jA=wA.offererId??(YA?xA.offerer.playerId:void 0),ie=wA.recipientId??(YA?xA.recipient.playerId:void 0),he=jA===n,le=ie===n;wA.accepted?he&&g("Trade accepted","Your offer was accepted"):he?g("Trade declined","Your offer was declined"):le&&g("Trade declined","You declined the offer"),YA&&(c(null),y.current=null)},X=wA=>{},O=wA=>{h(wA),wA.status==="complete"&&window.setTimeout(()=>h(xA=>xA===wA?null:xA),2500)};console.log("[Zentara] Setting up socket listeners for room",e),A.on(Vi.STATE_UPDATE,CA),A.on(Vi.TRADE_PROPOSED,_A),A.on(Vi.TRADE_RESOLVED,uA),A.on(Vi.GAME_OVER,X),A.on(Vi.RAID_PROGRESS,O);const cA=wA=>{D(xA=>({...xA,[wA.playerId]:wA.piece}))};return A.on(Vi.PIECE_SELECTED,cA),()=>{console.log("[Zentara] Cleaning up socket listeners for room",e),A.off(Vi.STATE_UPDATE,CA),A.off(Vi.TRADE_PROPOSED,_A),A.off(Vi.TRADE_RESOLVED,uA),A.off(Vi.GAME_OVER,X),A.off(Vi.RAID_PROGRESS,O),A.off(Vi.PIECE_SELECTED,cA)}},[A,e,n,g]);const k=E.useCallback((CA,_A)=>{A!=null&&A.connected&&A.emit(CA,{roomId:e,eventId:Mv(),..._A})},[A,e]),N=E.useCallback(async(CA,_A)=>{if(!(A!=null&&A.connected))return console.warn("[Zentara] startMatch: socket not connected"),!1;console.log("[Zentara] startMatch: sending START_MATCH with",CA.length,"players");const uA=await hsA(A,Vi.START_MATCH,{roomId:e,players:CA,boardSize:_A,eventId:Mv()});return console.log("[Zentara] startMatch response:",uA!=null&&uA.ok?"OK":"FAILED"),!!(uA&&uA.ok)},[A,e]),G=E.useCallback(CA=>{A!=null&&A.connected&&A.emit(Vi.SELECT_PIECE,{roomId:e,piece:CA,eventId:Mv()})},[A,e]),M=E.useCallback(()=>k(Vi.ROLL),[k]),w=E.useCallback(CA=>k(Vi.BUY,{tileId:CA}),[k]),b=E.useCallback(()=>k(Vi.SKIP_BUY),[k]),_=E.useCallback(()=>k(Vi.PAY_RENT),[k]),K=E.useCallback(()=>k(Vi.HERO_CLASH_ROLL),[k]),J=E.useCallback(()=>k(Vi.PAY_TAX),[k]),q=E.useCallback(()=>k(Vi.RESOLVE_CARD),[k]),v=E.useCallback(()=>k(Vi.APPLY_TELEPORT),[k]),U=E.useCallback(()=>k(Vi.PAY_BAIL),[k]),x=E.useCallback(()=>k(Vi.END_TURN),[k]),T=E.useCallback(CA=>k(Vi.UPGRADE,{tileId:CA}),[k]),z=E.useCallback(CA=>k(Vi.MORTGAGE,{tileId:CA}),[k]),Z=E.useCallback(CA=>k(Vi.SELL,{tileId:CA}),[k]),eA=E.useCallback(CA=>k(Vi.SABOTAGE,{tileId:CA}),[k]),aA=E.useCallback(CA=>k(Vi.DEBT_SELL,{tileId:CA}),[k]),sA=E.useCallback(CA=>k(Vi.DEBT_LIQUIDATE_ARM,{tileId:CA}),[k]),pA=E.useCallback(()=>k(Vi.DEBT_RESOLVE),[k]),gA=E.useCallback(()=>{},[]),yA=E.useCallback(()=>{},[]),fA=E.useCallback((CA,_A,uA,X,O)=>{k(Vi.PROPOSE_TRADE,{recipientId:CA,offererPropertyIds:_A,offererCredits:uA,recipientPropertyIds:X,recipientCredits:O})},[k]),RA=E.useCallback(()=>{const CA=y.current;CA&&k(Vi.ACCEPT_TRADE,{tradeId:CA.id})},[k]),qA=E.useCallback(()=>{const CA=y.current;CA&&k(Vi.DECLINE_TRADE,{tradeId:CA.id})},[k]),W=E.useCallback(()=>k(Vi.UPGRADE_ARMOR,{}),[k]),$=E.useCallback(()=>k(Vi.UPGRADE_WEAPON,{}),[k]),L=E.useCallback(()=>k(Vi.LIQUIDATE_ARMOR,{}),[k]),H=E.useCallback(()=>k(Vi.LIQUIDATE_WEAPON,{}),[k]),P=E.useCallback(CA=>{k(Vi.RESOLVE_RAID,CA??{})},[k]),tA=E.useCallback(CA=>{k(Vi.RAID_PROGRESS,CA)},[k]),iA=E.useCallback(CA=>k(Vi.PLANT_SPY,{group:CA}),[k]),oA=E.useCallback(CA=>k(Vi.SPY_PUZZLE_RESULT,{success:CA}),[k]),IA=E.useCallback(CA=>k(Vi.SPY_SHOT_RESULT,{outcome:CA}),[k]);return E.useEffect(()=>{var _A,uA,X;typeof window>"u"||!window.__E2E__||(window.__zentaraTestState=o?{ts:Date.now(),roomId:e,meId:t??null,phase:((_A=o.currentTurn)==null?void 0:_A.phase)??null,currentPlayerId:((uA=o.players[o.currentPlayerIndex])==null?void 0:uA.id)??null,currentPlayerIndex:o.currentPlayerIndex,pendingEffect:((X=o.pendingEffect)==null?void 0:X.action)??null,finished:!!o.finished,winnerId:o.winnerId??null,players:o.players.map(O=>({id:O.id,name:O.displayName,credits:O.credits,depleted:O.depleted,tileIndex:O.tileIndex})),turnHistoryLen:0,eventsLen:a.length}:{ts:Date.now(),roomId:e,meId:t??null,phase:null,finished:!1,players:[]})},[o,a.length,e,t]),{gameState:o,events:a,pendingEffect:(o==null?void 0:o.pendingEffect)??null,pendingTrade:I,rollTrigger:l,raidActivity:Q,connected:d,takenPieces:S,piecesMap:m,selectPiece:G,startMatch:N,actions:{roll:M,buyProperty:w,payRent:_,heroClashRoll:K,payTax:J,resolveCard:q,goToJail:gA,payBailAction:U,endTurn:x,skipBuy:b,upgradeProperty:T,mortgageProperty:z,sellProperty:Z,sabotageProperty:eA,debtSell:aA,debtLiquidateArm:sA,debtResolve:pA,proposeTrade:fA,acceptTrade:RA,declineTrade:qA,saveGame:yA,applyTeleport:v,upgradeArmor:W,upgradeWeapon:$,liquidateArmor:L,liquidateWeapon:H,resolveRaid:P,reportRaidProgress:tA,plantSpy:iA,spyPuzzleResult:oA,spyShotResult:IA}}}const R0e=({roomId:e})=>{var x;const{user:A,meId:t}=tn(),i=qi(),[n]=uw(),{room:g,joinRoom:o,leaveRoom:s}=nI(),{gameState:a,events:r,pendingEffect:I,pendingTrade:c,rollTrigger:l,raidActivity:B,connected:Q,takenPieces:h,piecesMap:d,selectPiece:p,startMatch:y,actions:m}=N0e(e),[D,S]=E.useState(!1),[k,N]=E.useState(null),[G,M]=E.useState(()=>n.get("boardSize")??"standard"),w=E.useRef(null),{bestHeroForEmpire:b}=Cz(),_=E.useCallback(T=>{N(T),p(T)},[p]),K=E.useCallback(()=>{var T;(T=s==null?void 0:s(e))==null||T.catch(()=>{}),i("/zentara")},[s,e,i]);E.useEffect(()=>{!e||w.current===e||(w.current=e,o(e).catch(T=>console.warn("[Zentara] joinRoom failed",T)))},[e,o]);const J=ue.useMemo(()=>g!=null&&g.players?g.players.map(T=>({id:T.id||T.playerId||T.userId,name:T.displayName||T.name||T.username||"Player",avatarUrl:T.avatarUrl||void 0})):[],[g==null?void 0:g.players]),q=((x=g==null?void 0:g.players)==null?void 0:x[0])&&g.players[0].id===t,v=E.useCallback(async()=>{if(D||!q||J.length<2||!k)return;S(!0);const T=J.map(z=>{var eA;const Z=z.id===t?k:d[z.id]??void 0;return{...z,piece:Z,heroId:z.id===t&&Z?(eA=b(Z))==null?void 0:eA.heroId:void 0}});await y(T,G),S(!1)},[D,q,J,y,k,t,d,b,G]);if(!a)return k?C.jsxs("div",{className:"zentara-match-container zentara-match-container--waiting",children:[C.jsx("h2",{className:"zentara-match-header",children:"Waiting for players..."}),k&&C.jsxs("div",{style:{fontSize:13,color:zu[k]},className:"zentara-match-subtext",children:["Your empire: ",gB[k].name]}),C.jsxs("div",{className:"zentara-match-action-group",children:[C.jsxs("div",{style:{fontSize:14,opacity:.7},children:[J.length," / 2+ players joined"]}),q&&J.length>=2&&C.jsx("button",{onClick:v,disabled:D,className:"zentara-match-primary-btn zentara-match-primary-btn--compact",children:D?"Starting...":"Start Game"})]}),C.jsx("div",{className:"zentara-match-players-list",children:J.map(T=>C.jsxs("div",{className:"zentara-match-player-item",children:[T.name," ",T.id===t?"(you)":""]},T.id))}),C.jsx("button",{onClick:K,className:"zentara-match-back-btn",children:"Back"}),C.jsx(ypA,{roomId:e,gameMode:"zentara"}),q&&J.length>=2&&C.jsx(C.Fragment,{children:C.jsx("div",{className:"zentara-match-size-selector",children:["standard","full"].map(T=>C.jsx("button",{onClick:()=>M(T),className:`zentara-match-size-btn zentara-match-size-btn--compact ${G===T?"zentara-match-size-btn--active":""}`,children:T==="standard"?"Standard (20 tiles)":"Full (40 tiles)"},T))})}),!Q&&C.jsx("div",{className:"zentara-match-reconnect-notice",children:"Reconnecting..."})]}):C.jsx(kQA,{taken:h,onSelect:_,bestHeroForEmpire:b,onBack:K});const U=a.players.map(T=>({id:T.id,name:T.displayName}));return C.jsx(G4,{players:U,localPlayerId:t,savedState:a,onSaveAndExit:K,multiplayerActions:m,multiplayerEvents:r,multiplayerPendingEffect:I,multiplayerPendingTrade:c,multiplayerRollTrigger:l,multiplayerRaidActivity:B,roomId:e},e)},G0e=["Rival","Nemesis","Warden","Phantom","Tyrant","Specter","Vortex","Hydra","Onyx","Ravager","Cipher","Hex","Eclipse","Talon","Vanguard","Reaper","Wraith","Sable","Khaos","Drake"],bO=["crimson-dominion","silver-pact","azure-sovereignty","golden-imperium","emerald-collective","void-enclave"],b0e=({matchId:e})=>{const A=qi(),[t]=uw(),i=t.get("autoplay")==="1",n=t.get("qm")==="1",[g,o]=E.useState(null),[s,a]=E.useState(!1),[r,I]=E.useState(!1),[c,l]=E.useState(null),[B,Q]=E.useState("standard"),[h,d]=E.useState(!1),{bestHeroForEmpire:p}=Cz(),y=ue.useMemo(()=>[...bO.filter(G=>G!==c)].sort(()=>Math.random()-.5),[c]),m=ue.useMemo(()=>[...G0e].sort(()=>Math.random()-.5),[e]),D=ue.useMemo(()=>{if(!i)return null;const N=parseInt(t.get("bots")??"",10),G=Number.isFinite(N)?Math.max(2,Math.min(bO.length,N)):5,M=[...bO].sort(()=>Math.random()-.5).slice(0,G),w=["Vega","Orion","Lyra","Rigel","Nova","Cygnus"];return M.map((b,_)=>{const K=$1(b),J=K.length>0?K[Math.floor(Math.random()*K.length)]??K[0]:null;return{id:`auto-p${_+1}`,name:w[_]??`Bot ${_+1}`,piece:b,heroId:J==null?void 0:J.id,isBot:!0}})},[i,e,t]);if(E.useEffect(()=>{Xo().then(N=>{o(Math.max(1,Math.min(5,N.zentaraBotCount??ds.zentaraBotCount??1))),a(!!N.zentaraDisableRaid),I(!!N.zentaraDisableSpyStrike)}).catch(()=>o(ds.zentaraBotCount??1))},[]),i&&D)return C.jsx(G4,{players:D,localPlayerId:"__autoplay_observer__",onSaveAndExit:()=>A("/lobby"),boardSize:"standard",autoplay:!0,gameRules:{disableRaid:s,disableSpyStrike:!1}},e);if(g===null)return null;const S=(()=>{const N=dQA();return N&&N.matchId===e?N:null})();if(!S&&!c)return C.jsx(kQA,{onSelect:l,bestHeroForEmpire:p,onBack:()=>A("/zentara")});if(!S&&c&&!h)return C.jsxs("div",{className:"zentara-match-container zentara-match-container--board-size",children:[C.jsx("h2",{className:"zentara-match-header zentara-match-header--board-size",children:"Choose Board Size"}),["standard","full"].map(N=>C.jsx("button",{onClick:()=>Q(N),className:`zentara-match-size-btn ${B===N?"zentara-match-size-btn--active":""}`,children:N==="standard"?"Standard — 20 tiles":"Full — 40 tiles"},N)),C.jsx("button",{onClick:()=>d(!0),className:"zentara-match-primary-btn",children:"Start Game"}),C.jsx("button",{onClick:()=>l(null),className:"zentara-match-back-btn zentara-match-back-btn--minimal",children:"← Back"})]});const k=S?S.players.map(N=>({id:N.id,name:N.displayName})):(()=>{const N=p(c),G=(N==null?void 0:N.tier)??0;return[{id:"local-p1",name:"You",piece:c,heroId:N==null?void 0:N.heroId},...Array.from({length:g},(M,w)=>{const b=y[w],_=$1(b).filter(J=>J.tier<=G),K=_.length>0?_[Math.floor(Math.random()*_.length)]:null;return{id:`local-p${w+2}`,name:m[w]??`Bot ${w+1}`,piece:b,heroId:K==null?void 0:K.id,isBot:!0}})]})();return C.jsx(G4,{players:k,localPlayerId:"local-p1",savedState:S,onSaveAndExit:()=>A("/lobby"),boardSize:S?void 0:B,botChatEnabled:n,gameRules:{disableRaid:s,disableSpyStrike:r}},e)},XS=()=>{const{matchId:e,roomId:A}=Qw(),[t]=uw(),i=A||t.get("roomId");return i?C.jsx(R0e,{roomId:i}):C.jsx(b0e,{matchId:e})},U0e=E.lazy(()=>Qi(()=>import("./TurretPreview-tL_lePQ9.js"),__vite__mapDeps([14,1])));E.lazy(()=>Qi(()=>import("./ShipPackPreview-C1SY9CLc.js"),__vite__mapDeps([15,1,16])));function v0e(){const e=qi(),A=ks();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),CI()},[e]),E.useEffect(()=>{CI(A.pathname)},[A.pathname]),E.useEffect(()=>{try{const t=A.pathname||"",i=t==="/lobby",n=/^\/room\//.test(t)||/^\/poker\/room\//.test(t);(()=>{var s;try{return/^(capacitor:|ionic:)/i.test(((s=window.location)==null?void 0:s.protocol)||"")}catch{return!1}})()?(document.body.classList.add("is-native-app"),document.documentElement.classList.add("is-native-app")):(document.body.classList.remove("is-native-app"),document.documentElement.classList.remove("is-native-app")),document.body.classList.toggle("page-home-screen",i),document.body.classList.toggle("page-gameroom",n),(i||n)&&(document.body.classList.remove("profile-page-body"),document.body.classList.remove("messages-page-body"));const o=document.documentElement;if(i||n){o.style.setProperty("overflow","hidden","important"),document.body.style.setProperty("overflow","hidden","important"),o.style.setProperty("overscroll-behavior","none","important"),document.body.style.setProperty("overscroll-behavior","none","important"),o.style.setProperty("height","100svh","important"),document.body.style.setProperty("height","100svh","important");try{window.scrollTo({top:0,left:0,behavior:"instant"})}catch{}document.documentElement.scrollTop=0,document.body.scrollTop=0;const s=()=>{const a=document.getElementById("root");a&&(a.scrollTop=0,a.style.removeProperty("overflow"),a.style.removeProperty("overflow-y"));const r=document.querySelector(".home-fixed-root");r&&(r.scrollTop=0,r.style.removeProperty("overflow"),r.style.removeProperty("overflow-y"),r.style.removeProperty("height"),r.style.removeProperty("min-height"))};s(),requestAnimationFrame(()=>{s()})}else o.style.removeProperty("overflow"),document.body.style.removeProperty("overflow"),o.style.removeProperty("overscroll-behavior"),document.body.style.removeProperty("overscroll-behavior"),o.style.removeProperty("height"),document.body.style.removeProperty("height")}catch{}},[A.pathname]),C.jsxs(Uf,{children:[C.jsxs(fe,{element:C.jsx(Tf,{}),children:[C.jsx(fe,{path:"/verify",element:C.jsx(Zf,{})}),C.jsx(fe,{path:"/review-login",element:C.jsx(Wf,{})}),C.jsx(fe,{path:"/qa-login",element:C.jsx(Vf,{})}),C.jsx(fe,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(fe,{path:"/add-chips",element:C.jsx(zf,{})}),C.jsxs(fe,{element:C.jsx(vf,{}),children:[C.jsx(fe,{path:"/profile",element:C.jsx(Hf,{})}),C.jsx(fe,{path:"/player/:playerId",element:C.jsx(Of,{})}),C.jsx(fe,{path:"/messages",element:C.jsx(Pf,{})}),C.jsx(fe,{path:"/settings",element:C.jsx(jf,{})}),C.jsx(fe,{path:"/admin",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/lobby",element:C.jsx(xf,{})}),C.jsx(fe,{path:"/room/:roomId",element:C.jsx(VR,{})}),C.jsx(fe,{path:"/poker",element:C.jsx(JZ,{})}),C.jsx(fe,{path:"/poker/mock",element:C.jsx(LZ,{})}),C.jsx(fe,{path:"/poker/room/:roomId",element:C.jsx(_Z,{})}),C.jsx(fe,{path:"/zentara",element:C.jsx(Tg,{to:"/",replace:!0})}),C.jsx(fe,{path:"/zentara/match/:matchId",element:C.jsx(XS,{})}),C.jsx(fe,{path:"/zentara/room/:roomId",element:C.jsx(XS,{})})]}),C.jsx(fe,{path:"/disclaimer",element:C.jsx(Xf,{})}),C.jsx(fe,{path:"/support",element:C.jsx($f,{})}),C.jsx(fe,{path:"/privacy",element:C.jsx(Ay,{})}),C.jsx(fe,{path:"/terms",element:C.jsx(ey,{})}),C.jsx(fe,{path:"/button-sandbox",element:C.jsx(XR,{})}),C.jsx(fe,{path:"/how-to-play",element:C.jsx(vd,{})}),C.jsx(fe,{path:"/turret-preview",element:C.jsx(E.Suspense,{fallback:null,children:C.jsx(U0e,{})})}),C.jsx(fe,{path:"/ship-pack-preview",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"*",element:C.jsx(Tg,{to:"/lobby",replace:!0})})]})}function K0e(){const e=qi(),A=ks();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),CI()},[e]),E.useEffect(()=>{CI(A.pathname)},[A.pathname]),E.useEffect(()=>{try{const t=A.pathname||"",i=t==="/lobby",n=/^\/room\//.test(t);(()=>{var s;try{return/^(capacitor:|ionic:)/i.test(((s=window.location)==null?void 0:s.protocol)||"")}catch{return!1}})()?(document.body.classList.add("is-native-app"),document.documentElement.classList.add("is-native-app")):(document.body.classList.remove("is-native-app"),document.documentElement.classList.remove("is-native-app")),document.body.classList.toggle("page-home-screen",i),document.body.classList.toggle("page-gameroom",n);const o=document.documentElement;if(i||n){o.style.setProperty("overflow","hidden","important"),document.body.style.setProperty("overflow","hidden","important"),o.style.setProperty("overscroll-behavior","none","important"),document.body.style.setProperty("overscroll-behavior","none","important"),o.style.setProperty("height","100svh","important"),document.body.style.setProperty("height","100svh","important");try{window.scrollTo({top:0,left:0,behavior:"instant"})}catch{}}else o.style.removeProperty("overflow"),document.body.style.removeProperty("overflow"),o.style.removeProperty("overscroll-behavior"),document.body.style.removeProperty("overscroll-behavior"),o.style.removeProperty("height"),document.body.style.removeProperty("height")}catch{}},[A.pathname]),C.jsxs(Uf,{children:[C.jsxs(fe,{element:C.jsx(Tf,{}),children:[C.jsx(fe,{path:"/verify",element:C.jsx(Zf,{})}),C.jsx(fe,{path:"/review-login",element:C.jsx(Wf,{})}),C.jsx(fe,{path:"/qa-login",element:C.jsx(Vf,{})}),C.jsx(fe,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(fe,{path:"/add-chips",element:C.jsx(zf,{})}),C.jsxs(fe,{element:C.jsx(vf,{}),children:[C.jsx(fe,{path:"/profile",element:C.jsx(Hf,{})}),C.jsx(fe,{path:"/player/:playerId",element:C.jsx(Of,{})}),C.jsx(fe,{path:"/messages",element:C.jsx(Pf,{})}),C.jsx(fe,{path:"/settings",element:C.jsx(jf,{})}),C.jsx(fe,{path:"/admin",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/lobby",element:C.jsx(xf,{})}),C.jsx(fe,{path:"/room/:roomId",element:C.jsx(VR,{})})]}),C.jsx(fe,{path:"/disclaimer",element:C.jsx(Xf,{})}),C.jsx(fe,{path:"/support",element:C.jsx($f,{})}),C.jsx(fe,{path:"/privacy",element:C.jsx(Ay,{})}),C.jsx(fe,{path:"/terms",element:C.jsx(ey,{})}),C.jsx(fe,{path:"/button-sandbox",element:C.jsx(XR,{})}),C.jsx(fe,{path:"/how-to-play",element:C.jsx(vd,{})}),C.jsx(fe,{path:"*",element:C.jsx(Tg,{to:"/lobby",replace:!0})})]})}function F0e(){const e=qi(),A=ks();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),CI()},[e]),E.useEffect(()=>{CI(A.pathname)},[A.pathname]),E.useEffect(()=>{try{const t=A.pathname||"",i=t==="/lobby",n=/^\/room\//.test(t);(()=>{var s;try{return/^(capacitor:|ionic:)/i.test(((s=window.location)==null?void 0:s.protocol)||"")}catch{return!1}})()?(document.body.classList.add("is-native-app"),document.documentElement.classList.add("is-native-app")):(document.body.classList.remove("is-native-app"),document.documentElement.classList.remove("is-native-app")),document.body.classList.toggle("page-home-screen",i),document.body.classList.toggle("page-gameroom",n);const o=document.documentElement;if(i||n){o.style.setProperty("overflow","hidden","important"),document.body.style.setProperty("overflow","hidden","important"),o.style.setProperty("overscroll-behavior","none","important"),document.body.style.setProperty("overscroll-behavior","none","important"),o.style.setProperty("height","100svh","important"),document.body.style.setProperty("height","100svh","important");try{window.scrollTo({top:0,left:0,behavior:"instant"})}catch{}}else o.style.removeProperty("overflow"),document.body.style.removeProperty("overflow"),o.style.removeProperty("overscroll-behavior"),document.body.style.removeProperty("overscroll-behavior"),o.style.removeProperty("height"),document.body.style.removeProperty("height")}catch{}},[A.pathname]),C.jsxs(Uf,{children:[C.jsxs(fe,{element:C.jsx(Tf,{}),children:[C.jsx(fe,{path:"/verify",element:C.jsx(Zf,{})}),C.jsx(fe,{path:"/review-login",element:C.jsx(Wf,{})}),C.jsx(fe,{path:"/qa-login",element:C.jsx(Vf,{})}),C.jsx(fe,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(fe,{path:"/add-chips",element:C.jsx(zf,{})}),C.jsxs(fe,{element:C.jsx(vf,{}),children:[C.jsx(fe,{path:"/profile",element:C.jsx(Hf,{})}),C.jsx(fe,{path:"/player/:playerId",element:C.jsx(Of,{})}),C.jsx(fe,{path:"/messages",element:C.jsx(Pf,{})}),C.jsx(fe,{path:"/settings",element:C.jsx(jf,{})}),C.jsx(fe,{path:"/admin",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/lobby",element:C.jsx(xf,{})}),C.jsx(fe,{path:"/room/:roomId",element:C.jsx(VR,{})})]}),C.jsx(fe,{path:"/disclaimer",element:C.jsx(Xf,{})}),C.jsx(fe,{path:"/support",element:C.jsx($f,{})}),C.jsx(fe,{path:"/privacy",element:C.jsx(Ay,{})}),C.jsx(fe,{path:"/terms",element:C.jsx(ey,{})}),C.jsx(fe,{path:"/button-sandbox",element:C.jsx(XR,{})}),C.jsx(fe,{path:"/how-to-play",element:C.jsx(vd,{})}),C.jsx(fe,{path:"*",element:C.jsx(Tg,{to:"/lobby",replace:!0})})]})}function _0e(){const e=qi(),A=ks();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),CI()},[e]),E.useEffect(()=>{CI(A.pathname)},[A.pathname]),E.useEffect(()=>{try{const t=A.pathname||"",i=t==="/lobby",n=/^\/poker\//.test(t);(()=>{var s;try{return/^(capacitor:|ionic:)/i.test(((s=window.location)==null?void 0:s.protocol)||"")}catch{return!1}})()?(document.body.classList.add("is-native-app"),document.documentElement.classList.add("is-native-app")):(document.body.classList.remove("is-native-app"),document.documentElement.classList.remove("is-native-app")),document.body.classList.toggle("page-home-screen",i),document.body.classList.toggle("page-gameroom",n);const o=document.documentElement;if(i||n){o.style.setProperty("overflow","hidden","important"),document.body.style.setProperty("overflow","hidden","important"),o.style.setProperty("overscroll-behavior","none","important"),document.body.style.setProperty("overscroll-behavior","none","important"),o.style.setProperty("height","100svh","important"),document.body.style.setProperty("height","100svh","important");try{window.scrollTo({top:0,left:0,behavior:"instant"})}catch{}}else o.style.removeProperty("overflow"),document.body.style.removeProperty("overflow"),o.style.removeProperty("overscroll-behavior"),document.body.style.removeProperty("overscroll-behavior"),o.style.removeProperty("height"),document.body.style.removeProperty("height")}catch{}},[A.pathname]),C.jsxs(Uf,{children:[C.jsxs(fe,{element:C.jsx(Tf,{}),children:[C.jsx(fe,{path:"/verify",element:C.jsx(Zf,{})}),C.jsx(fe,{path:"/review-login",element:C.jsx(Wf,{})}),C.jsx(fe,{path:"/qa-login",element:C.jsx(Vf,{})}),C.jsx(fe,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(fe,{path:"/add-chips",element:C.jsx(zf,{})}),C.jsxs(fe,{element:C.jsx(vf,{}),children:[C.jsx(fe,{path:"/profile",element:C.jsx(Hf,{})}),C.jsx(fe,{path:"/player/:playerId",element:C.jsx(Of,{})}),C.jsx(fe,{path:"/messages",element:C.jsx(Pf,{})}),C.jsx(fe,{path:"/settings",element:C.jsx(jf,{})}),C.jsx(fe,{path:"/admin",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/lobby",element:C.jsx(xf,{})}),C.jsx(fe,{path:"/poker",element:C.jsx(JZ,{})}),C.jsx(fe,{path:"/poker/mock",element:C.jsx(LZ,{})})]}),C.jsx(fe,{path:"/disclaimer",element:C.jsx(Xf,{})}),C.jsx(fe,{path:"/support",element:C.jsx($f,{})}),C.jsx(fe,{path:"/privacy",element:C.jsx(Ay,{})}),C.jsx(fe,{path:"/terms",element:C.jsx(ey,{})}),C.jsx(fe,{path:"/button-sandbox",element:C.jsx(XR,{})}),C.jsx(fe,{path:"/how-to-play",element:C.jsx(vd,{})}),C.jsx(fe,{path:"/poker/room/:roomId",element:C.jsx(_Z,{})}),C.jsx(fe,{path:"*",element:C.jsx(Tg,{to:"/poker",replace:!0})})]})}const b4=Wde(e=>({user:null,token:null,roomId:null,seed:null,startAt:null,endAt:null,driftMs:0,gameMode:"wordsearch",letters:void 0,questions:void 0,set:A=>e(A),setSession:A=>e(t=>({...t,roomId:A.roomId??t.roomId,seed:A.seed??t.seed,startAt:A.startAt??t.startAt,endAt:A.endAt??t.endAt,driftMs:A.driftMs??t.driftMs,gameMode:A.gameMode??t.gameMode,letters:A.letters??t.letters,questions:A.questions??t.questions}))}));function TmA({letters:e,onSubmit:A,disabled:t,cellSize:i=64,onTap:n,feedback:g,shakeKey:o,botTrail:s}){var q;const a=e.length,r=((q=e[0])==null?void 0:q.length)??0,[I,c]=E.useState([]),l=E.useRef(!1),B=E.useRef(null),[Q,h]=E.useState(-1),d=E.useRef(s);d.current=s,E.useEffect(()=>{if(!s||!s.path||s.path.length===0){h(-1);return}h(0);const v=Math.max(220,Math.min(320,Math.floor(2e3/s.path.length))),U=[],x=s.mine===!0;x&&Vl({volume:.6});for(let T=1;T<s.path.length;T++)U.push(window.setTimeout(()=>{h(T),x&&Vl({volume:.6})},T*v));return U.push(window.setTimeout(()=>h(-1),s.path.length*v+900)),()=>{U.forEach(T=>window.clearTimeout(T))}},[s==null?void 0:s.nonce]);const p=E.useCallback(v=>!s||Q<0?-1:s.path.slice(0,Q+1).findIndex(x=>x.r===v.r&&x.c===v.c),[s,Q]),y=(v,U)=>{const x=Math.abs(v.r-U.r),T=Math.abs(v.c-U.c);return x<=1&&T<=1&&!(x===0&&T===0)},m=v=>{if(v.length<2)return!0;for(let U=1;U<v.length;U++)if(!y(v[U-1],v[U]))return!1;return!0},D=E.useCallback(v=>I.findIndex(U=>U.r===v.r&&U.c===v.c),[I]),S=()=>c([]),k=(v,U)=>{const x=B.current;if(!x)return null;const T=x.getBoundingClientRect(),z=T.width/r,Z=T.height/a,eA=(v-T.left)/z,aA=(U-T.top)/Z,sA=Math.floor(eA),pA=Math.floor(aA);if(pA<0||pA>=a||sA<0||sA>=r)return null;if(l.current&&I.length>0){const gA=Math.abs(eA-sA-.5),yA=Math.abs(aA-pA-.5);if(gA+yA>.52)return null}return{r:pA,c:sA}},N=v=>{if(t)return;if(I.length===0){c([v]),Vl({volume:.3}),ti("Light"),n==null||n(v);return}const U=I[I.length-1];if(!U||U.r===v.r&&U.c===v.c)return;const x=D(v);if(x>=0){x===I.length-2&&(c(T=>T.slice(0,-1)),ti("Light"));return}y(U,v)?(c(T=>[...T,v]),Vl({volume:.3}),ti("Light"),n==null||n(v)):(c(T=>{const z=[...T];let Z=z[z.length-1];const eA=a+r;for(let aA=0;aA<eA&&!(Z.r===v.r&&Z.c===v.c);aA++){const sA=Math.sign(v.r-Z.r),pA=Math.sign(v.c-Z.c),gA={r:Z.r+sA,c:Z.c+pA};if(z.some(yA=>yA.r===gA.r&&yA.c===gA.c))break;z.push(gA),Z=gA}return z}),Vl({volume:.3}),ti("Light"),n==null||n(v))},G=v=>{l.current=!0;const U=k(v.clientX,v.clientY);U&&N(U)},M=v=>{if(!l.current)return;const U=k(v.clientX,v.clientY);U&&N(U)},w=()=>{l.current&&(l.current=!1,I.length>=3&&m(I)&&(ti("Medium"),A(I)),S())},b=(r-1)*3,_=(a-1)*3,K=`min(calc((100vw - 48px - ${b}px) / ${r}), calc((100vh - 180px - ${_}px) / ${a}), calc((100dvh - 180px - ${_}px) / ${a}), ${i}px)`,J=E.useMemo(()=>({gridTemplateColumns:`repeat(${r}, ${K})`,gridTemplateRows:`repeat(${a}, ${K})`,touchAction:"none"}),[r,a,K]);return C.jsxs("div",{className:["skillsGridWrap",o?"skillsGridWrap--shake":""].join(" "),children:[C.jsx("div",{ref:B,onPointerDown:G,onPointerMove:M,onPointerUp:w,onPointerCancel:()=>l.current=!1,style:J,className:"skillsGrid",children:e.map((v,U)=>v.map((x,T)=>{const z=D({r:U,c:T}),Z=z>=0,eA=p({r:U,c:T}),aA=eA>=0;return C.jsxs("div",{className:["skillsCell",Z?"skillsCell--selected":"skillsCell--idle",aA&&!Z?s!=null&&s.mine?"skillsCell--meTrail":"skillsCell--botTrail":"",t?"skillsCell--disabled":""].join(" "),style:{width:K,height:K},children:[x,Z&&C.jsx("span",{className:"skillsCellIndex",children:z+1}),aA&&!Z&&C.jsx("span",{className:"skillsCellIndex skillsCellIndex--bot",children:eA+1})]},`${U}-${T}`)}))}),g&&C.jsxs("span",{className:["skillsPointsBubble",g.points>=25?"skillsPointsBubble--big":""].join(" "),style:{left:`${(g.col+.5)/r*100}%`,top:`${(g.row+.5)/a*100}%`},children:["+",g.points]},g.nonce)]},o?`wrap-${o}`:"wrap")}function J0e({letters:e,foundWords:A,onSubmit:t,disabled:i,myScore:n=0}){const[g,o]=E.useState(""),[s,a]=E.useState([]),[r,I]=E.useState(null),[c,l]=E.useState(!1);E.useRef(null);const B=E.useMemo(()=>{const p=new Map;for(const y of e)p.set(y,(p.get(y)||0)+1);return p},[e]);E.useCallback(p=>{const y=new Map(B);for(const m of s){const D=e[m];y.set(D,(y.get(D)||0)-1)}for(const m of p.toUpperCase()){const D=y.get(m)||0;if(D<=0)return!1;y.set(m,D-1)}return!0},[B,s,e]);const Q=p=>{if(i||c)return;if(s.includes(p)){const m=s.indexOf(p);a(s.slice(0,m)),o(D=>D.slice(0,m))}else a([...s,p]),o(m=>m+e[p]);I(null)},h=()=>{a([]),o(""),I(null)},d=async()=>{if(i||c||g.length<3)return;const p=g.toUpperCase();if(A.includes(p)){I("Already found!");return}l(!0),I(null),t(p),h(),l(!1)};return E.useEffect(()=>{const p=y=>{if(i||c)return;if(y.key==="Enter"){d();return}if(y.key==="Backspace"){s.length>0&&(a(D=>D.slice(0,-1)),o(D=>D.slice(0,-1)));return}if(y.key==="Escape"){h();return}const m=y.key.toUpperCase();if(/^[A-Z]$/.test(m)){const D=e.findIndex((S,k)=>S===m&&!s.includes(k));D!==-1&&(a(S=>[...S,D]),o(S=>S+m),I(null))}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[i,c,e,s]),C.jsxs("div",{className:"anagrams-container",children:[C.jsxs("div",{className:"anagrams-score",children:["Score: ",C.jsx("strong",{children:n})]}),C.jsx("div",{className:"anagrams-letters",children:e.map((p,y)=>C.jsx("button",{className:`anagrams-letter ${s.includes(y)?"selected":""}`,onClick:()=>Q(y),disabled:i||c,children:p},y))}),C.jsxs("div",{className:"anagrams-input-area",children:[C.jsx("div",{className:"anagrams-current-word",children:g||C.jsx("span",{className:"placeholder",children:"Tap letters to form a word"})}),r&&C.jsx("div",{className:"anagrams-error",children:r})]}),C.jsxs("div",{className:"anagrams-actions",children:[C.jsx("button",{className:"anagrams-btn clear",onClick:h,disabled:i||c||g.length===0,children:"Clear"}),C.jsx("button",{className:"anagrams-btn submit",onClick:d,disabled:i||c||g.length<3,children:c?"...":"Submit"})]}),A.length>0&&C.jsxs("div",{className:"anagrams-found-words",children:[C.jsxs("div",{className:"found-label",children:["Your words (",A.length,"):"]}),C.jsx("div",{className:"found-list",children:A.map((p,y)=>C.jsx("span",{className:"found-word",children:p},y))})]})]})}function L0e({questions:e,currentQuestionIndex:A,onAnswer:t,myAnswers:i={},disabled:n,myScore:g=0}){const[o,s]=E.useState(null),[a,r]=E.useState(!1),[I,c]=E.useState(!1),[l,B]=E.useState(null),Q=e[A],h=i[A]!==void 0&&i[A].isCorrect!==void 0,d=i[A];E.useEffect(()=>{s(null),c(!1),B(null),r(!1)},[A]);const p=async D=>{n||a||h||(s(D),r(!0),t(A,D))};E.useEffect(()=>{const D=i[A];D&&D.isCorrect!==void 0&&(B({isCorrect:D.isCorrect,correctIndex:D.correctIndex??-1}),c(!0),r(!1))},[i,A]);const y=D=>{const S=["trivia-answer"];if(h||I){const k=(d==null?void 0:d.correctIndex)??(l==null?void 0:l.correctIndex),N=(d==null?void 0:d.answer)??o;D===k?S.push("correct"):D===N&&D!==k&&S.push("incorrect")}else o===D&&S.push("selected");return S.join(" ")},m={easy:"#4ade80",medium:"#fbbf24",hard:"#f87171"};return Q?C.jsxs("div",{className:"trivia-container",children:[C.jsxs("div",{className:"trivia-score",children:["Score: ",C.jsx("strong",{children:g})]}),C.jsxs("div",{className:"trivia-progress",children:[C.jsxs("span",{className:"progress-text",children:["Question ",A+1," of ",e.length]}),C.jsx("div",{className:"progress-bar",children:C.jsx("div",{className:"progress-fill",style:{width:`${(A+1)/e.length*100}%`}})})]}),C.jsxs("div",{className:"trivia-meta",children:[C.jsx("span",{className:"trivia-category",children:Q.category}),C.jsx("span",{className:"trivia-difficulty",style:{color:m[Q.difficulty]},children:Q.difficulty.toUpperCase()})]}),C.jsx("div",{className:"trivia-question",children:Q.question}),C.jsx("div",{className:"trivia-answers",children:Q.answers.map((D,S)=>C.jsxs("button",{className:y(S),onClick:()=>p(S),disabled:n||a||h,children:[C.jsx("span",{className:"answer-letter",children:String.fromCharCode(65+S)}),C.jsx("span",{className:"answer-text",children:D}),(h||I)&&C.jsxs("span",{className:"answer-indicator",children:[S===((d==null?void 0:d.correctIndex)??(l==null?void 0:l.correctIndex))&&"✓",S===((d==null?void 0:d.answer)??o)&&S!==((d==null?void 0:d.correctIndex)??(l==null?void 0:l.correctIndex))&&"✗"]})]},S))}),(I||h)&&C.jsx("div",{className:`trivia-feedback ${(d==null?void 0:d.isCorrect)??(l==null?void 0:l.isCorrect)?"correct":"incorrect"}`,children:(d==null?void 0:d.isCorrect)??(l==null?void 0:l.isCorrect)?"✓ Correct!":"✗ Wrong answer"}),C.jsx("style",{children:fsA})]}):C.jsxs("div",{className:"trivia-container",children:[C.jsxs("div",{className:"trivia-complete",children:[C.jsx("h2",{children:"🎉 Quiz Complete!"}),C.jsx("p",{children:"Waiting for final results..."})]}),C.jsx("style",{children:fsA})]})}const fsA=`
    .trivia-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12px;
        padding: 12px;
        max-width: 500px;
        margin: 0 auto;
        overflow-y: auto;
        max-height: calc(100vh - 180px);
        -webkit-overflow-scrolling: touch;
    }
    .trivia-score {
        font-size: 16px;
        color: #ffd700;
        text-align: center;
        width: 100%;
    }
    .trivia-score strong {
        font-size: 20px;
    }
    .trivia-progress {
        width: 100%;
        text-align: center;
    }
    .progress-text {
        font-size: 12px;
        color: #888;
        margin-bottom: 6px;
        display: block;
    }
    .progress-bar {
        height: 4px;
        background: #2a2a4a;
        border-radius: 2px;
        overflow: hidden;
    }
    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #4a7c59, #5d9b70);
        transition: width 0.3s ease;
    }
    .trivia-meta {
        display: flex;
        justify-content: space-between;
        width: 100%;
        font-size: 12px;
    }
    .trivia-category {
        color: #888;
        text-transform: uppercase;
        letter-spacing: 1px;
    }
    .trivia-difficulty {
        font-weight: bold;
    }
    .trivia-question {
        font-size: 18px;
        font-weight: 600;
        color: #fff;
        text-align: center;
        line-height: 1.3;
        padding: 12px;
        background: rgba(255,255,255,0.05);
        border-radius: 12px;
        width: 100%;
    }
    .trivia-answers {
        width: 100%;
        display: flex;
        flex-direction: column;
        gap: 8px;
    }
    .trivia-answer {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 12px 14px;
        background: linear-gradient(145deg, #2a2a4a, #1a1a2e);
        border: 2px solid #4a4a6a;
        border-radius: 10px;
        color: #fff;
        font-size: 15px;
        cursor: pointer;
        transition: all 0.2s ease;
        text-align: left;
    }
    .trivia-answer:hover:not(:disabled) {
        border-color: #6a6a8a;
        transform: translateX(4px);
    }
    .trivia-answer.selected {
        border-color: #5d9b70;
        background: rgba(74, 124, 89, 0.2);
    }
    .trivia-answer.correct {
        border-color: #4ade80;
        background: rgba(74, 222, 128, 0.2);
    }
    .trivia-answer.incorrect {
        border-color: #f87171;
        background: rgba(248, 113, 113, 0.2);
    }
    .trivia-answer:disabled {
        cursor: not-allowed;
        opacity: 0.7;
    }
    .answer-letter {
        width: 28px;
        height: 28px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(255,255,255,0.1);
        border-radius: 6px;
        font-weight: bold;
        font-size: 14px;
        flex-shrink: 0;
    }
    .answer-text {
        flex: 1;
    }
    .answer-indicator {
        font-size: 18px;
        font-weight: bold;
        flex-shrink: 0;
    }
    .trivia-answer.correct .answer-indicator {
        color: #4ade80;
    }
    .trivia-answer.incorrect .answer-indicator {
        color: #f87171;
    }
    .trivia-feedback {
        font-size: 18px;
        font-weight: bold;
        padding: 12px 24px;
        border-radius: 8px;
        animation: fadeIn 0.3s ease;
    }
    .trivia-feedback.correct {
        color: #4ade80;
        background: rgba(74, 222, 128, 0.1);
    }
    .trivia-feedback.incorrect {
        color: #f87171;
        background: rgba(248, 113, 113, 0.1);
    }
    .trivia-complete {
        text-align: center;
        padding: 40px 20px;
    }
    .trivia-complete h2 {
        font-size: 24px;
        margin-bottom: 8px;
    }
    .trivia-complete p {
        color: #888;
    }
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }
`,x0e={wordsearch:[{title:"Swipe to Form Words",description:"Drag your finger across adjacent letters to create words. Each letter can only be used once per word.",icon:"👆"},{title:"Minimum 3 Letters",description:"Words must be at least 3 letters long. Longer words score more points!",icon:"📝"},{title:"Race the Clock",description:"Find as many words as possible before time runs out. Beat the bot to win!",icon:"⏱️"}],anagrams:[{title:"Unscramble Letters",description:"You'll be given a set of jumbled letters. Form valid words using those letters.",icon:"🔤"},{title:"Type or Tap",description:"Type your words and press Enter to submit. Each valid word earns points.",icon:"⌨️"},{title:"Longer = Better",description:"Longer words score more points. Try to find the longest words possible!",icon:"🏆"}],trivia:[{title:"Answer Questions",description:"You'll be shown multiple choice questions. Select the correct answer.",icon:"❓"},{title:"Speed Matters",description:"Answer quickly! Faster correct answers earn bonus points.",icon:"⚡"},{title:"Stay Sharp",description:"Questions span various topics. Test your knowledge and beat your opponent!",icon:"🧠"}]},T0e=[{title:"Entry Fee",description:"Choose your entry fee before starting. Win double your entry (minus 10% house fee)!",icon:"💰"},{title:"Pick Your Duration",description:"Select 30, 60, or 90 second rounds. Longer rounds = more chances to score.",icon:"⏰"}];function q0e({open:e,onClose:A,gameMode:t="wordsearch"}){const[i,n]=E.useState(0),g=[...x0e[t],...T0e],o=g.length,s=E.useCallback(()=>{Ia.set({key:`skillsOnboarding_${t}`,value:"1"}),n(0),A()},[A,t]),a=E.useCallback(()=>{i<o-1?n(B=>B+1):s()},[i,o,s]),r=E.useCallback(()=>{i>0&&n(B=>B-1)},[i]);if(E.useEffect(()=>{e&&n(0)},[e]),E.useEffect(()=>{if(!e)return;const B=Q=>{Q.key==="Escape"&&s(),(Q.key==="ArrowRight"||Q.key==="Enter")&&a(),Q.key==="ArrowLeft"&&r()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[e,s,a,r]),E.useEffect(()=>{if(e)try{(()=>{var Q,h,d;return!!(window.__E2E===!0||(h=(Q=window.location)==null?void 0:Q.search)!=null&&h.includes("e2e=1")||((d=window.sessionStorage)==null?void 0:d.getItem("e2e"))==="1")})()&&(Ia.set({key:`skillsOnboarding_${t}`,value:"1"}),setTimeout(()=>A(),0))}catch{}},[e,A,t]),!e)return null;const I=g[i],c=i===o-1,l=t==="wordsearch"?"Word Search":t==="anagrams"?"Anagrams":"Trivia";return C.jsxs("div",{className:"skills-onb-modal",role:"dialog","aria-modal":"true","aria-label":`How to play ${l}`,children:[C.jsx("div",{className:"skills-onb-backdrop",onClick:s}),C.jsxs("div",{className:"skills-onb-card",onClick:B=>B.stopPropagation(),children:[C.jsx("button",{className:"skills-onb-close",onClick:s,"aria-label":"Close",children:C.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:C.jsx("path",{d:"M18 6L6 18M6 6l12 12",strokeLinecap:"round",strokeLinejoin:"round"})})}),C.jsxs("header",{className:"skills-onb-header",children:[C.jsx("span",{className:"skills-onb-badge",children:l}),C.jsx("h2",{className:"skills-onb-title",children:"How to Play"})]}),C.jsxs("div",{className:"skills-onb-content",children:[C.jsx("div",{className:"skills-onb-icon","aria-hidden":"true",children:I.icon}),C.jsx("h3",{className:"skills-onb-step-title",children:I.title}),C.jsx("p",{className:"skills-onb-step-desc",children:I.description})]}),C.jsx("div",{className:"skills-onb-dots","aria-label":`Step ${i+1} of ${o}`,children:g.map((B,Q)=>C.jsx("button",{className:`skills-onb-dot ${Q===i?"active":""}`,onClick:()=>n(Q),"aria-label":`Go to step ${Q+1}`},Q))}),C.jsxs("div",{className:"skills-onb-actions",children:[i>0&&C.jsx("button",{className:"skills-onb-btn skills-onb-btn--ghost",onClick:r,children:"Back"}),C.jsx("button",{className:"skills-onb-btn skills-onb-btn--primary",onClick:a,children:c?"Let's Play!":"Next"})]})]})]})}function Y0e(e){const[A,t]=E.useState(!1),[i,n]=E.useState(!1);E.useEffect(()=>{(async()=>{try{const{value:o}=await Ia.get({key:`skillsOnboarding_${e}`});t(o!=="1")}catch{t(!0)}n(!0)})()},[e]);const g=E.useCallback(()=>{t(!1)},[]);return{showOnboarding:i&&A,closeOnboarding:g}}const H0e=[50,100,250,500],O0e=[30,60,90];function ysA(e,A=8,t=8){let i=2166136261;for(const s of e)i=(i^s.charCodeAt(0))*16777619;const n=()=>((i=Math.imul(i^i>>>13,1274126177))>>>0)/2**32,g="EEEEAAAAIIONNRRTTLLSSUU DD GBCMP FHVWY KJX QZ".replace(/\s/g,""),o=()=>g[Math.floor(n()*g.length)]||"E";return Array.from({length:A},()=>Array.from({length:t},()=>o()))}const qmA=["Toy Box","Cowboys","Surfers","Speed Demons","Beach Club","Rookies","Wave Riders","Regulars","High Rollers"],gE=5,DsA=qmA.length;function YmA({level:e,levelName:A,winStreak:t,variant:i="expanded",previousWinStreak:n}){const g=Math.max(1,Math.min(DsA,Math.floor(e||1))),o=g>=DsA,s=A??qmA[g-1],a=Math.max(0,t)%gE,r=t>0&&a===0?gE:a,I=o?100:r/gE*100,[c,l]=E.useState(()=>{if(n===void 0)return I;const Q=Math.max(0,n)%gE,h=n>0&&Q===0?gE:Q;return o?100:h/gE*100}),B=E.useRef(!0);return E.useEffect(()=>{if(B.current&&n!==void 0){B.current=!1;const Q=requestAnimationFrame(()=>l(I));return()=>cancelAnimationFrame(Q)}l(I)},[I,n]),C.jsxs("div",{className:`skillsLevelBadge skillsLevelBadge--${i}`,children:[C.jsxs("div",{className:"skillsLevelBadge__row",children:[C.jsxs("div",{className:"skillsLevelBadge__chip",children:[C.jsx("span",{className:"skillsLevelBadge__chipLv",children:"LV"}),C.jsx("span",{className:"skillsLevelBadge__chipNum",children:g})]}),C.jsxs("div",{className:"skillsLevelBadge__nameCol",children:[C.jsx("span",{className:"skillsLevelBadge__name",children:s}),o?C.jsx("span",{className:"skillsLevelBadge__sub skillsLevelBadge__sub--max",children:"⭐ Max league"}):C.jsxs("span",{className:"skillsLevelBadge__sub",children:[r," / ",gE," wins to next league"]})]})]}),C.jsx("div",{className:`skillsLevelBadge__bar${o?" skillsLevelBadge__bar--max":""}`,role:"progressbar","aria-valuemin":0,"aria-valuemax":gE,"aria-valuenow":o?gE:r,"aria-label":`Level ${g} ${s} progress`,children:C.jsx("div",{className:"skillsLevelBadge__barFill",style:{width:`${c}%`}})})]})}function P0e({challenge:e}){const A=Math.min(100,Math.round(e.progress/e.goal*100));return C.jsxs("div",{className:["skillsDailyChallenge",e.completed?"skillsDailyChallenge--done":""].join(" "),children:[C.jsxs("div",{className:"skillsDailyChallenge__head",children:[C.jsx("span",{className:"skillsDailyChallenge__tag",children:"Daily Challenge"}),e.completed?C.jsx("span",{className:"skillsDailyChallenge__check",children:"✓ Done!"}):C.jsxs("span",{className:"skillsDailyChallenge__progress",children:[e.progress,"/",e.goal]})]}),C.jsx("div",{className:"skillsDailyChallenge__label",children:e.label}),C.jsx("div",{className:"skillsDailyChallenge__bar",children:C.jsx("div",{className:"skillsDailyChallenge__barFill",style:{width:`${A}%`}})})]})}const j0e=3e3;function z0e({isMultiplayer:e,activeGameMode:A,selectedStake:t,setSelectedStake:i,selectedDuration:n,setSelectedDuration:g,myBalance:o,stakeError:s,hasStarted:a,onStart:r,onShowHelp:I,isAuthenticated:c=!0,onLogin:l,isAdEnabled:B=!1,roomStake:Q,roomDuration:h,spLevel:d,spLevelName:p,winStreak:y=0,dailyChallenge:m}){const D=B&&e,[S,k]=E.useState(D);E.useEffect(()=>{if(!D){k(!1);return}const G=setTimeout(()=>k(!1),j0e);return()=>clearTimeout(G)},[D]);const N=async G=>{g(G);try{const{Preferences:M}=await Qi(async()=>{const{Preferences:w}=await Promise.resolve().then(()=>Oc);return{Preferences:w}},void 0);await M.set({key:"selectedSkillsDuration",value:String(G)})}catch{}};return C.jsxs("div",{className:"skillsStartContainer",children:[C.jsxs("div",{className:"skillsStartScrollable",children:[C.jsx("h2",{className:"skillsStartTitle",children:e?"Skills Lounge":A==="anagrams"?"Anagram Challenge":A==="trivia"?"Trivia Challenge":"Word Search Challenge"}),C.jsx("p",{className:"skillsStartDesc",children:e?"Click Ready when ready to play!":"Choose your entry fee!"}),c&&typeof d=="number"&&C.jsx(YmA,{level:d,levelName:p,winStreak:y,variant:"expanded"}),m&&C.jsx(P0e,{challenge:m}),e&&(typeof Q=="number"||typeof h=="number")&&C.jsxs("div",{className:"skillsRoomInfo",children:[C.jsx("p",{className:"skillsRoomInfoTitle",children:"Room Settings"}),C.jsxs("div",{className:"skillsRoomInfoDetails",children:[typeof Q=="number"&&C.jsxs("span",{className:"skillsRoomInfoItem",children:["💰 ",Q===0?"Free Play":`${Q.toLocaleString()} Credits`]}),typeof h=="number"&&C.jsxs("span",{className:"skillsRoomInfoItem",children:["⏱️ ",h," seconds"]}),typeof Q=="number"&&Q>0&&C.jsxs("span",{className:"skillsRoomInfoItem skillsRoomInfoWin",children:["🏆 Win: ",Math.floor(Q*2*.9).toLocaleString()]})]}),typeof Q=="number"&&Q>o&&C.jsxs("p",{className:"skillsRoomInfoWarning",children:["⚠️ You need ",Q.toLocaleString()," credits to play"]})]}),!c&&l&&C.jsxs("div",{className:"promo-banner",role:"region","aria-label":"Sign in banner",children:[C.jsx("div",{className:"promo-banner__content",children:C.jsx("span",{className:"promo-banner__title",children:"Sign in from home to save progress"})}),C.jsx("button",{className:"btn gold-fill",onClick:l,"aria-label":"Go to home",children:"Go Home"})]}),C.jsx("button",{className:"skillsHowToPlay",onClick:I,"aria-label":"How to play",children:"❓ How to Play"}),!e&&C.jsxs("div",{className:"skillsStakeSelector",children:[C.jsx("p",{className:"skillsStakeLabel",children:"Entry Fee:"}),C.jsx("div",{className:"skillsStakeOptions",children:H0e.map(G=>C.jsx("button",{className:`skillsStakeBtn ${t===G?"selected":""} ${o<G?"disabled":""}`,onClick:()=>i(G),disabled:o<G,children:G},G))}),C.jsxs("p",{className:"skillsStakePot",children:["Win: ",C.jsx("span",{className:"skillsStakeWin",children:Math.floor(t*2*.9)})," credits"]})]}),!e&&C.jsxs("div",{className:"skillsDurationSelector",children:[C.jsx("p",{className:"skillsDurationLabel",children:"Game Duration:"}),C.jsx("div",{className:"skillsDurationOptions",children:O0e.map(G=>C.jsxs("button",{className:`skillsDurationBtn ${n===G?"selected":""}`,onClick:()=>N(G),children:[G,"s"]},G))})]}),s&&C.jsx("p",{className:"skillsStakeError",children:s})]}),C.jsx("div",{className:"home-cta buttonRow",children:C.jsx("div",{className:"skillsStartButtonFixed",children:C.jsx("button",{id:"btn-play-game",className:"btn gold-fill skillsStartBtn",onClick:r,disabled:S||a||!e&&o<t,style:S?{opacity:.5,pointerEvents:"none"}:void 0,children:e?"Ready Up":`Play for ${t} Credits`})})})]})}const Z0e=3e3,W0e=0,lm=new Map,GM=new Map;async function V0e(e){var t,i,n,g,o,s,a;const A=encodeURIComponent(e);try{const r=await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${A}`);if(r.ok){const I=await r.json(),c=(i=(t=I==null?void 0:I[0])==null?void 0:t.meanings)==null?void 0:i[0],l=(g=(n=c==null?void 0:c.definitions)==null?void 0:n[0])==null?void 0:g.definition;if(l)return{definition:l,partOfSpeech:c==null?void 0:c.partOfSpeech}}}catch{}try{const r=await fetch(`https://en.wiktionary.org/api/rest_v1/page/definition/${A}`);if(r.ok){const I=await r.json(),c=(I==null?void 0:I.en)??Object.values(I??{})[0],l=c==null?void 0:c[0],B=(s=(o=l==null?void 0:l.definitions)==null?void 0:o[0])==null?void 0:s.definition;if(B)return{definition:B.replace(/<[^>]+>/g,""),partOfSpeech:(a=l==null?void 0:l.partOfSpeech)==null?void 0:a.toLowerCase()}}}catch{}throw new Error("no definition found")}function X0e(e,A){const t=e.toLowerCase();if(lm.has(t))return;lm.set(t,"loading");const i=new Set;GM.set(t,i),i.add(A),V0e(t).then(n=>lm.set(t,n)).catch(()=>lm.set(t,"error")).finally(()=>{var n;(n=GM.get(t))==null||n.forEach(g=>g()),GM.delete(t)})}function msA({word:e,points:A,isValid:t}){const[i,n]=E.useState(!1),[,g]=E.useState(0),o=E.useRef(null),s=E.useRef(null),a=e.toLowerCase();E.useEffect(()=>{var Q;const B=()=>g(h=>h+1);return(Q=GM.get(a))==null||Q.add(B),()=>{var h;(h=GM.get(a))==null||h.delete(B)}},[a]);const r=E.useCallback(()=>{if(i){n(!1);return}n(!0),lm.has(a)||X0e(a,()=>g(B=>B+1))},[i,a]),I=E.useCallback(B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),r())},[r]);E.useEffect(()=>{if(!i||!o.current||!s.current)return;const B=o.current.getBoundingClientRect(),Q=s.current,h=Q.getBoundingClientRect();let d=B.left+B.width/2-h.width/2,p=B.top-h.height-10;d=Math.max(8,Math.min(d,window.innerWidth-h.width-8)),p<8&&(p=B.bottom+10),Q.style.left=`${d}px`,Q.style.top=`${p}px`}),E.useEffect(()=>{if(!i)return;const B=Q=>{o.current&&!o.current.contains(Q.target)&&n(!1)};return document.addEventListener("pointerdown",B,!0),()=>document.removeEventListener("pointerdown",B,!0)},[i]);const c=t?"roundSummaryWord roundSummaryWordValid":"roundSummaryWord roundSummaryWordInvalid",l=lm.get(a)??null;return C.jsxs("span",{ref:o,className:`${c} wordDefWrapper`,onClick:r,onKeyDown:I,role:"button",tabIndex:0,children:[e," ",C.jsxs("small",{children:["(",A,")"]}),i&&C.jsxs("span",{ref:s,className:"wordDefTooltip",children:[l==="loading"&&C.jsx("em",{children:"Loading…"}),l==="error"&&C.jsx("em",{children:"Definition not available"}),l&&typeof l=="object"&&C.jsxs(C.Fragment,{children:[l.partOfSpeech&&C.jsx("strong",{className:"wordDefPos",children:l.partOfSpeech}),C.jsx("span",{className:"wordDefText",children:l.definition})]})]})]})}function $0e({myScore:e,players:A,scores:t,winnerId:i,iWon:n,isDraw:g,winnings:o,selectedStake:s,isMultiplayer:a,meId:r,roundSummary:I,winStreak:c,isAdEnabled:l=!1,spLevel:B,spLevelName:Q,onPlayAgain:h}){var K,J;const d=n?c:0,p=E.useRef(n?Math.max(0,c-1):d),y=l?Z0e:W0e,[m,D]=E.useState(y>0);E.useEffect(()=>{if(y<=0){D(!1);return}const q=setTimeout(()=>D(!1),y);return()=>clearTimeout(q)},[y]);const S=(I==null?void 0:I.playerWords)&&Object.keys(I.playerWords).length>0||(I==null?void 0:I.rejectedWords)&&Object.keys(I.rejectedWords).length>0,k=(I==null?void 0:I.playerAnswers)&&(I==null?void 0:I.questions)&&Object.keys(I.playerAnswers).length>0,N=q=>{if(q===r)return"You";const v=A.find(U=>U.id===q);return(v==null?void 0:v.name)||"Bot"},G=[...A].sort((q,v)=>q.id===r?-1:v.id===r?1:(t[v.id]??0)-(t[q.id]??0)),M=i?N(i):void 0,w=[];n&&w.push({label:"Round Won",value:"+1 XP"}),n&&c>=2&&w.push({label:`🔥 ${c}-win streak`,value:"streak alive"});let b=null;if(r&&((J=(K=I==null?void 0:I.playerWords)==null?void 0:K[r])!=null&&J.length))for(const q of I.playerWords[r])(!b||q.points>b.points)&&(b=q);b&&w.push({label:`Best word: ${b.word}`,value:`+${b.points} pts`});const _=n&&c>0&&c%5===0;return C.jsxs("div",{className:"roundEnd",children:[typeof B=="number"&&C.jsx(YmA,{level:B,levelName:Q,winStreak:d,previousWinStreak:p.current,variant:"compact"}),C.jsxs("div",{className:"roundEndRow",style:{flexWrap:"wrap",gap:"0.25rem 0.75rem"},children:[G.map(q=>C.jsxs("span",{className:"roundEndScore",style:q.id===i?{color:"var(--gold, #f5c542)"}:void 0,children:[N(q.id),": ",C.jsx("strong",{children:t[q.id]??0})]},q.id)),C.jsxs("span",{className:"roundEndResult",children:[n?"🏆 You Win!":g?"🤝 Draw":`😔 ${M??"Opponent"} Wins`,n&&o>0&&C.jsxs("span",{className:"roundEndWinnings",children:["+",o.toLocaleString()]}),!n&&!g&&C.jsxs("span",{className:"roundEndLoss",children:["-",s]})]}),n&&c>=2&&C.jsxs("div",{className:"roundEndStreak",children:[C.jsx("span",{className:"roundEndStreakFire",children:"🔥"}),C.jsx("span",{className:"roundEndStreakCount",children:c}),C.jsx("span",{className:"roundEndStreakLabel",children:"Win Streak!"})]})]}),w.length>0&&C.jsxs("div",{className:["skillsXpBreakdown",_?"skillsXpBreakdown--levelup":""].join(" "),children:[_&&C.jsx("div",{className:"skillsXpBreakdown__title",children:"✨ LEAGUE UP! ✨"}),w.map((q,v)=>C.jsxs("div",{className:"skillsXpBreakdown__row",children:[C.jsx("span",{className:"skillsXpBreakdown__label",children:q.label}),C.jsx("span",{className:"skillsXpBreakdown__value",children:q.value})]},v))]}),C.jsx("div",{className:"home-cta buttonRow",children:C.jsx("button",{id:"btn-play-again",className:"btn gold-fill cta-btn primaryButton",onClick:h,disabled:m,style:m?{opacity:.5,pointerEvents:"none"}:void 0,children:a?"Ready Up":"Play Again"})}),S&&C.jsxs("div",{className:"roundSummaryScrollable",children:[C.jsx("p",{className:"roundSummaryTitle",children:"Words Found"}),(()=>{const q=new Set([...Object.keys((I==null?void 0:I.playerWords)||{}),...Object.keys((I==null?void 0:I.rejectedWords)||{})]);return Array.from(q).map(v=>{var z,Z;const U=N(v),x=((z=I==null?void 0:I.playerWords)==null?void 0:z[v])||[],T=((Z=I==null?void 0:I.rejectedWords)==null?void 0:Z[v])||[];return C.jsxs("div",{className:"roundSummaryPlayer",children:[C.jsxs("span",{className:"roundSummaryLabel",children:[U,":"]}),C.jsxs("div",{className:"roundSummaryWordsList",children:[x.length>0?x.map((eA,aA)=>C.jsx(msA,{word:eA.word,points:eA.points,isValid:!0},aA)):!T.length&&C.jsx("span",{className:"roundSummaryNone",children:"No words"}),T.length>0&&T.map((eA,aA)=>C.jsx(msA,{word:eA,points:0,isValid:!1},`rej-${aA}`))]})]},v)})})()]}),k&&C.jsxs("div",{className:"roundSummaryScrollable",children:[C.jsx("p",{className:"roundSummaryTitle",children:"Answers"}),Object.entries(I.playerAnswers).map(([q,v])=>{const U=N(q);return C.jsxs("div",{className:"roundSummaryPlayer",children:[C.jsxs("span",{className:"roundSummaryLabel",children:[U,":"]}),C.jsx("div",{className:"roundSummaryAnswersList",children:v.length>0?v.map((x,T)=>C.jsxs("span",{className:`roundSummaryAnswer ${x.correct?"roundSummaryAnswerCorrect":"roundSummaryAnswerWrong"}`,children:["Q",x.questionIndex+1,": ",x.correct?"✓":"✗"]},T)):C.jsx("span",{className:"roundSummaryNone",children:"No answers"})})]},q)})]})]})}function Ake({countdown:e}){return C.jsx("div",{className:"skillsCountdownOverlay",children:C.jsx("div",{className:"skillsCountdownNumber",children:e})})}function eke({readyCount:e,totalPlayers:A}){return C.jsxs("div",{className:"skillsWaitingContainer",children:[C.jsx("div",{className:"skillsWaitingSpinner"}),C.jsxs("p",{className:"skillsWaitingText",children:["Waiting for players... (",e,"/",A," ready)"]})]})}function tke({message:e}){return C.jsx("div",{className:"skillsInvalidWord",children:C.jsx("span",{className:"skillsInvalidWordText",children:e})})}function ike({onRetry:e}){return C.jsx("div",{className:"card alertCard",role:"alert",children:C.jsxs("div",{className:"alertRow",children:[C.jsx("span",{className:"alertText",children:"⚠️ Connection lost. Reconnecting…"}),C.jsx("button",{className:"btn btn-secondary alertBtn",onClick:e,children:"Retry"})]})})}function nke(e){const{meId:A,setConnected:t,setScores:i,setRoundEnded:n,setWinnerId:g,setPlayers:o,setGameState:s,setHasStarted:a,setWinnings:r,setWinStreak:I,setRoundSummary:c,setMyAnagramWords:l,setClaimedWordPaths:B,setMyTriviaAnswers:Q,setCurrentTriviaQuestion:h,setCountdown:d,isMultiplayer:p,roundEnded:y,endRef:m,onWordClaimed:D}=e,{setSession:S}=b4(),{win:k,lose:N}=Jr(),{onHandEnd:G}=Yf(),M=E.useCallback(w=>{const b=new Set;return w.filter(_=>!(_!=null&&_.id)||b.has(_.id)?!1:(b.add(_.id),!0))},[]);Os({onSkillsRejoinedRoom:w=>{var b,_;if(w!=null&&w.room){if(console.log("[skills] rejoined room via server reconnect",{roomId:w.room.id,phase:(b=w.room.gameState)==null?void 0:b.phase,playerCount:(_=w.room.players)==null?void 0:_.length}),w.room.players){const K=M(w.room.players);o(K)}w.room.gameState&&(s(w.room.gameState),w.room.gameState.scores&&i(w.room.gameState.scores)),t(!0)}},onPlayerPresenceUpdate:w=>{if(!w)return;const{playerId:b,status:_}=w;!b||!_||b===A&&t(_==="active")},onSkillsSessionInfo:w=>{S({roomId:w.roomId,seed:w.seed,startAt:w.startAt,endAt:w.endAt,driftMs:w.driftMs,gameMode:w.gameMode||"wordsearch",letters:w.letters,questions:w.questions}),B([]),l([]),h(0),Q({})},onAnagramsWordFound:w=>{w.playerId===A&&l(b=>[...b,w.word])},onTriviaAnswer:w=>{w.playerId===A&&Q(b=>({...b,[w.questionIndex]:{answer:w.questionIndex,isCorrect:w.isCorrect,correctIndex:w.correctIndex}}))},onTriviaNextQuestion:w=>{h(w.questionIndex)},onRoomUpdateState:w=>{var x,T,z,Z,eA,aA,sA,pA,gA,yA,fA,RA,qA;const b=new Set(["skills","wordsearch","anagrams","trivia"]),_=((x=w.room)==null?void 0:x.gameMode)||((T=w.gameState)==null?void 0:T.gameMode)||((Z=(z=w.room)==null?void 0:z.gameState)==null?void 0:Z.gameMode);if(!_||!b.has(_))return;const K=((eA=w.room)==null?void 0:eA.players)||[],J=M(K);J.length>0&&o(W=>{const $=new Map;return W.forEach(L=>{typeof L.balance=="number"&&$.set(L.id,L.balance)}),J.map(L=>{if(typeof L.balance=="number")return L;const H=$.get(L.id);return typeof H=="number"?{...L,balance:H}:L})});const q=w.gameState||{};s(q),q.phase==="playing"&&q.seed&&!b4.getState().seed&&(console.log("[SkillsSocketListeners] Recovering session from room:update_state",{seed:q.seed,gameMode:q.gameMode}),S({roomId:(aA=w.room)==null?void 0:aA.id,seed:q.seed,startAt:q.startAt,endAt:q.endAt,gameMode:q.gameMode,letters:(sA=q.anagramsData)==null?void 0:sA.letters,questions:(gA=(pA=q.triviaData)==null?void 0:pA.questions)==null?void 0:gA.map(W=>({id:W.id,question:W.question,answers:W.answers,category:W.category,difficulty:W.difficulty}))}));const v=(yA=w.gameState)==null?void 0:yA.phase,U=((RA=(fA=w.gameState)==null?void 0:fA.readyMap)==null?void 0:RA[A||""])||!1;v==="waiting"&&!y&&(g(void 0),r(0),U||a(!1),i({}),c(null),B([]),l([]),Q({}),h(0)),v!=="playing"&&!y&&((qA=w.gameState)!=null&&qA.scores)&&i(w.gameState.scores)},onSkillsRoundStart:w=>{i({}),n(!1),g(void 0),c(null),B([]),l([]),Q({}),h(0),S({roomId:w.roomId,seed:w.seed,startAt:w.startAt,endAt:w.endAt}),p&&(a(!0),d(3))},onSkillsScoreUpdate:w=>{w.scores&&i(w.scores)},onSkillsRoundEnd:w=>{if(n(!0),w.scores&&i(w.scores),w.winnerId)if(g(w.winnerId),w.winnerId===A){A1();const b=typeof w.winnings=="number"?w.winnings:0;k("Winner!",b>0?`+Z$${b.toLocaleString()}`:void 0)}else e1(),N("Better Luck Next Time");typeof w.winnings=="number"&&r(w.winnings),I(typeof w.winnerStreak=="number"?w.winnerStreak:0),c({playerWords:w.playerWords,rejectedWords:w.rejectedWords,playerAnswers:w.playerAnswers,questions:w.questions}),m.current=Date.now(),G()},onPlayerBalanceUpdated:({playerId:w,balance:b})=>{o(_=>{if(!Array.isArray(_))return _;const K=_.findIndex(v=>String(v.id)===String(w));if(K===-1)return _;const J=_.slice(),q=J[K];return typeof(q==null?void 0:q.balance)=="number"&&q.balance===b?_:(J[K]={...q,balance:b},J)})},onOtherPlayerJoined:w=>{var q,v,U,x,T;if(!((q=w==null?void 0:w.room)!=null&&q.players))return;const b=new Set(["skills","wordsearch","anagrams","trivia"]),_=((v=w.room)==null?void 0:v.gameMode)||((U=w.gameState)==null?void 0:U.gameMode)||((T=(x=w.room)==null?void 0:x.gameState)==null?void 0:T.gameMode);if(!_||!b.has(_))return;const K=w.room.players||[],J=M(K);o(J)},onOtherLeft:w=>{var q,v,U,x,T;if(!((q=w==null?void 0:w.room)!=null&&q.players))return;const b=new Set(["skills","wordsearch","anagrams","trivia"]),_=((v=w.room)==null?void 0:v.gameMode)||((U=w.gameState)==null?void 0:U.gameMode)||((T=(x=w.room)==null?void 0:x.gameState)==null?void 0:T.gameMode);if(!_||!b.has(_))return;const K=w.room.players||[],J=M(K);o(J),w.gameState&&s(w.gameState)},onSkillsWordClaimed:w=>{D==null||D(w)}})}const U4="skills:dailyChallenge:";function HmA(){const e=new Date,A=e.getUTCFullYear(),t=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0");return`${A}-${t}-${i}`}function gke(){const e=new Date,A=Date.UTC(e.getUTCFullYear(),0,0),t=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate());return Math.floor((t-A)/864e5)}const SsA=[{kind:"find_long_word",label:"Find a 6-letter word",goal:1},{kind:"win_round",label:"Win a Skills round",goal:1},{kind:"score_100",label:"Score 100+ in a round",goal:1}];function oke(){return SsA[gke()%SsA.length]}function wsA(){const e=HmA(),A=`${U4}${e}`;try{const i=localStorage.getItem(A);if(i){const n=JSON.parse(i);if(n&&n.dateKey===e)return n}for(let n=0;n<localStorage.length;n++){const g=localStorage.key(n);if(g&&g.startsWith(U4)&&g!==A)try{localStorage.removeItem(g)}catch{}}}catch{}return{...oke(),progress:0,completed:!1,dateKey:e}}function ske(e){try{localStorage.setItem(`${U4}${e.dateKey}`,JSON.stringify(e))}catch{}}function ake(){const[e,A]=E.useState(()=>wsA()),t=E.useRef(e);E.useEffect(()=>{t.current=e},[e]),E.useEffect(()=>{const o=window.setInterval(()=>{if(t.current.dateKey!==HmA()){const s=wsA();A(s)}},6e4);return()=>window.clearInterval(o)},[]);const i=E.useCallback(o=>{A(s=>{if(s.completed)return s;const a=o(s);if(a===s)return s;const r=Math.min(a.goal,Math.max(s.progress,a.progress)),I=r>=a.goal,c={...a,progress:r,completed:I};return ske(c),c})},[]),n=E.useCallback(o=>{i(s=>s.kind==="win_round"&&o.iWon?{...s,progress:s.progress+1}:s.kind==="score_100"&&o.myScore>=100?{...s,progress:s.progress+1}:s)},[i]),g=E.useCallback(o=>{i(s=>s.kind==="find_long_word"&&o.length>=6?{...s,progress:s.progress+1}:s)},[i]);return{challenge:e,recordRoundResult:n,recordWord:g}}let rke=!1;function ksA(e,A){try{rke||n8()}catch{}}const Ike=new Set(["room.ready","tapAck","score","roundEnd"]),MsA=512,Cke=50;let Gu=null,OmA=1;const ep=new Set;let v4=0;function hT(){return Gu||(Gu=Vk(ZM||"",{path:"/socket.io",transports:["websocket","polling"],autoConnect:!1,reconnection:!0,reconnectionAttempts:1/0,reconnectionDelayMax:1e4,auth:{platform:"web"}}),Gu)}async function PmA(){const e=hT();let A;try{A=await uo()}catch{A=void 0}if(!A){if(e.auth={platform:"web"},e.connected)try{e.disconnect()}catch{}return}e.auth={...e.auth||{},platform:"web",token:A},e.connected||e.connect()}function cke(){if(Gu){try{Gu.removeAllListeners()}catch{}try{Gu.disconnect()}catch{}Gu=null}OmA=1,ep.clear(),v4=0}function lke(e){const A=hT(),t=(i,n)=>{Ike.has(i)&&e({type:i,payload:n})};return A.on("message",t),()=>{A.off("message",t)}}function Bke(e){const A=hT();if(e.type==="tap"){const t=Date.now();if(t-v4<Cke)return"throttled";v4=t}if(e.type==="tap"||e.type==="submit"){if(ep.has(e.payload.seq))return"duplicate";if(ep.add(e.payload.seq),ep.size>MsA){const t=ep.size-MsA,i=ep.values();for(let n=0;n<t;n++){const g=i.next().value;if(g===void 0)break;ep.delete(g)}}}return A.connected?(A.emit("message",e.type,e.payload),"sent"):"disconnected"}function jmA(){return OmA++}function Eke(e,A){return e-A}const Qke=Object.freeze(Object.defineProperty({__proto__:null,computeDrift:Eke,connectSocket:PmA,disconnectSocket:cke,getSocket:hT,nextSeq:jmA,onMessage:lke,send:Bke},Symbol.toStringTag,{value:"Module"}));function uke(){return ZM}const NsA=uke();async function dke(){if(!NsA)return null;try{let e;try{e=await uo()}catch{}const A={Accept:"application/json"};e&&(A.Authorization=`Bearer ${e}`);const t=await fetch(`${NsA}/api/auth/me`,{credentials:"include",headers:A});if(t.ok)return await t.json();if(t.status===204||t.status===401){if(t.status===401&&e)try{await kd()}catch{}return null}return null}catch{return null}}function hke({endAt:e,isActive:A,totalSeconds:t=30}){const[i,n]=E.useState(t),g=E.useRef(null);E.useEffect(()=>{if(!A||!e){n(t),g.current&&(cancelAnimationFrame(g.current),g.current=null);return}const I=()=>{const c=Date.now(),l=Math.max(0,Math.ceil((e-c)/1e3));n(l),l>0?g.current=requestAnimationFrame(I):g.current=null};return I(),()=>{g.current&&(cancelAnimationFrame(g.current),g.current=null)}},[e,A,t]);const o=A&&e!==void 0,s=i<=15,a=i<=5,r=i/t*100;return C.jsxs("div",{className:["poker-turn-timer",o?"":"poker-turn-timer--hidden",s?"poker-turn-timer--urgent":"",a?"poker-turn-timer--critical":""].filter(Boolean).join(" "),"aria-live":"polite","aria-atomic":"true",role:"timer","aria-hidden":!o,children:[C.jsxs("div",{className:"poker-turn-timer__ring",children:[C.jsxs("svg",{viewBox:"0 0 36 36",className:"poker-turn-timer__svg",children:[C.jsx("circle",{className:"poker-turn-timer__circle-bg",cx:"18",cy:"18",r:"16"}),C.jsx("circle",{className:"poker-turn-timer__circle-progress",cx:"18",cy:"18",r:"16",strokeDasharray:`${r} 100`})]}),C.jsx("div",{className:"poker-turn-timer__number",children:i})]}),C.jsx("div",{className:"poker-turn-timer__label","aria-hidden":"true",children:"Time Left"})]})}function pke(e){const{endAt:A,isRoundActive:t,scores:i,meId:n}=e,g=E.useMemo(()=>C.jsx(hke,{endAt:A,isActive:!!t&&!!A,totalSeconds:30}),[A,t]),o=E.useMemo(()=>{if(!(!i||!t))return s=>{const a=i[s.id]??0,r=s.id===n;return C.jsxs("div",{className:`skills-player-score ${r?"skills-player-score--me":""}`,children:[C.jsx("span",{className:"skills-score-value",children:a}),C.jsx("span",{className:"skills-score-label",children:"pts"})]})}},[i,t,n]);return C.jsx(rx,{...e,className:"skills-player-panel",hideDiceResults:!0,disableBankerFlash:!0,hideSideBets:!0,headerCommsLeftSlot:g,renderFacesOverride:o})}function TJ(){var ot,kt,ht;const{roomId:e,seed:A,startAt:t,endAt:i,driftMs:n,setSession:g,set:o,user:s,gameMode:a,letters:r,questions:I}=b4(),{meId:c,user:l}=tn(),B=Ms(),{cancelAd:Q,isAdEnabled:h}=Yf(),d=qi(),p=Ix();E.useEffect(()=>(p.acquire(),()=>{p.release()}),[p]);const[y]=uw(),{roomId:m}=Qw(),D=m||y.get("roomId"),S=y.get("mode"),k=y.get("e2e")==="1",N=y.get("autoplay")==="1",[G,M]=E.useState(!0),[w,b]=E.useState({}),_=E.useRef(!1),[K,J]=E.useState(!1),[q,v]=E.useState(),[U,x]=E.useState([]),[T,z]=E.useState({}),[Z,eA]=E.useState(!1),[aA,sA]=E.useState(null),[pA,gA]=E.useState(null),[yA,fA]=E.useState(null),[RA,qA]=E.useState(null),[W,$]=E.useState(0),L=E.useRef(0),H=E.useRef(null);E.useEffect(()=>()=>{H.current&&window.clearTimeout(H.current)},[]);const[P,tA]=E.useState(100),[iA,oA]=E.useState(30),[IA,CA]=E.useState(null),[_A,uA]=E.useState(0),[X,O]=E.useState(0),[cA,wA]=E.useState(0),[xA,YA]=E.useState(),[jA,ie]=E.useState(),[he,le]=E.useState(!1),[NA,EA]=E.useState(void 0),[PA,ZA]=E.useState(null),{active:FA,fire:Ie,onComplete:DA}=UZ(),{challenge:rA,recordRoundResult:BA,recordWord:j}=ake(),QA=E.useRef(0),dA=["loss-a","loss-b","loss-c"],UA=()=>{const ee=dA[QA.current%dA.length];return QA.current+=1,ee},[TA,oe]=E.useState(S||"wordsearch"),[me,be]=E.useState([]),[$e,ci]=E.useState(0),[ke,nt]=E.useState({}),[Ut,dt]=E.useState([]),Ht=E.useRef(null);E.useRef(null);const Ft=E.useRef({});Ft.current=w;const Jt=E.useRef(null),$A=E.useRef(null),{skillsSubmit:He,skillsSingleStart:Xe,skillsReady:St,skillsJoinRoom:kA,anagramsSubmit:se,triviaAnswer:Ce}=Mo(),{joinRoom:VA,leaveRoom:nA}=Il(),vA=E.useRef(nA);vA.current=nA;const KA=c||(s==null?void 0:s.id);E.useEffect(()=>{o({seed:null,startAt:null,endAt:null,roomId:null,letters:void 0,questions:void 0}),Jt.current=null,$A.current=null},[]),E.useEffect(()=>{if(!B)return;const ee=()=>{console.log("[SkillsPlay] socket reconnected — resetting guards"),Jt.current=null,Tn.current=!1};return B.on("connect",ee),()=>{B.off("connect",ee)}},[B]),E.useEffect(()=>{if(!D)return;const ee=()=>{console.log("[SkillsPlay] ad:complete — resetting join guard for room",D),Jt.current=null};return window.addEventListener("ad:complete",ee),()=>{window.removeEventListener("ad:complete",ee)}},[D]),E.useEffect(()=>{if(S){oe(S);return}(async()=>{try{const{Preferences:ee}=await Qi(async()=>{const{Preferences:Ct}=await Promise.resolve().then(()=>Oc);return{Preferences:Ct}},void 0),{value:je}=await ee.get({key:"selectedSkillsGameMode"});(je==="wordsearch"||je==="anagrams"||je==="trivia")&&oe(je)}catch{}})()},[S]),E.useEffect(()=>{(async()=>{try{const{Preferences:ee}=await Qi(async()=>{const{Preferences:At}=await Promise.resolve().then(()=>Oc);return{Preferences:At}},void 0),{value:je}=await ee.get({key:"selectedSkillsDuration"}),Ct=parseInt(je||"",10);(Ct===30||Ct===60||Ct===90)&&oA(Ct)}catch{}})()},[]),E.useEffect(()=>{(async()=>{try{const ee=await Xo();ee.botDifficultyLevel&&ee.botDifficultyLevel>=1&&ee.botDifficultyLevel<=9&&EA(ee.botDifficultyLevel)}catch{}})()},[]);const WA=(l==null?void 0:l.balance)??0,bA=!!l,pe=(()=>{try{return(l==null?void 0:l.isGuest)===!0}catch{return!1}})(),xe=!bA||pe,it=E.useCallback(()=>d("/lobby"),[d]),ve=KA?w[KA]??0:0,re=U.find(ee=>ee.id!==KA),Qe=re==null?void 0:re.id,HA=(re==null?void 0:re.name)||"Bot";Qe&&w[Qe];const ge=!!D,ye=U.find(ee=>ee.id===KA);ye!=null&&ye.isReady||(ot=T==null?void 0:T.readyMap)!=null&&ot[KA||""];const Te=E.useMemo(()=>{const ee=new Set;let je=U.filter(At=>!(At!=null&&At.id)||ee.has(At.id)?!1:(ee.add(At.id),!0)).map(At=>At.id===KA&&typeof At.balance!="number"&&typeof(l==null?void 0:l.balance)=="number"?{...At,balance:l.balance}:At);const Ct=typeof KA=="string"&&KA.length>0;return je.length===0&&Ct&&l&&(je=[{id:KA,name:l.name||l.email||"You",balance:l.balance??0,avatarUrl:l.avatarUrl??void 0}]),je},[U,KA,l==null?void 0:l.balance,l==null?void 0:l.name,l==null?void 0:l.email,l==null?void 0:l.avatarUrl,l]),gt=(T==null?void 0:T.everyoneReady)||!1,Qt=(T==null?void 0:T.phase)||"waiting",_e=S||(T==null?void 0:T.gameMode)||a||TA,{showOnboarding:Ze,closeOnboarding:at}=Y0e(_e),Ai=k?"demo-screenshot-seed-12345":null,Bi=A||(T==null?void 0:T.seed)||Ai,yi=k?"playing":Qt,mt=r||((kt=T==null?void 0:T.anagramsData)==null?void 0:kt.letters),ct=I||((ht=T==null?void 0:T.triviaData)==null?void 0:ht.questions),fi=yi==="playing"&&!!Bi&&!K&&_e==="wordsearch",Yi=yi==="playing"&&!K&&_e==="anagrams"&&(((mt==null?void 0:mt.length)??0)>0||k),si=yi==="playing"&&!K&&_e==="trivia"&&(((ct==null?void 0:ct.length)??0)>0||k),[jt,Zt]=E.useState(null),vi=E.useCallback(ee=>{dt(At=>At.some(zt=>zt.word===ee.word)?At:[...At,{word:ee.word,playerId:ee.playerId,path:ee.path}]);const je=ee.playerId===KA,Ct=Array.isArray(ee.path)&&ee.path.length>0;if(Ct&&je&&N&&Zt({path:ee.path,nonce:Date.now(),mine:!0}),N&&Ct&&je){const At=ee.word||"",zt=Math.max(220,Math.min(320,Math.floor(2e3/ee.path.length))),li=ee.path.length*zt+900,Ei=ee.path[ee.path.length-1],ai=At.length*At.length;L.current=Math.min(L.current+1,8);const Hi=1+(L.current-1)*.07;window.setTimeout(()=>{fA("valid");try{XP({volume:.6,rate:Hi})}catch{}setTimeout(()=>fA(null),400),Ei&&(qA({row:Ei.r,col:Ei.c,points:ai,nonce:Date.now()}),H.current&&window.clearTimeout(H.current),H.current=window.setTimeout(()=>qA(null),950)),(At.length>=6||L.current>=4)&&$(Date.now())},li)}},[KA,N]);nke({meId:KA,setConnected:M,setScores:b,setRoundEnded:J,setWinnerId:v,setPlayers:x,setGameState:z,setHasStarted:eA,setWinnings:uA,setWinStreak:O,setRoundSummary:ZA,setMyAnagramWords:be,setClaimedWordPaths:dt,setMyTriviaAnswers:nt,setCurrentTriviaQuestion:ci,setCountdown:sA,onWordClaimed:vi,isMultiplayer:ge,roundEnded:K,endRef:Ht}),E.useEffect(()=>{if(K||!KA)return;const ee=w[KA]??0,je=Object.entries(w).filter(([At])=>At!==KA).map(([,At])=>At),Ct=Math.max(0,...je);Ct>0&&ee<Ct&&(_.current=!0)},[w,KA,K]),E.useEffect(()=>{if(!K||!q||!KA)return;const ee=q===KA;if(wA(ee?X:0),BA({iWon:ee,myScore:w[KA]??0}),!ee){Ie(UA(),{displayMs:2e3});return}const je=w[KA]??0,Ct=Object.entries(w).filter(([zt])=>zt!==KA).map(([,zt])=>zt),At=Math.max(0,...Ct);At===0&&je>0?Ie("skills-perfect",{displayMs:3e3}):X>0&&X%5===0?Ie("streak-5",{displayMs:3500}):At>0&&je>=At*2?Ie("skills-dominate",{displayMs:2500}):_.current?Ie("skills-comeback",{displayMs:3e3}):X>=3?Ie("streak-3",{displayMs:2500}):Ie("big-win",{displayMs:2500}),_.current=!1},[K,q,KA,w,X,Ie,BA]),E.useEffect(()=>{const ee=T;(ee==null?void 0:ee.phase)==="playing"&&Array.isArray(ee==null?void 0:ee.claimedWords)&&ee.claimedWords.length>0&&dt(ee.claimedWords)},[T]),E.useEffect(()=>{Z||A?Yu():K||wL({volume:.0125})},[Z,K,A]);const kn=E.useRef(D);E.useEffect(()=>{kn.current!==D&&(ZA(null),J(!1),v(void 0),uA(0),b({}),_.current=!1,dt([]),be([]),ci(0),nt({}),kn.current=D)},[D]),E.useEffect(()=>{D&&Jt.current!==D&&(Jt.current=D,kA(D).then(async ee=>{var je,Ct;if(ee!=null&&ee.ok&&(ee!=null&&ee.data)){if(o({roomId:ee.data.roomId}),(je=ee.data.room)!=null&&je.players){const At=ee.data.room.players,zt=new Set,li=At.filter(Ei=>!(Ei!=null&&Ei.id)||zt.has(Ei.id)?!1:(zt.add(Ei.id),!0));x(li)}if((Ct=ee.data.room)!=null&&Ct.gameState&&z(ee.data.room.gameState),$A.current!==D)try{console.log("[SkillsPlay] Joining RTC room:",D),await VA(D),$A.current=D,console.log("[SkillsPlay] RTC room joined successfully:",D)}catch(At){console.error("[SkillsPlay] Failed to join RTC room:",At)}}else Jt.current=null}).catch(()=>{Jt.current=null}))},[D,kA,o,VA]),E.useEffect(()=>()=>{$A.current&&(console.log("[SkillsPlay] Leaving RTC room on unmount"),vA.current())},[]),E.useEffect(()=>{n8(),dke().then(ee=>o({user:ee}))},[o]),E.useEffect(()=>{if(!i||K||!Z)return;const ee=()=>{Date.now()+n>=i&&!K&&Z&&(console.log("[SkillsPlay] Timer expired locally, triggering round end"),J(!0))};ee();const je=i-(Date.now()+n);if(je>0){const Ct=setTimeout(ee,je+3e3);return()=>clearTimeout(Ct)}},[i,n,K,Z]),E.useEffect(()=>{if(!Z)return;let ee;(async()=>{try{const{App:Ct}=await Qi(async()=>{const{App:zt}=await Promise.resolve().then(()=>GR);return{App:zt}},void 0),At=await Ct.addListener("appStateChange",zt=>{if(zt.isActive){const li=Date.now()+n;i&&li>=i&&!K&&Z&&(console.log("[SkillsPlay] App resumed after timer expired, triggering round end"),J(!0))}});ee=()=>{try{At.remove()}catch{}}}catch{}})();const je=()=>{if(document.visibilityState==="visible"){const Ct=Date.now()+n;i&&Ct>=i&&!K&&Z&&(console.log("[SkillsPlay] Tab visible after timer expired, triggering round end"),J(!0))}};return document.addEventListener("visibilitychange",je),()=>{ee==null||ee(),document.removeEventListener("visibilitychange",je)}},[i,n,K,Z]);const gn=Date.now()+n,Ki=!!i&&gn<(i??0),Tn=E.useRef(!1),fg=E.useCallback(async()=>{if(!Tn.current){Tn.current=!0;try{console.log("[SkillsPlay] startGame() called",{selectedStake:P,activeGameMode:_e,selectedDuration:iA,myBalance:WA});const ee=await Xe(P,_e,iA,NA,N);console.log("[SkillsPlay] startGame() result",{ok:ee==null?void 0:ee.ok,error:ee==null?void 0:ee.error,hasData:!!(ee!=null&&ee.data)}),ee&&!ee.ok?(console.log("[SkillsPlay] startGame() failed",{error:ee.error,balance:ee.balance,stake:ee.stake}),Tn.current=!1,eA(!1),sA(null),ee.error!=="insufficient_balance"&&ee.error!=="already_starting"&&CA(ee.error||"Failed to start game")):ee!=null&&ee.data?(Tn.current=!1,ee.data.spLevel&&YA(ee.data.spLevel),ee.data.levelName&&ie(ee.data.levelName),g({...ee.data,gameMode:ee.data.gameMode||_e}),z(je=>({...je,phase:"playing",gameMode:ee.data.gameMode||_e,stake:ee.data.stake,pot:ee.data.pot}))):Tn.current=!1}catch{Tn.current=!1}}},[Xe,P,iA,_e,NA,N]),Zi=E.useCallback(async()=>{if(CA(null),console.log("[SkillsPlay] handleStart",{activeGameMode:_e,urlGameMode:S,preferredGameMode:TA,gameMode:a,gameStateMode:T==null?void 0:T.gameMode,isMultiplayer:ge}),ge){const ee=D||e;ee&&(console.log("[skills:ready] sending immediately on handleStart",{effectiveRoomId:ee}),Q(),eA(!0),await St(ee));return}if(console.log("[SkillsPlay] handleStart() balance check",{hasStarted:Z,myBalance:WA,selectedStake:P,passes:WA>=P}),!Z&&WA<P){console.log("[SkillsPlay] handleStart() CLIENT BALANCE CHECK FAILED",{myBalance:WA,selectedStake:P}),CA(`Insufficient balance. Need ${P} credits.`);return}console.log("[SkillsPlay] handleStart() starting countdown"),Yu(),eA(!0),sA(3)},[ge,P,_e,S,TA,a,T==null?void 0:T.gameMode,WA,D,e,St,Q]),te=E.useCallback(async()=>{Tn.current=!1,o({seed:null,startAt:null,endAt:null,roomId:null,letters:void 0,questions:void 0}),J(!1),eA(!0),sA(null),uA(0),b({}),_.current=!1,dt([]),v(void 0),ZA(null),be([]),ci(0),nt({}),L.current=0,qA(null),$(0),ge&&D?(Q(),await St(D)):(eA(!1),x([]),z({}))},[o,ge,D,St,Q]),Eg=E.useRef(0);E.useEffect(()=>{N&&(P!==500&&tA(500),iA!==90&&oA(90))},[N,P,iA]),E.useEffect(()=>{if(!N||ge)return;const ee=()=>{if(Z||K||aA!==null)return;if(!bA){console.log("[SkillsPlay autoplay] waiting for auth before starting");return}const At=Date.now();At-Eg.current<5e3||(Eg.current=At,console.log("[SkillsPlay autoplay] kicking countdown",{selectedStake:P,activeGameMode:_e,selectedDuration:iA,myBalance:WA}),Yu(),eA(!0),sA(3))},je=window.setTimeout(ee,1200),Ct=window.setInterval(ee,3e3);return()=>{window.clearTimeout(je),window.clearInterval(Ct)}},[N,ge,Z,K,aA,bA,P,_e,iA,WA]),E.useEffect(()=>{if(!N||ge||!K)return;const ee=window.setTimeout(()=>{Eg.current=0,te()},4e3);return()=>window.clearTimeout(ee)},[N,ge,K,te]),E.useEffect(()=>{if(aA===null)return;if(aA>0&&Vl({volume:.3}),aA===0){Vl({volume:.5}),sA(null),ge||fg();return}const ee=setTimeout(()=>{sA(je=>je!==null&&je>0?je-1:null)},1e3);return()=>clearTimeout(ee)},[aA,fg,ge]);const gi=E.useMemo(()=>A?ysA(A):[],[A]),Mg=E.useMemo(()=>Ut.filter(ee=>ee.playerId===KA).map(ee=>ee.word),[Ut,KA]),Hg=E.useMemo(()=>Ut.filter(ee=>ee.playerId!==KA).map(ee=>ee.word),[Ut,KA]),de=E.useCallback(async ee=>{!Ki||!e||K||ee.length<3||await se(e,ee.toUpperCase())},[Ki,e,K,se]),qe=E.useCallback(async(ee,je)=>{!Ki||!e||K||(nt(Ct=>({...Ct,[ee]:{answer:je,isCorrect:void 0,correctIndex:void 0}})),await Ce(e,ee,je))},[Ki,e,K,Ce]),OA=async ee=>{if(!Ki||!e||K||ee.length<3)return;const je=ee.map(({r:zt,c:li})=>{var Ei;return((Ei=gi[zt])==null?void 0:Ei[li])||""}).join("").toUpperCase();if(je.length<3)return;const Ct=jmA();ksA("word_submit",{len:ee.length});const At=await He(e,ee,je,Date.now(),Ct);if(At&&At.valid){L.current=Math.min(L.current+1,8);const zt=1+(L.current-1)*.07;fA("valid"),XP({volume:.4,rate:zt}),setTimeout(()=>fA(null),400);const li=ee[ee.length-1],Ei=typeof At.points=="number"?At.points:je.length*je.length;li&&(qA({row:li.r,col:li.c,points:Ei,nonce:Date.now()}),H.current&&window.clearTimeout(H.current),H.current=window.setTimeout(()=>qA(null),950)),(je.length>=6||L.current>=4)&&$(Date.now()),j(je)}else At&&!At.valid&&(L.current=0,fA("invalid"),setTimeout(()=>fA(null),400),At.error==="invalid_word"?gA(`"${je}" is not a word`):At.error==="word_already_used"?gA(`"${je}" already used`):At.error==="word_claimed"?gA(`"${je}" already taken`):(At.error==="path_not_contiguous"||At.error==="path_has_duplicates")&&gA("Invalid path"),setTimeout(()=>gA(null),800))},Ae=ee=>{ksA()},Ke=!fi&&!Yi&&!si&&!Z&&!K,Je=Z&&!fi&&!Yi&&!si&&ge&&!gt&&!K,pt=U.filter(ee=>{var je;return(je=T==null?void 0:T.readyMap)==null?void 0:je[ee.id]}).length,Tt=U.length,vt=q===KA,ei=!q&&K,Vt=E.useMemo(()=>({...T,gameMode:"skills"}),[T]),hA=E.useMemo(()=>{var li;if(ge)return;const ee=Number(xA??(l==null?void 0:l.spLevelSkills)??1),je=Number.isFinite(ee)&&ee>0?ee:1,Ct=Math.max(0,cA)%5,At=cA>0&&Ct===0?5:Ct,zt=jA??((li=nQ.find(Ei=>Ei.level===je))==null?void 0:li.name)??`Level ${je}`;return{level:je,levelName:zt,current:At,total:5,progressLabel:`${At}/5 consecutive wins`,goalLabel:`Win 5 rounds in a row to reach Level ${je+1}`,isMaxLevel:je>=nQ.length}},[ge,xA,jA,l==null?void 0:l.spLevelSkills,cA]),Re=`skillsPage${yA==="valid"?" skillsFlashValid":""}${yA==="invalid"?" skillsFlashInvalid":""}`;return C.jsxs("main",{className:Re,children:[C.jsx(pke,{players:Te,gameState:Vt,roomId:e||D||"",meId:KA||"",endAt:i??void 0,isRoundActive:Ki,scores:w,hideAvatars:Ke,singlePlayer:!ge,campaignProgress:hA}),C.jsx("div",{className:"skillsBody",children:C.jsxs("div",{className:"skillsContainer",children:[!G&&C.jsx(ike,{onRetry:()=>PmA()}),Ke&&C.jsx(z0e,{isMultiplayer:ge,activeGameMode:_e,selectedStake:P,setSelectedStake:tA,selectedDuration:iA,setSelectedDuration:oA,myBalance:WA,stakeError:IA,hasStarted:Z,onStart:Zi,onShowHelp:()=>le(!0),isAuthenticated:!xe,onLogin:it,isAdEnabled:h,roomStake:T==null?void 0:T.stake,roomDuration:T==null?void 0:T.duration,spLevel:xA??(l==null?void 0:l.spLevelSkills),spLevelName:jA,winStreak:cA,dailyChallenge:rA}),Je&&C.jsx(eke,{readyCount:pt,totalPlayers:Tt}),aA!==null&&C.jsx(Ake,{countdown:aA}),pA&&C.jsx(tke,{message:pA}),fi&&C.jsx("section",{className:"card gridCard",children:C.jsx(TmA,{letters:ysA(Bi),onSubmit:OA,onTap:Ae,disabled:!Ki||K||k,feedback:RA,shakeKey:W,botTrail:jt})}),fi&&(Mg.length>0||Hg.length>0)&&C.jsxs("div",{className:"foundWordsList",children:[Mg.length>0&&C.jsxs("div",{className:"foundWordsColumn foundWordsColumn--me",children:[C.jsx("span",{className:"foundWordsLabel",children:"You"}),C.jsx("div",{className:"foundWordsTags",children:Mg.map(ee=>C.jsx("span",{className:"foundWordTag foundWordTag--me",children:ee},ee))})]}),Hg.length>0&&C.jsxs("div",{className:"foundWordsColumn foundWordsColumn--opp",children:[C.jsx("span",{className:"foundWordsLabel",children:HA}),C.jsx("div",{className:"foundWordsTags",children:Hg.map(ee=>C.jsx("span",{className:"foundWordTag foundWordTag--opp",children:ee},ee))})]})]}),Yi&&mt&&C.jsx(J0e,{letters:mt,foundWords:me,onSubmit:de,disabled:!Ki||K,myScore:ve}),si&&ct&&C.jsx(L0e,{questions:ct,currentQuestionIndex:$e,onAnswer:qe,myAnswers:ke,disabled:!Ki||K,myScore:ve}),K&&C.jsx($0e,{myScore:ve,players:Te,scores:w,winnerId:q,iWon:vt,isDraw:ei,winnings:_A,selectedStake:P,isMultiplayer:ge,roundSummary:PA,meId:KA,winStreak:X,isAdEnabled:h,spLevel:xA??(l==null?void 0:l.spLevelSkills),spLevelName:jA,onPlayAgain:te})]})}),C.jsx(q0e,{open:Ze||he,onClose:()=>{at(),le(!1)},gameMode:_e}),FA&&C.jsx(bZ,{show:!0,contained:!0,variant:FA.variant,displayMs:FA.displayMs,zoomDurationMs:FA.zoomDurationMs,fadeDurationMs:FA.fadeDurationMs,ariaLabel:FA.ariaLabel,onComplete:DA})]})}function fke({startAt:e,endAt:A,driftMs:t=0}){const[i,n]=E.useState(()=>Date.now());E.useEffect(()=>{const a=setInterval(()=>n(Date.now()),100);return()=>clearInterval(a)},[]);const g=E.useMemo(()=>A?Math.max(0,A-(i+t)):0,[i,A,t]),o=Math.ceil(g/1e3),s=o<=10?"text-red-500":o<=20?"text-yellow-500":"text-casino-gold";return C.jsxs("div",{"aria-live":"polite",className:`text-3xl font-bold ${s} transition-colors duration-300 drop-shadow-lg`,children:[o,"s"]})}function yke(e,A=8,t=8){let i=2166136261;for(const s of e)i=(i^s.charCodeAt(0))*16777619;const n=()=>((i=Math.imul(i^i>>>13,1274126177))>>>0)/2**32,g="EEEEAAAAIIONNRRTTLLSSUU DD GBCMP FHVWY KJX QZ".replace(/\s/g,""),o=()=>g[Math.floor(n()*g.length)]||"E";return Array.from({length:A},()=>Array.from({length:t},()=>o()))}function zmA(){var Z,eA,aA,sA,pA,gA,yA;const{roomId:e}=Qw(),A=qi(),{meId:t}=tn(),[i,n]=E.useState(null),[g,o]=E.useState(null),[s,a]=E.useState([]),[r,I]=E.useState([]),[c,l]=E.useState(!1),[B,Q]=E.useState(!0),[h,d]=E.useState(null),[p,y]=E.useState(!1),[m,D]=E.useState(null),{skillsSpectatorJoin:S,skillsSpectatorLeave:k}=Mo(),N=E.useRef(!1);Os({onSkillsSpectatorState:fA=>{var RA,qA;console.log("[spectator] Got initial state:",fA),fA.roomId===e&&(n(fA.room),o(fA.gameState),a(((RA=fA.room)==null?void 0:RA.players)||[]),I(((qA=fA.room)==null?void 0:qA.spectators)||[]),l(fA.isSpectator??!0),Q(!1),d(null))},onSkillsSpectatorUpdate:fA=>{console.log("[spectator] Got update:",fA),fA.roomId===e&&(o(fA.gameState),fA.players&&a(fA.players),fA.spectators&&I(fA.spectators))},onSkillsSpectatorJoined:fA=>{console.log("[spectator] Spectator joined:",fA),fA.roomId===e&&fA.spectator&&!r.find(RA=>RA.id===fA.spectator.id)&&I(RA=>[...RA,fA.spectator])},onSkillsSpectatorLeft:fA=>{console.log("[spectator] Spectator left:",fA),fA.roomId===e&&I(RA=>RA.filter(qA=>qA.id!==fA.spectatorId))},onSkillsScoreUpdate:fA=>{fA.roomId===e&&o(RA=>RA&&{...RA,scores:fA.scores})},onSkillsRoundEnd:fA=>{fA.roomId===e&&(y(!0),fA.winnerId&&D(fA.winnerId),fA.scores&&o(RA=>RA&&{...RA,scores:fA.scores,phase:"finished"}))},onSkillsRoundStart:fA=>{fA.roomId===e&&(y(!1),D(null),o(RA=>RA&&{...RA,phase:"playing",seed:fA.seed,startAt:fA.startAt,endAt:fA.endAt,scores:{}}))}}),E.useEffect(()=>{if(!(!e||N.current))return N.current=!0,console.log("[spectator] Joining room:",e),S(e).then(fA=>{console.log("[spectator] Join response:",fA),fA.ok||(d(fA.error||"Failed to join as spectator"),Q(!1))}).catch(fA=>{console.error("[spectator] Join error:",fA),d("Failed to join as spectator"),Q(!1)}),()=>{console.log("[spectator] Leaving room:",e),k(e),N.current=!1}},[e,S,k]);const G=E.useMemo(()=>g!=null&&g.seed?yke(g.seed):null,[g==null?void 0:g.seed]),M=s[0],w=s[1],b=M?(g==null?void 0:g.scores[M.id])??0:0,_=w?(g==null?void 0:g.scores[w.id])??0:0,K=((Z=g==null?void 0:g.wordsearchData)==null?void 0:Z.foundWords[M==null?void 0:M.id])||((eA=g==null?void 0:g.anagramsData)==null?void 0:eA.foundWords[M==null?void 0:M.id])||[],J=((aA=g==null?void 0:g.wordsearchData)==null?void 0:aA.foundWords[w==null?void 0:w.id])||((sA=g==null?void 0:g.anagramsData)==null?void 0:sA.foundWords[w==null?void 0:w.id])||[],q=((pA=g==null?void 0:g.triviaData)==null?void 0:pA.playerAnswers[M==null?void 0:M.id])||{},v=((gA=g==null?void 0:g.triviaData)==null?void 0:gA.playerAnswers[w==null?void 0:w.id])||{},U=(g==null?void 0:g.gameMode)||"wordsearch",x=(g==null?void 0:g.phase)==="playing",T=(g==null?void 0:g.phase)==="waiting",z=(g==null?void 0:g.phase)==="finished"||p;return B?C.jsxs("div",{className:"skills-spectate-loading",children:[C.jsx("div",{className:"skills-loading-spinner"}),C.jsx("p",{children:"Joining as spectator..."})]}):h?C.jsxs("div",{className:"skills-spectate-error",children:[C.jsx("h2",{children:"Unable to Spectate"}),C.jsx("p",{children:h}),C.jsx("button",{onClick:()=>A("/lobby"),children:"Return to Lobby"})]}):C.jsxs("div",{className:"skills-spectate-container",children:[C.jsxs("div",{className:"skills-spectate-header",children:[C.jsxs("div",{className:"spectator-badge",children:[C.jsx("span",{className:"spectator-icon",children:"👁️"}),C.jsx("span",{children:"Spectating"})]}),C.jsx("button",{className:"spectate-leave-btn",onClick:()=>A("/lobby"),children:"Leave"})]}),r.length>0&&C.jsxs("div",{className:"spectator-count",children:[r.length," spectator",r.length!==1?"s":""," watching"]}),T&&C.jsx("div",{className:"skills-spectate-waiting",children:C.jsx("h3",{children:"Waiting for players to ready up..."})}),x&&(g==null?void 0:g.endAt)&&C.jsx("div",{className:"skills-spectate-timer",children:C.jsx(fke,{endAt:g.endAt})}),C.jsxs("div",{className:"skills-spectate-players",children:[C.jsxs("div",{className:"skills-spectate-player player-1",children:[C.jsxs("div",{className:"spectator-player-info",children:[C.jsx("span",{className:"spectator-player-name",children:(M==null?void 0:M.name)||"Player 1"}),C.jsxs("span",{className:"spectator-player-score",children:[b," pts"]})]}),(U==="wordsearch"||U==="anagrams")&&K.length>0&&C.jsxs("div",{className:"spectator-words",children:[C.jsxs("h4",{children:["Words Found: ",K.length]}),C.jsx("div",{className:"words-list",children:K.slice(-5).map((fA,RA)=>C.jsx("span",{className:"found-word",children:fA},RA))})]}),U==="trivia"&&C.jsx("div",{className:"spectator-trivia-progress",children:C.jsxs("span",{children:["Questions answered: ",Object.keys(q).length]})})]}),C.jsxs("div",{className:"skills-spectate-center",children:[U==="wordsearch"&&G&&x&&C.jsx("div",{className:"spectator-grid",children:C.jsx(TmA,{letters:G,onSubmit:()=>{},disabled:!0,cellSize:40})}),U==="anagrams"&&(g==null?void 0:g.anagramsData)&&x&&C.jsx("div",{className:"spectator-anagrams",children:C.jsx("div",{className:"anagram-letters",children:g.anagramsData.letters.map((fA,RA)=>C.jsx("span",{className:"letter-tile",children:fA},RA))})}),U==="trivia"&&(g==null?void 0:g.triviaData)&&x&&C.jsx("div",{className:"spectator-trivia",children:C.jsxs("div",{className:"trivia-question",children:[C.jsxs("span",{className:"question-number",children:["Q",g.triviaData.currentQuestion+1," / ",g.triviaData.questions.length]}),C.jsx("p",{children:(yA=g.triviaData.questions[g.triviaData.currentQuestion])==null?void 0:yA.question})]})}),z&&C.jsxs("div",{className:"spectator-result",children:[C.jsxs("h2",{children:[m===(M==null?void 0:M.id)?M==null?void 0:M.name:w==null?void 0:w.name," Wins!"]}),C.jsxs("div",{className:"final-scores",children:[C.jsxs("span",{children:[M==null?void 0:M.name,": ",b]}),C.jsxs("span",{children:[w==null?void 0:w.name,": ",_]})]})]})]}),C.jsxs("div",{className:"skills-spectate-player player-2",children:[C.jsxs("div",{className:"spectator-player-info",children:[C.jsx("span",{className:"spectator-player-name",children:(w==null?void 0:w.name)||"Player 2"}),C.jsxs("span",{className:"spectator-player-score",children:[_," pts"]})]}),(U==="wordsearch"||U==="anagrams")&&J.length>0&&C.jsxs("div",{className:"spectator-words",children:[C.jsxs("h4",{children:["Words Found: ",J.length]}),C.jsx("div",{className:"words-list",children:J.slice(-5).map((fA,RA)=>C.jsx("span",{className:"found-word",children:fA},RA))})]}),U==="trivia"&&C.jsx("div",{className:"spectator-trivia-progress",children:C.jsxs("span",{children:["Questions answered: ",Object.keys(v).length]})})]})]}),C.jsxs("div",{className:"skills-spectate-mode",children:[U==="wordsearch"&&"🔤 Word Search",U==="anagrams"&&"🔠 Anagrams",U==="trivia"&&"❓ Trivia"]})]})}function Dke(){const e=qi(),A=ks();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),CI()},[e]),E.useEffect(()=>{CI(A.pathname)},[A.pathname]),E.useEffect(()=>{try{const t=A.pathname||"",i=t==="/lobby"||t==="/",n=/^\/skills\/(play|room)/.test(t)||/^\/room\//.test(t);(()=>{var s;try{return/^(capacitor:|ionic:)/i.test(((s=window.location)==null?void 0:s.protocol)||"")}catch{return!1}})()?(document.body.classList.add("is-native-app"),document.documentElement.classList.add("is-native-app")):(document.body.classList.remove("is-native-app"),document.documentElement.classList.remove("is-native-app")),document.body.classList.toggle("page-home-screen",i),document.body.classList.toggle("page-gameroom",n);const o=document.documentElement;if(i||n){o.style.setProperty("overflow","hidden","important"),document.body.style.setProperty("overflow","hidden","important"),o.style.setProperty("overscroll-behavior","none","important"),document.body.style.setProperty("overscroll-behavior","none","important"),o.style.setProperty("height","100svh","important"),document.body.style.setProperty("height","100svh","important");try{window.scrollTo({top:0,left:0,behavior:"instant"})}catch{}}else o.style.removeProperty("overflow"),document.body.style.removeProperty("overflow"),o.style.removeProperty("overscroll-behavior"),document.body.style.removeProperty("overscroll-behavior"),o.style.removeProperty("height"),document.body.style.removeProperty("height")}catch{}},[A.pathname]),C.jsxs(Uf,{children:[C.jsxs(fe,{element:C.jsx(Tf,{}),children:[C.jsx(fe,{path:"/verify",element:C.jsx(Zf,{})}),C.jsx(fe,{path:"/review-login",element:C.jsx(Wf,{})}),C.jsx(fe,{path:"/qa-login",element:C.jsx(Vf,{})}),C.jsx(fe,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(fe,{path:"/add-chips",element:C.jsx(zf,{})}),C.jsxs(fe,{element:C.jsx(vf,{}),children:[C.jsx(fe,{path:"/profile",element:C.jsx(Hf,{})}),C.jsx(fe,{path:"/player/:playerId",element:C.jsx(Of,{})}),C.jsx(fe,{path:"/messages",element:C.jsx(Pf,{})}),C.jsx(fe,{path:"/settings",element:C.jsx(jf,{})}),C.jsx(fe,{path:"/",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/lobby",element:C.jsx(xf,{})}),C.jsx(fe,{path:"/room/:roomId",element:C.jsx(VR,{})}),C.jsx(fe,{path:"/skills/play",element:C.jsx(TJ,{})}),C.jsx(fe,{path:"/skills/room/:roomId",element:C.jsx(TJ,{})}),C.jsx(fe,{path:"/skills/spectate/:roomId",element:C.jsx(zmA,{})})]}),C.jsx(fe,{path:"/disclaimer",element:C.jsx(Xf,{})}),C.jsx(fe,{path:"/support",element:C.jsx($f,{})}),C.jsx(fe,{path:"/privacy",element:C.jsx(Ay,{})}),C.jsx(fe,{path:"/terms",element:C.jsx(ey,{})}),C.jsx(fe,{path:"/how-to-play",element:C.jsx(vd,{defaultMode:"skills"})}),C.jsx(fe,{path:"*",element:C.jsx(Tg,{to:"/lobby",replace:!0})})]})}const mke=E.lazy(()=>Qi(()=>import("./BroadcasterLive-BqXW-2JL.js"),__vite__mapDeps([17,1,18]))),Ske=E.lazy(()=>Qi(()=>import("./TurretPreview-tL_lePQ9.js"),__vite__mapDeps([14,1])));E.lazy(()=>Qi(()=>import("./ShipPackPreview-C1SY9CLc.js"),__vite__mapDeps([15,1,16])));function wke(){const e=qi(),A=ks();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),CI()},[e]),E.useEffect(()=>{CI(A.pathname)},[A.pathname]),E.useEffect(()=>{try{const t=A.pathname||"",i=t==="/lobby",n=/^\/room\//.test(t)||/^\/poker\/room\//.test(t);(()=>{var s;try{return/^(capacitor:|ionic:)/i.test(((s=window.location)==null?void 0:s.protocol)||"")}catch{return!1}})()?(document.body.classList.add("is-native-app"),document.documentElement.classList.add("is-native-app")):(document.body.classList.remove("is-native-app"),document.documentElement.classList.remove("is-native-app")),document.body.classList.toggle("page-home-screen",i),document.body.classList.toggle("page-gameroom",n);const o=document.documentElement;if(i||n){o.style.setProperty("overflow","hidden","important"),document.body.style.setProperty("overflow","hidden","important"),o.style.setProperty("overscroll-behavior","none","important"),document.body.style.setProperty("overscroll-behavior","none","important"),o.style.setProperty("height","100svh","important"),document.body.style.setProperty("height","100svh","important");try{window.scrollTo({top:0,left:0,behavior:"instant"})}catch{}}else o.style.removeProperty("overflow"),document.body.style.removeProperty("overflow"),o.style.removeProperty("overscroll-behavior"),document.body.style.removeProperty("overscroll-behavior"),o.style.removeProperty("height"),document.body.style.removeProperty("height")}catch{}},[A.pathname]),C.jsxs(Uf,{children:[C.jsxs(fe,{element:C.jsx(Tf,{}),children:[C.jsx(fe,{path:"/verify",element:C.jsx(Zf,{})}),C.jsx(fe,{path:"/review-login",element:C.jsx(Wf,{})}),C.jsx(fe,{path:"/qa-login",element:C.jsx(Vf,{})}),C.jsx(fe,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(fe,{path:"/add-chips",element:C.jsx(zf,{})}),C.jsxs(fe,{element:C.jsx(vf,{}),children:[C.jsx(fe,{path:"/profile",element:C.jsx(Hf,{})}),C.jsx(fe,{path:"/player/:playerId",element:C.jsx(Of,{})}),C.jsx(fe,{path:"/messages",element:C.jsx(Pf,{})}),C.jsx(fe,{path:"/settings",element:C.jsx(jf,{})}),C.jsx(fe,{path:"/admin",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/broadcaster",element:C.jsx(E.Suspense,{fallback:null,children:C.jsx(mke,{})})}),C.jsx(fe,{path:"/",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/lobby",element:C.jsx(xf,{})}),C.jsx(fe,{path:"/room/:roomId",element:C.jsx(VR,{})}),C.jsx(fe,{path:"/poker",element:C.jsx(JZ,{})}),C.jsx(fe,{path:"/poker/mock",element:C.jsx(LZ,{})}),C.jsx(fe,{path:"/poker/room/:roomId",element:C.jsx(_Z,{})}),C.jsx(fe,{path:"/skills/play",element:C.jsx(TJ,{})}),C.jsx(fe,{path:"/skills/room/:roomId",element:C.jsx(TJ,{})}),C.jsx(fe,{path:"/skills/spectate/:roomId",element:C.jsx(zmA,{})}),C.jsx(fe,{path:"/zentara",element:C.jsx(Tg,{to:"/",replace:!0})}),C.jsx(fe,{path:"/zentara/match/:matchId",element:C.jsx(XS,{})}),C.jsx(fe,{path:"/zentara/room/:roomId",element:C.jsx(XS,{})})]}),C.jsx(fe,{path:"/disclaimer",element:C.jsx(Xf,{})}),C.jsx(fe,{path:"/support",element:C.jsx($f,{})}),C.jsx(fe,{path:"/privacy",element:C.jsx(Ay,{})}),C.jsx(fe,{path:"/terms",element:C.jsx(ey,{})}),C.jsx(fe,{path:"/button-sandbox",element:C.jsx(XR,{})}),C.jsx(fe,{path:"/how-to-play",element:C.jsx(vd,{})}),C.jsx(fe,{path:"/turret-preview",element:C.jsx(E.Suspense,{fallback:null,children:C.jsx(Ske,{})})}),C.jsx(fe,{path:"/ship-pack-preview",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"*",element:C.jsx(Tg,{to:"/lobby",replace:!0})})]})}const kke=E.lazy(()=>Qi(()=>import("./BroadcasterLive-BqXW-2JL.js"),__vite__mapDeps([17,1,18]))),Mke=E.lazy(()=>Qi(()=>import("./TurretPreview-tL_lePQ9.js"),__vite__mapDeps([14,1])));E.lazy(()=>Qi(()=>import("./ShipPackPreview-C1SY9CLc.js"),__vite__mapDeps([15,1,16])));function Nke(){const e=qi(),A=ks();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),CI()},[e]),E.useEffect(()=>{CI(A.pathname)},[A.pathname]),E.useEffect(()=>{try{const t=A.pathname||"",i=t==="/lobby",n=/^\/match\//.test(t);(()=>{var s;try{return/^(capacitor:|ionic:)/i.test(((s=window.location)==null?void 0:s.protocol)||"")}catch{return!1}})()?(document.body.classList.add("is-native-app"),document.documentElement.classList.add("is-native-app")):(document.body.classList.remove("is-native-app"),document.documentElement.classList.remove("is-native-app")),document.body.classList.toggle("page-home-screen",i),document.body.classList.toggle("page-gameroom",n);const o=document.documentElement;if(i||n){o.style.setProperty("overflow","hidden","important"),document.body.style.setProperty("overflow","hidden","important"),o.style.setProperty("overscroll-behavior","none","important"),document.body.style.setProperty("overscroll-behavior","none","important"),o.style.setProperty("height","100svh","important"),document.body.style.setProperty("height","100svh","important");try{window.scrollTo({top:0,left:0,behavior:"instant"})}catch{}}else o.style.removeProperty("overflow"),document.body.style.removeProperty("overflow"),o.style.removeProperty("overscroll-behavior"),document.body.style.removeProperty("overscroll-behavior"),o.style.removeProperty("height"),document.body.style.removeProperty("height")}catch{}},[A.pathname]),C.jsxs(Uf,{children:[C.jsxs(fe,{element:C.jsx(Tf,{}),children:[C.jsx(fe,{path:"/verify",element:C.jsx(Zf,{})}),C.jsx(fe,{path:"/review-login",element:C.jsx(Wf,{})}),C.jsx(fe,{path:"/qa-login",element:C.jsx(Vf,{})}),C.jsx(fe,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(fe,{path:"/add-chips",element:C.jsx(zf,{})}),C.jsxs(fe,{element:C.jsx(vf,{}),children:[C.jsx(fe,{path:"/profile",element:C.jsx(Hf,{})}),C.jsx(fe,{path:"/player/:playerId",element:C.jsx(Of,{})}),C.jsx(fe,{path:"/messages",element:C.jsx(Pf,{})}),C.jsx(fe,{path:"/settings",element:C.jsx(jf,{})}),C.jsx(fe,{path:"/admin",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/broadcaster",element:C.jsx(E.Suspense,{fallback:null,children:C.jsx(kke,{})})}),C.jsx(fe,{path:"/",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"/lobby",element:C.jsx(xf,{})}),C.jsx(fe,{path:"/zentara/match/:matchId",element:C.jsx(XS,{})}),C.jsx(fe,{path:"/zentara/room/:roomId",element:C.jsx(XS,{})})]}),C.jsx(fe,{path:"/disclaimer",element:C.jsx(Xf,{})}),C.jsx(fe,{path:"/support",element:C.jsx($f,{})}),C.jsx(fe,{path:"/privacy",element:C.jsx(Ay,{})}),C.jsx(fe,{path:"/terms",element:C.jsx(ey,{})}),C.jsx(fe,{path:"/how-to-play",element:C.jsx(vd,{})}),C.jsx(fe,{path:"/turret-preview",element:C.jsx(E.Suspense,{fallback:null,children:C.jsx(Mke,{})})}),C.jsx(fe,{path:"/ship-pack-preview",element:C.jsx(Tg,{to:"/lobby",replace:!0})}),C.jsx(fe,{path:"*",element:C.jsx(Tg,{to:"/lobby",replace:!0})})]})}const Rke="ceelolounge",RsA=yGA.toLowerCase(),Gke=new Set(["","verify","auth","ceelolounge","review-login","qa-login"]);function UO(e){return!e||e.length===0||e.length>2048||!/^[A-Za-z0-9._-]+$/.test(e)?null:e}function bke(e){try{const A=new URL(e),t=A.protocol.replace(":","").toLowerCase(),i=(A.hostname||"").toLowerCase(),n=(A.pathname||"").toLowerCase(),g=t===Rke,o=A.protocol==="https:",s=n.endsWith("/verify")||n.includes("/auth/verify"),a=n.endsWith("/review-login")||n.includes("/review-login"),r=n.endsWith("/qa-login")||n.includes("/qa-login");if(g){if(!Gke.has(i)||!s&&!a&&!r&&!(i==="verify"||i==="review-login"||i==="qa-login")&&!((i===""||i==="ceelolounge")&&(n==="/"||n==="")))return null}else if(o){if(RsA&&i!==RsA||!s&&!a&&!r)return null}else return null;const I=UO(A.searchParams.get("token"));if(I)return I;const c=n.split("/").filter(Boolean),l=c.lastIndexOf("verify");return l>=0&&c[l+1]?UO(c[l+1]):c.length===1&&!["verify","auth","review-login","qa-login"].includes(c[0])?UO(c[0]):null}catch{return null}}function Uke(){const e=qi(),A=E.useRef(null);return E.useEffect(()=>{let t;const i=n=>{if(!n||A.current===n)return;const g=bke(n);if(!g){console.warn("Deep link ignored (not allowed or missing token)");return}A.current=n;try{const o=new URL(n),s=(o.pathname||"").toLowerCase(),a=(o.hostname||"").toLowerCase(),r=s.includes("/review-login")||a==="review-login"?"/review-login":s.includes("/qa-login")||a==="qa-login"?"/qa-login":"/verify";e(`${r}?token=${encodeURIComponent(g)}`,{replace:!0})}catch{e(`/verify?token=${encodeURIComponent(g)}`,{replace:!0})}};return Nr.getLaunchUrl().then(n=>i(n==null?void 0:n.url)).catch(()=>{}),(async()=>t=await Nr.addListener("appUrlOpen",({url:n})=>i(n)))(),()=>{var n;return(n=t==null?void 0:t.remove)==null?void 0:n.call(t)}},[e]),null}const ZmA="dl_invited_by_v1",WmA="dl_invited_by_ts_v1",K4=/^[A-Za-z0-9_-]{16,64}$/;function GsA(e,A){try{window.localStorage.setItem(e,A)}catch{}}function bsA(e){try{window.localStorage.removeItem(e)}catch{}}function F4(e){!e||!K4.test(e)||(GsA(ZmA,e),GsA(WmA,String(Date.now())))}function vke(){bsA(ZmA),bsA(WmA)}function VmA(){try{const e=new URL(window.location.href),A=e.searchParams.get("inviter");if(A&&K4.test(A))return F4(A),A;const t=e.pathname.match(/(?:^|\/)i\/([^/?#]+)/i);if(t&&t[1]&&K4.test(t[1]))return F4(t[1]),t[1]}catch{}return null}const Kke=Object.freeze(Object.defineProperty({__proto__:null,captureInviterFromLocation:VmA,clearInviter:vke,rememberInviter:F4},Symbol.toStringTag,{value:"Module"}));function Fke(e){switch(e.errorCode||""){case"UNAUTHORIZED":return{title:"Sign In Required",subtitle:"You must be logged in to bet."};case"BET_INVALID":return{title:"Invalid Bet",subtitle:e.error||"Bet not allowed."};case"BET_REJECTED":return{title:"Bet Rejected",subtitle:e.error||"Try a smaller amount."};case"LINE_LOCKED":return{title:"Line Locked",subtitle:"Pass/Don't Pass locked after point."};case"BALANCE_ADJUST_FAIL":return{title:"Balance Error",subtitle:"Could not adjust balance."};default:return{title:"Bet Error",subtitle:e.error||"Unable to place bet."}}}function _ke(){const{info:e}=Jr();return Os({onCrapsBetError:A=>{try{const{title:t,subtitle:i}=Fke(A);e(t,i)}catch{}}}),null}function UV(e,{strict:A=!0}={}){return!e||typeof e!="string"?!1:A?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function UsA(e){return UV(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const XmA="2.37.9";let ik={getDocsUrl:({docsBaseUrl:e,docsPath:A="",docsSlug:t})=>A?`${e??"https://viem.sh"}${A}${t?`#${t}`:""}`:void 0,version:`viem@${XmA}`},cl=class _4 extends Error{constructor(A,t={}){var s;const i=(()=>{var a;return t.cause instanceof _4?t.cause.details:(a=t.cause)!=null&&a.message?t.cause.message:t.details})(),n=t.cause instanceof _4&&t.cause.docsPath||t.docsPath,g=(s=ik.getDocsUrl)==null?void 0:s.call(ik,{...t,docsPath:n}),o=[A||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...g?[`Docs: ${g}`]:[],...i?[`Details: ${i}`]:[],...ik.version?[`Version: ${ik.version}`]:[]].join(`
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=n,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=A,this.version=XmA}walk(A){return $mA(this,A)}};function $mA(e,A){return A!=null&&A(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?$mA(e.cause,A):A?null:e}class Jke extends cl{constructor({address:A}){super(`Address "${A}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class ASA extends cl{constructor({size:A,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${A}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Yw(e,{dir:A,size:t=32}={}){return typeof e=="string"?Lke(e,{dir:A,size:t}):xke(e,{dir:A,size:t})}function Lke(e,{dir:A,size:t=32}={}){if(t===null)return e;const i=e.replace("0x","");if(i.length>t*2)throw new ASA({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[A==="right"?"padEnd":"padStart"](t*2,"0")}`}function xke(e,{dir:A,size:t=32}={}){if(t===null)return e;if(e.length>t)throw new ASA({size:e.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let n=0;n<t;n++){const g=A==="right";i[g?n:t-n-1]=e[g?n:e.length-n-1]}return i}class Tke extends cl{constructor({max:A,min:t,signed:i,size:n,value:g}){super(`Number "${g}" is not in safe ${n?`${n*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${A?`(${t} to ${A})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class qke extends cl{constructor({givenSize:A,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${A} bytes.`,{name:"SizeOverflowError"})}}function uG(e,{size:A}){if(UsA(e)>A)throw new qke({givenSize:UsA(e),maxSize:A})}const Yke=Array.from({length:256},(e,A)=>A.toString(16).padStart(2,"0"));function xGe(e,A={}){return typeof e=="number"||typeof e=="bigint"?$S(e,A):typeof e=="string"?tSA(e,A):typeof e=="boolean"?Hke(e,A):eSA(e,A)}function Hke(e,A={}){const t=`0x${Number(e)}`;return typeof A.size=="number"?(uG(t,{size:A.size}),Yw(t,{size:A.size})):t}function eSA(e,A={}){let t="";for(let n=0;n<e.length;n++)t+=Yke[e[n]];const i=`0x${t}`;return typeof A.size=="number"?(uG(i,{size:A.size}),Yw(i,{dir:"right",size:A.size})):i}function $S(e,A={}){const{signed:t,size:i}=A,n=BigInt(e);let g;i?t?g=(1n<<BigInt(i)*8n-1n)-1n:g=2n**(BigInt(i)*8n)-1n:typeof e=="number"&&(g=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof g=="bigint"&&t?-g-1n:0;if(g&&n>g||n<o){const a=typeof e=="bigint"?"n":"";throw new Tke({max:g?`${g}${a}`:void 0,min:`${o}${a}`,signed:t,size:i,value:`${e}${a}`})}const s=`0x${(t&&n<0?(1n<<BigInt(i*8))+BigInt(n):n).toString(16)}`;return i?Yw(s,{size:i}):s}const Oke=new TextEncoder;function tSA(e,A={}){const t=Oke.encode(e);return eSA(t,A)}const Pke=new TextEncoder;function jke(e,A={}){return typeof e=="number"||typeof e=="bigint"?Zke(e,A):typeof e=="boolean"?zke(e,A):UV(e)?iSA(e,A):nSA(e,A)}function zke(e,A={}){const t=new Uint8Array(1);return t[0]=Number(e),typeof A.size=="number"?(uG(t,{size:A.size}),Yw(t,{size:A.size})):t}const oE={zero:48,nine:57,A:65,F:70,a:97,f:102};function vsA(e){if(e>=oE.zero&&e<=oE.nine)return e-oE.zero;if(e>=oE.A&&e<=oE.F)return e-(oE.A-10);if(e>=oE.a&&e<=oE.f)return e-(oE.a-10)}function iSA(e,A={}){let t=e;A.size&&(uG(t,{size:A.size}),t=Yw(t,{dir:"right",size:A.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const n=i.length/2,g=new Uint8Array(n);for(let o=0,s=0;o<n;o++){const a=vsA(i.charCodeAt(s++)),r=vsA(i.charCodeAt(s++));if(a===void 0||r===void 0)throw new cl(`Invalid byte sequence ("${i[s-2]}${i[s-1]}" in "${i}").`);g[o]=a*16+r}return g}function Zke(e,A){const t=$S(e,A);return iSA(t)}function nSA(e,A={}){const t=Pke.encode(e);return typeof A.size=="number"?(uG(t,{size:A.size}),Yw(t,{dir:"right",size:A.size})):t}const Nv=BigInt(2**32-1),KsA=BigInt(32);function Wke(e,A=!1){return A?{h:Number(e&Nv),l:Number(e>>KsA&Nv)}:{h:Number(e>>KsA&Nv)|0,l:Number(e&Nv)|0}}function Vke(e,A=!1){const t=e.length;let i=new Uint32Array(t),n=new Uint32Array(t);for(let g=0;g<t;g++){const{h:o,l:s}=Wke(e[g],A);[i[g],n[g]]=[o,s]}return[i,n]}const Xke=(e,A,t)=>e<<t|A>>>32-t,$ke=(e,A,t)=>A<<t|e>>>32-t,AMe=(e,A,t)=>A<<t-32|e>>>64-t,eMe=(e,A,t)=>e<<t-32|A>>>64-t;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function tMe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function FsA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function qJ(e,...A){if(!tMe(e))throw new Error("Uint8Array expected");if(A.length>0&&!A.includes(e.length))throw new Error("Uint8Array expected of length "+A+", got length="+e.length)}function _sA(e,A=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(A&&e.finished)throw new Error("Hash#digest() has already been called")}function iMe(e,A){qJ(e);const t=A.outputLen;if(e.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function nMe(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function gSA(...e){for(let A=0;A<e.length;A++)e[A].fill(0)}const gMe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function oMe(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function sMe(e){for(let A=0;A<e.length;A++)e[A]=oMe(e[A]);return e}const JsA=gMe?e=>e:sMe;function aMe(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function oSA(e){return typeof e=="string"&&(e=aMe(e)),qJ(e),e}class rMe{}function IMe(e){const A=i=>e().update(oSA(i)).digest(),t=e();return A.outputLen=t.outputLen,A.blockLen=t.blockLen,A.create=()=>e(),A}const CMe=BigInt(0),nk=BigInt(1),cMe=BigInt(2),lMe=BigInt(7),BMe=BigInt(256),EMe=BigInt(113),sSA=[],aSA=[],rSA=[];for(let e=0,A=nk,t=1,i=0;e<24;e++){[t,i]=[i,(2*t+3*i)%5],sSA.push(2*(5*i+t)),aSA.push((e+1)*(e+2)/2%64);let n=CMe;for(let g=0;g<7;g++)A=(A<<nk^(A>>lMe)*EMe)%BMe,A&cMe&&(n^=nk<<(nk<<BigInt(g))-nk);rSA.push(n)}const ISA=Vke(rSA,!0),QMe=ISA[0],uMe=ISA[1],LsA=(e,A,t)=>t>32?AMe(e,A,t):Xke(e,A,t),xsA=(e,A,t)=>t>32?eMe(e,A,t):$ke(e,A,t);function dMe(e,A=24){const t=new Uint32Array(10);for(let i=24-A;i<24;i++){for(let o=0;o<10;o++)t[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){const s=(o+8)%10,a=(o+2)%10,r=t[a],I=t[a+1],c=LsA(r,I,1)^t[s],l=xsA(r,I,1)^t[s+1];for(let B=0;B<50;B+=10)e[o+B]^=c,e[o+B+1]^=l}let n=e[2],g=e[3];for(let o=0;o<24;o++){const s=aSA[o],a=LsA(n,g,s),r=xsA(n,g,s),I=sSA[o];n=e[I],g=e[I+1],e[I]=a,e[I+1]=r}for(let o=0;o<50;o+=10){for(let s=0;s<10;s++)t[s]=e[o+s];for(let s=0;s<10;s++)e[o+s]^=~t[(s+2)%10]&t[(s+4)%10]}e[0]^=QMe[i],e[1]^=uMe[i]}gSA(t)}class vV extends rMe{constructor(A,t,i,n=!1,g=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=A,this.suffix=t,this.outputLen=i,this.enableXOF=n,this.rounds=g,FsA(i),!(0<A&&A<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=nMe(this.state)}clone(){return this._cloneInto()}keccak(){JsA(this.state32),dMe(this.state32,this.rounds),JsA(this.state32),this.posOut=0,this.pos=0}update(A){_sA(this),A=oSA(A),qJ(A);const{blockLen:t,state:i}=this,n=A.length;for(let g=0;g<n;){const o=Math.min(t-this.pos,n-g);for(let s=0;s<o;s++)i[this.pos++]^=A[g++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:A,suffix:t,pos:i,blockLen:n}=this;A[i]^=t,t&128&&i===n-1&&this.keccak(),A[n-1]^=128,this.keccak()}writeInto(A){_sA(this,!1),qJ(A),this.finish();const t=this.state,{blockLen:i}=this;for(let n=0,g=A.length;n<g;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,g-n);A.set(t.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return A}xofInto(A){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(A)}xof(A){return FsA(A),this.xofInto(new Uint8Array(A))}digestInto(A){if(iMe(A,this),this.finished)throw new Error("digest() was already called");return this.writeInto(A),this.destroy(),A}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,gSA(this.state)}_cloneInto(A){const{blockLen:t,suffix:i,outputLen:n,rounds:g,enableXOF:o}=this;return A||(A=new vV(t,i,n,o,g)),A.state32.set(this.state32),A.pos=this.pos,A.posOut=this.posOut,A.finished=this.finished,A.rounds=g,A.suffix=i,A.outputLen=n,A.enableXOF=o,A.destroyed=this.destroyed,A}}const hMe=(e,A,t)=>IMe(()=>new vV(A,e,t)),pMe=hMe(1,136,256/8);function fMe(e,A){return pMe(UV(e,{strict:!1})?jke(e):e)}class KV extends Map{constructor(A){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=A}get(A){const t=super.get(A);return super.has(A)&&t!==void 0&&(this.delete(A),super.set(A,t)),t}set(A,t){if(super.set(A,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const yMe=/^0x[a-fA-F0-9]{40}$/,vO=new KV(8192);function DMe(e,A){const{strict:t=!0}=A??{},i=`${e}.${t}`;if(vO.has(i))return vO.get(i);const n=yMe.test(e)?e.toLowerCase()===e?!0:t?CSA(e)===e:!0:!1;return vO.set(i,n),n}const KO=new KV(8192);function CSA(e,A){if(KO.has(`${e}.${A}`))return KO.get(`${e}.${A}`);const t=e.substring(2).toLowerCase(),i=fMe(nSA(t)),n=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&n[o]&&(n[o]=n[o].toUpperCase()),(i[o>>1]&15)>=8&&n[o+1]&&(n[o+1]=n[o+1].toUpperCase());const g=`0x${n.join("")}`;return KO.set(`${e}.${A}`,g),g}function fp(e,A){if(!DMe(e,{strict:!1}))throw new Jke({address:e});return CSA(e,A)}function mMe(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}const Zp=(e,A,t)=>JSON.stringify(e,(i,n)=>typeof n=="bigint"?n.toString():n,t),FV=e=>e;class bM extends cl{constructor({body:A,cause:t,details:i,headers:n,status:g,url:o}){super("HTTP request failed.",{cause:t,details:i,metaMessages:[g&&`Status: ${g}`,`URL: ${FV(o)}`,A&&`Request body: ${Zp(A)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=A,this.headers=n,this.status=g,this.url=o}}class cSA extends cl{constructor({body:A,error:t,url:i}){super("RPC Request failed.",{cause:t,details:t.message,metaMessages:[`URL: ${FV(i)}`,`Request body: ${Zp(A)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t.code,this.data=t.data}}class TsA extends cl{constructor({body:A,url:t}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${FV(t)}`,`Request body: ${Zp(A)}`],name:"TimeoutError"})}}const SMe=-1;class hI extends cl{constructor(A,{code:t,docsPath:i,metaMessages:n,name:g,shortMessage:o}){super(o,{cause:A,docsPath:i,metaMessages:n||(A==null?void 0:A.metaMessages),name:g||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=g||A.name,this.code=A instanceof cSA?A.code:t??SMe}}class aC extends hI{constructor(A,t){super(A,t),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t.data}}class YN extends hI{constructor(A){super(A,{code:YN.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(YN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class HN extends hI{constructor(A){super(A,{code:HN.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(HN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class ON extends hI{constructor(A,{method:t}={}){super(A,{code:ON.code,name:"MethodNotFoundRpcError",shortMessage:`The method${t?` "${t}"`:""} does not exist / is not available.`})}}Object.defineProperty(ON,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class PN extends hI{constructor(A){super(A,{code:PN.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
`)})}}Object.defineProperty(PN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Aw extends hI{constructor(A){super(A,{code:Aw.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Aw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class jN extends hI{constructor(A){super(A,{code:jN.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
`)})}}Object.defineProperty(jN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class zN extends hI{constructor(A){super(A,{code:zN.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(zN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class $u extends hI{constructor(A){super(A,{code:$u.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty($u,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class ZN extends hI{constructor(A){super(A,{code:ZN.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(ZN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class yp extends hI{constructor(A,{method:t}={}){super(A,{code:yp.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}}Object.defineProperty(yp,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class ew extends hI{constructor(A){super(A,{code:ew.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(ew,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class WN extends hI{constructor(A){super(A,{code:WN.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(WN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class _s extends aC{constructor(A){super(A,{code:_s.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(_s,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class VN extends aC{constructor(A){super(A,{code:VN.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(VN,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class XN extends aC{constructor(A,{method:t}={}){super(A,{code:XN.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}}Object.defineProperty(XN,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class $N extends aC{constructor(A){super(A,{code:$N.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty($N,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class AR extends aC{constructor(A){super(A,{code:AR.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(AR,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Dd extends aC{constructor(A){super(A,{code:Dd.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Dd,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class eR extends aC{constructor(A){super(A,{code:eR.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(eR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class tR extends aC{constructor(A){super(A,{code:tR.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(tR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class iR extends aC{constructor(A){super(A,{code:iR.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(iR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class nR extends aC{constructor(A){super(A,{code:nR.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(nR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class gR extends aC{constructor(A){super(A,{code:gR.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(gR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class oR extends aC{constructor(A){super(A,{code:oR.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(oR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class sR extends aC{constructor(A){super(A,{code:sR.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(sR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class wMe extends hI{constructor(A){super(A,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}function kMe(){let e=()=>{},A=()=>{};return{promise:new Promise((i,n)=>{e=i,A=n}),resolve:e,reject:A}}const FO=new Map;function MMe({fn:e,id:A,shouldSplitBatch:t,wait:i=0,sort:n}){const g=async()=>{const I=a();o();const c=I.map(({args:l})=>l);c.length!==0&&e(c).then(l=>{n&&Array.isArray(l)&&l.sort(n);for(let B=0;B<I.length;B++){const{resolve:Q}=I[B];Q==null||Q([l[B],l])}}).catch(l=>{for(let B=0;B<I.length;B++){const{reject:Q}=I[B];Q==null||Q(l)}})},o=()=>FO.delete(A),s=()=>a().map(({args:I})=>I),a=()=>FO.get(A)||[],r=I=>FO.set(A,[...a(),I]);return{flush:o,async schedule(I){const{promise:c,resolve:l,reject:B}=kMe();return(t==null?void 0:t([...s(),I]))&&g(),a().length>0?(r({args:I,resolve:l,reject:B}),c):(r({args:I,resolve:l,reject:B}),setTimeout(g,i),c)}}}const Rv=new KV(8192);function NMe(e,{enabled:A=!0,id:t}){if(!A||!t)return e();if(Rv.get(t))return Rv.get(t);const i=e().finally(()=>Rv.delete(t));return Rv.set(t,i),i}async function RMe(e){return new Promise(A=>setTimeout(A,e))}function lSA(e,{delay:A=100,retryCount:t=2,shouldRetry:i=()=>!0}={}){return new Promise((n,g)=>{const o=async({count:s=0}={})=>{const a=async({error:r})=>{const I=typeof A=="function"?A({count:s,error:r}):A;I&&await RMe(I),o({count:s+1})};try{const r=await e();n(r)}catch(r){if(s<t&&await i({count:s,error:r}))return a({error:r});g(r)}};o()})}function GMe(e,A={}){return async(t,i={})=>{var c;const{dedupe:n=!1,methods:g,retryDelay:o=150,retryCount:s=3,uid:a}={...A,...i},{method:r}=t;if((c=g==null?void 0:g.exclude)!=null&&c.includes(r))throw new yp(new Error("method not supported"),{method:r});if(g!=null&&g.include&&!g.include.includes(r))throw new yp(new Error("method not supported"),{method:r});const I=n?tSA(`${a}.${Zp(t)}`):void 0;return NMe(()=>lSA(async()=>{try{return await e(t)}catch(l){const B=l;switch(B.code){case YN.code:throw new YN(B);case HN.code:throw new HN(B);case ON.code:throw new ON(B,{method:t.method});case PN.code:throw new PN(B);case Aw.code:throw new Aw(B);case jN.code:throw new jN(B);case zN.code:throw new zN(B);case $u.code:throw new $u(B);case ZN.code:throw new ZN(B);case yp.code:throw new yp(B,{method:t.method});case ew.code:throw new ew(B);case WN.code:throw new WN(B);case _s.code:throw new _s(B);case VN.code:throw new VN(B);case XN.code:throw new XN(B);case $N.code:throw new $N(B);case AR.code:throw new AR(B);case Dd.code:throw new Dd(B);case eR.code:throw new eR(B);case tR.code:throw new tR(B);case iR.code:throw new iR(B);case nR.code:throw new nR(B);case gR.code:throw new gR(B);case oR.code:throw new oR(B);case sR.code:throw new sR(B);case 5e3:throw new _s(B);default:throw l instanceof cl?l:new wMe(B)}}},{delay:({count:l,error:B})=>{var Q;if(B&&B instanceof bM){const h=(Q=B==null?void 0:B.headers)==null?void 0:Q.get("Retry-After");if(h!=null&&h.match(/\d/))return Number.parseInt(h,10)*1e3}return~~(1<<l)*o},retryCount:s,shouldRetry:({error:l})=>bMe(l)}),{enabled:n,id:I})}}function bMe(e){return"code"in e&&typeof e.code=="number"?e.code===-1||e.code===ew.code||e.code===Aw.code:e instanceof bM&&e.status?e.status===403||e.status===408||e.status===413||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504:!0}function BSA(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}function ESA(e,{errorInstance:A=new Error("timed out"),timeout:t,signal:i}){return new Promise((n,g)=>{(async()=>{let o;try{const s=new AbortController;t>0&&(o=setTimeout(()=>{i?s.abort():g(A)},t)),n(await e({signal:(s==null?void 0:s.signal)||null}))}catch(s){(s==null?void 0:s.name)==="AbortError"&&g(A),g(s)}finally{clearTimeout(o)}})()})}function UMe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const qsA=UMe();function vMe(e,A={}){return{async request(t){var l;const{body:i,fetchFn:n=A.fetchFn??fetch,onRequest:g=A.onRequest,onResponse:o=A.onResponse,timeout:s=A.timeout??1e4}=t,a={...A.fetchOptions??{},...t.fetchOptions??{}},{headers:r,method:I,signal:c}=a;try{const B=await ESA(async({signal:h})=>{const d={...a,body:Array.isArray(i)?Zp(i.map(D=>({jsonrpc:"2.0",id:D.id??qsA.take(),...D}))):Zp({jsonrpc:"2.0",id:i.id??qsA.take(),...i}),headers:{"Content-Type":"application/json",...r},method:I||"POST",signal:c||(s>0?h:null)},p=new Request(e,d),y=await(g==null?void 0:g(p,d))??{...d,url:e};return await n(y.url??e,y)},{errorInstance:new TsA({body:i,url:e}),timeout:s,signal:!0});o&&await o(B);let Q;if((l=B.headers.get("Content-Type"))!=null&&l.startsWith("application/json"))Q=await B.json();else{Q=await B.text();try{Q=JSON.parse(Q||"{}")}catch(h){if(B.ok)throw h;Q={error:Q}}}if(!B.ok)throw new bM({body:i,details:Zp(Q.error)||B.statusText,headers:B.headers,status:B.status,url:e});return Q}catch(B){throw B instanceof bM||B instanceof TsA?B:new bM({body:i,cause:B,url:e})}}}}const qK="2.21.2",KMe=()=>`@wagmi/core@${qK}`;var QSA=function(e,A,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof A=="function"?e!==A||!i:!A.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(e):i?i.value:A.get(e)},YJ,uSA;class aR extends Error{get docsBaseUrl(){return"https://wagmi.sh/core"}get version(){return KMe()}constructor(A,t={}){var g;super(),YJ.add(this),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"WagmiCoreError"});const i=t.cause instanceof aR?t.cause.details:(g=t.cause)!=null&&g.message?t.cause.message:t.details,n=t.cause instanceof aR&&t.cause.docsPath||t.docsPath;this.message=[A||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${this.docsBaseUrl}${n}.html${t.docsSlug?`#${t.docsSlug}`:""}`]:[],...i?[`Details: ${i}`]:[],`Version: ${this.version}`].join(`
`),t.cause&&(this.cause=t.cause),this.details=i,this.docsPath=n,this.metaMessages=t.metaMessages,this.shortMessage=A}walk(A){return QSA(this,YJ,"m",uSA).call(this,this,A)}}YJ=new WeakSet,uSA=function e(A,t){return t!=null&&t(A)?A:A.cause?QSA(this,YJ,"m",e).call(this,A.cause,t):A};class HJ extends aR{constructor(){super("Chain not configured."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ChainNotConfiguredError"})}}const J4=256;let Gv=J4,bv;function dSA(e=11){if(!bv||Gv+e>J4*2){bv="",Gv=0;for(let A=0;A<J4;A++)bv+=(256+Math.random()*256|0).toString(16).substring(1)}return bv.substring(Gv,Gv+++e)}function FMe(e){const{batch:A,chain:t,ccipRead:i,key:n="base",name:g="Base Client",type:o="base"}=e,s=e.experimental_blockTag??(typeof(t==null?void 0:t.experimental_preconfirmationTime)=="number"?"pending":void 0),a=(t==null?void 0:t.blockTime)??12e3,r=Math.min(Math.max(Math.floor(a/2),500),4e3),I=e.pollingInterval??r,c=e.cacheTime??I,l=e.account?mMe(e.account):void 0,{config:B,request:Q,value:h}=e.transport({chain:t,pollingInterval:I}),d={...B,...h},p={account:l,batch:A,cacheTime:c,ccipRead:i,chain:t,key:n,name:g,pollingInterval:I,request:Q,transport:d,type:o,uid:dSA(),...s?{experimental_blockTag:s}:{}};function y(m){return D=>{const S=D(m);for(const N in p)delete S[N];const k={...m,...S};return Object.assign(k,{extend:y(k)})}}return Object.assign(p,{extend:y(p)})}function _Me({key:e,methods:A,name:t,request:i,retryCount:n=3,retryDelay:g=150,timeout:o,type:s},a){const r=dSA();return{config:{key:e,methods:A,name:t,request:i,retryCount:n,retryDelay:g,timeout:o,type:s},request:GMe(i,{methods:A,retryCount:n,retryDelay:g,uid:r}),value:a}}class JMe extends cl{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function YsA(e,A={}){const{batch:t,fetchFn:i,fetchOptions:n,key:g="http",methods:o,name:s="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:r,retryDelay:I,raw:c}=A;return({chain:l,retryCount:B,timeout:Q})=>{const{batchSize:h=1e3,wait:d=0}=typeof t=="object"?t:{},p=A.retryCount??B,y=Q??A.timeout??1e4,m=e||(l==null?void 0:l.rpcUrls.default.http[0]);if(!m)throw new JMe;const D=vMe(m,{fetchFn:i,fetchOptions:n,onRequest:a,onResponse:r,timeout:y});return _Me({key:g,methods:o,name:s,async request({method:S,params:k}){const N={method:S,params:k},{schedule:G}=MMe({id:m,wait:d,shouldSplitBatch(_){return _.length>h},fn:_=>D.request({body:_}),sort:(_,K)=>_.id-K.id}),M=async _=>t?G(_):[await D.request({body:_})],[{error:w,result:b}]=await M(N);if(c)return{error:w,result:b};if(w)throw new cSA({body:N,error:w,url:m});return b},retryCount:p,retryDelay:I,timeout:y,type:"http"},{fetchOptions:n,url:m})}}let _O=!1;async function LMe(e,A={}){var r,I;if(_O)return[];_O=!0,e.setState(c=>({...c,status:c.current?"reconnecting":"connecting"}));const t=[];if((r=A.connectors)!=null&&r.length)for(const c of A.connectors){let l;typeof c=="function"?l=e._internal.connectors.setup(c):l=c,t.push(l)}else t.push(...e.connectors);let i;try{i=await((I=e.storage)==null?void 0:I.getItem("recentConnectorId"))}catch{}const n={};for(const[,c]of e.state.connections)n[c.connector.id]=1;i&&(n[i]=0);const g=Object.keys(n).length>0?[...t].sort((c,l)=>(n[c.id]??10)-(n[l.id]??10)):t;let o=!1;const s=[],a=[];for(const c of g){const l=await c.getProvider().catch(()=>{});if(!l||a.some(h=>h===l)||!await c.isAuthorized())continue;const Q=await c.connect({isReconnecting:!0}).catch(()=>null);Q&&(c.emitter.off("connect",e._internal.events.connect),c.emitter.on("change",e._internal.events.change),c.emitter.on("disconnect",e._internal.events.disconnect),e.setState(h=>{const d=new Map(o?h.connections:new Map).set(c.uid,{accounts:Q.accounts,chainId:Q.chainId,connector:c});return{...h,current:o?h.current:c.uid,connections:d}}),s.push({accounts:Q.accounts,chainId:Q.chainId,connector:c}),a.push(l),o=!0)}return(e.state.status==="reconnecting"||e.state.status==="connecting")&&(o?e.setState(c=>({...c,status:"connected"})):e.setState(c=>({...c,connections:new Map,current:null,status:"disconnected"}))),_O=!1,s}class tu extends aR{constructor(){super("Provider not found."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ProviderNotFoundError"})}}pT.type="injected";function pT(e={}){const{shimDisconnect:A=!0,unstable_shimAsyncInject:t}=e;function i(){const a=e.target;if(typeof a=="function"){const r=a();if(r)return r}return typeof a=="object"?a:typeof a=="string"?{...xMe[a]??{id:a,name:`${a[0].toUpperCase()}${a.slice(1)}`,provider:`is${a[0].toUpperCase()}${a.slice(1)}`}}:{id:"injected",name:"Injected",provider(r){return r==null?void 0:r.ethereum}}}let n,g,o,s;return a=>({get icon(){return i().icon},get id(){return i().id},get name(){return i().name},get supportsSimulation(){return!0},type:pT.type,async setup(){const r=await this.getProvider();r!=null&&r.on&&e.target&&(o||(o=this.onConnect.bind(this),r.on("connect",o)),n||(n=this.onAccountsChanged.bind(this),r.on("accountsChanged",n)))},async connect({chainId:r,isReconnecting:I,withCapabilities:c}={}){var Q,h,d,p,y,m;const l=await this.getProvider();if(!l)throw new tu;let B=[];if(I)B=await this.getAccounts().catch(()=>[]);else if(A)try{B=(p=(d=(h=(Q=(await l.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}))[0])==null?void 0:Q.caveats)==null?void 0:h[0])==null?void 0:d.value)==null?void 0:p.map(S=>fp(S)),B.length>0&&(B=await this.getAccounts())}catch(D){const S=D;if(S.code===_s.code)throw new _s(S);if(S.code===$u.code)throw S}try{!(B!=null&&B.length)&&!I&&(B=(await l.request({method:"eth_requestAccounts"})).map(k=>fp(k))),o&&(l.removeListener("connect",o),o=void 0),n||(n=this.onAccountsChanged.bind(this),l.on("accountsChanged",n)),g||(g=this.onChainChanged.bind(this),l.on("chainChanged",g)),s||(s=this.onDisconnect.bind(this),l.on("disconnect",s));let D=await this.getChainId();if(r&&D!==r){const S=await this.switchChain({chainId:r}).catch(k=>{if(k.code===_s.code)throw k;return{id:D}});D=(S==null?void 0:S.id)??D}return A&&await((y=a.storage)==null?void 0:y.removeItem(`${this.id}.disconnected`)),e.target||await((m=a.storage)==null?void 0:m.setItem("injected.connected",!0)),{accounts:c?B.map(S=>({address:S,capabilities:{}})):B,chainId:D}}catch(D){const S=D;throw S.code===_s.code?new _s(S):S.code===$u.code?new $u(S):S}},async disconnect(){var I,c;const r=await this.getProvider();if(!r)throw new tu;g&&(r.removeListener("chainChanged",g),g=void 0),s&&(r.removeListener("disconnect",s),s=void 0),o||(o=this.onConnect.bind(this),r.on("connect",o));try{await ESA(()=>r.request({method:"wallet_revokePermissions",params:[{eth_accounts:{}}]}),{timeout:100})}catch{}A&&await((I=a.storage)==null?void 0:I.setItem(`${this.id}.disconnected`,!0)),e.target||await((c=a.storage)==null?void 0:c.removeItem("injected.connected"))},async getAccounts(){const r=await this.getProvider();if(!r)throw new tu;return(await r.request({method:"eth_accounts"})).map(c=>fp(c))},async getChainId(){const r=await this.getProvider();if(!r)throw new tu;const I=await r.request({method:"eth_chainId"});return Number(I)},async getProvider(){if(typeof window>"u")return;let r;const I=i();return typeof I.provider=="function"?r=I.provider(window):typeof I.provider=="string"?r=YK(window,I.provider):r=I.provider,r&&!r.removeListener&&("off"in r&&typeof r.off=="function"?r.removeListener=r.off:r.removeListener=()=>{}),r},async isAuthorized(){var r,I;try{if(A&&await((r=a.storage)==null?void 0:r.getItem(`${this.id}.disconnected`))||!e.target&&!await((I=a.storage)==null?void 0:I.getItem("injected.connected")))return!1;if(!await this.getProvider()){if(t!==void 0&&t!==!1){const Q=async()=>(typeof window<"u"&&window.removeEventListener("ethereum#initialized",Q),!!await this.getProvider()),h=typeof t=="number"?t:1e3;if(await Promise.race([...typeof window<"u"?[new Promise(p=>window.addEventListener("ethereum#initialized",()=>p(Q()),{once:!0}))]:[],new Promise(p=>setTimeout(()=>p(Q()),h))]))return!0}throw new tu}return!!(await lSA(()=>this.getAccounts())).length}catch{return!1}},async switchChain({addEthereumChainParameter:r,chainId:I}){var Q,h,d,p;const c=await this.getProvider();if(!c)throw new tu;const l=a.chains.find(y=>y.id===I);if(!l)throw new Dd(new HJ);const B=new Promise(y=>{const m=D=>{"chainId"in D&&D.chainId===I&&(a.emitter.off("change",m),y())};a.emitter.on("change",m)});try{return await Promise.all([c.request({method:"wallet_switchEthereumChain",params:[{chainId:$S(I)}]}).then(async()=>{await this.getChainId()===I&&a.emitter.emit("change",{chainId:I})}),B]),l}catch(y){const m=y;if(m.code===4902||((h=(Q=m==null?void 0:m.data)==null?void 0:Q.originalError)==null?void 0:h.code)===4902)try{const{default:D,...S}=l.blockExplorers??{};let k;r!=null&&r.blockExplorerUrls?k=r.blockExplorerUrls:D&&(k=[D.url,...Object.values(S).map(M=>M.url)]);let N;(d=r==null?void 0:r.rpcUrls)!=null&&d.length?N=r.rpcUrls:N=[((p=l.rpcUrls.default)==null?void 0:p.http[0])??""];const G={blockExplorerUrls:k,chainId:$S(I),chainName:(r==null?void 0:r.chainName)??l.name,iconUrls:r==null?void 0:r.iconUrls,nativeCurrency:(r==null?void 0:r.nativeCurrency)??l.nativeCurrency,rpcUrls:N};return await Promise.all([c.request({method:"wallet_addEthereumChain",params:[G]}).then(async()=>{if(await this.getChainId()===I)a.emitter.emit("change",{chainId:I});else throw new _s(new Error("User rejected switch after adding network."))}),B]),l}catch(D){throw new _s(D)}throw m.code===_s.code?new _s(m):new Dd(m)}},async onAccountsChanged(r){var I;if(r.length===0)this.onDisconnect();else if(a.emitter.listenerCount("connect")){const c=(await this.getChainId()).toString();this.onConnect({chainId:c}),A&&await((I=a.storage)==null?void 0:I.removeItem(`${this.id}.disconnected`))}else a.emitter.emit("change",{accounts:r.map(c=>fp(c))})},onChainChanged(r){const I=Number(r);a.emitter.emit("change",{chainId:I})},async onConnect(r){const I=await this.getAccounts();if(I.length===0)return;const c=Number(r.chainId);a.emitter.emit("connect",{accounts:I,chainId:c});const l=await this.getProvider();l&&(o&&(l.removeListener("connect",o),o=void 0),n||(n=this.onAccountsChanged.bind(this),l.on("accountsChanged",n)),g||(g=this.onChainChanged.bind(this),l.on("chainChanged",g)),s||(s=this.onDisconnect.bind(this),l.on("disconnect",s)))},async onDisconnect(r){const I=await this.getProvider();r&&r.code===1013&&I&&(await this.getAccounts()).length||(a.emitter.emit("disconnect"),I&&(g&&(I.removeListener("chainChanged",g),g=void 0),s&&(I.removeListener("disconnect",s),s=void 0),o||(o=this.onConnect.bind(this),I.on("connect",o))))}})}const xMe={coinbaseWallet:{id:"coinbaseWallet",name:"Coinbase Wallet",provider(e){return e!=null&&e.coinbaseWalletExtension?e.coinbaseWalletExtension:YK(e,"isCoinbaseWallet")}},metaMask:{id:"metaMask",name:"MetaMask",provider(e){return YK(e,A=>{if(!A.isMetaMask||A.isBraveWallet&&!A._events&&!A._state)return!1;const t=["isApexWallet","isAvalanche","isBitKeep","isBlockWallet","isKuCoinWallet","isMathWallet","isOkxWallet","isOKExWallet","isOneInchIOSWallet","isOneInchAndroidWallet","isOpera","isPhantom","isPortal","isRabby","isTokenPocket","isTokenary","isUniswapWallet","isZerion"];for(const i of t)if(A[i])return!1;return!0})}},phantom:{id:"phantom",name:"Phantom",provider(e){var A,t;return(A=e==null?void 0:e.phantom)!=null&&A.ethereum?(t=e.phantom)==null?void 0:t.ethereum:YK(e,"isPhantom")}}};function YK(e,A){function t(n){return typeof A=="function"?A(n):typeof A=="string"?n[A]:!0}const i=e.ethereum;if(i!=null&&i.providers)return i.providers.find(n=>t(n));if(i&&t(i))return i}function TMe(e){if(typeof window>"u")return;const A=t=>e(t.detail);return window.addEventListener("eip6963:announceProvider",A),window.dispatchEvent(new CustomEvent("eip6963:requestProvider")),()=>window.removeEventListener("eip6963:announceProvider",A)}function qMe(){const e=new Set;let A=[];const t=()=>TMe(n=>{A.some(({info:g})=>g.uuid===n.info.uuid)||(A=[...A,n],e.forEach(g=>g(A,{added:[n]})))});let i=t();return{_listeners(){return e},clear(){e.forEach(n=>n([],{removed:[...A]})),A=[]},destroy(){this.clear(),e.clear(),i==null||i()},findProvider({rdns:n}){return A.find(g=>g.info.rdns===n)},getProviders(){return A},reset(){this.clear(),i==null||i(),i=t()},subscribe(n,{emitImmediately:g}={}){return e.add(n),g&&n(A,{added:A}),()=>e.delete(n)}}}const YMe=e=>(A,t,i)=>{const n=i.subscribe;return i.subscribe=(o,s,a)=>{let r=o;if(s){const I=(a==null?void 0:a.equalityFn)||Object.is;let c=o(i.getState());r=l=>{const B=o(l);if(!I(c,B)){const Q=c;s(c=B,Q)}},a!=null&&a.fireImmediately&&s(c,c)}return n(r)},e(A,t,i)},HMe=YMe;function OMe(e,A){let t;try{t=e()}catch{return}return{getItem:n=>{var g;const o=a=>a===null?null:JSON.parse(a,void 0),s=(g=t.getItem(n))!=null?g:null;return s instanceof Promise?s.then(o):o(s)},setItem:(n,g)=>t.setItem(n,JSON.stringify(g,void 0)),removeItem:n=>t.removeItem(n)}}const L4=e=>A=>{try{const t=e(A);return t instanceof Promise?t:{then(i){return L4(i)(t)},catch(i){return this}}}catch(t){return{then(i){return this},catch(i){return L4(i)(t)}}}},PMe=(e,A)=>(t,i,n)=>{let g={storage:OMe(()=>localStorage),partialize:h=>h,version:0,merge:(h,d)=>({...d,...h}),...A},o=!1;const s=new Set,a=new Set;let r=g.storage;if(!r)return e((...h)=>{console.warn(`[zustand persist middleware] Unable to update item '${g.name}', the given storage is currently unavailable.`),t(...h)},i,n);const I=()=>{const h=g.partialize({...i()});return r.setItem(g.name,{state:h,version:g.version})},c=n.setState;n.setState=(h,d)=>{c(h,d),I()};const l=e((...h)=>{t(...h),I()},i,n);n.getInitialState=()=>l;let B;const Q=()=>{var h,d;if(!r)return;o=!1,s.forEach(y=>{var m;return y((m=i())!=null?m:l)});const p=((d=g.onRehydrateStorage)==null?void 0:d.call(g,(h=i())!=null?h:l))||void 0;return L4(r.getItem.bind(r))(g.name).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==g.version){if(g.migrate)return[!0,g.migrate(y.state,y.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,y.state];return[!1,void 0]}).then(y=>{var m;const[D,S]=y;if(B=g.merge(S,(m=i())!=null?m:l),t(B,!0),D)return I()}).then(()=>{p==null||p(B,void 0),B=i(),o=!0,a.forEach(y=>y(B))}).catch(y=>{p==null||p(void 0,y)})};return n.persist={setOptions:h=>{g={...g,...h},h.storage&&(r=h.storage)},clearStorage:()=>{r==null||r.removeItem(g.name)},getOptions:()=>g,rehydrate:()=>Q(),hasHydrated:()=>o,onHydrate:h=>(s.add(h),()=>{s.delete(h)}),onFinishHydration:h=>(a.add(h),()=>{a.delete(h)})},g.skipHydration||Q(),B||l},jMe=PMe,HsA=e=>{let A;const t=new Set,i=(r,I)=>{const c=typeof r=="function"?r(A):r;if(!Object.is(c,A)){const l=A;A=I??(typeof c!="object"||c===null)?c:Object.assign({},A,c),t.forEach(B=>B(A,l))}},n=()=>A,s={setState:i,getState:n,getInitialState:()=>a,subscribe:r=>(t.add(r),()=>t.delete(r))},a=A=e(i,n,s);return s},JO=e=>e?HsA(e):HsA;var hSA={exports:{}};(function(e){var A=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(a,r,I){this.fn=a,this.context=r,this.once=I||!1}function g(a,r,I,c,l){if(typeof I!="function")throw new TypeError("The listener must be a function");var B=new n(I,c||a,l),Q=t?t+r:r;return a._events[Q]?a._events[Q].fn?a._events[Q]=[a._events[Q],B]:a._events[Q].push(B):(a._events[Q]=B,a._eventsCount++),a}function o(a,r){--a._eventsCount===0?a._events=new i:delete a._events[r]}function s(){this._events=new i,this._eventsCount=0}s.prototype.eventNames=function(){var r=[],I,c;if(this._eventsCount===0)return r;for(c in I=this._events)A.call(I,c)&&r.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(I)):r},s.prototype.listeners=function(r){var I=t?t+r:r,c=this._events[I];if(!c)return[];if(c.fn)return[c.fn];for(var l=0,B=c.length,Q=new Array(B);l<B;l++)Q[l]=c[l].fn;return Q},s.prototype.listenerCount=function(r){var I=t?t+r:r,c=this._events[I];return c?c.fn?1:c.length:0},s.prototype.emit=function(r,I,c,l,B,Q){var h=t?t+r:r;if(!this._events[h])return!1;var d=this._events[h],p=arguments.length,y,m;if(d.fn){switch(d.once&&this.removeListener(r,d.fn,void 0,!0),p){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,I),!0;case 3:return d.fn.call(d.context,I,c),!0;case 4:return d.fn.call(d.context,I,c,l),!0;case 5:return d.fn.call(d.context,I,c,l,B),!0;case 6:return d.fn.call(d.context,I,c,l,B,Q),!0}for(m=1,y=new Array(p-1);m<p;m++)y[m-1]=arguments[m];d.fn.apply(d.context,y)}else{var D=d.length,S;for(m=0;m<D;m++)switch(d[m].once&&this.removeListener(r,d[m].fn,void 0,!0),p){case 1:d[m].fn.call(d[m].context);break;case 2:d[m].fn.call(d[m].context,I);break;case 3:d[m].fn.call(d[m].context,I,c);break;case 4:d[m].fn.call(d[m].context,I,c,l);break;default:if(!y)for(S=1,y=new Array(p-1);S<p;S++)y[S-1]=arguments[S];d[m].fn.apply(d[m].context,y)}}return!0},s.prototype.on=function(r,I,c){return g(this,r,I,c,!1)},s.prototype.once=function(r,I,c){return g(this,r,I,c,!0)},s.prototype.removeListener=function(r,I,c,l){var B=t?t+r:r;if(!this._events[B])return this;if(!I)return o(this,B),this;var Q=this._events[B];if(Q.fn)Q.fn===I&&(!l||Q.once)&&(!c||Q.context===c)&&o(this,B);else{for(var h=0,d=[],p=Q.length;h<p;h++)(Q[h].fn!==I||l&&!Q[h].once||c&&Q[h].context!==c)&&d.push(Q[h]);d.length?this._events[B]=d.length===1?d[0]:d:o(this,B)}return this},s.prototype.removeAllListeners=function(r){var I;return r?(I=t?t+r:r,this._events[I]&&o(this,I)):(this._events=new i,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=t,s.EventEmitter=s,e.exports=s})(hSA);var zMe=hSA.exports;class ZMe{constructor(A){Object.defineProperty(this,"uid",{enumerable:!0,configurable:!0,writable:!0,value:A}),Object.defineProperty(this,"_emitter",{enumerable:!0,configurable:!0,writable:!0,value:new zMe.EventEmitter})}on(A,t){this._emitter.on(A,t)}once(A,t){this._emitter.once(A,t)}off(A,t){this._emitter.off(A,t)}emit(A,...t){const i=t[0];this._emitter.emit(A,{uid:this.uid,...i})}listenerCount(A){return this._emitter.listenerCount(A)}}function WMe(e){return new ZMe(e)}function VMe(e,A){return JSON.parse(e,(t,i)=>{let n=i;return(n==null?void 0:n.__type)==="bigint"&&(n=BigInt(n.value)),(n==null?void 0:n.__type)==="Map"&&(n=new Map(n.value)),(A==null?void 0:A(t,n))??n})}function OsA(e,A){return e.slice(0,A).join(".")||"."}function PsA(e,A){const{length:t}=e;for(let i=0;i<t;++i)if(e[i]===A)return i+1;return 0}function XMe(e,A){const t=typeof e=="function",i=typeof A=="function",n=[],g=[];return function(s,a){if(typeof a=="object")if(n.length){const r=PsA(n,this);r===0?n[n.length]=this:(n.splice(r),g.splice(r)),g[g.length]=s;const I=PsA(n,a);if(I!==0)return i?A.call(this,s,a,OsA(g,I)):`[ref=${OsA(g,I)}]`}else n[0]=a,g[0]=s;return t?e.call(this,s,a):a}}function $Me(e,A,t,i){return JSON.stringify(e,XMe((n,g)=>{let o=g;return typeof o=="bigint"&&(o={__type:"bigint",value:g.toString()}),o instanceof Map&&(o={__type:"Map",value:Array.from(g.entries())}),(A==null?void 0:A(n,o))??o},i),t??void 0)}function pSA(e){const{deserialize:A=VMe,key:t="wagmi",serialize:i=$Me,storage:n=fSA}=e;function g(o){return o instanceof Promise?o.then(s=>s).catch(()=>null):o}return{...n,key:t,async getItem(o,s){const a=n.getItem(`${t}.${o}`),r=await g(a);return r?A(r)??null:s??null},async setItem(o,s){const a=`${t}.${o}`;s===null?await g(n.removeItem(a)):await g(n.setItem(a,i(s)))},async removeItem(o){await g(n.removeItem(`${t}.${o}`))}}}const fSA={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function ANe(){const e=typeof window<"u"&&window.localStorage?window.localStorage:fSA;return{getItem(A){return e.getItem(A)},removeItem(A){e.removeItem(A)},setItem(A,t){try{e.setItem(A,t)}catch{}}}}const x4=256;let Uv=x4,vv;function eNe(e=11){if(!vv||Uv+e>x4*2){vv="",Uv=0;for(let A=0;A<x4;A++)vv+=(256+Math.random()*256|0).toString(16).substring(1)}return vv.substring(Uv,Uv+++e)}function tNe(e){const{multiInjectedProviderDiscovery:A=!0,storage:t=pSA({storage:ANe()}),syncConnectedChain:i=!0,ssr:n=!1,...g}=e,o=typeof window<"u"&&A?qMe():void 0,s=JO(()=>g.chains),a=JO(()=>{const S=[],k=new Set;for(const N of g.connectors??[]){const G=r(N);if(S.push(G),!n&&G.rdns){const M=typeof G.rdns=="string"?[G.rdns]:G.rdns;for(const w of M)k.add(w)}}if(!n&&o){const N=o.getProviders();for(const G of N)k.has(G.info.rdns)||S.push(r(I(G)))}return S});function r(S){var G;const k=WMe(eNe()),N={...S({emitter:k,chains:s.getState(),storage:t,transports:g.transports}),emitter:k,uid:k.uid};return k.on("connect",m),(G=N.setup)==null||G.call(N),N}function I(S){const{info:k}=S,N=S.provider;return pT({target:{...k,id:k.rdns,provider:N}})}const c=new Map;function l(S={}){const k=S.chainId??d.getState().chainId,N=s.getState().find(M=>M.id===k);if(S.chainId&&!N)throw new HJ;{const M=c.get(d.getState().chainId);if(M&&!N)return M;if(!N)throw new HJ}{const M=c.get(k);if(M)return M}let G;if(g.client)G=g.client({chain:N});else{const M=N.id,w=s.getState().map(K=>K.id),b={},_=Object.entries(g);for(const[K,J]of _)if(!(K==="chains"||K==="client"||K==="connectors"||K==="transports"))if(typeof J=="object")if(M in J)b[K]=J[M];else{if(w.some(v=>v in J))continue;b[K]=J}else b[K]=J;G=FMe({...b,chain:N,batch:b.batch??{multicall:!0},transport:K=>g.transports[M]({...K,connectors:a})})}return c.set(k,G),G}function B(){return{chainId:s.getState()[0].id,connections:new Map,current:null,status:"disconnected"}}let Q;const h="0.0.0-canary-";qK.startsWith(h)?Q=Number.parseInt(qK.replace(h,""),10):Q=Number.parseInt(qK.split(".")[0]??"0",10);const d=JO(HMe(t?jMe(B,{migrate(S,k){if(k===Q)return S;const N=B(),G=p(S,N.chainId);return{...N,chainId:G}},name:"store",partialize(S){return{connections:{__type:"Map",value:Array.from(S.connections.entries()).map(([k,N])=>{const{id:G,name:M,type:w,uid:b}=N.connector;return[k,{...N,connector:{id:G,name:M,type:w,uid:b}}]})},chainId:S.chainId,current:S.current}},merge(S,k){typeof S=="object"&&S&&"status"in S&&delete S.status;const N=p(S,k.chainId);return{...k,...S,chainId:N}},skipHydration:n,storage:t,version:Q}):B));d.setState(B());function p(S,k){return S&&typeof S=="object"&&"chainId"in S&&typeof S.chainId=="number"&&s.getState().some(N=>N.id===S.chainId)?S.chainId:k}i&&d.subscribe(({connections:S,current:k})=>{var N;return k?(N=S.get(k))==null?void 0:N.chainId:void 0},S=>{if(s.getState().some(N=>N.id===S))return d.setState(N=>({...N,chainId:S??N.chainId}))}),o==null||o.subscribe(S=>{const k=new Set,N=new Set;for(const M of a.getState())if(k.add(M.id),M.rdns){const w=typeof M.rdns=="string"?[M.rdns]:M.rdns;for(const b of w)N.add(b)}const G=[];for(const M of S){if(N.has(M.info.rdns))continue;const w=r(I(M));k.has(w.id)||G.push(w)}t&&!d.persist.hasHydrated()||a.setState(M=>[...M,...G],!0)});function y(S){d.setState(k=>{const N=k.connections.get(S.uid);return N?{...k,connections:new Map(k.connections).set(S.uid,{accounts:S.accounts??N.accounts,chainId:S.chainId??N.chainId,connector:N.connector})}:k})}function m(S){d.getState().status==="connecting"||d.getState().status==="reconnecting"||d.setState(k=>{const N=a.getState().find(G=>G.uid===S.uid);return N?(N.emitter.listenerCount("connect")&&N.emitter.off("connect",y),N.emitter.listenerCount("change")||N.emitter.on("change",y),N.emitter.listenerCount("disconnect")||N.emitter.on("disconnect",D),{...k,connections:new Map(k.connections).set(S.uid,{accounts:S.accounts,chainId:S.chainId,connector:N}),current:S.uid,status:"connected"}):k})}function D(S){d.setState(k=>{const N=k.connections.get(S.uid);if(N){const M=N.connector;M.emitter.listenerCount("change")&&N.connector.emitter.off("change",y),M.emitter.listenerCount("disconnect")&&N.connector.emitter.off("disconnect",D),M.emitter.listenerCount("connect")||N.connector.emitter.on("connect",m)}if(k.connections.delete(S.uid),k.connections.size===0)return{...k,connections:new Map,current:null,status:"disconnected"};const G=k.connections.values().next().value;return{...k,connections:new Map(k.connections),current:G.connector.uid}})}return{get chains(){return s.getState()},get connectors(){return a.getState()},storage:t,getClient:l,get state(){return d.getState()},setState(S){let k;typeof S=="function"?k=S(d.getState()):k=S;const N=B();typeof k!="object"&&(k=N),Object.keys(N).some(M=>!(M in k))&&(k=N),d.setState(k,!0)},subscribe(S,k,N){return d.subscribe(S,k,N?{...N,fireImmediately:N.emitImmediately}:void 0)},_internal:{mipd:o,async revalidate(){const S=d.getState(),k=S.connections;let N=S.current;for(const[,G]of k){const M=G.connector;M.isAuthorized&&await M.isAuthorized()||(k.delete(M.uid),N===M.uid&&(N=null))}d.setState(G=>({...G,connections:k,current:N}))},store:d,ssr:!!n,syncConnectedChain:i,transports:g.transports,chains:{setState(S){const k=typeof S=="function"?S(s.getState()):S;if(k.length!==0)return s.setState(k,!0)},subscribe(S){return s.subscribe(S)}},connectors:{providerDetailToConnector:I,setup:r,setState(S){return a.setState(typeof S=="function"?S(a.getState()):S,!0)},subscribe(S){return a.subscribe(S)}},events:{change:y,connect:m,disconnect:D}}}}function iNe(e,A){const{initialState:t,reconnectOnMount:i}=A;return t&&!e._internal.store.persist.hasHydrated()&&e.setState({...t,chainId:e.chains.some(n=>n.id===t.chainId)?t.chainId:e.chains[0].id,connections:i?t.connections:new Map,status:i?"reconnecting":"disconnected"}),{async onMount(){e._internal.ssr&&(await e._internal.store.persist.rehydrate(),e._internal.mipd&&e._internal.connectors.setState(n=>{var a;const g=new Set;for(const r of n??[])if(r.rdns){const I=Array.isArray(r.rdns)?r.rdns:[r.rdns];for(const c of I)g.add(c)}const o=[],s=((a=e._internal.mipd)==null?void 0:a.getProviders())??[];for(const r of s){if(g.has(r.info.rdns))continue;const I=e._internal.connectors.providerDetailToConnector(r),c=e._internal.connectors.setup(I);o.push(c)}return[...n,...o]})),i?LMe(e):e.storage&&e.setState(n=>({...n,connections:new Map}))}}}const nNe={getItem(e){return typeof window>"u"?null:gNe(document.cookie,e)??null},setItem(e,A){typeof window>"u"||(document.cookie=`${e}=${A};path=/;samesite=Lax`)},removeItem(e){typeof window>"u"||(document.cookie=`${e}=;max-age=-1;path=/`)}};function gNe(e,A){const t=e.split("; ").find(i=>i.startsWith(`${A}=`));if(t)return t.substring(A.length+1)}function oNe(e){var g,o,s;const{chain:A}=e,t=A.rpcUrls.default.http[0];if(!e.transports)return[t];const i=(o=(g=e.transports)==null?void 0:g[A.id])==null?void 0:o.call(g,{chain:A});return(((s=i==null?void 0:i.value)==null?void 0:s.transports)||[i]).map(({value:a})=>(a==null?void 0:a.url)||t)}function sNe(e){const{children:A,config:t,initialState:i,reconnectOnMount:n=!0}=e,{onMount:g}=iNe(t,{initialState:i,reconnectOnMount:n});t._internal.ssr||g();const o=E.useRef(!0);return E.useEffect(()=>{if(o.current&&t._internal.ssr)return g(),()=>{o.current=!1}},[]),A}const aNe=E.createContext(void 0);function rNe(e){const{children:A,config:t}=e,i={value:t};return E.createElement(sNe,e,E.createElement(aNe.Provider,i,A))}var fT=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},INe={setTimeout:(e,A)=>setTimeout(e,A),clearTimeout:e=>clearTimeout(e),setInterval:(e,A)=>setInterval(e,A),clearInterval:e=>clearInterval(e)},Cu,j4,BaA,CNe=(BaA=class{constructor(){Hn(this,Cu,INe);Hn(this,j4,!1)}setTimeoutProvider(e){Pi(this,Cu,e)}setTimeout(e,A){return et(this,Cu).setTimeout(e,A)}clearTimeout(e){et(this,Cu).clearTimeout(e)}setInterval(e,A){return et(this,Cu).setInterval(e,A)}clearInterval(e){et(this,Cu).clearInterval(e)}},Cu=new WeakMap,j4=new WeakMap,BaA),T4=new CNe;function cNe(e){setTimeout(e,0)}var yT=typeof window>"u"||"Deno"in globalThis;function bc(){}function lNe(e,A){return typeof e=="function"?e(A):e}function BNe(e){return typeof e=="number"&&e>=0&&e!==1/0}function ENe(e,A){return Math.max(e+(A||0)-Date.now(),0)}function q4(e,A){return typeof e=="function"?e(A):e}function QNe(e,A){return typeof e=="function"?e(A):e}function jsA(e,A){const{type:t="all",exact:i,fetchStatus:n,predicate:g,queryKey:o,stale:s}=e;if(o){if(i){if(A.queryHash!==_V(o,A.options))return!1}else if(!IR(A.queryKey,o))return!1}if(t!=="all"){const a=A.isActive();if(t==="active"&&!a||t==="inactive"&&a)return!1}return!(typeof s=="boolean"&&A.isStale()!==s||n&&n!==A.state.fetchStatus||g&&!g(A))}function zsA(e,A){const{exact:t,status:i,predicate:n,mutationKey:g}=e;if(g){if(!A.options.mutationKey)return!1;if(t){if(rR(A.options.mutationKey)!==rR(g))return!1}else if(!IR(A.options.mutationKey,g))return!1}return!(i&&A.state.status!==i||n&&!n(A))}function _V(e,A){return((A==null?void 0:A.queryKeyHashFn)||rR)(e)}function rR(e){return JSON.stringify(e,(A,t)=>Y4(t)?Object.keys(t).sort().reduce((i,n)=>(i[n]=t[n],i),{}):t)}function IR(e,A){return e===A?!0:typeof e!=typeof A?!1:e&&A&&typeof e=="object"&&typeof A=="object"?Object.keys(A).every(t=>IR(e[t],A[t])):!1}var uNe=Object.prototype.hasOwnProperty;function ySA(e,A){if(e===A)return e;const t=ZsA(e)&&ZsA(A);if(!t&&!(Y4(e)&&Y4(A)))return A;const n=(t?e:Object.keys(e)).length,g=t?A:Object.keys(A),o=g.length,s=t?new Array(o):{};let a=0;for(let r=0;r<o;r++){const I=t?r:g[r],c=e[I],l=A[I];if(c===l){s[I]=c,(t?r<n:uNe.call(e,I))&&a++;continue}if(c===null||l===null||typeof c!="object"||typeof l!="object"){s[I]=l;continue}const B=ySA(c,l);s[I]=B,B===c&&a++}return n===o&&a===n?e:s}function ZsA(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Y4(e){if(!WsA(e))return!1;const A=e.constructor;if(A===void 0)return!0;const t=A.prototype;return!(!WsA(t)||!t.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function WsA(e){return Object.prototype.toString.call(e)==="[object Object]"}function dNe(e){return new Promise(A=>{T4.setTimeout(A,e)})}function hNe(e,A,t){return typeof t.structuralSharing=="function"?t.structuralSharing(e,A):t.structuralSharing!==!1?ySA(e,A):A}function pNe(e,A,t=0){const i=[...e,A];return t&&i.length>t?i.slice(1):i}function fNe(e,A,t=0){const i=[A,...e];return t&&i.length>t?i.slice(0,-1):i}var JV=Symbol();function DSA(e,A){return!e.queryFn&&(A!=null&&A.initialPromise)?()=>A.initialPromise:!e.queryFn||e.queryFn===JV?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Dp,cu,$m,EaA,yNe=(EaA=class extends fT{constructor(){super();Hn(this,Dp);Hn(this,cu);Hn(this,$m);Pi(this,$m,A=>{if(!yT&&window.addEventListener){const t=()=>A();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}})}onSubscribe(){et(this,cu)||this.setEventListener(et(this,$m))}onUnsubscribe(){var A;this.hasListeners()||((A=et(this,cu))==null||A.call(this),Pi(this,cu,void 0))}setEventListener(A){var t;Pi(this,$m,A),(t=et(this,cu))==null||t.call(this),Pi(this,cu,A(i=>{typeof i=="boolean"?this.setFocused(i):this.onFocus()}))}setFocused(A){et(this,Dp)!==A&&(Pi(this,Dp,A),this.onFocus())}onFocus(){const A=this.isFocused();this.listeners.forEach(t=>{t(A)})}isFocused(){var A;return typeof et(this,Dp)=="boolean"?et(this,Dp):((A=globalThis.document)==null?void 0:A.visibilityState)!=="hidden"}},Dp=new WeakMap,cu=new WeakMap,$m=new WeakMap,EaA),mSA=new yNe;function DNe(){let e,A;const t=new Promise((n,g)=>{e=n,A=g});t.status="pending",t.catch(()=>{});function i(n){Object.assign(t,n),delete t.resolve,delete t.reject}return t.resolve=n=>{i({status:"fulfilled",value:n}),e(n)},t.reject=n=>{i({status:"rejected",reason:n}),A(n)},t}var mNe=cNe;function SNe(){let e=[],A=0,t=s=>{s()},i=s=>{s()},n=mNe;const g=s=>{A?e.push(s):n(()=>{t(s)})},o=()=>{const s=e;e=[],s.length&&n(()=>{i(()=>{s.forEach(a=>{t(a)})})})};return{batch:s=>{let a;A++;try{a=s()}finally{A--,A||o()}return a},batchCalls:s=>(...a)=>{g(()=>{s(...a)})},schedule:g,setNotifyFunction:s=>{t=s},setBatchNotifyFunction:s=>{i=s},setScheduler:s=>{n=s}}}var Sr=SNe(),AS,lu,eS,QaA,wNe=(QaA=class extends fT{constructor(){super();Hn(this,AS,!0);Hn(this,lu);Hn(this,eS);Pi(this,eS,A=>{if(!yT&&window.addEventListener){const t=()=>A(!0),i=()=>A(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",i,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",i)}}})}onSubscribe(){et(this,lu)||this.setEventListener(et(this,eS))}onUnsubscribe(){var A;this.hasListeners()||((A=et(this,lu))==null||A.call(this),Pi(this,lu,void 0))}setEventListener(A){var t;Pi(this,eS,A),(t=et(this,lu))==null||t.call(this),Pi(this,lu,A(this.setOnline.bind(this)))}setOnline(A){et(this,AS)!==A&&(Pi(this,AS,A),this.listeners.forEach(i=>{i(A)}))}isOnline(){return et(this,AS)}},AS=new WeakMap,lu=new WeakMap,eS=new WeakMap,QaA),OJ=new wNe;function kNe(e){return Math.min(1e3*2**e,3e4)}function SSA(e){return(e??"online")==="online"?OJ.isOnline():!0}var H4=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function wSA(e){let A=!1,t=0,i;const n=DNe(),g=()=>n.status!=="pending",o=h=>{var d;if(!g()){const p=new H4(h);l(p),(d=e.onCancel)==null||d.call(e,p)}},s=()=>{A=!0},a=()=>{A=!1},r=()=>mSA.isFocused()&&(e.networkMode==="always"||OJ.isOnline())&&e.canRun(),I=()=>SSA(e.networkMode)&&e.canRun(),c=h=>{g()||(i==null||i(),n.resolve(h))},l=h=>{g()||(i==null||i(),n.reject(h))},B=()=>new Promise(h=>{var d;i=p=>{(g()||r())&&h(p)},(d=e.onPause)==null||d.call(e)}).then(()=>{var h;i=void 0,g()||(h=e.onContinue)==null||h.call(e)}),Q=()=>{if(g())return;let h;const d=t===0?e.initialPromise:void 0;try{h=d??e.fn()}catch(p){h=Promise.reject(p)}Promise.resolve(h).then(c).catch(p=>{var k;if(g())return;const y=e.retry??(yT?0:3),m=e.retryDelay??kNe,D=typeof m=="function"?m(t,p):m,S=y===!0||typeof y=="number"&&t<y||typeof y=="function"&&y(t,p);if(A||!S){l(p);return}t++,(k=e.onFail)==null||k.call(e,t,p),dNe(D).then(()=>r()?void 0:B()).then(()=>{A?l(p):Q()})})};return{promise:n,status:()=>n.status,cancel:o,continue:()=>(i==null||i(),n),cancelRetry:s,continueRetry:a,canStart:I,start:()=>(I()?Q():B().then(Q),n)}}var mp,uaA,kSA=(uaA=class{constructor(){Hn(this,mp)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),BNe(this.gcTime)&&Pi(this,mp,T4.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(yT?1/0:5*60*1e3))}clearGcTimeout(){et(this,mp)&&(T4.clearTimeout(et(this,mp)),Pi(this,mp,void 0))}},mp=new WeakMap,uaA),Sp,tS,vC,wp,Xs,CR,kp,Uc,rE,daA,MNe=(daA=class extends kSA{constructor(A){super();Hn(this,Uc);Hn(this,Sp);Hn(this,tS);Hn(this,vC);Hn(this,wp);Hn(this,Xs);Hn(this,CR);Hn(this,kp);Pi(this,kp,!1),Pi(this,CR,A.defaultOptions),this.setOptions(A.options),this.observers=[],Pi(this,wp,A.client),Pi(this,vC,et(this,wp).getQueryCache()),this.queryKey=A.queryKey,this.queryHash=A.queryHash,Pi(this,Sp,VsA(this.options)),this.state=A.state??et(this,Sp),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var A;return(A=et(this,Xs))==null?void 0:A.promise}setOptions(A){if(this.options={...et(this,CR),...A},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=VsA(this.options);t.data!==void 0&&(this.setData(t.data,{updatedAt:t.dataUpdatedAt,manual:!0}),Pi(this,Sp,t))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&et(this,vC).remove(this)}setData(A,t){const i=hNe(this.state.data,A,this.options);return Ha(this,Uc,rE).call(this,{data:i,type:"success",dataUpdatedAt:t==null?void 0:t.updatedAt,manual:t==null?void 0:t.manual}),i}setState(A,t){Ha(this,Uc,rE).call(this,{type:"setState",state:A,setStateOptions:t})}cancel(A){var i,n;const t=(i=et(this,Xs))==null?void 0:i.promise;return(n=et(this,Xs))==null||n.cancel(A),t?t.then(bc).catch(bc):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(et(this,Sp))}isActive(){return this.observers.some(A=>QNe(A.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===JV||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(A=>q4(A.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(A=>A.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(A=0){return this.state.data===void 0?!0:A==="static"?!1:this.state.isInvalidated?!0:!ENe(this.state.dataUpdatedAt,A)}onFocus(){var t;const A=this.observers.find(i=>i.shouldFetchOnWindowFocus());A==null||A.refetch({cancelRefetch:!1}),(t=et(this,Xs))==null||t.continue()}onOnline(){var t;const A=this.observers.find(i=>i.shouldFetchOnReconnect());A==null||A.refetch({cancelRefetch:!1}),(t=et(this,Xs))==null||t.continue()}addObserver(A){this.observers.includes(A)||(this.observers.push(A),this.clearGcTimeout(),et(this,vC).notify({type:"observerAdded",query:this,observer:A}))}removeObserver(A){this.observers.includes(A)&&(this.observers=this.observers.filter(t=>t!==A),this.observers.length||(et(this,Xs)&&(et(this,kp)?et(this,Xs).cancel({revert:!0}):et(this,Xs).cancelRetry()),this.scheduleGc()),et(this,vC).notify({type:"observerRemoved",query:this,observer:A}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Ha(this,Uc,rE).call(this,{type:"invalidate"})}async fetch(A,t){var a,r,I,c,l,B,Q,h,d,p,y,m;if(this.state.fetchStatus!=="idle"&&((a=et(this,Xs))==null?void 0:a.status())!=="rejected"){if(this.state.data!==void 0&&(t!=null&&t.cancelRefetch))this.cancel({silent:!0});else if(et(this,Xs))return et(this,Xs).continueRetry(),et(this,Xs).promise}if(A&&this.setOptions(A),!this.options.queryFn){const D=this.observers.find(S=>S.options.queryFn);D&&this.setOptions(D.options)}const i=new AbortController,n=D=>{Object.defineProperty(D,"signal",{enumerable:!0,get:()=>(Pi(this,kp,!0),i.signal)})},g=()=>{const D=DSA(this.options,t),k=(()=>{const N={client:et(this,wp),queryKey:this.queryKey,meta:this.meta};return n(N),N})();return Pi(this,kp,!1),this.options.persister?this.options.persister(D,k,this):D(k)},s=(()=>{const D={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:et(this,wp),state:this.state,fetchFn:g};return n(D),D})();(r=this.options.behavior)==null||r.onFetch(s,this),Pi(this,tS,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((I=s.fetchOptions)==null?void 0:I.meta))&&Ha(this,Uc,rE).call(this,{type:"fetch",meta:(c=s.fetchOptions)==null?void 0:c.meta}),Pi(this,Xs,wSA({initialPromise:t==null?void 0:t.initialPromise,fn:s.fetchFn,onCancel:D=>{D instanceof H4&&D.revert&&this.setState({...et(this,tS),fetchStatus:"idle"}),i.abort()},onFail:(D,S)=>{Ha(this,Uc,rE).call(this,{type:"failed",failureCount:D,error:S})},onPause:()=>{Ha(this,Uc,rE).call(this,{type:"pause"})},onContinue:()=>{Ha(this,Uc,rE).call(this,{type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}));try{const D=await et(this,Xs).start();if(D===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(D),(B=(l=et(this,vC).config).onSuccess)==null||B.call(l,D,this),(h=(Q=et(this,vC).config).onSettled)==null||h.call(Q,D,this.state.error,this),D}catch(D){if(D instanceof H4){if(D.silent)return et(this,Xs).promise;if(D.revert){if(this.state.data===void 0)throw D;return this.state.data}}throw Ha(this,Uc,rE).call(this,{type:"error",error:D}),(p=(d=et(this,vC).config).onError)==null||p.call(d,D,this),(m=(y=et(this,vC).config).onSettled)==null||m.call(y,this.state.data,D,this),D}finally{this.scheduleGc()}}},Sp=new WeakMap,tS=new WeakMap,vC=new WeakMap,wp=new WeakMap,Xs=new WeakMap,CR=new WeakMap,kp=new WeakMap,Uc=new WeakSet,rE=function(A){const t=i=>{switch(A.type){case"failed":return{...i,fetchFailureCount:A.failureCount,fetchFailureReason:A.error};case"pause":return{...i,fetchStatus:"paused"};case"continue":return{...i,fetchStatus:"fetching"};case"fetch":return{...i,...NNe(i.data,this.options),fetchMeta:A.meta??null};case"success":const n={...i,data:A.data,dataUpdateCount:i.dataUpdateCount+1,dataUpdatedAt:A.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!A.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Pi(this,tS,A.manual?n:void 0),n;case"error":const g=A.error;return{...i,error:g,errorUpdateCount:i.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:i.fetchFailureCount+1,fetchFailureReason:g,fetchStatus:"idle",status:"error"};case"invalidate":return{...i,isInvalidated:!0};case"setState":return{...i,...A.state}}};this.state=t(this.state),Sr.batch(()=>{this.observers.forEach(i=>{i.onQueryUpdate()}),et(this,vC).notify({query:this,type:"updated",action:A})})},daA);function NNe(e,A){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:SSA(A.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function VsA(e){const A=typeof e.initialData=="function"?e.initialData():e.initialData,t=A!==void 0,i=t?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:A,dataUpdateCount:0,dataUpdatedAt:t?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:t?"success":"pending",fetchStatus:"idle"}}function XsA(e){return{onFetch:(A,t)=>{var I,c,l,B,Q;const i=A.options,n=(l=(c=(I=A.fetchOptions)==null?void 0:I.meta)==null?void 0:c.fetchMore)==null?void 0:l.direction,g=((B=A.state.data)==null?void 0:B.pages)||[],o=((Q=A.state.data)==null?void 0:Q.pageParams)||[];let s={pages:[],pageParams:[]},a=0;const r=async()=>{let h=!1;const d=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>(A.signal.aborted?h=!0:A.signal.addEventListener("abort",()=>{h=!0}),A.signal)})},p=DSA(A.options,A.fetchOptions),y=async(m,D,S)=>{if(h)return Promise.reject();if(D==null&&m.pages.length)return Promise.resolve(m);const N=(()=>{const b={client:A.client,queryKey:A.queryKey,pageParam:D,direction:S?"backward":"forward",meta:A.options.meta};return d(b),b})(),G=await p(N),{maxPages:M}=A.options,w=S?fNe:pNe;return{pages:w(m.pages,G,M),pageParams:w(m.pageParams,D,M)}};if(n&&g.length){const m=n==="backward",D=m?RNe:$sA,S={pages:g,pageParams:o},k=D(i,S);s=await y(S,k,m)}else{const m=e??g.length;do{const D=a===0?o[0]??i.initialPageParam:$sA(i,s);if(a>0&&D==null)break;s=await y(s,D),a++}while(a<m)}return s};A.options.persister?A.fetchFn=()=>{var h,d;return(d=(h=A.options).persister)==null?void 0:d.call(h,r,{client:A.client,queryKey:A.queryKey,meta:A.options.meta,signal:A.signal},t)}:A.fetchFn=r}}}function $sA(e,{pages:A,pageParams:t}){const i=A.length-1;return A.length>0?e.getNextPageParam(A[i],A,t[i],t):void 0}function RNe(e,{pages:A,pageParams:t}){var i;return A.length>0?(i=e.getPreviousPageParam)==null?void 0:i.call(e,A[0],A,t[0],t):void 0}var cR,Ol,Qr,Mp,Pl,WQ,haA,GNe=(haA=class extends kSA{constructor(A){super();Hn(this,Pl);Hn(this,cR);Hn(this,Ol);Hn(this,Qr);Hn(this,Mp);Pi(this,cR,A.client),this.mutationId=A.mutationId,Pi(this,Qr,A.mutationCache),Pi(this,Ol,[]),this.state=A.state||bNe(),this.setOptions(A.options),this.scheduleGc()}setOptions(A){this.options=A,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(A){et(this,Ol).includes(A)||(et(this,Ol).push(A),this.clearGcTimeout(),et(this,Qr).notify({type:"observerAdded",mutation:this,observer:A}))}removeObserver(A){Pi(this,Ol,et(this,Ol).filter(t=>t!==A)),this.scheduleGc(),et(this,Qr).notify({type:"observerRemoved",mutation:this,observer:A})}optionalRemove(){et(this,Ol).length||(this.state.status==="pending"?this.scheduleGc():et(this,Qr).remove(this))}continue(){var A;return((A=et(this,Mp))==null?void 0:A.continue())??this.execute(this.state.variables)}async execute(A){var o,s,a,r,I,c,l,B,Q,h,d,p,y,m,D,S,k,N,G,M;const t=()=>{Ha(this,Pl,WQ).call(this,{type:"continue"})},i={client:et(this,cR),meta:this.options.meta,mutationKey:this.options.mutationKey};Pi(this,Mp,wSA({fn:()=>this.options.mutationFn?this.options.mutationFn(A,i):Promise.reject(new Error("No mutationFn found")),onFail:(w,b)=>{Ha(this,Pl,WQ).call(this,{type:"failed",failureCount:w,error:b})},onPause:()=>{Ha(this,Pl,WQ).call(this,{type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>et(this,Qr).canRun(this)}));const n=this.state.status==="pending",g=!et(this,Mp).canStart();try{if(n)t();else{Ha(this,Pl,WQ).call(this,{type:"pending",variables:A,isPaused:g}),await((s=(o=et(this,Qr).config).onMutate)==null?void 0:s.call(o,A,this,i));const b=await((r=(a=this.options).onMutate)==null?void 0:r.call(a,A,i));b!==this.state.context&&Ha(this,Pl,WQ).call(this,{type:"pending",context:b,variables:A,isPaused:g})}const w=await et(this,Mp).start();return await((c=(I=et(this,Qr).config).onSuccess)==null?void 0:c.call(I,w,A,this.state.context,this,i)),await((B=(l=this.options).onSuccess)==null?void 0:B.call(l,w,A,this.state.context,i)),await((h=(Q=et(this,Qr).config).onSettled)==null?void 0:h.call(Q,w,null,this.state.variables,this.state.context,this,i)),await((p=(d=this.options).onSettled)==null?void 0:p.call(d,w,null,A,this.state.context,i)),Ha(this,Pl,WQ).call(this,{type:"success",data:w}),w}catch(w){try{throw await((m=(y=et(this,Qr).config).onError)==null?void 0:m.call(y,w,A,this.state.context,this,i)),await((S=(D=this.options).onError)==null?void 0:S.call(D,w,A,this.state.context,i)),await((N=(k=et(this,Qr).config).onSettled)==null?void 0:N.call(k,void 0,w,this.state.variables,this.state.context,this,i)),await((M=(G=this.options).onSettled)==null?void 0:M.call(G,void 0,w,A,this.state.context,i)),w}finally{Ha(this,Pl,WQ).call(this,{type:"error",error:w})}}finally{et(this,Qr).runNext(this)}}},cR=new WeakMap,Ol=new WeakMap,Qr=new WeakMap,Mp=new WeakMap,Pl=new WeakSet,WQ=function(A){const t=i=>{switch(A.type){case"failed":return{...i,failureCount:A.failureCount,failureReason:A.error};case"pause":return{...i,isPaused:!0};case"continue":return{...i,isPaused:!1};case"pending":return{...i,context:A.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:A.isPaused,status:"pending",variables:A.variables,submittedAt:Date.now()};case"success":return{...i,data:A.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...i,data:void 0,error:A.error,failureCount:i.failureCount+1,failureReason:A.error,isPaused:!1,status:"error"}}};this.state=t(this.state),Sr.batch(()=>{et(this,Ol).forEach(i=>{i.onMutationUpdate(A)}),et(this,Qr).notify({mutation:this,type:"updated",action:A})})},haA);function bNe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var QE,vc,lR,paA,UNe=(paA=class extends fT{constructor(A={}){super();Hn(this,QE);Hn(this,vc);Hn(this,lR);this.config=A,Pi(this,QE,new Set),Pi(this,vc,new Map),Pi(this,lR,0)}build(A,t,i){const n=new GNe({client:A,mutationCache:this,mutationId:++zG(this,lR)._,options:A.defaultMutationOptions(t),state:i});return this.add(n),n}add(A){et(this,QE).add(A);const t=Kv(A);if(typeof t=="string"){const i=et(this,vc).get(t);i?i.push(A):et(this,vc).set(t,[A])}this.notify({type:"added",mutation:A})}remove(A){if(et(this,QE).delete(A)){const t=Kv(A);if(typeof t=="string"){const i=et(this,vc).get(t);if(i)if(i.length>1){const n=i.indexOf(A);n!==-1&&i.splice(n,1)}else i[0]===A&&et(this,vc).delete(t)}}this.notify({type:"removed",mutation:A})}canRun(A){const t=Kv(A);if(typeof t=="string"){const i=et(this,vc).get(t),n=i==null?void 0:i.find(g=>g.state.status==="pending");return!n||n===A}else return!0}runNext(A){var i;const t=Kv(A);if(typeof t=="string"){const n=(i=et(this,vc).get(t))==null?void 0:i.find(g=>g!==A&&g.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Sr.batch(()=>{et(this,QE).forEach(A=>{this.notify({type:"removed",mutation:A})}),et(this,QE).clear(),et(this,vc).clear()})}getAll(){return Array.from(et(this,QE))}find(A){const t={exact:!0,...A};return this.getAll().find(i=>zsA(t,i))}findAll(A={}){return this.getAll().filter(t=>zsA(A,t))}notify(A){Sr.batch(()=>{this.listeners.forEach(t=>{t(A)})})}resumePausedMutations(){const A=this.getAll().filter(t=>t.state.isPaused);return Sr.batch(()=>Promise.all(A.map(t=>t.continue().catch(bc))))}},QE=new WeakMap,vc=new WeakMap,lR=new WeakMap,paA);function Kv(e){var A;return(A=e.options.scope)==null?void 0:A.id}var jl,faA,vNe=(faA=class extends fT{constructor(A={}){super();Hn(this,jl);this.config=A,Pi(this,jl,new Map)}build(A,t,i){const n=t.queryKey,g=t.queryHash??_V(n,t);let o=this.get(g);return o||(o=new MNe({client:A,queryKey:n,queryHash:g,options:A.defaultQueryOptions(t),state:i,defaultOptions:A.getQueryDefaults(n)}),this.add(o)),o}add(A){et(this,jl).has(A.queryHash)||(et(this,jl).set(A.queryHash,A),this.notify({type:"added",query:A}))}remove(A){const t=et(this,jl).get(A.queryHash);t&&(A.destroy(),t===A&&et(this,jl).delete(A.queryHash),this.notify({type:"removed",query:A}))}clear(){Sr.batch(()=>{this.getAll().forEach(A=>{this.remove(A)})})}get(A){return et(this,jl).get(A)}getAll(){return[...et(this,jl).values()]}find(A){const t={exact:!0,...A};return this.getAll().find(i=>jsA(t,i))}findAll(A={}){const t=this.getAll();return Object.keys(A).length>0?t.filter(i=>jsA(A,i)):t}notify(A){Sr.batch(()=>{this.listeners.forEach(t=>{t(A)})})}onFocus(){Sr.batch(()=>{this.getAll().forEach(A=>{A.onFocus()})})}onOnline(){Sr.batch(()=>{this.getAll().forEach(A=>{A.onOnline()})})}},jl=new WeakMap,faA),vo,Bu,Eu,iS,nS,Qu,gS,oS,yaA,KNe=(yaA=class{constructor(e={}){Hn(this,vo);Hn(this,Bu);Hn(this,Eu);Hn(this,iS);Hn(this,nS);Hn(this,Qu);Hn(this,gS);Hn(this,oS);Pi(this,vo,e.queryCache||new vNe),Pi(this,Bu,e.mutationCache||new UNe),Pi(this,Eu,e.defaultOptions||{}),Pi(this,iS,new Map),Pi(this,nS,new Map),Pi(this,Qu,0)}mount(){zG(this,Qu)._++,et(this,Qu)===1&&(Pi(this,gS,mSA.subscribe(async e=>{e&&(await this.resumePausedMutations(),et(this,vo).onFocus())})),Pi(this,oS,OJ.subscribe(async e=>{e&&(await this.resumePausedMutations(),et(this,vo).onOnline())})))}unmount(){var e,A;zG(this,Qu)._--,et(this,Qu)===0&&((e=et(this,gS))==null||e.call(this),Pi(this,gS,void 0),(A=et(this,oS))==null||A.call(this),Pi(this,oS,void 0))}isFetching(e){return et(this,vo).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return et(this,Bu).findAll({...e,status:"pending"}).length}getQueryData(e){var t;const A=this.defaultQueryOptions({queryKey:e});return(t=et(this,vo).get(A.queryHash))==null?void 0:t.state.data}ensureQueryData(e){const A=this.defaultQueryOptions(e),t=et(this,vo).build(this,A),i=t.state.data;return i===void 0?this.fetchQuery(e):(e.revalidateIfStale&&t.isStaleByTime(q4(A.staleTime,t))&&this.prefetchQuery(A),Promise.resolve(i))}getQueriesData(e){return et(this,vo).findAll(e).map(({queryKey:A,state:t})=>{const i=t.data;return[A,i]})}setQueryData(e,A,t){const i=this.defaultQueryOptions({queryKey:e}),n=et(this,vo).get(i.queryHash),g=n==null?void 0:n.state.data,o=lNe(A,g);if(o!==void 0)return et(this,vo).build(this,i).setData(o,{...t,manual:!0})}setQueriesData(e,A,t){return Sr.batch(()=>et(this,vo).findAll(e).map(({queryKey:i})=>[i,this.setQueryData(i,A,t)]))}getQueryState(e){var t;const A=this.defaultQueryOptions({queryKey:e});return(t=et(this,vo).get(A.queryHash))==null?void 0:t.state}removeQueries(e){const A=et(this,vo);Sr.batch(()=>{A.findAll(e).forEach(t=>{A.remove(t)})})}resetQueries(e,A){const t=et(this,vo);return Sr.batch(()=>(t.findAll(e).forEach(i=>{i.reset()}),this.refetchQueries({type:"active",...e},A)))}cancelQueries(e,A={}){const t={revert:!0,...A},i=Sr.batch(()=>et(this,vo).findAll(e).map(n=>n.cancel(t)));return Promise.all(i).then(bc).catch(bc)}invalidateQueries(e,A={}){return Sr.batch(()=>(et(this,vo).findAll(e).forEach(t=>{t.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},A)))}refetchQueries(e,A={}){const t={...A,cancelRefetch:A.cancelRefetch??!0},i=Sr.batch(()=>et(this,vo).findAll(e).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let g=n.fetch(void 0,t);return t.throwOnError||(g=g.catch(bc)),n.state.fetchStatus==="paused"?Promise.resolve():g}));return Promise.all(i).then(bc)}fetchQuery(e){const A=this.defaultQueryOptions(e);A.retry===void 0&&(A.retry=!1);const t=et(this,vo).build(this,A);return t.isStaleByTime(q4(A.staleTime,t))?t.fetch(A):Promise.resolve(t.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(bc).catch(bc)}fetchInfiniteQuery(e){return e.behavior=XsA(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(bc).catch(bc)}ensureInfiniteQueryData(e){return e.behavior=XsA(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return OJ.isOnline()?et(this,Bu).resumePausedMutations():Promise.resolve()}getQueryCache(){return et(this,vo)}getMutationCache(){return et(this,Bu)}getDefaultOptions(){return et(this,Eu)}setDefaultOptions(e){Pi(this,Eu,e)}setQueryDefaults(e,A){et(this,iS).set(rR(e),{queryKey:e,defaultOptions:A})}getQueryDefaults(e){const A=[...et(this,iS).values()],t={};return A.forEach(i=>{IR(e,i.queryKey)&&Object.assign(t,i.defaultOptions)}),t}setMutationDefaults(e,A){et(this,nS).set(rR(e),{mutationKey:e,defaultOptions:A})}getMutationDefaults(e){const A=[...et(this,nS).values()],t={};return A.forEach(i=>{IR(e,i.mutationKey)&&Object.assign(t,i.defaultOptions)}),t}defaultQueryOptions(e){if(e._defaulted)return e;const A={...et(this,Eu).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return A.queryHash||(A.queryHash=_V(A.queryKey,A)),A.refetchOnReconnect===void 0&&(A.refetchOnReconnect=A.networkMode!=="always"),A.throwOnError===void 0&&(A.throwOnError=!!A.suspense),!A.networkMode&&A.persister&&(A.networkMode="offlineFirst"),A.queryFn===JV&&(A.enabled=!1),A}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...et(this,Eu).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){et(this,vo).clear(),et(this,Bu).clear()}},vo=new WeakMap,Bu=new WeakMap,Eu=new WeakMap,iS=new WeakMap,nS=new WeakMap,Qu=new WeakMap,gS=new WeakMap,oS=new WeakMap,yaA),FNe=E.createContext(void 0),_Ne=({client:e,children:A})=>(E.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),C.jsx(FNe.Provider,{value:e,children:A}));const MSA=BSA({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),NSA=BSA({id:137,name:"Polygon",nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-rpc.com"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com",apiUrl:"https://api.polygonscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:25770160}}});LV.type="walletConnect";function LV(e){const A=e.isNewChainsStale??!0;let t,i;const n="eip155";let g,o,s,a,r,I;return c=>({id:"walletConnect",name:"WalletConnect",type:LV.type,async setup(){const l=await this.getProvider().catch(()=>null);l&&(s||(s=this.onConnect.bind(this),l.on("connect",s)),r||(r=this.onSessionDelete.bind(this),l.on("session_delete",r)))},async connect({chainId:l,withCapabilities:B,...Q}={}){var h,d;try{const p=await this.getProvider();if(!p)throw new tu;a||(a=this.onDisplayUri,p.on("display_uri",a));let y=l;if(!y){const k=await((h=c.storage)==null?void 0:h.getItem("state"))??{};c.chains.some(G=>G.id===k.chainId)?y=k.chainId:y=(d=c.chains[0])==null?void 0:d.id}if(!y)throw new Error("No chains found on connector.");const m=await this.isChainsStale();if(p.session&&m&&await p.disconnect(),!p.session||m){const k=c.chains.filter(N=>N.id!==y).map(N=>N.id);await p.connect({optionalChains:[y,...k],..."pairingTopic"in Q?{pairingTopic:Q.pairingTopic}:{}}),this.setRequestedChainsIds(c.chains.map(N=>N.id))}const D=(await p.enable()).map(k=>fp(k));let S=await this.getChainId();if(l&&S!==l){const k=await this.switchChain({chainId:l}).catch(N=>{var G;if(N.code===_s.code&&((G=N.cause)==null?void 0:G.message)!=="Missing or invalid. request() method: wallet_addEthereumChain")throw N;return{id:S}});S=(k==null?void 0:k.id)??S}return a&&(p.removeListener("display_uri",a),a=void 0),s&&(p.removeListener("connect",s),s=void 0),g||(g=this.onAccountsChanged.bind(this),p.on("accountsChanged",g)),o||(o=this.onChainChanged.bind(this),p.on("chainChanged",o)),I||(I=this.onDisconnect.bind(this),p.on("disconnect",I)),r||(r=this.onSessionDelete.bind(this),p.on("session_delete",r)),{accounts:B?D.map(k=>({address:k,capabilities:{}})):D,chainId:S}}catch(p){throw/(user rejected|connection request reset)/i.test(p==null?void 0:p.message)?new _s(p):p}},async disconnect(){const l=await this.getProvider();try{await(l==null?void 0:l.disconnect())}catch(B){if(!/No matching key/i.test(B.message))throw B}finally{o&&(l==null||l.removeListener("chainChanged",o),o=void 0),I&&(l==null||l.removeListener("disconnect",I),I=void 0),s||(s=this.onConnect.bind(this),l==null||l.on("connect",s)),g&&(l==null||l.removeListener("accountsChanged",g),g=void 0),r&&(l==null||l.removeListener("session_delete",r),r=void 0),this.setRequestedChainsIds([])}},async getAccounts(){return(await this.getProvider()).accounts.map(B=>fp(B))},async getProvider({chainId:l}={}){var Q;async function B(){const h=c.chains.map(p=>p.id);if(!h.length)return;const{EthereumProvider:d}=await Qi(async()=>{const{EthereumProvider:p}=await import("./index.es-LUPp7F4V.js").then(y=>y._);return{EthereumProvider:p}},__vite__mapDeps([19,1]));return await d.init({...e,disableProviderPing:!0,optionalChains:h,projectId:e.projectId,rpcMap:Object.fromEntries(c.chains.map(p=>{const[y]=oNe({chain:p,transports:c.transports});return[p.id,y]})),showQrModal:e.showQrModal??!0})}return t||(i||(i=B()),t=await i,t==null||t.events.setMaxListeners(Number.POSITIVE_INFINITY)),l&&await((Q=this.switchChain)==null?void 0:Q.call(this,{chainId:l})),t},async getChainId(){return(await this.getProvider()).chainId},async isAuthorized(){try{const[l,B]=await Promise.all([this.getAccounts(),this.getProvider()]);return l.length?await this.isChainsStale()&&B.session?(await B.disconnect().catch(()=>{}),!1):!0:!1}catch{return!1}},async switchChain({addEthereumChainParameter:l,chainId:B}){var d,p,y;const Q=await this.getProvider();if(!Q)throw new tu;const h=c.chains.find(m=>m.id===B);if(!h)throw new Dd(new HJ);try{await Promise.all([new Promise(D=>{const S=({chainId:k})=>{k===B&&(c.emitter.off("change",S),D())};c.emitter.on("change",S)}),Q.request({method:"wallet_switchEthereumChain",params:[{chainId:$S(B)}]})]);const m=await this.getRequestedChainsIds();return this.setRequestedChainsIds([...m,B]),h}catch(m){const D=m;if(/(user rejected)/i.test(D.message))throw new _s(D);try{let S;l!=null&&l.blockExplorerUrls?S=l.blockExplorerUrls:S=(d=h.blockExplorers)!=null&&d.default.url?[(p=h.blockExplorers)==null?void 0:p.default.url]:[];let k;(y=l==null?void 0:l.rpcUrls)!=null&&y.length?k=l.rpcUrls:k=[...h.rpcUrls.default.http];const N={blockExplorerUrls:S,chainId:$S(B),chainName:(l==null?void 0:l.chainName)??h.name,iconUrls:l==null?void 0:l.iconUrls,nativeCurrency:(l==null?void 0:l.nativeCurrency)??h.nativeCurrency,rpcUrls:k};await Q.request({method:"wallet_addEthereumChain",params:[N]});const G=await this.getRequestedChainsIds();return this.setRequestedChainsIds([...G,B]),h}catch(S){throw new _s(S)}}},onAccountsChanged(l){l.length===0?this.onDisconnect():c.emitter.emit("change",{accounts:l.map(B=>fp(B))})},onChainChanged(l){const B=Number(l);c.emitter.emit("change",{chainId:B})},async onConnect(l){const B=Number(l.chainId),Q=await this.getAccounts();c.emitter.emit("connect",{accounts:Q,chainId:B})},async onDisconnect(l){this.setRequestedChainsIds([]),c.emitter.emit("disconnect");const B=await this.getProvider();g&&(B.removeListener("accountsChanged",g),g=void 0),o&&(B.removeListener("chainChanged",o),o=void 0),I&&(B.removeListener("disconnect",I),I=void 0),r&&(B.removeListener("session_delete",r),r=void 0),s||(s=this.onConnect.bind(this),B.on("connect",s))},onDisplayUri(l){c.emitter.emit("message",{type:"display_uri",data:l})},onSessionDelete(){this.onDisconnect()},getNamespaceChainsIds(){var B,Q,h;return t?((h=(Q=(B=t.session)==null?void 0:B.namespaces[n])==null?void 0:Q.accounts)==null?void 0:h.map(d=>Number.parseInt(d.split(":")[1]||"",10)))??[]:[]},async getRequestedChainsIds(){var l;return await((l=c.storage)==null?void 0:l.getItem(this.requestedChainsStorageKey))??[]},async isChainsStale(){if(!A)return!1;const l=c.chains.map(h=>h.id),B=this.getNamespaceChainsIds();if(B.length&&!B.some(h=>l.includes(h)))return!1;const Q=await this.getRequestedChainsIds();return!l.every(h=>Q.includes(h))},async setRequestedChainsIds(l){var B;await((B=c.storage)==null?void 0:B.setItem(this.requestedChainsStorageKey,l))},get requestedChainsStorageKey(){return`${this.id}.requestedChains`}})}var LO={};const JNe=[MSA,NSA],LNe=new KNe,xNe=pSA({storage:nNe});function TNe(){const e=!!(import.meta.vitest||typeof process<"u"&&(LO!=null&&LO.VITEST_WORKER_ID)),A=[pT({shimDisconnect:!0})];if(e)console.info("[wallet] test environment detected – skipping walletConnect connector");else try{A.push(LV({projectId:"demo",showQrModal:!0}))}catch(t){console.warn("[wallet] walletConnect initialization skipped:",(t==null?void 0:t.message)||t)}return tNe({chains:JNe,multiInjectedProviderDiscovery:!0,transports:{[MSA.id]:YsA(),[NSA.id]:YsA()},connectors:A,ssr:!1,storage:xNe,syncConnectedChain:!0})}function qNe({children:e}){const A=TNe();return C.jsx(rNe,{config:A,children:C.jsx(_Ne,{client:LNe,children:e})})}E.createContext(void 0);const RSA=E.createContext(void 0);async function YNe(){try{const e=new AbortController,A=setTimeout(()=>e.abort(),5e3),t=await fetch("/api/features",{cache:"no-store",signal:e.signal});return clearTimeout(A),t.ok?await t.json():null}catch{return null}}function HNe({children:e}){const[A,t]=E.useState(!1),[i,n]=E.useState(!1),g=async()=>{var s;const o=await YNe();n(!!((s=o==null?void 0:o.features)!=null&&s.wallet)),t(!0)};return E.useEffect(()=>{const o=g(),s=window.setTimeout(()=>{t(a=>(a||console.warn("[features] fallback timeout - forcing loaded"),!0))},6e3);return o.finally(()=>clearTimeout(s)),()=>clearTimeout(s)},[]),C.jsx(RSA.Provider,{value:{loaded:A,walletEnabled:i,refresh:g},children:e})}function ONe(){return E.useContext(RSA)??{loaded:!0,walletEnabled:!1,refresh:()=>{}}}class GSA extends ue.Component{constructor(){super(...arguments);Oi(this,"state",{hasError:!1});Oi(this,"handleReset",()=>{var t,i;this.setState({hasError:!1,error:void 0}),(i=(t=this.props).onReset)==null||i.call(t)})}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){var g,o,s,a;(o=(g=this.props).onError)==null||o.call(g,t,i),WP.error("ErrorBoundary caught",{message:t==null?void 0:t.message,stack:(s=t==null?void 0:t.stack)==null?void 0:s.slice(0,1e3),componentStack:(a=i==null?void 0:i.componentStack)==null?void 0:a.slice(0,500)}),typeof process<"u"&&!0||typeof import.meta<"u"&&!0||console.error("ErrorBoundary caught an error:",t,i)}render(){return this.state.hasError?this.props.fallback?C.jsx(C.Fragment,{children:this.props.fallback}):C.jsxs("div",{className:"error-boundary",role:"alert",style:{padding:16},children:[C.jsx("h2",{children:"Something went wrong"}),C.jsx("p",{children:"Please refresh or return to the previous screen."}),C.jsx("button",{className:"felt-btn",onClick:this.handleReset,children:"Try again"})]}):this.props.children}}var AaA;(function(e){e[e.Sunday=1]="Sunday",e[e.Monday=2]="Monday",e[e.Tuesday=3]="Tuesday",e[e.Wednesday=4]="Wednesday",e[e.Thursday=5]="Thursday",e[e.Friday=6]="Friday",e[e.Saturday=7]="Saturday"})(AaA||(AaA={}));const ap=md("LocalNotifications",{web:()=>Qi(()=>import("./web-BC_xQ4dh.js"),__vite__mapDeps([20,1])).then(e=>new e.LocalNotificationsWeb)});let O4=null,eaA=!1,Fv=null;function PNe(){return O4||eaA?Promise.resolve():Fv||(eaA=!0,Fv=Qi(()=>import("./index-Dj2TZsNT.js"),__vite__mapDeps([21,1])).then(e=>{const A=e.FirebaseMessaging;A&&typeof A.getToken=="function"?(O4=A,console.info("[Push] FirebaseMessaging plugin loaded successfully")):console.warn("[Push] FirebaseMessaging plugin not available (native rebuild required)")}).catch(e=>{console.warn("[Push] Failed to load FirebaseMessaging (OTA update on old app version?):",e)}),Fv)}function jNe(){return O4}let taA=!1,tw=null;async function bSA(e={}){if(taA)return;taA=!0;const A=Ui.getPlatform(),t=A==="ios"||A==="android";if(console.info(`[Push] initNotifications called - platform=${A} isNative=${t}`),!t){console.info("[Push] Not native platform, skipping push setup");return}const i=e.enableLocal!==!1,n=e.enablePush!==!1;if(console.info(`[Push] enableLocal=${i} enablePush=${n}`),i)try{await zNe()}catch{}if(n)try{await ZNe(e.onPushToken)}catch(g){console.warn("[Push] Setup failed:",g)}}async function zNe(){var e;try{if((await ap.requestPermissions()).display!=="granted")return}catch{}try{await((e=ap.createChannel)==null?void 0:e.call(ap,{id:"default",name:"General",description:"General notifications",importance:4,visibility:1,sound:void 0,lights:!0,vibration:!0}))}catch{}try{ap.addListener("localNotificationActionPerformed",A=>{var i,n;console.info("[LocalNotifications] action",A==null?void 0:A.actionId,(i=A==null?void 0:A.notification)==null?void 0:i.id);const t=(n=A==null?void 0:A.notification)==null?void 0:n.extra;t!=null&&t.type&&USA({notification:{data:t}})})}catch{}}async function ZNe(e){console.info("[Push] setupPushNotifications starting..."),await PNe();const A=jNe();if(!A){console.warn("[Push] FirebaseMessaging not available, skipping push setup");return}try{console.info("[Push] Requesting permissions...");const t=await A.requestPermissions();if(console.info("[Push] Permission result:",JSON.stringify(t)),t.receive!=="granted"){console.warn("[Push] Permission not granted, receive=",t.receive);return}console.info("[Push] ✅ Permission granted")}catch(t){console.warn("[Push] Permission request failed:",t);return}try{console.info("[Push] Getting FCM token...");const{token:t}=await A.getToken();if(t){console.info("[Push] 🔥 FCM token received:",t.substring(0,20)+"..."),tw=t;try{e==null||e(t)}catch{}iw(t)}else console.warn("[Push] getToken returned empty token")}catch(t){console.warn("[Push] Failed to get FCM token:",t)}A.addListener("tokenReceived",({token:t})=>{console.info("[Push] 🔥 FCM token refreshed:",t.substring(0,20)+"..."),tw=t;try{e==null||e(t)}catch{}iw(t)}),A.addListener("notificationReceived",t=>{const i=t==null?void 0:t.notification,n=i==null?void 0:i.title,g=i==null?void 0:i.body;if(console.info("[Push] foreground received",n),!n)return;const o=i!=null&&i.data&&typeof i.data=="object"?{...i.data}:void 0;vSA(n,g||"",o).catch(()=>{})}),A.addListener("notificationActionPerformed",t=>{console.info("[Push] action performed",t),USA(t)})}let HK=!1,xO=!1,tp=0,P4=0;const TO=10,WNe=5e3;function VNe(){var A,t;const e=(globalThis==null?void 0:globalThis.APP_TARGET)||((t=(A=import.meta)==null?void 0:A.env)==null?void 0:t.VITE_APP_TARGET)||"";switch(e){case"skills":return"com.zentaraone.skillslounge";case"craps":return"com.zentaraone.crapslounge";case"ceelo":return"com.zentaraone.ceelolounge";case"poker":return"com.zentaraone.pokerlounge";default:return e||"unknown"}}function iw(e){const A=e||tw;if(!A){console.warn("[Push] registerPushTokenWithServer called but no token available");return}if(HK&&A===tw){console.info("[Push] Token already registered, skipping");return}if(xO){console.info("[Push] Token registration already pending, skipping");return}const t=Ui.getPlatform();if(t==="web"){console.info("[Push] Web platform, skipping token registration");return}const i=hw();if(console.info(`[Push] Socket state: exists=${!!i} connected=${i==null?void 0:i.connected}`),!(i!=null&&i.connected)){tp++,tp<=TO?(console.info(`[Push] Socket not connected, will retry (${tp}/${TO})`),setTimeout(()=>iw(A),2e3)):console.warn("[Push] Max registration retries reached, giving up");return}const n=VNe(),g=A.substring(0,20)+"..."+A.substring(A.length-10);console.info(`[Push] Registering token: ${g} platform=${t} appId=${n}`),xO=!0,i.emit("push:register_token",{token:A,platform:t,appId:n},o=>{xO=!1,o!=null&&o.success?(HK=!0,tp=0,P4=Date.now(),console.info("[Push] ✅ Token registered with server successfully")):(console.warn("[Push] ❌ Token registration failed:",o==null?void 0:o.error),!HK&&tp<TO&&(tp++,setTimeout(()=>iw(A),3e3)))})}function XNe(){if(tw){const e=Date.now();if(e-P4<WNe){console.info("[Push] Skipping re-register (debounce)");return}P4=e,HK=!1,tp=0,console.info("[Push] Re-registering token after reconnect"),iw(tw)}}function USA(e){var t;const A=(t=e==null?void 0:e.notification)==null?void 0:t.data;if(console.info("[Push] handlePushActionFirebase",{data:A}),!!A)switch(A.type){case"game_invite":if(A.roomId){const i=A.gameType||"";let n;i==="poker"?n=`/poker/room/${A.roomId}`:i==="skills"?n=`/skills/room/${A.roomId}`:n=`/room/${A.roomId}`,console.info("[Push] Navigating to room:",n),window.location.href=n}break;case"friend_request":console.info("[Push] Navigating to profile for friend request"),window.location.href="/profile";break;case"friend_accepted":console.info("[Push] Navigating to profile for friend accepted"),window.location.href="/profile";break;case"message":A.senderId?(console.info("[Push] Navigating to messages screen with peer:",A.senderId),window.location.href=`/messages?peer=${encodeURIComponent(A.senderId)}`):(console.info("[Push] Navigating to messages screen (no senderId)"),window.location.href="/messages");break;default:console.info("[Push] Unknown notification type, navigating to lobby"),window.location.href="/lobby";break}}async function vSA(e,A,t){if(!(Ui.getPlatform()==="ios"||Ui.getPlatform()==="android"))return;try{if((await ap.checkPermissions()).display!=="granted")return}catch{}const g={notifications:[{id:Math.floor(Date.now()%2147483647),title:e,body:A,schedule:{at:new Date(Date.now()+10)},smallIcon:"ic_stat_name",channelId:"default",extra:t}]};try{await ap.schedule(g)}catch{}}const $Ne=Object.freeze(Object.defineProperty({__proto__:null,initNotifications:bSA,reRegisterPushToken:XNe,registerPushTokenWithServer:iw,scheduleLocalNow:vSA},Symbol.toStringTag,{value:"Module"}));function ARe({cooldownMs:e=5e3,initialGraceMs:A=900}){const t=Ms(),{room:i}=nI(),n=E.useRef(0),g=E.useRef(!1),o=E.useRef(!1),s=E.useRef(Date.now());return E.useEffect(()=>{(()=>{try{return typeof window<"u"&&window.location.search.includes("debugForeground=1")||typeof localStorage<"u"&&localStorage.getItem("debug:foreground")==="1"}catch{return!1}})();const a=Date.now();try{window.__fgMountedAt=a}catch{}try{console.log("[fg] BotNudgeOnForeground mounted",{t:a,hint:"enable logs via ?debugForeground=1 or localStorage.setItem('debug:foreground','1')"})}catch{}},[]),E.useEffect(()=>{let a=[],r=!1;const I=(()=>{try{return typeof window<"u"&&window.location.search.includes("debugForeground=1")||typeof localStorage<"u"&&localStorage.getItem("debug:foreground")==="1"}catch{return!1}})(),c=async(p,y=!1)=>{if(r)return;const m=Date.now();if(!(!y&&m-s.current<A)&&!g.current&&!(!y&&m-n.current<e)){g.current=!0;try{const D=(i==null?void 0:i.id)||void 0;if(t)if(I)try{const S=await g1(t,Lt.BOTS_NUDGE,{roomId:D},{timeoutMs:5e3});try{window.__fgLastAck=S}catch{}console.log("[fg] nudged bots (ack)",{reason:p,roomId:D,force:y,ack:S})}catch(S){console.warn("[fg] nudged bots (ack failed)",{reason:p,roomId:D,force:y,error:S==null?void 0:S.message})}else await KcA(t,Lt.BOTS_NUDGE,{roomId:D}),I&&console.log("[fg] nudged bots",{reason:p,roomId:D,force:y});n.current=m}catch{}finally{g.current=!1}}},l=async(p,y=!1)=>{if(r)return;const m=Date.now();if(!(!y&&m-s.current<A)&&!o.current){if(o.current=!0,!y&&m-n.current<e){o.current=!1;return}try{const D=(i==null?void 0:i.id)||void 0;if(!t)return;try{await eM(t)}catch{}try{const S=await g1(t,Lt.ROOM_REFRESH_STATE,{roomId:D},{timeoutMs:5e3});!(S!=null&&S.ok)&&I?console.warn("[fg] refresh_state nack",{reason:p,roomId:D,ack:S}):I&&console.log("[fg] refresh_state ack",{reason:p,roomId:D}),n.current=m}catch(S){I&&console.warn("[fg] refresh_state failed",{reason:p,roomId:D,error:S==null?void 0:S.message})}}catch{}finally{o.current=!1}}};try{window.__fgNudge=(p,y)=>{c(p||"manual",!!y)}}catch{}(async()=>{try{const p=await Nr.addListener("appStateChange",y=>{if(!r)if(y.isActive)I&&console.log("[fg] appStateChange: active"),(async()=>{try{await eM(t)}catch{}c("native_appstate_active",!0),l("native_appstate_active")})();else{I&&console.log("[fg] appStateChange: inactive");try{Fp(t,"BotNudgeOnForeground: appStateChange inactive")}catch{}}});I&&console.log("[fg] appStateChange listener attached");try{window.__fgAppStateListener=!0}catch{}a.push(()=>{try{p.remove()}catch{}})}catch{I&&console.log("[fg] appStateChange not available (web or plugin missing)")}})(),(async()=>{try{const p=await Nr.addListener("pause",()=>{var y;I&&console.log("[fg] pause");try{(y=window==null?void 0:window.Capacitor)!=null&&y.isNativePlatform&&Fp(t,"BotNudgeOnForeground: pause event")}catch{}});I&&console.log("[fg] pause listener attached");try{window.__fgPauseListener=!0}catch{}a.push(()=>{try{p.remove()}catch{}})}catch{I&&console.log("[fg] pause not available")}})(),(async()=>{try{const p=await Nr.addListener("resume",async()=>{I&&console.log("[fg] resume");try{await eM(t)}catch{}c("native_resume",!0),l("native_resume")});I&&console.log("[fg] resume listener attached");try{window.__fgResumeListener=!0}catch{}a.push(()=>{try{p.remove()}catch{}})}catch{I&&console.log("[fg] resume not available")}})();const B=()=>{r||document.visibilityState==="visible"&&(I&&console.log("[fg] visibility: visible"),c("web_visibility"),l("web_visibility"))};document.addEventListener("visibilitychange",B),a.push(()=>document.removeEventListener("visibilitychange",B));const Q=()=>{r||(I&&console.log("[fg] window focus"),c("web_focus"),l("web_focus"))},h=()=>{r||(I&&console.log("[fg] window pageshow"),c("web_pageshow"),l("web_pageshow"))};window.addEventListener("focus",Q),window.addEventListener("pageshow",h),a.push(()=>{window.removeEventListener("focus",Q),window.removeEventListener("pageshow",h)});const d=setTimeout(()=>{I&&console.log("[fg] initial_mount nudge"),c("initial_mount"),l("initial_mount")},2500);return a.push(()=>clearTimeout(d)),()=>{r=!0,a.forEach(p=>{try{p()}catch{}})}},[t,i==null?void 0:i.id,e]),null}function da(){try{const e=performance.memory;return e?{usedJSHeapMB:Math.round(e.usedJSHeapSize/1048576),totalJSHeapMB:Math.round(e.totalJSHeapSize/1048576),limitJSHeapMB:Math.round(e.jsHeapSizeLimit/1048576)}:void 0}catch{return}}function eRe(){const e=Ms(),A=E.useRef(Date.now());return E.useEffect(()=>{let t=!1;const i=[];Ks.info("NativeCrashLogger mounted",{mem:da()});async function n(){const g=[Nr.addListener("appStateChange",s=>{t||(s.isActive?Ks.info("appStateChange → ACTIVE",{mem:da(),since:Date.now()-A.current}):Ks.warn("appStateChange → INACTIVE",{mem:da()}))}),Nr.addListener("pause",()=>{t||Ks.warn("PAUSE (backgrounded)",{mem:da()})}),Nr.addListener("resume",()=>{t||Ks.info("RESUME (foregrounded)",{mem:da()})}),Nr.addListener("backButton",()=>{t||Ks.info("BACK_BUTTON pressed")})],o=await Promise.allSettled(g);for(const s of o)if(s.status==="fulfilled")if(t)try{s.value.remove()}catch{}else i.push(s.value)}return n().catch(()=>{}),()=>{t=!0,i.forEach(g=>{try{g.remove()}catch{}})}},[]),E.useEffect(()=>{const t=()=>{document.visibilityState==="hidden"?Ks.warn("visibility → HIDDEN",{mem:da()}):Ks.info("visibility → VISIBLE",{mem:da()})},i=()=>Ks.info("network → ONLINE"),n=()=>Ks.warn("network → OFFLINE"),g=()=>Ks.error("PAGE FREEZE (frozen)",{mem:da()}),o=a=>Ks.warn("pagehide",{persisted:a.persisted,mem:da()}),s=a=>Ks.info("pageshow",{persisted:a.persisted,mem:da()});return document.addEventListener("visibilitychange",t),window.addEventListener("online",i),window.addEventListener("offline",n),window.addEventListener("freeze",g),window.addEventListener("pagehide",o),window.addEventListener("pageshow",s),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",i),window.removeEventListener("offline",n),window.removeEventListener("freeze",g),window.removeEventListener("pagehide",o),window.removeEventListener("pageshow",s)}},[]),E.useEffect(()=>{var I,c,l,B,Q,h,d,p;if(!e)return;const t=e,i=()=>{var y,m,D;return FC.info("CONNECTED",{id:t.id,transport:(D=(m=(y=t.io)==null?void 0:y.engine)==null?void 0:m.transport)==null?void 0:D.name})},n=y=>FC.warn("DISCONNECTED",{reason:y,mem:da()}),g=y=>{const m=String((y==null?void 0:y.message)||"");if(m==="NO_AUTH_TOKEN"){FC.info("CONNECT_SKIPPED_NO_AUTH",{message:m,type:y==null?void 0:y.type});return}FC.error("CONNECT_ERROR",{message:m,type:y==null?void 0:y.type})},o=y=>FC.info("RECONNECTED",{attempt:y}),s=y=>FC.debug("reconnect_attempt",{attempt:y}),a=y=>FC.warn("reconnect_error",{message:y==null?void 0:y.message}),r=()=>FC.error("RECONNECT_FAILED (gave up)");return t.on("connect",i),t.on("disconnect",n),t.on("connect_error",g),(c=(I=t.io)==null?void 0:I.on)==null||c.call(I,"reconnect",o),(B=(l=t.io)==null?void 0:l.on)==null||B.call(l,"reconnect_attempt",s),(h=(Q=t.io)==null?void 0:Q.on)==null||h.call(Q,"reconnect_error",a),(p=(d=t.io)==null?void 0:d.on)==null||p.call(d,"reconnect_failed",r),()=>{var y,m,D,S,k,N,G,M;t.off("connect",i),t.off("disconnect",n),t.off("connect_error",g),(m=(y=t.io)==null?void 0:y.off)==null||m.call(y,"reconnect",o),(S=(D=t.io)==null?void 0:D.off)==null||S.call(D,"reconnect_attempt",s),(N=(k=t.io)==null?void 0:k.off)==null||N.call(k,"reconnect_error",a),(M=(G=t.io)==null?void 0:G.off)==null||M.call(G,"reconnect_failed",r)}},[e]),E.useEffect(()=>{const t=n=>{var g;JI.error("WebGL CONTEXT LOST",{tagName:(g=n.target)==null?void 0:g.tagName,mem:da()})},i=n=>{var g;JI.info("WebGL context restored",{tagName:(g=n.target)==null?void 0:g.tagName})};return document.addEventListener("webglcontextlost",t,!0),document.addEventListener("webglcontextrestored",i,!0),()=>{document.removeEventListener("webglcontextlost",t,!0),document.removeEventListener("webglcontextrestored",i,!0)}},[]),E.useEffect(()=>{const t=n=>{var g,o,s;try{const a=n.message||"";if(a.includes("websocket error")||a.includes("WebSocket"))return;WP.error("window.error",{message:a,filename:n.filename,line:n.lineno,col:n.colno,stack:(s=(o=(g=n.error)==null?void 0:g.stack)==null?void 0:o.slice)==null?void 0:s.call(o,0,1e3),mem:da()})}catch{}},i=n=>{var g,o,s,a;try{const r=n.reason,I=typeof r=="string"?r:(r==null?void 0:r.message)||"unhandledrejection";if((r==null?void 0:r.name)==="AbortError"||(g=I==null?void 0:I.includes)!=null&&g.call(I,"aborted")||I==="NO_AUTH_TOKEN")return;WP.error("unhandledrejection",{message:(o=I==null?void 0:I.slice)==null?void 0:o.call(I,0,500),stack:(a=(s=(r==null?void 0:r.stack)||"").slice)==null?void 0:a.call(s,0,1e3),mem:da()})}catch{}};return window.addEventListener("error",t),window.addEventListener("unhandledrejection",i),()=>{window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",i)}},[]),E.useEffect(()=>{if(!performance.memory)return;const t=setInterval(()=>{const i=da();i&&i.usedJSHeapMB>150&&Ks.warn("HIGH_MEMORY",i)},3e4);return()=>clearInterval(t)},[]),E.useEffect(()=>{if(typeof PerformanceObserver>"u")return;let t=null;try{t=new PerformanceObserver(i=>{for(const n of i.getEntries()){const g=Math.round(n.duration);g>200&&Ks.warn("LONG_TASK",{durationMs:g,name:n.name,startTime:Math.round(n.startTime),mem:da()})}}),t.observe({type:"longtask",buffered:!1})}catch{}return()=>{try{t==null||t.disconnect()}catch{}}},[]),E.useEffect(()=>{let n=Date.now();const g=setInterval(()=>{const o=Date.now(),s=o-n;s>5e3&&Ks.error("EVENT_LOOP_STALL",{gapMs:s,expectedMs:2e3,mem:da()}),n=o},2e3);return()=>clearInterval(g)},[]),E.useEffect(()=>{try{window.__dumpLogs=()=>{const t=VM();return console.table(t.map(i=>({time:new Date(i.t).toISOString().slice(11,23),tag:i.tag,level:i.level,msg:i.msg,data:i.data?JSON.stringify(i.data).slice(0,120):""}))),t},window.__dumpCrashLogs=()=>{const t=C8();return console.table(t.map(i=>{var n;return{time:new Date(i.t).toISOString().slice(11,23),tag:i.tag,level:i.level,msg:i.msg,data:typeof i.data=="string"?i.data.slice(0,120):(n=JSON.stringify(i.data))==null?void 0:n.slice(0,120)}})),t}}catch{}},[]),null}function tRe(){const[e,A]=E.useState(()=>{var s;try{return((s=window.localStorage)==null?void 0:s.getItem("sfxDebug"))==="1"}catch{return!1}}),[t,i]=E.useState([]),n=200,g=E.useRef(null);if(E.useEffect(()=>{if(!e)return;const s=a=>{try{const r=a.detail;i(I=>{const c=[...I,r];return c.length>n&&c.splice(0,c.length-n),c})}catch{}};return window.addEventListener("sfx:debug",s),()=>window.removeEventListener("sfx:debug",s)},[e]),!e)return null;const o=E.useMemo(()=>t.map(s=>{const r=[new Date(s.t||Date.now()).toLocaleTimeString(),s.kind];return s.key&&r.push(s.key),s.volume!=null&&r.push(`v=${s.volume}`),s.rate!=null&&r.push(`r=${s.rate}`),s.reason&&r.push(`(${s.reason})`),r.join(" ")}),[t]);return E.useEffect(()=>{var s;try{(s=g.current)==null||s.scrollTo({top:g.current.scrollHeight})}catch{}},[o.length]),C.jsxs("div",{style:{position:"fixed",right:8,bottom:8,width:360,maxHeight:240,zIndex:99999,background:"rgba(0,0,0,0.7)",color:"#fff",borderRadius:6,border:"1px solid rgba(255,255,255,0.2)",boxShadow:"0 2px 8px rgba(0,0,0,0.3)"},children:[C.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"6px 8px",borderBottom:"1px solid rgba(255,255,255,0.15)"},children:[C.jsx("strong",{style:{fontSize:12,letterSpacing:.3},children:"SFX Debug"}),C.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:6},children:[C.jsx("button",{className:"btn btn-xxs",onClick:()=>i([]),children:"Clear"}),C.jsx("button",{className:"btn btn-xxs",onClick:()=>{A(!1);try{localStorage.removeItem("sfxDebug")}catch{}},children:"Close"})]})]}),C.jsx("div",{ref:g,style:{maxHeight:196,overflow:"auto",padding:"6px 8px",fontFamily:"monospace",fontSize:11,lineHeight:1.35},children:o.map((s,a)=>C.jsx("div",{children:s},a))})]})}function iRe(){const[e,A]=E.useState(()=>{var s;try{const r=new URL(window.location.href).searchParams.get("rtcDebug")==="1",I=((s=window.localStorage)==null?void 0:s.getItem("rtcDebug"))==="1",c=window.__RTC_DEBUG__===!0;return r||I||c}catch{return!1}}),[t,i]=E.useState(()=>{try{return VM().filter(s=>(s==null?void 0:s.tag)==="RTC")}catch{return[]}}),n=400,g=E.useRef(null);if(E.useEffect(()=>{const s=r=>{r.key==="rtcDebug"&&A(r.newValue==="1")};window.addEventListener("storage",s),window.rtcDebugOpen=()=>A(!0),window.rtcDebugClose=()=>A(!1);const a=()=>{try{new URL(window.location.href).searchParams.get("rtcDebug")==="1"&&A(!0)}catch{}};return window.addEventListener("popstate",a),()=>{window.removeEventListener("storage",s),window.removeEventListener("popstate",a);try{delete window.rtcDebugOpen,delete window.rtcDebugClose}catch{}}},[]),E.useEffect(()=>{if(!e)return;const s=a=>{try{const r=a.detail;if(!r||r.tag!=="RTC")return;i(I=>{const c=[...I,r];return c.length>n&&c.splice(0,c.length-n),c})}catch{}};return window.addEventListener("fe:log",s),()=>window.removeEventListener("fe:log",s)},[e]),!e)return null;const o=E.useMemo(()=>t.map(s=>{var l,B;const a=new Date(s.t||Date.now()).toLocaleTimeString(),r=((B=(l=s.level)==null?void 0:l.toUpperCase)==null?void 0:B.call(l))||"LOG",I=s.msg||"",c=s.data?JSON.stringify(s.data):"";return`${a} ${r} ${I} ${c}`}),[t]);return E.useEffect(()=>{var s;try{(s=g.current)==null||s.scrollTo({top:g.current.scrollHeight})}catch{}},[o.length]),C.jsxs("div",{style:{position:"fixed",left:8,bottom:8,width:420,maxHeight:260,zIndex:99998,background:"rgba(0,0,0,0.72)",color:"#fff",borderRadius:6,border:"1px solid rgba(255,255,255,0.2)",boxShadow:"0 2px 8px rgba(0,0,0,0.3)"},children:[C.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"6px 8px",borderBottom:"1px solid rgba(255,255,255,0.15)"},children:[C.jsx("strong",{style:{fontSize:12,letterSpacing:.3},children:"RTC Debug"}),C.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:6},children:[C.jsx("button",{className:"btn btn-xxs",onClick:()=>i([]),children:"Clear"}),C.jsx("button",{className:"btn btn-xxs",onClick:()=>{try{navigator.clipboard.writeText(JSON.stringify(t,null,2))}catch{}},children:"Copy"}),C.jsx("button",{className:"btn btn-xxs",onClick:()=>{A(!1);try{localStorage.removeItem("rtcDebug"),window.__RTC_DEBUG__=!1}catch{}},children:"Close"})]})]}),C.jsx("div",{ref:g,style:{maxHeight:212,overflow:"auto",padding:"6px 8px",fontFamily:"monospace",fontSize:11,lineHeight:1.35},children:o.map((s,a)=>C.jsx("div",{children:s},a))})]})}function nRe(){const{meId:e}=tn(),A=qi(),t=ks(),{info:i,onIdle:n}=Jr(),g=nI(),o=(g==null?void 0:g.room)??null,s=(g==null?void 0:g.setRoom)??null,{leaveRoom:a}=Il(),r=ue.useRef(!1);return ue.useEffect(()=>{const I=t.pathname||"";/^\/(room|poker\/room)\//.test(I)||(r.current=!1)},[t.pathname]),Os({onPlayerBalanceUpdated:({playerId:I,balance:c})=>{if(!(!e||I!==e)&&typeof c=="number"&&!(c>0)&&!r.current&&!MR){r.current=!0;try{o!=null&&o.id&&typeof a=="function"&&a(o.id)}catch{}try{s==null||s(null)}catch{}try{i("Out of Chips","Returning to Lobby…")}catch{}try{A("/lobby",{replace:!0})}catch{}}}}),null}function gRe(e){switch(e){case"cee-lo":return"Cee-Lo";case"craps":return"Craps";case"poker":return"Poker";case"skills":return"Skills Duel";case"zentara":return"Zentara";default:return e}}function oRe(){const e=fpA(),A=qi(),t=E.useRef(null),{getGameRoute:i}=D8(),n=e==null?void 0:e.currentInvite;if(E.useEffect(()=>{if(!n)return;const a=I=>{I.key==="Escape"&&(e==null||e.dismissCurrentInvite())},r=I=>{t.current&&!t.current.contains(I.target)&&(e==null||e.dismissCurrentInvite())};return document.addEventListener("keydown",a),document.addEventListener("mousedown",r),()=>{document.removeEventListener("keydown",a),document.removeEventListener("mousedown",r)}},[n,e]),!n)return null;const g=async()=>{const a=await(e==null?void 0:e.acceptInvite(n.inviteId));if(a!=null&&a.ok&&a.roomId){const r=i(n.gameMode,a.roomId);A(r)}},o=()=>{e==null||e.declineInvite(n.inviteId)},s=C.jsx("div",{className:"modal-backdrop",role:"presentation",style:{position:"fixed",inset:0,zIndex:99999,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0, 0, 0, 0.7)",backdropFilter:"blur(4px)"},children:C.jsxs("div",{className:"modal-panel",role:"dialog","aria-modal":"true","aria-label":"Game invite",ref:t,style:{maxWidth:340,position:"relative",background:"linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)",borderRadius:12,padding:"24px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.5)",border:"1px solid rgba(255, 215, 0, 0.2)"},children:[C.jsx("button",{className:"modal-close",onClick:o,"aria-label":"Close",style:{position:"absolute",top:8,right:8,background:"none",border:"none",color:"#fff",fontSize:"1.5rem",cursor:"pointer",opacity:.7},children:"×"}),C.jsx("h3",{className:"modal-title",style:{marginBottom:12,textAlign:"center",color:"#fff"},children:"🎲 Game Invite"}),C.jsxs("div",{style:{textAlign:"center",marginBottom:16,color:"#fff"},children:[C.jsxs("p",{style:{fontSize:"1rem",margin:"8px 0"},children:[C.jsx("strong",{children:n.fromUserName})," has invited you to play"]}),C.jsx("p",{style:{fontSize:"1.25rem",fontWeight:600,color:"var(--gold, #ffc107)",margin:"8px 0"},children:gRe(n.gameMode)}),C.jsxs("p",{style:{fontSize:"0.875rem",opacity:.8,margin:"4px 0"},children:["Room: ",n.roomName]})]}),C.jsxs("div",{style:{display:"flex",gap:12,marginTop:20,justifyContent:"center"},children:[C.jsx("button",{className:"felt-btn btn--ghost",onClick:o,style:{minWidth:100},children:"Decline"}),C.jsx("button",{className:"felt-btn felt-btn--primary",onClick:g,style:{minWidth:100},children:"Join Game"})]})]})});return er.createPortal(s,document.body)}function sRe(){const e=Ms(),A=E.useRef(0);return E.useEffect(()=>{let t;const i=()=>{var n;try{const g=Kl(),o=g.length?g[g.length-1].ts:0,s=Date.now();if(!e.connected&&s-o>2e4&&s-A.current>1e4){A.current=s,console.warn("[watchdog] No emits in 20s and socket disconnected. Forcing connect attempt…",{lastEmitTs:o,emits:g});try{const a=!!(e!=null&&e.__allowCookieAuth);Za(e,"SocketWatchdog",{allowCookieSession:a})}catch{}}}catch{}t=setTimeout(i,2e3),(n=t.unref)==null||n.call(t)};return i(),()=>clearTimeout(t)},[e]),null}function aRe({children:e,skip:A=!1,maxWaitMs:t=4e3,appTarget:i=""}){const[n,g]=E.useState(!1),[o,s]=E.useState({loaded:0,total:0}),[a,r]=E.useState(!1),I=E.useRef(!1),c=Ui.isNativePlatform(),l=i==="zentara",B=o.total>0?Math.round(o.loaded/o.total*100):0;E.useEffect(()=>{(!c||A)&&g(!0)},[c,A]);const Q=E.useCallback(async()=>{if(I.current)return;I.current=!0,r(!0);try{await On()}catch{}Mpe();const[h,d]=await Promise.all([IvA(t),kpe(t)]);(h||r2())&&d||console.warn("[SoundPreloadScreen] Preload timeout, showing app",{audioReady:h||r2(),videosReady:d}),g(!0)},[t]);return E.useEffect(()=>{if(!a||n)return;const h=setInterval(()=>{const d=rvA();s(d),r2()&&g(!0)},50);return()=>clearInterval(h)},[a,n]),n?C.jsx(C.Fragment,{children:e}):C.jsxs("div",{className:`sound-preload-screen${l?" sound-preload-screen--zentara":""}`,onClick:Q,children:[l&&C.jsxs("div",{className:"sound-preload-atmosphere","aria-hidden":"true",children:[C.jsx("span",{className:"sound-preload-orbit sound-preload-orbit--outer"}),C.jsx("span",{className:"sound-preload-orbit sound-preload-orbit--inner"}),C.jsx("span",{className:"sound-preload-scanline"})]}),C.jsx("div",{className:"sound-preload-content",children:C.jsx("div",{className:"sound-preload-panel",children:a?C.jsxs("div",{className:"sound-preload-loading",role:"status","aria-live":"polite",children:[C.jsx("span",{className:"sound-preload-spinner","aria-hidden":"true"}),C.jsx("p",{className:"sound-preload-status",children:l?"Synchronizing audio systems":"Loading game"}),C.jsx("div",{className:"sound-preload-progress",children:C.jsx("div",{className:"sound-preload-progress-bar",style:{width:`${B}%`}})}),o.total>0&&C.jsxs("p",{className:"sound-preload-progress-label",children:[B,"%"]})]}):C.jsxs(C.Fragment,{children:[l&&C.jsx("p",{className:"sound-preload-eyebrow",children:"Galactic Command Link"}),C.jsx(cQA,{className:"sound-preload-brand"}),C.jsx("p",{className:"sound-preload-prompt",children:l?"Enable audio to enter the command deck.":"Enable audio to begin."}),C.jsx("button",{className:"sound-preload-start",type:"button",children:l?"Enter Zentara":"Start"}),C.jsx("p",{className:"sound-preload-hint",children:"Tap once to initialize game audio"})]})})})]})}function rRe(){const e=MB();return E.useEffect(()=>{const A=t=>{var n;const i=(n=t==null?void 0:t.detail)==null?void 0:n.amount;typeof i=="number"&&i>0&&e.success(`+${i.toLocaleString()} daily credits added!`,{title:"Daily Bonus",duration:4500})};return window.addEventListener("daily-grant",A),()=>window.removeEventListener("daily-grant",A)},[e]),null}function IRe(){return MpA(),null}const iaA=["#ffd700","#f4c430","#ff6b6b","#4ecdc4","#45b7d1","#96ceb4","#ff9ff3","#54a0ff","#5f27cd","#ee5a24","#0abde3","#10ac84"],CRe=6e3;function cRe(e=40){return E.useMemo(()=>Array.from({length:e},(A,t)=>({left:`${Math.random()*100}%`,background:iaA[t%iaA.length],animationDelay:`${Math.random()*.8}s`,animationDuration:`${1.8+Math.random()*1.2}s`,width:`${5+Math.random()*6}px`,height:`${5+Math.random()*6}px`,borderRadius:Math.random()>.5?"50%":"2px"})),[e])}function lRe(){var r;const e=Ms(),{refreshUser:A,meId:t}=tn(),[i,n]=E.useState(null),g=cRe();E.useEffect(()=>{if(!e)return;const I=c=>{!c||typeof c.newLevel!="number"||c.playerId&&t&&c.playerId!==t||(n(c),A({force:!0}))};return e.on("sp:level_up",I),()=>{e.off("sp:level_up",I)}},[e,A,t]),E.useEffect(()=>{if(!i)return;const I=window.setTimeout(()=>n(null),CRe);return()=>window.clearTimeout(I)},[i]);const o=E.useCallback(()=>n(null),[]);if(!i)return null;const s=i.levelName||((r=nQ.find(I=>I.level===i.newLevel))==null?void 0:r.name)||`Level ${i.newLevel}`,a=C.jsx("div",{className:"levelup-backdrop",onClick:o,role:"dialog","aria-modal":"true","aria-label":"Level up celebration",children:C.jsxs("div",{className:"levelup-card",onClick:I=>I.stopPropagation(),children:[C.jsx("div",{className:"levelup-confetti",children:g.map((I,c)=>C.jsx("div",{className:"levelup-confetti-piece",style:I},c))}),C.jsx("div",{className:"levelup-stars",children:"⭐⭐⭐"}),C.jsx("p",{className:"levelup-title",children:"Table Cleared"}),C.jsxs("p",{className:"levelup-level",children:[i.oldLevel," to ",i.newLevel]}),C.jsx("p",{className:"levelup-name",children:s}),C.jsxs("p",{className:"levelup-subtitle",children:["You defeated every bot. Level ",i.newLevel," opponents start with z",i.newLevel*1e3," and play more aggressively."]}),C.jsx("button",{className:"levelup-btn",onClick:o,children:"Let’s Go"})]})});return er.createPortal(a,document.body)}const ip=fUA(),BRe=ip==="skills"?Dke:ip==="ceelo"?K0e:ip==="craps"?F0e:ip==="poker"?_0e:ip==="zentara"?Nke:ip==="unified"?wke:v0e;var DaA,maA,SaA,waA;try{const e=Ui.getPlatform();if((e==="ios"||e==="android")&&(Promise.resolve((maA=(DaA=ZG).enable)==null?void 0:maA.call(DaA,{config:{customColorsForSystemBars:!0,statusBarColor:"#00000000",statusBarContent:"light",navigationBarColor:"#00000000",navigationBarContent:"light"}})).catch(()=>{}),Gw().then(A=>{A&&(au().catch(t=>console.warn("[App] AdMob interstitial warmup failed:",t)),opA().catch(t=>console.warn("[App] AdMob rewarded warmup failed:",t)))}).catch(A=>console.warn("[App] AdMob init failed:",A))),e==="ios"||e==="android"){let A=0,t=0;const g=e==="ios"?47:36,o=document.documentElement,s=async()=>{var r,I;try{const c=ZG.getSafeAreaInsets;if(typeof c!="function")return;const l=await c.call(ZG),B=Math.round(((r=l==null?void 0:l.insets)==null?void 0:r.top)??(l==null?void 0:l.top)??0),Q=Math.round(((I=l==null?void 0:l.insets)==null?void 0:I.bottom)??(l==null?void 0:l.bottom)??0),h=window.innerHeight>window.innerWidth;h&&B>0&&(A=B),h&&Q>0&&(t=Q);const d=h?B>0?B:A:B,p=h?Q>0?Q:t:Q,y=Math.max(d,g);o.style.setProperty("--safe-top-global",`${y}px`),o.style.setProperty("--safe-bottom",`${p}px`)}catch{}};s();const a=()=>{setTimeout(s,50),setTimeout(s,150),setTimeout(s,300),setTimeout(s,500)};window.addEventListener("orientationchange",a),window.addEventListener("resize",s);try{(waA=(SaA=ZG).addListener)==null||waA.call(SaA,"safeAreaChanged",s)}catch{}if(e==="ios")try{document.documentElement.classList.add("is-native-app","platform-ios"),document.body.classList.add("is-native-app","platform-ios")}catch{}}}catch{}if(Ui.getPlatform()==="android"){const t=()=>{let i=24;const n=window.visualViewport;if(n&&typeof window.innerHeight=="number"){const g=Math.max(0,Math.round(window.innerHeight-(n.height+n.offsetTop)));g>0&&g<64&&(i=g)}document.documentElement.style.setProperty("--android-safe-area-bottom",`${i}px`),document.documentElement.style.setProperty("--android-safe-area-top","36px"),document.documentElement.style.setProperty("--android-extra-bottom","24px")};t(),window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100));try{document.documentElement.classList.add("is-native-app","platform-android"),document.body.classList.add("is-native-app","platform-android")}catch{}}function ERe(){const{loaded:e,walletEnabled:A}=ONe(),t=qi(),i=ks(),n=E.useRef(null),g=E.useRef(Date.now()),o=E.useCallback(a=>/^\/room\//.test(a)||/^\/poker\/room\//.test(a)||/^\/zentara\/(match|room)\//.test(a)||/^\/match\//.test(a),[]);return E.useEffect(()=>{const a=i.pathname||"";o(a)||sO()},[o,i.pathname]),E.useEffect(()=>{const a=()=>{if(document.visibilityState==="hidden"){sO();return}document.visibilityState==="visible"&&o(i.pathname||"")&&TgA()};document.addEventListener("visibilitychange",a);let r=null,I=null,c=!1;return(async()=>{var l,B;try{const{App:Q}=await Qi(async()=>{const{App:h}=await Promise.resolve().then(()=>GR);return{App:h}},void 0);if(c)return;if(r=await Q.addListener("pause",()=>{sO()}),I=await Q.addListener("resume",()=>{o(i.pathname||"")&&TgA()}),c){try{await((l=r==null?void 0:r.remove)==null?void 0:l.call(r))}catch{}try{await((B=I==null?void 0:I.remove)==null?void 0:B.call(I))}catch{}r=null,I=null}}catch{}})(),()=>{var l,B;c=!0;try{document.removeEventListener("visibilitychange",a)}catch{}try{(l=r==null?void 0:r.remove)==null||l.call(r)}catch{}try{(B=I==null?void 0:I.remove)==null||B.call(I)}catch{}r=null,I=null}},[o,i.pathname]),E.useEffect(()=>{try{VmA()}catch{}},[i.pathname,i.search]),E.useEffect(()=>{const r=()=>{n.current&&window.clearTimeout(n.current),n.current=window.setTimeout(()=>{i.search.includes("autoplay=1")||i.pathname!=="/lobby"&&t("/lobby",{replace:!0})},24e4)},I=()=>{g.current=Date.now(),r()};r();const c=()=>I(),l=()=>I(),B=()=>{document.visibilityState==="visible"&&I()};return window.addEventListener("pointerdown",c,{capture:!0}),window.addEventListener("keydown",l,{capture:!0}),document.addEventListener("visibilitychange",B),()=>{n.current&&window.clearTimeout(n.current),window.removeEventListener("pointerdown",c,{capture:!0}),window.removeEventListener("keydown",l,{capture:!0}),document.removeEventListener("visibilitychange",B)}},[t,i.pathname]),e?(a=>A?C.jsx(qNe,{children:a}):C.jsx(C.Fragment,{children:a}))(C.jsx(uUA,{children:C.jsx(fYA,{children:C.jsxs(gie,{children:[C.jsx(Uke,{}),C.jsx(SvA,{children:C.jsx(xYA,{children:C.jsxs(EUA,{children:[C.jsx(_ke,{}),C.jsx(nXA,{children:C.jsx($9A,{children:C.jsx(a8A,{children:C.jsx(Gie,{children:C.jsx(r8A,{children:C.jsx(oXA,{children:C.jsxs(yUA,{children:[C.jsx(rRe,{}),C.jsxs(GSA,{children:[C.jsx(BRe,{}),C.jsx(oRe,{}),C.jsx(nRe,{}),C.jsx(ARe,{}),C.jsx(eRe,{}),C.jsx(tRe,{}),C.jsx(iRe,{}),C.jsx(sRe,{}),C.jsx(lRe,{})]})]})})})})})})})]})})})]})})})):C.jsxs("div",{className:"HomeScreen theme-casino home-fixed-root",children:[C.jsx(tr,{className:"page-home-screen"}),C.jsx("div",{className:"home-preloader",children:C.jsx("div",{className:"home-preloader__spinner"})})]})}function QRe(){return E.useEffect(()=>{const e={current:null};return e.current=()=>{try{On()}catch{}e.current&&(window.removeEventListener("pointerdown",e.current,{capture:!0}),e.current=null)},window.addEventListener("pointerdown",e.current,{capture:!0}),()=>{e.current&&(window.removeEventListener("pointerdown",e.current,{capture:!0}),e.current=null)}},[]),E.useEffect(()=>{try{bSA()}catch{}},[]),C.jsxs(aRe,{maxWaitMs:5e3,appTarget:ip,children:[C.jsx(IRe,{}),C.jsx(iUA,{children:C.jsx(ORA,{children:C.jsx(HNe,{children:C.jsx(ERe,{})})})})]})}function uRe(e){const A=(e==null?void 0:e.healthIntervalMs)??8e3,t=(e==null?void 0:e.maxRetriesPerPlay)??3,i=!!(e!=null&&e.debug),[n,g]=E.useState(!1),[o,s]=E.useState(!1),[a,r]=E.useState(1),I=E.useRef({plays:0,failures:0,recovered:0,rebuilds:0}),c=E.useRef({}),l=E.useRef(!0),B=E.useRef(!1),Q=E.useRef(null),h=(...N)=>{i&&console.log("[audio-engine]",...N)},d=E.useCallback(()=>{if(n||B.current)return;B.current=!0;const N=()=>{try{c2==null||c2(),g(!0),h("activated via user gesture")}catch(G){h("activation error",G)}window.removeEventListener("pointerdown",N),window.removeEventListener("touchstart",N),window.removeEventListener("keydown",N)};window.addEventListener("pointerdown",N,{passive:!0,once:!0}),window.addEventListener("touchstart",N,{passive:!0,once:!0}),window.addEventListener("keydown",N,{passive:!0,once:!0})},[n,h]);E.useEffect(()=>{d()},[d]);const p=N=>{try{typeof W6=="function"&&(W6(N),I.current.rebuilds+=1,h("rebuild asset",N))}catch(G){h("rebuild asset failed",N,G)}},y=E.useCallback(async(N,G)=>{if(o&&!(G!=null&&G.allowDuringMute))return!1;n||d();const M=(G==null?void 0:G.volume)??a;let w=0;const b=()=>new Promise(_=>{let K=!1;const J=q=>{K||(K=!0,_(q))};try{const q=l2==null?void 0:l2(N,{volume:M,rate:G==null?void 0:G.rate,loop:G==null?void 0:G.loop});q&&typeof q.then=="function"?q.then(()=>J(!0)).catch(()=>J(!1)):setTimeout(()=>J(!0),0)}catch(q){h("play throw",N,q),J(!1)}});for(;w<=t;){if(await b())return I.current.plays+=1,w>0&&(I.current.recovered+=1),c.current[N]=0,!0;if(w+=1,I.current.failures+=1,c.current[N]=(c.current[N]||0)+1,h("play failed",N,"attempt",w),c.current[N]>=3&&p(N),w>t)break;await new Promise(K=>setTimeout(K,60*w))}return!1},[o,n,d,a,t,h]),m=E.useCallback(N=>{try{B2==null||B2(N)}catch{}},[]),D=E.useCallback(N=>{s(N)},[]),S=E.useCallback(N=>{r(Math.max(0,Math.min(1,N)))},[]);return E.useEffect(()=>{const N=async()=>{if(!l.current||!n)return;const G=I.current,M=G.plays+G.failures;if(M>=4){const w=G.failures/(M||1);if(w>.4){h("elevated failure ratio",w.toFixed(2),"running probe");try{await y("__probe__",{volume:0,allowDuringMute:!0})||(g(!1),B.current=!1,d(),h("probe failed → deactivated, awaiting gesture"))}catch(b){h("probe error",b)}}}};return Q.current=window.setInterval(N,A),()=>{Q.current&&window.clearInterval(Q.current)}},[A,n,y,d,h]),E.useEffect(()=>{const N=()=>{document.visibilityState==="visible"&&n&&y("__probe__",{volume:0,allowDuringMute:!0})};return document.addEventListener("visibilitychange",N),()=>document.removeEventListener("visibilitychange",N)},[n,y]),E.useEffect(()=>()=>{l.current=!1},[]),{play:y,preload:m,setMuted:D,setVolume:S,activationPrompt:d,isActivated:n,isMuted:o,volume:a,stats:I.current}}function dRe({children:e,config:A}){return uRe(A),C.jsx(C.Fragment,{children:e})}const hRe=[{id:"a",file:"/avatars/avatar-a.png",label:"Player A"},{id:"b",file:"/avatars/avatar-b.png",label:"Player B"},{id:"c",file:"/avatars/avatar-c.png",label:"Player C"},{id:"d",file:"/avatars/avatar-d.png",label:"Player D"}];function pRe({id:e,variant:A}){const t=hRe.find(g=>g.id===e);if(!t)return C.jsx("div",{style:{color:"#fff",padding:40},children:"Avatar not found"});const i=(A||"").toLowerCase(),n=i==="win"?"win":i==="lose"?"lose":i==="push"?"push":"";return C.jsxs("div",{className:"avatar-shot"+(n?` variant-${n}`:""),children:[C.jsxs("div",{className:"avatar-shot__frame",children:[C.jsx("img",{src:t.file,alt:t.label,className:"avatar-shot__img"}),n&&C.jsx("div",{className:"avatar-shot__fx fx-"+n})]}),C.jsx("div",{className:"avatar-shot__label",children:t.label})]})}function fRe(e,A){const t=/^\/capture\/avatar\/([a-z])$/i.exec(e);if(!t)return null;const n=new URLSearchParams(A).get("variant")||void 0;return{id:t[1].toLowerCase(),variant:n}}const yRe=[{id:"a",name:"Banker",avatar:"/avatars/avatar-a.png"},{id:"b",name:"Challenger 1",avatar:"/avatars/avatar-b.png"},{id:"c",name:"Challenger 2",avatar:"/avatars/avatar-c.png"},{id:"d",name:"Challenger 3",avatar:"/avatars/avatar-d.png"}],KSA={"pre-roll":{dice:[1,2,3],banker:"a",showRoll:!0,results:{a:"idle",b:"idle",c:"idle",d:"idle"},point:null},rolling:{dice:[0,0,0],banker:"a",rolling:!0,showRoll:!1,results:{a:"idle",b:"idle",c:"idle",d:"idle"},point:null},"banker-456":{dice:[4,5,6],banker:"a",shake:!0,showRoll:!1,results:{a:"win",b:"lose",c:"lose",d:"lose"},point:null,chipDeltas:{a:"+1500",b:"-500",c:"-500",d:"-500"}},"banker-point":{dice:[2,2,6],banker:"a",point:6,showRoll:!1,results:{a:"idle",b:"idle",c:"idle",d:"idle"}},"challenger-win":{dice:[3,3,5],banker:"a",point:5,showRoll:!1,results:{a:"lose",b:"win",c:"idle",d:"idle"},chipDeltas:{a:"-500",b:"+500"}},push:{dice:[5,5,2],banker:"a",point:2,showRoll:!1,results:{a:"push",b:"push",c:"idle",d:"idle"}},payout:{dice:[4,4,1],banker:"a",point:1,showRoll:!1,results:{a:"lose",b:"win",c:"win",d:"idle"},chipDeltas:{a:"-1000",b:"+500",c:"+500"}},"end-round":{dice:[6,6,3],banker:"a",point:null,showRoll:!1,roundSummary:"Round Over — New Banker",results:{a:"lose",b:"win",c:"idle",d:"idle"}}};function DRe(e){const A=/^\/capture\/cee-lo\/([a-z0-9-]+)$/i.exec(e);if(!A)return null;const t=A[1];return KSA[t]?{scene:t}:null}function FSA({scene:e}){const A=KSA[e];return A?C.jsx("div",{className:"cl-scene"+(A.shake?" fx-bg-shake":""),"data-scene":e,children:C.jsxs("div",{className:"cl-table",children:[C.jsx(mRe,{banker:A.banker,results:A.results,chipDeltas:A.chipDeltas}),C.jsx(SRe,{dice:A.dice,rolling:A.rolling}),A.point!=null&&A.point!==void 0&&C.jsx(kRe,{point:A.point}),A.showRoll&&C.jsx(MRe,{}),A.roundSummary&&C.jsx(NRe,{text:A.roundSummary})]})}):C.jsx("div",{style:{color:"#fff"},children:"Scene not found"})}function mRe({banker:e,results:A,chipDeltas:t}){return C.jsx("div",{className:"cl-seats",children:yRe.map(i=>{const n=(A==null?void 0:A[i.id])||"idle";return C.jsxs("div",{className:"cl-seat"+(i.id===e?" is-banker":"")+(n!=="idle"?` res-${n}`:""),children:[C.jsxs("div",{className:"cl-seat__avatar",children:[C.jsx("img",{src:i.avatar,alt:i.name}),n!=="idle"&&C.jsx("div",{className:"cl-seat__fx fx-"+n})]}),C.jsx("div",{className:"cl-seat__name",children:i.name}),(t==null?void 0:t[i.id])&&C.jsx("div",{className:"cl-seat__delta",children:t[i.id]})]},i.id)})})}function SRe({dice:e,rolling:A}){return C.jsx("div",{className:"cl-dice","aria-label":"dice",children:e.map((t,i)=>C.jsx(wRe,{value:t,rolling:A},i))})}function wRe({value:e,rolling:A}){const t=e===0?"?":String(e);return C.jsx("div",{className:"cl-die"+(A?" is-rolling":""),children:t})}function kRe({point:e}){return C.jsxs("div",{className:"cl-point",children:["POINT: ",e]})}function MRe(){return C.jsx("div",{className:"cl-roll-btn",children:"ROLL"})}function NRe({text:e}){return C.jsx("div",{className:"cl-summary",children:e})}const vk={on:()=>vk,off:()=>vk,once:()=>vk,emit:()=>vk,connected:!1,id:"ad-stub"};function RRe(e,A,t){const[i,n]=E.useState(e),g=E.useRef(!1),o=E.useRef(-1);return E.useEffect(()=>{if(g.current)return;g.current=!0;const s=performance.now();try{window.__adStartDate=Date.now()}catch{}let a=0;const r=[...A].sort((c,l)=>c.at-l.at),I=()=>{const c=(performance.now()-s)/1e3;let l=o.current;const B=[];for(let Q=o.current+1;Q<r.length&&r[Q].at<=c;Q++)B.push(r[Q].state),l=Q;B.length>0&&(o.current=l,n(Q=>B.reduce((h,d)=>({...h,...d}),Q))),a=requestAnimationFrame(I)};return a=requestAnimationFrame(I),()=>cancelAnimationFrame(a)},[]),i}const GRe={phase:"comeOut",point:null,pendingBets:[],balance:5e3,everyoneReady:!1,showReadyButton:!0,canRoll:!1,shooterName:"You",othersTotals:{},flashLabel:null},zg=(e,A)=>({id:`${e}-${A}-${Math.random().toString(36).slice(2,7)}`,type:e,amount:A}),_SA={comeout:[{at:.5,state:{pendingBets:[zg("pass",100)]}},{at:1.6,state:{pendingBets:[zg("pass",100),zg("pass",100)]}},{at:2.4,state:{pendingBets:[zg("pass",200),zg("field",50)],othersTotals:{pass:350}}},{at:3.4,state:{everyoneReady:!0,showReadyButton:!1,canRoll:!0}},{at:5,state:{flashLabel:"NATURAL · 7",balance:5300}},{at:6.5,state:{flashLabel:null,pendingBets:[],canRoll:!1,everyoneReady:!1,showReadyButton:!0}}],"point-six":[{at:.3,state:{phase:"point",point:6,pendingBets:[zg("pass",200)]}},{at:1,state:{pendingBets:[zg("pass",200),zg("place6",60)]}},{at:1.8,state:{pendingBets:[zg("pass",200),zg("place6",60),zg("place8",60)]}},{at:2.6,state:{pendingBets:[zg("pass",200),zg("place6",60),zg("place8",60),zg("oddsPass",200)],othersTotals:{pass:500,place6:120}}},{at:3.5,state:{everyoneReady:!0,showReadyButton:!1,canRoll:!0}},{at:5.4,state:{flashLabel:"POINT · 6",balance:5660}},{at:7,state:{flashLabel:null,phase:"comeOut",point:null,pendingBets:[],canRoll:!1,everyoneReady:!1,showReadyButton:!0}}],highlight:[{at:.4,state:{pendingBets:[zg("pass",100)]}},{at:1.2,state:{pendingBets:[zg("pass",100),zg("atsAll",25)]}},{at:2,state:{phase:"point",point:8,pendingBets:[zg("pass",100),zg("atsAll",25),zg("oddsPass",100)]}},{at:2.8,state:{pendingBets:[zg("pass",100),zg("atsAll",25),zg("oddsPass",100),zg("place6",60),zg("place8",60)]}},{at:3.6,state:{everyoneReady:!0,showReadyButton:!1,canRoll:!0,othersTotals:{pass:400,place6:120}}}]};function bRe(e,A){const t=/^\/capture\/craps-ad\/([a-z0-9-]+)$/i.exec(e);if(!t)return null;const i=t[1];return _SA[i]?{scene:i}:null}function URe({scene:e}){const A=_SA[e],t=RRe(GRe,A),i=E.useMemo(()=>({onChangeBets:()=>{},onClearAll:()=>{},onRoll:()=>{},onPassTurn:()=>{},onReadyClick:()=>{},onBetDelta:()=>{},onBetsBatch:()=>{},onChargeChange:()=>{}}),[]);return C.jsx(c8.Provider,{value:vk,children:C.jsxs("div",{className:"craps-ad-stage","data-scene":e,children:[C.jsx("div",{className:"craps-ad-stage__panel",children:C.jsx(ApA,{roomId:"ad-room",balance:t.balance,point:t.point,phase:t.phase,shooterName:t.shooterName,minBet:25,maxBet:2e3,oddsMultiple:{pass:5,dontPass:5,place:5},chips:[25,100,500,1e3],pendingBets:t.pendingBets,onChangeBets:i.onChangeBets,onClearAll:i.onClearAll,onRoll:i.onRoll,canRoll:t.canRoll,readyPlayers:t.everyoneReady?["ad-me","ad-bot"]:[],meId:"ad-me",everyoneReady:t.everyoneReady,showReadyButton:t.showReadyButton,onReadyClick:i.onReadyClick,readyStateLabel:t.everyoneReady?"Ready":"Get Ready",readyButtonDisabled:!1,countdownSeconds:0,myPlayerLineTotals:{pass:0,dontPass:0},othersTotals:t.othersTotals,myCommittedByType:{},canPassTurn:!1,onBetDelta:i.onBetDelta,onBetsBatch:i.onBetsBatch,onChargeChange:i.onChargeChange})}),t.flashLabel&&C.jsx("div",{className:"craps-ad-stage__flash",children:t.flashLabel},t.flashLabel)]})})}const JSA={"rolling-win":[{at:0,scene:"pre-roll"},{at:1,scene:"rolling"},{at:3.4,scene:"banker-456",flash:"4 · 5 · 6  WIN"},{at:6.2,scene:"payout",flash:null}],"point-chase":[{at:0,scene:"pre-roll"},{at:.8,scene:"rolling"},{at:2.6,scene:"banker-point",flash:"POINT · 6"},{at:4,scene:"rolling"},{at:5.6,scene:"challenger-win",flash:"CHALLENGER WINS"},{at:7.8,scene:"end-round",flash:null}],showdown:[{at:0,scene:"pre-roll"},{at:.6,scene:"rolling"},{at:2.4,scene:"push",flash:"PUSH"},{at:4.2,scene:"rolling"},{at:5.8,scene:"banker-456",flash:"TRIPS!"}]};function vRe(e){const A=/^\/capture\/cee-lo-ad\/([a-z0-9-]+)$/i.exec(e);return A&&JSA[A[1]]?{scene:A[1]}:null}function KRe({scene:e}){var o;const A=JSA[e],[t,i]=E.useState(0),[n,g]=E.useState(((o=A==null?void 0:A[0])==null?void 0:o.flash)??null);return E.useEffect(()=>{if(!A)return;try{window.__adStartDate=Date.now()}catch{}const s=performance.now();let a=0;const r=()=>{const I=(performance.now()-s)/1e3;let c=0;for(let l=0;l<A.length;l++)A[l].at<=I&&(c=l);i(c),g(A[c].flash??null),a=requestAnimationFrame(r)};return a=requestAnimationFrame(r),()=>cancelAnimationFrame(a)},[A]),A?C.jsxs("div",{className:"craps-ad-stage","data-ad":"cee-lo",children:[C.jsx("div",{className:"craps-ad-stage__panel",children:C.jsx(FSA,{scene:A[t].scene})}),n&&C.jsx("div",{className:"craps-ad-stage__flash",children:n},n)]}):C.jsx("div",{style:{color:"#fff"},children:"Scene not found"})}const naA=(e,A,t,i)=>({id:e,displayName:A,credits:5e3,tileIndex:0,inJail:!1,jailTurnsLeft:0,depleted:!1,piece:t,pieceColor:i,armorLevel:1,weaponLevel:1}),LSA={"raid-win":{confirmed:{winner:"attacker",attackerHits:28,defenderHits:4,credits:1200}},"raid-loss":{confirmed:{winner:"defender",attackerHits:6,defenderHits:22,credits:-800}}};function FRe(e){const A=/^\/capture\/zentara-ad\/([a-z0-9-]+)$/i.exec(e);return A&&LSA[A[1]]?{scene:A[1]}:null}function _Re({scene:e}){const A=LSA[e],t=E.useMemo(()=>naA("ad-att","Commander","crimson-dominion","#ff3a3a"),[]),i=E.useMemo(()=>naA("ad-def","Defender","azure-sovereignty","#3aa0ff"),[]);return E.useEffect(()=>{try{window.__adStartDate=Date.now()}catch{}},[]),A?C.jsx("div",{className:"craps-ad-stage","data-ad":"zentara-raid",children:C.jsx(wmA,{attacker:t,defender:i,onComplete:()=>{},isSpectator:!1,confirmedResult:A.confirmed})}):C.jsx("div",{style:{color:"#fff"},children:"Scene not found"})}const xSA={"royal-flush":[{at:0,hole:["AH","KH"],holeRevealed:{first:!0,both:!1},board:[],pot:600,flash:null,win:null},{at:.6,holeRevealed:{first:!0,both:!0}},{at:1.4,board:["QH","JH","10H"],flash:"FLOP"},{at:2.4,flash:null},{at:3,board:["QH","JH","10H","2C"],flash:"TURN"},{at:4,flash:null},{at:4.8,board:["QH","JH","10H","2C","5D"],pot:1850},{at:5.8,flash:"ROYAL FLUSH",win:{amount:1850,label:"+1,850"}}],"full-house":[{at:0,hole:["8S","8D"],holeRevealed:{first:!0,both:!0},board:["8H","KS","KH"],pot:480,flash:"FLOP",win:null},{at:1.5,flash:null},{at:2.2,board:["8H","KS","KH","4C"],flash:"TURN"},{at:3.4,flash:null},{at:4.2,board:["8H","KS","KH","4C","2S"],pot:1100},{at:5.4,flash:"FULL HOUSE",win:{amount:1100,label:"+1,100"}}],"river-suckout":[{at:0,hole:["AC","AS"],holeRevealed:{first:!0,both:!0},board:["7H","8H","9H"],pot:320,flash:"FLOP",win:null},{at:1.4,flash:null},{at:2,board:["7H","8H","9H","KC"],flash:"TURN"},{at:3.2,flash:null},{at:4,board:["7H","8H","9H","KC","AH"],pot:1450},{at:5,flash:"RIVER · ACES",win:{amount:1450,label:"+1,450"}}]};function JRe(e){const A=/^\/capture\/poker-ad\/([a-z0-9-]+)$/i.exec(e);return A&&xSA[A[1]]?{scene:A[1]}:null}const LRe={hole:[],holeRevealed:{first:!1,both:!1},board:[],pot:0,flash:null,win:null};function xRe({scene:e}){const A=xSA[e],[t,i]=E.useState(LRe);return E.useEffect(()=>{if(!A)return;try{window.__adStartDate=Date.now()}catch{}const n=performance.now();let g=0,o=-1;const s=[...A].sort((r,I)=>r.at-I.at),a=()=>{const r=(performance.now()-n)/1e3;for(let I=o+1;I<s.length&&s[I].at<=r;I++){const c=s[I];i(l=>({hole:c.hole??l.hole,holeRevealed:c.holeRevealed?{first:c.holeRevealed.first??l.holeRevealed.first,both:c.holeRevealed.both??l.holeRevealed.both}:l.holeRevealed,board:c.board??l.board,pot:c.pot??l.pot,flash:c.flash!==void 0?c.flash:l.flash,win:c.win!==void 0?c.win:l.win})),o=I}g=requestAnimationFrame(a)};return g=requestAnimationFrame(a),()=>cancelAnimationFrame(g)},[A]),A?C.jsxs("div",{className:"craps-ad-stage poker-ad","data-ad":"poker",children:[C.jsxs("div",{className:"poker-ad__felt",children:[C.jsxs("div",{className:"poker-ad__pot",children:["POT · z",t.pot.toLocaleString()]}),C.jsx("div",{className:"poker-ad__board",children:[0,1,2,3,4].map(n=>C.jsx(TRe,{value:t.board[n]},n))}),C.jsx("div",{className:"poker-ad__hero",children:C.jsx(bpA,{cards:t.hole,firstRevealed:t.holeRevealed.first,bothRevealed:t.holeRevealed.both})}),t.win&&C.jsx("div",{className:"poker-ad__chip-pop",children:t.win.label},t.win.label)]}),t.flash&&C.jsx("div",{className:"craps-ad-stage__flash",children:t.flash},t.flash)]}):C.jsx("div",{style:{color:"#fff"},children:"Scene not found"})}function TRe({value:e}){if(!e)return C.jsx("div",{className:"poker-ad__board-slot poker-ad__board-slot--empty"});const A=e==="10H"||e==="10S"||e==="10D"||e==="10C"?"10":e.slice(0,-1),t=e.slice(-1),i=t==="H"||t==="D",n=t==="H"?"♥":t==="D"?"♦":t==="C"?"♣":"♠";return C.jsxs("div",{className:`poker-ad__board-slot poker-ad__board-card ${i?"is-red":""}`,children:[C.jsx("span",{className:"poker-ad__board-rank",children:A}),C.jsx("span",{className:"poker-ad__board-suit",children:n})]})}const TSA={"find-fortune":{word:"FORTUNE",score:1450,grid:[["F","A","B","C","D","L"],["Q","O","R","T","U","X"],["M","P","R","V","N","E"],["Z","S","T","I","O","P"],["W","A","L","K","M","R"],["B","C","D","E","F","G"]],path:[{r:0,c:0},{r:1,c:1},{r:1,c:2},{r:1,c:3},{r:1,c:4},{r:2,c:4},{r:2,c:5}]},"find-jackpot":{word:"JACKPOT",score:2200,grid:[["Z","X","Q","W","L","M"],["J","A","C","B","D","V"],["Y","P","K","P","F","N"],["T","R","O","O","E","S"],["I","L","M","T","X","A"],["B","C","D","E","F","G"]],path:[{r:1,c:0},{r:1,c:1},{r:1,c:2},{r:2,c:2},{r:2,c:3},{r:3,c:3},{r:4,c:3}]},"find-victory":{word:"VICTORY",score:1800,grid:[["V","A","B","X","M","P"],["Q","I","C","L","D","F"],["Z","X","C","T","E","G"],["L","M","N","O","R","H"],["P","Q","S","T","Y","U"],["W","A","E","I","O","U"]],path:[{r:0,c:0},{r:1,c:1},{r:2,c:2},{r:2,c:3},{r:3,c:3},{r:3,c:4},{r:4,c:4}]}};function qRe(e){const A=/^\/capture\/skills-ad\/([a-z0-9-]+)$/i.exec(e);return A&&TSA[A[1]]?{scene:A[1]}:null}const qO=320;function YRe({scene:e}){var I;const A=TSA[e],[t,i]=E.useState(0),[n,g]=E.useState(!1);E.useEffect(()=>{if(!A)return;try{window.__adStartDate=Date.now()}catch{}let c=[];const l=window.setTimeout(()=>{for(let B=0;B<=A.path.length;B++)c.push(window.setTimeout(()=>i(B),B*qO));c.push(window.setTimeout(()=>g(!0),A.path.length*qO+400)),c.push(window.setTimeout(()=>{i(0),g(!1)},A.path.length*qO+2400))},600);return c.push(l),()=>c.forEach(B=>clearTimeout(B))},[A]);const o=E.useMemo(()=>{if(!A)return new Map;const c=new Map;for(let l=0;l<t;l++){const{r:B,c:Q}=A.path[l];c.set(`${B},${Q}`,l+1)}return c},[A,t]);if(!A)return C.jsx("div",{style:{color:"#fff"},children:"Scene not found"});const s=A.grid.length,a=((I=A.grid[0])==null?void 0:I.length)??0,r=A.word.slice(0,t);return C.jsx("div",{className:"craps-ad-stage skills-ad","data-ad":"skills",children:C.jsxs("div",{className:"skills-ad__stage",children:[C.jsxs("div",{className:"skills-ad__prompt",children:[C.jsx("span",{className:"skills-ad__label",children:"FIND"}),C.jsx("span",{className:"skills-ad__word",children:A.word})]}),C.jsx("div",{className:"skillsGrid skills-ad__grid",style:{gridTemplateColumns:`repeat(${a}, var(--skills-ad-cell))`,gridTemplateRows:`repeat(${s}, var(--skills-ad-cell))`},children:A.grid.map((c,l)=>c.map((B,Q)=>{const h=o.get(`${l},${Q}`),d=h!=null;return C.jsxs("div",{className:["skillsCell",d?"skillsCell--selected":"skillsCell--idle",n&&d?"skills-ad__cell--win":""].join(" "),children:[B,d&&C.jsx("span",{className:"skillsCellIndex",children:h})]},`${l}-${Q}`)}))}),C.jsx("div",{className:"skills-ad__trace",children:r.split("").map((c,l)=>C.jsx("span",{className:"skills-ad__trace-char",children:c},l))}),n&&C.jsxs("div",{className:"skills-ad__win",children:[C.jsx("span",{className:"skills-ad__win-word",children:A.word}),C.jsxs("span",{className:"skills-ad__win-points",children:["+",A.score]})]})]})})}async function HRe(){var e,A,t,i,n,g;try{const o=window.location.protocol;if(!(o==="capacitor:"||o==="ionic:"))return;let a=null;try{a=((A=(e=window.Capacitor)==null?void 0:e.Plugins)==null?void 0:A.Keyboard)||null}catch{}try{const c=window.visualViewport,l=d=>{try{document.documentElement.classList.toggle("kb-open",!!d),document.body.classList.toggle("kb-open",!!d)}catch{}};let B=(c==null?void 0:c.height)??window.innerHeight;const Q=()=>{try{B=(c==null?void 0:c.height)??window.innerHeight}catch{}},h=()=>{try{const d=(c==null?void 0:c.height)??window.innerHeight,p=Math.max(0,B-d);l(p>60)}catch{}};c?(c.addEventListener("resize",h),c.addEventListener("scroll",h)):(window.addEventListener("resize",h),window.addEventListener("orientationchange",()=>{Q(),h()})),window.addEventListener("focusin",d=>{const p=d==null?void 0:d.target;!!p&&(p.tagName==="INPUT"||p.tagName==="TEXTAREA"||p.isContentEditable)&&l(!0)}),window.addEventListener("focusout",()=>{window.setTimeout(h,120)}),window.setTimeout(()=>{Q(),h()},50)}catch{}if(a)try{await a.setResizeMode({mode:"none"})}catch{}const r=()=>{try{document.documentElement.classList.add("kb-open"),document.body.classList.add("kb-open")}catch{}},I=()=>{try{document.documentElement.classList.remove("kb-open"),document.body.classList.remove("kb-open")}catch{}};try{(t=a==null?void 0:a.addListener)==null||t.call(a,"keyboardWillShow",r)}catch{}try{(i=a==null?void 0:a.addListener)==null||i.call(a,"keyboardDidShow",r)}catch{}try{(n=a==null?void 0:a.addListener)==null||n.call(a,"keyboardWillHide",I)}catch{}try{(g=a==null?void 0:a.addListener)==null||g.call(a,"keyboardDidHide",I)}catch{}}catch{}}const gaA="fe:crashlog:sent_ts";function ORe(){try{return Ui.getPlatform()}catch{return"web"}}function PRe(){try{return"zentara"}catch{return"unknown"}}async function jRe(){try{const e=C8();if(!e.length)return;const A=Number(localStorage.getItem(gaA)||"0"),t=Math.max(...e.map(g=>g.t));if(t<=A)return;const i=Ca(),n=await fetch(`${i}/api/telemetry/logs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({logs:e.slice(-80),platform:ORe(),userAgent:navigator.userAgent,appTarget:PRe(),sessionId:sessionStorage.getItem("sid")||void 0})});n.ok?(localStorage.setItem(gaA,String(t)),gUA(),Ks.info("crash logs uploaded",{count:e.length})):Ks.warn("crash log upload failed",{status:n.status})}catch(e){try{Ks.warn("crash log upload error",{err:String(e)})}catch{}}}var kaA;try{const e=window.Capacitor,A=(kaA=e==null?void 0:e.getPlatform)==null?void 0:kaA.call(e);(A==="ios"||A==="android")&&Promise.resolve().then(()=>{try{Ll.notifyAppReady()}catch{}})}catch{}try{jRe()}catch{}try{window.addEventListener("error",e=>{console.error("[global error]",(e==null?void 0:e.error)||(e==null?void 0:e.message)||e)}),window.addEventListener("unhandledrejection",e=>{try{const A=e==null?void 0:e.reason;if((typeof A=="string"?A:A==null?void 0:A.message)==="NO_AUTH_TOKEN")return}catch{}console.error("[unhandled rejection]",(e==null?void 0:e.reason)||e)})}catch{}document.addEventListener("click",e=>{const A=e.target;if(!A)return;const t=A.closest('button, a, [role="button"], .felt-btn, .gold-link');if(t&&!t.closest("[data-no-global-haptic]")&&!(t.tagName==="BUTTON"&&t.disabled)&&t.getAttribute("aria-disabled")!=="true")try{ti("Light")}catch{}},{passive:!0});try{n8()}catch{}try{const e=window,A=e.location.protocol==="capacitor:"||e.location.protocol==="ionic:",t=/^(localhost|127\.0\.0\.1)$/.test(e.location.hostname),i=document.querySelector("script[data-adsbygoogle]");if(!A&&!t&&!i){const n=document.createElement("script");n.async=!0,n.src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4219446894372985",n.crossOrigin="anonymous",n.setAttribute("data-adsbygoogle","1"),n.onload=()=>{const g=window.adsbygoogle||[];try{g.push({})}catch{}},document.head.appendChild(n)}}catch{}try{const e="sess:initialized";Wc.get(e).then(A=>{if(!A)return Wc.clearSessionKeys().then(()=>Wc.set(e,"1"))}).catch(()=>{})}catch{}function zRe(){var e;window.__APP_MOUNTED__=!0,E.useEffect(()=>{var A;try{const t=window.Capacitor,i=(A=t==null?void 0:t.getPlatform)==null?void 0:A.call(t);(i==="ios"||i==="android")&&zCA().catch(()=>{})}catch{}},[]);try{const A=window.Capacitor,t=(e=A==null?void 0:A.getPlatform)==null?void 0:e.call(A);(t==="ios"||t==="android")&&Promise.resolve().then(()=>{try{Ll.notifyAppReady()}catch{}})}catch{}return C.jsx(QRe,{})}function YO(){try{const e=fRe(window.location.pathname,window.location.search);if(e){document.body.classList.add("ad-capture"),bQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(pRe,{id:e.id,variant:e.variant})}));return}const A=DRe(window.location.pathname);if(A){document.body.classList.add("ad-capture"),bQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(FSA,{scene:A.scene})}));return}const t=bRe(window.location.pathname,window.location.search);if(t){document.body.classList.add("ad-capture"),bQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(URe,{scene:t.scene})}));return}const i=vRe(window.location.pathname);if(i){document.body.classList.add("ad-capture"),bQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(KRe,{scene:i.scene})}));return}const n=FRe(window.location.pathname);if(n){document.body.classList.add("ad-capture"),bQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(_Re,{scene:n.scene})}));return}const g=JRe(window.location.pathname);if(g){document.body.classList.add("ad-capture"),bQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(xRe,{scene:g.scene})}));return}const o=qRe(window.location.pathname);if(o){document.body.classList.add("ad-capture"),bQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(YRe,{scene:o.scene})}));return}}catch{}bQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(GSA,{children:C.jsx(dRe,{config:{debug:!1},children:C.jsx(zRe,{})})})}))}function qSA(){try{(()=>{var A,t;try{const i=window.Capacitor,n=(A=i==null?void 0:i.getPlatform)==null?void 0:A.call(i);return n==="ios"||n==="android"?!0:/^(capacitor:|ionic:)/i.test(((t=window.location)==null?void 0:t.protocol)||"")}catch{return!1}})()?(async()=>{try{await yr.init()}catch{}YO();try{await HRe()}catch{}try{yr.healthCheck().catch(()=>{})}catch{}})():YO()}catch{YO()}}function ZRe(){qSA()}window.APP_TARGET||qSA();const TGe=Object.freeze(Object.defineProperty({__proto__:null,default:ZRe},Symbol.toStringTag,{value:"Module"}));export{rn as $,Fx as A,Ua as B,Et as C,AI as D,MW as E,br as F,kW as G,ny as H,iT as I,IQ as J,Ic as K,qg as L,pn as M,or as N,Hd as O,Wo as P,oo as Q,Fw as R,Cc as S,Nse as T,BV as U,SA as V,il as W,la as X,nV as Y,vse as Z,y4 as _,Mse as a,TE as a0,Od as a1,rQ as a2,NN as a3,AIe as a4,ayA as a5,lGe as a6,Iu as a7,QG as a8,iy as a9,Ni as aA,yB as aB,jx as aC,NIe as aD,Jw as aE,WIe as aF,_w as aG,CQ as aH,ue as aI,jDe as aJ,cl as aK,_Me as aL,ZN as aM,_s as aN,RMe as aO,YsA as aP,xGe as aQ,Oc as aR,TGe as aS,PDe as aa,sa as ab,xg as ac,sI as ad,Ag as ae,Ca as af,uo as ag,Vk as ah,oGe as ai,nw as aj,XRe as ak,oM as al,x7 as am,$Re as an,ho as ao,ca as ap,es as aq,EI as ar,xN as as,xd as at,Pt as au,An as av,ni as aw,Bn as ax,ji as ay,eyA as az,bIe as b,lt as c,eu as d,eIe as e,Tae as f,Ar as g,Lx as h,qW as i,C as j,VC as k,tG as l,Ba as m,xQe as n,oI as o,rG as p,oB as q,E as r,Kx as s,dV as t,ic as u,sue as v,uB as w,Ka as x,Kg as y,kg as z};
