const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/web-COWDW8-G.js","assets/index-ComZzUQM.js","assets/web-_QOCbX_X.js","assets/web-1K76zCcZ.js","assets/index.esm-Ct10TrAh.js","assets/index.esm2017-DuujyTn9.js","assets/index.esm-0EJQLKq6.js","assets/index.esm2017-B64x5eca.js","assets/web-D9Sye5xf.js","assets/index-DyJW_BMF.js","assets/InAppReviewService-D9_lw-TM.js","assets/web-C6m8J3cy.js","assets/web-CnmRTYxn.js","assets/index-Cv863TEx.js","assets/TurretPreview--d2p2lLC.js","assets/ShipPackPreview-DSd-Jms-.js","assets/ShipPackPreview-BeBfSYkD.css","assets/BroadcasterLive-ubUjlwKi.js","assets/BroadcasterLive-DDgCvhq9.css","assets/index.es-BiYYXYFK.js","assets/web-CKj7sOmP.js","assets/web-DwQT5qhV.js","assets/index-aO2K69ae.js"])))=>i.map(i=>d[i]);
var x0A=Object.defineProperty;var x9=e=>{throw TypeError(e)};var T0A=(e,A,t)=>A in e?x0A(e,A,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[A]=t;var Ti=(e,A,t)=>T0A(e,typeof A!="symbol"?A+"":A,t),Cq=(e,A,t)=>A.has(e)||x9("Cannot "+t);var tt=(e,A,t)=>(Cq(e,A,"read from private field"),t?t.call(e):A.get(e)),Tn=(e,A,t)=>A.has(e)?x9("Cannot add the same private member more than once"):A instanceof WeakSet?A.add(e):A.set(e,t),qi=(e,A,t,i)=>(Cq(e,A,"write to private field"),i?i.call(e,t):A.set(e,t),t),_r=(e,A,t)=>(Cq(e,A,"access private method"),t);var WG=(e,A,t,i)=>({set _(n){qi(e,A,n,t)},get _(){return tt(e,A,i)}});import{_ as li}from"./index-ComZzUQM.js";var rGe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function gw(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function aGe(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 brA={exports:{}},jJ={};/**
 * @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 q0A=Symbol.for("react.transitional.element"),Y0A=Symbol.for("react.fragment");function UrA(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:q0A,type:e,key:i,ref:A!==void 0?A:null,props:t}}jJ.Fragment=Y0A;jJ.jsx=UrA;jJ.jsxs=UrA;brA.exports=jJ;var C=brA.exports,vrA={exports:{}},tn={};/**
 * @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 W4=Symbol.for("react.transitional.element"),H0A=Symbol.for("react.portal"),O0A=Symbol.for("react.fragment"),P0A=Symbol.for("react.strict_mode"),j0A=Symbol.for("react.profiler"),z0A=Symbol.for("react.consumer"),Z0A=Symbol.for("react.context"),W0A=Symbol.for("react.forward_ref"),V0A=Symbol.for("react.suspense"),X0A=Symbol.for("react.memo"),KrA=Symbol.for("react.lazy"),$0A=Symbol.for("react.activity"),T9=Symbol.iterator;function AkA(e){return e===null||typeof e!="object"?null:(e=T9&&e[T9]||e["@@iterator"],typeof e=="function"?e:null)}var FrA={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_rA=Object.assign,JrA={};function ow(e,A,t){this.props=e,this.context=A,this.refs=JrA,this.updater=t||FrA}ow.prototype.isReactComponent={};ow.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")};ow.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function LrA(){}LrA.prototype=ow.prototype;function V4(e,A,t){this.props=e,this.context=A,this.refs=JrA,this.updater=t||FrA}var X4=V4.prototype=new LrA;X4.constructor=V4;_rA(X4,ow.prototype);X4.isPureReactComponent=!0;var q9=Array.isArray;function PO(){}var Xg={H:null,A:null,T:null,S:null},xrA=Object.prototype.hasOwnProperty;function $4(e,A,t){var i=t.ref;return{$$typeof:W4,type:e,key:A,ref:i!==void 0?i:null,props:t}}function ekA(e,A){return $4(e.type,A,e.props)}function Aj(e){return typeof e=="object"&&e!==null&&e.$$typeof===W4}function tkA(e){var A={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(t){return A[t]})}var Y9=/\/+/g;function cq(e,A){return typeof e=="object"&&e!==null&&e.key!=null?tkA(""+e.key):A.toString(36)}function ikA(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(PO,PO):(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 W4:case H0A:o=!0;break;case KrA:return o=e._init,MD(o(e._payload),A,t,i,n)}}if(o)return n=n(e),o=i===""?"."+cq(e,0):i,q9(n)?(t="",o!=null&&(t=o.replace(Y9,"$&/")+"/"),MD(n,A,t,"",function(a){return a})):n!=null&&(Aj(n)&&(n=ekA(n,t+(n.key==null||e&&e.key===n.key?"":(""+n.key).replace(Y9,"$&/")+"/")+o)),A.push(n)),1;o=0;var s=i===""?".":i+":";if(q9(e))for(var r=0;r<e.length;r++)i=e[r],g=s+cq(i,r),o+=MD(i,A,t,g,n);else if(r=AkA(e),typeof r=="function")for(e=r.call(e),r=0;!(i=e.next()).done;)i=i.value,g=s+cq(i,r++),o+=MD(i,A,t,g,n);else if(g==="object"){if(typeof e.then=="function")return MD(ikA(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 VG(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 nkA(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 H9=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)},gkA={map:VG,forEach:function(e,A,t){VG(e,function(){A.apply(this,arguments)},t)},count:function(e){var A=0;return VG(e,function(){A++}),A},toArray:function(e){return VG(e,function(A){return A})||[]},only:function(e){if(!Aj(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};tn.Activity=$0A;tn.Children=gkA;tn.Component=ow;tn.Fragment=O0A;tn.Profiler=j0A;tn.PureComponent=V4;tn.StrictMode=P0A;tn.Suspense=V0A;tn.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Xg;tn.__COMPILER_RUNTIME={__proto__:null,c:function(e){return Xg.H.useMemoCache(e)}};tn.cache=function(e){return function(){return e.apply(null,arguments)}};tn.cacheSignal=function(){return null};tn.cloneElement=function(e,A,t){if(e==null)throw Error("The argument must be a React element, but you passed "+e+".");var i=_rA({},e.props),n=e.key;if(A!=null)for(g in A.key!==void 0&&(n=""+A.key),A)!xrA.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 $4(e.type,n,i)};tn.createContext=function(e){return e={$$typeof:Z0A,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:z0A,_context:e},e};tn.createElement=function(e,A,t){var i,n={},g=null;if(A!=null)for(i in A.key!==void 0&&(g=""+A.key),A)xrA.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),r=0;r<o;r++)s[r]=arguments[r+2];n.children=s}if(e&&e.defaultProps)for(i in o=e.defaultProps,o)n[i]===void 0&&(n[i]=o[i]);return $4(e,g,n)};tn.createRef=function(){return{current:null}};tn.forwardRef=function(e){return{$$typeof:W0A,render:e}};tn.isValidElement=Aj;tn.lazy=function(e){return{$$typeof:KrA,_payload:{_status:-1,_result:e},_init:nkA}};tn.memo=function(e,A){return{$$typeof:X0A,type:e,compare:A===void 0?null:A}};tn.startTransition=function(e){var A=Xg.T,t={};Xg.T=t;try{var i=e(),n=Xg.S;n!==null&&n(t,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(PO,H9)}catch(g){H9(g)}finally{A!==null&&t.types!==null&&(A.types=t.types),Xg.T=A}};tn.unstable_useCacheRefresh=function(){return Xg.H.useCacheRefresh()};tn.use=function(e){return Xg.H.use(e)};tn.useActionState=function(e,A,t){return Xg.H.useActionState(e,A,t)};tn.useCallback=function(e,A){return Xg.H.useCallback(e,A)};tn.useContext=function(e){return Xg.H.useContext(e)};tn.useDebugValue=function(){};tn.useDeferredValue=function(e,A){return Xg.H.useDeferredValue(e,A)};tn.useEffect=function(e,A){return Xg.H.useEffect(e,A)};tn.useEffectEvent=function(e){return Xg.H.useEffectEvent(e)};tn.useId=function(){return Xg.H.useId()};tn.useImperativeHandle=function(e,A,t){return Xg.H.useImperativeHandle(e,A,t)};tn.useInsertionEffect=function(e,A){return Xg.H.useInsertionEffect(e,A)};tn.useLayoutEffect=function(e,A){return Xg.H.useLayoutEffect(e,A)};tn.useMemo=function(e,A){return Xg.H.useMemo(e,A)};tn.useOptimistic=function(e,A){return Xg.H.useOptimistic(e,A)};tn.useReducer=function(e,A,t){return Xg.H.useReducer(e,A,t)};tn.useRef=function(e){return Xg.H.useRef(e)};tn.useState=function(e){return Xg.H.useState(e)};tn.useSyncExternalStore=function(e,A,t){return Xg.H.useSyncExternalStore(e,A,t)};tn.useTransition=function(){return Xg.H.useTransition()};tn.version="19.2.0";vrA.exports=tn;var E=vrA.exports;const he=gw(E);var TrA={exports:{}},zJ={},qrA={exports:{}},YrA={};/**
 * @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 q=x-1>>>1,z=v[q];if(0<n(z,U))v[q]=U,v[x]=z,x=q;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 q=0,z=v.length,Z=z>>>1;q<Z;){var eA=2*(q+1)-1,aA=v[eA],sA=eA+1,pA=v[sA];if(0>n(aA,x))sA<z&&0>n(pA,aA)?(v[q]=pA,v[sA]=x,q=sA):(v[q]=aA,v[eA]=x,q=eA);else if(sA<z&&0>n(pA,x))v[q]=pA,v[sA]=x,q=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 r=[],a=[],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(a);U!==null;){if(U.callback===null)i(a);else if(U.startTime<=v)i(a),U.sortIndex=U.expirationTime,A(r,U);else break;U=t(a)}}function S(v){if(h=!1,D(v),!Q)if(t(r)!==null)Q=!0,k||(k=!0,_());else{var U=t(a);U!==null&&T(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(r);c!==null&&!(c.expirationTime>v&&w());){var q=c.callback;if(typeof q=="function"){c.callback=null,l=c.priorityLevel;var z=q(c.expirationTime<=v);if(v=e.unstable_now(),typeof z=="function"){c.callback=z,D(v),U=!0;break e}c===t(r)&&i(r),D(v)}else i(r);c=t(r)}if(c!==null)U=!0;else{var Z=t(a);Z!==null&&T(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 T(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 q=e.unstable_now();switch(typeof x=="object"&&x!==null?(x=x.delay,x=typeof x=="number"&&0<x?q+x:q):x=q,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>q?(v.sortIndex=x,A(a,v),t(r)===null&&v===t(a)&&(h?(y(N),N=-1):h=!0,T(S,x-q))):(v.sortIndex=z,A(r,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}}}})(YrA);qrA.exports=YrA;var okA=qrA.exports,HrA={exports:{}},Ka={};/**
 * @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 skA=E;function OrA(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 RQ(){}var wa={d:{f:RQ,r:function(){throw Error(OrA(522))},D:RQ,C:RQ,L:RQ,m:RQ,X:RQ,S:RQ,M:RQ},p:0,findDOMNode:null},rkA=Symbol.for("react.portal");function akA(e,A,t){var i=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:rkA,key:i==null?null:""+i,children:e,containerInfo:A,implementation:t}}var _k=skA.__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:""}Ka.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=wa;Ka.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(OrA(299));return akA(e,A,null,t)};Ka.flushSync=function(e){var A=_k.T,t=wa.p;try{if(_k.T=null,wa.p=2,e)return e()}finally{_k.T=A,wa.p=t,wa.d.f()}};Ka.preconnect=function(e,A){typeof e=="string"&&(A?(A=A.crossOrigin,A=typeof A=="string"?A==="use-credentials"?A:"":void 0):A=null,wa.d.C(e,A))};Ka.prefetchDNS=function(e){typeof e=="string"&&wa.d.D(e)};Ka.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"?wa.d.S(e,typeof A.precedence=="string"?A.precedence:void 0,{crossOrigin:i,integrity:n,fetchPriority:g}):t==="script"&&wa.d.X(e,{crossOrigin:i,integrity:n,fetchPriority:g,nonce:typeof A.nonce=="string"?A.nonce:void 0})}};Ka.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);wa.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&&wa.d.M(e)};Ka.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);wa.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})}};Ka.preloadModule=function(e,A){if(typeof e=="string")if(A){var t=ZJ(A.as,A.crossOrigin);wa.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 wa.d.m(e)};Ka.requestFormReset=function(e){wa.d.r(e)};Ka.unstable_batchedUpdates=function(e,A){return e(A)};Ka.useFormState=function(e,A,t){return _k.H.useFormState(e,A,t)};Ka.useFormStatus=function(){return _k.H.useHostTransitionStatus()};Ka.version="19.2.0";function PrA(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(PrA)}catch(e){console.error(e)}}PrA(),HrA.exports=Ka;var zr=HrA.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 Ks=okA,jrA=E,IkA=zr;function at(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 zrA(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function QR(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 ZrA(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 WrA(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 O9(e){if(QR(e)!==e)throw Error(at(188))}function CkA(e){var A=e.alternate;if(!A){if(A=QR(e),A===null)throw Error(at(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 O9(n),e;if(g===i)return O9(n),A;g=g.sibling}throw Error(at(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(at(189))}}if(t.alternate!==i)throw Error(at(190))}if(t.tag!==3)throw Error(at(188));return t.stateNode.current===t?e:A}function VrA(e){var A=e.tag;if(A===5||A===26||A===27||A===6)return e;for(e=e.child;e!==null;){if(A=VrA(e),A!==null)return A;e=e.sibling}return null}var eo=Object.assign,ckA=Symbol.for("react.element"),XG=Symbol.for("react.transitional.element"),sk=Symbol.for("react.portal"),_D=Symbol.for("react.fragment"),XrA=Symbol.for("react.strict_mode"),jO=Symbol.for("react.profiler"),$rA=Symbol.for("react.consumer"),mE=Symbol.for("react.context"),ej=Symbol.for("react.forward_ref"),zO=Symbol.for("react.suspense"),ZO=Symbol.for("react.suspense_list"),tj=Symbol.for("react.memo"),VQ=Symbol.for("react.lazy"),WO=Symbol.for("react.activity"),lkA=Symbol.for("react.memo_cache_sentinel"),P9=Symbol.iterator;function l0(e){return e===null||typeof e!="object"?null:(e=P9&&e[P9]||e["@@iterator"],typeof e=="function"?e:null)}var BkA=Symbol.for("react.client.reference");function VO(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===BkA?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case _D:return"Fragment";case jO:return"Profiler";case XrA:return"StrictMode";case zO:return"Suspense";case ZO:return"SuspenseList";case WO:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case sk:return"Portal";case mE:return e.displayName||"Context";case $rA:return(e._context.displayName||"Context")+".Consumer";case ej:var A=e.render;return e=e.displayName,e||(e=A.displayName||A.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case tj:return A=e.displayName||null,A!==null?A:VO(e.type)||"Memo";case VQ:A=e._payload,e=e._init;try{return VO(e(A))}catch{}}return null}var rk=Array.isArray,Ki=jrA.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Ig=IkA.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Np={pending:!1,data:null,method:null,action:null},XO=[],JD=-1;function wB(e){return{current:e}}function tr(e){0>JD||(e.current=XO[JD],XO[JD]=null,JD--)}function Yg(e,A){JD++,XO[JD]=e.current,e.current=A}var aB=wB(null),KM=wB(null),bu=wB(null),PK=wB(null);function jK(e,A){switch(Yg(bu,A),Yg(KM,e),Yg(aB,null),A.nodeType){case 9:case 11:e=(e=A.documentElement)&&(e=e.namespaceURI)?XX(e):0;break;default:if(e=A.tagName,A=A.namespaceURI)A=XX(A),e=hCA(A,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}tr(aB),Yg(aB,e)}function sS(){tr(aB),tr(KM),tr(bu)}function $O(e){e.memoizedState!==null&&Yg(PK,e);var A=aB.current,t=hCA(A,e.type);A!==t&&(Yg(KM,e),Yg(aB,t))}function zK(e){KM.current===e&&(tr(aB),tr(KM)),PK.current===e&&(tr(PK),PM._currentValue=Np)}var lq,j9;function _h(e){if(lq===void 0)try{throw Error()}catch(t){var A=t.stack.trim().match(/\n( *(at )?)/);lq=A&&A[1]||"",j9=-1<t.stack.indexOf(`
    at`)?" (<anonymous>)":-1<t.stack.indexOf("@")?"@unknown:0:0":""}return`
`+lq+e+j9}var Bq=!1;function Eq(e,A){if(!e||Bq)return"";Bq=!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 r=o.split(`
`),a=s.split(`
`);for(n=i=0;i<r.length&&!r[i].includes("DetermineComponentFrameRoot");)i++;for(;n<a.length&&!a[n].includes("DetermineComponentFrameRoot");)n++;if(i===r.length||n===a.length)for(i=r.length-1,n=a.length-1;1<=i&&0<=n&&r[i]!==a[n];)n--;for(;1<=i&&0<=n;i--,n--)if(r[i]!==a[n]){if(i!==1||n!==1)do if(i--,n--,0>n||r[i]!==a[n]){var I=`
`+r[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{Bq=!1,Error.prepareStackTrace=t}return(t=e?e.displayName||e.name:"")?_h(t):""}function EkA(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 Eq(e.type,!1);case 11:return Eq(e.type.render,!1);case 1:return Eq(e.type,!0);case 31:return _h("Activity");default:return""}}function z9(e){try{var A="",t=null;do A+=EkA(e,t),t=e,e=e.return;while(e);return A}catch(i){return`
Error generating stack: `+i.message+`
`+i.stack}}var A1=Object.prototype.hasOwnProperty,ij=Ks.unstable_scheduleCallback,Qq=Ks.unstable_cancelCallback,QkA=Ks.unstable_shouldYield,ukA=Ks.unstable_requestPaint,PI=Ks.unstable_now,dkA=Ks.unstable_getCurrentPriorityLevel,AaA=Ks.unstable_ImmediatePriority,eaA=Ks.unstable_UserBlockingPriority,ZK=Ks.unstable_NormalPriority,hkA=Ks.unstable_LowPriority,taA=Ks.unstable_IdlePriority,pkA=Ks.log,fkA=Ks.unstable_setDisableYieldValue,uR=null,jI=null;function uu(e){if(typeof pkA=="function"&&fkA(e),jI&&typeof jI.setStrictMode=="function")try{jI.setStrictMode(uR,e)}catch{}}var zI=Math.clz32?Math.clz32:mkA,ykA=Math.log,DkA=Math.LN2;function mkA(e){return e>>>=0,e===0?32:31-(ykA(e)/DkA|0)|0}var $G=256,Ab=262144,eb=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 WJ(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 dR(e,A){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&A)===0}function SkA(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 iaA(){var e=eb;return eb<<=1,!(eb&62914560)&&(eb=4194304),e}function uq(e){for(var A=[],t=0;31>t;t++)A.push(e);return A}function hR(e,A){e.pendingLanes|=A,A!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function wkA(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,r=e.expirationTimes,a=e.hiddenUpdates;for(t=o&~t;0<t;){var I=31-zI(t),c=1<<I;s[I]=0,r[I]=-1;var l=a[I];if(l!==null)for(a[I]=null,I=0;I<l.length;I++){var B=l[I];B!==null&&(B.lane&=-536870913)}t&=~c}i!==0&&naA(e,i,0),g!==0&&n===0&&e.tag!==0&&(e.suspendedLanes|=g&~(o&~A))}function naA(e,A,t){e.pendingLanes|=A,e.suspendedLanes&=~A;var i=31-zI(A);e.entangledLanes|=A,e.entanglements[i]=e.entanglements[i]|1073741824|t&261930}function gaA(e,A){var t=e.entangledLanes|=A;for(e=e.entanglements;t;){var i=31-zI(t),n=1<<i;n&A|e[i]&A&&(e[i]|=A),t&=~n}}function oaA(e,A){var t=A&-A;return t=t&42?1:nj(t),t&(e.suspendedLanes|A)?0:t}function nj(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 gj(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function saA(){var e=Ig.p;return e!==0?e:(e=window.event,e===void 0?32:RCA(e.type))}function Z9(e,A){var t=Ig.p;try{return Ig.p=e,A()}finally{Ig.p=t}}var md=Math.random().toString(36).slice(2),pr="__reactFiber$"+md,rI="__reactProps$"+md,sw="__reactContainer$"+md,e1="__reactEvents$"+md,kkA="__reactListeners$"+md,MkA="__reactHandles$"+md,W9="__reactResources$"+md,pR="__reactMarker$"+md;function oj(e){delete e[pr],delete e[rI],delete e[e1],delete e[kkA],delete e[MkA]}function LD(e){var A=e[pr];if(A)return A;for(var t=e.parentNode;t;){if(A=t[sw]||t[pr]){if(t=A.alternate,A.child!==null||t!==null&&t.child!==null)for(e=i6(e);e!==null;){if(t=e[pr])return t;e=i6(e)}return A}e=t,t=e.parentNode}return null}function rw(e){if(e=e[pr]||e[sw]){var A=e.tag;if(A===5||A===6||A===13||A===31||A===26||A===27||A===3)return e}return null}function ak(e){var A=e.tag;if(A===5||A===26||A===27||A===6)return e.stateNode;throw Error(at(33))}function Bm(e){var A=e[W9];return A||(A=e[W9]={hoistableStyles:new Map,hoistableScripts:new Map}),A}function $s(e){e[pR]=!0}var raA=new Set,aaA={};function Mf(e,A){rS(e,A),rS(e+"Capture",A)}function rS(e,A){for(aaA[e]=A,e=0;e<A.length;e++)raA.add(A[e])}var NkA=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]*$"),V9={},X9={};function RkA(e){return A1.call(X9,e)?!0:A1.call(V9,e)?!1:NkA.test(e)?X9[e]=!0:(V9[e]=!0,!1)}function Jv(e,A,t){if(RkA(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 tb(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 OB(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 LC(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function IaA(e){var A=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(A==="checkbox"||A==="radio")}function GkA(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 t1(e){if(!e._valueTracker){var A=IaA(e)?"checked":"value";e._valueTracker=GkA(e,A,""+e[A])}}function CaA(e){if(!e)return!1;var A=e._valueTracker;if(!A)return!0;var t=A.getValue(),i="";return e&&(i=IaA(e)?e.checked?"true":"false":e.value),e=i,e!==t?(A.setValue(e),!0):!1}function WK(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 bkA=/[\n"\\]/g;function YC(e){return e.replace(bkA,function(A){return"\\"+A.charCodeAt(0).toString(16)+" "})}function i1(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=""+LC(A)):e.value!==""+LC(A)&&(e.value=""+LC(A)):o!=="submit"&&o!=="reset"||e.removeAttribute("value"),A!=null?n1(e,o,LC(A)):t!=null?n1(e,o,LC(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=""+LC(s):e.removeAttribute("name")}function caA(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)){t1(e);return}t=t!=null?""+LC(t):"",A=A!=null?""+LC(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),t1(e)}function n1(e,A,t){A==="number"&&WK(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=""+LC(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 laA(e,A,t){if(A!=null&&(A=""+LC(A),A!==e.value&&(e.value=A),t==null)){e.defaultValue!==A&&(e.defaultValue=A);return}e.defaultValue=t!=null?""+LC(t):""}function BaA(e,A,t,i){if(A==null){if(i!=null){if(t!=null)throw Error(at(92));if(rk(i)){if(1<i.length)throw Error(at(93));i=i[0]}t=i}t==null&&(t=""),A=t}t=LC(A),e.defaultValue=t,i=e.textContent,i===t&&i!==""&&i!==null&&(e.value=i),t1(e)}function aS(e,A){if(A){var t=e.firstChild;if(t&&t===e.lastChild&&t.nodeType===3){t.nodeValue=A;return}}e.textContent=A}var UkA=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 $9(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||UkA.has(A)?A==="float"?e.cssFloat=t:e[A]=(""+t).trim():e[A]=t+"px"}function EaA(e,A,t){if(A!=null&&typeof A!="object")throw Error(at(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&&$9(e,n,i)}else for(var g in A)A.hasOwnProperty(g)&&$9(e,g,A[g])}function sj(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 vkA=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"]]),KkA=/^[\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 Lv(e){return KkA.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function SE(){}var g1=null;function rj(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 AX(e){var A=rw(e);if(A&&(e=A.stateNode)){var t=e[rI]||null;A:switch(e=A.stateNode,A.type){case"input":if(i1(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="'+YC(""+A)+'"][type="radio"]'),A=0;A<t.length;A++){var i=t[A];if(i!==e&&i.form===e.form){var n=i[rI]||null;if(!n)throw Error(at(90));i1(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&&CaA(i)}break A;case"textarea":laA(e,t.value,t.defaultValue);break A;case"select":A=t.value,A!=null&&Em(e,!!t.multiple,A,!1)}}}var dq=!1;function QaA(e,A,t){if(dq)return e(A,t);dq=!0;try{var i=e(A);return i}finally{if(dq=!1,(xD!==null||Qm!==null)&&(rL(),xD&&(A=xD,e=Qm,Qm=xD=null,AX(A),e)))for(A=0;A<e.length;A++)AX(e[A])}}function FM(e,A){var t=e.stateNode;if(t===null)return null;var i=t[rI]||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(at(231,A,typeof t));return t}var YE=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),o1=!1;if(YE)try{var B0={};Object.defineProperty(B0,"passive",{get:function(){o1=!0}}),window.addEventListener("test",B0,B0),window.removeEventListener("test",B0,B0)}catch{o1=!1}var du=null,aj=null,xv=null;function uaA(){if(xv)return xv;var e,A=aj,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 xv=n.slice(e,1<i?1-i:void 0)}function Tv(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 ib(){return!0}function eX(){return!1}function EI(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)?ib:eX,this.isPropagationStopped=eX,this}return eo(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=ib)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=ib)},persist:function(){},isPersistent:ib}),A}var Nf={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},VJ=EI(Nf),fR=eo({},Nf,{view:0,detail:0}),FkA=EI(fR),hq,pq,E0,XJ=eo({},fR,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Ij,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!==E0&&(E0&&e.type==="mousemove"?(hq=e.screenX-E0.screenX,pq=e.screenY-E0.screenY):pq=hq=0,E0=e),hq)},movementY:function(e){return"movementY"in e?e.movementY:pq}}),tX=EI(XJ),_kA=eo({},XJ,{dataTransfer:0}),JkA=EI(_kA),LkA=eo({},fR,{relatedTarget:0}),fq=EI(LkA),xkA=eo({},Nf,{animationName:0,elapsedTime:0,pseudoElement:0}),TkA=EI(xkA),qkA=eo({},Nf,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),YkA=EI(qkA),HkA=eo({},Nf,{data:0}),iX=EI(HkA),OkA={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},PkA={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"},jkA={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function zkA(e){var A=this.nativeEvent;return A.getModifierState?A.getModifierState(e):(e=jkA[e])?!!A[e]:!1}function Ij(){return zkA}var ZkA=eo({},fR,{key:function(e){if(e.key){var A=OkA[e.key]||e.key;if(A!=="Unidentified")return A}return e.type==="keypress"?(e=Tv(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?PkA[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Ij,charCode:function(e){return e.type==="keypress"?Tv(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Tv(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),WkA=EI(ZkA),VkA=eo({},XJ,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),nX=EI(VkA),XkA=eo({},fR,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Ij}),$kA=EI(XkA),AMA=eo({},Nf,{propertyName:0,elapsedTime:0,pseudoElement:0}),eMA=EI(AMA),tMA=eo({},XJ,{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}),iMA=EI(tMA),nMA=eo({},Nf,{newState:0,oldState:0}),gMA=EI(nMA),oMA=[9,13,27,32],Cj=YE&&"CompositionEvent"in window,Jk=null;YE&&"documentMode"in document&&(Jk=document.documentMode);var sMA=YE&&"TextEvent"in window&&!Jk,daA=YE&&(!Cj||Jk&&8<Jk&&11>=Jk),gX=" ",oX=!1;function haA(e,A){switch(e){case"keyup":return oMA.indexOf(A.keyCode)!==-1;case"keydown":return A.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function paA(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var TD=!1;function rMA(e,A){switch(e){case"compositionend":return paA(A);case"keypress":return A.which!==32?null:(oX=!0,gX);case"textInput":return e=A.data,e===gX&&oX?null:e;default:return null}}function aMA(e,A){if(TD)return e==="compositionend"||!Cj&&haA(e,A)?(e=uaA(),xv=aj=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 daA&&A.locale!=="ko"?null:A.data;default:return null}}var IMA={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 sX(e){var A=e&&e.nodeName&&e.nodeName.toLowerCase();return A==="input"?!!IMA[e.type]:A==="textarea"}function faA(e,A,t,i){xD?Qm?Qm.push(i):Qm=[i]:xD=i,A=BF(A,"onChange"),0<A.length&&(t=new VJ("onChange","change",null,t,i),e.push({event:t,listeners:A}))}var Lk=null,_M=null;function CMA(e){QCA(e,0)}function $J(e){var A=ak(e);if(CaA(A))return e}function rX(e,A){if(e==="change")return A}var yaA=!1;if(YE){var yq;if(YE){var Dq="oninput"in document;if(!Dq){var aX=document.createElement("div");aX.setAttribute("oninput","return;"),Dq=typeof aX.oninput=="function"}yq=Dq}else yq=!1;yaA=yq&&(!document.documentMode||9<document.documentMode)}function IX(){Lk&&(Lk.detachEvent("onpropertychange",DaA),_M=Lk=null)}function DaA(e){if(e.propertyName==="value"&&$J(_M)){var A=[];faA(A,_M,e,rj(e)),QaA(CMA,A)}}function cMA(e,A,t){e==="focusin"?(IX(),Lk=A,_M=t,Lk.attachEvent("onpropertychange",DaA)):e==="focusout"&&IX()}function lMA(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return $J(_M)}function BMA(e,A){if(e==="click")return $J(A)}function EMA(e,A){if(e==="input"||e==="change")return $J(A)}function QMA(e,A){return e===A&&(e!==0||1/e===1/A)||e!==e&&A!==A}var $I=typeof Object.is=="function"?Object.is:QMA;function JM(e,A){if($I(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(!A1.call(A,n)||!$I(e[n],A[n]))return!1}return!0}function CX(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function cX(e,A){var t=CX(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=CX(t)}}function maA(e,A){return e&&A?e===A?!0:e&&e.nodeType===3?!1:A&&A.nodeType===3?maA(e,A.parentNode):"contains"in e?e.contains(A):e.compareDocumentPosition?!!(e.compareDocumentPosition(A)&16):!1:!1}function SaA(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var A=WK(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=WK(e.document)}return A}function cj(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 uMA=YE&&"documentMode"in document&&11>=document.documentMode,qD=null,s1=null,xk=null,r1=!1;function lX(e,A,t){var i=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;r1||qD==null||qD!==WK(i)||(i=qD,"selectionStart"in i&&cj(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}),xk&&JM(xk,i)||(xk=i,i=BF(s1,"onSelect"),0<i.length&&(A=new VJ("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")},mq={},waA={};YE&&(waA=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(mq[e])return mq[e];if(!YD[e])return e;var A=YD[e],t;for(t in A)if(A.hasOwnProperty(t)&&t in waA)return mq[e]=A[t];return e}var kaA=Rf("animationend"),MaA=Rf("animationiteration"),NaA=Rf("animationstart"),dMA=Rf("transitionrun"),hMA=Rf("transitionstart"),pMA=Rf("transitioncancel"),RaA=Rf("transitionend"),GaA=new Map,a1="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(" ");a1.push("scrollEnd");function tl(e,A){GaA.set(e,A),Mf(A,[e])}var VK=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)},bC=[],HD=0,lj=0;function AL(){for(var e=HD,A=lj=HD=0;A<e;){var t=bC[A];bC[A++]=null;var i=bC[A];bC[A++]=null;var n=bC[A];bC[A++]=null;var g=bC[A];if(bC[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&&baA(t,n,g)}}function eL(e,A,t,i){bC[HD++]=e,bC[HD++]=A,bC[HD++]=t,bC[HD++]=i,lj|=i,e.lanes|=i,e=e.alternate,e!==null&&(e.lanes|=i)}function Bj(e,A,t,i){return eL(e,A,t,i),XK(e)}function Gf(e,A){return eL(e,null,null,A),XK(e)}function baA(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-zI(t),e=g.hiddenUpdates,i=e[n],i===null?e[n]=[A]:i.push(A),A.lane=t|536870912),g):null}function XK(e){if(50<Zk)throw Zk=0,R1=null,Error(at(185));for(var A=e.return;A!==null;)e=A,A=e.return;return e.tag===3?e.stateNode:null}var OD={};function fMA(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 xI(e,A,t,i){return new fMA(e,A,t,i)}function Ej(e){return e=e.prototype,!(!e||!e.isReactComponent)}function RE(e,A){var t=e.alternate;return t===null?(t=xI(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 UaA(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 qv(e,A,t,i,n,g){var o=0;if(i=e,typeof e=="function")Ej(e)&&(o=1);else if(typeof e=="string")o=wNA(e,t,aB.current)?26:e==="html"||e==="head"||e==="body"?27:5;else A:switch(e){case WO:return e=xI(31,t,A,n),e.elementType=WO,e.lanes=g,e;case _D:return Rp(t.children,n,g,A);case XrA:o=8,n|=24;break;case jO:return e=xI(12,t,A,n|2),e.elementType=jO,e.lanes=g,e;case zO:return e=xI(13,t,A,n),e.elementType=zO,e.lanes=g,e;case ZO:return e=xI(19,t,A,n),e.elementType=ZO,e.lanes=g,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case mE:o=10;break A;case $rA:o=9;break A;case ej:o=11;break A;case tj:o=14;break A;case VQ:o=16,i=null;break A}o=29,t=Error(at(130,e===null?"null":typeof e,"")),i=null}return A=xI(o,t,A,n),A.elementType=e,A.type=i,A.lanes=g,A}function Rp(e,A,t,i){return e=xI(7,e,i,A),e.lanes=t,e}function Sq(e,A,t){return e=xI(6,e,null,A),e.lanes=t,e}function vaA(e){var A=xI(18,null,null,0);return A.stateNode=e,A}function wq(e,A,t){return A=xI(4,e.children!==null?e.children:[],e.key,A),A.lanes=t,A.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},A}var BX=new WeakMap;function HC(e,A){if(typeof e=="object"&&e!==null){var t=BX.get(e);return t!==void 0?t:(A={value:e,source:A,stack:z9(A)},BX.set(e,A),A)}return{value:e,source:A,stack:z9(A)}}var PD=[],jD=0,$K=null,LM=0,xC=[],TC=0,Ad=null,AB=1,eB="";function IE(e,A){PD[jD++]=LM,PD[jD++]=$K,$K=e,LM=A}function KaA(e,A,t){xC[TC++]=AB,xC[TC++]=eB,xC[TC++]=Ad,Ad=e;var i=AB;e=eB;var n=32-zI(i)-1;i&=~(1<<n),t+=1;var g=32-zI(A)+n;if(30<g){var o=n-n%5;g=(i&(1<<o)-1).toString(32),i>>=o,n-=o,AB=1<<32-zI(A)+n|t<<n|i,eB=g+e}else AB=1<<g|t<<n|i,eB=e}function Qj(e){e.return!==null&&(IE(e,1),KaA(e,1,0))}function uj(e){for(;e===$K;)$K=PD[--jD],PD[jD]=null,LM=PD[--jD],PD[jD]=null;for(;e===Ad;)Ad=xC[--TC],xC[TC]=null,eB=xC[--TC],xC[TC]=null,AB=xC[--TC],xC[TC]=null}function FaA(e,A){xC[TC++]=AB,xC[TC++]=eB,xC[TC++]=Ad,AB=A.id,eB=A.overflow,Ad=e}var fr=null,Wg=null,jn=!1,Uu=null,OC=!1,I1=Error(at(519));function ed(e){var A=Error(at(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw xM(HC(A,e)),I1}function EX(e){var A=e.stateNode,t=e.type,i=e.memoizedProps;switch(A[pr]=e,A[rI]=i,t){case"dialog":Nn("cancel",A),Nn("close",A);break;case"iframe":case"object":case"embed":Nn("load",A);break;case"video":case"audio":for(t=0;t<HM.length;t++)Nn(HM[t],A);break;case"source":Nn("error",A);break;case"img":case"image":case"link":Nn("error",A),Nn("load",A);break;case"details":Nn("toggle",A);break;case"input":Nn("invalid",A),caA(A,i.value,i.defaultValue,i.checked,i.defaultChecked,i.type,i.name,!0);break;case"select":Nn("invalid",A);break;case"textarea":Nn("invalid",A),BaA(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||dCA(A.textContent,t)?(i.popover!=null&&(Nn("beforetoggle",A),Nn("toggle",A)),i.onScroll!=null&&Nn("scroll",A),i.onScrollEnd!=null&&Nn("scrollend",A),i.onClick!=null&&(A.onclick=SE),A=!0):A=!1,A||ed(e,!0)}function QX(e){for(fr=e.return;fr;)switch(fr.tag){case 5:case 31:case 13:OC=!1;return;case 27:case 3:OC=!0;return;default:fr=fr.return}}function Uy(e){if(e!==fr)return!1;if(!jn)return QX(e),jn=!0,!1;var A=e.tag,t;if((t=A!==3&&A!==27)&&((t=A===5)&&(t=e.type,t=!(t!=="form"&&t!=="button")||K1(e.type,e.memoizedProps)),t=!t),t&&Wg&&ed(e),QX(e),A===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(at(317));Wg=t6(e)}else if(A===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(at(317));Wg=t6(e)}else A===27?(A=Wg,Sd(e.type)?(e=L1,L1=null,Wg=e):Wg=A):Wg=fr?WC(e.stateNode.nextSibling):null;return!0}function Wp(){Wg=fr=null,jn=!1}function kq(){var e=Uu;return e!==null&&(Za===null?Za=e:Za.push.apply(Za,e),Uu=null),e}function xM(e){Uu===null?Uu=[e]:Uu.push(e)}var C1=wB(null),bf=null,wE=null;function iu(e,A,t){Yg(C1,A._currentValue),A._currentValue=t}function GE(e){e._currentValue=C1.current,tr(C1)}function c1(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 l1(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 r=0;r<A.length;r++)if(s.context===A[r]){g.lanes|=t,s=g.alternate,s!==null&&(s.lanes|=t),c1(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(at(341));o.lanes|=t,g=o.alternate,g!==null&&(g.lanes|=t),c1(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(at(387));if(o=o.memoizedProps,o!==null){var s=n.type;$I(n.pendingProps.value,o.value)||(e!==null?e.push(s):e=[s])}}else if(n===PK.current){if(o=n.alternate,o===null)throw Error(at(387));o.memoizedState.memoizedState!==n.memoizedState.memoizedState&&(e!==null?e.push(PM):e=[PM])}n=n.return}e!==null&&l1(A,e,t,i),A.flags|=262144}function AF(e){for(e=e.firstContext;e!==null;){if(!$I(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Vp(e){bf=e,wE=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function Dr(e){return _aA(bf,e)}function nb(e,A){return bf===null&&Vp(e),_aA(e,A)}function _aA(e,A){var t=A._currentValue;if(A={context:A,memoizedValue:t,next:null},wE===null){if(e===null)throw Error(at(308));wE=A,e.dependencies={lanes:0,firstContext:A},e.flags|=524288}else wE=wE.next=A;return t}var yMA=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()})}},DMA=Ks.unstable_scheduleCallback,mMA=Ks.unstable_NormalPriority,us={$$typeof:mE,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function dj(){return{controller:new yMA,data:new Map,refCount:0}}function yR(e){e.refCount--,e.refCount===0&&DMA(mMA,function(){e.controller.abort()})}var Tk=null,B1=0,IS=0,um=null;function SMA(e,A){if(Tk===null){var t=Tk=[];B1=0,IS=Yj(),um={status:"pending",value:void 0,then:function(i){t.push(i)}}}return B1++,A.then(uX,uX),A}function uX(){if(--B1===0&&Tk!==null){um!==null&&(um.status="fulfilled");var e=Tk;Tk=null,IS=0,um=null;for(var A=0;A<e.length;A++)(0,e[A])()}}function wMA(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 dX=Ki.S;Ki.S=function(e,A){VIA=PI(),typeof A=="object"&&A!==null&&typeof A.then=="function"&&SMA(e,A),dX!==null&&dX(e,A)};var Gp=wB(null);function hj(){var e=Gp.current;return e!==null?e:Jg.pooledCache}function Yv(e,A){A===null?Yg(Gp,Gp.current):Yg(Gp,A.pool)}function JaA(){var e=hj();return e===null?null:{parent:us._currentValue,pool:e}}var Iw=Error(at(460)),pj=Error(at(474)),tL=Error(at(542)),eF={then:function(){}};function hX(e){return e=e.status,e==="fulfilled"||e==="rejected"}function LaA(e,A,t){switch(t=e[t],t===void 0?e.push(A):t!==A&&(A.then(SE,SE),A=t),A.status){case"fulfilled":return A.value;case"rejected":throw e=A.reason,fX(e),e;default:if(typeof A.status=="string")A.then(SE,SE);else{if(e=Jg,e!==null&&100<e.shellSuspendCounter)throw Error(at(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,fX(e),e}throw bp=A,Iw}}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,Iw):t}}var bp=null;function pX(){if(bp===null)throw Error(at(459));var e=bp;return bp=null,e}function fX(e){if(e===Iw||e===tL)throw Error(at(483))}var dm=null,TM=0;function gb(e){var A=TM;return TM+=1,dm===null&&(dm=[]),LaA(dm,e,A)}function Q0(e,A){A=A.props.ref,e.ref=A!==void 0?A:null}function ob(e,A){throw A.$$typeof===ckA?Error(at(525)):(e=Object.prototype.toString.call(A),Error(at(31,e==="[object Object]"?"object with keys {"+Object.keys(A).join(", ")+"}":e)))}function xaA(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=RE(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=Sq(m,p.mode,D),y.return=p,y):(y=n(y,m),y.return=p,y)}function r(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),Q0(y,m),y.return=p,y):(y=qv(m.type,m.key,m.props,null,p.mode,D),Q0(y,m),y.return=p,y)}function a(p,y,m,D){return y===null||y.tag!==4||y.stateNode.containerInfo!==m.containerInfo||y.stateNode.implementation!==m.implementation?(y=wq(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=Sq(""+y,p.mode,m),y.return=p,y;if(typeof y=="object"&&y!==null){switch(y.$$typeof){case XG:return m=qv(y.type,y.key,y.props,null,p.mode,m),Q0(m,y),m.return=p,m;case sk:return y=wq(y,p.mode,m),y.return=p,y;case VQ:return y=Lh(y),c(p,y,m)}if(rk(y)||l0(y))return y=Rp(y,p.mode,m,null),y.return=p,y;if(typeof y.then=="function")return c(p,gb(y),m);if(y.$$typeof===mE)return c(p,nb(p,y),m);ob(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 XG:return m.key===S?r(p,y,m,D):null;case sk:return m.key===S?a(p,y,m,D):null;case VQ:return m=Lh(m),l(p,y,m,D)}if(rk(m)||l0(m))return S!==null?null:I(p,y,m,D,null);if(typeof m.then=="function")return l(p,y,gb(m),D);if(m.$$typeof===mE)return l(p,y,nb(p,m),D);ob(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 XG:return p=p.get(D.key===null?m:D.key)||null,r(y,p,D,S);case sk:return p=p.get(D.key===null?m:D.key)||null,a(y,p,D,S);case VQ:return D=Lh(D),B(p,y,m,D,S)}if(rk(D)||l0(D))return p=p.get(m)||null,I(y,p,D,S,null);if(typeof D.then=="function")return B(p,y,m,gb(D),S);if(D.$$typeof===mE)return B(p,y,m,nb(y,D),S);ob(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),jn&&IE(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 jn&&IE(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)}),jn&&IE(p,G),S}function h(p,y,m,D){if(m==null)throw Error(at(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),jn&&IE(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 jn&&IE(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,_)}),jn&&IE(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 XG: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),Q0(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=qv(m.type,m.key,m.props,null,p.mode,D),Q0(D,m),D.return=p,p=D)}return o(p);case sk: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=wq(m,p.mode,D),D.return=p,p=D}return o(p);case VQ:return m=Lh(m),d(p,y,m,D)}if(rk(m))return Q(p,y,m,D);if(l0(m)){if(S=l0(m),typeof S!="function")throw Error(at(150));return m=S.call(m),h(p,y,m,D)}if(typeof m.then=="function")return d(p,y,gb(m),D);if(m.$$typeof===mE)return d(p,y,nb(p,m),D);ob(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=Sq(m,p.mode,D),D.return=p,p=D),o(p)):t(p,y)}return function(p,y,m,D){try{TM=0;var S=d(p,y,m,D);return dm=null,S}catch(N){if(N===Iw||N===tL)throw N;var k=xI(29,N,null,p.mode);return k.lanes=D,k.return=p,k}finally{}}}var Xp=xaA(!0),TaA=xaA(!1),XQ=!1;function fj(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function E1(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,ag&2){var n=i.pending;return n===null?A.next=A:(A.next=n.next,n.next=A),i.pending=A,A=XK(e),baA(e,null,t),A}return eL(e,i,A,t),XK(e)}function qk(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,gaA(e,t)}}function Mq(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 Q1=!1;function Yk(){if(Q1){var e=um;if(e!==null)throw e}}function Hk(e,A,t,i){Q1=!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 r=s,a=r.next;r.next=null,o===null?g=a:o.next=a,o=r;var I=e.alternate;I!==null&&(I=I.updateQueue,s=I.lastBaseUpdate,s!==o&&(s===null?I.firstBaseUpdate=a:s.next=a,I.lastBaseUpdate=r))}if(g!==null){var c=n.baseState;o=0,I=a=r=null,s=g;do{var l=s.lane&-536870913,B=l!==s.lane;if(B?(_n&l)===l:(i&l)===l){l!==0&&l===IS&&(Q1=!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=eo({},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?(a=I=B,r=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&&(r=c),n.baseState=r,n.firstBaseUpdate=a,n.lastBaseUpdate=I,g===null&&(n.shared.lanes=0),id|=o,e.lanes=o,e.memoizedState=c}}function qaA(e,A){if(typeof e!="function")throw Error(at(191,e));e.call(A)}function YaA(e,A){var t=e.callbacks;if(t!==null)for(e.callbacks=null,e=0;e<t.length;e++)qaA(t[e],A)}var CS=wB(null),tF=wB(0);function yX(e,A){e=jE,Yg(tF,e),Yg(CS,A),jE=e|A.baseLanes}function u1(){Yg(tF,jE),Yg(CS,CS.current)}function yj(){jE=tF.current,tr(CS),tr(tF)}var AC=wB(null),ZC=null;function nu(e){var A=e.alternate;Yg(Zo,Zo.current&1),Yg(AC,e),ZC===null&&(A===null||CS.current!==null||A.memoizedState!==null)&&(ZC=e)}function d1(e){Yg(Zo,Zo.current),Yg(AC,e),ZC===null&&(ZC=e)}function HaA(e){e.tag===22?(Yg(Zo,Zo.current),Yg(AC,e),ZC===null&&(ZC=e)):gu()}function gu(){Yg(Zo,Zo.current),Yg(AC,AC.current)}function LI(e){tr(AC),ZC===e&&(ZC=null),tr(Zo)}var Zo=wB(0);function iF(e){for(var A=e;A!==null;){if(A.tag===13){var t=A.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||_1(t)||J1(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 HE=0,rn=null,Ng=null,Bs=null,nF=!1,hm=!1,$p=!1,gF=0,qM=0,pm=null,kMA=0;function Go(){throw Error(at(321))}function Dj(e,A){if(A===null)return!1;for(var t=0;t<A.length&&t<e.length;t++)if(!$I(e[t],A[t]))return!1;return!0}function mj(e,A,t,i,n,g){return HE=g,rn=A,A.memoizedState=null,A.updateQueue=null,A.lanes=0,Ki.H=e===null||e.memoizedState===null?fIA:Kj,$p=!1,g=t(i,n),$p=!1,hm&&(g=PaA(A,t,i,n)),OaA(e),g}function OaA(e){Ki.H=YM;var A=Ng!==null&&Ng.next!==null;if(HE=0,Bs=Ng=rn=null,nF=!1,qM=0,pm=null,A)throw Error(at(300));e===null||ds||(e=e.dependencies,e!==null&&AF(e)&&(ds=!0))}function PaA(e,A,t,i){rn=e;var n=0;do{if(hm&&(pm=null),qM=0,hm=!1,25<=n)throw Error(at(301));if(n+=1,Bs=Ng=null,e.updateQueue!=null){var g=e.updateQueue;g.lastEffect=null,g.events=null,g.stores=null,g.memoCache!=null&&(g.memoCache.index=0)}Ki.H=yIA,g=A(t,i)}while(hm);return g}function MMA(){var e=Ki.H,A=e.useState()[0];return A=typeof A.then=="function"?DR(A):A,e=e.useState()[0],(Ng!==null?Ng.memoizedState:null)!==e&&(rn.flags|=1024),A}function Sj(){var e=gF!==0;return gF=0,e}function wj(e,A,t){A.updateQueue=e.updateQueue,A.flags&=-2053,e.lanes&=~t}function kj(e){if(nF){for(e=e.memoizedState;e!==null;){var A=e.queue;A!==null&&(A.pending=null),e=e.next}nF=!1}HE=0,Bs=Ng=rn=null,hm=!1,qM=gF=0,pm=null}function Qa(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Bs===null?rn.memoizedState=Bs=e:Bs=Bs.next=e,Bs}function Xo(){if(Ng===null){var e=rn.alternate;e=e!==null?e.memoizedState:null}else e=Ng.next;var A=Bs===null?rn.memoizedState:Bs.next;if(A!==null)Bs=A,Ng=e;else{if(e===null)throw rn.alternate===null?Error(at(467)):Error(at(310));Ng=e,e={memoizedState:Ng.memoizedState,baseState:Ng.baseState,baseQueue:Ng.baseQueue,queue:Ng.queue,next:null},Bs===null?rn.memoizedState=Bs=e:Bs=Bs.next=e}return Bs}function iL(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function DR(e){var A=qM;return qM+=1,pm===null&&(pm=[]),e=LaA(pm,e,A),A=rn,(Bs===null?A.memoizedState:Bs.next)===null&&(A=A.alternate,Ki.H=A===null||A.memoizedState===null?fIA:Kj),e}function nL(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return DR(e);if(e.$$typeof===mE)return Dr(e)}throw Error(at(438,String(e)))}function Mj(e){var A=null,t=rn.updateQueue;if(t!==null&&(A=t.memoCache),A==null){var i=rn.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=iL(),rn.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]=lkA;return A.index++,t}function OE(e,A){return typeof A=="function"?A(e):A}function Hv(e){var A=Xo();return Nj(A,Ng,e)}function Nj(e,A,t){var i=e.queue;if(i===null)throw Error(at(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,r=null,a=A,I=!1;do{var c=a.lane&-536870913;if(c!==a.lane?(_n&c)===c:(HE&c)===c){var l=a.revertLane;if(l===0)r!==null&&(r=r.next={lane:0,revertLane:0,gesture:null,action:a.action,hasEagerState:a.hasEagerState,eagerState:a.eagerState,next:null}),c===IS&&(I=!0);else if((HE&l)===l){a=a.next,l===IS&&(I=!0);continue}else c={lane:0,revertLane:a.revertLane,gesture:null,action:a.action,hasEagerState:a.hasEagerState,eagerState:a.eagerState,next:null},r===null?(s=r=c,o=g):r=r.next=c,rn.lanes|=l,id|=l;c=a.action,$p&&t(g,c),g=a.hasEagerState?a.eagerState:t(g,c)}else l={lane:c,revertLane:a.revertLane,gesture:a.gesture,action:a.action,hasEagerState:a.hasEagerState,eagerState:a.eagerState,next:null},r===null?(s=r=l,o=g):r=r.next=l,rn.lanes|=c,id|=c;a=a.next}while(a!==null&&a!==A);if(r===null?o=g:r.next=s,!$I(g,e.memoizedState)&&(ds=!0,I&&(t=um,t!==null)))throw t;e.memoizedState=g,e.baseState=o,e.baseQueue=r,i.lastRenderedState=g}return n===null&&(i.lanes=0),[e.memoizedState,i.dispatch]}function Nq(e){var A=Xo(),t=A.queue;if(t===null)throw Error(at(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);$I(g,A.memoizedState)||(ds=!0),A.memoizedState=g,A.baseQueue===null&&(A.baseState=g),t.lastRenderedState=g}return[g,i]}function jaA(e,A,t){var i=rn,n=Xo(),g=jn;if(g){if(t===void 0)throw Error(at(407));t=t()}else t=A();var o=!$I((Ng||n).memoizedState,t);if(o&&(n.memoizedState=t,ds=!0),n=n.queue,Rj(WaA.bind(null,i,n,e),[e]),n.getSnapshot!==A||o||Bs!==null&&Bs.memoizedState.tag&1){if(i.flags|=2048,cS(9,{destroy:void 0},ZaA.bind(null,i,n,t,A),null),Jg===null)throw Error(at(349));g||HE&127||zaA(i,A,t)}return t}function zaA(e,A,t){e.flags|=16384,e={getSnapshot:A,value:t},A=rn.updateQueue,A===null?(A=iL(),rn.updateQueue=A,A.stores=[e]):(t=A.stores,t===null?A.stores=[e]:t.push(e))}function ZaA(e,A,t,i){A.value=t,A.getSnapshot=i,VaA(A)&&XaA(e)}function WaA(e,A,t){return t(function(){VaA(A)&&XaA(e)})}function VaA(e){var A=e.getSnapshot;e=e.value;try{var t=A();return!$I(e,t)}catch{return!0}}function XaA(e){var A=Gf(e,2);A!==null&&oI(A,e,2)}function h1(e){var A=Qa();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:OE,lastRenderedState:e},A}function $aA(e,A,t,i){return e.baseState=t,Nj(e,Ng,typeof i=="function"?i:OE)}function NMA(e,A,t,i,n){if(oL(e))throw Error(at(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)}};Ki.T!==null?t(!0):g.isTransition=!1,i(g),t=A.pending,t===null?(g.next=A.pending=g,AIA(A,g)):(g.next=t.next,A.pending=t.next=g)}}function AIA(e,A){var t=A.action,i=A.payload,n=e.state;if(A.isTransition){var g=Ki.T,o={};Ki.T=o;try{var s=t(n,i),r=Ki.S;r!==null&&r(o,s),DX(e,A,s)}catch(a){p1(e,A,a)}finally{g!==null&&o.types!==null&&(g.types=o.types),Ki.T=g}}else try{g=t(n,i),DX(e,A,g)}catch(a){p1(e,A,a)}}function DX(e,A,t){t!==null&&typeof t=="object"&&typeof t.then=="function"?t.then(function(i){mX(e,A,i)},function(i){return p1(e,A,i)}):mX(e,A,t)}function mX(e,A,t){A.status="fulfilled",A.value=t,eIA(A),e.state=t,A=e.pending,A!==null&&(t=A.next,t===A?e.pending=null:(t=t.next,A.next=t,AIA(e,t)))}function p1(e,A,t){var i=e.pending;if(e.pending=null,i!==null){i=i.next;do A.status="rejected",A.reason=t,eIA(A),A=A.next;while(A!==i)}e.action=null}function eIA(e){e=e.listeners;for(var A=0;A<e.length;A++)(0,e[A])()}function tIA(e,A){return A}function SX(e,A){if(jn){var t=Jg.formState;if(t!==null){A:{var i=rn;if(jn){if(Wg){e:{for(var n=Wg,g=OC;n.nodeType!==8;){if(!g){n=null;break e}if(n=WC(n.nextSibling),n===null){n=null;break e}}g=n.data,n=g==="F!"||g==="F"?n:null}if(n){Wg=WC(n.nextSibling),i=n.data==="F!";break A}}ed(i)}i=!1}i&&(A=t[0])}}return t=Qa(),t.memoizedState=t.baseState=A,i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:tIA,lastRenderedState:A},t.queue=i,t=dIA.bind(null,rn,i),i.dispatch=t,i=h1(!1),g=vj.bind(null,rn,!1,i.queue),i=Qa(),n={state:A,dispatch:null,action:e,pending:null},i.queue=n,t=NMA.bind(null,rn,n,g,t),n.dispatch=t,i.memoizedState=e,[A,t,!1]}function wX(e){var A=Xo();return iIA(A,Ng,e)}function iIA(e,A,t){if(A=Nj(e,A,tIA)[0],e=Hv(OE)[0],typeof A=="object"&&A!==null&&typeof A.then=="function")try{var i=DR(A)}catch(o){throw o===Iw?tL:o}else i=A;A=Xo();var n=A.queue,g=n.dispatch;return t!==A.memoizedState&&(rn.flags|=2048,cS(9,{destroy:void 0},RMA.bind(null,n,t),null)),[i,g,e]}function RMA(e,A){e.action=A}function kX(e){var A=Xo(),t=Ng;if(t!==null)return iIA(A,t,e);Xo(),A=A.memoizedState,t=Xo();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=rn.updateQueue,A===null&&(A=iL(),rn.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 nIA(){return Xo().memoizedState}function Ov(e,A,t,i){var n=Qa();rn.flags|=e,n.memoizedState=cS(1|A,{destroy:void 0},t,i===void 0?null:i)}function gL(e,A,t,i){var n=Xo();i=i===void 0?null:i;var g=n.memoizedState.inst;Ng!==null&&i!==null&&Dj(i,Ng.memoizedState.deps)?n.memoizedState=cS(A,g,t,i):(rn.flags|=e,n.memoizedState=cS(1|A,g,t,i))}function MX(e,A){Ov(8390656,8,e,A)}function Rj(e,A){gL(2048,8,e,A)}function GMA(e){rn.flags|=4;var A=rn.updateQueue;if(A===null)A=iL(),rn.updateQueue=A,A.events=[e];else{var t=A.events;t===null?A.events=[e]:t.push(e)}}function gIA(e){var A=Xo().memoizedState;return GMA({ref:A,nextImpl:e}),function(){if(ag&2)throw Error(at(440));return A.impl.apply(void 0,arguments)}}function oIA(e,A){return gL(4,2,e,A)}function sIA(e,A){return gL(4,4,e,A)}function rIA(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 aIA(e,A,t){t=t!=null?t.concat([e]):null,gL(4,4,rIA.bind(null,A,e),t)}function Gj(){}function IIA(e,A){var t=Xo();A=A===void 0?null:A;var i=t.memoizedState;return A!==null&&Dj(A,i[1])?i[0]:(t.memoizedState=[e,A],e)}function CIA(e,A){var t=Xo();A=A===void 0?null:A;var i=t.memoizedState;if(A!==null&&Dj(A,i[1]))return i[0];if(i=e(),$p){uu(!0);try{e()}finally{uu(!1)}}return t.memoizedState=[i,A],i}function bj(e,A,t){return t===void 0||HE&1073741824&&!(_n&261930)?e.memoizedState=A:(e.memoizedState=t,e=$IA(),rn.lanes|=e,id|=e,t)}function cIA(e,A,t,i){return $I(t,A)?t:CS.current!==null?(e=bj(e,t,i),$I(e,A)||(ds=!0),e):!(HE&42)||HE&1073741824&&!(_n&261930)?(ds=!0,e.memoizedState=t):(e=$IA(),rn.lanes|=e,id|=e,A)}function lIA(e,A,t,i,n){var g=Ig.p;Ig.p=g!==0&&8>g?g:8;var o=Ki.T,s={};Ki.T=s,vj(e,!1,A,t);try{var r=n(),a=Ki.S;if(a!==null&&a(s,r),r!==null&&typeof r=="object"&&typeof r.then=="function"){var I=wMA(r,i);Ok(e,A,I,ZI(e))}else Ok(e,A,i,ZI(e))}catch(c){Ok(e,A,{then:function(){},status:"rejected",reason:c},ZI())}finally{Ig.p=g,o!==null&&s.types!==null&&(o.types=s.types),Ki.T=o}}function bMA(){}function f1(e,A,t,i){if(e.tag!==5)throw Error(at(476));var n=BIA(e).queue;lIA(e,n,A,Np,t===null?bMA:function(){return EIA(e),t(i)})}function BIA(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:OE,lastRenderedState:Np},next:null};var t={};return A.next={memoizedState:t,baseState:t,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:OE,lastRenderedState:t},next:null},e.memoizedState=A,e=e.alternate,e!==null&&(e.memoizedState=A),A}function EIA(e){var A=BIA(e);A.next===null&&(A=e.alternate.memoizedState),Ok(e,A.next.queue,{},ZI())}function Uj(){return Dr(PM)}function QIA(){return Xo().memoizedState}function uIA(){return Xo().memoizedState}function UMA(e){for(var A=e.return;A!==null;){switch(A.tag){case 24:case 3:var t=ZI();e=vu(t);var i=Ku(A,e,t);i!==null&&(oI(i,A,t),qk(i,A,t)),A={cache:dj()},e.payload=A;return}A=A.return}}function vMA(e,A,t){var i=ZI();t={lane:i,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null},oL(e)?hIA(A,t):(t=Bj(e,A,t,i),t!==null&&(oI(t,e,i),pIA(t,A,i)))}function dIA(e,A,t){var i=ZI();Ok(e,A,t,i)}function Ok(e,A,t,i){var n={lane:i,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null};if(oL(e))hIA(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,$I(s,o))return eL(e,A,n,0),Jg===null&&AL(),!1}catch{}finally{}if(t=Bj(e,A,n,i),t!==null)return oI(t,e,i),pIA(t,A,i),!0}return!1}function vj(e,A,t,i){if(i={lane:2,revertLane:Yj(),gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},oL(e)){if(A)throw Error(at(479))}else A=Bj(e,t,i,2),A!==null&&oI(A,e,2)}function oL(e){var A=e.alternate;return e===rn||A!==null&&A===rn}function hIA(e,A){hm=nF=!0;var t=e.pending;t===null?A.next=A:(A.next=t.next,t.next=A),e.pending=A}function pIA(e,A,t){if(t&4194048){var i=A.lanes;i&=e.pendingLanes,t|=i,A.lanes=t,gaA(e,t)}}var YM={readContext:Dr,use:nL,useCallback:Go,useContext:Go,useEffect:Go,useImperativeHandle:Go,useLayoutEffect:Go,useInsertionEffect:Go,useMemo:Go,useReducer:Go,useRef:Go,useState:Go,useDebugValue:Go,useDeferredValue:Go,useTransition:Go,useSyncExternalStore:Go,useId:Go,useHostTransitionStatus:Go,useFormState:Go,useActionState:Go,useOptimistic:Go,useMemoCache:Go,useCacheRefresh:Go};YM.useEffectEvent=Go;var fIA={readContext:Dr,use:nL,useCallback:function(e,A){return Qa().memoizedState=[e,A===void 0?null:A],e},useContext:Dr,useEffect:MX,useImperativeHandle:function(e,A,t){t=t!=null?t.concat([e]):null,Ov(4194308,4,rIA.bind(null,A,e),t)},useLayoutEffect:function(e,A){return Ov(4194308,4,e,A)},useInsertionEffect:function(e,A){Ov(4,2,e,A)},useMemo:function(e,A){var t=Qa();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=Qa();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=vMA.bind(null,rn,e),[i.memoizedState,e]},useRef:function(e){var A=Qa();return e={current:e},A.memoizedState=e},useState:function(e){e=h1(e);var A=e.queue,t=dIA.bind(null,rn,A);return A.dispatch=t,[e.memoizedState,t]},useDebugValue:Gj,useDeferredValue:function(e,A){var t=Qa();return bj(t,e,A)},useTransition:function(){var e=h1(!1);return e=lIA.bind(null,rn,e.queue,!0,!1),Qa().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,A,t){var i=rn,n=Qa();if(jn){if(t===void 0)throw Error(at(407));t=t()}else{if(t=A(),Jg===null)throw Error(at(349));_n&127||zaA(i,A,t)}n.memoizedState=t;var g={value:t,getSnapshot:A};return n.queue=g,MX(WaA.bind(null,i,g,e),[e]),i.flags|=2048,cS(9,{destroy:void 0},ZaA.bind(null,i,g,t,A),null),t},useId:function(){var e=Qa(),A=Jg.identifierPrefix;if(jn){var t=eB,i=AB;t=(i&~(1<<32-zI(i)-1)).toString(32)+t,A="_"+A+"R_"+t,t=gF++,0<t&&(A+="H"+t.toString(32)),A+="_"}else t=kMA++,A="_"+A+"r_"+t.toString(32)+"_";return e.memoizedState=A},useHostTransitionStatus:Uj,useFormState:SX,useActionState:SX,useOptimistic:function(e){var A=Qa();A.memoizedState=A.baseState=e;var t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return A.queue=t,A=vj.bind(null,rn,!0,t),t.dispatch=A,[e,A]},useMemoCache:Mj,useCacheRefresh:function(){return Qa().memoizedState=UMA.bind(null,rn)},useEffectEvent:function(e){var A=Qa(),t={impl:e};return A.memoizedState=t,function(){if(ag&2)throw Error(at(440));return t.impl.apply(void 0,arguments)}}},Kj={readContext:Dr,use:nL,useCallback:IIA,useContext:Dr,useEffect:Rj,useImperativeHandle:aIA,useInsertionEffect:oIA,useLayoutEffect:sIA,useMemo:CIA,useReducer:Hv,useRef:nIA,useState:function(){return Hv(OE)},useDebugValue:Gj,useDeferredValue:function(e,A){var t=Xo();return cIA(t,Ng.memoizedState,e,A)},useTransition:function(){var e=Hv(OE)[0],A=Xo().memoizedState;return[typeof e=="boolean"?e:DR(e),A]},useSyncExternalStore:jaA,useId:QIA,useHostTransitionStatus:Uj,useFormState:wX,useActionState:wX,useOptimistic:function(e,A){var t=Xo();return $aA(t,Ng,e,A)},useMemoCache:Mj,useCacheRefresh:uIA};Kj.useEffectEvent=gIA;var yIA={readContext:Dr,use:nL,useCallback:IIA,useContext:Dr,useEffect:Rj,useImperativeHandle:aIA,useInsertionEffect:oIA,useLayoutEffect:sIA,useMemo:CIA,useReducer:Nq,useRef:nIA,useState:function(){return Nq(OE)},useDebugValue:Gj,useDeferredValue:function(e,A){var t=Xo();return Ng===null?bj(t,e,A):cIA(t,Ng.memoizedState,e,A)},useTransition:function(){var e=Nq(OE)[0],A=Xo().memoizedState;return[typeof e=="boolean"?e:DR(e),A]},useSyncExternalStore:jaA,useId:QIA,useHostTransitionStatus:Uj,useFormState:kX,useActionState:kX,useOptimistic:function(e,A){var t=Xo();return Ng!==null?$aA(t,Ng,e,A):(t.baseState=e,[e,t.queue.dispatch])},useMemoCache:Mj,useCacheRefresh:uIA};yIA.useEffectEvent=gIA;function Rq(e,A,t,i){A=e.memoizedState,t=t(i,A),t=t==null?A:eo({},A,t),e.memoizedState=t,e.lanes===0&&(e.updateQueue.baseState=t)}var y1={enqueueSetState:function(e,A,t){e=e._reactInternals;var i=ZI(),n=vu(i);n.payload=A,t!=null&&(n.callback=t),A=Ku(e,n,i),A!==null&&(oI(A,e,i),qk(A,e,i))},enqueueReplaceState:function(e,A,t){e=e._reactInternals;var i=ZI(),n=vu(i);n.tag=1,n.payload=A,t!=null&&(n.callback=t),A=Ku(e,n,i),A!==null&&(oI(A,e,i),qk(A,e,i))},enqueueForceUpdate:function(e,A){e=e._reactInternals;var t=ZI(),i=vu(t);i.tag=2,A!=null&&(i.callback=A),A=Ku(e,i,t),A!==null&&(oI(A,e,t),qk(A,e,t))}};function NX(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?!JM(t,i)||!JM(n,g):!0}function RX(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&&y1.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=eo({},t));for(var n in e)t[n]===void 0&&(t[n]=e[n])}return t}function DIA(e){VK(e)}function mIA(e){console.error(e)}function SIA(e){VK(e)}function oF(e,A){try{var t=e.onUncaughtError;t(A.value,{componentStack:A.stack})}catch(i){setTimeout(function(){throw i})}}function GX(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 D1(e,A,t){return t=vu(t),t.tag=3,t.payload={element:null},t.callback=function(){oF(e,A)},t}function wIA(e){return e=vu(e),e.tag=3,e}function kIA(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(){GX(A,t,i)}}var o=t.stateNode;o!==null&&typeof o.componentDidCatch=="function"&&(e.callback=function(){GX(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 KMA(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=AC.current,t!==null){switch(t.tag){case 31:case 13:return ZC===null?CF():t.alternate===null&&_o===0&&(_o=3),t.flags&=-257,t.flags|=65536,t.lanes=n,i===eF?t.flags|=16384:(A=t.updateQueue,A===null?t.updateQueue=new Set([i]):A.add(i),Tq(e,i,n)),!1;case 22:return t.flags|=65536,i===eF?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)),Tq(e,i,n)),!1}throw Error(at(435,t.tag))}return Tq(e,i,n),CF(),!1}if(jn)return A=AC.current,A!==null?(!(A.flags&65536)&&(A.flags|=256),A.flags|=65536,A.lanes=n,i!==I1&&(e=Error(at(422),{cause:i}),xM(HC(e,t)))):(i!==I1&&(A=Error(at(423),{cause:i}),xM(HC(A,t))),e=e.current.alternate,e.flags|=65536,n&=-n,e.lanes|=n,i=HC(i,t),n=D1(e.stateNode,i,n),Mq(e,n),_o!==4&&(_o=2)),!1;var g=Error(at(520),{cause:i});if(g=HC(g,t),zk===null?zk=[g]:zk.push(g),_o!==4&&(_o=2),A===null)return!0;i=HC(i,t),t=A;do{switch(t.tag){case 3:return t.flags|=65536,e=n&-n,t.lanes|=e,e=D1(t.stateNode,i,e),Mq(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=wIA(n),kIA(n,e,t,i),Mq(t,n),!1}t=t.return}while(t!==null);return!1}var Fj=Error(at(461)),ds=!1;function Qr(e,A,t,i){A.child=e===null?TaA(A,null,t,i):Xp(A,e.child,t,i)}function bX(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=mj(e,A,t,o,g,n),s=Sj(),e!==null&&!ds?(wj(e,A,n),PE(e,A,n)):(jn&&s&&Qj(A),A.flags|=1,Qr(e,A,i,n),A.child)}function UX(e,A,t,i,n){if(e===null){var g=t.type;return typeof g=="function"&&!Ej(g)&&g.defaultProps===void 0&&t.compare===null?(A.tag=15,A.type=g,MIA(e,A,g,i,n)):(e=qv(t.type,null,i,A,A.mode,n),e.ref=A.ref,e.return=A,A.child=e)}if(g=e.child,!_j(e,n)){var o=g.memoizedProps;if(t=t.compare,t=t!==null?t:JM,t(o,i)&&e.ref===A.ref)return PE(e,A,n)}return A.flags|=1,e=RE(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(JM(g,i)&&e.ref===A.ref)if(ds=!1,A.pendingProps=i=g,_j(e,n))e.flags&131072&&(ds=!0);else return A.lanes=e.lanes,PE(e,A,n)}return m1(e,A,t,i,n)}function NIA(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 vX(e,A,g,t,i)}if(t&536870912)A.memoizedState={baseLanes:0,cachePool:null},e!==null&&Yv(A,g!==null?g.cachePool:null),g!==null?yX(A,g):u1(),HaA(A);else return i=A.lanes=536870912,vX(e,A,g!==null?g.baseLanes|t:t,t,i)}else g!==null?(Yv(A,g.cachePool),yX(A,g),gu(),A.memoizedState=null):(e!==null&&Yv(A,null),u1(),gu());return Qr(e,A,n,t),A.child}function Ik(e,A){return e!==null&&e.tag===22||A.stateNode!==null||(A.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),A.sibling}function vX(e,A,t,i,n){var g=hj();return g=g===null?null:{parent:us._currentValue,pool:g},A.memoizedState={baseLanes:t,cachePool:g},e!==null&&Yv(A,null),u1(),HaA(A),e!==null&&aw(e,A,i,!0),A.childLanes=n,null}function Pv(e,A){return A=sF({mode:A.mode,children:A.children},e.mode),A.ref=e.ref,e.child=A,A.return=e,A}function KX(e,A,t){return Xp(A,e.child,null,t),e=Pv(A,A.pendingProps),e.flags|=2,LI(A),A.memoizedState=null,e}function FMA(e,A,t){var i=A.pendingProps,n=(A.flags&128)!==0;if(A.flags&=-129,e===null){if(jn){if(i.mode==="hidden")return e=Pv(A,i),A.lanes=536870912,Ik(null,e);if(d1(A),(e=Wg)?(e=fCA(e,OC),e=e!==null&&e.data==="&"?e:null,e!==null&&(A.memoizedState={dehydrated:e,treeContext:Ad!==null?{id:AB,overflow:eB}:null,retryLane:536870912,hydrationErrors:null},t=vaA(e),t.return=A,A.child=t,fr=A,Wg=null)):e=null,e===null)throw ed(A);return A.lanes=536870912,null}return Pv(A,i)}var g=e.memoizedState;if(g!==null){var o=g.dehydrated;if(d1(A),n)if(A.flags&256)A.flags&=-257,A=KX(e,A,t);else if(A.memoizedState!==null)A.child=e.child,A.flags|=128,A=null;else throw Error(at(558));else if(ds||aw(e,A,t,!1),n=(t&e.childLanes)!==0,ds||n){if(i=Jg,i!==null&&(o=oaA(i,t),o!==0&&o!==g.retryLane))throw g.retryLane=o,Gf(e,o),oI(i,e,o),Fj;CF(),A=KX(e,A,t)}else e=g.treeContext,Wg=WC(o.nextSibling),fr=A,jn=!0,Uu=null,OC=!1,e!==null&&FaA(A,e),A=Pv(A,i),A.flags|=4096;return A}return e=RE(e.child,{mode:i.mode,children:i.children}),e.ref=A.ref,A.child=e,e.return=A,e}function jv(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(at(284));(e===null||e.ref!==t)&&(A.flags|=4194816)}}function m1(e,A,t,i,n){return Vp(A),t=mj(e,A,t,i,void 0,n),i=Sj(),e!==null&&!ds?(wj(e,A,n),PE(e,A,n)):(jn&&i&&Qj(A),A.flags|=1,Qr(e,A,t,n),A.child)}function FX(e,A,t,i,n,g){return Vp(A),A.updateQueue=null,t=PaA(A,i,t,n),OaA(e),i=Sj(),e!==null&&!ds?(wj(e,A,g),PE(e,A,g)):(jn&&i&&Qj(A),A.flags|=1,Qr(e,A,t,g),A.child)}function _X(e,A,t,i,n){if(Vp(A),A.stateNode===null){var g=OD,o=t.contextType;typeof o=="object"&&o!==null&&(g=Dr(o)),g=new t(i,g),A.memoizedState=g.state!==null&&g.state!==void 0?g.state:null,g.updater=y1,A.stateNode=g,g._reactInternals=A,g=A.stateNode,g.props=i,g.state=A.memoizedState,g.refs={},fj(A),o=t.contextType,g.context=typeof o=="object"&&o!==null?Dr(o):OD,g.state=A.memoizedState,o=t.getDerivedStateFromProps,typeof o=="function"&&(Rq(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&&y1.enqueueReplaceState(g,g.state,null),Hk(A,i,g,n),Yk(),g.state=A.memoizedState),typeof g.componentDidMount=="function"&&(A.flags|=4194308),i=!0}else if(e===null){g=A.stateNode;var s=A.memoizedProps,r=Af(t,s);g.props=r;var a=g.context,I=t.contextType;o=OD,typeof I=="object"&&I!==null&&(o=Dr(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||a!==o)&&RX(A,g,i,o),XQ=!1;var l=A.memoizedState;g.state=l,Hk(A,i,g,n),Yk(),a=A.memoizedState,s||l!==a||XQ?(typeof c=="function"&&(Rq(A,t,c,i),a=A.memoizedState),(r=XQ||NX(A,t,r,i,l,a,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=a),g.props=i,g.state=a,g.context=o,i=r):(typeof g.componentDidMount=="function"&&(A.flags|=4194308),i=!1)}else{g=A.stateNode,E1(e,A),o=A.memoizedProps,I=Af(t,o),g.props=I,c=A.pendingProps,l=g.context,a=t.contextType,r=OD,typeof a=="object"&&a!==null&&(r=Dr(a)),s=t.getDerivedStateFromProps,(a=typeof s=="function"||typeof g.getSnapshotBeforeUpdate=="function")||typeof g.UNSAFE_componentWillReceiveProps!="function"&&typeof g.componentWillReceiveProps!="function"||(o!==c||l!==r)&&RX(A,g,i,r),XQ=!1,l=A.memoizedState,g.state=l,Hk(A,i,g,n),Yk();var B=A.memoizedState;o!==c||l!==B||XQ||e!==null&&e.dependencies!==null&&AF(e.dependencies)?(typeof s=="function"&&(Rq(A,t,s,i),B=A.memoizedState),(I=XQ||NX(A,t,I,i,l,B,r)||e!==null&&e.dependencies!==null&&AF(e.dependencies))?(a||typeof g.UNSAFE_componentWillUpdate!="function"&&typeof g.componentWillUpdate!="function"||(typeof g.componentWillUpdate=="function"&&g.componentWillUpdate(i,B,r),typeof g.UNSAFE_componentWillUpdate=="function"&&g.UNSAFE_componentWillUpdate(i,B,r)),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=r,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,jv(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)):Qr(e,A,t,n),A.memoizedState=g.state,e=A.child):e=PE(e,A,n),e}function JX(e,A,t,i){return Wp(),A.flags|=256,Qr(e,A,t,i),A.child}var Gq={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function bq(e){return{baseLanes:e,cachePool:JaA()}}function Uq(e,A,t){return e=e!==null?e.childLanes&~t:0,A&&(e|=TI),e}function RIA(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:(Zo.current&2)!==0),o&&(n=!0,A.flags&=-129),o=(A.flags&32)!==0,A.flags&=-33,e===null){if(jn){if(n?nu(A):gu(),(e=Wg)?(e=fCA(e,OC),e=e!==null&&e.data!=="&"?e:null,e!==null&&(A.memoizedState={dehydrated:e,treeContext:Ad!==null?{id:AB,overflow:eB}:null,retryLane:536870912,hydrationErrors:null},t=vaA(e),t.return=A,A.child=t,fr=A,Wg=null)):e=null,e===null)throw ed(A);return J1(e)?A.lanes=32:A.lanes=536870912,null}var s=i.children;return i=i.fallback,n?(gu(),n=A.mode,s=sF({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=bq(t),i.childLanes=Uq(e,o,t),A.memoizedState=Gq,Ik(null,i)):(nu(A),S1(A,s))}var r=e.memoizedState;if(r!==null&&(s=r.dehydrated,s!==null)){if(g)A.flags&256?(nu(A),A.flags&=-257,A=vq(e,A,t)):A.memoizedState!==null?(gu(),A.child=e.child,A.flags|=128,A=null):(gu(),s=i.fallback,n=A.mode,i=sF({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=bq(t),i.childLanes=Uq(e,o,t),A.memoizedState=Gq,A=Ik(null,i));else if(nu(A),J1(s)){if(o=s.nextSibling&&s.nextSibling.dataset,o)var a=o.dgst;o=a,i=Error(at(419)),i.stack="",i.digest=o,xM({value:i,source:null,stack:null}),A=vq(e,A,t)}else if(ds||aw(e,A,t,!1),o=(t&e.childLanes)!==0,ds||o){if(o=Jg,o!==null&&(i=oaA(o,t),i!==0&&i!==r.retryLane))throw r.retryLane=i,Gf(e,i),oI(o,e,i),Fj;_1(s)||CF(),A=vq(e,A,t)}else _1(s)?(A.flags|=192,A.child=e.child,A=null):(e=r.treeContext,Wg=WC(s.nextSibling),fr=A,jn=!0,Uu=null,OC=!1,e!==null&&FaA(A,e),A=S1(A,i.children),A.flags|=4096);return A}return n?(gu(),s=i.fallback,n=A.mode,r=e.child,a=r.sibling,i=RE(r,{mode:"hidden",children:i.children}),i.subtreeFlags=r.subtreeFlags&65011712,a!==null?s=RE(a,s):(s=Rp(s,n,t,null),s.flags|=2),s.return=A,i.return=A,i.sibling=s,A.child=i,Ik(null,i),i=A.child,s=e.child.memoizedState,s===null?s=bq(t):(n=s.cachePool,n!==null?(r=us._currentValue,n=n.parent!==r?{parent:r,pool:r}:n):n=JaA(),s={baseLanes:s.baseLanes|t,cachePool:n}),i.memoizedState=s,i.childLanes=Uq(e,o,t),A.memoizedState=Gq,Ik(e.child,i)):(nu(A),t=e.child,e=t.sibling,t=RE(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 S1(e,A){return A=sF({mode:"visible",children:A},e.mode),A.return=e,e.child=A}function sF(e,A){return e=xI(22,e,null,A),e.lanes=0,e}function vq(e,A,t){return Xp(A,e.child,null,t),e=S1(A,A.pendingProps.children),e.flags|=2,A.memoizedState=null,e}function LX(e,A,t){e.lanes|=A;var i=e.alternate;i!==null&&(i.lanes|=A),c1(e.return,A,t)}function Kq(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 GIA(e,A,t){var i=A.pendingProps,n=i.revealOrder,g=i.tail;i=i.children;var o=Zo.current,s=(o&2)!==0;if(s?(o=o&1|2,A.flags|=128):o&=1,Yg(Zo,o),Qr(e,A,i,t),i=jn?LM:0,!s&&e!==null&&e.flags&128)A:for(e=A.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&LX(e,t,A);else if(e.tag===19)LX(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&&iF(e)===null&&(n=t),t=t.sibling;t=n,t===null?(n=A.child,A.child=null):(n=t.sibling,t.sibling=null),Kq(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&&iF(e)===null){A.child=n;break}e=n.sibling,n.sibling=t,t=n,n=e}Kq(A,!0,t,null,g,i);break;case"together":Kq(A,!1,null,null,void 0,i);break;default:A.memoizedState=null}return A.child}function PE(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(at(153));if(A.child!==null){for(e=A.child,t=RE(e,e.pendingProps),A.child=t,t.return=A;e.sibling!==null;)e=e.sibling,t=t.sibling=RE(e,e.pendingProps),t.return=A;t.sibling=null}return A.child}function _j(e,A){return e.lanes&A?!0:(e=e.dependencies,!!(e!==null&&AF(e)))}function _MA(e,A,t){switch(A.tag){case 3:jK(A,A.stateNode.containerInfo),iu(A,us,e.memoizedState.cache),Wp();break;case 27:case 5:$O(A);break;case 4:jK(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,d1(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?RIA(e,A,t):(nu(A),e=PE(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 GIA(e,A,t);A.flags|=128}if(n=A.memoizedState,n!==null&&(n.rendering=null,n.tail=null,n.lastEffect=null),Yg(Zo,Zo.current),i)break;return null;case 22:return A.lanes=0,NIA(e,A,t,A.pendingProps);case 24:iu(A,us,e.memoizedState.cache)}return PE(e,A,t)}function bIA(e,A,t){if(e!==null)if(e.memoizedProps!==A.pendingProps)ds=!0;else{if(!_j(e,t)&&!(A.flags&128))return ds=!1,_MA(e,A,t);ds=!!(e.flags&131072)}else ds=!1,jn&&A.flags&1048576&&KaA(A,LM,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")Ej(e)?(i=Af(e,i),A.tag=1,A=_X(null,A,e,i,t)):(A.tag=0,A=m1(null,A,e,i,t));else{if(e!=null){var n=e.$$typeof;if(n===ej){A.tag=11,A=bX(null,A,e,i,t);break A}else if(n===tj){A.tag=14,A=UX(null,A,e,i,t);break A}}throw A=VO(e)||e,Error(at(306,A,""))}}return A;case 0:return m1(e,A,A.type,A.pendingProps,t);case 1:return i=A.type,n=Af(i,A.pendingProps),_X(e,A,i,n,t);case 3:A:{if(jK(A,A.stateNode.containerInfo),e===null)throw Error(at(387));i=A.pendingProps;var g=A.memoizedState;n=g.element,E1(e,A),Hk(A,i,null,t);var o=A.memoizedState;if(i=o.cache,iu(A,us,i),i!==g.cache&&l1(A,[us],t,!0),Yk(),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=JX(e,A,i,t);break A}else if(i!==n){n=HC(Error(at(424)),A),xM(n),A=JX(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(Wg=WC(e.firstChild),fr=A,jn=!0,Uu=null,OC=!0,t=TaA(A,null,i,t),A.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling}else{if(Wp(),i===n){A=PE(e,A,t);break A}Qr(e,A,i,t)}A=A.child}return A;case 26:return jv(e,A),e===null?(t=g6(A.type,null,A.pendingProps,null))?A.memoizedState=t:jn||(t=A.type,e=A.pendingProps,i=EF(bu.current).createElement(t),i[pr]=A,i[rI]=e,wr(i,t,e),$s(i),A.stateNode=i):A.memoizedState=g6(A.type,e.memoizedProps,A.pendingProps,e.memoizedState),null;case 27:return $O(A),e===null&&jn&&(i=A.stateNode=yCA(A.type,A.pendingProps,bu.current),fr=A,OC=!0,n=Wg,Sd(A.type)?(L1=n,Wg=WC(i.firstChild)):Wg=n),Qr(e,A,A.pendingProps.children,t),jv(e,A),e===null&&(A.flags|=4194304),A.child;case 5:return e===null&&jn&&((n=i=Wg)&&(i=lNA(i,A.type,A.pendingProps,OC),i!==null?(A.stateNode=i,fr=A,Wg=WC(i.firstChild),OC=!1,n=!0):n=!1),n||ed(A)),$O(A),n=A.type,g=A.pendingProps,o=e!==null?e.memoizedProps:null,i=g.children,K1(n,g)?i=null:o!==null&&K1(n,o)&&(A.flags|=32),A.memoizedState!==null&&(n=mj(e,A,MMA,null,null,t),PM._currentValue=n),jv(e,A),Qr(e,A,i,t),A.child;case 6:return e===null&&jn&&((e=t=Wg)&&(t=BNA(t,A.pendingProps,OC),t!==null?(A.stateNode=t,fr=A,Wg=null,e=!0):e=!1),e||ed(A)),null;case 13:return RIA(e,A,t);case 4:return jK(A,A.stateNode.containerInfo),i=A.pendingProps,e===null?A.child=Xp(A,null,i,t):Qr(e,A,i,t),A.child;case 11:return bX(e,A,A.type,A.pendingProps,t);case 7:return Qr(e,A,A.pendingProps,t),A.child;case 8:return Qr(e,A,A.pendingProps.children,t),A.child;case 12:return Qr(e,A,A.pendingProps.children,t),A.child;case 10:return i=A.pendingProps,iu(A,A.type,i.value),Qr(e,A,i.children,t),A.child;case 9:return n=A.type._context,i=A.pendingProps.children,Vp(A),n=Dr(n),i=i(n),A.flags|=1,Qr(e,A,i,t),A.child;case 14:return UX(e,A,A.type,A.pendingProps,t);case 15:return MIA(e,A,A.type,A.pendingProps,t);case 19:return GIA(e,A,t);case 31:return FMA(e,A,t);case 22:return NIA(e,A,t,A.pendingProps);case 24:return Vp(A),i=Dr(us),e===null?(n=hj(),n===null&&(n=Jg,g=dj(),n.pooledCache=g,g.refCount++,g!==null&&(n.pooledCacheLanes|=t),n=g),A.memoizedState={parent:i,cache:n},fj(A),iu(A,us,n)):(e.lanes&t&&(E1(e,A),Hk(A,null,null,t),Yk()),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,us,i)):(i=g.cache,iu(A,us,i),i!==n.cache&&l1(A,[us],t,!0))),Qr(e,A,A.pendingProps.children,t),A.child;case 29:throw A.pendingProps}throw Error(at(156,A.tag))}function PB(e){e.flags|=4}function Fq(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(tCA())e.flags|=8192;else throw bp=eF,pj}else e.flags&=-16777217}function xX(e,A){if(A.type!=="stylesheet"||A.state.loading&4)e.flags&=-16777217;else if(e.flags|=16777216,!SCA(A))if(tCA())e.flags|=8192;else throw bp=eF,pj}function sb(e,A){A!==null&&(e.flags|=4),e.flags&16384&&(A=e.tag!==22?iaA():536870912,e.lanes|=A,lS|=A)}function u0(e,A){if(!jn)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 zg(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 JMA(e,A,t){var i=A.pendingProps;switch(uj(A),A.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return zg(A),null;case 1:return zg(A),null;case 3:return t=A.stateNode,i=null,e!==null&&(i=e.memoizedState.cache),A.memoizedState.cache!==i&&(A.flags|=2048),GE(us),sS(),t.pendingContext&&(t.context=t.pendingContext,t.pendingContext=null),(e===null||e.child===null)&&(Uy(A)?PB(A):e===null||e.memoizedState.isDehydrated&&!(A.flags&256)||(A.flags|=1024,kq())),zg(A),null;case 26:var n=A.type,g=A.memoizedState;return e===null?(PB(A),g!==null?(zg(A),xX(A,g)):(zg(A),Fq(A,n,null,i,t))):g?g!==e.memoizedState?(PB(A),zg(A),xX(A,g)):(zg(A),A.flags&=-16777217):(e=e.memoizedProps,e!==i&&PB(A),zg(A),Fq(A,n,e,i,t)),null;case 27:if(zK(A),t=bu.current,n=A.type,e!==null&&A.stateNode!=null)e.memoizedProps!==i&&PB(A);else{if(!i){if(A.stateNode===null)throw Error(at(166));return zg(A),null}e=aB.current,Uy(A)?EX(A):(e=yCA(n,i,t),A.stateNode=e,PB(A))}return zg(A),null;case 5:if(zK(A),n=A.type,e!==null&&A.stateNode!=null)e.memoizedProps!==i&&PB(A);else{if(!i){if(A.stateNode===null)throw Error(at(166));return zg(A),null}if(g=aB.current,Uy(A))EX(A);else{var o=EF(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[pr]=A,g[rI]=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(wr(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&&PB(A)}}return zg(A),Fq(A,A.type,e===null?null:e.memoizedProps,A.pendingProps,t),null;case 6:if(e&&A.stateNode!=null)e.memoizedProps!==i&&PB(A);else{if(typeof i!="string"&&A.stateNode===null)throw Error(at(166));if(e=bu.current,Uy(A)){if(e=A.stateNode,t=A.memoizedProps,i=null,n=fr,n!==null)switch(n.tag){case 27:case 5:i=n.memoizedProps}e[pr]=A,e=!!(e.nodeValue===t||i!==null&&i.suppressHydrationWarning===!0||dCA(e.nodeValue,t)),e||ed(A,!0)}else e=EF(e).createTextNode(i),e[pr]=A,A.stateNode=e}return zg(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(at(318));if(e=A.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(at(557));e[pr]=A}else Wp(),!(A.flags&128)&&(A.memoizedState=null),A.flags|=4;zg(A),e=!1}else t=kq(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=t),e=!0;if(!e)return A.flags&256?(LI(A),A):(LI(A),null);if(A.flags&128)throw Error(at(558))}return zg(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(at(318));if(n=A.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(at(317));n[pr]=A}else Wp(),!(A.flags&128)&&(A.memoizedState=null),A.flags|=4;zg(A),n=!1}else n=kq(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),n=!0;if(!n)return A.flags&256?(LI(A),A):(LI(A),null)}return LI(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),sb(A,A.updateQueue),zg(A),null);case 4:return sS(),e===null&&Hj(A.stateNode.containerInfo),zg(A),null;case 10:return GE(A.type),zg(A),null;case 19:if(tr(Zo),i=A.memoizedState,i===null)return zg(A),null;if(n=(A.flags&128)!==0,g=i.rendering,g===null)if(n)u0(i,!1);else{if(_o!==0||e!==null&&e.flags&128)for(e=A.child;e!==null;){if(g=iF(e),g!==null){for(A.flags|=128,u0(i,!1),e=g.updateQueue,A.updateQueue=e,sb(A,e),A.subtreeFlags=0,e=t,t=A.child;t!==null;)UaA(t,e),t=t.sibling;return Yg(Zo,Zo.current&1|2),jn&&IE(A,i.treeForkCount),A.child}e=e.sibling}i.tail!==null&&PI()>aF&&(A.flags|=128,n=!0,u0(i,!1),A.lanes=4194304)}else{if(!n)if(e=iF(g),e!==null){if(A.flags|=128,n=!0,e=e.updateQueue,A.updateQueue=e,sb(A,e),u0(i,!0),i.tail===null&&i.tailMode==="hidden"&&!g.alternate&&!jn)return zg(A),null}else 2*PI()-i.renderingStartTime>aF&&t!==536870912&&(A.flags|=128,n=!0,u0(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=PI(),e.sibling=null,t=Zo.current,Yg(Zo,n?t&1|2:t&1),jn&&IE(A,i.treeForkCount),e):(zg(A),null);case 22:case 23:return LI(A),yj(),i=A.memoizedState!==null,e!==null?e.memoizedState!==null!==i&&(A.flags|=8192):i&&(A.flags|=8192),i?t&536870912&&!(A.flags&128)&&(zg(A),A.subtreeFlags&6&&(A.flags|=8192)):zg(A),t=A.updateQueue,t!==null&&sb(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&&tr(Gp),null;case 24:return t=null,e!==null&&(t=e.memoizedState.cache),A.memoizedState.cache!==t&&(A.flags|=2048),GE(us),zg(A),null;case 25:return null;case 30:return null}throw Error(at(156,A.tag))}function LMA(e,A){switch(uj(A),A.tag){case 1:return e=A.flags,e&65536?(A.flags=e&-65537|128,A):null;case 3:return GE(us),sS(),e=A.flags,e&65536&&!(e&128)?(A.flags=e&-65537|128,A):null;case 26:case 27:case 5:return zK(A),null;case 31:if(A.memoizedState!==null){if(LI(A),A.alternate===null)throw Error(at(340));Wp()}return e=A.flags,e&65536?(A.flags=e&-65537|128,A):null;case 13:if(LI(A),e=A.memoizedState,e!==null&&e.dehydrated!==null){if(A.alternate===null)throw Error(at(340));Wp()}return e=A.flags,e&65536?(A.flags=e&-65537|128,A):null;case 19:return tr(Zo),null;case 4:return sS(),null;case 10:return GE(A.type),null;case 22:case 23:return LI(A),yj(),e!==null&&tr(Gp),e=A.flags,e&65536?(A.flags=e&-65537|128,A):null;case 24:return GE(us),null;case 25:return null;default:return null}}function UIA(e,A){switch(uj(A),A.tag){case 3:GE(us),sS();break;case 26:case 27:case 5:zK(A);break;case 4:sS();break;case 31:A.memoizedState!==null&&LI(A);break;case 13:LI(A);break;case 19:tr(Zo);break;case 10:GE(A.type);break;case 22:case 23:LI(A),yj(),e!==null&&tr(Gp);break;case 24:GE(us)}}function mR(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){fg(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 r=t,a=s;try{a()}catch(I){fg(n,r,I)}}}i=i.next}while(i!==g)}}catch(I){fg(A,A.return,I)}}function vIA(e){var A=e.updateQueue;if(A!==null){var t=e.stateNode;try{YaA(A,t)}catch(i){fg(e,e.return,i)}}}function KIA(e,A,t){t.props=Af(e.type,e.memoizedProps),t.state=e.memoizedState;try{t.componentWillUnmount()}catch(i){fg(e,A,i)}}function Pk(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){fg(e,A,n)}}function tB(e,A){var t=e.ref,i=e.refCleanup;if(t!==null)if(typeof i=="function")try{i()}catch(n){fg(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){fg(e,A,n)}else t.current=null}function FIA(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){fg(e,e.return,n)}}function _q(e,A,t){try{var i=e.stateNode;sNA(i,e.type,t,A),i[rI]=A}catch(n){fg(e,e.return,n)}}function _IA(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Sd(e.type)||e.tag===4}function Jq(e){A:for(;;){for(;e.sibling===null;){if(e.return===null||_IA(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&&Sd(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 w1(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=SE));else if(i!==4&&(i===27&&Sd(e.type)&&(t=e.stateNode,A=null),e=e.child,e!==null))for(w1(e,A,t),e=e.sibling;e!==null;)w1(e,A,t),e=e.sibling}function rF(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&&Sd(e.type)&&(t=e.stateNode),e=e.child,e!==null))for(rF(e,A,t),e=e.sibling;e!==null;)rF(e,A,t),e=e.sibling}function JIA(e){var A=e.stateNode,t=e.memoizedProps;try{for(var i=e.type,n=A.attributes;n.length;)A.removeAttributeNode(n[0]);wr(A,i,t),A[pr]=e,A[rI]=t}catch(g){fg(e,e.return,g)}}var QE=!1,Es=!1,Lq=!1,TX=typeof WeakSet=="function"?WeakSet:Set,Zs=null;function xMA(e,A){if(e=e.containerInfo,U1=hF,e=SaA(e),cj(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,r=-1,a=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||(r=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&&++a===n&&(s=o),l===g&&++I===i&&(r=o),(B=c.nextSibling)!==null)break;c=l,l=c.parentNode}c=B}t=s===-1||r===-1?null:{start:s,end:r}}else t=null}t=t||{start:0,end:0}}else t=null;for(v1={focusedElem:e,selectionRange:t},hF=!1,Zs=A;Zs!==null;)if(A=Zs,e=A.child,(A.subtreeFlags&1028)!==0&&e!==null)e.return=A,Zs=e;else for(;Zs!==null;){switch(A=Zs,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){fg(t,t.return,h)}}break;case 3:if(e&1024){if(e=A.stateNode.containerInfo,t=e.nodeType,t===9)F1(e);else if(t===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":F1(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(at(163))}if(e=A.sibling,e!==null){e.return=A.return,Zs=e;break}Zs=A.return}}function LIA(e,A,t){var i=t.flags;switch(t.tag){case 0:case 11:case 15:zB(e,t),i&4&&mR(5,t);break;case 1:if(zB(e,t),i&4)if(e=t.stateNode,A===null)try{e.componentDidMount()}catch(o){fg(t,t.return,o)}else{var n=Af(t.type,A.memoizedProps);A=A.memoizedState;try{e.componentDidUpdate(n,A,e.__reactInternalSnapshotBeforeUpdate)}catch(o){fg(t,t.return,o)}}i&64&&vIA(t),i&512&&Pk(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{YaA(e,A)}catch(o){fg(t,t.return,o)}}break;case 27:A===null&&i&4&&JIA(t);case 26:case 5:zB(e,t),A===null&&i&4&&FIA(t),i&512&&Pk(t,t.return);break;case 12:zB(e,t);break;case 31:zB(e,t),i&4&&qIA(e,t);break;case 13:zB(e,t),i&4&&YIA(e,t),i&64&&(e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(t=ZMA.bind(null,t),ENA(e,t))));break;case 22:if(i=t.memoizedState!==null||QE,!i){A=A!==null&&A.memoizedState!==null||Es,n=QE;var g=Es;QE=i,(Es=A)&&!g?oE(e,t,(t.subtreeFlags&8772)!==0):zB(e,t),QE=n,Es=g}break;case 30:break;default:zB(e,t)}}function xIA(e){var A=e.alternate;A!==null&&(e.alternate=null,xIA(A)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(A=e.stateNode,A!==null&&oj(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 go=null,ja=!1;function jB(e,A,t){for(t=t.child;t!==null;)TIA(e,A,t),t=t.sibling}function TIA(e,A,t){if(jI&&typeof jI.onCommitFiberUnmount=="function")try{jI.onCommitFiberUnmount(uR,t)}catch{}switch(t.tag){case 26:Es||tB(t,A),jB(e,A,t),t.memoizedState?t.memoizedState.count--:t.stateNode&&(t=t.stateNode,t.parentNode.removeChild(t));break;case 27:Es||tB(t,A);var i=go,n=ja;Sd(t.type)&&(go=t.stateNode,ja=!1),jB(e,A,t),Wk(t.stateNode),go=i,ja=n;break;case 5:Es||tB(t,A);case 6:if(i=go,n=ja,go=null,jB(e,A,t),go=i,ja=n,go!==null)if(ja)try{(go.nodeType===9?go.body:go.nodeName==="HTML"?go.ownerDocument.body:go).removeChild(t.stateNode)}catch(g){fg(t,A,g)}else try{go.removeChild(t.stateNode)}catch(g){fg(t,A,g)}break;case 18:go!==null&&(ja?(e=go,A6(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,t.stateNode),uS(e)):A6(go,t.stateNode));break;case 4:i=go,n=ja,go=t.stateNode.containerInfo,ja=!0,jB(e,A,t),go=i,ja=n;break;case 0:case 11:case 14:case 15:td(2,t,A),Es||td(4,t,A),jB(e,A,t);break;case 1:Es||(tB(t,A),i=t.stateNode,typeof i.componentWillUnmount=="function"&&KIA(t,A,i)),jB(e,A,t);break;case 21:jB(e,A,t);break;case 22:Es=(i=Es)||t.memoizedState!==null,jB(e,A,t),Es=i;break;default:jB(e,A,t)}}function qIA(e,A){if(A.memoizedState===null&&(e=A.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{uS(e)}catch(t){fg(A,A.return,t)}}}function YIA(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){fg(A,A.return,t)}}function TMA(e){switch(e.tag){case 31:case 13:case 19:var A=e.stateNode;return A===null&&(A=e.stateNode=new TX),A;case 22:return e=e.stateNode,A=e._retryCache,A===null&&(A=e._retryCache=new TX),A;default:throw Error(at(435,e.tag))}}function rb(e,A){var t=TMA(e);A.forEach(function(i){if(!t.has(i)){t.add(i);var n=WMA.bind(null,e,i);i.then(n,n)}})}function Ta(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(Sd(s.type)){go=s.stateNode,ja=!1;break A}break;case 5:go=s.stateNode,ja=!1;break A;case 3:case 4:go=s.stateNode.containerInfo,ja=!0;break A}s=s.return}if(go===null)throw Error(at(160));TIA(g,o,n),go=null,ja=!1,g=n.alternate,g!==null&&(g.return=null),n.return=null}if(A.subtreeFlags&13886)for(A=A.child;A!==null;)HIA(A,e),A=A.sibling}var Uc=null;function HIA(e,A){var t=e.alternate,i=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Ta(A,e),qa(e),i&4&&(td(3,e,e.return),mR(3,e),td(5,e,e.return));break;case 1:Ta(A,e),qa(e),i&512&&(Es||t===null||tB(t,t.return)),i&64&&QE&&(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=Uc;if(Ta(A,e),qa(e),i&512&&(Es||t===null||tB(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[pR]||g[pr]||g.namespaceURI==="http://www.w3.org/2000/svg"||g.hasAttribute("itemprop"))&&(g=n.createElement(i),n.head.insertBefore(g,n.querySelector("head > title"))),wr(g,i,t),g[pr]=e,$s(g),i=g;break A;case"link":var o=s6("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),wr(g,i,t),n.head.appendChild(g);break;case"meta":if(o=s6("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),wr(g,i,t),n.head.appendChild(g);break;default:throw Error(at(468,i))}g[pr]=e,$s(g),i=g}e.stateNode=i}else r6(n,e.type,e.stateNode);else e.stateNode=o6(n,i,e.memoizedProps);else g!==i?(g===null?t.stateNode!==null&&(t=t.stateNode,t.parentNode.removeChild(t)):g.count--,i===null?r6(n,e.type,e.stateNode):o6(n,i,e.memoizedProps)):i===null&&e.stateNode!==null&&_q(e,e.memoizedProps,t.memoizedProps)}break;case 27:Ta(A,e),qa(e),i&512&&(Es||t===null||tB(t,t.return)),t!==null&&i&4&&_q(e,e.memoizedProps,t.memoizedProps);break;case 5:if(Ta(A,e),qa(e),i&512&&(Es||t===null||tB(t,t.return)),e.flags&32){n=e.stateNode;try{aS(n,"")}catch(Q){fg(e,e.return,Q)}}i&4&&e.stateNode!=null&&(n=e.memoizedProps,_q(e,n,t!==null?t.memoizedProps:n)),i&1024&&(Lq=!0);break;case 6:if(Ta(A,e),qa(e),i&4){if(e.stateNode===null)throw Error(at(162));i=e.memoizedProps,t=e.stateNode;try{t.nodeValue=i}catch(Q){fg(e,e.return,Q)}}break;case 3:if(Wv=null,n=Uc,Uc=QF(A.containerInfo),Ta(A,e),Uc=n,qa(e),i&4&&t!==null&&t.memoizedState.isDehydrated)try{uS(A.containerInfo)}catch(Q){fg(e,e.return,Q)}Lq&&(Lq=!1,OIA(e));break;case 4:i=Uc,Uc=QF(e.stateNode.containerInfo),Ta(A,e),qa(e),Uc=i;break;case 12:Ta(A,e),qa(e);break;case 31:Ta(A,e),qa(e),i&4&&(i=e.updateQueue,i!==null&&(e.updateQueue=null,rb(e,i)));break;case 13:Ta(A,e),qa(e),e.child.flags&8192&&e.memoizedState!==null!=(t!==null&&t.memoizedState!==null)&&(sL=PI()),i&4&&(i=e.updateQueue,i!==null&&(e.updateQueue=null,rb(e,i)));break;case 22:n=e.memoizedState!==null;var r=t!==null&&t.memoizedState!==null,a=QE,I=Es;if(QE=a||n,Es=I||r,Ta(A,e),Es=I,QE=a,qa(e),i&8192)A:for(A=e.stateNode,A._visibility=n?A._visibility&-2:A._visibility|1,n&&(t===null||r||QE||Es||xh(e)),t=null,A=e;;){if(A.tag===5||A.tag===26){if(t===null){r=t=A;try{if(g=r.stateNode,n)o=g.style,typeof o.setProperty=="function"?o.setProperty("display","none","important"):o.display="none";else{s=r.stateNode;var c=r.memoizedProps.style,l=c!=null&&c.hasOwnProperty("display")?c.display:null;s.style.display=l==null||typeof l=="boolean"?"":(""+l).trim()}}catch(Q){fg(r,r.return,Q)}}}else if(A.tag===6){if(t===null){r=A;try{r.stateNode.nodeValue=n?"":r.memoizedProps}catch(Q){fg(r,r.return,Q)}}}else if(A.tag===18){if(t===null){r=A;try{var B=r.stateNode;n?e6(B,!0):e6(r.stateNode,!1)}catch(Q){fg(r,r.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,rb(e,t))));break;case 19:Ta(A,e),qa(e),i&4&&(i=e.updateQueue,i!==null&&(e.updateQueue=null,rb(e,i)));break;case 30:break;case 21:break;default:Ta(A,e),qa(e)}}function qa(e){var A=e.flags;if(A&2){try{for(var t,i=e.return;i!==null;){if(_IA(i)){t=i;break}i=i.return}if(t==null)throw Error(at(160));switch(t.tag){case 27:var n=t.stateNode,g=Jq(e);rF(e,g,n);break;case 5:var o=t.stateNode;t.flags&32&&(aS(o,""),t.flags&=-33);var s=Jq(e);rF(e,s,o);break;case 3:case 4:var r=t.stateNode.containerInfo,a=Jq(e);w1(e,a,r);break;default:throw Error(at(161))}}catch(I){fg(e,e.return,I)}e.flags&=-3}A&4096&&(e.flags&=-4097)}function OIA(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var A=e;OIA(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;)LIA(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:tB(A,A.return);var t=A.stateNode;typeof t.componentWillUnmount=="function"&&KIA(A,A.return,t),xh(A);break;case 27:Wk(A.stateNode);case 26:case 5:tB(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 oE(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:oE(n,g,t),mR(4,g);break;case 1:if(oE(n,g,t),i=g,n=i.stateNode,typeof n.componentDidMount=="function")try{n.componentDidMount()}catch(a){fg(i,i.return,a)}if(i=g,n=i.updateQueue,n!==null){var s=i.stateNode;try{var r=n.shared.hiddenCallbacks;if(r!==null)for(n.shared.hiddenCallbacks=null,n=0;n<r.length;n++)qaA(r[n],s)}catch(a){fg(i,i.return,a)}}t&&o&64&&vIA(g),Pk(g,g.return);break;case 27:JIA(g);case 26:case 5:oE(n,g,t),t&&i===null&&o&4&&FIA(g),Pk(g,g.return);break;case 12:oE(n,g,t);break;case 31:oE(n,g,t),t&&o&4&&qIA(n,g);break;case 13:oE(n,g,t),t&&o&4&&YIA(n,g);break;case 22:g.memoizedState===null&&oE(n,g,t),Pk(g,g.return);break;case 30:break;default:oE(n,g,t)}A=A.sibling}}function Jj(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&&yR(t))}function Lj(e,A){e=null,A.alternate!==null&&(e=A.alternate.memoizedState.cache),A=A.memoizedState.cache,A!==e&&(A.refCount++,e!=null&&yR(e))}function fc(e,A,t,i){if(A.subtreeFlags&10256)for(A=A.child;A!==null;)PIA(e,A,t,i),A=A.sibling}function PIA(e,A,t,i){var n=A.flags;switch(A.tag){case 0:case 11:case 15:fc(e,A,t,i),n&2048&&mR(9,A);break;case 1:fc(e,A,t,i);break;case 3:fc(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&&yR(e)));break;case 12:if(n&2048){fc(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(r){fg(A,A.return,r)}}else fc(e,A,t,i);break;case 31:fc(e,A,t,i);break;case 13:fc(e,A,t,i);break;case 23:break;case 22:g=A.stateNode,o=A.alternate,A.memoizedState!==null?g._visibility&2?fc(e,A,t,i):jk(e,A):g._visibility&2?fc(e,A,t,i):(g._visibility|=2,ND(e,A,t,i,(A.subtreeFlags&10256)!==0||!1)),n&2048&&Jj(o,A);break;case 24:fc(e,A,t,i),n&2048&&Lj(A.alternate,A);break;default:fc(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,r=i,a=o.flags;switch(o.tag){case 0:case 11:case 15:ND(g,o,s,r,n),mR(8,o);break;case 23:break;case 22:var I=o.stateNode;o.memoizedState!==null?I._visibility&2?ND(g,o,s,r,n):jk(g,o):(I._visibility|=2,ND(g,o,s,r,n)),n&&a&2048&&Jj(o.alternate,o);break;case 24:ND(g,o,s,r,n),n&&a&2048&&Lj(o.alternate,o);break;default:ND(g,o,s,r,n)}A=A.sibling}}function jk(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:jk(t,i),n&2048&&Jj(i.alternate,i);break;case 24:jk(t,i),n&2048&&Lj(i.alternate,i);break;default:jk(t,i)}A=A.sibling}}var Ck=8192;function vy(e,A,t){if(e.subtreeFlags&Ck)for(e=e.child;e!==null;)jIA(e,A,t),e=e.sibling}function jIA(e,A,t){switch(e.tag){case 26:vy(e,A,t),e.flags&Ck&&e.memoizedState!==null&&kNA(t,Uc,e.memoizedState,e.memoizedProps);break;case 5:vy(e,A,t);break;case 3:case 4:var i=Uc;Uc=QF(e.stateNode.containerInfo),vy(e,A,t),Uc=i;break;case 22:e.memoizedState===null&&(i=e.alternate,i!==null&&i.memoizedState!==null?(i=Ck,Ck=16777216,vy(e,A,t),Ck=i):vy(e,A,t));break;default:vy(e,A,t)}}function zIA(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 d0(e){var A=e.deletions;if(e.flags&16){if(A!==null)for(var t=0;t<A.length;t++){var i=A[t];Zs=i,WIA(i,e)}zIA(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)ZIA(e),e=e.sibling}function ZIA(e){switch(e.tag){case 0:case 11:case 15:d0(e),e.flags&2048&&td(9,e,e.return);break;case 3:d0(e);break;case 12:d0(e);break;case 22:var A=e.stateNode;e.memoizedState!==null&&A._visibility&2&&(e.return===null||e.return.tag!==13)?(A._visibility&=-3,zv(e)):d0(e);break;default:d0(e)}}function zv(e){var A=e.deletions;if(e.flags&16){if(A!==null)for(var t=0;t<A.length;t++){var i=A[t];Zs=i,WIA(i,e)}zIA(e)}for(e=e.child;e!==null;){switch(A=e,A.tag){case 0:case 11:case 15:td(8,A,A.return),zv(A);break;case 22:t=A.stateNode,t._visibility&2&&(t._visibility&=-3,zv(A));break;default:zv(A)}e=e.sibling}}function WIA(e,A){for(;Zs!==null;){var t=Zs;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:yR(t.memoizedState.cache)}if(i=t.child,i!==null)i.return=t,Zs=i;else A:for(t=e;Zs!==null;){i=Zs;var n=i.sibling,g=i.return;if(xIA(i),i===t){Zs=null;break A}if(n!==null){n.return=g,Zs=n;break A}Zs=g}}}var qMA={getCacheForType:function(e){var A=Dr(us),t=A.data.get(e);return t===void 0&&(t=e(),A.data.set(e,t)),t},cacheSignal:function(){return Dr(us).controller.signal}},YMA=typeof WeakMap=="function"?WeakMap:Map,ag=0,Jg=null,Gn=null,_n=0,pg=0,_I=null,hu=!1,Cw=!1,xj=!1,jE=0,_o=0,id=0,Up=0,Tj=0,TI=0,lS=0,zk=null,Za=null,k1=!1,sL=0,VIA=0,aF=1/0,IF=null,Fu=null,Us=0,_u=null,BS=null,bE=0,M1=0,N1=null,XIA=null,Zk=0,R1=null;function ZI(){return ag&2&&_n!==0?_n&-_n:Ki.T!==null?Yj():saA()}function $IA(){if(TI===0)if(!(_n&536870912)||jn){var e=Ab;Ab<<=1,!(Ab&3932160)&&(Ab=262144),TI=e}else TI=536870912;return e=AC.current,e!==null&&(e.flags|=32),TI}function oI(e,A,t){(e===Jg&&(pg===2||pg===9)||e.cancelPendingCommit!==null)&&(ES(e,0),pu(e,_n,TI,!1)),hR(e,t),(!(ag&2)||e!==Jg)&&(e===Jg&&(!(ag&2)&&(Up|=t),_o===4&&pu(e,_n,TI,!1)),kB(e))}function ACA(e,A,t){if(ag&6)throw Error(at(327));var i=!t&&(A&127)===0&&(A&e.expiredLanes)===0||dR(e,A),n=i?PMA(e,A):xq(e,A,!0),g=i;do{if(n===0){Cw&&!i&&pu(e,A,0,!1);break}else{if(t=e.current.alternate,g&&!HMA(t)){n=xq(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=zk;var r=s.current.memoizedState.isDehydrated;if(r&&(ES(s,o).flags|=256),o=xq(s,o,!1),o!==2){if(xj&&!r){s.errorRecoveryDisabledLanes|=g,Up|=g,n=4;break A}g=Za,Za=n,g!==null&&(Za===null?Za=g:Za.push.apply(Za,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(at(345));case 4:if((A&4194048)!==A)break;case 6:pu(i,A,TI,!hu);break A;case 2:Za=null;break;case 3:case 5:break;default:throw Error(at(329))}if((A&62914560)===A&&(n=sL+300-PI(),10<n)){if(pu(i,A,TI,!hu),WJ(i,0,!0)!==0)break A;bE=A,i.timeoutHandle=pCA(qX.bind(null,i,t,Za,IF,k1,A,TI,Up,lS,hu,g,"Throttled",-0,0),n);break A}qX(i,t,Za,IF,k1,A,TI,Up,lS,hu,g,null,-0,0)}}break}while(!0);kB(e)}function qX(e,A,t,i,n,g,o,s,r,a,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:SE},jIA(A,g,c);var Q=(g&62914560)===g?sL-PI():(g&4194048)===g?VIA-PI():0;if(Q=MNA(c,Q),Q!==null){bE=g,e.cancelPendingCommit=Q(HX.bind(null,e,A,g,t,i,n,o,s,r,I,c,null,l,B)),pu(e,g,o,!a);return}}HX(e,A,g,t,i,n,o,s,r)}function HMA(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(!$I(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&=~Tj,A&=~Up,e.suspendedLanes|=A,e.pingedLanes&=~A,i&&(e.warmLanes|=A),i=e.expirationTimes;for(var n=A;0<n;){var g=31-zI(n),o=1<<g;i[g]=-1,n&=~o}t!==0&&naA(e,t,A)}function rL(){return ag&6?!0:(SR(0),!1)}function qj(){if(Gn!==null){if(pg===0)var e=Gn.return;else e=Gn,wE=bf=null,kj(e),dm=null,TM=0,e=Gn;for(;e!==null;)UIA(e.alternate,e),e=e.return;Gn=null}}function ES(e,A){var t=e.timeoutHandle;t!==-1&&(e.timeoutHandle=-1,INA(t)),t=e.cancelPendingCommit,t!==null&&(e.cancelPendingCommit=null,t()),bE=0,qj(),Jg=e,Gn=t=RE(e.current,null),_n=A,pg=0,_I=null,hu=!1,Cw=dR(e,A),xj=!1,lS=TI=Tj=Up=id=_o=0,Za=zk=null,k1=!1,A&8&&(A|=A&32);var i=e.entangledLanes;if(i!==0)for(e=e.entanglements,i&=A;0<i;){var n=31-zI(i),g=1<<n;A|=e[n],i&=~g}return jE=A,AL(),t}function eCA(e,A){rn=null,Ki.H=YM,A===Iw||A===tL?(A=pX(),pg=3):A===pj?(A=pX(),pg=4):pg=A===Fj?8:A!==null&&typeof A=="object"&&typeof A.then=="function"?6:1,_I=A,Gn===null&&(_o=1,oF(e,HC(A,e.current)))}function tCA(){var e=AC.current;return e===null?!0:(_n&4194048)===_n?ZC===null:(_n&62914560)===_n||_n&536870912?e===ZC:!1}function iCA(){var e=Ki.H;return Ki.H=YM,e===null?YM:e}function nCA(){var e=Ki.A;return Ki.A=qMA,e}function CF(){_o=4,hu||(_n&4194048)!==_n&&AC.current!==null||(Cw=!0),!(id&134217727)&&!(Up&134217727)||Jg===null||pu(Jg,_n,TI,!1)}function xq(e,A,t){var i=ag;ag|=2;var n=iCA(),g=nCA();(Jg!==e||_n!==A)&&(IF=null,ES(e,A)),A=!1;var o=_o;A:do try{if(pg!==0&&Gn!==null){var s=Gn,r=_I;switch(pg){case 8:qj(),o=6;break A;case 3:case 2:case 9:case 6:AC.current===null&&(A=!0);var a=pg;if(pg=0,_I=null,zD(e,s,r,a),t&&Cw){o=0;break A}break;default:a=pg,pg=0,_I=null,zD(e,s,r,a)}}OMA(),o=_o;break}catch(I){eCA(e,I)}while(!0);return A&&e.shellSuspendCounter++,wE=bf=null,ag=i,Ki.H=n,Ki.A=g,Gn===null&&(Jg=null,_n=0,AL()),o}function OMA(){for(;Gn!==null;)gCA(Gn)}function PMA(e,A){var t=ag;ag|=2;var i=iCA(),n=nCA();Jg!==e||_n!==A?(IF=null,aF=PI()+500,ES(e,A)):Cw=dR(e,A);A:do try{if(pg!==0&&Gn!==null){A=Gn;var g=_I;e:switch(pg){case 1:pg=0,_I=null,zD(e,A,g,1);break;case 2:case 9:if(hX(g)){pg=0,_I=null,YX(A);break}A=function(){pg!==2&&pg!==9||Jg!==e||(pg=7),kB(e)},g.then(A,A);break A;case 3:pg=7;break A;case 4:pg=5;break A;case 7:hX(g)?(pg=0,_I=null,YX(A)):(pg=0,_I=null,zD(e,A,g,7));break;case 5:var o=null;switch(Gn.tag){case 26:o=Gn.memoizedState;case 5:case 27:var s=Gn;if(o?SCA(o):s.stateNode.complete){pg=0,_I=null;var r=s.sibling;if(r!==null)Gn=r;else{var a=s.return;a!==null?(Gn=a,aL(a)):Gn=null}break e}}pg=0,_I=null,zD(e,A,g,5);break;case 6:pg=0,_I=null,zD(e,A,g,6);break;case 8:qj(),_o=6;break A;default:throw Error(at(462))}}jMA();break}catch(I){eCA(e,I)}while(!0);return wE=bf=null,Ki.H=i,Ki.A=n,ag=t,Gn!==null?0:(Jg=null,_n=0,AL(),_o)}function jMA(){for(;Gn!==null&&!QkA();)gCA(Gn)}function gCA(e){var A=bIA(e.alternate,e,jE);e.memoizedProps=e.pendingProps,A===null?aL(e):Gn=A}function YX(e){var A=e,t=A.alternate;switch(A.tag){case 15:case 0:A=FX(t,A,A.pendingProps,A.type,void 0,_n);break;case 11:A=FX(t,A,A.pendingProps,A.type.render,A.ref,_n);break;case 5:kj(A);default:UIA(t,A),A=Gn=UaA(A,jE),A=bIA(t,A,jE)}e.memoizedProps=e.pendingProps,A===null?aL(e):Gn=A}function zD(e,A,t,i){wE=bf=null,kj(A),dm=null,TM=0;var n=A.return;try{if(KMA(e,n,A,t,_n)){_o=1,oF(e,HC(t,e.current)),Gn=null;return}}catch(g){if(n!==null)throw Gn=n,g;_o=1,oF(e,HC(t,e.current)),Gn=null;return}A.flags&32768?(jn||i===1?e=!0:Cw||_n&536870912?e=!1:(hu=e=!0,(i===2||i===9||i===3||i===6)&&(i=AC.current,i!==null&&i.tag===13&&(i.flags|=16384))),oCA(A,e)):aL(A)}function aL(e){var A=e;do{if(A.flags&32768){oCA(A,hu);return}e=A.return;var t=JMA(A.alternate,A,jE);if(t!==null){Gn=t;return}if(A=A.sibling,A!==null){Gn=A;return}Gn=A=e}while(A!==null);_o===0&&(_o=5)}function oCA(e,A){do{var t=LMA(e.alternate,e);if(t!==null){t.flags&=32767,Gn=t;return}if(t=e.return,t!==null&&(t.flags|=32768,t.subtreeFlags=0,t.deletions=null),!A&&(e=e.sibling,e!==null)){Gn=e;return}Gn=e=t}while(e!==null);_o=6,Gn=null}function HX(e,A,t,i,n,g,o,s,r){e.cancelPendingCommit=null;do IL();while(Us!==0);if(ag&6)throw Error(at(327));if(A!==null){if(A===e.current)throw Error(at(177));if(g=A.lanes|A.childLanes,g|=lj,wkA(e,t,g,o,s,r),e===Jg&&(Gn=Jg=null,_n=0),BS=A,_u=e,bE=t,M1=g,N1=n,XIA=i,A.subtreeFlags&10256||A.flags&10256?(e.callbackNode=null,e.callbackPriority=0,VMA(ZK,function(){return CCA(),null})):(e.callbackNode=null,e.callbackPriority=0),i=(A.flags&13878)!==0,A.subtreeFlags&13878||i){i=Ki.T,Ki.T=null,n=Ig.p,Ig.p=2,o=ag,ag|=4;try{xMA(e,A,t)}finally{ag=o,Ig.p=n,Ki.T=i}}Us=1,sCA(),rCA(),aCA()}}function sCA(){if(Us===1){Us=0;var e=_u,A=BS,t=(A.flags&13878)!==0;if(A.subtreeFlags&13878||t){t=Ki.T,Ki.T=null;var i=Ig.p;Ig.p=2;var n=ag;ag|=4;try{HIA(A,e);var g=v1,o=SaA(e.containerInfo),s=g.focusedElem,r=g.selectionRange;if(o!==s&&s&&s.ownerDocument&&maA(s.ownerDocument.documentElement,s)){if(r!==null&&cj(s)){var a=r.start,I=r.end;if(I===void 0&&(I=a),"selectionStart"in s)s.selectionStart=a,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(r.start,Q),d=r.end===void 0?h:Math.min(r.end,Q);!B.extend&&h>d&&(o=d,d=h,h=o);var p=cX(s,h),y=cX(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}}hF=!!U1,v1=U1=null}finally{ag=n,Ig.p=i,Ki.T=t}}e.current=A,Us=2}}function rCA(){if(Us===2){Us=0;var e=_u,A=BS,t=(A.flags&8772)!==0;if(A.subtreeFlags&8772||t){t=Ki.T,Ki.T=null;var i=Ig.p;Ig.p=2;var n=ag;ag|=4;try{LIA(e,A.alternate,A)}finally{ag=n,Ig.p=i,Ki.T=t}}Us=3}}function aCA(){if(Us===4||Us===3){Us=0,ukA();var e=_u,A=BS,t=bE,i=XIA;A.subtreeFlags&10256||A.flags&10256?Us=5:(Us=0,BS=_u=null,ICA(e,e.pendingLanes));var n=e.pendingLanes;if(n===0&&(Fu=null),gj(t),A=A.stateNode,jI&&typeof jI.onCommitFiberRoot=="function")try{jI.onCommitFiberRoot(uR,A,void 0,(A.current.flags&128)===128)}catch{}if(i!==null){A=Ki.T,n=Ig.p,Ig.p=2,Ki.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{Ki.T=A,Ig.p=n}}bE&3&&IL(),kB(e),n=e.pendingLanes,t&261930&&n&42?e===R1?Zk++:(Zk=0,R1=e):Zk=0,SR(0)}}function ICA(e,A){(e.pooledCacheLanes&=A)===0&&(A=e.pooledCache,A!=null&&(e.pooledCache=null,yR(A)))}function IL(){return sCA(),rCA(),aCA(),CCA()}function CCA(){if(Us!==5)return!1;var e=_u,A=M1;M1=0;var t=gj(bE),i=Ki.T,n=Ig.p;try{Ig.p=32>t?32:t,Ki.T=null,t=N1,N1=null;var g=_u,o=bE;if(Us=0,BS=_u=null,bE=0,ag&6)throw Error(at(331));var s=ag;if(ag|=4,ZIA(g.current),PIA(g,g.current,o,t),ag=s,SR(0,!1),jI&&typeof jI.onPostCommitFiberRoot=="function")try{jI.onPostCommitFiberRoot(uR,g)}catch{}return!0}finally{Ig.p=n,Ki.T=i,ICA(e,A)}}function OX(e,A,t){A=HC(t,A),A=D1(e.stateNode,A,2),e=Ku(e,A,2),e!==null&&(hR(e,2),kB(e))}function fg(e,A,t){if(e.tag===3)OX(e,e,t);else for(;A!==null;){if(A.tag===3){OX(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=HC(t,e),t=wIA(2),i=Ku(A,t,2),i!==null&&(kIA(t,i,A,e),hR(i,2),kB(i));break}}A=A.return}}function Tq(e,A,t){var i=e.pingCache;if(i===null){i=e.pingCache=new YMA;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)||(xj=!0,n.add(t),e=zMA.bind(null,e,A,t),A.then(e,e))}function zMA(e,A,t){var i=e.pingCache;i!==null&&i.delete(A),e.pingedLanes|=e.suspendedLanes&t,e.warmLanes&=~t,Jg===e&&(_n&t)===t&&(_o===4||_o===3&&(_n&62914560)===_n&&300>PI()-sL?!(ag&2)&&ES(e,0):Tj|=t,lS===_n&&(lS=0)),kB(e)}function cCA(e,A){A===0&&(A=iaA()),e=Gf(e,A),e!==null&&(hR(e,A),kB(e))}function ZMA(e){var A=e.memoizedState,t=0;A!==null&&(t=A.retryLane),cCA(e,t)}function WMA(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(at(314))}i!==null&&i.delete(A),cCA(e,t)}function VMA(e,A){return ij(e,A)}var cF=null,RD=null,G1=!1,lF=!1,qq=!1,fu=0;function kB(e){e!==RD&&e.next===null&&(RD===null?cF=RD=e:RD=RD.next=e),lF=!0,G1||(G1=!0,$MA())}function SR(e,A){if(!qq&&lF){qq=!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-zI(42|e)+1)-1,g&=n&~(o&~s),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(t=!0,PX(i,g))}else g=_n,g=WJ(i,i===Jg?g:0,i.cancelPendingCommit!==null||i.timeoutHandle!==-1),!(g&3)||dR(i,g)||(t=!0,PX(i,g));i=i.next}while(t);qq=!1}}function XMA(){lCA()}function lCA(){lF=G1=!1;var e=0;fu!==0&&aNA()&&(e=fu);for(var A=PI(),t=null,i=cF;i!==null;){var n=i.next,g=BCA(i,A);g===0?(i.next=null,t===null?cF=n:t.next=n,n===null&&(RD=t)):(t=i,(e!==0||g&3)&&(lF=!0)),i=n}Us!==0&&Us!==5||SR(e),fu!==0&&(fu=0)}function BCA(e,A){for(var t=e.suspendedLanes,i=e.pingedLanes,n=e.expirationTimes,g=e.pendingLanes&-62914561;0<g;){var o=31-zI(g),s=1<<o,r=n[o];r===-1?(!(s&t)||s&i)&&(n[o]=SkA(s,A)):r<=A&&(e.expiredLanes|=s),g&=~s}if(A=Jg,t=_n,t=WJ(e,e===A?t:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),i=e.callbackNode,t===0||e===A&&(pg===2||pg===9)||e.cancelPendingCommit!==null)return i!==null&&i!==null&&Qq(i),e.callbackNode=null,e.callbackPriority=0;if(!(t&3)||dR(e,t)){if(A=t&-t,A===e.callbackPriority)return A;switch(i!==null&&Qq(i),gj(t)){case 2:case 8:t=eaA;break;case 32:t=ZK;break;case 268435456:t=taA;break;default:t=ZK}return i=ECA.bind(null,e),t=ij(t,i),e.callbackPriority=A,e.callbackNode=t,A}return i!==null&&i!==null&&Qq(i),e.callbackPriority=2,e.callbackNode=null,2}function ECA(e,A){if(Us!==0&&Us!==5)return e.callbackNode=null,e.callbackPriority=0,null;var t=e.callbackNode;if(IL()&&e.callbackNode!==t)return null;var i=_n;return i=WJ(e,e===Jg?i:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),i===0?null:(ACA(e,i,A),BCA(e,PI()),e.callbackNode!=null&&e.callbackNode===t?ECA.bind(null,e):null)}function PX(e,A){if(IL())return null;ACA(e,A,!0)}function $MA(){CNA(function(){ag&6?ij(AaA,XMA):lCA()})}function Yj(){if(fu===0){var e=IS;e===0&&(e=$G,$G<<=1,!($G&261888)&&($G=256)),fu=e}return fu}function jX(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Lv(""+e)}function zX(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 ANA(e,A,t,i,n){if(A==="submit"&&t&&t.stateNode===n){var g=jX((n[rI]||null).action),o=i.submitter;o&&(A=(A=o[rI]||null)?jX(A.formAction):o.getAttribute("formAction"),A!==null&&(g=A,o=null));var s=new VJ("action","action",null,i,n);e.push({event:s,listeners:[{instance:null,listener:function(){if(i.defaultPrevented){if(fu!==0){var r=o?zX(n,o):new FormData(n);f1(t,{pending:!0,data:r,method:n.method,action:g},null,r)}}else typeof g=="function"&&(s.preventDefault(),r=o?zX(n,o):new FormData(n),f1(t,{pending:!0,data:r,method:n.method,action:g},g,r))},currentTarget:n}]})}}for(var Yq=0;Yq<a1.length;Yq++){var Hq=a1[Yq],eNA=Hq.toLowerCase(),tNA=Hq[0].toUpperCase()+Hq.slice(1);tl(eNA,"on"+tNA)}tl(kaA,"onAnimationEnd");tl(MaA,"onAnimationIteration");tl(NaA,"onAnimationStart");tl("dblclick","onDoubleClick");tl("focusin","onFocus");tl("focusout","onBlur");tl(dMA,"onTransitionRun");tl(hMA,"onTransitionStart");tl(pMA,"onTransitionCancel");tl(RaA,"onTransitionEnd");rS("onMouseEnter",["mouseout","mouseover"]);rS("onMouseLeave",["mouseout","mouseover"]);rS("onPointerEnter",["pointerout","pointerover"]);rS("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 HM="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(" "),iNA=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(HM));function QCA(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],r=s.instance,a=s.currentTarget;if(s=s.listener,r!==g&&n.isPropagationStopped())break A;g=s,n.currentTarget=a;try{g(n)}catch(I){VK(I)}n.currentTarget=null,g=r}else for(o=0;o<i.length;o++){if(s=i[o],r=s.instance,a=s.currentTarget,s=s.listener,r!==g&&n.isPropagationStopped())break A;g=s,n.currentTarget=a;try{g(n)}catch(I){VK(I)}n.currentTarget=null,g=r}}}}function Nn(e,A){var t=A[e1];t===void 0&&(t=A[e1]=new Set);var i=e+"__bubble";t.has(i)||(uCA(A,e,2,!1),t.add(i))}function Oq(e,A,t){var i=0;A&&(i|=4),uCA(t,e,i,A)}var ab="_reactListening"+Math.random().toString(36).slice(2);function Hj(e){if(!e[ab]){e[ab]=!0,raA.forEach(function(t){t!=="selectionchange"&&(iNA.has(t)||Oq(t,!1,e),Oq(t,!0,e))});var A=e.nodeType===9?e:e.ownerDocument;A===null||A[ab]||(A[ab]=!0,Oq("selectionchange",!1,A))}}function uCA(e,A,t,i){switch(RCA(A)){case 2:var n=GNA;break;case 8:n=bNA;break;default:n=zj}t=n.bind(null,A,t,e),n=void 0,!o1||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 Pq(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 r=o.tag;if((r===3||r===4)&&o.stateNode.containerInfo===n)return;o=o.return}for(;s!==null;){if(o=LD(s),o===null)return;if(r=o.tag,r===5||r===6||r===26||r===27){i=g=o;continue A}s=s.parentNode}}i=i.return}QaA(function(){var a=g,I=rj(t),c=[];A:{var l=GaA.get(e);if(l!==void 0){var B=VJ,Q=e;switch(e){case"keypress":if(Tv(t)===0)break A;case"keydown":case"keyup":B=WkA;break;case"focusin":Q="focus",B=fq;break;case"focusout":Q="blur",B=fq;break;case"beforeblur":case"afterblur":B=fq;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=tX;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":B=JkA;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":B=$kA;break;case kaA:case MaA:case NaA:B=TkA;break;case RaA:B=eMA;break;case"scroll":case"scrollend":B=FkA;break;case"wheel":B=iMA;break;case"copy":case"cut":case"paste":B=YkA;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":B=nX;break;case"toggle":case"beforetoggle":B=gMA}var h=(A&4)!==0,d=!h&&(e==="scroll"||e==="scrollend"),p=h?l!==null?l+"Capture":null:l;h=[];for(var y=a,m;y!==null;){var D=y;if(m=D.stateNode,D=D.tag,D!==5&&D!==26&&D!==27||m===null||p===null||(D=FM(y,p),D!=null&&h.push(OM(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!==g1&&(Q=t.relatedTarget||t.fromElement)&&(LD(Q)||Q[sw]))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=a,Q=Q?LD(Q):null,Q!==null&&(d=QR(Q),h=Q.tag,Q!==d||h!==5&&h!==27&&h!==6)&&(Q=null)):(B=null,Q=a),B!==Q)){if(h=tX,D="onMouseLeave",p="onMouseEnter",y="mouse",(e==="pointerout"||e==="pointerover")&&(h=nX,D="onPointerLeave",p="onPointerEnter",y="pointer"),d=B==null?l:ak(B),m=Q==null?l:ak(Q),l=new h(D,y+"leave",B,t,I),l.target=d,l.relatedTarget=m,D=null,LD(I)===a&&(h=new h(p,y+"enter",Q,t,I),h.target=m,h.relatedTarget=d,D=h),d=D,B&&Q)e:{for(h=nNA,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&&ZX(c,l,B,h,!1),Q!==null&&d!==null&&ZX(c,d,Q,h,!0)}}A:{if(l=a?ak(a):window,B=l.nodeName&&l.nodeName.toLowerCase(),B==="select"||B==="input"&&l.type==="file")var k=rX;else if(sX(l))if(yaA)k=EMA;else{k=lMA;var N=cMA}else B=l.nodeName,!B||B.toLowerCase()!=="input"||l.type!=="checkbox"&&l.type!=="radio"?a&&sj(a.elementType)&&(k=rX):k=BMA;if(k&&(k=k(e,a))){faA(c,k,t,I);break A}N&&N(e,l,a),e==="focusout"&&a&&l.type==="number"&&a.memoizedProps.value!=null&&n1(l,"number",l.value)}switch(N=a?ak(a):window,e){case"focusin":(sX(N)||N.contentEditable==="true")&&(qD=N,s1=a,xk=null);break;case"focusout":xk=s1=qD=null;break;case"mousedown":r1=!0;break;case"contextmenu":case"mouseup":case"dragend":r1=!1,lX(c,t,I);break;case"selectionchange":if(uMA)break;case"keydown":case"keyup":lX(c,t,I)}var G;if(Cj)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?haA(e,t)&&(M="onCompositionEnd"):e==="keydown"&&t.keyCode===229&&(M="onCompositionStart");M&&(daA&&t.locale!=="ko"&&(TD||M!=="onCompositionStart"?M==="onCompositionEnd"&&TD&&(G=uaA()):(du=I,aj="value"in du?du.value:du.textContent,TD=!0)),N=BF(a,M),0<N.length&&(M=new iX(M,e,null,t,I),c.push({event:M,listeners:N}),G?M.data=G:(G=paA(t),G!==null&&(M.data=G)))),(G=sMA?rMA(e,t):aMA(e,t))&&(M=BF(a,"onBeforeInput"),0<M.length&&(N=new iX("onBeforeInput","beforeinput",null,t,I),c.push({event:N,listeners:M}),N.data=G)),ANA(c,e,a,t,I)}QCA(c,A)})}function OM(e,A,t){return{instance:e,listener:A,currentTarget:t}}function BF(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=FM(e,t),n!=null&&i.unshift(OM(e,n,g)),n=FM(e,A),n!=null&&i.push(OM(e,n,g))),e.tag===3)return i;e=e.return}return[]}function nNA(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function ZX(e,A,t,i,n){for(var g=A._reactName,o=[];t!==null&&t!==i;){var s=t,r=s.alternate,a=s.stateNode;if(s=s.tag,r!==null&&r===i)break;s!==5&&s!==26&&s!==27||a===null||(r=a,n?(a=FM(t,g),a!=null&&o.unshift(OM(t,a,r))):n||(a=FM(t,g),a!=null&&o.push(OM(t,a,r)))),t=t.return}o.length!==0&&e.push({event:A,listeners:o})}var gNA=/\r\n?/g,oNA=/\u0000|\uFFFD/g;function WX(e){return(typeof e=="string"?e:""+e).replace(gNA,`
`).replace(oNA,"")}function dCA(e,A){return A=WX(A),WX(e)===A}function kg(e,A,t,i,n,g){switch(t){case"children":typeof i=="string"?A==="body"||A==="textarea"&&i===""||aS(e,i):(typeof i=="number"||typeof i=="bigint")&&A!=="body"&&aS(e,""+i);break;case"className":tb(e,"class",i);break;case"tabIndex":tb(e,"tabindex",i);break;case"dir":case"role":case"viewBox":case"width":case"height":tb(e,t,i);break;case"style":EaA(e,i,g);break;case"data":if(A!=="object"){tb(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=Lv(""+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"&&kg(e,A,"name",n.name,n,null),kg(e,A,"formEncType",n.formEncType,n,null),kg(e,A,"formMethod",n.formMethod,n,null),kg(e,A,"formTarget",n.formTarget,n,null)):(kg(e,A,"encType",n.encType,n,null),kg(e,A,"method",n.method,n,null),kg(e,A,"target",n.target,n,null)));if(i==null||typeof i=="symbol"||typeof i=="boolean"){e.removeAttribute(t);break}i=Lv(""+i),e.setAttribute(t,i);break;case"onClick":i!=null&&(e.onclick=SE);break;case"onScroll":i!=null&&Nn("scroll",e);break;case"onScrollEnd":i!=null&&Nn("scrollend",e);break;case"dangerouslySetInnerHTML":if(i!=null){if(typeof i!="object"||!("__html"in i))throw Error(at(61));if(t=i.__html,t!=null){if(n.children!=null)throw Error(at(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=Lv(""+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":Nn("beforetoggle",e),Nn("toggle",e),Jv(e,"popover",i);break;case"xlinkActuate":OB(e,"http://www.w3.org/1999/xlink","xlink:actuate",i);break;case"xlinkArcrole":OB(e,"http://www.w3.org/1999/xlink","xlink:arcrole",i);break;case"xlinkRole":OB(e,"http://www.w3.org/1999/xlink","xlink:role",i);break;case"xlinkShow":OB(e,"http://www.w3.org/1999/xlink","xlink:show",i);break;case"xlinkTitle":OB(e,"http://www.w3.org/1999/xlink","xlink:title",i);break;case"xlinkType":OB(e,"http://www.w3.org/1999/xlink","xlink:type",i);break;case"xmlBase":OB(e,"http://www.w3.org/XML/1998/namespace","xml:base",i);break;case"xmlLang":OB(e,"http://www.w3.org/XML/1998/namespace","xml:lang",i);break;case"xmlSpace":OB(e,"http://www.w3.org/XML/1998/namespace","xml:space",i);break;case"is":Jv(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=vkA.get(t)||t,Jv(e,t,i))}}function b1(e,A,t,i,n,g){switch(t){case"style":EaA(e,i,g);break;case"dangerouslySetInnerHTML":if(i!=null){if(typeof i!="object"||!("__html"in i))throw Error(at(61));if(t=i.__html,t!=null){if(n.children!=null)throw Error(at(60));e.innerHTML=t}}break;case"children":typeof i=="string"?aS(e,i):(typeof i=="number"||typeof i=="bigint")&&aS(e,""+i);break;case"onScroll":i!=null&&Nn("scroll",e);break;case"onScrollEnd":i!=null&&Nn("scrollend",e);break;case"onClick":i!=null&&(e.onclick=SE);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!aaA.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[rI]||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,""):Jv(e,t,i)}}}function wr(e,A,t){switch(A){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Nn("error",e),Nn("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(at(137,A));default:kg(e,A,g,o,t,null)}}n&&kg(e,A,"srcSet",t.srcSet,t,null),i&&kg(e,A,"src",t.src,t,null);return;case"input":Nn("invalid",e);var s=g=o=n=null,r=null,a=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":r=I;break;case"defaultChecked":a=I;break;case"value":g=I;break;case"defaultValue":s=I;break;case"children":case"dangerouslySetInnerHTML":if(I!=null)throw Error(at(137,A));break;default:kg(e,A,i,I,t,null)}}caA(e,g,s,r,a,o,n,!1);return;case"select":Nn("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:kg(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":Nn("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(at(91));break;default:kg(e,A,o,s,t,null)}BaA(e,i,n,g);return;case"option":for(r in t)if(t.hasOwnProperty(r)&&(i=t[r],i!=null))switch(r){case"selected":e.selected=i&&typeof i!="function"&&typeof i!="symbol";break;default:kg(e,A,r,i,t,null)}return;case"dialog":Nn("beforetoggle",e),Nn("toggle",e),Nn("cancel",e),Nn("close",e);break;case"iframe":case"object":Nn("load",e);break;case"video":case"audio":for(i=0;i<HM.length;i++)Nn(HM[i],e);break;case"image":Nn("error",e),Nn("load",e);break;case"details":Nn("toggle",e);break;case"embed":case"source":case"link":Nn("error",e),Nn("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(a in t)if(t.hasOwnProperty(a)&&(i=t[a],i!=null))switch(a){case"children":case"dangerouslySetInnerHTML":throw Error(at(137,A));default:kg(e,A,a,i,t,null)}return;default:if(sj(A)){for(I in t)t.hasOwnProperty(I)&&(i=t[I],i!==void 0&&b1(e,A,I,i,t,void 0));return}}for(s in t)t.hasOwnProperty(s)&&(i=t[s],i!=null&&kg(e,A,s,i,t,null))}function sNA(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,r=null,a=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":r=c;default:i.hasOwnProperty(B)||kg(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":a=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(at(137,A));break;default:B!==c&&kg(e,A,l,B,i,c)}}i1(e,o,s,r,a,I,g,n);return;case"select":B=o=s=l=null;for(g in t)if(r=t[g],t.hasOwnProperty(g)&&r!=null)switch(g){case"value":break;case"multiple":B=r;default:i.hasOwnProperty(g)||kg(e,A,g,null,i,r)}for(n in i)if(g=i[n],r=t[n],i.hasOwnProperty(n)&&(g!=null||r!=null))switch(n){case"value":l=g;break;case"defaultValue":s=g;break;case"multiple":o=g;default:g!==r&&kg(e,A,n,g,i,r)}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:kg(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(at(91));break;default:n!==g&&kg(e,A,o,n,i,g)}laA(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:kg(e,A,Q,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"selected":e.selected=l&&typeof l!="function"&&typeof l!="symbol";break;default:kg(e,A,r,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)&&kg(e,A,h,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"children":case"dangerouslySetInnerHTML":if(l!=null)throw Error(at(137,A));break;default:kg(e,A,a,l,i,B)}return;default:if(sj(A)){for(var d in t)l=t[d],t.hasOwnProperty(d)&&l!==void 0&&!i.hasOwnProperty(d)&&b1(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||b1(e,A,I,l,i,B);return}}for(var p in t)l=t[p],t.hasOwnProperty(p)&&l!=null&&!i.hasOwnProperty(p)&&kg(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||kg(e,A,c,l,i,B)}function VX(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function rNA(){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&&VX(o)){for(o=0,s=n.responseEnd,i+=1;i<t.length;i++){var r=t[i],a=r.startTime;if(a>s)break;var I=r.transferSize,c=r.initiatorType;I&&VX(c)&&(r=r.responseEnd,o+=I*(r<s?1:(s-a)/(r-a)))}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 U1=null,v1=null;function EF(e){return e.nodeType===9?e:e.ownerDocument}function XX(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 hCA(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 K1(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 jq=null;function aNA(){var e=window.event;return e&&e.type==="popstate"?e===jq?!1:(jq=e,!0):(jq=null,!1)}var pCA=typeof setTimeout=="function"?setTimeout:void 0,INA=typeof clearTimeout=="function"?clearTimeout:void 0,$X=typeof Promise=="function"?Promise:void 0,CNA=typeof queueMicrotask=="function"?queueMicrotask:typeof $X<"u"?function(e){return $X.resolve(null).then(e).catch(cNA)}:pCA;function cNA(e){setTimeout(function(){throw e})}function Sd(e){return e==="head"}function A6(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")Wk(e.ownerDocument.documentElement);else if(t==="head"){t=e.ownerDocument.head,Wk(t);for(var g=t.firstChild;g;){var o=g.nextSibling,s=g.nodeName;g[pR]||s==="SCRIPT"||s==="STYLE"||s==="LINK"&&g.rel.toLowerCase()==="stylesheet"||t.removeChild(g),g=o}}else t==="body"&&Wk(e.ownerDocument.body);t=n}while(t);uS(A)}function e6(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 F1(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":F1(t),oj(t);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(t.rel.toLowerCase()==="stylesheet")continue}e.removeChild(t)}}function lNA(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[pR])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=WC(e.nextSibling),e===null)break}return null}function BNA(e,A,t){if(A==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=WC(e.nextSibling),e===null))return null;return e}function fCA(e,A){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!A||(e=WC(e.nextSibling),e===null))return null;return e}function _1(e){return e.data==="$?"||e.data==="$~"}function J1(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function ENA(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 WC(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 L1=null;function t6(e){e=e.nextSibling;for(var A=0;e;){if(e.nodeType===8){var t=e.data;if(t==="/$"||t==="/&"){if(A===0)return WC(e.nextSibling);A--}else t!=="$"&&t!=="$!"&&t!=="$?"&&t!=="$~"&&t!=="&"||A++}e=e.nextSibling}return null}function i6(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 yCA(e,A,t){switch(A=EF(t),e){case"html":if(e=A.documentElement,!e)throw Error(at(452));return e;case"head":if(e=A.head,!e)throw Error(at(453));return e;case"body":if(e=A.body,!e)throw Error(at(454));return e;default:throw Error(at(451))}}function Wk(e){for(var A=e.attributes;A.length;)e.removeAttributeNode(A[0]);oj(e)}var ec=new Map,n6=new Set;function QF(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var cQ=Ig.d;Ig.d={f:QNA,r:uNA,D:dNA,C:hNA,L:pNA,m:fNA,X:DNA,S:yNA,M:mNA};function QNA(){var e=cQ.f(),A=rL();return e||A}function uNA(e){var A=rw(e);A!==null&&A.tag===5&&A.type==="form"?EIA(A):cQ.r(e)}var cw=typeof document>"u"?null:document;function DCA(e,A,t){var i=cw;if(i&&typeof A=="string"&&A){var n=YC(A);n='link[rel="'+e+'"][href="'+n+'"]',typeof t=="string"&&(n+='[crossorigin="'+t+'"]'),n6.has(n)||(n6.add(n),e={rel:e,crossOrigin:t,href:A},i.querySelector(n)===null&&(A=i.createElement("link"),wr(A,"link",e),$s(A),i.head.appendChild(A)))}}function dNA(e){cQ.D(e),DCA("dns-prefetch",e,null)}function hNA(e,A){cQ.C(e,A),DCA("preconnect",e,A)}function pNA(e,A,t){cQ.L(e,A,t);var i=cw;if(i&&e&&A){var n='link[rel="preload"][as="'+YC(A)+'"]';A==="image"&&t&&t.imageSrcSet?(n+='[imagesrcset="'+YC(t.imageSrcSet)+'"]',typeof t.imageSizes=="string"&&(n+='[imagesizes="'+YC(t.imageSizes)+'"]')):n+='[href="'+YC(e)+'"]';var g=n;switch(A){case"style":g=QS(e);break;case"script":g=lw(e)}ec.has(g)||(e=eo({rel:"preload",href:A==="image"&&t&&t.imageSrcSet?void 0:e,as:A},t),ec.set(g,e),i.querySelector(n)!==null||A==="style"&&i.querySelector(wR(g))||A==="script"&&i.querySelector(kR(g))||(A=i.createElement("link"),wr(A,"link",e),$s(A),i.head.appendChild(A)))}}function fNA(e,A){cQ.m(e,A);var t=cw;if(t&&e){var i=A&&typeof A.as=="string"?A.as:"script",n='link[rel="modulepreload"][as="'+YC(i)+'"][href="'+YC(e)+'"]',g=n;switch(i){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=lw(e)}if(!ec.has(g)&&(e=eo({rel:"modulepreload",href:e},A),ec.set(g,e),t.querySelector(n)===null)){switch(i){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(t.querySelector(kR(g)))return}i=t.createElement("link"),wr(i,"link",e),$s(i),t.head.appendChild(i)}}}function yNA(e,A,t){cQ.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(wR(g)))s.loading=5;else{e=eo({rel:"stylesheet",href:e,"data-precedence":A},t),(t=ec.get(g))&&Oj(e,t);var r=o=i.createElement("link");$s(r),wr(r,"link",e),r._p=new Promise(function(a,I){r.onload=a,r.onerror=I}),r.addEventListener("load",function(){s.loading|=1}),r.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 DNA(e,A){cQ.X(e,A);var t=cw;if(t&&e){var i=Bm(t).hoistableScripts,n=lw(e),g=i.get(n);g||(g=t.querySelector(kR(n)),g||(e=eo({src:e,async:!0},A),(A=ec.get(n))&&Pj(e,A),g=t.createElement("script"),$s(g),wr(g,"link",e),t.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},i.set(n,g))}}function mNA(e,A){cQ.M(e,A);var t=cw;if(t&&e){var i=Bm(t).hoistableScripts,n=lw(e),g=i.get(n);g||(g=t.querySelector(kR(n)),g||(e=eo({src:e,async:!0,type:"module"},A),(A=ec.get(n))&&Pj(e,A),g=t.createElement("script"),$s(g),wr(g,"link",e),t.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},i.set(n,g))}}function g6(e,A,t,i){var n=(n=bu.current)?QF(n):null;if(!n)throw Error(at(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(wR(e)))&&!g._p&&(o.instance=g,o.state.loading=5),ec.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},ec.set(e,t),g||SNA(n,e,t,o.state))),A&&i===null)throw Error(at(528,""));return o}if(A&&i!==null)throw Error(at(529,""));return null;case"script":return A=t.async,t=t.src,typeof t=="string"&&A&&typeof A!="function"&&typeof A!="symbol"?(A=lw(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(at(444,e))}}function QS(e){return'href="'+YC(e)+'"'}function wR(e){return'link[rel="stylesheet"]['+e+"]"}function mCA(e){return eo({},e,{"data-precedence":e.precedence,precedence:null})}function SNA(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}),wr(A,"link",t),$s(A),e.head.appendChild(A))}function lw(e){return'[src="'+YC(e)+'"]'}function kR(e){return"script[async]"+e}function o6(e,A,t){if(A.count++,A.instance===null)switch(A.type){case"style":var i=e.querySelector('style[data-href~="'+YC(t.href)+'"]');if(i)return A.instance=i,$s(i),i;var n=eo({},t,{"data-href":t.href,"data-precedence":t.precedence,href:null,precedence:null});return i=(e.ownerDocument||e).createElement("style"),$s(i),wr(i,"style",n),Zv(i,t.precedence,e),A.instance=i;case"stylesheet":n=QS(t.href);var g=e.querySelector(wR(n));if(g)return A.state.loading|=4,A.instance=g,$s(g),g;i=mCA(t),(n=ec.get(n))&&Oj(i,n),g=(e.ownerDocument||e).createElement("link"),$s(g);var o=g;return o._p=new Promise(function(s,r){o.onload=s,o.onerror=r}),wr(g,"link",i),A.state.loading|=4,Zv(g,t.precedence,e),A.instance=g;case"script":return g=lw(t.src),(n=e.querySelector(kR(g)))?(A.instance=n,$s(n),n):(i=t,(n=ec.get(g))&&(i=eo({},t),Pj(i,n)),e=e.ownerDocument||e,n=e.createElement("script"),$s(n),wr(n,"link",i),e.head.appendChild(n),A.instance=n);case"void":return null;default:throw Error(at(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 Oj(e,A){e.crossOrigin==null&&(e.crossOrigin=A.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=A.referrerPolicy),e.title==null&&(e.title=A.title)}function Pj(e,A){e.crossOrigin==null&&(e.crossOrigin=A.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=A.referrerPolicy),e.integrity==null&&(e.integrity=A.integrity)}var Wv=null;function s6(e,A,t){if(Wv===null){var i=new Map,n=Wv=new Map;n.set(t,i)}else n=Wv,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[pR]||g[pr]||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 r6(e,A,t){e=e.ownerDocument||e,e.head.insertBefore(t,A==="title"?e.querySelector("head > title"):null)}function wNA(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 SCA(e){return!(e.type==="stylesheet"&&!(e.state.loading&3))}function kNA(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(wR(n));if(g){A=g._p,A!==null&&typeof A=="object"&&typeof A.then=="function"&&(e.count++,e=uF.bind(e),A.then(e,e)),t.state.loading|=4,t.instance=g,$s(g);return}g=A.ownerDocument||A,i=mCA(i),(n=ec.get(n))&&Oj(i,n),g=g.createElement("link"),$s(g);var o=g;o._p=new Promise(function(s,r){o.onload=s,o.onerror=r}),wr(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=uF.bind(e),A.addEventListener("load",t),A.addEventListener("error",t))}}var zq=0;function MNA(e,A){return e.stylesheets&&e.count===0&&Vv(e,e.stylesheets),0<e.count||0<e.imgCount?function(t){var i=setTimeout(function(){if(e.stylesheets&&Vv(e,e.stylesheets),e.unsuspend){var g=e.unsuspend;e.unsuspend=null,g()}},6e4+A);0<e.imgBytes&&zq===0&&(zq=62500*rNA());var n=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Vv(e,e.stylesheets),e.unsuspend)){var g=e.unsuspend;e.unsuspend=null,g()}},(e.imgBytes>zq?50:800)+A);return e.unsuspend=t,function(){e.unsuspend=null,clearTimeout(i),clearTimeout(n)}}:null}function uF(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Vv(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var dF=null;function Vv(e,A){e.stylesheets=null,e.unsuspend!==null&&(e.count++,dF=new Map,A.forEach(NNA,e),dF=null,uF.call(e))}function NNA(e,A){if(!(A.state.loading&4)){var t=dF.get(e);if(t)var i=t.get(null);else{t=new Map,dF.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=uF.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 PM={$$typeof:mE,Provider:null,Consumer:null,_currentValue:Np,_currentValue2:Np,_threadCount:0};function RNA(e,A,t,i,n,g,o,s,r){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=uq(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=uq(0),this.hiddenUpdates=uq(null),this.identifierPrefix=i,this.onUncaughtError=n,this.onCaughtError=g,this.onRecoverableError=o,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=r,this.incompleteTransitions=new Map}function wCA(e,A,t,i,n,g,o,s,r,a,I,c){return e=new RNA(e,A,t,o,r,a,I,c,s),A=1,g===!0&&(A|=24),g=xI(3,null,null,A),e.current=g,g.stateNode=e,A=dj(),A.refCount++,e.pooledCache=A,A.refCount++,g.memoizedState={element:i,isDehydrated:t,cache:A},fj(g),e}function kCA(e){return e?(e=OD,e):OD}function MCA(e,A,t,i,n,g){n=kCA(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&&(oI(t,e,A),qk(t,e,A))}function a6(e,A){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t<A?t:A}}function jj(e,A){a6(e,A),(e=e.alternate)&&a6(e,A)}function NCA(e){if(e.tag===13||e.tag===31){var A=Gf(e,67108864);A!==null&&oI(A,e,67108864),jj(e,67108864)}}function I6(e){if(e.tag===13||e.tag===31){var A=ZI();A=nj(A);var t=Gf(e,A);t!==null&&oI(t,e,A),jj(e,A)}}var hF=!0;function GNA(e,A,t,i){var n=Ki.T;Ki.T=null;var g=Ig.p;try{Ig.p=2,zj(e,A,t,i)}finally{Ig.p=g,Ki.T=n}}function bNA(e,A,t,i){var n=Ki.T;Ki.T=null;var g=Ig.p;try{Ig.p=8,zj(e,A,t,i)}finally{Ig.p=g,Ki.T=n}}function zj(e,A,t,i){if(hF){var n=x1(i);if(n===null)Pq(e,A,i,pF,t),C6(e,i);else if(vNA(n,e,A,t,i))i.stopPropagation();else if(C6(e,i),A&4&&-1<UNA.indexOf(e)){for(;n!==null;){var g=rw(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 r=1<<31-zI(o);s.entanglements[1]|=r,o&=~r}kB(g),!(ag&6)&&(aF=PI()+500,SR(0))}}break;case 31:case 13:s=Gf(g,2),s!==null&&oI(s,g,2),rL(),jj(g,2)}if(g=x1(i),g===null&&Pq(e,A,i,pF,t),g===n)break;n=g}n!==null&&i.stopPropagation()}else Pq(e,A,i,null,t)}}function x1(e){return e=rj(e),Zj(e)}var pF=null;function Zj(e){if(pF=null,e=LD(e),e!==null){var A=QR(e);if(A===null)e=null;else{var t=A.tag;if(t===13){if(e=ZrA(A),e!==null)return e;e=null}else if(t===31){if(e=WrA(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 pF=e,null}function RCA(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(dkA()){case AaA:return 2;case eaA:return 8;case ZK:case hkA:return 32;case taA:return 268435456;default:return 32}default:return 32}}var T1=!1,Ju=null,Lu=null,xu=null,jM=new Map,zM=new Map,ou=[],UNA="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 C6(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":jM.delete(A.pointerId);break;case"gotpointercapture":case"lostpointercapture":zM.delete(A.pointerId)}}function h0(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=rw(A),A!==null&&NCA(A)),e):(e.eventSystemFlags|=i,A=e.targetContainers,n!==null&&A.indexOf(n)===-1&&A.push(n),e)}function vNA(e,A,t,i,n){switch(A){case"focusin":return Ju=h0(Ju,e,A,t,i,n),!0;case"dragenter":return Lu=h0(Lu,e,A,t,i,n),!0;case"mouseover":return xu=h0(xu,e,A,t,i,n),!0;case"pointerover":var g=n.pointerId;return jM.set(g,h0(jM.get(g)||null,e,A,t,i,n)),!0;case"gotpointercapture":return g=n.pointerId,zM.set(g,h0(zM.get(g)||null,e,A,t,i,n)),!0}return!1}function GCA(e){var A=LD(e.target);if(A!==null){var t=QR(A);if(t!==null){if(A=t.tag,A===13){if(A=ZrA(t),A!==null){e.blockedOn=A,Z9(e.priority,function(){I6(t)});return}}else if(A===31){if(A=WrA(t),A!==null){e.blockedOn=A,Z9(e.priority,function(){I6(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 Xv(e){if(e.blockedOn!==null)return!1;for(var A=e.targetContainers;0<A.length;){var t=x1(e.nativeEvent);if(t===null){t=e.nativeEvent;var i=new t.constructor(t.type,t);g1=i,t.target.dispatchEvent(i),g1=null}else return A=rw(t),A!==null&&NCA(A),e.blockedOn=t,!1;A.shift()}return!0}function c6(e,A,t){Xv(e)&&t.delete(A)}function KNA(){T1=!1,Ju!==null&&Xv(Ju)&&(Ju=null),Lu!==null&&Xv(Lu)&&(Lu=null),xu!==null&&Xv(xu)&&(xu=null),jM.forEach(c6),zM.forEach(c6)}function Ib(e,A){e.blockedOn===A&&(e.blockedOn=null,T1||(T1=!0,Ks.unstable_scheduleCallback(Ks.unstable_NormalPriority,KNA)))}var Cb=null;function l6(e){Cb!==e&&(Cb=e,Ks.unstable_scheduleCallback(Ks.unstable_NormalPriority,function(){Cb===e&&(Cb=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(Zj(i||t)===null)continue;break}var g=rw(t);g!==null&&(e.splice(A,3),A-=3,f1(g,{pending:!0,data:n,method:t.method,action:i},i,n))}}))}function uS(e){function A(r){return Ib(r,e)}Ju!==null&&Ib(Ju,e),Lu!==null&&Ib(Lu,e),xu!==null&&Ib(xu,e),jM.forEach(A),zM.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);)GCA(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[rI]||null;if(typeof g=="function")o||l6(t);else if(o){var s=null;if(g&&g.hasAttribute("formAction")){if(n=g,o=g[rI]||null)s=o.formAction;else if(Zj(n)!==null)continue}else s=o.action;typeof s=="function"?t[i+1]=s:(t.splice(i,3),i-=3),l6(t)}}}function bCA(){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 Wj(e){this._internalRoot=e}CL.prototype.render=Wj.prototype.render=function(e){var A=this._internalRoot;if(A===null)throw Error(at(409));var t=A.current,i=ZI();MCA(t,i,e,A,null,null)};CL.prototype.unmount=Wj.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),rL(),A[sw]=null}};function CL(e){this._internalRoot=e}CL.prototype.unstable_scheduleHydration=function(e){if(e){var A=saA();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&&GCA(e)}};var B6=jrA.version;if(B6!=="19.2.0")throw Error(at(527,B6,"19.2.0"));Ig.findDOMNode=function(e){var A=e._reactInternals;if(A===void 0)throw typeof e.render=="function"?Error(at(188)):(e=Object.keys(e).join(","),Error(at(268,e)));return e=CkA(A),e=e!==null?VrA(e):null,e=e===null?null:e.stateNode,e};var FNA={bundleType:0,version:"19.2.0",rendererPackageName:"react-dom",currentDispatcherRef:Ki,reconcilerVersion:"19.2.0"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var cb=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!cb.isDisabled&&cb.supportsFiber)try{uR=cb.inject(FNA),jI=cb}catch{}}zJ.createRoot=function(e,A){if(!zrA(e))throw Error(at(299));var t=!1,i="",n=DIA,g=mIA,o=SIA;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=wCA(e,1,!1,null,null,t,i,null,n,g,o,bCA),e[sw]=A.current,Hj(e),new Wj(A)};zJ.hydrateRoot=function(e,A,t){if(!zrA(e))throw Error(at(299));var i=!1,n="",g=DIA,o=mIA,s=SIA,r=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&&(r=t.formState)),A=wCA(e,1,!0,A,t??null,i,n,r,g,o,s,bCA),A.context=kCA(null),t=A.current,i=ZI(),i=nj(i),n=vu(i),n.callback=null,Ku(t,n,i),t=i,A.current.lanes=t,hR(A,t),kB(A),e[sw]=A.current,Hj(e),new CL(A)};zJ.version="19.2.0";function UCA(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(UCA)}catch(e){console.error(e)}}UCA(),TrA.exports=zJ;var GQ=TrA.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 E6="popstate";function _NA(e={}){function A(i,n){let{pathname:g,search:o,hash:s}=i.location;return q1("",{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:ZM(n)}return LNA(A,t,null,e)}function Io(e,A){if(e===!1||e===null||typeof e>"u")throw new Error(A)}function tc(e,A){if(!e){typeof console<"u"&&console.warn(A);try{throw new Error(A)}catch{}}}function JNA(){return Math.random().toString(36).substring(2,10)}function Q6(e,A){return{usr:e.state,key:e.key,idx:A}}function q1(e,A,t=null,i){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof A=="string"?Bw(A):A,state:t,key:A&&A.key||i||JNA()}}function ZM({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 Bw(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 LNA(e,A,t,i={}){let{window:n=document.defaultView,v5Compat:g=!1}=i,o=n.history,s="POP",r=null,a=I();a==null&&(a=0,o.replaceState({...o.state,idx:a},""));function I(){return(o.state||{idx:null}).idx}function c(){s="POP";let d=I(),p=d==null?null:d-a;a=d,r&&r({action:s,location:h.location,delta:p})}function l(d,p){s="PUSH";let y=q1(h.location,d,p);a=I()+1;let m=Q6(y,a),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&&r&&r({action:s,location:h.location,delta:1})}function B(d,p){s="REPLACE";let y=q1(h.location,d,p);a=I();let m=Q6(y,a),D=h.createHref(y);o.replaceState(m,"",D),g&&r&&r({action:s,location:h.location,delta:0})}function Q(d){return xNA(d)}let h={get action(){return s},get location(){return e(n,o)},listen(d){if(r)throw new Error("A history only accepts one active listener");return n.addEventListener(E6,c),r=d,()=>{n.removeEventListener(E6,c),r=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 xNA(e,A=!1){let t="http://localhost";typeof window<"u"&&(t=window.location.origin!=="null"?window.location.origin:window.location.href),Io(t,"No window.location.(origin|href) available to create URL");let i=typeof e=="string"?e:ZM(e);return i=i.replace(/ $/,"%20"),!A&&i.startsWith("//")&&(i=t+i),new URL(i,t)}function vCA(e,A,t="/"){return TNA(e,A,t,!1)}function TNA(e,A,t,i){let n=typeof A=="string"?Bw(A):A,g=zE(n.pathname||"/",t);if(g==null)return null;let o=KCA(e);qNA(o);let s=null;for(let r=0;s==null&&r<o.length;++r){let a=$NA(g);s=VNA(o[r],a,i)}return s}function KCA(e,A=[],t=[],i=""){let n=(g,o,s)=>{let r={relativePath:s===void 0?g.path||"":s,caseSensitive:g.caseSensitive===!0,childrenIndex:o,route:g};r.relativePath.startsWith("/")&&(Io(r.relativePath.startsWith(i),`Absolute route path "${r.relativePath}" nested under path "${i}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),r.relativePath=r.relativePath.slice(i.length));let a=UE([i,r.relativePath]),I=t.concat(r);g.children&&g.children.length>0&&(Io(g.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${a}".`),KCA(g.children,A,I,a)),!(g.path==null&&!g.index)&&A.push({path:a,score:ZNA(a,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 r of FCA(g.path))n(g,o,r)}),A}function FCA(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=FCA(i.join("/")),s=[];return s.push(...o.map(r=>r===""?g:[g,r].join("/"))),n&&s.push(...o),s.map(r=>e.startsWith("/")&&r===""?"/":r)}function qNA(e){e.sort((A,t)=>A.score!==t.score?t.score-A.score:WNA(A.routesMeta.map(i=>i.childrenIndex),t.routesMeta.map(i=>i.childrenIndex)))}var YNA=/^:[\w-]+$/,HNA=3,ONA=2,PNA=1,jNA=10,zNA=-2,u6=e=>e==="*";function ZNA(e,A){let t=e.split("/"),i=t.length;return t.some(u6)&&(i+=zNA),A&&(i+=ONA),t.filter(n=>!u6(n)).reduce((n,g)=>n+(YNA.test(g)?HNA:g===""?PNA:jNA),i)}function WNA(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 VNA(e,A,t=!1){let{routesMeta:i}=e,n={},g="/",o=[];for(let s=0;s<i.length;++s){let r=i[s],a=s===i.length-1,I=g==="/"?A:A.slice(g.length)||"/",c=fF({path:r.relativePath,caseSensitive:r.caseSensitive,end:a},I),l=r.route;if(!c&&a&&t&&!i[i.length-1].route.index&&(c=fF({path:r.relativePath,caseSensitive:r.caseSensitive,end:!1},I)),!c)return null;Object.assign(n,c.params),o.push({params:n,pathname:UE([g,c.pathname]),pathnameBase:iRA(UE([g,c.pathnameBase])),route:l}),c.pathnameBase!=="/"&&(g=UE([g,c.pathnameBase]))}return o}function fF(e,A){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[t,i]=XNA(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((a,{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?a[I]=void 0:a[I]=(B||"").replace(/%2F/g,"/"),a},{}),pathname:g,pathnameBase:o,pattern:e}}function XNA(e,A=!1,t=!0){tc(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,r)=>(i.push({paramName:s,isOptional:r!=null}),r?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(i.push({paramName:"*"}),n+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?n+="\\/*$":e!==""&&e!=="/"&&(n+="(?:(?=\\/|$))"),[new RegExp(n,A?void 0:"i"),i]}function $NA(e){try{return e.split("/").map(A=>decodeURIComponent(A).replace(/\//g,"%2F")).join("/")}catch(A){return tc(!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 ARA(e,A="/"){let{pathname:t,search:i="",hash:n=""}=typeof e=="string"?Bw(e):e;return{pathname:t?t.startsWith("/")?t:eRA(t,A):A,search:nRA(i),hash:gRA(n)}}function eRA(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 tRA(e){return e.filter((A,t)=>t===0||A.route.path&&A.route.path.length>0)}function Vj(e){let A=tRA(e);return A.map((t,i)=>i===A.length-1?t.pathname:t.pathnameBase)}function Xj(e,A,t,i=!1){let n;typeof e=="string"?n=Bw(e):(n={...e},Io(!n.pathname||!n.pathname.includes("?"),Zq("?","pathname","search",n)),Io(!n.pathname||!n.pathname.includes("#"),Zq("#","pathname","hash",n)),Io(!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 r=ARA(n,s),a=o&&o!=="/"&&o.endsWith("/"),I=(g||o===".")&&t.endsWith("/");return!r.pathname.endsWith("/")&&(a||I)&&(r.pathname+="/"),r}var UE=e=>e.join("/").replace(/\/\/+/g,"/"),iRA=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),nRA=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,gRA=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function oRA(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}var _CA=["POST","PUT","PATCH","DELETE"];new Set(_CA);var sRA=["GET",..._CA];new Set(sRA);var Ew=E.createContext(null);Ew.displayName="DataRouter";var cL=E.createContext(null);cL.displayName="DataRouterState";E.createContext(!1);var JCA=E.createContext({isTransitioning:!1});JCA.displayName="ViewTransition";var rRA=E.createContext(new Map);rRA.displayName="Fetchers";var aRA=E.createContext(null);aRA.displayName="Await";var il=E.createContext(null);il.displayName="Navigation";var MR=E.createContext(null);MR.displayName="Location";var ac=E.createContext({outlet:null,matches:[],isDataRoute:!1});ac.displayName="Route";var $j=E.createContext(null);$j.displayName="RouteError";function IRA(e,{relative:A}={}){Io(Qw(),"useHref() may be used only in the context of a <Router> component.");let{basename:t,navigator:i}=E.useContext(il),{hash:n,pathname:g,search:o}=NR(e,{relative:A}),s=g;return t!=="/"&&(s=g==="/"?t:UE([t,g])),i.createHref({pathname:s,search:o,hash:n})}function Qw(){return E.useContext(MR)!=null}function ms(){return Io(Qw(),"useLocation() may be used only in the context of a <Router> component."),E.useContext(MR).location}var LCA="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function xCA(e){E.useContext(il).static||E.useLayoutEffect(e)}function Ji(){let{isDataRoute:e}=E.useContext(ac);return e?SRA():CRA()}function CRA(){Io(Qw(),"useNavigate() may be used only in the context of a <Router> component.");let e=E.useContext(Ew),{basename:A,navigator:t}=E.useContext(il),{matches:i}=E.useContext(ac),{pathname:n}=ms(),g=JSON.stringify(Vj(i)),o=E.useRef(!1);return xCA(()=>{o.current=!0}),E.useCallback((r,a={})=>{if(tc(o.current,LCA),!o.current)return;if(typeof r=="number"){t.go(r);return}let I=Xj(r,JSON.parse(g),n,a.relative==="path");e==null&&A!=="/"&&(I.pathname=I.pathname==="/"?A:UE([A,I.pathname])),(a.replace?t.replace:t.push)(I,a.state,a)},[A,t,g,n,e])}var cRA=E.createContext(null);function lRA(e){let A=E.useContext(ac).outlet;return A&&E.createElement(cRA.Provider,{value:e},A)}function uw(){let{matches:e}=E.useContext(ac),A=e[e.length-1];return A?A.params:{}}function NR(e,{relative:A}={}){let{matches:t}=E.useContext(ac),{pathname:i}=ms(),n=JSON.stringify(Vj(t));return E.useMemo(()=>Xj(e,JSON.parse(n),i,A==="path"),[e,n,i,A])}function BRA(e,A){return TCA(e,A)}function TCA(e,A,t,i){var p;Io(Qw(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:n}=E.useContext(il),{matches:g}=E.useContext(ac),o=g[g.length-1],s=o?o.params:{},r=o?o.pathname:"/",a=o?o.pathnameBase:"/",I=o&&o.route;{let y=I&&I.path||"";qCA(r,!I||y.endsWith("*")||y.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${r}" (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=ms(),l;if(A){let y=typeof A=="string"?Bw(A):A;Io(a==="/"||((p=y.pathname)==null?void 0:p.startsWith(a)),`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 "${a}" but pathname "${y.pathname}" was given in the \`location\` prop.`),l=y}else l=c;let B=l.pathname||"/",Q=B;if(a!=="/"){let y=a.replace(/^\//,"").split("/");Q="/"+B.replace(/^\//,"").split("/").slice(y.length).join("/")}let h=vCA(e,{pathname:Q});tc(I||h!=null,`No routes matched location "${l.pathname}${l.search}${l.hash}" `),tc(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=hRA(h&&h.map(y=>Object.assign({},y,{params:Object.assign({},s,y.params),pathname:UE([a,n.encodeLocation?n.encodeLocation(y.pathname).pathname:y.pathname]),pathnameBase:y.pathnameBase==="/"?a:UE([a,n.encodeLocation?n.encodeLocation(y.pathnameBase).pathname:y.pathnameBase])})),g,t,i);return A&&d?E.createElement(MR.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...l},navigationType:"POP"}},d):d}function ERA(){let e=mRA(),A=oRA(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 QRA=E.createElement(ERA,null),uRA=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(ac.Provider,{value:this.props.routeContext},E.createElement($j.Provider,{value:this.state.error,children:this.props.component})):this.props.children}};function dRA({routeContext:e,match:A,children:t}){let i=E.useContext(Ew);return i&&i.static&&i.staticContext&&(A.route.errorElement||A.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=A.route.id),E.createElement(ac.Provider,{value:e},t)}function hRA(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 r=n.findIndex(a=>a.route.id&&(g==null?void 0:g[a.route.id])!==void 0);Io(r>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(g).join(",")}`),n=n.slice(0,Math.min(n.length,r+1))}let o=!1,s=-1;if(t)for(let r=0;r<n.length;r++){let a=n[r];if((a.route.HydrateFallback||a.route.hydrateFallbackElement)&&(s=r),a.route.id){let{loaderData:I,errors:c}=t,l=a.route.loader&&!I.hasOwnProperty(a.route.id)&&(!c||c[a.route.id]===void 0);if(a.route.lazy||l){o=!0,s>=0?n=n.slice(0,s+1):n=[n[0]];break}}}return n.reduceRight((r,a,I)=>{let c,l=!1,B=null,Q=null;t&&(c=g&&a.route.id?g[a.route.id]:void 0,B=a.route.errorElement||QRA,o&&(s<0&&I===0?(qCA("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),l=!0,Q=null):s===I&&(l=!0,Q=a.route.hydrateFallbackElement||null)));let h=A.concat(n.slice(0,I+1)),d=()=>{let p;return c?p=B:l?p=Q:a.route.Component?p=E.createElement(a.route.Component,null):a.route.element?p=a.route.element:p=r,E.createElement(dRA,{match:a,routeContext:{outlet:r,matches:h,isDataRoute:t!=null},children:p})};return t&&(a.route.ErrorBoundary||a.route.errorElement||I===0)?E.createElement(uRA,{location:t.location,revalidation:t.revalidation,component:B,error:c,children:d(),routeContext:{outlet:null,matches:h,isDataRoute:!0}}):d()},null)}function A8(e){return`${e} must be used within a data router.  See https://reactrouter.com/en/main/routers/picking-a-router.`}function pRA(e){let A=E.useContext(Ew);return Io(A,A8(e)),A}function fRA(e){let A=E.useContext(cL);return Io(A,A8(e)),A}function yRA(e){let A=E.useContext(ac);return Io(A,A8(e)),A}function e8(e){let A=yRA(e),t=A.matches[A.matches.length-1];return Io(t.route.id,`${e} can only be used on routes that contain a unique "id"`),t.route.id}function DRA(){return e8("useRouteId")}function mRA(){var i;let e=E.useContext($j),A=fRA("useRouteError"),t=e8("useRouteError");return e!==void 0?e:(i=A.errors)==null?void 0:i[t]}function SRA(){let{router:e}=pRA("useNavigate"),A=e8("useNavigate"),t=E.useRef(!1);return xCA(()=>{t.current=!0}),E.useCallback(async(n,g={})=>{tc(t.current,LCA),t.current&&(typeof n=="number"?e.navigate(n):await e.navigate(n,{fromRouteId:A,...g}))},[e,A])}var d6={};function qCA(e,A,t){!A&&!d6[e]&&(d6[e]=!0,tc(!1,t))}E.memo(wRA);function wRA({routes:e,future:A,state:t}){return TCA(e,void 0,t,A)}function Fg({to:e,replace:A,state:t,relative:i}){Io(Qw(),"<Navigate> may be used only in the context of a <Router> component.");let{static:n}=E.useContext(il);tc(!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(ac),{pathname:o}=ms(),s=Ji(),r=Xj(e,Vj(g),o,i==="path"),a=JSON.stringify(r);return E.useEffect(()=>{s(JSON.parse(a),{replace:A,state:t,relative:i})},[s,a,i,A,t]),null}function YCA(e){return lRA(e.context)}function we(e){Io(!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 kRA({basename:e="/",children:A=null,location:t,navigationType:i="POP",navigator:n,static:g=!1}){Io(!Qw(),"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=Bw(t));let{pathname:r="/",search:a="",hash:I="",state:c=null,key:l="default"}=t,B=E.useMemo(()=>{let Q=zE(r,o);return Q==null?null:{location:{pathname:Q,search:a,hash:I,state:c,key:l},navigationType:i}},[o,r,a,I,c,l,i]);return tc(B!=null,`<Router basename="${o}"> is not able to match the URL "${r}${a}${I}" because it does not start with the basename, so the <Router> won't render anything.`),B==null?null:E.createElement(il.Provider,{value:s},E.createElement(MR.Provider,{children:A,value:B}))}function Uf({children:e,location:A}){return BRA(Y1(e),A)}function Y1(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,Y1(i.props.children,g));return}Io(i.type===we,`[${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>`),Io(!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=Y1(i.props.children,g)),t.push(o)}),t}var $v="get",AK="application/x-www-form-urlencoded";function lL(e){return e!=null&&typeof e.tagName=="string"}function MRA(e){return lL(e)&&e.tagName.toLowerCase()==="button"}function NRA(e){return lL(e)&&e.tagName.toLowerCase()==="form"}function RRA(e){return lL(e)&&e.tagName.toLowerCase()==="input"}function GRA(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function bRA(e,A){return e.button===0&&(!A||A==="_self")&&!GRA(e)}function H1(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 URA(e,A){let t=H1(e);return A&&A.forEach((i,n)=>{t.has(n)||A.getAll(n).forEach(g=>{t.append(n,g)})}),t}var lb=null;function vRA(){if(lb===null)try{new FormData(document.createElement("form"),0),lb=!1}catch{lb=!0}return lb}var KRA=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Wq(e){return e!=null&&!KRA.has(e)?(tc(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${AK}"`),null):e}function FRA(e,A){let t,i,n,g,o;if(NRA(e)){let s=e.getAttribute("action");i=s?zE(s,A):null,t=e.getAttribute("method")||$v,n=Wq(e.getAttribute("enctype"))||AK,g=new FormData(e)}else if(MRA(e)||RRA(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 r=e.getAttribute("formaction")||s.getAttribute("action");if(i=r?zE(r,A):null,t=e.getAttribute("formmethod")||s.getAttribute("method")||$v,n=Wq(e.getAttribute("formenctype"))||Wq(s.getAttribute("enctype"))||AK,g=new FormData(s,e),!vRA()){let{name:a,type:I,value:c}=e;if(I==="image"){let l=a?`${a}.`:"";g.append(`${l}x`,"0"),g.append(`${l}y`,"0")}else a&&g.append(a,c)}}else{if(lL(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');t=$v,i=null,n=AK,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 t8(e,A){if(e===!1||e===null||typeof e>"u")throw new Error(A)}function _RA(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 JRA(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 LRA(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 xRA(e,A,t){let i=await Promise.all(e.map(async n=>{let g=A.routes[n.route.id];if(g){let o=await JRA(g,t);return o.links?o.links():[]}return[]}));return HRA(i.flat(1).filter(LRA).filter(n=>n.rel==="stylesheet"||n.rel==="preload").map(n=>n.rel==="stylesheet"?{...n,rel:"prefetch",as:"style"}:{...n,rel:"prefetch"}))}function h6(e,A,t,i,n,g){let o=(r,a)=>t[a]?r.route.id!==t[a].route.id:!0,s=(r,a)=>{var I;return t[a].pathname!==r.pathname||((I=t[a].route.path)==null?void 0:I.endsWith("*"))&&t[a].params["*"]!==r.params["*"]};return g==="assets"?A.filter((r,a)=>o(r,a)||s(r,a)):g==="data"?A.filter((r,a)=>{var c;let I=i.routes[r.route.id];if(!I||!I.hasLoader)return!1;if(o(r,a)||s(r,a))return!0;if(r.route.shouldRevalidate){let l=r.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:r.params,defaultShouldRevalidate:!0});if(typeof l=="boolean")return l}return!0}):[]}function TRA(e,A,{includeHydrateFallback:t}={}){return qRA(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 qRA(e){return[...new Set(e)]}function YRA(e){let A={},t=Object.keys(e).sort();for(let i of t)A[i]=e[i];return A}function HRA(e,A){let t=new Set;return new Set(A),e.reduce((i,n)=>{let g=JSON.stringify(YRA(n));return t.has(g)||(t.add(g),i.push({key:g,link:n})),i},[])}function HCA(){let e=E.useContext(Ew);return t8(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function ORA(){let e=E.useContext(cL);return t8(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}var i8=E.createContext(void 0);i8.displayName="FrameworkContext";function OCA(){let e=E.useContext(i8);return t8(e,"You must render this element inside a <HydratedRouter> element"),e}function PRA(e,A){let t=E.useContext(i8),[i,n]=E.useState(!1),[g,o]=E.useState(!1),{onFocus:s,onBlur:r,onMouseEnter:a,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:p0(s,B),onBlur:p0(r,Q),onMouseEnter:p0(a,B),onMouseLeave:p0(I,Q),onTouchStart:p0(c,B)}]:[!1,l,{}]}function p0(e,A){return t=>{e&&e(t),t.defaultPrevented||A(t)}}function jRA({page:e,...A}){let{router:t}=HCA(),i=E.useMemo(()=>vCA(t.routes,e,t.basename),[t.routes,e,t.basename]);return i?E.createElement(ZRA,{page:e,matches:i,...A}):null}function zRA(e){let{manifest:A,routeModules:t}=OCA(),[i,n]=E.useState([]);return E.useEffect(()=>{let g=!1;return xRA(e,A,t).then(o=>{g||n(o)}),()=>{g=!0}},[e,A,t]),i}function ZRA({page:e,matches:A,...t}){let i=ms(),{manifest:n,routeModules:g}=OCA(),{basename:o}=HCA(),{loaderData:s,matches:r}=ORA(),a=E.useMemo(()=>h6(e,A,r,n,i,"data"),[e,A,r,n,i]),I=E.useMemo(()=>h6(e,A,r,n,i,"assets"),[e,A,r,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||(!a.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=_RA(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,a,A,e,g]),l=E.useMemo(()=>TRA(I,n),[I,n]),B=zRA(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 WRA(...e){return A=>{e.forEach(t=>{typeof t=="function"?t(A):t!=null&&(t.current=A)})}}var PCA=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{PCA&&(window.__reactRouterVersion="7.8.0")}catch{}function VRA({basename:e,children:A,window:t}){let i=E.useRef();i.current==null&&(i.current=_NA({window:t,v5Compat:!0}));let n=i.current,[g,o]=E.useState({action:n.action,location:n.location}),s=E.useCallback(r=>{E.startTransition(()=>o(r))},[o]);return E.useLayoutEffect(()=>n.listen(s),[n,s]),E.createElement(kRA,{basename:e,children:A,location:g.location,navigationType:g.action,navigator:n})}var jCA=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,qI=E.forwardRef(function({onClick:A,discover:t="render",prefetch:i="none",relative:n,reloadDocument:g,replace:o,state:s,target:r,to:a,preventScrollReset:I,viewTransition:c,...l},B){let{basename:Q}=E.useContext(il),h=typeof a=="string"&&jCA.test(a),d,p=!1;if(typeof a=="string"&&h&&(d=a,PCA))try{let M=new URL(window.location.href),w=a.startsWith("//")?new URL(M.protocol+a):new URL(a),b=zE(w.pathname,Q);w.origin===M.origin&&b!=null?a=b+w.search+w.hash:p=!0}catch{tc(!1,`<Link to="${a}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}let y=IRA(a,{relative:n}),[m,D,S]=PRA(i,l),k=eGA(a,{replace:o,state:s,target:r,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:WRA(B,D),target:r,"data-discover":!h&&t==="render"?"true":void 0});return m&&!h?E.createElement(E.Fragment,null,G,E.createElement(jRA,{page:y})):G});qI.displayName="Link";var XRA=E.forwardRef(function({"aria-current":A="page",caseSensitive:t=!1,className:i="",end:n=!1,style:g,to:o,viewTransition:s,children:r,...a},I){let c=NR(o,{relative:a.relative}),l=ms(),B=E.useContext(cL),{navigator:Q,basename:h}=E.useContext(il),d=B!=null&&oGA(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(qI,{...a,"aria-current":G,className:M,ref:I,style:w,to:o,viewTransition:s},typeof r=="function"?r(N):r)});XRA.displayName="NavLink";var $RA=E.forwardRef(({discover:e="render",fetcherKey:A,navigate:t,reloadDocument:i,replace:n,state:g,method:o=$v,action:s,onSubmit:r,relative:a,preventScrollReset:I,viewTransition:c,...l},B)=>{let Q=nGA(),h=gGA(s,{relative:a}),d=o.toLowerCase()==="get"?"get":"post",p=typeof s=="string"&&jCA.test(s),y=m=>{if(r&&r(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:a,preventScrollReset:I,viewTransition:c})};return E.createElement("form",{ref:B,method:d,action:h,onSubmit:i?r:y,...l,"data-discover":!p&&e==="render"?"true":void 0})});$RA.displayName="Form";function AGA(e){return`${e} must be used within a data router.  See https://reactrouter.com/en/main/routers/picking-a-router.`}function zCA(e){let A=E.useContext(Ew);return Io(A,AGA(e)),A}function eGA(e,{target:A,replace:t,state:i,preventScrollReset:n,relative:g,viewTransition:o}={}){let s=Ji(),r=ms(),a=NR(e,{relative:g});return E.useCallback(I=>{if(bRA(I,A)){I.preventDefault();let c=t!==void 0?t:ZM(r)===ZM(a);s(e,{replace:c,state:i,preventScrollReset:n,relative:g,viewTransition:o})}},[r,s,a,t,i,A,e,n,g,o])}function dw(e){tc(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(H1(e)),t=E.useRef(!1),i=ms(),n=E.useMemo(()=>URA(i.search,t.current?null:A.current),[i.search]),g=Ji(),o=E.useCallback((s,r)=>{const a=H1(typeof s=="function"?s(new URLSearchParams(n)):s);t.current=!0,g("?"+a,r)},[g,n]);return[n,o]}var tGA=0,iGA=()=>`__${String(++tGA)}__`;function nGA(){let{router:e}=zCA("useSubmit"),{basename:A}=E.useContext(il),t=DRA();return E.useCallback(async(i,n={})=>{let{action:g,method:o,encType:s,formData:r,body:a}=FRA(i,A);if(n.navigate===!1){let I=n.fetcherKey||iGA();await e.fetch(I,t,n.action||g,{preventScrollReset:n.preventScrollReset,formData:r,body:a,formMethod:n.method||o,formEncType:n.encType||s,flushSync:n.flushSync})}else await e.navigate(n.action||g,{preventScrollReset:n.preventScrollReset,formData:r,body:a,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 gGA(e,{relative:A}={}){let{basename:t}=E.useContext(il),i=E.useContext(ac);Io(i,"useFormAction must be used inside a RouteContext");let[n]=i.matches.slice(-1),g={...NR(e||".",{relative:A})},o=ms();if(e==null){g.search=o.search;let s=new URLSearchParams(g.search),r=s.getAll("index");if(r.some(I=>I==="")){s.delete("index"),r.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:UE([t,g.pathname])),ZM(g)}function oGA(e,{relative:A}={}){let t=E.useContext(JCA);Io(t!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=zCA("useViewTransitionState"),n=NR(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 fF(n.pathname,o)!=null||fF(n.pathname,g)!=null}/*! Capacitor: https://capacitorjs.com/ - MIT License */var dS;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(dS||(dS={}));class Vq extends Error{constructor(A,t,i){super(A),this.message=A,this.code=t,this.data=i}}const sGA=e=>{var A,t;return e!=null&&e.androidBridge?"android":!((t=(A=e==null?void 0:e.webkit)===null||A===void 0?void 0:A.messageHandlers)===null||t===void 0)&&t.bridge?"ios":"web"},rGA=e=>{const A=e.CapacitorCustomPlatform||null,t=e.Capacitor||{},i=t.Plugins=t.Plugins||{},n=()=>A!==null?A.name:sGA(e),g=()=>n()!=="web",o=c=>{const l=a.get(c);return!!(l!=null&&l.platforms.has(n())||s(c))},s=c=>{var l;return(l=t.PluginHeaders)===null||l===void 0?void 0:l.find(B=>B.name===c)},r=c=>e.console.error(c),a=new Map,I=(c,l={})=>{const B=a.get(c);if(B)return console.warn(`Capacitor plugin "${c}" already registered. Cannot register plugins twice.`),B.proxy;const Q=n(),h=s(c);let d;const p=async()=>(!d&&Q in l?d=typeof l[Q]=="function"?d=await l[Q]():d=l[Q]:A!==null&&!d&&"web"in l&&(d=typeof l.web=="function"?d=await l.web():d=l.web),d),y=(G,M)=>{var w,b;if(h){const _=h==null?void 0:h.methods.find(K=>M===K.name);if(_)return _.rtype==="promise"?K=>t.nativePromise(c,M.toString(),K):(K,J)=>t.nativeCallback(c,M.toString(),K,J);if(G)return(w=G[M])===null||w===void 0?void 0:w.bind(G)}else{if(G)return(b=G[M])===null||b===void 0?void 0:b.bind(G);throw new Vq(`"${c}" plugin is not implemented on ${Q}`,dS.Unimplemented)}},m=G=>{let M;const w=(...b)=>{const _=p().then(K=>{const J=y(K,G);if(J){const T=J(...b);return M=T==null?void 0:T.remove,T}else throw new Vq(`"${c}.${G}()" is not implemented on ${Q}`,dS.Unimplemented)});return G==="addListener"&&(_.remove=async()=>M()),_};return w.toString=()=>`${G.toString()}() { [capacitor code] }`,Object.defineProperty(w,"name",{value:G,writable:!1,configurable:!1}),w},D=m("addListener"),S=m("removeListener"),k=(G,M)=>{const w=D({eventName:G},M),b=async()=>{const K=await w;S({eventName:G,callbackId:K},M)},_=new Promise(K=>w.then(()=>K({remove:b})));return _.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await b()},_},N=new Proxy({},{get(G,M){switch(M){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return h?k:D;case"removeListener":return S;default:return m(M)}}});return i[c]=N,a.set(c,{name:c,proxy:N,platforms:new Set([...Object.keys(l),...h?[Q]:[]])}),N};return t.convertFileSrc||(t.convertFileSrc=c=>c),t.getPlatform=n,t.handleError=r,t.isNativePlatform=g,t.isPluginAvailable=o,t.registerPlugin=I,t.Exception=Vq,t.DEBUG=!!t.DEBUG,t.isLoggingEnabled=!!t.isLoggingEnabled,t},aGA=e=>e.Capacitor=rGA(e),ti=aGA(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),nl=ti.registerPlugin;class ZCA{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(A,t){let i=!1;this.listeners[A]||(this.listeners[A]=[],i=!0),this.listeners[A].push(t);const g=this.windowListeners[A];g&&!g.registered&&this.addWindowListener(g),i&&this.sendRetainedArgumentsForEvent(A);const o=async()=>this.removeListener(A,t);return Promise.resolve({remove:o})}async removeAllListeners(){this.listeners={};for(const A in this.windowListeners)this.removeWindowListener(this.windowListeners[A]);this.windowListeners={}}notifyListeners(A,t,i){const n=this.listeners[A];if(!n){if(i){let g=this.retainedEventArguments[A];g||(g=[]),g.push(t),this.retainedEventArguments[A]=g}return}n.forEach(g=>g(t))}hasListeners(A){var t;return!!(!((t=this.listeners[A])===null||t===void 0)&&t.length)}registerWindowListener(A,t){this.windowListeners[t]={registered:!1,windowEventName:A,pluginEventName:t,handler:i=>{this.notifyListeners(t,i)}}}unimplemented(A="not implemented"){return new ti.Exception(A,dS.Unimplemented)}unavailable(A="not available"){return new ti.Exception(A,dS.Unavailable)}async removeListener(A,t){const i=this.listeners[A];if(!i)return;const n=i.indexOf(t);this.listeners[A].splice(n,1),this.listeners[A].length||this.removeWindowListener(this.windowListeners[A])}addWindowListener(A){window.addEventListener(A.windowEventName,A.handler),A.registered=!0}removeWindowListener(A){A&&(window.removeEventListener(A.windowEventName,A.handler),A.registered=!1)}sendRetainedArgumentsForEvent(A){const t=this.retainedEventArguments[A];t&&(delete this.retainedEventArguments[A],t.forEach(i=>{this.notifyListeners(A,i)}))}}const p6=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),f6=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class IGA extends ZCA{async getCookies(){const A=document.cookie,t={};return A.split(";").forEach(i=>{if(i.length<=0)return;let[n,g]=i.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");n=f6(n).trim(),g=f6(g).trim(),t[n]=g}),t}async setCookie(A){try{const t=p6(A.key),i=p6(A.value),n=`; expires=${(A.expires||"").replace("expires=","")}`,g=(A.path||"/").replace("path=",""),o=A.url!=null&&A.url.length>0?`domain=${A.url}`:"";document.cookie=`${t}=${i||""}${n}; path=${g}; ${o};`}catch(t){return Promise.reject(t)}}async deleteCookie(A){try{document.cookie=`${A.key}=; Max-Age=0`}catch(t){return Promise.reject(t)}}async clearCookies(){try{const A=document.cookie.split(";")||[];for(const t of A)document.cookie=t.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(A){return Promise.reject(A)}}async clearAllCookies(){try{await this.clearCookies()}catch(A){return Promise.reject(A)}}}nl("CapacitorCookies",{web:()=>new IGA});const CGA=async e=>new Promise((A,t)=>{const i=new FileReader;i.onload=()=>{const n=i.result;A(n.indexOf(",")>=0?n.split(",")[1]:n)},i.onerror=n=>t(n),i.readAsDataURL(e)}),cGA=(e={})=>{const A=Object.keys(e);return Object.keys(e).map(n=>n.toLocaleLowerCase()).reduce((n,g,o)=>(n[g]=e[A[o]],n),{})},lGA=(e,A=!0)=>e?Object.entries(e).reduce((i,n)=>{const[g,o]=n;let s,r;return Array.isArray(o)?(r="",o.forEach(a=>{s=A?encodeURIComponent(a):a,r+=`${g}=${s}&`}),r.slice(0,-1)):(s=A?encodeURIComponent(o):o,r=`${g}=${s}`),`${i}&${r}`},"").substr(1):null,BGA=(e,A={})=>{const t=Object.assign({method:e.method||"GET",headers:e.headers},A),n=cGA(e.headers)["content-type"]||"";if(typeof e.data=="string")t.body=e.data;else if(n.includes("application/x-www-form-urlencoded")){const g=new URLSearchParams;for(const[o,s]of Object.entries(e.data||{}))g.set(o,s);t.body=g.toString()}else if(n.includes("multipart/form-data")||e.data instanceof FormData){const g=new FormData;if(e.data instanceof FormData)e.data.forEach((s,r)=>{g.append(r,s)});else for(const s of Object.keys(e.data))g.append(s,e.data[s]);t.body=g;const o=new Headers(t.headers);o.delete("content-type"),t.headers=o}else(n.includes("application/json")||typeof e.data=="object")&&(t.body=JSON.stringify(e.data));return t};class EGA extends ZCA{async request(A){const t=BGA(A,A.webFetchExtra),i=lGA(A.params,A.shouldEncodeUrlParams),n=i?`${A.url}?${i}`:A.url,g=await fetch(n,t),o=g.headers.get("content-type")||"";let{responseType:s="text"}=g.ok?A:{};o.includes("application/json")&&(s="json");let r,a;switch(s){case"arraybuffer":case"blob":a=await g.blob(),r=await CGA(a);break;case"json":r=await g.json();break;case"document":case"text":default:r=await g.text()}const I={};return g.headers.forEach((c,l)=>{I[l]=c}),{data:r,headers:I,status:g.status,url:g.url}}async get(A){return this.request(Object.assign(Object.assign({},A),{method:"GET"}))}async post(A){return this.request(Object.assign(Object.assign({},A),{method:"POST"}))}async put(A){return this.request(Object.assign(Object.assign({},A),{method:"PUT"}))}async patch(A){return this.request(Object.assign(Object.assign({},A),{method:"PATCH"}))}async delete(A){return this.request(Object.assign(Object.assign({},A),{method:"DELETE"}))}}nl("CapacitorHttp",{web:()=>new EGA});const WM=nl("SocialLogin",{web:()=>li(()=>import("./web-COWDW8-G.js"),__vite__mapDeps([0,1])).then(e=>new e.SocialLoginWeb)}),QGA={SOCKET:{NEEDS_PREMIUM:"premium_membership_required"}},uGA=(()=>{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}})(),dGA=(()=>{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 hGA(){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 VM=(()=>{const e=hGA();return e||(uGA?"https://dicelounge.app":dGA?"http://localhost:4000":"https://dicelounge.app")})(),pGA=globalThis==null?void 0:globalThis.APP_TARGET;var crA,lrA;const fGA=(lrA=(crA=globalThis==null?void 0:globalThis.process)==null?void 0:crA.env)==null?void 0:lrA.APP_TARGET;let O1;var BrA,ErA;try{O1=(ErA=(BrA=import.meta)==null?void 0:BrA.env)==null?void 0:ErA.VITE_APP_TARGET}catch{O1=void 0}const yGA=pGA??fGA??O1,Fs=yGA??"unified",Xq=Fs==="ceelo",vp=Fs==="craps",Kp=Fs==="poker",RR=Fs==="skills",_c=Fs==="zentara",Th=Fs==="unified",DGA="rcb_eaWheJLZtWHJDCzyjruqCITeZlrK",y6={ceelo:"goog_TshzudibKBufFkwSWOodGwQAzMI",craps:"goog_FJlwnXjmdmVYKAbOkaiNyICWjkd",poker:"goog_AwODgwTGrKmYPFStHgslgZENzyG",unified:"goog_TshzudibKBufFkwSWOodGwQAzMI",skills:"goog_iGrdhumdjhzgNbIWxdHFjChutDX",zentara:"goog_BNlqWfFLFTMPnLmGhHhcfdOsACj"},mGA=y6[Fs]??y6.ceelo,D6={ceelo:"appl_YhZbXhNlphlrxochELLsdNJajdp",craps:"appl_uCBrYNXSOUzHdUNnkbfMaNxBxXI",poker:"appl_SKqhTdSJqfYQQGUjeFYzVZoSBqA",skills:"appl_OSFruGMgnsBocgEzWxpUyLYtskV",zentara:"appl_mpxyEsCoRtxMImTCLdZVnAUhtpJ",unified:"appl_YhZbXhNlphlrxochELLsdNJajdp"},SGA=D6[Fs]??D6.ceelo,wGA="false",BL="default",kGA="com.zentaraone.ceeloLounge.chips",EL=kGA,MGA="com.zentaraone.ceeloLounge.chips1000",NGA="com.zentaraone.crapsLounge.chips_1000",RGA="com.zentaraone.pokerLounge.chips_1000",QL=vp?NGA:Kp?RGA:MGA,GGA="",n8="Premium",bGA="AIzaSyCmll0lLOqadkCyjlrM-bb5H4n1L8eMxkE",UGA="dice-lounge.firebaseapp.com",vGA="dice-lounge",KGA="1:423374558927:web:283377221554368e57c9ba",FGA="G-MYPNJQR9RN",_GA="dicelounge.app",JGA="PEcc15f3HTqKKafnvHp1yRrbxrS8ji1kzZ4dyS4R+fI=",LGA="193765381581-rucls0d90bmpkqaj0ginhp87chgjq70j.apps.googleusercontent.com",GR="193765381581-s0a3p66cb39cdfum20jrm0d2e87jmlu8.apps.googleusercontent.com",xGA=GR,TGA=GR,qGA=GR,YGA=GR,HGA=vp?xGA:Kp?TGA:RR?qGA:_c?YGA:GR,OGA="com.zentaraone.ceeloLounge.service",PGA="com.zentaraone.crapsLounge.service",jGA="com.zentaraone.pokerLounge.service",zGA="com.zentaraone.skillslounge.service",ZGA="com.zentaraone.zentara.service",WGA=vp?PGA:Kp?jGA:RR?zGA:_c?ZGA:OGA,VGA="https://dicelounge.app/api/auth/apple/callback",XGA="com.zentaraone.ceeloLounge",$GA="com.zentaraone.crapsLounge",AbA="com.zentaraone.pokerLounge",ebA="com.zentaraone.skillslounge",tbA="com.zentaraone.zentara",ibA=vp?$GA:Kp?AbA:RR?ebA:_c?tbA:XGA,m6={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"},S6={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"},nbA=m6[Fs]??m6.ceelo,w6=S6[Fs]??S6.ceelo,k6={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"},gbA=k6[Fs]??k6.ceelo,N6=M6[Fs]??M6.ceelo,jQ=100,R6=30,WCA=3,VCA=3,XCA=40,qh=6e4,GD=800,obA=!1,uL=nl("SecureStoragePlugin",{web:()=>li(()=>import("./web-_QOCbX_X.js"),__vite__mapDeps([2,1])).then(e=>new e.SecureStoragePluginWeb)}),sbA=Object.freeze(Object.defineProperty({__proto__:null,SecureStoragePlugin:uL},Symbol.toStringTag,{value:"Module"})),nr=nl("Preferences",{web:()=>li(()=>import("./web-1K76zCcZ.js"),__vite__mapDeps([3,1])).then(e=>new e.PreferencesWeb)}),Yc=Object.freeze(Object.defineProperty({__proto__:null,Preferences:nr},Symbol.toStringTag,{value:"Module"})),Bb="sess:";async function G6(e){const{value:A}=await nr.get({key:e});return A??null}async function b6(e,A){await nr.set({key:e,value:A})}async function $q(e){await nr.remove({key:e})}const zc={async get(e){return G6(e)},async set(e,A){await b6(e,A)},async remove(e){await $q(e)},async setSession(e,A){await b6(Bb+e,A)},async getSession(e){return G6(Bb+e)},async removeSession(e){return $q(Bb+e)},async clearSessionKeys(){var e;try{const t=((e=(await nr.keys()).keys)==null?void 0:e.filter(i=>i.startsWith(Bb)))||[];await Promise.all(t.map(i=>$q(i)))}catch{}}};async function hS(e){try{const A=await zc.getSession(e);return A?JSON.parse(A):null}catch{return null}}async function dL(e,A){try{await zc.setSession(e,JSON.stringify(A))}catch{}}async function pS(e){try{await zc.removeSession(e)}catch{}}const fS="session_token",g8=ti.isNativePlatform();async function ef(e){g8?await uL.set({key:fS,value:e}):await zc.setSession(fS,e)}async function Co(){if(g8)try{const{value:A}=await uL.get({key:fS});return A||void 0}catch{return}return await zc.getSession(fS)||void 0}async function wd(){if(g8)try{await uL.remove({key:fS})}catch{}else await zc.removeSession(fS)}const rbA=Object.freeze(Object.defineProperty({__proto__:null,clearToken:wd,getToken:Co,setToken:ef},Symbol.toStringTag,{value:"Module"})),Ky={done:!1};function U6(e){if(!e)return"";const A=String(e);return A.length<=12?A:`${A.slice(0,6)}…${A.slice(-6)}`}function pa(e,A){try{console.log(`[NativeAuth] ${e}`,A??"")}catch{}}async function abA(){const e=ti.getPlatform(),A={mode:"online"},t=LGA,i=HGA;A.clientId=t,A.webClientId=t,A.mode="online",A.iOSClientId=i;const n={mode:"online"},g=e==="ios"?ibA:WGA,o=VGA;n.clientId=g,e!=="ios"&&o&&(n.redirectUrl=o),pa("initialize",{platform:e,hasIOS:!0,googleKeys:Object.keys(A),ids:{web:U6(t),iOS:U6(i)},apple:!0}),await WM.initialize({...Object.keys(A).length?{google:A}:{},...Object.keys(n).length?{apple:n}:{}})}async function yS(e=!1){if(!(!e&&Ky.done)){if(!e&&Ky.promise)return Ky.promise;Ky.promise=abA().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 $CA(){try{await yS()}catch(e){pa("prewarm:err",String(e))}}function IbA(){var e,A;try{const t=ti.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 CbA(){var a,I,c,l,B,Q,h;await yS(!0),pa("apple:login:start");const A=ti.getPlatform()==="android"?{}:{scopes:["email","name"]},t=await WM.login({provider:"apple",options:A}),i=(a=t==null?void 0:t.result)==null?void 0:a.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(" ")),r=[o,s].filter(Boolean).join(" ").trim()||(n==null?void 0:n.name)||void 0;if(pa("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:r}}async function cbA(){var e,A,t,i;await yS(!0);try{pa("google:login:start");const g=ti.getPlatform()==="android"?{}:{scopes:["email","profile"]},o=await WM.login({provider:"google",options:g});pa("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,r=(A=o==null?void 0:o.result)==null?void 0:A.profile,a=(r==null?void 0:r.email)||void 0,I=(r==null?void 0:r.name)||[r==null?void 0:r.givenName,r==null?void 0:r.familyName].filter(Boolean).join(" ").trim()||void 0;if(pa("google:login:result",{hasIdToken:!!s,hasProfile:!!r,hasEmail:!!a}),!s)throw new Error("Google did not return an id token");return{provider:"google",idToken:s,email:a,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};pa("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{pa("google:login:err:attempt-reinit"),await yS(!0);const r=ti.getPlatform(),a=await WM.login({provider:"google",options:r==="android"?{}:{scopes:["email","profile"]}});pa("google:login:retry:response",{hasResult:!!(a!=null&&a.result)});const I=(t=a==null?void 0:a.result)==null?void 0:t.idToken,c=(i=a==null?void 0:a.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(r){pa("google:login:err:reinit-failed",String(r))}throw g}}async function lbA(e,A){try{await yS()}catch{}try{await WM.logout({provider:e}),pa("signOut",{provider:e,ok:!0})}catch(t){pa("signOut:err",String(t))}try{await new Promise(t=>setTimeout(t,120)),await yS(!0),pa("signOut:reinit:ok")}catch(t){pa("signOut:reinit:err",String(t))}if((A==null?void 0:A.clearLocal)!==!1)try{await wd()}catch{}}const fm={isNativePlatform:IbA,signInWithAppleNative:CbA,signInWithGoogleNative:cbA,signOut:lbA,prewarmNativeAuth:$CA};let yl;function BbA(){var e;try{const A=(e=ti==null?void 0:ti.getPlatform)==null?void 0:e.call(ti);if(A)return A==="android"}catch{}try{return typeof navigator<"u"&&/Android/i.test(navigator.userAgent)}catch{return!1}}function EbA(){var e;try{const A=(e=ti==null?void 0:ti.getPlatform)==null?void 0:e.call(ti);if(A)return A==="ios"}catch{}try{return typeof navigator<"u"&&/iPhone|iPad|iPod/i.test(navigator.userAgent)}catch{return!1}}function QbA(){var e,A,t;try{const i=(e=ti==null?void 0:ti.getPlatform)==null?void 0:e.call(ti);return i&&["ios","android"].includes(i)?!0:!!((t=(A=window.Capacitor)==null?void 0:A.isNativePlatform)!=null&&t.call(A))}catch{return!1}}function ubA(){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 gr(){var g;if(yl)return yl;const e=BbA(),A=EbA(),t=QbA();if(e||A&&t)return yl="https://dicelounge.app",yl;let i=null;if(!e&&!(A&&t)&&(i=ubA()),i)return yl=i,yl;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)?(yl="http://localhost:4000",yl):(yl="https://dicelounge.app",yl)}const Tu=gr();let Yh=null,bD=0,UD=null;const dbA=1e4;async function hL(e){const A=(e==null?void 0:e.force)===!0,t=e==null?void 0:e.signal;return!A&&Yh&&Date.now()-bD<dbA?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 r=null;try{r=await Co()??null}catch{r=null}if(!A&&!r&&s)return null;const a=!!r,I={Accept:"application/json"};a&&r&&(I.Authorization=`Bearer ${r}`);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(!a&&r){const l=await fetch(`${Tu}/api/auth/me`,{credentials:"include",headers:{Accept:"application/json",Authorization:`Bearer ${r}`},signal:t});if(l.ok){const B=await l.json();return Yh=B,bD=Date.now(),B}if(l.status===401)try{await wd()}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 AcA(e){let A=null;try{A=await Co()??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 wd()}catch{}try{Yh=null,bD=0,UD=null}catch{}}async function hbA(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 li(async()=>{const{clearInviter:n}=await Promise.resolve().then(()=>Oke);return{clearInviter:n}},void 0);i()}}catch{}return t}async function pbA(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 fbA(){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 ybA={};let A2=!1,DS=null,Fy=null;function DbA(){return{apiKey:bGA,authDomain:UGA,projectId:vGA,appId:KGA,measurementId:FGA}}function Vk(){return typeof window<"u"&&typeof document<"u"}function ecA(){if(!Vk())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 Xk(...e){ecA()&&console.info("[analytics]",...e)}async function o8(){if(A2||!Vk())return;try{if(typeof navigator<"u"&&/jsdom|playwright/i.test(navigator.userAgent||"")||typeof window<"u"&&window.__E2E===!0||typeof process<"u"&&(ybA.VITEST||!1)){A2=!0,Xk("skip:init (test env heuristic)");return}}catch{}const e=DbA();try{const[{initializeApp:A},{getAnalytics:t}]=await Promise.all([li(()=>import("./index.esm-Ct10TrAh.js"),__vite__mapDeps([4,5])),li(()=>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});DS=t(i),Xk("init:ok",{measurementId:e.measurementId})}catch(A){DS=null,Xk("init:fail",{error:(A==null?void 0:A.message)||String(A)})}finally{A2=!0}}function tf(e,A){if(DS)try{li(async()=>{const{logEvent:t}=await import("./index.esm-0EJQLKq6.js");return{logEvent:t}},__vite__mapDeps([6,5,7])).then(({logEvent:t})=>{const i=A||{};ecA()&&(i.debug_mode=!0);try{t(DS,e,i),Xk("event",{eventName:e,params:i})}catch{}})}catch{}}function aI(e,A){const t=Vk()?window.location.href:void 0,i=e??(Vk()?window.location.pathname:void 0),n=Vk()?document.title:void 0;tf("page_view",{page_location:t,page_path:i,page_title:n})}function e2(e){!DS||!e||li(async()=>{const{setUserId:A}=await import("./index.esm-0EJQLKq6.js");return{setUserId:A}},__vite__mapDeps([6,5,7])).then(({setUserId:A})=>{try{A(DS,e)}catch{}Xk("userId:set",{userId:e})})}async function mbA(e){const A=new Set([]);try{await nr.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 hB=Object.create(null);hB.open="0";hB.close="1";hB.ping="2";hB.pong="3";hB.message="4";hB.upgrade="5";hB.noop="6";const eK=Object.create(null);Object.keys(hB).forEach(e=>{eK[hB[e]]=e});const P1={type:"error",data:"parser error"},tcA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",icA=typeof ArrayBuffer=="function",ncA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,s8=({type:e,data:A},t,i)=>tcA&&A instanceof Blob?t?i(A):v6(A,i):icA&&(A instanceof ArrayBuffer||ncA(A))?t?i(A):v6(new Blob([A]),i):i(hB[e]+(A||"")),v6=(e,A)=>{const t=new FileReader;return t.onload=function(){const i=t.result.split(",")[1];A("b"+(i||""))},t.readAsDataURL(e)};function K6(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let t2;function SbA(e,A){if(tcA&&e.data instanceof Blob)return e.data.arrayBuffer().then(K6).then(A);if(icA&&(e.data instanceof ArrayBuffer||ncA(e.data)))return A(K6(e.data));s8(e,!1,t=>{t2||(t2=new TextEncoder),A(t2.encode(t))})}const F6="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ck=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<F6.length;e++)ck[F6.charCodeAt(e)]=e;const wbA=e=>{let A=e.length*.75,t=e.length,i,n=0,g,o,s,r;e[e.length-1]==="="&&(A--,e[e.length-2]==="="&&A--);const a=new ArrayBuffer(A),I=new Uint8Array(a);for(i=0;i<t;i+=4)g=ck[e.charCodeAt(i)],o=ck[e.charCodeAt(i+1)],s=ck[e.charCodeAt(i+2)],r=ck[e.charCodeAt(i+3)],I[n++]=g<<2|o>>4,I[n++]=(o&15)<<4|s>>2,I[n++]=(s&3)<<6|r&63;return a},kbA=typeof ArrayBuffer=="function",r8=(e,A)=>{if(typeof e!="string")return{type:"message",data:gcA(e,A)};const t=e.charAt(0);return t==="b"?{type:"message",data:MbA(e.substring(1),A)}:eK[t]?e.length>1?{type:eK[t],data:e.substring(1)}:{type:eK[t]}:P1},MbA=(e,A)=>{if(kbA){const t=wbA(e);return gcA(t,A)}else return{base64:!0,data:e}},gcA=(e,A)=>{switch(A){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},ocA="",NbA=(e,A)=>{const t=e.length,i=new Array(t);let n=0;e.forEach((g,o)=>{s8(g,!1,s=>{i[o]=s,++n===t&&A(i.join(ocA))})})},RbA=(e,A)=>{const t=e.split(ocA),i=[];for(let n=0;n<t.length;n++){const g=r8(t[n],A);if(i.push(g),g.type==="error")break}return i};function GbA(){return new TransformStream({transform(e,A){SbA(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 i2;function Eb(e){return e.reduce((A,t)=>A+t.length,0)}function Qb(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 bbA(e,A){i2||(i2=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(Eb(t)<1)break;const r=Qb(t,1);g=(r[0]&128)===128,n=r[0]&127,n<126?i=3:n===126?i=1:i=2}else if(i===1){if(Eb(t)<2)break;const r=Qb(t,2);n=new DataView(r.buffer,r.byteOffset,r.length).getUint16(0),i=3}else if(i===2){if(Eb(t)<8)break;const r=Qb(t,8),a=new DataView(r.buffer,r.byteOffset,r.length),I=a.getUint32(0);if(I>Math.pow(2,21)-1){s.enqueue(P1);break}n=I*Math.pow(2,32)+a.getUint32(4),i=3}else{if(Eb(t)<n)break;const r=Qb(t,n);s.enqueue(r8(g?r:i2.decode(r),A)),i=0}if(n===0||n>e){s.enqueue(P1);break}}}})}const scA=4;function hs(e){if(e)return UbA(e)}function UbA(e){for(var A in hs.prototype)e[A]=hs.prototype[A];return e}hs.prototype.on=hs.prototype.addEventListener=function(e,A){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(A),this};hs.prototype.once=function(e,A){function t(){this.off(e,t),A.apply(this,arguments)}return t.fn=A,this.on(e,t),this};hs.prototype.off=hs.prototype.removeListener=hs.prototype.removeAllListeners=hs.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};hs.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};hs.prototype.emitReserved=hs.prototype.emit;hs.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};hs.prototype.hasListeners=function(e){return!!this.listeners(e).length};const pL=typeof Promise=="function"&&typeof Promise.resolve=="function"?A=>Promise.resolve().then(A):(A,t)=>t(A,0),qC=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),vbA="arraybuffer";function rcA(e,...A){return A.reduce((t,i)=>(e.hasOwnProperty(i)&&(t[i]=e[i]),t),{})}const KbA=qC.setTimeout,FbA=qC.clearTimeout;function fL(e,A){A.useNativeTimers?(e.setTimeoutFn=KbA.bind(qC),e.clearTimeoutFn=FbA.bind(qC)):(e.setTimeoutFn=qC.setTimeout.bind(qC),e.clearTimeoutFn=qC.clearTimeout.bind(qC))}const _bA=1.33;function JbA(e){return typeof e=="string"?LbA(e):Math.ceil((e.byteLength||e.size)*_bA)}function LbA(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 acA(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function xbA(e){let A="";for(let t in e)e.hasOwnProperty(t)&&(A.length&&(A+="&"),A+=encodeURIComponent(t)+"="+encodeURIComponent(e[t]));return A}function TbA(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 qbA extends Error{constructor(A,t,i){super(A),this.description=t,this.context=i,this.type="TransportError"}}class a8 extends hs{constructor(A){super(),this.writable=!1,fL(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 qbA(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=r8(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=xbA(A);return t.length?"?"+t:""}}class YbA extends a8{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)};RbA(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,NbA(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]=acA()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(A,t)}}let IcA=!1;try{IcA=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const HbA=IcA;function ObA(){}class PbA extends YbA{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 tK extends hs{constructor(A,t,i){super(),this.createRequest=A,fL(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=rcA(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=tK.requestsCount++,tK.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=ObA,A)try{this._xhr.abort()}catch{}typeof document<"u"&&delete tK.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",_6);else if(typeof addEventListener=="function"){const e="onpagehide"in qC?"pagehide":"unload";addEventListener(e,_6,!1)}}function _6(){for(let e in ym.requests)ym.requests.hasOwnProperty(e)&&ym.requests[e].abort()}const jbA=function(){const e=CcA({xdomain:!1});return e&&e.responseType!==null}();class zbA extends PbA{constructor(A){super(A);const t=A&&A.forceBase64;this.supportsBinary=jbA&&!t}request(A={}){return Object.assign(A,{xd:this.xd},this.opts),new ym(CcA,this.uri(),A)}}function CcA(e){const A=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!A||HbA))return new XMLHttpRequest}catch{}if(!A)try{return new qC[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ccA=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ZbA extends a8{get name(){return"websocket"}doOpen(){const A=this.uri(),t=this.opts.protocols,i=ccA?{}:rcA(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;s8(i,this.supportsBinary,g=>{try{this.doWrite(i,g)}catch{}n&&pL(()=>{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]=acA()),this.supportsBinary||(t.b64=1),this.createUri(A,t)}}const n2=qC.WebSocket||qC.MozWebSocket;class WbA extends ZbA{createSocket(A,t,i){return ccA?new n2(A,t,i):t?new n2(A,t):new n2(A)}doWrite(A,t){this.ws.send(t)}}class VbA extends a8{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=bbA(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=A.readable.pipeThrough(t).getReader(),n=GbA();n.readable.pipeTo(A.writable),this._writer=n.writable.getWriter();const g=()=>{i.read().then(({done:s,value:r})=>{s||(this.onPacket(r),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&&pL(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var A;(A=this._transport)===null||A===void 0||A.close()}}const XbA={websocket:WbA,webtransport:VbA,polling:zbA},$bA=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,AUA=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function j1(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=$bA.exec(e||""),g={},o=14;for(;o--;)g[AUA[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=eUA(g,g.path),g.queryKey=tUA(g,g.query),g}function eUA(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 tUA(e,A){const t={};return A.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,n,g){n&&(t[n]=g)}),t}const z1=typeof addEventListener=="function"&&typeof removeEventListener=="function",iK=[];z1&&addEventListener("offline",()=>{iK.forEach(e=>e())},!1);class qu extends hs{constructor(A,t){if(super(),this.binaryType=vbA,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=j1(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=j1(t.host).host);fL(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=TbA(this.opts.query)),z1&&(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"})},iK.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(A){const t=Object.assign({},this.opts.query);t.EIO=scA,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+=JbA(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,pL(()=>{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(),z1&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const i=iK.indexOf(this._offlineEventListener);i!==-1&&iK.splice(i,1)}this.readyState="closed",this.id=null,this.emitReserved("close",A,t),this.writeBuffer=[],this._prevBufferLen=0}}}qu.protocol=scA;class iUA 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 r(){o("socket closed")}function a(c){t&&c.name!==t.name&&g()}const I=()=>{t.removeListener("open",n),t.removeListener("error",o),t.removeListener("close",s),this.off("close",r),this.off("upgrading",a)};t.once("open",n),t.once("error",o),t.once("close",s),this.once("close",r),this.once("upgrading",a),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 nUA=class extends iUA{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=>XbA[n]).filter(n=>!!n)),super(A,i)}};function gUA(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=j1(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 oUA=typeof ArrayBuffer=="function",sUA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,lcA=Object.prototype.toString,rUA=typeof Blob=="function"||typeof Blob<"u"&&lcA.call(Blob)==="[object BlobConstructor]",aUA=typeof File=="function"||typeof File<"u"&&lcA.call(File)==="[object FileConstructor]";function I8(e){return oUA&&(e instanceof ArrayBuffer||sUA(e))||rUA&&e instanceof Blob||aUA&&e instanceof File}function nK(e,A){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let t=0,i=e.length;t<i;t++)if(nK(e[t]))return!0;return!1}if(I8(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return nK(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&nK(e[t]))return!0;return!1}function IUA(e){const A=[],t=e.data,i=e;return i.data=Z1(t,A),i.attachments=A.length,{packet:i,buffers:A}}function Z1(e,A){if(!e)return e;if(I8(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]=Z1(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]=Z1(e[i],A));return t}return e}function CUA(e,A){return e.data=W1(e.data,A),delete e.attachments,e}function W1(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]=W1(e[t],A);else if(typeof e=="object")for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(e[t]=W1(e[t],A));return e}const cUA=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],lUA=5;var Hn;(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"})(Hn||(Hn={}));class BUA{constructor(A){this.replacer=A}encode(A){return(A.type===Hn.EVENT||A.type===Hn.ACK)&&nK(A)?this.encodeAsBinary({type:A.type===Hn.EVENT?Hn.BINARY_EVENT:Hn.BINARY_ACK,nsp:A.nsp,data:A.data,id:A.id}):[this.encodeAsString(A)]}encodeAsString(A){let t=""+A.type;return(A.type===Hn.BINARY_EVENT||A.type===Hn.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=IUA(A),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}}function J6(e){return Object.prototype.toString.call(e)==="[object Object]"}class C8 extends hs{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===Hn.BINARY_EVENT;i||t.type===Hn.BINARY_ACK?(t.type=i?Hn.EVENT:Hn.ACK,this.reconstructor=new EUA(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(I8(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(Hn[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===Hn.BINARY_EVENT||i.type===Hn.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(C8.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 Hn.CONNECT:return J6(t);case Hn.DISCONNECT:return t===void 0;case Hn.CONNECT_ERROR:return typeof t=="string"||J6(t);case Hn.EVENT:case Hn.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&cUA.indexOf(t[0])===-1);case Hn.ACK:case Hn.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class EUA{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=CUA(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const QUA=Object.freeze(Object.defineProperty({__proto__:null,Decoder:C8,Encoder:BUA,get PacketType(){return Hn},protocol:lUA},Symbol.toStringTag,{value:"Module"}));function vc(e,A,t){return e.on(A,t),function(){e.off(A,t)}}const uUA=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class BcA extends hs{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=[vc(A,"open",this.onopen.bind(this)),vc(A,"packet",this.onpacket.bind(this)),vc(A,"error",this.onerror.bind(this)),vc(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(uUA.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:Hn.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,r=this.connected&&!(!((g=this.io.engine)===null||g===void 0)&&g._hasPingExpired());return this.flags.volatile&&!s||(r?(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:Hn.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 Hn.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 Hn.EVENT:case Hn.BINARY_EVENT:this.onevent(A);break;case Hn.ACK:case Hn.BINARY_ACK:this.onack(A);break;case Hn.DISCONNECT:this.ondisconnect();break;case Hn.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:Hn.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:Hn.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 hw(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}hw.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};hw.prototype.reset=function(){this.attempts=0};hw.prototype.setMin=function(e){this.ms=e};hw.prototype.setMax=function(e){this.max=e};hw.prototype.setJitter=function(e){this.jitter=e};class V1 extends hs{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,fL(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 hw({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||QUA;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 nUA(this.uri,this.opts);const t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const n=vc(t,"open",function(){i.onopen(),A&&A()}),g=s=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",s),A?A(s):this.maybeReconnectOnOpen()},o=vc(t,"error",g);if(this._timeout!==!1){const s=this._timeout,r=this.setTimeoutFn(()=>{n(),g(new Error("timeout")),t.close()},s);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}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(vc(A,"ping",this.onping.bind(this)),vc(A,"data",this.ondata.bind(this)),vc(A,"error",this.onerror.bind(this)),vc(A,"close",this.onclose.bind(this)),vc(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){pL(()=>{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 BcA(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 f0={};function $k(e,A){typeof e=="object"&&(A=e,e=void 0),A=A||{};const t=gUA(e,A.path||"/socket.io"),i=t.source,n=t.id,g=t.path,o=f0[n]&&g in f0[n].nsps,s=A.forceNew||A["force new connection"]||A.multiplex===!1||o;let r;return s?r=new V1(i,A):(f0[n]||(f0[n]=new V1(i,A)),r=f0[n]),t.query&&!A.query&&(A.query=t.queryKey),r.socket(t.path,A)}Object.assign($k,{Manager:V1,Socket:BcA,io:$k,connect:$k});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 EcA(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 QcA=E.createContext(void 0),dUA=({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),[]),r=E.useCallback(I=>{t(!1),setTimeout(()=>t(!0),I)},[]),a=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:r,resetReveal:a,resetSpin:s};try{window.__diceRevealTest=c}catch{}return()=>{try{delete window.__diceRevealTest}catch{}}},[o,r,a,s]),C.jsx(QcA.Provider,{value:{reveal:A,triggerReveal:g,scheduleReveal:r,resetReveal:a,triggerSpin:o,rollTrigger:i,resetSpin:s},children:e})},MB=()=>{const e=E.useContext(QcA);if(!e)throw new Error("useDiceReveal must be used within a DiceRevealProvider");return e},g2={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_TARGET:"craps",VITE_OTA:"1",VITE_OTA_MANIFEST_URL:"https://cdn.dicelounge.app/ota/manifest.json"},XM=500,ucA=new Array(XM);let AM=0,yF=0;const c8="fe:crashlog",hUA=80;function dcA(){try{const e=$M().slice(-hUA).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(c8,JSON.stringify(e))}catch{}}function l8(){try{const e=localStorage.getItem(c8);return e?JSON.parse(e):[]}catch{return[]}}function pUA(){try{localStorage.removeItem(c8)}catch{}}let o2=null;function fUA(){o2||(o2=setTimeout(()=>{o2=null,dcA()},2e3))}function yUA(){var e;try{if(typeof window<"u"&&((e=window.localStorage)==null?void 0:e.getItem("logs:disable"))==="1"||typeof import.meta<"u"&&(g2==null?void 0:g2.VITE_LOGS_DISABLED)==="1")return!1}catch{}return!0}function DUA(e){ucA[AM]=e,AM=(AM+1)%XM,yF=Math.min(yF+1,XM);try{window.dispatchEvent(new CustomEvent("fe:log",{detail:e}))}catch{}e.level==="error"||e.level==="warn"?dcA():fUA()}function $M(){const e=[],A=yF;for(let t=0;t<A;t++){const i=(AM-A+t+XM)%XM,n=ucA[i];n&&e.push(n)}return e}function mUA(){AM=0,yF=0}function ps(e,A,t,i){const n={t:Date.now(),tag:e,level:A,msg:t,data:i};if(yUA()){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{}DUA(n)}}const ai={debug:(e,A)=>ps("RTC","debug",e,A),info:(e,A)=>ps("RTC","info",e,A),warn:(e,A)=>ps("RTC","warn",e,A),error:(e,A)=>ps("RTC","error",e,A)},Ns={debug:(e,A)=>ps("LIFE","debug",e,A),info:(e,A)=>ps("LIFE","info",e,A),warn:(e,A)=>ps("LIFE","warn",e,A),error:(e,A)=>ps("LIFE","error",e,A)},UC={debug:(e,A)=>ps("SOCK","debug",e,A),info:(e,A)=>ps("SOCK","info",e,A),warn:(e,A)=>ps("SOCK","warn",e,A),error:(e,A)=>ps("SOCK","error",e,A)},FI={debug:(e,A)=>ps("GL","debug",e,A),info:(e,A)=>ps("GL","info",e,A),warn:(e,A)=>ps("GL","warn",e,A),error:(e,A)=>ps("GL","error",e,A)},X1={debug:(e,A)=>ps("ERR","debug",e,A),info:(e,A)=>ps("ERR","info",e,A),warn:(e,A)=>ps("ERR","warn",e,A),error:(e,A)=>ps("ERR","error",e,A)};try{window.rtcLogs=$M,window.rtcLogsClear=mUA,window.feLogs=$M,window.feCrashLogs=l8}catch{}const B8=E.createContext(null);let Rs=null,L6="",lk=0,ub=0;const x6=1200;let E8=!1,db=0;const hcA=2e3;function qr(e,A,t){var g,o,s,r;if(!e||e.connected||e.active)return!1;let i="";try{i=String(((g=e.auth)==null?void 0:g.token)||((r=(s=(o=e==null?void 0:e.io)==null?void 0:o.opts)==null?void 0:s.auth)==null?void 0:r.token)||"")}catch{i=""}if(!i&&!(t!=null&&t.allowCookieSession))return UC.debug("safeSocketConnect SKIPPED - no auth token",{source:A}),!1;if(E8)return UC.warn("safeSocketConnect SKIPPED - session superseded",{source:A}),console.log("[safeSocketConnect] SKIPPED - session superseded",{source:A}),!1;const n=Date.now();if(n<db)return UC.debug("safeSocketConnect SKIPPED - debounce",{source:A,msRemaining:db-n}),console.log("[safeSocketConnect] SKIPPED - connect already in progress",{source:A,msRemaining:db-n}),!1;db=n+hcA,UC.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 SUA(){E8=!1}function pcA(){E8=!0,console.log("[SocketContext] Session superseded by another device/tab - auto-reconnect disabled")}function Q8(e=2e3){try{lk=Date.now()+Math.max(0,e|0)}catch{}}function pw(){return Rs}function wUA(e=2e3){try{Q8(e)}catch{}try{Rs==null||Rs.removeAllListeners()}catch{}try{Fp(Rs,"SocketContext: hardDisconnectSocket")}catch{}}function kUA(){const e=Rs;if(e){try{e.auth={}}catch{}try{e.__authSig=""}catch{}try{Fp(e,"SocketContext: logout refresh")}catch{}}}function MUA(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=$k(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 NUA(e){var A;if(Rs&&L6===e)return Rs;if(Rs){try{Rs.removeAllListeners()}catch{}try{EcA(Rs,"SocketContext: getSharedSocket replace")}catch{}Rs=null}Rs=MUA(e),L6=e;try{if(typeof window<"u"){(((A=window.location)==null?void 0:A.search)||"").includes("e2e=1")&&(window.__SOCKET=Rs,window.__sharedSocket=Rs,window.hardDisconnectSocket=wUA,window.suspendSocketAutoConnect=Q8);try{if(!window.__clientErrMon){window.__clientErrMon=!0;const i=g=>{try{const o=window.__sharedSocket||Rs;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,r;try{if(!g.error&&!g.message)return;const a=g.message||"";if(a.includes("websocket error")||a.includes("WebSocket"))return;i({message:a||"error",stack:(r=(s=(o=g.error)==null?void 0:o.stack)==null?void 0:s.slice)==null?void 0:r.call(s,0,5e3),filename:g.filename,line:g.lineno,col:g.colno,...n()})}catch{}}),window.addEventListener("unhandledrejection",g=>{var o,s,r,a,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:((r=l==null?void 0:l.slice)==null?void 0:r.call(l,0,500))||"unhandledrejection",stack:(I=(a=(c==null?void 0:c.stack)||"").slice)==null?void 0:I.call(a,0,5e3),...n()})}catch{}}),Rs.on("connect",()=>{try{const g=Rs,o=g==null?void 0:g.__pendingClientErrors;Array.isArray(o)&&o.length&&o.splice(0,o.length).forEach(r=>{try{g.emit("client_error",r)}catch{}})}catch{}})}}catch{}}}catch{}return Rs}function RUA({children:e}){const{user:A,initialized:t}=en(),i=gr(),n=E.useMemo(()=>NUA(i),[i]),{resetSpin:g}=MB();return E.useEffect(()=>{if(!t)return;let o=!1;return(async()=>{const s=I=>{try{n.__authSig=I}catch{}},r=()=>{try{return String(n.__authSig||"")}catch{return""}},a=I=>{var B;const c=Math.max(0,lk-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 Co();if(o)return;if(I){const c=r(),l=`t:${I}`;n.auth={token:I};try{n.__allowCookieAuth=!1}catch{}if(s(l),n.disconnected)a(()=>{o||(qr(n,"SocketContext:auth-token-connect"),g())});else if(c!==l){const B=Date.now();B-ub>=x6&&(ub=B,a(()=>{if(!o){try{Fp(n,"SocketContext: auth change soft reconnect")}catch{}setTimeout(()=>{o||(qr(n,"SocketContext:auth-change-reconnect"),g())},100)}}))}}else{const c=r(),l="c:*";try{n.auth={}}catch{}try{n.__allowCookieAuth=!0}catch{}if(s(l),n.disconnected)a(()=>{o||(qr(n,"SocketContext:cookie-session-connect",{allowCookieSession:!0}),g())});else if(c!==l){const B=Date.now();B-ub>=x6&&(ub=B,a(()=>{if(!o){try{Fp(n,"SocketContext: cookie auth soft reconnect")}catch{}setTimeout(()=>{o||(qr(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()<lk)return;const s=await Co();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 r=async a=>{if(String((a==null?void 0:a.message)||"")==="INVALID_TOKEN"){try{n.disconnect()}catch{}try{await wd()}catch{}if(!o){try{n.auth={},n.__authSig="c:*",n.__allowCookieAuth=!!A}catch{}A&&(s=setTimeout(()=>{o||qr(n,"SocketContext:invalid-token-cookie-fallback",{allowCookieSession:!0})},hcA+100))}}};return n.on("connect_error",r),()=>{o=!0,s&&clearTimeout(s),n.off("connect_error",r)}},[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()<lk)&&n.disconnected){try{const l=await Co();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);qr(n,"SocketContext:refreshAuthAndConnect",{allowCookieSession:l}),g()}}},r=()=>{try{document.visibilityState==="visible"&&s()}catch{}},a=()=>s(),I=()=>s(),c=()=>s();return window.addEventListener("visibilitychange",r),window.addEventListener("focus",a),window.addEventListener("pageshow",I),window.addEventListener("online",c),()=>{o=!0,window.removeEventListener("visibilitychange",r),window.removeEventListener("focus",a),window.removeEventListener("pageshow",I),window.removeEventListener("online",c)}},[n,g,A]),E.useEffect(()=>{const o=()=>{try{n.removeAllListeners()}catch{}try{EcA(n,"SocketContext: beforeunload")}catch{}};return window.addEventListener("beforeunload",o),()=>{window.removeEventListener("beforeunload",o)}},[n]),E.useEffect(()=>{let o=!1;const s=5e3,r=15e3,a=2e3;let I=!1;const l=setInterval(()=>{var p;if(o)return;try{if(document.visibilityState==="hidden")return}catch{}if(Date.now()<lk||!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);qr(n,"SocketContext:health-poll-disconnected",{allowCookieSession:y})}catch{}return}if(Q&&Date.now()-Q<r)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);qr(n,"SocketContext:health-poll-timeout-reconnect",{allowCookieSession:y})}catch{}},100)}},a);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(B8.Provider,{value:n,children:e})}function Ss(){const e=E.useContext(B8);if(!e)throw new Error("useSocket must be used within a SocketProvider");return e}const fcA=E.createContext({user:null,loading:!0,initialized:!1,refreshUser:async()=>{},logout:async()=>{},meId:"",updateBalance:()=>{}}),en=()=>E.useContext(fcA);function GUA(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 bUA=({children:e})=>{const[A,t]=E.useState(null),[i,n]=E.useState(""),[g,o]=E.useState(!0),[s,r]=E.useState(!1),a=ms(),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(a.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),r(!0);return}const m=async()=>{t(null),n("");try{e2(null)}catch{}};o(!0);const D=(async()=>{try{const k=await hL(),N=GUA(k);if(N){SUA(),t(N),n((N==null?void 0:N.id)||"");try{e2(N.id||null)}catch{}}else await m()}catch{if(!c.current)return;await m()}finally{o(!1),r(!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{Q8(2500)}catch{}d&&await AcA(d);try{await fetch("/api/auth/clear",{method:"POST",credentials:"include"})}catch{}}finally{if(!c.current)return;try{await wd()}catch{}try{await mbA()}catch{}t(null),n("");try{e2(null)}catch{}try{kUA()}catch{}try{(await li(()=>Promise.resolve().then(()=>wke),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(fcA.Provider,{value:h,children:e})},UUA=(()=>{var e,A;try{return(A=(e=import.meta)==null?void 0:e.env)==null?void 0:A.VITE_APP_TARGET}catch{return}})();function vUA(){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 KUA(e){var A;try{(A=window.localStorage)==null||A.setItem("app_target_lock",e)}catch{}}const T6=(()=>{try{return ti.getPlatform()}catch{return"web"}})(),ycA=vUA()??UUA??Fs;(T6==="ios"||T6==="android")&&KUA(ycA);const u8=ycA,Dm=u8==="zentara";function FUA(){return u8}if(typeof document<"u"){const A={zentara:"zentara-body"}[u8];if(A){const t=()=>{var i;(i=document.body)==null||i.classList.add(A)};document.body?t():document.addEventListener("DOMContentLoaded",t,{once:!0})}}function Zr({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}=en(),i=ms(),g=new URLSearchParams(i.search).get("e2e")==="1",o=i.pathname||"",s=/^\/poker\/room\//.test(o),r=/^\/room\//.test(o),a=/^\/(lobby|zentara\/)/.test(o);return!t||A?C.jsxs("div",{className:"HomeScreen theme-casino home-fixed-root",children:[C.jsx(Zr,{className:"page-home-screen"}),C.jsx("div",{className:"home-preloader",children:C.jsx("div",{className:"home-preloader__spinner"})})]}):!e&&!g&&!(s||r||a)?C.jsx(Fg,{to:"/lobby",replace:!0,state:{from:i}}):C.jsx(YCA,{})}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 _UA({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]),r=E.useCallback((I,c={})=>g({message:I,variant:"info",...c}),[g]),a=E.useMemo(()=>({show:g,success:o,error:s,info:r,dismiss:n}),[g,o,s,r,n]);return C.jsxs(DcA.Provider,{value:a,children:[e,zr.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 NB(){const e=E.useContext(DcA);if(!e){const A=()=>"noop";return{show:()=>"noop",success:A,error:A,info:A,dismiss:()=>{}}}return e}const mcA={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(mcA);const Kt=new Proxy(mcA,{set(){throw new TypeError("SocketEvents is read-only")},defineProperty(){throw new TypeError("SocketEvents is read-only")},deleteProperty(){throw new TypeError("SocketEvents is read-only")}}),JUA="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=",q6="/assets/flash-1UjQ_pjl.m4a",Y6="/assets/swoosh-DWLYYP2o.m4a",ScA="/assets/dice_whirr_merged-kYY8GDzo.m4a",LUA="/assets/loss-MbFJ6Xyb.m4a",xUA="/assets/winner-C_feQyA8.m4a",TUA="/assets/win-BofsSXdy.m4a",qUA="/assets/ante_up-BNJNkzdg.m4a",YUA="/assets/push-D8ciTeGD.m4a",HUA="/assets/your_turn-r-y-lDUH.m4a",OUA="/assets/point_set-BYYb2H7O.m4a",PUA="/assets/place_hit-B397CGff.m4a",jUA="/assets/yes-D6HNwLBK.m4a",zUA="/assets/smashing-CDhgl1WN.m4a",ZUA="/assets/love_you-ClILzZiq.m4a",WUA="/assets/gangster-BuThOTHu.m4a",VUA="/assets/skills_win-B9044Qtf.m4a",XUA="/assets/skills_lose-C2hT1pjV.m4a",wcA="/assets/skills_lobby-Wq3LgbVY.m4a",$UA="/assets/zentara_theme-CMLmkTk1.m4a",AvA="/assets/zentara_explosion1-CjEhUDBF.mp3",evA="/assets/zentara_explosion2-C8nIQN_s.mp3",tvA="/assets/zentara_explosion3-BTB3rcDN.mp3",ivA="/assets/zentara_fanfare-BovxnerY.mp3",nvA="data:audio/mpeg;base64, ",gvA="/assets/zentara_scan-DPmtrIPS.mp3",ovA="/assets/zentara_move-B9jZ_pmx.mp3",Ff=typeof navigator<"u"&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1),vE=typeof window<"u"?window.Capacitor:void 0,yL=!!vE&&typeof vE.isNativePlatform=="function"&&vE.isNativePlatform();var QrA;const vn=vE&&(((QrA=vE.Plugins)==null?void 0:QrA.NativeAudio)||vE.NativeAudio)||void 0,kd=yL&&!!vn,mS=yL&&Ff,svA=yL&&!Ff;let Wr=!1,II=!0,AN=null;const d8=500;function rvA(){return!!II}function H6(e){if(II=!!e,!II)try{wF(),nN()}catch{}}const avA=["vYes","vSmashing","vLove","vGangster"],ka={click:JUA,flash:q6,chip:Y6,win:xUA,winDing:TUA,lose:LUA,push:YUA,cardSwoosh:Y6,placeBets:qUA,yourTurn:HUA,vYes:jUA,vSmashing:zUA,vLove:ZUA,vGangster:WUA,pointSet:OUA,placeHit:PUA,betPlaced:q6,skillsWin:VUA,skillsLose:XUA,skillsLobby:wcA,zentaraExplosion1:AvA,zentaraExplosion2:evA,zentaraExplosion3:tvA,zentaraFanfare:ivA,zentaraLaser:nvA,zentaraScan:gvA,zentaraFuture:ovA},O6=["flash","win","winDing","lose","push","chip","cardSwoosh","placeBets","yourTurn","pointSet","vYes","vSmashing","vLove","vGangster","placeHit"],IvA=3,CvA=4,kcA=4,McA=6,cvA=e=>e==="zentaraLaser"?McA:e.startsWith("zentaraExplosion")?kcA:1,NcA=mS?1:Ff?2:8;let s2=0,h8=!1;function RcA(){const e=performance.now();h8=s2>0&&e-s2>50,s2=e,requestAnimationFrame(RcA)}typeof requestAnimationFrame<"u"&&requestAnimationFrame(RcA);const GcA={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},DF={},ZE={};let nd=0,bcA=0;const r2=new WeakMap;let a2=!1;const P6=[];function eN(e){P6.push(e),!a2&&(a2=!0,requestAnimationFrame(()=>{a2=!1;const A=P6.splice(0);for(const t of A)t()}))}const YI=new Set,I2=new Map,tN=new Map;function gd(e){const A=Date.now(),t=tN.get(e)||{count:0,last:0};t.count=Math.min(5,t.count+1),t.last=A,tN.set(e,t)}function DL(e){e?tN.delete(e):tN.clear()}function mL(e){const A=tN.get(e);if(!A)return!0;const t=Date.now(),i=2e3*Math.min(3,A.count);return t-A.last>i}function lvA(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 mF=new Map,j6=mS?100:20;async function BvA(e){if(!(vn!=null&&vn.getDuration))return!0;try{const A=await vn.getDuration({assetId:e});return A&&typeof A.duration=="number"&&A.duration>0}catch{return!1}}async function iN(e,A){if(!kd||!vn)throw new Error("Native audio not available");if(YI.has(e))return;const t=I2.get(e);if(t){if(await t,!YI.has(e))throw new Error("Asset preload failed");return}try{const i=lvA(A);if(!i)throw gd(e),new Error("Failed to resolve asset path");const n=(async()=>{await vn.preload({assetId:e,assetPath:i.path,audioChannelNum:cvA(e)}),YI.add(e),mF.set(e,Date.now())})();I2.set(e,n),await n.finally(()=>{I2.delete(e)})}catch(i){throw gd(e),i}}async function EvA(e,A,t){if(!kd||!vn)throw new Error("Native audio not available");if(!mL(e))throw new Error("Native audio cooldown active");try{if(await iN(e,A),!YI.has(e))throw new Error("Asset not loaded");const i=mF.get(e)||0,n=Date.now()-i;if(n<j6&&await new Promise(g=>setTimeout(g,j6-n)),mS&&!await BvA(e)){try{await vn.unload({assetId:e})}catch{}throw YI.delete(e),mF.delete(e),new Error("Asset verification failed - native player not ready")}if((t==null?void 0:t.volume)!=null&&vn.setVolume)try{await vn.setVolume({assetId:e,volume:Vr(t.volume,0,1)})}catch{}try{await vn.play({assetId:e})}catch{await new Promise(o=>setTimeout(o,30)),await vn.play({assetId:e})}t!=null&&t.durationMs&&t.durationMs>0&&window.setTimeout(()=>{try{vn.stop({assetId:e})}catch{}},Math.max(10,Math.floor(t.durationMs)))}catch(i){throw gd(e),i}}function p8(e){const A=new Audio(ka[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",()=>iB(e,A)),A}function Md(e){let A=ZE[e];if(!A){const t=UcA(e);A={free:[],busy:new Set,size:0};for(let i=0;i<t;i++)A.free.push(p8(e)),A.size++;ZE[e]=A}return A}function UcA(e){return e==="flash"?CvA:e==="zentaraLaser"?McA:e.startsWith("zentaraExplosion")?kcA:IvA}function f8(e){const A=UcA(e),t=Md(e);if(t.free.length>0)return t.free.pop();if(t.size<A){const i=p8(e);return t.size++,i}return null}function iB(e,A){const t=ZE[e];t&&t.busy.has(A)&&(t.busy.delete(A),t.free.push(A),nd=Math.max(0,nd-1))}function y8(){Object.keys(GcA).forEach(e=>delete DF[e])}function QvA(){try{YI.clear(),mF.clear(),DL()}catch{}}function SL(e,A=800){const t=r2.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",r)}catch{}},s=()=>{g||(g=!0,o(),n(!0))},r=()=>{g||(g=!0,o(),n(!1))};e.addEventListener("canplaythrough",s,{once:!0}),e.addEventListener("loadeddata",s,{once:!0}),e.addEventListener("error",r,{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 r2.set(e,i),i.finally(()=>{r2.delete(e)}),i}let hb=null,ss=null,KE=null,SF=!1;function wF(){Object.keys(ZE).forEach(e=>{const A=ZE[e];A&&[...A.busy].forEach(t=>{try{t.pause(),t.currentTime=0}catch{}iB(e,t)})});try{hb&&(hb.pause(),hb.currentTime=0)}catch{}try{ss&&(ss.pause(),ss.currentTime=0)}catch{}hb=null,ss=null;try{}catch{}try{const e=Object.keys(ka);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}FE[A]&&(window.clearTimeout(FE[A]),delete FE[A])}if(kd&&vn){for(const A of Object.keys(ka))if(YI.has(A)){try{ZD(vn.stop({assetId:A}))}catch{}try{vn.unload&&ZD(vn.unload({assetId:A}))}catch{}try{YI.delete(A)}catch{}}if(YI.has("loop_dice_whirr")){try{ZD(vn.stop({assetId:"loop_dice_whirr"}))}catch{}try{vn.unload&&ZD(vn.unload({assetId:"loop_dice_whirr"}))}catch{}try{YI.delete("loop_dice_whirr"),DL("loop_dice_whirr")}catch{}}SF=!1}}catch{}nd=0,y8()}let vcA=!1;function eM(e){vcA=!!e}let z6=0;const uvA=1500;async function dvA(e,A){if(!II||vcA)return!1;const t=Date.now();if(t-z6<uvA)return!1;if(z6=t,mS&&vn&&mL(e))try{return(async()=>{try{if(await iN(e,ka[e]),YI.has(e)){if(vn.setVolume)try{await vn.setVolume({assetId:e,volume:Vr(A,0,1)})}catch{}await vn.play({assetId:e})}}catch{gd(e)}})(),!0}catch{gd(e)}if(!Wr||Ff&&h8)return!1;try{const i=f8(e);if(!i){const g=new Audio(ka[e]);return g.volume=As(e,A),g.play().catch(()=>{}),!0}return Md(e).busy.add(i),nd++,i.currentTime=0,i.volume=As(e,A),i.play().catch(()=>iB(e,i)),!0}catch{return!1}}const hvA={3:"vGangster",4:"vLove",5:"vSmashing",6:"vYes",7:"vSmashing"};async function Z6(e,A=.5){const t=hvA[e>=7?7:e];return t?dvA(t,A):!1}function wL(e,A){if(!II||!Wr||nd>=NcA)return;const t=f8(e);if(!t)return;Md(e).busy.add(t),nd++;try{t.currentTime=0,(A==null?void 0:A.volume)!=null&&(t.volume=As(e,A.volume)),(A==null?void 0:A.rate)!=null&&(t.playbackRate=Vr(A.rate,.25,4));const n=A!=null&&A.durationMs&&A.durationMs>0?window.setTimeout(()=>{try{t.pause(),t.currentTime=0}catch{}iB(e,t)},Math.max(10,Math.floor(A.durationMs))):null;eN(()=>{t.play().catch(()=>{n&&window.clearTimeout(n),iB(e,t)})})}catch{iB(e,t)}}async function _s(e,A){if(!II)return;const t=Date.now();if(t<bcA||Ff&&h8&&e!=="win"&&e!=="lose"&&!(mS&&e==="zentaraLaser"))return;const i=GcA[e]??0;if(i>0){const o=DF[e]??0;if(t-o<i)return}if(DF[e]=t,mS&&vn&&mL(e)){(async()=>{try{await EvA(e,ka[e],{volume:A==null?void 0:A.volume,durationMs:A==null?void 0:A.durationMs})}catch{gd(e)}})();return}if(!Wr||AN&&t-AN<d8)return;if(svA){wL(e,A);return}if(nd>=NcA)return;const n=f8(e);if(!n)return;Md(e).busy.add(n),nd++;try{n.currentTime=0,(A==null?void 0:A.volume)!=null&&(n.volume=As(e,A.volume)),(A==null?void 0:A.rate)!=null&&(n.playbackRate=Vr(A.rate,.25,4));const o=A!=null&&A.durationMs&&A.durationMs>0?window.setTimeout(()=>{try{n.pause(),n.currentTime=0}catch{}iB(e,n)},Math.max(10,Math.floor(A.durationMs))):null;if(!await SL(n,1e3)){eN(()=>{n.play().catch(()=>{o&&window.clearTimeout(o),iB(e,n)})});return}eN(()=>{n.play().catch(()=>{o&&window.clearTimeout(o),iB(e,n)})})}catch{iB(e,n)}}const Vr=(e,A,t)=>Math.min(t,Math.max(A,e)),pvA={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,lobbyMusic:.03};function As(e,A){const t=Vr(A,0,1);if(Ff){const i=pvA[e];if(typeof i=="number")return Vr(Math.max(t,i),0,1)}return t}function $1(){Ff&&(Object.keys(ZE).forEach(e=>{const A=e,t=ZE[A];t&&t.free.forEach(i=>{try{i.pause(),i.src=ka[A],i.load()}catch{}})}),y8())}function fvA(){try{wF()}catch{}try{Yu()}catch{}try{nN()}catch{}}function yvA(){QvA();try{$1()}catch{}y8()}var urA;try{const e=vE&&(((urA=vE.Plugins)==null?void 0:urA.App)||vE.App)||void 0;yL&&(e!=null&&e.addListener)&&e.addListener("appStateChange",A=>{!!(A&&A.isActive)?yvA():fvA()})}catch{}let kF=null,np=!1,vD=0,KcA=0;function C2(){return!kd||np}function DvA(){return{loaded:vD,total:KcA}}async function mvA(e=5e3){if(!kd||np||!kF)return!0;try{return await Promise.race([kF,new Promise((A,t)=>setTimeout(()=>t(new Error("timeout")),e))]),!0}catch{return!1}}async function qn(){if(!Wr){Wr=!0,AN=Date.now(),bcA=Date.now()+d8,Object.keys(ka).forEach(e=>{try{Md(e)}catch{}});try{SS()}catch{}try{if(kd&&vn){const e=Object.keys(ka);KcA=e.length,vD=0,np=!1,kF=(async()=>{for(const t of O6)try{await iN(t,ka[t]),vD++,await new Promise(i=>setTimeout(i,15))}catch{vD++}const A=e.filter(t=>!O6.includes(t));for(const t of A)try{await iN(t,ka[t]),vD++,await new Promise(i=>setTimeout(i,15))}catch{vD++}np=!0})(),kF.catch(()=>{np=!0})}else np=!0}catch{np=!0}}}function D8(){return!!Wr}function SS(e){const A=e&&e.length?e:Object.keys(ka);for(const t of A)Md(t).free.forEach(n=>{try{n.load()}catch{}})}async function MF(e,A=800){const t=e&&e.length?e:Object.keys(ka),i=g=>new Promise(o=>{try{const r=Md(g).free[0]||p8(g);SL(r,A).then(o)}catch{o(!1)}});return(await Promise.all(t.map(i))).every(Boolean)}if(typeof document<"u"){const e=()=>{document.visibilityState==="hidden"?(wF(),Yu(),nN()):$1()};document.addEventListener("visibilitychange",e),window.addEventListener("pagehide",()=>{wF(),Yu(),nN()}),window.addEventListener("pageshow",()=>$1())}function Xl(e){const t=Vr((e==null?void 0:e.volume)??.01,0,1)*.5;_s("flash",{volume:As("flash",t),rate:e==null?void 0:e.rate})}function SvA(e){_s("chip",{volume:As("chip",(e==null?void 0:e.volume)??.25),durationMs:(e==null?void 0:e.durationMs)??500,rate:e==null?void 0:e.playbackRate})}function wvA(e){_s("cardSwoosh",{volume:As("cardSwoosh",e==null?void 0:e.volume),rate:(e==null?void 0:e.playbackRate)??1})}function m8(e){_s("lose",{volume:As("lose",(e==null?void 0:e.volume)??.1)})}function FcA(e){_s("push",{volume:As("push",(e==null?void 0:e.volume)??.1)})}function kvA(e){const A=Vr(e==null?void 0:e.volume,0,1),t=As("win",A);_s("winDing",{volume:.025}),_s("win",{volume:As("win",Vr(t*.35,0,1))})}function AP(e){_s("winDing",{volume:As("winDing",(e==null?void 0:e.volume)??.15),rate:e==null?void 0:e.rate})}function eP(e){_s("placeBets",{volume:As("placeBets",(e==null?void 0:e.volume)??.65)})}function W6(e){_s("pointSet",{volume:As("pointSet",(e==null?void 0:e.volume)??.15)})}function MvA(e){_s("betPlaced",{volume:As("betPlaced",e==null?void 0:e.volume)})}function tP(e){_s("skillsWin",{volume:As("skillsWin",(e==null?void 0:e.volume)??.5)}),_s("win",{volume:As("win",.35)})}function iP(e){_s("skillsLose",{volume:As("skillsLose",(e==null?void 0:e.volume)??.4)})}let CE=null,nP=!1;function kL(e){if(!(!II||!Wr)&&!(nP&&CE))try{CE||(CE=new Audio(wcA),CE.loop=!0),CE.volume=As("lobbyMusic",(e==null?void 0:e.volume)??.075),CE.play().then(()=>{nP=!0}).catch(()=>{})}catch{}}function Yu(){if(CE)try{CE.pause(),CE.currentTime=0,nP=!1}catch{}}const NvA=.72,RvA={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 fw(e,A){const t=RvA[e];return Vr((A??t.defaultVolume)*t.trim*NvA,0,1)}let cE=null,gP=!1;function GvA(e){if(!(!II||!Wr)&&!(gP&&cE))try{cE||(cE=new Audio($UA),cE.loop=!0),cE.volume=As("lobbyMusic",fw("music",e==null?void 0:e.volume)),cE.play().then(()=>{gP=!0}).catch(()=>{})}catch{}}function nN(){if(cE)try{cE.pause(),cE.currentTime=0,gP=!1}catch{}}const V6=["zentaraExplosion1","zentaraExplosion2","zentaraExplosion3"];let c2=0;function Br(e){if(!II||!Wr)return;const A=V6[c2%V6.length];c2++,wL(A,{volume:fw("explosion",e==null?void 0:e.volume),rate:.96+c2%3*.035})}function X6(e){!II||!Wr||wL("zentaraFanfare",{volume:fw("fanfare",e==null?void 0:e.volume)})}function Lc(e){!II||!Wr||_s("zentaraLaser",{volume:fw("laser",e==null?void 0:e.volume)})}function tM(e){!II||!Wr||wL("zentaraScan",{volume:fw("scan",e==null?void 0:e.volume)})}function bvA(e){_s("zentaraFuture",{volume:fw("move",e==null?void 0:e.volume)})}function $6(e){const A=Vr((e==null?void 0:e.sfxVolume)??.15,0,1);_s("winDing",{volume:Vr(A*.25,0,1)}),window.setTimeout(()=>{_s("placeHit",{volume:As("placeHit",A)})},90)}async function _cA(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 r=g/10;if(e.volume=Math.max(0,o*(1-r)),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 UvA(e){if(!II)return;const A=Vr(e==null?void 0:e.volume,0,1),t=Vr(e==null?void 0:e.playbackRate,.25,4);let i=!1;if(kd&&vn&&mL("loop_dice_whirr")){try{iN("loop_dice_whirr",ScA).then(async()=>{try{if(SF||(vn.loop?await vn.loop({assetId:"loop_dice_whirr"}):await vn.play({assetId:"loop_dice_whirr"}),SF=!0),vn.setVolume)try{await vn.setVolume({assetId:"loop_dice_whirr",volume:A})}catch{}}catch{gd("loop_dice_whirr"),l2(A,t)}}).catch(()=>{gd("loop_dice_whirr"),l2(A,t)}),i=!0}catch{}if(i){try{KE&&window.clearTimeout(KE),KE=window.setTimeout(()=>{try{kC()}catch{}},8e3)}catch{}return}}Wr&&l2(A,t)}function l2(e,A){if(Wr)try{if(!ss){ss=new Audio(ScA),ss.loop=!0,ss.preload="auto";try{ss.playsInline=!0}catch{}SL(ss,800)}if(!ss.paused){ss.volume=e,ss.playbackRate=A;return}ss.volume=e,ss.playbackRate=A,ss.currentTime=0,eN(()=>{ss&&ss.play().catch(()=>{})}),KE&&window.clearTimeout(KE),KE=window.setTimeout(()=>{try{kC()}catch{}},8e3)}catch{}}function kC(){if(KE&&(window.clearTimeout(KE),KE=null),kd&&vn)try{try{ZD(vn.stop({assetId:"loop_dice_whirr"}))}catch{}try{vn.unload&&ZD(vn.unload({assetId:"loop_dice_whirr"}))}catch{}try{YI.delete("loop_dice_whirr"),DL("loop_dice_whirr")}catch{}SF=!1}catch{}try{ss&&_cA(ss,120)}catch{}}function ZD(e){try{return e&&typeof e.then=="function"?e.catch(()=>{}):Promise.resolve()}catch{return Promise.resolve()}}const yu={},FE={};function JcA(e,A){avA.includes(e)||_s(e,{volume:A==null?void 0:A.volume,rate:A==null?void 0:A.rate,durationMs:A==null?void 0:A.durationMs})}function vvA(e,A){if(!(!II||!Wr)&&!(AN&&Date.now()-AN<d8))try{let t=yu[e];if(!t){t=new Audio(ka[e]),t.loop=!0,t.preload="auto";try{t.playsInline=!0}catch{}yu[e]=t,SL(t,800)}const i=Vr((A==null?void 0:A.volume)??.1,0,1),n=Vr((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,eN(()=>{t.play().catch(()=>{})}),FE[e]&&window.clearTimeout(FE[e]);const g=Math.max(5e3,Math.min(6e4,(A==null?void 0:A.maxMs)??15e3));FE[e]=window.setTimeout(()=>{try{LcA(e)}catch{}},g)}catch{}}async function LcA(e){try{FE[e]&&(window.clearTimeout(FE[e]),delete FE[e]);const A=yu[e];if(!A)return;await _cA(A,120),yu[e]=null}catch{}}function B2(){try{qn()}catch{}}async function E2(e,A){try{if(e==="__probe__")return Promise.resolve(!!Wr);const t=e;return t in ka?A!=null&&A.loop?(vvA(t,{volume:A.volume,rate:A.rate}),!0):(JcA(t,{volume:A==null?void 0:A.volume,rate:A==null?void 0:A.rate}),!0):!1}catch{return!1}}function Q2(e){try{SS(e)}catch{}}function A7(e){try{const A=e;try{LcA(A)}catch{}const t=ZE[A];if(t){try{[...t.busy].forEach(i=>{try{i.pause(),i.currentTime=0}catch{}})}catch{}delete ZE[A]}try{delete DF[A]}catch{}try{YI.delete(A),DL(A)}catch{}try{Md(A)}catch{}}catch{}}const KvA=(()=>{var e,A;try{return!!((A=(e=import.meta)==null?void 0:e.env)!=null&&A.DEV)}catch{return!1}})(),Du=[];function oP(e,A){try{Du.push({event:e,ts:Date.now(),mode:A}),Du.length>12&&Du.shift()}catch{}}function Fl(){return[...Du]}function iM(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")):(qr(e,"emit.ensureConnected",{allowCookieSession:t}),new Promise((r,a)=>{var d;let I=!1;const c=()=>{I||(I=!0,Q(),r())},l=p=>{I||(I=!0,Q(),a(p??new Error("socket connect error")))},B=()=>{I||(I=!0,Q(),a(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 sP(e,A,t,i){var o,s,r,a,I,c,l,B;try{TcA(A)}catch{}const n=(i==null?void 0:i.timeoutMs)??15e3;try{await iM(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);qr(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}oP(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=(r=(s=(o=e==null?void 0:e.io)==null?void 0:o.engine)==null?void 0:s.transport)==null?void 0:r.name,p=(t==null?void 0:t.roomId)||null,y=((a=Du[Du.length-1])==null?void 0:a.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);qr(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 xcA(e,A,t){try{TcA(A)}catch{}try{await iM(e),oP(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);qr(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;oP(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(KvA)try{console.warn("[emitFF] unexpected error",{event:String(A),message:n,connected:!!e.connected})}catch{}return}}function TcA(e){new Set([Kt.ROLL_DICE,Kt.PLACE_MAIN_BET,Kt.CREATE_SIDE_BET,Kt.ACCEPT_SIDE_BET,Kt.CANCEL_SIDE_BET,Kt.POKER_ACT,"poker:start_hand","craps:roll"]).has(e)&&qn()}const qcA=gr();async function FvA(e,A,t="usd"){return await(await fetch(`${qcA}/api/payment/chips`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({amount:e,userId:A,currency:t})})).json()}async function _vA(e,A){return await(await fetch(`${qcA}/api/payment/membership`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({planId:e,userId:A})})).json()}const e7={createChipsCheckout:FvA,createMembershipCheckout:_vA},YcA=E.createContext(void 0),JvA=({children:e})=>{const[A,t]=E.useState("idle"),[i,n]=E.useState(null),[g,o]=E.useState(!1),[s,r]=E.useState(!1),a=E.useCallback(async(c,l,B="usd")=>{t("loading"),n(null);try{const Q=await e7.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 e7.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(YcA.Provider,{value:{status:A,error:i,startChipsCheckout:a,startMembershipCheckout:I,setStatus:t,setError:n,membershipModalOpen:g,setMembershipModalOpen:o,chipsModalOpen:s,setChipsModalOpen:r},children:e})};function bR(){const e=E.useContext(YcA);return e||{status:"idle",error:null,startChipsCheckout:async()=>null,startMembershipCheckout:async()=>null,setStatus:()=>{},setError:()=>{},membershipModalOpen:!1,setMembershipModalOpen:()=>{},chipsModalOpen:!1,setChipsModalOpen:()=>{}}}function bI(){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 r=Array.from(s,a=>a.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.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 LvA(e,A){const t=E.useCallback(async()=>{if(!e)throw new Error("Socket unavailable");if(e.connected)return e;try{!e.active&&e.disconnected&&qr(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 r=await t();let a=o;if(o&&typeof o=="object"&&!o.eventId)try{a={...o,eventId:bI()}}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()=>sP(r,g,a,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&&qr(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 xcA(s,g,o)},[t]);return{ack:i,send:n}}function So(){const e=Ss(),{info:A}=NB(),t=E.useRef(0),i=E.useCallback(kA=>{const oe=Date.now();if(!(oe-t.current<1200)){t.current=oe;try{A("Please wait a moment - you're doing that too quickly.",{duration:2500})}catch{}}},[A]),{ack:n,send:g}=LvA(e,i),{setMembershipModalOpen:o}=bR(),{user:s}=en(),r=E.useCallback(kA=>{const oe=(()=>{const $A={};try{if($A.name=String(kA.name||"").trim().slice(0,60),(kA.isPrivate===!0||kA.isPrivate===!1)&&($A.isPrivate=!!kA.isPrivate),(kA.singlePlayer===!0||kA.singlePlayer===!1)&&($A.singlePlayer=!!kA.singlePlayer),typeof kA.botsPerRoom=="number"&&Number.isInteger(kA.botsPerRoom)&&($A.botsPerRoom=kA.botsPerRoom),(kA.gameMode==="cee-lo"||kA.gameMode==="craps"||kA.gameMode==="zentara")&&($A.gameMode=kA.gameMode),typeof kA.botLevel=="number"&&kA.botLevel>=1&&kA.botLevel<=9&&($A.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&&($A.gameRules=nA)}}catch{}return $A})(),ae=Date.now();try{console.log("[socket][createRoom] emitting",{sanitized:oe,timestamp:ae})}catch{}return n(Kt.CREATE_ROOM,oe).then($A=>{var vA,FA;const nA=Date.now()-ae;try{console.log("[socket][createRoom] response",{ok:$A==null?void 0:$A.ok,roomId:((vA=$A==null?void 0:$A.room)==null?void 0:vA.roomId)??((FA=$A==null?void 0:$A.room)==null?void 0:FA.id),duration:nA,error:$A==null?void 0:$A.error,res:$A}),$A&&$A.ok===!1&&console.warn("[socket][createRoom] ack error",$A.error)}catch{}return $A})},[n,o,s]),a=E.useCallback(async kA=>{const oe=Date.now();console.log("[joinRoom] attempting join",{roomId:kA,timestamp:oe,socketConnected:e==null?void 0:e.connected});const ae=async()=>n(Kt.JOIN_ROOM,{roomId:kA});let $A=await ae();const nA=Date.now()-oe;if(console.log("[joinRoom] first attempt result",{roomId:kA,ok:$A==null?void 0:$A.ok,duration:nA,error:$A==null?void 0:$A.error}),$A&&$A.ok===!1&&/Room not found/i.test(String($A.error||""))){console.warn("[useSocketEmitters] Room not found on first join attempt, retrying...",{roomId:kA,res:$A,firstAttemptDuration:nA});try{await new Promise(te=>setTimeout(te,120))}catch{}const vA=Date.now();$A=await ae();const FA=Date.now()-vA;$A&&$A.ok===!1?console.error("[useSocketEmitters] Room not found after retry",{roomId:kA,res:$A,retryDuration:FA,totalDuration:Date.now()-oe}):console.log("[useSocketEmitters] Retry successful",{roomId:kA,retryDuration:FA,totalDuration:Date.now()-oe})}if($A&&$A.ok===!1&&$A.error===QGA.SOCKET.NEEDS_PREMIUM)try{o(!0)}catch{}return $A},[n,o]),I=E.useCallback(kA=>n(Kt.LEAVE_ROOM,{roomId:kA}),[n]),c=E.useCallback(kA=>g(Kt.LEAVE_ROOM,{roomId:kA}),[g]),l=E.useCallback((kA,oe,ae,$A,nA)=>n("skills:submit",{roomId:kA,path:oe,word:ae,tsClient:$A,seq:nA}),[n]),B=E.useCallback((kA,oe,ae,$A,nA)=>n("skills:tap",{roomId:kA,r:oe,c:ae,tsClient:$A,seq:nA}),[n]),Q=E.useCallback((kA,oe)=>n("anagrams:submit",{roomId:kA,word:oe}),[n]),h=E.useCallback((kA,oe,ae)=>n("trivia:answer",{roomId:kA,questionIndex:oe,answerIndex:ae}),[n]),d=E.useCallback(kA=>n(Kt.ROLL_DICE,{roomId:kA}),[n]),p=E.useCallback(kA=>n(Kt.CONFIRM_BETS,{roomId:kA}),[n]),y=E.useCallback((kA,oe)=>n(Kt.CRAPS_PLACE_PASS,{roomId:kA,amount:oe}),[n]);E.useCallback((kA,oe)=>n(Kt.CRAPS_PLACE_DONT_PASS,{roomId:kA,amount:oe}),[n]);const m=E.useCallback((kA,oe,ae)=>n(Kt.CRAPS_PLACE_ODDS,{roomId:kA,amount:oe,passType:ae}),[n]),D=E.useCallback((kA,oe,ae)=>n(Kt.CRAPS_PLACE_PLACE,{roomId:kA,amount:oe,point:ae}),[n]),S=E.useCallback((kA,oe)=>n(Kt.CRAPS_PLACE_FIELD,{roomId:kA,amount:oe}),[n]),k=E.useCallback((kA,oe,ae)=>n(Kt.CRAPS_PLACE_BIG,{roomId:kA,amount:oe,kind:ae}),[n]),N=E.useCallback((kA,oe)=>n(Kt.CRAPS_PLACE_COME,{roomId:kA,amount:oe}),[n]),G=E.useCallback((kA,oe)=>n(Kt.CRAPS_PLACE_DONT_COME,{roomId:kA,amount:oe}),[n]),M=E.useCallback((kA,oe,ae)=>n(Kt.CRAPS_PLACE_COME_ODDS,{roomId:kA,point:oe,amount:ae}),[n]),w=E.useCallback((kA,oe,ae)=>n(Kt.CRAPS_PLACE_DONT_COME_ODDS,{roomId:kA,point:oe,amount:ae}),[n]),b=E.useCallback((kA,oe)=>n(Kt.CRAPS_TOGGLE_PLACE_WORKING,{roomId:kA,working:oe}),[n]),_=E.useCallback(async kA=>{try{const oe=eA.current.get(kA)||[],ae=aA.current.get(kA);if(ae&&(clearTimeout(ae),aA.current.delete(kA)),oe.length>0)if(eA.current.delete(kA),oe.length>1)await n("craps:add_bets_batch",{roomId:kA,bets:oe,eventId:bI()});else{const{type:$A,amount:nA}=oe[0];await n("craps:add_bet",{roomId:kA,type:$A,amount:nA,eventId:bI()})}}catch{}try{const oe=pA.current.get(kA)||[],ae=gA.current.get(kA);if(ae&&(clearTimeout(ae),gA.current.delete(kA)),oe.length>0)if(pA.current.delete(kA),oe.length>1)await n("craps:remove_bets_batch",{roomId:kA,bets:oe,eventId:bI()});else{const{type:$A,amount:nA}=oe[0];await n("craps:remove_bet",{roomId:kA,type:$A,amount:nA,eventId:bI()})}}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(Kt.CRAPS_ROLL,{roomId:kA})},[n,_]),J=E.useCallback(kA=>n(Kt.CRAPS_READY,{roomId:kA}),[n]),T=E.useCallback((kA,oe)=>n(Kt.CRAPS_FETCH_HISTORY,{roomId:kA,...oe||{}}),[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]),q=E.useCallback(kA=>n("craps:pass_turn",{roomId:kA}),[n]),z=E.useCallback((kA,oe)=>n("craps:set_order",{roomId:kA,order:oe}),[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:bI()}),[n]),RA=E.useCallback((kA,oe,ae)=>{const $A=eA.current.get(kA)||[];$A.push({type:oe,amount:ae}),eA.current.set(kA,$A);const nA=aA.current.get(kA);nA&&clearTimeout(nA);const vA=setTimeout(()=>{const FA=eA.current.get(kA)||[];if(FA.length!==0)if(eA.current.delete(kA),aA.current.delete(kA),FA.length>1)n("craps:add_bets_batch",{roomId:kA,bets:FA,eventId:bI()});else{const{type:te,amount:bA}=FA[0];n("craps:add_bet",{roomId:kA,type:te,amount:bA,eventId:bI()})}},sA);return aA.current.set(kA,vA),Promise.resolve({ok:!0})},[n]),YA=E.useCallback((kA,oe)=>n("craps:add_bets_batch",{roomId:kA,bets:oe,eventId:bI()}),[n]),W=E.useCallback((kA,oe)=>n("craps:remove_bets_batch",{roomId:kA,bets:oe,eventId:bI()}),[n]),$=E.useCallback((kA,oe,ae)=>{const $A=pA.current.get(kA)||[];$A.push({type:oe,amount:ae}),pA.current.set(kA,$A);const nA=gA.current.get(kA);nA&&clearTimeout(nA);const vA=setTimeout(()=>{const FA=pA.current.get(kA)||[];if(FA.length!==0)if(pA.current.delete(kA),gA.current.delete(kA),FA.length>1)n("craps:remove_bets_batch",{roomId:kA,bets:FA,eventId:bI()});else{const{type:te,amount:bA}=FA[0];n("craps:remove_bet",{roomId:kA,type:te,amount:bA,eventId:bI()})}},yA);return gA.current.set(kA,vA),Promise.resolve({ok:!0})},[n]),L=E.useCallback(kA=>n("craps:clear_bets",{roomId:kA,eventId:bI()}),[n]),H=E.useCallback(kA=>n("craps:summarize",{roomId:kA}),[n]),P=E.useCallback(kA=>n(Kt.BANKER_GIVE_UP,{roomId:kA}),[n]),tA=E.useCallback(async()=>{const kA=async()=>n(Kt.GET_ROOMS_LIST,{});let oe=await kA();return oe&&oe.ok===!1&&oe.error==="invalid_payload"&&(await new Promise(ae=>setTimeout(ae,80)),oe=await kA()),oe},[n]),iA=E.useCallback((kA,oe)=>n(Kt.SPECTATE_SET,{roomId:kA,spectate:oe}),[n]),oA=E.useCallback(async(kA,oe)=>{const ae=await n(Kt.PLACE_MAIN_BET,{roomId:kA,amount:oe});try{tf("bet_place",{game:"cee-lo",type:"MAIN",amount:oe})}catch{}return ae},[n]),CA=E.useCallback((kA,oe)=>n(Kt.CANCEL_MAIN_BET,{roomId:kA,wagerId:oe}),[n]),cA=E.useCallback((kA,oe)=>n(Kt.CREATE_SIDE_BET,{roomId:kA,...oe}),[n]),_A=E.useCallback((kA,oe)=>n(Kt.ACCEPT_SIDE_BET,{roomId:kA,wagerId:oe}),[n]),uA=E.useCallback((kA,oe)=>n(Kt.CANCEL_SIDE_BET,{roomId:kA,wagerId:oe}),[n]),X=E.useCallback(async kA=>{if(!kA)return{ok:!1,error:"no_room"};const oe={roomId:kA};try{console.debug("[socket][getWagers] emit",oe)}catch{}const ae=await n(Kt.GET_WAGERS,oe);if(ae&&ae.ok===!1)try{console.warn("[socket][getWagers] ack error",ae.error)}catch{}return ae},[n]),O=E.useCallback(kA=>n(Kt.RTC_JOIN,{roomId:kA}),[n]),lA=E.useCallback(kA=>{var oe,ae;try{(ae=(oe=e==null?void 0:e.volatile)==null?void 0:oe.emit)==null||ae.call(oe,Kt.RTC_LEAVE,{roomId:kA})}catch{}},[e]),wA=E.useCallback(async(kA,oe,ae)=>{try{await g(Kt.RTC_SIGNAL,{roomId:kA,toPeerId:oe,payload:ae})}catch($A){const nA=String(($A==null?void 0:$A.message)||$A||"");if(/disconnect|timeout|transport/i.test(nA)){await new Promise(vA=>setTimeout(vA,200));try{await g(Kt.RTC_SIGNAL,{roomId:kA,toPeerId:oe,payload:ae})}catch{}}}},[g]),xA=E.useCallback((kA,oe)=>n(Kt.RTC_SET_CAMERA_OWNER,{roomId:kA,ownerId:oe}),[n]),HA=E.useCallback(async(kA,oe)=>{try{if(!kA)return{ok:!1,error:"no_room"};const ae=await n(Kt.RTC_SET_VIDEO_ENABLED,{roomId:kA,enabled:oe});return ae.ok||console.error("Failed to set video enabled:",ae.error),ae}catch(ae){console.error("Error setting video enabled:",ae)}},[n,o]),zA=E.useCallback((kA,oe)=>n(Kt.ROOM_SEND_MESSAGE,{roomId:kA,text:oe}),[n]),ne=E.useCallback((kA,oe)=>n(Kt.ROOM_FETCH_HISTORY,{roomId:kA,sinceTs:oe}),[n]),ye=E.useCallback((kA,oe)=>n(Kt.DM_SEND_MESSAGE,{toUserId:kA,text:oe}),[n]),Ee=E.useCallback((kA,oe)=>n(Kt.DM_FETCH_HISTORY,{peerUserId:kA,sinceTs:oe}),[n]),NA=E.useCallback(()=>n(Kt.LOBBY_JOIN,{}),[n]),QA=E.useCallback(()=>g(Kt.LOBBY_LEAVE,{}),[g]),PA=E.useCallback(()=>n(Kt.LOBBY_LIST,{}),[n]),VA=E.useCallback(kA=>n(Kt.DELETE_ROOM,{roomId:kA}),[n]),KA=E.useCallback(()=>n(Kt.USER_GET_BALANCE,void 0),[n]),Ie=E.useCallback((kA,oe)=>n(Kt.SEND_FRIEND_REQUEST,{toUserId:kA,message:oe}),[n]),DA=E.useCallback(kA=>n(Kt.CANCEL_FRIEND_REQUEST,{requestId:kA}),[n]),IA=E.useCallback((kA,oe)=>n(Kt.RESPOND_FRIEND_REQUEST,{requestId:kA,action:oe}),[n]),EA=E.useCallback(kA=>n(Kt.UNFRIEND,{otherId:kA}),[n]),j=E.useCallback(kA=>n(Kt.BLOCK_USER,{blockedId:kA}),[n]),dA=E.useCallback(kA=>n(Kt.UNBLOCK_USER,{blockedId:kA}),[n]),hA=E.useCallback(()=>n(Kt.SOCIAL_GET_LIST,void 0),[n]),UA=E.useCallback((kA,oe,ae)=>n(Kt.GAME_INVITE_SEND,{roomId:kA,toUserId:oe,gameMode:ae}),[n]),TA=E.useCallback((kA,oe)=>n(Kt.GAME_INVITE_RESPOND,{inviteId:kA,action:oe}),[n]),se=E.useCallback((kA,oe)=>n(Kt.QUICK_MATCH_JOIN,{gameMode:kA,botsPerRoom:oe}),[n]),Ne=E.useCallback(()=>n(Kt.QUICK_MATCH_LEAVE,void 0),[n]),Ke=E.useCallback(()=>n(Kt.QUICK_MATCH_STATUS,void 0),[n]),At=E.useCallback(()=>n(Kt.SOCIAL_ONLINE_FRIENDS,void 0),[n]),ni=E.useCallback(kA=>n(Kt.USER_UPDATE_PROFILE,kA),[n]),Ge=E.useCallback(kA=>n(Kt.BOTS_NUDGE,{roomId:kA??null}),[n]),st=E.useCallback(kA=>n(Kt.ROOM_REFRESH_STATE,{roomId:kA??null}),[n]),Rt=E.useCallback((kA,oe)=>g("player:visibility",{roomId:kA,visible:oe}),[g]),Et=E.useCallback(async(kA,oe,ae,$A,nA)=>n("skills:single_start",{stake:kA,gameMode:oe,duration:ae,botLevel:$A,autoplay:nA}),[n]),_t=E.useCallback(async(kA,oe,ae)=>n("skills:autoplay_start",{gameMode:kA,duration:oe,botLevel:ae}),[n]),vt=E.useCallback(async kA=>n("skills:ready",{roomId:kA}),[n]),xt=E.useCallback(async kA=>n("skills:room_create",kA),[n]),ee=E.useCallback(async kA=>n("skills:join_room",{roomId:kA}),[n]),Oe=E.useCallback(async kA=>n("skills:leave_room",{roomId:kA}),[n]),We=E.useCallback(async kA=>n("skills:spectator_join",{roomId:kA}),[n]),pt=E.useCallback(async kA=>n("skills:spectator_leave",{roomId:kA}),[n]);return{createRoom:r,joinRoom:a,leaveRoom:I,leaveRoomTearDown:c,getRoomsList:tA,setSpectate:iA,bankerGiveUp:P,pokerCreateRoom:E.useCallback(kA=>{const oe={...kA};let ae=oe.maxPlayers;if((typeof ae!="number"||!Number.isInteger(ae)||ae<1||ae>4)&&(ae=oe.singlePlayer?1:4),oe.maxPlayers=ae,typeof oe.startingStack=="number"){const $A=Math.max(500,Math.min(1e6,Math.floor(oe.startingStack)));oe.startingStack=$A}oe.eliminationMode?oe.eliminationMode={enabled:!0}:delete oe.eliminationMode,typeof oe.botLevel=="number"&&oe.botLevel>=1&&oe.botLevel<=9||delete oe.botLevel;try{console.debug("[socket][pokerCreateRoom] emitting",oe)}catch{}return n(Kt.POKER_ROOM_CREATE,oe)},[n,s,o]),pokerDeleteRoom:E.useCallback(kA=>n(Kt.POKER_ROOM_DELETE,{roomId:kA}),[n]),pokerJoinRoom:E.useCallback(async kA=>n(Kt.POKER_JOIN_ROOM,{roomId:kA}),[n]),pokerStartHand:E.useCallback(kA=>n(Kt.POKER_START_HAND,{roomId:kA}),[n]),pokerFold:E.useCallback(kA=>n(Kt.POKER_ACT,{roomId:kA,action:"fold"}),[n]),pokerCheck:E.useCallback(kA=>n(Kt.POKER_ACT,{roomId:kA,action:"check"}),[n]),pokerCall:E.useCallback(kA=>n(Kt.POKER_ACT,{roomId:kA,action:"call"}),[n]),pokerBet:E.useCallback((kA,oe)=>n(Kt.POKER_ACT,{roomId:kA,action:"bet",amount:oe}),[n]),pokerRaise:E.useCallback((kA,oe)=>n(Kt.POKER_ACT,{roomId:kA,action:"raise",amount:oe}),[n]),pokerFetchHistory:E.useCallback((kA,oe,ae)=>n(Kt.POKER_FETCH_HISTORY,{roomId:kA,limit:oe,beforeSeq:ae}),[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:T,crapsGetState:v,crapsJoinOrder:U,crapsLeaveOrder:x,crapsPassTurn:q,crapsSetOrder:z,crapsResetShooter:Z,crapsListBets:fA,crapsAddBet:RA,crapsBatchAddBets:YA,crapsRemoveBet:$,crapsBatchRemoveBets:W,crapsClearBets:L,crapsSummarizeBets:H,placeMainBet:oA,cancelMainBet:CA,createSideBet:cA,acceptSideBet:_A,cancelSideBet:uA,getWagers:X,rtcJoin:O,rtcLeave:lA,rtcSignal:wA,rtcSetCameraOwner:xA,rtcSetVideoEnabled:HA,roomSendMessage:zA,roomFetchHistory:ne,dmSendMessage:ye,dmFetchHistory:Ee,lobbyJoin:NA,lobbyLeave:QA,lobbyList:PA,deleteRoom:VA,getUserBalance:KA,sendFriendRequest:Ie,cancelFriendRequest:DA,respondFriendRequest:IA,unfriend:EA,blockUser:j,unblockUser:dA,getFriendsList:hA,sendGameInvite:UA,respondGameInvite:TA,quickMatchJoin:se,quickMatchLeave:Ne,quickMatchStatus:Ke,getOnlineFriends:At,updateProfile:ni,botsNudge:Ge,refreshRoomState:st,sendVisibilityChange:Rt,skillsSubmit:l,skillsTap:B,skillsSingleStart:Et,skillsAutoplayStart:_t,skillsReady:vt,skillsRoomCreate:xt,skillsJoinRoom:ee,skillsLeaveRoom:Oe,skillsSpectatorJoin:We,skillsSpectatorLeave:pt,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 xs(e){const A=Ss(),t=E.useRef(e);E.useEffect(()=>{t.current=e},[e]),E.useEffect(()=>{var s,r;if(typeof window>"u"||!(((r=(s=window.location)==null?void 0:s.search)==null?void 0:r.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(a,I){const c=this[a];c.push(I),c.length>20&&c.shift()}}}),(()=>{const a=n.__crapsHandlers||{};a&&a.__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 a.onCrapsRollResult=="function"&&a.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 a.onCrapsBetResults=="function"&&a.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 a.onCrapsPointSet=="function"&&a.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 a.onCrapsPointMade=="function"&&a.onCrapsPointMade(I)}catch{}},__wrappedByBus:!0})})();const o={onCrapsRollResult:a=>{var I,c;return(c=(I=t.current).onCrapsRollResult)==null?void 0:c.call(I,a)},onCrapsBetResults:a=>{var I,c;return(c=(I=t.current).onCrapsBetResults)==null?void 0:c.call(I,a)},onCrapsPointSet:a=>{var I,c;return(c=(I=t.current).onCrapsPointSet)==null?void 0:c.call(I,a)},onCrapsPointMade:a=>{var I,c;return(c=(I=t.current).onCrapsPointMade)==null?void 0:c.call(I,a)}};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 a=n.__crapsHandlersBus._buffer;if(a){for(const I of a.onCrapsRollResult)try{o.onCrapsRollResult(I)}catch{}for(const I of a.onCrapsBetResults)try{o.onCrapsBetResults(I)}catch{}for(const I of a.onCrapsPointSet)try{o.onCrapsPointSet(I)}catch{}for(const I of a.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=IA=>{var EA,j;return(j=(EA=t.current).onLobbyRooms)==null?void 0:j.call(EA,IA)},n=IA=>{var EA,j;return(j=(EA=t.current).onRoomCreated)==null?void 0:j.call(EA,IA)},g=IA=>{var EA,j;return(j=(EA=t.current).onRoomUpdated)==null?void 0:j.call(EA,IA)},o=IA=>{var EA,j;return(j=(EA=t.current).onRoomDeleted)==null?void 0:j.call(EA,IA)},s=IA=>{var EA,j;return(j=(EA=t.current).onJoinedRoom)==null?void 0:j.call(EA,IA)},r=IA=>{var EA,j;return(j=(EA=t.current).onRejoinedRoom)==null?void 0:j.call(EA,IA)},a=IA=>{var EA,j,dA,hA,UA,TA,se;console.log("[socket] received other_player_joined_room",{roomId:(EA=IA==null?void 0:IA.room)==null?void 0:EA.id,playersCount:(dA=(j=IA==null?void 0:IA.room)==null?void 0:j.players)==null?void 0:dA.length,playerIds:(UA=(hA=IA==null?void 0:IA.room)==null?void 0:hA.players)==null?void 0:UA.map(Ne=>Ne==null?void 0:Ne.id)}),(se=(TA=t.current).onOtherPlayerJoined)==null||se.call(TA,IA)},I=IA=>{var EA,j,dA,hA,UA,TA,se;console.log("[socket] received other_player_left_room",{roomId:(EA=IA==null?void 0:IA.room)==null?void 0:EA.id,playersCount:(dA=(j=IA==null?void 0:IA.room)==null?void 0:j.players)==null?void 0:dA.length,playerIds:(UA=(hA=IA==null?void 0:IA.room)==null?void 0:hA.players)==null?void 0:UA.map(Ne=>Ne==null?void 0:Ne.id)}),(se=(TA=t.current).onOtherLeft)==null||se.call(TA,IA)},c=IA=>{var EA,j;return(j=(EA=t.current).onBankerChanged)==null?void 0:j.call(EA,IA)},l=IA=>{var EA,j;return(j=(EA=t.current).onDiceRolled)==null?void 0:j.call(EA,IA)},B=()=>{var IA,EA;return(EA=(IA=t.current).onNotYourTurn)==null?void 0:EA.call(IA)},Q=IA=>{var EA,j;return(j=(EA=t.current).onOtaUpdateAvailable)==null?void 0:j.call(EA,IA)},h=IA=>{var EA,j;return(j=(EA=t.current).onBetsUpdated)==null?void 0:j.call(EA,IA)},d=IA=>{var EA,j;return(j=(EA=t.current).onGetWagers)==null?void 0:j.call(EA,IA)},p=IA=>{var EA,j;return(j=(EA=t.current).onPlayerBalanceUpdated)==null?void 0:j.call(EA,IA)},y=IA=>{var EA,j;return(j=(EA=t.current).onSideBetCreated)==null?void 0:j.call(EA,IA)},m=IA=>{var EA,j;return(j=(EA=t.current).onSideBetAccepted)==null?void 0:j.call(EA,IA)},D=IA=>{var EA,j;return(j=(EA=t.current).onSideBetCanceled)==null?void 0:j.call(EA,IA)},S=IA=>{var EA,j;return(j=(EA=t.current).onForceLogout)==null?void 0:j.call(EA,IA)},k=IA=>{var EA,j;return(j=(EA=t.current).onError)==null?void 0:j.call(EA,IA)},N=IA=>{var EA,j;return(j=(EA=t.current).onRtcSignal)==null?void 0:j.call(EA,IA)},G=IA=>{var EA,j;return(j=(EA=t.current).onRtcPeerJoined)==null?void 0:j.call(EA,IA)},M=IA=>{var EA,j;return(j=(EA=t.current).onRtcPeerLeft)==null?void 0:j.call(EA,IA)},w=IA=>{var EA,j;return(j=(EA=t.current).onRtcCameraOwnerChanged)==null?void 0:j.call(EA,IA)},b=IA=>{var EA,j;return(j=(EA=t.current).onRtcVideoEnabled)==null?void 0:j.call(EA,IA)},_=IA=>{var EA,j;return(j=(EA=t.current).onRoomMessage)==null?void 0:j.call(EA,IA)},K=IA=>{var EA,j;return(j=(EA=t.current).onRoomHistory)==null?void 0:j.call(EA,IA)},J=IA=>{var EA,j;return(j=(EA=t.current).onDmMessage)==null?void 0:j.call(EA,IA)},T=IA=>{var EA,j;return(j=(EA=t.current).onDmHistory)==null?void 0:j.call(EA,IA)},v=IA=>{var EA,j;return(j=(EA=t.current).onFairnessReveal)==null?void 0:j.call(EA,IA)},U=IA=>{var EA,j;return(j=(EA=t.current).onFriendRequestReceived)==null?void 0:j.call(EA,IA)},x=IA=>{var EA,j;return(j=(EA=t.current).onFriendRequestCancelled)==null?void 0:j.call(EA,IA)},q=IA=>{var EA,j;return(j=(EA=t.current).onFriendRequestResponded)==null?void 0:j.call(EA,IA)},z=IA=>{var EA,j;return(j=(EA=t.current).onUnfriended)==null?void 0:j.call(EA,IA)},Z=IA=>{var EA,j;return(j=(EA=t.current).onUserBlocked)==null?void 0:j.call(EA,IA)},eA=IA=>{var EA,j;return(j=(EA=t.current).onUserUnblocked)==null?void 0:j.call(EA,IA)},aA=IA=>{var EA,j;return(j=(EA=t.current).onGameInviteReceived)==null?void 0:j.call(EA,IA)},sA=IA=>{var EA,j;return(j=(EA=t.current).onGameInviteCancelled)==null?void 0:j.call(EA,IA)},pA=IA=>{var EA,j;return(j=(EA=t.current).onTurnOrderUpdated)==null?void 0:j.call(EA,IA)},gA=IA=>{var EA,j;return(j=(EA=t.current).onSpectatorsUpdated)==null?void 0:j.call(EA,IA)},yA=IA=>{var EA,j;return(j=(EA=t.current).onPlayerProfileUpdated)==null?void 0:j.call(EA,IA)},fA=IA=>{var EA,j;return(j=(EA=t.current).onPlayerPresenceUpdate)==null?void 0:j.call(EA,IA)},RA=IA=>{var EA,j;return(j=(EA=t.current).onPokerMyHole)==null?void 0:j.call(EA,IA)},YA=IA=>{var EA,j;return(j=(EA=t.current).onPokerWinners)==null?void 0:j.call(EA,IA)},W=IA=>{var EA,j;return(j=(EA=t.current).onPokerRevealAll)==null?void 0:j.call(EA,IA)},$=IA=>{var EA,j;return(j=(EA=t.current).onPokerTimedOut)==null?void 0:j.call(EA,IA)},L=IA=>{var EA,j;return(j=(EA=t.current).onPokerMyBalance)==null?void 0:j.call(EA,IA)},H=IA=>{var EA,j;return(j=(EA=t.current).onRoomUpdateState)==null?void 0:j.call(EA,IA)},P=IA=>IA&&(!IA.dice&&typeof IA.d1=="number"&&typeof IA.d2=="number"&&(IA.dice=[IA.d1,IA.d2]),IA.dice&&(typeof IA.d1!="number"||typeof IA.d2!="number")&&(IA.d1=IA.dice[0],IA.d2=IA.dice[1]),IA.shooterId!==void 0&&IA.currentRollerId===void 0&&(IA.currentRollerId=IA.shooterId),IA.nextShooterId!==void 0&&IA.nextRollerId===void 0&&(IA.nextRollerId=IA.nextShooterId),IA),tA=IA=>{var EA,j;(j=(EA=t.current).onCrapsRollResult)==null||j.call(EA,P(IA))},iA=IA=>{var EA,j;(j=(EA=t.current).onCrapsReadyUpdate)==null||j.call(EA,IA)},oA=IA=>{var EA,j;(j=(EA=t.current).onCrapsBetsUpdate)==null||j.call(EA,IA)},CA=IA=>{var EA,j;(j=(EA=t.current).onCrapsBetDelta)==null||j.call(EA,IA)},cA=IA=>{var EA,j;(j=(EA=t.current).onCrapsBetResults)==null||j.call(EA,IA)},_A=IA=>{var EA,j;(j=(EA=t.current).onCrapsBetError)==null||j.call(EA,IA)},uA=IA=>{var EA,j;(j=(EA=t.current).onCrapsPointSet)==null||j.call(EA,IA)},X=IA=>{var EA,j;(j=(EA=t.current).onCrapsPointMade)==null||j.call(EA,IA)},O=IA=>{var EA,j;return(j=(EA=t.current).onSkillsRejoinedRoom)==null?void 0:j.call(EA,IA)},lA=IA=>{var EA,j;return(j=(EA=t.current).onSkillsScoreUpdate)==null?void 0:j.call(EA,IA)},wA=IA=>{var EA,j;return(j=(EA=t.current).onSkillsRoundStart)==null?void 0:j.call(EA,IA)},xA=IA=>{var EA,j;return(j=(EA=t.current).onSkillsRoundEnd)==null?void 0:j.call(EA,IA)},HA=IA=>{var EA,j;return(j=(EA=t.current).onSkillsSessionInfo)==null?void 0:j.call(EA,IA)},zA=IA=>{var EA,j;return(j=(EA=t.current).onAnagramsWordFound)==null?void 0:j.call(EA,IA)},ne=IA=>{var EA,j;return(j=(EA=t.current).onTriviaAnswer)==null?void 0:j.call(EA,IA)},ye=IA=>{var EA,j;return(j=(EA=t.current).onTriviaNextQuestion)==null?void 0:j.call(EA,IA)},Ee=IA=>{var EA,j;return(j=(EA=t.current).onSkillsSpectatorState)==null?void 0:j.call(EA,IA)},NA=IA=>{var EA,j;return(j=(EA=t.current).onSkillsSpectatorUpdate)==null?void 0:j.call(EA,IA)},QA=IA=>{var EA,j;return(j=(EA=t.current).onSkillsSpectatorJoined)==null?void 0:j.call(EA,IA)},PA=IA=>{var EA,j;return(j=(EA=t.current).onSkillsSpectatorLeft)==null?void 0:j.call(EA,IA)},VA=IA=>{var EA,j;return(j=(EA=t.current).onSkillsWordClaimed)==null?void 0:j.call(EA,IA)},KA=()=>{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,r),A.on(ze.OTHER_JOINED,a),A.on(ze.POKER_OTHER_JOINED,a),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,T),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,q),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,CA),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,YA),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 IA=EA=>{var j,dA;return(dA=(j=t.current).onCrapsState)==null?void 0:dA.call(j,EA)};return A.on(ze.CRAPS_STATE,IA),A.on("skills:rejoined_room",O),A.on(ze.SKILLS_SCORE_UPDATE,lA),A.on(ze.SKILLS_ROUND_START,wA),A.on(ze.SKILLS_ROUND_END,xA),A.on("skills:session_info",HA),A.on("anagrams:word_found",zA),A.on("trivia:answer",ne),A.on("trivia:next_question",ye),A.on("skills:spectator_state",Ee),A.on("skills:spectator_update",NA),A.on("skills:spectator_joined",QA),A.on("skills:spectator_left",PA),A.on("skills:word_claimed",VA),()=>{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,r),A.off(ze.OTHER_JOINED,a);try{A.off(ze.POKER_OTHER_JOINED,a)}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,T),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,q),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,CA),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,YA),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,IA),A.off("skills:rejoined_room",O),A.off(ze.SKILLS_SCORE_UPDATE,lA),A.off(ze.SKILLS_ROUND_START,wA),A.off(ze.SKILLS_ROUND_END,xA),A.off("skills:session_info",HA),A.off("anagrams:word_found",zA),A.off("trivia:answer",ne),A.off("trivia:next_question",ye),A.off("skills:spectator_state",Ee),A.off("skills:spectator_update",NA),A.off("skills:spectator_joined",QA),A.off("skills:spectator_left",PA),A.off("skills:word_claimed",VA)}};let Ie=KA();const DA=()=>{try{Ie&&Ie()}catch{}Ie=KA();try{li(async()=>{const{reRegisterPushToken:IA}=await Promise.resolve().then(()=>aRe);return{reRegisterPushToken:IA}},void 0).then(({reRegisterPushToken:IA})=>{IA()}).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 S8(){const{getRoomsList:e,createRoom:A,lobbyJoin:t,lobbyLeave:i}=So(),[n,g]=E.useState({public:[],private:[]}),[o,s]=E.useState(!0),[r,a]=E.useState(null),{setMembershipModalOpen:I}=bR(),{resetSpin:c}=MB(),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),a(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){a((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,T;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(q=>setTimeout(q,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 q=180*U,z=Math.floor(Math.random()*140);await new Promise(Z=>setTimeout(Z,q+z))}return A({name:N.name,isPrivate:N.isPrivate,singlePlayer:N.singlePlayer,gameMode:N.gameMode,botLevel:N.botLevel,gameRules:N.gameRules})};s(!0),a(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||((T=U.gameState)==null?void 0:T.gameMode)||"cee-lo"};g(q=>q.public.some(z=>z.roomId===x.roomId)||q.private.some(z=>z.roomId===x.roomId)?q:x.private?{...q,private:[x,...q.private]}:{...q,public:[x,...q.public]})}else await h();return c(),v}catch(v){const U=(v==null?void 0:v.message)??"Failed to create room.";throw a(U),v}finally{s(!1),m.inFlight=null}},[A,h,I,c]),k=Ss();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]),xs({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:r,refreshRooms:h,createRoom:S,getGameRoute:Q}}const xvA=[0,100,250,500,1e3,2500,5e3],TvA=[15,30,45,60,90,120],qvA=[{value:"wordsearch",label:"🔤 Word Search"},{value:"anagrams",label:"🔀 Anagrams"},{value:"trivia",label:"❓ Trivia"}];function YvA({gameMode:e}){const[A,t]=E.useState(""),[i,n]=E.useState(2),[g,o]=E.useState(!1),[s,r]=E.useState(!1),[a,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=Ji(),{createRoom:J}=S8(),{pokerCreateRoom:T,skillsRoomCreate:v}=So(),U=e==="skills",x=async q=>{var z,Z,eA;q.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 T({name:A,maxPlayers:i,isPrivate:g,singlePlayer:s,eliminationMode:a,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:q=>t(q.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:q=>n(Number(q.target.value)),required:!0,disabled:N})]}),U&&C.jsxs(C.Fragment,{children:[C.jsxs("label",{children:["Game Mode",C.jsx("select",{value:p,onChange:q=>y(q.target.value),className:"create-room-input",disabled:N,children:qvA.map(q=>C.jsx("option",{value:q.value,children:q.label},q.value))})]}),C.jsxs("label",{children:["Bet Amount",C.jsx("select",{value:B,onChange:q=>Q(Number(q.target.value)),className:"create-room-input",disabled:N,children:xvA.map(q=>C.jsx("option",{value:q,children:q===0?"Free Play":`${q.toLocaleString()} Credits`},q))})]}),C.jsxs("label",{children:["Game Duration",C.jsx("select",{value:h,onChange:q=>d(Number(q.target.value)),className:"create-room-input",disabled:N,children:TvA.map(q=>C.jsxs("option",{value:q,children:[q," seconds"]},q))})]})]}),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:q=>l(Math.max(500,Math.min(25e3,Number(q.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:a,onChange:q=>I(q.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:q=>D(q.target.checked),disabled:N}),"Disable Resource Raid"]}),C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",className:"create-room-checkbox",checked:S,onChange:q=>k(q.target.checked),disabled:N}),"Disable Spy Strike"]})]}),C.jsxs("label",{children:[C.jsx("input",{type:"checkbox",className:"create-room-checkbox",checked:g,onChange:q=>o(q.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 HcA(e){E.useEffect(()=>{if(!(typeof document>"u")){if(e){try{eM(!0)}catch{}try{kC()}catch{}try{document.body.classList.add("modal-open")}catch{}}else{try{eM(!1)}catch{}try{document.body.classList.remove("modal-open")}catch{}}return()=>{try{eM(!1)}catch{}try{document.body.classList.remove("modal-open")}catch{}}}},[e])}function HvA({open:e,onClose:A,gameMode:t}){const[i,n]=E.useState(t||"cee-lo");HcA(!!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(YvA,{gameMode:i})]})}):null}function t7({rooms:e,title:A,onJoinClick:t,spectateMode:i}){const n=Ji(),[g,o]=E.useState(null);if(e.length===0)return C.jsx("div",{className:"room-list",children:"No rooms available."});const s=async(r,a)=>{if(!g){o(r);try{if(t&&await t(),i&&a==="skills")return n(`/skills/spectate/${r}`);if(a==="poker")return n(`/poker/room/${r}`);if(a==="skills")return n(`/skills/room/${r}`);if(a==="zentara")return n(`/zentara/room/${r}`);n(`/room/${r}`)}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(r=>!r.singlePlayer&&!r.quickMatch).map(r=>C.jsxs("li",{className:"room-list__item",children:[C.jsxs("div",{className:"room-list__info",children:[C.jsx("span",{className:"room-list__name",children:r.name}),r.private&&C.jsx("span",{className:"room-list__private",children:"🔒"}),C.jsxs("span",{className:"room-list__players",children:[r.currentPlayers,"/",r.maxPlayers]}),C.jsx("span",{className:"room-list__phase",children:r.phase??"waiting"}),r.gameMode&&C.jsx("span",{className:"room-list__mode",title:"Game Mode",children:r.gameMode}),r.gameMode==="skills"&&C.jsxs(C.Fragment,{children:[typeof r.stake=="number"&&C.jsxs("span",{className:"room-list__stake",title:"Bet Amount",children:["💰 ",r.stake===0?"Free":r.stake.toLocaleString()]}),typeof r.duration=="number"&&C.jsxs("span",{className:"room-list__duration",title:"Game Duration",children:["⏱️ ",r.duration,"s"]})]}),C.jsx("span",{className:"room-list__created",children:new Date(r.createdAt).toLocaleTimeString()})]}),C.jsx("button",{className:`btn btn--join ${i&&r.gameMode==="skills"?"btn--spectate":""} ${g===r.roomId?"btn--loading":""}`,"data-game-mode":r.gameMode,onClick:()=>s(r.roomId,r.gameMode),disabled:g!==null,children:g===r.roomId?C.jsx("span",{className:"btn-spinner"}):i&&r.gameMode==="skills"?"👁️ Spectate":"Join"})]},r.roomId))})]})}function OvA({open:e,onClose:A,isPrivate:t,setIsPrivate:i,roomsList:n,onJoinClick:g,loading:o}){const s=E.useRef(null),[r,a]=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:r,onChange:I=>a(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(t7,{title:"Private Rooms",rooms:n.private,onJoinClick:g,spectateMode:r}):C.jsx("p",{children:"No private rooms available."}):n.public.length?C.jsx(t7,{title:"Public Rooms",rooms:n.public,onJoinClick:g,spectateMode:r}):C.jsx("p",{children:"No public rooms available."})]})}):null}function PvA({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 r=s.target,a=!!((c=n.current)!=null&&c.contains(r)),I=!!((l=e.current)!=null&&l.contains(r));!a&&!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 Qs={diceAudio:!0,backgroundMusic:!0,chatAudio:!1,video:!1,showAnimations:!0,showCelebrationImages:!0,lastGameMode:"cee-lo",diceColorTheme:"dice_white_black",theme:"dark",zentaraBotCount:3},OcA="app:settings:v1";async function Wo(){try{const{value:e}=await nr.get({key:OcA});if(!e)return{...Qs};const A=JSON.parse(e);return{...Qs,...A}}catch{return{...Qs}}}async function _E(e){await nr.set({key:OcA,value:JSON.stringify(e)});try{window.dispatchEvent(new CustomEvent("app:settings",{detail:e}))}catch{}}const PcA=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_SETTINGS:Qs,loadSettings:Wo,saveSettings:_E},Symbol.toStringTag,{value:"Module"})),Ma=nl("App",{web:()=>li(()=>import("./web-D9Sye5xf.js"),__vite__mapDeps([8,1])).then(e=>new e.AppWeb)}),UR=Object.freeze(Object.defineProperty({__proto__:null,App:Ma},Symbol.toStringTag,{value:"Module"}));var jvA=Object.create,jcA=Object.defineProperty,zvA=Object.getOwnPropertyDescriptor,ZvA=(e,A)=>(A=Symbol[e])?A:Symbol.for("Symbol."+e),zcA=e=>{throw TypeError(e)},ZcA=(e,A,t)=>A in e?jcA(e,A,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[A]=t,WvA=e=>[,,,jvA(null)],WcA=["class","method","getter","setter","accessor","field","value","get","set"],VcA=e=>e!==void 0&&typeof e!="function"?zcA("Function expected"):e,VvA=(e,A,t,i,n)=>({kind:WcA[e],name:A,metadata:i,addInitializer:g=>t._?zcA("Already initialized"):n.push(VcA(g||null))}),XvA=(e,A)=>ZcA(A,ZvA("metadata"),e[3]),$vA=(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},AKA=(e,A,t,i,n,g)=>{for(var o,s,r,a,I=A&7,c=!1,l=!1,B=2,Q=WcA[I+5],h=e[B]||(e[B]=[]),d=(n=n.prototype,zvA(n,t)),p=i.length-1;p>=0;p--)r=VvA(I,t,s={},e[3],h),r.static=c,r.private=l,a=r.access={has:y=>t in y},a.get=y=>y[t],I>2,o=(0,i[p])(d[Q],r),s._=1,VcA(o)&&(d[Q]=o);return d&&jcA(n,t,d),n},Tt=(e,A,t)=>ZcA(e,typeof A!="symbol"?A+"":A,t);const eKA="5";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(eKA);const w8=1,k8=2,XcA=4,tKA=8,iKA=16,nKA=1,gKA=2,oKA=4,sKA=8,rKA=16,aKA=1,IKA=2,CKA=4,cKA=1,lKA=2,Ha=Symbol(),gN="http://www.w3.org/2000/svg";function BKA(e){return e.endsWith("capture")&&e!=="gotpointercapture"&&e!=="lostpointercapture"}const EKA=["beforeinput","click","change","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"];function QKA(e){return EKA.includes(e)}const uKA={formnovalidate:"formNoValidate",ismap:"isMap",nomodule:"noModule",playsinline:"playsInline",readonly:"readOnly",defaultvalue:"defaultValue",defaultchecked:"defaultChecked",srcobject:"srcObject"};function dKA(e){return e=e.toLowerCase(),uKA[e]??e}const hKA=["touchstart","touchmove"];function pKA(e){return hKA.includes(e)}const fKA=!1;var ML=Array.isArray,yKA=Array.prototype.indexOf,M8=Array.from,DKA=Object.defineProperty,Hu=Object.getOwnPropertyDescriptor,$cA=Object.getOwnPropertyDescriptors,mKA=Object.prototype,SKA=Array.prototype,N8=Object.getPrototypeOf;function KD(e){return typeof e=="function"}const rg=()=>{};function wKA(e){return e()}function rP(e){for(var A=0;A<e.length;A++)e[A]()}const Vc=2,AlA=4,vR=8,NL=16,gl=32,KR=64,NF=128,_f=256,RF=512,CI=1024,od=2048,FR=4096,IB=8192,yw=16384,elA=32768,Nd=65536,kKA=1<<17,MKA=1<<19,tlA=1<<20,Ou=Symbol("$state"),ilA=Symbol("legacy props"),NKA=Symbol("");function nlA(e){return e===this.v}function glA(e,A){return e!=e?A==A:e!==A||e!==null&&typeof e=="object"||typeof e=="function"}function R8(e){return!glA(e,this.v)}function RKA(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function GKA(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function bKA(e){throw new Error("https://svelte.dev/e/effect_orphan")}function UKA(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function vKA(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function KKA(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function FKA(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function _KA(){throw new Error("https://svelte.dev/e/state_unsafe_local_read")}function JKA(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}let Dw=!1,LKA=!1;function xKA(){Dw=!0}function JI(e,A){var t={f:0,v:e,reactions:null,equals:nlA,rv:0,wv:0};return t}function gn(e){return olA(JI(e))}function RL(e,A=!1){var t;const i=JI(e);return A||(i.equals=R8),Dw&&Ag!==null&&Ag.l!==null&&((t=Ag.l).s??(t.s=[])).push(i),i}function kc(e,A=!1){return olA(RL(e,A))}function olA(e){return Qg!==null&&Qg.f&Vc&&(CB===null?WKA([e]):CB.push(e)),e}function bt(e,A){return Qg!==null&&F8()&&Qg.f&(Vc|NL)&&(CB===null||!CB.includes(e))&&JKA(),aP(e,A)}function aP(e,A){return e.equals(A)||(e.v,e.v=A,e.wv=ylA(),slA(e,od),F8()&&pn!==null&&pn.f&CI&&!(pn.f&gl)&&(Yr!==null&&Yr.includes(e)?(ol(pn,od),vL(pn)):Pu===null?VKA([e]):Pu.push(e))),A}function slA(e,A){var t=e.reactions;if(t!==null)for(var i=F8(),n=t.length,g=0;g<n;g++){var o=t[g],s=o.f;!(s&od)&&(!i&&o===pn||(ol(o,A),s&(CI|_f)&&(s&Vc?slA(o,FR):vL(o))))}}let G8=!1;function di(e,A=null,t){if(typeof e!="object"||e===null||Ou in e)return e;const i=N8(e);if(i!==mKA&&i!==SKA)return e;var n=new Map,g=ML(e),o=JI(0);g&&n.set("length",JI(e.length));var s;return new Proxy(e,{defineProperty(r,a,I){(!("value"in I)||I.configurable===!1||I.enumerable===!1||I.writable===!1)&&KKA();var c=n.get(a);return c===void 0?(c=JI(I.value),n.set(a,c)):bt(c,di(I.value,s)),!0},deleteProperty(r,a){var I=n.get(a);if(I===void 0)a in r&&n.set(a,JI(Ha));else{if(g&&typeof a=="string"){var c=n.get("length"),l=Number(a);Number.isInteger(l)&&l<c.v&&bt(c,l)}bt(I,Ha),i7(o)}return!0},get(r,a,I){var c;if(a===Ou)return e;var l=n.get(a),B=a in r;if(l===void 0&&(!B||(c=Hu(r,a))!=null&&c.writable)&&(l=JI(di(B?r[a]:Ha,s)),n.set(a,l)),l!==void 0){var Q=MA(l);return Q===Ha?void 0:Q}return Reflect.get(r,a,I)},getOwnPropertyDescriptor(r,a){var I=Reflect.getOwnPropertyDescriptor(r,a);if(I&&"value"in I){var c=n.get(a);c&&(I.value=MA(c))}else if(I===void 0){var l=n.get(a),B=l==null?void 0:l.v;if(l!==void 0&&B!==Ha)return{enumerable:!0,configurable:!0,value:B,writable:!0}}return I},has(r,a){var I;if(a===Ou)return!0;var c=n.get(a),l=c!==void 0&&c.v!==Ha||Reflect.has(r,a);if(c!==void 0||pn!==null&&(!l||(I=Hu(r,a))!=null&&I.writable)){c===void 0&&(c=JI(l?di(r[a],s):Ha),n.set(a,c));var B=MA(c);if(B===Ha)return!1}return l},set(r,a,I,c){var l,B=n.get(a),Q=a in r;if(g&&a==="length")for(var h=I;h<B.v;h+=1){var d=n.get(h+"");d!==void 0?bt(d,Ha):h in r&&(d=JI(Ha),n.set(h+"",d))}B===void 0?(!Q||(l=Hu(r,a))!=null&&l.writable)&&(B=JI(void 0),bt(B,di(I,s)),n.set(a,B)):(Q=B.v!==Ha,bt(B,di(I,s)));var p=Reflect.getOwnPropertyDescriptor(r,a);if(p!=null&&p.set&&p.set.call(c,I),!Q){if(g&&typeof a=="string"){var y=n.get("length"),m=Number(a);Number.isInteger(m)&&m>=y.v&&bt(y,m+1)}i7(o)}return!0},ownKeys(r){MA(o);var a=Reflect.ownKeys(r).filter(l=>{var B=n.get(l);return B===void 0||B.v!==Ha});for(var[I,c]of n)c.v!==Ha&&!(I in r)&&a.push(I);return a},setPrototypeOf(){FKA()}})}function i7(e,A=1){bt(e,e.v+A)}var n7,rlA,alA;function TKA(){if(n7===void 0){n7=window;var e=Element.prototype,A=Node.prototype;rlA=Hu(A,"firstChild").get,alA=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 _R(e=""){return document.createTextNode(e)}function nf(e){return rlA.call(e)}function GL(e){return alA.call(e)}function Xe(e,A){return nf(e)}function Ui(e,A){{var t=nf(e);return t instanceof Comment&&t.data===""?GL(t):t}}function Ht(e,A=1,t=!1){let i=e;for(;A--;)i=GL(i);return i}function qKA(e){e.textContent=""}function Ct(e){var A=Vc|od;pn===null?A|=_f:pn.f|=tlA;var t=Qg!==null&&Qg.f&Vc?Qg:null;const i={children:null,ctx:Ag,deps:null,equals:nlA,f:A,fn:e,reactions:null,rv:0,v:null,wv:0,parent:t??pn};return t!==null&&(t.children??(t.children=[])).push(i),i}function mm(e){const A=Ct(e);return A.equals=R8,A}function IlA(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&Vc?b8(i):ic(i)}}}function YKA(e){for(var A=e.parent;A!==null;){if(!(A.f&Vc))return A;A=A.parent}return null}function ClA(e){var A,t=pn;cI(YKA(e));try{IlA(e),A=DlA(e)}finally{cI(t)}return A}function clA(e){var A=ClA(e),t=(ap||e.f&_f)&&e.deps!==null?FR:CI;ol(e,t),e.equals(A)||(e.v=A,e.wv=ylA())}function b8(e){IlA(e),sN(e,0),ol(e,yw),e.v=e.children=e.deps=e.ctx=e.reactions=null}function llA(e){pn===null&&Qg===null&&bKA(),Qg!==null&&Qg.f&_f&&GKA(),K8&&RKA()}function HKA(e,A){var t=A.last;t===null?A.last=A.first=e:(t.next=e,e.prev=t,A.last=e)}function mw(e,A,t,i=!0){var n=(e&KR)!==0,g=pn,o={ctx:Ag,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{g7(!0),LR(o),o.f|=elA}catch(I){throw ic(o),I}finally{g7(s)}}else A!==null&&vL(o);var r=t&&o.deps===null&&o.first===null&&o.nodes_start===null&&o.teardown===null&&(o.f&tlA)===0;if(!r&&!n&&i&&(g!==null&&HKA(o,g),Qg!==null&&(Qg.f&Vc)!==0)){var a=Qg;(a.children??(a.children=[])).push(o)}return o}function BlA(e){const A=mw(vR,null,!1);return ol(A,CI),A.teardown=e,A}function wS(e){llA();var A=pn!==null&&(pn.f&gl)!==0&&Ag!==null&&!Ag.m;if(A){var t=Ag;(t.e??(t.e=[])).push({fn:e,effect:pn,reaction:Qg})}else{var i=bL(e);return i}}function OKA(e){return llA(),UL(e)}function PKA(e){const A=mw(KR,e,!0);return(t={})=>new Promise(i=>{t.outro?gf(A,()=>{ic(A),i(void 0)}):(ic(A),i(void 0))})}function bL(e){return mw(AlA,e,!1)}function Dl(e,A){var t=Ag,i={effect:null,ran:!1};t.l.r1.push(i),i.effect=UL(()=>{e(),!i.ran&&(i.ran=!0,bt(t.l.r2,!0),WE(A))})}function jKA(){var e=Ag;UL(()=>{if(MA(e.l.r2)){for(var A of e.l.r1){var t=A.effect;t.f&CI&&ol(t,FR),Sw(t)&&LR(t),A.ran=!1}e.l.r2.v=!1}})}function UL(e){return mw(vR,e,!0)}function Ft(e){return Rd(e)}function Rd(e,A=0){return mw(vR|NL|A,e,!0)}function VC(e,A=!0){return mw(vR|gl,e,!0,A)}function ElA(e){var A=e.teardown;if(A!==null){const t=K8,i=Qg;o7(!0),nc(null);try{A.call(null)}finally{o7(t),nc(i)}}}function QlA(e){var A=e.deriveds;if(A!==null){e.deriveds=null;for(var t=0;t<A.length;t+=1)b8(A[t])}}function ulA(e,A=!1){var t=e.first;for(e.first=e.last=null;t!==null;){var i=t.next;ic(t,A),t=i}}function zKA(e){for(var A=e.first;A!==null;){var t=A.next;!(A.f&gl)&&ic(A),A=t}}function ic(e,A=!0){var t=!1;if((A||e.f&MKA)&&e.nodes_start!==null){for(var i=e.nodes_start,n=e.nodes_end;i!==null;){var g=i===n?null:GL(i);i.remove(),i=g}t=!0}ulA(e,A&&!t),QlA(e),sN(e,0),ol(e,yw);var o=e.transitions;if(o!==null)for(const r of o)r.stop();ElA(e);var s=e.parent;s!==null&&s.first!==null&&dlA(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes_start=e.nodes_end=null}function dlA(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=[];U8(e,t,!0),hlA(t,()=>{ic(e),A&&A()})}function hlA(e,A){var t=e.length;if(t>0){var i=()=>--t||A();for(var n of e)n.out(i)}else A()}function U8(e,A,t){if(!(e.f&IB)){if(e.f^=IB,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&Nd)!==0||(i.f&gl)!==0;U8(i,A,g?t:!1),i=n}}}function oN(e){plA(e,!0)}function plA(e,A){if(e.f&IB){Sw(e)&&LR(e),e.f^=IB;for(var t=e.first;t!==null;){var i=t.next,n=(t.f&Nd)!==0||(t.f&gl)!==0;plA(t,n?A:!1),t=i}if(e.transitions!==null)for(const g of e.transitions)(g.is_global||A)&&g.in()}}let IP=!1,CP=[];function ZKA(){IP=!1;const e=CP.slice();CP=[],rP(e)}function Jf(e){IP||(IP=!0,queueMicrotask(ZKA)),CP.push(e)}function v8(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}let nM=!1,GF=!1,bF=null,Sm=!1,K8=!1;function g7(e){Sm=e}function o7(e){K8=e}let cP=[],gM=0,Qg=null;function nc(e){Qg=e}let pn=null;function cI(e){pn=e}let CB=null;function WKA(e){CB=e}let Yr=null,UI=0,Pu=null;function VKA(e){Pu=e}let flA=1,lP=0,ap=!1,Ag=null;function s7(e){Ag=e}function ylA(){return++flA}function F8(){return!Dw||Ag!==null&&Ag.l===null}function Sw(e){var A,t=e.f;if(t&od)return!0;if(t&FR){var i=e.deps,n=(t&_f)!==0;if(i!==null){var g,o,s=(t&RF)!==0,r=n&&pn!==null&&!ap,a=i.length;if(s||r){for(g=0;g<a;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^=RF)}for(g=0;g<a;g++)if(o=i[g],Sw(o)&&clA(o),o.wv>e.wv)return!0}(!n||pn!==null&&!ap)&&ol(e,CI)}return!1}function XKA(e,A){for(var t=A;t!==null;){if(t.f&NF)try{t.fn(e);return}catch{t.f^=NF}t=t.parent}throw nM=!1,e}function $KA(e){return(e.f&yw)===0&&(e.parent===null||(e.parent.f&NF)===0)}function u2(){nM=!1}function JR(e,A,t,i){if(nM){if(t===null&&(nM=!1),$KA(A))throw e;return}t!==null&&(nM=!0);{XKA(e,A);return}}function DlA(e){var A,t=Yr,i=UI,n=Pu,g=Qg,o=ap,s=CB,r=Ag,a=e.f;Yr=null,UI=0,Pu=null,Qg=a&(gl|KR)?null:e,ap=!Sm&&(a&_f)!==0,CB=null,Ag=e.ctx,lP++;try{var I=(0,e.fn)(),c=e.deps;if(Yr!==null){var l;if(sN(e,UI),c!==null&&UI>0)for(c.length=UI+Yr.length,l=0;l<Yr.length;l++)c[UI+l]=Yr[l];else e.deps=c=Yr;if(!ap)for(l=UI;l<c.length;l++)((A=c[l]).reactions??(A.reactions=[])).push(e)}else c!==null&&UI<c.length&&(sN(e,UI),c.length=UI);return I}finally{Yr=t,UI=i,Pu=n,Qg=g,ap=o,CB=s,Ag=r}}function AFA(e,A){let t=A.reactions;if(t!==null){var i=yKA.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&Vc&&(Yr===null||!Yr.includes(A))&&(ol(A,FR),!(A.f&(_f|RF))&&(A.f^=RF),sN(A,0))}function sN(e,A){var t=e.deps;if(t!==null)for(var i=A;i<t.length;i++)AFA(e,t[i])}function LR(e){var A=e.f;if(!(A&yw)){ol(e,CI);var t=pn,i=Ag;pn=e;try{A&NL?zKA(e):ulA(e),QlA(e),ElA(e);var n=DlA(e);e.teardown=typeof n=="function"?n:null,e.wv=flA;var g=e.deps,o;fKA&&LKA&&e.f&od}catch(s){JR(s,e,t,i||e.ctx)}finally{pn=t}}}function eFA(){if(gM>1e3){gM=0;try{UKA()}catch(e){if(bF!==null)JR(e,bF,null);else throw e}}gM++}function tFA(e){var A=e.length;if(A!==0){eFA();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=[];mlA(n,g),iFA(g)}}finally{Sm=t}}}function iFA(e){var A=e.length;if(A!==0)for(var t=0;t<A;t++){var i=e[t];if(!(i.f&(yw|IB)))try{Sw(i)&&(LR(i),i.deps===null&&i.first===null&&i.nodes_start===null&&(i.teardown===null?dlA(i):i.fn=null))}catch(n){JR(n,i,null,i.ctx)}}}function nFA(){if(GF=!1,gM>1001)return;const e=cP;cP=[],tFA(e),GF||(gM=0,bF=null)}function vL(e){GF||(GF=!0,queueMicrotask(nFA)),bF=e;for(var A=e;A.parent!==null;){A=A.parent;var t=A.f;if(t&(KR|gl)){if(!(t&CI))return;A.f^=CI}}cP.push(A)}function mlA(e,A){var t=e.first,i=[];A:for(;t!==null;){var n=t.f,g=(n&gl)!==0,o=g&&(n&CI)!==0,s=t.next;if(!o&&!(n&IB))if(n&vR){if(g)t.f^=CI;else try{Sw(t)&&LR(t)}catch(c){JR(c,t,null,t.ctx)}var r=t.first;if(r!==null){t=r;continue}}else n&AlA&&i.push(t);if(s===null){let c=t.parent;for(;c!==null;){if(e===c)break A;var a=c.next;if(a!==null){t=a;continue A}c=c.parent}}t=s}for(var I=0;I<i.length;I++)r=i[I],A.push(r),mlA(r,A)}function MA(e){var A,t=e.f,i=(t&Vc)!==0;if(i&&t&yw){var n=ClA(e);return b8(e),n}if(Qg!==null){CB!==null&&CB.includes(e)&&_KA();var g=Qg.deps;e.rv<lP&&(e.rv=lP,Yr===null&&g!==null&&g[UI]===e?UI++:Yr===null?Yr=[e]:Yr.push(e),Pu!==null&&pn!==null&&pn.f&CI&&!(pn.f&gl)&&Pu.includes(e)&&(ol(pn,od),vL(pn)))}else if(i&&e.deps===null)for(var o=e,s=o.parent,r=o;s!==null;)if(s.f&Vc){var a=s;r=a,s=a.parent}else{var I=s;(A=I.deriveds)!=null&&A.includes(r)||(I.deriveds??(I.deriveds=[])).push(r);break}return i&&(o=e,Sw(o)&&clA(o)),e.v}function WE(e){const A=Qg;try{return Qg=null,e()}finally{Qg=A}}const gFA=-7169;function ol(e,A){e.f=e.f&gFA|A}function Xr(e){return SlA().get(e)}function d2(e,A){return SlA().set(e,A),A}function SlA(e){return Ag===null&&v8(),Ag.c??(Ag.c=new Map(oFA(Ag)||void 0))}function oFA(e){let A=e.p;for(;A!==null;){const t=A.c;if(t!==null)return t;A=A.p}return null}function Mi(e,A=!1,t){Ag={p:Ag,c:null,e:null,m:!1,s:e,x:null,l:null},Dw&&!A&&(Ag.l={s:null,u:null,r1:[],r2:JI(!1)})}function Ni(e){const A=Ag;if(A!==null){e!==void 0&&(A.x=e);const o=A.e;if(o!==null){var t=pn,i=Qg;A.e=null;try{for(var n=0;n<o.length;n++){var g=o[n];cI(g.effect),nc(g.reaction),bL(g.fn)}}finally{cI(t),nc(i)}}Ag=A.p,A.m=!0}return e||{}}function gK(e){if(!(typeof e!="object"||!e||e instanceof EventTarget)){if(Ou in e)BP(e);else if(!Array.isArray(e))for(let A in e){const t=e[A];typeof t=="object"&&t&&Ou in t&&BP(t)}}}function BP(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{BP(e[i],A)}catch{}const t=N8(e);if(t!==Object.prototype&&t!==Array.prototype&&t!==Map.prototype&&t!==Set.prototype&&t!==Date.prototype){const i=$cA(t);for(let n in i){const g=i[n].get;if(g)try{g.call(e)}catch{}}}}}function sFA(e,A){if(A){const t=document.body;e.autofocus=!0,Jf(()=>{document.activeElement===t&&e.focus()})}}function rFA(e){var A=Qg,t=pn;nc(null),cI(null);try{return e()}finally{nc(A),cI(t)}}const wlA=new Set,EP=new Set;function klA(e,A,t,i){function n(g){if(i.capture||Bk.call(A,g),!g.cancelBubble)return rFA(()=>t.call(this,g))}return e.startsWith("pointer")||e.startsWith("touch")||e==="wheel"?Jf(()=>{A.addEventListener(e,n,i)}):A.addEventListener(e,n,i),n}function nB(e,A,t,i,n){var g={capture:i,passive:n},o=klA(e,A,t,g);(A===document.body||A===window||A===document)&&BlA(()=>{A.removeEventListener(e,o,g)})}function KL(e){for(var A=0;A<e.length;A++)wlA.add(e[A]);for(var t of EP)t(e)}function Bk(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,r=e.__root;if(r){var a=g.indexOf(r);if(a!==-1&&(t===document||t===window)){e.__root=t;return}var I=g.indexOf(t);if(I===-1)return;a<=I&&(s=a)}if(o=g[s]||e.target,o!==t){DKA(e,"currentTarget",{configurable:!0,get(){return o||i}});var c=Qg,l=pn;nc(null),cI(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(ML(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,nc(c),cI(l)}}}function _8(e){var A=document.createElement("template");return A.innerHTML=e,A.content}function of(e,A){var t=pn;t.nodes_start===null&&(t.nodes_start=e,t.nodes_end=A)}function St(e,A){var t=(A&cKA)!==0,i=(A&lKA)!==0,n,g=!e.startsWith("<!>");return()=>{n===void 0&&(n=_8(g?e:"<!>"+e),t||(n=nf(n)));var o=i?document.importNode(n,!0):n.cloneNode(!0);if(t){var s=nf(o),r=o.lastChild;of(s,r)}else of(o,o);return o}}function RB(e,A,t="svg"){var i=!e.startsWith("<!>"),n=`<${t}>${i?e:"<!>"+e}</${t}>`,g;return()=>{if(!g){var o=_8(n),s=nf(o);g=nf(s)}var r=g.cloneNode(!0);return of(r,r),r}}function sg(e=""){{var A=_R(e+"");return of(A,A),A}}function Jn(){var e=document.createDocumentFragment(),A=document.createComment(""),t=_R();return e.append(A,t),of(A,t),e}function Ue(e,A){e!==null&&e.before(A)}let UF=!0;function r7(e){UF=e}function Dn(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 QP(e,A){return aFA(e,A)}const _y=new Map;function aFA(e,{target:A,anchor:t,props:i={},events:n,context:g,intro:o=!0}){TKA();var s=new Set,r=c=>{for(var l=0;l<c.length;l++){var B=c[l];if(!s.has(B)){s.add(B);var Q=pKA(B);A.addEventListener(B,Bk,{passive:Q});var h=_y.get(B);h===void 0?(document.addEventListener(B,Bk,{passive:Q}),_y.set(B,1)):_y.set(B,h+1)}}};r(M8(wlA)),EP.add(r);var a=void 0,I=PKA(()=>{var c=t??A.appendChild(_R());return VC(()=>{if(g){Mi({});var l=Ag;l.c=g}n&&(i.$$events=n),UF=o,a=e(c,i)||{},UF=!0,g&&Ni()}),()=>{var l;for(var B of s){A.removeEventListener(B,Bk);var Q=_y.get(B);--Q===0?(document.removeEventListener(B,Bk),_y.delete(B)):_y.set(B,Q)}EP.delete(r),c!==t&&((l=c.parentNode)==null||l.removeChild(c))}});return uP.set(a,I),a}let uP=new WeakMap;function oK(e,A){const t=uP.get(e);return t?(uP.delete(e),t(A)):Promise.resolve()}function $t(e,A,t=!1){var i=e,n=null,g=null,o=Ha,s=t?Nd:0,r=!1;const a=(c,l=!0)=>{r=!0,I(l,c)},I=(c,l)=>{o!==(o=c)&&(o?(n?oN(n):l&&(n=VC(()=>l(i))),g&&gf(g,()=>{g=null})):(g?oN(g):l&&(g=VC(()=>l(i))),n&&gf(n,()=>{n=null})))};Rd(()=>{r=!1,A(a),r||I(null,null)},s)}function kS(e,A){return A}function IFA(e,A,t,i){for(var n=[],g=A.length,o=0;o<g;o++)U8(A[o].e,n,!0);var s=g>0&&n.length===0&&t!==null;if(s){var r=t.parentNode;qKA(r),r.append(t),i.clear(),$Q(e,A[0].prev,A[g-1].next)}hlA(n,()=>{for(var a=0;a<g;a++){var I=A[a];s||(i.delete(I.k),$Q(e,I.prev,I.next)),ic(I.e,!s)}})}function MS(e,A,t,i,n,g=null){var o=e,s={flags:A,items:new Map,first:null},r=(A&XcA)!==0;if(r){var a=e;o=a.appendChild(_R())}var I=null,c=!1;Rd(()=>{var l=t(),B=ML(l)?l:l==null?[]:M8(l),Q=B.length;if(!(c&&Q===0)){c=Q===0;{var h=Qg;CFA(B,s,o,n,A,(h.f&IB)!==0,i)}g!==null&&(Q===0?I?oN(I):I=VC(()=>g(o)):I!==null&&gf(I,()=>{I=null})),t()}})}function CFA(e,A,t,i,n,g,o,s){var r,a,I,c,l=(n&tKA)!==0,B=(n&(w8|k8))!==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&&((r=M.a)==null||r.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=lFA(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&&cFA(M,N,w,n),M.e.f&IB&&(oN(M.e),l&&((a=M.a)==null||a.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],T=S[S.length-1];for(K=0;K<S.length;K+=1)a7(S[K],_,t);for(K=0;K<k.length;K+=1)y.delete(k[K]);$Q(A,J.prev,T.next),$Q(A,m,J),$Q(A,T,_),p=_,m=T,w-=1,S=[],k=[]}else y.delete(M),a7(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&IB))&&(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?[]:M8(y);p!==null;)(g||!(p.e.f&IB))&&v.push(p),p=p.next;var U=v.length;if(U>0){var x=n&XcA&&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()}IFA(A,v,x,h)}}l&&Jf(()=>{var q;if(D!==void 0)for(M of D)(q=M.a)==null||q.apply()}),pn.first=A.first&&A.first.e,pn.last=m&&m.e}function cFA(e,A,t,i){i&w8&&aP(e.v,A),i&k8?aP(e.i,t):e.i=t}function lFA(e,A,t,i,n,g,o,s,r,a){var I=(r&w8)!==0,c=(r&iKA)===0,l=I?c?RL(n):JI(n):n,B=r&k8?JI(o):o,Q={i:B,v:l,k:g,a:null,e:null,prev:t,next:i};try{return Q.e=VC(()=>s(e,l,B),G8),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 a7(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=GL(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 Gd(e,A,t,i,n){var g=e,o="",s;Rd(()=>{o!==(o=A()??"")&&(s!==void 0&&(ic(s),s=void 0),o!==""&&(s=VC(()=>{var r=o+"",a=_8(r);of(nf(a),a.lastChild),g.before(a)})))})}function BFA(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 es(e,A,...t){var i=e,n=rg,g;Rd(()=>{n!==(n=A())&&(g&&(ic(g),g=null),g=VC(()=>n(i,...t)))},Nd)}function EFA(e,A,t){var i=e,n,g;Rd(()=>{n!==(n=A())&&(g&&(gf(g),g=null),n&&(g=VC(()=>t(i,n))))},Nd)}function vF(e,A,t,i,n,g){var o,s,r=null,a=e,I;Rd(()=>{const c=A()||null;var l=c==="svg"?gN:null;c!==o&&(I&&(c===null?gf(I,()=>{I=null,s=null}):c===s?oN(I):(ic(I),r7(!1))),c&&c!==s&&(I=VC(()=>{if(r=l?document.createElementNS(l,c):document.createElement(c),of(r,r),i){var B=r.appendChild(_R());i(r,B)}pn.nodes_end=r,a.before(r)})),o=c,o&&(s=o),r7(!0))},Nd)}function Qi(e,A){Jf(()=>{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 MlA(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=MlA(e[A]))&&(i&&(i+=" "),i+=t)}else for(t in e)e[t]&&(i&&(i+=" "),i+=t);return i}function QFA(){for(var e,A,t=0,i="",n=arguments.length;t<n;t++)(e=arguments[t])&&(A=MlA(e))&&(i&&(i+=" "),i+=A);return i}function NlA(e){return typeof e=="object"?QFA(e):e??""}function uFA(e,A){A?e.hasAttribute("selected")||e.setAttribute("selected",""):e.removeAttribute("selected")}function Ii(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[NKA]=t),t==null?e.removeAttribute(A):typeof t!="string"&&RlA(e).includes(A)?e[A]=t:e.setAttribute(A,t))}function KF(e,A,t,i,n=!1,g=!1,o=!1){var s=A||{},r=e.tagName==="OPTION";for(var a in A)a in t||(t[a]=null);t.class&&(t.class=NlA(t.class)),i!==void 0&&(t.class=t.class?t.class+" "+i:i);var I=RlA(e),c=e.__attributes??(e.__attributes={});for(const p in t){let y=t[p];if(r&&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=QKA(S);if(BKA(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,KL([S]);else{let k=function(N){s[p].call(this,N)};s[D]=klA(S,e,k,m)}else Q&&(e[`__${S}`]=void 0)}else if(p==="style"&&y!=null)e.style.cssText=y+"";else if(p==="autofocus")sFA(e,!!y);else if(p==="__value"||p==="value"&&y!=null)e.value=e[p]=e.__value=y;else if(p==="selected"&&r)uFA(e,y);else{var h=p;n||(h=dKA(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"&&Ii(e,h,y)}p==="style"&&"__styles"in e&&(e.__styles={})}}}return s}var I7=new Map;function RlA(e){var A=I7.get(e.nodeName);if(A)return A;I7.set(e.nodeName,A=[]);for(var t,i=e,n=Element.prototype;n!==i;){t=$cA(i);for(var g in t)t[g].set&&A.push(g);i=N8(i)}return A}function dFA(e,A,t){var i=e.__className,n=GlA(A,t);(i!==n||G8)&&(n===""?e.removeAttribute("class"):e.setAttribute("class",n),e.__className=n)}function sd(e,A,t){var i=e.__className,n=GlA(A,t);(i!==n||G8)&&(A==null&&!t?e.removeAttribute("class"):e.className=n,e.__className=n)}function GlA(e,A){return(e??"")+(A?" "+A:"")}function JE(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 hFA=()=>performance.now(),uE={tick:e=>requestAnimationFrame(e),now:()=>hFA(),tasks:new Set};function blA(){const e=uE.now();uE.tasks.forEach(A=>{A.c(e)||(uE.tasks.delete(A),A.f())}),uE.tasks.size!==0&&uE.tick(blA)}function pFA(e){let A;return uE.tasks.size===0&&uE.tick(blA),{promise:new Promise(t=>{uE.tasks.add(A={c:e,f:t})}),abort(){uE.tasks.delete(A)}}}function pb(e,A){e.dispatchEvent(new CustomEvent(A))}function fFA(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 C7(e){const A={},t=e.split(";");for(const i of t){const[n,g]=i.split(":");if(!n||g===void 0)break;const o=fFA(n.trim());A[o]=g.trim()}return A}const yFA=e=>e;function UlA(e,A,t,i){var n=(e&aKA)!==0,g=(e&IKA)!==0,o=n&&g,s=(e&CKA)!==0,r=o?"both":n?"in":"out",a,I=A.inert,c,l;function B(){var y=Qg,m=pn;nc(null),cI(null);try{return a??(a=t()(A,(i==null?void 0:i())??{},{direction:r}))}finally{nc(y),cI(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(),pb(A,"introstart"),c=dP(A,B(),l,1,()=>{pb(A,"introend"),c==null||c.abort(),c=a=void 0})},out(y){if(!g){y==null||y(),a=void 0;return}A.inert=!0,pb(A,"outrostart"),l=dP(A,B(),c,0,()=>{pb(A,"outroend"),y==null||y()})},stop:()=>{c==null||c.abort(),l==null||l.abort()}},h=pn;if((h.transitions??(h.transitions=[])).push(Q),n&&UF){var d=s;if(!d){for(var p=h.parent;p&&p.f&Nd;)for(;(p=p.parent)&&!(p.f&NL););d=!p||(p.f&elA)!==0}d&&bL(()=>{WE(()=>Q.in())})}}function dP(e,A,t,i,n){var g=i===1;if(KD(A)){var o,s=!1;return Jf(()=>{if(!s){var d=A({direction:g?"in":"out"});o=dP(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:rg,deactivate:rg,reset:rg,t:()=>i};const{delay:r=0,css:a,tick:I,easing:c=yFA}=A;var l=[];if(g&&t===void 0&&(I&&I(0,1),a)){var B=C7(a(0,1));l.push(B,B)}var Q=()=>1-i,h=e.animate(l,{duration:r});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(a)for(var D=Math.ceil(y/16.666666666666668),S=0;S<=D;S+=1){var k=d+p*c(S/D),N=a(k,1-k);m.push(C7(N))}Q=()=>{var G=h.currentTime;return d+p*c(G/y)},I&&pFA(()=>{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=rg)},deactivate:()=>{n=rg},reset:()=>{i===0&&(I==null||I(1,0))},t:()=>Q()}}function c7(e,A){return e===A||(e==null?void 0:e[Ou])===A}function vlA(e={},A,t,i){return bL(()=>{var n,g;return UL(()=>{n=g,g=[],WE(()=>{e!==t(...g)&&(A(e,...g),n&&c7(t(...n),e)&&A(null,...n))})}),()=>{Jf(()=>{g&&c7(t(...g),e)&&A(null,...g)})}}),e}function Ic(e=!1){const A=Ag,t=A.l.u;if(!t)return;let i=()=>gK(A.s);if(e){let n=0,g={};const o=Ct(()=>{let s=!1;const r=A.s;for(const a in r)r[a]!==g[a]&&(g[a]=r[a],s=!0);return s&&n++,n});i=()=>MA(o)}t.b.length&&OKA(()=>{l7(A,i),rP(t.b)}),wS(()=>{const n=WE(()=>t.m.map(wKA));return()=>{for(const g of n)typeof g=="function"&&g()}}),t.a.length&&wS(()=>{l7(A,i),rP(t.a)})}function l7(e,A){if(e.l.s)for(const t of e.l.s)MA(t);A()}function KlA(e,A){var t,i=(t=e.$$events)==null?void 0:t[A.type],n=ML(i)?i.slice():i==null?[]:[i];for(var g of n)g.call(this,A)}function gc(e){Ag===null&&v8(),Dw&&Ag.l!==null?DFA(Ag).m.push(e):wS(()=>{const A=WE(e);if(typeof A=="function")return A})}function xR(e){Ag===null&&v8(),gc(()=>()=>WE(e))}function DFA(e){var A=e.l;return A.u??(A.u={a:[],b:[],m:[]})}function mFA(e,A,t){if(e==null)return A(void 0),rg;const i=WE(()=>e.subscribe(A,t));return i.unsubscribe?()=>i.unsubscribe():i}let fb=!1;function QI(e,A,t){const i=t[A]??(t[A]={store:null,source:RL(void 0),unsubscribe:rg});if(i.store!==e)if(i.unsubscribe(),i.store=e??null,e==null)i.source.v=void 0,i.unsubscribe=rg;else{var n=!0;i.unsubscribe=mFA(e,g=>{n?i.source.v=g:bt(i.source,g)}),n=!1}return MA(i.source)}function uI(){const e={};return BlA(()=>{for(var A in e)e[A].unsubscribe()}),e}function SFA(e){var A=fb;try{return fb=!1,[e(),fb]}finally{fb=A}}const wFA={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 bd(e,A,t){return new Proxy({props:e,exclude:A},wFA)}const kFA={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===ilA)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 VE(...e){return new Proxy({props:e},kFA)}function B7(e){for(var A=pn,t=pn;A!==null&&!(A.f&(gl|KR));)A=A.parent;try{return cI(A),e()}finally{cI(t)}}function ri(e,A,t,i){var n,g=(t&nKA)!==0,o=!Dw||(t&gKA)!==0,s=(t&sKA)!==0,r=(t&rKA)!==0,a=!1,I;s?[I,a]=SFA(()=>e[A]):I=e[A];var c=Ou in e||ilA 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,r?B=WE(i):B=i),B);I===void 0&&i!==void 0&&(l&&o&&vKA(),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=B7(()=>(g?Ct:mm)(()=>e[A]));y.f|=kKA,p=()=>{var G=MA(y);return G!==void 0&&(B=void 0),G===void 0?B:G}}if(!(t&oKA))return p;if(l){var m=e.$$legacy;return function(G,M){return arguments.length>0?((!o||!M||m||a)&&l(M?p():G),G):p()}}var D=!1,S=!1,k=RL(I),N=B7(()=>Ct(()=>{var G=p(),M=MA(k);return D?(D=!1,S=!0,M):(S=!1,k.v=G)}));return g||(N.equals=R8),function(G,M){if(arguments.length>0){const w=M?MA(N):o&&s?di(G):G;return N.equals(w)||(D=!0,bt(k,w),h&&B!==void 0&&(B=w),WE(()=>MA(N))),G}return MA(N)}}function E7(e,A){var t=pn,i=Qg,n=Ag;cI(e),nc(e),s7(e.ctx);try{A()}finally{cI(t),nc(i),s7(n)}}function MFA(e,A,t){var i=e,n;Rd(()=>{var g=pn,o=!1;g.fn=s=>{var r=A.onerror;let a=A.failed;if(!r&&!a||o)throw s;var I=()=>{gf(n),E7(g,()=>{o=!1,n=VC(()=>t(i)),u2()})};r==null||r(s,I),n&&ic(n),a&&Jf(()=>{E7(g,()=>{o=!0;try{n=VC(()=>{a(i,()=>s,()=>I)})}catch(c){JR(c,g,null,g.ctx)}u2(),o=!1})})},n=VC(()=>t(i)),u2()},Nd|NF)}var fs=(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))(fs||{});class oM{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 sM?A:null}static convertPurchaseFlowErrorCodeToErrorCode(A){switch(A){case Bg.ErrorSettingUpPurchase:return 2;case Bg.ErrorChargingPayment:return 20;case Bg.NetworkError:return 10;case Bg.MissingEmailError:return 4;case Bg.AlreadyPurchasedError:return 6;default:return 0}}}var sM=(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))(sM||{});class fo extends Error{constructor(A,t,i,n){super(t),Tt(this,"toString",()=>`PurchasesError(code: ${fs[this.errorCode]}, message: ${this.message})`),this.errorCode=A,this.underlyingErrorMessage=i,this.extra=n}static getForBackendError(A,t){const i=oM.getErrorCodeForBackendErrorCode(A);return new fo(i,oM.getPublicMessage(i),t,{backendErrorCode:A})}static getForPurchasesFlowError(A){return new fo(oM.convertPurchaseFlowErrorCodeToErrorCode(A.errorCode),A.message,A.underlyingErrorMessage)}}class NFA extends Error{constructor(){super("Purchases must be configured before calling getInstance")}}var Ek=(e=>(e.Started="started",e.InProgress="in_progress",e.Succeeded="succeeded",e.Failed="failed",e))(Ek||{}),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||{}),vI=(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))(vI||{});let Xi=class{static setLogLevel(A){this.logLevel=A}static log(A,t=this.logLevel){const i=`[Purchases] ${A}`;if(!(this.logLevel<t||t===vI.Silent))switch(t){case vI.Error:console.error(i);break;case vI.Warn:console.warn(i);break;case vI.Info:console.info(i);break;case vI.Debug:console.debug(i);break;case vI.Verbose:console.debug(i);break}}static errorLog(A){this.log(A,vI.Error)}static warnLog(A){this.log(A,vI.Warn)}static infoLog(A){this.log(A,vI.Info)}static debugLog(A){this.log(A,vI.Debug)}static verboseLog(A){this.log(A,vI.Verbose)}};Tt(Xi,"logLevel",vI.Silent);function RFA(e){var A;return e.operation.redemption_info?{redeemUrl:((A=e.operation.redemption_info)==null?void 0:A.redeem_url)??null}:null}var Bg=(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))(Bg||{});class Gg 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===fs.ProductAlreadyPurchasedError?n=5:A.errorCode===fs.InvalidEmailError?n=4:A.errorCode===fs.NetworkError?n=3:n=Gg.fromBackendErrorCode((i=A.extra)==null?void 0:i.backendErrorCode)??t,new Gg(n,A.message,A.underlyingErrorMessage,A.errorCode,A.extra)}static fromBackendErrorCode(A){switch(A){case sM.BackendGatewaySetupErrorStripeTaxNotActive:return 6;case sM.BackendGatewaySetupErrorInvalidTaxOriginAddress:return 7;case sM.BackendGatewaySetupErrorMissingRequiredPermission:return 8;default:return null}}}class GFA{constructor(A,t,i=10){Tt(this,"operationSessionId",null),Tt(this,"backend"),Tt(this,"eventsTracker"),Tt(this,"maxNumberAttempts"),Tt(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(),r=await this.backend.postCheckoutStart(A,t,n,i,s,g,o);return this.operationSessionId=r.operation_session_id,r}catch(s){if(s instanceof fo)throw Gg.fromPurchasesError(s,0);{const r="Unknown error starting purchase: "+String(s);throw Xi.errorLog(r),new Gg(2,r)}}}async checkoutCalculateTax(A,t,i){const n=this.operationSessionId;if(!n)throw new Gg(0,"No purchase started");try{return await this.backend.postCheckoutCalculateTax(n,A,t,i)}catch(g){if(g instanceof fo)throw Gg.fromPurchasesError(g,0);{const o="Unknown error calculating tax: "+String(g);throw Xi.errorLog(o),new Gg(2,o)}}}async checkoutComplete(A){const t=this.operationSessionId;if(!t)throw new Gg(0,"No purchase started");try{return await this.backend.postCheckoutComplete(t,A)}catch(i){if(i instanceof fo)throw Gg.fromPurchasesError(i,0);{const n="Unknown error starting purchase: "+String(i);throw Xi.errorLog(n),new Gg(2,n)}}}async pollCurrentPurchaseForCompletion(){const A=this.operationSessionId;if(!A)throw new Gg(0,"No purchase in progress");return new Promise((t,i)=>{const n=(g=1)=>{if(g>this.maxNumberAttempts){this.clearPurchaseInProgress(),i(new Gg(2,"Max attempts reached trying to get successful purchase status"));return}this.backend.getCheckoutStatus(A).then(o=>{const s=o.operation.store_transaction_identifier,r=o.operation.product_identifier,a=o.operation.purchase_date?isNaN(Date.parse(o.operation.purchase_date))?null:new Date(o.operation.purchase_date):null;switch(o.operation.status){case Ek.Started:case Ek.InProgress:setTimeout(()=>n(g+1),this.waitMSBetweenAttempts);break;case Ek.Succeeded:if(this.clearPurchaseInProgress(),!s||!r||!a){i(new Gg(2,"Missing required fields in operation response."));return}t({redemptionInfo:RFA(o),operationSessionId:A,storeTransactionIdentifier:s,productIdentifier:r,purchaseDate:a});return;case Ek.Failed:this.clearPurchaseInProgress(),this.handlePaymentError(o.operation.error,i)}}).catch(o=>{const s=Gg.fromPurchasesError(o,3);i(s)})};n()})}clearPurchaseInProgress(){this.operationSessionId=null}handlePaymentError(A,t){if(A==null){t(new Gg(2,"Got an error status but error field is empty."));return}switch(A.code){case FD.SetupIntentCreationFailed:t(new Gg(0,"Setup intent creation failed"));return;case FD.PaymentMethodCreationFailed:t(new Gg(0,"Payment method creation failed"));return;case FD.PaymentChargeFailed:t(new Gg(1,"Payment charge failed"));return;case FD.SetupIntentCompletionFailed:t(new Gg(0,"Setup intent completion failed"));return;case FD.AlreadyPurchased:t(new Gg(5,"Purchased was already completed"));return;default:t(new Gg(2,"Unknown error code received"));return}}}const eC="rcb-ui-translator",wm="en",bFA={"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"},UFA={"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."},vFA={"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."},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":"ادفع {{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}} بتحصيل رسوم منك وفقًا لشروطها حتى تقوم بالإلغاء."},FFA={"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."},_FA={"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}} 按照其条款向您收费，直到您取消订阅。"},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":"總價已根據您的帳單地址更新稅金。請檢查後重試。您的信用卡只會被收取一次費用。","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}} 根據其條款向您收費，直到您取消為止。"},LFA={"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."},xFA={"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."},TFA={"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."},qFA={"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."},YFA={"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."},HFA={"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."},OFA={"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."},PFA={"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}} να σας χρεώνει σύμφωνα με τους όρους της έως ότου ακυρώσετε."},jFA={"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}} לחייב אותך בהתאם לתנאים שלהם עד שתבטל."},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":"{{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}} को रद्द करने तक उनकी शर्तों के अनुसार आपसे शुल्क लेने की अनुमति देने के लिए सहमत हैं."},ZFA={"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."},WFA={"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."},VFA={"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}}が利用規約に従って課金することを許可することに同意したことになります。"},XFA={"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}}이 약관에 따라 요금을 청구하는 데 동의하는 것입니다."},$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":"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."},A_A={"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."},e_A={"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."},t_A={"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."},i_A={"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."},n_A={"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}} будет взимать с вас плату в соответствии с их условиями до тех пор, пока вы не отмените подписку."},g_A={"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."},o_A={"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."},s_A={"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}} เรียกเก็บเงินจากคุณตามข้อกำหนดจนกว่าคุณจะยกเลิก"},r_A={"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."},a_A={"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}} стягувати з вас плату відповідно до їхніх умов, поки ви не скасуєте підписку."},I_A={"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 C_A={en:bFA,es:UFA,it:vFA,ar:KFA,ca:FFA,zh_Hans:_FA,zh_Hant:JFA,hr:LFA,cs:xFA,da:TFA,nl:qFA,fi:YFA,fr:HFA,de:OFA,el:PFA,he:jFA,hi:zFA,hu:ZFA,id:WFA,ja:VFA,ko:XFA,ms:$FA,no:A_A,pl:e_A,pt:t_A,ro:i_A,ru:n_A,sk:g_A,sv:o_A,th:s_A,tr:r_A,uk:a_A,vi:I_A};var hr=(e=>(e.Year="year",e.Month="month",e.Week="week",e.Day="day",e))(hr||{});function FlA(e){const A=e.match(/^PT?([0-9]+)([MDYW])$/);if(!A||A.length<3)return Xi.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 Xi.errorLog(`Invalid ISO 8601 unit duration format: ${e}`),null}}function hP(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 c_A=e=>e/1e6,ju=(e,A,t,i={})=>{const n=c_A(e),g={style:"currency",currency:A,currencyDisplay:"symbol",...i,minimumFractionDigits:i.maximumFractionDigits};return new Intl.NumberFormat(t,g).format(n).replace("US$","$")},l_A=(e,A)=>{const t=FlA(e);return t?A.translatePeriod(t.number,t.unit)||`${t.number} ${t.unit}s`:e},B_A=e=>{try{return e.charAt(0).toUpperCase()+e.slice(1)}catch{return e}},WD={noWhitespace:!1,short:!1},_lA={useMultipleWords:!1};class FL{constructor(A={},t=wm,i=wm){Tt(this,"locales",{}),this.selectedLocale=t,this.defaultLocale=i;const n={};Object.entries(C_A).forEach(([g,o])=>{n[g]=new Q7(o,g)}),this.locales=n,A&&this.override(A)}static fallback(){return new FL}override(A){Object.entries(A).forEach(([t,i])=>{this.locales[t]=new Q7({...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{Xi.errorLog(`Failed to create a price formatter for locale: ${this.locale}`)}try{return ju(A,t,this.fallbackLocale,i)}catch{Xi.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=_lA){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 Q7{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=_lA){const n=i==null?void 0:i.useMultipleWords,g=Math.abs(A)===1?`periods.${n===!0?"per":""}${n?B_A(t.toString()):t}Frequency`:`periods.${t}FrequencyPlural`;return this.translate(g,{amount:A.toString()})}translateDate(A,t={}){return A.toLocaleDateString(this.localeKey,t)}}xKA();const E_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 Q_A=St('<div style="color:var(--rc-color-primary);"><!></div>');function JlA(e){var A=Q_A(),t=Xe(A);Gd(t,()=>E_A),Ue(e,A)}var pP;(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"})(pP||(pP={}));var FF;(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"})(FF||(FF={}));var _F;(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"})(_F||(_F={}));var JF;(function(e){e.leading="start",e.center="center",e.trailing="end"})(JF||(JF={}));var fP;(function(e){e.vertical="column",e.horizontal="row",e.zlayer="zstack"})(fP||(fP={}));var yP;(function(e){e.top="flex-start",e.leading="flex-start",e.center="center",e.bottom="flex-end",e.trailing="flex-end"})(yP||(yP={}));var DP;(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"})(DP||(DP={}));const u_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"],d_A=({value:e="",variableDictionary:A})=>A?u_A.reduce((t,i)=>{var n;return t.replaceAll(`{{ ${i} }}`,((n=A[i])==null?void 0:n.toString())||"N/A")},e):e;function LlA(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 J8({text_lid:e,locale:A,defaultLocale:t,labels:i,variableDictionary:n}){if(!e)return"";const g=LlA(e,A,t,i);return d_A({value:g,variableDictionary:n})}const Jy=[];function h_A(e,A){return{subscribe:xlA(e,A).subscribe}}function xlA(e,A=rg){let t=null;const i=new Set;function n(s){if(glA(e,s)&&(e=s,t)){const r=!Jy.length;for(const a of i)a[1](),Jy.push(a,e);if(r){for(let a=0;a<Jy.length;a+=2)Jy[a][0](Jy[a+1]);Jy.length=0}}}function g(s){n(s(e))}function o(s,r=rg){const a=[s,r];return i.add(a),i.size===1&&(t=A(n,g)||rg),s(e),()=>{i.delete(a),i.size===0&&t&&(t(),t=null)}}return{set:n,update:g,subscribe:o}}const TlA=h_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()=>{}}),PC="light",mP="#000000",p_A="#FFFFFF";function u7(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 f_A(e){return pP[e]}function LE({colorMap:e,colorMode:A=PC,fallback:t="FFFFFF"}){if(!e)return t;const i=e[A]||e[PC];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 qlA(e,A=PC){if(!e)return"";const t=LE({colorMap:e.color,colorMode:A});return`${e.width}px solid ${t}`}function LF(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 _L({background_color:e,border:A,margin:t,padding:i,color:n,colorMode:g=PC,shape:o,shadow:s}){const r={"--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(r,u7(i,"padding")),t&&Object.assign(r,u7(t,"margin")),e&&(r["--background"]=LE({colorMap:e,colorMode:g,fallback:"transparent"})),n&&(r["--text-color"]=LE({colorMap:n,colorMode:g,fallback:mP})),A&&(r["--border"]=qlA(A,g)),(o==null?void 0:o.type)==="rectangle"&&o.corners&&Object.assign(r,LF(o.corners)),(o==null?void 0:o.type)==="pill"&&Object.assign(r,LF({bottom_leading:9999,bottom_trailing:9999,top_leading:9999,top_trailing:9999})),s&&(r["--shadow"]=`${s.x}px ${s.y}px ${s.radius}px 
      ${LE({colorMap:s.color,colorMode:g,fallback:mP})}`),r}function d7(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 TR(e){const A={"--width":"initial","--height":"initial","--flex":"initial"},t=d7(e.width),i=d7(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 YlA(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 y_A(e){const A={"--direction":"initial","--alignment":"initial","--distribution":"initial","--position":"relative","--inset":"initial","--transform":"initial"};return e.type!=="zlayer"&&(Object.assign(A,{"--direction":fP[e.type],"--alignment":yP[e.alignment]}),e.distribution&&Object.assign(A,{"--distribution":DP[e.distribution]})),A}function D_A(e,A=PC){var t,i;const{font_size:n,horizontal_alignment:g,font_weight:o,font_name:s,color:r}=e,a={"--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(a,{"--text-align":JF[g]||JF.leading,"--font-weight":FF[o]||FF.regular,"--font-size":_F[n]||_F.body_m,"--font-family":s||"sans-serif"}),r&&(((t=r[A])==null?void 0:t.type)==="linear"||((i=r[A])==null?void 0:i.type)==="radial")&&Object.assign(a,{"--background-clip":"text","--text-fill-color":"transparent","--background":LE({colorMap:r,colorMode:A})}),a}function tC(e){return Object.entries(e).map(([A,t])=>`${A}: ${t}`).join("; ")}function m_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 L8=(e,A)=>A?S_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},{}):{},S_A=e=>e?Object.entries(e).reduce((A,[t,i])=>(i&&A.push(t),A),[]):[];function Cc(e,A){return e?A?Object.entries(e).reduce((t,[i,n])=>{const g=i.replace(/^--/,`${A}-`);return t[`--${g}`]=n,t},{}):e:{}}function w_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 k_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,LF(e.corners)),A};function M_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[PC])==null?void 0:i.degrees)||0,o="50%",s="0%",r=`${Math.round(50+Math.sin((g+90)*Math.PI/90)*50)}%`,a=`${Math.round(50-Math.cos((g+90)*Math.PI/90)*50)}%`;return{x1:o,y1:s,x2:r,y2:a}}const HlA={light:{type:"hex",value:mP}},N_A={light:{type:"hex",value:p_A}},x8=e=>{const{font_size:A="body_m",color:t=HlA,background_color:i=N_A,padding:n,margin:g,size:o,purchaseState:s}=e,r={"--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"},a=L8(e.overrides,e.componentState),I=f_A(A),c=D_A({...e,...a},s.colorMode),l=_L({background_color:i,color:t,margin:g,padding:n,colorMode:s.colorMode,...a}),B=TR({...o,...a}),Q={...r,...l,...c,...B};return{textStyles:Cc(Q,"text"),tagToRender:I}};function R_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,_L({background_color:t,...e}),TR(A)),Object.assign(i,e.zStackChildStyles);const n=Cc(i,"text");return tC(n)}function G_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}=x8(e);return Object.assign(A,i),{tagToRender:t,textStyles:tC(A)}}function b_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 U_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 OlA(e,A){Mi(A,!0),Qi(e,U_A);const t=ri(A,"styleVariables",3,""),i=ri(A,"component",3,"p");var n=Jn(),g=Ui(n);vF(g,i,!1,(o,s)=>{let r;Ft(()=>r=KF(o,r,{id:A.id,style:t(),class:"rc-pw-text-block"},"svelte-1wz4si8",o.namespaceURI===gN,o.nodeName.includes("-")));var a=Jn(),I=Ui(a);es(I,()=>A.children??rg),Ue(s,a)}),Ue(e,n),Ni()}var v_A=St('<span class="rc-pw-text-wrapper svelte-11gzifq"><!></span>');const K_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 F_A(e,A){Mi(A,!0),Qi(e,K_A);const t=bd(A,["$$slots","$$events","$$legacy","id","labels","text_lid","purchaseState","variableDictionary","background_color","size"]),i=Ct(()=>G_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=Ct(()=>MA(i).tagToRender),g=Ct(()=>MA(i).textStyles),o=Ct(()=>R_A(t,A.size,A.background_color)),s=Ct(()=>J8({text_lid:A.text_lid,locale:A.purchaseState.locale,defaultLocale:A.purchaseState.defaultLocale,labels:A.labels,variableDictionary:A.variableDictionary})),r=Ct(()=>b_A(MA(s)));var a=v_A(),I=Xe(a);OlA(I,{get styleVariables(){return MA(g)},get component(){return MA(n)},get id(){return A.id},children:(c,l)=>{var B=Jn(),Q=Ui(B);Gd(Q,()=>MA(r)),Ue(c,B)},$$slots:{default:!0}}),Ft(()=>Ii(a,"style",MA(o))),Ue(e,a),Ni()}const __A=e=>{const{background_color:A,margin:t,padding:i,spacing:n,size:g,border:o,shape:s,shadow:r,dimension:a,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=L8(c,I);Object.assign(Q,_L({background_color:A,margin:t,padding:i,border:o,colorMode:l.colorMode,shape:s,shadow:r,...h}),y_A({...a,...h}),TR({...g,...h})),Object.assign(Q,B);const d=Cc(Q,"stack");return tC(d)};function J_A(e){var A,t,i,n,g,o;const{badge:s}=e;if(!s)return"";const r={"--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(r,YlA({alignment:s.alignment}),_L({...s,background_color:s.background_color,color:s.color,colorMode:e.purchaseState.colorMode})),s.style==="overlay"&&(r["--margin-block-start"]="0px",r["--margin-block-end"]="0px",r["--transform"]=yb(s,0,-(((A=e.border)==null?void 0:A.width)||0))),s.style==="edge_to_edge")if(r["--margin-block-start"]="0px",r["--margin-block-end"]="0px",r["--margin-inline-start"]="0px",r["--margin-inline-end"]="0px",s.alignment==="top"||s.alignment==="bottom"){r["--badge-width"]=`calc(100% + ${(((t=e.border)==null?void 0:t.width)||0)*2}px)`,r["--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"&&(r["--padding-block-end"]=`${I+s.padding.bottom}px`,r["--transform"]=yb(s,I)),s.alignment==="bottom"&&(r["--padding-block-start"]=`${I+s.padding.top}px`,r["--transform"]=yb(s,-I))}else r["--transform"]=yb(s),Object.assign(r,L_A(e));const a=Cc(r,"stack-badge");return tC(a)}const h7={top_leading:"bottom_trailing",top_trailing:"bottom_leading",bottom_leading:"top_trailing",bottom_trailing:"top_leading"},p7={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 L_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[p7[h7[s]]]=`${(t=g.shape)==null?void 0:t.corners[h7[s]]}px`,n[p7[s]]=`${((i=e.shape)==null?void 0:i.corners[s])-o}px`,n}function yb(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 x_A(e){const{badge:A}=e;if(!A)return{tagToRender:"",textStyles:""};const{tagToRender:t,textStyles:i}=x8({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=tC(n);return{tagToRender:t,textStyles:g}}function T_A(e){const{dimension:A}=e,t={"--inset":"initial","--transform":"initial","--position":"relative"};if(A.type!=="zlayer")return;const i=YlA({...A});return Object.assign(t,{...i,"--position":"absolute"}),t}var q_A=St('<span class="rc-pw-badge svelte-1b5bst5"><!></span>'),Y_A=St('<div class="rc-pw-stack-wrapper svelte-1b5bst5"><!> <div class="rc-pw-stack svelte-1b5bst5"></div></div>');const H_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 qR(e,A){Mi(A,!0),Qi(e,H_A);const t=bd(A,["$$slots","$$events","$$legacy","id","components","labels","onAction","purchaseState","variableDictionary","badge","zStackChildStyles"]),i=Ct(()=>__A({id:A.id,components:A.components,labels:A.labels,onAction:A.onAction,purchaseState:A.purchaseState,zStackChildStyles:A.zStackChildStyles,...t})),n=Ct(()=>J_A({id:A.id,components:A.components,labels:A.labels,onAction:A.onAction,purchaseState:A.purchaseState,badge:A.badge,...t})),g=Ct(()=>T_A({id:A.id,components:A.components,labels:A.labels,onAction:A.onAction,purchaseState:A.purchaseState,...t})),o=Ct(()=>{var Q;return J8({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=Ct(()=>x_A({id:A.id,components:A.components,labels:A.labels,onAction:A.onAction,purchaseState:A.purchaseState,variableDictionary:A.variableDictionary,badge:A.badge,...t})),r=Ct(()=>MA(s).tagToRender),a=Ct(()=>MA(s).textStyles);var I=Y_A(),c=Xe(I);{var l=Q=>{var h=q_A(),d=Xe(h);OlA(d,{get styleVariables(){return MA(a)},get component(){return MA(r)},children:(p,y)=>{var m=sg();Ft(()=>Dn(m,MA(o))),Ue(p,m)},$$slots:{default:!0}}),Ft(()=>Ii(h,"style",MA(n))),Ue(Q,h)};$t(c,Q=>{A.badge&&Q(l)})}var B=Ht(c,2);MS(B,21,()=>A.components,kS,(Q,h,d)=>{var p=Jn(),y=Ui(p);{var m=S=>{var k=Ct(()=>d>0?MA(g):void 0);xF(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=>{xF(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}})};$t(y,S=>{MA(g)?S(m):S(D,!1)})}Ue(Q,p)}),Ft(()=>{Ii(I,"id",A.id),Ii(I,"style",MA(i))}),Ue(e,I),Ni()}function O_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=Cc(A||{},"button");return tC({...g,position:"var(--button-position, relative)",inset:"var(--button-inset, 0)",transform:"var(--button-transform, initial)",width:n})}const P_A={hash:"svelte-mx8s0a",code:""};function j_A(e,A){Mi(A,!0),Qi(e,P_A);const t=bd(A,["$$slots","$$events","$$legacy","stack","action","onAction","labels","purchaseState","variableDictionary"]),i=()=>{A.onAction&&A.onAction(A.action)},n=Ct(()=>O_A({stack:A.stack,action:A.action,onAction:A.onAction,labels:A.labels,purchaseState:A.purchaseState,variableDictionary:A.variableDictionary,...t}));jlA(e,{onclick:i,get style(){return MA(n)},class:"rc-pw-button",children:(g,o)=>{qR(g,VE(()=>A.stack,{get labels(){return A.labels},get purchaseState(){return A.purchaseState},get variableDictionary(){return A.variableDictionary}}))},$$slots:{default:!0}}),Ni()}function xF(e,A){Mi(A,!0);const t=uI(),i=()=>QI(TlA,"$prefersDarkMode",t),n={stack:qR,text:F_A,image:HJA,button:j_A,purchase_button:jJA,package:VJA,footer:PlA,timeline:gLA},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=bd(A,["$$slots","$$events","$$legacy","nodeData","labels","onAction","purchaseState","variableDictionary","zStackChildStyles"]),s=Ct(()=>g(A.nodeData)),r=Ct(()=>MA(s)[0]),a=Ct(()=>MA(s)[1]);var I=Jn(),c=Ui(I);return EFA(c,()=>MA(r),(l,B)=>{B(l,VE(()=>MA(a)||{},{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=Jn(),p=Ui(d);MS(p,17,()=>A.nodeData.components,kS,(y,m)=>{xF(y,VE({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))}),Ue(Q,d)},$$slots:{default:!0}}))}),Ue(e,I),Ni({getComponentClass:g})}function z_A({background:e,colorMode:A}){const t={"--background":"initial"};(e==null?void 0:e.type)==="color"&&Object.assign(t,{"--background":LE({colorMap:e.value,colorMode:A,fallback:"transparent"})});const i=Cc(t,"paywall");return tC(i)}function Z_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[PC])==null?void 0:g.original)}var W_A=St('<div class="rc-pw-footer svelte-pg5jlz"><!></div>');const V_A={hash:"svelte-pg5jlz",code:".rc-pw-footer.svelte-pg5jlz {position:sticky;bottom:0;transform:translateY(50%);width:100%;}"};function PlA(e,A){Qi(e,V_A);var t=W_A(),i=Xe(t);qR(i,VE(()=>A.stack,{get labels(){return A.labels},get purchaseState(){return A.purchaseState},get variableDictionary(){return A.variableDictionary},get onAction(){return A.onAction}})),Ft(()=>Ii(t,"id",A.id)),Ue(e,t)}var X_A=St('<div class="rc-pw-paywall-background svelte-14bszwq"></div>'),$_A=St('<div class="rc-pw-paywall-background rc-pw-image-container svelte-14bszwq"><img class="rc-pw-image svelte-14bszwq" alt=""></div>'),AJA=St('<div class="rc-pw-paywall svelte-14bszwq"><!> <!> <!></div>');const eJA={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 tJA(e,A){Mi(A,!0),Qi(e,eJA);const t=uI(),i=()=>QI(TlA,"$prefersDarkMode",t),n=ri(A,"variablesPerPackage",19,()=>({}));let g=di({selectedPackageId:m_A(A.paywallData),locale:A.selectedLocale||A.paywallData.default_locale,defaultLocale:A.paywallData.default_locale,variablesPerPackage:n(),colorMode:A.preferredColorMode||(i()?"dark":PC)}),o=gn(di(n()[g.selectedPackageId||""]));const s=(p,y)=>{var m;(m=A.onRestorePurchasesClicked)==null||m.call(A)},r=(p,y)=>{var m;(m=A.onBackClicked)==null||m.call(A)},a=(p,y)=>{var m,D;if(p.destination==="customer_center"&&((m=A.onVisitCustomerCenterClicked)==null||m.call(A)),!p.url)return;const S=LlA(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&&bt(o,di(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":a(p);break;case"navigate_back":r();break;case"restore_purchases":s();break;case"purchase":c();break}},B=Ct(()=>{var p;return z_A({background:(p=A.paywallData.components_config.base)==null?void 0:p.background,colorMode:g.colorMode})}),Q=Ct(()=>Z_A(A.paywallData,g.colorMode));var h=Jn(),d=Ui(h);MFA(d,{get onerror(){return A.onError}},p=>{var y=AJA(),m=Xe(y);xF(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=Ht(m,2);{var S=M=>{PlA(M,VE(()=>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}))};$t(D,M=>{A.paywallData.components_config.base.sticky_footer&&M(S)})}var k=Ht(D,2);{var N=M=>{var w=X_A();Ft(()=>Ii(w,"style",MA(B))),Ue(M,w)},G=M=>{var w=Jn(),b=Ui(w);{var _=K=>{var J=$_A(),T=Xe(J);Ft(()=>Ii(T,"src",MA(Q))),Ue(K,J)};$t(b,K=>{var J;((J=A.paywallData.components_config.base.background)==null?void 0:J.type)==="image"&&K(_)},!0)}Ue(M,w)};$t(k,M=>{var w;((w=A.paywallData.components_config.base.background)==null?void 0:w.type)==="color"?M(N):M(G,!1)})}Ue(p,y)}),Ue(e,h),Ni()}const iJA=(e,A)=>{var t;(t=A.onclick)==null||t.call(A)};var nJA=St("<button><!></button>");const gJA={hash:"svelte-1wpam0z",code:"button.svelte-1wpam0z {border:none;cursor:pointer;background:transparent;width:fit-content;}"};function jlA(e,A){Mi(A,!0),Qi(e,gJA);var t=nJA();t.__click=[iJA,A];var i=Xe(t);es(i,()=>A.children??rg),Ft(()=>{sd(t,NlA(A.class),"svelte-1wpam0z"),t.disabled=!A.onclick,Ii(t,"style",A.style)}),Ue(e,t),Ni()}KL(["click"]);var oJA=St('<div class="rcb-processing svelte-2j2b59"></div>');const sJA={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 rJA(e,A){Qi(e,sJA);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=oJA();Ft(()=>Ii(n,"style",`--shadow-offset: ${i[t()].offset??""}; --width: ${i[t()].width??""};`)),Ue(e,n)}var aJA=St("<span><!></span>");const IJA={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 CJA(e,A){Mi(A,!0),Qi(e,IJA);const t=ri(A,"size",3,"body-base");var i=aJA(),n=Xe(i);es(n,()=>A.children??rg),Ft(()=>sd(i,`rcb-typography rcb-typography-${t()??""} svelte-byrjto`)),Ue(e,i),Ni()}const cJA={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"},lJA={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"},zlA={error:"color_error",focus:"color_accent",accent:"color_accent",primary:"color_buttons_primary"},BJA={...zlA,"input-background":"color_form_bg",background:"color_form_bg"},EJA={...zlA,"input-background":"color_product_info_bg",background:"color_product_info_bg"},ZlA={"input-border-radius":"4px","input-button-border-radius":"8px"},QJA={"input-border-radius":"0px","input-button-border-radius":"0px"},uJA={"input-border-radius":"12px","input-button-border-radius":"9999px"},f7=ZlA,y7="-apple-system, BlinkMacSystemFont, avenir next, avenir, segoe ui, helvetica neue, helvetica, Cantarell, Ubuntu, roboto, noto, arial, sans-serif",ml={regular:"400",medium:"500",semibold:"600"},vC={12:"12px",14:"14px",16:"16px",18:"18px",24:"24px",28:"28px",32:"32px",36:"36px"},Sl={120:"120%",130:"130%",140:"140%"},wl={tight:"0.20%",regular:"0"},as={heading2xl:{fontSize:vC[28],lineHeight:Sl[120],fontWeight:ml.semibold,letterSpacing:wl.tight},headingXl:{fontSize:vC[24],lineHeight:Sl[130],fontWeight:ml.semibold,letterSpacing:wl.regular},headingLg:{fontSize:"20px",lineHeight:Sl[130],fontWeight:ml.semibold,letterSpacing:wl.regular},headingMd:{fontSize:"16px",lineHeight:Sl[140],fontWeight:ml.medium,letterSpacing:wl.regular},bodyBase:{fontSize:vC[16],lineHeight:Sl[140],fontWeight:ml.regular,letterSpacing:wl.regular},bodySmall:{fontSize:vC[14],lineHeight:Sl[140],fontWeight:ml.regular,letterSpacing:wl.regular},labelButton:{fontSize:vC[16],lineHeight:Sl[140],fontWeight:ml.regular,letterSpacing:wl.tight},labelDefault:{fontSize:vC[14],lineHeight:Sl[140],fontWeight:ml.regular,letterSpacing:wl.tight},captionDefault:{fontSize:vC[12],lineHeight:Sl[140],fontWeight:ml.regular,letterSpacing:wl.regular},captionLink:{fontSize:vC[12],lineHeight:Sl[140],fontWeight:ml.regular,letterSpacing:wl.regular}},kl={heading2xl:{...as.heading2xl,fontSize:vC[36]},headingXl:{...as.headingXl,fontSize:vC[32]},headingLg:{...as.headingLg,fontSize:vC[24]},headingMd:{...as.headingMd,fontSize:vC[18]},bodyBase:{...as.bodyBase},bodySmall:{...as.bodySmall},labelButton:{...as.labelButton},labelDefault:{...as.labelDefault},captionDefault:{...as.captionDefault},captionLink:{...as.captionLink}},dJA={heading2xl:{mobile:as.heading2xl,desktop:kl.heading2xl},headingXl:{desktop:kl.headingXl,mobile:as.headingXl},headingLg:{desktop:kl.headingLg,mobile:as.headingLg},headingMd:{desktop:kl.headingMd,mobile:as.headingMd},bodyBase:{desktop:kl.bodyBase,mobile:as.bodyBase},bodySmall:{desktop:kl.bodySmall,mobile:as.bodySmall},labelButton:{desktop:kl.labelButton,mobile:as.labelButton},labelDefault:{desktop:kl.labelDefault,mobile:as.labelDefault},captionDefault:{desktop:kl.captionDefault,mobile:as.captionDefault},captionLink:{desktop:kl.captionLink,mobile:as.captionLink}},rN=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,T8=({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},q8=.37,hJA=(e,A=q8)=>{const t=T8({...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 pJA(e,A,t){const i=rN(e)||{r:0,g:0,b:0},n=rN(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`#${h2(g)}${h2(o)}${h2(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=rN(e)||t;(isNaN(g.r)||isNaN(g.g)||isNaN(g.b))&&(g=t,n="#FFFFFF");const o=T8({...g,luminanceThreshold:q8})?"#000000":"#FFFFFF";return pJA(n,o,i)}function h2(e){return e.toString(16).padStart(2,"0").toUpperCase()}const fJA=(e,A,t,i=q8)=>{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=rN(e);g!==null&&Object.assign(n,hJA(g))}if(A!=null&&A.startsWith("#")){const g=rN(A);g!==null&&(n["primary-text"]=T8({...g,luminanceThreshold:i})?"black":"white")}return n},yJA=e=>({"primary-hover":D7(e,.1),"primary-pressed":D7(e,.15)}),DJA=(e,A)=>e||A,mJA=(e,A,t)=>{const i=Object.entries(e).map(([n,g])=>[n,DJA(t?t[g]:null,A[n])]);return Object.fromEntries(i)},WlA=(e,A,t)=>{const i=mJA(e,A,t);return t?{...A,...i,...fJA(i.background,i.primary,A),...yJA(i.primary)}:{...A}},SJA=e=>WlA(EJA,lJA,e),VlA=e=>WlA(BJA,cJA,e),Y8=e=>{if(!e)return f7;switch(e.shapes){case"rounded":return ZlA;case"rectangle":return QJA;case"pill":return uJA;default:return f7}},TF=(e="",A)=>A.map(([t,i])=>`--rc-${e}-${t}: ${i}`).join("; "),wJA=e=>{const A=TF("color",Object.entries(SJA(e))),t=TF("shape",Object.entries(Y8(e)));return[A,t].join("; ")},kJA=e=>{const A=TF("color",Object.entries(VlA(e))),t=TF("shape",Object.entries(Y8(e)));return[A,t].join("; ")},MJA=(e="",A)=>Object.entries(A).flatMap(([t,{desktop:i,mobile:n}])=>[`--rc-${e}-${t}-desktop: normal normal ${i.fontWeight} ${i.fontSize}/${i.lineHeight} ${y7}`,`--rc-${e}-${t}-mobile: normal normal ${n.fontWeight} ${n.fontSize}/${n.lineHeight} ${y7}`,`--rc-${e}-${t}-desktop-font-size: ${i.fontSize}`,`--rc-${e}-${t}-mobile-font-size: ${n.fontSize}`]).join("; "),NJA=(e="",A)=>Object.entries(A).map(([t,{mobile:i,desktop:n}])=>`--rc-${e}-${t}-mobile: ${i};  --rc-${e}-${t}-desktop: ${n};`).join(" "),RJA={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 GJA=class{constructor(e){Tt(this,"brandingAppearance"),e?this.brandingAppearance=e:this.brandingAppearance=void 0}get shape(){return Y8(this.brandingAppearance)}get formColors(){return VlA(this.brandingAppearance)}get formStyleVars(){return kJA(this.brandingAppearance)}get productInfoStyleVars(){return wJA(this.brandingAppearance)}get spacing(){return RJA}get textStyles(){return dJA}get textStyleVars(){return MJA("text",this.textStyles)}get spacingStyleVars(){return NJA("spacing",this.spacing)}};var bJA=St("<button><!></button>");const UJA={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 XlA(e,A){Mi(A,!0),Qi(e,UJA);const t=ri(A,"intent",3,"primary"),i=ri(A,"disabled",3,!1),n=ri(A,"loading",3,!1),g=Ct(()=>new GJA(A.brandingAppearance)),o=Ct(()=>MA(g).textStyleVars),s=Ct(()=>MA(g).spacingStyleVars),r=Ct(()=>MA(g).productInfoStyleVars),a=Ct(()=>MA(g).formStyleVars),I=Ct(()=>[A.styleOverrides,MA(o),MA(s),MA(r),MA(a)].join("; "));var c=bJA();c.__click=function(...h){var d;(d=A.onclick)==null||d.apply(this,h)};var l=Xe(c);{var B=h=>{rJA(h,{size:"small"})},Q=h=>{CJA(h,{size:"body-base",children:(d,p)=>{var y=Jn(),m=Ui(y);BFA(m,A,"default",{}),Ue(d,y)},$$slots:{default:!0}})};$t(l,h=>{n()?h(B):h(Q,!1)})}Ft(()=>{sd(c,`${`intent-${t()}`??""} svelte-td7xvm`),c.disabled=i(),Ii(c,"data-testid",A.testId),Ii(c,"type",A.type),Ii(c,"style",MA(I))}),Ue(e,c),Ni()}KL(["click"]);const vJA=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=L8(t,i);Object.assign(g,n),Object.assign(g,TR({...A,...o})),Object.assign(g,k_A(e.mask_shape));const s=Cc(g,"image"),r=w_A(e),a=M_A(e);return{imageStyles:tC(s),maskPath:r,linearGradientAngle:a}};var KJA=RB('<ellipse cx="50" rx="50"></ellipse>'),FJA=RB("<path></path>"),_JA=RB("<stop></stop>"),JJA=RB("<linearGradient></linearGradient>"),LJA=RB("<stop></stop>"),xJA=RB('<radialGradient cx="50%" cy="50%" r="50%" fx="50%" fy="50%"></radialGradient>'),TJA=RB('<linearGradient><stop offset="0%"></stop></linearGradient>'),qJA=St('<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 YJA={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 HJA(e,A){Mi(A,!0),Qi(e,YJA);const t=bd(A,["$$slots","$$events","$$legacy","id","source","purchaseState"]);let i=gn(0),n;function g(){n&&bt(i,n.naturalHeight/n.naturalWidth)}const o=Ct(()=>vJA({id:A.id,colorMode:A.purchaseState.colorMode,source:A.source,purchaseState:A.purchaseState,...t,imageAspectRatio:MA(i)})),s=Ct(()=>MA(o).imageStyles),r=Ct(()=>MA(o).maskPath),a=Ct(()=>MA(o).linearGradientAngle),I=Ct(()=>{var G,M;const w=A.purchaseState.colorMode;return(G=A.source[w])!=null&&G.original?A.source[w].original:(M=A.source[PC])==null?void 0:M.original});var c=qJA(),l=Ui(c);vlA(l,G=>n=G,()=>n);var B=Ht(l,2),Q=Xe(B),h=Xe(Q),d=Xe(h);{var p=G=>{var M=KJA();Ft(()=>{Ii(M,"cy",MA(i)*50),Ii(M,"ry",MA(i)*50)}),Ue(G,M)},y=G=>{var M=FJA();Ft(()=>Ii(M,"d",MA(r))),Ue(G,M)};$t(d,G=>{var M;((M=A.mask_shape)==null?void 0:M.type)==="circle"?G(p):G(y,!1)})}var m=Ht(h);{var D=G=>{var M=JJA();MS(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:_[PC])==null?void 0:K.points)||[]},kS,(w,b)=>{var _=_JA();Ft(()=>{Ii(_,"offset",`${MA(b).percent}%`),Ii(_,"style",`stop-color: ${MA(b).color}`)}),Ue(w,_)}),Ft(()=>{Ii(M,"id",`gradient-${A.id}`),Ii(M,"x1",MA(a).x1),Ii(M,"y1",MA(a).y1),Ii(M,"x2",MA(a).x2),Ii(M,"y2",MA(a).y2)}),Ue(G,M)},S=G=>{var M=Jn(),w=Ui(M);{var b=K=>{var J=xJA();MS(J,21,()=>{var T,v,U,x;return((v=(T=A.color_overlay)==null?void 0:T[A.purchaseState.colorMode])==null?void 0:v.points)||((x=(U=A.color_overlay)==null?void 0:U[PC])==null?void 0:x.points)||[]},kS,(T,v)=>{var U=LJA();Ft(()=>{Ii(U,"offset",`${MA(v).percent}%`),Ii(U,"style",`stop-color: ${MA(v).color}`)}),Ue(T,U)}),Ft(()=>Ii(J,"id",`gradient-${A.id}`)),Ue(K,J)},_=K=>{var J=Jn(),T=Ui(J);{var v=U=>{var x=TJA(),q=Xe(x);Ft(()=>{var z,Z,eA;Ii(x,"id",`gradient-${A.id}`),Ii(q,"style",`stop-color: ${((z=A.color_overlay[A.purchaseState.colorMode])==null?void 0:z.value)||((eA=(Z=A.color_overlay)==null?void 0:Z[PC])==null?void 0:eA.value)}`)}),Ue(U,x)};$t(T,U=>{var x,q;((q=(x=A.color_overlay)==null?void 0:x[A.purchaseState.colorMode])==null?void 0:q.type)==="hex"&&U(v)},!0)}Ue(K,J)};$t(w,K=>{var J,T;((T=(J=A.color_overlay)==null?void 0:J[A.purchaseState.colorMode])==null?void 0:T.type)==="radial"?K(b):K(_,!1)},!0)}Ue(G,M)};$t(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=Ht(Q),N=Ht(k);Ft(()=>{Ii(l,"src",MA(I)),Ii(B,"id",`rc-pw-image-container-${A.id}`),Ii(B,"style",MA(s)),Ii(B,"viewBox",`0 0 100 ${MA(i)*100}`),Ii(h,"id",`clip-path-${A.id}`),Ii(k,"href",MA(I)),Ii(k,"height",MA(i)*100),Ii(k,"clip-path",`url(#clip-path-${A.id})`),Ii(k,"id",A.id),Ii(N,"height",MA(i)*100),Ii(N,"clip-path",`url(#clip-path-${A.id})`),Ii(N,"fill",`url(#gradient-${A.id})`)}),nB("load",l,g),Ue(e,c),Ni()}function OJA({stack:e,zStackChildStyles:A}){const t=e.size.width.type==="fill"?"100%":"fit-content",i=Cc(A||{},"purchase-button");return tC({...i,position:"var(--purchase-button-position, relative)",inset:"var(--purchase-button-inset, 0)",transform:"var(--purchase-button-transform, initial)",width:t})}const PJA={hash:"svelte-1x8zwdp",code:""};function jJA(e,A){Mi(A,!0),Qi(e,PJA);const t=bd(A,["$$slots","$$events","$$legacy","stack","labels","onAction","purchaseState","variableDictionary","zStackChildStyles"]),i=()=>{A.onAction&&A.onAction({type:"purchase"})},n=Ct(()=>OJA({stack:A.stack,labels:A.labels,onAction:A.onAction,purchaseState:A.purchaseState,variableDictionary:A.variableDictionary,zStackChildStyles:A.zStackChildStyles,...t}));jlA(e,{onclick:i,class:"rc-pw-purchase-button",get style(){return MA(n)},children:(g,o)=>{qR(g,VE(()=>A.stack,{get labels(){return A.labels},get purchaseState(){return A.purchaseState},get variableDictionary(){return A.variableDictionary}}))},$$slots:{default:!0}}),Ni()}const zJA=(e,A)=>{e.preventDefault(),e.stopPropagation(),A.onAction&&A.onAction({type:"select_package"},{packageId:A.package_id})};var ZJA=St('<button class="rc-pw-package svelte-123kamd"><!></button>');const WJA={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 VJA(e,A){Mi(A,!0),Qi(e,WJA);const t=Ct(()=>{var s;return((s=A.purchaseState.variablesPerPackage)==null?void 0:s[A.package_id])||A.variableDictionary}),i=Ct(()=>{var s;return{selected:((s=A.purchaseState)==null?void 0:s.selectedPackageId)===A.package_id}}),n=Ct(()=>tC(Cc(A.zStackChildStyles,"package")));var g=ZJA();g.__click=[zJA,A];var o=Xe(g);qR(o,VE(()=>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)}})),Ft(()=>{Ii(g,"id",A.id),Ii(g,"style",MA(n)),JE(g,"selected",MA(i).selected)}),Ue(e,g),Ni()}KL(["click"]);function XJA(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,TR(e.size)),Object.assign(A,e.zStackChildStyles);const t=Cc(A,"timeline");return tC(t)}function $JA(e){var A,t,i,n,g,o,s,r,a,I;const c={"--icon-size":`${e.icon.width_and_height}px`,"--icon-padding":`${e.icon.padding}px`,"--icon-color":LE({colorMap:e.icon.color,colorMode:(A=e.purchaseState)==null?void 0:A.colorMode}),"--icon-background-color":LE({colorMap:(t=e.icon_background)==null?void 0:t.color,colorMode:e.purchaseState.colorMode}),"--icon-border":qlA((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":LE({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,((r=(s=e.icon_background)==null?void 0:s.shape)==null?void 0:r.type)==="rectangle"?LF((I=(a=e.icon_background)==null?void 0:a.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=Cc(c,"timeline-item");return tC(l)}function m7(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"},r={color:((t=e[A])==null?void 0:t.color)||HlA,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:a,textStyles:I}=x8({...e,components:[],...r,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=tC(Cc(s,"timeline-item")),l=J8({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:a,textLabel:l}}var ALA=St('<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 eLA={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 tLA(e,A){Mi(A,!0),Qi(e,eLA);const t=bd(A,["$$slots","$$events","$$legacy"]),i=Ct(()=>$JA(t)),n=Ct(()=>m7(t,"title")),g=Ct(()=>MA(n).tagToRender),o=Ct(()=>MA(n).textStyles),s=Ct(()=>MA(n).textLabel),r=Ct(()=>m7(t,"description")),a=Ct(()=>MA(r).tagToRender),I=Ct(()=>MA(r).textStyles),c=Ct(()=>MA(r).textLabel);var l=ALA(),B=Ht(Xe(l),2),Q=Xe(B);vF(Q,()=>MA(g),!1,(p,y)=>{let m;Ft(()=>m=KF(p,m,{class:"rc-pw-timeline-item-content-title",style:MA(o)},"svelte-gjmo4g",p.namespaceURI===gN,p.nodeName.includes("-")));var D=sg();Ft(()=>Dn(D,MA(s))),Ue(y,D)});var h=Ht(Q,2);{var d=p=>{var y=Jn(),m=Ui(y);vF(m,()=>MA(a),!1,(D,S)=>{let k;Ft(()=>k=KF(D,k,{class:"rc-pw-timeline-item-content-description",style:MA(I)},"svelte-gjmo4g",D.namespaceURI===gN,D.nodeName.includes("-")));var N=sg();Ft(()=>Dn(N,MA(c))),Ue(S,N)}),Ue(p,y)};$t(h,p=>{MA(c)&&p(d)})}Ft(()=>Ii(l,"style",MA(i))),Ue(e,l),Ni()}var iLA=St('<div class="rc-pw-timeline-container svelte-12g27vu"></div>');const nLA={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 gLA(e,A){Mi(A,!0),Qi(e,nLA);const t=bd(A,["$$slots","$$events","$$legacy","items"]),i=Ct(()=>XJA({items:A.items,...t}));var n=Jn(),g=Ui(n);{var o=s=>{var r=iLA();MS(r,21,()=>A.items,kS,(a,I,c)=>{var l=Ct(()=>`${A.id}-${c}`),B=Ct(()=>`${A.name}-${c}`);tLA(a,VE(()=>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}}))}),Ft(()=>Ii(r,"style",MA(i))),Ue(s,r)};$t(g,s=>{A.items.length&&s(o)})}Ue(e,n),Ni()}var oLA=St('<footer class="rcb-modal-footer svelte-1f9z0o8"><!></footer>');const sLA={hash:"svelte-1f9z0o8",code:"footer.svelte-1f9z0o8 {display:flex;flex-direction:column;}"};function rLA(e,A){Mi(A,!1),Qi(e,sLA);let t=ri(A,"children",8);Ic();var i=oLA(),n=Xe(i);es(n,()=>t()??rg),Ue(e,i),Ni()}const aLA={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 ILA(e,A){Mi(A,!1),Qi(e,aLA);let t=ri(A,"as",8,"section"),i=ri(A,"children",8);Ic();var n=Jn(),g=Ui(n);vF(g,t,!1,(o,s)=>{KF(o,null,{class:"rcb-modal-section"},"svelte-1bzqb13",o.namespaceURI===gN,o.nodeName.includes("-"));var r=Jn(),a=Ui(r);es(a,()=>i()??rg),Ue(s,r)}),Ue(e,n),Ni()}var CLA=St("<div><!></div>");const cLA={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 $lA(e,A){Mi(A,!1),Qi(e,cLA);let t=ri(A,"gap",8,"small"),i=ri(A,"align",8,"start"),n=ri(A,"children",8);Ic();var g=CLA(),o=Xe(g);es(o,()=>n()??rg),Ft(()=>sd(g,`rcb-column gap-${t()??""} align-${i()??""} svelte-b5dygi`)),Ue(e,g),Ni()}var lLA=St('<div class="rcb-row svelte-1seeuxq"><!></div>');const BLA={hash:"svelte-1seeuxq",code:".rcb-row.svelte-1seeuxq {display:flex;flex-direction:row;justify-content:flex-start;}"};function ELA(e,A){Mi(A,!1),Qi(e,BLA);let t=ri(A,"children",8);Ic();var i=lLA(),n=Xe(i);es(n,()=>t()??rg),Ue(e,i),Ni()}var QLA=St("<span><!></span>");const uLA={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 Pn(e,A){Mi(A,!0),Qi(e,uLA);const t=ri(A,"size",3,"body-base"),i=ri(A,"branded",3,!1);var n=QLA(),g=Xe(n);es(g,()=>A.children??rg),Ft(()=>sd(n,`rcb-typography rcb-typography-${t()??""} ${(i()?"rcb-typography-branded":"")??""} svelte-orw2sj`)),Ue(e,n),Ni()}var dLA=St("<div><!></div>"),hLA=St('<span style="display: block;"><!></span>'),pLA=St("<!> <!>",1),fLA=St("<!> <!>",1),yLA=St('<div class="rcb-modal-message svelte-w46z5s" data-type="error"><!></div>');const DLA={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 mLA(e,A){Mi(A,!0),Qi(e,DLA);const t=ri(A,"title",3,null),i=ri(A,"icon",3,null),n=32;let g=gn(null),o=gn(!1),s;gc(()=>(MA(g)&&(s=new ResizeObserver(()=>{var I;bt(o,(((I=MA(g))==null?void 0:I.offsetHeight)??0)>n)}),s.observe(MA(g))),()=>{s==null||s.disconnect()}));var r=yLA(),a=Xe(r);$lA(a,{gap:"medium",align:"start",children:(I,c)=>{var l=fLA(),B=Ui(l);ELA(B,{children:(d,p)=>{var y=pLA(),m=Ui(y);{var D=N=>{var G=dLA(),M=Xe(G);es(M,i),Ft(()=>sd(G,`rcb-modal-message-icon ${MA(o)?"large":"small"} svelte-w46z5s`)),Ue(N,G)};$t(m,N=>{i()&&N(D)})}var S=Ht(m,2);{var k=N=>{var G=hLA(),M=Xe(G);Pn(M,{size:"heading-md",children:(w,b)=>{var _=sg();Ft(()=>Dn(_,t())),Ue(w,_)},$$slots:{default:!0}}),vlA(G,w=>bt(g,w),()=>MA(g)),Ue(N,G)};$t(S,N=>{t()&&N(k)})}Ue(d,y)},$$slots:{default:!0}});var Q=Ht(B,2);{var h=d=>{Pn(d,{size:"body-small",children:(p,y)=>{var m=Jn(),D=Ui(m);es(D,()=>A.message??rg),Ue(p,m)},$$slots:{default:!0}})};$t(Q,d=>{A.message&&d(h)})}Ue(I,l)},$$slots:{default:!0}}),Ft(()=>Ii(r,"data-has-title",!!t())),Ue(e,r),Ni()}var SLA=St('<div class="rcb-modal-message-icon svelte-c8cuu5"><!></div>'),wLA=St("<!> <!>",1),kLA=St('<div class="rcb-modal-message svelte-c8cuu5" data-type="success"><!></div>');const MLA={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 NLA(e,A){Mi(A,!0),Qi(e,MLA);const t=ri(A,"title",3,null),i=ri(A,"icon",3,null);var n=kLA(),g=Xe(n);$lA(g,{gap:"large",align:"center",children:(o,s)=>{var r=wLA(),a=Ui(r);{var I=B=>{var Q=SLA(),h=Xe(Q);es(h,i),Ue(B,Q)};$t(a,B=>{i()&&B(I)})}var c=Ht(a,2);{var l=B=>{Pn(B,{size:"heading-md",children:(Q,h)=>{var d=sg();Ft(()=>Dn(d,t())),Ue(Q,d)},$$slots:{default:!0}})};$t(c,B=>{t()&&B(l)})}Ue(o,r)},$$slots:{default:!0}}),Ft(()=>Ii(n,"data-has-title",!!t())),Ue(e,n),Ni()}const H8="rcb-ui-events-tracker",O8="branding";var RLA=St('<div class="message-layout svelte-qavr33"><div class="message-layout-content svelte-qavr33"><!></div> <div class="message-layout-footer"><!></div></div>');const GLA={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 P8(e,A){Mi(A,!0),Qi(e,GLA);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=Xr(O8);function s(){A.onDismiss()}var r=RLA(),a=Xe(r),I=Xe(a);ILA(I,{children:(B,Q)=>{var h=Jn(),d=Ui(h);{var p=m=>{NLA(m,{get title(){return t()},get icon(){return n()}})},y=m=>{mLA(m,{get title(){return t()},get icon(){return n()},get message(){return g()}})};$t(d,m=>{A.type==="success"?m(p):m(y,!1)})}Ue(B,h)},$$slots:{default:!0}});var c=Ht(a,2),l=Xe(c);rLA(l,{children:(B,Q)=>{XlA(B,{onclick:s,type:"submit",brandingAppearance:o,children:(h,d)=>{var p=sg();Ft(()=>Dn(p,i())),Ue(h,p)},$$slots:{default:!0}})},$$slots:{default:!0}}),Ue(e,r),Ni()}function Va(e,A){Mi(A,!0);const t=uI(),i=()=>QI(g,"$translator",t),n=ri(A,"key",3,""),g=Xr(eC),o=Ct(()=>n()?i().translate(n()||"",A.variables):void 0);var s=Jn(),r=Ui(s);{var a=c=>{var l=sg();Ft(()=>Dn(l,MA(o))),Ue(c,l)},I=c=>{var l=Jn(),B=Ui(l);es(B,()=>A.children??rg),Ue(c,l)};$t(r,c=>{MA(o)?c(a):c(I,!1)})}Ue(e,s),Ni()}var bLA=St('<p class="footer-caption svelte-1hbk6xu"><!></p>'),ULA=St('<p class="footer-caption svelte-1hbk6xu"><!></p>'),vLA=St('<div class="footer-caption-container svelte-1hbk6xu"><!> <!> <p class="footer-caption svelte-1hbk6xu"><!></p></div>');const KLA={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 FLA(e,A){Mi(A,!1),Qi(e,KLA);const t=uI(),i=()=>QI(d,"$translator",t),n=kc(),g=kc(),o=kc(),s=kc(),r=kc(),a=kc(),I=kc(),c=kc(),l=kc(),B=kc();let Q=ri(A,"brandingInfo",8,null),h=ri(A,"purchaseOption",8,null);const d=Xr(eC);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}Dl(()=>gK(h()),()=>{bt(n,p(h())?h():null)}),Dl(()=>gK(h()),()=>{bt(g,y(h())?h():null)}),Dl(()=>MA(n),()=>{bt(o,m(MA(n)))}),Dl(()=>MA(n),()=>{var b,_;bt(s,((b=MA(n))==null?void 0:b.introPrice)||((_=MA(n))==null?void 0:_.base))}),Dl(()=>(MA(g),MA(s)),()=>{var b,_;bt(r,((b=MA(g))==null?void 0:b.basePrice)||((_=MA(s))==null?void 0:_.price))}),Dl(()=>(MA(r),i()),()=>{bt(a,MA(r)?ju(MA(r).amountMicros,MA(r).currency,i().locale||i().fallbackLocale):null)}),Dl(()=>(MA(s),i()),()=>{var b,_,K,J,T;bt(I,(b=MA(s))!=null&&b.period?i().translatePeriodFrequency(((K=(_=MA(s))==null?void 0:_.period)==null?void 0:K.number)||1,(T=(J=MA(s))==null?void 0:J.period)==null?void 0:T.unit,{useMultipleWords:!0}):null)}),Dl(()=>(MA(n),i(),hP),()=>{var b,_;bt(c,(_=(b=MA(n))==null?void 0:b.trial)!=null&&_.period?i().translateDate(hP(new Date,MA(n).trial.period,!0),{year:"numeric",month:"long",day:"numeric"}):null)}),Dl(()=>(gK(Q()),MA(r),i(),MA(o),MA(a),MA(I),MA(c)),()=>{var b;bt(l,Q()&&MA(r)?i().translate(MA(o),{appName:(b=Q())==null?void 0:b.app_name,price:MA(a),perFrequency:MA(I),renewalDate:MA(c)}):null)}),Dl(()=>(MA(n),i(),oi),()=>{bt(B,MA(n)?i().translate(oi.PaymentEntryPageSubscriptionInfo):null)}),jKA(),Ic();var D=vLA(),S=Xe(D);{var k=b=>{var _=bLA(),K=Xe(_);Pn(K,{size:"caption-default",children:(J,T)=>{var v=sg();Ft(()=>Dn(v,MA(l))),Ue(J,v)},$$slots:{default:!0}}),Ue(b,_)};$t(S,b=>{MA(l)&&b(k)})}var N=Ht(S,2);{var G=b=>{var _=ULA(),K=Xe(_);Pn(K,{size:"caption-default",children:(J,T)=>{var v=sg();Ft(()=>Dn(v,MA(B))),Ue(J,v)},$$slots:{default:!0}}),Ue(b,_)};$t(N,b=>{MA(B)&&b(G)})}var M=Ht(N,2),w=Xe(M);Pn(w,{size:"caption-default",children:(b,_)=>{Va(b,{get key(){return oi.PaymentEntryPagePaymentStepTitle}})},$$slots:{default:!0}}),Ue(e,D),Ni()}var lI=(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))(lI||{}),j8=(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))(j8||{});function _LA({errorCode:e,errorMessage:A}){return{eventName:lI.CheckoutFlowError,properties:{errorCode:e,errorMessage:A}}}function JLA({errorCode:e,errorMessage:A}){return{eventName:lI.CheckoutPaymentFormError,properties:{errorCode:e,errorMessage:A}}}function LLA({appearance:e,rcPackage:A,purchaseOptionToUse:t,customerEmail:i}){return{eventName:lI.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 xLA({redemptionInfo:e}){return{eventName:lI.CheckoutSessionEnd,properties:{outcome:"finished",withRedemptionInfo:!!e}}}function TLA(){return{eventName:lI.CheckoutSessionEnd,properties:{outcome:"closed"}}}function qLA({errorCode:e,errorMessage:A}){return{eventName:lI.CheckoutSessionEnd,properties:{outcome:"errored",errorCode:e,errorMessage:A}}}function YLA({taxCalculation:e,taxCustomerDetails:A}){const t=e.failed_reason===j8.tax_collection_disabled?"disabled":e.failed_reason?"failed":e.tax_amount_in_micros===0?"not-taxed":"taxed",i=A===null?"auto":"form";return{eventName:lI.CheckoutPaymentTaxCalculation,properties:{outcome:t,ui_element:i,tax_inclusive:e.tax_inclusive,error_code:e.failed_reason??null}}}function HLA({selectedPaymentMethod:e}){return{eventName:lI.CheckoutPaymentFormSubmit,properties:{selectedPaymentMethod:e??null}}}function OLA({errorCode:e,errorMessage:A}){return{eventName:lI.CheckoutPaymentFormGatewayError,properties:{errorCode:e,errorMessage:A}}}const PLA=`<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 jLA=St('<div style="color:var(--rc-color-accent);" class="rcb-ui-asset-icon svelte-1sxpw7o"><!></div>');const zLA={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 ZLA(e){Qi(e,zLA);var A=jLA(),t=Xe(A);Gd(t,()=>PLA),Ue(e,A)}var WLA=St('<div class="rcb-modal-loader svelte-102edf4"><!></div>');const VLA={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 ABA(e){Qi(e,VLA);var A=WLA(),t=Xe(A);ZLA(t),Ue(e,A)}function XLA(e,A){var t,i;Mi(A,!0);const n=uI(),g=()=>QI(o,"$translator",n),o=Xr(eC),s=Xr(O8),r=Ct(()=>A.priceBreakdown?g().formatPrice(A.priceBreakdown.totalAmountInMicros,A.priceBreakdown.currency):null),a=(i=(t=A.subscriptionOption)==null?void 0:t.trial)==null?void 0:i.period,I=Ct(()=>a?g().translatePeriod(a.number,a.unit):null);XlA(e,{get disabled(){return A.disabled},testId:"PayButton",brandingAppearance:s,children:(c,l)=>{var B=Jn(),Q=Ui(B);{var h=p=>{var y=Ct(()=>({trialPeriodLabel:MA(I)}));Va(p,{get key(){return oi.PaymentEntryPageButtonStartTrial},get variables(){return MA(y)}})},d=p=>{var y=Jn(),m=Ui(y);{var D=k=>{var N=Ct(()=>({formattedPrice:MA(r)}));Va(k,{get key(){return oi.PaymentEntryPageButtonWithPrice},get variables(){return MA(N)}})},S=k=>{Va(k,{get key(){return oi.PaymentEntryPageButtonPay}})};$t(m,k=>{MA(r)?k(D):k(S,!1)},!0)}Ue(p,y)};$t(Q,p=>{var y;(y=A.subscriptionOption)!=null&&y.trial?p(h):p(d,!1)})}Ue(c,B)},$$slots:{default:!0}}),Ni()}const $LA={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"},AxA={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"},eBA={error:"color_error",focus:"color_accent",accent:"color_accent",primary:"color_buttons_primary"},exA={...eBA,"input-background":"color_form_bg",background:"color_form_bg"},txA={...eBA,"input-background":"color_product_info_bg",background:"color_product_info_bg"},tBA={"input-border-radius":"4px","input-button-border-radius":"8px"},ixA={"input-border-radius":"0px","input-button-border-radius":"0px"},nxA={"input-border-radius":"12px","input-button-border-radius":"9999px"},S7=tBA,qF="-apple-system, BlinkMacSystemFont, avenir next, avenir, segoe ui, helvetica neue, helvetica, Cantarell, Ubuntu, roboto, noto, arial, sans-serif",iBA="BrandCustomFont",w7=`${iBA}, ${qF}`,Ml={regular:"400",medium:"500",semibold:"600"},KC={12:"12px",14:"14px",16:"16px",18:"18px",24:"24px",28:"28px",32:"32px",36:"36px"},Nl={130:"130%",140:"140%"},Rl={tight:"0.20%",regular:"0",loose:"0.20%"},Is={heading2xl:{fontSize:KC[28],lineHeight:Nl[130],fontWeight:Ml.semibold,letterSpacing:Rl.loose},headingXl:{fontSize:KC[24],lineHeight:Nl[130],fontWeight:Ml.semibold,letterSpacing:Rl.loose},headingLg:{fontSize:"20px",lineHeight:Nl[130],fontWeight:Ml.semibold,letterSpacing:Rl.loose},headingMd:{fontSize:"16px",lineHeight:Nl[140],fontWeight:Ml.medium,letterSpacing:Rl.regular},bodyBase:{fontSize:KC[16],lineHeight:Nl[140],fontWeight:Ml.regular,letterSpacing:Rl.regular},bodySmall:{fontSize:KC[14],lineHeight:Nl[140],fontWeight:Ml.regular,letterSpacing:Rl.regular},labelButton:{fontSize:KC[16],lineHeight:Nl[140],fontWeight:Ml.semibold,letterSpacing:Rl.tight},labelDefault:{fontSize:KC[14],lineHeight:Nl[140],fontWeight:Ml.regular,letterSpacing:Rl.tight},captionDefault:{fontSize:KC[12],lineHeight:Nl[140],fontWeight:Ml.regular,letterSpacing:Rl.regular},captionLink:{fontSize:KC[12],lineHeight:Nl[140],fontWeight:Ml.regular,letterSpacing:Rl.regular}},Gl={heading2xl:{...Is.heading2xl,fontSize:KC[36]},headingXl:{...Is.headingXl,fontSize:KC[32]},headingLg:{...Is.headingLg,fontSize:KC[24]},headingMd:{...Is.headingMd,fontSize:KC[18]},bodyBase:{...Is.bodyBase},bodySmall:{...Is.bodySmall},labelButton:{...Is.labelButton},labelDefault:{...Is.labelDefault},captionDefault:{...Is.captionDefault},captionLink:{...Is.captionLink}},SP={heading2xl:{mobile:Is.heading2xl,desktop:Gl.heading2xl},headingXl:{desktop:Gl.headingXl,mobile:Is.headingXl},headingLg:{desktop:Gl.headingLg,mobile:Is.headingLg},headingMd:{desktop:Gl.headingMd,mobile:Is.headingMd},bodyBase:{desktop:Gl.bodyBase,mobile:Is.bodyBase},bodySmall:{desktop:Gl.bodySmall,mobile:Is.bodySmall},labelButton:{desktop:Gl.labelButton,mobile:Is.labelButton},labelDefault:{desktop:Gl.labelDefault,mobile:Is.labelDefault},captionDefault:{desktop:Gl.captionDefault,mobile:Is.captionDefault},captionLink:{desktop:Gl.captionLink,mobile:Is.captionLink}},aN=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,z8=({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},Z8=.37,gxA=(e,A=Z8)=>{const t=z8({...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 oxA(e,A,t){const i=aN(e)||{r:0,g:0,b:0},n=aN(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`#${p2(g)}${p2(o)}${p2(s)}`}function k7(e,A){const t={r:255,g:255,b:255},i=Math.max(0,Math.min(1,A));let n=e,g=aN(e)||t;(isNaN(g.r)||isNaN(g.g)||isNaN(g.b))&&(g=t,n="#FFFFFF");const o=z8({...g,luminanceThreshold:Z8})?"#000000":"#FFFFFF";return oxA(n,o,i)}function p2(e){return e.toString(16).padStart(2,"0").toUpperCase()}const sxA=(e,A,t,i=Z8)=>{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=aN(e);g!==null&&Object.assign(n,gxA(g))}if(A!=null&&A.startsWith("#")){const g=aN(A);g!==null&&(n["primary-text"]=z8({...g,luminanceThreshold:i})?"black":"white")}return n},rxA=e=>({"primary-hover":k7(e,.1),"primary-pressed":k7(e,.15)}),axA=(e,A)=>e||A,IxA=(e,A,t)=>{const i=Object.entries(e).map(([n,g])=>[n,axA(t?t[g]:null,A[n])]);return Object.fromEntries(i)},nBA=(e,A,t)=>{const i=IxA(e,A,t);return t?{...A,...i,...sxA(i.background,i.primary,A),...rxA(i.primary)}:{...A}},CxA=e=>nBA(txA,AxA,e),gBA=e=>nBA(exA,$LA,e),W8=e=>{if(!e)return S7;switch(e.shapes){case"rounded":return tBA;case"rectangle":return ixA;case"pill":return nxA;default:return S7}},YF=(e="",A)=>A.map(([t,i])=>`--rc-${e}-${t}: ${i}`).join("; "),oBA=e=>{const A=YF("color",Object.entries(CxA(e))),t=YF("shape",Object.entries(W8(e)));return[A,t].join("; ")},cxA=e=>{const A=YF("color",Object.entries(gBA(e))),t=YF("shape",Object.entries(W8(e)));return[A,t].join("; ")},lxA=(e="",A,t)=>Object.entries(A).flatMap(([i,{desktop:n,mobile:g}])=>{const o=`normal normal ${n.fontWeight} ${n.fontSize}/${n.lineHeight} ${qF}`,s=`normal normal ${g.fontWeight} ${g.fontSize}/${g.lineHeight} ${qF}`,r=`normal normal ${t==null?void 0:t.desktop.font_weight} ${t==null?void 0:t.desktop.font_size} ${w7}`,a=`normal normal ${t==null?void 0:t.mobile.font_weight} ${t==null?void 0:t.mobile.font_size} ${w7}`;return[`--rc-${e}-${i}-desktop: ${o}`,`--rc-${e}-${i}-mobile: ${s}`,`--rc-${e}-${i}-branded-desktop: ${t?r:o}`,`--rc-${e}-${i}-branded-mobile: ${t?a:s}`,`--rc-${e}-${i}-desktop-font-size: ${n.fontSize}`,`--rc-${e}-${i}-mobile-font-size: ${g.fontSize}`]}).join("; "),BxA=(e="",A)=>Object.entries(A).map(([t,{mobile:i,desktop:n}])=>`--rc-${e}-${t}-mobile: ${i};  --rc-${e}-${t}-desktop: ${n};`).join(" "),ExA={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 IN{constructor(A){Tt(this,"brandingAppearance"),A?this.brandingAppearance=A:this.brandingAppearance=void 0}get shape(){return W8(this.brandingAppearance)}get formColors(){return gBA(this.brandingAppearance)}get formStyleVars(){return cxA(this.brandingAppearance)}get productInfoStyleVars(){return oBA(this.brandingAppearance)}get spacing(){return ExA}get textStyles(){return SP}getTextStyleVars(A){return lxA("text",this.textStyles,A)}get spacingStyleVars(){return BxA("spacing",this.spacing)}}var sBA="basil",QxA=function(e){return e===3?"v3":e},rBA="https://js.stripe.com",uxA="".concat(rBA,"/").concat(sBA,"/stripe.js"),dxA=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/,hxA=/^https:\/\/js\.stripe\.com\/(v3|[a-z]+)\/stripe\.js(\?.*)?$/,pxA=function(e){return dxA.test(e)||hxA.test(e)},fxA=function(){for(var e=document.querySelectorAll('script[src^="'.concat(rBA,'"]')),A=0;A<e.length;A++){var t=e[A];if(pxA(t.src))return t}return null},M7=function(e){var A="",t=document.createElement("script");t.src="".concat(uxA).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},yxA=function(e,A){!e||!e._registerWrapper||e._registerWrapper({name:"stripe-js",version:"7.3.1",startTime:A})},y0=null,Db=null,mb=null,DxA=function(e){return function(A){e(new Error("Failed to load Stripe.js",{cause:A}))}},mxA=function(e,A){return function(){window.Stripe?e(window.Stripe):A(new Error("Stripe.js not available"))}},SxA=function(e){return y0!==null?y0:(y0=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=fxA();if(!(i&&e)){if(!i)i=M7(e);else if(i&&mb!==null&&Db!==null){var n;i.removeEventListener("load",mb),i.removeEventListener("error",Db),(n=i.parentNode)===null||n===void 0||n.removeChild(i),i=M7(e)}}mb=mxA(A,t),Db=DxA(t),i.addEventListener("load",mb),i.addEventListener("error",Db)}catch(g){t(g);return}}),y0.catch(function(A){return y0=null,Promise.reject(A)}))},wxA=function(e,A,t){if(e===null)return null;var i=A[0],n=i.match(/^pk_test/),g=QxA(e.version),o=sBA;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 yxA(s,t),s},Sb,aBA=!1,IBA=function(){return Sb||(Sb=SxA(null).catch(function(e){return Sb=null,Promise.reject(e)}),Sb)};Promise.resolve().then(function(){return IBA()}).catch(function(e){aBA||console.warn(e)});var kxA=function(){for(var e=arguments.length,A=new Array(e),t=0;t<e;t++)A[t]=arguments[t];aBA=!0;var i=Date.now();return IBA().then(function(n){return wxA(n,A,i)})},wP=(e=>(e[e.ErrorLoadingStripe=0]="ErrorLoadingStripe",e[e.HandledFormError=1]="HandledFormError",e[e.UnhandledFormError=2]="UnhandledFormError",e))(wP||{});class sK{constructor(A,t,i){this.code=A,this.gatewayErrorCode=t,this.message=i}}const CBA=class rK{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 r=await kxA(t,{stripeAccount:A}).catch(h=>{throw this.mapInitializationError(h)});if(!r)throw{code:0,gatewayErrorCode:void 0,message:"Stripe client not found"};const a=new IN(n==null?void 0:n.appearance),I=a.shape,c=a.formColors,l=a.textStyles,B=SP.bodyBase[s].fontSize||SP.bodyBase.mobile.fontSize;let Q;try{Q=r.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:r,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 sK(0,A.code,A.message)}static mapError(A){return this.isStripeHandledFormError(A)?new sK(1,A.code,A.message):new sK(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 r;if(s?r=await A.confirmSetup(o):r=await A.confirmPayment(o),r!=null&&r.error)throw this.mapError(r.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===hr.Year?(t.setFullYear(t.getFullYear()+A.number),t):A.unit===hr.Month?(t.setMonth(t.getMonth()+A.number),t):A.unit===hr.Week?(t.setDate(t.getDate()+A.number*7),t):(A.unit===hr.Day&&t.setDate(t.getDate()+A.number),t)}static applePayPeriod(A){return A.unit===hr.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=rK.microsToMinimumAmountPrice(t.totalAmountInMicros,t.currency),r=i.trial,a=(o=i.trial)==null?void 0:o.period,I=i.base.period,c=r&&a?rK.nextDateForPeriod(a,new Date):void 0,l=I?rK.applePayPeriod(I):{};return{applePay:{recurringPaymentRequest:{paymentDescription:A.title,managementURL:g,trialBilling:r?{label:n.translate(oi.ApplePayFreeTrial),amount:0}:void 0,regularBilling:{label:A.title,amount:s,recurringPaymentStartDate:c,...l}}}}}};Tt(CBA,"FORM_VALIDATED_CARD_ERROR_CODES",["card_declined","expired_card","incorrect_cvc","incorrect_number"]);let Or=CBA;var MxA=St("<div></div>");function NxA(e,A){Mi(A,!0);let t=null;const i="payment-element",n=async o=>{await A.onError(Or.mapInitializationError(o.error))};gc(()=>{var o;try{t=Or.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(Or.mapInitializationError(s))}}),xR(()=>{t==null||t.destroy(),t=null});var g=MxA();Ii(g,"id",i),Ue(e,g),Ni()}var RxA=St("<div></div>");function GxA(e,A){Mi(A,!0);let t=null;const i="link-authentication-element",n=async o=>{await A.onError(Or.mapInitializationError(o.error))};gc(()=>{try{t=Or.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(Or.mapInitializationError(o))}}),xR(()=>{t==null||t.destroy(),t=null});var g=RxA();Ii(g,"id",i),Ue(e,g),Ni()}var bxA=St('<div class="text-separator svelte-ch0h61"><hr class="line svelte-ch0h61"> <span class="text svelte-ch0h61"><!></span> <hr class="line svelte-ch0h61"></div>');const UxA={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 vxA(e,A){Qi(e,UxA);let t=ri(A,"text",8);var i=bxA(),n=Ht(Xe(i),2),g=Xe(n);Pn(g,{size:"caption-default",children:(o,s)=>{var r=sg();Ft(()=>Dn(r,t())),Ue(o,r)},$$slots:{default:!0}}),Ue(e,i)}var KxA=St("<div></div> <!>",1);function FxA(e,A){Mi(A,!0);const t=uI(),i=()=>QI(n,"$translator",t),n=Xr(eC);let g=null,o=gn(!1);const s="express-checkout-element",r=async h=>{const d={...A.expressCheckoutOptions?A.expressCheckoutOptions:{}};h.resolve(d)},a=async h=>{await A.onError(Or.mapInitializationError(h.error))},I=async h=>{var d;A.onSubmit(h.expressPaymentType,((d=h.billingDetails)==null?void 0:d.email)??"")},c=async h=>{bt(o,!h.availablePaymentMethods),A.onReady()};gc(()=>{try{g=Or.createExpressCheckoutElement(A.elements,A.billingAddressRequired,A.expressCheckoutOptions),g.mount(`#${s}`),g.on("ready",c),g.on("confirm",I),g.on("loaderror",a),g.on("click",r)}catch(h){A.onError(Or.mapInitializationError(h))}}),xR(()=>{g==null||g.destroy(),g=null});var l=Jn(),B=Ui(l);{var Q=h=>{var d=KxA(),p=Ui(d);Ii(p,"id",s);var y=Ht(p,2),m=Ct(()=>i().translate(oi.PaymentEntryPageExpressCheckoutDivider));vxA(y,{get text(){return MA(m)}}),Ue(h,d)};$t(B,h=>{MA(o)||h(Q)})}Ue(e,l),Ni()}var _xA=St('<div class="rc-elements svelte-6qa1vy"><!> <!> <!></div>');const JxA={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 LxA(e,A){Mi(A,!0),Qi(e,JxA);const t=uI(),i=()=>QI(o,"$translator",t);let n=ri(A,"stripe",15,null),g=ri(A,"elements",15,null);const o=Xr(eC),s=Or.getStripeLocale(i().locale||i().fallbackLocale);let r=gn(!1),a=gn(di(A.skipEmail)),I=gn(!1),c=gn(void 0),l=gn("mobile"),B=gn(void 0);function Q(){window.matchMedia&&window.matchMedia("(max-width: 767px)").matches?bt(l,"mobile"):bt(l,"desktop"),bt(c,di({fontSizeBase:"14px",fontFamily:qF,spacingGridRow:"16px"}))}function h(){clearTimeout(MA(B)),bt(B,di(setTimeout(()=>{Q()},150)))}const d=M=>{A.onError(M),A.onLoadingComplete()},p=async()=>{MA(a)||(bt(a,!0),MA(a)&&MA(r)&&MA(I)&&A.onLoadingComplete())},y=async()=>{MA(I)||(bt(I,!0),MA(a)&&MA(r)&&MA(I)&&A.onLoadingComplete())},m=async()=>{MA(r)||(bt(r,!0),MA(a)&&MA(r)&&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)};gc(()=>(window.addEventListener("resize",h),()=>{window.removeEventListener("resize",h)})),gc(async()=>{Q(),!n()&&(g()||!A.stripeAccountId||!A.publishableApiKey||!A.elementsConfiguration||await Or.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)}))}),wS(()=>{A.elementsConfiguration&&g()&&Or.updateElementsConfiguration(g(),A.elementsConfiguration)});var k=Jn(),N=Ui(k);{var G=M=>{var w=_xA(),b=Xe(w);FxA(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 _=Ht(b,2);{var K=T=>{GxA(T,{get elements(){return g()},onReady:p,onChange:S,onError:d})};$t(_,T=>{A.skipEmail||T(K)})}var J=Ht(_,2);NxA(J,{get elements(){return g()},get brandingInfo(){return A.brandingInfo},onReady:m,onChange:D,onError:d}),Ue(M,w)};$t(N,M=>{g()&&M(G)})}Ue(e,k),Ni()}const xxA=`<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 TxA=St('<div class="rcb-ui-asset-icon svelte-1rk57mx"><!></div>');const qxA={hash:"svelte-1rk57mx",code:".rcb-ui-asset-icon.svelte-1rk57mx {display:inline-block;width:1em;height:1em;}"};function cBA(e){Qi(e,qxA);var A=TxA(),t=Xe(A);Gd(t,()=>xxA),Ue(e,A)}var YxA=St('<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 HxA={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 OxA(e,A){Qi(e,HxA);var t=YxA(),i=Xe(t),n=Xe(i);cBA(n);var g=Ht(i,2),o=Xe(g),s=Xe(o);Pn(s,{size:"body-small",children:(I,c)=>{var l=sg();Ft(()=>Dn(l,A.title)),Ue(I,l)},$$slots:{default:!0}});var r=Ht(o,2),a=Xe(r);Pn(a,{size:"body-small",children:(I,c)=>{var l=sg();Ft(()=>Dn(l,A.message)),Ue(I,l)},$$slots:{default:!0}}),Ue(e,t)}function PxA(e,A){Mi(A,!0);const t=uI(),i=()=>QI(n,"$translator",t),n=Xr(eC);var g=Ct(()=>i().translate(oi.PriceUpdateTitle)),o=Ct(()=>{var s;return i().translate((s=A.subscriptionOption)!=null&&s.trial?oi.PriceUpdateTrialMessage:oi.PriceUpdateBaseMessage)});OxA(e,{get title(){return MA(g)},get message(){return MA(o)}}),Ni()}function lBA(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 N7 extends Error{}var jxA=St('<div class="rc-loading svelte-dg9m6p"><!></div>'),zxA=St('<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 ZxA={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 WxA(e,A){var t,i,n;Mi(A,!0),Qi(e,ZxA);const g=uI(),o=()=>QI(r,"$translator",g),s=Xr(H8),r=Xr(eC),a=(t=A.productDetails.subscriptionOptions)==null?void 0:t[A.purchaseOption.id],I=lBA(A.productDetails,A.purchaseOption);let c=gn(di(((i=A.defaultPriceBreakdown)==null?void 0:i.taxCalculationStatus)??((n=A.brandingInfo)!=null&&n.gateway_tax_collection_enabled?"unavailable":"disabled"))),l=gn(null),B=gn(null),Q=gn(di(I.amountMicros)),h=gn(di(I.amountMicros)),d=Ct(()=>A.defaultPriceBreakdown??{currency:I.currency,totalAmountInMicros:MA(h),totalExcludingTaxInMicros:MA(Q),taxCalculationStatus:MA(c),taxAmountInMicros:MA(l),taxBreakdown:MA(B)}),p=gn(di(A.gatewayParams.elements_configuration)),y=gn(null),m=gn(null),D=gn(null),S=gn(di(A.customerEmail??void 0)),k=gn(di(!!A.customerEmail)),N=gn(!0),G=gn(!1),M=gn(void 0),w=gn(void 0),b=gn(void 0),_=gn(!1),K=gn(null),J=Ct(()=>MA(N)||MA(_)?"loading":MA(w)?"error":"form"),T=gn("unavailable"),v=Ct(()=>!MA(_)&&MA(G)&&MA(k)&&(MA(c)==="disabled"||MA(c)==="calculated"||MA(c)==="miss-match")),U=Ct(()=>a&&A.managementUrl&&MA(d)?Or.buildStripeExpressCheckoutOptionsForSubscription(A.productDetails,MA(d),a,o(),A.managementUrl):void 0);wS(()=>{A.onPriceBreakdownUpdated(MA(d))}),gc(async()=>{MA(c)==="unavailable"&&await x(null).catch($)}),xR(()=>{MA(K)&&(MA(K).abort(),bt(K,null))});async function x(QA,PA){await A.purchaseOperationHelper.checkoutCalculateTax(QA==null?void 0:QA.countryCode,QA==null?void 0:QA.postalCode,PA).then(VA=>{const KA=YLA({taxCalculation:VA,taxCustomerDetails:QA});s.trackSDKEvent(KA),PA==null||PA.throwIfAborted(),VA.failed_reason?!QA&&VA.failed_reason===j8.invalid_tax_location?bt(c,"pending"):bt(c,"disabled"):bt(c,"calculated"),bt(l,di(VA.tax_amount_in_micros)),bt(Q,di(VA.total_excluding_tax_in_micros)),bt(h,di(VA.total_amount_in_micros)),bt(B,di(VA.tax_breakdown)),bt(p,di(VA.gateway_params.elements_configuration)),bt(y,di(QA))})}function q(){s.trackSDKEvent({eventName:lI.CheckoutPaymentFormImpression}),bt(N,!1)}async function z(QA,PA){bt(S,di(PA)),bt(k,di(QA)),await sA()}async function Z({complete:QA,paymentMethod:PA}){bt(M,di(PA)),bt(G,di(QA)),await sA()}async function eA(QA){if(QA==null||QA.preventDefault(),MA(_))return;const PA=HLA({selectedPaymentMethod:MA(M)??null});s.trackSDKEvent(PA),bt(_,!0),await pA()?A.onContinue():bt(_,!1)}async function aA(QA,PA){bt(M,di(QA)),bt(S,di(A.customerEmail??PA)),await eA()}async function sA(){MA(M)!=="card"||!MA(k)||!MA(G)||MA(_)||MA(c)==="disabled"||(MA(c)!=="loading"&&(bt(T,di(MA(c))),bt(c,"loading")),await gA(async QA=>{await yA().then(()=>QA.throwIfAborted()).then(()=>fA(QA)).then(()=>QA.throwIfAborted()).catch(PA=>{QA.aborted||$(PA)}).finally(()=>{MA(c)==="loading"&&!QA.aborted&&bt(c,di(MA(T)))})}))}async function pA(){return await gA(async QA=>{const PA=MA(h);let VA;return await yA().then(()=>QA.throwIfAborted()).then(()=>fA(QA)).then(KA=>{VA=KA}).then(()=>QA.throwIfAborted()).then(RA(PA)).then(()=>QA.throwIfAborted()).then(YA).then(()=>QA.throwIfAborted()).then(()=>W(VA)).then(()=>QA.throwIfAborted()).then(()=>!0).catch(KA=>(QA.aborted||$(KA),!1))})}async function gA(QA){MA(K)&&MA(K).abort(),bt(K,di(new AbortController));const PA=MA(K).signal;try{return await QA(PA)}catch(VA){if(VA instanceof DOMException&&VA.name==="AbortError")return Promise.resolve(void 0);throw VA}}async function yA(){MA(D)&&await Or.submitElements(MA(D))}async function fA(QA){var PA,VA;if(MA(c)==="unavailable"||MA(c)==="disabled"||!MA(D)||!MA(m))return;const{customerDetails:KA,confirmationTokenId:Ie}=await Or.extractTaxCustomerDetails(MA(D),MA(m));return QA==null||QA.throwIfAborted(),KA.postalCode===((PA=MA(y))==null?void 0:PA.postalCode)&&KA.countryCode===((VA=MA(y))==null?void 0:VA.countryCode)||await x(KA,QA),Ie&&MA(M)!=="card"?Ie:void 0}function RA(QA){return()=>{if(MA(h)!==QA)throw new N7}}async function YA(){var QA;const PA=await A.purchaseOperationHelper.checkoutComplete(MA(S)),VA=(QA=PA==null?void 0:PA.gateway_params)==null?void 0:QA.client_secret;VA&&bt(b,di(VA))}async function W(QA){!MA(m)||!MA(D)||!MA(b)||await Or.confirmElements(MA(m),MA(D),MA(b),QA)}async function $(QA){if(QA instanceof N7)bt(c,"miss-match");else if(QA instanceof Gg){const PA=JLA({errorCode:QA.errorCode.toString(),errorMessage:QA.message});s.trackSDKEvent(PA),QA.errorCode===Bg.MissingEmailError?bt(w,di(o().translate(oi.ErrorPageErrorMessageInvalidEmailError,{email:MA(S)}))):A.onError(QA)}else if(QA instanceof sK)await L(QA);else throw QA}async function L(QA){const PA=OLA({errorCode:QA.gatewayErrorCode??"",errorMessage:QA.message??""});s.trackSDKEvent(PA),QA.code===wP.HandledFormError||(QA.code===wP.UnhandledFormError?bt(w,di(QA.message)):A.onError(new Gg(Bg.ErrorSettingUpPurchase,"Failed to initialize payment form",QA.message)))}const H=()=>{bt(w,void 0)};var P=zxA(),tA=Xe(P);{var iA=QA=>{var PA=jxA(),VA=Xe(PA);ABA(VA),Ue(QA,PA)};$t(tA,QA=>{MA(J)==="loading"&&QA(iA)})}var oA=Ht(tA,2);{var CA=QA=>{var PA=Ct(()=>o().translate(oi.ErrorButtonTryAgain));P8(QA,{title:null,type:"error",get closeButtonTitle(){return MA(PA)},onDismiss:H,icon:VA=>{JlA(VA)},message:VA=>{var KA=sg();Ft(()=>Dn(KA,MA(w))),Ue(VA,KA)},$$slots:{icon:!0,message:!0}})};$t(oA,QA=>{MA(J)==="error"&&QA(CA)})}var cA=Ht(oA,2),_A=Xe(cA),uA=Xe(_A),X=Xe(uA),O=Ct(()=>!!A.customerEmail),lA=Ct(()=>MA(c)!=="disabled");LxA(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(lA)},onLoadingComplete:q,onError:L,onEmailChange:z,onPaymentInfoChange:Z,onExpressCheckoutElementSubmit:aA,get expressCheckoutOptions(){return MA(U)},get stripe(){return MA(m)},set stripe(QA){bt(m,di(QA))},get elements(){return MA(D)},set elements(QA){bt(D,di(QA))}});var wA=Ht(uA,2),xA=Xe(wA);PxA(xA,{subscriptionOption:a});var HA=Ht(wA,2),zA=Xe(HA),ne=Ct(()=>!MA(v)),ye=Ct(()=>{var QA;return(QA=A.brandingInfo)!=null&&QA.gateway_tax_collection_enabled?MA(d):void 0});XLA(zA,{get disabled(){return MA(ne)},subscriptionOption:a,get priceBreakdown(){return MA(ye)}});var Ee=Ht(zA,2),NA=Xe(Ee);FLA(NA,{get brandingInfo(){return A.brandingInfo},get purchaseOption(){return A.purchaseOption}}),Ft(()=>{JE(_A,"invisible",MA(J)!=="form"),JE(wA,"fully-hidden",MA(c)!=="miss-match"||MA(J)!=="form"),JE(HA,"fully-hidden",MA(J)!=="form")}),nB("submit",cA,eA),Ue(e,P),Ni()}function VxA(e){return e!=null}var _p=(e=>(e.Subscription="subscription",e.Consumable="consumable",e.NonConsumable="non_consumable",e))(_p||{});const BBA=e=>({amount:e.amount_micros/1e4,amountMicros:e.amount_micros,currency:e.currency,formattedPrice:ju(e.amount_micros,e.currency)}),f2=e=>{const A=e.period_duration,t=e.price?BBA(e.price):null,i=A?FlA(A):null;let n=null,g=null,o=null;if(t!==null&&i!==null){const s=XxA(i),r=1e4,a=Math.round(t.amountMicros*s.toWeek);n={amount:a/r,amountMicros:a,currency:t.currency,formattedPrice:ju(a,t.currency)};const I=Math.round(t.amountMicros*s.toMonth);g={amount:I/r,amountMicros:I,currency:t.currency,formattedPrice:ju(I,t.currency)};const c=Math.round(t.amountMicros*s.toYear);o={amount:c/r,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 XxA(e){const{number:A,unit:t}=e,i=7,n=30,g=365;let o;switch(t){case hr.Day:o=A;break;case hr.Week:o=A*i;break;case hr.Month:o=A*n;break;case hr.Year:o=A*g;break;default:o=0,Xi.errorLog(`Unknown period unit: ${t}`)}const s=o>0?i/o:0,r=o>0?n/o:0,a=o>0?g/o:0;return{toWeek:s,toMonth:r,toYear:a}}const $xA=e=>e.base==null?(Xi.debugLog("Missing base phase for subscription option. Ignoring."),null):{id:e.id,priceId:e.price_id,base:f2(e.base),trial:e.trial?f2(e.trial):null,introPrice:e.intro_price?f2(e.intro_price):null},ATA=e=>e.base_price==null?(Xi.debugLog("Missing base price for non-subscription option. Ignoring."),null):{id:e.id,priceId:e.price_id,basePrice:BBA(e.base_price)},eTA=(e,A)=>{const t=e.product_type;return t==="subscription"?iTA(e,A,t):tTA(e,A,t)},tTA=(e,A,t)=>{const i={};if(Object.entries(e.purchase_options).forEach(([o,s])=>{const r=ATA(s);r!=null&&(i[o]=r)}),Object.keys(i).length===0)return Xi.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?(Xi.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}},iTA=(e,A,t)=>{const i={};if(Object.entries(e.purchase_options).forEach(([s,r])=>{const a=$xA(r);a!=null&&(i[s]=a)}),Object.keys(i).length===0)return Xi.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 Xi.debugLog(`Product ${e.identifier} has no default subscription option. Ignoring.`),null;const o=g.base.price;return o==null?(Xi.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}},nTA=(e,A,t)=>{const i=t[A.platform_product_identifier];if(i===void 0)return null;const n=eTA(i,e);return n===null?null:{identifier:A.identifier,rcBillingProduct:n,webBillingProduct:n,packageType:oTA(A.identifier)}},gTA=(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=>nTA(n,s,t)).filter(VxA),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 oTA(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 sTA=RB('<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 rTA={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 wb(e,A){Qi(e,rTA);let t=ri(A,"direction",8);var i=sTA();Ft(()=>dFA(i,`arrow ${t()??""} svelte-1qexsu3`)),Ue(e,i)}var aTA=RB('<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 ITA={hash:"svelte-r0zny8",code:".arrow-fill.svelte-r0zny8 {fill:var(--rc-color-grey-text-dark);}"};function CTA(e){Qi(e,ITA);var A=aTA();Ue(e,A)}const cTA=`<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 lTA=St('<div style="color:var(--rc-color-gray-text-dark);"><!></div>');function BTA(e){var A=lTA(),t=Xe(A);Gd(t,()=>cTA),Ue(e,A)}const ETA=`<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 QTA=St('<div style="color:var(--rc-color-accent);" class="rcb-ui-asset-icon svelte-wgufvv"><!></div>');const uTA={hash:"svelte-wgufvv",code:"div.svelte-wgufvv {height:24px;width:24px;}"};function dTA(e){Qi(e,uTA);var A=QTA(),t=Xe(A);Gd(t,()=>ETA),Ue(e,A)}const hTA=`<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 pTA=St('<div style="color:var(--rc-color-primary)"><!></div>');function EBA(e){var A=pTA(),t=Xe(A);Gd(t,()=>hTA),Ue(e,A)}var fTA=RB('<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 yTA={hash:"svelte-1jpfelf",code:".arrow-fill.svelte-1jpfelf {fill:var(--arrow-fill-color, var(--rc-color-grey-text-dark));}"};function DTA(e){Qi(e,yTA);var A=fTA();Ue(e,A)}const mTA={cart:BTA,error:JlA,lock:dTA,success:EBA,back:CTA,info:cBA,close:DTA,"chevron-left":wb,"chevron-right":wb,"chevron-up":wb,"chevron-down":wb};function CN(e,A){Mi(A,!0);const t=mTA[A.name];let i=gn(di({}));if(A.name.startsWith("chevron")){const n=A.name.split("-")[1];bt(i,di({direction:n}))}t(e,VE(()=>MA(i))),Ni()}var STA=St('<span class="rc-sandbox-only-error svelte-1d8gf9n"><!></span> <br> <br>',1),wTA=St('<!> <a class="svelte-1d8gf9n"> </a>.',1),kTA=St("<!> <!>",1);const MTA={hash:"svelte-1d8gf9n",code:"a.svelte-1d8gf9n {color:var(--rc-color-grey-text-dark);}.rc-sandbox-only-error.svelte-1d8gf9n {font-weight:bold;}"};function NTA(e,A){Mi(A,!0),Qi(e,MTA);const t=uI(),i=()=>QI(g,"$translator",t),n=Ct(()=>A.lastError??new Gg(Bg.UnknownError,"Unknown error without state set.")),g=Xr(eC),o=Ct(()=>MA(n).errorCode===Bg.StripeTaxNotActive||MA(n).errorCode===Bg.StripeInvalidTaxOriginAddress||MA(n).errorCode===Bg.StripeMissingRequiredPermission);gc(()=>{Xi.errorLog(`Displayed error: ${Bg[MA(n).errorCode]}. Message: ${MA(n).message??"None"}. Underlying error: ${MA(n).underlyingErrorMessage??"None"}`)});function s(){return MA(n).errorCode===Bg.AlreadyPurchasedError?i().translate(oi.ErrorPageCloseButtonTitle,{appName:A.appName??"App"}):MA(o)?i().translate(oi.ErrorButtonClose):i().translate(oi.ErrorButtonTryAgain)}function r(){switch(MA(n).errorCode){case Bg.AlreadyPurchasedError:return A.productDetails.productType===_p.Subscription?i().translate(oi.ErrorPageErrorTitleAlreadySubscribed,{productTitle:A.productDetails.title}):i().translate(oi.ErrorPageErrorTitleAlreadyPurchased,{productTitle:A.productDetails.title});case Bg.StripeTaxNotActive:return i().translate(oi.ErrorPageErrorTitleStripeTaxNotActive);case Bg.StripeInvalidTaxOriginAddress:return i().translate(oi.ErrorPageErrorTitleStripeInvalidTaxOriginAddress);case Bg.StripeMissingRequiredPermission:return i().translate(oi.ErrorPageErrorTitleStripeMissingRequiredPermission);default:return i().translate(oi.ErrorPageErrorTitleOtherErrors)}}function a(){const Q=MA(n).getErrorCode();switch(MA(n).errorCode){case Bg.ErrorSettingUpPurchase:return i().translate(oi.ErrorPageErrorMessageErrorSettingUpPurchase,{errorCode:Q});case Bg.ErrorChargingPayment:return i().translate(oi.ErrorPageErrorMessageErrorChargingPayment,{errorCode:Q});case Bg.AlreadyPurchasedError:return A.productDetails.productType===_p.Subscription?i().translate(oi.ErrorPageErrorMessageAlreadySubscribed,{errorCode:Q}):i().translate(oi.ErrorPageErrorMessageAlreadyPurchased,{errorCode:Q});case Bg.StripeTaxNotActive:return i().translate(oi.ErrorPageErrorMessageStripeTaxNotActive,{errorCode:Q});case Bg.StripeInvalidTaxOriginAddress:return i().translate(oi.ErrorPageErrorMessageStripeInvalidTaxOriginAddress,{errorCode:Q});case Bg.StripeMissingRequiredPermission:return i().translate(oi.ErrorPageErrorMessageStripeMissingRequiredPermission,{errorCode:Q});case Bg.NetworkError:return i().translate(oi.ErrorPageErrorMessageNetworkError,{errorCode:Q});default:return i().translate(oi.ErrorPageErrorMessageUnknownError,{errorCode:Q})}}function I(){return MA(n).errorCode===Bg.AlreadyPurchasedError?oi.ErrorPageTroubleAccessing:oi.ErrorPageIfErrorPersists}function c(){return MA(n).errorCode===Bg.AlreadyPurchasedError?"success":"error"}var l=Ct(r),B=Ct(s);P8(e,{get title(){return MA(l)},get onDismiss(){return A.onDismiss},type:"error",get closeButtonTitle(){return MA(B)},icon:Q=>{var h=Ct(c);CN(Q,{get name(){return MA(h)}})},message:Q=>{var h=kTA(),d=Ui(h);{var p=S=>{var k=STA(),N=Ui(k),G=Xe(N);Va(G,{get key(){return oi.ErrorPageErrorMessageOnlyInSandbox}}),Ue(S,k)};$t(d,S=>{MA(o)&&S(p)})}var y=Ht(d);Ft(()=>Dn(y,` ${a()??""} `));var m=Ht(y);{var D=S=>{var k=wTA(),N=Ui(k),G=Ct(I);Va(N,{get key(){return MA(G)}});var M=Ht(N,2),w=Xe(M);Ft(()=>{Ii(M,"href",`mailto:${A.supportEmail??""}`),Dn(w,A.supportEmail)}),Ue(S,k)};$t(m,S=>{!MA(o)&&A.supportEmail&&S(D)})}Ue(Q,h)},$$slots:{icon:!0,message:!0}}),Ni()}function RTA(e,A){Mi(A,!1);const t=uI(),i=()=>QI(g,"$translator",t);let n=ri(A,"onContinue",8);const g=Xr(eC),o=Xr(H8);function s(){o.trackSDKEvent({eventName:lI.CheckoutPurchaseSuccessfulDismiss,properties:{ui_element:"go_back_to_app"}}),n()()}gc(()=>{o.trackSDKEvent({eventName:lI.CheckoutPurchaseSuccessfulImpression})}),Ic();var r=mm(()=>i().translate(oi.SuccessPagePurchaseSuccessful)),a=mm(()=>i().translate(oi.SuccessPageButtonClose));P8(e,{type:"success",get title(){return MA(r)},onDismiss:s,get closeButtonTitle(){return MA(a)},icon:I=>{EBA(I)},$$slots:{icon:!0}}),Ni()}function GTA(e){ABA(e)}var bTA=St('<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 UTA={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 vTA(e,A){Mi(A,!1),Qi(e,UTA);const t=uI(),i=()=>QI(o,"$translator",t);let n=ri(A,"isExpanded",12,!0),g=ri(A,"children",8);const o=Xr(eC);function s(){n(!n())}Ic();var r=bTA(),a=Xe(r),I=Xe(a);Pn(I,{size:"label-default",children:(y,m)=>{var D=Jn(),S=Ui(D);{var k=G=>{var M=sg();Ft(()=>Dn(M,i().translate(oi.PricingDropdownHideDetails))),Ue(G,M)},N=G=>{var M=sg();Ft(()=>Dn(M,i().translate(oi.PricingDropdownShowDetails))),Ue(G,M)};$t(S,G=>{n()?G(k):G(N,!1)})}Ue(y,D)},$$slots:{default:!0}});var c=Ht(I,2),l=Xe(c);{var B=y=>{CN(y,{name:"chevron-up"})},Q=y=>{CN(y,{name:"chevron-down"})};$t(l,y=>{n()?y(B):y(Q,!1)})}var h=Ht(a,2),d=Xe(h),p=Xe(d);es(p,()=>g()??rg),Ft(()=>{Ii(a,"aria-expanded",n()),JE(h,"collapsed",!n())}),nB("click",a,s),nB("keydown",a,y=>y.key==="Enter"||y.key===" "?s():null),Ue(e,r),Ni()}var KTA=St('<div class="rcb-pricing-table-value-loading svelte-erv89n"><!></div>');const FTA={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 _TA(e,A){Mi(A,!1),Qi(e,FTA);let t=ri(A,"children",8);Ic();var i=KTA(),n=Xe(i);es(n,()=>t()??rg),Ue(e,i),Ni()}var JTA=St('<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>'),LTA=St('<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>'),xTA=St('<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>'),TTA=St('<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),qTA=St('<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>'),YTA=St('<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 HTA={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 OTA(e,A){var t;Mi(A,!0),Qi(e,HTA);const i=uI(),n=()=>QI(s,"$translator",i),g=B=>{var Q=YTA(),h=Xe(Q);{var d=G=>{var M=TTA(),w=Ui(M),b=Xe(w),_=Xe(b);Pn(_,{size:"body-small",children:(x,q)=>{var z=sg();Ft(()=>Dn(z,n().translate(oi.PricingTotalExcludingTax))),Ue(x,z)},$$slots:{default:!0}});var K=Ht(b,2),J=Xe(K);Pn(J,{size:"body-small",children:(x,q)=>{var z=sg();Ft(()=>Dn(z,n().formatPrice(A.priceBreakdown.totalExcludingTaxInMicros,A.priceBreakdown.currency))),Ue(x,z)},$$slots:{default:!0}});var T=Ht(w,2);{var v=x=>{var q=JTA(),z=Xe(q),Z=Xe(z);Pn(Z,{size:"body-small",children:(sA,pA)=>{var gA=sg();Ft(()=>Dn(gA,n().translate(oi.PricingTableTax))),Ue(sA,gA)},$$slots:{default:!0}});var eA=Ht(z,2),aA=Xe(eA);Pn(aA,{size:"body-small",children:(sA,pA)=>{_TA(sA,{children:(gA,yA)=>{var fA=sg();Ft(()=>Dn(fA,n().formatPrice(1234e4,A.priceBreakdown.currency))),Ue(gA,fA)},$$slots:{default:!0}})},$$slots:{default:!0}}),Ue(x,q)},U=x=>{var q=Jn(),z=Ui(q);{var Z=aA=>{var sA=LTA(),pA=Xe(sA),gA=Xe(pA);Ft(()=>Dn(gA,n().translate(oi.PricingTableTax)));var yA=Ht(pA,2),fA=Xe(yA);Pn(fA,{size:"body-small",children:(RA,YA)=>{var W=sg();Ft(()=>Dn(W,n().translate(oi.PricingTableEnterBillingAddressToCalculate))),Ue(RA,W)},$$slots:{default:!0}}),Ue(aA,sA)},eA=aA=>{var sA=Jn(),pA=Ui(sA);{var gA=yA=>{var fA=Jn(),RA=Ui(fA);MS(RA,17,()=>A.priceBreakdown.taxBreakdown,kS,(YA,W)=>{var $=xTA(),L=Xe($),H=Xe(L);Pn(H,{size:"body-small",children:(iA,oA)=>{var CA=sg();Ft(()=>Dn(CA,MA(W).display_name)),Ue(iA,CA)},$$slots:{default:!0}});var P=Ht(L,2),tA=Xe(P);Pn(tA,{size:"body-small",children:(iA,oA)=>{var CA=sg();Ft(()=>Dn(CA,n().formatPrice(MA(W).tax_amount_in_micros,A.priceBreakdown.currency))),Ue(iA,CA)},$$slots:{default:!0}}),Ue(YA,$)}),Ue(yA,fA)};$t(pA,yA=>{A.priceBreakdown.taxBreakdown!==null&&yA(gA)},!0)}Ue(aA,sA)};$t(z,aA=>{A.priceBreakdown.taxCalculationStatus==="pending"?aA(Z):aA(eA,!1)},!0)}Ue(x,q)};$t(T,x=>{A.priceBreakdown.taxCalculationStatus==="loading"?x(v):x(U,!1)})}Ue(G,M)};$t(h,G=>{MA(r)&&G(d)})}var p=Ht(h,2);{var y=G=>{var M=qTA(),w=Xe(M),b=Xe(w);Pn(b,{size:"body-small",children:(J,T)=>{var v=sg();Ft(()=>Dn(v,n().translate(oi.PricingTableTrialEnds,{formattedTrialEndDate:n().translateDate(MA(o),{dateStyle:"medium"})}))),Ue(J,v)},$$slots:{default:!0}});var _=Ht(w,2),K=Xe(_);Pn(K,{size:"body-small",children:(J,T)=>{var v=sg();Ft(()=>Dn(v,n().formatPrice(A.priceBreakdown.totalAmountInMicros,A.priceBreakdown.currency))),Ue(J,v)},$$slots:{default:!0}}),Ue(G,M)};$t(p,G=>{MA(o)&&G(y)})}var m=Ht(p,2),D=Xe(m),S=Xe(D);Pn(S,{size:"body-small",children:(G,M)=>{var w=sg();Ft(()=>Dn(w,n().translate(oi.PricingTableTotalDueToday))),Ue(G,w)},$$slots:{default:!0}});var k=Ht(D,2),N=Xe(k);Pn(N,{size:"body-small",children:(G,M)=>{var w=Jn(),b=Ui(w);{var _=J=>{var T=sg();Ft(()=>Dn(T,n().formatPrice(0,A.priceBreakdown.currency))),Ue(J,T)},K=J=>{var T=sg();Ft(()=>Dn(T,n().formatPrice(A.priceBreakdown.totalAmountInMicros,A.priceBreakdown.currency))),Ue(J,T)};$t(b,J=>{MA(o)?J(_):J(K,!1)})}Ue(G,w)},$$slots:{default:!0}}),Ue(B,Q)};let o=gn(null);(t=A.trialPhase)!=null&&t.period&&bt(o,di(hP(new Date,A.trialPhase.period,!0)));const s=Xr(eC),r=Ct(()=>A.priceBreakdown.taxCalculationStatus!=="unavailable"&&A.priceBreakdown.taxCalculationStatus!=="disabled"&&A.priceBreakdown.taxBreakdown&&A.priceBreakdown.taxBreakdown.length>0);var a=Jn(),I=Ui(a);{var c=B=>{vTA(B,{children:(Q,h)=>{g(Q)},$$slots:{default:!0}})},l=B=>{g(B)};$t(I,B=>{MA(r)?B(c):B(l,!1)})}Ue(e,a),Ni()}var PTA=St('<div class="rcb-subscribe-to svelte-4fnm8t"><!></div>'),jTA=St('<span class="rcb-product-description svelte-4fnm8t"><!></span>'),zTA=St('<div class="rcb-pricing-info-header svelte-4fnm8t"><!> <div class="rcb-product-title svelte-4fnm8t"><!></div> <!></div>');const ZTA={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 WTA(e,A){Mi(A,!1),Qi(e,ZTA);let t=ri(A,"productDetails",8),i=ri(A,"showProductDescription",8);const n=t().productType===_p.Subscription;Ic();var g=zTA(),o=Xe(g);{var s=l=>{var B=PTA(),Q=Xe(B);Pn(Q,{size:"body-base",children:(h,d)=>{var p=mm(()=>({productTitle:t().title}));Va(h,{get key(){return oi.ProductInfoSubscribeTo},get variables(){return MA(p)}})},$$slots:{default:!0}}),Ue(l,B)};$t(o,l=>{n&&l(s)})}var r=Ht(o,2),a=Xe(r);Pn(a,{size:"heading-lg",branded:!0,children:(l,B)=>{var Q=mm(()=>({productTitle:t().title}));Va(l,{get key(){return oi.ProductInfoProductTitle},get variables(){return MA(Q)}})},$$slots:{default:!0}});var I=Ht(r,2);{var c=l=>{var B=jTA(),Q=Xe(B);Pn(Q,{size:"body-small",children:(h,d)=>{var p=mm(()=>({productDescription:t().description}));Va(h,{get key(){return oi.ProductInfoProductDescription},get variables(){return MA(p)}})},$$slots:{default:!0}}),Ue(l,B)};$t(I,l=>{i()&&t().description&&l(c)})}Ue(e,g),Ni()}var VTA=St("<div><!></div>"),XTA=St("<div><!> <!></div>"),$TA=St('<div class="rcb-product-price-container svelte-509gz3"><!> <!> <div><!> <!> <!></div></div>');const AqA={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 eqA(e,A){Mi(A,!0),Qi(e,AqA);const t=uI(),i=()=>QI(n,"$translator",t),n=Xr(eC),g=Ct(()=>{var w;return(w=A.introPricePhase)!=null&&w.period&&i().translatePeriod(A.introPricePhase.period.number*A.introPricePhase.cycleCount,A.introPricePhase.period.unit)||""}),o=Ct(()=>"heading-lg"),s=Ct(()=>{var w;return(w=A.trialPhase)!=null&&w.periodDuration?"heading-md":"heading-lg"}),r=Ct(()=>{var w,b;return(w=A.trialPhase)!=null&&w.periodDuration||(b=A.introPricePhase)!=null&&b.periodDuration?"heading-md":"heading-lg"}),a=Ct(()=>{var w;return(w=A.trialPhase)==null?void 0:w.periodDuration}),I=Ct(()=>{var w;return(w=A.introPricePhase)==null?void 0:w.periodDuration}),c=Ct(()=>{var w;return((w=A.introPricePhase)==null?void 0:w.cycleCount)==1}),l=Ct(()=>{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=Ct(()=>i().formatPrice(A.priceBreakdown.totalAmountInMicros,A.priceBreakdown.currency));var Q=$TA(),h=Xe(Q);{var d=w=>{var b=VTA(),_=Xe(b);Pn(_,{get size(){return MA(o)},children:(K,J)=>{var T=Ct(()=>({trialDuration:l_A(A.trialPhase.periodDuration,i())}));Va(K,{get key(){return oi.ProductInfoFreeTrialDuration},get variables(){return MA(T)}})},$$slots:{default:!0}}),Ue(w,b)};$t(h,w=>{var b;(b=A.trialPhase)!=null&&b.periodDuration&&w(d)})}var p=Ht(h,2);{var y=w=>{var b=XTA(),_=Xe(b);Pn(_,{get size(){return MA(s)},children:(v,U)=>{var x=Ct(()=>MA(a)?oi.ProductInfoIntroPricePhaseAfterTrial:oi.ProductInfoIntroPricePhase),q=Ct(()=>({introPriceDuration:MA(g),introPrice:MA(B)}));Va(v,{get key(){return MA(x)},get variables(){return MA(q)}})},$$slots:{default:!0}});var K=Ht(_,2);{var J=v=>{Pn(v,{size:"body-small",children:(U,x)=>{Va(U,{get key(){return oi.ProductInfoIntroPricePhasePaidOnce}})},$$slots:{default:!0}})},T=v=>{var U=Jn(),x=Ui(U);{var q=z=>{Pn(z,{size:"body-small",children:(Z,eA)=>{var aA=sg();Ft(()=>Dn(aA,i().translatePeriodFrequency(A.introPricePhase.period.number,A.introPricePhase.period.unit,{useMultipleWords:!0}))),Ue(Z,aA)},$$slots:{default:!0}})};$t(x,z=>{A.introPricePhase.period&&z(q)},!0)}Ue(v,U)};$t(K,v=>{MA(c)?v(J):v(T,!1)})}Ue(w,b)};$t(p,w=>{var b;(b=A.introPricePhase)!=null&&b.periodDuration&&w(y)})}var m=Ht(p,2),D=Xe(m);Pn(D,{get size(){return MA(r)},children:(w,b)=>{var _=sg();Ft(()=>Dn(_,MA(l))),Ue(w,_)},$$slots:{default:!0}});var S=Ht(D,2);{var k=w=>{Pn(w,{size:"body-small",children:(b,_)=>{var K=sg();Ft(()=>Dn(K,i().translatePeriodFrequency(A.basePhase.period.number,A.basePhase.period.unit,{useMultipleWords:!0}))),Ue(b,K)},$$slots:{default:!0}})};$t(S,w=>{var b;(b=A.basePhase)!=null&&b.period&&w(k)})}var N=Ht(S,2);{var G=w=>{Pn(w,{size:"body-small",children:(b,_)=>{Va(b,{get key(){return oi.ProductInfoAfter}})},$$slots:{default:!0}})},M=w=>{var b=Jn(),_=Ui(b);{var K=J=>{Pn(J,{size:"body-small",children:(T,v)=>{Va(T,{get key(){return oi.ProductInfoAfterTrial}})},$$slots:{default:!0}})};$t(_,J=>{MA(a)&&J(K)},!0)}Ue(w,b)};$t(N,w=>{MA(I)?w(G):w(M,!1)})}Ue(e,Q),Ni()}var tqA=St('<div class="rcb-pricing-info svelte-18guro7"><div class="rcb-pricing-info-header svelte-18guro7"><!> <!></div> <!></div>');const iqA={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 nqA(e,A){Qi(e,iqA);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,r=o==null?void 0:o.trial,a=o==null?void 0:o.introPrice;var I=tqA(),c=Xe(I),l=Xe(c);WTA(l,{get productDetails(){return t()},get showProductDescription(){return n()}});var B=Ht(l,2);eqA(B,{get priceBreakdown(){return g()},basePhase:s,trialPhase:r,introPricePhase:a});var Q=Ht(c,2);OTA(Q,{get priceBreakdown(){return g()},trialPhase:r}),Ue(e,I)}const Qk=e=>`https://da08ctfrofx1b.cloudfront.net/${e}`;var gqA=St('<div class="rcb-ui-container svelte-1h6xr8z"><!></div>');const oqA={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 sqA(e,A){Mi(A,!0),Qi(e,oqA);const t=ri(A,"brandingAppearance",3,void 0),i=ri(A,"brandFontConfig",3,void 0),n=ri(A,"isInElement",3,!1),g=Ct(()=>new IN(t()).getTextStyleVars(i())),o=Ct(()=>new IN(t()).spacingStyleVars),s=Ct(()=>[MA(g),MA(o)].join("; ")),r=Ct(()=>{var l;return(l=i())!=null&&l.font_url?Qk(i().font_url):null}),a=async l=>{try{const B=new FontFace(iBA,`url(${l})`);await B.load(),document.fonts.add(B)}catch(B){console.error("Failed to set brand font:",B)}};wS(()=>{MA(r)&&a(MA(r))});var I=gqA(),c=Xe(I);es(c,()=>A.children??rg),Ft(()=>{Ii(I,"style",MA(s)),JE(I,"fullscreen",!n()),JE(I,"inside",n())}),Ue(e,I),Ni()}var rqA=St('<div id="layout-query-container" class="svelte-1x4ow5d"><div class="rcb-ui-layout svelte-1x4ow5d"><!></div></div>');const aqA={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 IqA(e,A){Mi(A,!1),Qi(e,aqA);let t=ri(A,"style",8,""),i=ri(A,"children",8);Ic();var n=rqA(),g=Xe(n),o=Xe(g);es(o,()=>i()??rg),Ft(()=>Ii(g,"style",t())),Ue(e,n),Ni()}const CqA=e=>e;function cqA(e){const A=e-1;return A*A*A+1}function R7(e){const A=typeof e=="string"&&e.match(/^\s*(-?[\d.]+)([^\s]*)\s*$/);return A?[parseFloat(A[1]),A[2]||"px"]:[e,"px"]}function lqA(e,{delay:A=0,duration:t=400,easing:i=CqA}={}){const n=+getComputedStyle(e).opacity;return{delay:A,duration:t,easing:i,css:g=>`opacity: ${g*n}`}}function BqA(e,{delay:A=0,duration:t=400,easing:i=cqA,x:n=0,y:g=0,opacity:o=0}={}){const s=getComputedStyle(e),r=+s.opacity,a=s.transform==="none"?"":s.transform,I=r*(1-o),[c,l]=R7(n),[B,Q]=R7(g);return{delay:A,duration:t,easing:i,css:(h,d)=>`
			transform: ${a} translate(${(1-h)*c}${l}, ${(1-h)*B}${Q});
			opacity: ${r-I*d}`}}var EqA=St('<div><div class="layout-wrapper svelte-1w6qvx7"><div><!></div></div></div>');const QqA={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 QBA(e,A){Mi(A,!0),Qi(e,QqA);const t=`rcb-${A.location}`;var i=EqA();sd(i,`layout-wrapper-outer ${t??""} svelte-1w6qvx7`);var n=Xe(i),g=Xe(n);sd(g,`layout-content ${t??""} svelte-1w6qvx7`);var o=Xe(g);es(o,()=>A.children??rg),UlA(3,g,()=>lqA,()=>({duration:500,delay:50})),Ue(e,i),Ni()}var uqA=St('<div class="navbar-body svelte-jz90ay"><!></div>'),dqA=St('<div class="navbar-header svelte-jz90ay"><!></div> <!>',1),hqA=St('<div class="rcb-ui-navbar svelte-jz90ay"><!></div>');const pqA={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 fqA(e,A){Mi(A,!0),Qi(e,pqA);const t=ri(A,"brandingAppearance",3,void 0),i=Ct(()=>new IN(t()).productInfoStyleVars);var n=hqA(),g=Xe(n);QBA(g,{location:"navbar",children:(o,s)=>{var r=dqA(),a=Ui(r),I=Xe(a);es(I,()=>A.headerContent??rg);var c=Ht(a,2);{var l=B=>{var Q=uqA(),h=Xe(Q);es(h,()=>A.bodyContent??rg),Ue(B,Q)};$t(c,B=>{A.bodyContent&&B(l)})}Ue(o,r)},$$slots:{default:!0}}),Ft(()=>Ii(n,"style",MA(i))),Ue(e,n),Ni()}var yqA=St('<button class="rcb-close-button svelte-nssttr" data-testid="close-button"><!></button>');const DqA={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 uBA(e,A){Qi(e,DqA);var t=yqA(),i=Xe(t);CN(i,{name:"close"}),nB("click",t,function(n){KlA.call(this,A,n)}),Ue(e,t)}const mqA=`<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 SqA=St('<div style="color:var(--rc-color-accent);" class="rcb-ui-asset-icon svelte-5vi85d"><!></div>');const wqA={hash:"svelte-5vi85d",code:"div.svelte-5vi85d {height:12px;width:12px;}"};function kqA(e){Qi(e,wqA);var A=SqA(),t=Xe(A);Gd(t,()=>mqA),Ue(e,A)}var MqA=St('<span class="rcb-sandbox-text svelte-18xxdea">SANDBOX</span>'),NqA=St('<span class="rcb-sandbox-text svelte-18xxdea">Share feedback</span>'),RqA=St('<a class="rcb-ui-sandbox-banner-link svelte-18xxdea" target="_blank"><!> <!></a>'),GqA=St('<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 bqA={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 UqA(e,A){Mi(A,!1),Qi(e,bqA);let t=ri(A,"style",8,""),i=ri(A,"isInElement",8,!1),n=ri(A,"brandingInfo",8,null),g=kc(!0);function o(){Xi.debugLog("closeBanner"),bt(g,!1)}Ic();var s=Jn(),r=Ui(s);{var a=I=>{var c=GqA(),l=Ht(Xe(c),2),B=Xe(l);Pn(B,{size:"caption-default",children:(y,m)=>{var D=MqA();Ue(y,D)},$$slots:{default:!0}});var Q=Ht(l,2),h=Xe(Q);{var d=y=>{var m=RqA(),D=Xe(m);kqA(D);var S=Ht(D,2);Pn(S,{size:"caption-link",children:(k,N)=>{var G=NqA();Ue(k,G)},$$slots:{default:!0}}),Ft(()=>Ii(m,"href",n().sandbox_configuration.checkout_feedback_form_url)),Ue(y,m)};$t(h,y=>{var m;(m=n())!=null&&m.sandbox_configuration&&y(d)})}var p=Ht(h,2);uBA(p,{$$events:{click:o}}),Ft(()=>{Ii(c,"style",t()),JE(c,"isInElement",i())}),UlA(2,c,()=>BqA,()=>({y:-100,duration:300})),Ue(I,c)};$t(r,I=>{MA(g)&&I(a)})}Ue(e,s),Ni()}var vqA=St('<div class="rcb-ui-main svelte-nr408n"><!></div>');const KqA={hash:"svelte-nr408n",code:".rcb-ui-main.svelte-nr408n {flex:1;display:flex;background-color:var(--rc-color-background);}"};function FqA(e,A){Mi(A,!0),Qi(e,KqA);const t=Ct(()=>new IN(A.brandingAppearance).formStyleVars);var i=vqA(),n=Xe(i);QBA(n,{location:"main-block",children:(g,o)=>{var s=Jn(),r=Ui(s);es(r,()=>A.children??rg),Ue(g,s)},$$slots:{default:!0}}),Ft(()=>Ii(i,"style",MA(t))),Ue(e,i),Ni()}var _qA=St("<!> <!>",1),JqA=St("<!> <!>",1);function LqA(e,A){Mi(A,!0);const t=Ct(()=>{var g;return oBA((g=A.brandingInfo)==null?void 0:g.appearance)??""});var i=Ct(()=>{var g;return(g=A.brandingInfo)==null?void 0:g.appearance}),n=Ct(()=>{var g;return(g=A.brandingInfo)==null?void 0:g.brand_font_config});sqA(e,{get brandingAppearance(){return MA(i)},get brandFontConfig(){return MA(n)},get isInElement(){return A.isInElement},children:(g,o)=>{var s=JqA(),r=Ui(s);{var a=c=>{UqA(c,{get style(){return MA(t)},get isInElement(){return A.isInElement},get brandingInfo(){return A.brandingInfo}})};$t(r,c=>{A.isSandbox&&c(a)})}var I=Ht(r,2);IqA(I,{get style(){return MA(t)},children:(c,l)=>{var B=_qA(),Q=Ui(B);{var h=y=>{var m=Ct(()=>{var D;return(D=A.brandingInfo)==null?void 0:D.appearance});fqA(y,{get brandingAppearance(){return MA(m)},get headerContent(){return A.navbarHeaderContent},get bodyContent(){return A.navbarBodyContent}})};$t(Q,y=>{(A.navbarHeaderContent||A.navbarBodyContent)&&y(h)})}var d=Ht(Q,2),p=Ct(()=>{var y;return(y=A.brandingInfo)==null?void 0:y.appearance});FqA(d,{get brandingAppearance(){return MA(p)},children:(y,m)=>{var D=Jn(),S=Ui(D);es(S,()=>A.mainContent??rg),Ue(y,D)},$$slots:{default:!0}}),Ue(c,B)},$$slots:{default:!0}}),Ue(g,s)},$$slots:{default:!0}}),Ni()}var xqA=St('<source type="image/webp">'),TqA=St('<picture class="rcb-app-icon-picture-container svelte-el1u77"><!> <img class="rcb-app-icon svelte-el1u77" alt="App icon"></picture>'),qqA=St('<div class="rcb-app-icon loading svelte-el1u77"></div>');const YqA={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 HqA(e,A){Qi(e,YqA);var t=Jn(),i=Ui(t);{var n=o=>{var s=TqA(),r=Xe(s);{var a=c=>{var l=xqA();Ft(()=>Ii(l,"srcset",A.srcWebp)),Ue(c,l)};$t(r,c=>{A.srcWebp&&c(a)})}var I=Ht(r,2);Ft(()=>Ii(I,"src",A.src)),Ue(o,s)},g=o=>{var s=qqA();Ue(o,s)};$t(i,o=>{A.src?o(n):o(g,!1)})}Ue(e,t)}var OqA=St('<button class="rcb-back-button svelte-9xjbko" data-testid="close-button"><!></button>');const PqA={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 jqA(e,A){Qi(e,PqA);var t=OqA(),i=Xe(t);CN(i,{name:"back"}),nB("click",t,function(n){KlA.call(this,A,n)}),Ue(e,t)}var zqA=St('<source type="image/webp" class="rcb-app-icon svelte-19gv4gf">'),ZqA=St('<picture class="rcb-app-icon svelte-19gv4gf"><!> <img class="rcb-app-icon svelte-19gv4gf" alt="App icon"></picture>');const WqA={hash:"svelte-19gv4gf",code:".rcb-app-icon.svelte-19gv4gf {height:32px;}"};function VqA(e,A){Qi(e,WqA);var t=ZqA(),i=Xe(t);{var n=o=>{var s=zqA();Ft(()=>Ii(s,"srcset",A.srcWebp)),Ue(o,s)};$t(i,o=>{A.srcWebp&&o(n)})}var g=Ht(i,2);Ft(()=>Ii(g,"src",A.src)),Ue(e,t)}var XqA=St('<div class="rcb-back-wrapper svelte-11zapuq"><!></div>'),$qA=St('<div class="rcb-close-wrapper svelte-11zapuq"><!></div>'),A2A=St('<div class="rcb-header-wrapper svelte-11zapuq"><!> <div class="rcb-header svelte-11zapuq"><div class="rcb-title svelte-11zapuq"><!> <!></div></div> <!></div>');const e2A={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 t2A(e,A){Mi(A,!0),Qi(e,e2A);const t=G=>G==null||G==null||G==""?null:G,i=Ct(()=>{var G;return t((G=A.brandingInfo)==null?void 0:G.app_icon)}),n=Ct(()=>{var G;return t((G=A.brandingInfo)==null?void 0:G.app_icon_webp)}),g=Ct(()=>{var G;return t((G=A.brandingInfo)==null?void 0:G.app_wordmark)}),o=Ct(()=>{var G;return t((G=A.brandingInfo)==null?void 0:G.app_wordmark_webp)}),s=Ct(()=>MA(i)?Qk(MA(i)):null),r=Ct(()=>MA(n)?Qk(MA(n)):null),a=Ct(()=>MA(g)?Qk(MA(g)):null),I=Ct(()=>MA(o)?Qk(MA(o)):null),c=()=>{A.onClose&&A.onClose()};var l=A2A(),B=Xe(l);{var Q=G=>{var M=XqA(),w=Xe(M);jqA(w,{$$events:{click:c}}),Ue(G,M)};$t(B,G=>{A.showCloseButton&&G(Q)})}var h=Ht(B,2),d=Xe(h),p=Xe(d);{var y=G=>{VqA(G,{get src(){return MA(a)},get srcWebp(){return MA(I)}})},m=G=>{var M=Jn(),w=Ui(M);{var b=_=>{HqA(_,{get src(){return MA(s)},get srcWebp(){return MA(r)}})};$t(w,_=>{MA(s)!==null&&MA(r)!==null&&_(b)},!0)}Ue(G,M)};$t(p,G=>{MA(a)!==null?G(y):G(m,!1)})}var D=Ht(p,2);{var S=G=>{Pn(G,{size:"body-base",children:(M,w)=>{var b=sg();Ft(()=>{var _;return Dn(b,(_=A.brandingInfo)==null?void 0:_.app_name)}),Ue(M,b)},$$slots:{default:!0}})};$t(D,G=>{MA(a)===null&&G(S)})}var k=Ht(h,2);{var N=G=>{var M=$qA(),w=Xe(M);uBA(w,{$$events:{click:c}}),Ue(G,M)};$t(k,G=>{A.showCloseButton&&G(N)})}Ft(()=>JE(l,"rcb-with-close-button",A.showCloseButton)),Ue(e,l),Ni()}var i2A=St("<!> <!> <!> <!>",1);function n2A(e,A){Mi(A,!0);const t=ri(A,"onClose",3,void 0),i=lBA(A.productDetails,A.purchaseOptionToUse);let n=gn(di(A.defaultPriceBreakdown??{currency:i.currency,totalAmountInMicros:i.amountMicros,totalExcludingTaxInMicros:i.amountMicros,taxCalculationStatus:"unavailable",taxAmountInMicros:null,taxBreakdown:null}));const g=o=>{bt(n,di(o))};LqA(e,{get brandingInfo(){return A.brandingInfo},get isInElement(){return A.isInElement},get isSandbox(){return A.isSandbox},get onClose(){return t()},navbarHeaderContent:o=>{var s=Ct(()=>!A.isInElement&&!!t());t2A(o,{get brandingInfo(){return A.brandingInfo},get onClose(){return t()},get showCloseButton(){return MA(s)}})},navbarBodyContent:o=>{var s=Ct(()=>{var r,a;return((a=(r=A.brandingInfo)==null?void 0:r.appearance)==null?void 0:a.show_product_description)??!1});nqA(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=i2A(),r=Ui(s);{var a=d=>{GTA(d)};$t(r,d=>{A.currentPage==="payment-entry-loading"&&d(a)})}var I=Ht(r,2);{var c=d=>{WxA(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})};$t(I,d=>{A.currentPage==="payment-entry"&&d(c)})}var l=Ht(I,2);{var B=d=>{var p=Ct(()=>{var m;return((m=A.brandingInfo)==null?void 0:m.support_email)??null}),y=Ct(()=>{var m;return((m=A.brandingInfo)==null?void 0:m.app_name)??null});NTA(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)}})};$t(l,d=>{A.currentPage==="error"&&d(B)})}var Q=Ht(l,2);{var h=d=>{RTA(d,{get onContinue(){return A.onContinue}})};$t(Q,d=>{A.currentPage==="success"&&d(h)})}Ue(o,s)},$$slots:{navbarHeaderContent:!0,navbarBodyContent:!0,mainContent:!0}}),Ni()}function g2A(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 o2A(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 Xi.errorLog(A),new fo(fs.ConfigurationError,A)}}function s2A(e,A){var t;Mi(A,!0);const i=ri(A,"customTranslations",19,()=>({})),n=ri(A,"skipSuccessPage",3,!1),g=A.customerEmail?g2A(A.customerEmail):null;let o=gn(di(g?void 0:A.customerEmail)),s=A.rcPackage.webBillingProduct,r=gn(null);const a=A.rcPackage.webBillingProduct.identifier??null;let I=gn("payment-entry-loading"),c=gn(null),l=gn(di({})),B=gn(null),Q=gn(null),h=gn(null),d=gn(null),p=new FL(i(),A.selectedLocale,A.defaultLocale),y=xlA(p);d2(eC,y),d2(O8,(t=A.brandingInfo)==null?void 0:t.appearance),gc(()=>{A.isInElement||(bt(Q,di(document.documentElement.style.height)),bt(h,di(document.documentElement.style.overflow)),bt(d,di(document.body.style.height)),document.documentElement.style.height="100%",document.body.style.height="100%",document.documentElement.style.overflow="hidden")}),xR(()=>{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))}}),d2(H8,A.eventsTracker),gc(async()=>{if(a===null){D(new Gg(Bg.ErrorSettingUpPurchase,"Product ID was not set before purchase."));return}A.purchaseOperationHelper.checkoutStart(A.appUserId,a,A.purchaseOption,A.rcPackage.webBillingProduct.presentedOfferingContext,MA(o),A.metadata).then(G=>{bt(r,null),bt(I,"payment-entry"),bt(l,di(G.gateway_params)),bt(B,di(G.management_url))}).catch(G=>{if(G.errorCode===Bg.MissingEmailError)return bt(o,void 0),A.purchaseOperationHelper.checkoutStart(A.appUserId,a,A.purchaseOption,A.rcPackage.webBillingProduct.presentedOfferingContext,MA(o),A.metadata).then(M=>{bt(r,null),bt(I,"payment-entry"),bt(l,di(M.gateway_params)),bt(B,di(M.management_url))}).catch(M=>{D(M)});D(G)})});const m=()=>{if(MA(I)==="payment-entry"){A.purchaseOperationHelper.pollCurrentPurchaseForCompletion().then(G=>{bt(c,di(G)),n()?A.onFinished(G):bt(I,"success")}).catch(G=>{D(G)});return}if(MA(I)==="success"||MA(I)==="error"){A.onFinished(MA(c));return}bt(I,"success")},D=G=>{const M=_LA({errorCode:G.getErrorCode().toString(),errorMessage:G.message});A.eventsTracker.trackSDKEvent(M),bt(r,di(G)),bt(I,"error")},S=()=>{A.onError(MA(r)??new Gg(Bg.UnknownError,"Unknown error without state set."))};var k=Ct(()=>A.purchases.isSandbox()),N=Ct(()=>MA(o)??null);n2A(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(r)},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}}),Ni()}function dBA(e){return e==null?!0:new Date(e)>new Date}function r2A(e,A,t,i){const n=A.product_identifier;if(n in t)return a2A(e,A,t[n]);if(n in i)return I2A(e,A,i[n]);throw new fo(fs.CustomerInfoError,"Could not find entitlement product in subscriptions or non-subscriptions.")}function a2A(e,A,t){return{identifier:e,isActive:dBA(A.expires_date),willRenew:pBA(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:Yl(A.expires_date),productIdentifier:A.product_identifier,productPlanIdentifier:A.product_plan_identifier??null,unsubscribeDetectedAt:Yl(t==null?void 0:t.unsubscribe_detected_at),billingIssueDetectedAt:Yl(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 I2A(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 C2A(e,A,t){const i={},n={};for(const g in e){const o=r2A(g,e[g],A,t);i[g]=o,o.isActive&&(n[g]=o)}return{all:i,active:n}}function Yl(e){return e==null?null:new Date(e)}function hBA(e){const A=l2A(e),t=e.subscriber,i=E2A(t.non_subscriptions),n=Object.entries(e.subscriber.non_subscriptions).flatMap(([s,r])=>r.map(a=>({transactionIdentifier:a.id,productIdentifier:s,purchaseDate:new Date(a.purchase_date||a.original_purchase_date),storeTransactionId:a.store_transaction_id||null,store:a.store}))),g=new Date(e.request_date),o=Object.fromEntries(Object.entries(e.subscriber.subscriptions).map(([s,r])=>[s,{productIdentifier:s,purchaseDate:new Date(r.purchase_date),originalPurchaseDate:Yl(r.original_purchase_date),expiresDate:Yl(r.expires_date),store:r.store,unsubscribeDetectedAt:Yl(r.unsubscribe_detected_at),isSandbox:r.is_sandbox,billingIssuesDetectedAt:Yl(r.billing_issues_detected_at),gracePeriodExpiresDate:Yl(r.grace_period_expires_date),ownershipType:r.ownership_type??"UNKNOWN",periodType:r.period_type,refundedAt:Yl(r.refunded_at),storeTransactionId:r.store_transaction_id||null,isActive:dBA(r.expires_date),willRenew:pBA(r.expires_date,r)}]));return{entitlements:C2A(t.entitlements,t.subscriptions,i),allExpirationDatesByProduct:A,allPurchaseDatesByProduct:c2A(e,i),activeSubscriptions:B2A(A),managementURL:t.management_url,requestDate:g,firstSeenDate:new Date(t.first_seen),originalPurchaseDate:Yl(t.original_purchase_date),originalAppUserId:e.subscriber.original_app_user_id,nonSubscriptionTransactions:n,subscriptionsByProductIdentifier:o}}function pBA(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 c2A(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 l2A(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 B2A(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 E2A(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 fBA="1.13.1",Q2A="https://api.revenuecat.com",u2A="https://e.revenue.cat";var HF;(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"})(HF||(HF={}));const d2A=/^rcb_[a-zA-Z0-9_.-]+$/,h2A=/^pdl_[a-zA-Z0-9_.-]+$/,p2A=/^test_[a-zA-Z0-9_.-]+$/;function OF(e){return e?e.startsWith("rcb_sb_"):!1}function f2A(e){return e?d2A.test(e):!1}function y2A(e){return e?h2A.test(e):!1}function uk(e){return e?p2A.test(e):!1}async function yc(e,A,t){const{apiKey:i,body:n,headers:g,httpConfig:o}=A,s=`${(o==null?void 0:o.proxyURL)??Q2A}${e.urlPath()}`;try{const r=await fetch(s,{method:e.method,headers:RBA(i,g,o==null?void 0:o.additionalHeaders),body:m2A(n),signal:t});return await D2A(r,e),await r.json()}catch(r){throw r instanceof TypeError?new fo(fs.NetworkError,oM.getPublicMessage(fs.NetworkError),r.message):r}}async function D2A(e,A){const t=e.status;if(t>=HF.INTERNAL_SERVER_ERROR)y2(A,t,await e.text());else if(t>=HF.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=oM.convertCodeToBackendErrorCode(g);if(s==null)y2(A,t,n,g);else throw fo.getForBackendError(s,o)}else y2(A,t,n)}}function y2(e,A,t,i){throw new fo(fs.UnknownBackendError,"Unknown backend error.",`Request: ${e.name}. Status code: ${A}. Body: ${t}.`,{backendErrorCode:i})}function m2A(e){return e==null?null:JSON.stringify(e)}const yBA="Authorization",DBA="Content-Type",mBA="Accept",SBA="X-Platform",wBA="X-Version",kBA="X-Platform-Flavor",MBA="X-Platform-Flavor-Version",NBA="X-Is-Sandbox",S2A=new Set([yBA,DBA,mBA,SBA,wBA,NBA,kBA,MBA]);function RBA(e,A,t){let i={[yBA]:`Bearer ${e}`,[DBA]:"application/json",[mBA]:"application/json",[SBA]:"web",[wBA]:fBA,[NBA]:`${OF(e)}`};const n=gp.getPlatformInfo();if(n){const g={[kBA]:n.flavor,[MBA]:n.version};i={...i,...g}}return A&&(i={...i,...A}),t&&(i={...t,...i}),i}const JL="/v1/subscribers",ww="/rcbilling/v1";class w2A{constructor(A){Tt(this,"appUserId"),Tt(this,"method","GET"),Tt(this,"name","getOfferings"),this.appUserId=A}urlPath(){const A=encodeURIComponent(this.appUserId);return`${JL}/${A}/offerings`}}class k2A{constructor(A,t,i){Tt(this,"method","GET"),Tt(this,"name","getProducts"),Tt(this,"appUserId"),Tt(this,"productIds"),Tt(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`${ww}/subscribers/${A}/products?id=${t}${i}`}}class M2A{constructor(A){Tt(this,"method","GET"),Tt(this,"name","getCustomerInfo"),Tt(this,"appUserId"),this.appUserId=A}urlPath(){const A=encodeURIComponent(this.appUserId);return`${JL}/${A}`}}class N2A{constructor(){Tt(this,"method","GET"),Tt(this,"name","getBrandingInfo")}urlPath(){return`${ww}/branding`}}class R2A{constructor(){Tt(this,"method","POST"),Tt(this,"name","postCheckoutStart")}urlPath(){return`${ww}/checkout/start`}}class G2A{constructor(A){Tt(this,"method","POST"),Tt(this,"name","postCheckoutCalculateTax"),Tt(this,"operationSessionId"),this.operationSessionId=A}urlPath(){return`${ww}/checkout/${this.operationSessionId}/calculate_taxes`}}class b2A{constructor(A){Tt(this,"method","POST"),Tt(this,"name","postCheckoutComplete"),Tt(this,"operationSessionId"),this.operationSessionId=A}urlPath(){return`${ww}/checkout/${this.operationSessionId}/complete`}}class U2A{constructor(A){Tt(this,"method","GET"),Tt(this,"name","getCheckoutStatus"),Tt(this,"operationSessionId"),this.operationSessionId=A}urlPath(){return`${ww}/checkout/${this.operationSessionId}`}}class v2A{constructor(A){Tt(this,"method","POST"),Tt(this,"name","setAttributes"),Tt(this,"appUserId"),this.appUserId=A}urlPath(){const A=encodeURIComponent(this.appUserId);return`${JL}/${A}/attributes`}}class K2A{constructor(){Tt(this,"method","POST"),Tt(this,"name","postReceipt")}urlPath(){return"/v1/receipts"}}class F2A{constructor(A){Tt(this,"method","GET"),Tt(this,"name","getVirtualCurrencies"),Tt(this,"appUserId"),this.appUserId=A}urlPath(){const A=encodeURIComponent(this.appUserId);return`${JL}/${A}/virtual_currencies`}}const kP={};class _2A{constructor(A,t=kP){Tt(this,"API_KEY"),Tt(this,"httpConfig"),Tt(this,"isSandbox"),this.API_KEY=A,this.httpConfig=t,this.isSandbox=OF(A)}getIsSandbox(){return this.isSandbox}async getOfferings(A){return await yc(new w2A(A),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getCustomerInfo(A){return await yc(new M2A(A),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getProducts(A,t,i){return await yc(new k2A(A,t,i),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getBrandingInfo(){return await yc(new N2A,{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async postCheckoutStart(A,t,i,n,g,o,s=void 0){const r={app_user_id:A,product_id:t,email:o,price_id:n.priceId,presented_offering_identifier:i.offeringIdentifier,trace_id:g};return s&&(r.metadata=s),n.id!=="base_option"&&(r.offer_id=n.id),i.targetingContext&&(r.applied_targeting_rule={rule_id:i.targetingContext.ruleId,revision:i.targetingContext.revision}),i.placementIdentifier&&(r.presented_placement_identifier=i.placementIdentifier),await yc(new R2A,{apiKey:this.API_KEY,body:r,httpConfig:this.httpConfig})}async postCheckoutCalculateTax(A,t,i,n){const g={country_code:t,postal_code:i};return await yc(new G2A(A),{apiKey:this.API_KEY,body:g,httpConfig:this.httpConfig},n)}async postCheckoutComplete(A,t){const i={email:t};return await yc(new b2A(A),{apiKey:this.API_KEY,body:i,httpConfig:this.httpConfig})}async getCheckoutStatus(A){return await yc(new U2A(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 yc(new v2A(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 yc(new K2A,{apiKey:this.API_KEY,body:s,httpConfig:this.httpConfig})}async getVirtualCurrencies(A){return await yc(new F2A(A),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}}function J2A(e,A){if(!(f2A(e)||uk(e)||y2A(e)&&(A!=null&&A.allowPaddleAPIKey)))throw new fo(fs.InvalidCredentialsError,"Invalid API key. Use your Web Billing API key.")}function G7(e){if(!e||new Set(["no_user","null","none","nil","(null)","NaN","\\x00","","unidentified","undefined","unknown"]).has(e)||e.includes("/"))throw new fo(fs.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 L2A(e){if(e!=null&&e.endsWith("/"))throw new fo(fs.ConfigurationError,"Invalid proxy URL. The proxy URL should not end with a trailing slash.")}function x2A(e){if(e){for(const A in e)if(S2A.has(A))throw new fo(fs.ConfigurationError,"Invalid additional headers. Some headers are reserved for internal use.")}}var GBA=(e=>(e.Current="current",e))(GBA||{});function T2A(e,A){async function t(...i){return await this.preload(),await e.call(this,...i)}return t}const bBA=(e,A)=>{const t={...e.webBillingProduct,presentedOfferingContext:{...e.webBillingProduct.presentedOfferingContext,placementIdentifier:A}};return{...e,webBillingProduct:t,rcBillingProduct:t}},ch=(e,A)=>e==null?null:bBA(e,A),q2A=(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,r])=>[s,bBA(r,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 Y2A(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=gTA(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&&Xi.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 H2A=1000001;function O2A(e){return e.webBillingProduct.defaultPurchaseOption}function b7(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 P2A(e,A){return e.unit==="year"?A.translatePeriod(e.number*12,hr.Month):A.translatePeriod(e.number,e.unit)}function j2A({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 z2A({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 U7({price:e,period:A,full:t=!1,translator:i}){if(!A||!A.number||A.unit===hr.Month&&A.number==1)return i.formatPrice(e.amountMicros,e.currency);let n="";switch(A.unit){case hr.Year:n=i.formatPrice(e.amountMicros/12,e.currency);break;case hr.Month:n=i.formatPrice(e.amountMicros/A.number,e.currency);break;case hr.Week:n=i.formatPrice(e.amountMicros*4/A.number,e.currency);break;case hr.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(hr.Month,{noWhitespace:!0,short:!t})})}function Z2A(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]=W2A(g,i,A),n),{})}function W2A(e,A,t){const i=e.webBillingProduct,n=i.price||i.price,g=t.formatPrice(n.amountMicros,n.currency),o=O2A(e),s=i.productType,r={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){r.price_per_period=b7(g,o,t),r.price_per_period_full=b7(g,o,t,!0);const a=i.period||o.base.period;r.total_price_and_per_month=U7({price:n,period:a,translator:t}),r.total_price_and_per_month_full=U7({price:n,period:a,full:!0,translator:t}),r.sub_price_per_month=z2A({price:n,period:a,translator:t}),r.sub_price_per_week=j2A({price:n,period:a,translator:t}),r.sub_duration=t.translatePeriod(a==null?void 0:a.number,a==null?void 0:a.unit),r.sub_duration_in_months=P2A(a,t),r.sub_period=t.translatePeriodFrequency(a==null?void 0:a.number,a==null?void 0:a.unit),r.sub_period_length=a?t.translatePeriodUnit(a.unit,{noWhitespace:!0}):void 0,r.sub_period_abbreviated=a?t.translatePeriodUnit(a.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);r.sub_relative_discount=I===c?"":t.translate(oi.PaywallVariablesSubRelativeDiscount,{discount:l})}return(s===_p.NonConsumable||s===_p.Consumable)&&o&&(r.price=g,r.price_per_period=g,r.price_per_period_full=g,r.total_price_and_per_month=g,r.sub_price_per_month=g,r.sub_duration=t.translate(oi.PeriodsLifetime),r.sub_duration_in_months=t.translate(oi.PeriodsLifetime),r.sub_period=t.translate(oi.PeriodsLifetime),r.sub_price_per_week=void 0,r.sub_relative_discount=void 0,r.price_per_period_full=g,r.total_price_and_per_month_full=g,r.sub_period_length=void 0,r.sub_period_abbreviated=void 0),r}const lr=[];for(let e=0;e<256;++e)lr.push((e+256).toString(16).slice(1));function V2A(e,A=0){return(lr[e[A+0]]+lr[e[A+1]]+lr[e[A+2]]+lr[e[A+3]]+"-"+lr[e[A+4]]+lr[e[A+5]]+"-"+lr[e[A+6]]+lr[e[A+7]]+"-"+lr[e[A+8]]+lr[e[A+9]]+"-"+lr[e[A+10]]+lr[e[A+11]]+lr[e[A+12]]+lr[e[A+13]]+lr[e[A+14]]+lr[e[A+15]]).toLowerCase()}let D2;const X2A=new Uint8Array(16);function $2A(){if(!D2){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");D2=crypto.getRandomValues.bind(crypto)}return D2(X2A)}const AYA=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),v7={randomUUID:AYA};function UBA(e,A,t){var i;if(v7.randomUUID&&!e)return v7.randomUUID();e=e||{};const n=e.random??((i=e.rng)==null?void 0:i.call(e))??$2A();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,V2A(n)}var eYA=/(%?)(%([sdijo]))/g;function tYA(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 V8(e,...A){if(A.length===0)return e;let t=0,i=e.replace(eYA,(n,g,o,s)=>{const r=A[t],a=tYA(r,s);return g?n:(t++,a)});return t<A.length&&(i+=` ${A.slice(t).join(" ")}`),i=i.replace(/%{2,2}/g,"%"),i}var iYA=2;function nYA(e){if(!e.stack)return;const A=e.stack.split(`
`);A.splice(1,iYA),e.stack=A.join(`
`)}var gYA=class extends Error{constructor(e,...A){super(e),this.message=e,this.name="Invariant Violation",this.message=V8(e,...A),nYA(this)}},vBA=(e,A,...t)=>{if(!e)throw new gYA(A,...t)};vBA.as=(e,A,t,...i)=>{if(!A){const n=i.length===0?t:V8(t,...i);let g;try{g=Reflect.construct(e,[n])}catch{g=e(n)}throw g}};const oYA="[MSW]";function X8(e,...A){const t=V8(e,...A);return`${oYA} ${t}`}function sYA(e,...A){console.warn(X8(e,...A))}function rYA(e,...A){console.error(X8(e,...A))}const aYA={formatMessage:X8,warn:sYA,error:rYA};function IYA(){vBA(typeof URL<"u",aYA.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 KBA=(e=>(e.HEAD="HEAD",e.GET="GET",e.POST="POST",e.PUT="PUT",e.PATCH="PATCH",e.OPTIONS="OPTIONS",e.DELETE="DELETE",e))(KBA||{});IYA();class CYA{constructor(A,t,i,n){Tt(this,"initialDelay"),Tt(this,"maxDelay"),Tt(this,"jitterPercent"),Tt(this,"callback"),Tt(this,"currentDelay"),Tt(this,"timeoutId"),Tt(this,"executingCallback",!1),this.initialDelay=A,this.currentDelay=A,this.maxDelay=t,this.jitterPercent=i,this.callback=n}tryFlush(){if(this.backingOff()){Xi.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);Xi.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){Xi.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 FBA(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]=FBA(n):A[i]=n}return A}class cYA{constructor(A){Tt(this,"EVENT_TYPE","web_billing"),Tt(this,"id"),Tt(this,"timestampMs"),Tt(this,"data"),this.id=UBA(),this.timestampMs=Date.now(),this.data=A}toJSON(){return FBA({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 lYA(e,A){const t=new URLSearchParams(window.location.search);return{libraryName:"purchases-js",libraryVersion:fBA,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 BYA=2e3,EYA=5*6e4,QYA=.1;class uYA{constructor(A){Tt(this,"apiKey"),Tt(this,"eventsQueue",[]),Tt(this,"eventsUrl"),Tt(this,"flushManager"),Tt(this,"traceId",UBA()),Tt(this,"appUserId"),Tt(this,"isSilent"),Tt(this,"rcSource"),this.apiKey=A.apiKey,this.eventsUrl=`${u2A}/v1/events`,this.appUserId=A.appUserId,this.isSilent=A.silent||!1,this.rcSource=A.rcSource,this.flushManager=new CYA(BYA,EYA,QYA,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){Xi.verboseLog("Skipping event tracking, the EventsTracker is silent");return}try{const t=new cYA({eventName:A.eventName,traceId:this.traceId,appUserId:this.appUserId,context:lYA(A.source,this.rcSource),properties:A.properties||{}});this.eventsQueue.push(t),this.flushManager.tryFlush()}catch{Xi.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:KBA.POST,headers:RBA(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 Xi.debugLog("Events failed to flush due to server error"),new Error("Events failed to flush due to server error")}).catch(t=>{throw Xi.debugLog("Error while flushing events"),t})}}const dYA=()=>{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},hYA=["app","embedded"],m2={autoCollectUTMAsMetadata:!0,collectAnalyticsEvents:!0};function MP(){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 pYA=St('<p class="svelte-11vxb6p"><strong>Free Trial:</strong> </p>'),fYA=St('<p class="svelte-11vxb6p"><strong>Intro Price:</strong> </p>'),yYA=St('<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 DYA={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 mYA(e,A){Mi(A,!1),Qi(e,DYA);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),r=ri(A,"onFailedPurchase",8),a=ri(A,"onCancel",8);function I(J){J.target===J.currentTarget&&a()()}Ic();var c=yYA(),l=Xe(c),B=Xe(l),Q=Ht(Xe(B),2),h=Xe(Q),d=Xe(h),p=Ht(Xe(d)),y=Ht(d,2),m=Ht(Xe(y)),D=Ht(y,2),S=Ht(Xe(D)),k=Ht(D,2);{var N=J=>{var T=pYA(),v=Ht(Xe(T));Ft(()=>Dn(v,` ${g()??""}`)),Ue(J,T)};$t(k,J=>{g()&&J(N)})}var G=Ht(k,2);{var M=J=>{var T=fYA(),v=Ht(Xe(T));Ft(()=>Dn(v,` ${o()??""}`)),Ue(J,T)};$t(G,J=>{o()&&J(M)})}var w=Ht(Q,2),b=Xe(w),_=Ht(b,2),K=Ht(_,2);Ft(()=>{Dn(p,` ${t()??""}`),Dn(m,` ${i()??""}`),Dn(S,` ${n()??""}`)}),nB("click",b,function(...J){var T;(T=s())==null||T.apply(this,J)}),nB("click",_,function(...J){var T;(T=r())==null||T.apply(this,J)}),nB("click",K,function(...J){var T;(T=a())==null||T.apply(this,J)}),nB("click",c,I),Ue(e,c),Ni()}async function _BA(e,A,t){const i=new Date,n=`test_${i.getTime()}_${MP()}`,g=`test_store_operation_session_${MP()}`,o={storeTransactionId:n,productIdentifier:e.identifier,purchaseDate:i},s=await A.postReceipt(t,e.identifier,n,e.presentedOfferingContext,"purchase");return{customerInfo:hBA(s),redemptionInfo:null,operationSessionId:g,storeTransaction:o}}function SYA(e,A,t){const i=e.rcPackage.webBillingProduct,n=i.productType,g=i.freeTrialPhase,o=i.introPricePhase,s=i.price,r=a=>a?`${a.number} ${a.unit}${a.number>1?"s":""}`:"N/A";return new Promise((a,I)=>{var c;const l=document.createElement("div");document.body.appendChild(l);const B=()=>{Q&&oK(Q),document.body.removeChild(l)};let Q=null;Q=QP(mYA,{target:l,props:{productIdentifier:i.identifier,productType:n,basePrice:s.formattedPrice,freeTrialPeriod:g?r(g.period):void 0,introPriceFormatted:(c=o==null?void 0:o.price)==null?void 0:c.formattedPrice,onValidPurchase:async()=>{B();try{a(await _BA(i,A,t))}catch(h){I(h)}},onFailedPurchase:()=>{B(),I(new fo(fs.ProductNotAvailableForPurchaseError,"Simulated test purchase failure: no real transaction occurred"))},onCancel:()=>{B(),I(new fo(fs.UserCancelledError))}}})})}class wYA{constructor(){Tt(this,"virtualCurrenciesCache",new Map),Tt(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 kYA(e){return{balance:e.balance,name:e.name,code:e.code,serverDescription:e.description??null}}function MYA(e){const A={};for(const[t,i]of Object.entries(e.virtual_currencies))A[t]=kYA(i);return{all:A}}const K7="$RCAnonymousID:";var JBA,aK;JBA=[T2A];const dk=class Oa{constructor(A,t,i=kP,n=m2){$vA(aK,5,this),Tt(this,"_API_KEY"),Tt(this,"_appUserId"),Tt(this,"_brandingInfo",null),Tt(this,"_loadingResourcesPromise",null),Tt(this,"_flags"),Tt(this,"backend"),Tt(this,"purchaseOperationHelper"),Tt(this,"eventsTracker"),Tt(this,"inMemoryCache"),this._API_KEY=A,this._appUserId=t,this._flags={...m2,...n},OF(A)?Xi.debugLog("Initializing Purchases SDK with Web billing sandbox API Key"):uk(A)&&Xi.debugLog("Initializing Purchases SDK with RC Test store API Key."),this.eventsTracker=new uYA({apiKey:this._API_KEY,appUserId:this._appUserId,silent:!this._flags.collectAnalyticsEvents,rcSource:this._flags.rcSource??null}),this.backend=new _2A(this._API_KEY,i),this.inMemoryCache=new wYA,this.purchaseOperationHelper=new GFA(this.backend,this.eventsTracker),this.eventsTracker.trackSDKEvent({eventName:lI.SDKInitialized})}static setLogLevel(A){Xi.setLogLevel(A)}static setPlatformInfo(A){Oa._platformInfo=A}static getPlatformInfo(){return Oa._platformInfo}static getSharedInstance(){if(Oa.isConfigured())return Oa.instance;throw new NFA}static isConfigured(){return Oa.instance!==void 0}static configure(A,t,i,n){Oa.instance!==void 0&&Xi.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 fo(fs.ConfigurationError,"API key must be provided as a string");if(typeof t!="string")throw new fo(fs.ConfigurationError,"App user ID must be provided as a string");g={apiKey:A,appUserId:t,httpConfig:i,flags:n}}return Oa.configureInternal(g),Oa.getSharedInstance()}static configureInternal(A){const{apiKey:t,appUserId:i,httpConfig:n,flags:g}=A,o=n??kP,s=g??m2;Oa.validateConfig(A),Oa.instance=new Oa(t,i,o,s)}static validateConfig(A){var t,i;J2A(A.apiKey,A.flags),G7(A.appUserId),L2A((t=A.httpConfig)==null?void 0:t.proxyURL),x2A((i=A.httpConfig)==null?void 0:i.additionalHeaders)}async preload(){if(this.hasLoadedResources()){Xi.verboseLog("Purchases resources are loaded. Skipping.");return}if(this._loadingResourcesPromise!==null){Xi.verboseLog("Purchases resources are loading. Waiting."),await this._loadingResourcesPromise;return}return this._loadingResourcesPromise=this.fetchAndCacheBrandingInfo().catch(A=>{let t=`${A}`;A instanceof fo&&(t=`${A.message}. ${A.underlyingErrorMessage?`Underlying error: ${A.underlyingErrorMessage}`:""}`),Xi.errorLog(`Error fetching branding info: ${t}`)}).finally(()=>{this._loadingResourcesPromise=null}),this._loadingResourcesPromise}async fetchAndCacheBrandingInfo(){if(uk(this._API_KEY)){Xi.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=`${H2A}`,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 FL({},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})},r=l=>{var B;if(A.onNavigateToUrl){A.onNavigateToUrl(l);return}(B=window.open(l,"_blank"))==null||B.focus()},a=()=>{},I=()=>{if(A.onVisitCustomerCenter){A.onVisitCustomerCenter();return}},c=Z2A(n,o);return new Promise((l,B)=>{QP(tJA,{target:i,props:{paywallData:n.paywall_components,selectedLocale:g,onNavigateToUrlClicked:r,onVisitCustomerCenterClicked:I,onBackClicked:()=>{if(A.onBack){A.onBack();return}i.innerHTML="",Xi.debugLog("Purchase cancelled by user"),B(new fo(fs.UserCancelledError))},onRestorePurchasesClicked:a,onPurchaseClicked:Q=>{s(Q).then(h=>{l(h)}).catch(h=>B(h))},onError:Q=>B(Q),variablesPerPackage:c}})})}async getOfferings(A){o2A(A==null?void 0:A.currency);const t=this._appUserId,i=await this.backend.getOfferings(t),n=(A==null?void 0:A.offeringIdentifier)===GBA.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:q2A(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),Y2A(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:r=wm,skipSuccessPage:a=!1}=A;if(uk(this._API_KEY)){const D=await SYA(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;Xi.debugLog(`Presenting purchase form for package ${i.identifier}`);const B=s||r,Q=n??i.webBillingProduct.defaultPurchaseOption,h=LLA({appearance:(t=this._brandingInfo)==null?void 0:t.appearance,rcPackage:i,purchaseOptionToUse:Q,customerEmail:o});this.eventsTracker.trackSDKEvent(h);const d={...this._flags.autoCollectUTMAsMetadata?dYA():{},...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&&hYA.includes(this._flags.rcSource)?void 0:()=>{const N=TLA();this.eventsTracker.trackSDKEvent(N),window.removeEventListener("popstate",k),p&&oK(p),c.innerHTML="",Xi.debugLog("Purchase cancelled by user"),S(new fo(fs.UserCancelledError))};!m&&k&&window.addEventListener("popstate",k),p=QP(s2A,{target:c,props:{isInElement:m,appUserId:l,rcPackage:i,purchaseOption:Q,customerEmail:o,onFinished:async N=>{const G=xLA({redemptionInfo:N.redemptionInfo});this.eventsTracker.trackSDKEvent(G),this.inMemoryCache.invalidateAllCaches(),Xi.debugLog("Purchase finished"),p&&oK(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=qLA({errorCode:(G=N.errorCode)==null?void 0:G.toString(),errorMessage:N.message});this.eventsTracker.trackSDKEvent(M),p&&oK(p),c.innerHTML="",S(fo.getForPurchasesFlowError(N))},purchases:this,eventsTracker:this.eventsTracker,brandingInfo:this._brandingInfo,purchaseOperationHelper:this.purchaseOperationHelper,selectedLocale:B,metadata:d,defaultLocale:r,customTranslations:A.labelsOverride,skipSuccessPage:a}})})}async _postSimulatedStoreReceipt(A){return await _BA(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 G7(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&&Xi.debugLog(`Could not find product data for product ids:
        ${n.join()}.
        Please check that your product configuration is correct.`)}isSandbox(){return OF(this._API_KEY)||uk(this._API_KEY)}isAnonymous(){return this._appUserId.startsWith(K7)}async getVirtualCurrencies(){return await this._getVirtualCurrenciesForUserId(this._appUserId)}getCachedVirtualCurrencies(){return this.inMemoryCache.getCachedVirtualCurrencies(this._appUserId,!0)}invalidateVirtualCurrenciesCache(){this.inMemoryCache.invalidateVirtualCurrenciesCache(this._appUserId)}close(){Oa.instance===this?(this.eventsTracker&&this.eventsTracker.dispose(),Oa.instance=void 0):Xi.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 hBA(t)}async _getVirtualCurrenciesForUserId(A){const t=this.inMemoryCache.getCachedVirtualCurrencies(A);if(t)return Xi.debugLog("Vending VirtualCurrencies from cache."),t;const i=await this.backend.getVirtualCurrencies(A),n=MYA(i);return Xi.debugLog("VirtualCurrencies updated from the network."),this.inMemoryCache.cacheVirtualCurrencies(A,n),n}static generateRevenueCatAnonymousAppUserId(){return`${K7}${MP().replace(/-/g,"")}`}_trackEvent(A){this.eventsTracker.trackExternalEvent(A)}};aK=WvA(),AKA(aK,1,"purchase",JBA,dk),XvA(aK,dk),Tt(dk,"_platformInfo"),Tt(dk,"instance");let gp=dk;function NYA(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 NP(e){const A=e==="web"?DGA:e==="ios"?SGA:mGA;if(!A)throw new Error(`RevenueCat SDK key missing for ${e}. Add VITE_RC_API_KEY_* and restart.`);return NYA(e,String(A)),String(A)}function LBA(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 NS(e){const A=(e??"").toString();return{length:A.length,empty:A.length===0}}function RP(e){return e?String(e).slice(0,4):null}async function RYA(e){return Zl||op||(op=(async()=>{const A=ti.getPlatform();if(console.debug("[RC] configureOnce platform:",A),A==="web"){const i=NP("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:RP(i),appUserId:NS(e),observerMode:!1}),await gp.configure({apiKey:i,appUserId:e,observerMode:!1}),console.debug("[RC] configure:success",{platform:A});try{PF()}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=NP(A==="ios"?"ios":"android");try{const i=await li(()=>import("./index-DyJW_BMF.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:RP(t),appUserId:NS(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{PF()}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 $8(e){const A=LBA(e),t=await RYA(A);if(sf!==A){try{const i=t.Purchases;typeof(i==null?void 0:i.logIn)=="function"&&(console.debug("[RC] identify:begin",{platform:ti.getPlatform(),appUserId:NS(A)}),t.platform==="native"?await i.logIn({appUserID:A}):await i.logIn(A)),console.debug("[RC] logIn success"),console.debug("[RC] identify:done",{platform:ti.getPlatform()});try{PF()}catch{}}catch(i){console.warn("[RC] logIn failed or unsupported:",i)}sf=A}return t}function ua(){const e=Zl;if(!(e!=null&&e.Purchases)){if(ti.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=ti.getPlatform(),t=e.Purchases;function i(g){const o=Object.create(g);return typeof g.getOfferings=="function"&&(o.getOfferings=async()=>{var a,I,c;const s=A;let r=null;try{r=RP(NP(s==="ios"?"ios":s==="android"?"android":"web"))}catch{}console.debug("[RC] getOfferings:start",{platform:s,appTarget:Fs,keyPrefix:r});try{const l=await g.getOfferings(),B=((a=l==null?void 0:l.current)==null?void 0:a.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:Fs,offeringId:BL,chipsPackageId:EL,chipsProductId:QL,keyPrefix:r,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 PF(){const A={platform:ti.getPlatform(),user:NS(sf),clientReady:!!Zl,hasInitPromise:!!op,appTarget:Fs,offeringId:BL,chipsPackageId:EL,chipsProductId:QL};console.debug("[RC] config:state",A);try{Ma.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,$8(sf)}async function xBA(e){const A=LBA(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:NS(A),previousUser:NS(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 GYA=Object.freeze(Object.defineProperty({__proto__:null,getPurchases:ua,initRevenueCat:$8,logRevenueCatConfig:PF,loginRevenueCat:xBA,reconfigureRevenueCat:Hh},Symbol.toStringTag,{value:"Module"})),kb="rc_anonymous_device_id";async function bYA(){if(ti.isNativePlatform())try{const{SecureStoragePlugin:A}=await li(async()=>{const{SecureStoragePlugin:i}=await Promise.resolve().then(()=>sbA);return{SecureStoragePlugin:i}},void 0);try{const{value:i}=await A.get({key:kb});if(i&&i.length>10)return i}catch{}const t=`anon_${crypto.randomUUID()}`;return await A.set({key:kb,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(kb);if(A&&A.length>10)return A;const t=`anon_${crypto.randomUUID()}`;return localStorage.setItem(kb,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 F7(e){return e.startsWith("anon_")}const Ly={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_TARGET:"craps",VITE_OTA:"1",VITE_OTA_MANIFEST_URL:"https://cdn.dicelounge.app/ota/manifest.json"},_7=BL,UYA=EL,J7=QL,L7=n8,TBA=String(wGA).toLowerCase()==="true",IK={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 S2(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"?IK[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),r=(A==null?void 0:A.underlyingErrorMessage)||(A==null?void 0:A.nativeStack)||(A==null?void 0:A.stack),a=(A==null?void 0:A.message)||String(A);if(console.error(`${e} failed`,{code:g,name:o,backendErrorCode:s,message:a,underlying:r}),TBA){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 qBA=E.createContext({rc:null,ready:!1,error:null,isPremium:!1,anonymousBalance:null,buyChips:async()=>{},buySubscription:async()=>{},restorePurchases:async()=>{}});function vYA({children:e}){const{user:A,refreshUser:t}=en(),[i,n]=E.useState(null),[g,o]=E.useState(!1),[s,r]=E.useState(null),[a,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),r(null);try{const _=(A==null?void 0:A.id)??await bYA(),K=B.current;if(A!=null&&A.id&&K&&F7(K)&&K!==A.id){console.log("[RevenueCat] User logged in, transferring purchases from anonymous ID");try{await xBA(A.id),B.current=A.id;try{const x=(Ly==null?void 0:Ly.VITE_API_URL)||"",{getToken:q}=await li(async()=>{const{getToken:aA}=await Promise.resolve().then(()=>rbA);return{getToken:aA}},void 0),z=await q(),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 $8(_);B.current=_;let T=!1;const v=1e3,U=Date.now();for(;!b;){const q=ua()||(J==null?void 0:J.Purchases);if(q&&(typeof q.purchasePackage=="function"||typeof q.getOfferings=="function")){T=!0;break}if(Date.now()-U>v)break;await new Promise(z=>setTimeout(z,50))}!T&&(J==null?void 0:J.platform)==="web"&&(T=!0),b||(n(J),o(T))}catch(_){b||(r((_==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 _=ua();if(!(_!=null&&_.getCustomerInfo))return;const K=await _.getCustomerInfo(),J=((b=K==null?void 0:K.entitlements)==null?void 0:b.active)||{},T=Object.keys(J).length>0;let v=!1;L7&&(v=!!(J!=null&&J[L7])||T),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||!F7(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&&_[_7]?b.all[_7]:(b==null?void 0:b.current)||((K=b==null?void 0:b.all)==null?void 0:K.default)||null},[]),y=E.useCallback(b=>{var T,v;const _=[],K=U=>{var x;if(Array.isArray(U))for(const q of U){const z=(q==null?void 0:q.identifier)||((x=q==null?void 0:q.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(q))}};K(((T=b==null?void 0:b.current)==null?void 0:T.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,q;K(((x=J[U])==null?void 0:x.availablePackages)||((q=J[U])==null?void 0:q.packages))}),_},[]),m=b=>{var v,U,x,q,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)||""),T=String(((x=b==null?void 0:b.product)==null?void 0:x.title)||((q=b==null?void 0:b.product)==null?void 0:q.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(T)},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);TBA&&(console.debug("[RC] offerings(off):",_),console.debug("[RC] packages:",K)),/\s/.test(String(J7))&&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)===UYA);if(v)return v}{const v=K.find(U=>{var x;return((x=U==null?void 0:U.product)==null?void 0:x.identifier)===J7});if(v)return v}const J=K.find(v=>D(v));if(J)return J;const T=(_==null?void 0:_.availablePackages)||(_==null?void 0:_.packages)||[];return Array.isArray(T)&&T.length>0?T[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}`},T=K.find(z=>(z==null?void 0:z.packageType)==="MONTHLY")||K.find(z=>((z==null?void 0:z.identifier)||"").toLowerCase().includes("month"));if(T)return T;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 q=(_==null?void 0:_.availablePackages)||(_==null?void 0:_.packages)||[];return Array.isArray(q)&&q.length>0?q[0]:K[0]||null},[y,p]),N=E.useCallback(async()=>{var J,T;if(!g)throw new Error("RevenueCat not ready");let b=ua();if(!(b!=null&&b.getOfferings)||!(b!=null&&b.purchasePackage))try{await Hh(),b=ua()}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,q;return{identifier:U==null?void 0:U.identifier,productId:(x=U==null?void 0:U.product)==null?void 0:x.identifier,type:(q=U==null?void 0:U.product)==null?void 0:q.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=ua();if(!(x!=null&&x.purchasePackage))throw v;await x.purchasePackage(K),Q(),d();return}catch{}throw v}}catch(v){S2("[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"?IK[U]||`Code${U}`:"Unknown",q=((T=v==null?void 0:v.extra)==null?void 0:T.backendErrorCode)??(v==null?void 0:v.backendErrorCode),z=q===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}`:""}${q?` | backend ${q}`:""}).${z}`)}},[g,S,y,Q,d]),G=E.useCallback(async()=>{var J,T;if(!g)throw new Error("RevenueCat not ready");let b=ua();if(!(b!=null&&b.getOfferings)||!(b!=null&&b.purchasePackage))try{await Hh(),b=ua()}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=ua();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=ua();if(!(x!=null&&x.purchasePackage))throw v;await x.purchasePackage(K),Q(),h();return}catch{}throw v}}catch(v){S2("[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"?IK[U]||`Code${U}`:"Unknown",q=((T=v==null?void 0:v.extra)==null?void 0:T.backendErrorCode)??(v==null?void 0:v.backendErrorCode),z=q===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}`:""}${q?` | backend ${q}`:""}).${z}`)}},[g,k,Q,h]),M=E.useCallback(async()=>{var _,K,J;if(!g)throw new Error("RevenueCat not ready");let b=ua();if(!(b!=null&&b.getCustomerInfo)||!(b!=null&&b.syncPurchases))try{await Hh(),b=ua()}catch{}try{const T=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(T){S2("[RC] restorePurchases",T);const v=((K=T==null?void 0:T.getErrorCode)==null?void 0:K.call(T))??(T==null?void 0:T.errorCode)??(T==null?void 0:T.code),U=typeof v=="number"?IK[v]||`Code${v}`:"Unknown",x=((J=T==null?void 0:T.extra)==null?void 0:J.backendErrorCode)??(T==null?void 0:T.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:a,anonymousBalance:c,buyChips:N,buySubscription:G,restorePurchases:M}),[i,g,s,a,c,N,G,M]);return C.jsx(qBA.Provider,{value:w,children:e})}function YBA(){return E.useContext(qBA)}function KYA({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 A5="/assets/avatars-BLAbFok_.webp",e5="/assets/avatars2-BhCQ9Hmk.webp",t5="/assets/bikini_avatars-D9_A_byG.webp",i5="/assets/bikini_avatars2-CqEDCn9Y.webp",n5="/assets/car_avatars-C2asmsaV.webp",g5="/assets/cowboy_avatars-Dh4o-H8O.webp",o5="/assets/surf_avatars-BNzNQWcq.webp",s5="/assets/surf_avatars2-CP3KwVoE.webp",r5="/assets/toy_avatars-CYoTJdP7.webp",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-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",OBA="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",PBA="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",jBA="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",zBA="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",ZBA="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",FYA=0,_YA=2500,Vo={diceRevealDelayMs:FYA,diceSettleClientMs:_YA,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},jF=[A5,e5,t5,i5,n5,g5,o5,s5,r5];function JYA(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>=jF.length?null:{sheetIdx:t,tile:i%6}}function LYA(e){let A=0;for(let t=0;t<e.length;t++)A=A*31+e.charCodeAt(t)>>>0;return A%(jF.length*6)}function xYA(e,A){const t=JYA(e);if(t){const{sheetIdx:p,tile:y}=t,m=jF[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=LYA(A),n=Math.floor(i/6),g=i%6,o=jF[n],s=2,r=3,a=g%s,I=Math.floor(g/s),c=s*100,l=n===4?400:r*100,B=c/100,Q=l/100,h=a/(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 TYA={1:HBA,2:OBA,3:PBA,4:jBA,5:zBA,6:ZBA};function WBA(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:TYA[o],alt:`Dice ${o}`,className:"flash-die-face"},s))}),n&&C.jsx("span",{className:"flash-dice-label",children:n})]})}let Mb=null;async function VBA(){if(Mb)return Mb;const e=await li(()=>import("./lottie-C5jvl8NU.js").then(A=>A.l),[]);return Mb=e!=null&&e.default&&e.default.loadAnimation?e.default:e,Mb}let Nb=null,Rb=null;async function GP(e){if(e==="win"&&Nb)return Nb;if(e==="lose"&&Rb)return Rb;if(e==="win"){const A=await li(()=>import("./winning-lottie-CvaS4ZrO.js"),[]);return Nb=A.default||A,Nb}else{const A=await li(()=>import("./lose-lottie-C7Ut5v-G.js"),[]);return Rb=A.default||A,Rb}}const a5=E.createContext(null),qYA={win:void 0,lose:void 0,push:void 0,roll:void 0,info:void 0},YYA=typeof window<"u"&&window.requestIdleCallback||(e=>setTimeout(e,50));function HYA(){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 x7(){YYA(async()=>{try{await VBA(),await Promise.allSettled([GP("win"),GP("lose")])}catch{}})}function T7(){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 OYA(e,A,t,i){return typeof A=="boolean"?A:i?!1:e==="lose"&&typeof t!="number"}function PYA(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 jYA(){try{return document.querySelector(".card.player-panel, .card.craps-player-panel, .card.skills-player-panel")}catch{return null}}function w2(e){return typeof e!="string"?e:/[⚀⚁⚂⚃⚄⚅]/.test(e)?WBA(e):XBA(e)}function XBA(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 zYA(){E.useEffect(()=>{if(x7(),typeof window>"u")return;const e=()=>{x7(),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 ZYA(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 WYA(e){E.useEffect(()=>{let A=!1;const t=async()=>{try{if(!D8())try{await qn()}catch{}const n=e==="win"?["winDing","win"]:e==="lose"?["lose"]:e==="push"?["push"]:[];if(n.length){try{SS(n)}catch{}try{await MF(n,600)}catch{}}if(A)return;e==="lose"?m8({volume:.06}):e==="win"?kvA({volume:.25}):e==="push"&&FcA({volume:.04})}catch{}},i=window.setTimeout(()=>{t()},10);return()=>{A=!0,window.clearTimeout(i)}},[e])}function VYA(e){const{enabled:A,kind:t,targetRef:i,animationData:n,fallbackMap:g,isIOS:o,onComplete:s}=e,r=E.useRef(null);E.useEffect(()=>{if(!A||t!=="win"&&t!=="lose")return;let a=!1;return(async()=>{try{const I=await VBA(),c=n||(t?g[t]:void 0)||await GP(t);if(a||!i.current||!c)return;r.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&&r.current.addEventListener("complete",s)}catch{}})(),()=>{var I,c,l;a=!0;try{s&&r.current&&((c=(I=r.current).removeEventListener)==null||c.call(I,"complete",s)),(l=r.current)==null||l.destroy()}catch{}r.current=null,i.current&&(i.current.innerHTML="")}},[A,t,n,g,o,s,i])}function XYA({item:e,onDone:A,animations:t,zIndex:i}){const n=E.useRef(null),g=E.useRef(null),[o,s]=E.useState("enter"),r=E.useRef(!1),a=E.useCallback(()=>{r.current||(r.current=!0,A(e.id))},[A,e.id]),I=E.useCallback(()=>{s("leave"),window.setTimeout(a,320)},[a]);WYA(e.kind),ZYA(e.id,e.duration,I);const c=E.useMemo(HYA,[]),l=e.kind==="win"||e.kind==="lose";VYA({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:w2(p)})]})})():C.jsx("span",{children:XBA(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"&&a())},onTransitionEnd:h=>{h.target===n.current&&o==="leave"&&a()},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:xYA(S==null?void 0:S.avatarUrl,m)}),C.jsx("strong",{className:"flash-subtitle__name",children:m}),C.jsx("span",{className:"flash-subtitle__result",children:WBA(D)})]},d)}return C.jsx("span",{children:w2(h)},d)}):w2(e.subtitle)}),e.viral&&C.jsx(KYA,{viral:e.viral,onClose:()=>{}})]})]})}function $YA({children:e,baseDurationMs:A=Vo.flash.baseMs}){const[t,i]=E.useState([]),n=E.useRef(new Set),g=E.useRef({...qYA}),o=E.useRef(""),s=E.useRef(0);zYA();const r=E.useCallback(Q=>{i(h=>h.filter(d=>d.id!==Q))},[]),a=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"?T7():{isCraps:!1,isCeeLo:!1},p=d.isCeeLo,y=typeof Q.duration=="number"?Q.duration:p&&(Q.kind==="win"||Q.kind==="lose")?Vo.flash.ceeLoShortMs:Q.kind==="win"?Vo.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:OYA(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{Xl({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)=>(li(()=>import("./InAppReviewService-D9_lw-TM.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:r,clear:a,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,r,a,I,t.length]),B=E.useMemo(()=>{var N;if(typeof document>"u")return null;const Q=T7(),h=jYA(),d=t[0];if(!d)return null;const y=PYA(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 zr.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(XYA,{item:d,onDone:r,animations:g.current,zIndex:2e3}),C.jsx("div",{className:"flash-backdrop"})]},d.id),y)},[t,r]);return E.useEffect(()=>{},[c]),C.jsxs(a5.Provider,{value:l,children:[e,B]})}function Fa(){const e=E.useContext(a5);if(!e)throw new Error("useFlashOverlay must be used within <FlashOverlayProvider>");return e}function LL(){const e=E.useContext(a5);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 q7=BL,AHA=EL,eHA=QL,tHA=GGA,Y7=n8;function kw(){const{user:e,refreshUser:A}=en(),{rc:t,ready:i,error:n,buyChips:g,buySubscription:o,restorePurchases:s}=YBA(),{infoNow:r}=Fa(),[a,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),[T,v]=E.useState(!1),U=ti.getPlatform()==="web",x=gr(),q=!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[q7]?gA.all[q7]:(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=ua(),RA=await((gA=fA==null?void 0:fA.getCustomerInfo)==null?void 0:gA.call(fA));let YA=!1;const W=((yA=RA==null?void 0:RA.entitlements)==null?void 0:yA.active)||{},$=Object.keys(W).length>0;Y7&&(YA=!!(W!=null&&W[Y7])||$),y(YA)}catch{}},[z,q]);E.useEffect(()=>{i&&q&&Z()},[i,q,Z]),E.useEffect(()=>{if(!i||!q)return;let gA=0;const yA=6,fA=setInterval(()=>{gA+=1,Z(),gA>=yA&&clearInterval(fA)},500);return()=>clearInterval(fA)},[i,q,Z]),E.useEffect(()=>{let gA=!1;return(async()=>{var yA,fA,RA,YA;try{if(!i||!q)return;const W=ua(),$=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(lA=>{lA&&L.push(lA)})};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 lA,wA,xA;return(O==null?void 0:O.identifier)||((lA=O==null?void 0:O.product)==null?void 0:lA.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 lA=tA(O);return!!((O==null?void 0:O.packageType)==="MONTHLY"||(O==null?void 0:O.packageType)==="ANNUAL"||lA!=null&&lA.subscriptionPeriod||lA!=null&&lA.period||lA!=null&&lA.defaultSubscriptionOption||lA!=null&&lA.productType&&/subscription/i.test(String(lA.productType)))},oA=O=>{var lA,wA,xA,HA;return(O==null?void 0:O.priceString)||((lA=O==null?void 0:O.price)==null?void 0:lA.formattedPrice)||((wA=O==null?void 0:O.currentPrice)==null?void 0:wA.formattedPrice)||(O==null?void 0:O.price)||((HA=(xA=O==null?void 0:O.defaultPurchaseOption)==null?void 0:xA.basePrice)==null?void 0:HA.formattedPrice)},CA=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(lA=>P(lA)===O):void 0;let uA=_A(AHA)||_A(eHA);if(uA||(uA=L.find(O=>!iA(O))),uA){const O=tA(uA),lA=oA(O),wA=CA(O),xA=cA(O),HA=String(P(uA)||""),zA=PA=>{const VA=PA.match(/\b(\d{1,3}(?:[\,\._\s]\d{3})*|\d{2,})\b/);if(!VA)return null;const KA=VA[1].replace(/[\._\s,]/g,""),Ie=parseInt(KA,10);return Number.isFinite(Ie)?Ie:null},ne=zA(wA)??zA(xA)??zA(HA),ye=ne&&ne>0?ne:void 0,Ee=ye?new Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(ye):void 0,NA=Ee?`z${Ee}`:"Z Credits",QA=lA?`${NA} for ${lA}`:void 0;gA||D(QA),gA||G("Top up your Z Credits to keep playing.")}let X=_A(tHA);if(X||(X=L.find(wA=>(wA==null?void 0:wA.packageType)==="MONTHLY"||/month/i.test(String(P(wA)||""))||/month/i.test(CA(tA(wA))))||L.find(wA=>iA(wA)||/year|annual|week|month/i.test(String(P(wA)||"")))),gA||v(!!X),X){const O=tA(X),lA=oA(O),wA=lA?`${lA} Mo`:void 0;if(gA||k(wA),gA||w("Remove ads and unlock premium features."),gA||_(lA),!gA){let xA="Auto-renewing";const HA=(X==null?void 0:X.packageType)||(O==null?void 0:O.subscriptionPeriod)||(O==null?void 0:O.period)||((YA=O==null?void 0:O.defaultSubscriptionOption)==null?void 0:YA.period),zA=String(HA||"").toUpperCase();zA.includes("MONTH")||zA==="MONTHLY"||zA==="P1M"?xA="Monthly":zA.includes("YEAR")||zA==="ANNUAL"||zA==="P1Y"?xA="Annual":zA.includes("WEEK")||zA==="WEEKLY"||zA==="P1W"?xA="Weekly":(zA.includes("DAY")||zA==="P1D")&&(xA="Daily"),J(xA)}}}catch{}})(),()=>{gA=!0}},[i,q,z]);const eA=async()=>{var gA;if(!a){if(I(!0),l(!0),!i){r("Purchases initializing…","Please try again in a moment."),l(!1),I(!1);return}try{await g(),r("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),YA=typeof RA=="number"?RA===3?"PurchaseNotAllowedError":RA===2?"StoreProblemError":RA===5?"ProductNotAvailableForPurchaseError":void 0:void 0;YA==="PurchaseNotAllowedError"?fA="Purchases not allowed for this Apple ID/device. Use an App Store sandbox account and ensure the Paid Apps Agreement is accepted.":YA==="StoreProblemError"?fA="App Store is currently unavailable. Please try again later or verify sandbox account is signed in to the device.":YA==="ProductNotAvailableForPurchaseError"&&(fA="Product not available. Verify the product identifier matches App Store Connect and RevenueCat configuration for this app target.")}catch{}r("Purchase failed",fA)}finally{l(!1),I(!1)}}},aA=async()=>{if(!a){if(I(!0),Q(!0),!i){try{r("Purchases initializing…","Please try again in a moment.")}catch{}try{await(await li(async()=>{const{reconfigureRevenueCat:gA}=await Promise.resolve().then(()=>GYA);return{reconfigureRevenueCat:gA}},void 0)).reconfigureRevenueCat()}catch{}Q(!1),I(!1);return}try{await o(),await Z(),r("Subscription active","Thanks for supporting.")}finally{Q(!1),I(!1)}}},sA=async()=>{if(!a){if(I(!0),d(!0),!i)throw new Error("Payment service not ready");await s(),await Z();try{const gA=await Co();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{}r("Restored purchases","Your purchases have been restored."),d(!1),I(!1)}},pA=E.useMemo(()=>!i||!q?"Initializing…":p?"Premium Active":"Go Premium",[p,i,q]);return{ready:i,error:n||null,busy:a,busyChips:c,busySubscription:B,premiumActive:p,hasPremiumPackage:T,premiumLabel:pA,purchasesReady:q,isWeb:U,onBuyChips:eA,onGoPremium:aA,onRestore:sA,chipsSubtitle:m,premiumSubtitle:S,chipsDescription:N,premiumDescription:M,premiumPrice:b,premiumInterval:K}}var rM;(function(e){e.Heavy="HEAVY",e.Medium="MEDIUM",e.Light="LIGHT"})(rM||(rM={}));var H7;(function(e){e.Success="SUCCESS",e.Warning="WARNING",e.Error="ERROR"})(H7||(H7={}));const Oh=nl("Haptics",{web:()=>li(()=>import("./web-C6m8J3cy.js"),__vite__mapDeps([11,1])).then(e=>new e.HapticsWeb)}),iHA={Light:rM.Light,Medium:rM.Medium,Heavy:rM.Heavy},nHA={Light:10,Medium:20,Heavy:35};async function yo(e="Light"){var A;try{await Oh.impact({style:iHA[e]});return}catch{}try{(A=navigator.vibrate)==null||A.call(navigator,nHA[e])}catch{}}function Xt(e="Light"){yo(e)}async function $BA(){try{if(Oh!=null&&Oh.selectionStart){await Oh.selectionStart(),await Oh.selectionChanged(),await Oh.selectionEnd();return}}catch{}await yo("Light")}const bP=Object.freeze(Object.defineProperty({__proto__:null,hapticClick:Xt,hapticImpact:yo,hapticSelection:$BA},Symbol.toStringTag,{value:"Module"}));function I5({isPremium:e,className:A}){const[t,i]=E.useState(!1),{onGoPremium:n,busy:g,ready:o}=kw();if(!e)return null;const s=async()=>{try{i(!0);try{Xt("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 AEA({open:e,onClose:A,featureDescription:t}){const{user:i}=en(),{onGoPremium:n,onRestore:g,busy:o,premiumActive:s,hasPremiumPackage:r,premiumLabel:a,error:I,ready:c,premiumPrice:l,premiumInterval:B}=kw(),Q=Ji(),{infoNow:h}=Fa(),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&&r&&C.jsx("button",{className:"gold-btn felt-btn",onClick:d,disabled:o,children:p?o?"Processing…":a:"Sign in to Upgrade"}),s&&C.jsx("div",{style:{marginTop:12},children:C.jsx(I5,{isPremium:!0})}),!s&&r&&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(qI,{to:"/privacy",className:"legal-link",children:"Privacy Policy"})," and ",C.jsx(qI,{to:"/terms",className:"legal-link",children:"Terms of Use"}),"."]}),I&&C.jsx("p",{className:"error",role:"alert",children:I}),!s&&r&&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,O7=0;const gHA=3e4;function oHA(){const{user:e}=en(),[A,t]=E.useState(xy),[i,n]=E.useState(!1),[g,o]=E.useState(!1),s=gr(),r=E.useCallback(async(I=!1)=>{if(e){if(!I&&xy&&Date.now()-O7<gHA){t(xy);return}n(!0);try{const c=await Co(),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,O7=Date.now(),t(xy))}catch{}finally{n(!1)}}},[e,s]),a=E.useCallback(async()=>{if(!e||g)return null;o(!0);try{const I=await Co(),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 r(!0),l.data):null}catch{return null}finally{o(!1)}},[e,g,s,r]);return E.useEffect(()=>{e&&r()},[e,r]),{data:A,loading:i,claiming:g,refresh:r,claim:a}}function Ud({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."})]})]})]}),r=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."})]})]})]}),a=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"?r:t==="zentara"?I:a]})]})}function sHA({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(Ud,{defaultMode:t})]})}):null}let Ty=null,P7=0;const rHA=6e4;let D0=null;function eEA(){const{user:e}=en(),[A,t]=E.useState(Ty),[i,n]=E.useState(!1),[g,o]=E.useState(null),s=gr(),r=E.useCallback(async(a=!1)=>{if(e){if(!a&&Ty&&Date.now()-P7<rHA){t(Ty);return}if(D0){await D0,t(Ty);return}n(!0),o(null),D0=(async()=>{try{const I=await Co(),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,P7=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),D0=null}})(),await D0}},[e]);return E.useEffect(()=>{e&&r()},[e,r]),{data:A,loading:i,error:g,refresh:r}}const aHA={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 IHA({open:e,onClose:A}){var a;const[t]=dw(),i=t.get("e2e")==="1",{data:n,loading:g,error:o,refresh:s}=eEA(),r=E.useMemo(()=>i?aHA: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}),r&&C.jsxs("div",{className:"leaderboard-sections",children:[((a=r.skillsStreaks)==null?void 0:a.length)>0&&C.jsxs("section",{children:[C.jsx("h4",{children:"🔥 Skills Win Streaks"}),C.jsx("ol",{className:"lb-list",children:r.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:r.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:r.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:r.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))})]}),r.zentaraAllTime&&r.zentaraAllTime.length>0&&C.jsxs("section",{children:[C.jsx("h4",{children:"🪐 Zentara · Top Conquerors"}),C.jsx("ol",{className:"lb-list",children:r.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))})]}),r.zentaraWeekly&&r.zentaraWeekly.length>0&&C.jsxs("section",{children:[C.jsx("h4",{children:"🛰️ Zentara · This Week"}),C.jsx("ol",{className:"lb-list",children:r.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))})]}),r.zentaraBiggestWin&&r.zentaraBiggestWin.length>0&&C.jsxs("section",{children:[C.jsx("h4",{children:"💥 Zentara · Biggest Victories"}),C.jsx("ol",{className:"lb-list",children:r.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))})]}),r.zentaraTopEmpires&&r.zentaraTopEmpires.length>0&&C.jsxs("section",{children:[C.jsx("h4",{children:"👑 Zentara · Empire Dominance"}),C.jsx("ol",{className:"lb-list",children:r.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 CHA({open:e,onClose:A,onGoLogin:t,title:i,message:n}){const g=E.useRef(null),o=Ji();if(E.useEffect(()=>{if(!e)return;const r=I=>{I.key==="Escape"&&A()},a=I=>{g.current&&!g.current.contains(I.target)&&A()};return document.addEventListener("keydown",r),document.addEventListener("mousedown",a),()=>{document.removeEventListener("keydown",r),document.removeEventListener("mousedown",a)}},[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 xl=nl("CapacitorUpdater",{web:()=>li(()=>import("./web-CnmRTYxn.js"),__vite__mapDeps([12,1])).then(e=>new e.CapacitorUpdaterWeb)});var UP={exports:{}};const cHA="2.0.0",tEA=256,lHA=Number.MAX_SAFE_INTEGER||9007199254740991,BHA=16,EHA=tEA-6,QHA=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var xL={MAX_LENGTH:tEA,MAX_SAFE_COMPONENT_LENGTH:BHA,MAX_SAFE_BUILD_LENGTH:EHA,MAX_SAFE_INTEGER:lHA,RELEASE_TYPES:QHA,SEMVER_SPEC_VERSION:cHA,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},k2={};const uHA=typeof process=="object"&&k2&&k2.NODE_DEBUG&&/\bsemver\b/i.test(k2.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};var TL=uHA;(function(e,A){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:i,MAX_LENGTH:n}=xL,g=TL;A=e.exports={};const o=A.re=[],s=A.safeRe=[],r=A.src=[],a=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,r[D]=p,a[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",`(${r[I.NUMERICIDENTIFIER]})\\.(${r[I.NUMERICIDENTIFIER]})\\.(${r[I.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${r[I.NUMERICIDENTIFIERLOOSE]})\\.(${r[I.NUMERICIDENTIFIERLOOSE]})\\.(${r[I.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${r[I.NONNUMERICIDENTIFIER]}|${r[I.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${r[I.NONNUMERICIDENTIFIER]}|${r[I.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${r[I.PRERELEASEIDENTIFIER]}(?:\\.${r[I.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${r[I.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${r[I.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${l}+`),h("BUILD",`(?:\\+(${r[I.BUILDIDENTIFIER]}(?:\\.${r[I.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${r[I.MAINVERSION]}${r[I.PRERELEASE]}?${r[I.BUILD]}?`),h("FULL",`^${r[I.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${r[I.MAINVERSIONLOOSE]}${r[I.PRERELEASELOOSE]}?${r[I.BUILD]}?`),h("LOOSE",`^${r[I.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${r[I.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${r[I.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${r[I.XRANGEIDENTIFIER]})(?:\\.(${r[I.XRANGEIDENTIFIER]})(?:\\.(${r[I.XRANGEIDENTIFIER]})(?:${r[I.PRERELEASE]})?${r[I.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${r[I.XRANGEIDENTIFIERLOOSE]})(?:\\.(${r[I.XRANGEIDENTIFIERLOOSE]})(?:\\.(${r[I.XRANGEIDENTIFIERLOOSE]})(?:${r[I.PRERELEASELOOSE]})?${r[I.BUILD]}?)?)?`),h("XRANGE",`^${r[I.GTLT]}\\s*${r[I.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${r[I.GTLT]}\\s*${r[I.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),h("COERCE",`${r[I.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",r[I.COERCEPLAIN]+`(?:${r[I.PRERELEASE]})?(?:${r[I.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",r[I.COERCE],!0),h("COERCERTLFULL",r[I.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${r[I.LONETILDE]}\\s+`,!0),A.tildeTrimReplace="$1~",h("TILDE",`^${r[I.LONETILDE]}${r[I.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${r[I.LONETILDE]}${r[I.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${r[I.LONECARET]}\\s+`,!0),A.caretTrimReplace="$1^",h("CARET",`^${r[I.LONECARET]}${r[I.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${r[I.LONECARET]}${r[I.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${r[I.GTLT]}\\s*(${r[I.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${r[I.GTLT]}\\s*(${r[I.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${r[I.GTLT]}\\s*(${r[I.LOOSEPLAIN]}|${r[I.XRANGEPLAIN]})`,!0),A.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${r[I.XRANGEPLAIN]})\\s+-\\s+(${r[I.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${r[I.XRANGEPLAINLOOSE]})\\s+-\\s+(${r[I.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(UP,UP.exports);var YR=UP.exports;const dHA=Object.freeze({loose:!0}),hHA=Object.freeze({}),pHA=e=>e?typeof e!="object"?dHA:e:hHA;var C5=pHA;const j7=/^[0-9]+$/,iEA=(e,A)=>{const t=j7.test(e),i=j7.test(A);return t&&i&&(e=+e,A=+A),e===A?0:t&&!i?-1:i&&!t?1:e<A?-1:1},fHA=(e,A)=>iEA(A,e);var nEA={compareIdentifiers:iEA,rcompareIdentifiers:fHA};const Gb=TL,{MAX_LENGTH:z7,MAX_SAFE_INTEGER:bb}=xL,{safeRe:Ub,t:vb}=YR,yHA=C5,{compareIdentifiers:qy}=nEA;let DHA=class _l{constructor(A,t){if(t=yHA(t),A instanceof _l){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>z7)throw new TypeError(`version is longer than ${z7} characters`);Gb("SemVer",A,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const i=A.trim().match(t.loose?Ub[vb.LOOSE]:Ub[vb.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>bb||this.major<0)throw new TypeError("Invalid major version");if(this.minor>bb||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>bb||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<bb)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(Gb("SemVer.compare",this.version,this.options,A),!(A instanceof _l)){if(typeof A=="string"&&A===this.version)return 0;A=new _l(A,this.options)}return A.version===this.version?0:this.compareMain(A)||this.comparePre(A)}compareMain(A){return A instanceof _l||(A=new _l(A,this.options)),qy(this.major,A.major)||qy(this.minor,A.minor)||qy(this.patch,A.patch)}comparePre(A){if(A instanceof _l||(A=new _l(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(Gb("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 _l||(A=new _l(A,this.options));let t=0;do{const i=this.build[t],n=A.build[t];if(Gb("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?Ub[vb.PRERELEASELOOSE]:Ub[vb.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 _a=DHA;const Z7=_a,mHA=(e,A,t=!1)=>{if(e instanceof Z7)return e;try{return new Z7(e,A)}catch(i){if(!t)return null;throw i}};var Mw=mHA;const SHA=Mw,wHA=(e,A)=>{const t=SHA(e,A);return t?t.version:null};var kHA=wHA;const MHA=Mw,NHA=(e,A)=>{const t=MHA(e.trim().replace(/^[=v]+/,""),A);return t?t.version:null};var RHA=NHA;const W7=_a,GHA=(e,A,t,i,n)=>{typeof t=="string"&&(n=i,i=t,t=void 0);try{return new W7(e instanceof W7?e.version:e,t).inc(A,i,n).version}catch{return null}};var bHA=GHA;const V7=Mw,UHA=(e,A)=>{const t=V7(e,null,!0),i=V7(A,null,!0),n=t.compare(i);if(n===0)return null;const g=n>0,o=g?t:i,s=g?i:t,r=!!o.prerelease.length;if(!!s.prerelease.length&&!r){if(!s.patch&&!s.minor)return"major";if(s.compareMain(o)===0)return s.minor&&!s.patch?"minor":"patch"}const I=r?"pre":"";return t.major!==i.major?I+"major":t.minor!==i.minor?I+"minor":t.patch!==i.patch?I+"patch":"prerelease"};var vHA=UHA;const KHA=_a,FHA=(e,A)=>new KHA(e,A).major;var _HA=FHA;const JHA=_a,LHA=(e,A)=>new JHA(e,A).minor;var xHA=LHA;const THA=_a,qHA=(e,A)=>new THA(e,A).patch;var YHA=qHA;const HHA=Mw,OHA=(e,A)=>{const t=HHA(e,A);return t&&t.prerelease.length?t.prerelease:null};var PHA=OHA;const X7=_a,jHA=(e,A,t)=>new X7(e,t).compare(new X7(A,t));var sl=jHA;const zHA=sl,ZHA=(e,A,t)=>zHA(A,e,t);var WHA=ZHA;const VHA=sl,XHA=(e,A)=>VHA(e,A,!0);var $HA=XHA;const $7=_a,AOA=(e,A,t)=>{const i=new $7(e,t),n=new $7(A,t);return i.compare(n)||i.compareBuild(n)};var c5=AOA;const eOA=c5,tOA=(e,A)=>e.sort((t,i)=>eOA(t,i,A));var iOA=tOA;const nOA=c5,gOA=(e,A)=>e.sort((t,i)=>nOA(i,t,A));var oOA=gOA;const sOA=sl,rOA=(e,A,t)=>sOA(e,A,t)>0;var qL=rOA;const aOA=sl,IOA=(e,A,t)=>aOA(e,A,t)<0;var l5=IOA;const COA=sl,cOA=(e,A,t)=>COA(e,A,t)===0;var gEA=cOA;const lOA=sl,BOA=(e,A,t)=>lOA(e,A,t)!==0;var oEA=BOA;const EOA=sl,QOA=(e,A,t)=>EOA(e,A,t)>=0;var B5=QOA;const uOA=sl,dOA=(e,A,t)=>uOA(e,A,t)<=0;var E5=dOA;const hOA=gEA,pOA=oEA,fOA=qL,yOA=B5,DOA=l5,mOA=E5,SOA=(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 hOA(e,t,i);case"!=":return pOA(e,t,i);case">":return fOA(e,t,i);case">=":return yOA(e,t,i);case"<":return DOA(e,t,i);case"<=":return mOA(e,t,i);default:throw new TypeError(`Invalid operator: ${A}`)}};var sEA=SOA;const wOA=_a,kOA=Mw,{safeRe:Kb,t:Fb}=YR,MOA=(e,A)=>{if(e instanceof wOA)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?Kb[Fb.COERCEFULL]:Kb[Fb.COERCE]);else{const r=A.includePrerelease?Kb[Fb.COERCERTLFULL]:Kb[Fb.COERCERTL];let a;for(;(a=r.exec(e))&&(!t||t.index+t[0].length!==e.length);)(!t||a.index+a[0].length!==t.index+t[0].length)&&(t=a),r.lastIndex=a.index+a[1].length+a[2].length;r.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 kOA(`${i}.${n}.${g}${o}${s}`,A)};var NOA=MOA;class ROA{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 GOA=ROA,M2,A$;function rl(){if(A$)return M2;A$=1;const e=/\s+/g;class A{constructor(T,v){if(v=n(v),T instanceof A)return T.loose===!!v.loose&&T.includePrerelease===!!v.includePrerelease?T:new A(T.raw,v);if(T instanceof g)return this.raw=T.value,this.set=[[T]],this.formatted=void 0,this;if(this.options=v,this.loose=!!v.loose,this.includePrerelease=!!v.includePrerelease,this.raw=T.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 T=0;T<this.set.length;T++){T>0&&(this.formatted+="||");const v=this.set[T];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(T){const U=((this.options.includePrerelease&&B)|(this.options.loose&&Q))+":"+T,x=i.get(U);if(x)return x;const q=this.options.loose,z=q?r[a.HYPHENRANGELOOSE]:r[a.HYPHENRANGE];T=T.replace(z,_(this.options.includePrerelease)),o("hyphen replace",T),T=T.replace(r[a.COMPARATORTRIM],I),o("comparator trim",T),T=T.replace(r[a.TILDETRIM],c),o("tilde trim",T),T=T.replace(r[a.CARETTRIM],l),o("caret trim",T);let Z=T.split(" ").map(pA=>y(pA,this.options)).join(" ").split(/\s+/).map(pA=>b(pA,this.options));q&&(Z=Z.filter(pA=>(o("loose invalid filter",pA,this.options),!!pA.match(r[a.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(T,v){if(!(T instanceof A))throw new TypeError("a Range is required");return this.set.some(U=>p(U,v)&&T.set.some(x=>p(x,v)&&U.every(q=>x.every(z=>q.intersects(z,v)))))}test(T){if(!T)return!1;if(typeof T=="string")try{T=new s(T,this.options)}catch{return!1}for(let v=0;v<this.set.length;v++)if(K(this.set[v],T,this.options))return!0;return!1}}M2=A;const t=GOA,i=new t,n=C5,g=YL(),o=TL,s=_a,{safeRe:r,t:a,comparatorTrimReplace:I,tildeTrimReplace:c,caretTrimReplace:l}=YR,{FLAG_INCLUDE_PRERELEASE:B,FLAG_LOOSE:Q}=xL,h=J=>J.value==="<0.0.0-0",d=J=>J.value==="",p=(J,T)=>{let v=!0;const U=J.slice();let x=U.pop();for(;v&&U.length;)v=U.every(q=>x.intersects(q,T)),x=U.pop();return v},y=(J,T)=>(o("comp",J,T),J=k(J,T),o("caret",J),J=D(J,T),o("tildes",J),J=G(J,T),o("xrange",J),J=w(J,T),o("stars",J),J),m=J=>!J||J.toLowerCase()==="x"||J==="*",D=(J,T)=>J.trim().split(/\s+/).map(v=>S(v,T)).join(" "),S=(J,T)=>{const v=T.loose?r[a.TILDELOOSE]:r[a.TILDE];return J.replace(v,(U,x,q,z,Z)=>{o("tilde",J,U,x,q,z,Z);let eA;return m(x)?eA="":m(q)?eA=`>=${x}.0.0 <${+x+1}.0.0-0`:m(z)?eA=`>=${x}.${q}.0 <${x}.${+q+1}.0-0`:Z?(o("replaceTilde pr",Z),eA=`>=${x}.${q}.${z}-${Z} <${x}.${+q+1}.0-0`):eA=`>=${x}.${q}.${z} <${x}.${+q+1}.0-0`,o("tilde return",eA),eA})},k=(J,T)=>J.trim().split(/\s+/).map(v=>N(v,T)).join(" "),N=(J,T)=>{o("caret",J,T);const v=T.loose?r[a.CARETLOOSE]:r[a.CARET],U=T.includePrerelease?"-0":"";return J.replace(v,(x,q,z,Z,eA)=>{o("caret",J,x,q,z,Z,eA);let aA;return m(q)?aA="":m(z)?aA=`>=${q}.0.0${U} <${+q+1}.0.0-0`:m(Z)?q==="0"?aA=`>=${q}.${z}.0${U} <${q}.${+z+1}.0-0`:aA=`>=${q}.${z}.0${U} <${+q+1}.0.0-0`:eA?(o("replaceCaret pr",eA),q==="0"?z==="0"?aA=`>=${q}.${z}.${Z}-${eA} <${q}.${z}.${+Z+1}-0`:aA=`>=${q}.${z}.${Z}-${eA} <${q}.${+z+1}.0-0`:aA=`>=${q}.${z}.${Z}-${eA} <${+q+1}.0.0-0`):(o("no pr"),q==="0"?z==="0"?aA=`>=${q}.${z}.${Z}${U} <${q}.${z}.${+Z+1}-0`:aA=`>=${q}.${z}.${Z}${U} <${q}.${+z+1}.0-0`:aA=`>=${q}.${z}.${Z} <${+q+1}.0.0-0`),o("caret return",aA),aA})},G=(J,T)=>(o("replaceXRanges",J,T),J.split(/\s+/).map(v=>M(v,T)).join(" ")),M=(J,T)=>{J=J.trim();const v=T.loose?r[a.XRANGELOOSE]:r[a.XRANGE];return J.replace(v,(U,x,q,z,Z,eA)=>{o("xRange",J,U,x,q,z,Z,eA);const aA=m(q),sA=aA||m(z),pA=sA||m(Z),gA=pA;return x==="="&&gA&&(x=""),eA=T.includePrerelease?"-0":"",aA?x===">"||x==="<"?U="<0.0.0-0":U="*":x&&gA?(sA&&(z=0),Z=0,x===">"?(x=">=",sA?(q=+q+1,z=0,Z=0):(z=+z+1,Z=0)):x==="<="&&(x="<",sA?q=+q+1:z=+z+1),x==="<"&&(eA="-0"),U=`${x+q}.${z}.${Z}${eA}`):sA?U=`>=${q}.0.0${eA} <${+q+1}.0.0-0`:pA&&(U=`>=${q}.${z}.0${eA} <${q}.${+z+1}.0-0`),o("xRange return",U),U})},w=(J,T)=>(o("replaceStars",J,T),J.trim().replace(r[a.STAR],"")),b=(J,T)=>(o("replaceGTE0",J,T),J.trim().replace(r[T.includePrerelease?a.GTE0PRE:a.GTE0],"")),_=J=>(T,v,U,x,q,z,Z,eA,aA,sA,pA,gA)=>(m(U)?v="":m(x)?v=`>=${U}.0.0${J?"-0":""}`:m(q)?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,T,v)=>{for(let U=0;U<J.length;U++)if(!J[U].test(T))return!1;if(T.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===T.major&&x.minor===T.minor&&x.patch===T.patch)return!0}return!1}return!0};return M2}var N2,e$;function YL(){if(e$)return N2;e$=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 r(I.value,c).test(this.value):I.operator===""?I.value===""?!0:new r(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(">")))}}N2=A;const t=C5,{safeRe:i,t:n}=YR,g=sEA,o=TL,s=_a,r=rl();return N2}const bOA=rl(),UOA=(e,A,t)=>{try{A=new bOA(A,t)}catch{return!1}return A.test(e)};var HL=UOA;const vOA=rl(),KOA=(e,A)=>new vOA(e,A).set.map(t=>t.map(i=>i.value).join(" ").trim().split(" "));var FOA=KOA;const _OA=_a,JOA=rl(),LOA=(e,A,t)=>{let i=null,n=null,g=null;try{g=new JOA(A,t)}catch{return null}return e.forEach(o=>{g.test(o)&&(!i||n.compare(o)===-1)&&(i=o,n=new _OA(i,t))}),i};var xOA=LOA;const TOA=_a,qOA=rl(),YOA=(e,A,t)=>{let i=null,n=null,g=null;try{g=new qOA(A,t)}catch{return null}return e.forEach(o=>{g.test(o)&&(!i||n.compare(o)===1)&&(i=o,n=new TOA(i,t))}),i};var HOA=YOA;const R2=_a,OOA=rl(),t$=qL,POA=(e,A)=>{e=new OOA(e,A);let t=new R2("0.0.0");if(e.test(t)||(t=new R2("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 R2(o.semver.version);switch(o.operator){case">":s.prerelease.length===0?s.patch++:s.prerelease.push(0),s.raw=s.format();case"":case">=":(!g||t$(s,g))&&(g=s);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),g&&(!t||t$(t,g))&&(t=g)}return t&&e.test(t)?t:null};var jOA=POA;const zOA=rl(),ZOA=(e,A)=>{try{return new zOA(e,A).range||"*"}catch{return null}};var WOA=ZOA;const VOA=_a,rEA=YL(),{ANY:XOA}=rEA,$OA=rl(),A1A=HL,i$=qL,n$=l5,e1A=E5,t1A=B5,i1A=(e,A,t,i)=>{e=new VOA(e,i),A=new $OA(A,i);let n,g,o,s,r;switch(t){case">":n=i$,g=e1A,o=n$,s=">",r=">=";break;case"<":n=n$,g=t1A,o=i$,s="<",r="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(A1A(e,A,i))return!1;for(let a=0;a<A.set.length;++a){const I=A.set[a];let c=null,l=null;if(I.forEach(B=>{B.semver===XOA&&(B=new rEA(">=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===r||(!l.operator||l.operator===s)&&g(e,l.semver))return!1;if(l.operator===r&&o(e,l.semver))return!1}return!0};var Q5=i1A;const n1A=Q5,g1A=(e,A,t)=>n1A(e,A,">",t);var o1A=g1A;const s1A=Q5,r1A=(e,A,t)=>s1A(e,A,"<",t);var a1A=r1A;const g$=rl(),I1A=(e,A,t)=>(e=new g$(e,t),A=new g$(A,t),e.intersects(A,t));var C1A=I1A;const c1A=HL,l1A=sl;var B1A=(e,A,t)=>{const i=[];let n=null,g=null;const o=e.sort((I,c)=>l1A(I,c,t));for(const I of o)c1A(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 r=s.join(" || "),a=typeof A.raw=="string"?A.raw:String(A);return r.length<a.length?r:A};const o$=rl(),u5=YL(),{ANY:G2}=u5,m0=HL,d5=sl,E1A=(e,A,t={})=>{if(e===A)return!0;e=new o$(e,t),A=new o$(A,t);let i=!1;A:for(const n of e.set){for(const g of A.set){const o=u1A(n,g,t);if(i=i||o!==null,o)continue A}if(i)return!1}return!0},Q1A=[new u5(">=0.0.0-0")],s$=[new u5(">=0.0.0")],u1A=(e,A,t)=>{if(e===A)return!0;if(e.length===1&&e[0].semver===G2){if(A.length===1&&A[0].semver===G2)return!0;t.includePrerelease?e=Q1A:e=s$}if(A.length===1&&A[0].semver===G2){if(t.includePrerelease)return!0;A=s$}const i=new Set;let n,g;for(const B of e)B.operator===">"||B.operator===">="?n=r$(n,B,t):B.operator==="<"||B.operator==="<="?g=a$(g,B,t):i.add(B.semver);if(i.size>1)return null;let o;if(n&&g){if(o=d5(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&&!m0(B,String(n),t)||g&&!m0(B,String(g),t))return null;for(const Q of A)if(!m0(B,String(Q),t))return!1;return!0}let s,r,a,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===">=",a=a||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=r$(n,B,t),s===B&&s!==n)return!1}else if(n.operator===">="&&!m0(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(r=a$(g,B,t),r===B&&r!==g)return!1}else if(g.operator==="<="&&!m0(g.semver,String(B),t))return!1}if(!B.operator&&(g||n)&&o!==0)return!1}return!(n&&a&&!g&&o!==0||g&&I&&!n&&o!==0||l||c)},r$=(e,A,t)=>{if(!e)return A;const i=d5(e.semver,A.semver,t);return i>0?e:i<0||A.operator===">"&&e.operator===">="?A:e},a$=(e,A,t)=>{if(!e)return A;const i=d5(e.semver,A.semver,t);return i<0?e:i>0||A.operator==="<"&&e.operator==="<="?A:e};var d1A=E1A;const b2=YR,I$=xL,h1A=_a,C$=nEA,p1A=Mw,f1A=kHA,y1A=RHA,D1A=bHA,m1A=vHA,S1A=_HA,w1A=xHA,k1A=YHA,M1A=PHA,N1A=sl,R1A=WHA,G1A=$HA,b1A=c5,U1A=iOA,v1A=oOA,K1A=qL,F1A=l5,_1A=gEA,J1A=oEA,L1A=B5,x1A=E5,T1A=sEA,q1A=NOA,Y1A=YL(),H1A=rl(),O1A=HL,P1A=FOA,j1A=xOA,z1A=HOA,Z1A=jOA,W1A=WOA,V1A=Q5,X1A=o1A,$1A=a1A,APA=C1A,ePA=B1A,tPA=d1A;var iPA={parse:p1A,valid:f1A,clean:y1A,inc:D1A,diff:m1A,major:S1A,minor:w1A,patch:k1A,prerelease:M1A,compare:N1A,rcompare:R1A,compareLoose:G1A,compareBuild:b1A,sort:U1A,rsort:v1A,gt:K1A,lt:F1A,eq:_1A,neq:J1A,gte:L1A,lte:x1A,cmp:T1A,coerce:q1A,Comparator:Y1A,Range:H1A,satisfies:O1A,toComparators:P1A,maxSatisfying:j1A,minSatisfying:z1A,minVersion:Z1A,validRange:W1A,outside:V1A,gtr:X1A,ltr:$1A,intersects:APA,simplifyRange:ePA,subset:tPA,SemVer:h1A,re:b2.re,src:b2.src,tokens:b2.t,SEMVER_SPEC_VERSION:I$.SEMVER_SPEC_VERSION,RELEASE_TYPES:I$.RELEASE_TYPES,compareIdentifiers:C$.compareIdentifiers,rcompareIdentifiers:C$.rcompareIdentifiers};const Yy=gw(iPA),U2={},zF="https://updates.dicelounge.app";function nPA(){const A=String("craps").trim().toLowerCase();let t=A==="craps"||A==="ceelo"||A==="poker"||A==="skills"||A==="zentara"?`${zF}/${A}/manifest.json`:`${zF}/manifest.json`;t=t.replace(/manifest\.jjson$/i,"manifest.json");try{an("OTA_MANIFEST_URL_RESOLVE",{target:A,url:t})}catch{}return t}function Tl(){return Date.now()}function S0(){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 an(e,A){console.log(`[OTA] ${e}`,A)}function c$(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 gPA(e){try{const A=new URL(e);return`${A.protocol}//${A.host}`===zF}catch{return!1}}async function oPA(e){if(!gPA(e))throw new Error("Manifest origin not allowed");const A=Tl(),t=await fetch(e,{cache:"no-store",redirect:"error"});if(!t.ok)throw new Error(`HTTP ${t.status}`);const i=await t.json();return an("OTA_CHECK_FETCH",{ms:Tl()-A}),i}async function sPA(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 l$=globalThis.OTA_PUBLIC_KEY_B64||(U2==null?void 0:U2.VITE_OTA_PUBKEY)||JGA,v2=!0,rPA=50*1024*1024,aPA=/^(\d{12,14}|v?\d+\.\d+\.\d+(?:[-+].+)?)$/;async function IPA(){try{let e=Uint8Array.from(atob(l$),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{an("OTA_KEY_IMPORT_FAIL",{len:e.length})}catch{}return{legacyRaw:e}}}catch(e){try{an("OTA_KEY_PARSE_FAIL",{error:e==null?void 0:e.message})}catch{}return null}}const CPA=IPA();async function cPA(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 CPA;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{an("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 lPA{constructor(){Ti(this,"nativeVersion",null);Ti(this,"activeWebVersion",null);Ti(this,"pendingUpdateVersion",null);Ti(this,"previousWebVersion",null);Ti(this,"lastAppliedSha256",null)}async init(){var g;if(!S0()){an("OTA_INIT_SKIP_WEB",{});return}const A=Tl(),t=await Ma.getInfo();this.nativeVersion=t.version;const i=await nr.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 xl.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&&(an("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()),an("OTA_INIT",{ms:Tl()-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&&S0())try{i=(await Ma.getInfo()).version||null,this.nativeVersion=i,an("OTA_NATIVE_VERSION_SYNC",{nativeVersion:i})}catch(n){an("OTA_NATIVE_VERSION_SYNC_FAIL",{error:n==null?void 0:n.message})}i=i||"0.0.0";try{const n=nPA(),g=await oPA(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{an("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(v2&&!o.sig)return an("OTA_CHECK",{reason:"INVALID_MANIFEST",note:"sig_missing_but_required"}),{available:!1,reason:"INVALID_MANIFEST",nativeVersion:i,currentWebVersion:this.activeWebVersion};if(!aPA.test(o.webVersion))return an("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 an("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 an("OTA_CHECK",{reason:"INVALID_MANIFEST",note:"sha256_format"}),{available:!1,reason:"INVALID_MANIFEST",nativeVersion:i,currentWebVersion:this.activeWebVersion};const s=c$(i),r=c$(o.minNativeVersion),a=Yy.coerce(r)||"0.0.0",I=Yy.coerce(s)||"0.0.0",c=Yy.gte(I,a);if(an("OTA_VERSION_CHECK",{rawNative:i,normalizedNative:s,rawMin:o.minNativeVersion,normalizedMin:r,nativeOk:c}),!c)return an("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 an("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&&(an("OTA_CHECK_FORCE_CLEAR_PENDING",{pendingUpdateVersion:this.pendingUpdateVersion}),this.pendingUpdateVersion=null,await this.writePersist());const l=this.activeWebVersion;if(l&&l===o.webVersion)return an("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 an("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 an("OTA_CHECK",{nativeVersion:i,fromWebVersion:l,toWebVersion:d.webVersion,reason:"OK"}),{available:!0,reason:"OK",release:d,nativeVersion:i,currentWebVersion:l}}catch(n){return an("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(!S0())throw new Error("OTA only applies on native platforms");const i=Tl();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(),r=[];let a=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(r.push(p),a+=p.byteLength,a>rPA)throw new Error("SIZE_LIMIT");I>0&&(t==null||t({stage:"downloading",bytes:a,total:I,percent:Math.round(a/I*100)}))}}const c=new Blob(r,{type:"application/zip"});t==null||t({stage:"verifying"});const l=await sPA(c);if(l.toLowerCase()!==A.sha256.toLowerCase())throw an("OTA_VERIFY_FAIL",{expected:A.sha256,got:l}),new Error("SHA256_MISMATCH");try{const d=new URL(A.url);if(`${d.protocol}//${d.host}`!==zF)throw new Error("ORIGIN_MISMATCH")}catch{throw new Error("ORIGIN_MISMATCH")}const B=!!A.sig;if(!await cPA(A.sig,A)){const d=B?"SIG_INVALID":"SIG_MISSING";if(an("OTA_VERIFY_FAIL",{reason:d,require:v2}),d==="SIG_MISSING"&&v2)try{an("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 an("OTA_VERIFY_OK",{ms:Tl()-i,size:a}),{blob:c}}async clearCaches(){try{if("caches"in window){const A=await caches.keys();await Promise.all(A.map(t=>caches.delete(t))),an("OTA_CACHE_CLEAR",{type:"caches",count:A.length})}}catch(A){an("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())),an("OTA_CACHE_CLEAR",{type:"serviceWorker",count:A.length})}}catch(A){an("OTA_CACHE_CLEAR_FAIL",{type:"serviceWorker",error:String(A)})}}async applyUpdate(A,t){if(!S0())throw new Error("OTA only applies on native platforms");const i=Tl();an("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{an("OTA_APPLY_DOWNLOAD_START",{url:A.url,version:A.webVersion});const g=xl.download({url:A.url,version:A.webVersion}),o=new Promise((r,a)=>setTimeout(()=>a(new Error("OTA_APPLY_TIMEOUT")),n)),s=await Promise.race([g,o]);an("OTA_APPLY_DOWNLOAD_DONE",{bundleId:s.id}),await xl.set({id:s.id}),an("OTA_APPLY",{ms:Tl()-i,fromWebVersion:this.previousWebVersion,toWebVersion:A.webVersion})}catch(g){throw an("OTA_APPLY_ERROR",{error:(g==null?void 0:g.message)||String(g),url:A.url}),g}}async healthCheck(){if(!S0())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 xl.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 an("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=Tl(),i=window;for(;Tl()-t<A;){if(i.__APP_MOUNTED__)return!0;await new Promise(n=>setTimeout(n,100))}return!1}async rollbackIfBootFails(){try{await this.clearCaches(),await xl.reset(),this.pendingUpdateVersion=null,this.activeWebVersion=this.previousWebVersion??null,await this.writePersist(),an("OTA_ROLLBACK",{toWebVersion:this.activeWebVersion}),location.reload()}catch(A){an("OTA_ROLLBACK_FAIL",{error:A==null?void 0:A.message})}}async cleanupOldBundles(){var A;try{const t=await xl.list(),i=await xl.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 xl.delete({id:g.id}),an("OTA_BUNDLE_CLEANUP",{deletedId:g.id})}catch{}}catch(t){an("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 nr.set({key:"ota_state",value:JSON.stringify(A)})}}const fa=new lPA,B$="ota:lastCheckAt",BPA=18e4;function EPA(){try{const e=globalThis.__E2E_OTA_COOLDOWN_MS;if(typeof e=="number"&&e>=0)return e}catch{}return BPA}function QPA(){const[e,A]=E.useState(fa.getVersions()),[t,i]=E.useState(!1),[n,g]=E.useState(null),[o,s]=E.useState({stage:"idle"}),r=E.useRef(null);E.useEffect(()=>{A(fa.getVersions())},[]);const a=E.useCallback(async()=>{i(!0);try{try{const B=Date.now(),Q=await zc.get(B$),h=Q?Number(Q):0;if(h&&B-h<EPA()){i(!1);return}}catch{}const l=await fa.checkForUpdate();if(l.available&&l.release){g(l),r.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 fa.downloadUpdate(l.release,h=>s(h));s({stage:"applying"}),await fa.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),r.current=null):g(l);try{await zc.set(B$,String(Date.now()))}catch{}}finally{i(!1)}},[]),I=E.useCallback(async()=>{const l=r.current;if(!l)return;s({stage:"downloading",percent:0});const{blob:B}=await fa.downloadUpdate(l,Q=>s(Q));s({stage:"applying"}),await fa.applyUpdate(l,B)},[]),c=E.useCallback(()=>{s({stage:"idle"})},[]);return E.useEffect(()=>{a()},[a]),{current:e,checking:t,available:n,progress:o,applyNow:I,later:c}}function uPA({available:e,progress:A,applyNow:t,later:i}){if(!ti.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 dPA({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 fa.checkForUpdate();if(s.available&&s.release){try{const a=window;if(a.__OTA_AUTO_APPLY_RUNNING__)return;a.__OTA_AUTO_APPLY_RUNNING__=!0}catch{}const{blob:r}=await fa.downloadUpdate(s.release,a=>{});await fa.applyUpdate(s.release,r),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 Ma.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 hPA=gr(),pPA={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."},fPA="Join me on Dice Lounge — we both get 1,000 chips when you sign up.";async function yPA(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 aEA({className:e,style:A,label:t,gameMode:i}){const[n,g]=E.useState(!1),[o,s]=E.useState(null),r=E.useCallback(async()=>{if(!n){g(!0),s(null);try{const a=await Co(),c=await(await fetch(`${hPA}/api/referral/link`,{method:"GET",credentials:"include",headers:a?{Authorization:`Bearer ${a}`}: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&&pPA[i]||fPA,Q=await yPA(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:r,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 DPA(){const e=E.useRef(0),A=5e3;return E.useEffect(()=>{if(ti.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 Co();if(!s)return;const r=String(VM??"https://dicelounge.app").replace(/\/+$/,"");await fetch(`${r}/api/push/clear-badge`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch{}}}(async()=>{try{const g=await Ma.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 mPA="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(qI,{to:"/disclaimer",className:"lp-footer__link",children:"Disclaimer (18+)"}),C.jsx("span",{className:"lp-dot","aria-hidden":!0,children:"•"}),C.jsx(qI,{to:"/privacy",className:"lp-footer__link",children:"Privacy Policy"}),C.jsx("span",{className:"lp-dot","aria-hidden":!0,children:"•"}),C.jsx(qI,{to:"/terms",className:"lp-footer__link",children:"Terms of Use"}),C.jsx("span",{className:"lp-dot","aria-hidden":!0,children:"•"}),C.jsx(qI,{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 vP="/assets/logo-Bd_WWMIU.webp",SPA="/assets/ceelo-icon-DBUGq3gk.webp",wPA="/assets/craps-icon-Cxbu5IDi.webp",kPA="/assets/poker-icon-D9lS6jix.webp",MPA="/assets/skills-icon-BWMGnrDl.webp",NPA="/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 KP(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 RPA(e){if(Array.isArray(e))return e}function GPA(e){if(Array.isArray(e))return KP(e)}function bPA(e,A){if(!(e instanceof A))throw new TypeError("Cannot call a class as a function")}function UPA(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,IEA(i.key),i)}}function vPA(e,A,t){return A&&UPA(e.prototype,A),Object.defineProperty(e,"prototype",{writable:!1}),e}function CK(e,A){var t=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!t){if(Array.isArray(e)||(t=h5(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(r){throw r},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 r=t.next();return o=r.done,r},e:function(r){s=!0,g=r},f:function(){try{o||t.return==null||t.return()}finally{if(s)throw g}}}}function Yn(e,A,t){return(A=IEA(A))in e?Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[A]=t,e}function KPA(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function FPA(e,A){var t=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(t!=null){var i,n,g,o,s=[],r=!0,a=!1;try{if(g=(t=t.call(e)).next,A===0){if(Object(t)!==t)return;r=!1}else for(;!(r=(i=g.call(t)).done)&&(s.push(i.value),s.length!==A);r=!0);}catch(I){a=!0,n=I}finally{try{if(!r&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(a)throw n}}return s}}function _PA(){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 JPA(){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 E$(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 wt(e){for(var A=1;A<arguments.length;A++){var t=arguments[A]!=null?arguments[A]:{};A%2?E$(Object(t),!0).forEach(function(i){Yn(e,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):E$(Object(t)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(t,i))})}return e}function OL(e,A){return RPA(e)||FPA(e,A)||h5(e,A)||_PA()}function Xc(e){return GPA(e)||KPA(e)||h5(e)||JPA()}function LPA(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 IEA(e){var A=LPA(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 h5(e,A){if(e){if(typeof e=="string")return KP(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)?KP(e,A):void 0}}var Q$=function(){},p5={},CEA={},cEA=null,lEA={mark:Q$,measure:Q$};try{typeof window<"u"&&(p5=window),typeof document<"u"&&(CEA=document),typeof MutationObserver<"u"&&(cEA=MutationObserver),typeof performance<"u"&&(lEA=performance)}catch{}var xPA=p5.navigator||{},u$=xPA.userAgent,d$=u$===void 0?"":u$,rd=p5,$g=CEA,h$=cEA,_b=lEA;rd.document;var lQ=!!$g.documentElement&&!!$g.head&&typeof $g.addEventListener=="function"&&typeof $g.createElement=="function",BEA=~d$.indexOf("MSIE")||~d$.indexOf("Trident/"),K2,TPA=/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)?[\-\ ]/,qPA=/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,EEA={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"}},YPA={GROUP:"duotone-group",PRIMARY:"primary",SECONDARY:"secondary"},QEA=["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"],$r="classic",HR="duotone",uEA="sharp",dEA="sharp-duotone",hEA="chisel",pEA="etch",fEA="jelly",yEA="jelly-duo",DEA="jelly-fill",mEA="notdog",SEA="notdog-duo",wEA="slab",kEA="slab-press",MEA="thumbprint",NEA="whiteboard",HPA="Classic",OPA="Duotone",PPA="Sharp",jPA="Sharp Duotone",zPA="Chisel",ZPA="Etch",WPA="Jelly",VPA="Jelly Duo",XPA="Jelly Fill",$PA="Notdog",A3A="Notdog Duo",e3A="Slab",t3A="Slab Press",i3A="Thumbprint",n3A="Whiteboard",REA=[$r,HR,uEA,dEA,hEA,pEA,fEA,yEA,DEA,mEA,SEA,wEA,kEA,MEA,NEA];K2={},Yn(Yn(Yn(Yn(Yn(Yn(Yn(Yn(Yn(Yn(K2,$r,HPA),HR,OPA),uEA,PPA),dEA,jPA),hEA,zPA),pEA,ZPA),fEA,WPA),yEA,VPA),DEA,XPA),mEA,$PA),Yn(Yn(Yn(Yn(Yn(K2,SEA,A3A),wEA,e3A),kEA,t3A),MEA,i3A),NEA,n3A);var g3A={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"}},o3A={"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"}},s3A=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}]]),r3A={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"}},GEA=["fak","fa-kit","fakd","fa-kit-duotone"],p$={kit:{fak:"kit","fa-kit":"kit"},"kit-duotone":{fakd:"kit-duotone","fa-kit-duotone":"kit-duotone"}},a3A=["kit"],I3A="kit",C3A="kit-duotone",c3A="Kit",l3A="Kit Duotone";Yn(Yn({},I3A,c3A),C3A,l3A);var B3A={kit:{"fa-kit":"fak"}},E3A={"Font Awesome Kit":{400:"fak",normal:"fak"},"Font Awesome Kit Duotone":{400:"fakd",normal:"fakd"}},Q3A={kit:{fak:"fa-kit"}},f$={kit:{kit:"fak"},"kit-duotone":{"kit-duotone":"fakd"}},F2,Jb={GROUP:"duotone-group",SWAP_OPACITY:"swap-opacity",PRIMARY:"primary",SECONDARY:"secondary"},u3A=["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"],d3A="classic",h3A="duotone",p3A="sharp",f3A="sharp-duotone",y3A="chisel",D3A="etch",m3A="jelly",S3A="jelly-duo",w3A="jelly-fill",k3A="notdog",M3A="notdog-duo",N3A="slab",R3A="slab-press",G3A="thumbprint",b3A="whiteboard",U3A="Classic",v3A="Duotone",K3A="Sharp",F3A="Sharp Duotone",_3A="Chisel",J3A="Etch",L3A="Jelly",x3A="Jelly Duo",T3A="Jelly Fill",q3A="Notdog",Y3A="Notdog Duo",H3A="Slab",O3A="Slab Press",P3A="Thumbprint",j3A="Whiteboard";F2={},Yn(Yn(Yn(Yn(Yn(Yn(Yn(Yn(Yn(Yn(F2,d3A,U3A),h3A,v3A),p3A,K3A),f3A,F3A),y3A,_3A),D3A,J3A),m3A,L3A),S3A,x3A),w3A,T3A),k3A,q3A),Yn(Yn(Yn(Yn(Yn(F2,M3A,Y3A),N3A,H3A),R3A,O3A),G3A,P3A),b3A,j3A);var z3A="kit",Z3A="kit-duotone",W3A="Kit",V3A="Kit Duotone";Yn(Yn({},z3A,W3A),Z3A,V3A);var X3A={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"}},$3A={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"]},FP={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"}},A4A=["fa-solid","fa-regular","fa-light","fa-thin","fa-duotone","fa-brands","fa-semibold"],bEA=["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(u3A,A4A),e4A=["solid","regular","light","thin","duotone","brands","semibold"],UEA=[1,2,3,4,5,6,7,8,9,10],t4A=UEA.concat([11,12,13,14,15,16,17,18,19,20]),i4A=["aw","fw","pull-left","pull-right"],n4A=[].concat(Xc(Object.keys($3A)),e4A,i4A,["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",Jb.GROUP,Jb.SWAP_OPACITY,Jb.PRIMARY,Jb.SECONDARY]).concat(UEA.map(function(e){return"".concat(e,"x")})).concat(t4A.map(function(e){return"w-".concat(e)})),g4A={"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"}},XE="___FONT_AWESOME___",_P=16,vEA="fa",KEA="svg-inline--fa",rf="data-fa-i2svg",JP="data-fa-pseudo-element",o4A="data-fa-pseudo-element-pending",f5="data-prefix",y5="data-icon",y$="fontawesome-i2svg",s4A="async",r4A=["HTML","HEAD","STYLE","SCRIPT"],FEA=["::before","::after",":before",":after"],_EA=function(){try{return!0}catch{return!1}}();function OR(e){return new Proxy(e,{get:function(t,i){return i in t?t[i]:t[$r]}})}var JEA=wt({},EEA);JEA[$r]=wt(wt(wt(wt({},{"fa-duotone":"duotone"}),EEA[$r]),p$.kit),p$["kit-duotone"]);var a4A=OR(JEA),LP=wt({},r3A);LP[$r]=wt(wt(wt(wt({},{duotone:"fad"}),LP[$r]),f$.kit),f$["kit-duotone"]);var D$=OR(LP),xP=wt({},FP);xP[$r]=wt(wt({},xP[$r]),Q3A.kit);var LEA=OR(xP),TP=wt({},X3A);TP[$r]=wt(wt({},TP[$r]),B3A.kit);OR(TP);var I4A=TPA,xEA="fa-layers-text",C4A=qPA,c4A=wt({},g3A);OR(c4A);var l4A=["class","data-prefix","data-icon","data-fa-transform","data-fa-mask"],_2=YPA,B4A=[].concat(Xc(a3A),Xc(n4A)),aM=rd.FontAwesomeConfig||{};function E4A(e){var A=$g.querySelector("script["+e+"]");if(A)return A.getAttribute(e)}function Q4A(e){return e===""?!0:e==="false"?!1:e==="true"?!0:e}if($g&&typeof $g.querySelector=="function"){var u4A=[["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"]];u4A.forEach(function(e){var A=OL(e,2),t=A[0],i=A[1],n=Q4A(E4A(t));n!=null&&(aM[i]=n)})}var TEA={styleDefault:"solid",familyDefault:$r,cssPrefix:vEA,replacementClass:KEA,autoReplaceSvg:!0,autoAddCss:!0,searchPseudoElements:!1,searchPseudoElementsWarnings:!0,searchPseudoElementsFullScan:!1,observeMutations:!0,mutateApproach:"async",keepOriginalSource:!0,measurePerformance:!1,showMissingIcons:!0};aM.familyPrefix&&(aM.cssPrefix=aM.familyPrefix);var RS=wt(wt({},TEA),aM);RS.autoReplaceSvg||(RS.observeMutations=!1);var Ei={};Object.keys(TEA).forEach(function(e){Object.defineProperty(Ei,e,{enumerable:!0,set:function(t){RS[e]=t,IM.forEach(function(i){return i(Ei)})},get:function(){return RS[e]}})});Object.defineProperty(Ei,"familyPrefix",{enumerable:!0,set:function(A){RS.cssPrefix=A,IM.forEach(function(t){return t(Ei)})},get:function(){return RS.cssPrefix}});rd.FontAwesomeConfig=Ei;var IM=[];function d4A(e){return IM.push(e),function(){IM.splice(IM.indexOf(e),1)}}var Hy=_P,gB={size:16,x:0,y:0,rotate:0,flipX:!1,flipY:!1};function h4A(e){if(!(!e||!lQ)){var A=$g.createElement("style");A.setAttribute("type","text/css"),A.innerHTML=e;for(var t=$g.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 $g.head.insertBefore(A,i),e}}var p4A="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";function m$(){for(var e=12,A="";e-- >0;)A+=p4A[Math.random()*62|0];return A}function Nw(e){for(var A=[],t=(e||[]).length>>>0;t--;)A[t]=e[t];return A}function D5(e){return e.classList?Nw(e.classList):(e.getAttribute("class")||"").split(" ").filter(function(A){return A})}function qEA(e){return"".concat(e).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function f4A(e){return Object.keys(e||{}).reduce(function(A,t){return A+"".concat(t,'="').concat(qEA(e[t]),'" ')},"").trim()}function PL(e){return Object.keys(e||{}).reduce(function(A,t){return A+"".concat(t,": ").concat(e[t].trim(),";")},"")}function m5(e){return e.size!==gB.size||e.x!==gB.x||e.y!==gB.y||e.rotate!==gB.rotate||e.flipX||e.flipY}function y4A(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)"),r={transform:"".concat(g," ").concat(o," ").concat(s)},a={transform:"translate(".concat(i/2*-1," -256)")};return{outer:n,inner:r,path:a}}function D4A(e){var A=e.transform,t=e.width,i=t===void 0?_P:t,n=e.height,g=n===void 0?_P:n,o="";return BEA?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 m4A=`: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 YEA(){var e=vEA,A=KEA,t=Ei.cssPrefix,i=Ei.replacementClass,n=m4A;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 S$=!1;function J2(){Ei.autoAddCss&&!S$&&(h4A(YEA()),S$=!0)}var S4A={mixout:function(){return{dom:{css:YEA,insertCss:J2}}},hooks:function(){return{beforeDOMElementCreation:function(){J2()},beforeI2svg:function(){J2()}}}},$E=rd||{};$E[XE]||($E[XE]={});$E[XE].styles||($E[XE].styles={});$E[XE].hooks||($E[XE].hooks={});$E[XE].shims||($E[XE].shims=[]);var Hc=$E[XE],HEA=[],OEA=function(){$g.removeEventListener("DOMContentLoaded",OEA),WF=1,HEA.map(function(A){return A()})},WF=!1;lQ&&(WF=($g.documentElement.doScroll?/^loaded|^c/:/^loaded|^i|^c/).test($g.readyState),WF||$g.addEventListener("DOMContentLoaded",OEA));function w4A(e){lQ&&(WF?setTimeout(e,0):HEA.push(e))}function PR(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"?qEA(e):"<".concat(A," ").concat(f4A(i),">").concat(g.map(PR).join(""),"</").concat(A,">")}function w$(e,A,t){if(e&&e[A]&&e[A][t])return{prefix:A,iconName:t,icon:e[A][t]}}var L2=function(A,t,i,n){var g=Object.keys(A),o=g.length,s=t,r,a,I;for(i===void 0?(r=1,I=A[g[0]]):(r=0,I=i);r<o;r++)a=g[r],I=s(I,A[a],a,A);return I};function PEA(e){return Xc(e).length!==1?null:e.codePointAt(0).toString(16)}function k$(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 jEA(e,A){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=t.skipHooks,n=i===void 0?!1:i,g=k$(A);typeof Hc.hooks.addPack=="function"&&!n?Hc.hooks.addPack(e,k$(A)):Hc.styles[e]=wt(wt({},Hc.styles[e]||{}),g),e==="fas"&&jEA("fa",A)}var cN=Hc.styles,k4A=Hc.shims,zEA=Object.keys(LEA),M4A=zEA.reduce(function(e,A){return e[A]=Object.keys(LEA[A]),e},{}),S5=null,ZEA={},WEA={},VEA={},XEA={},$EA={};function N4A(e){return~B4A.indexOf(e)}function R4A(e,A){var t=A.split("-"),i=t[0],n=t.slice(1).join("-");return i===e&&n!==""&&!N4A(n)?n:null}var AQA=function(){var A=function(g){return L2(cN,function(o,s,r){return o[r]=L2(s,g,{}),o},{})};ZEA=A(function(n,g,o){if(g[3]&&(n[g[3]]=o),g[2]){var s=g[2].filter(function(r){return typeof r=="number"});s.forEach(function(r){n[r.toString(16)]=o})}return n}),WEA=A(function(n,g,o){if(n[o]=o,g[2]){var s=g[2].filter(function(r){return typeof r=="string"});s.forEach(function(r){n[r]=o})}return n}),$EA=A(function(n,g,o){var s=g[2];return n[o]=o,s.forEach(function(r){n[r]=o}),n});var t="far"in cN||Ei.autoFetchSvg,i=L2(k4A,function(n,g){var o=g[0],s=g[1],r=g[2];return s==="far"&&!t&&(s="fas"),typeof o=="string"&&(n.names[o]={prefix:s,iconName:r}),typeof o=="number"&&(n.unicodes[o.toString(16)]={prefix:s,iconName:r}),n},{names:{},unicodes:{}});VEA=i.names,XEA=i.unicodes,S5=jL(Ei.styleDefault,{family:Ei.familyDefault})};d4A(function(e){S5=jL(e.styleDefault,{family:Ei.familyDefault})});AQA();function w5(e,A){return(ZEA[e]||{})[A]}function G4A(e,A){return(WEA[e]||{})[A]}function Ip(e,A){return($EA[e]||{})[A]}function eQA(e){return VEA[e]||{prefix:null,iconName:null}}function b4A(e){var A=XEA[e],t=w5("fas",e);return A||(t?{prefix:"fas",iconName:t}:null)||{prefix:null,iconName:null}}function ad(){return S5}var tQA=function(){return{prefix:null,iconName:null,rest:[]}};function U4A(e){var A=$r,t=zEA.reduce(function(i,n){return i[n]="".concat(Ei.cssPrefix,"-").concat(n),i},{});return REA.forEach(function(i){(e.includes(t[i])||e.some(function(n){return M4A[i].includes(n)}))&&(A=i)}),A}function jL(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t=A.family,i=t===void 0?$r:t,n=a4A[i][e];if(i===HR&&!e)return"fad";var g=D$[i][e]||D$[i][n],o=e in Hc.styles?e:null,s=g||o||null;return s}function v4A(e){var A=[],t=null;return e.forEach(function(i){var n=R4A(Ei.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 N$=bEA.concat(GEA);function zL(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 N$.includes(B)})),o=M$(e.filter(function(B){return!N$.includes(B)})),s=g.filter(function(B){return n=B,!QEA.includes(B)}),r=OL(s,1),a=r[0],I=a===void 0?null:a,c=U4A(g),l=wt(wt({},v4A(o)),{},{prefix:jL(I,{family:c})});return wt(wt(wt({},l),J4A({values:e,family:c,styles:cN,config:Ei,canonical:l,givenPrefix:n})),K4A(i,n,l))}function K4A(e,A,t){var i=t.prefix,n=t.iconName;if(e||!i||!n)return{prefix:i,iconName:n};var g=A==="fa"?eQA(n):{},o=Ip(i,n);return n=g.iconName||o||n,i=g.prefix||i,i==="far"&&!cN.far&&cN.fas&&!Ei.autoFetchSvg&&(i="fas"),{prefix:i,iconName:n}}var F4A=REA.filter(function(e){return e!==$r||e!==HR}),_4A=Object.keys(FP).filter(function(e){return e!==$r}).map(function(e){return Object.keys(FP[e])}).flat();function J4A(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,r=e.config,a=r===void 0?{}:r,I=t===HR,c=A.includes("fa-duotone")||A.includes("fad"),l=a.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&&F4A.includes(t)){var Q=Object.keys(s).find(function(d){return _4A.includes(d)});if(Q||a.autoFetchSvg){var h=s3A.get(t).defaultShortPrefixId;i.prefix=h,i.iconName=Ip(i.prefix,i.iconName)||i.iconName}}return(i.prefix==="fa"||g==="fa")&&(i.prefix=ad()||"fas"),i}var L4A=function(){function e(){bPA(this,e),this.definitions={}}return vPA(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]=wt(wt({},t.definitions[s]||{}),o[s]),jEA(s,o[s]),AQA()})}},{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,r=o.iconName,a=o.icon,I=a[2];t[s]||(t[s]={}),I.length>0&&I.forEach(function(c){typeof c=="string"&&(t[s][c]=a)}),t[s][r]=a}),t}}])}(),R$=[],VD={},km={},x4A=Object.keys(km);function T4A(e,A){var t=A.mixoutsTo;return R$=e,VD={},Object.keys(km).forEach(function(i){x4A.indexOf(i)===-1&&delete km[i]}),R$.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 qP(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 af(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 YP(e){e.prefix==="fa"&&(e.prefix="fas");var A=e.iconName,t=e.prefix||ad();if(A)return A=Ip(t,A)||A,w$(iQA.definitions,t,A)||w$(Hc.styles,t,A)}var iQA=new L4A,q4A=function(){Ei.autoReplaceSvg=!1,Ei.observeMutations=!1,af("noAuto")},Y4A={i2svg:function(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return lQ?(af("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;Ei.autoReplaceSvg===!1&&(Ei.autoReplaceSvg=!0),Ei.observeMutations=!0,w4A(function(){O4A({autoReplaceSvgRoot:t}),af("watch",A)})}},H4A={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=jL(A[0]);return{prefix:i,iconName:Ip(i,t)||t}}if(typeof A=="string"&&(A.indexOf("".concat(Ei.cssPrefix,"-"))>-1||A.match(I4A))){var n=zL(A.split(" "),{skipLookups:!0});return{prefix:n.prefix||ad(),iconName:Ip(n.prefix,n.iconName)||n.iconName}}if(typeof A=="string"){var g=ad();return{prefix:g,iconName:Ip(g,A)||A}}}},iC={noAuto:q4A,config:Ei,dom:Y4A,parse:H4A,library:iQA,findIconDefinition:YP,toHtml:PR},O4A=function(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=A.autoReplaceSvgRoot,i=t===void 0?$g:t;(Object.keys(Hc.styles).length>0||Ei.autoFetchSvg)&&lQ&&Ei.autoReplaceSvg&&iC.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 PR(i)})}}),Object.defineProperty(e,"node",{get:function(){if(lQ){var i=$g.createElement("div");return i.innerHTML=e.html,i.children}}}),e}function P4A(e){var A=e.children,t=e.main,i=e.mask,n=e.attributes,g=e.styles,o=e.transform;if(m5(o)&&t.found&&!i.found){var s=t.width,r=t.height,a={x:s/r/2,y:.5};n.style=PL(wt(wt({},g),{},{"transform-origin":"".concat(a.x+o.x/16,"em ").concat(a.y+o.y/16,"em")}))}return[{tag:"svg",attributes:n,children:A}]}function j4A(e){var A=e.prefix,t=e.iconName,i=e.children,n=e.attributes,g=e.symbol,o=g===!0?"".concat(A,"-").concat(Ei.cssPrefix,"-").concat(t):g;return[{tag:"svg",attributes:{style:"display: none;"},children:[{tag:"symbol",attributes:wt(wt({},n),{},{id:o}),children:i}]}]}function z4A(e){var A=["aria-label","aria-labelledby","title","role"];return A.some(function(t){return t in e})}function k5(e){var A=e.icons,t=A.main,i=A.mask,n=e.prefix,g=e.iconName,o=e.transform,s=e.symbol,r=e.maskId,a=e.extra,I=e.watchable,c=I===void 0?!1:I,l=i.found?i:t,B=l.width,Q=l.height,h=[Ei.replacementClass,g?"".concat(Ei.cssPrefix,"-").concat(g):""].filter(function(S){return a.classes.indexOf(S)===-1}).filter(function(S){return S!==""||!!S}).concat(a.classes).join(" "),d={children:[],attributes:wt(wt({},a.attributes),{},{"data-prefix":n,"data-icon":g,class:h,role:a.attributes.role||"img",viewBox:"0 0 ".concat(B," ").concat(Q)})};!z4A(a.attributes)&&!a.attributes["aria-hidden"]&&(d.attributes["aria-hidden"]="true"),c&&(d.attributes[rf]="");var p=wt(wt({},d),{},{prefix:n,iconName:g,main:t,mask:i,maskId:r,transform:o,symbol:s,styles:wt({},a.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?j4A(p):P4A(p)}function G$(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,r=wt(wt({},g.attributes),{},{class:g.classes.join(" ")});s&&(r[rf]="");var a=wt({},g.styles);m5(n)&&(a.transform=D4A({transform:n,width:t,height:i}),a["-webkit-transform"]=a.transform);var I=PL(a);I.length>0&&(r.style=I);var c=[];return c.push({tag:"span",attributes:r,children:[A]}),c}function Z4A(e){var A=e.content,t=e.extra,i=wt(wt({},t.attributes),{},{class:t.classes.join(" ")}),n=PL(t.styles);n.length>0&&(i.style=n);var g=[];return g.push({tag:"span",attributes:i,children:[A]}),g}var x2=Hc.styles;function HP(e){var A=e[0],t=e[1],i=e.slice(4),n=OL(i,1),g=n[0],o=null;return Array.isArray(g)?o={tag:"g",attributes:{class:"".concat(Ei.cssPrefix,"-").concat(_2.GROUP)},children:[{tag:"path",attributes:{class:"".concat(Ei.cssPrefix,"-").concat(_2.SECONDARY),fill:"currentColor",d:g[0]}},{tag:"path",attributes:{class:"".concat(Ei.cssPrefix,"-").concat(_2.PRIMARY),fill:"currentColor",d:g[1]}}]}:o={tag:"path",attributes:{fill:"currentColor",d:g}},{found:!0,width:A,height:t,icon:o}}var W4A={found:!1,width:512,height:512};function V4A(e,A){!_EA&&!Ei.showMissingIcons&&e&&console.error('Icon with name "'.concat(e,'" and prefix "').concat(A,'" is missing.'))}function OP(e,A){var t=A;return A==="fa"&&Ei.styleDefault!==null&&(A=ad()),new Promise(function(i,n){if(t==="fa"){var g=eQA(e)||{};e=g.iconName||e,A=g.prefix||A}if(e&&A&&x2[A]&&x2[A][e]){var o=x2[A][e];return i(HP(o))}V4A(e,A),i(wt(wt({},W4A),{},{icon:Ei.showMissingIcons&&e?Id("missingIconAbstract")||{}:{}}))})}var b$=function(){},PP=Ei.measurePerformance&&_b&&_b.mark&&_b.measure?_b:{mark:b$,measure:b$},hk='FA "7.0.0"',X4A=function(A){return PP.mark("".concat(hk," ").concat(A," begins")),function(){return nQA(A)}},nQA=function(A){PP.mark("".concat(hk," ").concat(A," ends")),PP.measure("".concat(hk," ").concat(A),"".concat(hk," ").concat(A," begins"),"".concat(hk," ").concat(A," ends"))},M5={begin:X4A,end:nQA},cK=function(){};function U$(e){var A=e.getAttribute?e.getAttribute(rf):null;return typeof A=="string"}function $4A(e){var A=e.getAttribute?e.getAttribute(f5):null,t=e.getAttribute?e.getAttribute(y5):null;return A&&t}function AjA(e){return e&&e.classList&&e.classList.contains&&e.classList.contains(Ei.replacementClass)}function ejA(){if(Ei.autoReplaceSvg===!0)return lK.replace;var e=lK[Ei.autoReplaceSvg];return e||lK.replace}function tjA(e){return $g.createElementNS("http://www.w3.org/2000/svg",e)}function ijA(e){return $g.createElement(e)}function gQA(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t=A.ceFn,i=t===void 0?e.tag==="svg"?tjA:ijA:t;if(typeof e=="string")return $g.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(gQA(o,{ceFn:i}))}),n}function njA(e){var A=" ".concat(e.outerHTML," ");return A="".concat(A,"Font Awesome fontawesome.com "),A}var lK={replace:function(A){var t=A[0];if(t.parentNode)if(A[1].forEach(function(n){t.parentNode.insertBefore(gQA(n),t)}),t.getAttribute(rf)===null&&Ei.keepOriginalSource){var i=$g.createComment(njA(t));t.parentNode.replaceChild(i,t)}else t.remove()},nest:function(A){var t=A[0],i=A[1];if(~D5(t).indexOf(Ei.replacementClass))return lK.replace(A);var n=new RegExp("".concat(Ei.cssPrefix,"-.*"));if(delete i[0].attributes.id,i[0].attributes.class){var g=i[0].attributes.class.split(" ").reduce(function(s,r){return r===Ei.replacementClass||r.match(n)?s.toSvg.push(r):s.toNode.push(r),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 PR(s)}).join(`
`);t.setAttribute(rf,""),t.innerHTML=o}};function v$(e){e()}function oQA(e,A){var t=typeof A=="function"?A:cK;if(e.length===0)t();else{var i=v$;Ei.mutateApproach===s4A&&(i=rd.requestAnimationFrame||v$),i(function(){var n=ejA(),g=M5.begin("mutate");e.map(n),g(),t()})}}var N5=!1;function sQA(){N5=!0}function jP(){N5=!1}var VF=null;function K$(e){if(h$&&Ei.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,r=s===void 0?$g:s;VF=new h$(function(a){if(!N5){var I=ad();Nw(a).forEach(function(c){if(c.type==="childList"&&c.addedNodes.length>0&&!U$(c.addedNodes[0])&&(Ei.searchPseudoElements&&o(c.target),t(c.target)),c.type==="attributes"&&c.target.parentNode&&Ei.searchPseudoElements&&o([c.target],!0),c.type==="attributes"&&U$(c.target)&&~l4A.indexOf(c.attributeName))if(c.attributeName==="class"&&$4A(c.target)){var l=zL(D5(c.target)),B=l.prefix,Q=l.iconName;c.target.setAttribute(f5,B||I),Q&&c.target.setAttribute(y5,Q)}else AjA(c.target)&&n(c.target)})}}),lQ&&VF.observe(r,{childList:!0,attributes:!0,characterData:!0,subtree:!0})}}function gjA(){VF&&VF.disconnect()}function ojA(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 sjA(e){var A=e.getAttribute("data-prefix"),t=e.getAttribute("data-icon"),i=e.innerText!==void 0?e.innerText.trim():"",n=zL(D5(e));return n.prefix||(n.prefix=ad()),A&&t&&(n.prefix=A,n.iconName=t),n.iconName&&n.prefix||(n.prefix&&i.length>0&&(n.iconName=G4A(n.prefix,e.innerText)||w5(n.prefix,PEA(e.innerText))),!n.iconName&&Ei.autoFetchSvg&&e.firstChild&&e.firstChild.nodeType===Node.TEXT_NODE&&(n.iconName=e.firstChild.data)),n}function rjA(e){var A=Nw(e.attributes).reduce(function(t,i){return t.name!=="class"&&t.name!=="style"&&(t[i.name]=i.value),t},{});return A}function ajA(){return{iconName:null,prefix:null,transform:gB,symbol:!1,mask:{iconName:null,prefix:null,rest:[]},maskId:null,extra:{classes:[],styles:{},attributes:{}}}}function F$(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{styleParser:!0},t=sjA(e),i=t.iconName,n=t.prefix,g=t.rest,o=rjA(e),s=qP("parseNodeAttributes",{},e),r=A.styleParser?ojA(e):[];return wt({iconName:i,prefix:n,transform:gB,mask:{iconName:null,prefix:null,rest:[]},maskId:null,symbol:!1,extra:{classes:g,styles:r,attributes:o}},s)}var IjA=Hc.styles;function rQA(e){var A=Ei.autoReplaceSvg==="nest"?F$(e,{styleParser:!1}):F$(e);return~A.extra.classes.indexOf(xEA)?Id("generateLayersText",e,A):Id("generateSvgReplacementMutation",e,A)}function CjA(){return[].concat(Xc(GEA),Xc(bEA))}function _$(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!lQ)return Promise.resolve();var t=$g.documentElement.classList,i=function(c){return t.add("".concat(y$,"-").concat(c))},n=function(c){return t.remove("".concat(y$,"-").concat(c))},g=Ei.autoFetchSvg?CjA():QEA.concat(Object.keys(IjA));g.includes("fa")||g.push("fa");var o=[".".concat(xEA,":not([").concat(rf,"])")].concat(g.map(function(I){return".".concat(I,":not([").concat(rf,"])")})).join(", ");if(o.length===0)return Promise.resolve();var s=[];try{s=Nw(e.querySelectorAll(o))}catch{}if(s.length>0)i("pending"),n("complete");else return Promise.resolve();var r=M5.begin("onTree"),a=s.reduce(function(I,c){try{var l=rQA(c);l&&I.push(l)}catch(B){_EA||B.name==="MissingIcon"&&console.error(B)}return I},[]);return new Promise(function(I,c){Promise.all(a).then(function(l){oQA(l,function(){i("active"),i("complete"),n("pending"),typeof A=="function"&&A(),r(),I()})}).catch(function(l){r(),c(l)})})}function cjA(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;rQA(e).then(function(t){t&&oQA([t],A)})}function ljA(e){return function(A){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=(A||{}).icon?A:YP(A||{}),n=t.mask;return n&&(n=(n||{}).icon?n:YP(n||{})),e(i,wt(wt({},t),{},{mask:n}))}}var BjA=function(A){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=t.transform,n=i===void 0?gB:i,g=t.symbol,o=g===void 0?!1:g,s=t.mask,r=s===void 0?null:s,a=t.maskId,I=a===void 0?null:a,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(wt({type:"icon"},A),function(){return af("beforeDOMElementCreation",{iconDefinition:A,params:t}),k5({icons:{main:HP(m),mask:r?HP(r.icon):{found:!1,width:null,height:null,icon:{}}},prefix:p,iconName:y,transform:wt(wt({},gB),n),symbol:o,maskId:I,extra:{attributes:Q,styles:d,classes:l}})})}},EjA={mixout:function(){return{icon:ljA(BjA)}},hooks:function(){return{mutationObserverCallbacks:function(t){return t.treeCallback=_$,t.nodeCallback=cjA,t}}},provides:function(A){A.i2svg=function(t){var i=t.node,n=i===void 0?$g:i,g=t.callback,o=g===void 0?function(){}:g;return _$(n,o)},A.generateSvgReplacementMutation=function(t,i){var n=i.iconName,g=i.prefix,o=i.transform,s=i.symbol,r=i.mask,a=i.maskId,I=i.extra;return new Promise(function(c,l){Promise.all([OP(n,g),r.iconName?OP(r.iconName,r.prefix):Promise.resolve({found:!1,width:512,height:512,icon:{}})]).then(function(B){var Q=OL(B,2),h=Q[0],d=Q[1];c([t,k5({icons:{main:h,mask:d},prefix:g,iconName:n,transform:o,symbol:s,maskId:a,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,r=PL(s);r.length>0&&(n.style=r);var a;return m5(o)&&(a=Id("generateAbstractTransformGrouping",{main:g,transform:o,containerWidth:g.width,iconWidth:g.width})),i.push(a||g.icon),{children:i,attributes:n}}}},QjA={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(){af("beforeDOMElementCreation",{assembler:t,params:i});var o=[];return t(function(s){Array.isArray(s)?s.map(function(r){o=o.concat(r.abstract)}):o=o.concat(s.abstract)}),[{tag:"span",attributes:{class:["".concat(Ei.cssPrefix,"-layers")].concat(Xc(g)).join(" ")},children:o}]})}}}},ujA={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,r=i.styles,a=r===void 0?{}:r;return ZL({type:"counter",content:t},function(){return af("beforeDOMElementCreation",{content:t,params:i}),Z4A({content:t.toString(),extra:{attributes:s,styles:a,classes:["".concat(Ei.cssPrefix,"-layers-counter")].concat(Xc(g))}})})}}}},djA={mixout:function(){return{text:function(t){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=i.transform,g=n===void 0?gB:n,o=i.classes,s=o===void 0?[]:o,r=i.attributes,a=r===void 0?{}:r,I=i.styles,c=I===void 0?{}:I;return ZL({type:"text",content:t},function(){return af("beforeDOMElementCreation",{content:t,params:i}),G$({content:t,transform:wt(wt({},gB),g),extra:{attributes:a,styles:c,classes:["".concat(Ei.cssPrefix,"-layers-text")].concat(Xc(s))}})})}}},provides:function(A){A.generateLayersText=function(t,i){var n=i.transform,g=i.extra,o=null,s=null;if(BEA){var r=parseInt(getComputedStyle(t).fontSize,10),a=t.getBoundingClientRect();o=a.width/r,s=a.height/r}return Promise.resolve([t,G$({content:t.innerHTML,width:o,height:s,transform:n,extra:g,watchable:!0})])}}},aQA=new RegExp('"',"ug"),J$=[1105920,1112319],L$=wt(wt(wt(wt({},{FontAwesome:{normal:"fas",400:"fas"}}),o3A),g4A),E3A),zP=Object.keys(L$).reduce(function(e,A){return e[A.toLowerCase()]=L$[A],e},{}),hjA=Object.keys(zP).reduce(function(e,A){var t=zP[A];return e[A]=t[900]||Xc(Object.entries(t))[0][1],e},{});function pjA(e){var A=e.replace(aQA,"");return PEA(Xc(A)[0]||"")}function fjA(e){var A=e.getPropertyValue("font-feature-settings").includes("ss01"),t=e.getPropertyValue("content"),i=t.replace(aQA,""),n=i.codePointAt(0),g=n>=J$[0]&&n<=J$[1],o=i.length===2?i[0]===i[1]:!1;return g||o||A}function yjA(e,A){var t=e.replace(/^['"]|['"]$/g,"").toLowerCase(),i=parseInt(A),n=isNaN(i)?"normal":i;return(zP[t]||{})[n]||hjA[t]}function x$(e,A){var t="".concat(o4A).concat(A.replace(":","-"));return new Promise(function(i,n){if(e.getAttribute(t)!==null)return i();var g=Nw(e.children),o=g.filter(function(k){return k.getAttribute(JP)===A})[0],s=rd.getComputedStyle(e,A),r=s.getPropertyValue("font-family"),a=r.match(C4A),I=s.getPropertyValue("font-weight"),c=s.getPropertyValue("content");if(o&&!a)return e.removeChild(o),i();if(a&&c!=="none"&&c!==""){var l=s.getPropertyValue("content"),B=yjA(r,I),Q=pjA(l),h=a[0].startsWith("FontAwesome"),d=fjA(s),p=w5(B,Q),y=p;if(h){var m=b4A(Q);m.iconName&&m.prefix&&(p=m.iconName,B=m.prefix)}if(p&&!d&&(!o||o.getAttribute(f5)!==B||o.getAttribute(y5)!==y)){e.setAttribute(t,y),o&&e.removeChild(o);var D=ajA(),S=D.extra;S.attributes[JP]=A,OP(p,B).then(function(k){var N=k5(wt(wt({},D),{},{icons:{main:k,mask:tQA()},prefix:B,iconName:y,extra:S,watchable:!0})),G=$g.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 PR(M)}).join(`
`),e.removeAttribute(t),i()}).catch(n)}else i()}else i()})}function DjA(e){return Promise.all([x$(e,"::before"),x$(e,"::after")])}function mjA(e){return e.parentNode!==document.head&&!~r4A.indexOf(e.tagName.toUpperCase())&&!e.getAttribute(JP)&&(!e.parentNode||e.parentNode.tagName!=="svg")}var SjA=function(A){return!!A&&FEA.some(function(t){return A.includes(t)})},wjA=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 r=CK(i),a;try{for(r.s();!(a=r.n()).done;){var I=a.value;if(SjA(I)){var c=FEA.reduce(function(l,B){return l.replace(B,"")},I);c!==""&&c!=="*"&&t.add(c)}}}catch(l){r.e(l)}finally{r.f()}return t};function T$(e){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(lQ){var t;if(A)t=e;else if(Ei.searchPseudoElementsFullScan)t=e.querySelectorAll("*");else{var i=new Set,n=CK(document.styleSheets),g;try{for(n.s();!(g=n.n()).done;){var o=g.value;try{var s=CK(o.cssRules),r;try{for(s.s();!(r=s.n()).done;){var a=r.value,I=wjA(a.selectorText),c=CK(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){Ei.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=Nw(t).filter(mjA).map(DjA),y=M5.begin("searchPseudoElements");sQA(),Promise.all(p).then(function(){y(),jP(),h()}).catch(function(){y(),jP(),d()})})}}var kjA={hooks:function(){return{mutationObserverCallbacks:function(t){return t.pseudoElementsCallback=T$,t}}},provides:function(A){A.pseudoElements2svg=function(t){var i=t.node,n=i===void 0?$g:i;Ei.searchPseudoElements&&T$(n)}}},q$=!1,MjA={mixout:function(){return{dom:{unwatch:function(){sQA(),q$=!0}}}},hooks:function(){return{bootstrap:function(){K$(qP("mutationObserverCallbacks",{}))},noAuto:function(){gjA()},watch:function(t){var i=t.observeMutationsRoot;q$?jP():K$(qP("mutationObserverCallbacks",{observeMutationsRoot:i}))}}}},Y$=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)},NjA={mixout:function(){return{parse:{transform:function(t){return Y$(t)}}}},hooks:function(){return{parseNodeAttributes:function(t,i){var n=i.getAttribute("data-fa-transform");return n&&(t.transform=Y$(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)")},r="translate(".concat(n.x*32,", ").concat(n.y*32,") "),a="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(r," ").concat(a," ").concat(I)},l={transform:"translate(".concat(o/2*-1," -256)")},B={outer:s,inner:c,path:l};return{tag:"g",attributes:wt({},B.outer),children:[{tag:"g",attributes:wt({},B.inner),children:[{tag:i.icon.tag,children:i.icon.children,attributes:wt(wt({},i.icon.attributes),B.path)}]}]}}}},T2={x:0,y:0,width:"100%",height:"100%"};function H$(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 RjA(e){return e.tag==="g"?e.children:[e]}var GjA={hooks:function(){return{parseNodeAttributes:function(t,i){var n=i.getAttribute("data-fa-mask"),g=n?zL(n.split(" ").map(function(o){return o.trim()})):tQA();return g.prefix||(g.prefix=ad()),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,r=t.transform,a=g.width,I=g.icon,c=o.width,l=o.icon,B=y4A({transform:r,containerWidth:c,iconWidth:a}),Q={tag:"rect",attributes:wt(wt({},T2),{},{fill:"white"})},h=I.children?{children:I.children.map(H$)}:{},d={tag:"g",attributes:wt({},B.inner),children:[H$(wt({tag:I.tag,attributes:wt(wt({},I.attributes),B.path)},h))]},p={tag:"g",attributes:wt({},B.outer),children:[d]},y="mask-".concat(s||m$()),m="clip-".concat(s||m$()),D={tag:"mask",attributes:wt(wt({},T2),{},{id:y,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse"}),children:[Q,p]},S={tag:"defs",children:[{tag:"clipPath",attributes:{id:m},children:RjA(l)},D]};return i.push(S,{tag:"rect",attributes:wt({fill:"currentColor","clip-path":"url(#".concat(m,")"),mask:"url(#".concat(y,")")},T2)}),{children:i,attributes:n}}}},bjA={provides:function(A){var t=!1;rd.matchMedia&&(t=rd.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:wt(wt({},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=wt(wt({},g),{},{attributeName:"opacity"}),s={tag:"circle",attributes:wt(wt({},n),{},{cx:"256",cy:"364",r:"28"}),children:[]};return t||s.children.push({tag:"animate",attributes:wt(wt({},g),{},{attributeName:"r",values:"28;14;28;28;14;28;"})},{tag:"animate",attributes:wt(wt({},o),{},{values:"1;0;1;1;0;1;"})}),i.push(s),i.push({tag:"path",attributes:wt(wt({},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:wt(wt({},o),{},{values:"1;0;0;0;0;1;"})}]}),t||i.push({tag:"path",attributes:wt(wt({},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:wt(wt({},o),{},{values:"0;0;1;1;0;0;"})}]}),{tag:"g",attributes:{class:"missing"},children:i}}}},UjA={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}}}},vjA=[S4A,EjA,QjA,ujA,djA,kjA,MjA,NjA,GjA,bjA,UjA];T4A(vjA,{mixoutsTo:iC});iC.noAuto;iC.config;iC.library;iC.dom;var ZP=iC.parse;iC.findIconDefinition;iC.toHtml;var KjA=iC.icon;iC.layer;iC.text;iC.counter;var IQA={exports:{}},FjA="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",_jA=FjA,JjA=_jA;function CQA(){}function cQA(){}cQA.resetWarningCache=CQA;var LjA=function(){function e(i,n,g,o,s,r){if(r!==JjA){var a=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 a.name="Invariant Violation",a}}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:cQA,resetWarningCache:CQA};return t.PropTypes=t,t};IQA.exports=LjA();var xjA=IQA.exports;const yn=gw(xjA);var TjA={};function WP(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 qjA(e){if(Array.isArray(e))return e}function YjA(e){if(Array.isArray(e))return WP(e)}function Au(e,A,t){return(A=VjA(A))in e?Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[A]=t,e}function HjA(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function OjA(e,A){var t=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(t!=null){var i,n,g,o,s=[],r=!0,a=!1;try{if(g=(t=t.call(e)).next,A!==0)for(;!(r=(i=g.call(t)).done)&&(s.push(i.value),s.length!==A);r=!0);}catch(I){a=!0,n=I}finally{try{if(!r&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(a)throw n}}return s}}function PjA(){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 jjA(){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 O$(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 Wl(e){for(var A=1;A<arguments.length;A++){var t=arguments[A]!=null?arguments[A]:{};A%2?O$(Object(t),!0).forEach(function(i){Au(e,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):O$(Object(t)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(t,i))})}return e}function zjA(e,A){if(e==null)return{};var t,i,n=ZjA(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 ZjA(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 P$(e,A){return qjA(e)||OjA(e,A)||lQA(e,A)||PjA()}function VP(e){return YjA(e)||HjA(e)||lQA(e)||jjA()}function WjA(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 VjA(e){var A=WjA(e,"string");return typeof A=="symbol"?A:A+""}function XF(e){"@babel/helpers - typeof";return XF=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},XF(e)}function lQA(e,A){if(e){if(typeof e=="string")return WP(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)?WP(e,A):void 0}}var XjA="7.0.0-alpha1",XP;try{var $jA=require("@fortawesome/fontawesome-svg-core/package.json");XP=$jA.version}catch{XP=TjA.FA_VERSION||"7.0.0-alpha8"}function A8A(e){var A=e.beat,t=e.fade,i=e.beatFade,n=e.bounce,g=e.shake,o=e.flash,s=e.spin,r=e.spinPulse,a=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=e8A(XP,XjA),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":a,"fa-spin-pulse":r,"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 e8A(e,A){for(var t=e.split("-"),i=P$(t,2),n=i[0],g=i[1],o=A.split("-"),s=P$(o,2),r=s[0],a=s[1],I=n.split("."),c=r.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&&!a)}function t8A(e){return e=e-0,e===e}function BQA(e){return t8A(e)?e:(e=e.replace(/[\-_\s]+(.)?/g,function(A,t){return t?t.toUpperCase():""}),e.substr(0,1).toLowerCase()+e.substr(1))}var i8A=["style"];function n8A(e){return e.charAt(0).toUpperCase()+e.slice(1)}function g8A(e){return e.split(";").map(function(A){return A.trim()}).filter(function(A){return A}).reduce(function(A,t){var i=t.indexOf(":"),n=BQA(t.slice(0,i)),g=t.slice(i+1).trim();return n.startsWith("webkit")?A[n8A(n)]=g:A[n]=g,A},{})}function EQA(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(r){return EQA(e,r)}),n=Object.keys(A.attributes||{}).reduce(function(r,a){var I=A.attributes[a];switch(a){case"class":r.attrs.className=I,delete A.attributes.class;break;case"style":r.attrs.style=g8A(I);break;default:a.indexOf("aria-")===0||a.indexOf("data-")===0?r.attrs[a.toLowerCase()]=I:r.attrs[BQA(a)]=I}return r},{attrs:{}}),g=t.style,o=g===void 0?{}:g,s=zjA(t,i8A);return n.attrs.style=Wl(Wl({},n.attrs.style),o),e.apply(void 0,[A.tag,Wl(Wl({},n.attrs),s)].concat(VP(i)))}var QQA=!1;try{QQA=!0}catch{}function o8A(){if(!QQA&&console&&typeof console.error=="function"){var e;(e=console).error.apply(e,arguments)}}function j$(e){if(e&&XF(e)==="object"&&e.prefix&&e.iconName&&e.icon)return e;if(ZP.icon)return ZP.icon(e);if(e===null)return null;if(e&&XF(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 q2(e,A){return Array.isArray(A)&&A.length>0||!Array.isArray(A)&&A?Au({},e,A):{}}var z$={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=he.forwardRef(function(e,A){var t=Wl(Wl({},z$),e),i=t.icon,n=t.mask,g=t.symbol,o=t.className,s=t.title,r=t.titleId,a=t.maskId,I=j$(i),c=q2("classes",[].concat(VP(A8A(t)),VP((o||"").split(" ")))),l=q2("transform",typeof t.transform=="string"?ZP.transform(t.transform):t.transform),B=q2("mask",j$(n)),Q=KjA(I,Wl(Wl(Wl(Wl({},c),l),B),{},{symbol:g,title:s,titleId:r,maskId:a}));if(!Q)return o8A("Could not find icon",I),null;var h=Q.abstract,d={ref:A};return Object.keys(t).forEach(function(p){z$.hasOwnProperty(p)||(d[p]=t[p])}),s8A(h[0],d)});Cd.displayName="FontAwesomeIcon";Cd.propTypes={beat:yn.bool,border:yn.bool,beatFade:yn.bool,bounce:yn.bool,className:yn.string,fade:yn.bool,flash:yn.bool,mask:yn.oneOfType([yn.object,yn.array,yn.string]),maskId:yn.string,fixedWidth:yn.bool,inverse:yn.bool,flip:yn.oneOf([!0,!1,"horizontal","vertical","both"]),icon:yn.oneOfType([yn.object,yn.array,yn.string]),listItem:yn.bool,pull:yn.oneOf(["right","left"]),pulse:yn.bool,rotation:yn.oneOf([0,90,180,270]),rotateBy:yn.bool,shake:yn.bool,size:yn.oneOf(["2xs","xs","sm","lg","xl","2xl","1x","2x","3x","4x","5x","6x","7x","8x","9x","10x"]),spin:yn.bool,spinPulse:yn.bool,spinReverse:yn.bool,symbol:yn.oneOfType([yn.bool,yn.string]),title:yn.string,titleId:yn.string,transform:yn.oneOfType([yn.string,yn.object]),swapOpacity:yn.bool,widthAuto:yn.bool};var s8A=EQA.bind(null,he.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 r8A={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"]},a8A={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"]},I8A=a8A,C8A={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"]},c8A={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"]},l8A=c8A;const B8A=[{key:"cee-lo",title:"CEE-LO",tagline:"Fast • Social • Casual",icon:SPA},{key:"craps",title:"CRAPS",tagline:"High Energy • Strategy",icon:wPA},{key:"poker",title:"POKER",tagline:"Skill-Based • Competitive",icon:kPA},{key:"skills",title:"SKILLS",tagline:"Challenge • Mastery",icon:MPA},{key:"zentara",title:"ZENTARA",tagline:"Conquer • Build • Dominate",icon:NPA}];function E8A({selectedMode:e,onSelectMode:A,slides:t=B8A,interval:i=4e3,width:n=140,height:g=140,className:o=""}){const[s,r]=E.useState(0),[a,I]=E.useState(!1);E.useEffect(()=>{if(e){const D=t.findIndex(S=>S.key===e);D>=0&&D!==s&&r(D)}},[e,t,s]),E.useEffect(()=>{if(a||e||i<=0)return;const D=setInterval(()=>{r(S=>(S+1)%t.length)},i);return()=>clearInterval(D)},[a,e,i,t.length]);const c=E.useCallback(D=>{r(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=vP},[]),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:I8A})}),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:l8A})})]})}const Q8A="/assets/logo-256-CalulGNO.webp",u8A="/assets/logo-420-D7JbtaQr.webp",d8A="/assets/logo-256-BQd-RHpb.avif",h8A="/assets/logo-420-CxzlrsyU.avif",p8A="/assets/zentara-icon-transparent-HQ2ticUo.webp";function uQA({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,r=s==="craps"||s==="poker"||s==="ceelo"||s==="skills"||s==="zentara",a=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=p8A),C.jsxs("div",{className:`logo-hero ${i}`,"data-testid":"logo-hero",children:[r?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:a,decoding:"async",loading:"eager",fetchPriority:"high",style:{maxWidth:"100%",height:"auto"},onError:p=>{try{p.currentTarget.src=vP}catch{}}})]}):C.jsxs("picture",{children:[C.jsx("source",{type:"image/avif",srcSet:`${d8A} 256w, ${h8A} 420w`,sizes:"(max-width: 600px) 60vw, 420px"}),C.jsx("source",{type:"image/webp",srcSet:`${Q8A} 256w, ${u8A} 420w`,sizes:"(max-width: 600px) 60vw, 420px"}),C.jsx("img",{width:e,height:A,src:vP,alt:a,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 dQA=E.createContext(void 0),f8A=({children:e})=>{const{user:A}=en(),[t,i]=E.useState([]),[n,g]=E.useState([]),[o,s]=E.useState([]),{blockUser:r,unblockUser:a,getFriendsList:I,sendFriendRequest:c,unfriend:l,respondFriendRequest:B}=So(),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]);xs({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 r(G)).ok&&s(w=>w.find(b=>b.id===G)?w:[...w,{id:G}])},[r]),k=E.useCallback(async G=>{(await a(G)).ok&&s(w=>w.filter(b=>b.id!==G))},[a]),N=E.useCallback(G=>!!o.find(M=>M.id===G),[o]);return C.jsx(dQA.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 vd(){const e=E.useContext(dQA);if(!e)throw new Error("useSocial must be used within a SocialProvider");return e}const hQA=E.createContext(null),jR=()=>E.useContext(hQA),lh=e=>`room:${e}`,DC=(e,A)=>`dm:${[e,A].sort().join("|")}`,Z$=e=>{if(!e.startsWith("dm:"))return null;const t=e.slice(3).split("|");return t.length===2?t:null},Y2=(e,A)=>e.ts===A.ts?e.id<A.id?-1:e.id>A.id?1:0:e.ts-A.ts,W$=()=>"tmp:"+Math.random().toString(36).slice(2)+Date.now().toString(36),H2=e=>({id:e.id,ts:e.ts,senderId:e.fromUserId,text:e.text,roomId:e.roomId}),O2=e=>({id:e.id,ts:e.ts,senderId:e.fromUserId,text:e.text,toUserId:e.toUserId});function y8A({children:e}){const{user:A}=en(),t=(A==null?void 0:A.id)??"anon",{roomSendMessage:i,roomFetchHistory:n,dmSendMessage:g,dmFetchHistory:o}=So(),[s,r]=E.useState({}),[a,I]=E.useState({}),[c,l]=E.useState(null),[B,Q]=E.useState({}),h=E.useRef(new Set),{info:d}=LL(),p=eA=>eA?eA.length>100?eA.slice(0,100)+"…":eA:"",y=E.useCallback((eA,aA,sA)=>{if(aA!=null&&aA.length&&(r(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 YA=yA.get(RA.id);yA.set(RA.id,{...YA??{},...RA,pending:!1,error:void 0})}const fA=Array.from(yA.values()).sort(Y2);return{...pA,[eA]:fA}}),eA.startsWith("dm:")&&(sA!=null&&sA.fromPeerId))){const pA=sA.fromPeerId,gA=DC(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)=>{r(pA=>{const gA=(pA[eA]??[]).slice();return gA.push(aA),gA.sort(Y2),{...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),r(yA=>{const fA=yA[eA]??[],RA=fA.some(W=>W.id===gA);let YA;return RA?YA=fA.filter(W=>W.id!==aA.id):YA=fA.map(W=>W.id===aA.id?{...W,id:gA,pending:!1,error:void 0}:W),YA.sort(Y2),{...yA,[eA]:YA}})}catch(pA){r(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=>{r(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=W$(),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=DC(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(O2);y(aA,pA),I(gA=>({...gA,[aA]:0}))}}finally{Q(sA=>({...sA,[aA]:!0}))}},[o,y,t,B]),b=E.useCallback(eA=>{const aA=DC(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=DC(t,eA),gA=W$(),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(DC(t,eA)),[D,t]),J=E.useCallback(eA=>S(DC(t,eA)),[S,t]),T=E.useCallback(eA=>{const aA=DC(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&&(T(eA),w(eA))},[T,w]),U=E.useCallback(eA=>{const aA=[];for(const[sA,pA]of Object.entries(s??{})){if(!sA.startsWith("dm:"))continue;const gA=Z$(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:(a==null?void 0:a[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,a,t]),x=E.useCallback(eA=>{const aA=new Set(eA);let sA=0;for(const[pA,gA]of Object.entries(a)){if(gA<=0)continue;const yA=Z$(pA);if(!yA)continue;const fA=yA[0]===t?yA[1]:yA[0];aA.has(fA)&&(sA+=gA)}return sA},[a,t]),q=E.useCallback(eA=>{const aA=DC(t,eA);return(a==null?void 0:a[aA])??0},[a,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(H2);y(aA,pA)}}catch{}}xs({onRoomMessage:eA=>{if(!(!(eA!=null&&eA.id)||!eA.roomId)&&!h.current.has(eA.id)){h.current.add(eA.id),y(lh(eA.roomId),[H2(eA)]);try{d("Message",p(eA.text))}catch{}}},onRoomHistory:({roomId:eA,messages:aA})=>{!eA||!Array.isArray(aA)||y(lh(eA),aA.map(H2))},onDmMessage:eA=>{if(!(eA!=null&&eA.id))return;const aA=eA.fromUserId===t?eA.toUserId:eA.fromUserId;if(!aA)return;const sA=DC(t,aA),pA=O2(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=DC(t,eA);y(sA,aA.map(O2)),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:T,setActiveDm:v,loadDmHistory:w,threads:s,getTotalFriendUnread:x,getUnreadForPeer:q}),[k,N,G,M,b,_,K,J,U,T,v,w,s,x,q]);return C.jsx(hQA.Provider,{value:Z,children:e})}const D8A=5e3;function m8A(){const{quickMatchJoin:e,quickMatchLeave:A,quickMatchStatus:t}=So(),i=Ss(),n=Ji(),[g,o]=E.useState({status:"idle"}),[s,r]=E.useState({}),a=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}),a.current&&setTimeout(()=>{n(m.route),setTimeout(()=>o({status:"idle"}),500)},1500))},d=m=>{m!=null&&m.queueSizes&&r(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&&r(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)??D8A;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 Wo()).zentaraBotCount??Qs.zentaraBotCount??3)):void 0,m=await e(h,y);m!=null&&m.ok?m.matched||m.queueSizes&&r(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 V$({gameMode:e,disabled:A,onFallbackToSinglePlayer:t}){const{state:i,leave:n,join:g}=m8A(),o=E.useCallback(()=>{e&&(Xt("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",r=i.status==="found";return C.jsx("button",{className:`btn gold-outline cta-btn primaryButton${s?" quick-match-btn--searching":""}${r?" quick-match-btn--found":""}`,onClick:o,disabled:A||!e||r,"aria-label":s?"Cancel Quick Match":r?"Match Found!":"Quick Match",type:"button",children:r?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 S8A="purple",w8A="cyan",k8A="orange",M8A="red",N8A="yellow",R8A="green",G8A="blue",b8A="magenta",$P=S8A,Mm=w8A,Nm=k8A,Rm=M8A,Gm=N8A,bm=R8A,Um=G8A,lN=b8A,X$=[{id:0,name:"Command Base",type:"start"},{id:1,name:"Alpha Centauri",type:"planet",group:$P,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:$P,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:lN,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:lN,cost:400,rent:[50,200,600,1400,1700,2e3],upgradeCost:200}],$$=[{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:lN,cost:350,rent:[35,175,500,1100,1300,1500],upgradeCost:200},{id:19,name:"Zentara",type:"planet",group:lN,cost:400,rent:[50,200,600,1400,1700,2e3],upgradeCost:200}],pQA={startingCredits:1500,passStartBonus:200,jailBailCost:50,armorUpgradeCost:200,weaponUpgradeCost:250,armorDamageReduction:.15,maxArmorLevel:3,maxWeaponLevel:3},U8A={tiles:X$,tileCount:X$.length,...pQA},v8A={tiles:$$,tileCount:$$.length,...pQA},K8A={[$P]:"#7b2ff2",[Mm]:"#00e5ff",[Nm]:"#ff9100",[Rm]:"#ff1744",[Gm]:"#ffd600",[bm]:"#00e676",[Um]:"#2979ff",[lN]:"#e040fb"};function F8A(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 fQA(e){return{tiles:e.tiles.map(F8A),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 un=fQA(U8A),_8A=fQA(v8A);function $F(e){return e==="standard"?_8A:un}const cs=K8A,WL="zentara_saved_game";function yQA(e){const{board:A,...t}=e;localStorage.setItem(WL,JSON.stringify(t))}function J8A(){return localStorage.getItem(WL)!==null}function DQA(){const e=localStorage.getItem(WL);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:$F(A.boardSize).tiles}}catch{return null}}function A3(){localStorage.removeItem(WL)}const L8A="/assets/azure-sovereignty-t1-DmX6oKNg.webp",R5=Object.freeze(Object.defineProperty({__proto__:null,default:L8A},Symbol.toStringTag,{value:"Module"})),x8A="/assets/azure-sovereignty-t2-HrQch5a7.webp",G5=Object.freeze(Object.defineProperty({__proto__:null,default:x8A},Symbol.toStringTag,{value:"Module"})),T8A="/assets/azure-sovereignty-t3-DXjh05IZ.webp",b5=Object.freeze(Object.defineProperty({__proto__:null,default:T8A},Symbol.toStringTag,{value:"Module"})),q8A="/assets/azure-sovereignty-t4-DGQWyj9i.webp",U5=Object.freeze(Object.defineProperty({__proto__:null,default:q8A},Symbol.toStringTag,{value:"Module"})),Y8A="/assets/azure-sovereignty-t5-DskYl0iv.webp",v5=Object.freeze(Object.defineProperty({__proto__:null,default:Y8A},Symbol.toStringTag,{value:"Module"})),H8A="/assets/azure-sovereignty-t6-B08urHNJ.webp",K5=Object.freeze(Object.defineProperty({__proto__:null,default:H8A},Symbol.toStringTag,{value:"Module"})),O8A="/assets/crimson-dominion-t1-Vf8IUB_D.webp",F5=Object.freeze(Object.defineProperty({__proto__:null,default:O8A},Symbol.toStringTag,{value:"Module"})),P8A="/assets/crimson-dominion-t2-R4fcfwor.webp",_5=Object.freeze(Object.defineProperty({__proto__:null,default:P8A},Symbol.toStringTag,{value:"Module"})),j8A="/assets/crimson-dominion-t3-Dq48yda7.webp",J5=Object.freeze(Object.defineProperty({__proto__:null,default:j8A},Symbol.toStringTag,{value:"Module"})),z8A="/assets/crimson-dominion-t4-jQ3WbC0q.webp",L5=Object.freeze(Object.defineProperty({__proto__:null,default:z8A},Symbol.toStringTag,{value:"Module"})),Z8A="/assets/crimson-dominion-t5-BxD0z7Ym.webp",x5=Object.freeze(Object.defineProperty({__proto__:null,default:Z8A},Symbol.toStringTag,{value:"Module"})),W8A="/assets/crimson-dominion-t6-DdFNyKQB.webp",T5=Object.freeze(Object.defineProperty({__proto__:null,default:W8A},Symbol.toStringTag,{value:"Module"})),V8A="/assets/emerald-collective-t1-BFDYbRJC.webp",q5=Object.freeze(Object.defineProperty({__proto__:null,default:V8A},Symbol.toStringTag,{value:"Module"})),X8A="/assets/emerald-collective-t2-B0HN4oSa.webp",Y5=Object.freeze(Object.defineProperty({__proto__:null,default:X8A},Symbol.toStringTag,{value:"Module"})),$8A="/assets/emerald-collective-t3-bX8hcHMX.webp",H5=Object.freeze(Object.defineProperty({__proto__:null,default:$8A},Symbol.toStringTag,{value:"Module"})),A5A="/assets/emerald-collective-t4-Bfmm0OcF.webp",O5=Object.freeze(Object.defineProperty({__proto__:null,default:A5A},Symbol.toStringTag,{value:"Module"})),e5A="/assets/emerald-collective-t5-Bgb0YdAC.webp",P5=Object.freeze(Object.defineProperty({__proto__:null,default:e5A},Symbol.toStringTag,{value:"Module"})),t5A="/assets/emerald-collective-t6-BTeZLW--.webp",j5=Object.freeze(Object.defineProperty({__proto__:null,default:t5A},Symbol.toStringTag,{value:"Module"})),i5A="/assets/golden-imperium-t1-2Ac07vhL.webp",z5=Object.freeze(Object.defineProperty({__proto__:null,default:i5A},Symbol.toStringTag,{value:"Module"})),n5A="/assets/golden-imperium-t2-B1z9wYCA.webp",Z5=Object.freeze(Object.defineProperty({__proto__:null,default:n5A},Symbol.toStringTag,{value:"Module"})),g5A="/assets/golden-imperium-t3-sQgzUnhL.webp",W5=Object.freeze(Object.defineProperty({__proto__:null,default:g5A},Symbol.toStringTag,{value:"Module"})),o5A="/assets/golden-imperium-t4-QLhb8vtv.webp",V5=Object.freeze(Object.defineProperty({__proto__:null,default:o5A},Symbol.toStringTag,{value:"Module"})),s5A="/assets/golden-imperium-t5-ztz2kNG1.webp",X5=Object.freeze(Object.defineProperty({__proto__:null,default:s5A},Symbol.toStringTag,{value:"Module"})),r5A="/assets/golden-imperium-t6-Cw2Zjnaw.webp",$5=Object.freeze(Object.defineProperty({__proto__:null,default:r5A},Symbol.toStringTag,{value:"Module"})),a5A="/assets/silver-pact-t1-dcR9QgEE.webp",Az=Object.freeze(Object.defineProperty({__proto__:null,default:a5A},Symbol.toStringTag,{value:"Module"})),I5A="/assets/silver-pact-t2-BpNmnrg8.webp",ez=Object.freeze(Object.defineProperty({__proto__:null,default:I5A},Symbol.toStringTag,{value:"Module"})),C5A="/assets/silver-pact-t3-wI2PlS3S.webp",tz=Object.freeze(Object.defineProperty({__proto__:null,default:C5A},Symbol.toStringTag,{value:"Module"})),c5A="/assets/silver-pact-t4-BCVdufU2.webp",iz=Object.freeze(Object.defineProperty({__proto__:null,default:c5A},Symbol.toStringTag,{value:"Module"})),l5A="/assets/silver-pact-t5-CvVwxwL3.webp",nz=Object.freeze(Object.defineProperty({__proto__:null,default:l5A},Symbol.toStringTag,{value:"Module"})),B5A="/assets/silver-pact-t6-AkEiFdAv.webp",gz=Object.freeze(Object.defineProperty({__proto__:null,default:B5A},Symbol.toStringTag,{value:"Module"})),E5A="/assets/void-enclave-t1-CT6bXzYA.webp",oz=Object.freeze(Object.defineProperty({__proto__:null,default:E5A},Symbol.toStringTag,{value:"Module"})),Q5A="/assets/void-enclave-t2-B5lyWeE-.webp",sz=Object.freeze(Object.defineProperty({__proto__:null,default:Q5A},Symbol.toStringTag,{value:"Module"})),u5A="/assets/void-enclave-t3-D_btJABX.webp",rz=Object.freeze(Object.defineProperty({__proto__:null,default:u5A},Symbol.toStringTag,{value:"Module"})),d5A="/assets/void-enclave-t4-CnK-DAE8.webp",az=Object.freeze(Object.defineProperty({__proto__:null,default:d5A},Symbol.toStringTag,{value:"Module"})),h5A="/assets/void-enclave-t5-BazUHlmh.webp",Iz=Object.freeze(Object.defineProperty({__proto__:null,default:h5A},Symbol.toStringTag,{value:"Module"})),p5A="/assets/void-enclave-t6-DftImh4t.webp",Cz=Object.freeze(Object.defineProperty({__proto__:null,default:p5A},Symbol.toStringTag,{value:"Module"})),mQA=gr();async function f5A(){try{const e=await Co(),A=await fetch(`${mQA}/api/heroes/mine`,{credentials:"include",headers:e?{Authorization:`Bearer ${e}`}:{}});return A.ok?(await A.json()).heroes:[]}catch{return[]}}async function y5A(e){try{const A=await Co(),t=await fetch(`${mQA}/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 SQA={1:"Recruit",2:"Guardian",3:"Commander",4:"Warlord",5:"Champion",6:"Legend"},wQA={"crimson-dominion":"offense","silver-pact":"balanced","azure-sovereignty":"defense","golden-imperium":"offense","emerald-collective":"defense","void-enclave":"balanced"},kQA={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}},D5A=.08,m5A=.05,S5A=.05,w5A=.08;function mu(e,A){const t=kQA[A],i=wQA[e];let n=t.baseAttack,g=t.baseDefense;return i==="offense"?(n+=D5A,g=Math.max(0,g-m5A)):i==="defense"&&(n=Math.max(0,n-S5A),g+=w5A),{attack:n,defense:g}}const cz=[{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."}],ys=Object.fromEntries(cz.map(e=>[e.id,e]));function e3(e){return cz.filter(A=>A.empire===e)}function lz(){const[e,A]=E.useState([]),[t,i]=E.useState(!0),[n,g]=E.useState(!1),o=E.useCallback(async()=>{i(!0);const I=await f5A();A(I),i(!1)},[]);E.useEffect(()=>{o()},[o]);const s=E.useMemo(()=>new Set(e.map(I=>I.heroId)),[e]),r=E.useCallback(async I=>{if(n)return{ok:!1,error:"BUSY"};g(!0);const c=await y5A(I);return c.ok&&A(l=>[...l,c.hero]),g(!1),c},[n]),a=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:cz,owned:e,ownedIds:s,loading:t,buying:n,buy:r,refresh:o,bestHeroForEmpire:a,getHeroModifiers:mu,HERO_TIER_STATS:kQA,HERO_BY_ID:ys,getHeroesForEmpire:e3}}const oB={"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 Zi(e){var A;return((A=oB[e])==null?void 0:A.name)??"Unknown Fleet"}const Bz="/assets/piece_0-Bszryx6y.webp",Ez="/assets/piece_1-Cv-uF1qp.webp",Qz="/assets/piece_2-BtsgKQre.webp",uz="/assets/piece_3-jPIn8UPt.webp",dz="/assets/piece_4-CVIaULeN.webp",hz="/assets/piece_5-BbmWhI1d.webp",k5A="/assets/board_azure_t1-uhzyJ5O2.png",M5A="/assets/board_azure_t2-7WFg6SFe.png",N5A="/assets/board_azure_t3-DFyQ1yFA.png",R5A="/assets/board_azure_t4--LjmjFOc.png",G5A="/assets/board_azure_t5-kCVv9B_8.png",b5A="/assets/board_azure_t6-JV5uCTqU.png",U5A="/assets/board_crimson_t1-BwxUw8u0.png",v5A="/assets/board_crimson_t2-6NEJAqMc.png",K5A="/assets/board_crimson_t3-BWlzMzt2.png",F5A="/assets/board_crimson_t4-D8Jc5yCO.png",_5A="/assets/board_crimson_t5-D6RFLgkV.png",J5A="/assets/board_crimson_t6-gnYH98X_.png",L5A="/assets/board_emerald_t1-B2egbD2-.png",x5A="/assets/board_emerald_t2-BQCAt0fS.png",T5A="/assets/board_emerald_t3-Bi2inM_Z.png",q5A="/assets/board_emerald_t4-Fpn-yafL.png",Y5A="/assets/board_emerald_t5-ChEu-JPO.png",H5A="/assets/board_emerald_t6-C6qK5wVr.png",O5A="/assets/board_golden_t1-wUo-Md-J.png",P5A="/assets/board_golden_t2-DpOComt8.png",j5A="/assets/board_golden_t3-Cr04-aIZ.png",z5A="/assets/board_golden_t4-DmLVdFD-.png",Z5A="/assets/board_golden_t5-BO_7glbk.png",W5A="/assets/board_golden_t6-Cn2N92HZ.png",V5A="/assets/board_silver_t1-Dk3k-NaJ.png",X5A="/assets/board_silver_t2-gY9z7Ocy.png",$5A="/assets/board_silver_t3-DxuzmvQw.png",AzA="/assets/board_silver_t4-CkoaQVfe.png",ezA="/assets/board_silver_t5-B63wrBnz.png",tzA="/assets/board_silver_t6-cX56Pc6H.png",izA="/assets/board_void_t1-DDec7uko.png",nzA="/assets/board_void_t2-HWwY4zjd.png",gzA="/assets/board_void_t3-Bm65kPQF.png",ozA="/assets/board_void_t4-DpFcFdts.png",szA="/assets/board_void_t5-4mh4n7wE.png",rzA="/assets/board_void_t6-BnFIOu4n.png",pB={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},azA="/assets/board_crimson-Bbfxhd3p.webp",IzA="/assets/board_silver-Cng7mb9O.webp",CzA="/assets/board_azure-BFKhjmxp.webp",czA="/assets/board_golden-CanbSjjJ.webp",lzA="/assets/board_emerald-DJHSvo6l.webp",BzA="/assets/board_void-5g3WxUBA.webp",EzA="/assets/board_crimson_still-iwJEtNQX.webp",QzA="/assets/board_silver_still-BzHbQUh7.webp",uzA="/assets/board_azure_still-W7WJD2Dq.webp",dzA="/assets/board_golden_still-CYKBiKVV.webp",hzA="/assets/board_emerald_still-Cf5Bc4Q4.webp",pzA="/assets/board_void_still-C_C-otYo.webp",fzA=Object.assign({"../../assets/optimized/board_azure_t1.png":k5A,"../../assets/optimized/board_azure_t2.png":M5A,"../../assets/optimized/board_azure_t3.png":N5A,"../../assets/optimized/board_azure_t4.png":R5A,"../../assets/optimized/board_azure_t5.png":G5A,"../../assets/optimized/board_azure_t6.png":b5A,"../../assets/optimized/board_crimson_t1.png":U5A,"../../assets/optimized/board_crimson_t2.png":v5A,"../../assets/optimized/board_crimson_t3.png":K5A,"../../assets/optimized/board_crimson_t4.png":F5A,"../../assets/optimized/board_crimson_t5.png":_5A,"../../assets/optimized/board_crimson_t6.png":J5A,"../../assets/optimized/board_emerald_t1.png":L5A,"../../assets/optimized/board_emerald_t2.png":x5A,"../../assets/optimized/board_emerald_t3.png":T5A,"../../assets/optimized/board_emerald_t4.png":q5A,"../../assets/optimized/board_emerald_t5.png":Y5A,"../../assets/optimized/board_emerald_t6.png":H5A,"../../assets/optimized/board_golden_t1.png":O5A,"../../assets/optimized/board_golden_t2.png":P5A,"../../assets/optimized/board_golden_t3.png":j5A,"../../assets/optimized/board_golden_t4.png":z5A,"../../assets/optimized/board_golden_t5.png":Z5A,"../../assets/optimized/board_golden_t6.png":W5A,"../../assets/optimized/board_silver_t1.png":V5A,"../../assets/optimized/board_silver_t2.png":X5A,"../../assets/optimized/board_silver_t3.png":$5A,"../../assets/optimized/board_silver_t4.png":AzA,"../../assets/optimized/board_silver_t5.png":ezA,"../../assets/optimized/board_silver_t6.png":tzA,"../../assets/optimized/board_void_t1.png":izA,"../../assets/optimized/board_void_t2.png":nzA,"../../assets/optimized/board_void_t3.png":gzA,"../../assets/optimized/board_void_t4.png":ozA,"../../assets/optimized/board_void_t5.png":szA,"../../assets/optimized/board_void_t6.png":rzA}),MQA={};for(const[e,A]of Object.entries(fzA)){const t=e.split("/").pop();t&&(MQA[t]=A)}const yzA={"crimson-dominion":"crimson","silver-pact":"silver","azure-sovereignty":"azure","golden-imperium":"golden","emerald-collective":"emerald","void-enclave":"void"};function DzA(e,A,t){const i=yzA[e];return MQA[`board_${i}_t${A}.png`]??t}const mzA={"crimson-dominion":azA,"silver-pact":IzA,"azure-sovereignty":CzA,"golden-imperium":czA,"emerald-collective":lzA,"void-enclave":BzA},NQA={"crimson-dominion":EzA,"silver-pact":QzA,"azure-sovereignty":uzA,"golden-imperium":dzA,"emerald-collective":hzA,"void-enclave":pzA},pk=150,A_=pk*.75,Oy=A_,Py=A_,SzA=.72,wzA=ti.getPlatform()==="android";for(const e of[...Object.values(mzA),...Object.values(NQA)]){const A=new Image;A.src=e}const kzA=1e3,MzA=350,RQA=E.forwardRef(({initialX:e,initialY:A,shape:t,isCurrentPlayer:i,rotation:n=0,rotationTransition:g=!1,zoom:o=10,label:s,isMoving:r=!1,isLanding:a=!1,sizeScale:I=1,pickerPiece:c=!1,tier:l=1,outlineFilterId:B},Q)=>{const h=DzA(t,l,NQA[t]),[d,p]=E.useState(!1);E.useEffect(()=>{if(!r){p(!1);return}if(a){const G=setTimeout(()=>p(!1),MzA);return()=>clearTimeout(G)}const N=setTimeout(()=>p(!0),kzA);return()=>clearTimeout(N)},[r,a]);const y=r&&d,m=Math.min(Math.max(1,5/o),1.5),D=E.useMemo(()=>r?a?{transform:`scale(${I})`,transition:`transform ${pB.LAND_PHASE_MS}ms cubic-bezier(0.42, 0, 0.32, 1)`,willChange:"transform"}:{transform:"scale(1)",transition:`transform ${pB.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"},[r,a,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(${SzA} 1)`,children:[r&&C.jsx("image",{className:`zentara-piece-shadow-img${!y||a?"":" zentara-piece-shadow-img--hidden"}`,href:h,x:-Oy/2,y:-Py/2+A_*.06,width:Oy,height:Py,preserveAspectRatio:"xMidYMid meet",pointerEvents:"none",filter:`url(#${S})`}),C.jsxs("g",{className:r?"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":""}${r?" zentara-piece-img--moving":""}`,href:h,x:c?-pk:-Oy/2,y:c?-pk:-Py/2,width:c?pk*2:Oy,height:c?pk*2:Py,preserveAspectRatio:"xMidYMid meet",style:k})]})]}),s&&(()=>{const N=s==="Cryosleep",G=N?"❄  CRYOSLEEP":"VISITING";return C.jsx("text",{x:0,y:A_*.28,textAnchor:"middle",...wzA?{lengthAdjust:"spacingAndGlyphs",textLength:N?78:50}:{},className:`zentara-piece-label${N?" zentara-piece-label--cryo":" zentara-piece-label--visiting"}`,children:G})})()]})})})})});RQA.displayName="ZentaraPlayerPiece";const GQA=he.memo(RQA),AAA={"crimson-dominion":Bz,"silver-pact":Ez,"azure-sovereignty":Qz,"golden-imperium":uz,"emerald-collective":dz,"void-enclave":hz},NzA=Object.assign({"../../assets/heroes/azure-sovereignty-t1.webp":R5,"../../assets/heroes/azure-sovereignty-t2.webp":G5,"../../assets/heroes/azure-sovereignty-t3.webp":b5,"../../assets/heroes/azure-sovereignty-t4.webp":U5,"../../assets/heroes/azure-sovereignty-t5.webp":v5,"../../assets/heroes/azure-sovereignty-t6.webp":K5,"../../assets/heroes/crimson-dominion-t1.webp":F5,"../../assets/heroes/crimson-dominion-t2.webp":_5,"../../assets/heroes/crimson-dominion-t3.webp":J5,"../../assets/heroes/crimson-dominion-t4.webp":L5,"../../assets/heroes/crimson-dominion-t5.webp":x5,"../../assets/heroes/crimson-dominion-t6.webp":T5,"../../assets/heroes/emerald-collective-t1.webp":q5,"../../assets/heroes/emerald-collective-t2.webp":Y5,"../../assets/heroes/emerald-collective-t3.webp":H5,"../../assets/heroes/emerald-collective-t4.webp":O5,"../../assets/heroes/emerald-collective-t5.webp":P5,"../../assets/heroes/emerald-collective-t6.webp":j5,"../../assets/heroes/golden-imperium-t1.webp":z5,"../../assets/heroes/golden-imperium-t2.webp":Z5,"../../assets/heroes/golden-imperium-t3.webp":W5,"../../assets/heroes/golden-imperium-t4.webp":V5,"../../assets/heroes/golden-imperium-t5.webp":X5,"../../assets/heroes/golden-imperium-t6.webp":$5,"../../assets/heroes/silver-pact-t1.webp":Az,"../../assets/heroes/silver-pact-t2.webp":ez,"../../assets/heroes/silver-pact-t3.webp":tz,"../../assets/heroes/silver-pact-t4.webp":iz,"../../assets/heroes/silver-pact-t5.webp":nz,"../../assets/heroes/silver-pact-t6.webp":gz,"../../assets/heroes/void-enclave-t1.webp":oz,"../../assets/heroes/void-enclave-t2.webp":sz,"../../assets/heroes/void-enclave-t3.webp":rz,"../../assets/heroes/void-enclave-t4.webp":az,"../../assets/heroes/void-enclave-t5.webp":Iz,"../../assets/heroes/void-enclave-t6.webp":Cz}),lE={};for(const[e,A]of Object.entries(NzA)){const t=e.split("/").pop().replace(".webp","");lE[t]=A.default}const zu={"crimson-dominion":"#ff3a3a","silver-pact":"#b0c4de","azure-sovereignty":"#4488ff","golden-imperium":"#ffaa00","emerald-collective":"#39ff14","void-enclave":"#cc44ff"},RzA=["crimson-dominion","silver-pact","azure-sovereignty","golden-imperium","emerald-collective","void-enclave"],bQA=({taken:e=[],onSelect:A,heading:t,bestHeroForEmpire:i,onBack:n})=>{const[g,o]=E.useState(null),s=g&&i?i(g):null,r=s?ys[s.heroId]:null,a=r?mu(r.empire,r.tier):null,I=g?oB[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":`${oB[g].name} board piece`,children:C.jsx(GQA,{initialX:0,initialY:0,isCurrentPlayer:!0,shape:g,pickerPiece:!0,tier:(r==null?void 0:r.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:RzA.map(l=>{const B=oB[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:AAA[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:r&&lE[r.id]?lE[r.id]:AAA[g],alt:(r==null?void 0:r.name)??I.name,className:`zpp__portrait${r?"":" zpp__portrait--emblem"}`})}),C.jsxs("div",{className:"zpp__hero-info",children:[C.jsx("span",{className:"zpp__hero-label",children:r?"Equipped Hero":"Empire Fleet"}),C.jsx("span",{className:"zpp__hero-name",children:(r==null?void 0:r.name)??I.name}),C.jsx("span",{className:"zpp__hero-title",children:r?`${r.title} · ${SQA[r.tier]}`:I.motto}),a?C.jsxs("span",{className:"zpp__hero-stats",children:[C.jsxs("span",{children:["⚔ +",Math.round(a.attack*100),"%"]}),C.jsxs("span",{children:["🛡 +",Math.round(a.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 t3={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 r(m){return!!(m===""||m&&m.charCodeAt&&m.substr)}function a(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()),r(m)&&m.match("%v")?{pos:m,neg:m.replace("-","").replace("%v","-%v"),zero:m}:!m||!m.pos||!m.pos.match("%v")?r(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(a(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(a(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(a(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,T){if(a(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,T){return r(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})()})(t3,t3.exports);var GzA=t3.exports;const cB=gw(GzA),bzA=Object.assign({"../../assets/heroes/azure-sovereignty-t1.webp":R5,"../../assets/heroes/azure-sovereignty-t2.webp":G5,"../../assets/heroes/azure-sovereignty-t3.webp":b5,"../../assets/heroes/azure-sovereignty-t4.webp":U5,"../../assets/heroes/azure-sovereignty-t5.webp":v5,"../../assets/heroes/azure-sovereignty-t6.webp":K5,"../../assets/heroes/crimson-dominion-t1.webp":F5,"../../assets/heroes/crimson-dominion-t2.webp":_5,"../../assets/heroes/crimson-dominion-t3.webp":J5,"../../assets/heroes/crimson-dominion-t4.webp":L5,"../../assets/heroes/crimson-dominion-t5.webp":x5,"../../assets/heroes/crimson-dominion-t6.webp":T5,"../../assets/heroes/emerald-collective-t1.webp":q5,"../../assets/heroes/emerald-collective-t2.webp":Y5,"../../assets/heroes/emerald-collective-t3.webp":H5,"../../assets/heroes/emerald-collective-t4.webp":O5,"../../assets/heroes/emerald-collective-t5.webp":P5,"../../assets/heroes/emerald-collective-t6.webp":j5,"../../assets/heroes/golden-imperium-t1.webp":z5,"../../assets/heroes/golden-imperium-t2.webp":Z5,"../../assets/heroes/golden-imperium-t3.webp":W5,"../../assets/heroes/golden-imperium-t4.webp":V5,"../../assets/heroes/golden-imperium-t5.webp":X5,"../../assets/heroes/golden-imperium-t6.webp":$5,"../../assets/heroes/silver-pact-t1.webp":Az,"../../assets/heroes/silver-pact-t2.webp":ez,"../../assets/heroes/silver-pact-t3.webp":tz,"../../assets/heroes/silver-pact-t4.webp":iz,"../../assets/heroes/silver-pact-t5.webp":nz,"../../assets/heroes/silver-pact-t6.webp":gz,"../../assets/heroes/void-enclave-t1.webp":oz,"../../assets/heroes/void-enclave-t2.webp":sz,"../../assets/heroes/void-enclave-t3.webp":rz,"../../assets/heroes/void-enclave-t4.webp":az,"../../assets/heroes/void-enclave-t5.webp":Iz,"../../assets/heroes/void-enclave-t6.webp":Cz}),i3={};for(const[e,A]of Object.entries(bzA)){const t=e.split("/").pop().replace(".webp","");i3[t]=A.default}const UzA=["crimson-dominion","silver-pact","azure-sovereignty","golden-imperium","emerald-collective","void-enclave"],vzA={"crimson-dominion":"🐉","silver-pact":"🦅","azure-sovereignty":"🔱","golden-imperium":"👑","emerald-collective":"🌿","void-enclave":"👁️"},KzA={offense:"⚔ Offense",defense:"🛡 Defense",balanced:"⚖ Balanced"},FzA=({onClose:e})=>{const{roster:A,ownedIds:t,loading:i,buying:n,buy:g,HERO_TIER_STATS:o,getHeroModifiers:s}=lz(),{user:r,updateBalance:a}=en(),I=(r==null?void 0:r.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}),a(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:UzA.map(m=>{const D=oB[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:vzA[m]}),C.jsx("span",{className:"hero-shop__tab-name",children:D.name.replace("The ","")})]},m)})}),C.jsx("div",{className:"hero-shop__spec",children:KzA[wQA[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:[i3[m.id]&&C.jsx("img",{src:i3[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 _zA={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"]},JzA={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 LzA=_zA,xzA=JzA,TzA=(()=>{try{const e=ti.getPlatform();return e==="ios"||e==="android"}catch{return!1}})(),eAA="single_player_guest_id";function tAA(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 Lb=null;function Lf(){const{available:e,progress:A,applyNow:t,later:i}=QPA(),{membershipModalOpen:n,setMembershipModalOpen:g}=bR(),o=Ji(),{roomsList:s,loading:r,createRoom:a,getGameRoute:I,refreshRooms:c}=S8(),{pokerCreateRoom:l,getUserBalance:B}=So(),{logout:Q,user:h,refreshUser:d}=en(),{friends:p}=vd(),{getTotalFriendUnread:y}=jR(),m=E.useMemo(()=>y(p.map($A=>$A.id)),[y,p]),{refresh:D}=eEA();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),[T,v]=E.useState(!1),U="craps",x=(()=>{try{return(window==null?void 0:window.APP_TARGET)??""}catch{return""}})(),q=(U||x).toString().toLowerCase().trim(),z=q==="craps"?"craps":q==="poker"?"poker":q==="skills"?"skills":q==="zentara"?"zentara":q==="cee-lo"||q==="ceelo"?"cee-lo":null,[Z,eA]=E.useState(z??Lb??null),[aA,sA]=E.useState(!1),[pA,gA]=E.useState(!1),[yA,fA]=E.useState(!1),[RA,YA]=E.useState("wordsearch"),W=E.useRef(null),{info:$,error:L}=NB(),{clear:H}=Fa();E.useEffect(()=>{try{H()}catch{}},[H]),E.useEffect(()=>{z&&Z!==z&&eA(z)},[z,Z]),E.useEffect(()=>{(async()=>{try{const{Preferences:$A}=await li(async()=>{const{Preferences:vA}=await Promise.resolve().then(()=>Yc);return{Preferences:vA}},void 0),{value:nA}=await $A.get({key:"selectedSkillsGameMode"});(nA==="wordsearch"||nA==="anagrams"||nA==="trivia")&&YA(nA)}catch{}})()},[]),E.useEffect(()=>{if(!z){if(Lb){eA(Lb);return}(async()=>{try{const{Preferences:$A}=await li(async()=>{const{Preferences:vA}=await Promise.resolve().then(()=>Yc);return{Preferences:vA}},void 0),{value:nA}=await $A.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&&(Lb=Z,(async()=>{try{const{Preferences:$A}=await li(async()=>{const{Preferences:nA}=await Promise.resolve().then(()=>Yc);return{Preferences:nA}},void 0);await $A.set({key:"selectedGameMode",value:Z})}catch{}})())},[Z,z]),E.useEffect(()=>{z!=="zentara"&&kL({volume:.0125})},[z]),E.useEffect(()=>{const $A=()=>{window.scrollTo(0,0),document.body.scrollTop=0,document.documentElement.scrollTop=0;const FA=document.getElementById("root");FA&&(FA.scrollTop=0)};$A();const nA=requestAnimationFrame($A),vA=setTimeout($A,50);return()=>{cancelAnimationFrame(nA),clearTimeout(vA)}},[]);const P=E.useMemo(()=>{const $A=z??Z;if(!$A)return s;const nA=vA=>vA.filter(FA=>(FA.gameMode||"cee-lo")===$A);return{public:nA(s.public),private:nA(s.private)}},[s,z,Z]),tA=E.useRef(null),iA=E.useCallback(()=>{Xt("Light")},[]),oA=E.useCallback(()=>{try{Xl({volume:.5})}catch{}},[]),CA=E.useCallback(()=>{try{qn()}catch{}},[]),cA=E.useCallback($A=>{CA(),$A!==Z?(iA(),oA(),eA($A)):(iA(),oA())},[Z,iA,oA,CA]),_A=E.useRef(null),uA=E.useRef(null),[X,O]=E.useState(1),[lA,wA]=E.useState(null),xA=E.useCallback(()=>{const $A=uA.current,nA=_A.current;if(!$A||!nA)return;const vA=$A.style.transform;$A.style.transform="none";const FA=$A.scrollHeight,te=window.innerHeight;let bA=Math.min(1,te/FA);O(bA),wA(FA*bA),$A.style.transform=vA},[]);E.useLayoutEffect(()=>{xA()},[xA,Z]),E.useEffect(()=>{const $A=new ResizeObserver(()=>requestAnimationFrame(xA)),nA=uA.current;nA&&$A.observe(nA),window.addEventListener("resize",xA);const vA=setTimeout(xA,250),FA=setTimeout(xA,800);return()=>{$A.disconnect(),window.removeEventListener("resize",xA),clearTimeout(vA),clearTimeout(FA)}},[xA]);const HA=E.useCallback(()=>{o("/profile")},[o]),zA=E.useCallback(()=>{o("/messages")},[o]);E.useCallback(()=>{o("/settings")},[o]);const ne=E.useCallback(()=>{o("/add-chips")},[o]),ye=E.useCallback(()=>{o("/lobby")},[o]),Ee=E.useCallback(()=>{CA(),iA(),oA(),Q()},[Q,iA,oA,CA]),NA=async()=>{var $A;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(($A=nA.data)==null?void 0:$A.balance)=="number")return Number(nA.data.balance)}catch{}return null},QA=E.useCallback(async()=>{var $A,nA,vA;if(h!=null&&h.id)return!0;try{let FA=await Co().catch(()=>null);if(!FA){const bA=await fbA();if(!(bA!=null&&bA.ok)||!bA.token)return $("Please sign in from home to start a game.",{duration:3e3}),!1;FA=bA.token,await ef(FA);const De=(($A=bA==null?void 0:bA.user)==null?void 0:$A.id)||tAA(FA);if(De)try{(nA=window.sessionStorage)==null||nA.setItem(eAA,De)}catch{}}if(!FA)return $("Please sign in from home to start a game.",{duration:3e3}),!1;const te=tAA(FA);if(te)try{(vA=window.sessionStorage)==null||vA.setItem(eAA,te)}catch{}try{const bA=pw();if(bA){if(!bA.connected&&bA.active)try{bA.disconnect()}catch{}bA.auth={token:FA},bA.__authSig=`t:${FA}`,bA.__allowCookieAuth=!1,qr(bA,"HomeScreen:guest-single-player")}}catch{}return!0}catch(FA){return console.warn("[single-player] guest session failed",FA),$("Please sign in from home to start a game.",{duration:3e3}),!1}},[$,h==null?void 0:h.id]),PA=E.useCallback(async()=>{CA(),iA(),oA(),console.log(h);try{if((h==null?void 0:h.isGuest)===!0){v(!0);return}}catch{}if(Z==="poker")try{const $A=await NA();if($A!=null&&$A<1e3){sA(!0);return}}catch{}G(!0)},[CA,iA,oA,Z,h,d,g]),VA=E.useCallback(async()=>{console.log("[HomeScreen] handleOpenRooms called"),CA(),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 $A=await NA();if($A!=null&&$A<1e3){sA(!0);return}}catch{}console.log("[HomeScreen] Opening rooms modal"),c(),w(!0)},[CA,iA,oA,Z,h,d,g,c]),KA=E.useCallback(()=>{var nA;const $A=document.activeElement;(nA=$A==null?void 0:$A.blur)==null||nA.call($A)},[]);E.useCallback(()=>{KA(),VA()},[KA,VA]),E.useCallback(()=>{KA(),PA()},[KA,PA]);const{meId:Ie}=en(),DA=E.useCallback(async $A=>{var vA,FA,te;const nA=!!($A!=null&&$A.fromQuickMatch);if(CA(),!!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 De=await Wo(),jA=De.botDifficultyLevel&&De.botDifficultyLevel>=1&&De.botDifficultyLevel<=9?De.botDifficultyLevel:void 0;if((Z==="cee-lo"||Z==="craps"||Z==="poker")&&!await QA())return;switch(Z){case"poker":bA=await l({name:"Single Player Room",singlePlayer:!0,botLevel:jA});break;case"cee-lo":case"craps":bA=await a({singlePlayer:!0,name:"Single Player Room",gameMode:Z,botLevel:jA});break;case"skills":o(`/skills/play?mode=${RA}`);return;case"zentara":o(`/zentara/match/${crypto.randomUUID()}${nA?"?qm=1":""}`);return;default:bA=await a({singlePlayer:!0,name:"Single Player Room"});break}try{window.location.search.includes("e2e=1")&&(window.__handleCreateSingleRes=bA)}catch{}const me=(bA==null?void 0:bA.room)??((vA=bA==null?void 0:bA.roomsList)==null?void 0:vA.room)??((FA=bA==null?void 0:bA.data)==null?void 0:FA.room)??null,le=(()=>{var WA;try{return window.location.search.includes("e2e=1")||window.__E2E===!0||((WA=window.sessionStorage)==null?void 0:WA.getItem("e2e"))==="1"}catch{return!1}})(),qA=(me==null?void 0:me.roomId)??(me==null?void 0:me.id)??(bA==null?void 0:bA.roomId)??((te=bA==null?void 0:bA.data)==null?void 0:te.roomId);if(qA&&me){W.current&&(clearTimeout(W.current),W.current=null);try{window.__PRESEEDED_ROOM=me}catch{}const WA=le?"?e2e=1":"",Se=I(Z,qA)+WA;console.log(Se,"roomPath",Z),o(Se)}else if(bA!=null&&bA.error){const WA=(()=>{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}})(),Se=String(bA.error||"");if(!WA&&/insufficient|minimum buy-in/i.test(Se)){sA(!0);return}}}catch(bA){console.warn(bA);const De=(()=>{var jA;try{return window.location.search.includes("e2e=1")||window.__E2E===!0||((jA=window.sessionStorage)==null?void 0:jA.getItem("e2e"))==="1"}catch{return!1}})();if(De){const jA=`e2e-${Math.random().toString(36).slice(2,8)}`;try{window.__handleCreateSingleRes={ok:!0,roomId:jA}}catch{}const me=De?"&e2e=1":"";o(Z==="poker"?`/poker/room/${jA}?m=${Z}${me}`:`/room/${jA}?m=${Z}${me}`)}else{const jA=String((bA==null?void 0:bA.message)??bA??"");/insufficient|minimum buy-in/i.test(jA)?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)}}},[CA,a,iA,oA,o,K,Z,Ie,$,RA,l,I,QA]),IA=E.useCallback($A=>()=>{CA(),iA(),oA(),$A()},[CA,iA,oA]);h==null||h.membershipTier;const EA=!!h,j=(()=>{try{return(h==null?void 0:h.isGuest)===!0}catch{return!1}})(),dA=E.useMemo(()=>{const $A=[{key:"chips",label:"Shop",onClick:IA(ne)}];return EA&&!j&&($A.unshift({key:"profile",label:"Profile",onClick:IA(HA)}),$A.splice(1,0,{key:"messages",label:"Messages",onClick:IA(zA),badge:m}),$A.push({key:"logout",label:"Log Out",onClick:IA(Ee)})),$A},[IA,HA,zA,ne,Ee,EA,j,m]),[hA,UA]=E.useState(!1),[TA,se]=E.useState(!1),Ne=E.useCallback(async $A=>{const nA=$A==="google"?UA:se;nA(!0);try{try{await AcA("");const vA=gr();await fetch(`${vA}/api/auth/clear`,{method:"POST",credentials:"include"}).catch(()=>{})}catch{}if(TzA){const vA=$A==="apple"?await fm.signInWithAppleNative():await fm.signInWithGoogleNative(),FA=gr(),te=await fetch(`${FA}/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(!te.ok)throw new Error("Native verify failed");const bA=await te.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 pbA($A)}catch(vA){console.warn("[home-auth]",$A,(vA==null?void 0:vA.message)??vA),L("Sign-in failed. Please try again.")}finally{nA(!1)}},[d,L]),[Ke,At]=E.useState(!1);E.useEffect(()=>{(z??Z)==="zentara"&&At(J8A())},[z,Z]);const ni=E.useCallback(()=>{const $A=DQA();$A&&o(`/zentara/match/${$A.matchId}`)},[o]),Ge=E.useCallback($A=>{$A.stopPropagation(),CA(),iA(),oA(),_(nA=>!nA)},[CA,iA,oA]),st=E.useCallback(()=>_(!1),[]),Rt=E.useCallback(()=>G(!1),[]),Et=E.useCallback(()=>w(!1),[]),_t=E.useCallback(()=>g(!1),[g]),[vt,xt]=E.useState(!1),ee=E.useCallback(()=>{CA(),iA(),oA(),xt(!0)},[CA,iA,oA]),Oe=E.useCallback(()=>xt(!1),[]),[We,pt]=E.useState(!1),kA=E.useCallback(()=>{CA(),iA(),oA(),pt(!0)},[CA,iA,oA]),oe=E.useCallback(()=>pt(!1),[]),ae=z==="zentara"?"theme-zentara":z==="skills"?"theme-skills":"theme-casino";return C.jsxs("div",{className:`HomeScreen ${ae} home-fixed-root`,children:[C.jsx(Zr,{className:"page-home-screen"}),C.jsx(dPA,{}),C.jsx(DPA,{}),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:ee,role:"button",children:[C.jsx("img",{src:mPA,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(aEA,{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:Ge,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(PvA,{anchorRef:tA,open:b,onClose:st,items:dA})]}),C.jsx("div",{ref:_A,className:`home-fit-shell ${ae}`,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(qzA,{onPlay:()=>DA(),playDisabled:!Z||K}),!z&&C.jsx(E8A,{selectedMode:z??Z,onSelectMode:z?void 0:cA,interval:z?0:4e3}),z&&C.jsx(uQA,{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:$A,label:nA})=>C.jsx("button",{className:RA===$A?"active":"",onClick:async()=>{iA(),oA(),YA($A);try{const{Preferences:vA}=await li(async()=>{const{Preferences:FA}=await Promise.resolve().then(()=>Yc);return{Preferences:FA}},void 0);await vA.set({key:"selectedSkillsGameMode",value:$A})}catch{}},children:nA},$A))}),C.jsxs("section",{className:"home-cta buttonRow","aria-label":"Actions",children:[(!EA||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:()=>Ne("google"),disabled:hA||TA,"aria-label":"Continue with Google",children:[C.jsx(Cd,{icon:LzA}),C.jsx("span",{children:"Google"})]}),C.jsxs("button",{className:"promo-oauth-btn promo-oauth-btn--apple",onClick:()=>Ne("apple"),disabled:hA||TA,"aria-label":"Continue with Apple",children:[C.jsx(Cd,{icon:xzA}),C.jsx("span",{children:"Apple"})]})]})]}),C.jsx("div",{className:"cta-spotlight","aria-hidden":!0}),Ke&&(z??Z)==="zentara"&&C.jsx("button",{className:"btn gold-fill cta-btn primaryButton",onClick:ni,"aria-label":"Continue Game",children:"Continue Game"}),C.jsx("button",{id:"btn-single-player",className:`btn ${Ke&&(z??Z)==="zentara"?"gold-outline":"gold-fill"} cta-btn primaryButton`,onClick:()=>DA(),disabled:!Z||K,"aria-label":Ke&&(z??Z)==="zentara"?"New Game":"Single Player",children:Ke&&(z??Z)==="zentara"?"New Game":"Single Player"}),z==="zentara"?C.jsxs(C.Fragment,{children:[EA&&!j&&C.jsx(V$,{gameMode:z??Z,disabled:!Z||K,onFallbackToSinglePlayer:()=>DA({fromQuickMatch:!0})}),EA&&!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:[EA&&!j&&C.jsx(V$,{gameMode:z??Z,disabled:!Z||K,onFallbackToSinglePlayer:()=>DA({fromQuickMatch:!0})}),EA&&!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(HvA,{open:N,onClose:Rt,gameMode:Z??"cee-lo"}),C.jsx(OvA,{open:M,onClose:Et,isPrivate:S,setIsPrivate:k,roomsList:P,onJoinClick:c,loading:r}),C.jsx(AEA,{open:n,onClose:_t,planId:h==null?void 0:h.membershipTier}),C.jsx(sHA,{open:vt,onClose:Oe,defaultMode:z??void 0}),C.jsx(IHA,{open:We,onClose:oe}),C.jsx(CHA,{open:T,onClose:()=>v(!1),onGoLogin:()=>ye(),title:"Login Required",message:C.jsx(C.Fragment,{children:"Please log in to access Settings and Multiplayer."})}),C.jsx(uPA,{available:e,progress:A,applyNow:t,later:i}),yA&&C.jsx(FzA,{onClose:()=>fA(!1)}),C.jsx(Jp,{})]})}function qzA({onPlay:e,playDisabled:A}){const{data:t,claiming:i,claim:n,refresh:g}=oHA();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:r,reward:a,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 +${a.toLocaleString()} coins!`:C.jsxs(C.Fragment,{children:[o," — ",C.jsxs("strong",{children:["+",a.toLocaleString()]})," coins"]})})]}),!c&&C.jsx("span",{className:"daily-challenge-go","aria-hidden":!0,children:I?i?"…":"💰":`${r}/${s}`})]})}function xf(){const{user:e,loading:A,initialized:t,refreshUser:i}=en(),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(Fg,{to:"/lobby",replace:!0}):C.jsx(YCA,{})}var iAA={};function YzA(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 HzA=Object.defineProperty,OzA=(e,A,t)=>A in e?HzA(e,A,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[A]=t,nAA=(e,A,t)=>OzA(e,typeof A!="symbol"?A+"":A,t);let Ua=class{constructor(){nAA(this,"_locking"),nAA(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 Jo(e,A){if(!e)throw new Error(A)}const PzA=34028234663852886e22,jzA=-34028234663852886e22,zzA=4294967295,ZzA=2147483647,WzA=-2147483648;function BK(e){if(typeof e!="number")throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>ZzA||e<WzA)throw new Error("invalid int 32: "+e)}function n3(e){if(typeof e!="number")throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>zzA||e<0)throw new Error("invalid uint 32: "+e)}function UQA(e){if(typeof e!="number")throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>PzA||e<jzA))throw new Error("invalid float 32: "+e)}const vQA=Symbol("@bufbuild/protobuf/enum-type");function VzA(e){const A=e[vQA];return Jo(A,"missing enum type on enum object"),A}function KQA(e,A,t,i){e[vQA]=FQA(A,t.map(n=>({no:n.no,name:n.name,localName:e[n.no]})))}function FQA(e,A,t){const i=Object.create(null),n=Object.create(null),g=[];for(const o of A){const s=_QA(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 XzA(e,A,t){const i={};for(const n of A){const g=_QA(n);i[g.localName]=g.no,i[g.no]=g.localName}return KQA(i,e,A),i}function _QA(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class pz{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 $zA(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 pz),Object.assign(o,{runtime:e,typeName:A,fields:e.util.newFieldList(t),fromBinary(s,r){return new o().fromBinary(s,r)},fromJson(s,r){return new o().fromJson(s,r)},fromJsonString(s,r){return new o().fromJsonString(s,r)},equals(s,r){return e.util.equals(o,s,r)}}),o}function AZA(){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 P2(e,A,t){for(let g=0;g<28;g=g+7){const o=e>>>g,s=!(!(o>>>7)&&A==0),r=(s?o|128:o)&255;if(t.push(r),!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),r=(s?o|128:o)&255;if(t.push(r),!s)return}t.push(A>>>31&1)}}const EK=4294967296;function gAA(e){const A=e[0]==="-";A&&(e=e.slice(1));const t=1e6;let i=0,n=0;function g(o,s){const r=Number(e.slice(o,s));n*=t,i=i*t+r,i>=EK&&(n=n+(i/EK|0),i=i%EK)}return g(-24,-18),g(-18,-12),g(-12,-6),g(-6),A?LQA(i,n):fz(i,n)}function eZA(e,A){let t=fz(e,A);const i=t.hi&2147483648;i&&(t=LQA(t.lo,t.hi));const n=JQA(t.lo,t.hi);return i?"-"+n:n}function JQA(e,A){if({lo:e,hi:A}=tZA(e,A),A<=2097151)return String(EK*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 r=1e7;return g>=r&&(o+=Math.floor(g/r),g%=r),o>=r&&(s+=Math.floor(o/r),o%=r),s.toString()+oAA(o)+oAA(g)}function tZA(e,A){return{lo:e>>>0,hi:A>>>0}}function fz(e,A){return{lo:e|0,hi:A|0}}function LQA(e,A){return A=~A,e?e=~e+1:A+=1,fz(e,A)}const oAA=e=>{const A=String(e);return"0000000".slice(A.length)+A};function sAA(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 iZA(){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 nZA(){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 iAA!="object"||iAA.BUF_BIGINT_DISABLE!=="1")){const n=BigInt("-9223372036854775808"),g=BigInt("9223372036854775807"),o=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(r){const a=typeof r=="bigint"?r:BigInt(r);if(a>g||a<n)throw new Error("int64 invalid: ".concat(r));return a},uParse(r){const a=typeof r=="bigint"?r:BigInt(r);if(a>s||a<o)throw new Error("uint64 invalid: ".concat(r));return a},enc(r){return e.setBigInt64(0,this.parse(r),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(r){return e.setBigInt64(0,this.uParse(r),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(r,a){return e.setInt32(0,r,!0),e.setInt32(4,a,!0),e.getBigInt64(0,!0)},uDec(r,a){return e.setInt32(0,r,!0),e.setInt32(4,a,!0),e.getBigUint64(0,!0)}}}const t=n=>Jo(/^-?[0-9]+$/.test(n),"int64 invalid: ".concat(n)),i=n=>Jo(/^[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),gAA(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),i(n),gAA(n)},dec(n,g){return eZA(n,g)},uDec(n,g){return JQA(n,g)}}}const ro=nZA();var Bt;(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"})(Bt||(Bt={}));var cd;(function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"})(cd||(cd={}));function bQ(e,A,t){if(A===t)return!0;if(e==Bt.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 Bt.UINT64:case Bt.FIXED64:case Bt.INT64:case Bt.SFIXED64:case Bt.SINT64:return A==t}return!1}function GS(e,A){switch(e){case Bt.BOOL:return!1;case Bt.UINT64:case Bt.FIXED64:case Bt.INT64:case Bt.SFIXED64:case Bt.SINT64:return A==0?ro.zero:"0";case Bt.DOUBLE:case Bt.FLOAT:return 0;case Bt.BYTES:return new Uint8Array(0);case Bt.STRING:return"";default:return 0}}function xQA(e,A){switch(e){case Bt.BOOL:return A===!1;case Bt.STRING:return A==="";case Bt.BYTES:return A instanceof Uint8Array&&!A.byteLength;default:return A==0}}var jo;(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"})(jo||(jo={}));class gZA{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(n3(A);A>127;)this.buf.push(A&127|128),A=A>>>7;return this.buf.push(A),this}int32(A){return BK(A),sAA(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){UQA(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){n3(A);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,A,!0),this.raw(t)}sfixed32(A){BK(A);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,A,!0),this.raw(t)}sint32(A){return BK(A),A=(A<<1^A>>31)>>>0,sAA(A,this.buf),this}sfixed64(A){let t=new Uint8Array(8),i=new DataView(t.buffer),n=ro.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=ro.uEnc(A);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(A){let t=ro.enc(A);return P2(t.lo,t.hi,this.buf),this}sint64(A){let t=ro.enc(A),i=t.hi>>31,n=t.lo<<1^i,g=(t.hi<<1|t.lo>>>31)^i;return P2(n,g,this.buf),this}uint64(A){let t=ro.uEnc(A);return P2(t.lo,t.hi,this.buf),this}}class oZA{constructor(A,t){this.varint64=AZA,this.uint32=iZA,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 jo.Varint:for(;this.buf[this.pos++]&128;);break;case jo.Bit64:this.pos+=4;case jo.Bit32:this.pos+=4;break;case jo.LengthDelimited:let n=this.uint32();this.pos+=n;break;case jo.StartGroup:for(;;){const[g,o]=this.tag();if(o===jo.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 ro.dec(...this.varint64())}uint64(){return ro.uDec(...this.varint64())}sint64(){let[A,t]=this.varint64(),i=-(A&1);return A=(A>>>1|(t&1)<<31)^i,t=t>>>1^i,ro.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 ro.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ro.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 sZA(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 TQA(e){const A=e.field.localName,t=Object.create(null);return t[A]=rZA(e),[t,()=>t[A]]}function rZA(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 GS(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 aZA(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 dE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),VL=[];for(let e=0;e<dE.length;e++)VL[dE[e].charCodeAt(0)]=e;VL[45]=dE.indexOf("+");VL[95]=dE.indexOf("/");const qQA={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=VL[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+=dE[i>>2],n=(i&3)<<4,t=1;break;case 1:A+=dE[n|i>>4],n=(i&15)<<2,t=2;break;case 2:A+=dE[n|i>>6],A+=dE[i&63],t=0;break}return t&&(A+=dE[n],A+="=",t==1&&(A+="=")),A}};function IZA(e,A,t){HQA(A,e);const i=A.runtime.bin.makeReadOptions(t),n=aZA(e.getType().runtime.bin.listUnknownFields(e),A.field),[g,o]=TQA(A);for(const s of n)A.runtime.bin.readField(g,i.readerFactory(s.data),A.field,s.wireType,i);return o()}function CZA(e,A,t,i){HQA(A,e);const n=A.runtime.bin.makeReadOptions(i),g=A.runtime.bin.makeWriteOptions(i);if(YQA(e,A)){const a=e.getType().runtime.bin.listUnknownFields(e).filter(I=>I.no!=A.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(const I of a)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 r=n.readerFactory(o.finish());for(;r.pos<r.len;){const[a,I]=r.tag(),c=r.skip(I,a);e.getType().runtime.bin.onUnknownField(e,a,I,c)}}function YQA(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 HQA(e,A){Jo(e.extendee.typeName==A.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function OQA(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:!xQA(e.T,A[t]);case"message":return A[t]!==void 0;case"map":return Object.keys(A[t]).length>0}}function rAA(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?GS(e.T,e.L):void 0;break;case"message":A[t]=void 0;break}}function hE(e,A){if(e===null||typeof e!="object"||!Object.getOwnPropertyNames(pz.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 PQA(e,A){return hE(A)||!e.fieldWrapper?A:e.fieldWrapper.wrapField(A)}Bt.DOUBLE,Bt.FLOAT,Bt.INT64,Bt.UINT64,Bt.INT32,Bt.UINT32,Bt.BOOL,Bt.STRING,Bt.BYTES;const aAA={ignoreUnknownFields:!1},IAA={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function cZA(e){return e?Object.assign(Object.assign({},aAA),e):aAA}function lZA(e){return e?Object.assign(Object.assign({},IAA),e):IAA}const e_=Symbol(),QK=Symbol();function BZA(){return{makeReadOptions:cZA,makeWriteOptions:lZA,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(Hl(A)));i=i??new e;const n=new Map,g=t.typeRegistry;for(const[o,s]of Object.entries(A)){const r=e.fields.findJsonName(o);if(r){if(r.oneof){if(s===null&&r.kind=="scalar")continue;const a=n.get(r.oneof);if(a!==void 0)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(r.oneof.name,'" present: "').concat(a,'", "').concat(o,'"'));n.set(r.oneof,o)}CAA(i,s,r,t,e)}else{let a=!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){a=!0;const[c,l]=TQA(I);CAA(c,s,I.field,t,I),CZA(i,I,l(),t)}}if(!a&&!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(!OQA(n,e)){if(n.req)throw"required field not set";if(!A.emitDefaultValues||!QZA(n))continue}const o=n.oneof?e[n.oneof.localName].value:e[n.localName],s=cAA(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&&YQA(e,s)){const r=IZA(e,s,A),a=cAA(s.field,r,A);a!==void 0&&(i[s.field.jsonName]=a)}}}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 CM(e,A,t??cd.BIGINT,!0)},writeScalar(e,A,t){if(A!==void 0&&(t||xQA(e,A)))return uK(e,A)},debug:Hl}}function Hl(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 CAA(e,A,t,i,n){let g=t.localName;if(t.repeated){if(Jo(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(Hl(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(Hl(s)));switch(t.kind){case"message":o.push(t.T.fromJson(s,i));break;case"enum":const r=j2(t.T,s,i.ignoreUnknownFields,!0);r!==QK&&o.push(r);break;case"scalar":try{o.push(CM(t.T,s,t.L,!0))}catch(a){let I="cannot decode field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Hl(s));throw a instanceof Error&&a.message.length>0&&(I+=": ".concat(a.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(Hl(A)));const o=e[g];for(const[s,r]of Object.entries(A)){if(r===null)throw new Error("cannot decode field ".concat(n.typeName,".").concat(t.name," from JSON: map value null"));let a;try{a=EZA(t.K,s)}catch(I){let c="cannot decode map key for field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Hl(A));throw I instanceof Error&&I.message.length>0&&(c+=": ".concat(I.message)),new Error(c)}switch(t.V.kind){case"message":o[a]=t.V.T.fromJson(r,i);break;case"enum":const I=j2(t.V.T,r,i.ignoreUnknownFields,!0);I!==QK&&(o[a]=I);break;case"scalar":try{o[a]=CM(t.V.T,r,cd.BIGINT,!0)}catch(c){let l="cannot decode map value for field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Hl(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];hE(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 r=j2(t.T,A,i.ignoreUnknownFields,!1);switch(r){case e_:rAA(t,e);break;case QK:break;default:e[g]=r;break}break;case"scalar":try{const a=CM(t.T,A,t.L,!1);switch(a){case e_:rAA(t,e);break;default:e[g]=a;break}}catch(a){let I="cannot decode field ".concat(n.typeName,".").concat(t.name," from JSON: ").concat(Hl(A));throw a instanceof Error&&a.message.length>0&&(I+=": ".concat(a.message)),new Error(I)}break}}function EZA(e,A){if(e===Bt.BOOL)switch(A){case"true":A=!0;break;case"false":A=!1;break}return CM(e,A,cd.BIGINT,!0).toString()}function CM(e,A,t,i){if(A===null)return i?GS(e,t):e_;switch(e){case Bt.DOUBLE:case Bt.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==Bt.FLOAT&&UQA(n),n;case Bt.INT32:case Bt.FIXED32:case Bt.SFIXED32:case Bt.SINT32:case Bt.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==Bt.UINT32||e==Bt.FIXED32?n3(g):BK(g),g;case Bt.INT64:case Bt.SFIXED64:case Bt.SINT64:if(typeof A!="number"&&typeof A!="string")break;const o=ro.parse(A);return t?o.toString():o;case Bt.FIXED64:case Bt.UINT64:if(typeof A!="number"&&typeof A!="string")break;const s=ro.uParse(A);return t?s.toString():s;case Bt.BOOL:if(typeof A!="boolean")break;return A;case Bt.STRING:if(typeof A!="string")break;try{encodeURIComponent(A)}catch{throw new Error("invalid UTF8")}return A;case Bt.BYTES:if(A==="")return new Uint8Array(0);if(typeof A!="string")break;return qQA.dec(A)}throw new Error}function j2(e,A,t,i){if(A===null)return e.typeName=="google.protobuf.NullValue"?0:i?e.values[0].no:e_;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 QK;break}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Hl(A)))}function QZA(e){return e.repeated||e.kind=="map"?!0:!(e.oneof||e.kind=="message"||e.opt||e.req)}function cAA(e,A,t){if(e.kind=="map"){Jo(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()]=uK(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()]=z2(g,s,t.enumAsInteger);break}return t.emitDefaultValues||n.length>0?i:void 0}if(e.repeated){Jo(Array.isArray(A));const i=[];switch(e.kind){case"scalar":for(let n=0;n<A.length;n++)i.push(uK(e.T,A[n]));break;case"enum":for(let n=0;n<A.length;n++)i.push(z2(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 uK(e.T,A);case"enum":return z2(e.T,A,t.enumAsInteger);case"message":return PQA(e.T,A).toJson(t)}}function z2(e,A,t){var i;if(Jo(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 uK(e,A){switch(e){case Bt.INT32:case Bt.SFIXED32:case Bt.SINT32:case Bt.FIXED32:case Bt.UINT32:return Jo(typeof A=="number"),A;case Bt.FLOAT:case Bt.DOUBLE:return Jo(typeof A=="number"),Number.isNaN(A)?"NaN":A===Number.POSITIVE_INFINITY?"Infinity":A===Number.NEGATIVE_INFINITY?"-Infinity":A;case Bt.STRING:return Jo(typeof A=="string"),A;case Bt.BOOL:return Jo(typeof A=="boolean"),A;case Bt.UINT64:case Bt.FIXED64:case Bt.INT64:case Bt.SFIXED64:case Bt.SINT64:return Jo(typeof A=="bigint"||typeof A=="string"||typeof A=="number"),A.toString();case Bt.BYTES:return Jo(A instanceof Uint8Array),qQA.enc(A)}}const jy=Symbol("@bufbuild/protobuf/unknown-fields"),lAA={readUnknownFields:!0,readerFactory:e=>new oZA(e)},BAA={writeUnknownFields:!0,writerFactory:()=>new gZA};function uZA(e){return e?Object.assign(Object.assign({},lAA),e):lAA}function dZA(e){return e?Object.assign(Object.assign({},BAA),e):BAA}function hZA(){return{makeReadOptions:uZA,makeWriteOptions:dZA,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,r;for(;A.pos<o&&([s,r]=A.tag(),!(n===!0&&r==jo.EndGroup));){const a=g.fields.find(s);if(!a){const I=A.skip(r,s);i.readUnknownFields&&this.onUnknownField(e,s,r,I);continue}EAA(e,A,a,r,i)}if(n&&(r!=jo.EndGroup||s!==t))throw new Error("invalid end group tag")},readField:EAA,writeMessage(e,A,t){const i=e.getType();for(const n of i.fields.byNumber()){if(!OQA(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];QAA(n,g,A,t)}return t.writeUnknownFields&&this.writeUnknownFields(e,A),A},writeField(e,A,t,i){A!==void 0&&QAA(e,A,t,i)}}}function EAA(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"?Bt.INT32:t.T;let r=t_;if(t.kind=="scalar"&&t.L>0&&(r=fZA),g){let l=e[o];if(i==jo.LengthDelimited&&s!=Bt.STRING&&s!=Bt.BYTES){let Q=A.uint32()+A.pos;for(;A.pos<Q;)l.push(r(A,s))}else l.push(r(A,s))}else e[o]=r(A,s);break;case"message":const a=t.T;g?e[o].push(dK(A,new a,n,t)):hE(e[o])?dK(A,e[o],n,t):(e[o]=dK(A,new a,n,t),a.fieldWrapper&&!t.oneof&&!t.repeated&&(e[o]=a.fieldWrapper.unwrapField(e[o])));break;case"map":let[I,c]=pZA(t,A,n);e[o][I]=c;break}}function dK(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 pZA(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=t_(A,e.K);break;case 2:switch(e.V.kind){case"scalar":o=t_(A,e.V.T);break;case"enum":o=A.int32();break;case"message":o=dK(A,new e.V.T,t,void 0);break}break}}if(g===void 0&&(g=GS(e.K,cd.BIGINT)),typeof g!="string"&&typeof g!="number"&&(g=g.toString()),o===void 0)switch(e.V.kind){case"scalar":o=GS(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 fZA(e,A){const t=t_(e,A);return typeof t=="bigint"?t.toString():t}function t_(e,A){switch(A){case Bt.STRING:return e.string();case Bt.BOOL:return e.bool();case Bt.DOUBLE:return e.double();case Bt.FLOAT:return e.float();case Bt.INT32:return e.int32();case Bt.INT64:return e.int64();case Bt.UINT64:return e.uint64();case Bt.FIXED64:return e.fixed64();case Bt.BYTES:return e.bytes();case Bt.FIXED32:return e.fixed32();case Bt.SFIXED32:return e.sfixed32();case Bt.SFIXED64:return e.sfixed64();case Bt.SINT64:return e.sint64();case Bt.UINT32:return e.uint32();case Bt.SINT32:return e.sint32()}}function QAA(e,A,t,i){Jo(A!==void 0);const n=e.repeated;switch(e.kind){case"scalar":case"enum":let g=e.kind=="enum"?Bt.INT32:e.T;if(n)if(Jo(Array.isArray(A)),e.packed)DZA(t,g,e.no,A);else for(const o of A)cM(t,g,e.no,o);else cM(t,g,e.no,A);break;case"message":if(n){Jo(Array.isArray(A));for(const o of A)uAA(t,i,e,o)}else uAA(t,i,e,A);break;case"map":Jo(typeof A=="object"&&A!=null);for(const[o,s]of Object.entries(A))yZA(t,i,e,o,s);break}}function yZA(e,A,t,i,n){e.tag(t.no,jo.LengthDelimited),e.fork();let g=i;switch(t.K){case Bt.INT32:case Bt.FIXED32:case Bt.UINT32:case Bt.SFIXED32:case Bt.SINT32:g=Number.parseInt(i);break;case Bt.BOOL:Jo(i=="true"||i=="false"),g=i=="true";break}switch(cM(e,t.K,1,g),t.V.kind){case"scalar":cM(e,t.V.T,2,n);break;case"enum":cM(e,Bt.INT32,2,n);break;case"message":Jo(n!==void 0),e.tag(2,jo.LengthDelimited).bytes(n.toBinary(A));break}e.join()}function uAA(e,A,t,i){const n=PQA(t.T,i);t.delimited?e.tag(t.no,jo.StartGroup).raw(n.toBinary(A)).tag(t.no,jo.EndGroup):e.tag(t.no,jo.LengthDelimited).bytes(n.toBinary(A))}function cM(e,A,t,i){Jo(i!==void 0);let[n,g]=jQA(A);e.tag(t,n)[g](i)}function DZA(e,A,t,i){if(!i.length)return;e.tag(t,jo.LengthDelimited).fork();let[,n]=jQA(A);for(let g=0;g<i.length;g++)e[n](i[g]);e.join()}function jQA(e){let A=jo.Varint;switch(e){case Bt.BYTES:case Bt.STRING:A=jo.LengthDelimited;break;case Bt.DOUBLE:case Bt.FIXED64:case Bt.SFIXED64:A=jo.Bit64;break;case Bt.FIXED32:case Bt.SFIXED32:case Bt.FLOAT:A=jo.Bit32;break}const t=Bt[e].toLowerCase();return[A,t]}function mZA(){return{setEnumType:KQA,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 r=i.findField(s);let a=o[n].value;r&&r.kind=="message"&&!hE(a,r.T)?a=new r.T(a):r&&r.kind==="scalar"&&r.T===Bt.BYTES&&(a=w0(a)),g[n]={case:s,value:a};break;case"scalar":case"enum":let I=o[n];i.T===Bt.BYTES&&(I=i.repeated?I.map(w0):w0(I)),g[n]=I;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===Bt.BYTES)for(const[B,Q]of Object.entries(o[n]))g[n][B]=w0(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=>hE(l,c)?l:new c(l));else{const l=o[n];c.fieldWrapper?c.typeName==="google.protobuf.BytesValue"?g[n]=w0(l):g[n]=l:g[n]=hE(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)=>bQ(i.T,o,g[s]));case"enum":return n.every((o,s)=>bQ(Bt.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&&!hE(o)&&(o=i.T.fieldWrapper.wrapField(o)),s!==void 0&&!hE(s)&&(s=i.T.fieldWrapper.wrapField(s))),i.T.equals(o,s);case"enum":return bQ(Bt.INT32,n,g);case"scalar":return bQ(i.T,n,g);case"oneof":if(n.case!==g.case)return!1;const r=i.findField(n.case);if(r===void 0)return!0;switch(r.kind){case"message":return r.T.equals(n.value,g.value);case"enum":return bQ(Bt.INT32,n.value,g.value);case"scalar":return bQ(r.T,n.value,g.value)}throw new Error("oneof cannot contain ".concat(r.kind));case"map":const a=Object.keys(n).concat(Object.keys(g));switch(i.V.kind){case"message":const I=i.V.T;return a.every(l=>I.equals(n[l],g[l]));case"enum":return a.every(l=>bQ(Bt.INT32,n[l],g[l]));case"scalar":const c=i.V.T;return a.every(l=>bQ(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(xb);else if(n.kind=="map"){o=i[n.localName];for(const[s,r]of Object.entries(g))o[s]=xb(r)}else n.kind=="oneof"?o=n.findField(g.case)?{case:g.case,value:xb(g.value)}:{case:void 0}:o=xb(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 xb(e){if(e===void 0)return e;if(hE(e))return e.clone();if(e instanceof Uint8Array){const A=new Uint8Array(e.byteLength);return A.set(e),A}return e}function w0(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function SZA(e,A,t){return{syntax:e,json:BZA(),bin:hZA(),util:Object.assign(Object.assign({},mZA()),{newFieldList:A,initFields:t}),makeMessageType(i,n,g){return $zA(this,i,n,g)},makeEnum:XzA,makeEnumType:FQA,getEnumType:VzA,makeExtension(i,n,g){return sZA(this,i,n,g)}}}class wZA{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 zQA(e,A){const t=ZQA(e);return A?t:bZA(GZA(t))}function kZA(e){return zQA(e,!1)}const MZA=ZQA;function ZQA(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 NZA=new Set(["constructor","toString","toJSON","valueOf"]),RZA=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),WQA=e=>"".concat(e,"$"),GZA=e=>RZA.has(e)?WQA(e):e,bZA=e=>NZA.has(e)?WQA(e):e;class UZA{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=kZA(A)}addField(A){Jo(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 vZA(e,A){var t,i,n,g,o,s;const r=[];let a;for(const I of typeof e=="function"?e():e){const c=I;if(c.localName=zQA(I.name,I.oneof!==void 0),c.jsonName=(t=I.jsonName)!==null&&t!==void 0?t:MZA(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!=Bt.BYTES&&I.T!=Bt.STRING),I.oneof!==void 0){const l=typeof I.oneof=="string"?I.oneof:I.oneof.name;(!a||a.name!=l)&&(a=new UZA(l)),c.oneof=a,a.addField(c)}r.push(c)}return r}const ve=SZA("proto3",e=>new wZA(e,A=>vZA(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]=GS(A.T,A.L);break}}});class Wa extends pz{constructor(A){super(),this.seconds=ro.zero,this.nanos=0,ve.util.initPartial(A,this)}fromJson(A,t){if(typeof A!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(ve.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=ro.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 Wa.fromDate(new Date)}static fromDate(A){const t=A.getTime();return new Wa({seconds:ro.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(A,t){return new Wa().fromBinary(A,t)}static fromJson(A,t){return new Wa().fromJson(A,t)}static fromJsonString(A,t){return new Wa().fromJsonString(A,t)}static equals(A,t){return ve.util.equals(Wa,A,t)}}Wa.runtime=ve;Wa.typeName="google.protobuf.Timestamp";Wa.fields=ve.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const KZA=ve.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Wa},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:FZA,repeated:!0},{no:5,name:"events",kind:"message",T:JZA,repeated:!0}]),FZA=ve.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:_ZA,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),_ZA=ve.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Wa},{no:3,name:"value",kind:"scalar",T:2}]),JZA=ve.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:Wa},{no:7,name:"normalized_end_timestamp",kind:"message",T:Wa,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),VQA=ve.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),xc=ve.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),ls=ve.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"}]),yz=ve.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),fk=ve.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),BN=ve.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Oc=ve.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=ve.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"}]),LZA=ve.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Vs=ve.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"}]),XL=ve.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:i_,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:IuA}]),i_=ve.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),xZA=ve.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:ve.getEnumType(ls),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=ve.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:ve.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:xZA},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:ve.getEnumType(EN)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:ve.getEnumType(Oc)},{no:18,name:"kind_details",kind:"enum",T:ve.getEnumType(TZA),repeated:!0}]),vm=ve.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),EN=ve.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"}]),TZA=ve.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),bs=ve.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),qZA=ve.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:ve.getEnumType(XQA)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),XD=ve.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:ve.getEnumType(xc)},{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:ve.getEnumType(ls)},{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:qZA,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:ve.getEnumType(bs)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:IuA},{no:19,name:"audio_features",kind:"enum",T:ve.getEnumType(Vs),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:ve.getEnumType(VQA)}]),Zu=ve.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:ve.getEnumType(yz)},{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}]),XQA=ve.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"}]),ya=ve.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:ve.getEnumType(Sn)},{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:Dz,oneof:"value"},{no:3,name:"speaker",kind:"message",T:YZA,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:tuA,oneof:"value"},{no:7,name:"transcription",kind:"message",T:HZA,oneof:"value"},{no:8,name:"metrics",kind:"message",T:KZA,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:n_,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:mz,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Sz,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:wz,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:g_,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:o_,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:s_,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:$QA,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Sn=ve.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),$QA=ve.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:ve.getEnumType(bs)},{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}]),AuA=ve.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Dz,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:n_,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:mz,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Sz,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:wz,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:g_,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:o_,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:s_,oneof:"value"}]),YZA=ve.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:euA,repeated:!0}]),euA=ve.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}]),Dz=ve.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}]),tuA=ve.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),HZA=ve.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:OZA,repeated:!0}]),OZA=ve.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}]),n_=ve.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}]),mz=ve.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}]),Sz=ve.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),wz=ve.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:iuA,oneof:"value"}]),iuA=ve.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}]),nuA=ve.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),guA=ve.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:ve.getEnumType(ouA)},{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}]),ouA=ve.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),suA=ve.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:ve.getEnumType(ruA)},{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}]),ruA=ve.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"}]),auA=ve.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:dAA},{no:2,name:"screen",kind:"message",T:dAA},{no:3,name:"resume_connection",kind:"enum",T:ve.getEnumType(BN)},{no:4,name:"disabled_codecs",kind:"message",T:PZA},{no:5,name:"force_relay",kind:"enum",T:ve.getEnumType(BN)}]),dAA=ve.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:ve.getEnumType(BN)}]),PZA=ve.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:i_,repeated:!0},{no:2,name:"publish",kind:"message",T:i_,repeated:!0}]),IuA=ve.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),g3=ve.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),CuA=ve.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:ve.getEnumType(g3)},{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"}),cuA=ve.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),g_=ve.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:ve.getEnumType(bs)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:CuA,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:cuA,oneof:"content_header"}],{localName:"DataStream_Header"}),o_=ve.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"}),s_=ve.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"}),jZA=ve.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),Tc=ve.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),o3=ve.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),zZA=ve.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),ZZA=ve.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:$L,oneof:"message"},{no:4,name:"add_track",kind:"message",T:QN,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ax,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ex,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:luA,oneof:"message"},{no:8,name:"leave",kind:"message",T:tx,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:EuA,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:duA,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Gz,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Jl,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Nz,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:fuA,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Mz,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:BuA,oneof:"message"}]),hAA=ve.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:WZA,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:$L,oneof:"message"},{no:5,name:"update",kind:"message",T:$ZA,oneof:"message"},{no:6,name:"track_published",kind:"message",T:kz,oneof:"message"},{no:8,name:"leave",kind:"message",T:tx,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ax,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:AWA,oneof:"message"},{no:11,name:"room_update",kind:"message",T:eWA,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:iWA,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:gWA,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:sWA,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:aWA,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:XZA,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:VZA,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:CWA,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:BWA,oneof:"message"},{no:22,name:"request_response",kind:"message",T:EWA,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:QWA,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:IWA,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:pWA,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:rWA,oneof:"message"}]),s3=ve.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:ve.getEnumType(XQA)}]),QN=ve.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:ve.getEnumType(xc)},{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:ve.getEnumType(ls)},{no:9,name:"layers",kind:"message",T:Zu,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:s3,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:ve.getEnumType(bs)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:ve.getEnumType(VQA)},{no:17,name:"audio_features",kind:"enum",T:ve.getEnumType(Vs),repeated:!0}]),$L=ve.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:ve.getEnumType(Tc)},{no:3,name:"final",kind:"scalar",T:8}]),Ax=ve.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),WZA=ve.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:XL},{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:QuA,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:auA},{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:guA},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:i_,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),VZA=ve.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:QuA,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:auA},{no:3,name:"server_info",kind:"message",T:guA},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),kz=ve.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:XD}]),XZA=ve.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ld=ve.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}}]),$ZA=ve.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:If,repeated:!0}]),ex=ve.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:nuA,repeated:!0}]),luA=ve.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:ve.getEnumType(yz)},{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}]),Mz=ve.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:ve.getEnumType(Vs),repeated:!0}]),BuA=ve.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}]),tx=ve.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:ve.getEnumType(Oc)},{no:3,name:"action",kind:"enum",T:ve.getEnumType(Km)},{no:4,name:"regions",kind:"message",T:cWA}]),Km=ve.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),EuA=ve.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Zu,repeated:!0}]),Nz=ve.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}]),QuA=ve.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}]),AWA=ve.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:euA,repeated:!0}]),eWA=ve.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:XL}]),tWA=ve.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:ve.getEnumType(fk)},{no:3,name:"score",kind:"scalar",T:2}]),iWA=ve.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:tWA,repeated:!0}]),nWA=ve.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:ve.getEnumType(o3)}]),gWA=ve.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:nWA,repeated:!0}]),Rz=ve.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:ve.getEnumType(yz)},{no:2,name:"enabled",kind:"scalar",T:8}]),oWA=ve.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Rz,repeated:!0}]),sWA=ve.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Rz,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:oWA,repeated:!0}]),rWA=ve.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:jZA,repeated:!0}]),uuA=ve.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}]),duA=ve.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:uuA,repeated:!0}]),aWA=ve.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}]),IWA=ve.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:XL},{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}]),Gz=ve.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:ld},{no:2,name:"subscription",kind:"message",T:ex},{no:3,name:"publish_tracks",kind:"message",T:kz,repeated:!0},{no:4,name:"data_channels",kind:"message",T:puA,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:huA,repeated:!0}]),huA=ve.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),puA=ve.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:ve.getEnumType(Tc)}]),Jl=ve.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:ve.getEnumType(zZA),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"}]),fuA=ve.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),CWA=ve.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),cWA=ve.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:lWA,repeated:!0}]),lWA=ve.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}]),BWA=ve.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:ve.getEnumType(LZA)}]),EWA=ve.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:ve.getEnumType(bz)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:$L,oneof:"request"},{no:5,name:"add_track",kind:"message",T:QN,oneof:"request"},{no:6,name:"mute",kind:"message",T:Ax,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Nz,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Mz,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:BuA,oneof:"request"}]),bz=ve.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"}]),QWA=ve.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),yuA=ve.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}]),uWA=ve.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:suA},{no:2,name:"connection_settings",kind:"message",T:yuA},{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:QN,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:ve.getEnumType(Ph)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Gz}]),dWA=ve.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:ve.getEnumType(hWA)},{no:2,name:"join_request",kind:"scalar",T:12}]),hWA=ve.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),pWA=ve.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function fWA(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var hK={exports:{}},yWA=hK.exports,pAA;function DWA(){return pAA||(pAA=1,function(e){(function(A,t){e.exports?e.exports=t():A.log=t()})(yWA,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 r(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function a(h){return h==="debug"&&(h="log"),typeof console===t?!1:h==="trace"&&i?r: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 a(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})}(hK)),hK.exports}var ix=DWA(),r3;(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"})(r3||(r3={}));var $c;(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"})($c||($c={}));let Cn=ix.getLogger("livekit");Object.values($c).map(e=>ix.getLogger(e));Cn.setDefaultLevel(r3.info);function AQ(e){const A=ix.getLogger(e);return A.setDefaultLevel(Cn.getLevel()),A}const mWA=ix.getLogger("lk-e2ee"),k0=7e3,SWA=[0,300,2*2*300,3*3*300,4*4*300,k0,k0,k0,k0,k0];class wWA{constructor(A){this._retryDelays=A!==void 0?[...A]:SWA}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 kWA(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{a(i.next(I))}catch(c){o(c)}}function r(I){try{a(i.throw(I))}catch(c){o(c)}}function a(I){I.done?g(I.value):n(I.value).then(s,r)}a((i=i.apply(e,A||[])).next())})}function fAA(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 pE(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 fAA=="function"?fAA(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,r){o=e[g](o),n(s,r,o.done,o.value)})}}function n(g,o,s,r){Promise.resolve(r).then(function(a){g({value:a,done:s})},o)}}var Tb={exports:{}},yAA;function MWA(){if(yAA)return Tb.exports;yAA=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)}Tb.exports=g,Tb.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 r(D){return D._maxListeners===void 0?g.defaultMaxListeners:D._maxListeners}g.prototype.getMaxListeners=function(){return r(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 a(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=r(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 a(this,S,k,!1)},g.prototype.on=g.prototype.addListener,g.prototype.prependListener=function(S,k){return a(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 Tb.exports}var GB=MWA();let DuA=!0,muA=!0;function yk(e,A,t){const i=e.match(A);return i&&i.length>=t&&parseFloat(i[t],10)}function Tf(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 r=a=>{const I=t(a);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,r),n.apply(this,[o,r])};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 r=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,r])},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 NWA(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 RWA(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(muA=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function SuA(){if(typeof window=="object"){if(DuA)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Uz(e,A){muA&&console.warn(e+" is deprecated, please use "+A+" instead.")}function GWA(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(yk(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)A.browser="chrome",A.version=parseInt(yk(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))A.browser="safari",A.version=parseInt(yk(t.userAgent,/AppleWebKit\/(\d+)\./,1)),A.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,A._safariVersion=yk(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return A.browser="Not a supported browser.",A;return A}function DAA(e){return Object.prototype.toString.call(e)==="[object Object]"}function wuA(e){return DAA(e)?Object.keys(e).reduce(function(A,t){const i=DAA(e[t]),n=i?wuA(e[t]):e[t],g=i&&!Object.keys(n).length;return n===void 0||g?A:Object.assign(A,{[t]:n})},{}):e}function a3(e,A,t){!A||t.has(A.id)||(t.set(A.id,A),Object.keys(A).forEach(i=>{i.endsWith("Id")?a3(e,e.get(A[i]),t):i.endsWith("Ids")&&A[i].forEach(n=>{a3(e,e.get(n),t)})}))}function mAA(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&&a3(e,s,n)})}),n}const SAA=SuA;function kuA(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 r={};return Object.keys(s).forEach(a=>{if(a==="require"||a==="advanced"||a==="mediaSource")return;const I=typeof s[a]=="object"?s[a]:{ideal:s[a]};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){r.optional=r.optional||[];let l={};typeof I.ideal=="number"?(l[c("min",a)]=I.ideal,r.optional.push(l),l={},l[c("max",a)]=I.ideal,r.optional.push(l)):(l[c("",a)]=I.ideal,r.optional.push(l))}I.exact!==void 0&&typeof I.exact!="number"?(r.mandatory=r.mandatory||{},r.mandatory[c("",a)]=I.exact):["min","max"].forEach(l=>{I[l]!==void 0&&(r.mandatory=r.mandatory||{},r.mandatory[c(l,a)]=I[l])})}),s.advanced&&(r.optional=(r.optional||[]).concat(s.advanced)),r},n=function(s,r){if(A.version>=61)return r(s);if(s=JSON.parse(JSON.stringify(s)),s&&typeof s.audio=="object"){const a=function(I,c,l){c in I&&!(l in I)&&(I[l]=I[c],delete I[c])};s=JSON.parse(JSON.stringify(s)),a(s.audio,"autoGainControl","googAutoGainControl"),a(s.audio,"noiseSuppression","googNoiseSuppression"),s.audio=i(s.audio)}if(s&&typeof s.video=="object"){let a=s.video.facingMode;a=a&&(typeof a=="object"?a:{ideal:a});const I=A.version<66;if(a&&(a.exact==="user"||a.exact==="environment"||a.ideal==="user"||a.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!I)){delete s.video.facingMode;let c;if(a.exact==="environment"||a.ideal==="environment"?c=["back","rear"]:(a.exact==="user"||a.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=a.exact?{exact:B.deviceId}:{ideal:B.deviceId}),s.video=i(s.video),SAA("chrome: "+JSON.stringify(s)),r(s)})}s.video=i(s.video)}return SAA("chrome: "+JSON.stringify(s)),r(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,r,a){n(s,I=>{t.webkitGetUserMedia(I,r,c=>{a&&a(g(c))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(r){return n(r,a=>s(a).then(I=>{if(a.audio&&!I.getAudioTracks().length||a.video&&!I.getVideoTracks().length)throw I.getTracks().forEach(c=>{c.stop()}),new DOMException("","NotFoundError");return I},I=>Promise.reject(g(I))))}}}function MuA(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function NuA(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 Tf(e,"track",A=>(A.transceiver||Object.defineProperty(A,"transceiver",{value:{receiver:A.receiver}}),A))}function RuA(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,r){let a=n.apply(this,arguments);return a||(a=A(this,s),this._senders.push(a)),a};const g=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(s){g.apply(this,arguments);const r=this._senders.indexOf(s);r!==-1&&this._senders.splice(r,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(r=>r.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 GuA(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=>mAA(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}),Tf(e,"track",i=>(i.receiver._pc=i.srcElement,i)),e.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(g=>mAA(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 buA(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 r=A.apply(this,arguments);return this._shimmedLocalStreams[s.id]?this._shimmedLocalStreams[s.id].indexOf(r)===-1&&this._shimmedLocalStreams[s.id].push(r):this._shimmedLocalStreams[s.id]=[s,r],r};const t=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(a=>{if(this.getSenders().find(c=>c.track===a))throw new DOMException("Track already exists.","InvalidAccessError")});const s=this.getSenders();t.apply(this,arguments);const r=this.getSenders().filter(a=>s.indexOf(a)===-1);this._shimmedLocalStreams[o.id]=[o].concat(r)};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 r=this._shimmedLocalStreams[s].indexOf(o);r!==-1&&this._shimmedLocalStreams[s].splice(r,1),this._shimmedLocalStreams[s].length===1&&delete this._shimmedLocalStreams[s]}),n.apply(this,arguments)}}function UuA(e,A){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&A.version>=65)return buA(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(a,I){let c=I.sdp;return Object.keys(a._reverseStreams||[]).forEach(l=>{const B=a._reverseStreams[l],Q=a._streams[B.id];c=c.replace(new RegExp(Q.id,"g"),B.id)}),new RTCSessionDescription({type:I.type,sdp:c})}function o(a,I){let c=I.sdp;return Object.keys(a._reverseStreams||[]).forEach(l=>{const B=a._reverseStreams[l],Q=a._streams[B.id];c=c.replace(new RegExp(B.id,"g"),Q.id)}),new RTCSessionDescription({type:I.type,sdp:c})}["createOffer","createAnswer"].forEach(function(a){const I=e.RTCPeerConnection.prototype[a],c={[a](){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[a]=c[a]});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 r=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const a=r.get.apply(this);return a.type===""?a:g(this,a)}}),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 I3(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 vuA(e,A){Tf(e,"negotiationneeded",t=>{const i=t.target;if(!((A.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var wAA=Object.freeze({__proto__:null,fixNegotiationNeeded:vuA,shimAddTrackRemoveTrack:UuA,shimAddTrackRemoveTrackWithNative:buA,shimGetSendersWithDtmf:RuA,shimGetUserMedia:kuA,shimMediaStream:MuA,shimOnTrack:NuA,shimPeerConnection:I3,shimSenderReceiverGetStats:GuA});function KuA(e,A){const t=e&&e.navigator,i=e&&e.MediaStreamTrack;if(t.getUserMedia=function(n,g,o){Uz("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,r){s in o&&!(r in o)&&(o[r]=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 bWA(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 FuA(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 C3(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(r=>{if(A.version<53&&!o)try{r.forEach(a=>{a.type=t[a.type]||a.type})}catch(a){if(a.name!=="TypeError")throw a;r.forEach((I,c)=>{r.set(c,Object.assign({},I,{type:t[I.type]||I.type}))})}return r}).then(o,s)}}function _uA(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 JuA(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}),Tf(e,"track",t=>(t.receiver._pc=t.srcElement,t)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function LuA(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(t){Uz("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function xuA(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function TuA(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 quA(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 YuA(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 HuA(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 kAA=Object.freeze({__proto__:null,shimAddTransceiver:TuA,shimCreateAnswer:HuA,shimCreateOffer:YuA,shimGetDisplayMedia:bWA,shimGetParameters:quA,shimGetUserMedia:KuA,shimOnTrack:FuA,shimPeerConnection:C3,shimRTCDataChannel:xuA,shimReceiverGetStats:JuA,shimRemoveStream:LuA,shimSenderGetStats:_uA});function OuA(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 PuA(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 juA(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(a,I){const c=arguments.length>=2?arguments[2]:arguments[0],l=t.apply(this,[c]);return I?(l.then(a,I),Promise.resolve()):l},A.createAnswer=function(a,I){const c=arguments.length>=2?arguments[2]:arguments[0],l=i.apply(this,[c]);return I?(l.then(a,I),Promise.resolve()):l};let s=function(r,a,I){const c=n.apply(this,[r]);return I?(c.then(a,I),Promise.resolve()):c};A.setLocalDescription=s,s=function(r,a,I){const c=g.apply(this,[r]);return I?(c.then(a,I),Promise.resolve()):c},A.setRemoteDescription=s,s=function(r,a,I){const c=o.apply(this,[r]);return I?(c.then(a,I),Promise.resolve()):c},A.addIceCandidate=s}function zuA(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(ZuA(n))}!A.getUserMedia&&A.mediaDevices&&A.mediaDevices.getUserMedia&&(A.getUserMedia=(function(i,n,g){A.mediaDevices.getUserMedia(i).then(n,g)}).bind(A))}function ZuA(e){return e&&e.video!==void 0?Object.assign({},e,{video:wuA(e.video)}):e}function WuA(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?(Uz("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 VuA(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 XuA(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 $uA(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var MAA=Object.freeze({__proto__:null,shimAudioContext:$uA,shimCallbacksAPI:juA,shimConstraints:ZuA,shimCreateOfferLegacy:XuA,shimGetUserMedia:zuA,shimLocalStreamsAPI:OuA,shimRTCIceServerUrls:WuA,shimRemoteStreamsAPI:PuA,shimTrackEventTransceiver:VuA}),Z2={exports:{}},NAA;function UWA(){return NAA||(NAA=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 r=g[s],a=A.matchPrefix(t,"a=rtpmap:"+r+" ")[0];if(a){const I=A.parseRtpMap(a),c=A.matchPrefix(t,"a=fmtp:"+r+" ");switch(I.parameters=c.length?A.parseFmtp(c[0]):{},I.rtcpFeedback=A.matchPrefix(t,"a=rtcp-fb:"+r+" ").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(r=>{s.rtcpFeedback.find(I=>I.type===r.type&&I.parameter===r.parameter)||s.rtcpFeedback.push(r)})}),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"),r=s.length>0&&s[0].ssrc;let a;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]===r&&(a=I[0][1]),n.codecs.forEach(l=>{if(l.name.toUpperCase()==="RTX"&&l.parameters.apt){let B={ssrc:r,codecPayloadType:parseInt(l.parameters.apt,10)};r&&a&&(B.rtx={ssrc:a}),i.push(B),g&&(B=JSON.parse(JSON.stringify(B)),B.fec={ssrc:r,mechanism:o?"red+ulpfec":"red"},i.push(B))}}),i.length===0&&r&&i.push({ssrc:r});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 r=s[0].substring(10).split(" ");return{port:parseInt(r[0],10),protocol:r[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}(Z2)),Z2.exports}var AdA=UWA(),Fm=fWA(AdA),vWA=YzA({__proto__:null,default:Fm},[AdA]);function pK(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,Tf(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function c3(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Tf(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 fK(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 r=Fm.splitSections(s.sdp);return r.shift(),r.some(a=>{const I=Fm.parseMLine(a);return I&&I.kind==="application"&&I.protocol.indexOf("SCTP")!==-1})},i=function(s){const r=s.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(r===null||r.length<2)return-1;const a=parseInt(r[1],10);return a!==a?-1:a},n=function(s){let r=65536;return A.browser==="firefox"&&(A.version<57?s===-1?r=16384:r=2147483637:A.version<60?r=A.version===57?65535:65536:r=2147483637),r},g=function(s,r){let a=65536;A.browser==="firefox"&&A.version===57&&(a=65535);const I=Fm.matchPrefix(s.sdp,"a=max-message-size:");return I.length>0?a=parseInt(I[0].substring(19),10):A.browser==="firefox"&&r!==-1&&(a=2147483637),a},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,A.browser==="chrome"&&A.version>=76){const{sdpSemantics:r}=this.getConfiguration();r==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const r=i(arguments[0]),a=n(r),I=g(arguments[0],r);let c;a===0&&I===0?c=Number.POSITIVE_INFINITY:a===0||I===0?c=Math.max(a,I):c=Math.min(a,I);const l={};Object.defineProperty(l,"maxMessageSize",{get(){return c}}),this._sctp=l}return o.apply(this,arguments)}}function yK(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],r=s.length||s.size||s.byteLength;if(i.readyState==="open"&&n.sctp&&r>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},Tf(e,"datachannel",i=>(A(i.channel,i.target),i))}function l3(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 B3(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 DK(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 mK(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 KWA=Object.freeze({__proto__:null,removeExtmapAllowMixed:B3,shimAddIceCandidateNullOrEmpty:DK,shimConnectionState:l3,shimMaxMessageSize:fK,shimParameterlessSetLocalDescription:mK,shimRTCIceCandidate:pK,shimRTCIceCandidateRelayProtocol:c3,shimSendThrowTypeError:yK});function FWA(){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=SuA,i=GWA(e),n={browserDetails:i,commonShim:KWA,extractVersion:yk,disableLog:NWA,disableWarnings:RWA,sdp:vWA};switch(i.browser){case"chrome":if(!wAA||!I3||!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=wAA,DK(e,i),mK(e),kuA(e,i),MuA(e),I3(e,i),NuA(e),UuA(e,i),RuA(e),GuA(e),vuA(e,i),pK(e),c3(e),l3(e),fK(e,i),yK(e),B3(e,i);break;case"firefox":if(!kAA||!C3||!A.shimFirefox)return t("Firefox shim is not included in this adapter release."),n;t("adapter.js shimming firefox."),n.browserShim=kAA,DK(e,i),mK(e),KuA(e,i),C3(e,i),FuA(e),LuA(e),_uA(e),JuA(e),xuA(e),TuA(e),quA(e),YuA(e),HuA(e),pK(e),l3(e),fK(e,i),yK(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,DK(e,i),mK(e),WuA(e),XuA(e),juA(e),OuA(e),PuA(e),VuA(e),zuA(e),$uA(e),pK(e),c3(e),fK(e,i),yK(e),B3(e,i);break;default:t("Unsupported browser!");break}return n}FWA({window:typeof window>"u"?void 0:window});class AI 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 _WA=/version\/(\d+(\.?_?\d+)+)/i;let W2;function sI(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(W2===void 0||A){const i=JWA.find(n=>{let{test:g}=n;return g.test(t)});W2=i==null?void 0:i.describe(t)}return W2}const JWA=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:"Firefox",version:SK(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:V2(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:"Chrome",version:SK(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:V2(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:"Safari",version:SK(_WA,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:V2(e)}}}];function SK(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 V2(e){return e.includes("mac os")?SK(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}var LWA="2.17.0";const xWA=LWA,TWA=16;class bB extends Error{constructor(A,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=A}}var vg;(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"})(vg||(vg={}));class wi extends bB{constructor(A,t,i,n){super(1,A),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=vg[t]}static notAllowed(A,t,i){return new wi(A,vg.NotAllowed,t,i)}static timeout(A){return new wi(A,vg.Timeout)}static leaveRequest(A,t){return new wi(A,vg.LeaveRequest,void 0,t)}static internal(A,t){return new wi(A,vg.InternalError,void 0,t)}static cancelled(A){return new wi(A,vg.Cancelled)}static serverUnreachable(A,t){return new wi(A,vg.ServerUnreachable,t)}static websocket(A,t,i){return new wi(A,vg.WebSocket,t,i)}static serviceNotFound(A,t){return new wi(A,vg.ServiceNotFound,void 0,t)}}class vz extends bB{constructor(A){super(21,A??"device is unsupported"),this.name="DeviceUnsupportedError"}}class fE extends bB{constructor(A){super(20,A??"track is invalid"),this.name="TrackInvalidError"}}class qWA extends bB{constructor(A){super(10,A??"unsupported server"),this.name="UnsupportedServer"}}class Po extends bB{constructor(A){super(12,A??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class _m extends bB{constructor(A){super(13,A??"unable to negotiate"),this.name="NegotiationError"}}class RAA extends bB{constructor(A,t){super(15,A),this.name="PublishTrackError",this.status=t}}class GAA extends bB{constructor(A,t){super(15,A),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:bz[t]}}var da;(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"})(da||(da={}));class MC extends bB{constructor(A,t){super(16,A),this.name="DataStreamError",this.reason=t,this.reasonName=da[t]}}class zy extends bB{constructor(A){super(18,A),this.name="SignalReconnectError"}}var r_;(function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"})(r_||(r_={}));(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})(r_||(r_={}));class mr{}mr.setTimeout=function(){return setTimeout(...arguments)};mr.setInterval=function(){return setInterval(...arguments)};mr.clearTimeout=function(){return clearTimeout(...arguments)};mr.clearInterval=function(){return clearInterval(...arguments)};var ut;(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"})(ut||(ut={}));var Lt;(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"})(Lt||(Lt={}));var Ut;(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"})(Ut||(Ut={}));var kt;(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"})(kt||(kt={}));function YWA(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 Mg{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 HWA=["vp8","h264"],OWA=["vp8","h264","vp9","av1","h265"];function PWA(e){return!!HWA.find(A=>A===e)}const jWA=PWA;var bAA;(function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"})(bAA||(bAA={}));var E3;(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}})(E3||(E3={}));const bS={h90:new Mg(160,90,9e4,20),h180:new Mg(320,180,16e4,20),h216:new Mg(384,216,18e4,20),h360:new Mg(640,360,45e4,20),h540:new Mg(960,540,8e5,25),h720:new Mg(1280,720,17e5,30),h1080:new Mg(1920,1080,3e6,30),h1440:new Mg(2560,1440,5e6,30),h2160:new Mg(3840,2160,8e6,30)},Q3={h120:new Mg(160,120,7e4,20),h180:new Mg(240,180,125e3,20),h240:new Mg(320,240,14e4,20),h360:new Mg(480,360,33e4,20),h480:new Mg(640,480,5e5,20),h540:new Mg(720,540,6e5,25),h720:new Mg(960,720,13e5,30),h1080:new Mg(1440,1080,23e5,30),h1440:new Mg(1920,1440,38e5,30)},Kz={h360fps3:new Mg(640,360,2e5,3,"medium"),h360fps15:new Mg(640,360,4e5,15,"medium"),h720fps5:new Mg(1280,720,8e5,5,"medium"),h720fps15:new Mg(1280,720,15e5,15,"medium"),h720fps30:new Mg(1280,720,2e6,30,"medium"),h1080fps15:new Mg(1920,1080,25e5,15,"medium"),h1080fps30:new Mg(1920,1080,5e6,30,"medium"),original:new Mg(0,0,7e6,30,"medium")};function edA(e,A,t){var i,n,g,o;const{optionsWithoutProcessor:s,audioProcessor:r,videoProcessor:a}=ndA(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&&(u3(l.audio,A),(i=(g=l.audio).deviceId)!==null&&i!==void 0||(g.deviceId={ideal:"default"}),(r||I)&&(l.audio.processor=r??I)),l.video&&(u3(l.video,t),(n=(o=l.video).deviceId)!==null&&n!==void 0||(o.deviceId={ideal:"default"}),(a||c)&&(l.video.processor=a??c)),l}function u3(e,A){return Object.keys(A).forEach(t=>{e[t]===void 0&&(e[t]=A[t])}),e}function Fz(e){var A,t,i,n;const g={};if(e.video)if(typeof e.video=="object"){const o={},s=o,r=e.video;Object.keys(r).forEach(a=>{switch(a){case"resolution":u3(s,r.resolution);break;default:s[a]=r[a]}}),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 tdA(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=idA();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 Sr(t),n.getByteTimeDomainData(o);const r=o.some(a=>a!==128&&a!==0);return i.close(),!r}return!1}()})}function idA(){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 zWA(e){return e==="audioinput"?ot.Source.Microphone:e==="videoinput"?ot.Source.Camera:ot.Source.Unknown}function d3(e){return e===ot.Source.Microphone?"audioinput":e===ot.Source.Camera?"videoinput":void 0}function ZWA(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 lM(e){return e.split("/")[1].toLowerCase()}function WWA(e){const A=[];return e.forEach(t=>{t.track!==void 0&&A.push(new kz({cid:t.track.mediaStreamID,track:t.trackInfo}))}),A}function Mn(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?Mn(e.track):{})}}function VWA(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function XWA(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 ndA(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:YWA(A)}}function $WA(e){switch(e){case ls.CAMERA:return ot.Source.Camera;case ls.MICROPHONE:return ot.Source.Microphone;case ls.SCREEN_SHARE:return ot.Source.ScreenShare;case ls.SCREEN_SHARE_AUDIO:return ot.Source.ScreenShareAudio;default:return ot.Source.Unknown}}function UAA(e,A){return e.width*e.height<A.width*A.height}function AVA(e,A){var t;return(t=e.layers)===null||t===void 0?void 0:t.find(i=>i.quality===A)}const eVA=5e3,M0=[];var HI;(function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"})(HI||(HI={}));class ot extends GB.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=ot.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Cn,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),eVA):this.handleAppVisibilityChanged()},this.log=AQ((n=i.loggerName)!==null&&n!==void 0?n:$c.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=A,this._mediaStreamID=A.id,this.source=ot.Source.Unknown}get logContext(){var A;return Object.assign(Object.assign({},(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this)),Mn(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(A){let t="audio";this.kind===ot.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===ot.Kind.Video&&this.addAppVisibilityListener(),A||(t==="audio"&&(M0.forEach(g=>{g.parentElement===null&&!A&&(A=g)}),A&&M0.splice(M0.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?kt.AudioPlaybackStarted:kt.VideoPlaybackStarted)}).catch(g=>{g.name==="NotAllowedError"?this.emit(n?kt.AudioPlaybackFailed:kt.VideoPlaybackFailed,g):g.name==="AbortError"?Cn.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):Cn.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(kt.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(kt.ElementDetached,A)),A}const t=[];return this.attachedElements.forEach(i=>{Jm(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(kt.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=AQ(A.loggerName)),A.loggerContextCb&&(this.loggerContextCb=A.loggerContextCb)}recycleElement(A){if(A instanceof HTMLAudioElement){let t=!0;A.pause(),M0.forEach(i=>{i.parentElement||(t=!1)}),t&&M0.push(A)}}handleAppVisibilityChanged(){return ZA(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===ot.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(A=>A.play().catch(()=>{})),0)})}addAppVisibilityListener(){eI()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){eI()&&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(a){a.Audio="audio",a.Video="video",a.Unknown="unknown"})(A=e.Kind||(e.Kind={}));let t;(function(a){a.Camera="camera",a.Microphone="microphone",a.ScreenShare="screen_share",a.ScreenShareAudio="screen_share_audio",a.Unknown="unknown"})(t=e.Source||(e.Source={}));let i;(function(a){a.Active="active",a.Paused="paused",a.Unknown="unknown"})(i=e.StreamState||(e.StreamState={}));function n(a){switch(a){case A.Audio:return xc.AUDIO;case A.Video:return xc.VIDEO;default:return xc.DATA}}e.kindToProto=n;function g(a){switch(a){case xc.AUDIO:return A.Audio;case xc.VIDEO:return A.Video;default:return A.Unknown}}e.kindFromProto=g;function o(a){switch(a){case t.Camera:return ls.CAMERA;case t.Microphone:return ls.MICROPHONE;case t.ScreenShare:return ls.SCREEN_SHARE;case t.ScreenShareAudio:return ls.SCREEN_SHARE_AUDIO;default:return ls.UNKNOWN}}e.sourceToProto=o;function s(a){switch(a){case ls.CAMERA:return t.Camera;case ls.MICROPHONE:return t.Microphone;case ls.SCREEN_SHARE:return t.ScreenShare;case ls.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}e.sourceFromProto=s;function r(a){switch(a){case o3.ACTIVE:return i.Active;case o3.PAUSED:return i.Paused;default:return i.Unknown}}e.streamStateFromProto=r})(ot||(ot={}));const tVA="|",vAA="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function iVA(e){const A=e.split(tVA);return A.length>1?[A[0],e.substr(A[0].length+1)]:[e,""]}function Sr(e){return new AI(A=>mr.setTimeout(A,e))}function h3(){return"addTransceiver"in RTCPeerConnection.prototype}function p3(){return"addTrack"in RTCPeerConnection.prototype}function nVA(){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 gVA(){if(!("getCapabilities"in RTCRtpSender)||Cf())return!1;if(cf()){const t=sI();if(t!=null&&t.version&&yB(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&yB(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 qc(e){return e==="av1"||e==="vp9"}function f3(e){return!document||uN()?!1:(e||(e=document.createElement("audio")),"setSinkId"in e)}function oVA(){return typeof RTCPeerConnection>"u"?!1:h3()||p3()}function Cf(){var e;return((e=sI())===null||e===void 0?void 0:e.name)==="Firefox"}function KAA(){const e=sI();return!!e&&e.name==="Chrome"&&e.os!=="iOS"}function cf(){var e;return((e=sI())===null||e===void 0?void 0:e.name)==="Safari"}function uN(){const e=sI();return(e==null?void 0:e.name)==="Safari"||(e==null?void 0:e.os)==="iOS"}function sVA(){const e=sI();return(e==null?void 0:e.name)==="Safari"&&e.version.startsWith("17.")||(e==null?void 0:e.os)==="iOS"&&!!(e!=null&&e.osVersion)&&yB(e.osVersion,"17")>=0}function rVA(e){return e||(e=sI()),(e==null?void 0:e.name)==="Safari"&&yB(e.version,"18.3")>0||(e==null?void 0:e.os)==="iOS"&&!!(e!=null&&e.osVersion)&&yB(e.osVersion,"18.3")>0}function gdA(){var e,A;return eI()?(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 aVA(){const e=sI(),A="17.2";if(e)return e.name!=="Safari"&&e.os!=="iOS"||e.os==="iOS"&&e.osVersion&&yB(e.osVersion,A)>=0?!0:e.name==="Safari"&&yB(e.version,A)>=0}function eI(){return typeof document<"u"}function fB(){return navigator.product=="ReactNative"}function US(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function X2(e){return US(e)?e.hostname.split(".")[0]:null}function odA(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function sdA(){if(!fB())return;let e=odA();if(e)return e.platform}function FAA(){if(eI())return window.devicePixelRatio;if(fB()){let e=odA();if(e)return e.devicePixelRatio}return 1}function yB(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 IVA(e){for(const A of e)A.target.handleResize(A)}function CVA(e){for(const A of e)A.target.handleVisibilityChanged(A)}let $2=null;const _AA=()=>($2||($2=new ResizeObserver(IVA)),$2);let AY=null;const JAA=()=>(AY||(AY=new IntersectionObserver(CVA,{root:null,rootMargin:"0px"})),AY);function cVA(){var e;const A=new suA({sdk:ruA.JS,protocol:TWA,version:xWA});return fB()&&(A.os=(e=sdA())!==null&&e!==void 0?e:""),A}function LAA(){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 N0;function eY(){if(!N0){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(),[N0]=i.stream.getAudioTracks(),!N0)throw Error("Could not get empty media stream audio track");N0.enabled=!1}return N0.clone()}class jC{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 lVA(e){return OWA.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 BVA(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}function dN(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function EVA(e,A){return e.segments.map(t=>{let{id:i,text:n,language:g,startTime:o,endTime:s,final:r}=t;var a;const I=(a=A.get(i))!==null&&a!==void 0?a:Date.now(),c=Date.now();return r?A.delete(i):A.set(i,I),{id:i,text:n,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(s.toString()),final:r,language:g,firstReceivedTime:I,lastReceivedTime:c}})}function QVA(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 xAA(e){switch(e.reason){case vg.LeaveRequest:return e.context;case vg.Cancelled:return Oc.CLIENT_INITIATED;case vg.NotAllowed:return Oc.USER_REJECTED;case vg.ServerUnreachable:return Oc.JOIN_FAILURE;default:return Oc.UNKNOWN_REASON}}function wK(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 lB(e){return!!e&&e.kind==ot.Kind.Audio}function Kd(e){return!!e&&e.kind==ot.Kind.Video}function UQ(e){return Lm(e)&&Kd(e)}function sE(e){return Lm(e)&&lB(e)}function y3(e){return!!e&&!e.isLocal}function uVA(e){return!!e&&!e.isLocal}function tY(e){return y3(e)&&Kd(e)}function dVA(e){return e.isLocal}function hVA(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 pVA(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 fVA(e,A){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=yVA(e,A);return t?i:_z(i,"v1")}function yVA(e,A){const t=new URL(BVA(e));return A.forEach((i,n)=>{t.searchParams.set(n,i)}),_z(t,"rtc")}function DVA(e){const A=new URL(dN(e));return _z(A,"validate")}function rdA(e){return e.endsWith("/")?e:"".concat(e,"/")}function _z(e,A){return e.pathname="".concat(rdA(e.pathname)).concat(A),e}function TAA(e){if(typeof e=="string")return hAA.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return hAA.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}function mVA(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 SVA=10,R0="lk_e2ee",wVA="LKFrameEncryptionKey",kVA={sharedKey:!1,ratchetSalt:wVA,ratchetWindowSize:8,failureTolerance:SVA,keyringSize:16};var Vu;(function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"})(Vu||(Vu={}));var qAA;(function(e){e.KeyRatcheted="keyRatcheted"})(qAA||(qAA={}));var Su;(function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"})(Su||(Su={}));var YAA;(function(e){e.Error="cryptorError"})(YAA||(YAA={}));function MVA(){return NVA()||D3()}function D3(){return typeof window.RTCRtpScriptTransform<"u"}function NVA(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function RVA(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 AuA({value:e.value})}class lGe extends GB.EventEmitter{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,n)=>{Cn.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},kVA),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 HAA;(function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"})(HAA||(HAA={}));class GVA extends GB.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(Cn.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 r=this.decryptDataRequests.get(s.uuid);r!=null&&r.resolve&&r.resolve(s);break;case"encryptDataResponse":const a=this.encryptDataRequests.get(s.uuid);a!=null&&a.resolve&&a.resolve(s);break}},this.onWorkerError=i=>{Cn.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(!MVA())throw new vz("tried to setup end-to-end encryption on an unsupported browser");if(Cn.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:mWA.getLevel()}};this.worker&&(Cn.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(A,t){Cn.debug("set e2ee to ".concat(A," for participant ").concat(t)),this.postEnable(A,t)}setSifTrailer(A){!A||A.length===0?Cn.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(A)}setupEngine(A){A.on(Ut.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(A,t){A.on(ut.TrackPublished,(i,n)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==bs.NONE,n.identity)),A.on(ut.ConnectionStateChanged,i=>{i===Zn.Connected&&A.remoteParticipants.forEach(n=>{n.trackPublications.forEach(g=>{this.setParticipantCryptorEnabled(g.trackInfo.encryption!==bs.NONE,n.identity)})})}).on(ut.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(ut.TrackSubscribed,(i,n,g)=>{this.setupE2EEReceiver(i,g.identity,n.trackInfo)}).on(ut.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(Lt.LocalSenderCreated,(i,n)=>ZA(this,void 0,void 0,function*(){this.setupE2EESender(n,i)})),A.localParticipant.on(Lt.LocalTrackPublished,i=>{if(!Kd(i.track)||!uN())return;const n={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:lM(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 jC;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 jC;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"?lM(i.mimeType):void 0)}}setupE2EESender(A,t){if(!Lm(A)||!t){t||Cn.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(D3()&&!KAA()){const g={kind:"decode",participantIdentity:i,trackId:t,codec:n};A.transform=new RTCRtpScriptTransform(this.worker,g)}else{if(R0 in A&&n){const r={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(r);return}let g=A.writableStream,o=A.readableStream;if(!g||!o){const r=A.createEncodedStreams();A.writableStream=r.writable,g=r.writable,A.readableStream=r.readable,o=r.readable}const s={kind:"decode",data:{readableStream:o,writableStream:g,trackId:t,codec:n,participantIdentity:i,isReuse:R0 in A}};this.worker.postMessage(s,[o,g])}A[R0]=!0}})}handleSender(A,t,i){var n;if(!(R0 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(D3()&&!KAA()){Cn.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{Cn.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[R0]=!0}}}const bVA=500,UVA=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=X2(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,Sr(Math.min(bVA*Math.pow(2,g),UVA)))}getBackOffPromise(A){const t=new URL(A),i=t&&X2(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(A){const t=new URL(A),i=t&&X2(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}xm._instance=null;const iY="default";class Ar{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Ar),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=Ar.userMediaPromiseMap)===null||g===void 0?void 0:g.size)>0){Cn.debug("awaiting getUserMedia promise");try{t?yield Ar.userMediaPromiseMap.get(t):yield Promise.all(Ar.userMediaPromiseMap.values())}catch{Cn.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(n&&!(cf()&&i.hasDeviceInUse(t))&&(o.filter(r=>r.kind===t).length===0||o.some(r=>{const a=r.label==="",I=t?r.kind===t:!0;return a&&I}))){const r={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},a=yield navigator.mediaDevices.getUserMedia(r);o=yield navigator.mediaDevices.enumerateDevices(),a.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!==iY)return t;const n=yield this.getDevices(A),g=n.find(s=>s.deviceId===iY);if(!g){Cn.warn("could not reliably determine default device");return}const o=n.find(s=>s.deviceId!==iY&&s.groupId===(i??g.groupId));if(!o){Cn.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(A){return A?Ar.userMediaPromiseMap.has(A):Ar.userMediaPromiseMap.size>0}}Ar.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Ar.userMediaPromiseMap=new Map;var BM;(function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"})(BM||(BM={}));class vVA{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ua,this.nextTaskIndex=0}run(A){return ZA(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:BM.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=BM.RUNNING,yield A()}finally{t.status=BM.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 KVA{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:r}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return g.close(s,r)};this.opened=new AI((s,r)=>{const a=()=>{r(wi.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",a)},g.addEventListener("error",a)}),this.closed=new AI((s,r)=>{const a=()=>ZA(this,void 0,void 0,function*(){const I=new AI(l=>{g.readyState!==WebSocket.CLOSED&&g.addEventListener("close",B=>{l(B)},{once:!0})}),c=yield AI.race([Sr(250),I]);c?s(c):r(wi.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",a)},g.addEventListener("error",a)}),t.signal&&(t.signal.onabort=()=>g.close()),this.close=o}}const FVA=["syncState","trickle","offer","answer","simulate","leave"];function _VA(e){const A=FVA.indexOf(e.case)>=0;return Cn.trace("request allowed to bypass queue:",{canPass:A,req:e}),A}var bg;(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"})(bg||(bg={}));const JVA=250;class Jz{get currentState(){return this.state}get isDisconnected(){return this.state===bg.DISCONNECTING||this.state===bg.DISCONNECTED}get isEstablishingConnection(){return this.state===bg.CONNECTING||this.state===bg.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=bg.DISCONNECTED,this.log=Cn,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=AQ((i=t.loggerName)!==null&&i!==void 0?i:$c.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=A,this.requestQueue=new vVA,this.queuedRequests=[],this.closingLock=new Ua,this.connectionLock=new Ua,this.state=bg.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,r){var a=this;let I=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){return a.state=bg.CONNECTING,a.options=s,yield a.connect(g,o,s,r,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=bg.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,r){var a=this;let I=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){const c=yield a.connectionLock.lock();a.connectOptions=s,a.useV0SignalPath=I;const l=cVA(),B=I?LVA(o,l,s):xVA(o,l,s),Q=fVA(g,B,I).toString(),h=DVA(Q).toString();return new Promise((d,p)=>ZA(a,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,_=mVA(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(wi.cancelled(_))});r==null||r.addEventListener("abort",S);const k=()=>{clearTimeout(N),r==null||r.removeEventListener("abort",S)},N=setTimeout(()=>{S(wi.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 KVA(Q);try{this.ws.closed.then(v=>{var U;this.isEstablishingConnection&&p(wi.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===bg.CONNECTED&&this.handleOnClose((U=v.reason)!==null&&U!==void 0?U:"Unexpected WS error"))}).catch(v=>{this.isEstablishingConnection&&p(wi.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!==bg.CONNECTED){this.state=bg.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 wi.internal("no message received as first message");const K=TAA(_.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 T=J.shouldProcessFirstMessage?K:void 0;G(w,T),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 Sr(this.signalLatency));const{done:i,value:n}=yield A.read();if(i)break;const g=TAA(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([bg.DISCONNECTING||bg.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=bg.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,Sr(JVA)])}}catch(g){A.log.debug("websocket error while closing",Object.assign(Object.assign({},A.logContext),{error:g}))}finally{t&&(A.state=bg.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 $L({candidateInit:JSON.stringify(A),target:t})})}sendMuteTrack(A,t){return this.sendRequest({case:"mute",value:new Ax({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 Nz({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 EuA({trackSid:A,layers:t})})}sendUpdateSubscriptionPermissions(A,t){return this.sendRequest({case:"subscriptionPermission",value:new duA({allParticipants:A,trackPermissions:t})})}sendSimulateScenario(A){return this.sendRequest({case:"simulate",value:A})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ro.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new fuA({timestamp:ro.parse(Date.now()),rtt:ro.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(A,t){return this.sendRequest({case:"updateAudioTrack",value:new Mz({trackSid:A,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new tx({reason:Oc.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&&!_VA(t)&&i.state===bg.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 Sr(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 ZZA({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=OAA(n.value);this.onAnswer&&this.onAnswer(o,n.value.id,n.value.midToTrackId)}else if(n.case==="offer"){const o=OAA(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===bg.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=mr.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&&mr.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=mr.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&mr.clearInterval(this.pingInterval)}handleSignalConnected(A,t,i){this.state=bg.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===bg.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:wi.leaveRequest("Received leave request while trying to (re)connect",A.message.value.reason)}:t?{isValid:!1,error:wi.internal("Unexpected first message")}:{isValid:!1,error:wi.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 wi.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const n=yield i.text();return wi.notAllowed(n,i.status);default:break}return A instanceof wi?A:wi.internal("Encountered unknown websocket error during connection: ".concat(A),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof wi?i:wi.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function OAA(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 LVA(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",fB()?"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 xVA(e,A,t){const i=new URLSearchParams;i.set("access_token",e);const n=new uWA({clientInfo:A,connectionSettings:new yuA({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 dWA({joinRequest:n.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(g.toBinary()))),i}class PAA{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 TVA{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 Dc={},nY={},gY={exports:{}},jAA;function Lz(){if(jAA)return gY.exports;jAA=1;var e=gY.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")})}),gY.exports}var zAA;function qVA(){return zAA||(zAA=1,function(e){var A=function(s){return String(Number(s))===s?Number(s):s},t=function(s,r,a,I){if(I&&!a)r[I]=A(s[1]);else for(var c=0;c<a.length;c+=1)s[c+1]!=null&&(r[a[c]]=A(s[c+1]))},i=function(s,r,a){var I=s.name&&s.names;s.push&&!r[s.push]?r[s.push]=[]:I&&!r[s.name]&&(r[s.name]={});var c=s.push?{}:I?r[s.name]:r;t(a.match(s.reg),c,s.names,s.name),s.push&&r[s.push].push(c)},n=Lz(),g=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(s){var r={},a=[],I=r;return s.split(/(\r\n|\r|\n)/).filter(g).forEach(function(c){var l=c[0],B=c.slice(2);l==="m"&&(a.push({rtp:[],fmtp:[]}),I=a[a.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)}}),r.media=a,r};var o=function(s,r){var a=r.split(/=(.+)/,2);return a.length===2?s[a[0]]=A(a[1]):a.length===1&&r.length>1&&(s[a[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 r=[],a=s.split(" ").map(A),I=0;I<a.length;I+=3)r.push({component:a[I],ip:a[I+1],port:a[I+2]});return r},e.parseImageAttributes=function(s){return s.split(" ").map(function(r){return r.substring(1,r.length-1).split(",").reduce(o,{})})},e.parseSimulcastStreamList=function(s){return s.split(";").map(function(r){return r.split(",").map(function(a){var I,c=!1;return a[0]!=="~"?I=A(a):(I=A(a.substring(1,a.length)),c=!0),{scid:I,paused:c}})})}}(nY)),nY}var oY,ZAA;function YVA(){if(ZAA)return oY;ZAA=1;var e=Lz(),A=/%[sdv%]/g,t=function(o){var s=1,r=arguments,a=r.length;return o.replace(A,function(I){if(s>=a)return I;var c=r[s];switch(s+=1,I){case"%%":return"%";case"%s":return String(c);case"%d":return Number(c);case"%v":return""}})},i=function(o,s,r){var a=s.format instanceof Function?s.format(s.push?r:r[s.name]):s.format,I=[o+"="+a];if(s.names)for(var c=0;c<s.names.length;c+=1){var l=s.names[c];s.name?I.push(r[s.name][l]):I.push(r[s.names[c]])}else I.push(r[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 oY=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 r=s.outerOrder||n,a=s.innerOrder||g,I=[];return r.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)),a.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
`},oY}var WAA;function HVA(){if(WAA)return Dc;WAA=1;var e=qVA(),A=YVA(),t=Lz();return Dc.grammar=t,Dc.write=A,Dc.parse=e.parse,Dc.parseParams=e.parseParams,Dc.parseFmtpConfig=e.parseFmtpConfig,Dc.parsePayloads=e.parsePayloads,Dc.parseRemoteCandidates=e.parseRemoteCandidates,Dc.parseImageAttributes=e.parseImageAttributes,Dc.parseSimulcastStreamList=e.parseSimulcastStreamList,Dc}var zQ=HVA();function xz(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,r=t.maxWait,a=Date.now(),I=[];function c(){if(r!==void 0){var B=Date.now()-a;if(B+A>=r)return r-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,a=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 OVA=.7,PVA=20,Tm={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class VAA extends GB.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=Cn,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=xz(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}}),PVA),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=AQ((i=t.loggerName)!==null&&i!==void 0?i:$c.PCTransport),this.loggerOptions=t,this.config=A,this._pc=this.createPC(),this.offerLock=new Ua}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}=jVA(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=Tz(o.mid);o.type==="audio"&&this.trackBitrates.some(r=>{if(!r.transceiver||s!=r.transceiver.mid)return!1;let a=0;if(o.rtp.some(c=>c.codec.toUpperCase()===r.codec.toUpperCase()?(a=c.payload,!0):!1),a===0)return!0;let I=!1;for(const c of o.fmtp)if(c.payload===a){c.config=c.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),r.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(r.maxbr*1e3)),I=!0;break}return I||r.maxbr>0&&o.fmtp.push({payload:a,config:"maxaveragebitrate=".concat(r.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=>{$AA(s),s.type==="audio"?XAA(s,["all"],[]):s.type==="video"&&this.trackBitrates.some(r=>{if(!s.msid||!r.cid||!s.msid.includes(r.cid))return!1;let a=0;if(s.rtp.some(c=>c.codec.toUpperCase()===r.codec.toUpperCase()?(a=c.payload,!0):!1),a===0||(qc(r.codec)&&!cf()&&this.ensureVideoDDExtensionForSVC(s,o),!qc(r.codec)))return!0;const I=Math.round(r.maxbr*OVA);for(const c of s.fmtp)if(c.payload===a){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=>{$AA(n),n.type==="audio"&&XAA(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 Po("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 Po("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===vAA))){if(this.ddExtID===0){let o=0;t.media.forEach(s=>{var r;s.type==="video"&&((r=s.ext)===null||r===void 0||r.forEach(a=>{a.value>o&&(o=a.value)}))}),this.ddExtID=o+1}(n=A.ext)===null||n===void 0||n.push({value:this.ddExtID,uri:vAA})}}}function XAA(e,A,t){const i=Tz(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 jVA(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 r=Tz(o.mid);o.type==="audio"&&(o.rtp.some(a=>a.codec==="opus"?(g=a.payload,!0):!1),!((s=o.rtcpFb)===null||s===void 0)&&s.some(a=>a.payload===g&&a.type==="nack")&&i.push(r),o.fmtp.some(a=>a.payload===g?(a.config.includes("sprop-stereo=1")&&t.push(r),!0):!1))}),{stereoMids:t,nackMids:i}}function $AA(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 Tz(e){return typeof e=="number"?e.toFixed(0):e}const m3="vp8",zVA={audioPreset:E3.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Kz.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:m3,backupCodec:!0,preConnectBuffer:!1},adA={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},IdA={deviceId:{ideal:"default"},resolution:bS.h720.resolution},ZVA={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new wWA,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},qz={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var vo;(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"})(vo||(vo={}));class WVA{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=qz.peerConnectionTimeout,this.log=Cn,this.updateState=()=>{var g,o;const s=this.state,r=this.requiredTransports.map(a=>a.getConnectionState());r.every(a=>a==="connected")?this.state=vo.CONNECTED:r.some(a=>a==="failed")?this.state=vo.FAILED:r.some(a=>a==="connecting")?this.state=vo.CONNECTING:r.every(a=>a==="closed")?this.state=vo.CLOSED:r.some(a=>a==="closed")?this.state=vo.CLOSING:r.every(a=>a==="new")&&(this.state=vo.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(vo[s]," to ").concat(vo[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=AQ((n=i.loggerName)!==null&&n!==void 0?n:$c.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new VAA(A,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new VAA(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,Tc.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,Tc.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=vo.NEW,this.connectionLock=new Ua,this.remoteOfferLock=new Ua}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===Tc.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 AI((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===Tc.PUBLISHER?this.publisher.getConnectedAddress():A===Tc.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((r,a)=>ZA(g,void 0,void 0,function*(){const I=()=>{this.log.warn("abort transport connection",this.logContext),mr.clearTimeout(c),a(wi.cancelled("room connection has been cancelled"))};n!=null&&n.signal.aborted&&I(),n==null||n.signal.addEventListener("abort",I);const c=mr.setTimeout(()=>{n==null||n.signal.removeEventListener("abort",I),a(wi.internal("could not establish pc connection"))},o);for(;this.state!==vo.CONNECTED;)if(yield Sr(50),n!=null&&n.signal.aborted){a(wi.cancelled("room connection has been cancelled"));return}mr.clearTimeout(c),n==null||n.signal.removeEventListener("abort",I),r()}))}()})}}const CdA=5e3,VVA=3e4;class Xn{static fetchRegionSettings(A,t,i){return ZA(this,void 0,void 0,function*(){const n=yield Xn.fetchLock.lock();try{const g=yield fetch("".concat(XVA(A),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(g.ok){const o=pVA(g.headers),s=o?o*1e3:CdA;return{regionSettings:yield g.json(),updatedAtInMs:Date.now(),maxAgeInMs:s}}else throw g.status===401?wi.notAllowed("Could not fetch region settings: ".concat(g.statusText),g.status):wi.internal("Could not fetch region settings: ".concat(g.statusText))}catch(g){throw g instanceof wi?g:i!=null&&i.aborted?wi.cancelled("Region fetching was aborted"):wi.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=Xn.settingsTimeouts.get(A.hostname);clearTimeout(n),Xn.settingsTimeouts.set(A.hostname,setTimeout(()=>ZA(this,void 0,void 0,function*(){try{const g=yield Xn.fetchRegionSettings(A,t);Xn.updateCachedRegionSettings(A,t,g)}catch(g){if(g instanceof wi&&g.reason===vg.NotAllowed){Cn.debug("token is not valid, cancelling auto region refresh");return}Cn.debug("auto refetching of region settings failed",{error:g}),Xn.scheduleRefetch(A,t,i)}}),i))})}static updateCachedRegionSettings(A,t,i){Xn.cache.set(A.hostname,i),Xn.scheduleRefetch(A,t,i.maxAgeInMs)}static stopRefetch(A){const t=Xn.settingsTimeouts.get(A);t&&(clearTimeout(t),Xn.settingsTimeouts.delete(A))}static scheduleCleanup(A){let t=Xn.connectionTrackers.get(A);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=Xn.connectionTrackers.get(A);i&&i.connectionCount===0&&(Cn.debug("stopping region refetch after disconnect delay",{hostname:A}),Xn.stopRefetch(A)),i&&(i.cleanupTimeout=void 0)},VVA))}static cancelCleanup(A){const t=Xn.connectionTrackers.get(A);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const A=this.serverUrl.hostname;let t=Xn.connectionTrackers.get(A);t||(t={connectionCount:0},Xn.connectionTrackers.set(A,t)),t.connectionCount++,Xn.cancelCleanup(A)}notifyDisconnected(){const A=this.serverUrl.hostname,t=Xn.connectionTrackers.get(A);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&Xn.scheduleCleanup(A))}constructor(A,t){this.attemptedRegions=[],this.serverUrl=new URL(A),this.token=t}updateToken(A){this.token=A}isCloud(){return US(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(A){return ZA(this,void 0,void 0,function*(){return Xn.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=Xn.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(A),Xn.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),Cn.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(A){Xn.updateCachedRegionSettings(this.serverUrl,this.token,A)}}Xn.cache=new Map;Xn.settingsTimeouts=new Map;Xn.connectionTrackers=new Map;Xn.fetchLock=new Ua;function XVA(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}let Da=class zh extends Error{constructor(A,t,i){super(t),this.code=A,this.message=AeA(t,zh.MAX_MESSAGE_BYTES),this.data=i?AeA(i,zh.MAX_DATA_BYTES):void 0}static fromProto(A){return new zh(A.code,A.message,A.data)}toProto(){return new iuA({code:this.code,message:this.message,data:this.data})}static builtIn(A,t){return new zh(zh.ErrorCode[A],zh.ErrorMessage[A],t)}};Da.MAX_MESSAGE_BYTES=256;Da.MAX_DATA_BYTES=15360;Da.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};Da.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 cdA=15360;function Yz(e){return new TextEncoder().encode(e).length}function AeA(e,A){if(Yz(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 Hz=2e3;function nx(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 Oz=typeof MediaRecorder<"u";class $VA{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const A9A=Oz?MediaRecorder:$VA;class e9A extends A9A{constructor(A,t){if(!Oz)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=r=>{n==null||n.error(r),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",s),n=void 0};this.byteStream=new ReadableStream({start:r=>{n=r,i=a=>ZA(this,void 0,void 0,function*(){let I;if(a.data.arrayBuffer){const c=yield a.data.arrayBuffer();I=new Uint8Array(c)}else if(a.data.byteArray)I=a.data.byteArray;else throw new Error("no data available!");g()||r.enqueue(I)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",s)}}function t9A(){return Oz}const i9A=1e3,n9A=1e4;class ldA extends ot{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=xz(()=>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(kt.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new Ua,this.pauseUpstreamLock=new Ua,this.trackChangeLock=new Ua,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!==ot.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]:i9A;return function*(){var i;if(A.kind===ot.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=sI())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Sr(10));const n=Date.now();for(;Date.now()-n<t;){const g=A.dimensions;if(g)return g;yield Sr(50)}throw new fE("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===ot.Source.ScreenShare)return;const{deviceId:i,groupId:n}=A._mediaStreamTrack.getSettings(),g=A.kind===ot.Kind.Audio?"audioinput":"videoinput";return t?Ar.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 fE("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=kWA(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===ot.Kind.Video?o.video=i||n?{deviceId:i,facingMode:n}:!0:o.audio=i?Object.assign({deviceId:i},g):!0,this.attachedElements.forEach(a=>{Jm(this.mediaStreamTrack,a)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===ot.Kind.Video&&(yield r.applyConstraints(g)),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=A,this.emit(kt.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?kt.Muted:kt.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),gdA()&&(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(kt.UpstreamPaused,this);const i=sI();if((i==null?void 0:i.name)==="Safari"&&yB(i.version,"12.0")<0)throw new vz("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(kt.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),r={kind:i.kind,track:i._mediaStreamTrack,element:s,audioContext:i.audioContext};if(yield t.init(r),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(a=>{a instanceof DOMException&&a.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:a})),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:a}))}),i.processor=t,i.processorElement=s,i.processor.processedTrack){for(const a of i.attachedElements)a!==i.processorElement&&n&&(Jm(i._mediaStreamTrack,a),$D(i.processor.processedTrack,a));yield(g=i.sender)===null||g===void 0?void 0:g.replaceTrack(i.processor.processedTrack)}i.emit(kt.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(kt.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!t9A()){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 e9A(this,{mimeType:t})}this.localTrackRecorder.start(A),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},n9A)}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 ldA{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,ot.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=nx(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(kt.AudioTrackFeatureUpdate,this,Vs.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(kt.AudioTrackFeatureUpdate,this,Vs.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===ot.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===ot.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=Fz({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(){eI()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Hz)))}setProcessor(A){return ZA(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!fB()&&!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(kt.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 tdA(this);return A&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(kt.AudioSilenceDetected)),A})}}function g9A(e,A,t){switch(e.kind){case"audio":return new a_(e,A,!1,void 0,t);case"video":return new I_(e,A,!1,t);default:throw new fE("unsupported track type: ".concat(e.kind))}}const o9A=Object.values(bS),s9A=Object.values(Q3),r9A=Object.values(Kz),a9A=[bS.h180,bS.h360],I9A=[Q3.h180,Q3.h360],C9A=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>{var i,n;return new Mg(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)}),S3=["q","h","f"];function w3(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,r=i==null?void 0:i.scalabilityMode,a=i==null?void 0:i.videoCodec;if(!o&&!s&&!r||!A||!t)return[{}];o||(o=l9A(e,A,t,a),Cn.debug("using video encoding",o));const I=o.maxFramerate,c=new Mg(A,t,o.maxBitrate,o.maxFramerate,o.priority);if(r&&qc(a)){const Q=new BdA(r),h=[];if(Q.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(r));const d=sI();if(uN()||fB()||(d==null?void 0:d.name)==="Chrome"&&yB(d==null?void 0:d.version,"113")<0){const p=Q.suffix=="h"?2:3,y=rVA(d);for(let m=0;m<Q.spatial;m+=1)h.push({rid:S3[2-m],maxBitrate:o.maxBitrate/Math.pow(p,m),maxFramerate:c.encoding.maxFramerate,scaleResolutionDownBy:y?Math.pow(2,m):void 0});h[0].scalabilityMode=r}else h.push({maxBitrate:o.maxBitrate,maxFramerate:c.encoding.maxFramerate,scalabilityMode:r});return c.encoding.priority&&(h[0].priority=c.encoding.priority,h[0].networkPriority=c.encoding.priority),Cn.debug("using svc encoding",{encodings:h}),h}if(!s)return[o];let l=[];e?l=(n=teA(i==null?void 0:i.screenShareSimulcastLayers))!==null&&n!==void 0?n:eeA(e,c):l=(g=teA(i==null?void 0:i.videoSimulcastLayers))!==null&&g!==void 0?g:eeA(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 sY(A,t,[Q,B,c],I);if(h>=480)return sY(A,t,[Q,c],I)}return sY(A,t,[c])}function c9A(e,A,t){var i,n,g,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;A!==t.backupCodec.codec&&Cn.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(),r=(i=s.width)!==null&&i!==void 0?i:(n=e.dimensions)===null||n===void 0?void 0:n.width,a=(g=s.height)!==null&&g!==void 0?g:(o=e.dimensions)===null||o===void 0?void 0:o.height;return e.source===ot.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),w3(e.source===ot.Source.ScreenShare,r,a,t)}function l9A(e,A,t,i){const n=B9A(e,A,t);let{encoding:g}=n[0];const o=Math.max(A,t);for(let s=0;s<n.length;s+=1){const r=n[s];if(g=r.encoding,r.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 B9A(e,A,t){if(e)return r9A;const i=A>t?A/t:t/A;return Math.abs(i-16/9)<Math.abs(i-4/3)?o9A:s9A}function eeA(e,A){if(e)return C9A(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)?a9A:I9A}function sY(e,A,t,i){const n=[];if(t.forEach((g,o)=>{if(o>=S3.length)return;const s=Math.min(e,A),a={rid:S3[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&&(a.maxFramerate=I);const c=Cf()||o===0;g.encoding.priority&&c&&(a.priority=g.encoding.priority,a.networkPriority=g.encoding.priority),n.push(a)}),fB()&&sdA()==="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 r;s.maxFramerate!=g&&(o&&(o=!1,Cn.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Cn.info('Setting framerate of encoding "'.concat((r=s.rid)!==null&&r!==void 0?r:"",'" to ').concat(g)),s.maxFramerate=g)})}return n}function teA(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 BdA{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 E9A(e){return e.source===ot.Source.ScreenShare||e.constraints.height&&Wu(e.constraints.height)>=1080?"maintain-resolution":"balanced"}const Q9A=5e3;class I_ extends ldA{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,ot.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(r){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:r}));return}const o=new Map(g.map(r=>[r.rid,r])),s=g.some(r=>r.qualityLimitationReason==="cpu");if(s!==this.isCpuConstrained&&(this.isCpuConstrained=s,this.isCpuConstrained&&this.emit(kt.CpuConstrained)),this.prevStats){let r=0;o.forEach((a,I)=>{var c;const l=(c=this.prevStats)===null||c===void 0?void 0:c.get(I);r+=nx(a,l)}),this._currentBitrate=r}this.prevStats=o}),this.senderLock=new Ua}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(A){var t;if(this.signalClient=A,!eI())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()},Hz))}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,r=pE(this.simulcastCodecs.values()),a;a=yield r.next(),t=a.done,!t;s=!0)g=a.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=r.return)&&(yield n.call(r))}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,r=pE(this.simulcastCodecs.values()),a;a=yield r.next(),t=a.done,!t;s=!0){g=a.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=r.return)&&(yield n.call(r))}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===ot.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===ot.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=HI.LOW;i<=HI.HIGH;i+=1)t.push(new Rz({quality:i,enabled:i<=A}));this.log.debug("setting publishing quality. max quality ".concat(A),this.logContext),this.setPublishingLayers(qc(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=Fz({video:A});typeof c.video!="boolean"&&(s=c.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var r=!0,a=pE(this.simulcastCodecs.values()),I;I=yield a.next(),t=I.done,!t;r=!0){g=I.value,r=!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{!r&&!t&&(n=a.return)&&(yield n.call(a))}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,r,a,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=pE(n.simulcastCodecs.values()),Q;Q=yield B.next(),o=Q.done,!o;l=!0)a=Q.value,l=!1,yield(c=a.sender)===null||c===void 0?void 0:c.replaceTrack(n.processor.processedTrack)}catch(h){s={error:h}}finally{try{!l&&!o&&(r=B.return)&&(yield r.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)},Q9A))}setPublishingCodecs(A){return ZA(this,void 0,void 0,function*(){var t,i,n,g,o,s,r;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(qc(A[0].codec),A[0].qualities),[];this.subscribedCodecs=A;const a=[];try{for(t=!0,i=pE(A);n=yield i.next(),g=n.done,!g;t=!0){r=n.value,t=!1;const I=r;if(!this.codec||this.codec===I.codec)yield this.setPublishingLayers(qc(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){a.push(I.codec);break}}else c.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(I.codec),this.logContext),yield ieA(c.sender,c.encodings,I.qualities,this.senderLock,qc(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 a})}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 ieA(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&&qc(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),gdA()&&this.isInBackground&&this.source===ot.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ieA(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 r=e.getParameters(),{encodings:a}=r;if(!a)return;if(a.length!==A.length){g.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:A}));return}let I=!1;!1&&a[0].scalabilityMode||(n&&t.some(B=>B.enabled)&&t.forEach(B=>B.enabled=!0),a.forEach((l,B)=>{var Q;let h=(Q=l.rid)!==null&&Q!==void 0?Q:"";h===""&&(h="q");const d=EdA(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&&(r.encodings=a,g.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:r.encodings})),yield e.setParameters(r))}finally{s()}})}function EdA(e){switch(e){case"f":return HI.HIGH;case"h":return HI.MEDIUM;case"q":return HI.LOW;default:return HI.HIGH}}function neA(e,A,t,i){if(!t)return[new Zu({quality:HI.HIGH,width:e,height:A,bitrate:0,ssrc:0})];if(i){const n=t[0].scalabilityMode,g=new BdA(n),o=[],s=g.suffix=="h"?1.5:2,r=g.suffix=="h"?2:3;for(let a=0;a<g.spatial;a+=1)o.push(new Zu({quality:Math.min(HI.HIGH,g.spatial-1)-a,width:Math.ceil(e/Math.pow(s,a)),height:Math.ceil(A/Math.pow(s,a)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(r,a)):0,ssrc:0}));return o}return t.map(n=>{var g,o,s;const r=(g=n.scaleResolutionDownBy)!==null&&g!==void 0?g:1;let a=EdA((o=n.rid)!==null&&o!==void 0?o:"");return new Zu({quality:a,width:Math.ceil(e/r),height:Math.ceil(A/r),bitrate:(s=n.maxBitrate)!==null&&s!==void 0?s:0,ssrc:0})})}const geA="_lossy",oeA="_reliable",u9A=2*1e3,rY="leave-reconnect",d9A=3e4,h9A=8*1024,p9A=256*1024;var mC;(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"})(mC||(mC={}));class f9A extends GB.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(A){var t;super(),this.options=A,this.rtcConfig={},this.peerConnectionTimeout=qz.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=mC.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=Cn,this.reliableDataSequence=1,this.reliableMessageBuffer=new PAA,this.reliableReceivedState=new TVA(d9A),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===oeA)g.reliableDCSub=o;else if(o.label===geA)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,r;const a=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=ya.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(Ut.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=AuA.fromBinary(l.payload),Q=new ya({value:B.value,participantIdentity:c.participantIdentity,participantSid:c.participantSid});((s=Q.value)===null||s===void 0?void 0:s.case)==="user"&&seA(Q,Q.value.value),this.emit(Ut.DataPacketReceived,Q,c.value.value.encryptionType)}else((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&seA(c,c.value.value),this.emit(Ut.DataPacketReceived,c,bs.NONE)}finally{a()}}),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?Sn.LOSSY:Sn.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=r=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(r,"ms. giving up"),this.logContext),this.emit(Ut.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(s===null){g(o);return}i===rY&&(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=mr.setTimeout(()=>this.attemptReconnect(n).finally(()=>this.reconnectTimeout=void 0),s)},this.waitForRestarted=()=>new Promise((i,n)=>{this.pcState===mC.Connected&&i();const g=()=>{this.off(Ut.Disconnected,o),i()},o=()=>{this.off(Ut.Restarted,g),n()};this.once(Ut.Restarted,g),this.once(Ut.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{if(i===Sn.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(Ut.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(dN(this.url),{method:"HEAD"}).then(n=>n.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===bg.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===bg.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(dN(this.url),{method:"HEAD"}),Sr(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=AQ((t=A.loggerName)!==null&&t!==void 0?t:$c.Engine),this.loggerOptions={loggerName:A.loggerName,loggerContextCb:()=>this.logContext},this.client=new Jz(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new Ua,this.dataProcessLock=new Ua,this.dcBufferStatus=new Map([[Sn.LOSSY,!0],[Sn.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(Ut.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(Ut.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(Ut.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(Ut.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(Ut.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(Ut.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(Ut.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(Ut.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,r){var a=this;let I=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){a.url=g,a.token=o,a.signalOpts=s,a.maxJoinAttempts=s.maxRetries;try{a.joinAttempts+=1,a.setupSignalClientCallbacks();const c=yield a.client.join(g,o,s,r,I);return a._isClosed=!1,a.latestJoinResponse=c,a.subscriberPrimary=c.subscriberPrimary,a.pcManager||(yield a.configure(c,!I)),(!a.subscriberPrimary||c.fastPublish)&&a.negotiate().catch(l=>{Cn.error(l,a.logContext)}),a.registerOnLineListener(),a.clientConfiguration=c.clientConfiguration,a.emit(Ut.SignalConnected,c),c}catch(c){if(c instanceof wi){if(c.reason===vg.ServerUnreachable){if(a.log.warn("Couldn't connect to server, attempt ".concat(a.joinAttempts," of ").concat(a.maxJoinAttempts),a.logContext),a.joinAttempts<a.maxJoinAttempts)return a.join(g,o,s,r,I)}else if(c.reason===vg.ServiceNotFound)return a.log.warn("Initial connection failed: ".concat(c.message," – Retrying")),a.join(g,o,s,r,!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(Ut.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 PAA,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 fE("a track with the same ID has already been published");return new Promise((t,i)=>{const n=setTimeout(()=>{delete this.pendingTrackResolvers[A.cid],i(wi.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!==vo.NEW)return;this.participantSid=(i=A.participant)===null||i===void 0?void 0:i.sid;const g=this.makeRTCConfiguration(A);this.pcManager=new WVA(g,t?"publisher-only":A.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(Ut.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,r)=>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===vo.CONNECTED){const c=this.pcState===mC.New;this.pcState=mC.Connected,c&&this.emit(Ut.Connected,A)}else o===vo.FAILED&&(this.pcState===mC.Connected||this.pcState===mC.Reconnecting)&&(this.pcState=mC.Disconnected,this.handleDisconnect("peerconnection failed",r==="failed"?Ph.RR_SUBSCRIBER_FAILED:Ph.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===bg.RECONNECTING,I=[vo.FAILED,vo.CLOSING,vo.CLOSED].includes(o);a&&I&&!this._isClosed&&this.emit(Ut.Offline)}),this.pcManager.onTrack=o=>{o.streams.length!==0&&this.emit(Ut.MediaTrackAdded,o.track,o.streams[0],o.receiver)},y9A((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(Ut.LocalTrackUnpublished,A)},this.client.onLocalTrackSubscribed=A=>{this.emit(Ut.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(Ut.RemoteMute,A,t)},this.client.onSubscribedQualityUpdate=A=>{this.emit(Ut.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(Ut.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:CdA,regionSettings:A.regions})),A.action){case Km.DISCONNECT:this.emit(Ut.Disconnected,A==null?void 0:A.reason),this.close();break;case Km.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(rY);break;case Km.RESUME:this.handleDisconnect(rY)}}}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===BN.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(geA,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(oeA,{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(Sn.LOSSY);if(A){const t=this.lossyDataStatByterate/10;A.bufferedAmountLowThreshold=Math.min(Math.max(t,h9A),p9A)}},1e3))}createSender(A,t,i){return ZA(this,void 0,void 0,function*(){if(h3())return yield this.createTransceiverRTCRtpSender(A,t,i);if(p3())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(A.mediaStreamTrack);throw new Po("Required webRTC APIs not supported on this device")})}createSimulcastSender(A,t,i,n){return ZA(this,void 0,void 0,function*(){if(h3())return this.createSimulcastTransceiverSender(A,t,i,n);if(p3())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(A.mediaStreamTrack);throw new Po("Cannot stream on this device")})}createTransceiverRTCRtpSender(A,t,i){return ZA(this,void 0,void 0,function*(){if(!this.pcManager)throw new Po("publisher is closed");const n=[];A.mediaStream&&n.push(A.mediaStream),Kd(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 Po("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 Po("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){Cn.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===BN.DISABLED||((n=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&n!==void 0?n:vo.NEW)===vo.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 Po?(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(Ut.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 Po("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Ut.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 wi&&o.reason===vg.NotAllowed?new Po("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(Ut.SignalRestarted,g),yield this.waitForPCReconnected(),this.client.currentState!==bg.CONNECTED)throw new zy("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(Ut.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 Po("could not reconnect, url or token not saved");if(!this.pcManager)throw new Po("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Ut.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 wi&&n.reason===vg.NotAllowed?new Po("could not reconnect, token might be expired"):n instanceof wi&&n.reason===vg.LeaveRequest?n:new zy(g)}if(this.emit(Ut.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!==bg.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(Ut.Resumed)})}waitForPCInitialConnection(A,t){return ZA(this,void 0,void 0,function*(){if(!this.pcManager)throw new Po("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,A)})}waitForPCReconnected(){return ZA(this,void 0,void 0,function*(){this.pcState=mC.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Sr(u9A),!this.pcManager)throw new Po("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=mC.Connected}catch(A){throw this.pcState=mC.Disconnected,wi.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 ya({destinationIdentities:[A],kind:Sn.RELIABLE,value:{case:"rpcResponse",value:new wz({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(g,Sn.RELIABLE)})}publishRpcAck(A,t){return ZA(this,void 0,void 0,function*(){const i=new ya({destinationIdentities:[A],kind:Sn.RELIABLE,value:{case:"rpcAck",value:new Sz({requestId:t})}});yield this.sendDataPacket(i,Sn.RELIABLE)})}sendDataPacket(A,t){return ZA(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const g=RVA(A);if(g){const o=yield this.e2eeManager.encryptData(g.toBinary());A.value={case:"encryptedPacket",value:new $QA({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}t===Sn.RELIABLE&&(A.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=A.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===Sn.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(Sn.RELIABLE);const t=this.dataChannelForKind(Sn.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(A),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(Sn.RELIABLE)})}waitForBufferStatusLow(A){return new AI((t,i)=>ZA(this,void 0,void 0,function*(){if(this.isBufferStatusLow(A))t();else{const n=()=>i(new Po("engine closed"));for(this.once(Ut.Closing,n);!this.dcBufferStatus.get(A);)yield Sr(10);this.off(Ut.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 Po("PC manager is closed");const o=n?i.pcManager.subscriber:i.pcManager.publisher,s=n?"Subscriber":"Publisher";if(!o)throw wi.internal("".concat(s," connection not set"));let r=!1;!n&&!i.dataChannelForKind(t,n)&&(i.createDataChannels(),r=!0),!r&&!n&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(r=!0),r&&i.negotiate().catch(c=>{Cn.error(c,i.logContext)});const a=i.dataChannelForKind(t,n);if((a==null?void 0:a.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 Sr(50)}throw wi.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!==vo.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return ZA(this,void 0,void 0,function*(){return new AI((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(Ut.Closing,n),this.pcManager.publisher.once(Tm.RTPVideoPayloadTypes,g=>{const o=new Map;g.forEach(s=>{const r=s.codec.toLowerCase();lVA(r)&&o.set(s.payload,r)}),this.emit(Ut.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(Ut.Closing,n)}}))})}dataChannelForKind(A,t){if(t){if(A===Sn.LOSSY)return this.lossyDCSub;if(A===Sn.RELIABLE)return this.reliableDCSub}else{if(A===Sn.LOSSY)return this.lossyDC;if(A===Sn.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(),r=this.pcManager.publisher.getRemoteDescription(),a=(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 Gz({answer:this.pcManager.mode==="publisher-only"?r?Am({sdp:r.sdp,type:r.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:a?Am({sdp:a.sdp,type:a.type}):void 0,subscription:new ex({trackSids:l,subscribe:!c,participantTracks:[]}),publishTracks:WWA(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:B,datachannelReceiveStates:this.reliableReceivedState.map((Q,h)=>new huA({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 puA({label:i.label,id:i.id,target:n}))};return t(this.dataChannelForKind(Sn.LOSSY),Tc.PUBLISHER),t(this.dataChannelForKind(Sn.RELIABLE),Tc.PUBLISHER),t(this.dataChannelForKind(Sn.LOSSY,!0),Tc.SUBSCRIBER),t(this.dataChannelForKind(Sn.RELIABLE,!0),Tc.SUBSCRIBER),A}clearReconnectTimeout(){this.reconnectTimeout&&mr.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){eI()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){eI()&&(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 y9A(e){return e!==void 0&&e>13}function seA(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 QdA{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 MC("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),da.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new MC("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),da.LengthExceeded)}}constructor(A,t,i,n){this.reader=t,this.totalByteSize=i,this._info=A,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class D9A extends QdA{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 jC,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:r,value:a}=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 r?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(a),{done:!1,value:a.content})}catch(r){throw g(),r}}),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 r=t.signal?A.withAbortSignal(t.signal):A;try{for(var a=!0,I=pE(r),c;c=yield I.next(),i=c.done,!i;a=!0){o=c.value,a=!1;const l=o;s.add(l)}}catch(l){n={error:l}}finally{try{!a&&!i&&(g=I.return)&&(yield g.call(I))}finally{if(n)throw n.error}}return Array.from(s)}()})}}class m9A extends QdA{constructor(A,t,i,n){super(A,t,i,n),this.receivedChunks=new Map}handleChunkReceived(A){var t;const i=wK(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 jC,n=null,g=null;if(this.signal){const s=this.signal;g=()=>{var r;(r=i.reject)===null||r===void 0||r.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,r;try{const{done:a,value:I}=yield Promise.race([A.read(),i.promise,(r=(s=this.outOfBandFailureRejectingFuture)===null||s===void 0?void 0:s.promise)!==null&&r!==void 0?r:new Promise(()=>{})]);if(a)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(I);let c;try{c=t.decode(I.content)}catch(l){throw new MC("Cannot decode datastream chunk ".concat(I.chunkIndex," as text: ").concat(l),da.DecodeFailed)}return{done:!1,value:c}}}catch(a){throw o(),a}}),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 r=t.signal?A.withAbortSignal(t.signal):A;try{for(var a=!0,I=pE(r),c;c=yield I.next(),i=c.done,!i;a=!0)o=c.value,a=!1,s+=o}catch(l){n={error:l}}finally{try{!a&&!i&&(g=I.return)&&(yield g.call(I))}finally{if(n)throw n.error}}return s}()})}}class S9A{constructor(){this.log=Cn,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 MC('A text stream handler for topic "'.concat(A,'" has already been set.'),da.HandlerAlreadyRegistered);this.textStreamHandlers.set(A,t)}unregisterTextStreamHandler(A){this.textStreamHandlers.delete(A)}registerByteStreamHandler(A,t){if(this.byteStreamHandlers.has(A))throw new MC('A byte stream handler for topic "'.concat(A,'" has already been set.'),da.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(r=>r[1].sendingParticipantIdentity===A),s=Array.from(this.byteStreamControllers.entries()).filter(r=>r[1].sendingParticipantIdentity===A);if(o.length>0||s.length>0){const r=new MC("Participant ".concat(A," unexpectedly disconnected in the middle of sending data"),da.AbnormalEnd);for(const[a,I]of s)(i=(t=I.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(t,r),this.byteStreamControllers.delete(a);for(const[a,I]of o)(g=(n=I.outOfBandFailureRejectingFuture).reject)===null||g===void 0||g.call(n,r),this.textStreamControllers.delete(a)}}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 jC;s.promise.catch(I=>{this.log.error(I)});const r={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:wK(A.timestamp),attributes:A.attributes,encryptionType:i},a=new ReadableStream({start:I=>{if(o=I,this.textStreamControllers.has(A.streamId))throw new MC("A data stream read is already in progress for a stream with id ".concat(A.streamId,"."),da.AlreadyOpened);this.byteStreamControllers.set(A.streamId,{info:r,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:s})}});g(new D9A(r,a,wK(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 jC;s.promise.catch(I=>{this.log.error(I)});const r={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},a=new ReadableStream({start:I=>{if(o=I,this.textStreamControllers.has(A.streamId))throw new MC("A data stream read is already in progress for a stream with id ".concat(A.streamId,"."),da.AlreadyOpened);this.textStreamControllers.set(A.streamId,{info:r,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:s})}});g(new m9A(r,a,wK(A.totalLength),s),{identity:t})}})}handleStreamChunk(A,t){const i=this.byteStreamControllers.get(A.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new MC("Encryption type mismatch for stream ".concat(A.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),da.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 MC("Encryption type mismatch for stream ".concat(A.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),da.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 MC("Encryption type mismatch for stream ".concat(A.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),da.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 MC("Encryption type mismatch for stream ".concat(A.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),da.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),A.attributes),n.controller.close()),this.byteStreamControllers.delete(A.streamId))}}class udA{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 w9A extends udA{}class k9A extends udA{}const reA=15e3;class M9A{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()),r=new Array(s?s.length+1:1).fill(0),a=(c,l)=>{var B;r[l]=c;const Q=r.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),a(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=>{a(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?bs.GCM:bs.NONE},s=new g_({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 CuA({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"?g3.UPDATE:g3.CREATE})}}),r=A==null?void 0:A.destinationIdentities,a=new ya({destinationIdentities:r,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,Sn.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 hVA(h,reA)){const p=new o_({content:d,streamId:g,chunkIndex:jh(I)}),y=new ya({destinationIdentities:r,value:{case:"streamChunk",value:p}});yield c.sendDataPacket(y,Sn.RELIABLE),I+=1}})},close(){return ZA(this,void 0,void 0,function*(){const h=new s_({streamId:g}),d=new ya({destinationIdentities:r,value:{case:"streamTrailer",value:h}});yield c.sendDataPacket(d,Sn.RELIABLE)})},abort(h){console.log("Sink error:",h)}});let B=()=>ZA(this,void 0,void 0,function*(){yield Q.close()});c.once(Ut.Closing,B);const Q=new w9A(l,o,()=>this.engine.off(Ut.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:r}=yield o.read();if(s)break;yield g.write(r)}return yield g.close(),g.info})}streamBytes(A){return ZA(this,void 0,void 0,function*(){var t,i,n,g,o,s;const r=(t=A==null?void 0:A.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=A==null?void 0:A.destinationIdentities,I={id:r,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?bs.GCM:bs.NONE},c=new g_({totalLength:jh((s=I.size)!==null&&s!==void 0?s:0),mimeType:I.mimeType,streamId:r,topic:I.topic,timestamp:jh(Date.now()),attributes:I.attributes,contentHeader:{case:"byteHeader",value:new cuA({name:I.name})}}),l=new ya({destinationIdentities:a,value:{case:"streamHeader",value:c}});yield this.engine.sendDataPacket(l,Sn.RELIABLE);let B=0;const Q=new Ua,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+reA),N=new ya({destinationIdentities:a,value:{case:"streamChunk",value:new o_({content:k,streamId:r,chunkIndex:jh(B)})}});yield h.sendDataPacket(N,Sn.RELIABLE),B+=1,S+=k.byteLength}}finally{D()}})},close(){return ZA(this,void 0,void 0,function*(){const m=new s_({streamId:r}),D=new ya({destinationIdentities:a,value:{case:"streamTrailer",value:m}});yield h.sendDataPacket(D,Sn.RELIABLE)})},abort(m){d.error("Sink error:",m)}});return new k9A(p,I)})}}class ddA extends ot{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?kt.Muted:kt.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(kt.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(),Hz)),VWA()&&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(kt.TimeSyncUpdate,{timestamp:n,rtpTimestamp:g}),this.rtpTimestamp=g)}};A()}}class N9A extends ddA{constructor(A,t,i,n,g,o){super(A,t,ot.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=nx(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;fB()&&this._mediaStreamTrack._setVolume(A),this.elementVolume=A}getVolume(){if(this.elementVolume)return this.elementVolume;if(fB())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(f3(t))return t.setSinkId(A)}))})}attach(A){const t=this.attachedElements.length===0;return A?super.attach(A):A=super.attach(),this.sinkId&&f3(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(kt.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(n=>{this.emit(kt.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 aY=100;class R9A extends ddA{constructor(A,t,i,n,g){super(A,t,ot.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=nx(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=xz(()=>{this.updateDimensions()},aY),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(A){super.setStreamState(A),this.log.debug("setStreamState",A),this.isAdaptiveStream&&A===ot.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 G9A(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((r,a)=>Math.max(r,a.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(r=>r.pictureInPicture),s=this.elementInfos.some(r=>r.visible)&&!g||o;if(!(this.lastVisible===s&&!A)){if(!s&&Date.now()-n<aY){mr.setTimeout(()=>{this.updateVisibility()},aY);return}this.lastVisible=s,this.emit(kt.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,r=o.height()*g;s+r>i+n&&(i=s,n=r)}((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(kt.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var A;const t=(A=this.adaptiveStreamSettings)===null||A===void 0?void 0:A.pixelDensity;return t==="screen"?FAA():t||(FAA()>2?2:1)}}class G9A{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=G0(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=G0(this.element),(g=this.handleVisibilityChanged)===null||g===void 0||g.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=G0(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=A,this.isIntersecting=t??k3(A),this.isPiP=eI()&&G0(A),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var A,t,i;this.isIntersecting=k3(this.element),this.isPiP=G0(this.element),this.element.handleResize=()=>{var n;(n=this.handleResize)===null||n===void 0||n.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,JAA().observe(this.element),_AA().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=JAA())===null||A===void 0||A.unobserve(this.element),(t=_AA())===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 G0(e){var A,t;return document.pictureInPictureElement===e?!0:!((A=window.documentPictureInPicture)===null||A===void 0)&&A.window?k3(e,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function k3(e,A){const t=A||window;let i=e.offsetTop,n=e.offsetLeft;const g=e.offsetWidth,o=e.offsetHeight,{hidden:s}=e,{display:r}=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&&r!=="none"}class BE extends GB.EventEmitter{constructor(A,t,i,n){var g;super(),this.metadataMuted=!1,this.encryption=bs.NONE,this.log=Cn,this.handleMuted=()=>{this.emit(kt.Muted)},this.handleUnmuted=()=>{this.emit(kt.Unmuted)},this.log=AQ((g=n==null?void 0:n.loggerName)!==null&&g!==void 0?g:$c.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=A,this.trackSid=t,this.trackName=i,this.source=ot.Source.Unknown}setTrack(A){this.track&&(this.track.off(kt.Muted,this.handleMuted),this.track.off(kt.Unmuted,this.handleUnmuted)),this.track=A,A&&(A.on(kt.Muted,this.handleMuted),A.on(kt.Unmuted,this.handleUnmuted))}get logContext(){var A;return Object.assign(Object.assign({},(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this)),Mn(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==bs.NONE}get audioTrack(){if(lB(this.track))return this.track}get videoTrack(){if(Kd(this.track))return this.track}updateInfo(A){this.trackSid=A.sid,this.trackName=A.name,this.source=ot.sourceFromProto(A.source),this.mimeType=A.mimeType,this.kind===ot.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={}))})(BE||(BE={}));class M3 extends BE{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(kt.Ended)},this.handleCpuConstrained=()=>{this.track&&Kd(this.track)&&this.emit(kt.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(A){this.track&&(this.track.off(kt.Ended,this.handleTrackEnded),this.track.off(kt.CpuConstrained,this.handleCpuConstrained)),super.setTrack(A),A&&(A.on(kt.Ended,this.handleTrackEnded),A.on(kt.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(lB(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(Vs.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Vs.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Vs.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Vs.TF_STEREO),!((A=this.options)===null||A===void 0)&&A.dtx||i.add(Vs.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Vs.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function gx(e,A){return ZA(this,void 0,void 0,function*(){e??(e={});let t=!1;const{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:g}=ndA(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 r=edA(g,adA,IdA),a=Fz(r),I=navigator.mediaDevices.getUserMedia(a);g.audio&&(Ar.userMediaPromiseMap.set("audioinput",I),I.catch(()=>Ar.userMediaPromiseMap.delete("audioinput"))),g.video&&(Ar.userMediaPromiseMap.set("videoinput",I),I.catch(()=>Ar.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?r.audio:r.video;(typeof Q=="boolean"||!Q)&&(Q={});let h;const d=B?a.audio:a.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=g9A(l,h,A);return y.kind===ot.Kind.Video?y.source=ot.Source.Camera:y.kind===ot.Kind.Audio&&(y.source=ot.Source.Microphone),y.mediaStream=c,lB(y)&&i?yield y.setProcessor(i):Kd(y)&&n&&(yield y.setProcessor(n)),y})))}catch(c){if(!t)throw c;return gx(Object.assign(Object.assign({},e),{audio:o,video:s}),A)}})}function b9A(e){return ZA(this,void 0,void 0,function*(){return(yield gx({audio:!1,video:!0}))[0]})}function U9A(e){return ZA(this,void 0,void 0,function*(){return(yield gx({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 v9A(e){switch(e){case fk.EXCELLENT:return su.Excellent;case fk.GOOD:return su.Good;case fk.POOR:return su.Poor;case fk.LOST:return su.Lost;default:return su.Unknown}}class hdA extends GB.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===EN.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]:EN.STANDARD;var r;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=su.Unknown,this.log=Cn,this.log=AQ((r=o==null?void 0:o.loggerName)!==null&&r!==void 0?r:$c.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 jC,this.once(Lt.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(ot.Source.Camera);return!(!((A=t==null?void 0:t.isMuted)!==null&&A!==void 0)||A)}get isMicrophoneEnabled(){var A;const t=this.getTrackPublication(ot.Source.Microphone);return!(!((A=t==null?void 0:t.isMuted)!==null&&A!==void 0)||A)}get isScreenShareEnabled(){return!!this.getTrackPublication(ot.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(Lt.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(Lt.ParticipantMetadataChanged,i)}_setName(A){const t=this.name!==A;this.name=A,t&&this.emit(Lt.ParticipantNameChanged,A)}_setAttributes(A){const t=XWA(this.attributes,A);this._attributes=A,Object.keys(t).length>0&&this.emit(Lt.AttributesChanged,t)}setPermissions(A){var t,i,n,g,o,s;const r=this.permissions,a=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,a&&this.emit(Lt.ParticipantPermissionsChanged,r),a}setIsSpeaking(A){A!==this.isSpeaking&&(this.isSpeaking=A,A&&(this.lastSpokeAt=new Date),this.emit(Lt.IsSpeakingChanged,A))}setConnectionQuality(A){const t=this._connectionQuality;this._connectionQuality=v9A(A),t!==this._connectionQuality&&this.emit(Lt.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=>lB(t.track)&&t.track.setAudioContext(A))}addTrackPublication(A){A.on(kt.Muted,()=>{this.emit(Lt.TrackMuted,A)}),A.on(kt.Unmuted,()=>{this.emit(Lt.TrackUnmuted,A)});const t=A;switch(t.track&&(t.track.sid=A.trackSid),this.trackPublications.set(A.trackSid,A),A.kind){case ot.Kind.Audio:this.audioTrackPublications.set(A.trackSid,A);break;case ot.Kind.Video:this.videoTrackPublications.set(A.trackSid,A);break}}}function K9A(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 uuA({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 F9A extends hdA{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=bs.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new jC)},this.handleReconnected=()=>{var s,r;(r=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||r===void 0||r.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var s,r,a,I,c,l;this.reconnectFuture&&(this.reconnectFuture.promise.catch(B=>this.log.warn(B.message,this.logContext)),(r=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((I=(a=this.signalConnectedFuture).reject)===null||I===void 0||I.call(a,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 r,a;s.participant&&this.updateInfo(s.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new jC),(a=(r=this.signalConnectedFuture).resolve)===null||a===void 0||a.call(r)},this.handleSignalRequestResponse=s=>{const{requestId:r,reason:a,message:I}=s,c=this.pendingSignalRequests.get(r);c&&(a!==bz.OK&&c.reject(new GAA(I,a)),this.pendingSignalRequests.delete(r))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let r=s.value.value,a=null,I=null;r.value.case==="payload"?a=r.value.value:r.value.case==="error"&&(I=Da.fromProto(r.value.value)),this.handleIncomingRpcResponse(r.requestId,a,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=>K9A(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,r)=>{if(r===void 0&&(r=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Mn(s)));return}this.engine.updateMuteStatus(s.sid,r)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Mn(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Mn(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const r=this.audioTrackPublications.get(s.sid);if(!r){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(r.trackSid,r.getTrackFeatures())},this.onTrackCpuConstrained=(s,r)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),Mn(r))),this.emit(Lt.LocalTrackCpuConstrained,s,r)},this.handleSubscribedQualityUpdate=s=>ZA(this,void 0,void 0,function*(){var r,a,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=pE(Q),p;p=yield d.next(),r=p.done,!r;h=!0){c=p.value,h=!1;const y=c;jWA(y)&&(this.log.debug("publish ".concat(y," for ").concat(B.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Mn(B))),yield this.publishAdditionalCodecForTrack(B.videoTrack,y,B.options))}}catch(y){a={error:y}}finally{try{!h&&!r&&(I=d.return)&&(yield I.call(d))}finally{if(a)throw a.error}}}),this.handleLocalTrackUnpublished=s=>{const r=this.trackPublications.get(s.trackSid);if(!r){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(r.track)},this.handleTrackEnded=s=>ZA(this,void 0,void 0,function*(){if(s.source===ot.Source.ScreenShare||s.source===ot.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Mn(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(sE(s)||UQ(s))try{if(eI())try{const r=yield navigator==null?void 0:navigator.permissions.query({name:s.source===ot.Source.Camera?"camera":"microphone"});if(r&&r.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),Mn(s))),r.onchange=()=>{r.state!=="denied"&&(s.isMuted||s.restartTrack(),r.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),Mn(s))),sE(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),Mn(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!==bs.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(Ut.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(Ut.Connected,this.handleReconnected).on(Ut.SignalConnected,this.handleSignalConnected).on(Ut.SignalRestarted,this.handleReconnected).on(Ut.SignalResumed,this.handleReconnected).on(Ut.Restarting,this.handleReconnecting).on(Ut.Resuming,this.handleReconnecting).on(Ut.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Ut.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Ut.Closing,this.handleClosing).on(Ut.SignalRequestResponse,this.handleSignalRequestResponse).on(Ut.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 AI((s,r)=>ZA(i,void 0,void 0,function*(){var a,I;try{let c=!1;const l=yield this.engine.client.sendUpdateLocalMetadata((a=n??this.metadata)!==null&&a!==void 0?a:"",(I=g??this.name)!==null&&I!==void 0?I:"",o),B=performance.now();for(this.pendingSignalRequests.set(l,{resolve:s,reject:Q=>{r(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 Sr(50)}r(new GAA("Request to update local metadata timed out","TimeoutError"))}catch(c){c instanceof Error?r(c):r(new Error(String(c)))}}))}()})}setCameraEnabled(A,t,i){return this.setTrackEnabled(ot.Source.Camera,A,t,i)}setMicrophoneEnabled(A,t,i){return this.setTrackEnabled(ot.Source.Microphone,A,t,i)}setScreenShareEnabled(A,t,i){return this.setTrackEnabled(ot.Source.ScreenShare,A,t,i)}setE2EEEnabled(A){return ZA(this,void 0,void 0,function*(){this.encryptionType=A?bs.GCM:bs.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 r;if(this.pendingPublishing.has(A)){const a=yield this.waitForPendingPublicationOfSource(A);return a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:A})),yield a==null?void 0:a.unmute(),a}this.pendingPublishing.add(A);try{switch(A){case ot.Source.Camera:r=yield this.createTracks({video:(g=i)!==null&&g!==void 0?g:!0});break;case ot.Source.Microphone:r=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case ot.Source.ScreenShare:r=yield this.createScreenTracks(Object.assign({},i));break;default:throw new fE(A)}}catch(a){throw r==null||r.forEach(I=>{I.stop()}),a instanceof Error&&this.emit(Lt.MediaDevicesError,a,d3(A)),this.pendingPublishing.delete(A),a}for(const a of r){const I=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);A===ot.Source.Microphone&&lB(a)&&I.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),a.startPreConnectBuffer())}try{const a=[];for(const c of r)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Mn(c))),a.push(this.publishTrack(c,n));[s]=yield Promise.all(a)}catch(a){throw r==null||r.forEach(I=>{I.stop()}),a}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===ot.Source.ScreenShare){s=yield this.unpublishTrack(s.track);const r=this.getTrackPublication(ot.Source.ScreenShareAudio);r&&r.track&&this.unpublishTrack(r.track)}else yield s.mute();return s})}enableCameraAndMicrophone(){return ZA(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(ot.Source.Camera)||this.pendingPublishing.has(ot.Source.Microphone))){this.pendingPublishing.add(ot.Source.Camera),this.pendingPublishing.add(ot.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(ot.Source.Camera),this.pendingPublishing.delete(ot.Source.Microphone)}}})}createTracks(A){return ZA(this,void 0,void 0,function*(){var t,i;A??(A={});const n=edA(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 gx(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(s=>(lB(s)&&(this.microphoneError=void 0,s.setAudioContext(this.audioContext),s.source=ot.Source.Microphone,this.emit(Lt.AudioStreamAcquired)),Kd(s)&&(this.cameraError=void 0,s.source=ot.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 vz("getDisplayMedia not supported");A.resolution===void 0&&!sVA()&&(A.resolution=Kz.h1080fps30.resolution);const t=ZWA(A),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(n.length===0)throw new fE("no video track found");const g=new I_(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});g.source=ot.Source.ScreenShare,A.contentHint&&(g.mediaStreamTrack.contentHint=A.contentHint);const o=[g];if(i.getAudioTracks().length>0){this.emit(Lt.AudioStreamAcquired);const s=new a_(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=ot.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,r,a,I;sE(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 ot.Source.Microphone:p="audioinput";break;case ot.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 I_(i,c,!0,{loggerName:g.roomOptions.loggerName,loggerContextCb:()=>g.logContext});break;default:throw new fE("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),Mn(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=(r=B.forceStereo)!==null&&r!==void 0?r: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),Mn(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."),(a=B.dtx)!==null&&a!==void 0||(B.dtx=!1),(I=B.red)!==null&&I!==void 0||(B.red=!1)),!aVA()&&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!==bg.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Mn(i)}));let m=!1;const D=setTimeout(()=>{m=!0,i.stop(),y(new RAA("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 jC),this.signalConnectedFuture.promise}hasPermissionsToPublish(A){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Mn(A))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(n=>$WA(n)).includes(A.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Mn(A))),!1)}publish(A,t,i){return ZA(this,void 0,void 0,function*(){var n,g,o,s,r,a,I,c,l,B;if(!this.hasPermissionsToPublish(A))throw new RAA("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>Lm(A)&&M.source===A.source)&&A.source!==ot.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(A.source),Object.assign(Object.assign({},this.logContext),Mn(A))),t.stopMicTrackOnMute&&lB(A)&&(A.stopOnMute=!0),A.source===ot.Source.ScreenShare&&Cf()&&(t.simulcast=!1),t.videoCodec==="av1"&&!nVA()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!gVA()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=m3),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===lM(M.mime))||(t.videoCodec=lM(this.enabledPublishVideoCodecs[0].mime)));const h=t.videoCodec;A.on(kt.Muted,this.onTrackMuted),A.on(kt.Unmuted,this.onTrackUnmuted),A.on(kt.Ended,this.handleTrackEnded),A.on(kt.UpstreamPaused,this.onTrackUpstreamPaused),A.on(kt.UpstreamResumed,this.onTrackUpstreamResumed),A.on(kt.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const d=[],p=!(!((n=t.dtx)!==null&&n!==void 0)||n),y=A.getSourceTrackSettings();y.autoGainControl&&d.push(Vs.TF_AUTO_GAIN_CONTROL),y.echoCancellation&&d.push(Vs.TF_ECHO_CANCELLATION),y.noiseSuppression&&d.push(Vs.TF_NOISE_SUPPRESSION),y.channelCount&&y.channelCount>1&&d.push(Vs.TF_STEREO),p&&d.push(Vs.TF_NO_DTX),sE(A)&&A.hasPreConnectBuffer&&d.push(Vs.TF_PRECONNECT_BUFFER);const m=new QN({cid:A.mediaStreamTrack.id,name:t.name,type:ot.kindToProto(A.kind),muted:A.isMuted,source:ot.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===ot.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:bS.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),Mn(A)),{dims:M}))}m.width=M.width,m.height=M.height,UQ(A)&&(qc(h)&&(A.source===ot.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),Mn(A))))),t.scalabilityMode=(r=t.scalabilityMode)!==null&&r!==void 0?r:"L3T3_KEY"),m.simulcastCodecs=[new s3({codec:h,cid:A.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:m3}),t.backupCodec&&h!==t.backupCodec.codec&&m.encryption===bs.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new s3({codec:t.backupCodec.codec,cid:""})))),D=w3(A.source===ot.Source.ScreenShare,m.width,m.height,t),m.layers=neA(m.width,m.height,D,qc(t.videoCodec))}else A.kind===ot.Kind.Audio&&(D=[{maxBitrate:(a=t.audioPreset)===null||a===void 0?void 0:a.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 Po("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 Po("pcManager is not ready");if(A.sender=yield this.engine.createSender(A,t,D),this.emit(Lt.LocalSenderCreated,A.sender,A),UQ(A)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=E9A(A)),A.setDegradationPreference(t.degradationPreference)),D)if(Cf()&&A.kind===ot.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&&qc(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),Mn(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===ot.Kind.Video){const w=lM(M);w!==h&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Mn(A)),{codec:w})),t.videoCodec=w,D=w3(A.source===ot.Source.ScreenShare,m.width,m.height,t))}yield S()}const G=new M3(A.kind,k,A,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(G.on(kt.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})),UQ(A)?A.startMonitor(this.engine.client):sE(A)&&A.startMonitor(),this.addTrackPublication(G),this.emit(Lt.LocalTrackPublished,G),sE(A)&&k.audioFeatures.includes(Vs.TF_PRECONNECT_BUFFER)){const M=A.getPreConnectBuffer(),w=A.getPreConnectBufferMimeType();this.on(Lt.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),Mn(A))),A.stopPreConnectBuffer()}}),M&&new Promise((_,K)=>ZA(this,void 0,void 0,function*(){var J,T,v,U,x,q;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Mn(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),Mn(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((q=y.channelCount)!==null&&q!==void 0?q:"1")}});try{for(var z=!0,Z=pE(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){T={error:gA}}finally{try{!z&&!J&&(v=Z.return)&&(yield v.call(Z))}finally{if(T)throw T.error}}yield pA.close(),_()}catch(aA){K(aA)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Mn(A)))}).catch(_=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Mn(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!==bs.NONE)return;let g;if(this.trackPublications.forEach(B=>{B.track&&B.track===A&&(g=B)}),!g)throw new fE("track is not published");if(!UQ(A))throw new fE("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=c9A(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),Mn(A)));return}const r=A.addSimulcastTrack(t,s);if(!r)return;const a=new QN({cid:r.mediaStreamTrack.id,type:ot.kindToProto(A.kind),muted:A.isMuted,source:ot.sourceToProto(A.source),sid:A.sid,simulcastCodecs:[{codec:o.videoCodec,cid:r.mediaStreamTrack.id}]});if(a.layers=neA(a.width,a.height,s),!this.engine||this.engine.isClosed)throw new Po("cannot publish track when not connected");const I=()=>ZA(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(A,r,o,s),yield this.engine.negotiate()}),l=(yield Promise.all([this.engine.addTrack(a),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 a=this.pendingPublishPromises.get(A);a&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Mn(A))),yield a)}const g=this.getPublicationForTrack(A),o=g?Mn(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(kt.Muted,this.onTrackMuted),A.off(kt.Unmuted,this.onTrackUnmuted),A.off(kt.Ended,this.handleTrackEnded),A.off(kt.UpstreamPaused,this.onTrackUpstreamPaused),A.off(kt.UpstreamResumed,this.onTrackUpstreamResumed),A.off(kt.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 r=A.sender;if(A.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<vo.FAILED&&r)try{for(const a of this.engine.pcManager.publisher.getTransceivers())a.sender===r&&(a.direction="inactive",s=!0);if(this.engine.removeTrack(r)&&(s=!0),UQ(A)){for(const[,a]of A.simulcastCodecs)a.sender&&(this.engine.removeTrack(a.sender)&&(s=!0),a.sender=void 0);A.simulcastCodecs.clear()}}catch(a){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:a}))}switch(this.trackPublications.delete(g.trackSid),g.kind){case ot.Kind.Audio:this.audioTrackPublications.delete(g.trackSid);break;case ot.Kind.Video:this.videoTrackPublications.delete(g.trackSid);break}return this.emit(Lt.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 AI((g,o)=>ZA(i,void 0,void 0,function*(){try{const s=[];this.trackPublications.forEach(r=>{r.track&&(t&&(r.options=Object.assign(Object.assign({},r.options),t)),s.push(r))}),yield Promise.all(s.map(r=>ZA(this,void 0,void 0,function*(){const a=r.track;yield this.unpublishTrack(a,!1),n&&!a.isMuted&&a.source!==ot.Source.ScreenShare&&a.source!==ot.Source.ScreenShareAudio&&(sE(a)||UQ(a))&&!a.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:r.trackSid})),yield a.restartTrack()),yield this.publishOrRepublishTrack(a,r.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?Sn.RELIABLE:Sn.LOSSY,o=n.destinationIdentities,s=n.topic;let r=new Dz({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:s});const a=new ya({kind:g,value:{case:"user",value:r}});yield i.engine.sendDataPacket(a,g)}()})}publishDtmf(A,t){return ZA(this,void 0,void 0,function*(){const i=new ya({kind:Sn.RELIABLE,value:{case:"sipDtmf",value:new tuA({code:A,digit:t})}});yield this.engine.sendDataPacket(i,Sn.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 ya({value:{case:"chatMessage",value:new n_(Object.assign(Object.assign({},i),{timestamp:ro.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,Sn.RELIABLE),this.emit(Lt.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 ya({value:{case:"chatMessage",value:new n_(Object.assign(Object.assign({},i),{timestamp:ro.parse(i.timestamp),editTimestamp:ro.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,Sn.RELIABLE),this.emit(Lt.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 AI((r,a)=>ZA(this,void 0,void 0,function*(){var I,c,l,B;if(Yz(n)>cdA){a(Da.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&&yB((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){a(Da.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),a(Da.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),a(Da.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?a(m):r(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 ya({destinationIdentities:[A],kind:Sn.RELIABLE,value:{case:"rpcRequest",value:new mz({id:t,method:i,payload:n,responseTimeoutMs:g,version:1})}});yield this.engine.sendDataPacket(o,Sn.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,Da.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),Mn(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 jC),this.activeAgentFuture.promise)}getPublicationForTrack(A){let t;return this.trackPublications.forEach(i=>{const n=i.track;n&&(A instanceof MediaStreamTrack?(sE(n)||UQ(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 Sr(20)}})}}class _9A extends BE{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(kt.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 ex({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new nuA({participantSid:"",trackSids:[this.trackSid]})]});this.emit(kt.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?BE.SubscriptionStatus.Unsubscribed:super.isSubscribed?BE.SubscriptionStatus.Subscribed:BE.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?BE.PermissionStatus.Allowed:BE.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||(tY(this.track)&&(this.requestedVideoDimensions=A),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(A){this.isManualOperationAllowed()&&tY(this.track)&&this.fps!==A&&(this.fps=A,this.emitTrackUpdate())}get videoQuality(){var A;return(A=this.requestedMaxQuality)!==null&&A!==void 0?A:HI.HIGH}setTrack(A){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==A&&(n&&(n.off(kt.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(kt.VisibilityChanged,this.handleVisibilityChange),n.off(kt.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(kt.Unsubscribed,n)),super.setTrack(A),A&&(A.sid=this.trackSid,A.on(kt.VideoDimensionsChanged,this.handleVideoDimensionsChange),A.on(kt.VisibilityChanged,this.handleVisibilityChange),A.on(kt.Ended,this.handleEnded),this.emit(kt.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(kt.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?kt.Muted:kt.Unmuted)}emitSubscriptionUpdateIfChanged(A){const t=this.subscriptionStatus;A!==t&&this.emit(kt.SubscriptionStatusChanged,t,A)}emitPermissionUpdateIfChanged(A){this.permissionStatus!==A&&this.emit(kt.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 tY(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const A=new luA({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===ot.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)UAA(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=AVA(this.trackInfo,this.requestedMaxQuality);i&&UAA(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:HI.HIGH})),A.quality=HI.HIGH)}this.emit(kt.UpdateSettings,A)}}class C_ extends hdA{static fromParticipantInfo(A,t,i){return new C_(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 r=arguments.length>7&&arguments[7]!==void 0?arguments[7]:EN.STANDARD;super(t,i||"",n,g,o,s,r),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(kt.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Mn(A)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),A.on(kt.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),A.on(kt.SubscriptionPermissionChanged,t=>{this.emit(Lt.TrackSubscriptionPermissionChanged,A,t)}),A.on(kt.SubscriptionStatusChanged,t=>{this.emit(Lt.TrackSubscriptionStatusChanged,A,t)}),A.on(kt.Subscribed,t=>{this.emit(Lt.TrackSubscribed,t,A)}),A.on(kt.Unsubscribed,t=>{this.emit(Lt.TrackUnsubscribed,t,A)}),A.on(kt.SubscriptionFailed,t=>{this.emit(Lt.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]:ot.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]:ot.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(Lt.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),Mn(s))),this.emit(Lt.TrackSubscriptionFailed,t);return}const r=A.kind==="video";let a;return r?a=new R9A(A,t,n,g):a=new N9A(A,t,n,this.audioContext,this.audioOutput),a.source=s.source,a.isMuted=s.isMuted,a.setMediaStream(i),a.start(),s.setTrack(a),this.volumeMap.has(s.source)&&y3(a)&&lB(a)&&a.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 r=ot.kindFromProto(n.type);if(!r)return;s=new _9A(r,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 a=Array.from(this.trackPublications.values()).find(I=>I.source===(s==null?void 0:s.source));a&&s.source!==ot.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:Mn(a),newTrack:Mn(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),Mn(n))),this.unpublishTrack(n.trackSid,!0))}),i.forEach(n=>{this.emit(Lt.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 ot.Kind.Audio:this.audioTrackPublications.delete(A);break;case ot.Kind.Video:this.videoTrackPublications.delete(A);break}t&&this.emit(Lt.TrackUnpublished,i)}setAudioOutput(A){return ZA(this,void 0,void 0,function*(){this.audioOutput=A;const t=[];this.audioTrackPublications.forEach(i=>{var n;lB(i.track)&&y3(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 Zn;(function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"})(Zn||(Zn={}));const J9A=4*1e3;class vS extends GB.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(A){var t,i,n,g,o;if(super(),t=this,this.state=Zn.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Cn,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(s,r,a)=>ZA(this,void 0,void 0,function*(){var I;if(!oVA())throw fB()?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===Zn.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(Zn.Connecting),((I=this.regionUrlProvider)===null||I===void 0?void 0:I.getServerUrl().toString())!==rdA(s)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),US(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Xn(s,r):this.regionUrlProvider.updateToken(r),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 wi.cancelled("Connection attempt aborted");yield this.attemptConnection(d??s,r,a,m),this.abortController=void 0,Q()}catch(D){if(this.regionUrlProvider&&D instanceof wi&&D.reason!==vg.Cancelled&&D.reason!==vg.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 wi&&(k.status===401||k.reason===vg.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),h(k);return}}[vg.InternalError,vg.ServerUnreachable,vg.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,xAA(D)),h(D))}else{let S=Oc.UNKNOWN_REASON;D instanceof wi&&(S=xAA(D)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,S),h(D)}}}),B=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new jC((Q,h)=>{l(Q,h,B)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,r,a,I,c,l)=>ZA(this,void 0,void 0,function*(){var B,Q,h;const d=yield a.join(s,r,{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 qWA("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 r=s.participant;if(this.localParticipant.sid=r.sid,this.localParticipant.identity=r.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([r,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,r,a,I)=>ZA(this,void 0,void 0,function*(){var c,l;this.state===Zn.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({},qz),a),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,r,this.engine,this.connOptions,this.options,I);this.applyJoinResponse(B),this.setupLocalParticipantEvents(),this.emit(ut.SignalConnected)}catch(B){yield this.engine.close(),this.recreateEngine();const Q=I.signal.aborted?wi.cancelled("Signal connection aborted"):wi.serverUnreachable("could not establish signal connection");throw B instanceof Error&&(Q.message="".concat(Q.message,": ").concat(B.message)),B instanceof wi&&(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(),wi.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,I)}catch(B){throw yield this.engine.close(),this.recreateEngine(),B}eI()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),eI()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Zn.Connected),this.emit(ut.Connected),xm.getInstance().resetFailedConnectionAttempts(s),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var s=arguments.length,r=new Array(s),a=0;a<s;a++)r[a]=arguments[a];return ZA(t,[...r],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===Zn.Disconnected){I.log.debug("already disconnected",I.logContext);return}if(I.log.info("disconnect from room",Object.assign({},I.logContext)),I.state===Zn.Connecting||I.state===Zn.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,wi.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,Oc.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=[],r=sI();if(r&&r.os==="iOS"){const a="livekit-dummy-audio-el";let I=document.getElementById(a);if(!I){I=document.createElement("audio"),I.id=a,I.autoplay=!0,I.hidden=!0;const c=eY();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(ut.Disconnected,()=>{I==null||I.remove(),I=null})}s.push(I)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(I=>{I.track&&I.track.attachedElements.forEach(c=>{s.push(c)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>ZA(this,void 0,void 0,function*(){const s=[];for(const r of this.remoteParticipants.values())r.videoTrackPublications.forEach(a=>{var I;(I=a.track)===null||I===void 0||I.attachedElements.forEach(c=>{s.includes(c)||s.push(c)})});yield Promise.all(s.map(r=>r.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(r=>{r.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(Zn.Reconnecting)&&this.emit(ut.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(r){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:r}))}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(Zn.Connected),this.emit(ut.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(r=>{var a;if(r.identity===this.localParticipant.identity){this.localParticipant.updateInfo(r);return}r.identity===""&&(r.identity=(a=this.sidToIdentity.get(r.sid))!==null&&a!==void 0?a:"");let I=this.remoteParticipants.get(r.identity);r.state===vm.DISCONNECTED?this.handleParticipantDisconnected(r.identity,I):I=this.getOrCreateParticipant(r.identity,r)})},this.handleActiveSpeakersUpdate=s=>{const r=[],a={};s.forEach(I=>{if(a[I.sid]=!0,I.sid===this.localParticipant.sid)this.localParticipant.audioLevel=I.level,this.localParticipant.setIsSpeaking(!0),r.push(this.localParticipant);else{const c=this.getRemoteParticipantBySid(I.sid);c&&(c.audioLevel=I.level,c.setIsSpeaking(!0),r.push(c))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(I=>{a[I.sid]||(I.audioLevel=0,I.setIsSpeaking(!1))}),this.activeSpeakers=r,this.emitWhenConnected(ut.ActiveSpeakersChanged,r)},this.handleSpeakersChanged=s=>{const r=new Map;this.activeSpeakers.forEach(I=>{const c=this.remoteParticipants.get(I.identity);c&&c.sid!==I.sid||r.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?r.set(I.sid,c):r.delete(I.sid))});const a=Array.from(r.values());a.sort((I,c)=>c.audioLevel-I.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(ut.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(r=>{const a=this.getRemoteParticipantBySid(r.participantSid);if(!a)return;const I=a.getTrackPublicationBySid(r.trackSid);if(!I||!I.track)return;const c=ot.streamStateFromProto(r.state);I.track.setStreamState(c),c!==I.track.streamState&&(a.emit(Lt.TrackStreamStateChanged,I,I.track.streamState),this.emitWhenConnected(ut.TrackStreamStateChanged,I,I.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const r=this.getRemoteParticipantBySid(s.participantSid);if(!r)return;const a=r.getTrackPublicationBySid(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const r=Array.from(this.remoteParticipants.values()).find(I=>I.trackPublications.has(s.trackSid));if(!r)return;const a=r.getTrackPublicationBySid(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=(s,r)=>{const a=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(a,s.value.value,s.kind,r);else if(s.value.case==="transcription")this.handleTranscription(a,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(a,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(a,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,a);else if(s.value.case==="streamHeader"||s.value.case==="streamChunk"||s.value.case==="streamTrailer")this.handleDataStream(s,r);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,r,a,I)=>{this.emit(ut.DataReceived,r.payload,s,a,r.topic,I),s==null||s.emit(Lt.DataReceived,r.payload,a,I)},this.handleSipDtmf=(s,r)=>{this.emit(ut.SipDTMFReceived,r,s),s==null||s.emit(Lt.SipDTMFReceived,r)},this.handleTranscription=(s,r)=>{const a=r.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(r.transcribedParticipantIdentity),I=a==null?void 0:a.trackPublications.get(r.trackId),c=EVA(r,this.transcriptionReceivedTimes);I==null||I.emit(kt.TranscriptionReceived,c),a==null||a.emit(Lt.TranscriptionReceived,c,I),this.emit(ut.TranscriptionReceived,c,a,I)},this.handleChatMessage=(s,r)=>{const a=QVA(r);this.emit(ut.ChatMessage,a,s)},this.handleMetrics=(s,r)=>{this.emit(ut.MetricsReceived,s,r)},this.handleDataStream=(s,r)=>{this.incomingDataStreamManager.handleDataStreamPacket(s,r)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(ut.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(ut.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ut.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ut.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>ZA(this,void 0,void 0,function*(){var s;((s=sI())===null||s===void 0?void 0:s.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(ut.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const r=this.roomInfo;this.roomInfo=s,r&&r.metadata!==s.metadata&&this.emitWhenConnected(ut.RoomMetadataChanged,s.metadata),(r==null?void 0:r.activeRecording)!==s.activeRecording&&this.emitWhenConnected(ut.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(r=>{if(r.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(r.quality);return}const a=this.getRemoteParticipantBySid(r.participantSid);a&&a.setConnectionQuality(r.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(ut.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(ut.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(ut.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(ut.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(ut.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var r;(r=s==null?void 0:s.onPublish)===null||r===void 0||r.call(s,this)},this.onLocalTrackPublished=s=>ZA(this,void 0,void 0,function*(){var r,a,I,c,l,B;(r=s.track)===null||r===void 0||r.on(kt.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(kt.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(ut.LocalTrackPublished,s,this.localParticipant),sE(s.track)&&(yield s.track.checkForSilence())&&this.emit(ut.LocalAudioSilenceDetected,s);const Q=yield(B=s.track)===null||B===void 0?void 0:B.getDeviceId(!1),h=d3(s.source);h&&Q&&Q!==this.localParticipant.activeDeviceMap.get(h)&&(this.localParticipant.activeDeviceMap.set(h,Q),this.emit(ut.ActiveDeviceChanged,h,Q))}),this.onLocalTrackUnpublished=s=>{var r,a;(r=s.track)===null||r===void 0||r.off(kt.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(kt.Restarted,this.onLocalTrackRestarted),this.emit(ut.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>ZA(this,void 0,void 0,function*(){const r=yield s.getDeviceId(!1),a=d3(s.source);a&&r&&r!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(r," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,r),this.emit(ut.ActiveDeviceChanged,a,r))}),this.onLocalConnectionQualityChanged=s=>{this.emit(ut.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=(s,r)=>{this.emit(ut.MediaDevicesError,s,r)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(ut.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(ut.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},ZVA),A),this.log=AQ((i=this.options.loggerName)!==null&&i!==void 0?i:$c.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},adA),A==null?void 0:A.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},IdA),A==null?void 0:A.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},zVA),A==null?void 0:A.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new S9A,this.outgoingDataStreamManager=new M9A(this.engine,this.log),this.disconnectLock=new Ua,this.localParticipant=new F9A("","",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)),eI()){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}),vS.cleanupRegistry&&vS.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 GVA(i,t),this.e2eeManager.on(Su.ParticipantEncryptionStatusChanged,(n,g)=>{dVA(g)&&(this.isE2EEEnabled=n),this.emit(ut.ParticipantEncryptionStatusChanged,n,g)}),this.e2eeManager.on(Su.EncryptionError,(n,g)=>{const o=g?this.getParticipantByIdentity(g):void 0;this.emit(ut.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===Zn.Disconnected?AI.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?AI.resolve(this.roomInfo.sid):new AI((A,t)=>{const i=n=>{n.sid!==""&&(this.engine.off(Ut.RoomUpdate,i),A(n.sid))};this.engine.on(Ut.RoomUpdate,i),this.once(ut.Disconnected,()=>{this.engine.off(Ut.RoomUpdate,i),t(new Po("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 f9A(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Ut.ParticipantUpdate,this.handleParticipantUpdates).on(Ut.RoomUpdate,this.handleRoomUpdate).on(Ut.SpeakersChanged,this.handleSpeakersChanged).on(Ut.StreamStateChanged,this.handleStreamStateUpdate).on(Ut.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Ut.SubscriptionError,this.handleSubscriptionError).on(Ut.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Ut.MediaTrackAdded,(A,t,i)=>{this.onTrackAdded(A,t,i)}).on(Ut.Disconnected,A=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,A)}).on(Ut.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Ut.DataPacketReceived,this.handleDataPacket).on(Ut.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Zn.SignalReconnecting)&&this.emit(ut.SignalReconnecting)}).on(Ut.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Zn.Connected)&&this.emit(ut.Reconnected)}).on(Ut.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Zn.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(Ut.Restarting,this.handleRestarting).on(Ut.SignalRestarted,this.handleSignalRestarted).on(Ut.Offline,()=>{this.setAndEmitConnectionState(Zn.Reconnecting)&&this.emit(ut.Reconnecting)}).on(Ut.DCBufferStatusChanged,(A,t)=>{this.emit(ut.DCBufferStatusChanged,A,t)}).on(Ut.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(Lt.LocalTrackSubscribed,t),this.emitWhenConnected(ut.LocalTrackSubscribed,t,this.localParticipant)}).on(Ut.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(ut.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 Ar.getInstance().getDevices(A,t)}prepareConnection(A,t){return ZA(this,void 0,void 0,function*(){if(this.state===Zn.Disconnected){this.log.debug("prepareConnection to ".concat(A),this.logContext);try{if(US(new URL(A))&&t){this.regionUrlProvider=new Xn(A,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Zn.Disconnected&&(this.regionUrl=i,yield fetch(dN(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(dN(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 Jl({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new Jl({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new Jl({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new Jl({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 Jl({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 Jl({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 Jl({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 tx({reason:Oc.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 Jl({scenario:{case:"subscriberBandwidth",value:jh(t)}});break;case"leave-full-reconnect":n=new Jl({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,r,a,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===ot.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=(r=g.getActiveDevice(i))!==null&&r!==void 0?r:g.options.videoCaptureDefaults.deviceId;g.options.videoCaptureDefaults.deviceId=d;const y=Array.from(g.localParticipant.videoTrackPublications.values()).filter(D=>D.source===ot.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,!f3()&&!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=(a=yield Ar.getInstance().normalizeDeviceId("audiooutput",n))!==null&&a!==void 0?a:""),(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(ut.ActiveDeviceChanged,i,n)),Q}()})}setupLocalParticipantEvents(){this.localParticipant.on(Lt.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Lt.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(Lt.AttributesChanged,this.onLocalAttributesChanged).on(Lt.TrackMuted,this.onLocalTrackMuted).on(Lt.TrackUnmuted,this.onLocalTrackUnmuted).on(Lt.LocalTrackPublished,this.onLocalTrackPublished).on(Lt.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Lt.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Lt.MediaDevicesError,this.onMediaDevicesError).on(Lt.AudioStreamAcquired,this.startAudio).on(Lt.ChatMessage,this.onLocalChatMessageSent).on(Lt.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===Zn.Connecting||this.state===Zn.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(ut.Reconnected,c),this.off(ut.Connected,c),this.off(ut.Disconnected,l)};this.once(ut.Reconnected,c),this.once(ut.Connected,c),this.once(ut.Disconnected,l);return}if(this.state===Zn.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=iVA(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 r=Array.from(this.remoteParticipants.values()).find(c=>c.sid===g);if(!r){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 a;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?a=this.options.adaptiveStream:a={});const I=r.addSubscribedMediaTrack(A,s,t,i,a);I!=null&&I.isEncrypted&&!this.e2eeManager&&this.emit(ut.EncryptionError,new Error("Encrypted ".concat(I.source," track received from participant ").concat(r.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!==Zn.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,r;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()):(r=g.track)===null||r===void 0||r.stopMonitor()}),this.localParticipant.off(Lt.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Lt.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(Lt.AttributesChanged,this.onLocalAttributesChanged).off(Lt.TrackMuted,this.onLocalTrackMuted).off(Lt.TrackUnmuted,this.onLocalTrackUnmuted).off(Lt.LocalTrackPublished,this.onLocalTrackPublished).off(Lt.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Lt.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Lt.MediaDevicesError,this.onMediaDevicesError).off(Lt.AudioStreamAcquired,this.startAudio).off(Lt.ChatMessage,this.onLocalChatMessageSent).off(Lt.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),eI()&&(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(Zn.Disconnected),this.emit(ut.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(ut.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,Da.builtIn("UNSUPPORTED_VERSION"));return}const s=this.rpcHandlers.get(i);if(!s){yield this.engine.publishRpcResponse(A,t,null,Da.builtIn("UNSUPPORTED_METHOD"));return}let r=null,a=null;try{const I=yield s({requestId:t,callerIdentity:A,payload:n,responseTimeout:g});Yz(I)>cdA?(r=Da.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):a=I}catch(I){I instanceof Da?r=I:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),I),r=Da.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(A,t,a,r)})}selectDefaultDevices(){return ZA(this,void 0,void 0,function*(){var A,t,i;const n=Ar.getInstance().previousDevices,g=yield Ar.getInstance().getDevices(void 0,!1),o=sI();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let r of g){const a=n.find(I=>I.deviceId===r.deviceId);a&&a.label!==""&&a.kind===r.kind&&a.label!==r.label&&this.getActiveDevice(r.kind)==="default"&&this.emit(ut.ActiveDeviceChanged,r.kind,r.deviceId)}const s=["audiooutput","audioinput","videoinput"];for(let r of s){const a=zWA(r),I=this.localParticipant.getTrackPublication(a);if(I&&(!((A=I.track)===null||A===void 0)&&A.isUserProvided))continue;const c=g.filter(B=>B.kind===r),l=this.getActiveDevice(r);if(l===((t=n.filter(B=>B.kind===r)[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(r,c[0].deviceId);continue}r==="audioinput"&&!uN()||r==="videoinput"||c.length>0&&!c.find(B=>B.deviceId===this.getActiveDevice(r))&&(r!=="audiooutput"||!uN())&&(yield this.switchActiveDevice(r,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=idA())!==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(),Sr(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(ut.AudioPlaybackStatusChanged,i))})}createParticipant(A,t){var i;let n;return t?n=C_.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):n=new C_(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(ut.ParticipantConnected,i),i.on(Lt.TrackPublished,n=>{this.emitWhenConnected(ut.TrackPublished,n,i)}).on(Lt.TrackSubscribed,(n,g)=>{n.kind===ot.Kind.Audio?(n.on(kt.AudioPlaybackStarted,this.handleAudioPlaybackStarted),n.on(kt.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):n.kind===ot.Kind.Video&&(n.on(kt.VideoPlaybackFailed,this.handleVideoPlaybackFailed),n.on(kt.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(ut.TrackSubscribed,n,g,i)}).on(Lt.TrackUnpublished,n=>{this.emit(ut.TrackUnpublished,n,i)}).on(Lt.TrackUnsubscribed,(n,g)=>{this.emit(ut.TrackUnsubscribed,n,g,i)}).on(Lt.TrackMuted,n=>{this.emitWhenConnected(ut.TrackMuted,n,i)}).on(Lt.TrackUnmuted,n=>{this.emitWhenConnected(ut.TrackUnmuted,n,i)}).on(Lt.ParticipantMetadataChanged,n=>{this.emitWhenConnected(ut.ParticipantMetadataChanged,n,i)}).on(Lt.ParticipantNameChanged,n=>{this.emitWhenConnected(ut.ParticipantNameChanged,n,i)}).on(Lt.AttributesChanged,n=>{this.emitWhenConnected(ut.ParticipantAttributesChanged,n,i)}).on(Lt.ConnectionQualityChanged,n=>{this.emitWhenConnected(ut.ConnectionQualityChanged,n,i)}).on(Lt.ParticipantPermissionsChanged,n=>{this.emitWhenConnected(ut.ParticipantPermissionsChanged,n,i)}).on(Lt.TrackSubscriptionStatusChanged,(n,g)=>{this.emitWhenConnected(ut.TrackSubscriptionStatusChanged,n,g,i)}).on(Lt.TrackSubscriptionFailed,(n,g)=>{this.emit(ut.TrackSubscriptionFailed,n,i,g)}).on(Lt.TrackSubscriptionPermissionChanged,(n,g)=>{this.emitWhenConnected(ut.TrackSubscriptionPermissionChanged,n,g,i)}).on(Lt.Active,()=>{this.emitWhenConnected(ut.ParticipantActive,i),i.kind===EN.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&&uVA(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=mr.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,Oc.STATE_MISMATCH))):A=0},J9A)}clearConnectionReconcile(){this.connectionReconcileInterval&&mr.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(A){return A===this.state?!1:(this.state=A,this.emit(ut.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===Zn.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([A,i]);else if(this.state===Zn.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 XL({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ro.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(ut.SignalConnected),this.emit(ut.Connected),this.setAndEmitConnectionState(Zn.Connected),o.video){const r=new M3(ot.Kind.Video,new XD({source:ls.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:xc.AUDIO,name:"video-dummy"}),new I_(o.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:LAA(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(r),this.localParticipant.emit(Lt.LocalTrackPublished,r)}if(o.audio){const r=new M3(ot.Kind.Audio,new XD({source:ls.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:xc.AUDIO}),new a_(o.useRealTracks&&(!((n=navigator.mediaDevices)===null||n===void 0)&&n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:eY(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(r),this.localParticipant.emit(Lt.LocalTrackPublished,r)}for(let r=0;r<s.count-1;r+=1){let a=new If({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(r),state:vm.ACTIVE,tracks:[],joinedAt:ro.parse(Date.now())});const I=this.getOrCreateParticipant(a.identity,a);if(s.video){const c=LAA(160*((g=s.aspectRatios[r%s.aspectRatios.length])!==null&&g!==void 0?g:1),160,!1,!0),l=new XD({source:ls.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:xc.AUDIO});I.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),a.tracks=[...a.tracks,l]}if(s.audio){const c=eY(),l=new XD({source:ls.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:xc.AUDIO});I.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),a.tracks=[...a.tracks,l]}I.updateInfo(a)}})}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!==ut.ActiveSpeakersChanged&&A!==ut.TranscriptionReceived){const g=pdA(i).filter(o=>o!==void 0);(A===ut.TrackSubscribed||A===ut.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)}}vS.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{e()});function pdA(e){return e.map(A=>{if(A)return Array.isArray(A)?pdA(A):typeof A=="object"?"logContext"in A?A.logContext:void 0:A})}var Kc;(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"})(Kc||(Kc={}));class Fd extends GB.EventEmitter{constructor(A,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Kc.IDLE,this.logs=[],this.options={},this.url=A,this.token=t,this.name=this.constructor.name,this.room=new vS(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(A){return ZA(this,void 0,void 0,function*(){if(this.status!==Kc.IDLE)throw Error("check is running already");this.setStatus(Kc.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!==Kc.SKIPPED&&this.setStatus(this.isSuccess()?Kc.SUCCESS:Kc.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===Zn.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!==Zn.Disconnected&&(yield this.room.disconnect(),yield new Promise(A=>setTimeout(A,500)))})}skip(){this.setStatus(Kc.SKIPPED)}switchProtocol(A){return ZA(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(ut.Reconnecting,()=>{t=!0}),this.room.once(ut.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 Sr(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 L9A extends Fd{get description(){return"Cloud regions"}perform(){return ZA(this,void 0,void 0,function*(){const A=new Xn(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,r=1e6/o,a="A".repeat(o),I=Date.now();for(let Q=0;Q<r;Q++)yield g.write(a);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 IY=1e4;class x9A extends Fd{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/(IY/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(IY/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],a=(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 a.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,IY)),clearInterval(c),s.stop(),t.remove(),yield this.disconnect(),I})}}class T9A extends Fd{get description(){return"Can publish audio"}perform(){return ZA(this,void 0,void 0,function*(){var A;const t=yield this.connect(),i=yield U9A();if(yield tdA(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 q9A extends Fd{get description(){return"Can publish video"}perform(){return ZA(this,void 0,void 0,function*(){var A;const t=yield this.connect(),i=yield b9A();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,r;const a=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=(r=(s=I.height)!==null&&s!==void 0?s:i.videoHeight)!==null&&r!==void 0?r:720;a.width=c,a.height=l;const B=a.getContext("2d");B.drawImage(i,0,0);const h=B.getImageData(0,0,a.width,a.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 Y9A extends Fd{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(a=>{setTimeout(a,5e3),g=a}),s=()=>{i=!0};t.on(ut.SignalReconnecting,s).on(ut.Reconnecting,s).on(ut.Reconnected,()=>{n=!0,g(!0)}),(A=t.engine.client.ws)===null||A===void 0||A.close();const r=t.engine.client.onClose;if(r&&r(""),yield o,i){if(!n||t.state!==Zn.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 H9A extends Fd{get description(){return"Can connect via TURN"}perform(){return ZA(this,void 0,void 0,function*(){var A,t,i;US(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(A=yield new Xn(this.url,this.token).getNextBestRegionUrl())!==null&&A!==void 0?A:this.url);const n=new Jz,g=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,s=!1,r=!1;for(let a of g.iceServers)for(let I of a.urls)I.startsWith("turn:")?(s=!0,r=!0):I.startsWith("turns:")&&(s=!0,r=!0,o=!0),I.startsWith("stun:")&&(r=!0);r?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(a=>setTimeout(a,0)))})}}class O9A extends Fd{get description(){return"Establishing WebRTC connection"}perform(){return ZA(this,void 0,void 0,function*(){let A=!1,t=!1;this.room.on(ut.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 r="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(P9A(s.address)?r+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(A=!0,r+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(r)}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(),Cn.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 P9A(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 j9A extends Fd{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 Jz,g;try{g=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(o){if(US(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const r=yield new Xn(this.url,this.token).getNextBestRegionUrl();r&&(g=yield n.join(r,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)===ouA.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 BGe extends GB.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:Kc.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!==Kc.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(j9A)})}checkWebRTC(){return ZA(this,void 0,void 0,function*(){return this.createAndRunCheck(O9A)})}checkTURN(){return ZA(this,void 0,void 0,function*(){return this.createAndRunCheck(H9A)})}checkReconnect(){return ZA(this,void 0,void 0,function*(){return this.createAndRunCheck(Y9A)})}checkPublishAudio(){return ZA(this,void 0,void 0,function*(){return this.createAndRunCheck(T9A)})}checkPublishVideo(){return ZA(this,void 0,void 0,function*(){return this.createAndRunCheck(q9A)})}checkConnectionProtocol(){return ZA(this,void 0,void 0,function*(){const A=yield this.createAndRunCheck(x9A);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(L9A)})}}function Kn(e,A,t){return(A=Z9A(A))in e?Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[A]=t,e}function z9A(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 Z9A(e){var A=z9A(e,"string");return typeof A=="symbol"?A:A+""}new TextEncoder;new TextDecoder;class Ja extends Error{constructor(A,t){var i;super(A,t),Kn(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}Kn(Ja,"code","ERR_JOSE_GENERIC");class W9A extends Ja{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}}),Kn(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Kn(this,"claim",void 0),Kn(this,"reason",void 0),Kn(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}}Kn(W9A,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class V9A extends Ja{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}}),Kn(this,"code","ERR_JWT_EXPIRED"),Kn(this,"claim",void 0),Kn(this,"reason",void 0),Kn(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}}Kn(V9A,"code","ERR_JWT_EXPIRED");class X9A extends Ja{constructor(){super(...arguments),Kn(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Kn(X9A,"code","ERR_JOSE_ALG_NOT_ALLOWED");class $9A extends Ja{constructor(){super(...arguments),Kn(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Kn($9A,"code","ERR_JOSE_NOT_SUPPORTED");class AXA extends Ja{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),Kn(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Kn(AXA,"code","ERR_JWE_DECRYPTION_FAILED");class eXA extends Ja{constructor(){super(...arguments),Kn(this,"code","ERR_JWE_INVALID")}}Kn(eXA,"code","ERR_JWE_INVALID");class tXA extends Ja{constructor(){super(...arguments),Kn(this,"code","ERR_JWS_INVALID")}}Kn(tXA,"code","ERR_JWS_INVALID");class iXA extends Ja{constructor(){super(...arguments),Kn(this,"code","ERR_JWT_INVALID")}}Kn(iXA,"code","ERR_JWT_INVALID");class nXA extends Ja{constructor(){super(...arguments),Kn(this,"code","ERR_JWK_INVALID")}}Kn(nXA,"code","ERR_JWK_INVALID");class gXA extends Ja{constructor(){super(...arguments),Kn(this,"code","ERR_JWKS_INVALID")}}Kn(gXA,"code","ERR_JWKS_INVALID");class oXA extends Ja{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),Kn(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Kn(oXA,"code","ERR_JWKS_NO_MATCHING_KEY");class sXA extends Ja{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),Kn(this,Symbol.asyncIterator,void 0),Kn(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Kn(sXA,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class rXA extends Ja{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),Kn(this,"code","ERR_JWKS_TIMEOUT")}}Kn(rXA,"code","ERR_JWKS_TIMEOUT");class aXA extends Ja{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),Kn(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Kn(aXA,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const aeA=15e3,IXA=1e4,fdA=E.createContext(null),CXA=()=>E.useContext(fdA);function cXA({children:e}){const{user:A}=en(),t=Ss(),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,r]=E.useState(null),a=E.useRef(null);E.useEffect(()=>{a.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),T=E.useRef(null);E.useEffect(()=>{T.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 CA=(_A=oA.getTrackPublication(ot.Source.Camera))==null?void 0:_A.track,cA=(uA=oA.getTrackPublication(ot.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:CA||void 0,audioTrack:cA||void 0})}),D(P);const tA=H.localParticipant;if(tA){const oA=tA.getTrackPublication(ot.Source.Camera),CA=oA==null?void 0:oA.track,cA=(iA=tA.getTrackPublication(ot.Source.Microphone))==null?void 0:iA.track;console.log("[LiveKit] updateParticipants - localVideoTrack:",CA),k({id:tA.identity,name:tA.name||tA.identity,isSelf:!0,audioEnabled:tA.isMicrophoneEnabled,videoEnabled:tA.isCameraEnabled,isSpeaking:tA.isSpeaking,videoTrack:CA||void 0,audioTrack:cA||void 0}),_(CA||null),G(tA.isMicrophoneEnabled),w(tA.isCameraEnabled)}},[]),U=E.useRef(null),x=E.useRef(!1),q=E.useRef(0),z=3,Z=E.useCallback(async L=>{if(!g||!t){h("Not authenticated");return}if(!(a.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),r(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(a.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&&(q.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"))},IXA);t.emit("livekit_join",{roomId:L},lA=>{clearTimeout(O),uA(lA)})});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,CA={};oA&&Array.isArray(oA)&&oA.length>0&&(CA.iceServers=oA,CA.iceTransportPolicy="all",console.log("[LiveKit] Using custom ICE servers:",oA.length,"servers"));const cA=new vS({adaptiveStream:!0,dynacast:!0,videoCaptureDefaults:{resolution:bS.h540.resolution}});await cA.prepareConnection(iA,tA),cA.on(ut.Connected,()=>{console.log("[LiveKit] Connected to room"),c(!0),B(!1),v(cA)}),cA.on(ut.ParticipantConnected,uA=>{console.log("[LiveKit] Participant connected:",uA.identity),v(cA)}),cA.on(ut.ParticipantDisconnected,uA=>{console.log("[LiveKit] Participant disconnected:",uA.identity),v(cA)}),cA.on(ut.TrackSubscribed,(uA,X,O)=>{console.log("[LiveKit] Track subscribed:",uA.kind,O.identity),v(cA)}),cA.on(ut.TrackUnsubscribed,(uA,X,O)=>{console.log("[LiveKit] Track unsubscribed:",uA.kind,O.identity),v(cA)}),cA.on(ut.LocalTrackPublished,(uA,X)=>{if(console.log("[LiveKit] Local track published:",uA.kind,"track:",uA.track),v(cA),uA.kind===ot.Kind.Video){let O=0;const lA=()=>{var xA;if(o.current!==cA&&O>0)return;if((xA=X.getTrackPublication(ot.Source.Camera))==null?void 0:xA.track){v(cA);return}O++<8&&setTimeout(lA,75)};setTimeout(lA,50)}}),cA.on(ut.LocalTrackUnpublished,(uA,X)=>{console.log("[LiveKit] Local track unpublished:",uA.kind),v(cA)}),cA.on(ut.ActiveSpeakersChanged,()=>{v(cA)}),cA.on(ut.ConnectionStateChanged,uA=>{if(o.current===cA)if(console.log("[LiveKit] Connection state changed:",uA),uA===Zn.Disconnected){o.current=null,c(!1),v(),J(L);const X=a.current;X&&!x.current&&L===X&&(console.log("[LiveKit] Unexpected disconnect, attempting auto-reconnect to:",L),setTimeout(()=>{!x.current&&a.current===L&&eA(L,0)},1500))}else uA===Zn.Reconnecting?console.log("[LiveKit] Connection reconnecting..."):uA===Zn.Connected&&(console.log("[LiveKit] Connection restored"),c(!0))});const _A=Object.keys(CA).length>0?{rtcConfig:CA}: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,r(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 q.current=H+1,eA(L,H+1)}return h((P==null?void 0:P.message)||"Failed to join room"),B(!1),r(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),r(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 ${aeA/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 CA=a.current;o.current=null;try{tA.disconnect()}catch{}c(!1),r(null),D([]),k(null),_(null),CA&&J(CA)},aeA)},[]),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=T.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,ot.Source.Camera),H||sA()}catch(H){console.error("[LiveKit] Toggle video error:",H)}},[gA,v,pA,sA]),YA=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,ot.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:YA,setVideoEnabled:W,localVideoTrack:b};return C.jsx(fdA.Provider,{value:$,children:e})}const ydA=E.createContext(null),lXA=()=>E.useContext(ydA);function Tg(e){return e.connectionState==="closed"||e.signalingState==="closed"}function qb(e){if(e)try{e.getTracks().forEach(A=>A.stop())}catch{}}function BXA(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 r;return{id:s.id,kind:s.kind,enabled:s.enabled,ready:s.readyState,settings:((r=s.getSettings)==null?void 0:r.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 EXA=(()=>{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 b0(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 r=s.trim();if(r.startsWith("stun:")){const a=`${r}|`;t.has(a)||(t.add(a),i.push({urls:r}));continue}if(r.startsWith("turn:")||r.startsWith("turns:")){const a=g.username,I=g.credential;if(a&&I){const c=`${r}|${a}|${I}`;t.has(c)||(t.add(c),i.push({urls:r,username:a,credential:I}))}}}};return(e||[]).forEach(n),i.length===0&&A.forEach(n),i.length?i:A}function QXA(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 U0(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 uXA({children:e}){const{user:A}=en(),t=Ss(),i=A==null?void 0:A.id,n=!!(A!=null&&A.email&&/@guest\.local$/i.test(A.email)),g=!!i&&!n;function o(j,dA){try{const hA=window;hA.__rtcVideoDisableReasons||(hA.__rtcVideoDisableReasons=[]),hA.__rtcVideoDisableReasons.push({t:Date.now(),reason:j,...dA?{data:dA}:{}});try{N3(`video:disable:${j}`)}catch{}}catch{}}const{rtcJoin:s,rtcSignal:r,rtcLeave:a,rtcSetVideoEnabled:I}=So(),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,T]=E.useState(0),v=E.useRef(null);E.useRef([]);const U=E.useRef({audio:!1,video:!1}),x=J>0||w||G,q=E.useCallback(async()=>{var j;try{const dA=navigator;(j=dA==null?void 0:dA.wakeLock)!=null&&j.request&&!v.current&&(v.current=await dA.wakeLock.request("screen"),v.current.addEventListener("release",()=>{}))}catch{}},[]),z=E.useCallback(async()=>{var j,dA;try{await((dA=(j=v.current)==null?void 0:j.release)==null?void 0:dA.call(j))}catch{}v.current=null},[]);E.useEffect(()=>(ai.debug("wakeLock:effect",{need:x}),x?q():z(),()=>{z()}),[x,q,z]),E.useEffect(()=>{const j=()=>{document.visibilityState==="visible"&&x&&q()};return document.addEventListener("visibilitychange",j),()=>document.removeEventListener("visibilitychange",j)},[x,q]);const Z=(()=>{var j,dA;try{return((dA=(j=window.Capacitor)==null?void 0:j.getPlatform)==null?void 0:dA.call(j))==="ios"}catch{return!1}})();async function eA(j,dA){var hA;if(!g||U.current[dA])return null;U.current[dA]=!0;try{if(!((hA=navigator.mediaDevices)!=null&&hA.getUserMedia))return console.error(`[RTC] getUserMedia not available for ${dA}`),ai.error("gUM:not-available",{kind:dA,isNativeIOS:Z}),null;console.log(`[RTC] Requesting ${dA} with constraints:`,j);const UA=await navigator.mediaDevices.getUserMedia(j);return console.log(`[RTC] getUserMedia ${dA} 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 ${dA} failed:`,UA==null?void 0:UA.name,UA==null?void 0:UA.message,UA),ai.error("gUM:failed",{kind:dA,errName:UA==null?void 0:UA.name,errMsg:UA==null?void 0:UA.message,isNativeIOS:Z}),null}finally{U.current[dA]=!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 dA=j.getAudioTracks()[0];dA&&(dA.enabled=!1),D.current=j}return D.current}async function sA(){if(!g)return;if(m.current)return m.current;const dA=await eA({audio:!1,video:EXA?{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 dA&&(m.current=dA,y(dA),ai.info("ensureVideo:acquired",BXA(dA))),m.current}function pA(){var dA;const j=((dA=m.current)==null?void 0:dA.getVideoTracks())??[];console.log("[RTC] releaseVideo called, stopping",j.length,"video tracks");try{j.forEach(hA=>{console.log("[RTC] stopping video track",hA.id,hA.readyState),hA.stop()})}catch(hA){console.error("[RTC] releaseVideo error",hA)}m.current=void 0,y(void 0)}function gA(){var j,dA;try{(dA=(j=D.current)==null?void 0:j.getAudioTracks())==null||dA.forEach(hA=>hA.stop())}catch{}D.current=void 0}const yA=E.useRef(new Map),[fA,RA]=E.useState({});function YA(j,dA){var _t;if(yA.current.get(j))return;const hA=((_t=dA==null?void 0:dA.getAudioTracks)==null?void 0:_t.call(dA))??[];if(!hA.length||hA.every(vt=>vt.readyState!=="live"))return;let UA;try{UA=new AudioContext}catch(vt){ai.warn("vad:audiocontext-failed",{pid:j,err:String(vt)});return}let TA,se;try{TA=UA.createMediaStreamSource(dA),se=UA.createAnalyser(),se.fftSize=2048,TA.connect(se)}catch(vt){ai.warn("vad:setup-failed",{pid:j,err:String(vt)});try{UA.close()}catch{}return}const Ne=new Uint8Array(se.fftSize);let Ke=0;const At=.04,ni=.02;let Ge=!1,st=!1;const Rt=()=>{if(!st){try{se.getByteTimeDomainData(Ne);let vt=0;for(let ee=0;ee<Ne.length;ee++){const Oe=(Ne[ee]-128)/128;vt+=Oe*Oe}const xt=Math.sqrt(vt/Ne.length);!Ge&&xt>=At?(Ge=!0,RA(ee=>ee[j]===!0?ee:{...ee,[j]:!0})):Ge&&xt<=ni&&(Ge=!1,RA(ee=>ee[j]===!1?ee:{...ee,[j]:!1}))}catch{}st||(Ke=requestAnimationFrame(Rt))}};Ke=requestAnimationFrame(Rt);const Et=()=>{st=!0,cancelAnimationFrame(Ke);try{TA.disconnect()}catch{}try{se.disconnect()}catch{}UA.close().catch(()=>{})};yA.current.set(j,Et)}function W(j){const dA=yA.current.get(j);dA&&(dA(),yA.current.delete(j)),RA(hA=>{if(!(j in hA))return hA;const UA={...hA};return delete UA[j],UA})}function $(j,dA){try{return Tg(j)?void 0:j.getTransceivers().find(hA=>{var UA;return((UA=hA.receiver.track)==null?void 0:UA.kind)===dA})??j.getTransceivers().find(hA=>{var UA;return((UA=hA.sender.track)==null?void 0:UA.kind)===dA})??j.getTransceivers()[dA==="audio"?0:1]}catch{return}}function L(j,dA){var hA;try{return Tg(j)?void 0:j.getSenders().find(UA=>{var TA;return((TA=UA.track)==null?void 0:TA.kind)===dA})??((hA=$(j,dA))==null?void 0:hA.sender)}catch{return}}async function H(j,dA){var hA;try{if(Tg(j))return;const UA=((hA=dA==null?void 0:dA.getAudioTracks)==null?void 0:hA.call(dA)[0])??null,TA=L(j,"audio");TA&&await TA.replaceTrack(UA)}catch(UA){ai.warn("upsertAudioTrack:failed",{err:String(UA)})}}async function P(j,dA){var hA;try{if(Tg(j))return;const UA=((hA=dA==null?void 0:dA.getVideoTracks)==null?void 0:hA.call(dA)[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){ai.warn("upsertVideoTrack:failed",{err:String(UA)}),console.error("[RTC] upsertVideoTrack failed:",UA)}}async function tA(j,dA){try{const hA=dA.pc,UA=Date.now();let TA=0,se=0;(await hA.getStats()).forEach(At=>{At.type==="outbound-rtp"&&!At.isRemote&&(TA+=At.bytesSent??0),At.type==="inbound-rtp"&&!At.isRemote&&(se+=At.bytesReceived??0)});const Ke=N.current.get(j);N.current.set(j,{t:UA,up:TA,down:se}),Ke&&hA.connectionState==="connected"&&TA===Ke.up&&se===Ke.down&&UA-Ke.t>2e4&&await O(j,dA)}catch{}}function iA(j,dA){if(k.current.get(j))return;const hA=window.setInterval(()=>tA(j,dA),1e4);k.current.set(j,hA)}function oA(j){const dA=k.current.get(j);dA&&(clearInterval(dA),k.current.delete(j)),N.current.delete(j)}function CA(){const j=typeof window<"u"?new URL(window.location.href):null,dA=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",hA=!!_A._compat,UA=!!(dA||hA),TA={iceServers:b0(K.current,_),bundlePolicy:"balanced",iceTransportPolicy:UA?"relay":"all",rtcpMuxPolicy:"require",iceCandidatePoolSize:2},se=TA.iceServers.some(Ke=>(Array.isArray(Ke.urls)?Ke.urls:[Ke.urls]).some(ni=>ni.startsWith("turn:")||ni.startsWith("turns:")));console.log("[RTC] newPc config",{relayOnly:UA,hasTurn:se,iceTransportPolicy:TA.iceTransportPolicy,serverCount:TA.iceServers.length,servers:TA.iceServers.map(Ke=>({urls:Ke.urls,hasCredentials:!!(Ke.username&&Ke.credential)}))}),ai.debug("pc:new",{relayOnly:UA,iceTransportPolicy:TA.iceTransportPolicy,iceServers:(TA.iceServers||[]).map(Ke=>{var At;return typeof Ke.urls=="string"?Ke.urls:(At=Ke.urls)==null?void 0:At[0]})});let Ne;try{Ne=new RTCPeerConnection(TA)}catch(Ke){ai.error("pc:new-failed",{err:String(Ke),servers:TA.iceServers});const At={...TA,iceServers:_};Ne=new RTCPeerConnection(At)}return Ne.addTransceiver("audio",{direction:"sendrecv"}),Ne.addTransceiver("video",{direction:"sendrecv"}),Ne}async function cA(j,dA){try{const hA=await dA.getStats(),UA={};hA.forEach(se=>{se&&se.id&&(UA[se.id]=se)});let TA;if(hA.forEach(se=>{se.type==="transport"&&se.selectedCandidatePairId&&UA[se.selectedCandidatePairId]&&(TA=UA[se.selectedCandidatePairId])}),TA||hA.forEach(se=>{se.type==="candidate-pair"&&(se.selected||se.state==="succeeded")&&(TA=se)}),TA){const se=UA[TA.localCandidateId],Ne=UA[TA.remoteCandidateId];ai.info("ice:selected",{peerId:j,state:TA.state,nominated:TA.nominated,bytesSent:TA.bytesSent,bytesReceived:TA.bytesReceived,local:se?{type:se.candidateType,protocol:se.protocol,address:se.address,port:se.port}:void 0,remote:Ne?{type:Ne.candidateType,protocol:Ne.protocol,address:Ne.address,port:Ne.port}:void 0})}else ai.debug("ice:selected:none",{peerId:j})}catch(hA){ai.error("ice:selected-failed",{peerId:j,err:String(hA)})}}async function _A(){try{if(_A._ran)return;_A._ran=!0;const j={iceServers:b0(K.current,_),bundlePolicy:"balanced",iceTransportPolicy:"all"},dA=new RTCPeerConnection(j),hA={host:0,srflx:0,relay:0,prflx:0};dA.onicecandidate=At=>{if(!At.candidate)return;const Ge=(At.candidate.candidate||"").match(/ typ ([a-z]+)/),st=(Ge==null?void 0:Ge[1])||"unknown";hA[st]===void 0&&(hA[st]=0),hA[st]+=1},dA.createDataChannel("probe");const UA=await dA.createOffer({iceRestart:!1});await dA.setLocalDescription(UA),await new Promise(At=>setTimeout(At,4e3));try{dA.close()}catch{}const TA=(hA.relay||0)>0,se=(hA.srflx||0)>0,Ne=(hA.host||0)>0,Ke=TA&&!se&&Ne;if(Ke){ai.warn("ice:probe-forcing-relay",{counts:hA,reason:"no-srflx"}),_A._compat=!0;try{localStorage.setItem("rtcRelayOnly","1")}catch{}}else!TA&&!se&&ai.error("ice:probe-restricted-network",{counts:hA,warning:"Voice/video may not work"});ai.info("ice:probe",{counts:hA,relayOK:TA,srflxOK:se,needsRelayOnly:Ke})}catch(j){ai.error("ice:probe-failed",{err:String(j)})}}function uA(j){let dA=c.current.get(j);if(dA)return dA;const hA=CA(),UA={pc:hA,iceBuffer:[],makingOffer:!1,ignoreOffer:!1,isSettingRemoteAnswerPending:!1};return hA.onicecandidate=TA=>{TA.candidate&&(ai.debug("pc:icecandidate",{peerId:j,ctype:TA.candidate.type,proto:TA.candidate.protocol,addr:TA.candidate.address,port:TA.candidate.port}),r(S.current,j,{ice:TA.candidate.toJSON()}).catch(console.error))},hA.ontrack=TA=>{if(ai.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(se=>{const Ne=se[j]??new MediaStream;return Ne.getTracks().includes(TA.track)||(Ne.addTrack(TA.track),console.log("[RTC] Track added to stream",{peerId:j,kind:TA.track.kind,streamId:Ne.id,trackCount:Ne.getTracks().length}),TA.track.addEventListener("ended",()=>{ai.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(Ke=>{const At=Ke[j];if(!At)return Ke;try{At.removeTrack(TA.track)}catch{}return{...Ke,[j]:At}}),TA.track.kind==="video"&&d(Ke=>({...Ke,[j]:!1}))}),TA.track.kind==="video"&&(TA.track.addEventListener("mute",()=>{console.log("[RTC] Video track muted",{peerId:j,trackId:TA.track.id}),d(Ke=>({...Ke,[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(Ke=>({...Ke,[j]:!0}))}))),{...se,[j]:Ne}}),TA.track.kind==="video"){const se=TA.track.readyState==="live"&&!TA.track.muted;console.log("[RTC] Video track received, setting remoteVideoFlags",{peerId:j,isLive:se,muted:TA.track.muted}),d(Ne=>({...Ne,[j]:se}))}},hA.onnegotiationneeded=()=>{ai.debug("pc:onnegotiationneeded",{peerId:j})},hA.onconnectionstatechange=()=>{const{connectionState:TA}=hA,se=hA.iceConnectionState;if(ai.info("pc:state",{peerId:j,state:TA,ice:se}),console.log("[RTC] connectionstatechange",{peerId:j,connectionState:TA,iceConnectionState:se,signalingState:hA.signalingState}),TA==="connected"&&(UA.degradedAt=null,UA.iceRestartCount=0,UA.rebuildAttempts=0,QXA(j,UA),iA(j,UA),setTimeout(()=>cA(j,hA),500)),TA==="closed"&&(U0(UA),oA(j)),(TA==="disconnected"||X(TA,se))&&!UA.degradedAt&&(UA.degradedAt=Date.now()),TA==="disconnected"&&UA.degradedAt){const Ke=Date.now()-UA.degradedAt;Ke>3e3&&Ke<8e3?O(j,UA):Ke>=8e3&&(ai.warn("pc:prolonged-disconnect",{peerId:j,degradedMs:Ke}),HA(j))}X(TA,se)&&O(j,UA)},hA.oniceconnectionstatechange=()=>{const TA=hA.iceConnectionState;ai.debug("pc:ice-state",{peerId:j,ice:TA}),console.log("[RTC] iceconnectionstatechange",{peerId:j,iceConnectionState:TA,connectionState:hA.connectionState}),TA==="failed"&&O(j,UA),TA==="disconnected"&&setTimeout(()=>{!Tg(hA)&&hA.iceConnectionState==="disconnected"&&(ai.warn("ice:prolonged-disconnect",{peerId:j}),O(j,UA))},4e3)},hA.onicegatheringstatechange=()=>{console.log("[RTC] icegatheringstatechange",{peerId:j,iceGatheringState:hA.iceGatheringState})},hA.ondatachannel=TA=>{if(TA.channel.label==="ka"){const se=TA.channel;UA.dc=se,ai.debug("pc:datachannel",{peerId:j,label:se.label,state:se.readyState})}},c.current.set(j,UA),T(c.current.size),ai.info("peer:new",{peerId:j}),UA}function X(j,dA){return j==="failed"||dA==="failed"}async function O(j,dA){if(Tg(dA.pc))return;const hA=Date.now(),UA=dA.lastIceRestartAt,TA=dA.iceRestartCount??0,se=Math.min(1e4*Math.pow(2,TA),6e4);if(!(UA&&hA-UA<se)){if(TA>=3){ai.warn("ice:restart-exhausted",{peerId:j,restartCount:TA}),dA.iceRestartCount=0,await HA(j);return}if(ai.warn("ice:restart",{peerId:j,attempt:TA+1}),!(dA.makingOffer||Tg(dA.pc))&&(dA.pc.signalingState!=="stable"&&await ne(dA.pc),!Tg(dA.pc)))try{const Ne=await dA.pc.createOffer({iceRestart:!0});if(Tg(dA.pc))return;await dA.pc.setLocalDescription(Ne),await r(S.current,j,{sdp:dA.pc.localDescription}),dA.lastIceRestartAt=hA,dA.iceRestartCount=TA+1}catch(Ne){ai.error("ice:restart-failed",{peerId:j,err:String(Ne)}),dA.iceRestartCount=0,await HA(j)}}}const lA=E.useRef(new Map),wA=3,xA=3e4;async function HA(j){const dA=lA.current.get(j)??{count:0,lastAt:0},hA=Date.now();if(hA-dA.lastAt>xA*3&&(dA.count=0),dA.count>=wA){const Ne=xA-(hA-dA.lastAt);if(Ne>0){ai.warn("rebuild:rate-limited",{peerId:j,attempts:dA.count,waitMs:Ne}),setTimeout(()=>{lA.current.delete(j),HA(j)},Ne);return}dA.count=0}dA.count++,dA.lastAt=hA,lA.current.set(j,dA),ai.info("rebuild:peer",{peerId:j,attempt:dA.count});const UA=c.current.get(j);if(UA){U0(UA);try{UA.pc.close()}catch{}c.current.delete(j)}B(Ne=>{if(!Ne[j])return Ne;const Ke={...Ne};return qb(Ke[j]),delete Ke[j],Ke}),W(j),d(Ne=>{const{[j]:Ke,...At}=Ne;return At});const{pc:TA}=uA(j);await PA(TA);const se=c.current.get(j);await ye(j,TA,se)}function zA(j){return j.signalingState==="stable"}function ne(j){return j.signalingState==="stable"||Tg(j)?Promise.resolve():new Promise(dA=>{const hA=()=>{const UA=j.signalingState;(UA==="stable"||UA==="closed")&&(j.removeEventListener("signalingstatechange",hA),dA())};j.addEventListener("signalingstatechange",hA)})}async function ye(j,dA,hA){var UA;try{if(Tg(dA)||(zA(dA)||await ne(dA),!zA(dA)||hA.makingOffer||Tg(dA)))return;hA.makingOffer=!0,ai.debug("sdp:offer",{peerId:j}),console.log("[RTC] Creating offer for peer",{peerId:j,signalingState:dA.signalingState});const TA=await dA.createOffer();if(Tg(dA)){hA.makingOffer=!1;return}await dA.setLocalDescription(TA),console.log("[RTC] Sending offer via rtcSignal",{peerId:j,room:S.current,type:(UA=dA.localDescription)==null?void 0:UA.type}),await r(S.current,j,{sdp:dA.localDescription})}catch(TA){ai.warn("safeRenegotiate:failed",{peerId:j,err:String(TA)})}finally{hA.makingOffer=!1}}const Ee=E.useCallback(async j=>{if(j!==w){if(!g){b(!1),o("preferences:init"),b(!1);return}if(b(j),i&&d(dA=>({...dA,[i]:j})),j){try{eM(!0)}catch{}if(!await sA()){b(!1),i&&d(TA=>({...TA,[i]:!1}));return}for(const[TA,se]of c.current)await P(se.pc,m.current),await ye(TA,se.pc,se);const hA=()=>{try{eM(!1)}catch{}};let UA=!1;for(const[,TA]of c.current){const se=TA.pc,Ne=()=>{!UA&&se.connectionState==="connected"&&(UA=!0,hA(),se.removeEventListener("connectionstatechange",Ne))};se.addEventListener("connectionstatechange",Ne)}window.setTimeout(()=>{UA||hA()},2500)}else{console.log("[RTC] setVideoEnabled(false) - disabling camera");for(const[dA,hA]of c.current)console.log("[RTC] removing video track from peer",dA),await P(hA.pc,void 0),await ye(dA,hA.pc,hA);pA()}I(S.current,j).catch(()=>{});try{N3(j?"videoEnabled:on":"videoEnabled:off")}catch{}}},[w,i,g,A==null?void 0:A.membershipTier,c,sA,P,ye,pA,I]),NA=async j=>{var hA,UA;if(!g){M(!1);return}if(M(j),j&&!D.current&&!await aA()){M(!1);return}const dA=(UA=(hA=D.current)==null?void 0:hA.getAudioTracks)==null?void 0:UA.call(hA)[0];dA&&(dA.enabled=j);for(const[,TA]of c.current)await H(TA.pc,D.current)},QA=j=>{var hA,UA,TA;if(j===i)return!!((UA=(hA=m.current)==null?void 0:hA.getVideoTracks)!=null&&UA.call(hA).some(se=>se.readyState==="live"));const dA=l[j];return!!((TA=dA==null?void 0:dA.getVideoTracks)!=null&&TA.call(dA).some(se=>se.readyState==="live"))},PA=async j=>{if(!Tg(j)){if(!g){await H(j,void 0),await P(j,void 0);return}try{if(await aA(),w&&await sA(),Tg(j))return;ai.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(dA){ai.warn("attachLocalTracks:failed",{err:String(dA)})}}},VA=E.useRef(0),KA=90*60*1e3;E.useEffect(()=>{if(!S.current||c.current.size===0)return;const j=async()=>{const hA=Date.now();if(!(hA-VA.current<KA)){ai.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=b0([..._,...UA.iceServers],_);K.current=TA,VA.current=hA,ai.debug("ice:credentials-refreshed",{count:TA.length})}}catch(UA){ai.warn("ice:refresh-failed",{err:String(UA)})}}},dA=window.setInterval(j,6e4);return()=>clearInterval(dA)},[J,s]);const Ie=async j=>{var se;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,ai.info("rtc:join",{roomId:j});const dA=3,hA=150;let UA=null,TA=null;for(let Ne=0;Ne<dA&&(UA=await s(j),console.log("[RTC] joinRtc raw response",{ok:UA==null?void 0:UA.ok,attempt:Ne,iceServersCount:(se=UA==null?void 0:UA.iceServers)==null?void 0:se.length}),!(UA!=null&&UA.ok||(TA=(UA==null?void 0:UA.error)||"rtc_join failed",!/not a member|room not found/i.test(TA||"")||Ne>=dA-1)));Ne++)ai.warn("rtc:join:retry",{roomId:j,attempt:Ne+1,error:TA}),await new Promise(At=>setTimeout(At,hA*(Ne+1)));if(!(UA!=null&&UA.ok))throw new Error(TA||"rtc_join failed");if(Array.isArray(UA.iceServers)&&UA.iceServers.length){const Ne=b0([..._,...UA.iceServers],_);K.current=Ne,VA.current=Date.now();const Ke=Ne.some(At=>(Array.isArray(At.urls)?At.urls:[At.urls]).some(Ge=>Ge.startsWith("turn:")||Ge.startsWith("turns:")));console.log("[RTC] joinRtc received ICE servers",{count:Ne.length,hasTurn:Ke,servers:Ne.map(At=>({urls:At.urls,hasCredentials:!!(At.username&&At.credential)}))}),ai.debug("rtc:ice-servers",{count:Ne.length,servers:Ne.map(At=>At.urls).slice(0,4)})}else K.current=[..._],VA.current=Date.now();if(_A(),w&&!m.current){const Ne=await sA();Ne&&y(Ne)}for(const Ne of UA.peers.filter(Ke=>Ke!==i)){const{pc:Ke}=uA(Ne);await PA(Ke);const At=c.current.get(Ne);await ye(Ne,Ke,At)}T(c.current.size)},DA=j=>{var dA,hA,UA,TA;!j||S.current&&S.current,ai.info("rtc:leave",{roomId:j});try{a(j)}catch{}for(const[,se]of c.current){U0(se);try{se.pc.close()}catch{}}c.current.clear(),T(0),S.current=void 0,z(),B(se=>(Object.values(se).forEach(qb),{}));for(const se of Array.from(yA.current.keys()))W(se);(hA=(dA=D.current)==null?void 0:dA.getTracks())==null||hA.forEach(se=>se.stop()),(TA=(UA=m.current)==null?void 0:UA.getTracks())==null||TA.forEach(se=>se.stop()),D.current=void 0,m.current=void 0,y(void 0),d({})},IA=async(j,dA)=>{},EA=async()=>{g&&await Ee(!0)};return E.useEffect(()=>{if(!w||!S.current||c.current.size===0)return;const j=async()=>{var UA;if(!w||!m.current)return;const hA=m.current.getVideoTracks()[0];if(!((!hA||hA.readyState!=="live")&&(console.log("[RTC] Health check: local video track not live, re-acquiring"),ai.warn("health:video-track-dead"),m.current=void 0,!await sA()))){for(const[TA,se]of c.current)if(!Tg(se.pc))try{const Ne=se.pc.getSenders().find(ni=>{var Ge;return((Ge=ni.track)==null?void 0:Ge.kind)==="video"}),Ke=Ne==null?void 0:Ne.track,At=(UA=m.current)==null?void 0:UA.getVideoTracks()[0];At&&(!Ke||Ke.id!==At.id)&&(console.log("[RTC] Health check: re-attaching video track to peer",{peerId:TA}),ai.info("health:reattach-video",{peerId:TA}),await P(se.pc,m.current),await ye(TA,se.pc,se))}catch(Ne){ai.warn("health:check-failed",{peerId:TA,err:String(Ne)})}}},dA=window.setInterval(j,5e3);return j(),()=>clearInterval(dA)},[w,J]),E.useEffect(()=>{if(!t||!g)return;const j=async()=>{const dA=S.current;if(dA){ai.info("socket:reconnect:rtc-rejoin",{roomId:dA,peerCount:c.current.size}),console.log("[RTC] Socket reconnected, re-joining RTC room",{roomId:dA});for(const[,hA]of c.current){U0(hA);try{hA.pc.close()}catch{}}c.current.clear(),T(0),B(hA=>(Object.values(hA).forEach(qb),{})),d({});try{const hA=await s(dA);if(!(hA!=null&&hA.ok)){ai.warn("socket:reconnect:rtc-rejoin-failed",{roomId:dA,error:hA==null?void 0:hA.error});return}if(Array.isArray(hA.iceServers)&&hA.iceServers.length){const UA=b0([..._,...hA.iceServers],_);K.current=UA,VA.current=Date.now()}for(const UA of hA.peers.filter(TA=>TA!==i)){const{pc:TA}=uA(UA);await PA(TA);const se=c.current.get(UA);await ye(UA,TA,se)}T(c.current.size),ai.info("socket:reconnect:rtc-rejoin-success",{roomId:dA,peerCount:c.current.size})}catch(hA){ai.error("socket:reconnect:rtc-rejoin-error",{roomId:dA,err:String(hA)})}}};return t.on("connect",j),t.on("reconnect",j),()=>{t.off("connect",j),t.off("reconnect",j)}},[t,g,i,s]),E.useEffect(()=>{var dA,hA;const j=(hA=(dA=D.current)==null?void 0:dA.getAudioTracks)==null?void 0:hA.call(dA)[0];G&&j&&D.current?YA(i,D.current):W(i)},[D.current,i,G]),E.useEffect(()=>{for(const[j,dA]of Object.entries(l))(dA==null?void 0:dA.getAudioTracks().some(UA=>UA.enabled))&&YA(j,dA);for(const j of yA.current.keys())j!==i&&!l[j]&&W(j)},[l,i]),xs({onRtcPeerJoined:async({peerId:j})=>{if(ai.info("sig:peer-joined",{peerId:j}),!(!S.current||j===i))try{const{pc:dA}=uA(j);if(Tg(dA))return;await PA(dA);const hA=c.current.get(j);hA&&!Tg(dA)&&await ye(j,dA,hA)}catch(dA){ai.warn("sig:peer-joined:failed",{peerId:j,err:String(dA)})}},onRtcPeerLeft:({peerId:j})=>{ai.info("sig:peer-left",{peerId:j});const dA=c.current.get(j);if(dA){U0(dA),oA(j);try{dA.pc.close()}catch{}}c.current.delete(j),T(c.current.size),B(hA=>{const UA={...hA};return qb(UA[j]),delete UA[j],UA}),W(j),d(hA=>{const{[j]:UA,...TA}=hA;return TA})},onRtcSignal:async({fromPeerId:j,payload:dA})=>{var TA;let hA,UA;try{hA=uA(j),UA=hA.pc}catch(se){ai.warn("sig:getPeer-failed",{fromPeerId:j,err:String(se)});return}if(Tg(UA)){ai.debug("sig:pc-closed",{fromPeerId:j});return}try{if(dA.sdp){if(ai.debug("sig:sdp",{fromPeerId:j,type:dA.sdp.type}),console.log("[RTC] Received SDP",{fromPeerId:j,type:dA.sdp.type,signalingState:UA.signalingState}),Tg(UA))return;const se=dA.sdp;if(se.type==="answer"&&zA(UA)){ai.debug("sig:stale-answer-ignored",{fromPeerId:j,signalingState:UA.signalingState}),console.log("[RTC] Ignoring stale answer (connection already stable)",{fromPeerId:j});return}const Ne=zA(UA)||hA.isSettingRemoteAnswerPending,Ke=se.type==="offer"&&!Ne;if(hA.ignoreOffer=!(i<j)&&Ke,hA.ignoreOffer){console.log("[RTC] Ignoring offer due to collision",{fromPeerId:j});return}if(se.type==="answer"&&(hA.isSettingRemoteAnswerPending=!0),Ke&&(console.log("[RTC] Rolling back due to offer collision",{fromPeerId:j}),Tg(UA)||await UA.setLocalDescription({type:"rollback"})),Tg(UA))return;if(await UA.setRemoteDescription(se),console.log("[RTC] Set remote description",{fromPeerId:j,type:se.type,signalingState:UA.signalingState}),hA.isSettingRemoteAnswerPending=!1,se.type==="offer"&&!Tg(UA)){const At=await UA.createAnswer();if(Tg(UA))return;await UA.setLocalDescription(At),console.log("[RTC] Sending answer",{fromPeerId:j,type:(TA=UA.localDescription)==null?void 0:TA.type}),await r(S.current,j,{sdp:UA.localDescription})}for(;hA.iceBuffer.length&&!Tg(UA);){const At=hA.iceBuffer.shift();try{await UA.addIceCandidate(At)}catch{}}}else if(dA.ice){if(ai.debug("sig:ice",{fromPeerId:j,hasRemote:!!UA.remoteDescription}),Tg(UA))return;const se=dA.ice;if(UA.remoteDescription)try{await UA.addIceCandidate(se)}catch{}else hA.iceBuffer.push(se)}}catch(se){const Ne=String(se);ai.error("sig:error",{fromPeerId:j,err:Ne}),console.error("[RTC] Signal error",{fromPeerId:j,err:Ne}),(Ne.includes("order of m-lines")||Ne.includes("m-line")||Ne.includes("InvalidAccessError"))&&(console.log("[RTC] M-line mismatch detected, rebuilding peer",{fromPeerId:j}),ai.warn("sig:mline-mismatch-rebuild",{fromPeerId:j}),await HA(j))}},onRtcVideoEnabled:({playerId:j,enabled:dA})=>{ai.debug("sig:video-enabled",{playerId:j,enabled:dA}),d(hA=>({...hA,[j]:!!dA}))}}),E.useEffect(()=>{let j=!0;return(async()=>{try{const dA=await Wo();if(!j)return;b(!1),i&&d(hA=>({...hA,[i]:!1})),M(g?!!dA.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,dA]of c.current)await H(dA.pc,void 0),await P(dA.pc,void 0),await ye(j,dA.pc,dA).catch(()=>{})})(),gA(),pA())},[g,i]),E.useEffect(()=>{const j=dA=>{const hA=dA.detail;hA&&(typeof hA.video=="boolean"&&hA.video===!1&&(b(!1),d(UA=>({...UA,[i]:!1}))),typeof hA.chatAudio=="boolean"&&M(hA.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)},dA=()=>{for(const[UA,TA]of c.current)O(UA,TA)},hA=()=>{for(const[UA,TA]of c.current)O(UA,TA)};return document.addEventListener("visibilitychange",j),window.addEventListener("online",dA),window.addEventListener("offline",hA),()=>{document.removeEventListener("visibilitychange",j),window.removeEventListener("online",dA),window.removeEventListener("offline",hA)}},[]),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(ydA.Provider,{value:{videoEnabled:w,setVideoEnabled:Ee,enableCamera:EA,joinRtc:Ie,leaveRtc:DA,cameraOwnerId:Q,setCameraOwner:IA,remoteStreams:l,myVideo:p,micEnabled:G,setMicEnabled:NA,hasVideo:QA,speaking:fA,remoteVideoFlags:h},children:e})}function dXA(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 N3(e){var A,t,i,n;try{const g=window,o=g.__rtcCtxInternal||{},s=o.peers||new Map,r=(A=o.myVideoRef)==null?void 0:A.current,a=(t=r==null?void 0:r.getVideoTracks)==null?void 0:t.call(r)[0],I={t:Date.now(),label:e,videoEnabled:(i=o.videoEnabledState)==null?void 0:i.current,hasStream:!!r,trackState:a==null?void 0:a.readyState,muted:a==null?void 0:a.muted,peers:dXA(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=N3})}catch{}function al(){var _;const e=CXA(),A=lXA(),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,r=A==null?void 0:A.leaveRtc,a=A==null?void 0:A.setVideoEnabled,I=A==null?void 0:A.setMicEnabled,c=E.useRef(s);c.current=s;const l=E.useRef(r);l.current=r;const B=E.useRef(a);B.current=a;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,T,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 q=K.mediaStream,z=((T=q.getVideoTracks()[0])==null?void 0:T.id)??"";return((v=k.current)==null?void 0:v.trackId)===z?k.current.ms:(k.current={trackId:z,ms:q},q)}const x=K.mediaStreamTrack;if(x instanceof MediaStreamTrack){if(((U=k.current)==null?void 0:U.trackId)===x.id)return k.current.ms;const q=new MediaStream;return q.addTrack(x),k.current={trackId:x.id,ms:q},q}}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,T=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 q=(U==null?void 0:U.id)??"",z=(x==null?void 0:x.id)??"";T.add(v.id);const Z=J[v.id];if(Z&&Z.videoId===q&&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:q,audioId:z,ms:eA},K[v.id]=eA}for(const v of Object.keys(J))T.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),tI=()=>E.useContext(DdA),CY={};function hXA({children:e}){const{user:A,meId:t}=en(),i=t||(A==null?void 0:A.id),{resetSpin:n}=MB(),g=Ji(),{joinRoom:o,leaveRoom:s,setSpectate:r,pokerJoinRoom:a,getRoomsList:I}=So(),[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}=al(),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,T,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=(T=window.location)==null?void 0:T.search)==null?void 0:v.includes("e2e=1"))||window.__E2E===!0||typeof window.sessionStorage<"u"&&window.sessionStorage.getItem("e2e")==="1")))throw U;const q=Date.now(),z=i||"e2e-user",Z=(A==null?void 0:A.name)||"E2E User",eA={id:w,name:"E2E Room",gameMode:"craps",createdAt:q,updatedAt:q,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 T=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 q=T.get(U);q?J.push({...q,...x,name:x.name||q.name,avatarUrl:x.avatarUrl??q.avatarUrl}):J.push(x)}}return{...w,...b,players:J}}catch{return b||w}},[]);xs({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 T,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||""),q=x&&U.some(z=>String(z==null?void 0:z.id)===x);if(q&&K)try{delete d.current[String(K.id||"")]}catch{}if(!q&&K){if(!!(w!=null&&w.singlePlayer||J!=null&&J.singlePlayer)||((T=w==null?void 0:w.gameState)==null?void 0:T.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(T=>T.id!==w?T:{...T,...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(T=>[T.id,T])),K=new Map((w.players||[]).map(T=>[T.id,T])),J=b.players.map(T=>{const v=K.get(T.id);if(!v)return T;const U={...T,...v};return(!v.name||v.name==="Player"||v.name==="Anonymous")&&T.name&&T.name!=="Player"&&T.name!=="Anonymous"&&(U.name=T.name),v.avatarUrl==null&&T.avatarUrl&&(U.avatarUrl=T.avatarUrl),U});for(const[T,v]of K.entries())_.has(T)||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"&&pcA();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 T=!1,v=null;if(l(U=>{var q;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"||((q=U==null?void 0:U.gameState)==null?void 0:q.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}:(T=!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}}),T){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 T=_.players.slice();return T[K]={...J,balance:b},{..._,players:T}})},onError:w=>{console.warn("Socket error:",w);try{const b=(Fl==null?void 0:Fl())||[],_=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 r(c.id,w)}catch(b){return{ok:!1,error:(b==null?void 0:b.message)||"Failed"}}}}),[c,p,y,m,r]),k=Ss(),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 T=((Fl==null?void 0:Fl())||[]).slice(-1)[0];if(T&&String(T.event).toLowerCase().includes("create_room")&&w-(T.ts||0)<1500)return}catch{}return}try{const T=((Fl==null?void 0:Fl())||[]).slice(-1)[0];T&&String(T.event).toLowerCase().includes("create_room")&&w-(T.ts||0)<1500&&await new Promise(U=>setTimeout(U,1100))}catch{}try{const J=(c==null?void 0:c.gameMode)==="poker";let T;if(J&&typeof a=="function"){const v=CY[b];if(v)T=await v;else{const U=a(b);CY[b]=U;try{T=await U}finally{delete CY[b]}}}else T=await o(b);if(T!=null&&T.ok){try{n()}catch{}if(l(T.room),!((_=T.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(q=>(q==null?void 0:q.id)===b);x&&Array.isArray(x.players)&&l(q=>!q||q.id!==b?q:{...q,players:x.players})}catch{}}}catch(J){console.warn("[room] rejoin after reconnect failed",J)}},[c==null?void 0:c.id,a,o,n,Q,I]);return E.useEffect(()=>{var J;if(!k)return;const w=T=>{T!=="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 T;k.off("disconnect",w),k.off("connect",b);try{k.io.off("reconnect",_)}catch{}try{(T=k.off)==null||T.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 Yb=globalThis.__lastWagersFetchAt||(globalThis.__lastWagersFetchAt={}),IeA=500;function ox(e,A){const t=Ss(),{room:i}=tI(),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 hS(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 hS(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:r,cancelSideBet:a,acceptSideBet:I,placeMainBet:c,cancelMainBet:l}=So(),[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&&pS(n)},[e,n]),xs({onBetsUpdated:W=>{n&&(async()=>{try{const P=W.open.find(tA=>tA.type==="MAIN"&&tA.playerId===A);P?await dL(n,{roundSeq:W.roundSeq,mainWagerId:P.id}):await pS(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=Yb[e]||0;H-P<IeA||(Yb[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-(Yb[e]||0)<IeA)){W.current=iA,Yb[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))},Vo.mySettledDelayMs);return()=>clearTimeout(W)},[D,A]);const[J,T]=E.useState(null);E.useEffect(()=>{const W=setTimeout(()=>{T(g.playerBalance)},Vo.balanceDelayMs);return()=>clearTimeout(W)},[g.playerBalance]);const[v,U]=E.useState([]);E.useEffect(()=>{const W=setTimeout(()=>{U(D)},Vo.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]),q=()=>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 r(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,r]),aA=E.useCallback(async W=>{try{const $=await a(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,a]),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),YA=E.useRef(new Set);return E.useEffect(()=>{RA.current!==g.roundSeq&&(RA.current=g.roundSeq,YA.current.clear(),fA([]));const W=g.settledAll.filter($=>$.roundSeq===g.roundSeq&&!YA.current.has($.id));if(W.length>0){W.forEach(L=>YA.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:q,markAsSeen:z,offersToMe:x,newOfferCount:p,markOffersAsSeen:Z,placeSideBet:eA,cancelSideBet:aA,acceptSideBet:sA,placeMainBet:pA,cancelMainBet:gA,playerBalance:J,newSettlements:yA}}function CeA(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=ceA(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=CeA(e.result),s=pXA(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=ceA(e),r=e.result==="WIN"?s:0,a={myResult:e.result,myPayout:r,label:Zh(e.result,r,e.amount)};if(a.myResult==="WIN"&&a.myPayout<=0){const I=typeof e.payout=="number"&&e.payout>0?e.payout:e.amount;return{myResult:a.myResult,myPayout:I,label:Zh(a.myResult,I,e.amount)}}return a}else{const s=CeA(e.result),r=fXA(e),a=s==="WIN"?r:0,I={myResult:s,myPayout:a,label:Zh(s,a,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 ceA(e){return typeof e.payout=="number"?e.payout:e.amount}function pXA(e){return e.amount}function fXA(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 yXA(e){return!e||e.length===0?0:e.reduce((A,t)=>A+Number((t==null?void 0:t.amount)||0),0)}function mdA({meId:e,items:A,onClose:t,nameOf:i,crapsRollHistory:n,gameMode:g,crapsLedgerItems:o}){const s=A,r=g==="craps",a={};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)),a[l]=(a[l]??0)+Q}const I=Object.entries(a).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"})]}),!r&&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))})}),r&&C.jsxs(C.Fragment,{children:[(()=>{const c=yXA(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)})]})]}),!r&&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 leA;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(leA||(leA={}));var BeA;(function(e){e.Body="body",e.Ionic="ionic",e.Native="native",e.None="none"})(BeA||(BeA={}));const Hb=nl("Keyboard"),DXA=e=>{if(e<1e3)return String(e);const A=e/1e3;return`${Number.isInteger(A)?A.toFixed(0):A.toFixed(1)}K`};function SdA({onPlaceBet:e,onCancelBet:A,disabled:t=!1,showCancel:i=!1,min:n=1,max:g,defaultValue:o=25,heading:s,quickAmounts:r=[],onAmountChange:a}){const[I,c]=E.useState(o),l=E.useRef(!1),[B,Q]=E.useState(0),h=E.useRef(null);E.useEffect(()=>{if(!ti.isNativePlatform())return;Hb.setAccessoryBarVisible({isVisible:!0});const k=Hb.addListener("keyboardWillShow",G=>Q(G.keyboardHeight)),N=Hb.addListener("keyboardWillHide",()=>Q(0));return()=>{Hb.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),a==null||a(M)},[g,a]),p=E.useCallback(()=>{var N;if(l.current||t||i)return;const k=Math.max(n,Math.floor(I));k<=0||(l.current=!0,Xt("Light"),(N=h.current)==null||N.blur(),e(k),setTimeout(()=>{l.current=!1},600))},[t,i,I,n,e]),y=E.useCallback(()=>{i&&(Xt("Light"),A())},[i,A]),m=E.useCallback(k=>{if(t||i)return;Xt("Light");const N=g!=null?Math.min(k,g):k;c(N),a==null||a(N)},[t,g,a,i]),D=!t&&!i&&I>=n,S=r.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:r.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:["ℤ",DXA(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&&zr.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 mXA="/assets/roll-btn-web-wZ6ex-aH.webp",wdA=50,Ob=wdA/1200;function kdA({disabled:e,busy:A=!1,onClick:t,onPressStart:i,onChargeChange:n,label:g="ROLL",className:o,"aria-label":s,useImage:r=!0,"data-testid":a}){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+Ob),(S=Q.current)==null||S.call(Q,l.current),l.current>=.25&&l.current<.25+Ob*1.5?yo("Light"):l.current>=.6&&l.current<.6+Ob*1.5?yo("Medium"):l.current>=.95&&l.current<.95+Ob*1.5&&yo("Heavy")},wdA)},[]),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,qn(),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 yo("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 yo("Heavy")}},[I,t,i]);return C.jsx("div",{className:["roll-wrapper",o].filter(Boolean).join(" "),children:C.jsxs("button",{type:"button",className:["roll",r?"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":a,children:[r&&C.jsx("img",{src:mXA,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"}),!r&&C.jsx("span",{className:"roll__gloss","aria-hidden":"true"}),!r&&C.jsx("span",{className:"roll__label","aria-live":"polite",children:A?"ROLLING…":g})]})})}function SXA({roomId:e,meId:A,bankerId:t,players:i,className:n,hasBankRoll:g,gameState:o,gameplay:s,onChargeChange:r}){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=NB(),S=(o.banker??(I?o.currentRollerId:void 0)??t)===A,{settled:k,myOpenMain:N,placeMainBet:G,cancelMainBet:M}=ox(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,T=(o==null?void 0:o.betsLocked)??!1;o==null||o.roundSeq;const v=!!(o!=null&&o.bankRoll),U=v,[x,q]=E.useState(!1),z=E.useRef(T),Z=E.useRef(null);E.useEffect(()=>(z.current&&!T&&(q(!0),Z.current&&window.clearTimeout(Z.current),Z.current=window.setTimeout(()=>{q(!1),Z.current=null},3e3)),T&&Z.current&&(window.clearTimeout(Z.current),Z.current=null,q(!1)),z.current=T,()=>{Z.current&&window.clearTimeout(Z.current)}),[T]);const eA=E.useCallback(async fA=>{var YA;try{qn()}catch{}if(h)return;const RA=Math.floor(fA??Q);if(RA<=0){m.info("Enter a bet amount.");return}if(!v){if(T||U){m.info("Bets are closed.");return}if((YA=o==null?void 0:o.spectators)!=null&&YA.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,T,U,o,G]),aA=E.useCallback(async()=>{try{qn()}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||T||w,yA=S?"Banker":pA?"Spectating":N||w?"Bet Locked":U||T?"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(kdA,{disabled:!K||pA,busy:!J,onClick:_,onChargeChange:r,useImage:!1,className:"roll-wrapper--rect","data-testid":"roll-button"})}),!S&&C.jsx("div",{className:"betpanel__row",children:C.jsx(SdA,{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(mdA,{meId:A,items:k,onClose:()=>y(!1)})]})}const wXA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let cY=(e=21)=>{let A="",t=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)A+=wXA[t[e]&63];return A};const MdA=E.createContext({});function kXA(e){const A=E.useRef(null);return A.current===null&&(A.current=e()),A.current}const Pz=typeof window<"u",MXA=Pz?E.useLayoutEffect:E.useEffect,jz=E.createContext(null);function zz(e,A){e.indexOf(A)===-1&&e.push(A)}function Zz(e,A){const t=e.indexOf(A);t>-1&&e.splice(t,1)}const eQ=(e,A,t)=>t>A?A:t<e?e:t;let Wz=()=>{};const tQ={},NdA=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function RdA(e){return typeof e=="object"&&e!==null}const GdA=e=>/^0[^.\s]+$/u.test(e);function Vz(e){let A;return()=>(A===void 0&&(A=e()),A)}const XC=e=>e,NXA=(e,A)=>t=>A(e(t)),zR=(...e)=>e.reduce(NXA),hN=(e,A,t)=>{const i=A-e;return i===0?1:(t-e)/i};class Xz{constructor(){this.subscriptions=[]}add(A){return zz(this.subscriptions,A),()=>Zz(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 BB=e=>e*1e3,EB=e=>e/1e3;function bdA(e,A){return A?e*(1e3/A):0}const UdA=(e,A,t)=>(((1-3*t+3*A)*e+(3*t-6*A))*e+3*A)*e,RXA=1e-7,GXA=12;function bXA(e,A,t,i,n){let g,o,s=0;do o=A+(t-A)/2,g=UdA(o,i,n)-e,g>0?t=o:A=o;while(Math.abs(g)>RXA&&++s<GXA);return o}function ZR(e,A,t,i){if(e===A&&t===i)return XC;const n=g=>bXA(g,0,1,e,t);return g=>g===0||g===1?g:UdA(n(g),A,i)}const vdA=e=>A=>A<=.5?e(2*A)/2:(2-e(2*(1-A)))/2,KdA=e=>A=>1-e(1-A),FdA=ZR(.33,1.53,.69,.99),$z=KdA(FdA),_dA=vdA($z),JdA=e=>(e*=2)<1?.5*$z(e):.5*(2-Math.pow(2,-10*(e-1))),AZ=e=>1-Math.sin(Math.acos(e)),LdA=KdA(AZ),xdA=vdA(AZ),UXA=ZR(.42,0,1,1),vXA=ZR(0,0,.58,1),TdA=ZR(.42,0,.58,1),KXA=e=>Array.isArray(e)&&typeof e[0]!="number",qdA=e=>Array.isArray(e)&&typeof e[0]=="number",FXA={linear:XC,easeIn:UXA,easeInOut:TdA,easeOut:vXA,circIn:AZ,circInOut:xdA,circOut:LdA,backIn:$z,backInOut:_dA,backOut:FdA,anticipate:JdA},_XA=e=>typeof e=="string",EeA=e=>{if(qdA(e)){Wz(e.length===4);const[A,t,i,n]=e;return ZR(A,t,i,n)}else if(_XA(e))return FXA[e];return e},Pb=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function JXA(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 r(I){o.has(I)&&(a.schedule(I),e()),I(s)}const a={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(r),t.clear(),n=!1,g&&(g=!1,a.process(I))}};return a}const LXA=40;function YdA(e,A){let t=!1,i=!0;const n={delta:0,timestamp:0,isProcessing:!1},g=()=>t=!0,o=Pb.reduce((m,D)=>(m[D]=JXA(g),m),{}),{setup:s,read:r,resolveKeyframes:a,preUpdate:I,update:c,preRender:l,render:B,postRender:Q}=o,h=()=>{const m=tQ.useManualTiming?n.timestamp:performance.now();t=!1,tQ.useManualTiming||(n.delta=i?1e3/60:Math.max(Math.min(m-n.timestamp,LXA),1)),n.timestamp=m,n.isProcessing=!0,s.process(n),r.process(n),a.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:Pb.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<Pb.length;D++)o[Pb[D]].cancel(m)},state:n,steps:o}}const{schedule:ao,cancel:Bd,state:Er,steps:lY}=YdA(typeof requestAnimationFrame<"u"?requestAnimationFrame:XC,!0);let kK;function xXA(){kK=void 0}const iI={now:()=>(kK===void 0&&iI.set(Er.isProcessing||tQ.useManualTiming?Er.timestamp:performance.now()),kK),set:e=>{kK=e,queueMicrotask(xXA)}},HdA=e=>A=>typeof A=="string"&&A.startsWith(e),eZ=HdA("--"),TXA=HdA("var(--"),tZ=e=>TXA(e)?qXA.test(e.split("/*")[0].trim()):!1,qXA=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Rw={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},pN={...Rw,transform:e=>eQ(0,1,e)},jb={...Rw,default:1},EM=e=>Math.round(e*1e5)/1e5,iZ=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function YXA(e){return e==null}const HXA=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,nZ=(e,A)=>t=>!!(typeof t=="string"&&HXA.test(t)&&t.startsWith(e)||A&&!YXA(t)&&Object.prototype.hasOwnProperty.call(t,A)),OdA=(e,A,t)=>i=>{if(typeof i!="string")return i;const[n,g,o,s]=i.match(iZ);return{[e]:parseFloat(n),[A]:parseFloat(g),[t]:parseFloat(o),alpha:s!==void 0?parseFloat(s):1}},OXA=e=>eQ(0,255,e),BY={...Rw,transform:e=>Math.round(OXA(e))},Cp={test:nZ("rgb","red"),parse:OdA("red","green","blue"),transform:({red:e,green:A,blue:t,alpha:i=1})=>"rgba("+BY.transform(e)+", "+BY.transform(A)+", "+BY.transform(t)+", "+EM(pN.transform(i))+")"};function PXA(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 R3={test:nZ("#"),parse:PXA,transform:Cp.transform},WR=e=>({test:A=>typeof A=="string"&&A.endsWith(e)&&A.split(" ").length===1,parse:parseFloat,transform:A=>`${A}${e}`}),ZQ=WR("deg"),QB=WR("%"),vi=WR("px"),jXA=WR("vh"),zXA=WR("vw"),QeA={...QB,parse:e=>QB.parse(e)/100,transform:e=>QB.transform(e*100)},em={test:nZ("hsl","hue"),parse:OdA("hue","saturation","lightness"),transform:({hue:e,saturation:A,lightness:t,alpha:i=1})=>"hsla("+Math.round(e)+", "+QB.transform(EM(A))+", "+QB.transform(EM(t))+", "+EM(pN.transform(i))+")"},Cs={test:e=>Cp.test(e)||R3.test(e)||em.test(e),parse:e=>Cp.test(e)?Cp.parse(e):em.test(e)?em.parse(e):R3.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Cp.transform(e):em.transform(e),getAnimatableNone:e=>{const A=Cs.parse(e);return A.alpha=0,Cs.transform(A)}},ZXA=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function WXA(e){var A,t;return isNaN(e)&&typeof e=="string"&&(((A=e.match(iZ))==null?void 0:A.length)||0)+(((t=e.match(ZXA))==null?void 0:t.length)||0)>0}const PdA="number",jdA="color",VXA="var",XXA="var(",ueA="${}",$XA=/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 fN(e){const A=e.toString(),t=[],i={color:[],number:[],var:[]},n=[];let g=0;const s=A.replace($XA,r=>(Cs.test(r)?(i.color.push(g),n.push(jdA),t.push(Cs.parse(r))):r.startsWith(XXA)?(i.var.push(g),n.push(VXA),t.push(r)):(i.number.push(g),n.push(PdA),t.push(parseFloat(r))),++g,ueA)).split(ueA);return{values:t,split:s,indexes:i,types:n}}function zdA(e){return fN(e).values}function ZdA(e){const{split:A,types:t}=fN(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===PdA?g+=EM(n[o]):s===jdA?g+=Cs.transform(n[o]):g+=n[o]}return g}}const A6A=e=>typeof e=="number"?0:Cs.test(e)?Cs.getAnimatableNone(e):e;function e6A(e){const A=zdA(e);return ZdA(e)(A.map(A6A))}const Ed={test:WXA,parse:zdA,createTransformer:ZdA,getAnimatableNone:e6A};function EY(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 t6A({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,r=2*t-s;n=EY(r,s,e+1/3),g=EY(r,s,e),o=EY(r,s,e-1/3)}return{red:Math.round(n*255),green:Math.round(g*255),blue:Math.round(o*255),alpha:i}}function l_(e,A){return t=>t>0?A:e}const Do=(e,A,t)=>e+(A-e)*t,QY=(e,A,t)=>{const i=e*e,n=t*(A*A-i)+i;return n<0?0:Math.sqrt(n)},i6A=[R3,Cp,em],n6A=e=>i6A.find(A=>A.test(e));function deA(e){const A=n6A(e);if(!A)return!1;let t=A.parse(e);return A===em&&(t=t6A(t)),t}const heA=(e,A)=>{const t=deA(e),i=deA(A);if(!t||!i)return l_(e,A);const n={...t};return g=>(n.red=QY(t.red,i.red,g),n.green=QY(t.green,i.green,g),n.blue=QY(t.blue,i.blue,g),n.alpha=Do(t.alpha,i.alpha,g),Cp.transform(n))},G3=new Set(["none","hidden"]);function g6A(e,A){return G3.has(e)?t=>t<=0?e:A:t=>t>=1?A:e}function o6A(e,A){return t=>Do(e,A,t)}function gZ(e){return typeof e=="number"?o6A:typeof e=="string"?tZ(e)?l_:Cs.test(e)?heA:a6A:Array.isArray(e)?WdA:typeof e=="object"?Cs.test(e)?heA:s6A:l_}function WdA(e,A){const t=[...e],i=t.length,n=e.map((g,o)=>gZ(g)(g,A[o]));return g=>{for(let o=0;o<i;o++)t[o]=n[o](g);return t}}function s6A(e,A){const t={...e,...A},i={};for(const n in t)e[n]!==void 0&&A[n]!==void 0&&(i[n]=gZ(e[n])(e[n],A[n]));return n=>{for(const g in i)t[g]=i[g](n);return t}}function r6A(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 a6A=(e,A)=>{const t=Ed.createTransformer(A),i=fN(e),n=fN(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?G3.has(e)&&!n.values.length||G3.has(A)&&!i.values.length?g6A(e,A):zR(WdA(r6A(i,n),n.values),t):l_(e,A)};function VdA(e,A,t){return typeof e=="number"&&typeof A=="number"&&typeof t=="number"?Do(e,A,t):gZ(e)(e,A)}const I6A=e=>{const A=({timestamp:t})=>e(t);return{start:(t=!0)=>ao.update(A,t),stop:()=>Bd(A),now:()=>Er.isProcessing?Er.timestamp:iI.now()}},XdA=(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)})`},B_=2e4;function oZ(e){let A=0;const t=50;let i=e.next(A);for(;!i.done&&A<B_;)A+=t,i=e.next(A);return A>=B_?1/0:A}function C6A(e,A=100,t){const i=t({...e,keyframes:[0,A]}),n=Math.min(oZ(i),B_);return{type:"keyframes",ease:g=>i.next(n*g).value/A,duration:EB(n)}}const c6A=5;function $dA(e,A,t){const i=Math.max(A-c6A,0);return bdA(t-e(i),A-i)}const Ko={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},uY=.001;function l6A({duration:e=Ko.duration,bounce:A=Ko.bounce,velocity:t=Ko.velocity,mass:i=Ko.mass}){let n,g,o=1-A;o=eQ(Ko.minDamping,Ko.maxDamping,o),e=eQ(Ko.minDuration,Ko.maxDuration,EB(e)),o<1?(n=a=>{const I=a*o,c=I*e,l=I-t,B=b3(a,o),Q=Math.exp(-c);return uY-l/B*Q},g=a=>{const c=a*o*e,l=c*t+t,B=Math.pow(o,2)*Math.pow(a,2)*e,Q=Math.exp(-c),h=b3(Math.pow(a,2),o);return(-n(a)+uY>0?-1:1)*((l-B)*Q)/h}):(n=a=>{const I=Math.exp(-a*e),c=(a-t)*e+1;return-uY+I*c},g=a=>{const I=Math.exp(-a*e),c=(t-a)*(e*e);return I*c});const s=5/e,r=E6A(n,g,s);if(e=BB(e),isNaN(r))return{stiffness:Ko.stiffness,damping:Ko.damping,duration:e};{const a=Math.pow(r,2)*i;return{stiffness:a,damping:o*2*Math.sqrt(i*a),duration:e}}}const B6A=12;function E6A(e,A,t){let i=t;for(let n=1;n<B6A;n++)i=i-e(i)/A(i);return i}function b3(e,A){return e*Math.sqrt(1-A*A)}const Q6A=["duration","bounce"],u6A=["stiffness","damping","mass"];function peA(e,A){return A.some(t=>e[t]!==void 0)}function d6A(e){let A={velocity:Ko.velocity,stiffness:Ko.stiffness,damping:Ko.damping,mass:Ko.mass,isResolvedFromDuration:!1,...e};if(!peA(e,u6A)&&peA(e,Q6A))if(e.visualDuration){const t=e.visualDuration,i=2*Math.PI/(t*1.2),n=i*i,g=2*eQ(.05,1,1-(e.bounce||0))*Math.sqrt(n);A={...A,mass:Ko.mass,stiffness:n,damping:g}}else{const t=l6A(e);A={...A,...t,mass:Ko.mass},A.isResolvedFromDuration=!0}return A}function E_(e=Ko.visualDuration,A=Ko.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:r,damping:a,mass:I,duration:c,velocity:l,isResolvedFromDuration:B}=d6A({...t,velocity:-EB(t.velocity||0)}),Q=l||0,h=a/(2*Math.sqrt(r*I)),d=o-g,p=EB(Math.sqrt(r/I)),y=Math.abs(d)<5;i||(i=y?Ko.restSpeed.granular:Ko.restSpeed.default),n||(n=y?Ko.restDelta.granular:Ko.restDelta.default);let m;if(h<1){const S=b3(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?BB(Q):$dA(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(oZ(D),B_),k=XdA(N=>D.next(S*N).value,S,30);return S+"ms "+k},toTransition:()=>{}};return D}E_.applyToOptions=e=>{const A=C6A(e,100,E_);return e.ease=A.ease,e.duration=BB(A.duration),e.type="keyframes",e};function U3({keyframes:e,velocity:A=0,power:t=.8,timeConstant:i=325,bounceDamping:n=10,bounceStiffness:g=500,modifyTarget:o,min:s,max:r,restDelta:a=.5,restSpeed:I}){const c=e[0],l={done:!1,value:c},B=G=>s!==void 0&&G<s||r!==void 0&&G>r,Q=G=>s===void 0?r:r===void 0||Math.abs(s-G)<Math.abs(r-G)?s:r;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)<=a,l.value=l.done?p:w};let S,k;const N=G=>{B(l.value)&&(S=G,k=E_({keyframes:[l.value,Q(l.value)],velocity:$dA(m,G,l.value),damping:n,stiffness:g,restDelta:a,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 h6A(e,A,t){const i=[],n=t||tQ.mix||VdA,g=e.length-1;for(let o=0;o<g;o++){let s=n(e[o],e[o+1]);if(A){const r=Array.isArray(A)?A[o]||XC:A;s=zR(r,s)}i.push(s)}return i}function p6A(e,A,{clamp:t=!0,ease:i,mixer:n}={}){const g=e.length;if(Wz(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=h6A(A,i,n),r=s.length,a=I=>{if(o&&I<e[0])return A[0];let c=0;if(r>1)for(;c<e.length-2&&!(I<e[c+1]);c++);const l=hN(e[c],e[c+1],I);return s[c](l)};return t?I=>a(eQ(e[0],e[g-1],I)):a}function f6A(e,A){const t=e[e.length-1];for(let i=1;i<=A;i++){const n=hN(0,A,i);e.push(Do(t,1,n))}}function y6A(e){const A=[0];return f6A(A,e.length-1),A}function D6A(e,A){return e.map(t=>t*A)}function m6A(e,A){return e.map(()=>A||TdA).splice(0,e.length-1)}function QM({duration:e=300,keyframes:A,times:t,ease:i="easeInOut"}){const n=KXA(i)?i.map(EeA):EeA(i),g={done:!1,value:A[0]},o=D6A(t&&t.length===A.length?t:y6A(A),e),s=p6A(o,A,{ease:Array.isArray(n)?n:m6A(A,n)});return{calculatedDuration:e,next:r=>(g.value=s(r),g.done=r>=e,g)}}const S6A=e=>e!==null;function sZ(e,{repeat:A,repeatType:t="loop"},i,n=1){const g=e.filter(S6A),s=n<0||A&&t!=="loop"&&A%2===1?0:g.length-1;return!s||i===void 0?g[s]:i}const w6A={decay:U3,inertia:U3,tween:QM,keyframes:QM,spring:E_};function AhA(e){typeof e.type=="string"&&(e.type=w6A[e.type])}class rZ{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 k6A=e=>e/100;class aZ extends rZ{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!==iI.now()&&this.tick(iI.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;AhA(A);const{type:t=QM,repeat:i=0,repeatDelay:n=0,repeatType:g,velocity:o=0}=A;let{keyframes:s}=A;const r=t||QM;r!==QM&&typeof s[0]!="number"&&(this.mixKeyframes=zR(k6A,VdA(s[0],s[1])),s=[0,100]);const a=r({...A,keyframes:s});g==="mirror"&&(this.mirroredGenerator=r({...A,keyframes:[...s].reverse(),velocity:-o})),a.calculatedDuration===null&&(a.calculatedDuration=oZ(a));const{calculatedDuration:I}=a;this.calculatedDuration=I,this.resolvedDuration=I+n,this.totalDuration=this.resolvedDuration*(i+1)-n,this.generator=a}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:r}=this;if(this.startTime===null)return i.next(0);const{delay:a=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-a*(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=eQ(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&&r!==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!==U3&&(S.value=sZ(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 EB(this.calculatedDuration)}get time(){return EB(this.currentTime)}set time(A){var t;A=BB(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(iI.now());const t=this.playbackSpeed!==A;this.playbackSpeed=A,t&&(this.time=EB(this.currentTime))}play(){var n,g;if(this.isStopped)return;const{driver:A=I6A,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(iI.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 M6A(e){for(let A=1;A<e.length;A++)e[A]??(e[A]=e[A-1])}const cp=e=>e*180/Math.PI,v3=e=>{const A=cp(Math.atan2(e[1],e[0]));return K3(A)},N6A={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:v3,rotateZ:v3,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},K3=e=>(e=e%360,e<0&&(e+=360),e),feA=v3,yeA=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),DeA=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),R6A={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:yeA,scaleY:DeA,scale:e=>(yeA(e)+DeA(e))/2,rotateX:e=>K3(cp(Math.atan2(e[6],e[5]))),rotateY:e=>K3(cp(Math.atan2(-e[2],e[0]))),rotateZ:feA,rotate:feA,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 F3(e){return e.includes("scale")?1:0}function _3(e,A){if(!e||e==="none")return F3(A);const t=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,n;if(t)i=R6A,n=t;else{const s=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=N6A,n=s}if(!n)return F3(A);const g=i[A],o=n[1].split(",").map(b6A);return typeof g=="function"?g(o):o[g]}const G6A=(e,A)=>{const{transform:t="none"}=getComputedStyle(e);return _3(t,A)};function b6A(e){return parseFloat(e.trim())}const Gw=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],bw=new Set(Gw),meA=e=>e===Rw||e===vi,U6A=new Set(["x","y","z"]),v6A=Gw.filter(e=>!U6A.has(e));function K6A(e){const A=[];return v6A.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})=>_3(A,"x"),y:(e,{transform:A})=>_3(A,"y")};Lp.translateX=Lp.x;Lp.translateY=Lp.y;const xp=new Set;let J3=!1,L3=!1,x3=!1;function ehA(){if(L3){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=K6A(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)})}L3=!1,J3=!1,xp.forEach(e=>e.complete(x3)),xp.clear()}function thA(){xp.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(L3=!0)})}function F6A(){x3=!0,thA(),ehA(),x3=!1}class IZ{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),J3||(J3=!0,ao.read(thA),ao.resolveKeyframes(ehA))):(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])}M6A(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 _6A=e=>e.startsWith("--");function J6A(e,A,t){_6A(A)?e.style.setProperty(A,t):e.style[A]=t}const L6A=Vz(()=>window.ScrollTimeline!==void 0),x6A={};function T6A(e,A){const t=Vz(e);return()=>x6A[A]??t()}const ihA=T6A(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Dk=([e,A,t,i])=>`cubic-bezier(${e}, ${A}, ${t}, ${i})`,SeA={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Dk([0,.65,.55,1]),circOut:Dk([.55,0,1,.45]),backIn:Dk([.31,.01,.66,-.59]),backOut:Dk([.33,1.53,.69,.99])};function nhA(e,A){if(e)return typeof e=="function"?ihA()?XdA(e,A):"ease-out":qdA(e)?Dk(e):Array.isArray(e)?e.map(t=>nhA(t,A)||SeA.easeOut):SeA[e]}function q6A(e,A,t,{delay:i=0,duration:n=300,repeat:g=0,repeatType:o="loop",ease:s="easeOut",times:r}={},a=void 0){const I={[A]:t};r&&(I.offset=r);const c=nhA(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 a&&(l.pseudoElement=a),e.animate(I,l)}function ghA(e){return typeof e=="function"&&"applyToOptions"in e}function Y6A({type:e,...A}){return ghA(e)&&ihA()?e.applyToOptions(A):(A.duration??(A.duration=300),A.ease??(A.ease="easeOut"),A)}class H6A extends rZ{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:r}=A;this.isPseudoElement=!!g,this.allowFlatten=o,this.options=A,Wz(typeof A.type!="string");const a=Y6A(A);this.animation=q6A(t,i,n,a,g),a.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!g){const I=sZ(n,this.options,s,this.speed);this.updateMotionValue?this.updateMotionValue(I):J6A(t,i,I),this.animation.cancel()}r==null||r(),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 EB(Number(A))}get time(){return EB(Number(this.animation.currentTime)||0)}set time(A){this.finishedTime=null,this.animation.currentTime=BB(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&&L6A()?(this.animation.timeline=A,XC):t(this)}}const ohA={anticipate:JdA,backInOut:_dA,circInOut:xdA};function O6A(e){return e in ohA}function P6A(e){typeof e.ease=="string"&&O6A(e.ease)&&(e.ease=ohA[e.ease])}const weA=10;class j6A extends H6A{constructor(A){P6A(A),AhA(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 aZ({...o,autoplay:!1}),r=BB(this.finishedTime??this.time);t.setWithVelocity(s.sample(r-weA).value,s.sample(r).value,weA),s.stop()}}const keA=(e,A)=>A==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(Ed.test(e)||e==="0")&&!e.startsWith("url("));function z6A(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 Z6A(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=keA(n,A),s=keA(g,A);return!o||!s?!1:z6A(e)||(t==="spring"||ghA(t))&&i}function T3(e){e.duration=0,e.type}const W6A=new Set(["opacity","clipPath","filter","transform"]),V6A=Vz(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function X6A(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:r,transformTemplate:a}=A.owner.getProps();return V6A()&&t&&W6A.has(t)&&(t!=="transform"||!a)&&!r&&!i&&n!=="mirror"&&g!==0&&o!=="inertia"}const $6A=40;class A7A extends rZ{constructor({autoplay:A=!0,delay:t=0,type:i="keyframes",repeat:n=0,repeatDelay:g=0,repeatType:o="loop",keyframes:s,name:r,motionValue:a,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=iI.now();const l={autoplay:A,delay:t,type:i,repeat:n,repeatDelay:g,repeatType:o,name:r,motionValue:a,element:I,...c},B=(I==null?void 0:I.KeyframeResolver)||IZ;this.keyframeResolver=new B(s,(h,d,p)=>this.onKeyframesResolved(h,d,l,!p),r,a,I),(Q=this.keyframeResolver)==null||Q.scheduleResolve()}onKeyframesResolved(A,t,i,n){this.keyframeResolver=void 0;const{name:g,type:o,velocity:s,delay:r,isHandoff:a,onUpdate:I}=i;this.resolvedAt=iI.now(),Z6A(A,g,o,s)||((tQ.instantAnimations||!r)&&(I==null||I(sZ(A,i,t))),A[0]=A[A.length-1],T3(i),i.repeat=0);const l={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>$6A?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:t,...i,keyframes:A},B=!a&&X6A(l)?new j6A({...l,element:l.motionValue.owner.current}):new aZ(l);B.finished.then(()=>this.notifyFinished()).catch(XC),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(),F6A()),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 e7A=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function t7A(e){const A=e7A.exec(e);if(!A)return[,];const[,t,i,n]=A;return[`--${t??i}`,n]}function shA(e,A,t=1){const[i,n]=t7A(e);if(!i)return;const g=window.getComputedStyle(A).getPropertyValue(i);if(g){const o=g.trim();return NdA(o)?parseFloat(o):o}return tZ(n)?shA(n,A,t+1):n}function CZ(e,A){return(e==null?void 0:e[A])??(e==null?void 0:e.default)??e}const rhA=new Set(["width","height","top","left","right","bottom",...Gw]),i7A={test:e=>e==="auto",parse:e=>e},ahA=e=>A=>A.test(e),IhA=[Rw,vi,QB,ZQ,zXA,jXA,i7A],MeA=e=>IhA.find(ahA(e));function n7A(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||GdA(e):!0}const g7A=new Set(["brightness","contrast","saturate","opacity"]);function o7A(e){const[A,t]=e.slice(0,-1).split("(");if(A==="drop-shadow")return e;const[i]=t.match(iZ)||[];if(!i)return e;const n=t.replace(i,"");let g=g7A.has(A)?1:0;return i!==t&&(g*=100),A+"("+g+n+")"}const s7A=/\b([a-z-]*)\(.*?\)/gu,q3={...Ed,getAnimatableNone:e=>{const A=e.match(s7A);return A?A.map(o7A).join(" "):e}},NeA={...Rw,transform:Math.round},r7A={rotate:ZQ,rotateX:ZQ,rotateY:ZQ,rotateZ:ZQ,scale:jb,scaleX:jb,scaleY:jb,scaleZ:jb,skew:ZQ,skewX:ZQ,skewY:ZQ,distance:vi,translateX:vi,translateY:vi,translateZ:vi,x:vi,y:vi,z:vi,perspective:vi,transformPerspective:vi,opacity:pN,originX:QeA,originY:QeA,originZ:vi},cZ={borderWidth:vi,borderTopWidth:vi,borderRightWidth:vi,borderBottomWidth:vi,borderLeftWidth:vi,borderRadius:vi,radius:vi,borderTopLeftRadius:vi,borderTopRightRadius:vi,borderBottomRightRadius:vi,borderBottomLeftRadius:vi,width:vi,maxWidth:vi,height:vi,maxHeight:vi,top:vi,right:vi,bottom:vi,left:vi,padding:vi,paddingTop:vi,paddingRight:vi,paddingBottom:vi,paddingLeft:vi,margin:vi,marginTop:vi,marginRight:vi,marginBottom:vi,marginLeft:vi,backgroundPositionX:vi,backgroundPositionY:vi,...r7A,zIndex:NeA,fillOpacity:pN,strokeOpacity:pN,numOctaves:NeA},a7A={...cZ,color:Cs,backgroundColor:Cs,outlineColor:Cs,fill:Cs,stroke:Cs,borderColor:Cs,borderTopColor:Cs,borderRightColor:Cs,borderBottomColor:Cs,borderLeftColor:Cs,filter:q3,WebkitFilter:q3},ChA=e=>a7A[e];function chA(e,A){let t=ChA(e);return t!==q3&&(t=Ed),t.getAnimatableNone?t.getAnimatableNone(A):void 0}const I7A=new Set(["auto","none","0"]);function C7A(e,A,t){let i=0,n;for(;i<e.length&&!n;){const g=e[i];typeof g=="string"&&!I7A.has(g)&&fN(g).values.length&&(n=e[i]),i++}if(n&&t)for(const g of A)e[g]=chA(t,n)}class c7A extends IZ{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 r=0;r<A.length;r++){let a=A[r];if(typeof a=="string"&&(a=a.trim(),tZ(a))){const I=shA(a,t.current);I!==void 0&&(A[r]=I),r===A.length-1&&(this.finalKeyframe=a)}}if(this.resolveNoneKeyframes(),!rhA.has(i)||A.length!==2)return;const[n,g]=A,o=MeA(n),s=MeA(g);if(o!==s)if(meA(o)&&meA(s))for(let r=0;r<A.length;r++){const a=A[r];typeof a=="string"&&(A[r]=parseFloat(a))}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||n7A(A[n]))&&i.push(n);i.length&&C7A(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(([r,a])=>{A.getValue(r).set(a)}),this.resolveNoneKeyframes()}}function l7A(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 lhA=(e,A)=>A&&typeof e=="number"?A.transform(e):e;function B7A(e){return RdA(e)&&"offsetHeight"in e}const ReA=30,E7A=e=>!isNaN(parseFloat(e));class Q7A{constructor(A,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=i=>{var g;const n=iI.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=iI.now(),this.canTrackVelocity===null&&A!==void 0&&(this.canTrackVelocity=E7A(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 Xz);const i=this.events[A].add(t);return A==="change"?()=>{i(),ao.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=iI.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||A-this.updatedAt>ReA)return 0;const t=Math.min(this.updatedAt-this.prevUpdatedAt,ReA);return bdA(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 KS(e,A){return new Q7A(e,A)}const{schedule:lZ}=YdA(queueMicrotask,!1),Mc={x:!1,y:!1};function BhA(){return Mc.x||Mc.y}function u7A(e){return e==="x"||e==="y"?Mc[e]?null:(Mc[e]=!0,()=>{Mc[e]=!1}):Mc.x||Mc.y?null:(Mc.x=Mc.y=!0,()=>{Mc.x=Mc.y=!1})}function EhA(e,A){const t=l7A(e),i=new AbortController,n={passive:!0,...A,signal:i.signal};return[t,n,()=>i.abort()]}function GeA(e){return!(e.pointerType==="touch"||BhA())}function d7A(e,A,t={}){const[i,n,g]=EhA(e,t),o=s=>{if(!GeA(s))return;const{target:r}=s,a=A(r,s);if(typeof a!="function"||!r)return;const I=c=>{GeA(c)&&(a(c),r.removeEventListener("pointerleave",I))};r.addEventListener("pointerleave",I,n)};return i.forEach(s=>{s.addEventListener("pointerenter",o,n)}),g}const QhA=(e,A)=>A?e===A?!0:QhA(e,A.parentElement):!1,BZ=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,h7A=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function p7A(e){return h7A.has(e.tagName)||e.tabIndex!==-1}const MK=new WeakSet;function beA(e){return A=>{A.key==="Enter"&&e(A)}}function dY(e,A){e.dispatchEvent(new PointerEvent("pointer"+A,{isPrimary:!0,bubbles:!0}))}const f7A=(e,A)=>{const t=e.currentTarget;if(!t)return;const i=beA(()=>{if(MK.has(t))return;dY(t,"down");const n=beA(()=>{dY(t,"up")}),g=()=>dY(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 UeA(e){return BZ(e)&&!BhA()}function y7A(e,A,t={}){const[i,n,g]=EhA(e,t),o=s=>{const r=s.currentTarget;if(!UeA(s))return;MK.add(r);const a=A(r,s),I=(B,Q)=>{window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",l),MK.has(r)&&MK.delete(r),UeA(B)&&typeof a=="function"&&a(B,{success:Q})},c=B=>{I(B,r===window||r===document||t.useGlobalTarget||QhA(r,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),B7A(s)&&(s.addEventListener("focus",a=>f7A(a,n)),!p7A(s)&&!s.hasAttribute("tabindex")&&(s.tabIndex=0))}),g}function uhA(e){return RdA(e)&&"ownerSVGElement"in e}function D7A(e){return uhA(e)&&e.tagName==="svg"}const Pr=e=>!!(e&&e.getVelocity),m7A=[...IhA,Cs,Ed],S7A=e=>m7A.find(ahA(e)),dhA=E.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function w7A(e=!0){const A=E.useContext(jz);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 hhA=E.createContext({strict:!1}),veA={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"]},FS={};for(const e in veA)FS[e]={isEnabled:A=>veA[e].some(t=>!!A[t])};function k7A(e){for(const A in e)FS[A]={...FS[A],...e[A]}}const M7A=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 Q_(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||M7A.has(e)}let phA=e=>!Q_(e);function N7A(e){typeof e=="function"&&(phA=A=>A.startsWith("on")?!Q_(A):e(A))}try{N7A(require("@emotion/is-prop-valid").default)}catch{}function R7A(e,A,t){const i={};for(const n in e)n==="values"&&typeof e.values=="object"||(phA(n)||t===!0&&Q_(n)||!A&&!Q_(n)||e.draggable&&n.startsWith("onDrag"))&&(i[n]=e[n]);return i}const sx=E.createContext({});function rx(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function yN(e){return typeof e=="string"||Array.isArray(e)}const EZ=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],QZ=["initial",...EZ];function ax(e){return rx(e.animate)||QZ.some(A=>yN(e[A]))}function fhA(e){return!!(ax(e)||e.variants)}function G7A(e,A){if(ax(e)){const{initial:t,animate:i}=e;return{initial:t===!1||yN(t)?t:void 0,animate:yN(i)?i:void 0}}return e.inherit!==!1?A:{}}function b7A(e){const{initial:A,animate:t}=G7A(e,E.useContext(sx));return E.useMemo(()=>({initial:A,animate:t}),[KeA(A),KeA(t)])}function KeA(e){return Array.isArray(e)?e.join(" "):e}const DN={};function U7A(e){for(const A in e)DN[A]=e[A],eZ(A)&&(DN[A].isCSSVariable=!0)}function yhA(e,{layout:A,layoutId:t}){return bw.has(e)||e.startsWith("origin")||(A||t!==void 0)&&(!!DN[e]||e==="opacity")}const v7A={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},K7A=Gw.length;function F7A(e,A,t){let i="",n=!0;for(let g=0;g<K7A;g++){const o=Gw[g],s=e[o];if(s===void 0)continue;let r=!0;if(typeof s=="number"?r=s===(o.startsWith("scale")?1:0):r=parseFloat(s)===0,!r||t){const a=lhA(s,cZ[o]);if(!r){n=!1;const I=v7A[o]||o;i+=`${I}(${a}) `}t&&(A[o]=a)}}return i=i.trim(),t?i=t(A,n?"":i):n&&(i="none"),i}function uZ(e,A,t){const{style:i,vars:n,transformOrigin:g}=e;let o=!1,s=!1;for(const r in A){const a=A[r];if(bw.has(r)){o=!0;continue}else if(eZ(r)){n[r]=a;continue}else{const I=lhA(a,cZ[r]);r.startsWith("origin")?(s=!0,g[r]=I):i[r]=I}}if(A.transform||(o||t?i.transform=F7A(A,e.transform,t):i.transform&&(i.transform="none")),s){const{originX:r="50%",originY:a="50%",originZ:I=0}=g;i.transformOrigin=`${r} ${a} ${I}`}}const dZ=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function DhA(e,A,t){for(const i in A)!Pr(A[i])&&!yhA(i,t)&&(e[i]=A[i])}function _7A({transformTemplate:e},A){return E.useMemo(()=>{const t=dZ();return uZ(t,A,e),Object.assign({},t.vars,t.style)},[A])}function J7A(e,A){const t=e.style||{},i={};return DhA(i,t,e),Object.assign(i,_7A(e,A)),i}function L7A(e,A){const t={},i=J7A(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 x7A={offset:"stroke-dashoffset",array:"stroke-dasharray"},T7A={offset:"strokeDashoffset",array:"strokeDasharray"};function q7A(e,A,t=1,i=0,n=!0){e.pathLength=1;const g=n?x7A:T7A;e[g.offset]=vi.transform(-i);const o=vi.transform(A),s=vi.transform(t);e[g.array]=`${o} ${s}`}function mhA(e,{attrX:A,attrY:t,attrScale:i,pathLength:n,pathSpacing:g=1,pathOffset:o=0,...s},r,a,I){if(uZ(e,s,a),r){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&&q7A(c,n,g,o,!1)}const ShA=()=>({...dZ(),attrs:{}}),whA=e=>typeof e=="string"&&e.toLowerCase()==="svg";function Y7A(e,A,t,i){const n=E.useMemo(()=>{const g=ShA();return mhA(g,A,whA(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 H7A=["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 hZ(e){return typeof e!="string"||e.includes("-")?!1:!!(H7A.indexOf(e)>-1||/[A-Z]/u.test(e))}function O7A(e,A,t,{latestValues:i},n,g=!1){const s=(hZ(e)?Y7A:L7A)(A,i,n,e),r=R7A(A,typeof e=="string",g),a=e!==E.Fragment?{...r,...s,ref:t}:{},{children:I}=A,c=E.useMemo(()=>Pr(I)?I.get():I,[I]);return E.createElement(e,{...a,children:c})}function FeA(e){const A=[{},{}];return e==null||e.values.forEach((t,i)=>{A[0][i]=t.get(),A[1][i]=t.getVelocity()}),A}function pZ(e,A,t,i){if(typeof A=="function"){const[n,g]=FeA(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]=FeA(i);A=A(t!==void 0?t:e.custom,n,g)}return A}function NK(e){return Pr(e)?e.get():e}function P7A({scrapeMotionValuesFromProps:e,createRenderState:A},t,i,n){return{latestValues:j7A(t,i,n,e),renderState:A()}}function j7A(e,A,t,i){const n={},g=i(e,{});for(const l in g)n[l]=NK(g[l]);let{initial:o,animate:s}=e;const r=ax(e),a=fhA(e);A&&a&&!r&&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"&&!rx(c)){const l=Array.isArray(c)?c:[c];for(let B=0;B<l.length;B++){const Q=pZ(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 khA=e=>(A,t)=>{const i=E.useContext(sx),n=E.useContext(jz),g=()=>P7A(e,A,i,n);return t?g():kXA(g)};function fZ(e,A,t){var g;const{style:i}=e,n={};for(const o in i)(Pr(i[o])||A.style&&Pr(A.style[o])||yhA(o,e)||((g=t==null?void 0:t.getValue(o))==null?void 0:g.liveStyle)!==void 0)&&(n[o]=i[o]);return n}const z7A=khA({scrapeMotionValuesFromProps:fZ,createRenderState:dZ});function MhA(e,A,t){const i=fZ(e,A,t);for(const n in e)if(Pr(e[n])||Pr(A[n])){const g=Gw.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;i[g]=e[n]}return i}const Z7A=khA({scrapeMotionValuesFromProps:MhA,createRenderState:ShA}),W7A=Symbol.for("motionComponentSymbol");function tm(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function V7A(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 yZ=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),X7A="framerAppearId",NhA="data-"+yZ(X7A),RhA=E.createContext({});function $7A(e,A,t,i,n){var h,d;const{visualElement:g}=E.useContext(sx),o=E.useContext(hhA),s=E.useContext(jz),r=E.useContext(dhA).reducedMotion,a=E.useRef(null);i=i||o.renderer,!a.current&&i&&(a.current=i(e,{visualState:A,parent:g,props:t,presenceContext:s,blockInitialAnimation:s?s.initial===!1:!1,reducedMotionConfig:r}));const I=a.current,c=E.useContext(RhA);I&&!I.projection&&n&&(I.type==="html"||I.type==="svg")&&A$A(a.current,t,n,c);const l=E.useRef(!1);E.useInsertionEffect(()=>{I&&l.current&&I.update(t,s)});const B=t[NhA],Q=E.useRef(!!B&&!((h=window.MotionHandoffIsComplete)!=null&&h.call(window,B))&&((d=window.MotionHasOptimisedAnimation)==null?void 0:d.call(window,B)));return MXA(()=>{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 A$A(e,A,t,i){const{layoutId:n,layout:g,drag:o,dragConstraints:s,layoutScroll:r,layoutRoot:a,layoutCrossfade:I}=A;e.projection=new t(e.latestValues,A["data-framer-portal-id"]?void 0:GhA(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:r,layoutRoot:a})}function GhA(e){if(e)return e.options.allowProjection!==!1?e.projection:GhA(e.parent)}function hY(e,{forwardMotionProps:A=!1}={},t,i){t&&k7A(t);const n=hZ(e)?Z7A:z7A;function g(s,r){let a;const I={...E.useContext(dhA),...s,layoutId:e$A(s)},{isStatic:c}=I,l=b7A(s),B=n(s,c);if(!c&&Pz){t$A();const Q=i$A(I);a=Q.MeasureLayout,l.visualElement=$7A(e,B,I,i,Q.ProjectionNode)}return C.jsxs(sx.Provider,{value:l,children:[a&&l.visualElement?C.jsx(a,{visualElement:l.visualElement,...I}):null,O7A(e,s,V7A(B,l.visualElement,r),B,c,A)]})}g.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const o=E.forwardRef(g);return o[W7A]=e,o}function e$A({layoutId:e}){const A=E.useContext(MdA).id;return A&&e!==void 0?A+"-"+e:e}function t$A(e,A){E.useContext(hhA).strict}function i$A(e){const{drag:A,layout:t}=FS;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 n$A(e,A){if(typeof Proxy>"u")return hY;const t=new Map,i=(g,o)=>hY(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,hY(o,void 0,e,A)),t.get(o))})}function bhA({top:e,left:A,right:t,bottom:i}){return{x:{min:A,max:t},y:{min:e,max:i}}}function g$A({x:e,y:A}){return{top:A.min,right:e.max,bottom:A.max,left:e.min}}function o$A(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 pY(e){return e===void 0||e===1}function Y3({scale:e,scaleX:A,scaleY:t}){return!pY(e)||!pY(A)||!pY(t)}function Wh(e){return Y3(e)||UhA(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function UhA(e){return _eA(e.x)||_eA(e.y)}function _eA(e){return e&&e!=="0%"}function u_(e,A,t){const i=e-t,n=A*i;return t+n}function JeA(e,A,t,i,n){return n!==void 0&&(e=u_(e,n,i)),u_(e,t,i)+A}function H3(e,A=0,t=1,i,n){e.min=JeA(e.min,A,t,i,n),e.max=JeA(e.max,A,t,i,n)}function vhA(e,{x:A,y:t}){H3(e.x,A.translate,A.scale,A.originPoint),H3(e.y,t.translate,t.scale,t.originPoint)}const LeA=.999999999999,xeA=1.0000000000001;function s$A(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:r}=g.options;r&&r.props.style&&r.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,vhA(e,o)),i&&Wh(g.latestValues)&&nm(e,g.latestValues))}A.x<xeA&&A.x>LeA&&(A.x=1),A.y<xeA&&A.y>LeA&&(A.y=1)}function im(e,A){e.min=e.min+A,e.max=e.max+A}function TeA(e,A,t,i,n=.5){const g=Do(e.min,e.max,n);H3(e,A,t,g,i)}function nm(e,A){TeA(e.x,A.x,A.scaleX,A.scale,A.originX),TeA(e.y,A.y,A.scaleY,A.scale,A.originY)}function KhA(e,A){return bhA(o$A(e.getBoundingClientRect(),A))}function r$A(e,A,t){const i=KhA(e,t),{scroll:n}=A;return n&&(im(i.x,n.offset.x),im(i.y,n.offset.y)),i}const qeA=()=>({translate:0,scale:1,origin:0,originPoint:0}),gm=()=>({x:qeA(),y:qeA()}),YeA=()=>({min:0,max:0}),Oo=()=>({x:YeA(),y:YeA()}),d_={current:null},DZ={current:!1};function FhA(){if(DZ.current=!0,!!Pz)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),A=()=>d_.current=e.matches;e.addEventListener("change",A),A()}else d_.current=!1}const a$A=new WeakMap;function I$A(e,A,t){for(const i in A){const n=A[i],g=t[i];if(Pr(n))e.addValue(i,n);else if(Pr(g))e.addValue(i,KS(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,KS(o!==void 0?o:n,{owner:e}))}}for(const i in t)A[i]===void 0&&e.removeValue(i);return A}const HeA=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class C$A{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=IZ,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=iI.now();this.renderScheduledAt<l&&(this.renderScheduledAt=l,ao.render(this.render,!1,!0))};const{latestValues:r,renderState:a}=o;this.latestValues=r,this.baseTarget={...r},this.initialValues=t.initial?{...r}:{},this.renderState=a,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=fhA(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];r[l]!==void 0&&Pr(B)&&B.set(r[l])}}mount(A){var t;this.current=A,a$A.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)),DZ.current||FhA(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:d_.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=bw.has(A);i&&this.onBindTransform&&this.onBindTransform();const n=t.on("change",o=>{this.latestValues[A]=o,this.props.onUpdate&&ao.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 FS){const t=FS[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):Oo()}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<HeA.length;i++){const n=HeA[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=I$A(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=KS(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"&&(NdA(i)||GdA(i))?i=parseFloat(i):!S7A(i)&&Ed.test(t)&&(i=chA(A,t)),this.setBaseTarget(A,Pr(i)?i.get():i)),Pr(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=pZ(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&&!Pr(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 Xz),this.events[A].add(t)}notify(A,...t){this.events[A]&&this.events[A].notify(...t)}scheduleRenderMicrotask(){lZ.render(this.render)}}class _hA extends C$A{constructor(){super(...arguments),this.KeyframeResolver=c7A}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;Pr(A)&&(this.childSubscription=A.on("change",t=>{this.current&&(this.current.textContent=`${t}`)}))}}function JhA(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 c$A(e){return window.getComputedStyle(e)}class l$A extends _hA{constructor(){super(...arguments),this.type="html",this.renderInstance=JhA}readValueFromInstance(A,t){var i;if(bw.has(t))return(i=this.projection)!=null&&i.isProjecting?F3(t):G6A(A,t);{const n=c$A(A),g=(eZ(t)?n.getPropertyValue(t):n[t])||0;return typeof g=="string"?g.trim():g}}measureInstanceViewportBox(A,{transformPagePoint:t}){return KhA(A,t)}build(A,t,i){uZ(A,t,i.transformTemplate)}scrapeMotionValuesFromProps(A,t,i){return fZ(A,t,i)}}const LhA=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 B$A(e,A,t,i){JhA(e,A,void 0,i);for(const n in A.attrs)e.setAttribute(LhA.has(n)?n:yZ(n),A.attrs[n])}class E$A extends _hA{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Oo}getBaseTargetFromProps(A,t){return A[t]}readValueFromInstance(A,t){if(bw.has(t)){const i=ChA(t);return i&&i.default||0}return t=LhA.has(t)?t:yZ(t),A.getAttribute(t)}scrapeMotionValuesFromProps(A,t,i){return MhA(A,t,i)}build(A,t,i){mhA(A,t,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(A,t,i,n){B$A(A,t,i,n)}mount(A){this.isSVGTag=whA(A.tagName),super.mount(A)}}const Q$A=(e,A)=>hZ(e)?new E$A(A):new l$A(A,{allowProjection:e!==E.Fragment});function qm(e,A,t){const i=e.getProps();return pZ(i,A,t!==void 0?t:i.custom,e)}const O3=e=>Array.isArray(e);function u$A(e,A,t){e.hasValue(A)?e.getValue(A).set(t):e.addValue(A,KS(t))}function d$A(e){return O3(e)?e[e.length-1]||0:e}function h$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=d$A(g[o]);u$A(e,o,s)}}function p$A(e){return!!(Pr(e)&&e.add)}function P3(e,A){const t=e.getValue("willChange");if(p$A(t))return t.add(A);if(!t&&tQ.WillChange){const i=new tQ.WillChange("auto");e.addValue("willChange",i),i.add(A)}}function xhA(e){return e.props[NhA]}const f$A=e=>e!==null;function y$A(e,{repeat:A,repeatType:t="loop"},i){const n=e.filter(f$A),g=A&&t!=="loop"&&A%2===1?0:n.length-1;return n[g]}const D$A={type:"spring",stiffness:500,damping:25,restSpeed:10},m$A=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),S$A={type:"keyframes",duration:.8},w$A={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},k$A=(e,{keyframes:A})=>A.length>2?S$A:bw.has(e)?e.startsWith("scale")?m$A(A[1]):D$A:w$A;function M$A({when:e,delay:A,delayChildren:t,staggerChildren:i,staggerDirection:n,repeat:g,repeatType:o,repeatDelay:s,from:r,elapsed:a,...I}){return!!Object.keys(I).length}const mZ=(e,A,t,i={},n,g)=>o=>{const s=CZ(i,e)||{},r=s.delay||i.delay||0;let{elapsed:a=0}=i;a=a-BB(r);const I={keyframes:Array.isArray(t)?t:[null,t],ease:"easeOut",velocity:A.getVelocity(),...s,delay:-a,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};M$A(s)||Object.assign(I,k$A(e,I)),I.duration&&(I.duration=BB(I.duration)),I.repeatDelay&&(I.repeatDelay=BB(I.repeatDelay)),I.from!==void 0&&(I.keyframes[0]=I.from);let c=!1;if((I.type===!1||I.duration===0&&!I.repeatDelay)&&(T3(I),I.delay===0&&(c=!0)),(tQ.instantAnimations||tQ.skipAnimations)&&(c=!0,T3(I),I.delay=0),I.allowFlatten=!s.type&&!s.ease,c&&!g&&A.get()!==void 0){const l=y$A(I.keyframes,s);if(l!==void 0){ao.update(()=>{I.onUpdate(l),I.onComplete()});return}}return s.isSync?new aZ(I):new A7A(I)};function N$A({protectedKeys:e,needsAnimating:A},t){const i=e.hasOwnProperty(t)&&A[t]!==!0;return A[t]=!1,i}function ThA(e,A,{delay:t=0,transitionOverride:i,type:n}={}){let{transition:g=e.getDefaultTransition(),transitionEnd:o,...s}=A;i&&(g=i);const r=[],a=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||a&&N$A(a,I))continue;const B={delay:t,...CZ(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=xhA(e);if(p){const y=window.MotionHandoffAnimation(p,I,ao);y!==null&&(B.startTime=y,h=!0)}}P3(e,I),c.start(mZ(I,c,l,e.shouldReduceMotion&&rhA.has(I)?{type:!1}:B,e,h));const d=c.animation;d&&r.push(d)}return o&&Promise.all(r).then(()=>{ao.update(()=>{o&&h$A(e,o)})}),r}function qhA(e,A,t,i=0,n=1){const g=Array.from(e).sort((a,I)=>a.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 j3(e,A,t={}){var r;const i=qm(e,A,t.type==="exit"?(r=e.presenceContext)==null?void 0:r.custom:void 0);let{transition:n=e.getDefaultTransition()||{}}=i||{};t.transitionOverride&&(n=t.transitionOverride);const g=i?()=>Promise.all(ThA(e,i,t)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(a=0)=>{const{delayChildren:I=0,staggerChildren:c,staggerDirection:l}=n;return R$A(e,A,a,I,c,l,t)}:()=>Promise.resolve(),{when:s}=n;if(s){const[a,I]=s==="beforeChildren"?[g,o]:[o,g];return a().then(()=>I())}else return Promise.all([g(),o(t.delay)])}function R$A(e,A,t=0,i=0,n=0,g=1,o){const s=[];for(const r of e.variantChildren)r.notify("AnimationStart",A),s.push(j3(r,A,{...o,delay:t+(typeof i=="function"?0:i)+qhA(e.variantChildren,r,i,n,g)}).then(()=>r.notify("AnimationComplete",A)));return Promise.all(s)}function G$A(e,A,t={}){e.notify("AnimationStart",A);let i;if(Array.isArray(A)){const n=A.map(g=>j3(e,g,t));i=Promise.all(n)}else if(typeof A=="string")i=j3(e,A,t);else{const n=typeof A=="function"?qm(e,A,t.custom):A;i=Promise.all(ThA(e,n,t))}return i.then(()=>{e.notify("AnimationComplete",A)})}function YhA(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 b$A=QZ.length;function HhA(e){if(!e)return;if(!e.isControllingVariants){const t=e.parent?HhA(e.parent)||{}:{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}const A={};for(let t=0;t<b$A;t++){const i=QZ[t],n=e.props[i];(yN(n)||n===!1)&&(A[i]=n)}return A}const U$A=[...EZ].reverse(),v$A=EZ.length;function K$A(e){return A=>Promise.all(A.map(({animation:t,options:i})=>G$A(e,t,i)))}function F$A(e){let A=K$A(e),t=OeA(),i=!0;const n=r=>(a,I)=>{var l;const c=qm(e,I,r==="exit"?(l=e.presenceContext)==null?void 0:l.custom:void 0);if(c){const{transition:B,transitionEnd:Q,...h}=c;a={...a,...h,...Q}}return a};function g(r){A=r(e)}function o(r){const{props:a}=e,I=HhA(e.parent)||{},c=[],l=new Set;let B={},Q=1/0;for(let d=0;d<v$A;d++){const p=U$A[d],y=t[p],m=a[p]!==void 0?a[p]:I[p],D=yN(m),S=p===r?y.isActive:null;S===!1&&(Q=d);let k=m===I[p]&&m!==a[p]&&D;if(k&&i&&e.manuallyAnimateOnMount&&(k=!1),y.protectedKeys={...B},!y.isActive&&S===null||!m&&!y.prevProp||rx(m)||typeof m=="boolean")continue;const N=_$A(y.prevProp,m);let G=N||p===r&&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],q=_[U];if(B.hasOwnProperty(U))continue;let z=!1;O3(x)&&O3(q)?z=!YhA(x,q):z=x!==q,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 T=k&&N;G&&(!T||M)&&c.push(...w.map(U=>{const x={type:p};if(typeof U=="string"&&i&&!T&&e.manuallyAnimateOnMount&&e.parent){const{parent:q}=e,z=qm(q,U);if(q.enteringChildren&&z){const{delayChildren:Z}=z.transition||{};x.delay=qhA(q.enteringChildren,e,Z)}}return{animation:U,options:x}}))}if(l.size){const d={};if(typeof a.initial!="boolean"){const p=qm(e,Array.isArray(a.initial)?a.initial[0]:a.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&&(a.initial===!1||a.initial===a.animate)&&!e.manuallyAnimateOnMount&&(h=!1),i=!1,h?A(c):Promise.resolve()}function s(r,a){var c;if(t[r].isActive===a)return Promise.resolve();(c=e.variantChildren)==null||c.forEach(l=>{var B;return(B=l.animationState)==null?void 0:B.setActive(r,a)}),t[r].isActive=a;const I=o(r);for(const l in t)t[l].protectedKeys={};return I}return{animateChanges:o,setActive:s,setAnimateFunction:g,getState:()=>t,reset:()=>{t=OeA(),i=!0}}}function _$A(e,A){return typeof A=="string"?A!==e:Array.isArray(A)?!YhA(A,e):!1}function Bh(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function OeA(){return{animate:Bh(!0),whileInView:Bh(),whileHover:Bh(),whileTap:Bh(),whileDrag:Bh(),whileFocus:Bh(),exit:Bh()}}class _d{constructor(A){this.isMounted=!1,this.node=A}update(){}}class J$A extends _d{constructor(A){super(A),A.animationState||(A.animationState=F$A(A))}updateAnimationControlsSubscription(){const{animate:A}=this.node.getProps();rx(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 L$A=0;class x$A extends _d{constructor(){super(...arguments),this.id=L$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 T$A={animation:{Feature:J$A},exit:{Feature:x$A}};function mN(e,A,t,i={passive:!0}){return e.addEventListener(A,t,i),()=>e.removeEventListener(A,t)}function VR(e){return{point:{x:e.pageX,y:e.pageY}}}const q$A=e=>A=>BZ(A)&&e(A,VR(A));function uM(e,A,t,i){return mN(e,A,q$A(t),i)}const OhA=1e-4,Y$A=1-OhA,H$A=1+OhA,PhA=.01,O$A=0-PhA,P$A=0+PhA;function Na(e){return e.max-e.min}function j$A(e,A,t){return Math.abs(e-A)<=t}function PeA(e,A,t,i=.5){e.origin=i,e.originPoint=Do(A.min,A.max,e.origin),e.scale=Na(t)/Na(A),e.translate=Do(t.min,t.max,e.origin)-e.originPoint,(e.scale>=Y$A&&e.scale<=H$A||isNaN(e.scale))&&(e.scale=1),(e.translate>=O$A&&e.translate<=P$A||isNaN(e.translate))&&(e.translate=0)}function dM(e,A,t,i){PeA(e.x,A.x,t.x,i?i.originX:void 0),PeA(e.y,A.y,t.y,i?i.originY:void 0)}function jeA(e,A,t){e.min=t.min+A.min,e.max=e.min+Na(A)}function z$A(e,A,t){jeA(e.x,A.x,t.x),jeA(e.y,A.y,t.y)}function zeA(e,A,t){e.min=A.min-t.min,e.max=e.min+Na(A)}function hM(e,A,t){zeA(e.x,A.x,t.x),zeA(e.y,A.y,t.y)}function SC(e){return[e("x"),e("y")]}const jhA=({current:e})=>e?e.ownerDocument.defaultView:null,ZeA=(e,A)=>Math.abs(e-A);function Z$A(e,A){const t=ZeA(e.x,A.x),i=ZeA(e.y,A.y);return Math.sqrt(t**2+i**2)}class zhA{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=yY(this.lastMoveEventInfo,this.history),B=this.startEvent!==null,Q=Z$A(l.offset,{x:0,y:0})>=this.distanceThreshold;if(!B&&!Q)return;const{point:h}=l,{timestamp:d}=Er;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=fY(B,this.transformPagePoint),ao.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=yY(l.type==="pointercancel"?this.lastMoveEventInfo:fY(B,this.transformPagePoint),this.history);this.startEvent&&Q&&Q(l,p),h&&h(l,p)},!BZ(A))return;this.dragSnapToOrigin=g,this.handlers=t,this.transformPagePoint=i,this.distanceThreshold=o,this.contextWindow=n||window;const s=VR(A),r=fY(s,this.transformPagePoint),{point:a}=r,{timestamp:I}=Er;this.history=[{...a,timestamp:I}];const{onSessionStart:c}=t;c&&c(A,yY(r,this.history)),this.removeListeners=zR(uM(this.contextWindow,"pointermove",this.handlePointerMove),uM(this.contextWindow,"pointerup",this.handlePointerUp),uM(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(A){this.handlers=A}end(){this.removeListeners&&this.removeListeners(),Bd(this.updatePoint)}}function fY(e,A){return A?{point:A(e.point)}:e}function WeA(e,A){return{x:e.x-A.x,y:e.y-A.y}}function yY({point:e},A){return{point:e,delta:WeA(e,ZhA(A)),offset:WeA(e,W$A(A)),velocity:V$A(A,.1)}}function W$A(e){return e[0]}function ZhA(e){return e[e.length-1]}function V$A(e,A){if(e.length<2)return{x:0,y:0};let t=e.length-1,i=null;const n=ZhA(e);for(;t>=0&&(i=e[t],!(n.timestamp-i.timestamp>BB(A)));)t--;if(!i)return{x:0,y:0};const g=EB(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 X$A(e,{min:A,max:t},i){return A!==void 0&&e<A?e=i?Do(A,e,i.min):Math.max(e,A):t!==void 0&&e>t&&(e=i?Do(t,e,i.max):Math.min(e,t)),e}function VeA(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 $$A(e,{top:A,left:t,bottom:i,right:n}){return{x:VeA(e.x,t,n),y:VeA(e.y,A,i)}}function XeA(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 AAe(e,A){return{x:XeA(e.x,A.x),y:XeA(e.y,A.y)}}function eAe(e,A){let t=.5;const i=Na(e),n=Na(A);return n>i?t=hN(A.min,A.max-i,e.min):i>n&&(t=hN(e.min,e.max-n,A.min)),eQ(0,1,t)}function tAe(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 z3=.35;function iAe(e=z3){return e===!1?e=0:e===!0&&(e=z3),{x:$eA(e,"left","right"),y:$eA(e,"top","bottom")}}function $eA(e,A,t){return{min:AtA(e,A),max:AtA(e,t)}}function AtA(e,A){return typeof e=="number"?e:e[A]||0}const nAe=new WeakMap;class gAe{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=Oo(),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(VR(c).point)},o=(c,l)=>{const{drag:B,dragPropagation:Q,onDragStart:h}=this.getProps();if(B&&!Q&&(this.openDragLock&&this.openDragLock(),this.openDragLock=u7A(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),SC(p=>{let y=this.getAxisMotionValue(p).get()||0;if(QB.test(y)){const{projection:m}=this.visualElement;if(m&&m.layout){const D=m.layout.layoutBox[p];D&&(y=Na(D)*(parseFloat(y)/100))}}this.originPoint[p]=y}),h&&ao.postRender(()=>h(c,l)),P3(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=oAe(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)},r=(c,l)=>{this.latestPointerEvent=c,this.latestPanInfo=l,this.stop(c,l),this.latestPointerEvent=null,this.latestPanInfo=null},a=()=>SC(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 zhA(A,{onSessionStart:g,onStart:o,onMove:s,onSessionEnd:r,resumeAnimation:a},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:I,distanceThreshold:i,contextWindow:jhA(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&&ao.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||!zb(A,n,this.currentDirection))return;const g=this.getAxisMotionValue(A);let o=this.originPoint[A]+i[A];this.constraints&&this.constraints[A]&&(o=X$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=$$A(i.layoutBox,A):this.constraints=!1,this.elastic=iAe(t),n!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&SC(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=tAe(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=r$A(i,n.root,this.visualElement.getTransformPagePoint());let o=AAe(n.layout.layoutBox,g);if(t){const s=t(g$A(o));this.hasMutatedConstraints=!!s,s&&(o=bhA(s))}return o}startAnimation(A){const{drag:t,dragMomentum:i,dragElastic:n,dragTransition:g,dragSnapToOrigin:o,onDragTransitionEnd:s}=this.getProps(),r=this.constraints||{},a=SC(I=>{if(!zb(I,t,this.currentDirection))return;let c=r&&r[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(a).then(s)}startAxisValueAnimation(A,t){const i=this.getAxisMotionValue(A);return P3(this.visualElement,A),i.start(mZ(A,i,0,t,this.visualElement,!1))}stopAnimation(){SC(A=>this.getAxisMotionValue(A).stop())}pauseAnimation(){SC(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){SC(t=>{const{drag:i}=this.getProps();if(!zb(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]-Do(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};SC(o=>{const s=this.getAxisMotionValue(o);if(s&&this.constraints!==!1){const r=s.get();n[o]=eAe({min:r,max:r},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(),SC(o=>{if(!zb(o,A,null))return;const s=this.getAxisMotionValue(o),{min:r,max:a}=this.constraints[o];s.set(Do(r,a,n[o]))})}addListeners(){if(!this.visualElement.current)return;nAe.set(this.visualElement,this);const A=this.visualElement.current,t=uM(A,"pointerdown",r=>{const{drag:a,dragListener:I=!0}=this.getProps();a&&I&&this.start(r)}),i=()=>{const{dragConstraints:r}=this.getProps();tm(r)&&r.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,g=n.addEventListener("measure",i);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),ao.read(i);const o=mN(window,"resize",()=>this.scalePositionWithinConstraints()),s=n.addEventListener("didUpdate",({delta:r,hasLayoutChanged:a})=>{this.isDragging&&a&&(SC(I=>{const c=this.getAxisMotionValue(I);c&&(this.originPoint[I]+=r[I].translate,c.set(c.get()+r[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=z3,dragMomentum:s=!0}=A;return{...A,drag:t,dragDirectionLock:i,dragPropagation:n,dragConstraints:g,dragElastic:o,dragMomentum:s}}}function zb(e,A,t){return(A===!0||A===e)&&(t===null||t===e)}function oAe(e,A=10){let t=null;return Math.abs(e.y)>A?t="y":Math.abs(e.x)>A&&(t="x"),t}class sAe extends _d{constructor(A){super(A),this.removeGroupControls=XC,this.removeListeners=XC,this.controls=new gAe(A)}mount(){const{dragControls:A}=this.node.getProps();A&&(this.removeGroupControls=A.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||XC}unmount(){this.removeGroupControls(),this.removeListeners()}}const etA=e=>(A,t)=>{e&&ao.postRender(()=>e(A,t))};class rAe extends _d{constructor(){super(...arguments),this.removePointerDownListener=XC}onPointerDown(A){this.session=new zhA(A,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:jhA(this.node)})}createPanHandlers(){const{onPanSessionStart:A,onPanStart:t,onPan:i,onPanEnd:n}=this.node.getProps();return{onSessionStart:etA(A),onStart:etA(t),onMove:i,onEnd:(g,o)=>{delete this.session,n&&ao.postRender(()=>n(g,o))}}}mount(){this.removePointerDownListener=uM(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 RK={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function ttA(e,A){return A.max===A.min?0:e/(A.max-A.min)*100}const v0={correct:(e,A)=>{if(!A.target)return e;if(typeof e=="string")if(vi.test(e))e=parseFloat(e);else return e;const t=ttA(e,A.target.x),i=ttA(e,A.target.y);return`${t}% ${i}%`}},aAe={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,r=t.y.scale*A.y;n[0+o]/=s,n[1+o]/=r;const a=Do(s,r,.5);return typeof n[2+o]=="number"&&(n[2+o]/=a),typeof n[3+o]=="number"&&(n[3+o]/=a),g(n)}};let DY=!1;class IAe extends E.Component{componentDidMount(){const{visualElement:A,layoutGroup:t,switchLayoutGroup:i,layoutId:n}=this.props,{projection:g}=A;U7A(CAe),g&&(t.group&&t.group.add(g),i&&i.register&&n&&i.register(g),DY&&g.root.didUpdate(),g.addEventListener("animationComplete",()=>{this.safeToRemove()}),g.setOptions({...g.options,onExitComplete:()=>this.safeToRemove()})),RK.hasEverUpdated=!0}getSnapshotBeforeUpdate(A){const{layoutDependency:t,visualElement:i,drag:n,isPresent:g}=this.props,{projection:o}=i;return o&&(o.isPresent=g,DY=!0,n||A.layoutDependency!==t||t===void 0||A.isPresent!==g?o.willUpdate():this.safeToRemove(),A.isPresent!==g&&(g?o.promote():o.relegate()||ao.postRender(()=>{const s=o.getStack();(!s||!s.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:A}=this.props.visualElement;A&&(A.root.didUpdate(),lZ.postRender(()=>{!A.currentAnimation&&A.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:A,layoutGroup:t,switchLayoutGroup:i}=this.props,{projection:n}=A;DY=!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 WhA(e){const[A,t]=w7A(),i=E.useContext(MdA);return C.jsx(IAe,{...e,layoutGroup:i,switchLayoutGroup:E.useContext(RhA),isPresent:A,safeToRemove:t})}const CAe={borderRadius:{...v0,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:v0,borderTopRightRadius:v0,borderBottomLeftRadius:v0,borderBottomRightRadius:v0,boxShadow:aAe};function cAe(e,A,t){const i=Pr(e)?e:KS(e);return i.start(mZ("",i,A,t)),i.animation}const lAe=(e,A)=>e.depth-A.depth;class BAe{constructor(){this.children=[],this.isDirty=!1}add(A){zz(this.children,A),this.isDirty=!0}remove(A){Zz(this.children,A),this.isDirty=!0}forEach(A){this.isDirty&&this.children.sort(lAe),this.isDirty=!1,this.children.forEach(A)}}function EAe(e,A){const t=iI.now(),i=({timestamp:n})=>{const g=n-t;g>=A&&(Bd(i),e(g-A))};return ao.setup(i,!0),()=>Bd(i)}const VhA=["TopLeft","TopRight","BottomLeft","BottomRight"],QAe=VhA.length,itA=e=>typeof e=="string"?parseFloat(e):e,ntA=e=>typeof e=="number"||vi.test(e);function uAe(e,A,t,i,n,g){n?(e.opacity=Do(0,t.opacity??1,dAe(i)),e.opacityExit=Do(A.opacity??1,0,hAe(i))):g&&(e.opacity=Do(A.opacity??1,t.opacity??1,i));for(let o=0;o<QAe;o++){const s=`border${VhA[o]}Radius`;let r=gtA(A,s),a=gtA(t,s);if(r===void 0&&a===void 0)continue;r||(r=0),a||(a=0),r===0||a===0||ntA(r)===ntA(a)?(e[s]=Math.max(Do(itA(r),itA(a),i),0),(QB.test(a)||QB.test(r))&&(e[s]+="%")):e[s]=a}(A.rotate||t.rotate)&&(e.rotate=Do(A.rotate||0,t.rotate||0,i))}function gtA(e,A){return e[A]!==void 0?e[A]:e.borderRadius}const dAe=XhA(0,.5,LdA),hAe=XhA(.5,.95,XC);function XhA(e,A,t){return i=>i<e?0:i>A?1:t(hN(e,A,i))}function otA(e,A){e.min=A.min,e.max=A.max}function pC(e,A){otA(e.x,A.x),otA(e.y,A.y)}function stA(e,A){e.translate=A.translate,e.scale=A.scale,e.originPoint=A.originPoint,e.origin=A.origin}function rtA(e,A,t,i,n){return e-=A,e=u_(e,1/t,i),n!==void 0&&(e=u_(e,1/n,i)),e}function pAe(e,A=0,t=1,i=.5,n,g=e,o=e){if(QB.test(A)&&(A=parseFloat(A),A=Do(o.min,o.max,A/100)-o.min),typeof A!="number")return;let s=Do(g.min,g.max,i);e===g&&(s-=A),e.min=rtA(e.min,A,t,s,n),e.max=rtA(e.max,A,t,s,n)}function atA(e,A,[t,i,n],g,o){pAe(e,A[t],A[i],A[n],A.scale,g,o)}const fAe=["x","scaleX","originX"],yAe=["y","scaleY","originY"];function ItA(e,A,t,i){atA(e.x,A,fAe,t?t.x:void 0,i?i.x:void 0),atA(e.y,A,yAe,t?t.y:void 0,i?i.y:void 0)}function CtA(e){return e.translate===0&&e.scale===1}function $hA(e){return CtA(e.x)&&CtA(e.y)}function ctA(e,A){return e.min===A.min&&e.max===A.max}function DAe(e,A){return ctA(e.x,A.x)&&ctA(e.y,A.y)}function ltA(e,A){return Math.round(e.min)===Math.round(A.min)&&Math.round(e.max)===Math.round(A.max)}function ApA(e,A){return ltA(e.x,A.x)&&ltA(e.y,A.y)}function BtA(e){return Na(e.x)/Na(e.y)}function EtA(e,A){return e.translate===A.translate&&e.scale===A.scale&&e.originPoint===A.originPoint}class mAe{constructor(){this.members=[]}add(A){zz(this.members,A),A.scheduleRender()}remove(A){if(Zz(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 SAe(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:a,rotate:I,rotateX:c,rotateY:l,skewX:B,skewY:Q}=t;a&&(i=`perspective(${a}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,r=e.y.scale*A.y;return(s!==1||r!==1)&&(i+=`scale(${s}, ${r})`),i||"none"}const mY=["","X","Y","Z"],wAe=1e3;let kAe=0;function SY(e,A,t,i){const{latestValues:n}=A;n[e]&&(t[e]=n[e],A.setStaticValue(e,0),i&&(i[e]=0))}function epA(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:A}=e.options;if(!A)return;const t=xhA(A);if(window.MotionHasOptimisedAnimation(t,"transform")){const{layout:n,layoutId:g}=e.options;window.MotionCancelOptimisedAnimation(t,"transform",ao,!(n||g))}const{parent:i}=e;i&&!i.hasCheckedOptimisedAppear&&epA(i)}function tpA({attachResizeListener:e,defaultParent:A,measureScroll:t,checkIsScrollRoot:i,resetTransform:n}){return class{constructor(o={},s=A==null?void 0:A()){this.id=kAe++,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(RAe),this.nodes.forEach(vAe),this.nodes.forEach(KAe),this.nodes.forEach(GAe)},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 r=0;r<this.path.length;r++)this.path[r].shouldResetTransform=!0;this.root===this&&(this.nodes=new BAe)}addEventListener(o,s){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new Xz),this.eventHandlers.get(o).add(s)}notifyListeners(o,...s){const r=this.eventHandlers.get(o);r&&r.notify(...s)}hasListeners(o){return this.eventHandlers.has(o)}mount(o){if(this.instance)return;this.isSVG=uhA(o)&&!D7A(o),this.instance=o;const{layoutId:s,layout:r,visualElement:a}=this.options;if(a&&!a.current&&a.mount(o),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(r||s)&&(this.isLayoutDirty=!0),e){let I,c=0;const l=()=>this.root.updateBlockedByResize=!1;ao.read(()=>{c=window.innerWidth}),e(o,()=>{const B=window.innerWidth;B!==c&&(c=B,this.root.updateBlockedByResize=!0,I&&I(),I=EAe(l,250),RK.hasAnimatedSinceResize&&(RK.hasAnimatedSinceResize=!1,this.nodes.forEach(dtA)))})}s&&this.root.registerSharedNode(s,this),this.options.animate!==!1&&a&&(s||r)&&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||a.getDefaultTransition()||xAe,{onLayoutAnimationStart:h,onLayoutAnimationComplete:d}=a.getProps(),p=!this.targetLayout||!ApA(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={...CZ(Q,"layout"),onPlay:h,onComplete:d};(a.shouldReduceMotion||this.options.layoutRoot)&&(m.delay=0,m.type=!1),this.startAnimation(m),this.setAnimationOrigin(I,y)}else c||dtA(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(FAe),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&&epA(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:r}=this.options;if(s===void 0&&!r)return;const a=this.getTransformTemplate();this.prevTransformTemplateValue=a?a(this.latestValues,""):void 0,this.updateSnapshot(),o&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(QtA);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(utA);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(UAe),this.nodes.forEach(MAe),this.nodes.forEach(NAe)):this.nodes.forEach(utA),this.clearAllSnapshots();const s=iI.now();Er.delta=eQ(0,1e3/60,s-Er.timestamp),Er.timestamp=s,Er.isProcessing=!0,lY.update.process(Er),lY.preRender.process(Er),lY.render.process(Er),Er.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,lZ.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(bAe),this.sharedNodes.forEach(_Ae)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ao.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ao.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Na(this.snapshot.measuredBox.x)&&!Na(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 r=0;r<this.path.length;r++)this.path[r].updateScroll();const o=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Oo(),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 r=i(this.instance);this.scroll={animationId:this.root.animationId,phase:o,isRoot:r,offset:t(this.instance),wasRoot:this.scroll?this.scroll.isRoot:r}}}resetTransform(){if(!n)return;const o=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,s=this.projectionDelta&&!$hA(this.projectionDelta),r=this.getTransformTemplate(),a=r?r(this.latestValues,""):void 0,I=a!==this.prevTransformTemplateValue;o&&this.instance&&(s||Wh(this.latestValues)||I)&&(n(this.instance,a),this.shouldResetTransform=!1,this.scheduleRender())}measure(o=!0){const s=this.measurePageBox();let r=this.removeElementScroll(s);return o&&(r=this.removeTransform(r)),TAe(r),{animationId:this.root.animationId,measuredBox:s,layoutBox:r,latestValues:{},source:this.id}}measurePageBox(){var a;const{visualElement:o}=this.options;if(!o)return Oo();const s=o.measureViewportBox();if(!(((a=this.scroll)==null?void 0:a.wasRoot)||this.path.some(qAe))){const{scroll:I}=this.root;I&&(im(s.x,I.offset.x),im(s.y,I.offset.y))}return s}removeElementScroll(o){var r;const s=Oo();if(pC(s,o),(r=this.scroll)!=null&&r.wasRoot)return s;for(let a=0;a<this.path.length;a++){const I=this.path[a],{scroll:c,options:l}=I;I!==this.root&&c&&l.layoutScroll&&(c.wasRoot&&pC(s,o),im(s.x,c.offset.x),im(s.y,c.offset.y))}return s}applyTransform(o,s=!1){const r=Oo();pC(r,o);for(let a=0;a<this.path.length;a++){const I=this.path[a];!s&&I.options.layoutScroll&&I.scroll&&I!==I.root&&nm(r,{x:-I.scroll.offset.x,y:-I.scroll.offset.y}),Wh(I.latestValues)&&nm(r,I.latestValues)}return Wh(this.latestValues)&&nm(r,this.latestValues),r}removeTransform(o){const s=Oo();pC(s,o);for(let r=0;r<this.path.length;r++){const a=this.path[r];if(!a.instance||!Wh(a.latestValues))continue;Y3(a.latestValues)&&a.updateSnapshot();const I=Oo(),c=a.measurePageBox();pC(I,c),ItA(s,a.latestValues,a.snapshot?a.snapshot.layoutBox:void 0,I)}return Wh(this.latestValues)&&ItA(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!==Er.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 r=!!this.resumingFrom||this!==s;if(!(o||r&&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=Er.timestamp,!this.targetDelta&&!this.relativeTarget){const B=this.getClosestProjectingParent();B&&B.layout&&this.animationProgress!==1?(this.relativeParent=B,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Oo(),this.relativeTargetOrigin=Oo(),hM(this.relativeTargetOrigin,this.layout.layoutBox,B.layout.layoutBox),pC(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Oo(),this.targetWithTransforms=Oo()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),z$A(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):pC(this.target,this.layout.layoutBox),vhA(this.target,this.targetDelta)):pC(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=Oo(),this.relativeTargetOrigin=Oo(),hM(this.relativeTargetOrigin,this.target,B.target),pC(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Y3(this.parent.latestValues)||UhA(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 r=!0;if((this.isProjectionDirty||(Q=this.parent)!=null&&Q.isProjectionDirty)&&(r=!1),s&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(r=!1),this.resolvedRelativeTargetAt===Er.timestamp&&(r=!1),r)return;const{layout:a,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||!(a||I))return;pC(this.layoutCorrected,this.layout.layoutBox);const c=this.treeScale.x,l=this.treeScale.y;s$A(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=Oo());const{target:B}=o;if(!B){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(stA(this.prevProjectionDelta.x,this.projectionDelta.x),stA(this.prevProjectionDelta.y,this.projectionDelta.y)),dM(this.projectionDelta,this.layoutCorrected,B,this.latestValues),(this.treeScale.x!==c||this.treeScale.y!==l||!EtA(this.projectionDelta.x,this.prevProjectionDelta.x)||!EtA(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 r=this.getStack();r&&r.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 r=this.snapshot,a=r?r.latestValues:{},I={...this.latestValues},c=gm();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!s;const l=Oo(),B=r?r.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(LAe));this.animationProgress=0;let m;this.mixTargetDelta=D=>{const S=D/1e3;htA(c.x,o.x,S),htA(c.y,o.y,S),this.setTargetDelta(c),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(hM(l,this.layout.layoutBox,this.relativeParent.layout.layoutBox),JAe(this.relativeTarget,this.relativeTargetOrigin,l,S),m&&DAe(this.relativeTarget,m)&&(this.isProjectionDirty=!1),m||(m=Oo()),pC(m,this.relativeTarget)),h&&(this.animationValues=I,uAe(I,a,this.latestValues,S,y,p)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){var s,r,a;this.notifyListeners("animationStart"),(s=this.currentAnimation)==null||s.stop(),(a=(r=this.resumingFrom)==null?void 0:r.currentAnimation)==null||a.stop(),this.pendingAnimation&&(Bd(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ao.update(()=>{RK.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=KS(0)),this.currentAnimation=cAe(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(wAe),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:s,target:r,layout:a,latestValues:I}=o;if(!(!s||!r||!a)){if(this!==o&&this.layout&&a&&ipA(this.options.animationType,this.layout.layoutBox,a.layoutBox)){r=this.target||Oo();const c=Na(this.layout.layoutBox.x);r.x.min=o.target.x.min,r.x.max=r.x.min+c;const l=Na(this.layout.layoutBox.y);r.y.min=o.target.y.min,r.y.max=r.y.min+l}pC(s,r),nm(s,I),dM(this.projectionDeltaWithTransform,this.layoutCorrected,s,I)}}registerSharedNode(o,s){this.sharedNodes.has(o)||this.sharedNodes.set(o,new mAe),this.sharedNodes.get(o).add(s);const a=s.options.initialPromotionConfig;s.promote({transition:a?a.transition:void 0,preserveFollowOpacity:a&&a.shouldPreserveFollowOpacity?a.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:r}={}){const a=this.getStack();a&&a.promote(this,r),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:r}=o;if((r.z||r.rotate||r.rotateX||r.rotateY||r.rotateZ||r.skewX||r.skewY)&&(s=!0),!s)return;const a={};r.z&&SY("z",o,a,this.animationValues);for(let I=0;I<mY.length;I++)SY(`rotate${mY[I]}`,o,a,this.animationValues),SY(`skew${mY[I]}`,o,a,this.animationValues);o.render();for(const I in a)o.setStaticValue(I,a[I]),this.animationValues&&(this.animationValues[I]=a[I]);o.scheduleRender()}applyProjectionStyles(o,s){if(!this.instance||this.isSVG)return;if(!this.isVisible){o.visibility="hidden";return}const r=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,o.visibility="",o.opacity="",o.pointerEvents=NK(s==null?void 0:s.pointerEvents)||"",o.transform=r?r(this.latestValues,""):"none";return}const a=this.getLead();if(!this.projectionDelta||!this.layout||!a.target){this.options.layoutId&&(o.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,o.pointerEvents=NK(s==null?void 0:s.pointerEvents)||""),this.hasProjected&&!Wh(this.latestValues)&&(o.transform=r?r({},""):"none",this.hasProjected=!1);return}o.visibility="";const I=a.animationValues||a.latestValues;this.applyTransformsToTarget();let c=SAe(this.projectionDeltaWithTransform,this.treeScale,I);r&&(c=r(I,c)),o.transform=c;const{x:l,y:B}=this.projectionDelta;o.transformOrigin=`${l.origin*100}% ${B.origin*100}% 0`,a.animationValues?o.opacity=a===this?I.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:I.opacityExit:o.opacity=a===this?I.opacity!==void 0?I.opacity:"":I.opacityExit!==void 0?I.opacityExit:0;for(const Q in DN){if(I[Q]===void 0)continue;const{correct:h,applyTo:d,isCSSVariable:p}=DN[Q],y=c==="none"?I[Q]:h(I[Q],a);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=a===this?NK(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(QtA),this.root.sharedNodes.clear()}}}function MAe(e){e.updateLayout()}function NAe(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"?SC(c=>{const l=o?A.measuredBox[c]:A.layoutBox[c],B=Na(l);l.min=i[c].min,l.max=l.min+B}):ipA(g,A.layoutBox,i)&&SC(c=>{const l=o?A.measuredBox[c]:A.layoutBox[c],B=Na(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();dM(s,i,A.layoutBox);const r=gm();o?dM(r,e.applyTransform(n,!0),A.measuredBox):dM(r,i,A.layoutBox);const a=!$hA(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=Oo();hM(Q,A.layoutBox,l.layoutBox);const h=Oo();hM(h,i,B.layoutBox),ApA(Q,h)||(I=!0),c.options.layoutRoot&&(e.relativeTarget=h,e.relativeTargetOrigin=Q,e.relativeParent=c)}}}e.notifyListeners("didUpdate",{layout:i,snapshot:A,delta:r,layoutDelta:s,hasLayoutChanged:a,hasRelativeLayoutChanged:I})}else if(e.isLead()){const{onExitComplete:i}=e.options;i&&i()}e.options.transition=void 0}function RAe(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 GAe(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function bAe(e){e.clearSnapshot()}function QtA(e){e.clearMeasurements()}function utA(e){e.isLayoutDirty=!1}function UAe(e){const{visualElement:A}=e.options;A&&A.getProps().onBeforeLayoutMeasure&&A.notify("BeforeLayoutMeasure"),e.resetTransform()}function dtA(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function vAe(e){e.resolveTargetDelta()}function KAe(e){e.calcProjection()}function FAe(e){e.resetSkewAndRotation()}function _Ae(e){e.removeLeadSnapshot()}function htA(e,A,t){e.translate=Do(A.translate,0,t),e.scale=Do(A.scale,1,t),e.origin=A.origin,e.originPoint=A.originPoint}function ptA(e,A,t,i){e.min=Do(A.min,t.min,i),e.max=Do(A.max,t.max,i)}function JAe(e,A,t,i){ptA(e.x,A.x,t.x,i),ptA(e.y,A.y,t.y,i)}function LAe(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const xAe={duration:.45,ease:[.4,0,.1,1]},ftA=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),ytA=ftA("applewebkit/")&&!ftA("chrome/")?Math.round:XC;function DtA(e){e.min=ytA(e.min),e.max=ytA(e.max)}function TAe(e){DtA(e.x),DtA(e.y)}function ipA(e,A,t){return e==="position"||e==="preserve-aspect"&&!j$A(BtA(A),BtA(t),.2)}function qAe(e){var A;return e!==e.root&&((A=e.scroll)==null?void 0:A.wasRoot)}const YAe=tpA({attachResizeListener:(e,A)=>mN(e,"resize",A),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),wY={current:void 0},npA=tpA({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!wY.current){const e=new YAe({});e.mount(window),e.setOptions({layoutScroll:!0}),wY.current=e}return wY.current},resetTransform:(e,A)=>{e.style.transform=A!==void 0?A:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),HAe={pan:{Feature:rAe},drag:{Feature:sAe,ProjectionNode:npA,MeasureLayout:WhA}};function mtA(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&&ao.postRender(()=>g(A,VR(A)))}class OAe extends _d{mount(){const{current:A}=this.node;A&&(this.unmount=d7A(A,(t,i)=>(mtA(this.node,i,"Start"),n=>mtA(this.node,n,"End"))))}unmount(){}}class PAe extends _d{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=zR(mN(this.node.current,"focus",()=>this.onFocus()),mN(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function StA(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&&ao.postRender(()=>g(A,VR(A)))}class jAe extends _d{mount(){const{current:A}=this.node;A&&(this.unmount=y7A(A,(t,i)=>(StA(this.node,i,"Start"),(n,{success:g})=>StA(this.node,n,g?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Z3=new WeakMap,kY=new WeakMap,zAe=e=>{const A=Z3.get(e.target);A&&A(e)},ZAe=e=>{e.forEach(zAe)};function WAe({root:e,...A}){const t=e||document;kY.has(t)||kY.set(t,{});const i=kY.get(t),n=JSON.stringify(A);return i[n]||(i[n]=new IntersectionObserver(ZAe,{root:e,...A})),i[n]}function VAe(e,A,t){const i=WAe(A);return Z3.set(e,t),i.observe(e),()=>{Z3.delete(e),i.unobserve(e)}}const XAe={some:0,all:1};class $Ae extends _d{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:XAe[n]},s=r=>{const{isIntersecting:a}=r;if(this.isInView===a||(this.isInView=a,g&&!a&&this.hasEnteredView))return;a&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",a);const{onViewportEnter:I,onViewportLeave:c}=this.node.getProps(),l=a?I:c;l&&l(r)};return VAe(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(Aee(A,t))&&this.startObserver()}unmount(){}}function Aee({viewport:e={}},{viewport:A={}}={}){return t=>e[t]!==A[t]}const eee={inView:{Feature:$Ae},tap:{Feature:jAe},focus:{Feature:PAe},hover:{Feature:OAe}},tee={layout:{ProjectionNode:npA,MeasureLayout:WhA}},iee={...T$A,...eee,...HAe,...tee},WI=n$A(iee,Q$A);function nee(){!DZ.current&&FhA();const[e]=E.useState(d_.current);return e}const gee="_panelRoot_cg615_1",oee="_crapsPlaceTile_cg615_43",see="_mobileShow_cg615_64",ree="_mobileHide_cg615_68",aee="_spotBtn_cg615_95",Iee="_spotRow_cg615_108",Cee="_actions_cg615_120",cee="_actionBtn_cg615_124",lee="_amountBadge_cg615_130",Bee="_badgeMinus_cg615_137",Eee="_crapsStatusBar_cg615_148",Qee="_crapsStatusText_cg615_154",uee="_crapsHighlight_cg615_162",dee="_crapsPlaceRow_cg615_179",hee="_crapsBetTile_cg615_190",pee="_crapsActionsBar_cg615_198",fee="_crapsActionButton_cg615_202",yee="_crapsActionButtonPrimary_cg615_207",Dee="_crapsActionButtonSecondary_cg615_208",mee="_crapsMainBets_cg615_214",See="_disabled_cg615_334",wee="_spotBtnTopRow_cg615_520",kee="_lineWin_cg615_571",Mee="_lineLose_cg615_576",Nee="_linePush_cg615_581",Ree="_outcomeBadge_cg615_586",Gee="_locked_cg615_600",bee="_amountBadgeDisabled_cg615_628",Uee="_lockIcon_cg615_634",vee="_aggBadge_cg615_674",Kee="_rollBtn_cg615_890",Fee="_rollIcon_cg615_897",_ee="_clear_cg615_923",Jee="_errorLive_cg615_940",Lee="_tooltip_cg615_948",xee="_betInfoBtn_cg615_972",Tee="_betInfoModalOverlay_cg615_1000",qee="_betInfoModal_cg615_1000",Yee="_betInfoHeader_cg615_1034",Hee="_betInfoClose_cg615_1050",Oee="_betInfoContent_cg615_1071",Pee="_betInfoItem_cg615_1079",jee="_shake_cg615_1165",zee="_attnHalo_cg615_1213",Zee="_crapsAtsLabel_cg615_1335",Wee="_crapsIronCrossBtn_cg615_1355",Vee="_crapsMinusBadge_cg615_1470",Xee="_rollHaloActive_cg615_1657",$ee="_crapsClearIcon_cg615_1770",Ate="_particle_cg615_1804",ete="_particleContainer_cg615_1810",tte="_floatingWinAmount_cg615_1860",ite="_countdownBadge_cg615_1975",nte="_countdownUrgent_cg615_1998",gte="_countdownCritical_cg615_2005",ote="_chipPickerWrapper_cg615_2329",ste="_chipPickerToggle_cg615_2334",rte="_chipPickerToggleOpen_cg615_2377",ate="_chipPickerChip_cg615_2387",Ite="_chipPickerDropdown_cg615_2391",Cte="_chipPickerOption_cg615_2413",cte="_chipPickerOptionSelected_cg615_2422",lte="_chipPickerChipSelected_cg615_2426",Bte="_crapsAtsSection_cg615_2446",yt={panelRoot:gee,crapsPlaceTile:oee,mobileShow:see,mobileHide:ree,spotBtn:aee,spotRow:Iee,actions:Cee,actionBtn:cee,amountBadge:lee,badgeMinus:Bee,crapsStatusBar:Eee,crapsStatusText:Qee,crapsHighlight:uee,crapsPlaceRow:dee,crapsBetTile:hee,crapsActionsBar:pee,crapsActionButton:fee,crapsActionButtonPrimary:yee,crapsActionButtonSecondary:Dee,crapsMainBets:mee,disabled:See,spotBtnTopRow:wee,lineWin:kee,lineLose:Mee,linePush:Nee,outcomeBadge:Ree,locked:Gee,amountBadgeDisabled:bee,lockIcon:Uee,aggBadge:vee,rollBtn:Kee,rollIcon:Fee,clear:_ee,errorLive:Jee,tooltip:Lee,betInfoBtn:xee,betInfoModalOverlay:Tee,betInfoModal:qee,betInfoHeader:Yee,betInfoClose:Hee,betInfoContent:Oee,betInfoItem:Pee,shake:jee,attnHalo:zee,crapsAtsLabel:Zee,crapsIronCrossBtn:Wee,crapsMinusBadge:Vee,rollHaloActive:Xee,crapsClearIcon:$ee,particle:Ate,particleContainer:ete,floatingWinAmount:tte,countdownBadge:ite,countdownUrgent:nte,countdownCritical:gte,chipPickerWrapper:ote,chipPickerToggle:ste,chipPickerToggleOpen:rte,chipPickerChip:ate,chipPickerDropdown:Ite,chipPickerOption:Cte,chipPickerOptionSelected:cte,chipPickerChipSelected:lte,crapsAtsSection:Bte},Ete={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 Qte({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:yt.betInfoModalOverlay,role:"presentation",children:C.jsxs("div",{className:yt.betInfoModal,role:"dialog","aria-modal":"true","aria-label":"Craps Bet Guide",ref:t,children:[C.jsxs("div",{className:yt.betInfoHeader,children:[C.jsx("h3",{children:"Craps Bet Guide"}),C.jsx("button",{className:yt.betInfoClose,onClick:A,"aria-label":"Close",children:"✕"})]}),C.jsx("div",{className:yt.betInfoContent,children:Object.entries(Ete).map(([n,{title:g,description:o}])=>C.jsxs("div",{className:yt.betInfoItem,children:[C.jsx("strong",{children:g}),C.jsx("p",{children:o})]},n))})]})});return zr.createPortal(i,document.body)}const ute="_atsProgressContainer_bok0p_3",dte="_inline_bok0p_15",hte="_atsSection_bok0p_25",pte="_complete_bok0p_42",fte="_justCompleted_bok0p_47",yte="_atsSectionAll_bok0p_66",Dte="_atsSectionHeader_bok0p_75",mte="_atsSectionLabel_bok0p_84",Ste="_atsSectionCount_bok0p_97",wte="_atsNumberRow_bok0p_107",kte="_atsNumber_bok0p_107",Mte="_hit_bok0p_138",Nte="_atsCompleteText_bok0p_160",Rte="_atsLockedBadge_bok0p_181",dg={atsProgressContainer:ute,inline:dte,atsSection:hte,complete:pte,justCompleted:fte,atsSectionAll:yte,atsSectionHeader:Dte,atsSectionLabel:mte,atsSectionCount:Ste,atsNumberRow:wte,atsNumber:kte,hit:Mte,atsCompleteText:Nte,atsLockedBadge:Rte},Gte=[2,3,4,5,6],bte=[8,9,10,11,12];function Ute({hitNumbers:e,smallProgress:A,tallProgress:t,allProgress:i,betsLocked:n,lastCompletedCategory:g,inline:o=!1}){const s=c=>e.includes(c),r=A===5,a=t===5,I=i===10;return C.jsxs("div",{className:`${dg.atsProgressContainer} ${o?dg.inline:""}`,children:[C.jsxs("div",{className:`${dg.atsSection} ${r?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:Gte.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} ${a?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:bte.map(c=>C.jsx("div",{className:`${dg.atsNumber} ${s(c)?dg.hit:""}`,"aria-label":`${c} ${s(c)?"hit":"not hit"}`,children:c},c))})]})]})}const bl={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"},MY={hitNumbers:[],smallProgress:0,tallProgress:0,allProgress:0,betsLocked:!1};function vte(e){const A=Ss(),[t,i]=E.useState(MY),[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})},r=l=>{l.roomId===e&&g("small")},a=l=>{l.roomId===e&&g("tall")},I=l=>{l.roomId===e&&g("all")},c=l=>{l.roomId===e&&(i(MY),g(null))};return A.on(bl.PROGRESS,s),A.on(bl.SMALL_COMPLETE,r),A.on(bl.TALL_COMPLETE,a),A.on(bl.ALL_COMPLETE,I),A.on(bl.RESET,c),()=>{A.off(bl.PROGRESS,s),A.off(bl.SMALL_COMPLETE,r),A.off(bl.TALL_COMPLETE,a),A.off(bl.ALL_COMPLETE,I),A.off(bl.RESET,c)}},[A,e]);const o=E.useCallback(s=>t.hitNumbers.includes(s),[t.hitNumbers]);return{atsProgress:t,lastCompletedCategory:n,isNumberHit:o,reset:()=>i(MY)}}const om=e=>`z${e.toLocaleString(void 0,{maximumFractionDigits:0})}`;function Zc({value:e,onAdd:A,onClear:t,disabled:i,selectedTimes:n=0,style:g,mini:o=!1,className:s,hideValue:r=!1}){const a=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":"",a?"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:[!r&&C.jsx("span",{className:"chip__value",children:e>=1e3?`${(Number(e)/1e3).toLocaleString(void 0,{maximumFractionDigits:e>=1e4?0:1})}k`:e}),a&&l&&C.jsxs("span",{className:"chip__count",children:["×",n]})]}),a&&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 ur(e){return`z${e}`}function FC(e,A){return e.filter(t=>t.type===A).reduce((t,i)=>t+i.amount,0)}function Kte(e,A){return e*A}function wtA(e,A,t){const{phase:i,point:n,balance:g,pendingBets:o,minBet:s,maxBet:r,oddsMultiple:a,committedAddBack:I=0}=t,c=o.reduce((D,S)=>D+S.amount,0),l=FC(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 ${ur(s)}`}}if(d){if(!n)return{ok:!1,reason:"Come bets only after point"};if(l===0&&A<s)return{ok:!1,reason:`Minimum ${ur(s)}`};if(l+A>r)return{ok:!1,reason:`Max ${ur(r)}`}}if(p){if(!n)return{ok:!1,reason:"Point required for odds"};const S=FC(o,e==="oddsPass"?"pass":"dontPass");if(!S)return{ok:!1,reason:"Need line bet first"};const k=Kte(S,e==="oddsPass"?a.pass:a.dontPass);if(l+A>k)return{ok:!1,reason:`Max odds ${ur(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 ${ur(s)}`};if(l+A>r)return{ok:!1,reason:`Max ${ur(r)}`}}if(e==="field"||e==="big6"||e==="big8"){if(l===0&&A<s)return{ok:!1,reason:`Minimum ${ur(s)}`};if(l+A>r)return{ok:!1,reason:`Max ${ur(r)}`}}if(e==="atsSmall"||e==="atsTall"||e==="atsAll"){if(l===0&&A<s)return{ok:!1,reason:`Minimum ${ur(s)}`};if(l+A>r)return{ok:!1,reason:`Max ${ur(r)}`}}return{ok:!0}}const Fte=[{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"}],_te=[{key:"atsSmall",label:"Small"},{key:"atsTall",label:"Tall"},{key:"atsAll",label:"All"}],Jte=[{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 Lte(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 xte(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 Tte(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(`.${yt.crapsPlaceRow}`),g=n?n.querySelector(`.${yt.crapsIronCrossBtn}`):document.querySelector(`.${yt.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 qte(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(`.${yt.crapsPlaceRow}`),n=i?i.querySelector(`.${yt.crapsAtsLabel}`):document.querySelector(`.${yt.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 Yte(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(`.${yt.crapsMainBets}`),o=t.current||document.querySelector(`.${yt.crapsPlaceRow}`),s=(r,a)=>{if(!r)return;const I=r.scrollWidth,c=r.clientWidth;I<=c||window.setTimeout(()=>{r.scrollTo({left:I,behavior:"smooth"}),window.setTimeout(()=>{r.scrollTo({left:0,behavior:"smooth"})},600)},a)};s(g,0),s(o,150)},500);return()=>window.clearTimeout(n)},[e,A,t])}function Hte(e){const{phase:A,point:t,balance:i,pendingBets:n,minBet:g,maxBet:o,oddsMultiple:s,myPlayerLineTotals:r,myPlayerPlaceTotal:a}=e;return E.useMemo(()=>{const I=((r==null?void 0:r.pass)??0)+((r==null?void 0:r.dontPass)??0)+(a??0),c=FC(n,"pass")+FC(n,"dontPass")+FC(n,"place4")+FC(n,"place5")+FC(n,"place6")+FC(n,"place8")+FC(n,"place9")+FC(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,r==null?void 0:r.pass,r==null?void 0:r.dontPass,a])}function Ote(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 Pte(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 r of e){const a=`${r.type}:${r.amount}`;i.current.has(a)||i.current.set(a,g)}const o=new Set(e.map(r=>`${r.type}:${r.amount}`));for(const r of i.current.keys())o.has(r)||i.current.delete(r);const s=e.filter(r=>{const a=Number(A[r.type]||0);if(r.amount===0&&a>0)return!0;if(r.amount===a)return!1;const I=`${r.type}:${r.amount}`,c=i.current.get(I)||g;return g-c>n?(console.warn("[CrapsBettingPanel] Pruning stuck pending bet (timeout)",{type:r.type,amount:r.amount,committed:a}),!1):!0});s.length!==e.length&&t(s)},[e,A,t])}function jte(e){const{recentSettlements:A,meId:t,myPlayerLineTotals:i}=e,n=E.useMemo(()=>{if(!A.length||!t)return{};const a=A.filter(c=>(c.betType==="pass"||c.betType==="dontPass")&&c.playerId===t),I={};for(const c of a)(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 a=A.filter(c=>c.betType.startsWith("place")&&c.playerId===t),I={};for(const c of a)I[c.betType]=c.outcome;return I},[A,t]),o=E.useMemo(()=>{if(!A.length||!t)return{};const a=A.filter(c=>c.betType==="field"&&c.playerId===t),I={};for(const c of a)I[c.betType]=c.outcome;return I},[A,t]),s=E.useMemo(()=>{if(!A.length||!t)return{};const a=A.filter(c=>(c.betType==="big6"||c.betType==="big8")&&c.playerId===t),I={};for(const c of a)I[c.betType]=c.outcome;return I},[A,t]),r=E.useMemo(()=>{if(!A.length||!t)return{};const a=A.filter(c=>(c.betType==="come"||c.betType==="dontCome")&&c.playerId===t),I={};for(const c of a)I[c.betType]=c.outcome;return I},[A,t]);return{lineOutcomeMap:n,placeOutcomeMap:g,fieldOutcomeMap:o,bigOutcomeMap:s,comeOutcomeMap:r}}function zte(e,A){E.useEffect(()=>{const t=document.querySelectorAll(e),i=[];return t.forEach(n=>{if(n.querySelector(`.${yt.particleContainer}`))return;const g=document.createElement("div");g.className=yt.particleContainer,n.appendChild(g);const o=()=>{const r=document.createElement("div");r.className=yt.particle;const a=Math.random()*100,I=(Math.random()-.5)*40,c=-(80+Math.random()*60),l=1.8+Math.random()*1,B=Math.random()*.3;r.style.setProperty("--start-x",`${a}%`),r.style.setProperty("--drift-x",`${I}px`),r.style.setProperty("--rise-y",`${c}px`),r.style.setProperty("--duration",`${l}s`),r.style.setProperty("--delay",`${B}s`),r.style.left="0",r.style.bottom="0",g.appendChild(r),window.setTimeout(()=>r.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(`.${yt.particleContainer}`))==null?void 0:g.remove()})}},[e,A])}function Zte(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 r=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(!r.length)return;const a=window.setTimeout(()=>{const I={};r.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=`+${ur(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(a)},[A,t,i,n])}function gpA(e){const{roomId:A,balance:t,phase:i,point:n,shooterName:g,minBet:o,maxBet:s,oddsMultiple:r,chips:a,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:T,onChargeChange:v}=e,U=B,{selectedChip:x,setSelectedChip:q}=Lte(a),{atsProgress:z,lastCompletedCategory:Z}=vte(A??null),[eA,aA]=E.useState(!1),[sA,pA]=E.useState(),[gA,yA]=E.useState(),{info:fA}=LL(),RA=E.useRef(!1),YA=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),CA=E.useRef(null),cA=E.useRef(z.betsLocked),_A=xte({pendingBets:I,myPlayerPlaceTotal:d,myCommittedByType:K}),uA=i==="point"&&!!n&&!_A;Tte(uA,n,oA),qte(Z,oA),Yte(A,iA,oA),E.useEffect(()=>{const Ge=cA.current,st=z.betsLocked;cA.current=st,Ge!==st&&(st&&CA.current?CA.current.scrollTo({left:CA.current.scrollWidth,behavior:"smooth"}):!st&&CA.current&&CA.current.scrollTo({left:0,behavior:"smooth"}))},[z.betsLocked]);const X=E.useCallback(()=>{RA.current||(RA.current=!0,qn(),W.current=0,v==null||v(0),YA.current&&clearInterval(YA.current),YA.current=setInterval(()=>{W.current=Math.min(1,W.current+L),v==null||v(W.current),W.current>=.95?Xt("Heavy"):W.current>=.6?Xt("Medium"):W.current>=.25&&Xt("Light")},$))},[v]),O=E.useCallback(()=>{if(RA.current){if(RA.current=!1,YA.current&&(clearInterval(YA.current),YA.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]),lA=Hte({phase:i,point:n,balance:t,pendingBets:I,minBet:o,maxBet:s,oddsMultiple:r,myPlayerLineTotals:b,myPlayerPlaceTotal:d}),wA=Ote(I,K);Pte(I,K,c);const xA=E.useMemo(()=>{const Ge=FC(I,"pass")>0||FC(I,"dontPass")>0,st=((b==null?void 0:b.pass)??0)>0||((b==null?void 0:b.dontPass)??0)>0,Rt=wA("pass")>0||wA("dontPass")>0;return Ge||st||Rt},[I,b==null?void 0:b.pass,b==null?void 0:b.dontPass,wA]),{lineOutcomeMap:HA,placeOutcomeMap:zA,fieldOutcomeMap:ne,bigOutcomeMap:ye,comeOutcomeMap:Ee}=jte({recentSettlements:w,meId:y,myPlayerLineTotals:b}),NA=E.useMemo(()=>`.${yt.spotBtn}[data-win-outcome="true"]`,[]),QA=E.useMemo(()=>JSON.stringify({lineOutcomeMap:HA,placeOutcomeMap:zA,fieldOutcomeMap:ne,bigOutcomeMap:ye,comeOutcomeMap:Ee}),[HA,zA,ne,ye,Ee]);zte(NA,QA),Zte({recentSettlements:w,meId:y,winSelector:NA,floatingClass:yt.floatingWinAmount});const PA=E.useMemo(()=>{const Ge=new Set;for(const st of I){const Rt=Number(K[st.type]||0);st.amount!==Rt&&Ge.add(st.type)}return Ge},[I,K]),VA=E.useRef(new Set);E.useEffect(()=>{const Ge=VA.current,st=PA;for(const Rt of Ge)if(!st.has(Rt)){try{MvA({volume:.03})}catch{}break}VA.current=new Set(st)},[PA]),PA.size>0,E.useMemo(()=>PA.size>0,[PA]);const KA=E.useCallback((Ge,st)=>{if(st===0)return;const Rt=I.find(vt=>vt.type===Ge);if(st>0){const vt=st,{ok:xt,reason:ee}=wtA(Ge,vt,lA);if(!xt){if(pA(ee),yA(Ge),ee==="Insufficient balance")try{fA("Insufficient funds","Add chips to place this bet")}catch{}window.setTimeout(()=>yA(void 0),600);return}if(Rt)c(I.map(Oe=>Oe===Rt?{...Oe,amount:Oe.amount+vt}:Oe));else{const Oe=Number(K[Ge]||0);c([...I,{id:cY(),type:Ge,amount:Oe+vt}])}m==null||m(Ge,vt);return}let Et=(Rt==null?void 0:Rt.amount)??0;if(!Rt){const vt=Number(K[Ge]||0);if(vt<=0)return;Et=vt}const _t=Et+st;c(Rt?I.map(vt=>vt===Rt?{...vt,amount:Math.max(0,_t)}:vt):[...I,{id:cY(),type:Ge,amount:Math.max(0,_t)}]),m==null||m(Ge,st)},[I,c,o,K,lA,m,fA]),Ie=E.useCallback((Ge,st)=>{const Rt=Ge==="oddsPass",Et=Ge==="oddsDontPass",_t=Ge==="atsSmall"||Ge==="atsTall"||Ge==="atsAll",vt=Ge==="pass"||Ge==="dontPass"?P:Rt?i!=="point"||!n||wA("pass")===0:Et?i!=="point"||!n||wA("dontPass")===0:Ge.startsWith("place")||Ge==="come"||Ge==="dontCome"?!n:_t?i!=="comeOut"||z.betsLocked:!1,xt=Ge==="pass"||Ge==="dontPass",ee=Ge==="come"||Ge==="dontCome",Oe=!Ge.startsWith("place"),We=xt&&P,pt=xt?HA[Ge]:Ge==="field"?ne[Ge]:Ge==="big6"||Ge==="big8"?ye[Ge]:ee?Ee[Ge]:void 0,kA=pt==="WIN"?yt.lineWin:pt==="LOSE"?yt.lineLose:pt==="PUSH"?yt.linePush:"",oe=xt&&H&&!xA,ae=[yt.spotBtn,yt.crapsBetTile,Ge.startsWith("place")?yt.crapsPlaceTile:"",vt?yt.locked:"",gA===Ge?yt.shake:"",kA,oe?yt.attnHalo:"",Ge.startsWith("place")&&uA?yt.attnHalo:""],$A=B||tA,nA=_&&typeof _[Ge]=="number"?_[Ge]:0,vA=wA(Ge);if(Oe){const bA=[...ae,yt.spotBtnTopRow,"gold-link",$A?yt.disabled:""].filter(Boolean).join(" ");return C.jsxs(WI.a,{role:"button",tabIndex:0,"aria-disabled":$A||void 0,className:bA,"data-bet-type":Ge,"data-attn":oe?"need-line":void 0,"data-has-bet":vA>0?"true":"false","data-win-outcome":pt==="WIN"?"true":"false","data-no-global-haptic":!0,"aria-label":`Place bet on ${st}, +${x}`,onClick:De=>{De.preventDefault(),!vt&&!$A&&(qn(),Xt("Light"),KA(Ge,x))},onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&!vt&&!$A&&(De.preventDefault(),qn(),Xt("Light"),KA(Ge,x))},whileTap:{scale:.94},children:[st,nA>0&&C.jsx("div",{className:yt.aggBadge,"aria-label":`Others ${st} total ${ur(nA)}`,children:ur(nA)}),vA>0&&C.jsxs("div",{className:yt.amountBadge+(We?" "+yt.amountBadgeDisabled:""),"aria-disabled":We||void 0,children:[!We&&C.jsx("span",{role:"button",tabIndex:0,className:[yt.badgeMinus,yt.crapsMinusBadge].join(" "),"aria-label":`Remove chip from ${st}`,onClick:De=>{De.stopPropagation(),qn(),Xt("Light"),KA(Ge,-x)},onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.preventDefault(),De.stopPropagation(),qn(),Xt("Light"),KA(Ge,-x))},children:"−"}),ur(vA),We&&C.jsx("span",{className:yt.lockIcon,"aria-hidden":"true",children:"🔒"}),pt&&C.jsx("span",{className:yt.outcomeBadge,"aria-label":`Outcome ${pt}`,children:pt==="WIN"?"✓":pt==="LOSE"?"✕":"⟳"})]}),gA===Ge&&sA&&C.jsx("div",{className:yt.tooltip,children:sA})]},Ge)}const FA=Ge.startsWith("place")?zA[Ge]:Ge==="field"?ne[Ge]:Ge==="big6"||Ge==="big8"?ye[Ge]:void 0,te=ae.filter(Boolean).join(" ");return C.jsxs(WI.button,{type:"button",className:te,"data-bet-type":Ge,"data-attn":Ge.startsWith("place")&&uA?"need-places":void 0,"data-has-bet":vA>0?"true":"false","data-win-outcome":pt==="WIN"||FA==="WIN"?"true":"false","aria-label":`Place bet on ${st}, +${x}`,onClick:()=>{!vt&&!$A&&(qn(),Xt("Light"),KA(Ge,x))},disabled:B||tA,whileTap:{scale:.94},children:[st,nA>0&&C.jsx("div",{className:yt.aggBadge,"aria-label":`Others ${st} total ${ur(nA)}`,children:ur(nA)}),vA>0&&C.jsxs("div",{className:yt.amountBadge+(We?" "+yt.amountBadgeDisabled:""),"aria-disabled":We||void 0,children:[!We&&C.jsx("span",{role:"button",tabIndex:0,className:[yt.badgeMinus,yt.crapsMinusBadge].join(" "),"aria-label":`Remove chip from ${st}`,onClick:bA=>{bA.stopPropagation(),qn(),Xt("Light"),KA(Ge,-x)},onKeyDown:bA=>{(bA.key==="Enter"||bA.key===" ")&&(bA.preventDefault(),bA.stopPropagation(),qn(),Xt("Light"),KA(Ge,-x))},children:"−"}),ur(vA),We&&C.jsx("span",{className:yt.lockIcon,"aria-hidden":"true",children:"🔒"}),pt&&C.jsx("span",{className:yt.outcomeBadge,"aria-label":`Outcome ${pt}`,children:pt==="WIN"?"✓":pt==="LOSE"?"✕":"⟳"})]}),gA===Ge&&sA&&C.jsx("div",{className:yt.tooltip,children:sA})]},Ge)},[KA,B,tA,wA,sA,gA,H,xA,uA,x,P,i,n,HA,zA,ne,ye,Ee,_,z.betsLocked]),DA=E.useMemo(()=>{const Ge=[...Fte],st=(Rt,Et,_t)=>{const vt=Ge.findIndex(xt=>xt.key===Rt);vt>=0&&!Ge.some(xt=>xt.key===Et)&&Ge.splice(vt+1,0,{key:Et,label:_t})};return st("pass","oddsPass","Odds Pass"),st("dontPass","oddsDontPass","Odds Don't"),Ge},[]),IA=E.useMemo(()=>DA.map(Ge=>Ie(Ge.key,Ge.label)),[DA,Ie]),EA=E.useMemo(()=>Jte.map(Ge=>Ie(Ge.key,Ge.label)),[Ie]),j=E.useMemo(()=>_te.map(Ge=>Ie(Ge.key,Ge.label)),[Ie]),dA=E.useCallback(()=>{if(B||tA)return;qn(),Xt("Light");const Ge=["place4","place5","place6","place8","place9","place10"],st=[];for(const Et of Ge){I.find(ee=>ee.type===Et);const _t=x,{ok:vt,reason:xt}=wtA(Et,_t,lA);if(!vt){if(pA(xt),yA(Et),xt==="Insufficient balance")try{fA("Insufficient funds","Add chips to place All Places bet")}catch{}window.setTimeout(()=>yA(void 0),600);return}st.push({type:Et,delta:_t})}let Rt=[...I];for(const{type:Et,delta:_t}of st){const vt=Rt.find(xt=>xt.type===Et);if(vt)Rt=Rt.map(xt=>xt===vt?{...xt,amount:xt.amount+_t}:xt);else{const xt=Number(K[Et]||0);Rt.push({id:cY(),type:Et,amount:xt+_t})}}c(Rt),D?D(st.map(({type:Et,delta:_t})=>({type:Et,amount:_t}))):m&&st.forEach(({type:Et,delta:_t})=>m(Et,_t))},[B,tA,I,x,o,lA,c,K,D,m,fA]),hA=!!S,UA=hA?N||"Ready":"Roll",TA=hA?!!G:U||h===!1,se=!hA&&!TA&&h!==!1&&(i!=="point"||_A),[Ne,Ke]=E.useState(!1),At=E.useRef(null);E.useEffect(()=>{if(!Ne)return;const Ge=st=>{At.current&&!At.current.contains(st.target)&&Ke(!1)};return document.addEventListener("mousedown",Ge),()=>document.removeEventListener("mousedown",Ge)},[Ne]);const ni=g;return C.jsxs("div",{className:[yt.panelRoot,B?yt.disabled:""].join(" "),children:[C.jsxs("div",{className:yt.crapsStatusBar,children:[C.jsxs("div",{className:yt.chipPickerWrapper,ref:At,children:[C.jsx("div",{className:[yt.chipPickerToggle,Ne?yt.chipPickerToggleOpen:""].join(" "),onClick:()=>{qn(),Xt("Light"),Ke(Ge=>!Ge)},role:"button",tabIndex:0,"aria-label":`Selected chip ${x}, click to change`,"aria-expanded":Ne,onKeyDown:Ge=>{(Ge.key==="Enter"||Ge.key===" ")&&(Ge.preventDefault(),qn(),Xt("Light"),Ke(st=>!st))},children:C.jsx(Zc,{value:x,mini:!0,className:yt.chipPickerChip,onAdd:()=>{qn(),Xt("Light"),Ke(Ge=>!Ge)}})}),Ne&&C.jsx("div",{className:yt.chipPickerDropdown,children:a.map(Ge=>C.jsx("div",{className:[yt.chipPickerOption,Ge===x?yt.chipPickerOptionSelected:""].join(" "),children:C.jsx(Zc,{value:Ge,mini:!0,className:Ge===x?yt.chipPickerChipSelected:"",onAdd:()=>{qn(),$BA(),q(Ge),Ke(!1)}})},Ge))})]}),C.jsxs("span",{className:yt.crapsStatusText,children:[C.jsx("span",{className:yt.mobileHide,children:i==="comeOut"?"COME-OUT":"POINT"}),C.jsx("span",{className:yt.mobileShow,children:i==="comeOut"?"CO":"PT"})," • ",C.jsx("span",{className:yt.mobileHide,children:"SHOOTER: "}),C.jsx("strong",{className:yt.crapsHighlight,children:ni})," • ",C.jsx("span",{className:yt.mobileHide,children:"POINT: "}),C.jsx("span",{className:yt.mobileShow,children:"P: "}),C.jsx("strong",{className:yt.crapsHighlight,children:n??"—"})]}),C.jsx("button",{type:"button",className:yt.betInfoBtn,onClick:()=>{Xt("Light"),aA(!0)},"aria-label":"Show bet information",children:C.jsx(Cd,{icon:C8A})})]}),C.jsx(Qte,{open:eA,onClose:()=>aA(!1)}),C.jsx("div",{className:[yt.spotRow,yt.crapsMainBets].join(" "),ref:iA,children:IA}),C.jsxs("div",{className:yt.crapsPlaceRow,ref:oA,children:[EA,C.jsx("button",{type:"button",className:[yt.spotBtn,yt.crapsBetTile,yt.crapsIronCrossBtn].join(" "),onClick:dA,disabled:!n||B||tA,"aria-label":"Place All Places (4/5/6/8/9/10)",children:"All Places"})]}),C.jsxs("div",{className:yt.crapsAtsSection,ref:CA,children:[C.jsx("span",{className:yt.crapsAtsLabel,children:"ATS"}),j,C.jsx(Ute,{hitNumbers:z.hitNumbers,smallProgress:z.smallProgress,tallProgress:z.tallProgress,allProgress:z.allProgress,betsLocked:z.betsLocked,lastCompletedCategory:Z,inline:!0})]}),C.jsx("div",{className:yt.crapsActionsBar,children:C.jsxs("div",{className:yt.actions,children:[C.jsxs("button",{type:"button",className:[yt.actionBtn,yt.rollBtn,yt.crapsActionButton,yt.crapsActionButtonPrimary,se?yt.rollHaloActive:""].join(" "),onClick:Ge=>{if(hA){if(G)return;try{qn(),Xt("Light")}catch{}k==null||k();return}if(RA.current){Ge.preventDefault();return}if(!TA){v==null||v(1),qn(),Xt("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:()=>{hA||TA||(X(),Xt("Medium"))},onPointerUp:()=>{hA||O()},onPointerCancel:()=>{O()},onPointerLeave:()=>{O()},disabled:TA,"aria-label":hA?"Mark ready":"Roll dice",children:[!hA&&C.jsx(Cd,{icon:r8A,className:yt.rollIcon,"aria-hidden":"true"}),UA,hA&&M>0&&C.jsx("span",{className:[yt.countdownBadge,M<=5?yt.countdownCritical:M<=10?yt.countdownUrgent:""].join(" "),"aria-label":`${M} seconds remaining`,children:M})]}),!S&&T&&J&&C.jsx("button",{type:"button",className:[yt.actionBtn,yt.crapsActionButton,yt.crapsActionButtonSecondary].join(" "),onClick:()=>{console.log("[CrapsBettingPanel] Pass button clicked");try{qn(),Xt("Light")}catch{}J()},"aria-label":"Pass dice to next shooter",children:"Pass"}),C.jsxs("button",{type:"button",className:[yt.actionBtn,yt.clear,yt.crapsActionButton,yt.crapsActionButtonSecondary].join(" "),onClick:()=>{qn(),Xt("Light"),l()},"aria-label":"Clear all bets",children:[C.jsx("span",{className:yt.crapsClearIcon,"aria-hidden":"true",children:"✕"})," Clear"]})]})}),C.jsx("div",{className:yt.errorLive,"aria-live":"polite",children:sA||""})]})}function Wte(e,A){const{crapsGetState:t,crapsJoinOrder:i,crapsLeaveOrder:n,crapsSetOrder:g,crapsRoll:o,crapsResetShooter:s,crapsReady:r,crapsPassTurn:a}=So(),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?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,passTurn: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}}let K0={},Vte=1;function opA(e){var $;const{roomId:A,myPlayerId:t,autoJoinOrder:i=!0,onRoll:n,onState:g}=e,{crapsReady:o}=So(),s=(()=>{try{return tI&&tI()}catch{return null}})(),r=(s==null?void 0:s.room)??null,a=(s==null?void 0:s.setRoom)??(()=>{}),c=(($=r==null?void 0:r.gameState)==null?void 0:$.gameMode)==="craps",l=Wte(A,{enabled:c}),B=E.useMemo(()=>{const L=r==null?void 0:r.gameState;return!L||L.gameMode!=="craps"?null:{point:L.crapsPoint??null,currentRollerId:L.currentRollerId??null,turnOrder:L.turnOrder??[]}},[r==null?void 0:r.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),T=E.useRef(null),{triggerSpin:v}=MB(),U=E.useRef(null),x=E.useRef(null),q=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),q.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 CA=/invalid_payload/i.test(oA),cA=/no_room/i.test(oA),_A=/forbidden|unauthorized/i.test(oA);if(CA||cA||_A){console.warn("[craps][roll_emit][ack_reject]",{err:oA}),x.current&&(window.clearTimeout(x.current),x.current=null),m(!1),q.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),q.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),q.current=null;try{aA()}catch{}L==null||L(!1)}):(D.current=!1,m(!1),q.current=null,L==null||L(!1))}catch{try{console.warn("[craps][roll_emit][exception]")}catch{}D.current=!1,m(!1),q.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]),YA=E.useRef(0);YA.current===0&&(YA.current=Vte++);const W=E.useMemo(()=>A?K0[A]?K0[A]===YA.current:(K0[A]=YA.current,!0):!1,[A]);return E.useEffect(()=>()=>{try{A&&K0[A]===YA.current&&delete K0[A]}catch{}},[A]),xs({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,CA,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)??((CA=L.state)==null?void 0:CA.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{a(O=>{if(!O||O.id!==A)return O;const lA=O.gameState||{},wA=tA?"point":"come-out";return{...O,gameState:{...lA,gameMode:lA.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{}a(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 CA={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}};q.current||(q.current=Date.now(),h(null),v());try{D.current=!1,m(!0),U.current&&(window.clearTimeout(U.current),U.current=null);const cA=q.current?Date.now()-q.current:0,_A=Math.max(z-cA,0)+Z;U.current=window.setTimeout(()=>{m(!1),q.current=null,U.current=null},_A),x.current&&(window.clearTimeout(x.current),x.current=null)}catch{}h(CA),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]===CA.dice[0]&&xA.dice[1]===CA.dice[1]&&_A-xA.ts<X)return cA}const lA=[{...CA,ts:_A,phase:CA.point?"point":"come-out"},...cA];lA.length>uA&&(lA.length=uA);try{if(A){const wA={v:1,roomId:A,ts:_A,items:lA};dL(`craps-roll-history:${A}`,wA)}}catch{}return lA});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)&&a(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(CA)},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=(CA,cA)=>{if(!CA&&!cA)return!0;if(!CA||!cA||CA.length!==cA.length)return!1;for(let _A=0;_A<CA.length;_A++)if(CA[_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"]);a(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=r==null?void 0:r.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{}},[r==null?void 0:r.gameState]),E.useEffect(()=>{if(!c||!A||!W)return;let L=0;const H=500,P=()=>{try{const CA=Date.now();if(CA-L<H)return;L=CA,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 hS(`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),T.current&&(window.clearTimeout(T.current),T.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=!!(r&&r.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{T.current&&(window.clearTimeout(T.current),T.current=null),T.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{T.current&&(window.clearTimeout(T.current),T.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 CA=await o(A);L==null||L(!!(CA!=null&&CA.ok),CA==null?void 0:CA.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&&pS(`craps-roll-history:${A}`)}catch{}}}}function Xte(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,r=(i==null?void 0:i.currentRollerId)||null;if(!!!(t&&(s?s===t:r===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 NY=new Map,RY={pass:[],dontPass:[],odds:[],place:[],field:[],big:[],come:[],dontCome:[],ats:[],lastUpdated:0};function spA(e){const{roomId:A,myPlayerId:t,autoListOnMount:i=!0,autoClearSettlementsMs:n=8e3}=e;Ss();const{room:g,setRoom:o}=tI(),[s,r]=E.useState(RY),a=E.useRef(RY),[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:T,crapsSummarizeBets:v}=So(),U=E.useCallback(H=>{if(!A)return;const P=NY.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 NY.set(A,tA),tA.finally(()=>{NY.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||r(tA=>{const iA={...tA,lastUpdated:Date.now()};if(H==="pass")tA.pass.find(CA=>CA.playerId===t)?iA.pass=tA.pass.map(CA=>CA.playerId===t?{...CA,amount:CA.amount+P}:CA):iA.pass=[...tA.pass,{playerId:t,amount:P}];else if(H==="dontPass")tA.dontPass.find(CA=>CA.playerId===t)?iA.dontPass=tA.dontPass.map(CA=>CA.playerId===t?{...CA,amount:CA.amount+P}:CA):iA.dontPass=[...tA.dontPass,{playerId:t,amount:P}];else if(H.startsWith("place")){const oA=H.match(/^place(\d+)$/);if(oA){const CA=Number(oA[1]);tA.place.find(_A=>_A.playerId===t&&_A.point===CA)?iA.place=tA.place.map(_A=>_A.playerId===t&&_A.point===CA?{..._A,amount:_A.amount+P}:_A):iA.place=[...tA.place,{playerId:t,point:CA,amount:P}]}}return a.current=iA,iA})},[t]),q=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||r(tA=>{const iA={...tA,lastUpdated:Date.now()};if(H==="pass"){const oA=[...iA.pass||[]],CA=oA.findIndex(cA=>cA.playerId===t);CA!==-1&&(oA[CA]={...oA[CA],amount:Math.max(0,oA[CA].amount-P)},oA[CA].amount===0&&oA.splice(CA,1)),iA.pass=oA}else if(H==="dontPass"){const oA=[...iA.dontPass||[]],CA=oA.findIndex(cA=>cA.playerId===t);CA!==-1&&(oA[CA]={...oA[CA],amount:Math.max(0,oA[CA].amount-P)},oA[CA].amount===0&&oA.splice(CA,1)),iA.dontPass=oA}else if(H.startsWith("place")){const oA=H.replace("place",""),CA=parseInt(oA,10);if(!isNaN(CA)){const cA=[...iA.place||[]],_A=cA.findIndex(uA=>uA.playerId===t&&uA.point===CA);_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 a.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=T(A);return H&&P.then(tA=>H(tA)).catch(tA=>H({ok:!1,error:String((tA==null?void 0:tA.message)||tA)})),P},[T,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 hS(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;r(CA=>{if(CA.lastUpdated!==0||CA.place.length+CA.pass.length+CA.dontPass.length>0)return CA;const cA={...CA};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(),a.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 hS(sA);if(!tA)return;const iA=Number(tA.pass||0),oA=Number(tA.dontPass||0),CA=Array.isArray(tA.place)?tA.place:[],cA=Date.now();try{await U()}catch{}const _A=Date.now()+1200;for(;(a.current.lastUpdated||0)<=cA&&Date.now()<_A;)await new Promise(HA=>setTimeout(HA,120));if((a.current.lastUpdated||0)<=cA)return;const uA=a.current,X=((H=(uA.pass||[]).find(HA=>HA.playerId===t))==null?void 0:H.amount)||0,O=((P=(uA.dontPass||[]).find(HA=>HA.playerId===t))==null?void 0:P.amount)||0,lA={};for(const HA of uA.place||[])HA.playerId===t&&(lA[HA.point]=(lA[HA.point]||0)+HA.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 HA of CA){const zA=Number(HA.point),ne=Number(HA.amount||0),ye=Number(lA[zA]||0),Ee=Math.max(0,ne-ye);if(Ee>0)try{const NA=`place${zA}`;await K(A,NA,Ee)}catch{}}}catch{}},[sA,t,A,U,s,K]),fA=E.useCallback(H=>{!H||typeof H!="object"||r(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 a.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(CA=>{if(!CA||CA.id!==A)return CA;const cA={...CA.gameState||{}};return cA.lastCrapsSettlementsTs=Date.now(),cA.lastCrapsSettlements=P,{...CA,gameState:cA}})}catch{}const oA=new Map;for(const CA of P)CA.outcome==="WIN"&&CA.playerId&&oA.set(CA.playerId,(oA.get(CA.playerId)||0)+1);for(const[CA,cA]of oA){const _A=b.current.get(CA)||0,uA=_A+cA;if(b.current.set(CA,uA),_A>=6&&uA>_A)Z6(7,.55);else for(const X of[3,4,5,6])if(_A<X&&uA>=X){Z6(X,.55);break}if(CA===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]);xs({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){r(oA=>{if(!oA.place.length)return oA;const CA={...oA,place:[],lastUpdated:Date.now()};return a.current=CA,CA});try{o(oA=>{if(!oA||oA.id!==A)return oA;const CA={...oA.gameState||{}};return CA.crapsPlaceBets=[],{...oA,gameState:CA}})}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 CA of Object.keys(P))tA.has(CA)||(oA[CA]=P[CA]);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,CA=((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:CA,place:cA};oA||CA||cA.length?await dL(sA,_A):await pS(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){r(RY),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 YA=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:YA,dontPassTotal:W,fieldTotal:$,myLine:L,listBets:U,addBet:q,removeBet:Z,clearBets:eA,summarize:aA,clearRecentSettlements:()=>c([]),pointSetEvent:Q,pointMadeEvent:d,readyPlayers:y,requiredReadyPlayers:D,readinessDeadline:k}}function $te(){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 ZB(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 F0(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 ktA(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 Aie(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 eie(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 tie({balance:e,meId:A,readyPlayers:t,onChargeChange:i,onRollAffordanceChange:n}){var ye,Ee,NA;const{user:g,meId:o}=en(),{room:s,setRoom:r}=tI(),a=(s==null?void 0:s.id)??null,I=E.useMemo(()=>$te(),[]),c=E.useMemo(()=>{if(o)return o;const QA=g;return(QA==null?void 0:QA.id)??(QA==null?void 0:QA.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}=opA({roomId:a,myPlayerId:l}),S=spA({roomId:a,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||[],T=G.dontCome||[],v=G.odds||[],U=G.ats||[],x=E.useMemo(()=>Aie(b,l),[b,l]),q=E.useMemo(()=>{let QA=0;for(const PA of[4,5,6,8,9,10])QA+=x[PA]||0;return QA},[x]),z=E.useMemo(()=>{var se,Ne;const QA={};if(!l)return QA;const PA=((se=S.myLine)==null?void 0:se.pass)??ZB(M,l),VA=((Ne=S.myLine)==null?void 0:Ne.dontPass)??ZB(w,l);PA>0&&(QA.pass=PA),VA>0&&(QA.dontPass=VA);for(const Ke of[4,5,6,8,9,10]){const At=x[Ke]||0;At>0&&(QA[`place${Ke}`]=At)}const KA=ZB(_,l);KA>0&&(QA.field=KA);const Ie=Eh(K,l,Ke=>Ke.kind==="big6");Ie>0&&(QA.big6=Ie);const DA=Eh(K,l,Ke=>Ke.kind==="big8");DA>0&&(QA.big8=DA);const IA=ZB(J,l);IA>0&&(QA.come=IA);const EA=ZB(T,l);EA>0&&(QA.dontCome=EA);const j=Eh(v,l,Ke=>Ke.passType==="pass");j>0&&(QA.oddsPass=j);const dA=Eh(v,l,Ke=>Ke.passType==="dontPass");dA>0&&(QA.oddsDontPass=dA);const hA=Eh(U,l,Ke=>Ke.kind==="atsSmall");hA>0&&(QA.atsSmall=hA);const UA=Eh(U,l,Ke=>Ke.kind==="atsTall");UA>0&&(QA.atsTall=UA);const TA=Eh(U,l,Ke=>Ke.kind==="atsAll");return TA>0&&(QA.atsAll=TA),QA},[l,(ye=S.myLine)==null?void 0:ye.pass,(Ee=S.myLine)==null?void 0:Ee.dontPass,M,w,x,_,K,J,T,v,U]),Z=E.useMemo(()=>{const QA=l;return QA?{pass:F0(M,QA),dontPass:F0(w,QA),field:F0(_,QA),big6:ktA(K,QA,PA=>PA.kind==="big6"),big8:ktA(K,QA,PA=>PA.kind==="big8"),come:F0(J,QA),dontCome:F0(T,QA),place4:Zy(b,QA,4),place5:Zy(b,QA,5),place6:Zy(b,QA,6),place8:Zy(b,QA,8),place9:Zy(b,QA,9),place10:Zy(b,QA,10)}:{}},[l,M,w,_,K,J,T,b]),eA=E.useCallback(QA=>Q(QA),[]),aA=E.useRef(0),sA=E.useCallback(()=>{if(!a||!l||!B.length)return;const QA=Date.now();if(!(QA-aA.current<1e3)){aA.current=QA;try{const PA=ZB(M,l),VA=ZB(w,l),KA=x;for(const Ie of B){const DA=Ie.type;let IA=0;if(DA==="pass")IA=PA;else if(DA==="dontPass")IA=VA;else if(DA.startsWith("place")){const dA=parseInt(DA.replace("place",""),10);IA=KA[dA]||0}else continue;const EA=Math.max(0,Number(Ie.amount)||0),j=Math.max(0,EA-IA);if(j>0)try{N.addBet(DA,j)}catch{}}}catch{}}},[a,l,B,M,w,x,N]);xs({onJoinedRoom:({room:QA})=>{(QA==null?void 0:QA.id)===a&&sA()},onRejoinedRoom:({room:QA})=>{(QA==null?void 0:QA.id)===a&&sA()}}),E.useEffect(()=>{if(!l)return;const QA=B.filter(PA=>{if(PA.type==="pass")return!(ZB(M,l)>=PA.amount);if(PA.type==="dontPass")return!(ZB(w,l)>=PA.amount);if(PA.type.startsWith("place")){const VA=parseInt(PA.type.replace("place",""),10);return!((x[VA]||0)>=PA.amount)}return!0});QA.length!==B.length&&Q(QA)},[l,M,w,x,B]),E.useEffect(()=>{if(!a||!l||!r||!I)return;const QA=s==null?void 0:s.gameState,PA=QA==null?void 0:QA.currentRollerId;if(!PA||PA!==l)return;const VA=QA==null?void 0:QA.crapsPassBets,KA=QA==null?void 0:QA.crapsDontPassBets;if(!(VA!=null&&VA.some(DA=>DA.playerId===l&&DA.amount>0)||KA!=null&&KA.some(DA=>DA.playerId===l&&DA.amount>0)))try{r(DA=>{if(!DA||DA.id!==a)return DA;const IA=DA.gameState||{},EA=Array.isArray(IA.crapsPassBets)?IA.crapsPassBets.slice():[];return EA.push({playerId:l,amount:10}),{...DA,gameState:{...IA,crapsPassBets:EA,gameMode:IA.gameMode||"craps"}}})}catch{}},[a,s==null?void 0:s.gameState,l,r,I]);const pA=E.useCallback((QA,PA)=>{a&&(PA>0?N.addBet(QA,PA):PA<0&&N.removeBet(QA,Math.abs(PA)))},[a,N]),gA=E.useMemo(()=>{const QA=s==null?void 0:s.gameState;if((QA==null?void 0:QA.gameMode)==="craps"){const PA=QA.crapsPhase||(h!=null&&h.point?"point":"comeOut");return{point:QA.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}=MB(),{displayPoint:fA,displayPhase:RA}=eie(gA,yA);E.useEffect(()=>{if(gA.point==null&&yA){const QA=B.filter(PA=>!PA.type.startsWith("place"));QA.length!==B.length&&Q(QA)}},[gA.point,yA,B]);const YA=s==null?void 0:s.gameState,W=S.readinessDeadline??null,$=S.requiredReadyPlayers??[],L=Xte({roomId:a,userId:c,shooterState:h,roomGameState:YA,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:YA,readyPlayers:k,requiredReadyPlayers:$,readinessDeadline:W}}catch{}},[H,g,p,h,YA,k,$,W,I]);const P=!a,tA=E.useMemo(()=>{var PA;const QA=(PA=s==null?void 0:s.gameState)==null?void 0:PA.currentRollerId;return l?QA===l:!1},[s==null?void 0:s.gameState,l]),iA=E.useMemo(()=>{const QA=tA&&gA.phase==="comeOut"&&gA.point===null;return console.log("[CrapsBetSection] canPassTurn",{isCurrentShooter:tA,phase:gA.phase,point:gA.point,result:QA}),QA},[tA,gA.phase,gA.point]),oA=!!(l&&k.includes(l)),[CA,cA]=E.useState(!1);E.useEffect(()=>{oA&&cA(!1)},[oA]);const _A=E.useRef(null),uA=E.useCallback(()=>{if(!(!a||!l||CA||oA)){cA(!0);try{m()}catch{}_A.current&&window.clearTimeout(_A.current),_A.current=window.setTimeout(()=>{cA(!1)},5e3)}},[a,l,CA,oA,m]);E.useEffect(()=>()=>{_A.current&&window.clearTimeout(_A.current)},[]);const[X,O]=E.useState(Date.now());E.useEffect(()=>{if(!W)return;const QA=window.setInterval(()=>O(Date.now()),1e3);return()=>window.clearInterval(QA)},[W]);const lA=W?Math.max(0,Math.ceil((W-X)/1e3)):0,wA=E.useMemo(()=>{var QA,PA;try{const VA=((QA=s==null?void 0:s.gameState)==null?void 0:QA.currentRollerId)??null;if(!VA)return null;const KA=(PA=s==null?void 0:s.players)==null?void 0:PA.find(Ie=>Ie.id===VA);return(KA==null?void 0:KA.name)||(KA==null?void 0:KA.id)||null}catch{return null}},[s==null?void 0:s.gameState,s==null?void 0:s.players]),xA=5,HA=500,zA=E.useMemo(()=>[1,5,10,25,100],[]);return C.jsx(gpA,{roomId:a,balance:e,point:fA,phase:RA,shooterName:wA,minBet:xA,maxBet:HA,oddsMultiple:{pass:3,dontPass:3,place:1},chips:zA,pendingBets:B,onChangeBets:eA,onClearAll:()=>{Q([]),N.clearBets()},disabled:P,onRoll:()=>d(),canRoll:H,myPlayerPlaceTotal:q,myCommittedByType:z,readyPlayers:k,meId:l,onBetDelta:pA,showReadyButton:!tA,onReadyClick:uA,readyStateLabel:"Ready",readyButtonDisabled:p||CA||oA,countdownSeconds:lA,recentSettlements:S.recentSettlements,myPlayerLineTotals:S.myLine,othersTotals:Z,onPassTurn:()=>{console.log("[CrapsBetSection] onPassTurn called, invoking passTurn()"),D()},canPassTurn:iA,onChargeChange:i})}function iie({balance:e,meId:A,readyPlayers:t,onChargeChange:i,onRollAffordanceChange:n}){return C.jsx("div",{className:"craps-bet-panel",children:C.jsx(tie,{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 nie(){var c;const{infoNow:e}=Fa(),{room:A}=tI(),{meId:t}=en(),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}),r=E.useRef(new Map),a=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 xs({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},a.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);a.current=new Map(Q.filter(Boolean).map(y=>[y.id,y]));return}const d=a.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}`)}}a.current=p}catch{}},onCrapsBetsUpdate:l=>{try{const B=(l==null?void 0:l.snapshot)||{},Q=r.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){r.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)}`)}}r.current=h}catch{}}}),E.useEffect(()=>{},[]),null}function gie(e,A){const{rollDice:t,placeMainBet:i,cancelMainBet:n,createSideBet:g,acceptSideBet:o,cancelSideBet:s,confirmBets:r,bankerGiveUp:a,setSpectate:I,getWagers:c}=So(),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(()=>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})),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(()=>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})),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 oie(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 sie(){switch(Fs){case"ceelo":return"cee-lo";case"craps":return"craps";case"poker":return"poker";case"skills":return"skills";default:return null}}function NtA(e){var i,n;const A=sie();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 RtA(e,A){if(!A)return"Anonymous";const t=e.find(i=>i.id===A);return(t==null?void 0:t.name)||"Anonymous"}function rie(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 GY(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 hS(e);!g&&o!==null&&i(o)}catch{}n.current=!0})(),()=>{g=!0}},[e]),E.useEffect(()=>{e&&n.current&&(async()=>{try{await dL(e,t)}catch{}})()},[e,t]),[t,i]}function SZ(e,A,t){var Ee;const{info:i}=LL(),n=(t==null?void 0:t.autoJoin)??!0,g=Ji(),o=NB(),{leaveRoom:s}=So(),{joinRoom:r}=tI(),a=r,I=gie(e||null),{reveal:c,rollTrigger:l,triggerSpin:B}=MB(),{user:Q}=en(),[h,d]=E.useState(null),{room:p}=tI(),y=(()=>{try{return tI&&tI()}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),[T,v]=E.useState(void 0),[U,x]=GY(e?`gp:${e}:${A}:deadline`:void 0,30),[q,z]=GY(e?`gp:${e}:${A}:serverNow`:void 0,30),[Z,eA]=GY(e?`gp:${e}:${A}:feed`:void 0,[]),[aA,sA]=E.useState([]),[pA,gA]=E.useState(null),[yA,fA]=E.useState([]),[RA,YA]=E.useState(!1),[W,$]=E.useState(!1),L=E.useRef(null),H=E.useRef(null);E.useEffect(()=>{e&&(async()=>{try{await pS(`gp:${e}:${A}:diceSettled`),await pS(`gp:${e}:${A}:diceResults`)}catch{}})()},[e,A]),E.useEffect(()=>()=>{L.current&&(window.clearTimeout(L.current),L.current=null)},[]),E.useEffect(()=>{var VA,KA;if(!h||!h.singlePlayer){YA(!1),$(!1),L.current&&(window.clearTimeout(L.current),L.current=null),H.current=null;return}const QA=(((VA=h.gameState)==null?void 0:VA.gameMode)||((KA=h.gameState)==null?void 0:KA.mode))==="craps"?1:3;if(h.players.length>=QA+1){W||$(!0),YA(!1),L.current&&(window.clearTimeout(L.current),L.current=null),H.current=null;return}W||(L.current||(L.current=window.setTimeout(()=>{YA(!0),L.current=null},250)),H.current?Date.now()>H.current&&($(!0),YA(!1)):H.current=Date.now()+5e3)},[h,W]);const P=(t==null?void 0:t.listeners)??!0;xs(P?{onJoinedRoom:({room:NA})=>{d(NA),eA(QA=>[{kind:"system",message:`You joined ${NA.name}`,ts:Date.now()},...QA]);try{K===!1&&(b.current&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>{K===!1&&!w.current&&J(!0),b.current=null},Vo.diceSettleClientMs));const QA=(NA==null?void 0:NA.gameState)||{};!(QA!=null&&QA.bankRoll)&&!(QA!=null&&QA.lastRoll)&&K===!1&&!w.current&&J(!0)}catch{}},onRejoinedRoom:({room:NA})=>{NtA(NA)&&(d(NA),eA(QA=>[{kind:"system",message:`Rejoined ${NA.name}`,ts:Date.now()},...QA]))},onOtherLeft:({room:NA})=>{d(NA)},onOtherPlayerJoined:({room:NA})=>{d(NA),eA(QA=>[{kind:"system",message:"Another player joined.",ts:Date.now()},...QA])},onSpectatorsUpdated:NA=>{const{spectators:QA,roundSeq:PA}=NA||{};d(VA=>{var Ie;if(!VA)return VA;const KA=(Ie=VA.gameState)==null?void 0:Ie.roundSeq;return typeof PA=="number"&&typeof KA=="number"&&PA!==KA?VA:{...VA,gameState:{...VA.gameState,spectators:QA??[]}}})},onDiceRolled:NA=>{const{rollerId:QA,results:PA,rank:VA,room:KA,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 IA=2e3,EA=600,j=_.current?Date.now()-_.current:0,dA=Math.max(IA-j,0)+EA;w.current=window.setTimeout(()=>{J(!0),_.current=null,KA&&d(hA=>hA?{...hA,...KA,spLevel:KA.spLevel??hA.spLevel,levelName:KA.levelName??hA.levelName}:KA),w.current=null},dA),z(DA),M(QA),v(PA)},onBetsUpdated:NA=>{var QA;(QA=NA.room)!=null&&QA.players&&d(PA=>{if(!PA)return PA;const VA=Array.isArray(NA.room.players)?NA.room.players:[];if(!VA.length)return PA;const KA=new Map((PA.players??[]).map(Ie=>[Ie.id,Ie]));for(const Ie of VA){const DA=KA.get(Ie.id);KA.set(Ie.id,DA?{...DA,...Ie}:Ie)}return{...PA,players:Array.from(KA.values())}})},onSideBetCreated:NA=>{if(!NA||NA.acceptedById||!NA.subjectId||NA.subjectId!==A)return;const PA=`${RtA((h==null?void 0:h.players)??[],NA.playerId)} offered: ${rie(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"?(pcA(),eA(QA=>[{kind:"system",message:"You logged in from another device.",ts:Date.now()},...QA])):eA(QA=>[{kind:"system",message:"You were logged out.",ts:Date.now()},...QA]),g("/lobby",{replace:!0})},onError:NA=>N(NA),onBankerChanged:NA=>{NA!=null&&NA.roomId&&d(QA=>!QA||QA.id!==NA.roomId?QA:{...QA,gameState:{...QA.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 QA=RtA(NA.room.players,NA.banker);eA(PA=>[{kind:"system",message:`${QA} is now the banker for the new round.`,ts:Date.now()},...PA])},onRoomUpdateState:NA=>{const{roomId:QA,gameState:PA,room:VA}=NA||{},KA=(VA==null?void 0:VA.gameState)??PA;if(!QA||!KA||!NtA(VA??{gameState:KA}))return;const Ie=Array.isArray(VA==null?void 0:VA.players)?VA.players:[],DA=IA=>{if(!Ie.length)return IA;const EA=new Map(IA.map(j=>[j.id,j]));for(const j of Ie){const dA=EA.get(j.id);EA.set(j.id,dA?{...dA,...j}:j)}return Array.from(EA.values())};d(IA=>{var UA;if(!IA||IA.id!==QA)return{...IA,gameState:KA,...Ie.length?{players:Ie}:{}};const EA=(UA=IA.gameState)==null?void 0:UA.roundSeq,j=KA==null?void 0:KA.roundSeq,dA=typeof EA=="number"&&typeof j=="number"&&EA!==j,hA={...IA,players:DA(IA.players??[]),gameState:{...IA.gameState,...KA}};if(dA&&!w.current){try{J(!0)}catch{}try{v(void 0)}catch{}try{M(null)}catch{}}return hA})}}:{}),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},Vo.diceSettleClientMs)):K===!0&&b.current&&(window.clearTimeout(b.current),b.current=null)},[K]);const iA=E.useRef(null),oA=E.useRef(void 0),CA=E.useRef(!1);iA.current=a,E.useEffect(()=>{if(!n)return;let NA=!1;if(oA.current!==e)return oA.current=e,CA.current=!1,(async()=>{var VA,KA,Ie,DA,IA;if(!e){N("No room id provided."),S(!1);return}if(S(!0),N(null),!iA.current){N("No join ref");return}const QA=(()=>{var EA,j;try{return typeof window<"u"&&(((j=(EA=window.location)==null?void 0:EA.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 EA=()=>QA?Promise.race([iA.current(e),new Promise(hA=>setTimeout(()=>hA({ok:!1,error:"e2e-timeout"}),1800))]):iA.current(e),j=Zb[e]||EA();Zb[e]=j;try{PA=await j}finally{delete Zb[e]}}catch(EA){if(delete Zb[e],!QA){N((EA==null?void 0:EA.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(!QA){N((PA==null?void 0:PA.error)??"Failed to join room."),S(!1);return}const EA=Date.now(),j=(Q==null?void 0:Q.id)||"e2e-user",dA=(Q==null?void 0:Q.name)||"E2E User",UA=((()=>{try{const Ke=new URLSearchParams(window.location.search).get("m");return Ke==="cee-lo"||Ke==="craps"?Ke:null}catch{return null}})()||(e!=null&&e.toLowerCase().includes("ceelo")?"cee-lo":"craps"))==="cee-lo",TA=[{id:j,name:dA,isReady:!0,balance:1e3},{id:"bank",name:"Bank",isReady:!0,balance:1e6}],se=UA?{id:e,name:"E2E Cee-Lo Room",gameMode:"cee-lo",createdAt:EA,updatedAt:EA,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:EA,updatedAt:EA,bankerId:"bank",players:TA,gameState:{gameMode:"craps",crapsPoint:null,currentRollerId:j,turnOrder:[j],roundSeq:1,crapsPassBets:[],crapsDontPassBets:[],crapsPlaceBets:[]}};d(se);try{m==null||m(se)}catch{}typeof window<"u"&&(window.__e2eRoomHydrated={id:se.id,players:se.players.map(Ne=>Ne.id),gameMode:se.gameState.gameMode,ts:Date.now()}),S(!1);return}d(PA.room);try{m==null||m(PA.room)}catch{}typeof window<"u"&&(window.__e2eRoomHydrated={id:(VA=PA.room)==null?void 0:VA.id,players:(Ie=(KA=PA.room)==null?void 0:KA.players)==null?void 0:Ie.map(EA=>EA.id),gameMode:(IA=(DA=PA.room)==null?void 0:DA.gameState)==null?void 0:IA.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||{},QA=(NA==null?void 0:NA.gameMode)??"cee-lo";return((NA==null?void 0:NA.banker)??(QA==="cee-lo"?NA==null?void 0:NA.currentRollerId:void 0))===A},[h,A]),{open:uA,openAll:X}=ox(e,A),O=E.useMemo(()=>(uA||[]).some(NA=>NA.type==="MAIN"&&Number(NA.amount)>0),[uA]),lA=E.useMemo(()=>(X||[]).some(NA=>NA.type==="MAIN"),[X]),wA=((Ee=h==null?void 0:h.gameState)==null?void 0:Ee.currentRollerId)??null,xA=E.useMemo(()=>{const NA=(h==null?void 0:h.gameState)||(p==null?void 0:p.gameState)||{},QA=(NA==null?void 0:NA.gameMode)??"cee-lo",PA=!!(NA!=null&&NA.roundEnded);if(QA==="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&&!lA)return gA("Waiting for bets"),fA([]),!1;const VA=!!(NA!=null&&NA.bankRoll),KA=oie({isMyTurn:cA,isBanker:_A,diceSettled:K,hasMainBetPlaced:O,bankPointExists:VA,roundEnded:PA});return gA(KA.reason??null),fA([]),KA.canRoll},[h==null?void 0:h.gameState,p==null?void 0:p.gameState,cA,_A,O,K,lA,h==null?void 0:h.singlePlayer]),HA=E.useCallback(()=>{e&&(s(e),g("/lobby"))},[e,s,g]),zA=E.useCallback(()=>{if(e&&xA){if(_A&&!lA){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(),QA=(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(QA)){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,lA,h==null?void 0:h.gameState]),ne=E.useCallback(async()=>{var NA;if(e)return(NA=I.giveUpBank)==null?void 0:NA.call(I)},[e,I]),ye=E.useCallback(async NA=>{var QA;if(e)return(QA=I.spectate)==null?void 0:QA.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:T,deadline:U,serverNow:q,canRoll:xA,canRollReason:pA,canRollBlocking:yA,handleRoll:zA,handleLeave:HA,giveUpBank:ne,setSpectateMode:ye,currentRollerId:wA,readyPlayers:aA}}function aie({meId:e,players:A,openSideBets:t,onCancelSideBet:i,onAcceptSideBet:n,offersToMe:g=[],newOffersCount:o=0,onOffersSeen:s,disabled:r=!1,betsLocked:a,hasBankRoll:I,hasRolledThisRound:c}){const l=NB(),[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{qn()}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&&!r,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(Zc,{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:r||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,T=!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(Zc,{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":T||"Cannot cancel",disabled:!J||!!r,onClick:async()=>{if(!J)return;try{qn()}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 Iie({roomId:e,meId:A,bankerId:t,players:i,gameState:n,gameplay:g}){const o=NB(),s=t===A,{myOpenMain:r,myOpenSides:a,placeSideBet:I,cancelSideBet:c,acceptSideBet:l,offersToMe:B,newOfferCount:Q,markOffersAsSeen:h}=ox(e,A),d=SZ(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&&!!!r,M=s&&!m&&!D,w=E.useCallback(async()=>{try{qn()}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{qn()}catch{}try{}catch{}try{await yo("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(T=>(T.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(aie,{isBanker:s,openSideBets:a,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(T=>T.playerId===J&&(T.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 $C({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 Cie=new TextEncoder;function cie(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 lie(e){const A=await crypto.subtle.digest("SHA-256",Cie.encode(e));return cie(A)}async function Bie(e,A){return!e||!A?!1:(await lie(e)).toLowerCase()===A.toLowerCase()}const bY=(e,A)=>`${e}:${A}`;function rpA(e){const[A,t]=E.useState({}),[i,n]=E.useState({}),g=E.useRef({});E.useEffect(()=>{t({}),n({}),g.current={}},[e]),xs({onDiceRolled:r=>{var B,Q;const a=r==null?void 0:r.fairness,I=r==null?void 0:r.rollerId,c=(a==null?void 0:a.roundSeq)??((Q=(B=r==null?void 0:r.room)==null?void 0:B.gameState)==null?void 0:Q.roundSeq);if(!a||!I||typeof c!="number")return;const l=bY(c,I);t(h=>h[l]?h:{...h,[l]:a}),delete g.current[l]},onCrapsRollResult:r=>{var B;const a=r==null?void 0:r.fairness,I=((B=r==null?void 0:r.fairness)==null?void 0:B.rollerId)||(r==null?void 0:r.currentRollerId),c=a==null?void 0:a.roundSeq;if(!a||!I||typeof c!="number")return;const l=bY(c,I);t(Q=>Q[l]?Q:{...Q,[l]:a}),delete g.current[l]},onFairnessReveal:r=>{typeof(r==null?void 0:r.roundSeq)!="number"||!r.commit||!r.serverSeed||n(a=>{const I=a[r.roundSeq];if(!I||I.commit!==r.commit)for(const c of Object.keys(g.current))c.startsWith(`${r.roundSeq}:`)&&delete g.current[c];return{...a,[r.roundSeq]:{commit:r.commit,serverSeed:r.serverSeed}}})}});const o=E.useCallback(async(r,a,I)=>{const c=bY(a,r);if(g.current[c])return g.current[c];const l=A[c],B=i[a];if(!l||!B)return g.current[c]="unverifiable","unverifiable";const h=await Bie(B.serverSeed,l.commit)?"verified":"bad-commit";return g.current[c]=h,h},[A,i]),s=E.useMemo(()=>{const r=Object.keys(i).map(a=>Number(a)).filter(a=>!Number.isNaN(a));return r.length?Math.max(...r):void 0},[i]);return{proofs:A,reveals:i,verifyFor:o,lastRoundWithReveal:s}}const Wc=obA;let Fo=null,mk=null,Sk=null,GtA=!1;async function XR(){if(Fo)return!0;try{const e=await li(()=>import("./index-Cv863TEx.js"),__vite__mapDeps([13,1]));return Fo=e.AdMob,mk=e.RewardAdPluginEvents,Sk=e.InterstitialAdPluginEvents,console.log("[NativeAdService] AdMob plugin loaded"),!0}catch(e){return console.warn("[NativeAdService] AdMob plugin not available:",e),!1}}let Bf=!1,wk=!1,UY=!1;const Eie=45e3;function wu(e){var A;try{(A=e==null?void 0:e.remove)==null||A.call(e)}catch{}}function apA(){return{adId:IpA(),isTesting:Wc,immersiveMode:!1}}function Qie(){const e=ti.getPlatform();return e==="web"||e==="ios"?!1:e==="ios"||e==="android"}async function Uw(){if(Bf)return!0;const e=ti.getPlatform();if(e==="web")return console.log("[NativeAdService] Skipping AdMob init on web"),!1;if(console.log(`[NativeAdService] Initializing AdMob — platform=${e} testMode=${Wc}`),GtA||(GtA=!0,console.log("[NativeAdService] Active native ad config",{appTarget:Fs,platform:e,testMode:Wc,interstitialAdUnitId:IpA(),rewardedAdUnitId:wZ()})),!await XR()||!Fo)return console.error("[NativeAdService] Plugin load failed — cannot initialize"),!1;try{return await Fo.initialize({requestTrackingAuthorization:!0,initializeForTesting:Wc}),Bf=!0,console.log("[NativeAdService] AdMob initialized successfully"),!0}catch(t){return console.error("[NativeAdService] AdMob initialization failed:",t),!1}}function wZ(){const e=ti.getPlatform();return e==="ios"?nbA:w6}function IpA(){const e=ti.getPlatform();return e==="ios"?gbA:N6}async function CpA(){if(ti.getPlatform()==="web"||!await XR()||!Fo)return!1;Bf||await Uw();try{const t=wZ();return console.log(`[NativeAdService] prepareRewardVideoAd adId=${t} isTesting=${Wc}`),await Fo.prepareRewardVideoAd({adId:t,isTesting:Wc}),wk=!0,console.log("[NativeAdService] Rewarded ad prepared successfully"),!0}catch(t){return console.error("[NativeAdService] Failed to prepare rewarded ad:",t),!1}}async function uie(){return ti.getPlatform()==="web"?{ok:!1,error:"NOT_NATIVE"}:!await XR()||!Fo?{ok:!1,error:"PLUGIN_NOT_AVAILABLE"}:!Bf&&!await Uw()?{ok:!1,error:"INIT_FAILED"}:new Promise(async t=>{let i=!1,n,g;const o=await Fo.addListener(mk.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 Fo.addListener(mk.Dismissed,()=>{console.log("[NativeAdService] Ad dismissed, rewarded:",i),I(),t(i?{ok:!0,rewardType:n,rewardAmount:g}:{ok:!1,error:"AD_DISMISSED"})}),r=await Fo.addListener(mk.FailedToShow,c=>{console.error("[NativeAdService] Ad failed to show:",c),I(),t({ok:!1,error:"FAILED_TO_SHOW"})}),a=await Fo.addListener(mk.FailedToLoad,c=>{console.error("[NativeAdService] Rewarded ad failed to load:",c),wk=!1,I(),t({ok:!1,error:"FAILED_TO_LOAD"})}),I=()=>{wu(o),wu(s),wu(r),wu(a)};try{if(wk)console.log("[NativeAdService] Rewarded ad already prepared, skipping load");else{const c=wZ();console.log(`[NativeAdService] prepareRewardVideoAd (in show) adId=${c} isTesting=${Wc}`),await Fo.prepareRewardVideoAd({adId:c,isTesting:Wc})}wk=!1,console.log("[NativeAdService] Calling showRewardVideoAd..."),await Fo.showRewardVideoAd()}catch(c){wk=!1,console.error("[NativeAdService] Error showing ad:",c),I(),t({ok:!1,error:(c==null?void 0:c.message)||"UNKNOWN_ERROR"})}})}async function ru(){if(!Qie())return console.log("[NativeAdService] Interstitial disabled or unsupported on this platform"),!1;if(!await XR()||!Fo)return!1;Bf||await Uw();try{const A=apA();return console.log(`[NativeAdService] prepareInterstitial adId=${A.adId} isTesting=${Wc}`),await Fo.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 kk(){const e=ti.getPlatform();return e==="web"?{ok:!1,error:"NOT_NATIVE"}:e==="ios"?{ok:!1,error:"IOS_INTERSTITIAL_DISABLED"}:!await XR()||!Fo?{ok:!1,error:"PLUGIN_NOT_AVAILABLE"}:!Bf&&!await Uw()?{ok:!1,error:"INIT_FAILED"}:UY?(console.warn("[NativeAdService] Interstitial show skipped: another interstitial is already active"),{ok:!1,error:"ALREADY_SHOWING"}):(console.log(`[NativeAdService] showInterstitialAd — initialized=${Bf} testMode=${Wc}`),new Promise(async t=>{UY=!0;let i=!1,n=null,g=null,o=null,s=null,r=null;const a=()=>{wu(g),wu(o),wu(s),wu(r)},I=c=>{i||(i=!0,n&&clearTimeout(n),UY=!1,a(),t(c))};n=setTimeout(()=>{console.warn("[NativeAdService] Interstitial timed out waiting for native close/fail callback"),I({ok:!1,error:"DISMISS_TIMEOUT"})},Eie),g=await Fo.addListener(Sk.Dismissed,()=>{console.log("[NativeAdService] Interstitial dismissed ✓"),I({ok:!0}),ru().catch(()=>{})}),o=await Fo.addListener(Sk.Showed,()=>{console.log("[NativeAdService] Interstitial showed ✓")}),s=await Fo.addListener(Sk.FailedToLoad,c=>{console.error("[NativeAdService] Interstitial failed to load:",JSON.stringify(c)),I({ok:!1,error:"FAILED_TO_LOAD"})}),r=await Fo.addListener(Sk.FailedToShow,c=>{console.error("[NativeAdService] Interstitial failed to show:",JSON.stringify(c)),I({ok:!1,error:"FAILED_TO_SHOW"})});try{const c=apA();console.log(`[NativeAdService] prepareInterstitial (in show) adId=${c.adId} isTesting=${Wc}`),await Fo.prepareInterstitial(c),console.log("[NativeAdService] Calling showInterstitial..."),await Fo.showInterstitial()}catch(c){console.error("[NativeAdService] Error showing interstitial:",c),I({ok:!1,error:(c==null?void 0:c.message)||"UNKNOWN_ERROR"})}}))}function cpA(){const e=ti.getPlatform();return e==="ios"||e==="android"}const vY={initializeAdMob:Uw,prepareRewardedAd:CpA,showRewardedAd:uie,prepareInterstitialAd:ru,showInterstitialAd:kk,isNativeAdSupported:cpA},btA=n8,UtA=WCA,vtA=VCA,Wb=XCA,Wy="ad:complete",lpA=E.createContext({onHandEnd:async()=>{},onCrapsShooterTurnEnd:async()=>{},onZentaraTurnEnd:async()=>{},showAdNow:async()=>{},cancelAd:()=>{},isAdEnabled:!1,isAdShowing:!1,adConfig:{handsPerAd:WCA,crapsShooterTurnsPerAd:VCA,minIntervalMs:qh,displayDelayMs:GD,zentaraTurnsPerAd:XCA}}),qf=()=>E.useContext(lpA);function die({children:e}){const[A,t]=E.useState(!1),[i,n]=E.useState(!1),g=cpA(),o=!A&&g;E.useEffect(()=>{console.log(`[AdContext] isAdEnabled=${o} isPremium=${A} isNative=${g}`)},[o,A,g]);const s=E.useRef(!1),r=E.useRef(0),a=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=ua();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;btA&&(K=!!(b!=null&&b[btA])||_),t(K)}catch{}};S();const k=setInterval(S,6e4);return()=>clearInterval(k)},[]),E.useEffect(()=>{o&&ru().catch(()=>{})},[o]);const h=E.useCallback(async()=>{if(!o||s.current)return;const S=Date.now();if(!(S-c.current<qh)&&(r.current+=1,!(r.current<UtA))){s.current=!0,r.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 kk()}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{}ru().catch(()=>{})}}},[o]),d=E.useCallback(async()=>{if(!o||s.current)return;const S=Date.now();if(!(S-c.current<qh)&&(a.current+=1,!(a.current<vtA))){s.current=!0,a.current=0,c.current=S;try{window.__adShowingDoNotDisconnect=!0,window.__adShowingPauseGame=!0}catch{}n(!0),await new Promise(k=>setTimeout(k,GD));try{await kk()}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{}ru().catch(()=>{})}}},[o]),p=E.useCallback(async()=>{if(console.log(`[AdContext] onZentaraTurnEnd — enabled=${o} showing=${s.current} turns=${I.current+1}/${Wb} 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<Wb){console.log(`[AdContext] Skipping ad — need ${Wb} 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 kk()}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{}ru().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,r.current=0,a.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 kk()}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{}ru().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:UtA,crapsShooterTurnsPerAd:vtA,zentaraTurnsPerAd:Wb,minIntervalMs:qh,displayDelayMs:GD};return C.jsx(lpA.Provider,{value:{onHandEnd:h,onCrapsShooterTurnEnd:d,onZentaraTurnEnd:p,showAdNow:y,cancelAd:m,isAdEnabled:o,isAdShowing:i,adConfig:D},children:e})}const BpA=gr();async function hie(e){if(!e)return null;try{const A=await Co(),t=`${BpA}/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 pie(e){if(!e)return null;try{const A=await Co(),i=await(await fetch(`${BpA}/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 kZ=[A5,e5,t5,i5,n5,g5,o5,s5,r5];function fie(e){let A=0;for(let t=0;t<e.length;t++)A=A*31+e.charCodeAt(t)>>>0;return A%(kZ.length*6)}function yie(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>=kZ.length?null:{sheetIdx:t,tile:i%6}}function KtA({seed:e,sheetIdx:A,tile:t}){const i=fie(e),n=A??Math.floor(i/6),g=t??i%6,o=kZ[n],s=2,r=3,a=g%s,I=Math.floor(g/s),c=s*100,l=n===4?400:r*100,B=c/100,Q=l/100,h=a/(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 Die({stream:e,labelFallback:A,muted:t=!0,forceHideVideo:i=!1,active:n=!1,avatarUrl:g}){const o=E.useRef(null),[s,r]=E.useState(!1),[a,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){r(!1);return}const d=()=>r(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()&&r(!0)},y=setInterval(()=>{const m=c(),D=d.readyState>=2;r(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(()=>yie(g),[g]),Q=E.useCallback(()=>I(!0),[]),h=B?C.jsx(KtA,{seed:A,sheetIdx:B.sheetIdx,tile:B.tile}):g&&!a?C.jsx("img",{src:g,alt:A,className:"avatar-uploaded",style:{width:"100%",height:"100%",objectFit:"cover"},onError:Q}):C.jsx(KtA,{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 mie(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 Sie=E.memo(Die,mie);function wie(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 MZ(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 pM(e,A){return MZ(e)}function FtA(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 KY(e){if(!e||e.length!==3)return{score:0,label:"—",kind:"invalid"};const A=MZ(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 EpA(e){const{anchorRect:A,anchorEl:t,onClose:i,onMessages:n,onSendMoney:g,onAddFriend:o,onUnfriend:s,onBlockUser:r,onViewProfile:a,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:[a&&C.jsx("button",{role:"menuitem",onClick:()=>{a(),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:()=>{r==null||r(),i()},className:"avatar-context-menu__item",disabled:!r,title:c?"Unblock user":"Block user",children:c?"Unblock":"Block"})]});return typeof document<"u"?zr.createPortal(m,document.body):m}function QpA({targetId:e,anchorRect:A,anchorEl:t,onClose:i,onOpenDM:n,onOpenSendMoney:g,meId:o}){const{friends:s,friendRequests:r,isBlocked:a,blockUser:I,unblockUser:c,addFriend:l,removeFriend:B}=vd();Ji();const Q=r.some(h=>h.status==="PENDING"&&h.fromUserId===o&&h.toUserId===e);return C.jsx(EpA,{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)&&!a(e)&&l(e)},onUnfriend:()=>{s.find(h=>h.id===e)&&B(e)},onBlockUser:async()=>{a(e)?await c(e):await I(e)},isFriend:!!s.find(h=>h.id===e),isBlocked:a(e)})}const kie=E.forwardRef(function({id:A,display:t,isCurrentRoller:i,isMe:n,balance:g,isSpectating:o=!1,folded:s=!1,tags:r,stream:a,diceResult:I,onOpenMenu:c,showMenu:l,menuProps:B,forceHideVideo:Q,actDeadlineTs:h,avatarUrl:d,showActingTimerRing:p=!0,presenceStatus:y},m){const D=wie(t);return C.jsxs(WI.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}${r.length?" · "+r.join(" · "):""}`,"aria-label":`${t}${r.length?", "+r.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(Sie,{active:i,stream:a,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}),r.includes("B")&&C.jsx("span",{className:"player-tag tag--B","aria-label":"Banker",children:"BANK"}),r.includes("D")&&C.jsx("span",{className:"player-tag tag--D","aria-label":"Dealer",children:"D"}),r.includes("SB")&&C.jsx("span",{className:"player-tag tag--SB","aria-label":"Small blind",children:"SB"}),r.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(QpA,{...B})]})}),upA=[A5,e5,t5,i5,n5,g5,o5,s5,r5];function Mie(e){let A=0;for(let t=0;t<e.length;t++)A=A*31+e.charCodeAt(t)>>>0;return A%(upA.length*6)}function Nie({seed:e}){const A=Mie(e),t=Math.floor(A/6),i=A%6,n=upA[t],g=2,o=3,s=i%g,r=Math.floor(i/g),a={display:"block",width:"100%",height:"100%",borderRadius:"8px",backgroundImage:`url(${n})`,backgroundSize:`${g*100}% ${o*100}%`,backgroundPosition:`${s*(100/(g-1))}% ${r*(100/(o-1))}%`,backgroundRepeat:"no-repeat"};return C.jsx("span",{className:"avatar-sprite",style:a,"aria-hidden":!0})}function GK({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 r=o.id??String(s),a=o.name??r;return C.jsxs("li",{className:["player","player--avatar",r===A?"is-me":""].join(" "),"data-player-id":r,title:a,"aria-label":a,onClick:()=>n==null?void 0:n(r),role:n?"button":void 0,tabIndex:n?0:-1,onKeyDown:I=>{n&&(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),n(r))},children:[C.jsx("div",{className:"avatar-ring","aria-hidden":!0,children:C.jsx("div",{className:"video-bubble",children:C.jsx(Nie,{seed:o.id})})}),r===A&&C.jsx("span",{className:"status-dot","aria-hidden":!0}),C.jsxs("div",{className:"player-info",children:[C.jsx("div",{className:"player-name",children:a}),i&&C.jsx("div",{className:"player-bank",children:C.jsxs("b",{children:["$",o.balance??0]})})]}),g==null?void 0:g(o)]},r)})})})}function NZ(){const[e,A]=E.useState(null),[t,i]=E.useState(null),[n,g]=E.useState(null);return{forUserId:e,anchorRect:t,anchorEl:n,openFor:(r,a)=>{a&&(A(r),g(a),i(a.getBoundingClientRect()))},close:()=>{A(null),i(null),g(null)}}}function dpA({players:e,meId:A,className:t,onOpenDM:i,onOpenSendMoney:n,renderActionsOverride:g}){const{forUserId:o,anchorRect:s,anchorEl:r,openFor:a,close:I}=NZ(),c=(B,Q)=>{!Q||B===A||a(B,Q)},l=()=>I();return C.jsxs("div",{className:t,children:[C.jsx(GK,{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(QpA,{targetId:o,anchorRect:s,anchorEl:r,onClose:l,onOpenDM:i,onOpenSendMoney:n,meId:A})]})}function Rie(e,A,t,i){const n=E.useRef(new Map),g=E.useRef(new Map),[o,s]=E.useState(0),r=E.useRef(i),a=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(()=>{r.current!==i&&(n.current.clear(),g.current.clear(),a.current=0,s(c=>c+1),r.current=i)},[i]),E.useEffect(()=>{for(let c=a.current;c<e.length;c++){const l=e[c],B=l.result;pM(B,l.playerId===A)!=="nothing"&&I(l.playerId)}a.current=e.length},[e,I,A]),E.useEffect(()=>{var l;if(!A||!((l=t.bankRoll)!=null&&l.raw))return;pM(t.bankRoll.raw)!=="nothing"&&I(A)},[A,t.bankRoll,I]),{revealedPlayers:n.current,revealTimesRef:g,revealVersion:o,markRevealed:I}}function Gie(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 bie(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 RZ(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():"",r=!1;if(!s||!["WIN","LOSE","PUSH","TIE"].includes(s)){const c=lf(e,A);c&&c.myResult&&(s=c.myResult.toUpperCase(),r=!0)}const a=s==="WIN"||s==="LOSE",I=s==="PUSH"||s==="TIE";if(!a&&!I)return{outcome:null,isChallenger:!1,needsAnimation:!1};if(r)return a?i=s==="WIN"?"win":"lose":i="push",g=a,{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};a?(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(a?(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(Gie(e.predicate)),e.subjectId&&B.push(`on ${e.subjectId}`),B.length&&(o=B.join(" "))}}return{outcome:i,isChallenger:n,subtitle:o,needsAnimation:g}}function Uie(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),r=A(g);if(!s||!r||Math.hypot(r.x-s.x,r.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:r.x,endY:r.y}}function hpA(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 vie={1:HBA,2:OBA,3:PBA,4:jBA,5:zBA,6:ZBA};function ppA({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:vie[A],alt:`Dice face ${A}`,style:{width:22,height:22,borderRadius:"4px"}},t))})}function GZ(){const[e,A]=E.useState(!1),[t,i]=E.useState(!0);E.useEffect(()=>{let g=!0;return(async()=>{try{const o=await Wo();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 Wo(),r={...Qs,...s,showAnimations:o};await _E(r)}catch{}},[t]);return{ready:e,showAnimations:t,toggleAnimations:n}}const fpA=[1,5,10,25,100,500];var bK=(e=>(e.FREE="FREE",e.PREMIUM="PREMIUM",e))(bK||{});const Vb={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]},Kie=[500,100,25,10,5,1],FY=20;function bZ(e){const A=[];let t=Math.max(1,Math.floor(e));for(const i of Kie){for(;t>=i&&(A.push(i),t-=i,!(A.length>=FY)););if(A.length>=FY)break}return t>0&&A.length<FY&&A.push(t),A.length===0&&A.push(1),A}function ypA({anim:e,onComplete:A}){const{showAnimations:t}=GZ(),i=t===!1,n=E.useRef(!1),g=E.useRef(e).current,{amount:o,startX:s,startY:r,endX:a,endY:I}=g,c=E.useRef([]);if(c.current.length===0){const B=bZ(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=a-18,y=r-18+Q.yOffset,m=I-18+Q.yOffset;return C.jsx(WI.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(Zc,{mini:!0,value:Q.value,className:"chip--flight"})},Q.id)})})()})}const W3=new Set;function Fie(e){return W3.add(e),()=>W3.delete(e)}function _ie(e){e&&W3.forEach(A=>{try{A(e)}catch{}})}function Jie({newSettlements:e,roundSeqNow:A,getAvatarCenter:t,getPlayerName:i,myId:n,bankerDice:g,bankerId:o,isPartyReady:s,onAnimCompleteBySettlement:r}){const[a,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=>Uie(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,q=(M==null?void 0:M.acceptedById)||(M==null?void 0:M.bankerId);if(!(!!x&&s(x)&&!!q&&s(q))){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 T,v;if(J==="WIN"?(T=_,v=K):J==="LOSE"&&(T=K,v=_),T&&v){const x=m(T),q=m(v);if(!x||!q){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=hpA(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:_}=RZ(w,n);_&&p(setTimeout(()=>S(w),200))}},[e,A,n,o,S]),E.useEffect(()=>{c.length===0&&a.length>0&&(l(a[0]),I(M=>M.slice(1)))},[c.length,a]);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 r=="function"&&r(_.settlementId),_!=null&&_.settlementId&&(_ie(_.settlementId),B.current.add(_.settlementId))}catch{}return b})},[r]),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 Lie(){const{hasActive:e}=Fa(),A=E.useRef([]),t=E.useRef(!1),i=E.useRef(null),n=E.useRef(new Set),g=E.useCallback(()=>{yo("Light").catch(()=>{})},[]),o=()=>typeof performance<"u"&&performance.now?performance.now():Date.now(),s=(Vo==null?void 0:Vo.diceToChipDelayMs)+600,r=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]),a=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}),r()},[r]),I=E.useCallback(()=>{i.current&&(window.clearTimeout(i.current),i.current=null),t.current=!1,r()},[r]),c=E.useCallback(()=>{i.current&&(window.clearTimeout(i.current),i.current=null),A.current=[],t.current=!1},[]);return{schedule:a,nudge:I,clear:c,hasActive:e}}function xie({newSettlements:e,roundSeqNow:A,myId:t,bankerDice:i,getPlayerName:n,getPlayerAvatarUrl:g,getPlayerDice:o,getRevealTime:s,postRevealDelayMs:r=0,bankerId:a}){const{win:I,lose:c,push:l}=Fa(),B=E.useRef(new Set),{schedule:Q,nudge:h,clear:d}=Lie(),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,T)=>J-T).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"?(AP({volume:.18}),window.setTimeout(()=>{try{JcA("win",{volume:.4})}catch{}},90)):M==="lose"?m8({volume:.08}):FcA({volume:.09}))},[A]),N=E.useCallback((M,w,b,_,K,J,T,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():"",q=T!=null&&T.length?{playerAvatars:T}:void 0;if(_)M==="win"?I(`${_}${U}`,b,void 0,void 0,q):M==="lose"?c(_,b,void 0,void 0,q):l(_,b,void 0,void 0,q);else if(K)M==="win"?I("win",b,void 0,void 0,q):M==="lose"?c("lose",b,void 0,void 0,q):l("push",b,void 0,void 0,q);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,q):M==="lose"?c(Z,b,void 0,void 0,q):l("Push!",b,void 0,void 0,q)}},[k,I,c,l]),G=E.useCallback((M,w,b,_,K,J={})=>{const T=w&&(p.current??0)>=5&&M==="win";Q(()=>N(M,T,b,_,K,void 0,void 0,J.key),J)},[Q,N]);E.useEffect(()=>{const M=hpA(e,A,B.current,a);if(M.length)for(const w of M){const{outcome:b,isChallenger:_,subtitle:K,needsAnimation:J}=RZ(w,t);if(!b)continue;let T=K,v=!1;if(w.type==="SIDE"){const fA=w.subjectId&&n(w.subjectId)||w.subjectId||"Player",RA=bie(w.predicate);let YA;b==="win"?YA=`${fA} ${RA}`:b==="lose"?RA==="beats banker"?YA=`${fA} does not beat banker`:RA==="loses to banker"?YA=`${fA} does not lose to banker`:RA==="ties banker"?YA=`${fA} does not tie banker`:YA=`${fA} ${RA}`:YA=`${fA} ${RA}`,T=YA,v=!0}else K&&w.subjectId&&K.includes("on ")&&(T=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 YA=String(fA.label||"").trim(),W=String(T||"").trim();if(W.length===0)T=YA;else if(YA.length>0){const $=W.toLowerCase(),L=YA.toLowerCase();$.includes(L)||(T=`${W} — ${YA}`)}}}catch{}b==="push"&&((T||"").trim()||(T="No Action"));const U=w.type==="SIDE"?w.subjectId||void 0:w.playerId,x=w.type==="SIDE"?a:w.acceptedById||w.bankerId||a,q=!!(y.current||m.current),z=q||w.type==="SIDE"?!1:J,Z=q?!0:!z,eA=!q&&z?Vo.diceToChipDelayMs+50:0,aA=U,sA=x,pA=s?Vo.revealFlashPostDelayMs:0,gA=s&&!q?{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,YA;try{const L=w,H=(Array.isArray(L.bankerDice)&&L.bankerDice.length===3?L.bankerDice:null)||(o&&a?o(a):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&&a?o(a):"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=a&&n(a)||"Banker",CA=n(w.playerId)||"Challenger",cA={name:oA,avatarUrl:a&&g?g(a):void 0},_A={name:CA,avatarUrl:g?g(w.playerId):void 0};if(H&&P){const uA=KY(H),X=KY(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=`${CA}: ${iA(P)} ${X.label}`;uA.score>=X.score?(RA=`${wA}
${xA}`,YA=[cA,_A]):(RA=`${xA}
${wA}`,YA=[_A,cA])}}else if(H){const uA=KY(H);(uA.kind==="456"||uA.kind==="123")&&(RA=`${a&&n(a)||"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,YA,String(w.id))},{immediate:q?!0:Z&&!gA,delayMs:yA,revealGate:gA,key:String(w.id)})}else G(b,_,T,void 0,v,{immediate:q?!0:Z&&!gA,delayMs:yA,revealGate:gA,key:String(w.id)})}},[e,A,t,n,G,a]),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,_=a&&n(a)||"Banker",K=["","⚀","⚁","⚂","⚃","⚄","⚅"],T=i?` ${(z=>z.slice().sort((Z,eA)=>Z-eA).map(Z=>K[Z]||String(Z)).join(""))(i)}`:"",v=b?`${_}:${T} 4‑5‑6`:`${_}:${T} 1‑2‑3`,U=b?"All challengers lose":"All challengers win",x=a&&t&&a===t,q=b?x?"win":"lose":x?"lose":"win";Q(()=>N(q,!1,U,v,!0,void 0,void 0,`auto-${A}`),{immediate:!0,key:`auto-${A}`}),S.current=A},[e,A,t,a,Q,N]),E.useEffect(()=>{const M=Fie(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=Ji(),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 zr.createPortal(o,document.body)}function Tie({isUserTurn:e=!1,onOpen:A,isConnected:t=!0}){const{micEnabled:i,videoEnabled:n,speaking:g}=al(),[o,s]=E.useState(!1),r=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{Xt("Light")}catch{}A()}},[t,e,A]),l=E.useCallback(()=>{t&&(r.current=setTimeout(()=>{if(s(!0),e){try{Xt("Medium")}catch{}A()}},500))},[t,e,A]),B=E.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null),setTimeout(()=>s(!1),1500)},[]),Q=E.useCallback(()=>{r.current&&(clearTimeout(r.current),r.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(qie,{}),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 qie(){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 Yie({open:e,onClose:A,roomId:t,onLeaveVoice:i,onBlockReport:n}){const{micEnabled:g,setMicEnabled:o,videoEnabled:s,setVideoEnabled:r,leaveRoom:a}=al(),[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{Xt("Light")}catch{}B(!0);try{await o(!g)}catch{}finally{B(!1)}}},[g,o,l]),m=E.useCallback(async()=>{if(!Q){try{Xt("Light")}catch{}h(!0);try{await r(!s)}catch{}finally{h(!1)}}},[s,r,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{Xt("Medium")}catch{}a(t),i==null||i(),A()},[t,a,i,A]),k=E.useCallback(()=>{try{Xt("Medium")}catch{}n==null||n(),A()},[n,A]);return e?zr.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 mpA({roomId:e,isUserTurn:A=!1,leftSlot:t,singlePlayer:i}){al();const{user:n}=en(),[g,o]=E.useState(!1),[s,r]=E.useState(!1),[a,I]=E.useState(rvA()),c=(()=>{try{return(n==null?void 0:n.isGuest)===!0}catch{return!1}})(),l=E.useCallback(Q=>()=>{try{Xt("Light")}catch{}try{}catch{}Q()},[]);E.useEffect(()=>{let Q=!0;return(async()=>{try{const h=await Wo();if(!Q)return;const d=!!h.diceAudio;I(d),H6(d)}catch{}})(),()=>{Q=!1}},[]),l(()=>{const Q=!a;if(I(Q),H6(Q),Q)try{qn()}catch{}(async()=>{try{const d={...await Wo(),diceAudio:Q};await _E(d)}catch{}})()}),E.useMemo(()=>a?"Mute sounds":"Unmute sounds",[a]);const B=E.useCallback(()=>{if(c){o(!0);return}r(!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(Tie,{isUserTurn:A,onOpen:B,isConnected:!!e&&!i})}),C.jsx(Yie,{open:s,onClose:()=>r(!1),roomId:e}),C.jsx(DpA,{open:g,onClose:()=>o(!1)})]})}const SpA=E.createContext(void 0),Hie=({children:e})=>{const[A,t]=E.useState([]),[i,n]=E.useState(null),{sendGameInvite:g,respondGameInvite:o}=So(),s=NB();xs({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 r=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]),a=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(SpA.Provider,{value:{pendingInvites:A,currentInvite:i,sendInvite:r,acceptInvite:a,declineInvite:I,dismissCurrentInvite:c},children:e})};function wpA(){return E.useContext(SpA)}function kpA({roomId:e,gameMode:A,className:t}){const[i,n]=E.useState(!1),[g,o]=E.useState(null),[s,r]=E.useState(new Set),a=E.useRef(null),I=wpA(),{friends:c}=vd();E.useEffect(()=>{if(!i)return;const h=p=>{p.key==="Escape"&&n(!1)},d=p=>{a.current&&!a.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&&r(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:a,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&&zr.createPortal(Q,document.body)]})}function Ix(e){var Cg,Dg,ng,wo;const{roomName:A,players:t,bankerId:i,currentRollerId:n,meId:g,gameState:o,roomId:s,onOpenDM:r,onOpenSendMoney:a,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(dpA,{players:t,meId:g,className:c,onOpenDM:r,onOpenSendMoney:a});const{handleLeave:S}=SZ(s,g,{autoJoin:!1}),k=Ji(),{onBuyChips:N,busy:G,ready:M,isWeb:w}=kw(),{onHandEnd:b}=qf(),_=al(),{remoteStreams:K,myVideo:J,remoteVideoFlags:T}=_,{proofs:v,reveals:U,verifyFor:x}=rpA(s),{user:q,updateBalance:z}=en(),Z=(()=>{try{return(q==null?void 0:q.isGuest)===!0}catch{return!1}})(),[eA,aA]=E.useState(!1),[sA,pA]=E.useState(!1),[gA,yA]=E.useState({}),{settledAll:fA,playerBalance:RA,mySettledAll:YA,newSettlements:W,openAllMain:$}=ox(s,g),{leaveRoom:L,skillsLeaveRoom:H}=So();o==null||o.betsLocked;const P=E.useCallback(()=>{const fe=o==null?void 0:o.gameMode;if(fe==="poker"){s&&L(s),k("/lobby");return}if(fe==="skills"){s&&H(s),k("/");return}S()},[o,s,L,H,k,S]),tA=E.useCallback(fe=>()=>{try{Xt("Light")}catch{}try{}catch{}fe()},[]),iA=E.useMemo(()=>{var fe;return(fe=t.find(Pe=>Pe.id===g))==null?void 0:fe.balance},[t,g]),oA=o==null?void 0:o.gameMode,CA=(()=>{const fe=typeof RA=="number"?RA:void 0,Pe=typeof iA=="number"?iA:void 0;if(oA==="craps")return Pe??fe??0;if(oA==="poker"){const OA=fe??Pe??0,_e=(Array.isArray(o==null?void 0:o.pokerSeats)?o.pokerSeats:[]).find(rA=>rA.playerId===g),xe=_e&&typeof _e.stack=="number"?_e.stack:0;return OA+xe}return fe??Pe??0})(),[cA,_A]=E.useState(CA),[uA,X]=E.useState(!1),O=E.useRef(CA),lA=E.useRef(new Set),wA=E.useRef({}),xA=E.useRef(0),HA=5e3,zA=E.useRef({}),[ne,ye]=E.useState(0);E.useEffect(()=>{Date.now()-xA.current<HA||O.current!==CA&&(O.current=CA,_A(CA))},[CA]);const Ee=E.useMemo(()=>{if((o==null?void 0:o.gameMode)!=="poker")return null;const Pe=Array.isArray(o==null?void 0:o.pokerSeats)?o.pokerSeats:[],OA=new Set;for(const XA of Pe)XA!=null&&XA.playerId&&OA.add(String(XA.playerId));return OA},[o==null?void 0:o.gameMode,o==null?void 0:o.pokerSeats]),NA=E.useCallback(fe=>{const Pe=o==null?void 0:o.gameMode;if(Pe==="poker"){const OA=typeof fe.balance=="number"?fe.balance:0,_e=(Array.isArray(o==null?void 0:o.pokerSeats)?o.pokerSeats:[]).find(rA=>rA.playerId===fe.id);if(_e&&typeof _e.stack=="number")return Math.max(0,_e.stack);const xe=typeof(_e==null?void 0:_e.committed)=="number"?_e.committed:0;return Math.max(0,OA-xe)}return Pe==="craps"&&fe.id!==g&&typeof zA.current[fe.id]=="number"?zA.current[fe.id]:fe.id===g?Number(cA??0):typeof fe.balance=="number"?fe.balance:0},[o,g,cA,ne]),QA=E.useMemo(()=>{var OA;const fe=o==null?void 0:o.gameMode;return fe==="poker"?Ee?t.filter(XA=>Ee.has(XA.id)):t:fe==="craps"||fe==="skills"||(o==null?void 0:o.mode)==="single"||((OA=e.roomId)==null?void 0:OA.includes("single"))?t:t.filter(XA=>{var xe,rA;return XA.id===g||(xe=XA.id)!=null&&xe.startsWith("bot_")||(rA=XA.id)!=null&&rA.startsWith("craps_bot_")?!0:NA(XA)>0})},[t,Ee,o==null?void 0:o.gameMode,o==null?void 0:o.mode,g,NA,e.roomId]),PA=E.useMemo(()=>Object.fromEntries(QA.map(fe=>[fe.id,fe])),[QA]),VA=E.useRef(void 0),KA=E.useRef(new Map);E.useEffect(()=>{if((o==null?void 0:o.gameMode)!=="poker")return;const Pe=e.roomId||"unknown";VA.current!==Pe&&(VA.current=Pe,KA.current=new Map);const OA=KA.current;let XA=-1;OA.forEach(_e=>{_e>XA&&(XA=_e)});for(const _e of QA)OA.has(_e.id)||(XA+=1,OA.set(_e.id,XA))},[QA,e.roomId,o==null?void 0:o.gameMode]);const Ie=E.useMemo(()=>{const fe=o==null?void 0:o.gameMode;if(fe==="poker"){const XA=KA.current;return QA.map(_e=>_e.id).slice().sort((_e,xe)=>(XA.get(_e)??0)-(XA.get(xe)??0))}if(fe==="skills")return QA.map(XA=>XA.id);const Pe=Array.isArray(o==null?void 0:o.turnOrder)?o.turnOrder:[],OA=(()=>{if(!Pe.length)return QA.map(rA=>rA.id);const XA=new Set(QA.map(rA=>rA.id)),_e=Pe.filter(rA=>XA.has(rA)),xe=QA.map(rA=>rA.id).filter(rA=>!_e.includes(rA));return[..._e,...xe]})();if(e.localFirst&&g){const XA=OA.indexOf(g);if(XA>0)return[...OA.slice(XA),...OA.slice(0,XA)]}return OA},[QA,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 fe of W){if(!fe||fe.roundSeq!==DA||lA.current.has(fe.id))continue;const Pe={...fe,type:fe.type||(fe.predicate||fe.subjectId?"SIDE":"MAIN")},OA=RZ(Pe,g);if(!OA.outcome)continue;lA.current.add(fe.id);let XA=0,_e=0;try{const Fe=lf(fe,g);Fe&&(Fe.myResult==="WIN"?XA=Fe.myPayout||0:Fe.myResult==="LOSE"&&(_e=fe.amount||0))}catch{}const xe=XA>0?XA:_e>0?-_e:0;if(xe===0)continue;const rA=OA.needsAnimation?2e3:0,pe=window.setTimeout(()=>{_A(Fe=>Fe+xe),X(!0),window.setTimeout(()=>X(!1),2e3),delete wA.current[fe.id]},rA);wA.current[fe.id]=pe}return()=>{Object.values(wA.current).forEach(fe=>window.clearTimeout(fe)),wA.current={}}}},[W,DA,g]);const IA=E.useMemo(()=>typeof o.roundSeq=="number"?(o.turnHistory??[]).filter(fe=>fe.roundSeq===o.roundSeq):o.turnHistory??[],[o.turnHistory,o.roundSeq]),[EA,j]=E.useState(!1),[dA,hA]=E.useState(0),[UA,TA]=E.useState(void 0);E.useEffect(()=>{if(!(!W||!W.length||(o==null?void 0:o.gameMode)==="poker"))for(const Pe of W){if(!Pe||Pe.roundSeq!==DA||Pe.playerId!==g)continue;const OA=lf(Pe,g);if(OA&&OA.myResult==="LOSE"){const XA=Number(Pe.amount||0);hA(XA>0?XA:0),TA(void 0),j(!0);break}}},[W,DA,g,o]);const[se,Ne]=E.useState(null),[Ke,At]=E.useState(null),[ni,Ge]=E.useState(!1),[st,Rt]=E.useState(!1),Et=E.useRef(null),[_t,vt]=E.useState(new Map),{sendVisibilityChange:xt}=So();E.useEffect(()=>{Ne(null)},[s]);const ee=E.useCallback(async()=>{if(s)try{const fe=await hie(s);fe&&Ne(fe)}catch{}},[s]),Oe=E.useCallback(async()=>{if(s)try{Ge(!0);const fe=await pie(s);At(fe||null)}catch{At(null)}finally{Ge(!1)}},[s]);E.useEffect(()=>{st&&(o==null?void 0:o.gameMode)==="craps"&&ee()},[st,o,ee]),E.useEffect(()=>{if(!s||!v||typeof v!="object")return;let fe=!1;const Pe=DA,OA=`${Pe}:`,XA=Object.keys(v||{}).filter(_e=>_e.startsWith(OA));if(XA.length)return XA.forEach(_e=>{const xe=_e.split(":")[1];xe&&(async()=>{try{const rA=await x(xe,Pe);fe||yA(pe=>pe[_e]===rA?pe:{...pe,[_e]:rA})}catch{fe||yA(rA=>rA[_e]==="unverifiable"?rA:{...rA,[_e]:"unverifiable"})}})()}),()=>{fe=!0}},[v,U,x,s,DA]);const We=E.useMemo(()=>{var fe;if(!i)return null;for(let Pe=IA.length-1;Pe>=0;Pe--){const OA=IA[Pe];if(OA.playerId===i&&Array.isArray(OA.result)&&OA.result.length===3){const XA=OA.result;if(pM(XA)!=="nothing")return XA}}if((fe=o.bankRoll)!=null&&fe.raw&&Array.isArray(o.bankRoll.raw)&&o.bankRoll.raw.length===3){const Pe=o.bankRoll.raw;if(pM(Pe)!=="nothing")return Pe}return null},[i,IA,o.bankRoll]),{revealedPlayers:pt,revealTimesRef:kA}=Rie(IA,i,o,DA),{show:oe,roll:ae,activeKind:$A,hasActive:nA,onIdle:vA,info:FA}=Fa(),te=E.useRef(null),bA=E.useRef(null);E.useEffect(()=>{if(!(oA!=="craps"&&oA!=="poker"&&oA!=="skills")||!We||We.length!==3||MZ(We)!=="point")return;const Pe={};for(const xe of We)Pe[xe]=(Pe[xe]||0)+1;const OA=Object.keys(Pe).map(Number).find(xe=>Pe[xe]===1);if(OA==null)return;const XA=`${DA}:${OA}`;if(te.current===XA)return;bA.current&&window.clearTimeout(bA.current);const _e=[...We];bA.current=window.setTimeout(()=>{var $e;if(bA.current=null,te.current===XA)return;te.current=XA;const xe=i&&(($e=t.find(Gt=>Gt.id===i))==null?void 0:$e.name),rA=["","⚀","⚁","⚂","⚃","⚄","⚅"],pe=Gt=>Gt.slice().sort((Ot,qt)=>Ot-qt).map(Ot=>rA[Ot]||String(Ot)).join(""),Fe=`${xe||"Banker"}'s Point`,je=`${pe(_e)} — point is ${OA}`;ae(Fe,je)},Vo.revealFlashPostDelayMs)},[We,DA,oA,i,t,ae]);const De=E.useRef(new Set),jA=E.useRef(!1);E.useEffect(()=>{if(!jA.current){const fe=new Set(t.map(Pe=>String(Pe.id)));De.current=fe,jA.current=!0}},[t]);const me=E.useMemo(()=>{const fe=new Map;try{const Pe=Array.isArray($)?$:[];for(const OA of Pe){const XA=OA==null?void 0:OA.roundSeq;typeof XA=="number"&&XA!==DA||OA&&OA.playerId&&typeof OA.amount=="number"&&fe.set(OA.playerId,OA.amount)}}catch{}return fe},[$,DA]),le=E.useRef({});E.useRef(0),E.useRef(null),xs({onOtherPlayerJoined:({room:fe})=>{try{if(!fe||!Array.isArray(fe.players))return;const Pe=De.current,OA=new Set(fe.players.map(_e=>String(_e.id)));if(!jA.current){De.current=OA,jA.current=!0;return}const XA=[...OA].filter(_e=>!Pe.has(_e));if(XA.length>0){const _e=new Map(fe.players.map(xe=>[String(xe.id),xe]));for(const xe of XA){if(xe===g)continue;const rA=_e.get(xe),pe=(rA==null?void 0:rA.name)||(rA==null?void 0:rA.email)||xe;try{FA&&FA("Player Joined",String(pe))}catch{}}}De.current=OA}catch{}},onOtherLeft:({room:fe})=>{try{if(!fe||!Array.isArray(fe.players))return;const Pe=De.current,OA=new Set(fe.players.map(_e=>String(_e.id)));if(!jA.current){De.current=OA,jA.current=!0;return}const XA=[...Pe].filter(_e=>!OA.has(_e));if(XA.length>0){const _e=new Map;try{t.forEach(xe=>_e.set(String(xe.id),xe.name||xe.email||String(xe.id)))}catch{}for(const xe of XA){if(xe===g)continue;const rA=_e.get(xe)||xe;try{FA&&FA("Player Left",String(rA))}catch{}}}De.current=OA}catch{}},onPlayerBalanceUpdated:({playerId:fe,balance:Pe})=>{if(fe!==g){zA.current[fe]=Pe,ye(OA=>OA+1);return}xA.current=Date.now(),Object.values(wA.current).forEach(OA=>window.clearTimeout(OA)),wA.current={},lA.current.clear(),O.current=Pe,_A(Pe),z(Pe),X(!0),window.setTimeout(()=>X(!1),2e3)},onCrapsBetResults:fe=>{!fe||fe.roomId!==s||(Et.current&&window.clearTimeout(Et.current),Et.current=window.setTimeout(()=>{ee()},350))},onCrapsBetsUpdate:fe=>{!fe||fe.roomId!==s||(Et.current&&window.clearTimeout(Et.current),Et.current=window.setTimeout(()=>{ee()},250))},onCrapsPointSet:fe=>{!fe||fe.roomId!==s||(Et.current&&window.clearTimeout(Et.current),Et.current=window.setTimeout(()=>{ee()},300))},onCrapsPointMade:fe=>{!fe||fe.roomId!==s||(Et.current&&window.clearTimeout(Et.current),Et.current=window.setTimeout(()=>{ee()},300))},onPlayerPresenceUpdate:fe=>{if(!fe||fe.roomId!==s)return;const{playerId:Pe,status:OA}=fe;!Pe||!OA||vt(XA=>{const _e=new Map(XA);return _e.set(Pe,OA),_e})}}),E.useEffect(()=>()=>{Et.current&&window.clearTimeout(Et.current)},[]),E.useEffect(()=>{if(!s)return;const fe=()=>{const OA=!document.hidden;xt(s,OA)};xt(s,!document.hidden),document.addEventListener("visibilitychange",fe);let Pe=null;return(async()=>{try{const{App:OA}=await li(async()=>{const{App:XA}=await Promise.resolve().then(()=>UR);return{App:XA}},void 0);Pe=await OA.addListener("appStateChange",XA=>{xt(s,XA.isActive)})}catch{}})(),()=>{document.removeEventListener("visibilitychange",fe),Pe&&typeof Pe.remove=="function"&&Pe.remove()}},[s,xt]);const qA=E.useCallback(fe=>{let Pe=le.current[fe];if(Pe&&Pe.getAttribute("data-player-id")!==fe&&(Pe=null),!Pe)try{const _e=window.CSS&&typeof window.CSS.escape=="function"?window.CSS.escape(fe):String(fe).replace(/[^a-zA-Z0-9_-]/g,"_");Pe=document.querySelector(`.players.players--avatars [data-player-id="${_e}"]`)}catch{}if(!Pe)return null;const OA=Pe.querySelector(".avatar-ring");let XA=null;if(OA)XA=OA.getBoundingClientRect();else try{XA=Pe.getBoundingClientRect()}catch{}return!XA||XA.width===0&&XA.height===0?null:{x:XA.left+XA.width/2,y:XA.top+XA.height/2}},[]),WA=E.useRef(IA.length),Se=E.useRef(null),Qe=E.useRef(null),ce=E.useRef(null);E.useEffect(()=>{WA.current=IA.length},[DA]),E.useEffect(()=>{ce.current=null},[DA]);const{forUserId:Ve,anchorRect:Dt,anchorEl:Mt,openFor:ct,close:gt}=NZ(),et=(fe,Pe)=>{!Pe||fe===g||ct(fe,Pe)},Li=()=>gt(),Ri=E.useMemo(()=>{const fe=new Map;for(const Pe of t)fe.set(Pe.id,Pe.name||Pe.email||Pe.id);for(const Pe of fA){const OA=Pe==null?void 0:Pe.playerId,XA=Pe==null?void 0:Pe.bankerId;OA&&!fe.has(OA)&&fe.set(OA,OA),XA&&!fe.has(XA)&&fe.set(XA,XA)}return fe},[t,fA]),gi=E.useCallback(fe=>Ri.get(fe||"")||fe||"Unknown",[Ri]),Jt=E.useCallback(fe=>gi(fe),[gi]),jt=E.useMemo(()=>{const fe=new Map;for(const Pe of t)Pe.avatarUrl&&fe.set(Pe.id,Pe.avatarUrl);return fe},[t]),Ci=E.useCallback(fe=>jt.get(fe),[jt]),Pi=E.useCallback(fe=>FtA(fe,IA,i,o.bankRoll,We),[IA,i,o.bankRoll,We]);xie({newSettlements:W,roundSeqNow:DA,myId:g,bankerDice:We,getPlayerName:Jt,getPlayerAvatarUrl:Ci,getPlayerDice:Pi,getRevealTime:fe=>{var Pe,OA;return(OA=(Pe=kA==null?void 0:kA.current)==null?void 0:Pe.get)==null?void 0:OA.call(Pe,fe)},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(XA=>XA.id.startsWith("bot_")&&(XA.balance??0)>0).length===0)&&setTimeout(async()=>{try{await b()}catch{}},2500))},[W,DA,g,o,b,e.singlePlayer,t]);const pi=(o==null?void 0:o.gameMode)==="cee-lo"||(o==null?void 0:o.gameMode)==="ceeLo"||!(o!=null&&o.gameMode);o==null||o.gameMode;const Ai=E.useCallback(fe=>{var _e,xe;if(!pi)return!0;if(!fe||!(pt.get(fe)===!0))return!1;const OA=(xe=(_e=kA==null?void 0:kA.current)==null?void 0:_e.get)==null?void 0:xe.call(_e,fe);return(typeof OA=="number"?performance.now()-OA:0)>=Vo.diceToChipDelayMs},[pi,pt,kA]),{activeBatch:xi,handleAnimItemComplete:ui,resetForRound:ie}=Jie({newSettlements:W,roundSeqNow:DA,getAvatarCenter:qA,getPlayerName:Jt,myId:g,bankerDice:We,bankerId:i,isPartyReady:Ai});E.useEffect(()=>{ie()},[DA,ie]);const ln=E.useRef(null),Zt=E.useRef(null),lo=E.useMemo(()=>{var Pe;if((o==null?void 0:o.gameMode)==="poker"){const OA=Number((o==null?void 0:o.pokerUiLockedUntilTs)||0),XA=OA>0&&Date.now()<OA,_e=7e3;XA&&ln.current==null&&(ln.current=Date.now());const xe=ln.current||0,rA=xe>0?Date.now()-xe:Number.POSITIVE_INFINITY,pe=XA&&rA<=_e,Fe=Array.isArray(o==null?void 0:o.pokerSeats)?o.pokerSeats:[],je=typeof(o==null?void 0:o.pokerActingSeat)=="number"?o.pokerActingSeat:void 0,$e=typeof je=="number"&&((Pe=Fe.find(Gt=>Gt.seatIndex===je))==null?void 0:Pe.playerId)||null;return pe?Zt.current??$e??null:(Zt.current=$e??null,ln.current=null,$e??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 fe=Qe.current,Pe=lo||void 0;if(!fe||!Pe||ce.current===Pe)return;const OA=le.current[Pe];if(!OA)return;const XA=()=>{try{const _e=fe.getBoundingClientRect(),xe=OA.getBoundingClientRect(),rA=xe.left-_e.left+fe.scrollLeft,pe=Math.max(0,Math.min(rA-fe.clientWidth/2+xe.width/2,fe.scrollWidth-fe.clientWidth));fe.scrollTo({left:pe,behavior:"smooth"}),ce.current=Pe}catch{}};return Se.current&&clearTimeout(Se.current),Se.current=setTimeout(()=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(XA):XA()},100),()=>{Se.current&&(clearTimeout(Se.current),Se.current=null)}},[lo,Ie]);const Hg=e.campaignProgress?e.campaignProgress.isMaxLevel?100:e.campaignProgress.total>0?Math.min(100,e.campaignProgress.current/e.campaignProgress.total*100):0:0,xo=!!(e.campaignProgress&&e.singlePlayer&&!sA);return E.useEffect(()=>{pA(!1)},[(Cg=e.campaignProgress)==null?void 0:Cg.level,(Dg=e.campaignProgress)==null?void 0:Dg.current,(ng=e.campaignProgress)==null?void 0:ng.total,(wo=e.campaignProgress)==null?void 0:wo.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($C,{className:"icon",style:{color:"var(--gold, #caa64d)"}})}),(()=>{const fe=G||!M||!1,Pe=fe?"Balance (login to Buy 1000 Z Credits)":w?"Buy 1000 Z Credits":"Buy 1000 Z Credits (App Store / Play)",OA=fe?"Login to Buy 1000 Z Credits":w?"Buy 1000 Z Credits":"Buy 1000 Z Credits (App Store / Play)",XA=tA(()=>{if(Z){aA(!0);return}N()});return C.jsx("a",{className:"gold-link balance-display"+(fe?" disabled":"")+(uA?" balance--pulse":""),role:"button","aria-label":Pe,title:OA,"aria-disabled":fe||void 0,onClick:XA,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 fe=o==null?void 0:o.gameMode;fe==="craps"?(ee(),Rt(!0)):fe==="poker"?e.onOpenHistory&&e.onOpenHistory():Oe().then(()=>Rt(!0))}),"aria-haspopup":"dialog","aria-controls":"my-bets-modal",children:"History"}),s&&!Z&&!e.singlePlayer&&C.jsx(kpA,{roomId:s,gameMode:(o==null?void 0:o.gameMode)||"cee-lo"})]}),C.jsx("div",{className:"header-slot header-slot--right",children:C.jsx(mpA,{roomId:s,leftSlot:D,singlePlayer:e.singlePlayer})})]}),xo&&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:fe=>{fe.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:`${Hg}%`}})})]})]}),xi.length>0&&C.jsxs("div",{style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:1e4},children:[xi.map(fe=>C.jsx(ypA,{anim:fe,onComplete:()=>ui(fe.id)},fe.id)),!1]}),C.jsx("div",{className:"chip-fly-container",children:!y&&C.jsx(WI.ul,{className:"players players--avatars",role:"list",ref:Qe,layout:!0,transition:{type:"spring",stiffness:420,damping:38,mass:.6},children:Ie.map(fe=>{var it;const Pe=(o==null?void 0:o.currentRollerId)??n,OA=PA[fe];if(!OA)return null;const XA=OA.id,_e=[];if((o==null?void 0:o.gameMode)==="poker"){const dt=o,ft=Array.isArray(dt.pokerSeats)?dt.pokerSeats:[],ci=typeof dt.pokerDealerSeat=="number"?dt.pokerDealerSeat:void 0,Hi=ft.find(Wi=>Wi.playerId===XA);if(Hi&&typeof ci=="number"){Hi.seatIndex===ci&&_e.push("D");const Wi=ft.filter(hi=>!!hi.playerId).map(hi=>hi.seatIndex).sort((hi,Bo)=>hi-Bo),Vi=Wi.length;if(Vi>=2){const hi=Wi.indexOf(ci);if(hi!==-1){let Bo,Fn;Vi===2?(Bo=ci,Fn=Wi[(hi+1)%Vi]):(Bo=Wi[(hi+1)%Vi],Fn=Wi[(hi+2)%Vi]),Hi.seatIndex===Bo&&_e.push("SB"),typeof Fn=="number"&&Hi.seatIndex===Fn&&_e.push("BB")}}}}pi&&i&&XA===i&&_e.push("B"),XA===Pe&&!pt.get(XA)&&_e.push("Rolling"),XA===Pe&&_e.push("Shooter");let xe=!1;if((o==null?void 0:o.gameMode)==="poker"){const dt=o,ft=typeof dt.pokerActingSeat=="number"?dt.pokerActingSeat:void 0;typeof ft=="number"&&Array.isArray(dt.pokerSeats)&&(xe=((it=dt.pokerSeats.find(Hi=>Hi.seatIndex===ft))==null?void 0:it.playerId)===XA)}else xe=XA===Pe;let rA=!1;if((o==null?void 0:o.gameMode)==="poker"){const ft=(Array.isArray(o==null?void 0:o.pokerSeats)?o.pokerSeats:[]).find(ci=>ci.playerId===XA);ft&&String(ft.status||"").toLowerCase()==="folded"&&(rA=!0)}const pe=XA===g?J:K[XA],Fe=T[XA]?pe:void 0,je=!B&&pt.get(XA)?FtA(XA,IA,i,o.bankRoll,We):null;let $e=!B&&je&&Array.isArray(je)&&je.length===3&&!je.every(dt=>dt===0)&&pM(je)!=="nothing"?C.jsx(ppA,{dice:je}):null;const Ot=(o.spectators??[]).includes(XA);let qt;if(m)qt=m(OA);else if(Ot)qt=null;else if(pi&&!pt.get(XA)){const dt=me.get(XA);qt=typeof dt=="number"&&dt>0?C.jsxs("span",{className:"player-bet-pill","aria-label":`Bet z${cB.formatMoney(dt,"",0)}`,children:["z",cB.formatMoney(dt,"",0)]}):null}else qt=$e;const ei=(o==null?void 0:o.gameMode)==="poker",Yt=NA(OA),Ce=Number.isFinite(Yt)?Yt:void 0;return C.jsx(kie,{ref:dt=>{le.current[XA]=dt},id:XA,display:OA.name??OA.email??XA,isCurrentRoller:xe,isMe:XA===g,balance:Ce,isSpectating:Ot,folded:rA,tags:_e,stream:Fe,isMuted:XA===g,diceResult:qt,onOpenMenu:(dt,ft)=>et(dt,ft),showMenu:Ve===XA,menuProps:Ve===XA?{targetId:XA,anchorRect:Dt,anchorEl:Mt,onClose:Li,onOpenDM:r,onOpenSendMoney:a,meId:g}:null,forceHideVideo:!T[XA],avatarUrl:OA.avatarUrl,showActingTimerRing:ei,presenceStatus:_t.get(XA)},XA)})})}),st&&C.jsx(mdA,{onClose:()=>Rt(!1),items:Array.isArray(Ke)&&Ke.length>0?Ke:YA,meId:g,nameOf:gi,crapsRollHistory:h,gameMode:o==null?void 0:o.gameMode,crapsLedgerItems:(se||[]).slice().sort((fe,Pe)=>Number(Pe.ts)-Number(fe.ts))}),C.jsx(DpA,{open:eA,onClose:()=>aA(!1),message:"This feature is for logged in users."})]})}const Oie={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 Pie(e){return e.startsWith("place")?`Place ${e.replace("place","")}`:Oie[e]??e}function jie(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 zie(e){return e.outcome==="WIN"?`+z${e.payout}`:e.outcome==="LOSE"?`-z${e.amount}`:"Returned"}function Zie({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:Pie(i.betType)}),C.jsx("b",{className:`craps-roll-result__amount craps-roll-result__amount--${i.outcome.toLowerCase()}`,children:zie(i)})]},`${i.betType}-${i.outcome}-${n}`))})]})}function Wie(e){const{gameState:A,roomId:t,meId:i}=e,{show:n,rollNow:g}=Fa(),{onHandEnd:o}=qf(),s=E.useRef(null),r=E.useRef(new Set),a=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}=MB(),{recentSettlements:y,lastSettlementRoll:m,pointSetEvent:D,pointMadeEvent:S}=spA({roomId:t||null,myPlayerId:i}),k=E.useCallback((N,G,M,w,b)=>{if(s.current===b||r.current.has(b))return;(()=>{s.current=b,r.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||r.current.has(N)||(a.current={key:N,point:D.point},I.current&&clearTimeout(I.current),p&&(I.current=setTimeout(()=>{const G=a.current;if(G){if(r.current.has(G.key)){a.current=null;return}s.current=G.key,r.current.add(G.key);try{W6({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}),a.current=null}},Vo.revealFlashPostDelayMs)))},[D,t,g,n,p]),E.useEffect(()=>{!p||!a.current||(I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{const G=a.current;if(G){if(r.current.has(G.key)){a.current=null;return}s.current=G.key,r.current.add(G.key);try{W6({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}),a.current=null}},Vo.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(r.current.has(N.key)){c.current=null;return}k("win","Point Made!",`${N.point} hit`,1300,N.key);try{$6({sfxVolume:.15,voiceVolume:.55})}catch{}try{window.dispatchEvent(new CustomEvent("craps:point_made",{detail:{point:N.point}}))}catch{}c.current=null}},Vo.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(r.current.has(G.key)){c.current=null;return}k("win","Point Made!",`${G.point} hit`,1300,G.key);try{$6({sfxVolume:.15,voiceVolume:.55})}catch{}try{window.dispatchEvent(new CustomEvent("craps:point_made",{detail:{point:G.point}}))}catch{}c.current=null}},Vo.revealFlashPostDelayMs))},[p,k]),E.useEffect(()=>()=>{I.current&&clearTimeout(I.current),l.current&&clearTimeout(l.current),Q.current&&clearTimeout(Q.current)},[]),E.useEffect(()=>{var CA,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 T=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"),q=w.filter(X=>X.betType==="come"||X.betType==="dontCome"),z=w.filter(X=>X.betType==="atsSmall"||X.betType==="atsTall"||X.betType==="atsAll"),Z=T.some(X=>X.outcome==="WIN"),eA=v.length>0,aA=U.some(X=>X.outcome==="WIN"),sA=x.some(X=>X.outcome==="WIN"),pA=q.some(X=>X.outcome==="WIN"),gA=z.some(X=>X.outcome==="WIN"),yA=z.some(X=>X.outcome==="LOSE"),fA=T.some(X=>X.outcome==="LOSE"),RA=U.some(X=>X.outcome==="LOSE"),YA=x.some(X=>X.outcome==="LOSE"),W=q.some(X=>X.outcome==="LOSE"),$=q.some(X=>X.outcome==="PUSH"),L=!Z&&!fA&&T.some(X=>X.outcome==="PUSH");let H="",P="";d(jie(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),lA=X.map(wA=>wA.betType==="atsAll"?"ALL":wA.betType==="atsSmall"?"SMALL":wA.betType==="atsTall"?"TALL":wA.betType);H=X.length>1?`ATS ${lA.join(" & ")}!`:`ATS ${lA[0]}!`,P=`+${O}`,n({kind:"win",title:H,subtitle:P,duration:2e3});try{window.dispatchEvent(new CustomEvent("craps:ats_win",{detail:{payout:O,bets:lA}}))}catch{}return}if(Z){if(eA&&oA&&i&&iA===i){const O=v.reduce((lA,wA)=>lA+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=T.filter(O=>O.outcome==="WIN").reduce((O,lA)=>O+(lA.payout+lA.amount),0);H="Line Win",P=`+${X}`,n({kind:"win",title:H,subtitle:P,duration:1100});return}if(eA){const X=v.reduce((O,lA)=>O+lA.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,lA)=>O+lA.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":((CA=X[0])==null?void 0:CA.betType)==="big6"?"Big 6 Win":"Big 8 Win",P=`+${O}`,n({kind:"win",title:H,subtitle:P,duration:1e3});return}if(pA){const X=q.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=T.filter(O=>O.outcome==="LOSE").reduce((O,lA)=>O+lA.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,lA)=>O+lA.amount,0);H="Field Lose",P=`-${X}`,n({kind:"lose",title:H,subtitle:P,duration:1e3});return}if(YA){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=q.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(lA=>lA.outcome==="LOSE").reduce((lA,wA)=>lA+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(Ix,{...e,hideDiceResults:!0,className:"craps-player-panel"}),h&&C.jsx(Zie,{summary:h})]})}function Vie(e){return C.jsx(Ix,{...e,headerCommsLeftSlot:void 0})}function Xie({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,r=i<=5,a=i/30*100;return C.jsxs("div",{className:["poker-turn-timer",o?"":"poker-turn-timer--hidden",s?"poker-turn-timer--urgent":"",r?"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:`${a} 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 _Y({state:e,startingShields:A,maxTokens:t}){if(e.eliminated)return C.jsxs("div",{className:"elim-badge elim-badge--eliminated","aria-label":`Eliminated — ${$ie(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 $ie(e){const A=["th","st","nd","rd"],t=e%100;return e+(A[(t-20)%10]||A[t]||A[0])}function UZ(e){const A=E.useMemo(()=>e.headerExtras,[e.headerExtras]),t=E.useMemo(()=>{var I;const r=Array.isArray((I=e.gameState)==null?void 0:I.pokerSeats)?e.gameState.pokerSeats:[],a=new Map;for(const c of r){const l=(c.totalCommitted||0)+(c.committed||0);a.set(c.playerId,l)}return a},[e.gameState]),i=E.useMemo(()=>{var I;const r=Array.isArray((I=e.gameState)==null?void 0:I.pokerSeats)?e.gameState.pokerSeats:[],a=new Set;for(const c of r)c!=null&&c.playerId&&String(c.status||"").toLowerCase()==="folded"&&a.add(c.playerId);return a},[e.gameState]),n=E.useMemo(()=>{const r=new Map,a=Array.isArray(e.revealedHands)?e.revealedHands:[];for(const I of a)I!=null&&I.playerId&&Array.isArray(I.hole)&&I.hole.length===2&&r.set(String(I.playerId),I.hole);return r},[e.revealedHands]),g=E.useMemo(()=>r=>{var B,Q,h,d,p,y,m,D;const a=(B=e.elimConfig)!=null&&B.enabled?(Q=e.elimStates)==null?void 0:Q[r.id]:void 0,I=n.get(r.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]})]}),a&&C.jsx(_Y,{state:a,startingShields:((h=e.elimConfig)==null?void 0:h.startingShields)??3,maxTokens:((d=e.elimConfig)==null?void 0:d.maxTokens)??3})]})}if(i.has(r.id))return C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"poker-avatar__bet","aria-label":"Folded",children:"Folded"}),a&&C.jsx(_Y,{state:a,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(r.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}),a&&C.jsx(_Y,{state:a,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(dpA,{className:"",players:e.players,meId:e.meId,onOpenDM:e.onOpenDM,onOpenSendMoney:e.onOpenSendMoney,renderActionsOverride:r=>g({id:r.id})});const o=E.useMemo(()=>{var c;const r=Array.isArray((c=e.gameState)==null?void 0:c.pokerSeats)?e.gameState.pokerSeats:[],a=new Map,I=new Set;for(const l of r){if(!l||!l.playerId)continue;const B=typeof l.stack=="number"?l.stack:void 0;typeof B=="number"&&a.set(String(l.playerId),B),I.add(String(l.playerId))}return e.players.map(l=>{const B=a.get(String(l.id));return typeof B=="number"?{...l,balance:B}:l})},[e.players]),s=E.useMemo(()=>C.jsx(Xie,{deadlineTs:e.turnDeadlineTs,isActive:!!e.isBettingStreet&&!!e.turnDeadlineTs,showTurnLabel:!!e.isHeroTurn}),[e.turnDeadlineTs,e.isBettingStreet,e.isHeroTurn]);return C.jsx(Ix,{...e,className:"player-panel",players:o,hideDiceResults:!0,disableBankerFlash:!0,hideSideBets:!0,headerExtras:A,headerCommsLeftSlot:s,renderFacesOverride:r=>g(r)})}function _tA(e){var t;const A=((t=e.gameState)==null?void 0:t.gameMode)||"cee-lo";return A==="craps"?C.jsx(Wie,{...e}):A==="poker"?C.jsx(UZ,{...e}):C.jsx(Vie,{...e})}function Ane(){const{remoteStreams:e}=al(),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[r,a]of Object.entries(e)){const I=A.current[r];I&&I.srcObject!==a&&(I.srcObject=a)}(async()=>{for(const r of Object.values(A.current)){if(!r)continue;await n(r)||(o=!0)}i(o)})();for(const r of Object.keys(A.current))if(!e[r]){const a=A.current[r];if(a){try{a.pause()}catch{}a.srcObject=null}delete A.current[r]}},[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 r;console.warn("remote audio error",o,(r=s==null?void 0:s.currentTarget)==null?void 0:r.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 ene="_overlay_d52xd_3",tne="_overlayClosed_d52xd_15",ine="_drawer_d52xd_22",nne="_drawerClosed_d52xd_59",gne="_header_d52xd_72",one="_headerTitle_d52xd_82",sne="_closeBtn_d52xd_91",rne="_body_d52xd_108",ane="_threadList_d52xd_115",Ine="_noPeers_d52xd_132",Cne="_threadBtn_d52xd_140",cne="_threadBtnActive_d52xd_163",lne="_avatar_d52xd_169",Bne="_threadLabel_d52xd_189",Ene="_threadName_d52xd_195",Qne="_threadPreview_d52xd_204",une="_unreadBadge_d52xd_212",dne="_activeThread_d52xd_229",hne="_scroller_d52xd_237",pne="_scrollerEmpty_d52xd_251",fne="_message_d52xd_258",yne="_messageMine_d52xd_275",Dne="_messageContent_d52xd_284",mne="_messageTime_d52xd_297",Sne="_pending_d52xd_308",wne="_error_d52xd_316",kne="_composer_d52xd_324",Mne="_composerInput_d52xd_336",Nne="_composerSend_d52xd_363",Rne="_composerSendDisabled_d52xd_389",cg={overlay:ene,overlayClosed:tne,drawer:ine,drawerClosed:nne,header:gne,headerTitle:one,closeBtn:sne,body:rne,threadList:ane,noPeers:Ine,threadBtn:Cne,threadBtnActive:cne,avatar:lne,threadLabel:Bne,threadName:Ene,threadPreview:Qne,unreadBadge:une,activeThread:dne,scroller:hne,scrollerEmpty:pne,message:fne,messageMine:yne,messageContent:Dne,messageTime:mne,pending:Sne,error:wne,composer:kne,composerInput:Mne,composerSend:Nne,composerSendDisabled:Rne};function Gne(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 bne({open:e,onClose:A,peers:t,initialPeerId:i}){const{user:n}=en(),g=(n==null?void 0:n.id)??(n==null?void 0:n.email)??"",{getDmSummary:o,getDmMessages:s,sendDmMessage:r,markDmRead:a,setActiveDm:I,threads:c,loadDmHistory:l}=jR(),[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(),T=J==null?void 0:J.find(v=>v.unread>0);T?K=T.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,a(B))},[e,B,a]);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[DC(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),a(K)},M=()=>{if(!B)return;const K=h.trim();if(!K)return;r(B,K)&&d("")},w=K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),M())},b=K=>{const J=t.find(T=>T.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:`${cg.overlay} ${e?"":cg.overlayClosed}`}),C.jsxs("aside",{"aria-hidden":!e,role:"dialog","aria-label":"Direct Messages",className:`${cg.drawer} ${e?"":cg.drawerClosed}`,onClick:K=>K.stopPropagation(),children:[C.jsxs("div",{className:cg.header,children:[C.jsx("strong",{className:cg.headerTitle,children:"Messages"}),C.jsx("button",{onClick:A,className:cg.closeBtn,"aria-label":"Close messages",children:"✕"})]}),C.jsxs("div",{className:cg.body,children:[C.jsxs("div",{className:cg.threadList,children:[t.length===0&&C.jsx("div",{className:cg.noPeers,children:"No other players yet."}),t.map(K=>{var x;const J=K.id===B,T=Gne(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:`${cg.threadBtn} ${J?cg.threadBtnActive:""}`,title:b(K.id),children:[C.jsx("div",{className:cg.avatar,"aria-hidden":!0,children:T}),C.jsxs("div",{className:cg.threadLabel,children:[C.jsx("div",{className:cg.threadName,children:b(K.id)}),C.jsx("div",{className:cg.threadPreview,children:U})]}),v>0&&C.jsx("span",{"aria-label":`${v} unread`,className:cg.unreadBadge,children:v>99?"99+":v})]},K.id)})]}),C.jsxs("div",{className:cg.activeThread,children:[C.jsxs("div",{ref:N,className:cg.scroller,children:[!B&&C.jsx("div",{className:cg.scrollerEmpty,children:"Select a conversation to begin."}),B&&D.map(K=>{const J=K.senderId===g,T=new Date(K.ts),v=T.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return C.jsxs("div",{className:`${cg.message} ${J?cg.messageMine:""}`,title:T.toLocaleString(),children:[C.jsx("div",{className:cg.messageContent,children:K.text}),C.jsx("div",{className:cg.messageTime,children:v}),K.pending&&C.jsx("div",{className:cg.pending,children:"sending…"}),K.error&&C.jsx("div",{className:cg.error,children:K.error})]},K.id)})]}),C.jsxs("div",{className:cg.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:cg.composerInput}),C.jsx("button",{onClick:M,disabled:!B||h.trim()==="",className:`${cg.composerSend} ${!B||h.trim()===""?cg.composerSendDisabled:""}`,children:"Send"})]})]})]})]})]})}const Une="/assets/fairness-BcL04fcA.webp";function MpA({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:Une,alt:"Fairness verified",className:"fairness-img"}):t.icon})}function vne({roomId:e,lastRollerId:A,roundSeq:t,className:i,autoHideMs:n}){const{verifyFor:g,lastRoundWithReveal:o,proofs:s,reveals:r}=rpA(e),[a,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"?!!(r!=null&&r[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(a){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(MpA,{state:a}),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 NpA({open:e,onClose:A,title:t,tagline:i,steps:n,primaryLabel:g,persistKey:o="seenOnboardingV1",secondaryLabel:s="Log In",onSecondary:r,targetSelector:a=".home-mode-toggle-row",coachText:I="Pick a game mode"}){const c=Ji(),{user:l,loading:B}=en(),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&&nr.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=a?document.querySelector(a):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,a]);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&&nr.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:r||(()=>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 JtA=["Bones Bot","Stickman","Railbird","High Roller","Side Bet Sam","Mainline Max"];function Cx(){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 Kne={"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"}]},RpA=(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}`},Fne=e=>{const[A,t,i]=e.split("-").map(Number),n=new Date(A,t-1,i);return n.setDate(n.getDate()-1),RpA(n)},GpA=(e,A)=>`community_missions_v1:${e}:${A||"guest"}`,Xb=e=>({dateKey:e,streak:1,lastPlayedDateKey:e,progress:{},completed:{}});function LtA(e,A){const t=RpA();try{const i=window.localStorage.getItem(GpA(e,A));if(!i)return Xb(t);const n=JSON.parse(i);if(n.dateKey===t)return{...Xb(t),...n};const g=n.dateKey===Fne(t)?Math.max(1,(n.streak||1)+1):1;return{...Xb(t),streak:g,lastPlayedDateKey:t}}catch{return Xb(t)}}function _ne(e,A,t){try{window.localStorage.setItem(GpA(e,A),JSON.stringify(t))}catch{}}function Jne(e,A){const t=NB(),i=Kne[e],[n,g]=E.useState(()=>LtA(e,A));E.useEffect(()=>{g(LtA(e,A))},[e,A]),E.useEffect(()=>{_ne(e,A,n)},[e,A,n]);const o=E.useCallback((a,I)=>{g(c=>{let l=!1;const B={...c.progress},Q={...c.completed};for(const h of i){if(h.event!==a||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(a=>{const I=Math.min(a.target,n.progress[a.id]||0);return{id:a.id,label:a.label,target:a.target,progress:I,completed:!!n.completed[a.id]||I>=a.target}}),[i,n.completed,n.progress]),r=s.filter(a=>a.completed).length;return{missions:s,streak:n.streak,completedCount:r,totalCount:s.length}}const xtA=["#ffd700","#ff6b6b","#4fc3f7","#81c784","#ba68c8","#ffb74d","#f06292","#aed581"],Lne=50;function xne(e){const A=xtA[e%xtA.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"],r=s[e%s.length];return C.jsx("span",{className:`lms-confetti__piece lms-confetti__piece--${r}`,style:{left:`${t}%`,animationDelay:`${i}s`,animationDuration:`${n}s`,backgroundColor:A,width:r==="rect"?`${g*.5}px`:`${g}px`,height:`${g}px`,transform:`rotate(${o}deg)`}},e)}function bpA({winnerName:e,bonus:A,isHero:t,onDismiss:i,onPlayAgain:n,playAgainBusy:g}){const[o,s]=E.useState(!1);E.useEffect(()=>{requestAnimationFrame(()=>s(!0))},[]);const r=E.useMemo(()=>Array.from({length:Lne},(a,I)=>xne(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:r}),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:a=>{a.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 Tne=2e3,qne=2500,Yne=400,Hne=1e3,vZ=({show:e,variant:A,onComplete:t,zoomDurationMs:i=Tne,displayMs:n=qne,fadeDurationMs:g=Yne,ariaLabel:o,contained:s=!1})=>{const[r,a]=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),a(!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(Hne,n)),d.current.fade=setTimeout(()=>{B(!0)},n),d.current.complete=setTimeout(()=>{a(!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),a(!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]),!r)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:zr.createPortal(y,document.body)},One=500;function KZ(){const[e,A]=E.useState(null),[t,i]=E.useState(Qs.showCelebrationImages!==!1),n=E.useRef([]),g=E.useRef(null),o=E.useCallback(()=>{if(n.current.length===0){g.current=null,A(null);return}const a=n.current.shift();a&&(g.current=a,A(a))},[]),s=E.useCallback((a,I)=>{if(!t)return;const c={variant:a,...I};if(n.current.push(c),!g.current){const l=n.current.shift();g.current=l,A(l)}},[t]),r=E.useCallback(()=>{g.current=null,A(null),setTimeout(()=>o(),One)},[o]);return E.useEffect(()=>{let a=!0;Wo().then(c=>{a&&i(c.showCelebrationImages!==!1)}).catch(()=>{a&&i(Qs.showCelebrationImages!==!1)});const I=c=>{const l=c.detail;l&&typeof l.showCelebrationImages=="boolean"&&i(l.showCelebrationImages)};return window.addEventListener("app:settings",I),()=>{a=!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:r}}function Pne(e){var a,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=((a=i==null?void 0:i.includes)==null?void 0:a.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 r=((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 r&&g.push({variant:"generic-loss",displayMs:2e3}),{celebrations:g,sevenOut:r,isNatural:o,pointMade:!!s}}const iQ=[{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"}],TtA=E.lazy(()=>li(()=>Promise.resolve().then(()=>Uhe),void 0)),jne="single_player_guest_id";function $R(){var le,qA,WA,Se,Qe,ce,Ve,Dt,Mt,ct,gt,et,Li,Ri,gi,Jt,jt,Ci,Pi,si,pi,Ai,xi,ui,ie,ln,Zt,lo,Hg,xo,Cg,Dg,ng,wo,fe,Pe;const{roomId:e}=uw(),A=Ji(),{user:t,meId:i}=en(),{error:n}=NB();bR();const g=Cx();E.useEffect(()=>(g.acquire(),()=>{g.release()}),[g]),E.useEffect(()=>{const OA=()=>{try{D8()||qn()}catch{}};OA();const XA=["pointerdown","touchstart","mousedown","click","keydown"];return XA.forEach(_e=>{document.addEventListener(_e,OA,{once:!0,capture:!0})}),()=>{XA.forEach(_e=>{document.removeEventListener(_e,OA,{capture:!0})})}},[]);const o=(()=>{var OA;try{return((OA=window.sessionStorage)==null?void 0:OA.getItem(jne))||""}catch{return""}})(),s=i||(t==null?void 0:t.id)||(t==null?void 0:t.email)||o||"",[r,a]=E.useState(0),{rollTrigger:I,resetSpin:c}=MB(),[l,B]=E.useState(0),Q=E.useRef(null),h=SZ(e,s,{autoJoin:!0}),{room:d,joining:p,error:y,lastRollerId:m,deadline:D,serverNow:S,diceSettled:k}=h,N=opA({roomId:e||null,myPlayerId:s,autoJoinOrder:!0}),G=((le=d==null?void 0:d.gameState)==null?void 0:le.gameMode)==="craps"?N.shooterState:null,M=E.useMemo(()=>{var XA;const OA=d==null?void 0:d.gameState;if((OA==null?void 0:OA.gameMode)==="craps"){const _e=((XA=N.lastRoll)==null?void 0:XA.point)??null,xe=_e??OA.crapsPoint??null,rA=G?{...G}:{},pe={...OA,...rA,crapsPoint:xe,lastRoll:N.lastRoll};return pe.crapsPhase=xe?"point":"come-out",pe}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 XA=N.lastRoll;return XA&&Array.isArray(XA.dice)?[XA.dice[0],XA.dice[1],0]:void 0}return h.diceResults},[(qA=d==null?void 0:d.gameState)==null?void 0:qA.gameMode,N.lastRoll,h.diceResults]),b=E.useRef(()=>{}),[_,K]=E.useState(!1),J=E.useCallback(OA=>{b.current=OA.roll,K(XA=>XA===OA.canRoll?XA:OA.canRoll)},[]),T=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)&&!T,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)}}},[_]),q=E.useMemo(()=>{var Fe,je;if(((Fe=d==null?void 0:d.gameState)==null?void 0:Fe.gameMode)!=="craps")return[];const OA=(d==null?void 0:d.players)??[],XA=(G==null?void 0:G.turnOrder)||((je=d==null?void 0:d.gameState)==null?void 0:je.turnOrder)||[];if(!XA.length)return OA;const _e=new Map(OA.map($e=>[$e.id,$e])),xe=new Set(XA),rA=XA.map(($e,Gt)=>{const Ot=_e.get($e);if(Ot)return Ot;const qt=$e.includes("craps_bot_")||$e.includes("bot_");return{id:$e,name:qt?JtA[Gt%JtA.length]||`Bot ${Gt+1}`:"Player",isReady:!0,balance:qt?500:0,avatarUrl:null,isBot:qt}}),pe=OA.filter($e=>!xe.has($e.id)&&!$e.isBot);return[...rA,...pe]},[(WA=d==null?void 0:d.gameState)==null?void 0:WA.gameMode,d==null?void 0:d.players,G==null?void 0:G.turnOrder,(Se=d==null?void 0:d.gameState)==null?void 0:Se.turnOrder]),z=E.useMemo(()=>{var Ot,qt,ei,Yt,Ce;if(!(d!=null&&d.singlePlayer))return;const OA=(Ot=d==null?void 0:d.gameState)==null?void 0:Ot.gameMode;if(OA!=="craps"&&OA!=="cee-lo")return;const XA=OA==="craps"?t==null?void 0:t.spLevelCraps:t==null?void 0:t.spLevelCeelo,_e=Number((d==null?void 0:d.spLevel)??((qt=d==null?void 0:d.gameState)==null?void 0:qt._spLevel)??XA??1),xe=Number.isFinite(_e)&&_e>0?_e:1,rA=new Map;if(OA==="craps")for(const it of q)rA.set(String((it==null?void 0:it.id)??""),it);for(const it of(d==null?void 0:d.players)??[])rA.set(String((it==null?void 0:it.id)??""),it);const pe=(ei=d==null?void 0:d.gameState)==null?void 0:ei._botBalances;for(const[it,dt]of Object.entries(pe??{}))rA.has(it)||rA.set(it,{id:it,isBot:!0,balance:dt});const Fe=Array.from(rA.values()).filter(it=>(it==null?void 0:it.isBot)||String((it==null?void 0:it.id)??"").includes("bot_")),je=Fe.filter(it=>{const dt=pe==null?void 0:pe[String((it==null?void 0:it.id)??"")];return Number(dt??(it==null?void 0:it.balance)??0)<=0}).length,$e=(d==null?void 0:d.levelName)??((Yt=d==null?void 0:d.gameState)==null?void 0:Yt._levelName)??((Ce=iQ.find(it=>it.level===xe))==null?void 0:Ce.name)??`Level ${xe}`,Gt=Fe.length;return{level:xe,levelName:$e,current:je,total:Gt,progressLabel:`${je}/${Gt} bots defeated`,goalLabel:`Defeat every bot to reach Level ${xe+1}`,isMaxLevel:xe>=iQ.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,q,t==null?void 0:t.spLevelCraps,t==null?void 0:t.spLevelCeelo]),{onCrapsShooterTurnEnd:Z,cancelAd:eA}=qf(),aA=E.useRef(null);E.useEffect(()=>{var xe;if(((xe=d==null?void 0:d.gameState)==null?void 0:xe.gameMode)!=="craps")return;const OA=N.lastRoll;if(!OA||aA.current===OA)return;aA.current=OA;const{currentRollerId:XA,nextRollerId:_e}=OA;XA&&_e&&XA!==_e&&Z()},[N.lastRoll,(Qe=d==null?void 0:d.gameState)==null?void 0:Qe.gameMode,Z]);const sA=E.useRef(null),[pA,gA]=E.useState(1),[yA,fA]=E.useState(null),[RA,YA]=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=((ce=d==null?void 0:d.gameState)==null?void 0:ce.phase)==="waiting"&&!I,CA=(((Ve=d==null?void 0:d.gameState)==null?void 0:Ve.gameMode)||"cee-lo")==="cee-lo"&&!!((Dt=d==null?void 0:d.gameState)!=null&&Dt.roundEnded),cA=typeof((Mt=d==null?void 0:d.gameState)==null?void 0:Mt.roundSeq)=="number"?(d==null?void 0:d.gameState).roundSeq:0;E.useEffect(()=>{CA&&P!==cA&&H(cA)},[P,cA,CA]),E.useEffect(()=>{H(null),tA(null)},[e]),E.useEffect(()=>{oA?kL({volume:.0125}):Yu()},[oA]);const _A=E.useCallback(OA=>{$(OA),YA(!0)},[]),uA=E.useCallback(()=>{YA(!1),$(void 0)},[]),X=E.useRef(void 0);E.useEffect(()=>{var XA,_e,xe;const OA=(XA=d==null?void 0:d.gameState)==null?void 0:XA.roundSeq;if(typeof OA=="number"&&X.current!==void 0&&OA!==X.current&&(a(0),(((_e=d==null?void 0:d.gameState)==null?void 0:_e.gameMode)||"cee-lo")==="cee-lo")){const rA=(xe=d==null?void 0:d.gameState)==null?void 0:xe.banker,pe=rA&&s&&rA===s;try{pe||eP({volume:.6})}catch{}}typeof OA=="number"&&(X.current=OA)},[(ct=d==null?void 0:d.gameState)==null?void 0:ct.roundSeq]);const O=Ss(),{joinRoom:lA}=tI(),[wA,xA]=E.useState(!1);E.useCallback(async()=>{if(!wA&&!(!O||!e)){xA(!0);try{if(lA)try{await lA(e)}catch(OA){console.warn("[manualRefresh] joinRoom failed",OA)}}catch(OA){console.warn("[manualRefresh] failed",OA)}finally{xA(!1)}}},[wA,O,e,lA]),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=XA=>{var _e;if(!(!XA||XA.winnerId!==s)){console.log("[game] last man standing (server event)",{myId:s});try{eA()}catch{}ee({winnerId:s}),(_e=j.current)==null||_e.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=XA=>{!XA||XA.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[HA,zA]=E.useState(()=>typeof window>"u"?!1:window.innerWidth>window.innerHeight);E.useEffect(()=>{const OA=()=>zA(window.innerWidth>window.innerHeight);window.addEventListener("resize",OA);const XA=setTimeout(OA,0);return()=>{window.removeEventListener("resize",OA),clearTimeout(XA)}},[]),E.useEffect(()=>{y&&n(y,{title:"Room Error",duration:5e3})},[y,n]);const ne=E.useRef(0),ye=E.useRef(!1),Ee=E.useRef(!1),NA=E.useRef(!1),QA=E.useRef(!1),PA=E.useRef(null),VA=E.useRef(null),[KA,Ie]=E.useState(0),{active:DA,fire:IA,onComplete:EA}=KZ(),j=E.useRef(IA);j.current=IA;const dA=E.useRef(0),hA=E.useRef(null),UA=E.useRef(0),TA=E.useRef(0),se=E.useRef(0),Ne=E.useRef(0),Ke=E.useRef(0),At=["ceelo-noir-win"],ni=["craps-noir-win"],Ge=["loss-ceelo","loss-craps"],st=["loss-craps","loss-ceelo"],Rt=()=>{const OA=At[se.current%At.length];return se.current+=1,OA},Et=()=>{const OA=ni[Ne.current%ni.length];return Ne.current+=1,OA},_t=()=>{const OA=Ge[Ke.current%Ge.length];return Ke.current+=1,OA},vt=()=>{const OA=st[Ke.current%st.length];return Ke.current+=1,OA},[xt,ee]=E.useState(null),[Oe,We]=E.useState(!1),[pt,kA]=E.useState(!1);E.useEffect(()=>{},[s,IA]);const{createRoom:oe}=So(),[ae,$A]=E.useState(),nA=E.useRef(null);E.useEffect(()=>{var xe,rA,pe;const OA=((xe=d==null?void 0:d.gameState)==null?void 0:xe.gameMode)||"cee-lo",XA=(rA=d==null?void 0:d.gameState)==null?void 0:rA.currentRollerId,_e=!!((pe=d==null?void 0:d.gameState)!=null&&pe.roundEnded);if(OA==="cee-lo"){if(_e){$A(void 0),nA.current=null;return}XA&&XA!==nA.current&&(nA.current=XA,$A(Date.now()+3e4))}},[(gt=d==null?void 0:d.gameState)==null?void 0:gt.currentRollerId,(et=d==null?void 0:d.gameState)==null?void 0:et.roundEnded,(Li=d==null?void 0:d.gameState)==null?void 0:Li.gameMode]);const[vA,FA]=E.useState(!1);E.useEffect(()=>{var _e;const OA=(_e=d==null?void 0:d.gameState)==null?void 0:_e.gameMode;if(!OA)return;let XA=!0;return(async()=>{try{const{Preferences:xe}=await li(async()=>{const{Preferences:Fe}=await Promise.resolve().then(()=>Yc);return{Preferences:Fe}},void 0),rA=OA==="craps"?"onb_craps_v1":"onb_ceelo_v1",{value:pe}=await xe.get({key:rA});if(!XA)return;FA(pe!=="1")}catch{if(!XA)return;FA(!0)}})(),()=>{XA=!1}},[(Ri=d==null?void 0:d.gameState)==null?void 0:Ri.gameMode]);const te=E.useCallback(()=>{var XA;const OA=(XA=d==null?void 0:d.gameState)==null?void 0:XA.gameMode;(async()=>{try{const{Preferences:_e}=await li(async()=>{const{Preferences:xe}=await Promise.resolve().then(()=>Yc);return{Preferences:xe}},void 0);await _e.set({key:OA==="craps"?"onb_craps_v1":"onb_ceelo_v1",value:"1"})}catch{}FA(!1)})()},[(gi=d==null?void 0:d.gameState)==null?void 0:gi.gameMode]);E.useEffect(()=>{var Fe;if(((Fe=d==null?void 0:d.gameState)==null?void 0:Fe.gameMode)==="craps"){ye.current=!1,Ee.current=!1;return}const OA=h==null?void 0:h.diceResults;if(!OA||OA.length!==3){ye.current=!1,Ee.current=!1,NA.current=!1,PA.current=null;return}const XA=OA.join(",");if(XA===PA.current)return;PA.current=XA;const _e=[...OA].sort().join(","),xe=_e==="4,5,6",rA=xe||_e==="1,2,3",pe=OA[0]===OA[1]&&OA[1]===OA[2];NA.current=pe,ye.current=rA,Ee.current=xe},[h==null?void 0:h.diceResults,(Jt=d==null?void 0:d.gameState)==null?void 0:Jt.gameMode]),E.useEffect(()=>{var pe,Fe;if(((pe=d==null?void 0:d.gameState)==null?void 0:pe.gameMode)==="craps"){VA.current=null;return}const OA=(Fe=d==null?void 0:d.gameState)==null?void 0:Fe.bankRoll;if(!OA||!Array.isArray(OA.raw)||OA.raw.length!==3){VA.current=null;return}const XA=OA.raw,_e={};for(const je of XA)_e[je]=(_e[je]||0)+1;const xe=Object.keys(_e).map(Number);xe.length===2&&xe.some(je=>_e[je]===1)?VA.current=xe.find(je=>_e[je]===1)||null:VA.current=null},[(jt=d==null?void 0:d.gameState)==null?void 0:jt.bankRoll,(Ci=d==null?void 0:d.gameState)==null?void 0:Ci.gameMode]),E.useEffect(()=>{var qt,ei;if(((qt=d==null?void 0:d.gameState)==null?void 0:qt.gameMode)==="craps"){QA.current=!1;return}const OA=(ei=d==null?void 0:d.gameState)==null?void 0:ei.banker;if(OA&&s&&OA===s){QA.current=!1;return}const _e=VA.current;if(!_e||_e<1){QA.current=!1;return}const xe=h==null?void 0:h.diceResults;if(!xe||xe.length!==3){QA.current=!1;return}const pe=[...xe].sort((Yt,Ce)=>Yt-Ce).join(",")==="4,5,6",Fe={};for(const Yt of xe)Fe[Yt]=(Fe[Yt]||0)+1;const je=Object.keys(Fe).map(Number),$e=je.length===1,Ot=je.length===2&&je.some(Yt=>Fe[Yt]===1)?je.find(Yt=>Fe[Yt]===1):null;QA.current=pe||$e||Ot!==null&&Ot>_e},[h==null?void 0:h.diceResults,d==null?void 0:d.gameState,s,(Pi=d==null?void 0:d.gameState)==null?void 0:Pi.gameMode]),E.useEffect(()=>{var XA;if(!(h!=null&&h.diceSettled))return;const OA=Date.now();if(ye.current||Ee.current||NA.current||QA.current){if(OA-ne.current<800){ye.current=!1,Ee.current=!1,NA.current=!1,QA.current=!1;return}ne.current=OA;const _e=(d==null?void 0:d.singlePlayer)===!0,xe=(XA=d==null?void 0:d.gameState)==null?void 0:XA.banker,rA=xe&&s&&xe===s,pe=m,Fe=pe==null?void 0:pe.startsWith("bot_");!Fe&&(_e||pe&&s&&pe===s||!rA)&&(Ee.current?IA("bang-bang-456",{displayMs:3e3,zoomDurationMs:2500}):NA.current&&IA("trips",{displayMs:2500})),QA.current&&!Fe&&IA("clutch",{displayMs:2500}),ye.current=!1,Ee.current=!1,NA.current=!1,QA.current=!1,Ie(Gt=>Gt+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,IA]),E.useEffect(()=>{var _e;if((((_e=d==null?void 0:d.gameState)==null?void 0:_e.gameMode)||"cee-lo")!=="cee-lo")return;const XA=xe=>{var pe;const rA=(pe=xe.detail)==null?void 0:pe.result;if(rA==="win"){TA.current+=1;const Fe=TA.current;Fe>=5&&Fe%5===0?IA("streak-5",{displayMs:3500}):Fe>=3&&Fe%3===0?IA("streak-3",{displayMs:3e3}):IA(Rt(),{displayMs:2e3})}else rA==="lose"&&(TA.current=0,IA(_t(),{displayMs:2e3}))};return window.addEventListener("ceelo:result",XA),()=>window.removeEventListener("ceelo:result",XA)},[(pi=d==null?void 0:d.gameState)==null?void 0:pi.gameMode,IA]),E.useEffect(()=>{var $e;if((($e=d==null?void 0:d.gameState)==null?void 0:$e.gameMode)!=="craps")return;const OA=N.lastRoll;if(!OA||hA.current===OA)return;hA.current=OA;const{total:XA,point:_e,resolutions:xe,events:rA}=OA,pe=Pne({total:XA,point:_e,events:rA??[],resolutions:xe??{passLineWins:!1,passLineLosses:!1,pushes:!1}});let Fe=null;xe!=null&&xe.passLineWins?(dA.current+=1,dA.current>=5?(Fe="streak-5",dA.current=0):dA.current>=2&&(Fe="hot-streak")):xe!=null&&xe.passLineLosses&&(dA.current=0);const je=pe.celebrations[0];if(je){const Gt=je.variant==="generic-loss"?vt():je.variant;IA(Gt,{displayMs:je.displayMs})}else Fe?IA(Fe,{displayMs:Fe==="streak-5"?3500:3e3}):xe!=null&&xe.passLineWins&&IA(Et(),{displayMs:2e3})},[N.lastRoll,(Ai=d==null?void 0:d.gameState)==null?void 0:Ai.gameMode,IA]),E.useEffect(()=>{var ei;if((((ei=d==null?void 0:d.gameState)==null?void 0:ei.gameMode)||"cee-lo")!=="cee-lo")return;const XA=d==null?void 0:d.gameState,_e=(XA==null?void 0:XA.roundSeq)??0,xe=(XA==null?void 0:XA.turnHistory)??[],rA=xe.filter(Yt=>Yt.roundSeq===_e),pe=rA.find(Yt=>Yt.playerId===s),Fe=rA.filter(Yt=>Yt.playerId!==s);if(console.log("[sweep-check]",{roundEnded:XA==null?void 0:XA.roundEnded,roundSeq:_e,lastSweepSeq:UA.current,banker:XA==null?void 0:XA.banker,myId:s,bankerMatch:(XA==null?void 0:XA.banker)===s,historyLen:xe.length,roundEntryCount:rA.length,bankerEntry:pe?{rank:pe.rank,playerId:pe.playerId}:null,challengerCount:Fe.length,challengers:Fe.map(Yt=>{var Ce;return{playerId:(Ce=Yt.playerId)==null?void 0:Ce.slice(0,8),rank:Yt.rank}}),allLost:pe?Fe.every(Yt=>Yt.rank<pe.rank):!1}),!(XA!=null&&XA.roundEnded))return;const je=XA.roundSeq??0;if(je<=UA.current)return;const $e=XA.banker;if(!$e||$e!==s)return;const Gt=rA.find(Yt=>Yt.playerId===s),Ot=rA.filter(Yt=>Yt.playerId!==s);!Gt||Ot.length<2||!Ot.every(Yt=>Yt.rank<Gt.rank)||(UA.current=je,console.log("[sweep-check] 🎉 FIRING ceelo-sweep celebration",{roundSeq:je}),IA("ceelo-sweep",{displayMs:3e3}))},[(xi=d==null?void 0:d.gameState)==null?void 0:xi.roundEnded,(ui=d==null?void 0:d.gameState)==null?void 0:ui.roundSeq,(ie=d==null?void 0:d.gameState)==null?void 0:ie.gameMode,s,IA]),E.useEffect(()=>{var _e;if(((_e=d==null?void 0:d.gameState)==null?void 0:_e.gameMode)!=="craps")return;const OA=()=>{IA(Et(),{displayMs:2e3})},XA=()=>{IA("craps-big-win",{displayMs:3500})};return window.addEventListener("craps:place_win",OA),window.addEventListener("craps:ats_win",XA),()=>{window.removeEventListener("craps:place_win",OA),window.removeEventListener("craps:ats_win",XA)}},[(ln=d==null?void 0:d.gameState)==null?void 0:ln.gameMode,IA]);const bA=Jne(((Zt=d==null?void 0:d.gameState)==null?void 0:Zt.gameMode)==="craps"?"craps":"cee-lo",s);if(p)return C.jsxs("div",{className:"HomeScreen theme-casino home-fixed-root",children:[C.jsx(Zr,{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(Zr,{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 De=((lo=d.gameState)==null?void 0:lo.gameMode)==="craps",jA=((Hg=d.gameState)==null?void 0:Hg.gameMode)!=="craps";return C.jsxs(zne,{className:De?"mode-craps":jA?"mode-ceelo":void 0,bgShakeTrigger:KA,children:[C.jsx(Zr,{className:"page-gameroom"}),C.jsx(nie,{}),C.jsx(NpA,{open:vA,onClose:te,title:De?"Craps":"Cee‑Lo",tagline:De?"Place your bets and roll the point.":"Banker vs challengers. Roll to win.",steps:De?["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:De?"onb_craps_v1":"onb_ceelo_v1"}),C.jsxs("div",{className:"room-grid-fit",style:!HA&&yA&&!De?{height:yA}:void 0,children:[C.jsx("div",{className:"fairness-container",children:C.jsx(vne,{roomId:e,lastRollerId:m,roundSeq:(xo=d==null?void 0:d.gameState)==null?void 0:xo.roundSeq,autoHideMs:De?3e3:void 0})}),C.jsxs("div",{ref:sA,className:"room-grid"+(De?" 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(vZ,{show:!0,contained:!0,variant:DA.variant,displayMs:DA.displayMs,zoomDurationMs:DA.zoomDurationMs,fadeDurationMs:DA.fadeDurationMs,ariaLabel:DA.ariaLabel,onComplete:EA}),De?C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"players-row",children:C.jsx(_tA,{className:"PlayerPanel",roomId:e,roomName:d.name,players:q,bankerId:(Cg=d.gameState)==null?void 0:Cg.banker,currentRollerId:(Dg=d.gameState)==null?void 0:Dg.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(TtA,{isWaiting:oA,rollTrigger:I,results:w,preRollTrigger:r,gameMode:(ng=d.gameState)==null?void 0:ng.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(_e=>_e.id===s),XA=(OA==null?void 0:OA.balance)??(t==null?void 0:t.balance)??1e3;return C.jsx(iie,{meId:s,balance:XA,onChargeChange:B,onRollAffordanceChange:J})})()]})]}):C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"players-row",children:C.jsx(_tA,{className:"player-panel",roomId:e,roomName:d.name,players:d.gameState.turnOrder.map(OA=>d.players.find(XA=>XA.id===OA)).filter(OA=>!!OA),bankerId:(wo=d.gameState)==null?void 0:wo.banker,currentRollerId:(fe=d.gameState)==null?void 0:fe.currentRollerId,meId:s,gameState:M,lastRollerId:m,onOpenDM:_A,onOpenSendMoney:()=>{},singlePlayer:d==null?void 0:d.singlePlayer,turnDeadlineTs:ae,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(TtA,{isWaiting:oA,rollTrigger:I,results:w,preRollTrigger:r,gameMode:(Pe=d.gameState)==null?void 0:Pe.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(SXA,{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(Iie,{roomId:e,meId:s,bankerId:d.gameState.banker,players:d.players,gameState:M,gameplay:h})})]})]})]})]}),C.jsx(Ane,{}),C.jsx(bne,{open:RA,onClose:uA,peers:iA,initialPeerId:W}),xt&&C.jsx(bpA,{winnerName:(()=>{const OA=((d==null?void 0:d.players)??[]).find(XA=>XA.id===xt.winnerId);return(OA==null?void 0:OA.name)||"You"})(),bonus:0,isHero:!0,onDismiss:()=>{ee(null),A("/lobby")},playAgainBusy:Oe,onPlayAgain:async()=>{var OA,XA,_e;if(!Oe){try{const{hapticClick:xe}=await li(async()=>{const{hapticClick:rA}=await Promise.resolve().then(()=>bP);return{hapticClick:rA}},void 0);xe("Medium")}catch{}We(!0);try{const{loadSettings:xe}=await li(async()=>{const{loadSettings:Ot}=await Promise.resolve().then(()=>PcA);return{loadSettings:Ot}},void 0),rA=await xe(),pe=rA.botDifficultyLevel&&rA.botDifficultyLevel>=1&&rA.botDifficultyLevel<=9?rA.botDifficultyLevel:void 0,Fe=((OA=d==null?void 0:d.gameState)==null?void 0:OA.gameMode)||"cee-lo",je=await oe({name:"Single Player Room",singlePlayer:!0,gameMode:Fe,botLevel:pe}),$e=(je==null?void 0:je.room)??((XA=je==null?void 0:je.data)==null?void 0:XA.room)??null,Gt=($e==null?void 0:$e.roomId)??($e==null?void 0:$e.id)??(je==null?void 0:je.roomId)??((_e=je==null?void 0:je.data)==null?void 0:_e.roomId);Gt?(ee(null),A(`/room/${Gt}`,{replace:!0})):(console.warn("[game:play_again] no room id in response",je),We(!1))}catch(xe){console.error("[game:play_again] error",xe),We(!1)}}}}),pt&&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 zne({children:e,className:A,bgShakeTrigger:t}){const i=E.useRef(null),n=E.useRef(!0),{showAnimations:g}=GZ();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 Zne(e=3e4){const{friends:A}=vd(),{getOnlineFriends:t}=So(),[i,n]=E.useState(new Set),[g,o]=E.useState(!0),s=E.useCallback(async()=>{try{const a=await t();a!=null&&a.ok&&Array.isArray(a.online)&&n(new Set(a.online))}catch{}o(!1)},[t]);return E.useEffect(()=>{s();const a=setInterval(s,e);return()=>clearInterval(a)},[s,e]),E.useEffect(()=>{s()},[A.length,s]),{onlineFriends:A.filter(a=>i.has(a.id)).map(a=>({...a,isOnline:!0})),loading:g,refresh:s}}function Wne({gameMode:e}){const{onlineFriends:A,loading:t}=Zne(),{user:i}=en();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(Vne,{friend:n,gameMode:e},n.id))})]})}function Vne({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 $b="theme-light",AU="theme-dark";function eU(e){const A=document.documentElement,t=document.body;e==="light"?(A.classList.add($b),A.classList.remove(AU),t.classList.add($b),t.classList.remove(AU)):(A.classList.add(AU),A.classList.remove($b),t.classList.add(AU),t.classList.remove($b))}function UpA(){const[e,A]=E.useState(!1),[t,i]=E.useState("dark");E.useEffect(()=>{let o=!0;return(async()=>{try{const r=(await Wo()).theme??"dark";o&&(i(r),eU(r),A(!0))}catch{o&&(eU("dark"),A(!0))}})(),()=>{o=!1}},[]),E.useEffect(()=>{e&&eU(t)},[t,e]);const n=E.useCallback(async o=>{i(o),eU(o);try{const s=await Wo(),r={...Qs,...s,theme:o};await _E(r)}catch{}},[]),g=E.useCallback(async()=>{await n(t==="dark"?"light":"dark")},[t,n]);return{ready:e,theme:t,setTheme:n,toggleTheme:g}}const Xne="/assets/ceelo-icon-DBUGq3gk.webp",$ne="/assets/craps-icon-Cxbu5IDi.webp",Age="/assets/poker-icon-D9lS6jix.webp",ege="/assets/skills-icon-BWMGnrDl.webp",tge="/assets/zentara-icon-CtcCkOmF.webp";function ige(){const e=Ss(),A=Ji(),{user:t}=en(),{friends:i,friendRequests:n,blockedUsers:g,addFriend:o}=vd(),[s,r]=E.useState(""),[a,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(Kt.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=>r(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}),a.length>0&&C.jsx("ul",{className:"friend-search-results",children:a.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&&a.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 Yf(){const e=Ji(),{user:A,refreshUser:t,logout:i}=en(),{updateProfile:n}=So(),{membershipModalOpen:g,setMembershipModalOpen:o}=bR(),{isPremium:s}=YBA(),{friends:r,friendRequests:a,blockedUsers:I,refreshSocial:c,isBlocked:l,blockUser:B,unblockUser:Q,removeFriend:h,respondToFriendRequest:d}=vd(),{getUnreadForPeer:p}=jR(),{forUserId:y,anchorRect:m,anchorEl:D,openFor:S,close:k}=NZ(),[N,G]=E.useState(null),[M,w]=E.useState(null),b=E.useCallback((qA,WA,Se,Qe)=>{S(qA,WA),G(Se),w(Qe||null)},[S]),_=E.useCallback(()=>{k(),G(null),w(null)},[k]),[K,J]=E.useState((A==null?void 0:A.name)??""),[T,v]=E.useState((A==null?void 0:A.email)??""),[U,x]=E.useState((A==null?void 0:A.avatarUrl)??""),[q,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,YA]=E.useState(null),[W,$]=E.useState("received"),[L,H]=E.useState("idle"),[P,tA]=E.useState(0),[iA,oA]=E.useState(null),CA=E.useRef(null),{onBuyChips:cA,onGoPremium:_A,onRestore:uA,busy:X,busyChips:O,ready:lA,isWeb:wA,premiumActive:xA,hasPremiumPackage:HA,premiumLabel:zA,premiumSubtitle:ne,premiumDescription:ye,premiumPrice:Ee,premiumInterval:NA}=kw(),[QA,PA]=E.useState(!!(A!=null&&A.botChatDisabled)),[VA,KA]=E.useState((A==null?void 0:A.ceeloBotsPerRoom)??null),[Ie,DA]=E.useState((A==null?void 0:A.crapsBotsPerRoom)??null),[IA,EA]=E.useState((A==null?void 0:A.pokerBotsPerRoom)??null),[j,dA]=E.useState((A==null?void 0:A.sex)??""),[hA,UA]=E.useState((A==null?void 0:A.location)??""),[TA,se]=E.useState((A==null?void 0:A.age)!=null?String(A.age):""),[Ne,Ke]=E.useState((A==null?void 0:A.interests)??""),[At,ni]=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)),KA((A==null?void 0:A.ceeloBotsPerRoom)??null),DA((A==null?void 0:A.crapsBotsPerRoom)??null),EA((A==null?void 0:A.pokerBotsPerRoom)??null),dA((A==null?void 0:A.sex)??""),UA((A==null?void 0:A.location)??""),se((A==null?void 0:A.age)!=null?String(A.age):""),Ke((A==null?void 0:A.interests)??""),ni((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 Ge=E.useCallback(async()=>{z(!0),eA(null);try{const qA={};K!==(A==null?void 0:A.name)&&(qA.name=K),T!==(A==null?void 0:A.email)&&(qA.email=T),U!==(A==null?void 0:A.avatarUrl)&&(qA.avatarUrl=U),typeof QA=="boolean"&&(qA.botChatDisabled=QA);const WA=j.trim()||null;WA!==((A==null?void 0:A.sex)??null)&&(qA.sex=WA);const Se=hA.trim()||null;Se!==((A==null?void 0:A.location)??null)&&(qA.location=Se);const Qe=TA.trim()?Number(TA.trim()):null;Qe!==((A==null?void 0:A.age)??null)&&(qA.age=Qe);const ce=Ne.trim()||null;ce!==((A==null?void 0:A.interests)??null)&&(qA.interests=ce);const Ve=At.trim()||null;Ve!==((A==null?void 0:A.aboutMe)??null)&&(qA.aboutMe=Ve);const Dt=Th||Xq,Mt=Th||vp,ct=Th||Kp;Dt&&VA!==((A==null?void 0:A.ceeloBotsPerRoom)??null)&&(qA.ceeloBotsPerRoom=VA),Mt&&Ie!==((A==null?void 0:A.crapsBotsPerRoom)??null)&&(qA.crapsBotsPerRoom=Ie),ct&&IA!==((A==null?void 0:A.pokerBotsPerRoom)??null)&&(qA.pokerBotsPerRoom=IA);const gt=await n(qA);if(!(gt!=null&&gt.ok))eA((gt==null?void 0:gt.error)||"Failed to save");else{try{await t({force:!0})}catch{}await c()}}catch(qA){eA((qA==null?void 0:qA.message)||"Failed to save")}finally{z(!1)}},[K,T,U,A,n,c,t,VA,Ie,IA,QA,j,hA,TA,Ne,At]),st=E.useCallback(async qA=>{l(qA)?await Q(qA):await B(qA)},[l,B,Q]),Rt=E.useCallback(qA=>{h(qA)},[h]),Et=E.useCallback(qA=>{e(`/messages?peer=${encodeURIComponent(qA)}`)},[e]),_t=E.useCallback(async qA=>{await d(qA.id,"ACCEPT")},[d]);E.useCallback(async qA=>{await d(qA.id,"DECLINE")},[d]);const vt=E.useCallback(async qA=>{sA(!0),gA(null);try{if(qA.size>5242880){gA("File size must be less than 5MB");return}if(!["image/jpeg","image/jpg","image/png","image/webp","image/gif"].includes(qA.type)){gA("File must be a valid image (JPEG, PNG, WebP, or GIF)");return}const Qe=new FormData;Qe.append("avatar",qA);const ce=String(VM??"http://localhost:4000").replace(/\/+$/,"");let Ve={},Dt;try{const et=await Co();et&&(Ve={Authorization:`Bearer ${et}`},Dt=et)}catch{}const Mt=new URL(`${ce}/api/avatar/upload`);Dt&&Mt.searchParams.set("token",Dt);const ct=await fetch(Mt.toString(),{method:"POST",body:Qe,headers:Ve,credentials:"include"});if(!ct.ok){const et=await ct.json().catch(()=>({error:"Upload failed"}));throw new Error(et.error||`Upload failed with status ${ct.status}`)}const gt=await ct.json();gt.avatarUrl&&x(gt.avatarUrl)}catch(WA){console.error("[avatar] upload error:",WA),gA((WA==null?void 0:WA.message)||"Failed to upload avatar")}finally{sA(!1)}},[]),xt=E.useCallback(qA=>{var Se;const WA=(Se=qA.target.files)==null?void 0:Se[0];WA&&vt(WA),CA.current&&(CA.current.value="")},[vt]),ee=E.useCallback(()=>{var Se;if(!((A==null?void 0:A.membershipTier)==="PREMIUM"||s)){try{o(!0)}catch{}return}(Se=CA.current)==null||Se.click()},[A,s,o]),Oe=E.useMemo(()=>{const qA=new Map;for(const WA of r)qA.set(WA.id,WA);for(const WA of I)qA.has(WA.id)||qA.set(WA.id,WA);return qA},[r,I]),We=E.useMemo(()=>a.map(qA=>{const WA=(A==null?void 0:A.id)===qA.toUserId,Se=WA?qA.fromUserId:qA.toUserId;if(!Se)return null;const Qe=(WA?qA.fromUser:qA.toUser)||Oe.get(Se),ce=(Qe==null?void 0:Qe.name)??Se,Ve=(Qe==null?void 0:Qe.avatarUrl)??void 0;return{id:Se,name:ce,avatarUrl:Ve,_req:qA,_incoming:WA}}).filter(Boolean),[a,A==null?void 0:A.id,Oe]),{showAnimations:pt,toggleAnimations:kA,ready:oe}=GZ();UpA();const[ae,$A]=E.useState(Qs.diceColorTheme),[nA,vA]=E.useState(void 0),[FA,te]=E.useState(Qs.zentaraBotCount??1);E.useEffect(()=>{(async()=>{try{const qA=await Wo();$A(qA.diceColorTheme??Qs.diceColorTheme),vA(qA.botDifficultyLevel),te(qA.zentaraBotCount??Qs.zentaraBotCount??1)}catch{$A(Qs.diceColorTheme)}})()},[]);const bA=E.useCallback(async qA=>{try{const WA=await Wo(),Se={...Qs,...WA,botDifficultyLevel:qA};await _E(Se),vA(qA)}catch{}},[]),De=E.useCallback(async qA=>{const WA=Math.max(1,Math.min(5,qA));try{const Se=await Wo(),Qe={...Qs,...Se,zentaraBotCount:WA};await _E(Qe),te(WA)}catch{}},[]),jA=E.useCallback(async qA=>{try{const WA=await Wo(),Se={...Qs,...WA,diceColorTheme:qA};await _E(Se),$A(qA)}catch{}},[]),me=E.useCallback(()=>o(!1),[o]);E.useEffect(()=>{t()},[]);const le=E.useCallback(async()=>{try{if(YA(null),!window.confirm("Are you sure you want to permanently delete your account? This action cannot be undone."))return;const WA=String(VM??"http://localhost:4000").replace(/\/+$/,"");let Se;try{const ce=await Co();ce&&(Se={Authorization:`Bearer ${ce}`})}catch{}const Qe=await fetch(`${WA}/api/account`,{method:"DELETE",credentials:"include",headers:Se});if(!Qe.ok){const ce=await Qe.json().catch(()=>({error:"Deletion failed"}));throw new Error(ce.error||`Failed with status ${Qe.status}`)}console.log("[account-delete] account deleted successfully",Qe)}catch(qA){YA((qA==null?void 0:qA.message)||"Failed to delete account")}finally{i()}},[e]);return C.jsxs("div",{className:`${_c?"theme-zentara":"theme-casino"} home-fixed-root add-chips`,children:[C.jsx(Zr,{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{Xt("Light")}catch{}history.back()},children:[C.jsx($C,{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(Wne,{}),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:CA,type:"file",accept:"image/jpeg,image/jpg,image/png,image/webp,image/gif",onChange:xt,disabled:aA,style:{display:"none"}}),C.jsx("button",{className:"profile-avatar-upload-btn","data-no-global-haptic":!0,onClick:()=>{try{Xt("Light")}catch{}ee()},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{Xt("Light")}catch{}_A()},style:{fontSize:"0.9em",padding:"6px 12px"},children:"Upgrade to Premium"})})]})]})]})]})}),C.jsx("div",{className:"profile-section",children:C.jsx(ige,{})}),C.jsxs("div",{className:"profile-section",children:[C.jsx("strong",{children:"Friends:"}),r.length?C.jsx("div",{className:"friends-scroll",children:C.jsx(GK,{className:"friends-panel",players:r,meId:(A==null?void 0:A.id)||"",onPlayerClick:qA=>{const WA=document.querySelector(`[data-player-id="${qA}"]`),Se=WA==null?void 0:WA.querySelector(".avatar-ring");Se&&b(qA,Se,"friends")},renderActions:qA=>{const WA=p(qA.id);return WA<=0?null:C.jsx("span",{className:"friend-unread-badge","aria-label":`${WA} unread message${WA>1?"s":""}`,children:WA>99?"99+":WA})}})}):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 qA=We.filter(WA=>W==="received"?WA._incoming:!WA._incoming);return qA.length?C.jsx("div",{className:"friends-scroll",children:C.jsx(GK,{className:"friends-panel",players:qA,meId:(A==null?void 0:A.id)||"",onPlayerClick:WA=>{const Se=document.querySelector(`[data-player-id="${WA}"]`),Qe=Se==null?void 0:Se.querySelector(".avatar-ring"),ce=We.find(Ve=>Ve.id===WA);Qe&&(ce!=null&&ce._req)&&b(WA,Qe,"requests",{id:ce._req.id,incoming:!!ce._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(GK,{className:"friends-panel",players:I,meId:(A==null?void 0:A.id)||"",onPlayerClick:qA=>{const WA=document.querySelector(`[data-player-id="${qA}"]`),Se=WA==null?void 0:WA.querySelector(".avatar-ring");Se&&b(qA,Se,"blocked")}})}):C.jsx("span",{children:"No blocked users"})]}),y&&m&&N&&C.jsx(EpA,{anchorRect:m,anchorEl:D,onClose:_,onViewProfile:()=>{e(`/player/${y}`),_()},onMessages:N==="friends"?()=>{Et(y),_()}:void 0,onUnfriend:N==="friends"?()=>{Rt(y),_()}:void 0,onBlockUser:N!=="requests"?async()=>{await st(y),_()}:void 0,isFriend:N==="friends",isBlocked:N==="blocked",...N==="requests"&&(M!=null&&M.incoming)?{onAddFriend:()=>{_t({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:qA=>J(qA.target.value),disabled:q})})]}),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:T,onChange:qA=>v(qA.target.value),disabled:q})})]})]}),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:qA=>dA(qA.target.value),disabled:q,"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:qA=>se(qA.target.value),disabled:q,"aria-label":"Age",children:[C.jsx("option",{value:"",children:"Prefer not to say"}),Array.from({length:103},(qA,WA)=>WA+18).map(qA=>C.jsx("option",{value:qA,children:qA},qA))]})})]})]}),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:hA,onChange:qA=>UA(qA.target.value),disabled:q,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:Ne,onChange:qA=>Ke(qA.target.value),disabled:q,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:At,onChange:qA=>ni(qA.target.value),disabled:q,placeholder:"Tell other players about yourself...",maxLength:500,rows:3,"aria-label":"About Me",style:{resize:"vertical",minHeight:60}})})]})}),(()=>{const qA=Th||Xq,WA=Th||vp,Se=Th||Kp;return C.jsxs(C.Fragment,{children:[(qA||WA)&&C.jsxs("div",{className:"profile-row profile-row--two",children:[qA&&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:VA==null?"":String(VA),onChange:Qe=>{const ce=Qe.target.value;KA(ce===""?null:Math.max(0,Math.min(8,Math.trunc(Number(ce)))))},disabled:q,"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((Qe,ce)=>C.jsx("option",{value:ce,children:ce},ce))]}),C.jsx("div",{className:"subtle",children:"Applies when you create single‑player rooms."})]})]}),WA&&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:Qe=>{const ce=Qe.target.value;DA(ce===""?null:Math.max(0,Math.min(8,Math.trunc(Number(ce)))))},disabled:q,"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((Qe,ce)=>C.jsx("option",{value:ce,children:ce},ce))]}),C.jsx("div",{className:"subtle",children:"Applies when you create single‑player rooms."})]})]})]}),Se&&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:IA==null?"":String(IA),onChange:Qe=>{const ce=Qe.target.value;EA(ce===""?null:Math.max(0,Math.min(8,Math.trunc(Number(ce)))))},disabled:q,"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((Qe,ce)=>C.jsx("option",{value:ce,children:ce},ce))]}),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 Qe;const qA=(()=>{const ce=A;return ce?vp?ce.spLevelCraps??1:Xq?ce.spLevelCeelo??1:Kp?ce.spLevelPoker??1:Math.max(ce.spLevelCeelo??1,ce.spLevelCraps??1,ce.spLevelPoker??1,ce.spLevelSkills??1):1})(),WA=Math.max(1,Math.min(9,qA)),Se=((Qe=iQ.find(ce=>ce.level===WA))==null?void 0:Qe.name)??`Level ${WA}`;return C.jsxs("select",{value:nA??"",onChange:ce=>{const Ve=ce.target.value;bA(Ve===""?void 0:Number(Ve))},"aria-label":"Bot difficulty level for single-player games",children:[C.jsxs("option",{value:"",children:["Default — ",WA,". ",Se]}),iQ.map(ce=>{const Ve=ce.level>WA;return C.jsxs("option",{value:ce.level,disabled:Ve,children:[Ve?"🔒 ":"",ce.level,". ",ce.name,Ve?" (locked)":""]},ce.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:FA,onChange:qA=>De(Number(qA.target.value)),"aria-label":"Number of bot opponents in Zentara singleplayer",children:[1,2,3,4,5].map(qA=>C.jsxs("option",{value:qA,children:[qA," bot",qA>1?"s":""]},qA))}),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{Xt("Light")}catch{}Ge()},disabled:q,children:q?"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:!oe,checked:!!pt,onChange:()=>kA(),"aria-label":pt?"Disable animations (dice physics, chip flights, background shake)":"Enable animations (dice physics, chip flights, background shake)"}),C.jsx("span",{children:pt?"Enabled":"Disabled"})]}),C.jsx("div",{className:"subtle",style:{opacity:.7},children:pt?"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:ae==="dice_red_white",onChange:()=>jA("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:ae==="dice_green_gold",onChange:()=>jA("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:ae==="dice_white_black",onChange:()=>jA("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:ae==="dice_blue_silver",onChange:()=>jA("dice_blue_silver"),"aria-label":"Use blue/silver dice"}),C.jsx("span",{children:"Blue/Silver"})]})]})]})]}),!_c&&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{Xt("Light")}catch{}try{cA()}catch{}},disabled:q||X||!lA||!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{Xt("Light")}catch{}try{uA()}catch{}},disabled:X||!lA||!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)===bK.PREMIUM?"Premium Active":"Free",C.jsx("span",{className:"badge","aria-live":"polite",children:(A==null?void 0:A.membershipTier)===bK.PREMIUM?"P":""})]}),C.jsxs("div",{className:"editable-field",children:[(A==null?void 0:A.membershipTier)===bK.PREMIUM?C.jsx(I5,{isPremium:!0,className:"felt-btn"}):HA&&C.jsx("button",{className:"felt-btn","data-no-global-haptic":!0,onClick:()=>{try{Xt("Light")}catch{}try{_A()}catch{}},disabled:X,"aria-label":zA,title:zA,children:"Go Premium"}),!xA&&HA&&C.jsx("div",{className:"meta",style:{marginTop:6},children:(()=>{const qA="$1.99",WA="Monthly",Se=Ee||qA,Qe=NA||WA,ce=ne||`${Se} Mo`,Ve=ye||"Remove ads and unlock premium features.";return C.jsxs(C.Fragment,{children:[ce&&C.jsx("div",{className:"subtle","aria-hidden":!0,children:ce}),C.jsx("div",{className:"legal-note","aria-hidden":!0,children:Ve}),C.jsxs("div",{className:"legal-note",role:"note",children:[C.jsx("strong",{children:"Premium Subscription"})," — ",Se," (",Qe,"). Auto‑renews until canceled. Manage or cancel in account settings on your device. See our ",C.jsx(qI,{to:"/privacy",className:"legal-link",children:"Privacy Policy"})," and ",C.jsx(qI,{to:"/terms",className:"legal-link",children:"Terms of Use"}),"."]})]})})()})]})]})}),C.jsx(nge,{}),ti.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{Xt("Light")}catch{}H("checking"),oA(null),tA(0);try{const qA=await fa.checkForUpdate({force:!0});if(qA.available&&qA.release){H("downloading");const{blob:WA}=await fa.downloadUpdate(qA.release,Se=>{tA(Se.percent??0)});H("applying"),await fa.applyUpdate(qA.release,WA),setTimeout(()=>{try{window.location.reload()}catch{}},500)}else H("up-to-date")}catch(qA){H("error"),oA((qA==null?void 0:qA.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{Xt("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{Xt("Light")}catch{}le()},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(AEA,{open:g,onClose:me,planId:A==null?void 0:A.membershipTier,featureDescription:"Upload custom avatars and create multiplayer rooms with Premium membership."}),C.jsx(Jp,{})]})}const qtA=[{key:"ceelo",name:"Cee-Lo Lounge",tagline:"Street dice with style",icon:Xne,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:$ne,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:Age,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:ege,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:tge,android:"https://play.google.com/store/apps/details?id=com.zentaraone.zentara",ios:"https://apps.apple.com/br/app/zentara-galaxy-conquest/id6761544336"}];function nge(){const e=(()=>{try{return ti.isNativePlatform()}catch{return!1}})(),A=(()=>{try{return ti.getPlatform()}catch{return"web"}})(),t=qtA.filter(g=>g.key!==Fs),i=Th?qtA: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 Hf(){const{playerId:e}=uw(),A=Ji(),t=Ss(),{user:i}=en(),{friends:n,friendRequests:g,blockedUsers:o,addFriend:s}=vd(),[r,a]=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?a(K.player):B(K.error||"Player not found"))}),()=>{_=!0}},[t,e]);const N=E.useCallback(async()=>{if(!(!e||m||D||S||Q||d||r!=null&&r.isBot)){p(!0);try{await s(e),h(!0)}catch{h(!1)}finally{p(!1)}}},[e,m,D,S,Q,d,s,r==null?void 0:r.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(Zr,{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{Xt("Light")}catch{}k()},children:[C.jsx($C,{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||!r)return C.jsxs("div",{className:`${Dm?"theme-zentara":"theme-casino"} home-fixed-root`,children:[C.jsx(Zr,{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{Xt("Light")}catch{}k()},children:[C.jsx($C,{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=r.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(Zr,{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{Xt("Light")}catch{}k()},children:[C.jsx($C,{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:r.avatarUrl?C.jsx("img",{src:r.avatarUrl,alt:r.name||"Player",className:"pp-avatar-img"}):C.jsx("div",{className:"pp-avatar-placeholder",children:(r.name||"?")[0].toUpperCase()})}),C.jsxs("div",{className:"pp-header-info",children:[C.jsxs("h2",{className:"pp-name",children:[r.name||"Anonymous",M&&C.jsx("span",{className:"pp-bot-badge",children:"Bot"})]}),C.jsxs("div",{className:"pp-meta-row",children:[r.age&&C.jsxs("span",{className:"pp-meta-tag",children:[r.age," yrs"]}),r.sex&&C.jsx("span",{className:"pp-meta-tag",children:r.sex}),r.location&&C.jsx("span",{className:"pp-meta-tag",children:r.location})]})]})]}),!y&&!M&&C.jsxs("div",{className:"pp-actions",children:[w&&C.jsx("button",{className:"felt-btn pp-action-btn",onClick:()=>{try{Xt("Light")}catch{}N()},disabled:b,children:w}),m&&C.jsx("button",{className:"felt-btn pp-action-btn",onClick:()=>{try{Xt("Light")}catch{}G()},children:"Message"})]}),r.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:r.aboutMe})]}),r.interests&&C.jsxs("div",{className:"pp-section",children:[C.jsx("h3",{className:"pp-section-title",children:"Interests"}),C.jsx("div",{className:"pp-interests",children:r.interests.split(/[,;]+/).map(_=>_.trim()).filter(Boolean).map((_,K)=>C.jsx("span",{className:"pp-interest-tag",children:_},K))})]})]})})})}),C.jsx(Jp,{})]})}function gge(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 Of(){const e=Ji(),[A]=dw(),{user:t}=en(),i=(t==null?void 0:t.id)??(t==null?void 0:t.email)??"",{friends:n}=vd(),{getDmSummary:g,sendDmMessage:o,markDmRead:s,setActiveDm:r,threads:a,loadDmHistory:I}=jR(),[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),r(b),I(b),e("/messages",{replace:!0});return}const _=g(),K=_==null?void 0:_.find(T=>T.unread>0);let J=null;K?J=K.peerUserId:n.length&&(J=n[0].id),J&&(l(J),r(J),I(J))},[n,g,r,I,A,e]),E.useEffect(()=>{c&&d.current!==c&&(d.current=c,s(c))},[c,s]);const y=E.useMemo(()=>c?(a==null?void 0:a[DC(c,i)])??[]:[],[c,a,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),r(b),s(b),I(b)},[r,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{Xt("Light")}catch{}e(-1)},[e]);return C.jsxs("div",{className:`${Dm?"theme-zentara":"theme-casino"} home-fixed-root messages-page`,children:[C.jsx(Zr,{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($C,{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=gge(b.name||b.id),J=((v=D.get(b.id))==null?void 0:v.unread)??0,T=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:T})]}),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 oge=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 Pf(){const e=Ji(),{logout:A}=en(),[t,i]=E.useState(Qs),[n,g]=E.useState(!1),o=E.useRef(null);E.useEffect(()=>{let a=!0;return(async()=>{const I=await Wo();a&&(i(I),g(!0))})(),()=>{a=!1,o.current&&window.clearTimeout(o.current)}},[]),E.useEffect(()=>{n&&(o.current&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>{_E(t).catch(()=>{})},200))},[t,n]);const s=a=>i(I=>({...I,[a]:!I[a]})),r=()=>{try{Xt("Light")}catch{}A(),e("/lobby")};return Dm?C.jsxs("div",{className:"zentara-settings",children:[C.jsx("div",{className:"zentara-settings__stars",children:oge.map((a,I)=>C.jsx("div",{className:"zentara-settings__star",style:{width:a.width,height:a.height,opacity:a.opacity,left:a.left,top:a.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(([a,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[a],onChange:()=>s(a),disabled:!n}),C.jsx("span",{className:"zentara-settings__toggle-track"})]})]},a)),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:a=>i(I=>({...I,zentaraBotCount:Number(a.target.value)})),disabled:!n,"aria-label":"Number of bot opponents in Zentara singleplayer",children:[1,2,3,4,5].map(a=>C.jsxs("option",{value:a,children:[a," bot",a>1?"s":""]},a))})]}),C.jsx("div",{className:"zentara-settings__divider"}),[["zentaraDisableRaid","Disable Resource Raid"],["zentaraDisableSpyStrike","Disable Spy Strike"]].map(([a,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[a],onChange:()=>s(a),disabled:!n}),C.jsx("span",{className:"zentara-settings__toggle-track"})]})]},a)),C.jsx("div",{className:"zentara-settings__divider"}),C.jsx("button",{className:"zentara-settings__logout","data-no-global-haptic":!0,onClick:r,"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:a=>i(I=>({...I,zentaraBotCount:Number(a.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(a=>C.jsxs("option",{value:a,children:[a," bot",a>1?"s":""]},a))})]}),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:r,"aria-label":"Log Out",title:"Log Out",children:"Log Out"})})]})}const vpA=gr();async function sge(){try{const e=await Co(),A=await fetch(`${vpA}/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 rge(){try{const e=await Co(),A=await fetch(`${vpA}/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 YtA={claimAdReward:sge,getAdRewardCooldown:rge};function jf(){const{busy:e,busyChips:A,ready:t,error:i,premiumActive:n,hasPremiumPackage:g,premiumLabel:o,isWeb:s,onBuyChips:r,onGoPremium:a,onRestore:I,chipsSubtitle:c,premiumSubtitle:l,chipsDescription:B,premiumDescription:Q,premiumPrice:h,premiumInterval:d}=kw(),{refreshUser:p}=en(),{infoNow:y}=Fa(),[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=vY.isNativeAdSupported(),_=!n&&b&&!RR,K=E.useCallback(YA=>{const W=Math.ceil(YA/1e3),$=Math.floor(W/60),L=W%60;return`${$}m ${L}s`},[]);E.useEffect(()=>{_&&(async()=>{try{const YA=await YtA.getAdRewardCooldown();YA!=null&&YA.ok&&YA.nextAt&&YA.nextAt>Date.now()&&k(YA.nextAt)}catch(YA){console.error("[AddChips] Failed to fetch ad cooldown:",YA)}})()},[_]),E.useEffect(()=>{!_||w||vY.prepareRewardedAd().catch(()=>{})},[_,w]),E.useEffect(()=>{if(!w)return;const YA=setInterval(()=>G(Date.now()),1e3);return()=>clearInterval(YA)},[w]);const J=E.useCallback(async()=>{if(!(m||w||!_)){Xt("Light"),D(!0);try{const YA=await vY.showRewardedAd();if(!YA.ok){YA.error==="AD_DISMISSED"?y==null||y("Ad skipped - watch the full ad to earn credits!"):y==null||y(`Ad unavailable: ${YA.error}`),D(!1);return}const W=await YtA.claimAdReward();if(W.ok){const $=R6*60*1e3;k(Date.now()+$),y==null||y(_c?`+${jQ} Z Credits added to your fleet!`:`+${jQ} Z Credits earned!`);try{p()}catch{}}else if(W.error==="COOLDOWN_ACTIVE"){const $=W.retryInMs??R6*60*1e3;k(Date.now()+$),y==null||y("Please wait before watching another ad.")}else y==null||y(`Reward failed: ${W.error}`)}catch(YA){console.error("[AddChips] Watch ad error:",YA),y==null||y("Something went wrong. Please try again.")}finally{D(!1)}}},[m,w,_,y,p]),T="$1.99",v="Monthly",U=h||T,x=d||v,q=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{Xt("Light")}catch{}try{r()}catch{}},gA=()=>{try{Xt("Light")}catch{}try{a()}catch{}},yA=()=>{try{Xt("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(Zr,{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{Xt("Light")}catch{}history.back()},children:[C.jsx($C,{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:_c?{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)}`:_c?`📡 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:_c?"Watch a short video to earn free Z Credits!":"Watch a short video to earn free credits!"})]})]}),!_c&&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:[q&&C.jsx("div",{className:"subtle","aria-hidden":!0,children:q}),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(qI,{to:"/privacy",className:"legal-link",children:"Privacy Policy"})," and ",C.jsx(qI,{to:"/terms",className:"legal-link",children:"Terms of Use"}),"."]})]})]}),n&&C.jsx("div",{style:{textAlign:"center"},children:C.jsx(I5,{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 FZ({open:e,onClose:A,title:t="Error",message:i}){return HcA(!!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=Ji(),{refreshUser:i}=en();E.useEffect(()=>{(async()=>{const s=new URLSearchParams(window.location.search).get("token");if(!s)return A("error");try{const r=await hbA(s);if(r!=null&&r.success){r.token&&await ef(r.token);try{await i({force:!0})}catch{}try{setTimeout(()=>{i({force:!0}).catch(()=>{})},400)}catch{}if(await hL()){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(FZ,{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(Zr,{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 Zf(){const[e,A]=E.useState("verifying"),[t,i]=E.useState(!1),n=Ji(),g=gr();return E.useEffect(()=>{(async()=>{const r=new URLSearchParams(window.location.search).get("token");if(!r){A("error");return}try{const a=await fetch(`${g}/api/auth/review-login?token=${encodeURIComponent(r)}`,{method:"GET",credentials:"include",redirect:"follow"});if(!a.ok){A("error");return}let I=null;try{const c=await a.json().catch(()=>null);c!=null&&c.token&&await ef(c.token)}catch{}if(I=await hL(),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(FZ,{open:t,onClose:()=>i(!1),title:"Review login failed",message:"Review login failed. Please check your link."})})}function Wf(){const[e,A]=E.useState("verifying"),[t,i]=E.useState(!1),n=Ji(),g=gr();return E.useEffect(()=>{(async()=>{const r=new URLSearchParams(window.location.search).get("token");if(!r){A("error");return}try{const a=await fetch(`${g}/api/auth/qa-login?token=${encodeURIComponent(r)}`,{method:"GET",credentials:"include",redirect:"follow"});if(!a.ok){A("error");return}try{const c=await a.json().catch(()=>null);c!=null&&c.token&&await ef(c.token)}catch{}if(await hL()){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(FZ,{open:t,onClose:()=>i(!1),title:"QA login failed",message:"QA login failed. Please check your link."})})}function V3({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 KpA({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 age({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,r]=E.useState(!1),a=E.useMemo(()=>o==null?void 0:o.filter(l=>t?!0:l.playerId===i||l.acceptedById===i),[o,t,i]),I=E.useMemo(()=>a.reduce((l,B)=>l+(B.amount||0),0),[a]),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(WI.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:()=>{r(!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:()=>r(!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:()=>r(!1),children:"Close"})]}),a.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:a.map(l=>C.jsx("li",{className:"betitem",children:C.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[C.jsxs(C.Fragment,{children:[" ",bZ(l.amount).map(B=>C.jsx(Zc,{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 Ige={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 FpA({selectedTimes:e,onAdd:A,onClear:t,onPlaceBet:i,onCancelBet:n,disabled:g,collapsed:o=!1,collapseLabel:s="Placed bet",miniChips:r=!1,betTokenProps:{isBanker:a,meId:I,open:c,players:l,show:B,labelPrefix:Q},hasBankRoll:h,betsLocked:d,myOpenMain:p,mainAmt:y,heading:m,rollerMeta:D}){const S=fpA,k=nee(),N=E.useCallback(()=>{Xt("Light")},[]),G=E.useRef(!1),M=!!d,w=!!h,b=!g&&!M&&!w&&!a&&!p,_=E.useCallback(()=>{G.current||!b||(G.current=!0,N(),i==null||i(),setTimeout(()=>{G.current=!1},600))},[b,i,N]),K=E.useCallback(T=>{if(!(g||M)){N();try{}catch{}A==null||A(T)}},[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(WI.div,{className:"chipRack__scroller",role:"listbox","aria-label":"Bet chips",initial:!1,style:{pointerEvents:g||M||o||p?"none":"auto"},children:S.map(T=>{const v=(e[T]??0)>0;return C.jsx(WI.div,{role:"option","aria-selected":v,variants:k?void 0:Ige,layout:!0,className:"chipRack__chipWrapper",children:C.jsx(Zc,{value:T,onAdd:K,onClear:t,disabled:!b,selectedTimes:e[T]??0,mini:r,"data-chip":T})},T)})})]}),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(KpA,{onClick:_,disabled:!b,mini:r})}),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(WI.div,{children:C.jsx(V3,{onClick:J,disabled:g||w||!p})}),C.jsx(age,{isBanker:a,meId:I,open:c,players:l,show:B,labelPrefix:Q})]})]})]})}function Cge({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=Vo.chipFlyDurationMs,o=0,s=100;i.current=window.setTimeout(()=>{try{SvA({playbackRate:1.25})}catch{}},o+s);const r=setTimeout(A,g+600);return()=>{clearTimeout(r),i.current&&(window.clearTimeout(i.current),i.current=null)}},[A]);const n=18;return E.useRef(null),C.jsx(WI.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:Vo.chipFlyDurationMs/1e3},onAnimationComplete:A,style:{pointerEvents:"none"},children:C.jsx(Zc,{mini:!0,value:t.amount,disabled:!0,className:"chip--flight",selectedTimes:0})})}function fM({label:e,subtitle:A,onClick:t,className:i,disabled:n,imageName:g,imgSrc:o,size:s="md",ariaLabel:r,showHalo:a}){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":r||e,children:[a&&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 $l({label:e,subtitle:A,onClick:t,disabled:i,size:n="md",ariaLabel:g,className:o,variant:s="pill",showHalo:r}){const a=[o,s==="circle"?"poker-action--circle":""].filter(Boolean).join(" "),[I,c]=he.useState(!1),l=he.useCallback(()=>{try{qn()}catch{}c(!1),requestAnimationFrame(()=>{c(!0),window.setTimeout(()=>c(!1),260)});try{Xt("Light")}catch{}try{}catch{}typeof t=="function"&&t()},[t]),B=typeof r=="boolean"?r:!i;return C.jsx("span",{className:["poker-action-spring",I?"is-spring":""].filter(Boolean).join(" "),"data-no-global-haptic":!0,children:C.jsx(fM,{label:e,subtitle:A,onClick:l,disabled:i,size:n,ariaLabel:g,className:a,showHalo:B})})}function AG(){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),[r,a]=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(T=>[...T,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),a(!0),console.log(`[sandbox] Bet placed with amount: $${n}`)},N=()=>{s(!1),a(!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(Zr,{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(Zc,{mini:!0,value:5,disabled:!0,className:"chip--flight"})},G))}),C.jsxs("div",{ref:l,children:[C.jsx(Zc,{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(Zc,{mini:!0,value:25,disabled:!0,className:"chip--flight"})},G))})]})]}),I.map(G=>C.jsx(Cge,{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($l,{label:"Check",ariaLabel:"Check",size:"md",className:"poker-action--green poker-action--secondary poker-action--check",onClick:()=>{}}),C.jsx($l,{label:"Call",subtitle:"z120",ariaLabel:"Call 120",size:"md",className:"poker-action--green poker-action--primary poker-action--call",onClick:()=>{}}),C.jsx($l,{label:"Bet",subtitle:"z250",ariaLabel:"Bet 250",size:"md",className:"poker-action--flat poker-action--secondary poker-action--bet",onClick:()=>{}}),C.jsx($l,{label:"Raise",subtitle:"z400",ariaLabel:"Raise 400",size:"md",className:"poker-action--flat poker-action--secondary poker-action--raise",onClick:()=>{}}),C.jsx($l,{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(kdA,{onClick:()=>{},label:"ROLL",busy:!1,disabled:!1})}),C.jsx("div",{className:"button-item",children:C.jsx(V3,{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(V3,{onClick:N,busy:!1,disabled:!1,label:"Cancel Bet"}):C.jsx(KpA,{disabled:n<=0,onClick:k,busy:!1,label:"✓"})}),C.jsx("div",{className:"button-item",children:C.jsx(FpA,{selectedTimes:t,onAdd:D,onClear:S,disabled:o,collapsed:r,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(MpA,{state:"verified"})})]})]})}function Vf(){const e=Ji(),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($C,{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 Xf(){const e=Ji();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($C,{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 $f(){const e=Ji();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($C,{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 Ay(){const e=Ji();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($C,{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(qI,{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."]})]})})}gr();const HtA={GET:!0,HEAD:!0};function cge(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=HtA[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(lge(A,B),{...Q,headers:{...g,...Q.headers||{},...k?{Authorization:`Bearer ${k}`}:{}},signal:D.signal});if(clearTimeout(S),N.status===401)throw i==null||i(),OtA("Unauthorized",N.status,await PtA(N));if((o.retryOn??[]).includes(N.status)&&m<d-1){await jtA((o.backoffMs??400)*(m+1));continue}if(!N.ok)throw OtA(`HTTP ${N.status}`,N.status,await PtA(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&&HtA[h]){await jtA((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 lge(e,A){return!e.endsWith("/")&&!A.startsWith("/")?`${e}/${A}`:e.endsWith("/")&&A.startsWith("/")?e+A.slice(1):e+A}function OtA(e,A,t){const i=new Error(e);return i.status=A,i.body=t,i}async function PtA(e){try{return await e.json()}catch{try{return await e.text()}catch{return null}}}const jtA=e=>new Promise(A=>setTimeout(A,e)),QGe=cge({baseURL:gr(),getToken:()=>Co().then(e=>e??null),onUnauthorized:()=>{wd()},defaultTimeoutMs:12e3});function _Z({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(Zr,{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 _pA({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(ztA,{value:i,revealed:!!A||!!t}),C.jsx(ztA,{value:n,revealed:!!t})]})}function ztA({value:e,revealed:A=!1}){if(!e)return C.jsx("span",{className:"poker-card"+(A?" revealed":""),"aria-hidden":!0});const{rank:t,suit:i}=Bge(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:Ege(i)})]})}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({gameState:e,players:A,winners:t,hands:i,durationMs:n,meId:g}){const o=E.useRef(null),s=E.useRef(null),r=E.useRef(null),{info:a}=Fa();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),q=(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}`;r.current!==aA&&(a(`${q}: ${z}`,void 0),r.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),T=`heur:${K}:${G.seatIndex}:${M}:${J}:${N}`;r.current!==T&&(a(_,void 0),r.current=T)},[e,A,a,n])}function ZtA({enabled:e,onComplete:A,perCardSec:t=.55,staggerSec:i=.12,origin:n,handKey:g,getTargets:o,passes:s=2}){const r=E.useRef(null),[a,I]=E.useState([]),[c,l]=E.useState(!1),B=E.useMemo(()=>{if(!r.current)return{x:0,y:0};const d=r.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,r.current]);E.useEffect(()=>{if(!e)return;const h=r.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{SS(["cardSwoosh"])}catch{}(async()=>{const y=await MF(["cardSwoosh"],900);l(y)})();const h=a.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,a,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<a.length;y++){const m=p*a.length+y;h.push({key:`card-${p}-${y}`,delay:m*i,to:a[y]})}return h},[a,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{wvA({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:r,className:"poker-dealing-layer","aria-hidden":!0,style:{willChange:"transform, opacity"},children:Q.map(h=>C.jsx(WI.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 uge({players:e,entries:A,onClose:t}){const i=he.useCallback((o,s)=>{var r;return((r=e.find(a=>a.id===o))==null?void 0:r.name)||`Seat ${s+1}`},[e]),n=he.useCallback(o=>{if(!o||typeof o.category!="number")return;const s=o.category|0,r=Array.isArray(o.tiebreak)?o.tiebreak:[],a=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"})[a(c)]||a(c);switch(s){case 8:return`Straight Flush (${I(r[0]??0)} high)`;case 7:return`Four of a Kind (${I(r[0]??0)}s)`;case 6:return`Full House (${I(r[0]??0)}s over ${I(r[1]??0)}s)`;case 5:return`Flush (${[r[0],r[1],r[2],r[3],r[4]].filter(c=>c!=null).map(c=>a(c)).join("")})`;case 4:return`Straight (${I(r[0]??0)} high)`;case 3:return`Three of a Kind (${I(r[0]??0)}s)`;case 2:return`Two Pair (${I(r[0]??0)}s & ${I(r[1]??0)}s)`;case 1:return`One Pair (${I(r[0]??0)}s)`;default:return`High Card (${I(r[0]??0)})`}},[]),g=he.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,r)=>{const a=o.winners.find(h=>h.playerId===s.playerId),I=i(s.playerId,s.seatIndex),c=!!a,l=String(s.status||"").toLowerCase()==="folded",B=n(s.rank||(a==null?void 0:a.rank)),Q=typeof(a==null?void 0:a.amount)=="number"?a.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}-${r}`)})})]},o.roundSeq))})]})]})}const X3=["A","K","Q","J","10","9","8","7","6","5","4","3","2"],dge={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 JpA(e){const A=String(e||"").trim().toUpperCase();if(!A)return null;const t=A.slice(0,-1),i=t==="T"?"10":t;return X3.includes(i)?i:null}function LpA(e){return e.map(JpA).filter(A=>A!==null)}function JZ(e){const A=LpA(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 hge(e){return JZ(e).length>0}function pge(e){const A=LpA(e);if(A.length===0)return null;let t=null,i=X3.length;for(const n of A){const g=X3.indexOf(n);g!==-1&&g<i&&(i=g,t=n)}return t}function fge(e){const A=pge(e);return A?`${dge[A]} High`:null}function yge(e,A){if(A<0||A>=e.length)return!1;const t=JpA(e[A]);return t?JZ(e).includes(t):!1}function Dge(e){const A=[];if(!e||e.length===0)return A;hge(e)&&A.push({label:"Paired Board",type:"paired"});const t=fge(e);return t&&A.push({label:t,type:"high"}),A}function mge(e){return e<0||e>4?null:e<=2?"flop":e===3?"turn":"river"}function Sge({boardCards:e}){const A=Dge(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 wge({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 a of s){const I=t[a],c=(I==null?void 0:I.place)??o.length+1;a!==e&&o.push({playerId:a,place:c})}const r=e===n;return C.jsxs("div",{className:"elim-gameover",onClick:g,children:[C.jsx("div",{className:"elim-gameover__title",children:r?"🏆 You Win!":"Game Over"}),C.jsx("div",{className:"elim-gameover__subtitle",children:r?"Last player standing — champion!":e?`${i(e)} wins the tournament!`:"Tournament complete"}),C.jsx("ol",{className:"elim-gameover__standings",children:o.map(a=>{const I=a.place===1,c=a.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:a.place===1?"🥇":a.place===2?"🥈":a.place===3?"🥉":`#${a.place}`}),C.jsxs("span",{className:"elim-gameover__player-name",children:[i(a.playerId),c?" (You)":""]})]},a.playerId)})}),C.jsx("button",{type:"button",className:"elim-gameover__dismiss",onClick:g,children:"OK"})]})}function WtA(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 kge(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 Mge(e){switch(e){case"hearts":return"♥";case"diamonds":return"♦";case"clubs":return"♣";case"spades":return"♠";default:return"?"}}function Nge({value:e,concealed:A,position:t,isPaired:i,animateEntrance:n}){if(!e)return null;const{rank:g,suit:o}=kge(e),r=["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:r,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:Mge(o)})]})}const _0=Object.create(null),JY=Object.create(null);function LZ(){var sa,Nr,ra,yI,Bc,sC;const{roomId:e}=uw(),{user:A,refreshUser:t}=en(),i=Ss(),{onHandEnd:n,isAdShowing:g}=qf(),o=String((A==null?void 0:A.id)??(A==null?void 0:A.email)??""),{joinRoom:s,leaveRoom:r,connected:a,participants:I,localParticipant:c}=al(),l=Cx(),{active:B,fire:Q,onComplete:h}=KZ(),d=he.useRef(0),p=["loss-a","loss-b","loss-c"],y=()=>{const BA=p[d.current%p.length];return d.current+=1,BA};E.useEffect(()=>{const BA=()=>{try{D8()||qn()}catch{}};BA();const LA=["pointerdown","touchstart","mousedown","click","keydown"];return LA.forEach(re=>{document.addEventListener(re,BA,{once:!0,capture:!0})}),()=>{LA.forEach(re=>{document.removeEventListener(re,BA,{capture:!0})})}},[]);const{pokerJoinRoom:m,pokerStartHand:D,pokerCreateRoom:S,pokerFold:k,pokerCheck:N,pokerCall:G,pokerBet:M,pokerRaise:w,pokerFetchHistory:b}=So(),_=Ji(),{info:K,win:J,onIdle:T,show:v}=Fa(),[U,x]=E.useState(null);E.useEffect(()=>{var re;const BA=(re=U==null?void 0:U.gameState)==null?void 0:re.pokerPhase;return BA&&BA!=="waiting"?l.acquire():l.release(),()=>{l.release()}},[U==null?void 0:U.gameState,l]),E.useEffect(()=>{var re;const BA=(re=U==null?void 0:U.gameState)==null?void 0:re.pokerPhase;!BA||BA==="waiting"?kL({volume:.0125}):Yu()},[U==null?void 0:U.gameState]);const[q,z]=E.useState(!1),Z=he.useRef(!1),[eA,aA]=E.useState(null),[sA,pA]=E.useState(!1),[gA,yA]=E.useState(!1),[fA,RA]=E.useState(!1),YA=he.useRef(!1),W=he.useRef(!1),$=he.useRef(null);he.useEffect(()=>{YA.current=fA},[fA]),he.useEffect(()=>{W.current=sA},[sA]),he.useEffect(()=>{$.current=eA},[eA]),he.useEffect(()=>{Z.current=q},[q]),he.useEffect(()=>{(!eA||eA.length!==2)&&(PA.current=0)},[eA]);const L=he.useRef(null),H=he.useRef(0);he.useRef(0);const P=he.useRef(null),tA=he.useRef(null),iA=he.useRef(null),[oA,CA]=E.useState(0),[cA,_A]=E.useState(0),[uA,X]=E.useState([]),[O,lA]=E.useState([]),[wA,xA]=E.useState(!1),[HA,zA]=E.useState([]),ne=he.useRef(0),ye=he.useRef(0),Ee=he.useRef(0),NA=he.useRef(!1),QA=he.useRef(null),PA=he.useRef(0),VA=he.useRef(void 0),KA=he.useRef(0),[Ie,DA]=he.useState([]),IA=he.useRef(0),EA=he.useRef(0),j=he.useRef(0),[dA,hA]=he.useState(!1),UA=he.useRef(0),TA=he.useRef(new Set),se=he.useRef(null),Ne=he.useRef(null),[Ke,At]=E.useState(0),[ni,Ge]=E.useState(0),[st,Rt]=he.useState(new Set),Et=he.useRef([]),_t=he.useRef(null),vt=he.useRef(0),xt=!0,[ee,Oe]=E.useState(!0),We=he.useRef(0),pt=he.useRef(null),kA=he.useRef(null),oe=he.useRef(null),[ae,$A]=E.useState(null),[nA,vA]=E.useState({}),[FA,te]=E.useState([]),[bA,De]=E.useState(null),[jA,me]=E.useState(null);he.useEffect(()=>{var LA;const BA=U==null?void 0:U.gameState;BA&&(LA=BA.pokerElimination)!=null&&LA.enabled&&($A({enabled:!0,startingShields:BA.pokerElimination.startingShields??3,maxTokens:BA.pokerElimination.maxTokens??3}),BA.pokerEliminationState&&vA(BA.pokerEliminationState),BA.pokerEliminatedOrder&&te(BA.pokerEliminatedOrder))},[U==null?void 0:U.gameState]);const[le,qA]=E.useState(null),WA=he.useMemo(()=>A?A.id:"",[A]),[Se,Qe]=E.useState(!1);E.useEffect(()=>{let BA=!0;return(async()=>{try{const{Preferences:LA}=await li(async()=>{const{Preferences:ke}=await Promise.resolve().then(()=>Yc);return{Preferences:ke}},void 0),{value:re}=await LA.get({key:"onb_poker_v1"});if(!BA)return;Qe(re!=="1")}catch{if(!BA)return;Qe(!0)}})(),()=>{BA=!1}},[]);const ce=he.useCallback(()=>{(async()=>{try{const{Preferences:BA}=await li(async()=>{const{Preferences:LA}=await Promise.resolve().then(()=>Yc);return{Preferences:LA}},void 0);await BA.set({key:"onb_poker_v1",value:"1"})}catch{}Qe(!1)})()},[]);he.useEffect(()=>{let BA=!1,LA=null,re=null,ke=null;const ue=Te=>{try{const rt=Te.getBoundingClientRect();if(rt&&isFinite(rt.height)){const Bn=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",`${Bn}px`)}}catch{}},Le=()=>{if(BA||typeof document>"u")return;const Te=document.querySelector(".card-header.card-header--two-rows");if(Te){pt.current=Te;try{LA=new ResizeObserver(()=>ue(Te)),LA.observe(Te)}catch{ke=()=>ue(Te),window.addEventListener("resize",ke)}ue(Te)}};if(Le(),!pt.current)try{re=window.setTimeout(Le,0)}catch{}return()=>{BA=!0;try{document.body.style.removeProperty("--poker-header-height")}catch{}if(LA)try{LA.disconnect()}catch{}if(ke){try{window.removeEventListener("resize",ke)}catch{}ke=null}if(re!=null){try{clearTimeout(re)}catch{}re=null}}},[]);const Ve=he.useCallback(BA=>{var LA;try{const ke=document.body.querySelector(`li.player--avatar[data-player-id="${BA}"]`),Le=(LA=(ke==null?void 0:ke.querySelector(".avatar-ring"))||ke)==null?void 0:LA.getBoundingClientRect();return Le?{x:Le.left+Le.width/2,y:Le.top+Le.height/2}:null}catch{return null}},[]),Dt=he.useCallback(()=>{try{const BA=QA.current;if(!BA)return null;const LA=BA.querySelectorAll(".poker-pot-stack");if(!LA||LA.length===0){const Te=BA.getBoundingClientRect();return Te?{x:Te.left+Te.width/2,y:Te.top+Te.height/2}:null}let re=1/0,ke=1/0,ue=-1/0,Le=-1/0;return LA.forEach(Te=>{const rt=Te.getBoundingClientRect();rt&&(re=Math.min(re,rt.left),ke=Math.min(ke,rt.top),ue=Math.max(ue,rt.right),Le=Math.max(Le,rt.bottom))}),!isFinite(re)||!isFinite(ke)||!isFinite(ue)||!isFinite(Le)?null:{x:(re+ue)/2,y:(ke+Le)/2}}catch{return null}},[]);E.useEffect(()=>{T(()=>{var BA;try{const LA=O||[];if(!LA.length)return;We.current=Date.now();const re=Dt();if(!re)return;const ke=[],ue=Number(cA||((BA=U==null?void 0:U.gameState)==null?void 0:BA.pokerRoundSeq)||0)||Date.now();if(ue&&IA.current===ue)return;LA.forEach((Le,Te)=>{const rt=Ve(Le.playerId);rt&&ke.push({id:`poker-pot-${ue}-${Te}`,amount:Math.max(1,Number(Le.amount||0)),fromId:"pot",toId:Le.playerId,startX:re.x,startY:re.y,endX:rt.x,endY:rt.y})}),ke.length&&(IA.current=ue,EA.current=ue,j.current=ke.length,DA(Le=>[...Le,...ke]),Oe(!1))}catch{}})},[O,cA,U==null?void 0:U.gameState]),E.useEffect(()=>{var Le;const BA=(Le=U==null?void 0:U.gameState)==null?void 0:Le.pokerPhase,LA=Array.isArray(O)&&O.length>0&&BA!=="pre-flop"?O.map(Te=>String(Te.playerId)):[],re=TA.current,ke=new Set(LA),ue=(Te,rt)=>{try{const Qt=document.querySelector(`li.player--avatar[data-player-id="${Te}"]`);Qt&&(rt?Qt.classList.add("player--winner-shake"):Qt.classList.remove("player--winner-shake"))}catch{}};return re.forEach(Te=>{ke.has(Te)||ue(Te,!1)}),ke.forEach(Te=>{re.has(Te)||ue(Te,!0)}),TA.current=ke,()=>{TA.current.forEach(Te=>ue(Te,!1)),TA.current.clear()}},[O,U==null?void 0:U.gameState]),E.useEffect(()=>{try{window.__pokerRoomMounted=Date.now()}catch{}},[]),E.useEffect(()=>()=>{if(Et.current.forEach(BA=>clearTimeout(BA)),Et.current=[],_t.current&&(clearTimeout(_t.current),_t.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 BA=String(e||"");if(BA&&$.current&&$.current.length===2){const LA=(U==null?void 0:U.gameState)||{},re=Number((LA==null?void 0:LA.pokerRoundSeq)||PA.current||0)||0;_0[BA]={myHole:$.current.slice(),roundSeq:re,first:!!gA,both:!!sA,ts:Date.now()};try{const ke=window;ke&&(ke.__pokerHoleDiag=ke.__pokerHoleDiag||[],ke.__pokerHoleDiag.push({kind:"persist_hole_on_unmount",at:Date.now(),round:re}))}catch{}}}catch{}},[]),E.useEffect(()=>{const BA=String(e||"");if(BA)try{const LA=_0[BA];if(!LA)return;if(!(Date.now()-(LA.ts||0)<3e4)){delete _0[BA];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 ke=window;ke&&(ke.__pokerHoleDiag=ke.__pokerHoleDiag||[],ke.__pokerHoleDiag.push({kind:"restore_persisted_hole_on_mount",at:Date.now(),round:LA.roundSeq}))}catch{}}}catch{}},[e]);function Mt(BA){if(!BA||typeof BA.category!="number")return;const LA=BA.category|0,re=Array.isArray(BA.tiebreak)?BA.tiebreak:[],ke=Le=>"23456789TJQKA"[Math.max(0,Math.min(12,Le))]||"?",ue=Le=>({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"})[ke(Le)]||ke(Le);switch(LA){case 8:return`Straight Flush (${ue(re[0]??0)} high)`;case 7:return`Four of a Kind (${ue(re[0]??0)}s)`;case 6:return`Full House (${ue(re[0]??0)}s over ${ue(re[1]??0)}s)`;case 5:return`Flush (${[re[0],re[1],re[2],re[3],re[4]].filter(Le=>Le!=null).map(Le=>ke(Le)).join("")})`;case 4:return`Straight (${ue(re[0]??0)} high)`;case 3:return`Three of a Kind (${ue(re[0]??0)}s)`;case 2:return`Two Pair (${ue(re[0]??0)}s & ${ue(re[1]??0)}s)`;case 1:return`One Pair (${ue(re[0]??0)}s)`;default:return`High Card (${ue(re[0]??0)})`}}E.useEffect(()=>{if(!e)return;let BA=!1;const LA=m,re=t;return(async()=>{if(se.current!==e&&!(U&&U.id===e))try{const ke=JY[e]||(async()=>LA(e))();JY[e]=ke;const ue=await ke;if(!BA&&(ue!=null&&ue.ok)){se.current=e,x(ue.room);try{s&&Ne.current!==e&&(await Promise.resolve(s(e)),Ne.current=e)}catch(Le){console.warn("[poker] RTC join failed",Le)}try{await re()}catch{}}else if(!BA&&ue&&!ue.ok)try{K("Poker",ue.error||"Failed to join room")}catch{}}catch(ke){console.warn("[poker] join failed",ke)}finally{delete JY[e]}})(),()=>{BA=!0,se.current===e&&(se.current=null),r&&Ne.current===e&&(Ne.current=null,r().catch(()=>{}))}},[e]);const ct=he.useCallback((BA,LA)=>{if(!BA||BA.id&&(LA!=null&&LA.id)&&BA.id!==LA.id)return LA;try{const re=Array.isArray(BA.players)?BA.players:[],ke=Array.isArray(LA==null?void 0:LA.players)?LA.players:[];if(ke.length===0&&re.length>0)return{...BA,...LA,players:re};const ue=ke.map(Le=>{const Te=re.find(rt=>String(rt.id)===String(Le.id));return Te?{...Te,...Le}:Le});return{...BA,...LA,players:ue}}catch{return LA||BA}},[]);xs({onJoinedRoom:({room:BA})=>{try{if(BA&&BA.id===e){x(LA=>LA&&LA.id===BA.id?ct(LA,BA):BA),se.current=e||null;try{const LA=BA==null?void 0:BA.gameState;if(!Z.current&&LA&&typeof LA.pokerPhase=="string"&&LA.pokerPhase.length>0){z(!0);const re=LA.pokerPhase;re&&re!=="pre-flop"&&re!=="waiting"&&RA(!1)}}catch{}}}catch{}},onRejoinedRoom:({room:BA})=>{try{if(BA&&BA.id===e){x(LA=>LA&&LA.id===BA.id?ct(LA,BA):BA),se.current=e||null,RA(!1);try{const LA=BA==null?void 0:BA.gameState;!Z.current&&LA&&typeof LA.pokerPhase=="string"&&LA.pokerPhase.length>0&&z(!0)}catch{}}}catch{}},onOtherPlayerJoined:({room:BA})=>{try{BA&&BA.id===e&&x(LA=>LA&&LA.id===BA.id?ct(LA,BA):BA)}catch{}},onOtherLeft:({room:BA})=>{try{BA&&BA.id===e&&x(LA=>LA&&LA.id===BA.id?ct(LA,BA):BA)}catch{}},onPlayerBalanceUpdated:({playerId:BA,balance:LA})=>{x(re=>{if(!re||!Array.isArray(re.players))return re;const ke=re.players.findIndex(Te=>String(Te.id)===String(BA));if(ke===-1)return re;const ue=re.players.slice(),Le=ue[ke];return typeof(Le==null?void 0:Le.balance)=="number"&&Le.balance===LA?re:(ue[ke]={...Le,balance:LA},{...re,players:ue})})},onPokerMyBalance:({roomId:BA,seatIndex:LA,stack:re,committed:ke})=>{BA===e&&x(ue=>{if(!ue||!ue.gameState)return ue;const Le=Array.isArray(ue.gameState.pokerSeats)?[...ue.gameState.pokerSeats]:[],Te=Le.findIndex(Qt=>(Qt==null?void 0:Qt.seatIndex)===LA);if(Te===-1)return ue;const rt=Le[Te];return rt.stack===re&&rt.committed===ke?ue:(Le[Te]={...rt,stack:re,committed:ke},{...ue,gameState:{...ue.gameState,pokerSeats:Le}})})},onRoomUpdateState:BA=>{var ue,Le,Te,rt,Qt,Bn,gg,Ln,og,ks,to,xn,En,mg,Qo,yi;if(!BA||BA.roomId!==e)return;if(console.log("[poker] onRoomUpdateState",{roomId:BA.roomId,phase:(Le=(ue=BA==null?void 0:BA.room)==null?void 0:ue.gameState)==null?void 0:Le.pokerPhase,roundSeq:(rt=(Te=BA==null?void 0:BA.room)==null?void 0:Te.gameState)==null?void 0:rt.pokerRoundSeq,seatCount:(gg=(Bn=(Qt=BA==null?void 0:BA.room)==null?void 0:Qt.gameState)==null?void 0:Bn.pokerSeats)==null?void 0:gg.length,hasMyHole:!!(BA!=null&&BA.myHole&&Array.isArray(BA.myHole)&&BA.myHole.length===2)}),BA.myHole&&Array.isArray(BA.myHole)&&BA.myHole.length===2){const fi=Number(((og=(Ln=BA==null?void 0:BA.room)==null?void 0:Ln.gameState)==null?void 0:og.pokerRoundSeq)||0);if(!$.current||$.current.length!==2||PA.current&&PA.current!==fi){aA(BA.myHole),fi>0&&(PA.current=fi),H.current=Date.now();try{const Qn=typeof window<"u"?window:void 0;Qn&&(Qn.__pokerHoleDiag=Qn.__pokerHoleDiag||[],Qn.__pokerHoleDiag.push({kind:"hole_from_state",at:Date.now(),round:fi}))}catch{}const Di=(to=(ks=BA==null?void 0:BA.room)==null?void 0:ks.gameState)==null?void 0:to.pokerPhase;!YA.current&&Di!=="pre-flop"&&(yA(!0),setTimeout(()=>pA(!0),180))}}x(fi=>{try{const Di=BA==null?void 0:BA.room,Qn=Di==null?void 0:Di.gameState;if(!fi||fi.id&&fi.id!==BA.roomId)return Di&&Di.id===BA.roomId?Di:fi;let Fi=Qn?{...fi,gameState:Qn}:{...fi};return Di&&Di.id===fi.id&&(Fi=ct(Fi,Di),Qn&&(Fi.gameState=Qn)),Fi}catch{return fi}});try{const fi=(xn=BA==null?void 0:BA.room)==null?void 0:xn.gameState;!Z.current&&fi&&typeof fi.pokerPhase=="string"&&fi.pokerPhase.length>0&&z(!0)}catch{}const LA=(mg=(En=BA==null?void 0:BA.room)==null?void 0:En.gameState)==null?void 0:mg.pokerPhase,re=Number(((yi=(Qo=BA==null?void 0:BA.room)==null?void 0:Qo.gameState)==null?void 0:yi.pokerRoundSeq)||0),ke=VA.current;if(VA.current=LA,(LA||"")==="pre-flop"){const fi=re>0&&re!==ne.current&&re!==ye.current,Di=!ke||["waiting","showdown","complete"].includes(String(ke));if(fi&&Di){if(pA(!1),yA(!1),$.current&&$.current.length===2)if(PA.current===0){PA.current=re;try{const Fi=typeof window<"u"?window:void 0;Fi&&(Fi.__pokerHoleDiag=Fi.__pokerHoleDiag||[],Fi.__pokerHoleDiag.push({kind:"assign_hole_round_on_preflop",at:Date.now(),round:re}))}catch{}}else if(PA.current!==re){aA(null);try{const Fi=String(e||"");Fi&&delete _0[Fi]}catch{}try{const Fi=typeof window<"u"?window:void 0;Fi&&(Fi.__pokerHoleDiag=Fi.__pokerHoleDiag||[],Fi.__pokerHoleDiag.push({kind:"clear_hole_new_round",at:Date.now(),toRound:re,prevHoleRound:PA.current}))}catch{}}else try{const Fi=typeof window<"u"?window:void 0;Fi&&(Fi.__pokerHoleDiag=Fi.__pokerHoleDiag||[],Fi.__pokerHoleDiag.push({kind:"keep_hole_new_round",at:Date.now(),round:re}))}catch{}else PA.current=0;ye.current=re,vt.current=Date.now(),CA(re);try{SS(["cardSwoosh"])}catch{}const Qn=KA.current!==re;Qn&&(KA.current=re),(async()=>{if(await MF(["cardSwoosh"],900),RA(!0),Qn)try{eP({volume:.6})}catch{}})()}else if(fi&&!Di)try{const Qn=window;Qn&&(Qn.__pokerHoleDiag=Qn.__pokerHoleDiag||[],Qn.__pokerHoleDiag.push({kind:"skip_preflop_midhand",at:Date.now(),round:re,prevPhase:ke}))}catch{}_A(0),X([]),lA([]),Oe(!0)}else if((LA||"")==="waiting"){if(pA(!1),yA(!1),RA(!1),L.current!=null){try{clearTimeout(L.current)}catch{}L.current=null}CA(fi=>fi+1),ye.current=0,$.current||(PA.current=0);try{const fi=String(e||"");fi&&!$.current&&delete _0[fi]}catch{}}},onPokerMyHole:BA=>{var LA,re,ke;if(!(!BA||BA.roomId!==e)&&Array.isArray(BA.hole)&&BA.hole.length===2){aA(BA.hole);try{const Te=(U==null?void 0:U.gameState)||{},rt=Number((Te==null?void 0:Te.pokerRoundSeq)||0);rt>0&&(PA.current=rt)}catch{}H.current=Date.now();try{const Te=typeof window<"u"?window:void 0;Te&&(Te.__pokerHoleDiag=Te.__pokerHoleDiag||[],Te.__pokerHoleDiag.push({kind:"hole",at:Date.now(),phase:(LA=U==null?void 0:U.gameState)==null?void 0:LA.pokerPhase,dealing:YA.current,round:Number(((re=U==null?void 0:U.gameState)==null?void 0:re.pokerRoundSeq)||0)}))}catch{}const Le=(((ke=U==null?void 0:U.gameState)==null?void 0:ke.pokerPhase)||"")==="pre-flop";if(Z.current)if(!fA&&!Le)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 Te=Date.now();if(YA.current&&Te-(H.current||Te)>3e3&&RA(!1),!Z.current&&Te-(H.current||Te)<4e3){try{L.current=window.setTimeout(()=>{},500)}catch{}return}yA(!0),pA(!0);try{const Qt=typeof window<"u"?window:void 0;Qt&&(Qt.__pokerHoleDiag=Qt.__pokerHoleDiag||[],Qt.__pokerHoleDiag.push({kind:"fallback_reveal",at:Te}))}catch{}},1800)}catch{}}}},onPokerRevealAll:BA=>{var ke,ue,Le;if(!BA||BA.roomId!==e)return;const LA=Number((BA==null?void 0:BA.roundSeq)||0),re=Number(((ke=U==null?void 0:U.gameState)==null?void 0:ke.pokerRoundSeq)||0);if(LA&&re){const Te=LA===re,rt=re===LA+1;if(!Te&&!rt)return}if(!(cA&&cA===LA)&&Array.isArray(BA.hands)){X(BA.hands.filter(rt=>Array.isArray(rt==null?void 0:rt.hole)&&rt.hole.length===2)),_A(LA||re||Date.now());const Te=Array.isArray(O)&&O.length>0?O:[];if((LA||re)&&Te.length>0){const rt=Number(LA||re),Bn=Te.reduce((gg,Ln)=>gg+(Number(Ln.amount)||0),0)||Number(((Le=(ue=U==null?void 0:U.gameState)==null?void 0:ue.wagerPool)==null?void 0:Le.totalAmount)||0)||0;zA(gg=>{var ks;const Ln=gg.findIndex(to=>to.roundSeq===rt),og={roundSeq:rt,ts:Date.now(),winners:Te.slice(),hands:(BA.hands||[]).slice(),pot:Bn,seats:Array.isArray((ks=U==null?void 0:U.gameState)==null?void 0:ks.pokerSeats)?U.gameState.pokerSeats.map(to=>{var xn,En;return{playerId:to.playerId,seatIndex:to.seatIndex,status:to.status,rank:((xn=Te.find(mg=>mg.playerId===to.playerId))==null?void 0:xn.rank)||void 0,winnings:(En=Te.find(mg=>mg.playerId===to.playerId))==null?void 0:En.amount}}):void 0};if(Ln>=0){const to=gg.slice();return to[Ln]=og,to}return[...gg,og].slice(-20)})}}},onPokerWinners:BA=>{var ue,Le,Te,rt,Qt,Bn,gg,Ln,og,ks,to;if(!BA||BA.roomId!==e)return;const LA=Number((BA==null?void 0:BA.roundSeq)||0),re=Number(((ue=U==null?void 0:U.gameState)==null?void 0:ue.pokerRoundSeq)||0);if(LA&&re){const xn=LA===re,En=re===LA+1;if(!xn&&!En)return}cA&&cA===LA?lA(xn=>xn.length?xn:Array.isArray(BA.winners)?BA.winners:[]):(lA(Array.isArray(BA.winners)?BA.winners:[]),cA||_A(LA||re||Date.now()));try{const xn=Number(LA||re||0)||0;if(xn&&Ee.current!==xn){const En=Array.isArray(BA.winners)?BA.winners:[],Qo=En.slice().sort((Di,Qn)=>String(Di.playerId).localeCompare(String(Qn.playerId))).map(Di=>`${Di.playerId}:${Number(Di.amount)||0}:${Number(Di.seatIndex)||0}:${Di.rank&&Number(Di.rank.category)||-1}`).join("|"),yi=typeof window<"u"?window:void 0,fi=yi&&yi.__pokerWinnersFlashGuard;if(!fi||fi.roundSeq!==xn||fi.content!==Qo){const Di=En.find(io=>io&&io.rank&&typeof io.rank.category=="number"),Qn=Mt(Di==null?void 0:Di.rank),qo=En.reduce((io,El)=>io+(Number(El.amount)||0),0)||Number(((Te=(Le=U==null?void 0:U.gameState)==null?void 0:Le.wagerPool)==null?void 0:Te.totalAmount)||0)||0,Ec=qo>0?`Pot: z${qo}`:void 0,ar=[Qn,Ec].filter(Boolean).join(" ");yi&&(yi.__pokerWinnersFlashGuard={roundSeq:xn,content:Qo,at:Date.now()});try{yi&&(yi.__pokerWinnersFlashed=!0)}catch{}const rC=String((A==null?void 0:A.id)??(A==null?void 0:A.email)??"");if(En.some(io=>String(io.playerId)===rC)){const io=En.find(aa=>String(aa.playerId)===rC),El=Number((io==null?void 0:io.amount)||0),BQ=El>0?`You won: z${El}`:"You won!";try{v({kind:"win",title:BQ,subtitle:ar,duration:4e3})}catch{}try{tP()}catch{}try{yi&&(yi.__E2E===!0||(((rt=yi.location)==null?void 0:rt.search)||"").includes("e2e=1"))&&(yi.__pokerWinnersFlashed={title:BQ,subtitle:ar,roundSeq:xn,at:Date.now(),__viaServer:!0})}catch{}try{const aa=((Qt=io==null?void 0:io.rank)==null?void 0:Qt.category)??((Bn=Di==null?void 0:Di.rank)==null?void 0:Bn.category),Ql=((gg=io==null?void 0:io.rank)==null?void 0:gg.tiebreak)??((Ln=Di==null?void 0:Di.rank)==null?void 0:Ln.tiebreak)??[];typeof aa=="number"?aa===8&&Ql[0]===12?Q("royal-flush",{displayMs:4e3}):aa===8?Q("straight-flush",{displayMs:3500}):aa===7?Q("quads",{displayMs:3e3}):aa===6?Q("full-house",{displayMs:2500}):aa===5?Q("flush",{displayMs:2500}):aa===4&&Q("straight",{displayMs:2500}):En.length===1&&!Di&&Q("poker-bluff",{displayMs:2500})}catch{}}Ee.current=xn}}}catch{}try{const xn=String((A==null?void 0:A.id)??(A==null?void 0:A.email)??""),En=Array.isArray(BA.winners)?BA.winners:[];if(!En.some(Qo=>String(Qo.playerId)===xn)){let Qo=0;const fi=(Array.isArray((og=U==null?void 0:U.gameState)==null?void 0:og.pokerSeats)?U.gameState.pokerSeats:[]).find(ar=>String(ar.playerId||"")===xn),Di=Number((fi==null?void 0:fi.committed)||0),Qn=Number((fi==null?void 0:fi.returned)||0);Di>0&&(Qo=Math.max(0,Di-(Number.isFinite(Qn)?Qn:0)));const Fi=En.find(ar=>ar&&ar.rank&&typeof ar.rank.category=="number"),qo=Fi?`Winner: ${Mt(Fi.rank)}`:void 0,Ec=Qo>0?`You lost: z${Qo}`:"You lost";try{T(()=>{try{v({kind:"lose",title:Ec,subtitle:qo})}catch{}try{iP()}catch{}try{Q(y(),{displayMs:2e3})}catch{}})}catch{}}}catch{}try{const xn=Number(LA||re||0);xn&&UA.current!==xn&&(UA.current=xn,hA(!0),setTimeout(()=>hA(!1),5200))}catch{}const ke=Array.isArray(uA)&&uA.length>0?uA:[];if((LA||re)&&ke.length>0){const xn=Number(LA||re),En=Array.isArray(BA.winners)?BA.winners:[],Qo=En.reduce((yi,fi)=>yi+(Number(fi.amount)||0),0)||Number(((to=(ks=U==null?void 0:U.gameState)==null?void 0:ks.wagerPool)==null?void 0:to.totalAmount)||0)||0;zA(yi=>{var Qn;const fi=yi.findIndex(Fi=>Fi.roundSeq===xn),Di={roundSeq:xn,ts:Date.now(),winners:En.slice(),hands:ke.slice(),pot:Qo,seats:Array.isArray((Qn=U==null?void 0:U.gameState)==null?void 0:Qn.pokerSeats)?U.gameState.pokerSeats.map(Fi=>{var qo,Ec;return{playerId:Fi.playerId,seatIndex:Fi.seatIndex,status:Fi.status,rank:((qo=En.find(ar=>ar.playerId===Fi.playerId))==null?void 0:qo.rank)||void 0,winnings:(Ec=En.find(ar=>ar.playerId===Fi.playerId))==null?void 0:Ec.amount}}):void 0};if(fi>=0){const Fi=yi.slice();return Fi[fi]=Di,Fi}return[...yi,Di].slice(-20)})}try{n()}catch{}},onPokerTimedOut:BA=>{try{if(!BA||BA.roomId!==e)return;const LA=String((A==null?void 0:A.id)??(A==null?void 0:A.email)??"");if(BA.playerId!==LA)return;const re=BA.action==="check"?"auto-check":"auto-fold";Pw(`🕒 Timed out — ${re}`)}catch{}}}),E.useEffect(()=>{if(!i||!e)return;const BA=ke=>{ke.roomId===e&&(console.log("[poker] start_ready_update",ke),Hi(ke.readyPlayers||[]),Vi(ke.requiredPlayers||[]),ke.allReady&&(Ce(!1),At(0)))},LA=ke=>{ke.roomId===e&&(console.log("[poker] start_countdown",ke),At(ke.endsAt),Hi(ke.readyPlayers||[]),Vi(ke.requiredPlayers||[]))},re=ke=>{ke.roomId===e&&(console.log("[poker] start_countdown_cancelled",ke),At(0),Ge(0))};return i.on("poker:start_ready_update",BA),i.on("poker:start_countdown",LA),i.on("poker:start_countdown_cancelled",re),()=>{i.off("poker:start_ready_update",BA),i.off("poker:start_countdown",LA),i.off("poker:start_countdown_cancelled",re)}},[i,e]),E.useEffect(()=>{if(!i||!e)return;const BA=ue=>{(ue==null?void 0:ue.roomId)===e&&(console.log("[poker:elimination] update",ue),ue.config&&$A({enabled:!0,startingShields:ue.config.startingShields??3,maxTokens:ue.config.maxTokens??3}),ue.states&&vA(ue.states),ue.eliminatedOrder&&te(ue.eliminatedOrder))},LA=ue=>{if((ue==null?void 0:ue.roomId)!==e)return;console.log("[poker:elimination] eliminated",ue);const Le=ue.place??"";if(ue.playerId===WA)try{v({kind:"lose",title:"Eliminated!",subtitle:`You finished in ${WtA(Le)} place`,duration:4e3})}catch{}},re=ue=>{var Le,Te;if((ue==null?void 0:ue.roomId)===e&&(console.log("[poker:elimination] player_eliminated",ue),ue.playerId&&ue.playerId!==WA)){const rt=((Te=(Le=U==null?void 0:U.players)==null?void 0:Le.find(Qt=>Qt.id===ue.playerId))==null?void 0:Te.name)||"A player";me({text:`${rt} eliminated!`,sub:ue.place?`${WtA(ue.place)} place`:void 0}),setTimeout(()=>me(null),3e3)}},ke=ue=>{if((ue==null?void 0:ue.roomId)===e){console.log("[poker:elimination] gameover",ue),De({winner:ue.winner,eliminatedOrder:ue.eliminatedOrder||[],finalStates:ue.finalStates||{}});try{ue.winner===WA?tP():iP()}catch{}}};return i.on("poker:elimination_update",BA),i.on("poker:eliminated",LA),i.on("poker:player_eliminated",re),i.on("poker:elimination_gameover",ke),()=>{i.off("poker:elimination_update",BA),i.off("poker:eliminated",LA),i.off("poker:player_eliminated",re),i.off("poker:elimination_gameover",ke)}},[i,e,WA,U==null?void 0:U.players]);const gt=he.useRef(0);E.useEffect(()=>{if(!i||!WA)return;const BA=LA=>{var re;!LA||((re=LA.winner)==null?void 0:re.userId)!==WA||(console.log("[poker] last man standing (server event)",{meId:WA,bonus:LA.bonus}),qA({winnerUserId:WA,bonus:LA.bonus??0}))};return i.on("poker:last_man_standing",BA),()=>{i.off("poker:last_man_standing",BA)}},[i,WA]),E.useEffect(()=>{const BA=U==null?void 0:U.gameState;if(!BA||!WA)return;const LA=BA.pokerPhase;if(LA!=="complete"&&LA!=="waiting")return;const re=Array.isArray(BA.pokerSeats)?BA.pokerSeats.filter(Le=>!!(Le!=null&&Le.playerId)):[],ke=re.filter(Le=>(Le.stack??0)>0);if(ke.length!==1||ke[0].playerId!==WA)return;const ue=Number(BA.pokerRoundSeq||0);ue<=0||ue===gt.current||(gt.current=ue,console.log("[poker] last man standing detected (client)",{meId:WA,roundSeq:ue,phase:LA,totalSeats:re.length,aliveSeats:ke.length}),qA({winnerUserId:WA,bonus:0}))},[U==null?void 0:U.gameState,WA]),E.useEffect(()=>{if(!Ke||Ke<=Date.now()){Ge(0);return}const BA=()=>{const re=Math.max(0,Math.ceil((Ke-Date.now())/1e3));Ge(re),re<=0&&At(0)};BA();const LA=setInterval(BA,1e3);return()=>clearInterval(LA)},[Ke]);const et=he.useRef("waiting");E.useEffect(()=>{var ue;const BA=((ue=U==null?void 0:U.gameState)==null?void 0:ue.pokerPhase)||"waiting",LA=et.current;et.current=BA;const re=!["waiting","complete"].includes(BA),ke=!["waiting","complete"].includes(LA);return(re||BA==="waiting"&&ke)&&(Hi([]),Vi([]),At(0),Ge(0),Ce(!1)),ke&&!re?(Ot(!0),clearTimeout(qt.current),qt.current=setTimeout(()=>Ot(!1),1500)):re&&(clearTimeout(qt.current),Ot(!1)),()=>clearTimeout(qt.current)},[(sa=U==null?void 0:U.gameState)==null?void 0:sa.pokerPhase]),E.useEffect(()=>{const BA=U==null?void 0:U.gameState;if(!BA)return;const LA=BA==null?void 0:BA.pokerPhase,re=Number((BA==null?void 0:BA.pokerRoundSeq)||0);if((LA||"")==="pre-flop"&&re>0&&re!==ne.current&&re!==ye.current){if(console.log("[poker] triggering initial dealing animation for roundSeq",re),pA(!1),yA(!1),$.current&&$.current.length===2)if(PA.current===0){PA.current=re;try{const ue=typeof window<"u"?window:void 0;ue&&(ue.__pokerHoleDiag=ue.__pokerHoleDiag||[],ue.__pokerHoleDiag.push({kind:"assign_hole_round_on_initial_preflop",at:Date.now(),round:re}))}catch{}}else if(PA.current!==re){aA(null);try{const ue=typeof window<"u"?window:void 0;ue&&(ue.__pokerHoleDiag=ue.__pokerHoleDiag||[],ue.__pokerHoleDiag.push({kind:"clear_hole_initial_preflop",at:Date.now(),toRound:re,prevHoleRound:PA.current}))}catch{}}else try{const ue=typeof window<"u"?window:void 0;ue&&(ue.__pokerHoleDiag=ue.__pokerHoleDiag||[],ue.__pokerHoleDiag.push({kind:"keep_hole_initial_preflop",at:Date.now(),round:re}))}catch{}else PA.current=0;ye.current=re,vt.current=Date.now(),CA(re);try{SS(["cardSwoosh"])}catch{}const ke=KA.current!==re;ke&&(KA.current=re),(async()=>{if(await MF(["cardSwoosh"],900),RA(!0),ke)try{eP({volume:.6})}catch{}})()}},[U==null?void 0:U.gameState]),he.useEffect(()=>{var BA;try{const LA=typeof window<"u"?window:void 0;if(!(!!LA&&(LA.__E2E===!0||typeof((BA=LA.location)==null?void 0:BA.search)=="string"&&LA.location.search.includes("e2e=1")||LA.sessionStorage&&LA.sessionStorage.getItem("e2e")==="1")))return;const ke=(e||"").startsWith("e2e-"),ue=!U||!U.gameState||!Array.isArray(U.gameState.pokerSeats);if(!ke||!ue||NA.current)return;NA.current=!0;try{window.__pokerFallbackArmed=Date.now()}catch{}const Le=setTimeout(()=>{try{const Te=Date.now()%1e5,rt={playerId:String(WA||o||"hero"),seatIndex:0,amount:120,rank:{category:1,tiebreak:[12,7,5,4,2]}},Qt=[{playerId:String(WA||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"]}];lA([rt]),X(Qt),_A(Te);const Bn=`You: +z${Number(rt.amount||0)}`,gg=`Pot: z${Number(rt.amount||0)}`,Ln=`${Mt(rt.rank)} ${gg}`;try{window.__pokerWinnersFlashed={title:Bn,subtitle:Ln,roundSeq:Te,at:Date.now(),__fallback:!0}}catch{}try{window.__pokerFallbackFired=Date.now()}catch{}}catch{}},5500);return()=>clearTimeout(Le)}catch{}},[]),he.useEffect(()=>{var BA;try{const LA=typeof window<"u"?window:void 0;if(!(!!LA&&(LA.__E2E===!0||typeof((BA=LA.location)==null?void 0:BA.search)=="string"&&LA.location.search.includes("e2e=1")||LA.sessionStorage&&LA.sessionStorage.getItem("e2e")==="1")))return;const ke=setTimeout(()=>{try{if(window.__pokerWinnersFlashed)return;const ue=Date.now()%1e5,Le={playerId:String(WA||o||"hero"),seatIndex:0,amount:80,rank:{category:1,tiebreak:[11,9,6,4,2]}},Te=[{playerId:String(WA||o||"hero"),seatIndex:0,hole:["As","Ad"]}];lA([Le]),X(Te),_A(ue);const rt=`You: +z${Number(Le.amount||0)}`,Qt=`Pot: z${Number(Le.amount||0)}`,Bn=`${Mt(Le.rank)} ${Qt}`;try{window.__pokerWinnersFlashed={title:rt,subtitle:Bn,roundSeq:ue,at:Date.now(),__safety:!0}}catch{}}catch{}},1e4);return()=>clearTimeout(ke)}catch{}},[J,WA,o]),E.useEffect(()=>{var re;const BA=(re=U==null?void 0:U.gameState)==null?void 0:re.pokerPhase,LA=["flop","turn","river","showdown"].includes(BA||"");q&&LA&&eA&&eA.length===2&&!sA&&!fA&&(yA(!0),pA(!0))},[U==null?void 0:U.gameState,eA,sA,fA,q]),E.useEffect(()=>{var re;const LA=(((re=U==null?void 0:U.gameState)==null?void 0:re.pokerPhase)||"")==="pre-flop";if(q&&LA&&!fA&&eA&&eA.length===2&&!sA){yA(!0);const ke=setTimeout(()=>pA(!0),220);return()=>clearTimeout(ke)}},[fA,U==null?void 0:U.gameState,eA,sA,q]),E.useEffect(()=>{if(!q||!eA||eA.length!==2||sA)return;const BA=setTimeout(()=>{!W.current&&$.current&&$.current.length===2&&(yA(!0),setTimeout(()=>pA(!0),180))},300);return()=>clearTimeout(BA)},[q,eA,sA]),E.useEffect(()=>()=>{PA.current=0},[]);const Li=(U==null?void 0:U.name)||"Poker Room",Ri=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]),gi=he.useRef(0),Jt=E.useMemo(()=>{var gg,Ln;if(!(U!=null&&U.singlePlayer))return;const BA=Array.isArray((gg=U==null?void 0:U.gameState)==null?void 0:gg.pokerSeats),LA=BA?U.gameState.pokerSeats:[],re=new Set(LA.map(og=>String((og==null?void 0:og.playerId)??"")).filter(og=>og.startsWith("poker_bot_"))),ke=new Set([...re,...Ri.map(og=>og.id).filter(og=>og.startsWith("poker_bot_")),...Object.keys(nA).filter(og=>og.startsWith("poker_bot_"))]);gi.current=Math.max(gi.current,ke.size);const ue=gi.current,Le=Object.entries(nA).filter(([og,ks])=>og.startsWith("poker_bot_")&&(ks==null?void 0:ks.eliminated)).length,Te=BA?Math.max(Le,ue-re.size):Le,rt=Number((U==null?void 0:U.spLevel)??(A==null?void 0:A.spLevelPoker)??1),Qt=Number.isFinite(rt)&&rt>0?rt:1,Bn=(U==null?void 0:U.levelName)??((Ln=iQ.find(og=>og.level===Qt))==null?void 0:Ln.name)??`Level ${Qt}`;return{level:Qt,levelName:Bn,current:Te,total:ue,progressLabel:`${Te}/${ue} bots eliminated`,goalLabel:`Eliminate every bot to reach Level ${Qt+1}`,isMaxLevel:Qt>=iQ.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,Ri,nA,A==null?void 0:A.spLevelPoker]);he.useCallback((BA,LA)=>{var re;return((re=Ri.find(ke=>ke.id===BA))==null?void 0:re.name)||`Seat ${LA+1}`},[Ri]);const jt=E.useMemo(()=>U!=null&&U.gameState?U.gameState:{gameMode:"poker",roundSeq:1},[U==null?void 0:U.gameState]);Qge({gameState:jt,players:Ri,winners:O,hands:uA,meId:WA});const[Ci]=E.useState(()=>Date.now()),Pi=E.useMemo(()=>{var LA;const BA=(LA=U==null?void 0:U.gameState)==null?void 0:LA.pokerPhase;return BA==="pre-flop"||BA==="flop"||BA==="turn"||BA==="river"||BA==="showdown"},[U==null?void 0:U.gameState]),si=Number(((Nr=U==null?void 0:U.gameState)==null?void 0:Nr.pokerUiLockedUntilTs)||0),pi=si>0&&Date.now()<si,Ai=7e3,xi=he.useRef(null);he.useEffect(()=>{var LA;const BA=String(((LA=U==null?void 0:U.gameState)==null?void 0:LA.pokerPhase)||"");pi?xi.current==null&&(xi.current=Date.now()):BA==="waiting"&&(xi.current=null)},[pi,U==null?void 0:U.gameState]);const ui=xi.current??(vt.current||0),ie=ui>0?Date.now()-ui:Number.POSITIVE_INFINITY,ln=pi&&ie<=Ai,[,Zt]=he.useReducer(BA=>BA+1,0);he.useEffect(()=>{if(!pi)return;const BA=ui>0?ui+Ai:Number.POSITIVE_INFINITY,LA=si>0?si:Number.POSITIVE_INFINITY,re=Math.min(BA,LA);if(!isFinite(re))return;const ke=Math.max(0,Math.min(15e3,Math.ceil(re-Date.now()+2))),ue=window.setTimeout(()=>{try{Zt()}catch{}},ke);return()=>{window.clearTimeout(ue)}},[pi,si,ui,Ai]);const lo=E.useMemo(()=>{const BA=(U==null?void 0:U.gameState)||{},LA=(BA==null?void 0:BA.pokerPhase)||"",re=Array.isArray(BA==null?void 0:BA.pokerCommunity)?BA.pokerCommunity:[];return LA==="flop"?re.length>=3&&![0,1,2].some(ke=>st.has(ke)):LA==="turn"?re.length>=4&&!st.has(3):LA==="river"?re.length>=5&&!st.has(4):!0},[U==null?void 0:U.gameState,st]),Hg=((ra=U==null?void 0:U.gameState)==null?void 0:ra.pokerPhase)||"",xo=["showdown","complete"].includes(Hg),Cg=Date.now()-Ci<800||!Pi||fA||ln||!lo||xo,{isBettingStreet:Dg,isHeroTurn:ng,heroStatus:wo,toCall:fe,canCheck:Pe,canCall:OA,canBet:XA,canRaise:_e,showActions:xe,minRaiseTo:rA,currentBet:pe,heroStack:Fe,turnDeadlineTs:je}=E.useMemo(()=>{const BA=(U==null?void 0:U.gameState)||{},LA=(BA==null?void 0:BA.pokerPhase)||"",re=["pre-flop","flop","turn","river"].includes(LA),ue=(Array.isArray(BA==null?void 0:BA.pokerSeats)?BA.pokerSeats:[]).find(yi=>String(yi.playerId)===String(WA)),Le=typeof(BA==null?void 0:BA.pokerActingSeat)=="number"?BA.pokerActingSeat:void 0,Te=!!ue&&typeof Le=="number"&&ue.seatIndex===Le,rt=Number((BA==null?void 0:BA.pokerCurrentBet)||0),Qt=Number((ue==null?void 0:ue.committed)||0),Bn=Number((ue==null?void 0:ue.stack)||0),gg=String((ue==null?void 0:ue.status)||"active"),Ln=Math.max(0,rt-Qt),og=Ln===0&&gg==="active",ks=Ln>0&&gg==="active"&&Bn>0,to=rt===0&&gg==="active"&&Bn>0,xn=rt>0&&gg==="active"&&Bn>0,En=re&&!!ue&&gg==="active",mg=Number((BA==null?void 0:BA.pokerMinRaiseTo)||0),Qo=Number((BA==null?void 0:BA.pokerTurnDeadlineTs)||0)||void 0;return{isBettingStreet:re,isHeroTurn:Te,heroStatus:gg,toCall:Ln,canCheck:og,canCall:ks,canBet:to,canRaise:xn,showActions:En,minRaiseTo:mg,currentBet:rt,heroStack:Bn,turnDeadlineTs:Qo}},[U==null?void 0:U.gameState,WA]),$e=Cg||!ng||wo!=="active",[Gt,Ot]=E.useState(!1),qt=he.useRef(void 0),ei=E.useMemo(()=>{const BA=(U==null?void 0:U.gameState)||{},LA=(BA==null?void 0:BA.pokerPhase)||"waiting",re=Array.isArray(BA==null?void 0:BA.pokerSeats)?BA.pokerSeats:[];return["waiting","complete"].includes(LA)&&re.length>=2&&!fA&&!ln&&!!e&&!g&&!Gt},[U==null?void 0:U.gameState,fA,ln,e,g,Gt]),[Yt,Ce]=E.useState(!1),it=E.useMemo(()=>{if(!e||!(U!=null&&U.singlePlayer))return!1;const BA=(U==null?void 0:U.gameState)||{},LA=(BA==null?void 0:BA.pokerPhase)||"waiting";if(LA!=="waiting"&&LA!=="complete")return!1;const re=Array.isArray(BA==null?void 0:BA.pokerSeats)?BA.pokerSeats.filter(ue=>!!(ue!=null&&ue.playerId)):[],ke=re.find(ue=>String(ue.playerId||"")===WA);return!!(re.length<=1&&ke||!ke||ke&&Number(ke.stack||0)===0)},[U==null?void 0:U.gameState,U==null?void 0:U.singlePlayer,e,WA]),[dt,ft]=E.useState(!1),[ci,Hi]=E.useState([]),[Wi,Vi]=E.useState([]),hi=E.useMemo(()=>ci.includes(WA),[ci,WA]),Bo=he.useCallback(()=>{P.current!=null&&(clearTimeout(P.current),P.current=null),tA.current!=null&&(clearTimeout(tA.current),tA.current=null),iA.current=null},[]),[Fn,ea]=E.useState(0),ta=Fn,[ia,na]=E.useState(!1),[hI,Eo]=E.useState(null),Og=WA,cl=!!Pi&&!fA&&!(Array.isArray(uA)&&uA.length>0),[ga,Od]=E.useState({active:!1,key:0,indices:[]}),lc=he.useRef(0);E.useEffect(()=>{var ke;const LA=(Array.isArray((ke=U==null?void 0:U.gameState)==null?void 0:ke.pokerCommunity)?U.gameState.pokerCommunity:[]).length,re=lc.current;if(LA>re){const ue=Array.from({length:LA-re},(Le,Te)=>re+Te);Rt(Le=>{const Te=new Set(Le);return ue.forEach(rt=>Te.add(rt)),Te}),_t.current&&(clearTimeout(_t.current),_t.current=null),_t.current=window.setTimeout(()=>{Od({active:!0,key:Date.now(),indices:ue}),_t.current=null},3e3),lc.current=LA}else lc.current=LA},[U==null?void 0:U.gameState]),he.useEffect(()=>{const BA=oe.current;if(!BA)return;BA.style.marginTop=BA.style.marginTop==="0px"?"0.01px":"0px";const LA=window.setTimeout(()=>{BA&&(BA.style.marginTop="")},0);return()=>window.clearTimeout(LA)},[fA,sA,gA,ia]);const ll=(BA,LA)=>{!BA&&LA&&K("Poker",LA)},ry=async()=>{if(!e)return;Bo();const BA=await N(e);ll(BA==null?void 0:BA.ok,BA==null?void 0:BA.error)},oa=async()=>{if(!e)return;Bo();const BA=await G(e);ll(BA==null?void 0:BA.ok,BA==null?void 0:BA.error)},Bl=async()=>{if(!e)return;Bo();const BA=await k(e);ll(BA==null?void 0:BA.ok,BA==null?void 0:BA.error)},Pd=()=>{$e||!XA||(Eo("bet"),na(!0))},vB=()=>{$e||!_e||(Eo("raise"),na(!0))},jd=async BA=>{if(!e||!hI)return;Bo();let LA=BA??ta;if(hI==="bet"){(!LA||LA<=0)&&(LA=Math.max(1,rA||1));const re=Math.floor(LA),ke=await M(e,re);ll(ke==null?void 0:ke.ok,ke==null?void 0:ke.error),ke!=null&&ke.ok&&(ea(0),na(!1),Eo(null))}else if(hI==="raise"){if(!LA||LA<=0){const ue=Math.max(0,rA-pe);LA=Math.max(1,ue)}LA=Math.min(LA,Math.max(0,Fe));const re=Math.floor(LA),ke=await w(e,re);ll(ke==null?void 0:ke.ok,ke==null?void 0:ke.error),ke!=null&&ke.ok&&(ea(0),na(!1),Eo(null))}},ay=()=>{ea(0),na(!1),Eo(null)},[To,pI]=he.useState(null),Pw=he.useCallback(BA=>{try{const LA=Ve(WA);LA&&pI({x:LA.x,y:Math.max(0,LA.y-70),text:BA});const re=document.querySelector(`li.player--avatar[data-player-id="${WA}"]`);re&&(re.classList.add("player--timeout"),setTimeout(()=>{try{re.classList.remove("player--timeout")}catch{}},2500)),setTimeout(()=>pI(null),2600)}catch{}},[Ve,WA]);E.useEffect(()=>{($e||!xe)&&(na(!1),Eo(null),ea(0))},[$e,xe]);const fI=he.useRef(0);return E.useEffect(()=>{const BA=U==null?void 0:U.gameState;if(!BA)return;const LA=BA==null?void 0:BA.pokerLastAction;if(!LA||typeof LA.seq!="number"||fI.current===LA.seq)return;const re=String(LA.action||"").toLowerCase();if(!["bet","raise","call"].includes(re)){fI.current=LA.seq;return}const ke=Math.max(0,Number(LA.amountDelta||0));if(ke<=0){fI.current=LA.seq;return}const Le=(Array.isArray(BA==null?void 0:BA.pokerSeats)?BA.pokerSeats:[]).find(rt=>rt.seatIndex===LA.seatIndex),Te=Le!=null&&Le.playerId?String(Le.playerId):void 0;T(()=>{try{const rt=Dt();if(!rt)return;const Qt=Te?Ve(Te):null;if(!Qt)return;const Bn=`poker-commit-${LA.seq}-${Te||LA.seatIndex}-${Date.now()}`;DA(gg=>[...gg,{id:`${Bn}-to-pot`,amount:ke,fromId:Te||`seat:${LA.seatIndex}`,toId:"pot",startX:Qt.x,startY:Qt.y,endX:rt.x,endY:rt.y,startDelaySec:.1}])}catch{}}),fI.current=LA.seq},[U==null?void 0:U.gameState,T,Ve,xt]),C.jsxs(C.Fragment,{children:[C.jsx(Zr,{className:"page-poker-room"}),C.jsx(NpA,{open:Se,onClose:ce,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(_Z,{showAvatarBacks:cl,overlay:B?C.jsx(vZ,{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(UZ,{roomName:Li,roomId:e,players:Ri,meId:Og,gameState:jt,lastRollerId:null,showHeader:!0,revealedHands:uA,historyHalo:dA,singlePlayer:U==null?void 0:U.singlePlayer,campaignProgress:Jt,turnDeadlineTs:je,isBettingStreet:Dg,isHeroTurn:ng,elimConfig:ae,elimStates:nA,onOpenHistory:async()=>{var BA;if(xA(!0),!!e)try{const LA=await b(e,20);if(LA!=null&&LA.ok&&Array.isArray((BA=LA==null?void 0:LA.data)==null?void 0:BA.items)){const re=LA.data.items;zA(ke=>{const ue=re.map(Te=>({roundSeq:Number(Te.seq||Te.roundSeq||0),ts:Number(Te.endedAt||Te.createdAt||Date.now()),pot:Number(Te.mainPot||Te.pot||0),winners:Array.isArray(Te.seats)?Te.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(Te.seats)?Te.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(Te.seats)?Te.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})),Le=new Map;for(const Te of[...ke,...ue])Le.set(Te.roundSeq,Te);return Array.from(Le.values()).sort((Te,rt)=>rt.roundSeq-Te.roundSeq).slice(0,20)})}}catch(LA){console.warn("[poker] fetch_history failed",LA)}}})}),children:[C.jsx(ZtA,{enabled:fA,handKey:oA,perCardSec:.6,staggerSec:.14,onComplete:()=>{RA(!1);const BA=ye.current;if(BA>0&&(ne.current=BA),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(ZtA,{enabled:ga.active,handKey:`board-${ga.key}`,perCardSec:.5,staggerSec:.12,passes:1,getTargets:BA=>{var LA;try{const re=BA.getBoundingClientRect(),ke=(LA=BA.ownerDocument)==null?void 0:LA.querySelector(".poker-board");if(!ke)return[];const ue=Array.from(ke.querySelectorAll(".poker-card"));return ga.indices.map(Te=>{const rt=ue[Te];if(!rt)return null;const Qt=rt.getBoundingClientRect();return{x:(Qt.left+Qt.right)/2-re.left,y:(Qt.top+Qt.bottom)/2-re.top}}).filter(Boolean)}catch{return[]}},onComplete:()=>{const BA=ga.indices.slice();if(Od(LA=>({...LA,active:!1})),BA.length>0){Rt(re=>{const ke=new Set(re);return BA.forEach(ue=>ke.add(ue)),ke});const LA=window.setTimeout(()=>{Rt(re=>{const ke=new Set(re);return BA.forEach(ue=>ke.delete(ue)),ke})},250);Et.current.push(LA)}}}),C.jsxs("div",{className:"poker-mock",children:[it&&!ei&&C.jsx("div",{className:"poker-start-hand",children:C.jsx("button",{type:"button",className:["gold-link","poker-start-hand__btn",dt?"is-busy":""].filter(Boolean).join(" "),"aria-label":"Play Again",disabled:dt,onClick:async()=>{var BA,LA,re;if(!dt){try{const{hapticClick:ke}=await li(async()=>{const{hapticClick:ue}=await Promise.resolve().then(()=>bP);return{hapticClick:ue}},void 0);ke("Medium")}catch{}ft(!0);try{const{loadSettings:ke}=await li(async()=>{const{loadSettings:Bn}=await Promise.resolve().then(()=>PcA);return{loadSettings:Bn}},void 0),ue=await ke(),Le=ue.botDifficultyLevel&&ue.botDifficultyLevel>=1&&ue.botDifficultyLevel<=9?ue.botDifficultyLevel:void 0,Te=await S({name:"Single Player Room",singlePlayer:!0,botLevel:Le}),rt=(Te==null?void 0:Te.room)??((BA=Te==null?void 0:Te.roomsList)==null?void 0:BA.room)??((LA=Te==null?void 0:Te.data)==null?void 0:LA.room)??null,Qt=(rt==null?void 0:rt.roomId)??(rt==null?void 0:rt.id)??(Te==null?void 0:Te.roomId)??((re=Te==null?void 0:Te.data)==null?void 0:re.roomId);if(Qt){try{window.__PRESEEDED_ROOM=rt}catch{}_(`/poker/room/${Qt}`,{replace:!0})}else{console.warn("[poker:play_again] no room id in response",Te);try{K("Poker",(Te==null?void 0:Te.error)||"Unable to create room")}catch{}ft(!1)}}catch(ke){console.error("[poker:play_again] error",ke);try{K("Poker","Unable to create room")}catch{}ft(!1)}}},children:"Play Again"})}),ei&&C.jsxs("div",{className:"poker-start-hand",children:[ni>0&&C.jsxs("div",{className:"poker-start-hand__countdown",children:["Starting in ",ni,"s"]}),Wi.length>1&&C.jsxs("div",{className:"poker-start-hand__readiness",children:[ci.length,"/",Wi.length," ready"]}),C.jsx("button",{type:"button",className:["gold-link","poker-start-hand__btn",Yt?"is-busy":"",hi?"is-ready":""].filter(Boolean).join(" "),"aria-label":hi?"Waiting for others":"Start Hand",disabled:Yt||hi,onClick:async()=>{if(e){try{const{hapticClick:BA}=await li(async()=>{const{hapticClick:LA}=await Promise.resolve().then(()=>bP);return{hapticClick:LA}},void 0);BA("Medium")}catch{}console.log("[poker:start_hand] button clicked",{roomId:e}),Ce(!0);try{const BA=await D(e);if(console.log("[poker:start_hand] response",BA),BA!=null&&BA.countdown&&(console.log("[poker:start_hand] countdown started",{endsAt:BA==null?void 0:BA.countdown}),At(BA==null?void 0:BA.countdown)),BA!=null&&BA.waiting){console.log("[poker:start_hand] waiting for other players",{readyPlayers:BA==null?void 0:BA.readyPlayers,requiredPlayers:BA==null?void 0:BA.requiredPlayers}),Hi((BA==null?void 0:BA.readyPlayers)||[]),Vi((BA==null?void 0:BA.requiredPlayers)||[]);return}if(!(BA!=null&&BA.ok)){console.warn("[poker:start_hand] error response",BA);try{K("Poker",(BA==null?void 0:BA.error)||"Unable to start hand")}catch{}}Ce(!1)}catch(BA){console.error("[poker:start_hand] exception",BA);try{K("Poker","Unable to start hand")}catch{}Ce(!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:QA,style:ee?void 0:{visibility:"hidden"},children:(()=>{var re;const BA=Number(((re=jt==null?void 0:jt.wagerPool)==null?void 0:re.totalAmount)||0),LA=bZ(BA);return Object.entries(LA.reduce((ke,ue)=>{const Le=String(ue);return ke[Le]=(ke[Le]||0)+1,ke},{})).sort((ke,ue)=>Number(ue[0])-Number(ke[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",Fe]}),C.jsx("span",{className:"poker-pot__divider","aria-hidden":"true",children:"•"}),C.jsxs("span",{className:`poker-pot__pot-info ${fe>0&&Fe>0&&fe/Fe>=.25?"poker-pot__pot-info--high":""}`,children:[fe>0?`To Call: z${fe}`:`Pot: z${BA}`,fe>0&&Fe>0&&fe/Fe>=.5&&C.jsxs("span",{className:"poker-pot__high-pct","aria-label":"High percentage of stack",children:[Math.round(fe/Fe*100),"%"]})]})]})})})()}),C.jsx(Sge,{boardCards:Array.isArray((yI=U==null?void 0:U.gameState)==null?void 0:yI.pokerCommunity)?U.gameState.pokerCommunity:[]}),C.jsx("div",{className:"poker-board poker-community","aria-label":"community-cards",children:Array.isArray((Bc=U==null?void 0:U.gameState)==null?void 0:Bc.pokerCommunity)&&U.gameState.pokerCommunity.map((BA,LA)=>{const re=st.has(LA)||LA>=(lc.current||0),ke=U.gameState.pokerCommunity,ue=mge(LA),Le=yge(ke,LA),Te=ue==="river"&&ke.length===5;return C.jsx(Nge,{value:BA,concealed:re,position:ue,isPaired:Le,animateEntrance:Te&&!re},`${BA}-${LA}`)})}),Array.isArray((sC=U==null?void 0:U.gameState)==null?void 0:sC.pokerCommunity)&&U.gameState.pokerCommunity.length>0&&(()=>{const BA=U.gameState.pokerCommunity;return JZ(BA).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":"",ng&&!$e?"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(_pA,{cards:eA,firstRevealed:!!gA,bothRevealed:!!sA})]})})]}),To&&C.jsx("div",{className:"poker-timeout-toast","aria-live":"polite",style:{position:"fixed",left:To.x,top:To.y,transform:"translate(-50%, -100%)"},children:To.text})]}),wA&&C.jsx(uge,{players:Ri,entries:HA,onClose:()=>xA(!1)}),Ie.length>0&&C.jsx(ypA,{anim:Ie[0],onComplete:()=>{Ie[0],DA(BA=>BA.slice(1))}},Ie[0].id)]}),C.jsxs("div",{className:"poker-actions-wrap",ref:oe,children:[C.jsxs("div",{className:["poker-actions","poker-actions--group","poker-actions--segmented",ng&&!$e?"poker-actions--halo":""].filter(Boolean).join(" "),role:"group","aria-label":"Action buttons","aria-disabled":$e||void 0,children:[Pe&&C.jsx($l,{label:"Check",ariaLabel:"Check",size:"md",disabled:$e,onClick:ry,className:"poker-action--flat poker-action--secondary poker-action--check"}),!Pe&&OA&&C.jsx($l,{label:"Call",subtitle:`z${fe}`,ariaLabel:`Call ${fe}`,size:"md",disabled:$e,onClick:oa,className:"poker-action--flat poker-action--primary poker-action--call"}),XA&&C.jsx($l,{label:"Bet",subtitle:ta>0?`z${ta}`:void 0,ariaLabel:"Bet",size:"md",disabled:$e,onClick:Pd,className:"poker-action--green poker-action--secondary poker-action--bet"}),!XA&&_e&&C.jsx($l,{label:"Raise",subtitle:ta>0?`z${ta}`:void 0,ariaLabel:"Raise",size:"md",disabled:$e,onClick:vB,className:["poker-action--green","poker-action--secondary","poker-action--raise",hI==="raise"&&ia?"raise-active":""].filter(Boolean).join(" ")}),wo==="active"&&C.jsx($l,{label:"Fold",ariaLabel:"Fold",size:"md",disabled:$e,onClick:Bl,className:"poker-action--flat poker-action--danger poker-action--fold"})]}),C.jsx("div",{className:"poker-chiprack",style:ia?void 0:{visibility:"hidden",pointerEvents:"none"},children:C.jsx(SdA,{onPlaceBet:jd,onCancelBet:ay,disabled:$e,defaultValue:Math.max(1,rA||1),max:Fe>0?Fe:void 0})})]})]}),jA&&C.jsxs("div",{className:"elim-toast",children:[C.jsx("div",{className:"elim-toast__text",children:jA.text}),jA.sub&&C.jsx("div",{className:"elim-toast__sub",children:jA.sub})]}),bA&&C.jsx(wge,{winner:bA.winner,eliminatedOrder:bA.eliminatedOrder,finalStates:bA.finalStates,nameOf:BA=>{const LA=Ri.find(re=>re.id===BA);return(LA==null?void 0:LA.name)||BA.slice(0,6)},meId:Og,onDismiss:()=>De(null)}),le&&C.jsx(bpA,{winnerName:(()=>{var LA;const BA=Ri.find(re=>re.id===le.winnerUserId);return(BA==null?void 0:BA.name)||((LA=le.winnerUserId)==null?void 0:LA.slice(0,6))||"Winner"})(),bonus:le.bonus,isHero:le.winnerUserId===Og,onDismiss:()=>qA(null)})]})}function xZ(){const e=Ji(),{user:A}=en(),[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(_Z,{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(fM,{label:"Check",ariaLabel:"Check",size:"md",onClick:()=>{},className:"poker-action--flat"}),C.jsx(fM,{label:"Bet",ariaLabel:"Bet",size:"md",onClick:()=>{},className:"poker-action--flat"}),C.jsx(fM,{label:"Fold",ariaLabel:"Fold",size:"md",onClick:()=>{},className:"poker-action--flat poker-action--fold"})]})})]})}const Qh=(e,A)=>({rank:e,suit:A}),J0={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}]},Rge=[{kind:"call",amount:25},{kind:"fold"},{kind:"check"},{kind:"bet",amount:0},{kind:"raise",to:0}];function VtA(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 XtA(e){return`${e.rank}${e.suit}`}function Gge(e={1:0,5:0,10:0,25:0,100:0,500:0}){const[A,t]=E.useState(e),i=E.useMemo(()=>fpA.reduce((s,r)=>s+r*(A[r]??0),0),[A]),n=E.useCallback(s=>{t(r=>({...r,[s]:(r[s]??0)+1}))},[]),g=E.useCallback(s=>{t(r=>r[s]?{...r,[s]:0}:r)},[]),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 TZ(){const{user:e}=en(),[A,t]=he.useState(!1),i=J0.players.find(l=>l.isHero),n=J0.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:r,addChip:a,clearChip:I,clearAllChips:c}=Gge();return C.jsx(C.Fragment,{children:C.jsx(_Z,{header:C.jsx("div",{className:"poker-room-header",children:C.jsx(UZ,{roomName:J0.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:J0.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":XtA(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:["$",J0.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":XtA(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:Rge.map((l,B)=>C.jsx(fM,{label:VtA(l),ariaLabel:VtA(l),size:"md",onClick:()=>{}},B))})}),C.jsx("div",{className:"poker-chiprack",children:C.jsx(FpA,{selectedTimes:s,onAdd:a,onClear:I,onPlaceBet:()=>{c()},onCancelBet:()=>{c()},disabled:!1,collapsed:!1,miniChips:!0,mainAmt:r,betTokenProps:{isBanker:!1,meId:i.id,open:[],players:n,show:!0}})})]})})})}function xpA(){const e=Math.floor(Math.random()*6)+1,A=Math.floor(Math.random()*6)+1;return[e,A]}function TpA(e){return e[0]===e[1]}function bge(e,A,t){const i=(e+A)%t,n=e+A>=t;return{newTile:i,passedStart:n}}function Uge(e,A,t){const i=[];let n=e;for(;n!==A;)n=(n+1)%t,i.push(n);return i}function vge(e,A){return{...e,credits:e.credits+A.passStartBonus}}function Kge(e,A,t){const i=A[0]+A[1],{newTile:n,passedStart:g}=bge(e.tileIndex,i,t.tileCount),o=Uge(e.tileIndex,n,t.tileCount);let s={...e,tileIndex:n};return g&&(s=vge(s,t)),{player:s,passedStart:g,path:o}}function yM(e,A){return{...e,tileIndex:A,inJail:!0,jailTurnsLeft:3}}function Fge(e,A,t){if(TpA(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 _ge(e,A){return{...e,inJail:!1,jailTurnsLeft:0,credits:e.credits-A}}function Jge(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 Lge(e,A,t,i){return e.rent?e.rent[A.upgradeLevel]??e.rent[0]??0:0}function xge(e,A,t){const i=Jge(e,A,t);return i<=0?0:25*Math.pow(2,i-1)}const Tge=[{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}],qge=[{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}],Yge=[{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}],Hge=[{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 qZ(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=Lge(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=xge(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(a=>a.type==="wormhole").sort((a,I)=>a.id-I.id),o=g.findIndex(a=>a.id===e.id),s=o>=0?o%2===0?o+1:o-1:-1,r=s>=0?g[s]:void 0;return{tileId:e.id,action:"wormhole",targetTile:(r==null?void 0:r.id)??e.id}}case"asteroid":{const g=n?qge:Tge,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 r=i.filter(I=>I.type==="station").map(I=>I.id).sort((I,c)=>I-c),a=r.filter(I=>I>A.tileIndex);s.cardMoveTo=a.length>0?a[0]:r[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?Hge:Yge,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 qpA(e){const A=e.findIndex(t=>t.type==="jail");return A>=0?A:10}function YpA(e){return{playerId:e,phase:"pre-roll",diceValues:null,doublesCount:0,rolledDoubles:!1,landedTile:null,strikeUsed:!1}}function Oge(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={...un,tileCount:e.board.length},o=qpA(e.board);let s={...e.players[n]};const r=A??xpA();i.diceValues=r,t.push({type:"roll",playerId:s.id,dice:r});const a=TpA(r);if(i.doublesCount=a?i.doublesCount+1:0,i.rolledDoubles=a,i.doublesCount>=3){s=yM(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}=Fge(s,r,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}=Kge(s,r,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?qZ(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:a?"pre-roll":"done"}},events:t,effect:null};!Q||Q.action==="none"?i.phase=a?"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&&ys[s.heroId]&&(S!=null&&S.heroId)&&ys[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(q=>q.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,T=Number.POSITIVE_INFINITY;for(const[v,U]of _)(U.count>J||U.count===J&&U.firstTile<T)&&(K=v,J=U.count,T=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 Pge(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=yM(i,qpA(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 jge(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:YpA(e.players[t].id),roundNumber:i,pendingEffect:null}}const Tp=1e3,qp=500,HpA=1e3,OpA=500,PpA=3,Ym={bullseye:.55,hit:1.4,graze:2.4},LY=["crimson-dominion","silver-pact","azure-sovereignty","golden-imperium","emerald-collective","void-enclave"],$tA=["#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 r=g.map(l=>{const B=i.find(Q=>Q.tileId===l&&Q.ownerId===e);return B?B.upgradeLevel:0}),a=Math.min(...r),I=i.find(l=>l.tileId===A&&l.ownerId===e),c=I?I.upgradeLevel:0;return c>a?c:Math.min(c+1,5)}function zge(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(a=>A.some(I=>I.tileId===a&&I.ownerId===g.ownerId))?g:(i=!0,{...g,upgradeLevel:0})});return i?n:A}function Zge(e,A,t,i,n){const g=i??LY[t%LY.length],o=LY.indexOf(g);return{id:e,displayName:A,credits:un.startingCredits,tileIndex:0,inJail:!1,jailTurnsLeft:0,depleted:!1,piece:g,pieceColor:$tA[o>=0?o:t%$tA.length],armorLevel:0,weaponLevel:0,heroId:n}}function Wge(e,A,t){const i=e.map((g,o)=>Zge(g.id,g.name,o,g.piece,g.heroId)),n=$F(A);return{matchId:crypto.randomUUID(),boardSize:A,players:i,properties:[],currentTurn:YpA(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 AiA(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),r=e.properties.filter(m=>s.includes(m.tileId)&&m.ownerId===g.id).length,I=s.length>0&&r===s.length?HpA:OpA,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+PpA};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=qZ(p,l[i],B,e.board);if(y&&y.action==="energy-toll"){const m=l[i];m.heroId&&ys[m.heroId]&&g.heroId&&ys[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 Vge(e,A,t,i,n=!1){const[g,o]=E.useState(()=>A??Wge(e,t,i)),s=E.useRef(g);s.current=g;const[r,a]=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,a(W)}else if(B.current.length>0){const W=B.current;B.current=[],a($=>[...$,...W])}}),E.useEffect(()=>{o(W=>{const $=zge(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=xpA(),$=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=Oge(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 CA=$.currentTurn.rolledDoubles?"pre-roll":"done",cA={...$.currentTurn,phase:CA};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*un.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(HA=>HA.tileId===$.tileId&&HA.ownerId!==H.id&&HA.upgradeLevel>0&&!HA.dormant);if(xA!==-1){oA=[...oA];const HA=oA[xA],zA=HA.upgradeLevel-1;oA[xA]={...HA,upgradeLevel:zA},B.current.push({type:"strike",playerId:H.id,tileId:$.tileId,newLevel:zA})}}const CA=oA.find(xA=>xA.tileId===$.tileId);if(!CA)return W;const cA=H.credits-iA,_A={...H,credits:cA},uA=W.players.findIndex(xA=>xA.id===CA.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:CA.ownerId,tileId:$.tileId,amount:iA});const O=oA!==W.properties,lA={...W.currentTurn,strikeUsed:O?!0:W.currentTurn.strikeUsed};if(cA<=0){if(oA.filter(HA=>HA.ownerId===H.id).length>0)return{...W,players:X,properties:oA,currentTurn:{...lA,phase:"in-debt"},pendingEffect:null};X[L]={..._A,credits:0,depleted:!0},B.current.push({type:"depleted",playerId:H.id})}const wA=lA.rolledDoubles?"pre-roll":"done";return{...W,players:X,properties:oA,currentTurn:{...lA,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(EA=>EA.tileId===$.tileId);if(!tA)return W;const iA=W.players.find(EA=>EA.id===tA.ownerId);if(!iA)return W;const oA=H.heroId?ys[H.heroId]:null,CA=iA!=null&&iA.heroId?ys[iA.heroId]:null;if(!oA||!CA)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,lA=X+O,wA=mu(oA.empire,oA.tier).defense,xA=mu(CA.empire,CA.tier).attack,HA=Math.min(wA*uA/7,.9),zA=Math.min(xA*lA/7,3),ne=H.armorLevel*un.armorDamageReduction;let ye=W.properties;if(H.weaponLevel>=1&&W.currentTurn.rolledDoubles&&!W.currentTurn.strikeUsed){const EA=ye.findIndex(j=>j.tileId===$.tileId&&j.ownerId!==H.id&&j.upgradeLevel>0&&!j.dormant);if(EA!==-1){ye=[...ye];const j=ye[EA],dA=j.upgradeLevel-1;ye[EA]={...j,upgradeLevel:dA},B.current.push({type:"strike",playerId:H.id,tileId:$.tileId,newLevel:dA})}}const Ee=Math.round(P*(1+zA)),NA=Math.max(1,Math.round(Ee*(1-ne)*(1-HA)));B.current.push({type:"hero-clash",attackerId:iA.id,defenderId:H.id,tileId:$.tileId,attackDice:[X,O],defenseDice:[cA,_A],attackHeroId:CA.id,defenseHeroId:oA.id,baseDamage:P,finalDamage:NA});const QA=H.credits-NA,PA={...H,credits:QA},VA=W.players.findIndex(EA=>EA.id===tA.ownerId),KA=[...W.players];KA[L]=PA,VA!==-1&&(KA[VA]={...KA[VA],credits:KA[VA].credits+NA}),B.current.push({type:"energy-toll",payerId:H.id,ownerId:tA.ownerId,tileId:$.tileId,amount:NA});const Ie=ye!==W.properties,DA={...W.currentTurn,strikeUsed:Ie?!0:W.currentTurn.strikeUsed};if(QA<=0){if(ye.filter(dA=>dA.ownerId===H.id).length>0)return{...W,players:KA,properties:ye,currentTurn:{...DA,phase:"in-debt"},pendingEffect:null};KA[L]={...PA,credits:0,depleted:!0},B.current.push({type:"depleted",playerId:H.id});const j=DA.rolledDoubles?"pre-roll":"done";return{...W,players:KA,properties:ye,currentTurn:{...DA,phase:j},pendingEffect:null}}const IA=DA.rolledDoubles?"pre-roll":"done";return{...W,players:KA,properties:ye,currentTurn:{...DA,phase:IA},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",CA={...W.currentTurn,phase:oA};return{...W,players:iA,currentTurn:CA,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 CA=W.board.findIndex(cA=>cA.type==="jail");return tA[L]=yM(W.players[L],CA>=0?CA: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 CA=W.players[L].tileIndex,cA=$.cardMoveTo,_A=cA<CA;let uA={...W.players[L],tileIndex:cA};_A&&(uA={...uA,credits:uA.credits+un.passStartBonus}),H!==0&&(uA={...uA,credits:uA.credits+H}),tA[L]=uA,B.current.push({type:"move",playerId:uA.id,from:CA,to:cA,passedStart:_A});const X=W.board[cA];if(X){const lA=qZ(X,uA,W.properties,W.board);if(lA.action==="go-to-jail"){const wA=W.board.findIndex(xA=>xA.type==="jail");return tA[L]=yM(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(lA.action!=="none")return{...W,players:tA,currentTurn:{...W.currentTurn,phase:"action"},pendingEffect:lA}}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 CA=Math.abs(H),cA=W.players[L].credits-CA;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=yM(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=>Pge(W))},[]),N=E.useCallback(()=>{o(W=>{const $=W.currentPlayerIndex,L=_ge(W.players[$],un.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:jge(W)),B.current=[],Q.current=!1,a([])},[]),M=E.useCallback(()=>{o(W=>(yQA(W),W))},[]);E.useEffect(()=>{g.finished&&A3()},[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 CA=[...$.players];CA[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:CA,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),CA=[...$.players];CA[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:CA,properties:cA}})},[]),[K,J]=E.useState(null),T=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),CA=[...$.players];CA[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:CA,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),CA=[...$.players];CA[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:CA,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),CA=[...$.players];CA[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:CA,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}}})},[]),q=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),CA=$.properties.filter(O=>oA.includes(O.tileId)&&O.ownerId===H.id&&!O.dormant).length;if(CA<=0)return $;const cA=iA.upgradeCost*(oA.length-CA+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 CA=[...$.players],cA=W.offerer.credits-W.recipient.credits;CA[L]={...P,credits:P.credits-cA},CA[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:CA,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>=un.maxArmorLevel||L.credits<un.armorUpgradeCost)return W;const H=L.armorLevel+1,P=[...W.players];return P[$]={...L,credits:L.credits-un.armorUpgradeCost,armorLevel:H},B.current.push({type:"upgrade-armor",playerId:L.id,level:H,cost:un.armorUpgradeCost}),{...W,players:P}})},[]),sA=E.useCallback(()=>{o(W=>{const $=W.currentPlayerIndex,L=W.players[$];if(L.weaponLevel>=un.maxWeaponLevel||L.credits<un.weaponUpgradeCost)return W;const H=L.weaponLevel+1,P=[...W.players];return P[$]={...L,credits:L.credits-un.weaponUpgradeCost,weaponLevel:H},B.current.push({type:"upgrade-weapon",playerId:L.id,level:H,cost:un.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(un.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(un.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,lA;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)??((lA=$.players.find(wA=>wA.id!==P))==null?void 0:lA.id);if(!P||!tA)return $;const iA=L===P?tA:P,oA=$.players.findIndex(wA=>wA.id===L),CA=$.players.findIndex(wA=>wA.id===iA);if(oA===-1||CA===-1)return $;const cA=Number.isFinite(W.creditsStolen)?Math.max(0,Math.floor(W.creditsStolen)):0,_A=Math.min(cA,$.players[CA].credits),uA=[...$.players];return uA[oA]={...uA[oA],credits:uA[oA].credits+_A},uA[CA]={...uA[CA],credits:Math.max(0,uA[CA].credits-_A)},B.current.push({type:"raid",attackerId:P,defenderId:tA,winnerId:L,creditsStolen:_A}),{...$,players:uA}})},[]),fA=E.useCallback(W=>{o($=>{var zA,ne,ye;if((zA=$.gameRules)!=null&&zA.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||(ne=$.spies)!=null&&ne[W])return $;const tA=((ye=$.siegeCooldowns)==null?void 0:ye[W])??0;if($.roundNumber<tA)return $;const iA=$.board.filter(Ee=>Ee.group===W).map(Ee=>Ee.id);if(iA.length===0)return $;const oA=new Map(iA.map(Ee=>{var NA;return[Ee,(NA=$.properties.find(QA=>QA.tileId===Ee))==null?void 0:NA.ownerId]})),CA=iA.filter(Ee=>oA.get(Ee)===H.id).length,cA=iA.filter(Ee=>oA.get(Ee)!==H.id),_A=iA.some(Ee=>{const NA=oA.get(Ee);return!!NA&&NA!==H.id}),uA=oA.get(iA[0]),X=!!uA&&uA!==H.id&&iA.every(Ee=>$.properties.some(NA=>NA.tileId===Ee&&NA.ownerId===uA&&!NA.dormant));let O=null,lA=0;if(n&&CA>0&&_A)O="foothold",lA=qp;else if(n&&X)O="monopoly",lA=Tp;else if(CA===0){const Ee=oA.get(iA[0]);if(!Ee||Ee===H.id||!iA.every(QA=>$.properties.some(PA=>PA.tileId===QA&&PA.ownerId===Ee&&!PA.dormant)))return $;O="monopoly",lA=Tp}else if(cA.length>0&&cA.every(Ee=>!!oA.get(Ee)))O="foothold",lA=qp;else return $;if(H.credits<lA)return $;const wA=[...$.players];wA[$.currentPlayerIndex]={...H,credits:H.credits-lA};const xA={...$.spies??{},[W]:H.id},HA={...$.spyKinds??{},[W]:O};return B.current.push({type:"spy-plant",playerId:H.id,group:W,cost:lA}),{...$,players:wA,spies:xA,spyKinds:HA}})},[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"}}:AiA($,L,B.current))})},[]),YA=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(lA=>lA.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 AiA($,L,B.current);const iA={...$.currentTurn},oA=$.board.filter(lA=>lA.group===L.group).map(lA=>lA.id),CA=$.properties.map(lA=>oA.includes(lA.tileId)&&lA.ownerId!==H.id?(B.current.push({type:"seizure",attackerId:H.id,defenderId:tA.id,tileId:lA.tileId,group:L.group}),{...lA,ownerId:H.id}):lA),cA=[...$.players];if(tA.heroId){const lA=tA.heroId;cA[P]={...tA,heroId:void 0,formerHeroId:lA,heroVanquishedById:H.id},B.current.push({type:"hero-vanquished",vanquisherId:H.id,victimId:tA.id,formerHeroId:lA})}const _A={...$.spies??{}};delete _A[L.group];const uA=Object.keys(_A).length>0?_A:void 0,X={...$.siegeCooldowns??{},[L.group]:$.roundNumber+PpA};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:CA,currentTurn:{...iA,phase:O},pendingEffect:null,spies:uA,siegeCooldowns:X}})},[]);return{gameState:g,events:r,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:T,debtSell:v,debtLiquidateArm:U,debtResolve:x,sabotageProperty:q,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:YA}}}const h_=new Map;let tU=null;function $3(){if(h_.size===0)return;const e=pw();if(e)for(const[A,t]of h_)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 jpA(){const e=pw();if(!(!e||tU===e)){if(tU)try{tU.off("connect",$3)}catch{}tU=e;try{e.on("connect",$3)}catch{}}}function Xge(e,A,t){if(!e||!Array.isArray(t)||t.length===0)return;jpA();const i=pw();if(i)try{i.emit("client:game-events",{gameId:e,gameType:A,events:t})}catch{}}function $ge(e,A,t){e&&(h_.set(e,{gameType:A,...t}),jpA(),$3())}function Aoe(e){if(!e)return;h_.delete(e);const A=pw();if(A)try{A.emit("client:broadcast-unregister",{gameId:e})}catch{}}function Jr(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=Zi(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 eoe(e,A){var t;if(!(!e||!A))return(t=e.players.find(i=>i.id===A))==null?void 0:t.credits}function toe(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=Jr(A,n.playerId),g.dice=n.dice,g.amount=n.dice[0]+n.dice[1];break}case"move":{g.playerName=Jr(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=Jr(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=Jr(A,n.payerId),g.otherName=Jr(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=eoe(A,n.payerId);break}case"upgrade":case"sabotage":{g.playerName=Jr(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=Jr(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=Jr(A,n.playerId);break}case"card":{g.playerName=Jr(A,n.playerId);break}case"void-drain":{g.playerName=Jr(A,n.playerId),g.amount=n.amount;break}case"trade":{g.playerName=Jr(A,n.offererId),g.otherName=Jr(A,n.recipientId);break}case"seizure":{g.playerName=Jr(A,n.attackerId),g.otherName=Jr(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=Jr(A,n.playerId),g.level=n.level,g.amount=n.cost;break}default:{const o=n;if(o.playerId&&(g.playerName=Jr(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 ioe=3e3,WB=3e3,noe=3e3,goe=noe+750,ooe=500,soe=750;function roe({isMyTurn:e,phase:A,pendingEffect:t,pendingTrade:i,inJail:n,credits:g,botPlayerIds:o,currentPlayerId:s,properties:r,board:a,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=a[M],_=(b==null?void 0:b.cost)??100,K=r.find(T=>T.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=a.filter(x=>x.group===b.group).map(x=>x.id).filter(x=>x!==M),U=v.filter(x=>r.some(q=>q.tileId===x&&q.ownerId===S&&!q.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=a.filter(x=>x.group===b.group).map(x=>x.id).filter(x=>x!==M),U=v.filter(x=>r.some(q=>q.tileId===x&&q.ownerId===S&&!q.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()},WB);return()=>clearTimeout(D)},[i,o,I,a,r]),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?a[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 T=a.filter(v=>v.group===b).map(v=>v.id);if(T.length>0){const v=new Map(T.map(aA=>{var sA;return[aA,(sA=r.find(pA=>pA.tileId===aA))==null?void 0:sA.ownerId]})),U=T.filter(aA=>v.get(aA)===s).length,x=T.filter(aA=>v.get(aA)!==s);let q=!1;const z=T.some(aA=>{const sA=v.get(aA);return!!sA&&sA!==s}),Z=v.get(T[0]),eA=!!Z&&Z!==s&&T.every(aA=>r.some(sA=>sA.tileId===aA&&sA.ownerId===Z&&!sA.dormant));if(d&&U>0&&z)q=g>=qp;else if(d&&eA)q=g>=Tp;else if(U===0){const aA=v.get(T[0]);q=!!aA&&aA!==s&&T.every(pA=>r.some(gA=>gA.tileId===pA&&gA.ownerId===aA&&!gA.dormant))&&g>=Tp}else x.length>0&&x.every(aA=>!!v.get(aA))&&(q=g>=qp);if(q)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()},soe)},ooe),D}}}}if(A==="pre-roll"){const G=`${s}|${h??0}`;if(I.proposeTrade&&y.current!==G&&!i&&l){const w=[],b=r.filter(K=>K.ownerId===s&&!K.dormant);for(const K of b){const J=a[K.tileId];if(!J||J.type!=="planet"||!J.group)continue;const T=a.filter(q=>q.group===J.group).map(q=>q.id);if(T.length<2)continue;const v=T.filter(q=>q!==K.tileId),U=new Map;for(const q of v){const z=(N=r.find(Z=>Z.tileId===q))==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[q,z]of U){const Z=l.find(pA=>pA.id===q&&!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:q,offerTileIds:[K.tileId],askCredits:sA,requestTileIds:[],giveCredits:0,priority:(eA?100:10)+z})}if(U.size===0)for(const q of l){if(q.id===s||q.depleted)continue;const z=Math.min(Math.max(0,q.credits-30),Math.max(20,Math.round((J.cost??100)*.95)+x));z<=0||w.push({rivalId:q.id,offerTileIds:[K.tileId],askCredits:z,requestTileIds:[],giveCredits:0,priority:1})}}const _=new Map;for(const K of b){const J=a[K.tileId];J!=null&&J.group&&_.set(J.group,(_.get(J.group)??0)+1)}for(const K of a){if(!K||K.type!=="planet"||!K.group)continue;const J=r.find(sA=>sA.tileId===K.id);if(!J||J.ownerId===s||J.dormant)continue;const T=l.find(sA=>sA.id===J.ownerId&&!sA.depleted);if(!T)continue;const v=a.filter(sA=>sA.group===K.group).map(sA=>sA.id);if(v.length<2)continue;const U=_.get(K.group)??0,x=v.length,q=U===x-1;let z,Z;if(q)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=>r.some(gA=>gA.tileId===pA&&gA.ownerId===T.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:T.id,offerTileIds:[],askCredits:0,requestTileIds:[K.id],giveCredits:aA,priority:Z})}if(w.length>0){w.sort((J,T)=>T.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)},WB),D}}const M=r.filter(w=>w.ownerId===s&&!w.dormant&&w.upgradeLevel<Hm(s,w.tileId,a,r)).map(w=>{var b;return{...w,cost:((b=a[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)},WB):p.current=setTimeout(()=>{n&&g>=un.jailBailCost&&I.payBailAction(),I.roll()},ioe)}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()}},WB);else if(A==="action"&&!t)p.current=setTimeout(()=>{I.endTurn()},WB);else if(A==="in-debt"){const G=r.filter(b=>b.ownerId===s).map(b=>{var _;return{...b,value:((_=a[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)},WB):M?p.current=setTimeout(()=>{I.debtLiquidateArm(M.tileId)},WB):p.current=setTimeout(()=>{I.debtResolve()},WB):p.current=setTimeout(()=>{I.debtResolve()},WB)}else A==="done"&&(p.current=setTimeout(()=>{I.endTurn()},goe));return D},[e,A,t,i,n,g,o,s,r,a,I,c,l,B,Q,h,d])}const aoe="/assets/azzure_turret_1-BSF6kRPN.png",Ioe="/assets/azzure_turret_2-BS9BQ0Wh.png",Coe="/assets/azzure_turret_3-wzqgy1Re.png",coe="/assets/azzure_turret_4-DszsO8pE.png",loe="/assets/azzure_turret_5-BDNt-52F.png",Boe="data:image/png;base64, ",Eoe="/assets/crimson_turret_2-Dzdivnfl.png",Qoe="/assets/crimson_turret_3-FCW5cjNx.png",uoe="/assets/crimson_turret_4-x6XdwjO_.png",doe="/assets/crimson_turret_5-COBT408e.png",hoe="/assets/emerald_turret_1-BAxyQCsm.png",poe="/assets/emerald_turret_2-Cb5EKOec.png",foe="/assets/emerald_turret_3-Djy1RF5l.png",yoe="/assets/emerald_turret_4-Dvqo9xGL.png",Doe="/assets/emerald_turret_5-DbPXnTsf.png",moe="/assets/gold_turret_1-ouFUy0uc.png",Soe="/assets/gold_turret_2-lUsFpFSb.png",woe="/assets/gold_turret_3-DdV6hrcF.png",koe="/assets/gold_turret_4-DTvBKETa.png",Moe="/assets/gold_turret_5-BoxTnz4z.png",Noe="/assets/silver_turret_1-BruS00ga.png",Roe="/assets/silver_turret_2-BIg82_xi.png",Goe="/assets/silver_turret_3-CJ-TtmjD.png",boe="/assets/silver_turret_4-Db8itTac.png",Uoe="/assets/silver_turret_5-BuHepi2d.png",voe="/assets/void_turret_1-CR92XhVP.png",Koe="/assets/void_turret_2-CTH3oOBV.png",Foe="/assets/void_turret_3-BoJPDIYG.png",_oe="/assets/void_turret_4-BAmR9i7p.png",Joe="/assets/void_turret_5-D-M1TouY.png",zpA=[{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"}],p_=1e3,f_=780,A4=40,YZ=Array.from({length:A4},(e,A)=>{const t=A*360/A4-90,i=t*Math.PI/180;return{x:p_+f_*Math.cos(i),y:p_+f_*Math.sin(i),rotation:t+90}});function ZpA(e){return e===A4?YZ:Array.from({length:e},(A,t)=>{const i=t*360/e-90,n=i*Math.PI/180;return{x:p_+f_*Math.cos(n),y:p_+f_*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 Loe=pB.FLIGHT_DURATION_MS,eiA=pB.LIFTOFF_DELAY_MS,WpA=pB.BOARD_ROTATE_MS,xoe=`transform ${WpA}ms cubic-bezier(0.4, 0, 0.2, 1)`,tiA=1e3,xY=pB.DESTROY_BLAST_MS;function Toe(e){return e<=1?1:e===2?.72:e===3?.62:e===4?.54:e===5?.48:.44}function qoe(e){return e<=1?1:e===2?.62:e===3?.52:e===4?.44:e===5?.39:.35}function Yoe(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,r=16,a=20,I=s/(2*Math.sin(Math.PI/Math.max(o,2))),c=Math.max(a,I)+i*r,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 Hoe(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 Ooe=0,Poe=({players:e,currentPlayerId:A,onMoveStart:t,onFlightStart:i,onArrival:n,zoom:g=10,boardRotation:o=0,tileCount:s=40,gameTileCount:r,jailTileIndex:a=10,onlyCurrentPlayer:I=!1})=>{const c=r??s,l=s===40?YZ:ZpA(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 q=v.id===A;d(Z=>{const eA=new Set(Z);return eA.add(v.id),eA}),D(Z=>({...Z,[v.id]:o})),q&&(i==null||i()),M.current[v.id+"_rotate"]=setTimeout(()=>{q&&(t==null||t(x,U))},eiA);const z=eiA+WpA+pB.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}),q&&(n==null||n(U))},Loe)}},[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 q=B[U.id]??U.tileIndex;console.log("[PIECE EXPLOSION] Triggering for",U.displayName,"at tile",q,"duration:",xY,"ms"),b(z=>({...z,[U.id]:{tileIndex:q}})),clearTimeout(M.current[U.id+"_destroy"]),M.current[U.id+"_destroy"]=setTimeout(()=>{console.log("[PIECE EXPLOSION] Removing piece",U.displayName,"after",xY,"ms"),b(z=>{if(!z[U.id])return z;const Z={...z};return delete Z[U.id],Z})},xY)}b(U=>{let x=!1;const q={};for(const[z,Z]of Object.entries(U)){if(!v.has(z)){x=!0,clearTimeout(M.current[z+"_destroy"]);continue}q[z]=Z}return x?q: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,q=v.get(x)??[];q.push(U),v.set(x,q)}return v},[_,B]),J=E.useMemo(()=>[..._].sort((v,U)=>(v.id===A?1:0)-(U.id===A?1:0)),[_,A]),T=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:T(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?Hoe(aA,eA.length):Yoe(aA,eA.length),gA=sA?qoe(eA.length):Toe(eA.length),yA=h.has(v.id),fA=v.tileIndex===a&&U===a&&!yA?v.inJail?"Cryosleep":"Visiting":void 0,RA=pA.headingDeg+Ooe,YA=Z,W=Om(v.tileIndex,o,c,s),$=l[W],L=yA&&YA&&$&&v.tileIndex!==U?Math.atan2($.y-YA.y,$.x-YA.x)*180/Math.PI:RA,H=x!==void 0?{transformOrigin:`${tiA}px ${tiA}px`,transform:`rotate(${x-o}deg)`,transition:xoe,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(GQA,{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:T(v.id),tier:(v.heroId?(iA=ys[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}`)})]})},joe=he.memo(Poe),VpA="data:image/webp;base64, ",XpA="data:image/webp;base64, ",HZ="data:image/webp;base64, ",OZ="data:image/webp;base64, ",$pA="data:image/webp;base64, ",e4="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",AfA="/assets/tile_station-BU45WlAz.webp",efA="data:image/webp;base64, ",tfA="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==",ifA="data:image/webp;base64, ",PZ="/assets/explosion-CCKtR9yS.webp",zoe=Object.assign({"../../assets/optimized/azzure_turret_1.png":aoe,"../../assets/optimized/azzure_turret_2.png":Ioe,"../../assets/optimized/azzure_turret_3.png":Coe,"../../assets/optimized/azzure_turret_4.png":coe,"../../assets/optimized/azzure_turret_5.png":loe,"../../assets/optimized/crimson_turret_1.png":Boe,"../../assets/optimized/crimson_turret_2.png":Eoe,"../../assets/optimized/crimson_turret_3.png":Qoe,"../../assets/optimized/crimson_turret_4.png":uoe,"../../assets/optimized/crimson_turret_5.png":doe,"../../assets/optimized/emerald_turret_1.png":hoe,"../../assets/optimized/emerald_turret_2.png":poe,"../../assets/optimized/emerald_turret_3.png":foe,"../../assets/optimized/emerald_turret_4.png":yoe,"../../assets/optimized/emerald_turret_5.png":Doe,"../../assets/optimized/gold_turret_1.png":moe,"../../assets/optimized/gold_turret_2.png":Soe,"../../assets/optimized/gold_turret_3.png":woe,"../../assets/optimized/gold_turret_4.png":koe,"../../assets/optimized/gold_turret_5.png":Moe,"../../assets/optimized/silver_turret_1.png":Noe,"../../assets/optimized/silver_turret_2.png":Roe,"../../assets/optimized/silver_turret_3.png":Goe,"../../assets/optimized/silver_turret_4.png":boe,"../../assets/optimized/silver_turret_5.png":Uoe,"../../assets/optimized/void_turret_1.png":voe,"../../assets/optimized/void_turret_2.png":Koe,"../../assets/optimized/void_turret_3.png":Foe,"../../assets/optimized/void_turret_4.png":_oe,"../../assets/optimized/void_turret_5.png":Joe}),Zoe=Object.fromEntries(Object.entries(zoe).map(([e,A])=>[e.split("/").pop()??e,A])),Woe={"crimson-dominion":"crimson","silver-pact":"silver","azure-sovereignty":"azzure","golden-imperium":"gold","emerald-collective":"emerald","void-enclave":"void"},Voe={"crimson-dominion":0,"silver-pact":0,"azure-sovereignty":0,"golden-imperium":135,"emerald-collective":0,"void-enclave":135},Xoe={"crimson-dominion":!1,"silver-pact":!1,"azure-sovereignty":!1,"golden-imperium":!0,"emerald-collective":!1,"void-enclave":!0};function $oe(e,A){const t=Woe[e],i=Math.max(1,Math.min(5,Math.trunc(A))),n=`${t}_turret_${i}.png`;return Zoe[n]??null}const iiA=ti.getPlatform()==="android",dn=1e3,_S=780,yr=_S-60,Xs=_S+60,eG=40,Ef=360/eG,sm=80,L0=dn-Xs-sm,iU=(Xs+sm)*2,Ase={start:VpA,planet:XpA,asteroid:HZ,nebula:OZ,wormhole:$pA,"void-drain":e4,station:AfA,jail:efA,"go-to-jail":tfA,"free-parking":ifA},ese=["#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"],t4=["#283593","#2d1060","#0c3545","#0c3545","#ef6c00","#3d2010","#3d2010","#6a1b9a","#3d1018","#3d1018","#455a64","#3d3008","#3d3008","#6a1b9a","#103520","#103520","#e53935","#102050","#102050","#351040"];function tse(e){return e===20?t4:ese}const ise=Array.from({length:eG},(e,A)=>{const t=-90+A*Ef,i=t*Math.PI/180;return{cx:dn+_S*Math.cos(i),cy:dn+_S*Math.sin(i),baseRot:t+90}});function TY(e,A){const t=((e+A)%360+360)%360,i=t>90&&t<270;return{angleDeg:i?e+180:e,flipped:i}}const niA=yr+14,nse=Array.from({length:eG},(e,A)=>{const t=-90+A*Ef-Ef*.4,i=t*Math.PI/180;return{x:dn+niA*Math.cos(i),y:dn+niA*Math.sin(i),rot:t+90}}),gse=Array.from({length:eG},(e,A)=>{const t=-90+A*Ef+Ef*.38,i=t*Math.PI/180,n=yr+8;return{x:dn+n*Math.cos(i),y:dn+n*Math.sin(i),rot:t+90}}),ose=[18,24,32,42,54],sse=[.6,.75,.9,1.1,1.4],rse=Array.from({length:eG},(e,A)=>{const i=(-90+A*Ef-Ef/2)*Math.PI/180;return{x1:dn+yr*Math.cos(i),y1:dn+yr*Math.sin(i),x2:dn+(yr-12)*Math.cos(i),y2:dn+(yr-12)*Math.sin(i)}}),qY=e=>/^#[0-9a-f]{3,8}$/i.test(e);function ku(e,A){const t=e*Math.PI/180;return{x:dn+A*Math.cos(t),y:dn+A*Math.sin(t)}}function Hr(e){return e.toFixed(2)}function ase(e,A){const t=360/A,i=-90+e*t,n=ku(i-t/2,Xs),g=ku(i+t/2,Xs),o=ku(i-t/2,yr),s=ku(i+t/2,yr);return`M${Hr(n.x)},${Hr(n.y)} A${Xs},${Xs} 0 0 1 ${Hr(g.x)},${Hr(g.y)} L${Hr(s.x)},${Hr(s.y)} A${yr},${yr} 0 0 0 ${Hr(o.x)},${Hr(o.y)} Z`}const nU=Xs-16;function Ise(e,A){const t=360/A,i=-90+e*t,n=ku(i-t/2,Xs),g=ku(i+t/2,Xs),o=ku(i-t/2,nU),s=ku(i+t/2,nU);return`M${Hr(n.x)},${Hr(n.y)} A${Xs},${Xs} 0 0 1 ${Hr(g.x)},${Hr(g.y)} L${Hr(s.x)},${Hr(s.y)} A${nU},${nU} 0 0 0 ${Hr(o.x)},${Hr(o.y)} Z`}const Cse={purple:"#7b2ff2",cyan:"#00e5ff",orange:"#ff9100",red:"#ff1744",yellow:"#ffd600",green:"#00e676",blue:"#2979ff",magenta:"#e040fb"};function nfA(e){const A=e.length;return Array.from({length:A},(t,i)=>{const n=e[i],g=n!=null&&n.group?Cse[n.group]??null:null;return{wedge:ase(i,A),fill:"#0d1b2a",strip:g?Ise(i,A):null,stripColor:g}})}const giA=new Map([[40,zpA]]);function cse(e){if(e.length===40)return zpA;const A=giA.get(e.length);if(A)return A;const t=nfA(e);return giA.set(e.length,t),t}function lse(e){const A=360/e,t=yr+14;return{positions:Array.from({length:e},(i,n)=>{const g=-90+n*A,o=g*Math.PI/180;return{cx:dn+_S*Math.cos(o),cy:dn+_S*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:dn+t*Math.cos(o),y:dn+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:dn+t*Math.cos(o),y:dn+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:dn+yr*Math.cos(o),y1:dn+yr*Math.sin(o),x2:dn+(yr-12)*Math.cos(o),y2:dn+(yr-12)*Math.sin(o)}})}}const oiA=new Map([[40,{positions:ise,badgePositions:nse,turretPositions:gse,tickMarks:rse}]]);function Bse(e){const A=oiA.get(e);if(A)return A;const t=lse(e);return oiA.set(e,t),t}const Ese=({tiles:e,onTileClick:A,children:t,rotationDeg:i=0,mini:n=!1,properties:g=[],players:o=[],liftedTile:s,laserBeamTile:r,laserBeamSeq:a=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(r==null){y(!1);return}y(!1);const K=setTimeout(()=>y(!0),d+16);return()=>{clearTimeout(K),y(!1)}},[r,a]);const m=h===20,D=m?40:h,S=Bse(D),k=E.useMemo(()=>m?nfA([...e,...e]):cse(e),[h]),N=m?[...t4,...t4]:tse(h),G=D===40?YZ:ZpA(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 q=v[x%v.length];J.set(x,{color:U[q],letter:K[q],upgradeLevel:5,piece:q})}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:qY(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(()=>r==null?null:Om(r,i,h,D),[r,i,h,D]),_=E.useMemo(()=>{if(!p||r==null||n||b==null)return null;const K=G[b];if(!K)return null;const J=g.find(q=>q.tileId===r),T=J==null?void 0:J.ownerId,v=T?o.find(q=>q.id===T):null,U=v!=null&&v.pieceColor&&qY(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,r,b,G,g,o,n,I]);return E.useMemo(()=>{if(!p||r==null||n||b==null)return null;const K=G[b];if(!K)return null;const J=g.find(q=>q.tileId===r),T=J==null?void 0:J.ownerId;if(!T)return null;const v=o.find(q=>q.id===T),U=v!=null&&v.pieceColor&&qY(v.pieceColor)?v.pieceColor:"#ff4444",x=[];for(const q of g){if(q.ownerId!==T||q.upgradeLevel<=0)continue;const z=Om(q.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,r,b,g,o,n,S,G,i,h,D]),C.jsxs("svg",{viewBox:`${L0} ${L0} ${iU} ${iU}`,className:"zentara-svg",children:[C.jsx("rect",{x:L0,y:L0,width:iU,height:iU,fill:"transparent"}),C.jsxs("g",{ref:l,style:{transformOrigin:`${dn}px ${dn}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:dn,cy:dn,r:Xs+4,fill:"none",stroke:"#5ab0e0",strokeWidth:6,opacity:.18}),C.jsx("circle",{cx:dn,cy:dn,r:Xs,fill:"none",stroke:"#3a80b0",strokeWidth:2.5,opacity:.55,className:n||iiA?void 0:"zentara-orbit-ring"}),!n&&!iiA&&C.jsx("circle",{cx:dn,cy:dn,r:Xs-8,fill:"none",stroke:"#8eeaff",strokeWidth:3,strokeLinecap:"round",strokeDasharray:"38 180",opacity:.55,className:"zentara-orbit-scan"}),C.jsx("circle",{cx:dn,cy:dn,r:yr,fill:"none",stroke:"#1e4a6e",strokeWidth:1.5,opacity:.45}),!n&&C.jsx("circle",{cx:dn,cy:dn,r:yr-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 T=e[J%h],v=S.positions[J],U=(T==null?void 0:T.type)==="start",x=J>=h;return C.jsxs("g",{"data-visual-tile":J,onClick:!n&&!x&&A?()=>A(T.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&&T&&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 CA;const T=e[J%h];if(!T)return null;const{angleDeg:v,flipped:U}=TY(K.baseRot,i),x=U?-28:28,q=T.name,z=15;let Z;if(q.length>10&&q.includes(" ")){const cA=Math.floor(q.length/2),uA=[...q.matchAll(/ /g)].map(X=>X.index).reduce((X,O)=>Math.abs(O-cA)<Math.abs(X-cA)?O:X);Z=[q.slice(0,uA),q.slice(uA+1)]}else Z=[q];const eA=J%h,aA=w.get(eA);let sA=null;if(aA&&T.rent&&T.rent.length>0){const cA=Math.max(0,Math.min(T.rent.length-1,aA.upgradeLevel));sA=`⚡ ${T.rent[cA]}`}else typeof T.cost=="number"&&T.cost>0&&(sA=`◈ ${T.cost}`);const pA=Z.length*z+14,gA=Math.max(...Z.map(cA=>cA.length*8.2+32)),yA=K.cy+x,fA=(CA=k[J])==null?void 0:CA.stripColor,RA=fA??"rgba(100,170,255,0.45)",YA=fA?1.8:1,W=fA?`${fA}55`:"rgba(80,150,255,0.18)",$=T.type==="start",L=$?"rgba(32,55,72,0.78)":RA,H=$?1.4:YA,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:Ase[T.type],x:K.cx-18,y:uA-18,width:18*2,height:18*2,preserveAspectRatio:"xMidYMid slice",clipPath:`url(#${X})`,opacity:.95}),sA&&(()=>{const lA=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-lA/2,y:O-wA/2,width:lA,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:T}])=>(m?[K,K+h]:[K]).map(U=>{const x=S.badgePositions[U];if(!x)return null;const{angleDeg:q}=TY(x.rot,i);return C.jsxs("g",{style:{transform:`translate(${x.x}px, ${x.y}px) rotate(${q}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:T})]},`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,T]=K.split("|"),v=Number(T),U=sse[v-1]??1,x=parseInt(J.slice(1,3),16)/255,q=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 ${q} 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:T,color:v}])=>{var q;if(J<=0)return[];const U=m?[K,K+h]:[K],x=p&&r!=null&&((q=w.get(r))==null?void 0:q.color)===v;return U.map(z=>{const Z=S.turretPositions[z];if(!Z)return null;const eA=$oe(T,J);if(!eA)return null;const aA=G[z],sA=Voe[T]??0;let pA;aA?pA=Math.atan2(aA.y-Z.y,aA.x-Z.x)*180/Math.PI+180+sA:pA=TY(Z.rot,i).angleDeg+sA;const gA=ose[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,YA=-gA/2,W=RA+gA*.08,$=YA+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:Xoe[T]?{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:YA,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:PZ,x:_.cx-K/2,y:_.cy-K/2,width:K,height:K,className:"zentara-blast-explosion",pointerEvents:"none"})})()]}),n&&C.jsx("path",{d:`M${dn},${dn} L${dn},${L0} A${Xs+sm},${Xs+sm} 0 0 1 ${dn+(Xs+sm)*Math.sin(Math.PI)},${dn-(Xs+sm)*Math.cos(Math.PI)} Z`,fill:"rgba(123, 47, 242, 0.08)",stroke:"rgba(123, 47, 242, 0.3)",strokeWidth:3})]})};function Qse(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 use=he.memo(Ese,Qse);function gU(e,A){return 180-e*(360/A)}function YY(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 dse(e,A,t,i,n){const o=-((t-A+i)%i)*(360/n);return e+o}function hse(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 pse=1.5,fse=2.25,siA=[pse,fse],yse=ti.isNativePlatform(),Dse=({gameState:e,onTileClick:A,zoomOverride:t,onPieceArrival:i,onPieceMoveStart:n,onZoomChange:g,focusTileIndex:o,toggleZoomRef:s,laserBeamTile:r,laserBeamSeq:a,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=hse(e),y=d===20?40:d,[m,D]=E.useState(()=>gU(Q,y)),S=E.useRef([]),k=E.useRef(null),N=E.useRef(null),[G,M]=E.useState(0),w=siA[G],b=t??w,_=E.useCallback(()=>M(iA=>(iA+1)%siA.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=>YY(oA,gU(Q,y),d,y)),1200);return()=>clearTimeout(iA)}},[e.currentPlayerIndex,Q,e.finished,d,y]);const[T,v]=E.useState(null),U=E.useRef(void 0),x=E.useRef(null),q=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 CA=Om(iA,YA.current,d,y),cA=YA.current,_A=dse(cA,iA,oA,d,y),uA=(oA-iA+d)%d,X=lA=>{var HA;const wA=q.current;if(!wA)return;(HA=k.current)==null||HA.classList.remove("zentara-tile--moving-lit");const xA=wA.querySelector(`[data-visual-tile="${lA}"]`);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)}),!yse){X(CA);for(let lA=1;lA<=uA;lA+=1){const wA=(lA-.5)/Math.max(uA,1),xA=pB.BOARD_ROTATE_MS*wA,HA=(CA+lA)%y;S.current.push(setTimeout(()=>X(HA),xA))}}},[d,z,y]);E.useEffect(()=>{o!=null&&D(iA=>YY(iA,gU(o,y),d,y))},[o,d,y]);const eA=E.useCallback(iA=>{var oA;z(),D(CA=>YY(CA,gU(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 CA=x.current;if(!CA)return 0;const cA=CA.getBoundingClientRect(),_A=cA.left+cA.width/2,uA=cA.top+cA.height/2;return Math.atan2(oA-uA,iA-_A)*(180/Math.PI)},[]),YA=E.useRef(m);YA.current=m;const W=E.useCallback(iA=>{var cA,_A,uA,X,O,lA;if(iA.button!==0)return;(_A=(cA=iA.target).setPointerCapture)==null||_A.call(cA,iA.pointerId),fA();const oA=parseFloat(((O=(X=(uA=q.current)==null?void 0:uA.style.transform)==null?void 0:X.match(/rotate\(([^)]+)deg\)/))==null?void 0:O[1])??"NaN"),CA=Number.isFinite(oA)?oA:YA.current;aA.current={active:!0,startAngle:RA(iA.clientX,iA.clientY),startRot:CA},gA.current=[{rot:CA,t:performance.now()}],(lA=x.current)==null||lA.classList.add("zentara-board-container--dragging")},[RA,fA]),$=E.useCallback(iA=>{if(!aA.current.active)return;const CA=RA(iA.clientX,iA.clientY)-aA.current.startAngle,cA=aA.current.startRot+CA;sA.current=cA;const _A=q.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 CA=iA[iA.length-1],cA=iA[0],_A=CA.t-cA.t;let uA=_A>0?(CA.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 lA=CA.rot,wA=performance.now();const xA=()=>{const HA=performance.now(),zA=HA-wA;wA=HA,lA+=uA*zA,uA*=Math.exp(-.0042*zA);const ne=q.current;ne&&(ne.style.transform=`rotate(${lA}deg)`),D(lA),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=CA=>{CA.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(use,{tiles:e.board,onTileClick:A,rotationDeg:m,properties:e.properties,players:e.players,liftedTile:T,laserBeamTile:r,laserBeamSeq:a,blastDamage:I,ringRef:q,currentPlayerTile:Q,currentPlayerColor:h,children:C.jsx(joe,{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]})})},mse=he.memo(Dse);let V;const Wn=new Array(128).fill(void 0);function lg(e){return Wn[e]}Wn.push(void 0,null,!0,!1);let DM=Wn.length;function rs(e){DM===Wn.length&&Wn.push(Wn.length+1);const A=DM;return DM=Wn[A],Wn[A]=e,A}function HY(e,A){try{return e.apply(this,A)}catch(t){V.__wbindgen_export_0(rs(t))}}function Gi(e){return e==null}let Vh=null;function zs(){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 SN(e){const A=lg(e);return function(t){t<132||(Wn[t]=DM,DM=t)}(e),A}const gfA=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder<"u"&&gfA.decode();let Mk=null;function ofA(e,A){return e>>>=0,gfA.decode((Mk!==null&&Mk.byteLength!==0||(Mk=new Uint8Array(V.memory.buffer)),Mk).subarray(e,e+A))}function Ae(e,A){if(!(e instanceof A))throw new Error(`expected instance of ${A.name}`)}let Ug=128;function oo(e){if(Ug==1)throw new Error("out of js stack");return Wn[--Ug]=e,Ug}let Nk=null;function sfA(){return Nk!==null&&Nk.byteLength!==0||(Nk=new Float32Array(V.memory.buffer)),Nk}function riA(e,A){return e>>>=0,sfA().subarray(e/4,e/4+A)}let Rk=null;function rfA(){return Rk!==null&&Rk.byteLength!==0||(Rk=new Uint32Array(V.memory.buffer)),Rk}let KI=0;function dh(e,A){const t=A(4*e.length,4)>>>0;return sfA().set(e,t/4),KI=e.length,t}function oU(e,A){const t=A(4*e.length,4)>>>0;return rfA().set(e,t/4),KI=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"}),Fc=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"}),Cr=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"}),OY=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,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_rawbroadphase_free(A,0)}constructor(){const A=V.rawbroadphase_new();return this.__wbg_ptr=A>>>0,OY.register(this,this.__wbg_ptr,this),this}}const aiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawccdsolver_free(e>>>0,1));class i4{__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_rawccdsolver_free(A,0)}constructor(){const A=V.rawccdsolver_new();return this.__wbg_ptr=A>>>0,aiA.register(this,this.__wbg_ptr,this),this}}const IiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcharactercollision_free(e>>>0,1));class afA{__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_rawcharactercollision_free(A,0)}constructor(){const A=V.rawcharactercollision_new();return this.__wbg_ptr=A>>>0,IiA.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 de.__wrap(A)}translationDeltaRemaining(){const A=V.rawcharactercollision_translationDeltaRemaining(this.__wbg_ptr);return de.__wrap(A)}toi(){return V.rawcharactercollision_toi(this.__wbg_ptr)}worldWitness1(){const A=V.rawcharactercollision_worldWitness1(this.__wbg_ptr);return de.__wrap(A)}worldWitness2(){const A=V.rawcharactercollision_worldWitness2(this.__wbg_ptr);return de.__wrap(A)}worldNormal1(){const A=V.rawcharactercollision_worldNormal1(this.__wbg_ptr);return de.__wrap(A)}worldNormal2(){const A=V.rawcharactercollision_worldNormal2(this.__wbg_ptr);return de.__wrap(A)}}const PY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcolliderset_free(e>>>0,1));class po{static __wrap(A){A>>>=0;const t=Object.create(po.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_rawcolliderset_free(A,0)}coTranslation(A){const t=V.rawcolliderset_coTranslation(this.__wbg_ptr,A);return de.__wrap(t)}coRotation(A){const t=V.rawcolliderset_coRotation(this.__wbg_ptr,A);return mn.__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:de.__wrap(t)}coHalfExtents(A){const t=V.rawcolliderset_coHalfExtents(this.__wbg_ptr,A);return t===0?void 0:de.__wrap(t)}coSetHalfExtents(A,t){Ae(t,de),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=zs().getInt32(n+0,!0),i=zs().getInt32(n+4,!0);let g;return t!==0&&(g=riA(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=zs().getInt32(n+0,!0),i=zs().getInt32(n+4,!0);let g;return t!==0&&(g=function(o,s){return o>>>=0,rfA().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=zs().getInt32(n+0,!0),i=zs().getInt32(n+4,!0);let g;return t!==0&&(g=riA(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:de.__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=zs().getInt32(n+0,!0),i=zs().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 Ae(t,de),V.rawcolliderset_coContainsPoint(this.__wbg_ptr,A,t.__wbg_ptr)!==0}coCastShape(A,t,i,n,g,o,s,r,a){Ae(t,de),Ae(i,Si),Ae(n,de),Ae(g,mn),Ae(o,de);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,r,a);return I===0?void 0:ux.__wrap(I)}coCastCollider(A,t,i,n,g,o,s){Ae(t,de),Ae(n,de);const r=V.rawcolliderset_coCastCollider(this.__wbg_ptr,A,t.__wbg_ptr,i,n.__wbg_ptr,g,o,s);return r===0?void 0:lx.__wrap(r)}coIntersectsShape(A,t,i,n){return Ae(t,Si),Ae(i,de),Ae(n,mn),V.rawcolliderset_coIntersectsShape(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr)!==0}coContactShape(A,t,i,n,g){Ae(t,Si),Ae(i,de),Ae(n,mn);const o=V.rawcolliderset_coContactShape(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g);return o===0?void 0:wN.__wrap(o)}coContactCollider(A,t,i){const n=V.rawcolliderset_coContactCollider(this.__wbg_ptr,A,t,i);return n===0?void 0:wN.__wrap(n)}coProjectPoint(A,t,i){Ae(t,de);const n=V.rawcolliderset_coProjectPoint(this.__wbg_ptr,A,t.__wbg_ptr,i);return Bx.__wrap(n)}coIntersectsRay(A,t,i,n){return Ae(t,de),Ae(i,de),V.rawcolliderset_coIntersectsRay(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n)!==0}coCastRay(A,t,i,n,g){return Ae(t,de),Ae(i,de),V.rawcolliderset_coCastRay(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n,g)}coCastRayAndGetNormal(A,t,i,n,g){Ae(t,de),Ae(i,de);const o=V.rawcolliderset_coCastRayAndGetNormal(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n,g);return o===0?void 0:Qx.__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){Ae(t,Si),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){Ae(i,de),Ae(n,de),Ae(g,mn),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,PY.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,r,a,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);Ae(t,Si),Ae(i,de),Ae(n,mn),Ae(s,de),Ae(r,de),Ae(a,mn),Ae(M,Zg),V.rawcolliderset_createCollider(_,this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o,s.__wbg_ptr,r.__wbg_ptr,a.__wbg_ptr,I,c,l,B,Q,h,d,p,y,m,D,S,k,N,G,M.__wbg_ptr);var w=zs().getInt32(_+0,!0),b=zs().getFloat64(_+8,!0);return w===0?void 0:b}finally{V.__wbindgen_add_to_stack_pointer(16)}}remove(A,t,i,n){Ae(t,gQ),Ae(i,Zg),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,oo(A))}finally{Wn[Ug++]=void 0}}}const CiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcollidershapecasthit_free(e>>>0,1));class lx{static __wrap(A){A>>>=0;const t=Object.create(lx.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_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 de.__wrap(A)}witness2(){const A=V.rawcollidershapecasthit_witness2(this.__wbg_ptr);return de.__wrap(A)}normal1(){const A=V.rawcharactercollision_translationDeltaApplied(this.__wbg_ptr);return de.__wrap(A)}normal2(){const A=V.rawcharactercollision_translationDeltaRemaining(this.__wbg_ptr);return de.__wrap(A)}}const ciA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcontactforceevent_free(e>>>0,1));class jZ{static __wrap(A){A>>>=0;const t=Object.create(jZ.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_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 de.__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 de.__wrap(A)}max_force_magnitude(){return V.rawcontactforceevent_max_force_magnitude(this.__wbg_ptr)}}const liA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcontactmanifold_free(e>>>0,1));let Sse=class IfA{static __wrap(A){A>>>=0;const t=Object.create(IfA.prototype);return t.__wbg_ptr=A,liA.register(t,t.__wbg_ptr,t),t}__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_rawcontactmanifold_free(A,0)}normal(){const A=V.rawcontactmanifold_normal(this.__wbg_ptr);return de.__wrap(A)}local_n1(){const A=V.rawcontactmanifold_local_n1(this.__wbg_ptr);return de.__wrap(A)}local_n2(){const A=V.rawcontactmanifold_local_n2(this.__wbg_ptr);return de.__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:de.__wrap(t)}contact_local_p2(A){const t=V.rawcontactmanifold_contact_local_p2(this.__wbg_ptr,A);return t===0?void 0:de.__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:de.__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 de.__wrap(t)}};const BiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawcontactpair_free(e>>>0,1));let wse=class CfA{static __wrap(A){A>>>=0;const t=Object.create(CfA.prototype);return t.__wbg_ptr=A,BiA.register(t,t.__wbg_ptr,t),t}__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_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:Sse.__wrap(t)}};const EiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawdebugrenderpipeline_free(e>>>0,1));let kse=class{__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_rawdebugrenderpipeline_free(A,0)}constructor(){const A=V.rawdebugrenderpipeline_new();return this.__wbg_ptr=A>>>0,EiA.register(this,this.__wbg_ptr,this),this}vertices(){return SN(V.rawdebugrenderpipeline_vertices(this.__wbg_ptr))}colors(){return SN(V.rawdebugrenderpipeline_colors(this.__wbg_ptr))}render(A,t,i,n,g){Ae(A,Zg),Ae(t,po),Ae(i,nQ),Ae(n,oQ),Ae(g,Qd),V.rawdebugrenderpipeline_render(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr)}};const QiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawdeserializedworld_free(e>>>0,1));let Mse=class cfA{static __wrap(A){A>>>=0;const t=Object.create(cfA.prototype);return t.__wbg_ptr=A,QiA.register(t,t.__wbg_ptr,t),t}__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_rawdeserializedworld_free(A,0)}takeGravity(){const A=V.rawdeserializedworld_takeGravity(this.__wbg_ptr);return A===0?void 0:de.__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:gQ.__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:Zg.__wrap(A)}takeColliders(){const A=V.rawdeserializedworld_takeColliders(this.__wbg_ptr);return A===0?void 0:po.__wrap(A)}takeImpulseJoints(){const A=V.rawdeserializedworld_takeImpulseJoints(this.__wbg_ptr);return A===0?void 0:nQ.__wrap(A)}takeMultibodyJoints(){const A=V.rawdeserializedworld_takeMultibodyJoints(this.__wbg_ptr);return A===0?void 0:oQ.__wrap(A)}};const uiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawdynamicraycastvehiclecontroller_free(e>>>0,1));class Nse{__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_rawdynamicraycastvehiclecontroller_free(A,0)}constructor(A){const t=V.rawdynamicraycastvehiclecontroller_new(A);return this.__wbg_ptr=t>>>0,uiA.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){Ae(A,de),Ae(t,de),Ae(i,de),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{Ae(t,Zg),Ae(i,po),Ae(n,zZ),V.rawdynamicraycastvehiclecontroller_update_vehicle(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,Gi(o)?4294967297:o>>>0,oo(s))}finally{Wn[Ug++]=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:de.__wrap(t)}set_wheel_chassis_connection_point_cs(A,t){Ae(t,de),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:de.__wrap(t)}set_wheel_direction_cs(A,t){Ae(t,de),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:de.__wrap(t)}set_wheel_axle_cs(A,t){Ae(t,de),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:de.__wrap(t)}wheel_contact_point_ws(A){const t=V.rawdynamicraycastvehiclecontroller_wheel_contact_point_ws(this.__wbg_ptr,A);return t===0?void 0:de.__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:de.__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=zs().getInt32(n+0,!0),i=zs().getFloat64(n+8,!0);return t===0?void 0:i}finally{V.__wbindgen_add_to_stack_pointer(16)}}}const diA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_raweventqueue_free(e>>>0,1));class lfA{__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_raweventqueue_free(A,0)}constructor(A){const t=V.raweventqueue_new(A);return this.__wbg_ptr=t>>>0,diA.register(this,this.__wbg_ptr,this),this}drainCollisionEvents(A){try{V.raweventqueue_drainCollisionEvents(this.__wbg_ptr,oo(A))}finally{Wn[Ug++]=void 0}}drainContactForceEvents(A){try{V.raweventqueue_drainContactForceEvents(this.__wbg_ptr,oo(A))}finally{Wn[Ug++]=void 0}}clear(){V.raweventqueue_clear(this.__wbg_ptr)}}const hiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawgenericjoint_free(e>>>0,1));class Ws{static __wrap(A){A>>>=0;const t=Object.create(Ws.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_rawgenericjoint_free(A,0)}static generic(A,t,i,n){Ae(A,de),Ae(t,de),Ae(i,de);const g=V.rawgenericjoint_generic(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n);return g===0?void 0:Ws.__wrap(g)}static spring(A,t,i,n,g){Ae(n,de),Ae(g,de);const o=V.rawgenericjoint_spring(A,t,i,n.__wbg_ptr,g.__wbg_ptr);return Ws.__wrap(o)}static rope(A,t,i){Ae(t,de),Ae(i,de);const n=V.rawgenericjoint_rope(A,t.__wbg_ptr,i.__wbg_ptr);return Ws.__wrap(n)}static spherical(A,t){Ae(A,de),Ae(t,de);const i=V.rawgenericjoint_spherical(A.__wbg_ptr,t.__wbg_ptr);return Ws.__wrap(i)}static prismatic(A,t,i,n,g,o){Ae(A,de),Ae(t,de),Ae(i,de);const s=V.rawgenericjoint_prismatic(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n,g,o);return s===0?void 0:Ws.__wrap(s)}static fixed(A,t,i,n){Ae(A,de),Ae(t,mn),Ae(i,de),Ae(n,mn);const g=V.rawgenericjoint_fixed(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr);return Ws.__wrap(g)}static revolute(A,t,i){Ae(A,de),Ae(t,de),Ae(i,de);const n=V.rawgenericjoint_revolute(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr);return n===0?void 0:Ws.__wrap(n)}}const jY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawimpulsejointset_free(e>>>0,1));class nQ{static __wrap(A){A>>>=0;const t=Object.create(nQ.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_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 mn.__wrap(t)}jointFrameX2(A){const t=V.rawimpulsejointset_jointFrameX2(this.__wbg_ptr,A);return mn.__wrap(t)}jointAnchor1(A){const t=V.rawimpulsejointset_jointAnchor1(this.__wbg_ptr,A);return de.__wrap(t)}jointAnchor2(A){const t=V.rawimpulsejointset_jointAnchor2(this.__wbg_ptr,A);return de.__wrap(t)}jointSetAnchor1(A,t){Ae(t,de),V.rawimpulsejointset_jointSetAnchor1(this.__wbg_ptr,A,t.__wbg_ptr)}jointSetAnchor2(A,t){Ae(t,de),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,jY.register(this,this.__wbg_ptr,this),this}createJoint(A,t,i,n){return Ae(A,Ws),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,oo(A))}finally{Wn[Ug++]=void 0}}forEachJointAttachedToRigidBody(A,t){try{V.rawimpulsejointset_forEachJointAttachedToRigidBody(this.__wbg_ptr,A,oo(t))}finally{Wn[Ug++]=void 0}}}const zY=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,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_rawintegrationparameters_free(A,0)}constructor(){const A=V.rawintegrationparameters_new();return this.__wbg_ptr=A>>>0,zY.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 ZY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawislandmanager_free(e>>>0,1));class gQ{static __wrap(A){A>>>=0;const t=Object.create(gQ.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_rawislandmanager_free(A,0)}constructor(){const A=V.rawislandmanager_new();return this.__wbg_ptr=A>>>0,ZY.register(this,this.__wbg_ptr,this),this}forEachActiveRigidBodyHandle(A){try{V.rawislandmanager_forEachActiveRigidBodyHandle(this.__wbg_ptr,oo(A))}finally{Wn[Ug++]=void 0}}}const piA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawkinematiccharactercontroller_free(e>>>0,1));class Rse{__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_rawkinematiccharactercontroller_free(A,0)}constructor(A){const t=V.rawkinematiccharactercontroller_new(A);return this.__wbg_ptr=t>>>0,piA.register(this,this.__wbg_ptr,this),this}up(){const A=V.rawcharactercollision_translationDeltaApplied(this.__wbg_ptr);return de.__wrap(A)}setUp(A){Ae(A,de),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,r,a,I,c){try{Ae(t,Zg),Ae(i,po),Ae(n,zZ),Ae(o,de),V.rawkinematiccharactercontroller_computeColliderMovement(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o.__wbg_ptr,s,Gi(r)?4294967297:Math.fround(r),a,Gi(I)?4294967297:I>>>0,oo(c))}finally{Wn[Ug++]=void 0}}computedMovement(){const A=V.rawkinematiccharactercontroller_computedMovement(this.__wbg_ptr);return de.__wrap(A)}computedGrounded(){return V.rawkinematiccharactercontroller_computedGrounded(this.__wbg_ptr)!==0}numComputedCollisions(){return V.rawkinematiccharactercontroller_numComputedCollisions(this.__wbg_ptr)>>>0}computedCollision(A,t){return Ae(t,afA),V.rawkinematiccharactercontroller_computedCollision(this.__wbg_ptr,A,t.__wbg_ptr)!==0}}const WY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawmultibodyjointset_free(e>>>0,1));class oQ{static __wrap(A){A>>>=0;const t=Object.create(oQ.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_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 mn.__wrap(t)}jointFrameX2(A){const t=V.rawmultibodyjointset_jointFrameX2(this.__wbg_ptr,A);return mn.__wrap(t)}jointAnchor1(A){const t=V.rawmultibodyjointset_jointAnchor1(this.__wbg_ptr,A);return de.__wrap(t)}jointAnchor2(A){const t=V.rawmultibodyjointset_jointAnchor2(this.__wbg_ptr,A);return de.__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,WY.register(this,this.__wbg_ptr,this),this}createJoint(A,t,i,n){return Ae(A,Ws),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,oo(A))}finally{Wn[Ug++]=void 0}}forEachJointAttachedToRigidBody(A,t){try{V.rawmultibodyjointset_forEachJointAttachedToRigidBody(this.__wbg_ptr,A,oo(t))}finally{Wn[Ug++]=void 0}}}const VY=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,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_rawnarrowphase_free(A,0)}constructor(){const A=V.rawnarrowphase_new();return this.__wbg_ptr=A>>>0,VY.register(this,this.__wbg_ptr,this),this}contact_pairs_with(A,t){V.rawnarrowphase_contact_pairs_with(this.__wbg_ptr,A,rs(t))}contact_pair(A,t){const i=V.rawnarrowphase_contact_pair(this.__wbg_ptr,A,t);return i===0?void 0:wse.__wrap(i)}intersection_pairs_with(A,t){V.rawnarrowphase_intersection_pairs_with(this.__wbg_ptr,A,rs(t))}intersection_pair(A,t){return V.rawnarrowphase_intersection_pair(this.__wbg_ptr,A,t)!==0}}const fiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawphysicspipeline_free(e>>>0,1));class Gse{__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_rawphysicspipeline_free(A,0)}constructor(){const A=V.rawphysicspipeline_new();return this.__wbg_ptr=A>>>0,fiA.register(this,this.__wbg_ptr,this),this}step(A,t,i,n,g,o,s,r,a,I){Ae(A,de),Ae(t,uf),Ae(i,gQ),Ae(n,Qf),Ae(g,Qd),Ae(o,Zg),Ae(s,po),Ae(r,nQ),Ae(a,oQ),Ae(I,i4),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,r.__wbg_ptr,a.__wbg_ptr,I.__wbg_ptr)}stepWithEvents(A,t,i,n,g,o,s,r,a,I,c,l,B,Q){Ae(A,de),Ae(t,uf),Ae(i,gQ),Ae(n,Qf),Ae(g,Qd),Ae(o,Zg),Ae(s,po),Ae(r,nQ),Ae(a,oQ),Ae(I,i4),Ae(c,lfA),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,r.__wbg_ptr,a.__wbg_ptr,I.__wbg_ptr,c.__wbg_ptr,rs(l),rs(B),rs(Q))}}const yiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawpidcontroller_free(e>>>0,1));class bse{__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_rawpidcontroller_free(A,0)}constructor(A,t,i,n){const g=V.rawpidcontroller_new(A,t,i,n);return this.__wbg_ptr=g>>>0,yiA.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){Ae(t,Zg),Ae(n,de),Ae(g,de),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){Ae(t,Zg),Ae(n,mn),Ae(g,de),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){Ae(t,Zg),Ae(n,de),Ae(g,de);const o=V.rawpidcontroller_linear_correction(this.__wbg_ptr,A,t.__wbg_ptr,i,n.__wbg_ptr,g.__wbg_ptr);return de.__wrap(o)}angular_correction(A,t,i,n,g){Ae(t,Zg),Ae(n,mn),Ae(g,de);const o=V.rawpidcontroller_angular_correction(this.__wbg_ptr,A,t.__wbg_ptr,i,n.__wbg_ptr,g.__wbg_ptr);return de.__wrap(o)}}const DiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawpointcolliderprojection_free(e>>>0,1));class y_{static __wrap(A){A>>>=0;const t=Object.create(y_.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_rawpointcolliderprojection_free(A,0)}colliderHandle(){return V.rawpointcolliderprojection_colliderHandle(this.__wbg_ptr)}point(){const A=V.rawpointcolliderprojection_point(this.__wbg_ptr);return de.__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 miA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawpointprojection_free(e>>>0,1));class Bx{static __wrap(A){A>>>=0;const t=Object.create(Bx.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_rawpointprojection_free(A,0)}point(){const A=V.rawpointprojection_point(this.__wbg_ptr);return de.__wrap(A)}isInside(){return V.rawpointprojection_isInside(this.__wbg_ptr)!==0}}const SiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawquerypipeline_free(e>>>0,1));class zZ{__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_rawquerypipeline_free(A,0)}constructor(){const A=V.rawquerypipeline_new();return this.__wbg_ptr=A>>>0,SiA.register(this,this.__wbg_ptr,this),this}update(A){Ae(A,po),V.rawquerypipeline_update(this.__wbg_ptr,A.__wbg_ptr)}castRay(A,t,i,n,g,o,s,r,a,I,c){try{Ae(A,Zg),Ae(t,po),Ae(i,de),Ae(n,de);const l=V.rawquerypipeline_castRay(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o,s,Gi(r)?4294967297:r>>>0,!Gi(a),Gi(a)?0:a,!Gi(I),Gi(I)?0:I,oo(c));return l===0?void 0:ZZ.__wrap(l)}finally{Wn[Ug++]=void 0}}castRayAndGetNormal(A,t,i,n,g,o,s,r,a,I,c){try{Ae(A,Zg),Ae(t,po),Ae(i,de),Ae(n,de);const l=V.rawquerypipeline_castRayAndGetNormal(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o,s,Gi(r)?4294967297:r>>>0,!Gi(a),Gi(a)?0:a,!Gi(I),Gi(I)?0:I,oo(c));return l===0?void 0:Ex.__wrap(l)}finally{Wn[Ug++]=void 0}}intersectionsWithRay(A,t,i,n,g,o,s,r,a,I,c,l){try{Ae(A,Zg),Ae(t,po),Ae(i,de),Ae(n,de),V.rawquerypipeline_intersectionsWithRay(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g,o,oo(s),r,Gi(a)?4294967297:a>>>0,!Gi(I),Gi(I)?0:I,!Gi(c),Gi(c)?0:c,oo(l))}finally{Wn[Ug++]=void 0,Wn[Ug++]=void 0}}intersectionWithShape(A,t,i,n,g,o,s,r,a,I){try{const B=V.__wbindgen_add_to_stack_pointer(-16);Ae(A,Zg),Ae(t,po),Ae(i,de),Ae(n,mn),Ae(g,Si),V.rawquerypipeline_intersectionWithShape(B,this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,o,Gi(s)?4294967297:s>>>0,!Gi(r),Gi(r)?0:r,!Gi(a),Gi(a)?0:a,oo(I));var c=zs().getInt32(B+0,!0),l=zs().getFloat64(B+8,!0);return c===0?void 0:l}finally{V.__wbindgen_add_to_stack_pointer(16),Wn[Ug++]=void 0}}projectPoint(A,t,i,n,g,o,s,r,a){try{Ae(A,Zg),Ae(t,po),Ae(i,de);const I=V.rawquerypipeline_projectPoint(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n,g,Gi(o)?4294967297:o>>>0,!Gi(s),Gi(s)?0:s,!Gi(r),Gi(r)?0:r,oo(a));return I===0?void 0:y_.__wrap(I)}finally{Wn[Ug++]=void 0}}projectPointAndGetFeature(A,t,i,n,g,o,s,r){try{Ae(A,Zg),Ae(t,po),Ae(i,de);const a=V.rawquerypipeline_projectPointAndGetFeature(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n,Gi(g)?4294967297:g>>>0,!Gi(o),Gi(o)?0:o,!Gi(s),Gi(s)?0:s,oo(r));return a===0?void 0:y_.__wrap(a)}finally{Wn[Ug++]=void 0}}intersectionsWithPoint(A,t,i,n,g,o,s,r,a){try{Ae(A,Zg),Ae(t,po),Ae(i,de),V.rawquerypipeline_intersectionsWithPoint(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,oo(n),g,Gi(o)?4294967297:o>>>0,!Gi(s),Gi(s)?0:s,!Gi(r),Gi(r)?0:r,oo(a))}finally{Wn[Ug++]=void 0,Wn[Ug++]=void 0}}castShape(A,t,i,n,g,o,s,r,a,I,c,l,B,Q){try{Ae(A,Zg),Ae(t,po),Ae(i,de),Ae(n,mn),Ae(g,de),Ae(o,Si);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,r,a,I,Gi(c)?4294967297:c>>>0,!Gi(l),Gi(l)?0:l,!Gi(B),Gi(B)?0:B,oo(Q));return h===0?void 0:lx.__wrap(h)}finally{Wn[Ug++]=void 0}}intersectionsWithShape(A,t,i,n,g,o,s,r,a,I,c){try{Ae(A,Zg),Ae(t,po),Ae(i,de),Ae(n,mn),Ae(g,Si),V.rawquerypipeline_intersectionsWithShape(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n.__wbg_ptr,g.__wbg_ptr,oo(o),s,Gi(r)?4294967297:r>>>0,!Gi(a),Gi(a)?0:a,!Gi(I),Gi(I)?0:I,oo(c))}finally{Wn[Ug++]=void 0,Wn[Ug++]=void 0}}collidersWithAabbIntersectingAabb(A,t,i){try{Ae(A,de),Ae(t,de),V.rawquerypipeline_collidersWithAabbIntersectingAabb(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,oo(i))}finally{Wn[Ug++]=void 0}}}const wiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawraycolliderhit_free(e>>>0,1));class ZZ{static __wrap(A){A>>>=0;const t=Object.create(ZZ.prototype);return t.__wbg_ptr=A,wiA.register(t,t.__wbg_ptr,t),t}__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_rawraycolliderhit_free(A,0)}colliderHandle(){return V.rawcharactercollision_handle(this.__wbg_ptr)}timeOfImpact(){return V.rawcollidershapecasthit_time_of_impact(this.__wbg_ptr)}}const kiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawraycolliderintersection_free(e>>>0,1));class Ex{static __wrap(A){A>>>=0;const t=Object.create(Ex.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_rawraycolliderintersection_free(A,0)}colliderHandle(){return V.rawpointcolliderprojection_colliderHandle(this.__wbg_ptr)}normal(){const A=V.rawcollidershapecasthit_witness1(this.__wbg_ptr);return de.__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 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_rawrayintersection_free(A,0)}normal(){const A=V.rawcollidershapecasthit_witness1(this.__wbg_ptr);return de.__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 XY=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawrigidbodyset_free(e>>>0,1));class Zg{static __wrap(A){A>>>=0;const t=Object.create(Zg.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_rawrigidbodyset_free(A,0)}rbTranslation(A){const t=V.rawrigidbodyset_rbTranslation(this.__wbg_ptr,A);return de.__wrap(t)}rbRotation(A){const t=V.rawrigidbodyset_rbRotation(this.__wbg_ptr,A);return mn.__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 de.__wrap(t)}rbNextRotation(A){const t=V.rawrigidbodyset_rbNextRotation(this.__wbg_ptr,A);return mn.__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){Ae(t,de),V.rawrigidbodyset_rbSetLinvel(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbSetAngvel(A,t,i){Ae(t,de),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){Ae(t,po),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){Ae(i,de),Ae(n,de),Ae(g,mn),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 de.__wrap(t)}rbAngvel(A){const t=V.rawrigidbodyset_rbAngvel(this.__wbg_ptr,A);return de.__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 de.__wrap(t)}rbLocalCom(A){const t=V.rawrigidbodyset_rbLocalCom(this.__wbg_ptr,A);return de.__wrap(t)}rbWorldCom(A){const t=V.rawrigidbodyset_rbWorldCom(this.__wbg_ptr,A);return de.__wrap(t)}rbInvPrincipalInertiaSqrt(A){const t=V.rawrigidbodyset_rbInvPrincipalInertiaSqrt(this.__wbg_ptr,A);return de.__wrap(t)}rbPrincipalInertiaLocalFrame(A){const t=V.rawrigidbodyset_rbPrincipalInertiaLocalFrame(this.__wbg_ptr,A);return mn.__wrap(t)}rbPrincipalInertia(A){const t=V.rawrigidbodyset_rbPrincipalInertia(this.__wbg_ptr,A);return de.__wrap(t)}rbEffectiveWorldInvInertiaSqrt(A){const t=V.rawrigidbodyset_rbEffectiveWorldInvInertiaSqrt(this.__wbg_ptr,A);return D_.__wrap(t)}rbEffectiveAngularInertia(A){const t=V.rawrigidbodyset_rbEffectiveAngularInertia(this.__wbg_ptr,A);return D_.__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){Ae(t,de),V.rawrigidbodyset_rbAddForce(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbApplyImpulse(A,t,i){Ae(t,de),V.rawrigidbodyset_rbApplyImpulse(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbAddTorque(A,t,i){Ae(t,de),V.rawrigidbodyset_rbAddTorque(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbApplyTorqueImpulse(A,t,i){Ae(t,de),V.rawrigidbodyset_rbApplyTorqueImpulse(this.__wbg_ptr,A,t.__wbg_ptr,i)}rbAddForceAtPoint(A,t,i,n){Ae(t,de),Ae(i,de),V.rawrigidbodyset_rbAddForceAtPoint(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n)}rbApplyImpulseAtPoint(A,t,i,n){Ae(t,de),Ae(i,de),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 de.__wrap(t)}rbUserTorque(A){const t=V.rawrigidbodyset_rbUserTorque(this.__wbg_ptr,A);return de.__wrap(t)}constructor(){const A=V.rawrigidbodyset_new();return this.__wbg_ptr=A>>>0,XY.register(this,this.__wbg_ptr,this),this}createRigidBody(A,t,i,n,g,o,s,r,a,I,c,l,B,Q,h,d,p,y,m,D,S,k,N,G,M,w){return Ae(t,de),Ae(i,mn),Ae(s,de),Ae(r,de),Ae(a,de),Ae(I,de),Ae(c,mn),V.rawrigidbodyset_createRigidBody(this.__wbg_ptr,A,t.__wbg_ptr,i.__wbg_ptr,n,g,o,s.__wbg_ptr,r.__wbg_ptr,a.__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){Ae(t,gQ),Ae(i,po),Ae(n,nQ),Ae(g,oQ),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,oo(A))}finally{Wn[Ug++]=void 0}}propagateModifiedBodyPositionsToColliders(A){Ae(A,po),V.rawrigidbodyset_propagateModifiedBodyPositionsToColliders(this.__wbg_ptr,A.__wbg_ptr)}}const $Y=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawrotation_free(e>>>0,1));class mn{static __wrap(A){A>>>=0;const t=Object.create(mn.prototype);return t.__wbg_ptr=A,$Y.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,$Y.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,$Y.register(this,this.__wbg_ptr,this),this}static identity(){const A=V.rawrotation_identity();return mn.__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 NiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawsdpmatrix3_free(e>>>0,1));class D_{static __wrap(A){A>>>=0;const t=Object.create(D_.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_rawsdpmatrix3_free(A,0)}elements(){return SN(V.rawsdpmatrix3_elements(this.__wbg_ptr))}}const RiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawserializationpipeline_free(e>>>0,1));class Use{__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_rawserializationpipeline_free(A,0)}constructor(){const A=V.rawserializationpipeline_new();return this.__wbg_ptr=A>>>0,RiA.register(this,this.__wbg_ptr,this),this}serializeAll(A,t,i,n,g,o,s,r,a){return Ae(A,de),Ae(t,uf),Ae(i,gQ),Ae(n,Qf),Ae(g,Qd),Ae(o,Zg),Ae(s,po),Ae(r,nQ),Ae(a,oQ),SN(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,r.__wbg_ptr,a.__wbg_ptr))}deserializeAll(A){const t=V.rawserializationpipeline_deserializeAll(this.__wbg_ptr,rs(A));return t===0?void 0:Mse.__wrap(t)}}const GiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawshape_free(e>>>0,1));class Si{static __wrap(A){A>>>=0;const t=Object.create(Si.prototype);return t.__wbg_ptr=A,GiA.register(t,t.__wbg_ptr,t),t}__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_rawshape_free(A,0)}static cuboid(A,t,i){const n=V.rawshape_cuboid(A,t,i);return Si.__wrap(n)}static roundCuboid(A,t,i,n){const g=V.rawshape_roundCuboid(A,t,i,n);return Si.__wrap(g)}static ball(A){const t=V.rawshape_ball(A);return Si.__wrap(t)}static halfspace(A){Ae(A,de);const t=V.rawshape_halfspace(A.__wbg_ptr);return Si.__wrap(t)}static capsule(A,t){const i=V.rawshape_capsule(A,t);return Si.__wrap(i)}static cylinder(A,t){const i=V.rawshape_cylinder(A,t);return Si.__wrap(i)}static roundCylinder(A,t,i){const n=V.rawshape_roundCylinder(A,t,i);return Si.__wrap(n)}static cone(A,t){const i=V.rawshape_cone(A,t);return Si.__wrap(i)}static roundCone(A,t,i){const n=V.rawshape_roundCone(A,t,i);return Si.__wrap(n)}static polyline(A,t){const i=dh(A,V.__wbindgen_export_2),n=KI,g=oU(t,V.__wbindgen_export_2),o=KI,s=V.rawshape_polyline(i,n,g,o);return Si.__wrap(s)}static trimesh(A,t,i){const n=dh(A,V.__wbindgen_export_2),g=KI,o=oU(t,V.__wbindgen_export_2),s=KI,r=V.rawshape_trimesh(n,g,o,s,i);return r===0?void 0:Si.__wrap(r)}static heightfield(A,t,i,n,g){const o=dh(i,V.__wbindgen_export_2),s=KI;Ae(n,de);const r=V.rawshape_heightfield(A,t,o,s,n.__wbg_ptr,g);return Si.__wrap(r)}static segment(A,t){Ae(A,de),Ae(t,de);const i=V.rawshape_segment(A.__wbg_ptr,t.__wbg_ptr);return Si.__wrap(i)}static triangle(A,t,i){Ae(A,de),Ae(t,de),Ae(i,de);const n=V.rawshape_triangle(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr);return Si.__wrap(n)}static roundTriangle(A,t,i,n){Ae(A,de),Ae(t,de),Ae(i,de);const g=V.rawshape_roundTriangle(A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n);return Si.__wrap(g)}static convexHull(A){const t=dh(A,V.__wbindgen_export_2),i=KI,n=V.rawshape_convexHull(t,i);return n===0?void 0:Si.__wrap(n)}static roundConvexHull(A,t){const i=dh(A,V.__wbindgen_export_2),n=KI,g=V.rawshape_roundConvexHull(i,n,t);return g===0?void 0:Si.__wrap(g)}static convexMesh(A,t){const i=dh(A,V.__wbindgen_export_2),n=KI,g=oU(t,V.__wbindgen_export_2),o=KI,s=V.rawshape_convexMesh(i,n,g,o);return s===0?void 0:Si.__wrap(s)}static roundConvexMesh(A,t,i){const n=dh(A,V.__wbindgen_export_2),g=KI,o=oU(t,V.__wbindgen_export_2),s=KI,r=V.rawshape_roundConvexMesh(n,g,o,s,i);return r===0?void 0:Si.__wrap(r)}castShape(A,t,i,n,g,o,s,r,a,I){Ae(A,de),Ae(t,mn),Ae(i,de),Ae(n,Si),Ae(g,de),Ae(o,mn),Ae(s,de);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,r,a,I);return c===0?void 0:ux.__wrap(c)}intersectsShape(A,t,i,n,g){return Ae(A,de),Ae(t,mn),Ae(i,Si),Ae(n,de),Ae(g,mn),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){Ae(A,de),Ae(t,mn),Ae(i,Si),Ae(n,de),Ae(g,mn);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:wN.__wrap(s)}containsPoint(A,t,i){return Ae(A,de),Ae(t,mn),Ae(i,de),V.rawshape_containsPoint(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr)!==0}projectPoint(A,t,i,n){Ae(A,de),Ae(t,mn),Ae(i,de);const g=V.rawshape_projectPoint(this.__wbg_ptr,A.__wbg_ptr,t.__wbg_ptr,i.__wbg_ptr,n);return Bx.__wrap(g)}intersectsRay(A,t,i,n,g){return Ae(A,de),Ae(t,mn),Ae(i,de),Ae(n,de),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 Ae(A,de),Ae(t,mn),Ae(i,de),Ae(n,de),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){Ae(A,de),Ae(t,mn),Ae(i,de),Ae(n,de);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:Qx.__wrap(s)}}const biA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawshapecasthit_free(e>>>0,1));class ux{static __wrap(A){A>>>=0;const t=Object.create(ux.prototype);return t.__wbg_ptr=A,biA.register(t,t.__wbg_ptr,t),t}__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_rawshapecasthit_free(A,0)}time_of_impact(){return V.rawrotation_x(this.__wbg_ptr)}witness1(){const A=V.rawshapecasthit_witness1(this.__wbg_ptr);return de.__wrap(A)}witness2(){const A=V.rawcontactforceevent_total_force(this.__wbg_ptr);return de.__wrap(A)}normal1(){const A=V.rawshapecasthit_normal1(this.__wbg_ptr);return de.__wrap(A)}normal2(){const A=V.rawshapecasthit_normal2(this.__wbg_ptr);return de.__wrap(A)}}const UiA=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawshapecontact_free(e>>>0,1));class wN{static __wrap(A){A>>>=0;const t=Object.create(wN.prototype);return t.__wbg_ptr=A,UiA.register(t,t.__wbg_ptr,t),t}__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_rawshapecontact_free(A,0)}distance(){return V.rawkinematiccharactercontroller_maxSlopeClimbAngle(this.__wbg_ptr)}point1(){const A=V.rawpointprojection_point(this.__wbg_ptr);return de.__wrap(A)}point2(){const A=V.rawcollidershapecasthit_witness1(this.__wbg_ptr);return de.__wrap(A)}normal1(){const A=V.rawcollidershapecasthit_witness2(this.__wbg_ptr);return de.__wrap(A)}normal2(){const A=V.rawcharactercollision_translationDeltaApplied(this.__wbg_ptr);return de.__wrap(A)}}const AH=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>V.__wbg_rawvector_free(e>>>0,1));class de{static __wrap(A){A>>>=0;const t=Object.create(de.prototype);return t.__wbg_ptr=A,AH.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const A=this.__wbg_ptr;return this.__wbg_ptr=0,AH.unregister(this),A}free(){const A=this.__destroy_into_raw();V.__wbg_rawvector_free(A,0)}static zero(){const A=V.rawvector_zero();return de.__wrap(A)}constructor(A,t,i){const n=V.rawvector_new(A,t,i);return this.__wbg_ptr=n>>>0,AH.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 de.__wrap(A)}yxz(){const A=V.rawvector_yxz(this.__wbg_ptr);return de.__wrap(A)}zxy(){const A=V.rawvector_zxy(this.__wbg_ptr);return de.__wrap(A)}xzy(){const A=V.rawvector_xzy(this.__wbg_ptr);return de.__wrap(A)}yzx(){const A=V.rawvector_yzx(this.__wbg_ptr);return de.__wrap(A)}zyx(){const A=V.rawvector_zyx(this.__wbg_ptr);return de.__wrap(A)}}async function BfA(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,r){return rs(lg(g).bind(lg(o),lg(s),lg(r)))},n.wbg.__wbg_buffer_609cc3eee51ed158=function(g){return rs(lg(g).buffer)},n.wbg.__wbg_call_7cccdd69e0791ae2=function(){return HY(function(g,o,s){return rs(lg(g).call(lg(o),lg(s)))},arguments)},n.wbg.__wbg_call_833bed5770ea2041=function(){return HY(function(g,o,s,r){return rs(lg(g).call(lg(o),lg(s),lg(r)))},arguments)},n.wbg.__wbg_call_b8adc8b1d0a0d8eb=function(){return HY(function(g,o,s,r,a){return rs(lg(g).call(lg(o),lg(s),lg(r),lg(a)))},arguments)},n.wbg.__wbg_length_3b4f022188ae8db6=function(g){return lg(g).length},n.wbg.__wbg_length_a446193dc22c12f8=function(g){return lg(g).length},n.wbg.__wbg_new_a12002a7f91c75be=function(g){return rs(new Uint8Array(lg(g)))},n.wbg.__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a=function(g,o,s){return rs(new Uint8Array(lg(g),o>>>0,s>>>0))},n.wbg.__wbg_newwithbyteoffsetandlength_e6b7e69acd4c7354=function(g,o,s){return rs(new Float32Array(lg(g),o>>>0,s>>>0))},n.wbg.__wbg_newwithlength_5a5efe313cfd59f1=function(g){return rs(new Float32Array(g>>>0))},n.wbg.__wbg_rawcontactforceevent_new=function(g){return rs(jZ.__wrap(g))},n.wbg.__wbg_rawraycolliderintersection_new=function(g){return rs(Ex.__wrap(g))},n.wbg.__wbg_set_10bad9bee0e9c58b=function(g,o,s){lg(g).set(lg(o),s>>>0)},n.wbg.__wbg_set_65595bdd868b3009=function(g,o,s){lg(g).set(lg(o),s>>>0)},n.wbg.__wbindgen_boolean_get=function(g){const o=lg(g);return typeof o=="boolean"?o?1:0:2},n.wbg.__wbindgen_is_function=function(g){return typeof lg(g)=="function"},n.wbg.__wbindgen_memory=function(){return rs(V.memory)},n.wbg.__wbindgen_number_get=function(g,o){const s=lg(o),r=typeof s=="number"?s:void 0;zs().setFloat64(g+8,Gi(r)?0:r,!0),zs().setInt32(g+0,!Gi(r),!0)},n.wbg.__wbindgen_number_new=function(g){return rs(g)},n.wbg.__wbindgen_object_drop_ref=function(g){SN(g)},n.wbg.__wbindgen_throw=function(g,o){throw new Error(ofA(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,BfA.__wbindgen_wasm_module=g,Vh=null,Nk=null,Rk=null,Mk=null,V}(t,i)}class Pm{constructor(A,t,i){this.x=A,this.y=t,this.z=i}}class Be{static new(A,t,i){return new Pm(A,t,i)}static intoRaw(A){return new de(A.x,A.y,A.z)}static zeros(){return Be.new(0,0,0)}static fromRaw(A){if(!A)return null;let t=Be.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 m_{constructor(A,t,i,n){this.x=A,this.y=t,this.z=i,this.w=n}}class An{static identity(){return new m_(0,0,0,1)}static fromRaw(A){if(!A)return null;let t=new m_(A.x,A.y,A.z,A.w);return A.free(),t}static intoRaw(A){return new mn(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 WZ{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 S_{static fromRaw(A){const t=new WZ(A.elements());return A.free(),t}}var _C,js,w_,k_,JS,df,ts,M_,N_,R_,G_,kE,kN,b_,MN,Mu;(function(e){e[e.Dynamic=0]="Dynamic",e[e.Fixed=1]="Fixed",e[e.KinematicPositionBased=2]="KinematicPositionBased",e[e.KinematicVelocityBased=3]="KinematicVelocityBased"})(_C||(_C={}));class U_{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 Be.fromRaw(A)}rotation(){let A=this.rawSet.rbRotation(this.handle);return An.fromRaw(A)}nextTranslation(){let A=this.rawSet.rbNextTranslation(this.handle);return Be.fromRaw(A)}nextRotation(){let A=this.rawSet.rbNextRotation(this.handle);return An.fromRaw(A)}setTranslation(A,t){this.rawSet.rbSetTranslation(this.handle,A.x,A.y,A.z,t)}setLinvel(A,t){let i=Be.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=Be.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 Be.fromRaw(this.rawSet.rbLinvel(this.handle))}angvel(){return Be.fromRaw(this.rawSet.rbAngvel(this.handle))}mass(){return this.rawSet.rbMass(this.handle)}effectiveInvMass(){return Be.fromRaw(this.rawSet.rbEffectiveInvMass(this.handle))}invMass(){return this.rawSet.rbInvMass(this.handle)}localCom(){return Be.fromRaw(this.rawSet.rbLocalCom(this.handle))}worldCom(){return Be.fromRaw(this.rawSet.rbWorldCom(this.handle))}invPrincipalInertiaSqrt(){return Be.fromRaw(this.rawSet.rbInvPrincipalInertiaSqrt(this.handle))}principalInertia(){return Be.fromRaw(this.rawSet.rbPrincipalInertia(this.handle))}principalInertiaLocalFrame(){return An.fromRaw(this.rawSet.rbPrincipalInertiaLocalFrame(this.handle))}effectiveWorldInvInertiaSqrt(){return S_.fromRaw(this.rawSet.rbEffectiveWorldInvInertiaSqrt(this.handle))}effectiveAngularInertia(){return S_.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=Be.intoRaw(t),s=Be.intoRaw(i),r=An.intoRaw(n);this.rawSet.rbSetAdditionalMassProperties(this.handle,A,o,s,r,g),o.free(),s.free(),r.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=Be.intoRaw(A);this.rawSet.rbAddForce(this.handle,i,t),i.free()}applyImpulse(A,t){const i=Be.intoRaw(A);this.rawSet.rbApplyImpulse(this.handle,i,t),i.free()}addTorque(A,t){const i=Be.intoRaw(A);this.rawSet.rbAddTorque(this.handle,i,t),i.free()}applyTorqueImpulse(A,t){const i=Be.intoRaw(A);this.rawSet.rbApplyTorqueImpulse(this.handle,i,t),i.free()}addForceAtPoint(A,t,i){const n=Be.intoRaw(A),g=Be.intoRaw(t);this.rawSet.rbAddForceAtPoint(this.handle,n,g,i),n.free(),g.free()}applyImpulseAtPoint(A,t,i){const n=Be.intoRaw(A),g=Be.intoRaw(t);this.rawSet.rbApplyImpulseAtPoint(this.handle,n,g,i),n.free(),g.free()}userForce(){return Be.fromRaw(this.rawSet.rbUserForce(this.handle))}userTorque(){return Be.fromRaw(this.rawSet.rbUserTorque(this.handle))}}class JC{constructor(A){this.enabled=!0,this.status=A,this.translation=Be.zeros(),this.rotation=An.identity(),this.gravityScale=1,this.linvel=Be.zeros(),this.mass=0,this.massOnly=!1,this.centerOfMass=Be.zeros(),this.translationsEnabledX=!0,this.translationsEnabledY=!0,this.angvel=Be.zeros(),this.principalAngularInertia=Be.zeros(),this.angularInertiaLocalFrame=An.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 JC(_C.Dynamic)}static kinematicPositionBased(){return new JC(_C.KinematicPositionBased)}static kinematicVelocityBased(){return new JC(_C.KinematicVelocityBased)}static fixed(){return new JC(_C.Fixed)}static newDynamic(){return new JC(_C.Dynamic)}static newKinematicPositionBased(){return new JC(_C.KinematicPositionBased)}static newKinematicVelocityBased(){return new JC(_C.KinematicVelocityBased)}static newStatic(){return new JC(_C.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 An.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 Be.copy(this.angvel,A),this}setAdditionalMassProperties(A,t,i,n){return this.mass=A,Be.copy(this.centerOfMass,t),Be.copy(this.principalAngularInertia,i),An.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 dx{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 VZ{constructor(A){this.raw=A||new Zg,this.map=new dx,A&&A.forEachRigidBodyHandle(t=>{this.map.set(t,new U_(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=Be.intoRaw(t.translation),n=An.intoRaw(t.rotation),g=Be.intoRaw(t.linvel),o=Be.intoRaw(t.centerOfMass),s=Be.intoRaw(t.angvel),r=Be.intoRaw(t.principalAngularInertia),a=An.intoRaw(t.angularInertiaLocalFrame),I=this.raw.createRigidBody(t.enabled,i,n,t.gravityScale,t.mass,t.massOnly,o,g,s,r,a,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(),r.free(),a.free();const c=new U_(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 XZ{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"})(js||(js={})),function(e){e[e.AccelerationBased=0]="AccelerationBased",e[e.ForceBased=1]="ForceBased"}(w_||(w_={})),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"}(k_||(k_={}));class oc{constructor(A,t,i){this.rawSet=A,this.bodySet=t,this.handle=i}static newTyped(A,t,i){switch(A.jointType(i)){case Fc.Revolute:return new iW(A,t,i);case Fc.Prismatic:return new tW(A,t,i);case Fc.Fixed:return new $Z(A,t,i);case Fc.Spring:return new eW(A,t,i);case Fc.Rope:return new AW(A,t,i);case Fc.Spherical:return new gW(A,t,i);case Fc.Generic:return new nW(A,t,i);default:return new oc(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 An.fromRaw(this.rawSet.jointFrameX1(this.handle))}frameX2(){return An.fromRaw(this.rawSet.jointFrameX2(this.handle))}anchor1(){return Be.fromRaw(this.rawSet.jointAnchor1(this.handle))}anchor2(){return Be.fromRaw(this.rawSet.jointAnchor2(this.handle))}setAnchor1(A){const t=Be.intoRaw(A);this.rawSet.jointSetAnchor1(this.handle,t),t.free()}setAnchor2(A){const t=Be.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 hx extends oc{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 $Z extends oc{}class AW extends oc{}class eW extends oc{}class tW extends hx{rawAxis(){return cx.LinX}}class iW extends hx{rawAxis(){return cx.AngX}}class nW extends oc{}class gW extends oc{}class Ol{constructor(){}static fixed(A,t,i,n){let g=new Ol;return g.anchor1=A,g.anchor2=i,g.frame1=t,g.frame2=n,g.jointType=js.Fixed,g}static spring(A,t,i,n,g){let o=new Ol;return o.anchor1=n,o.anchor2=g,o.length=A,o.stiffness=t,o.damping=i,o.jointType=js.Spring,o}static rope(A,t,i){let n=new Ol;return n.anchor1=t,n.anchor2=i,n.length=A,n.jointType=js.Rope,n}static generic(A,t,i,n){let g=new Ol;return g.anchor1=A,g.anchor2=t,g.axis=i,g.axesMask=n,g.jointType=js.Generic,g}static spherical(A,t){let i=new Ol;return i.anchor1=A,i.anchor2=t,i.jointType=js.Spherical,i}static prismatic(A,t,i){let n=new Ol;return n.anchor1=A,n.anchor2=t,n.axis=i,n.jointType=js.Prismatic,n}static revolute(A,t,i){let n=new Ol;return n.anchor1=A,n.anchor2=t,n.axis=i,n.jointType=js.Revolute,n}intoRaw(){let A,t,i=Be.intoRaw(this.anchor1),n=Be.intoRaw(this.anchor2),g=!1,o=0,s=0;switch(this.jointType){case js.Fixed:let r=An.intoRaw(this.frame1),a=An.intoRaw(this.frame2);t=Ws.fixed(i,r,n,a),r.free(),a.free();break;case js.Spring:t=Ws.spring(this.length,this.stiffness,this.damping,i,n);break;case js.Rope:t=Ws.rope(this.length,i,n);break;case js.Prismatic:A=Be.intoRaw(this.axis),this.limitsEnabled&&(g=!0,o=this.limits[0],s=this.limits[1]),t=Ws.prismatic(i,n,A,g,o,s),A.free();break;case js.Generic:A=Be.intoRaw(this.axis);let I=this.axesMask;t=Ws.generic(i,n,A,I);break;case js.Spherical:t=Ws.spherical(i,n);break;case js.Revolute:A=Be.intoRaw(this.axis),t=Ws.revolute(i,n,A),A.free()}return i.free(),n.free(),t}}class oW{constructor(A){this.raw=A||new nQ,this.map=new dx,A&&A.forEachJointHandle(t=>{this.map.set(t,oc.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 r=oc.newTyped(this.raw,A,s);return this.map.set(s,r),r}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 sQ{constructor(A,t){this.rawSet=A,this.handle=t}static newTyped(A,t){switch(A.jointType(t)){case Fc.Revolute:return new aW(A,t);case Fc.Prismatic:return new rW(A,t);case Fc.Fixed:return new sW(A,t);case Fc.Spherical:return new IW(A,t);default:return new sQ(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 px extends sQ{}class sW extends sQ{}class rW extends px{rawAxis(){return cx.LinX}}class aW extends px{rawAxis(){return cx.AngX}}class IW extends sQ{}class CW{constructor(A){this.raw=A||new oQ,this.map=new dx,A&&A.forEachJointHandle(t=>{this.map.set(t,sQ.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=sQ.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"})(JS||(JS={}));class cW{constructor(A){this.raw=A||new i4}free(){this.raw&&this.raw.free(),this.raw=void 0}}class lW{constructor(A){this.raw=A||new gQ}free(){this.raw&&this.raw.free(),this.raw=void 0}forEachActiveRigidBodyHandle(A){this.raw.forEachActiveRigidBodyHandle(A)}}class BW{constructor(A){this.raw=A||new Qf}free(){this.raw&&this.raw.free(),this.raw=void 0}}class EW{constructor(A){this.raw=A||new Qd,this.tempManifold=new QW(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 QW{constructor(A){this.raw=A}free(){this.raw&&this.raw.free(),this.raw=void 0}normal(){return Be.fromRaw(this.raw.normal())}localNormal1(){return Be.fromRaw(this.raw.local_n1())}localNormal2(){return Be.fromRaw(this.raw.local_n2())}subshape1(){return this.raw.subshape1()}subshape2(){return this.raw.subshape2()}numContacts(){return this.raw.num_contacts()}localContactPoint1(A){return Be.fromRaw(this.raw.contact_local_p1(A))}localContactPoint2(A){return Be.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 Be.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 Be.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(),Be.fromRaw(A.point1()),Be.fromRaw(A.point2()),Be.fromRaw(A.normal1()),Be.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 vw{constructor(A,t){this.point=A,this.isInside=t}static fromRaw(A){if(!A)return null;const t=new vw(Be.fromRaw(A.point()),A.isInside());return A.free(),t}}class LS{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 LS(A.get(t.colliderHandle()),Be.fromRaw(t.point()),t.isInside(),t.featureType(),t.featureId());return t.free(),i}}class EfA{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 Kw{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 Kw(A.time_of_impact(),Be.fromRaw(A.normal()),A.featureType(),A.featureId());return A.free(),t}}class xS{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 xS(A.get(t.colliderHandle()),t.time_of_impact(),Be.fromRaw(t.normal()),t.featureType(),t.featureId());return t.free(),i}}class tG{constructor(A,t){this.collider=A,this.timeOfImpact=t}static fromRaw(A,t){if(!t)return null;const i=new tG(A.get(t.colliderHandle()),t.timeOfImpact());return t.free(),i}}class ey{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 ey(t.time_of_impact(),Be.fromRaw(t.witness1()),Be.fromRaw(t.witness2()),Be.fromRaw(t.normal1()),Be.fromRaw(t.normal2()));return t.free(),i}}class Fw extends ey{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 Fw(A.get(t.colliderHandle()),t.time_of_impact(),Be.fromRaw(t.witness1()),Be.fromRaw(t.witness2()),Be.fromRaw(t.normal1()),Be.fromRaw(t.normal2()));return t.free(),i}}class ws{static fromRaw(A,t){const i=A.coShapeType(t);let n,g,o,s,r,a,I;switch(i){case Cr.Ball:return new fx(A.coRadius(t));case Cr.Cuboid:return n=A.coHalfExtents(t),new yx(n.x,n.y,n.z);case Cr.RoundCuboid:return n=A.coHalfExtents(t),g=A.coRoundRadius(t),new Dx(n.x,n.y,n.z,g);case Cr.Capsule:return r=A.coHalfHeight(t),a=A.coRadius(t),new mx(r,a);case Cr.Segment:return o=A.coVertices(t),new Sx(Be.new(o[0],o[1],o[2]),Be.new(o[3],o[4],o[5]));case Cr.Polyline:return o=A.coVertices(t),s=A.coIndices(t),new Mx(o,s);case Cr.Triangle:return o=A.coVertices(t),new wx(Be.new(o[0],o[1],o[2]),Be.new(o[3],o[4],o[5]),Be.new(o[6],o[7],o[8]));case Cr.RoundTriangle:return o=A.coVertices(t),g=A.coRoundRadius(t),new kx(Be.new(o[0],o[1],o[2]),Be.new(o[3],o[4],o[5]),Be.new(o[6],o[7],o[8]),g);case Cr.HalfSpace:return I=Be.fromRaw(A.coHalfspaceNormal(t)),new uW(I);case Cr.TriMesh:o=A.coVertices(t),s=A.coIndices(t);const c=A.coTriMeshFlags(t);return new Nx(o,s,c);case Cr.HeightField:const l=A.coHeightfieldScale(t),B=A.coHeightfieldHeights(t),Q=A.coHeightfieldNRows(t),h=A.coHeightfieldNCols(t),d=A.coHeightFieldFlags(t);return new Rx(Q,h,B,l,d);case Cr.ConvexPolyhedron:return o=A.coVertices(t),s=A.coIndices(t),new NN(o,s);case Cr.RoundConvexPolyhedron:return o=A.coVertices(t),s=A.coIndices(t),g=A.coRoundRadius(t),new RN(o,s,g);case Cr.Cylinder:return r=A.coHalfHeight(t),a=A.coRadius(t),new Gx(r,a);case Cr.RoundCylinder:return r=A.coHalfHeight(t),a=A.coRadius(t),g=A.coRoundRadius(t),new bx(r,a,g);case Cr.Cone:return r=A.coHalfHeight(t),a=A.coRadius(t),new Ux(r,a);case Cr.RoundCone:return r=A.coHalfHeight(t),a=A.coRadius(t),g=A.coRoundRadius(t),new vx(r,a,g);default:throw new Error("unknown shape type: "+i)}}castShape(A,t,i,n,g,o,s,r,a,I){let c=Be.intoRaw(A),l=An.intoRaw(t),B=Be.intoRaw(i),Q=Be.intoRaw(g),h=An.intoRaw(o),d=Be.intoRaw(s),p=this.intoRaw(),y=n.intoRaw(),m=ey.fromRaw(null,p.castShape(c,l,B,y,Q,h,d,r,a,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=Be.intoRaw(A),s=An.intoRaw(t),r=Be.intoRaw(n),a=An.intoRaw(g),I=this.intoRaw(),c=i.intoRaw(),l=I.intersectsShape(o,s,c,r,a);return o.free(),s.free(),r.free(),a.free(),I.free(),c.free(),l}contactShape(A,t,i,n,g,o){let s=Be.intoRaw(A),r=An.intoRaw(t),a=Be.intoRaw(n),I=An.intoRaw(g),c=this.intoRaw(),l=i.intoRaw(),B=hf.fromRaw(c.contactShape(s,r,l,a,I,o));return s.free(),r.free(),a.free(),I.free(),c.free(),l.free(),B}containsPoint(A,t,i){let n=Be.intoRaw(A),g=An.intoRaw(t),o=Be.intoRaw(i),s=this.intoRaw(),r=s.containsPoint(n,g,o);return n.free(),g.free(),o.free(),s.free(),r}projectPoint(A,t,i,n){let g=Be.intoRaw(A),o=An.intoRaw(t),s=Be.intoRaw(i),r=this.intoRaw(),a=vw.fromRaw(r.projectPoint(g,o,s,n));return g.free(),o.free(),s.free(),r.free(),a}intersectsRay(A,t,i,n){let g=Be.intoRaw(t),o=An.intoRaw(i),s=Be.intoRaw(A.origin),r=Be.intoRaw(A.dir),a=this.intoRaw(),I=a.intersectsRay(g,o,s,r,n);return g.free(),o.free(),s.free(),r.free(),a.free(),I}castRay(A,t,i,n,g){let o=Be.intoRaw(t),s=An.intoRaw(i),r=Be.intoRaw(A.origin),a=Be.intoRaw(A.dir),I=this.intoRaw(),c=I.castRay(o,s,r,a,n,g);return o.free(),s.free(),r.free(),a.free(),I.free(),c}castRayAndGetNormal(A,t,i,n,g){let o=Be.intoRaw(t),s=An.intoRaw(i),r=Be.intoRaw(A.origin),a=Be.intoRaw(A.dir),I=this.intoRaw(),c=Kw.fromRaw(I.castRayAndGetNormal(o,s,r,a,n,g));return o.free(),s.free(),r.free(),a.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"})(ts||(ts={})),function(e){e[e.FIX_INTERNAL_EDGES=1]="FIX_INTERNAL_EDGES"}(M_||(M_={})),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"}(N_||(N_={}));class fx extends ws{constructor(A){super(),this.type=ts.Ball,this.radius=A}intoRaw(){return Si.ball(this.radius)}}class uW extends ws{constructor(A){super(),this.type=ts.HalfSpace,this.normal=A}intoRaw(){let A=Be.intoRaw(this.normal),t=Si.halfspace(A);return A.free(),t}}class yx extends ws{constructor(A,t,i){super(),this.type=ts.Cuboid,this.halfExtents=Be.new(A,t,i)}intoRaw(){return Si.cuboid(this.halfExtents.x,this.halfExtents.y,this.halfExtents.z)}}class Dx extends ws{constructor(A,t,i,n){super(),this.type=ts.RoundCuboid,this.halfExtents=Be.new(A,t,i),this.borderRadius=n}intoRaw(){return Si.roundCuboid(this.halfExtents.x,this.halfExtents.y,this.halfExtents.z,this.borderRadius)}}class mx extends ws{constructor(A,t){super(),this.type=ts.Capsule,this.halfHeight=A,this.radius=t}intoRaw(){return Si.capsule(this.halfHeight,this.radius)}}class Sx extends ws{constructor(A,t){super(),this.type=ts.Segment,this.a=A,this.b=t}intoRaw(){let A=Be.intoRaw(this.a),t=Be.intoRaw(this.b),i=Si.segment(A,t);return A.free(),t.free(),i}}class wx extends ws{constructor(A,t,i){super(),this.type=ts.Triangle,this.a=A,this.b=t,this.c=i}intoRaw(){let A=Be.intoRaw(this.a),t=Be.intoRaw(this.b),i=Be.intoRaw(this.c),n=Si.triangle(A,t,i);return A.free(),t.free(),i.free(),n}}class kx extends ws{constructor(A,t,i,n){super(),this.type=ts.RoundTriangle,this.a=A,this.b=t,this.c=i,this.borderRadius=n}intoRaw(){let A=Be.intoRaw(this.a),t=Be.intoRaw(this.b),i=Be.intoRaw(this.c),n=Si.roundTriangle(A,t,i,this.borderRadius);return A.free(),t.free(),i.free(),n}}class Mx extends ws{constructor(A,t){super(),this.type=ts.Polyline,this.vertices=A,this.indices=t??new Uint32Array(0)}intoRaw(){return Si.polyline(this.vertices,this.indices)}}class Nx extends ws{constructor(A,t,i){super(),this.type=ts.TriMesh,this.vertices=A,this.indices=t,this.flags=i}intoRaw(){return Si.trimesh(this.vertices,this.indices,this.flags)}}class NN extends ws{constructor(A,t){super(),this.type=ts.ConvexPolyhedron,this.vertices=A,this.indices=t}intoRaw(){return this.indices?Si.convexMesh(this.vertices,this.indices):Si.convexHull(this.vertices)}}class RN extends ws{constructor(A,t,i){super(),this.type=ts.RoundConvexPolyhedron,this.vertices=A,this.indices=t,this.borderRadius=i}intoRaw(){return this.indices?Si.roundConvexMesh(this.vertices,this.indices,this.borderRadius):Si.roundConvexHull(this.vertices,this.borderRadius)}}class Rx extends ws{constructor(A,t,i,n,g){super(),this.type=ts.HeightField,this.nrows=A,this.ncols=t,this.heights=i,this.scale=n,this.flags=g}intoRaw(){let A=Be.intoRaw(this.scale),t=Si.heightfield(this.nrows,this.ncols,this.heights,A,this.flags);return A.free(),t}}class Gx extends ws{constructor(A,t){super(),this.type=ts.Cylinder,this.halfHeight=A,this.radius=t}intoRaw(){return Si.cylinder(this.halfHeight,this.radius)}}class bx extends ws{constructor(A,t,i){super(),this.type=ts.RoundCylinder,this.borderRadius=i,this.halfHeight=A,this.radius=t}intoRaw(){return Si.roundCylinder(this.halfHeight,this.radius,this.borderRadius)}}class Ux extends ws{constructor(A,t){super(),this.type=ts.Cone,this.halfHeight=A,this.radius=t}intoRaw(){return Si.cone(this.halfHeight,this.radius)}}class vx extends ws{constructor(A,t,i){super(),this.type=ts.RoundCone,this.halfHeight=A,this.radius=t,this.borderRadius=i}intoRaw(){return Si.roundCone(this.halfHeight,this.radius,this.borderRadius)}}class dW{constructor(A){this.raw=A||new Gse}free(){this.raw&&this.raw.free(),this.raw=void 0}step(A,t,i,n,g,o,s,r,a,I,c,l){let B=Be.intoRaw(A);c?this.raw.stepWithEvents(B,t.raw,i.raw,n.raw,g.raw,o.raw,s.raw,r.raw,a.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,r.raw,a.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"})(R_||(R_={}));class hW{constructor(A){this.raw=A||new zZ}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,r,a,I){let c=Be.intoRaw(i.origin),l=Be.intoRaw(i.dir),B=tG.fromRaw(t,this.raw.castRay(A.raw,t.raw,c,l,n,g,o,s,r,a,I));return c.free(),l.free(),B}castRayAndGetNormal(A,t,i,n,g,o,s,r,a,I){let c=Be.intoRaw(i.origin),l=Be.intoRaw(i.dir),B=xS.fromRaw(t,this.raw.castRayAndGetNormal(A.raw,t.raw,c,l,n,g,o,s,r,a,I));return c.free(),l.free(),B}intersectionsWithRay(A,t,i,n,g,o,s,r,a,I,c){let l=Be.intoRaw(i.origin),B=Be.intoRaw(i.dir);this.raw.intersectionsWithRay(A.raw,t.raw,l,B,n,g,Q=>o(xS.fromRaw(t,Q)),s,r,a,I,c),l.free(),B.free()}intersectionWithShape(A,t,i,n,g,o,s,r,a,I){let c=Be.intoRaw(i),l=An.intoRaw(n),B=g.intoRaw(),Q=this.raw.intersectionWithShape(A.raw,t.raw,c,l,B,o,s,r,a,I);return c.free(),l.free(),B.free(),Q}projectPoint(A,t,i,n,g,o,s,r,a){let I=Be.intoRaw(i),c=LS.fromRaw(t,this.raw.projectPoint(A.raw,t.raw,I,n,g,o,s,r,a));return I.free(),c}projectPointAndGetFeature(A,t,i,n,g,o,s,r){let a=Be.intoRaw(i),I=LS.fromRaw(t,this.raw.projectPointAndGetFeature(A.raw,t.raw,a,n,g,o,s,r));return a.free(),I}intersectionsWithPoint(A,t,i,n,g,o,s,r,a){let I=Be.intoRaw(i);this.raw.intersectionsWithPoint(A.raw,t.raw,I,n,g,o,s,r,a),I.free()}castShape(A,t,i,n,g,o,s,r,a,I,c,l,B,Q){let h=Be.intoRaw(i),d=An.intoRaw(n),p=Be.intoRaw(g),y=o.intoRaw(),m=Fw.fromRaw(t,this.raw.castShape(A.raw,t.raw,h,d,p,y,s,r,a,I,c,l,B,Q));return h.free(),d.free(),p.free(),y.free(),m}intersectionsWithShape(A,t,i,n,g,o,s,r,a,I,c){let l=Be.intoRaw(i),B=An.intoRaw(n),Q=g.intoRaw();this.raw.intersectionsWithShape(A.raw,t.raw,l,B,Q,o,s,r,a,I,c),l.free(),B.free(),Q.free()}collidersWithAabbIntersectingAabb(A,t,i){let n=Be.intoRaw(A),g=Be.intoRaw(t);this.raw.collidersWithAabbIntersectingAabb(n,g,i),n.free(),g.free()}}class v_{constructor(A){this.raw=A||new Use}free(){this.raw&&this.raw.free(),this.raw=void 0}serializeAll(A,t,i,n,g,o,s,r,a){let I=Be.intoRaw(A);const c=this.raw.serializeAll(I,t.raw,i.raw,n.raw,g.raw,o.raw,s.raw,r.raw,a.raw);return I.free(),c}deserializeAll(A){return iG.fromRaw(this.raw.deserializeAll(A))}}class pW{constructor(A,t){this.vertices=A,this.colors=t}}class fW{constructor(A){this.raw=A||new kse}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 yW{}class DW{constructor(A,t,i,n,g){this.params=t,this.bodies=i,this.colliders=n,this.queries=g,this.raw=new Rse(A),this.rawCharacterCollision=new afA,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=Be.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=Be.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 Be.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 yW).translationDeltaApplied=Be.fromRaw(i.translationDeltaApplied()),t.translationDeltaRemaining=Be.fromRaw(i.translationDeltaRemaining()),t.toi=i.toi(),t.witness1=Be.fromRaw(i.worldWitness1()),t.witness2=Be.fromRaw(i.worldWitness2()),t.normal1=Be.fromRaw(i.worldNormal1()),t.normal2=Be.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"})(G_||(G_={}));class mW{constructor(A,t,i,n,g,o){this.params=A,this.bodies=t,this.raw=new bse(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=Be.intoRaw(t),g=Be.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=An.intoRaw(t),g=Be.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=Be.intoRaw(t),g=Be.intoRaw(i),o=this.raw.linear_correction(this.params.dt,this.bodies.raw,A.handle,n,g);return n.free(),g.free(),Be.fromRaw(o)}angularCorrection(A,t,i){let n=An.intoRaw(t),g=Be.intoRaw(i),o=this.raw.angular_correction(this.params.dt,this.bodies.raw,A.handle,n,g);return n.free(),g.free(),Be.fromRaw(o)}}class SW{constructor(A,t,i,n){this.raw=new Nse(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=Be.intoRaw(A),s=Be.intoRaw(t),r=Be.intoRaw(i);this.raw.add_wheel(o,s,r,n,g),o.free(),s.free(),r.free()}numWheels(){return this.raw.num_wheels()}wheelChassisConnectionPointCs(A){return Be.fromRaw(this.raw.wheel_chassis_connection_point_cs(A))}setWheelChassisConnectionPointCs(A,t){let i=Be.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 Be.fromRaw(this.raw.wheel_direction_cs(A))}setWheelDirectionCs(A,t){let i=Be.intoRaw(t);this.raw.set_wheel_direction_cs(A,i),i.free()}wheelAxleCs(A){return Be.fromRaw(this.raw.wheel_axle_cs(A))}setWheelAxleCs(A,t){let i=Be.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 Be.fromRaw(this.raw.wheel_contact_normal_ws(A))}wheelContactPoint(A){return Be.fromRaw(this.raw.wheel_contact_point_ws(A))}wheelSuspensionLength(A){return this.raw.wheel_suspension_length(A)}wheelHardPoint(A){return Be.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 iG{constructor(A,t,i,n,g,o,s,r,a,I,c,l,B,Q){this.gravity=A,this.integrationParameters=new XZ(t),this.islands=new lW(i),this.broadPhase=new BW(n),this.narrowPhase=new EW(g),this.bodies=new VZ(o),this.colliders=new MW(s),this.impulseJoints=new oW(r),this.multibodyJoints=new CW(a),this.ccdSolver=new cW(I),this.queryPipeline=new hW(c),this.physicsPipeline=new dW(l),this.serializationPipeline=new v_(B),this.debugRenderPipeline=new fW(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 iG(Be.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 v_().deserializeAll(A)}debugRender(){return this.debugRenderPipeline.render(this.bodies,this.colliders,this.impulseJoints,this.multibodyJoints,this.narrowPhase),new pW(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 DW(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 mW(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 SW(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,r){return this.queryPipeline.castRay(this.bodies,this.colliders,A,t,i,n,g,o?o.handle:null,s?s.handle:null,this.colliders.castClosure(r))}castRayAndGetNormal(A,t,i,n,g,o,s,r){return this.queryPipeline.castRayAndGetNormal(this.bodies,this.colliders,A,t,i,n,g,o?o.handle:null,s?s.handle:null,this.colliders.castClosure(r))}intersectionsWithRay(A,t,i,n,g,o,s,r,a){this.queryPipeline.intersectionsWithRay(this.bodies,this.colliders,A,t,i,n,g,o,s?s.handle:null,r?r.handle:null,this.colliders.castClosure(a))}intersectionWithShape(A,t,i,n,g,o,s,r){let a=this.queryPipeline.intersectionWithShape(this.bodies,this.colliders,A,t,i,n,g,o?o.handle:null,s?s.handle:null,this.colliders.castClosure(r));return a!=null?this.colliders.get(a):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,r,a,I,c,l){return this.queryPipeline.castShape(this.bodies,this.colliders,A,t,i,n,g,o,s,r,a,I?I.handle:null,c?c.handle:null,this.colliders.castClosure(l))}intersectionsWithShape(A,t,i,n,g,o,s,r,a){this.queryPipeline.intersectionsWithShape(this.bodies,this.colliders,A,t,i,this.colliders.castClosure(n),g,o,s?s.handle:null,r?r.handle:null,this.colliders.castClosure(a))}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"})(kE||(kE={}));class wW{free(){this.raw&&this.raw.free(),this.raw=void 0}collider1(){return this.raw.collider1()}collider2(){return this.raw.collider2()}totalForce(){return Be.fromRaw(this.raw.total_force())}totalForceMagnitude(){return this.raw.total_force_magnitude()}maxForceDirection(){return Be.fromRaw(this.raw.max_force_direction())}maxForceMagnitude(){return this.raw.max_force_magnitude()}}class kW{constructor(A,t){this.raw=t||new lfA(A)}free(){this.raw&&this.raw.free(),this.raw=void 0}drainCollisionEvents(A){this.raw.drainCollisionEvents(A)}drainContactForceEvents(A){let t=new wW;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"})(kN||(kN={})),function(e){e[e.EMPTY=0]="EMPTY",e[e.COMPUTE_IMPULSE=1]="COMPUTE_IMPULSE"}(b_||(b_={})),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"}(MN||(MN={}));class K_{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=ws.fromRaw(this.colliderSet.raw,this.handle))}get shape(){return this.ensureShapeIsCached(),this._shape}isValid(){return this.colliderSet.raw.contains(this.handle)}translation(){return Be.fromRaw(this.colliderSet.raw.coTranslation(this.handle))}rotation(){return An.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=Be.intoRaw(t),o=Be.intoRaw(i),s=An.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 Be.fromRaw(this.colliderSet.raw.coHalfExtents(this.handle))}setHalfExtents(A){const t=Be.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 Be.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=Be.intoRaw(A),i=this.colliderSet.raw.coContainsPoint(this.handle,t);return t.free(),i}projectPoint(A,t){let i=Be.intoRaw(A),n=vw.fromRaw(this.colliderSet.raw.coProjectPoint(this.handle,i,t));return i.free(),n}intersectsRay(A,t){let i=Be.intoRaw(A.origin),n=Be.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,r){let a=Be.intoRaw(A),I=Be.intoRaw(i),c=An.intoRaw(n),l=Be.intoRaw(g),B=t.intoRaw(),Q=ey.fromRaw(this.colliderSet,this.colliderSet.raw.coCastShape(this.handle,a,B,I,c,l,o,s,r));return a.free(),I.free(),c.free(),l.free(),B.free(),Q}castCollider(A,t,i,n,g,o){let s=Be.intoRaw(A),r=Be.intoRaw(i),a=Fw.fromRaw(this.colliderSet,this.colliderSet.raw.coCastCollider(this.handle,s,t.handle,r,n,g,o));return s.free(),r.free(),a}intersectsShape(A,t,i){let n=Be.intoRaw(t),g=An.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=Be.intoRaw(t),o=An.intoRaw(i),s=A.intoRaw(),r=hf.fromRaw(this.colliderSet.raw.coContactShape(this.handle,s,g,o,n));return g.free(),o.free(),s.free(),r}contactCollider(A,t){return hf.fromRaw(this.colliderSet.raw.coContactCollider(this.handle,A.handle,t))}castRay(A,t,i){let n=Be.intoRaw(A.origin),g=Be.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=Be.intoRaw(A.origin),g=Be.intoRaw(A.dir),o=Kw.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 Uo{constructor(A){this.enabled=!0,this.shape=A,this.massPropsMode=Mu.Density,this.density=1,this.friction=.5,this.restitution=0,this.rotation=An.identity(),this.translation=Be.zeros(),this.isSensor=!1,this.collisionGroups=4294967295,this.solverGroups=4294967295,this.frictionCombineRule=JS.Average,this.restitutionCombineRule=JS.Average,this.activeCollisionTypes=MN.DEFAULT,this.activeEvents=kE.NONE,this.activeHooks=kN.NONE,this.mass=0,this.centerOfMass=Be.zeros(),this.contactForceEventThreshold=0,this.contactSkin=0,this.principalAngularInertia=Be.zeros(),this.angularInertiaLocalFrame=An.identity()}static ball(A){const t=new fx(A);return new Uo(t)}static capsule(A,t){const i=new mx(A,t);return new Uo(i)}static segment(A,t){const i=new Sx(A,t);return new Uo(i)}static triangle(A,t,i){const n=new wx(A,t,i);return new Uo(n)}static roundTriangle(A,t,i,n){const g=new kx(A,t,i,n);return new Uo(g)}static polyline(A,t){const i=new Mx(A,t);return new Uo(i)}static trimesh(A,t,i){const n=new Nx(A,t,i);return new Uo(n)}static cuboid(A,t,i){const n=new yx(A,t,i);return new Uo(n)}static roundCuboid(A,t,i,n){const g=new Dx(A,t,i,n);return new Uo(g)}static heightfield(A,t,i,n,g){const o=new Rx(A,t,i,n,g);return new Uo(o)}static cylinder(A,t){const i=new Gx(A,t);return new Uo(i)}static roundCylinder(A,t,i){const n=new bx(A,t,i);return new Uo(n)}static cone(A,t){const i=new Ux(A,t);return new Uo(i)}static roundCone(A,t,i){const n=new vx(A,t,i);return new Uo(n)}static convexHull(A){const t=new NN(A,null);return new Uo(t)}static convexMesh(A,t){const i=new NN(A,t);return new Uo(i)}static roundConvexHull(A,t){const i=new RN(A,null,t);return new Uo(i)}static roundConvexMesh(A,t,i){const n=new RN(A,t,i);return new Uo(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 An.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,Be.copy(this.centerOfMass,t),Be.copy(this.principalAngularInertia,i),An.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 MW{constructor(A){this.raw=A||new po,this.map=new dx,A&&A.forEachColliderHandle(t=>{this.map.set(t,new K_(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=Be.intoRaw(t.translation),s=An.intoRaw(t.rotation),r=Be.intoRaw(t.centerOfMass),a=Be.intoRaw(t.principalAngularInertia),I=An.intoRaw(t.angularInertiaLocalFrame),c=this.raw.createCollider(t.enabled,g,o,s,t.massPropsMode,t.mass,r,a,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(),r.free(),a.free(),I.free();let l=n?A.get(i):null,B=new K_(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 vse(e,A,t,i){return new(t||(t=Promise))(function(n,g){function o(a){try{r(i.next(a))}catch(I){g(I)}}function s(a){try{r(i.throw(a))}catch(I){g(I)}}function r(a){var I;a.done?n(a.value):(I=a.value,I instanceof t?I:new t(function(c){c(I)})).then(o,s)}r((i=i.apply(e,[])).next())})}for(var Kse={byteLength:function(e){var A=viA(e),t=A[0],i=A[1];return 3*(t+i)/4-i},toByteArray:function(e){var A,t,i=viA(e),n=i[0],g=i[1],o=new Fse(function(a,I,c){return 3*(I+c)/4-c}(0,n,g)),s=0,r=g>0?n-4:n;for(t=0;t<r;t+=4)A=wC[e.charCodeAt(t)]<<18|wC[e.charCodeAt(t+1)]<<12|wC[e.charCodeAt(t+2)]<<6|wC[e.charCodeAt(t+3)],o[s++]=A>>16&255,o[s++]=A>>8&255,o[s++]=255&A;return g===2&&(A=wC[e.charCodeAt(t)]<<2|wC[e.charCodeAt(t+1)]>>4,o[s++]=255&A),g===1&&(A=wC[e.charCodeAt(t)]<<10|wC[e.charCodeAt(t+1)]<<4|wC[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(Jse(e,o,o+g>s?s:o+g));return i===1?(A=e[t-1],n.push(Vl[A>>2]+Vl[A<<4&63]+"==")):i===2&&(A=(e[t-2]<<8)+e[t-1],n.push(Vl[A>>10]+Vl[A>>4&63]+Vl[A<<2&63]+"=")),n.join("")}},Vl=[],wC=[],Fse=typeof Uint8Array<"u"?Uint8Array:Array,eH="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Vy=0,_se=eH.length;Vy<_se;++Vy)Vl[Vy]=eH[Vy],wC[eH.charCodeAt(Vy)]=Vy;function viA(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 Jse(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(Vl[(n=i)>>18&63]+Vl[n>>12&63]+Vl[n>>6&63]+Vl[63&n]);return g.join("")}function QfA(){return vse(this,void 0,void 0,function*(){yield BfA(Kse.toByteArray(" ").buffer)})}function ufA(){return function(){let e,A;try{const n=V.__wbindgen_add_to_stack_pointer(-16);V.version(n);var t=zs().getInt32(n+0,!0),i=zs().getInt32(n+4,!0);return e=t,A=i,ofA(t,i)}finally{V.__wbindgen_add_to_stack_pointer(16),V.__wbindgen_export_1(e,A,1)}}()}wC[45]=62,wC[95]=63;var Lse=Object.freeze({__proto__:null,version:ufA,Vector3:Pm,VectorOps:Be,Quaternion:m_,RotationOps:An,SdpMatrix3:WZ,SdpMatrix3Ops:S_,get RigidBodyType(){return _C},RigidBody:U_,RigidBodyDesc:JC,RigidBodySet:VZ,IntegrationParameters:XZ,get JointType(){return js},get MotorModel(){return w_},get JointAxesMask(){return k_},ImpulseJoint:oc,UnitImpulseJoint:hx,FixedImpulseJoint:$Z,RopeImpulseJoint:AW,SpringImpulseJoint:eW,PrismaticImpulseJoint:tW,RevoluteImpulseJoint:iW,GenericImpulseJoint:nW,SphericalImpulseJoint:gW,JointData:Ol,ImpulseJointSet:oW,MultibodyJoint:sQ,UnitMultibodyJoint:px,FixedMultibodyJoint:sW,PrismaticMultibodyJoint:rW,RevoluteMultibodyJoint:aW,SphericalMultibodyJoint:IW,MultibodyJointSet:CW,get CoefficientCombineRule(){return JS},CCDSolver:cW,IslandManager:lW,BroadPhase:BW,NarrowPhase:EW,TempContactManifold:QW,Shape:ws,get ShapeType(){return ts},get HeightFieldFlags(){return M_},get TriMeshFlags(){return N_},Ball:fx,HalfSpace:uW,Cuboid:yx,RoundCuboid:Dx,Capsule:mx,Segment:Sx,Triangle:wx,RoundTriangle:kx,Polyline:Mx,TriMesh:Nx,ConvexPolyhedron:NN,RoundConvexPolyhedron:RN,Heightfield:Rx,Cylinder:Gx,RoundCylinder:bx,Cone:Ux,RoundCone:vx,get ActiveCollisionTypes(){return MN},Collider:K_,get MassPropsMode(){return Mu},ColliderDesc:Uo,ColliderSet:MW,get FeatureType(){return df},Ray:EfA,RayIntersection:Kw,RayColliderIntersection:xS,RayColliderHit:tG,PointProjection:vw,PointColliderProjection:LS,ShapeCastHit:ey,ColliderShapeCastHit:Fw,ShapeContact:hf,World:iG,PhysicsPipeline:dW,SerializationPipeline:v_,get ActiveEvents(){return kE},TempContactForceEvent:wW,EventQueue:kW,get ActiveHooks(){return kN},get SolverFlags(){return b_},DebugRenderBuffers:pW,DebugRenderPipeline:fW,get QueryFilterFlags(){return R_},QueryPipeline:hW,init:QfA,CharacterCollision:yW,KinematicCharacterController:DW,get PidAxesMask(){return G_},PidController:mW,DynamicRayCastVehicleController:SW});const xse=Object.freeze(Object.defineProperty({__proto__:null,get ActiveCollisionTypes(){return MN},get ActiveEvents(){return kE},get ActiveHooks(){return kN},Ball:fx,BroadPhase:BW,CCDSolver:cW,Capsule:mx,CharacterCollision:yW,get CoefficientCombineRule(){return JS},Collider:K_,ColliderDesc:Uo,ColliderSet:MW,ColliderShapeCastHit:Fw,Cone:Ux,ConvexPolyhedron:NN,Cuboid:yx,Cylinder:Gx,DebugRenderBuffers:pW,DebugRenderPipeline:fW,DynamicRayCastVehicleController:SW,EventQueue:kW,get FeatureType(){return df},FixedImpulseJoint:$Z,FixedMultibodyJoint:sW,GenericImpulseJoint:nW,HalfSpace:uW,get HeightFieldFlags(){return M_},Heightfield:Rx,ImpulseJoint:oc,ImpulseJointSet:oW,IntegrationParameters:XZ,IslandManager:lW,get JointAxesMask(){return k_},JointData:Ol,get JointType(){return js},KinematicCharacterController:DW,get MassPropsMode(){return Mu},get MotorModel(){return w_},MultibodyJoint:sQ,MultibodyJointSet:CW,NarrowPhase:EW,PhysicsPipeline:dW,get PidAxesMask(){return G_},PidController:mW,PointColliderProjection:LS,PointProjection:vw,Polyline:Mx,PrismaticImpulseJoint:tW,PrismaticMultibodyJoint:rW,Quaternion:m_,get QueryFilterFlags(){return R_},QueryPipeline:hW,Ray:EfA,RayColliderHit:tG,RayColliderIntersection:xS,RayIntersection:Kw,RevoluteImpulseJoint:iW,RevoluteMultibodyJoint:aW,RigidBody:U_,RigidBodyDesc:JC,RigidBodySet:VZ,get RigidBodyType(){return _C},RopeImpulseJoint:AW,RotationOps:An,RoundCone:vx,RoundConvexPolyhedron:RN,RoundCuboid:Dx,RoundCylinder:bx,RoundTriangle:kx,SdpMatrix3:WZ,SdpMatrix3Ops:S_,Segment:Sx,SerializationPipeline:v_,Shape:ws,ShapeCastHit:ey,ShapeContact:hf,get ShapeType(){return ts},get SolverFlags(){return b_},SphericalImpulseJoint:gW,SphericalMultibodyJoint:IW,SpringImpulseJoint:eW,TempContactForceEvent:wW,TempContactManifold:QW,TriMesh:Nx,get TriMeshFlags(){return N_},Triangle:wx,UnitImpulseJoint:hx,UnitMultibodyJoint:px,Vector3:Pm,VectorOps:Be,World:iG,default:Lse,init:QfA,version:ufA},Symbol.toStringTag,{value:"Module"}));var dfA={exports:{}},Jd={};/**
 * @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.
 */Jd.ConcurrentRoot=1;Jd.ContinuousEventPriority=8;Jd.DefaultEventPriority=32;Jd.DiscreteEventPriority=2;Jd.IdleEventPriority=268435456;Jd.LegacyRoot=0;Jd.NoEventPriority=0;dfA.exports=Jd;var UK=dfA.exports;/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */const nG="180",Tse={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},qse={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},hfA=0,n4=1,pfA=2,Yse=3,ffA=0,Kx=1,mM=2,Nc=3,Al=0,kr=1,Xa=2,xE=0,Yp=1,Vg=2,g4=3,o4=4,yfA=5,au=100,DfA=101,mfA=102,SfA=103,wfA=104,kfA=200,MfA=201,NfA=202,RfA=203,F_=204,__=205,GfA=206,bfA=207,UfA=208,vfA=209,KfA=210,FfA=211,_fA=212,JfA=213,LfA=214,J_=0,L_=1,x_=2,pf=3,T_=4,q_=5,Y_=6,H_=7,gG=0,xfA=1,TfA=2,uB=0,qfA=1,YfA=2,HfA=3,ty=4,OfA=5,PfA=6,jfA=7,s4="attached",zfA="detached",Fx=300,rQ=301,ud=302,GN=303,bN=304,_w=306,va=1e3,nI=1001,ff=1002,Ds=1003,oG=1004,Hse=1004,Nu=1005,Ose=1005,_g=1006,Hp=1007,Pse=1007,Ra=1008,jse=1008,sc=1009,NW=1010,RW=1011,TS=1012,_x=1013,aQ=1014,Ga=1015,iy=1016,Jx=1017,Lx=1018,qS=1020,GW=35902,bW=35899,UW=1021,vW=1022,jr=1023,YS=1026,HS=1027,xx=1028,sG=1029,KW=1030,Tx=1031,zse=1032,qx=1033,SM=33776,wM=33777,kM=33778,MM=33779,O_=35840,P_=35841,j_=35842,z_=35843,Z_=36196,W_=37492,V_=37496,X_=37808,$_=37809,AJ=37810,eJ=37811,tJ=37812,iJ=37813,nJ=37814,gJ=37815,oJ=37816,sJ=37817,rJ=37818,aJ=37819,IJ=37820,CJ=37821,cJ=36492,lJ=36494,BJ=36495,EJ=36283,QJ=36284,uJ=36285,dJ=36286,FW=2200,hJ=2201,ZfA=2202,yf=2300,dd=2301,vK=2302,lp=2400,Bp=2401,UN=2402,Yx=2500,_W=2501,JW=0,rG=1,Df=2,WfA=3200,VfA=3201,Zse=3202,Wse=3203,Ld=0,XfA=1,yE="",sn="srgb",Mr="srgb-linear",vN="linear",hg="srgb",Vse=0,Xh=7680,Xse=7681,$se=7682,Are=7683,ere=34055,tre=34056,ire=5386,nre=512,gre=513,ore=514,sre=515,rre=516,are=517,Ire=518,r4=519,$fA=512,AyA=513,eyA=514,LW=515,tyA=516,iyA=517,nyA=518,gyA=519,KN=35044,oyA=35048,Cre=35040,cre=35045,lre=35049,Bre=35041,Ere=35046,Qre=35050,ure=35042,dre="100",a4="300 es",OI=2e3,OS=2001,hre={COMPUTE:"compute",RENDER:"render"},pre={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},fre={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"};class UB{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 Lr=["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 KiA=1234567;const Op=Math.PI/180,PS=180/Math.PI;function VI(){const e=Math.random()*4294967295|0,A=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Lr[e&255]+Lr[e>>8&255]+Lr[e>>16&255]+Lr[e>>24&255]+"-"+Lr[A&255]+Lr[A>>8&255]+"-"+Lr[A>>16&15|64]+Lr[A>>24&255]+"-"+Lr[t&63|128]+Lr[t>>8&255]+"-"+Lr[t>>16&255]+Lr[t>>24&255]+Lr[i&255]+Lr[i>>8&255]+Lr[i>>16&255]+Lr[i>>24&255]).toLowerCase()}function bi(e,A,t){return Math.max(A,Math.min(t,e))}function xW(e,A){return(e%A+A)%A}function yre(e,A,t,i,n){return i+(e-A)*(n-i)/(t-A)}function Dre(e,A,t){return e!==A?(t-e)/(A-e):0}function NM(e,A,t){return(1-t)*e+t*A}function mre(e,A,t,i){return NM(e,A,1-Math.exp(-t*i))}function Sre(e,A=1){return A-Math.abs(xW(e,A*2)-A)}function wre(e,A,t){return e<=A?0:e>=t?1:(e=(e-A)/(t-A),e*e*(3-2*e))}function kre(e,A,t){return e<=A?0:e>=t?1:(e=(e-A)/(t-A),e*e*e*(e*(e*6-15)+10))}function Mre(e,A){return e+Math.floor(Math.random()*(A-e+1))}function Nre(e,A){return e+Math.random()*(A-e)}function Rre(e){return e*(.5-Math.random())}function Gre(e){e!==void 0&&(KiA=e);let A=KiA+=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 bre(e){return e*Op}function Ure(e){return e*PS}function vre(e){return(e&e-1)===0&&e!==0}function Kre(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))}function Fre(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function _re(e,A,t,i,n){const g=Math.cos,o=Math.sin,s=g(t/2),r=o(t/2),a=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,r*c,r*l,s*a);break;case"YZY":e.set(r*l,s*I,r*c,s*a);break;case"ZXZ":e.set(r*c,r*l,s*I,s*a);break;case"XZX":e.set(s*I,r*Q,r*B,s*a);break;case"YXY":e.set(r*B,s*I,r*Q,s*a);break;case"ZYZ":e.set(r*Q,r*B,s*I,s*a);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function Sa(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 on(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 zC={DEG2RAD:Op,RAD2DEG:PS,generateUUID:VI,clamp:bi,euclideanModulo:xW,mapLinear:yre,inverseLerp:Dre,lerp:NM,damp:mre,pingpong:Sre,smoothstep:wre,smootherstep:kre,randInt:Mre,randFloat:Nre,randFloatSpread:Rre,seededRandom:Gre,degToRad:bre,radToDeg:Ure,isPowerOfTwo:vre,ceilPowerOfTwo:Kre,floorPowerOfTwo:Fre,setQuaternionFromProperEuler:_re,normalize:on,denormalize:Sa};class It{constructor(A=0,t=0){It.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=bi(this.x,A.x,t.x),this.y=bi(this.y,A.y,t.y),this}clampScalar(A,t){return this.x=bi(this.x,A,t),this.y=bi(this.y,A,t),this}clampLength(A,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(bi(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(bi(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 Ao{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 r=i[n+0],a=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]=r,A[t+1]=a,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||r!==l||a!==B||I!==Q){let d=1-s;const p=r*l+a*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(r=r*d+l*D,a=a*d+B*D,I=I*d+Q*D,c=c*d+h*D,d===1-s){const S=1/Math.sqrt(r*r+a*a+I*I+c*c);r*=S,a*=S,I*=S,c*=S}}A[t]=r,A[t+1]=a,A[t+2]=I,A[t+3]=c}static multiplyQuaternionsFlat(A,t,i,n,g,o){const s=i[n],r=i[n+1],a=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+r*B-a*l,A[t+1]=r*Q+I*l+a*c-s*B,A[t+2]=a*Q+I*B+s*l-r*c,A[t+3]=I*Q-s*c-r*l-a*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,r=Math.sin,a=s(i/2),I=s(n/2),c=s(g/2),l=r(i/2),B=r(n/2),Q=r(g/2);switch(o){case"XYZ":this._x=l*I*c+a*B*Q,this._y=a*B*c-l*I*Q,this._z=a*I*Q+l*B*c,this._w=a*I*c-l*B*Q;break;case"YXZ":this._x=l*I*c+a*B*Q,this._y=a*B*c-l*I*Q,this._z=a*I*Q-l*B*c,this._w=a*I*c+l*B*Q;break;case"ZXY":this._x=l*I*c-a*B*Q,this._y=a*B*c+l*I*Q,this._z=a*I*Q+l*B*c,this._w=a*I*c-l*B*Q;break;case"ZYX":this._x=l*I*c-a*B*Q,this._y=a*B*c+l*I*Q,this._z=a*I*Q-l*B*c,this._w=a*I*c+l*B*Q;break;case"YZX":this._x=l*I*c+a*B*Q,this._y=a*B*c+l*I*Q,this._z=a*I*Q-l*B*c,this._w=a*I*c-l*B*Q;break;case"XZY":this._x=l*I*c-a*B*Q,this._y=a*B*c-l*I*Q,this._z=a*I*Q+l*B*c,this._w=a*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],r=t[9],a=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-r)*B,this._y=(g-a)*B,this._z=(o-n)*B}else if(i>s&&i>c){const B=2*Math.sqrt(1+i-s-c);this._w=(I-r)/B,this._x=.25*B,this._y=(n+o)/B,this._z=(g+a)/B}else if(s>c){const B=2*Math.sqrt(1+s-i-c);this._w=(g-a)/B,this._x=(n+o)/B,this._y=.25*B,this._z=(r+I)/B}else{const B=2*Math.sqrt(1+c-i-s);this._w=(o-n)/B,this._x=(g+a)/B,this._y=(r+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(bi(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,r=t._y,a=t._z,I=t._w;return this._x=i*I+o*s+n*a-g*r,this._y=n*I+o*r+g*s-i*a,this._z=g*I+o*a+i*r-n*s,this._w=o*I-i*s-n*r-g*a,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 r=1-s*s;if(r<=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 a=Math.sqrt(r),I=Math.atan2(a,s),c=Math.sin((1-t)*I)/a,l=Math.sin(t*I)/a;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(FiA.setFromEuler(A))}applyAxisAngle(A,t){return this.applyQuaternion(FiA.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,r=A.w,a=2*(o*n-s*i),I=2*(s*t-g*n),c=2*(g*i-o*t);return this.x=t+r*a+o*c-s*I,this.y=i+r*I+s*a-g*c,this.z=n+r*c+g*I-o*a,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=bi(this.x,A.x,t.x),this.y=bi(this.y,A.y,t.y),this.z=bi(this.z,A.z,t.z),this}clampScalar(A,t){return this.x=bi(this.x,A,t),this.y=bi(this.y,A,t),this.z=bi(this.z,A,t),this}clampLength(A,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(bi(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,r=t.z;return this.x=n*r-g*s,this.y=g*o-i*r,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 tH.copy(this).projectOnVector(A),this.sub(tH)}reflect(A){return this.sub(tH.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(bi(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 tH=new SA,FiA=new Ao;class $i{constructor(A,t,i,n,g,o,s,r,a){$i.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,r,a)}set(A,t,i,n,g,o,s,r,a){const I=this.elements;return I[0]=A,I[1]=n,I[2]=s,I[3]=t,I[4]=g,I[5]=r,I[6]=i,I[7]=o,I[8]=a,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],r=i[6],a=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+r*S,g[3]=o*d+s*m+r*k,g[6]=o*p+s*D+r*N,g[1]=a*h+I*y+c*S,g[4]=a*d+I*m+c*k,g[7]=a*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],r=A[6],a=A[7],I=A[8];return t*o*I-t*s*a-i*g*I+i*s*r+n*g*a-n*o*r}invert(){const A=this.elements,t=A[0],i=A[1],n=A[2],g=A[3],o=A[4],s=A[5],r=A[6],a=A[7],I=A[8],c=I*o-s*a,l=s*r-I*g,B=a*g-o*r,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*a-I*i)*h,A[2]=(s*i-n*o)*h,A[3]=l*h,A[4]=(I*t-n*r)*h,A[5]=(n*g-s*t)*h,A[6]=B*h,A[7]=(i*r-a*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 r=Math.cos(g),a=Math.sin(g);return this.set(i*r,i*a,-i*(r*o+a*s)+o+A,-n*a,n*r,-n*(-a*o+r*s)+s+t,0,0,1),this}scale(A,t){return this.premultiply(iH.makeScale(A,t)),this}rotate(A){return this.premultiply(iH.makeRotation(-A)),this}translate(A,t){return this.premultiply(iH.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 iH=new $i;function syA(e){for(let A=e.length-1;A>=0;--A)if(e[A]>=65535)return!0;return!1}const Jre={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function rm(e,A){return new Jre[e](A)}function FN(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function ryA(){const e=FN("canvas");return e.style.display="block",e}const _iA={};function _N(e){e in _iA||(_iA[e]=!0,console.warn(e))}function Lre(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 JiA=new $i().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),LiA=new $i().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function xre(){const e={enabled:!0,workingColorSpace:Mr,spaces:{},convert:function(n,g,o){return this.enabled===!1||g===o||!g||!o||(this.spaces[g].transfer===hg&&(n.r=TE(n.r),n.g=TE(n.g),n.b=TE(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===hg&&(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===yE?vN: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 _N("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(n,g)},toWorkingColorSpace:function(n,g){return _N("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({[Mr]:{primaries:A,whitePoint:i,transfer:vN,toXYZ:JiA,fromXYZ:LiA,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:sn},outputColorSpaceConfig:{drawingBufferColorSpace:sn}},[sn]:{primaries:A,whitePoint:i,transfer:hg,toXYZ:JiA,fromXYZ:LiA,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:sn}}}),e}const Rn=xre();function TE(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 ayA{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=FN("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=FN("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]=TE(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(TE(t[i]/255)*255):t[i]=TE(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 Tre=0;class Ru{constructor(A=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Tre++}),this.uuid=VI(),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(nH(n[o].image)):g.push(nH(n[o]))}else g=nH(n);i.url=g}return t||(A.images[this.uuid]=i),i}}function nH(e){return typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap?ayA.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 qre=0;const gH=new SA;class Rg extends UB{constructor(A=Rg.DEFAULT_IMAGE,t=Rg.DEFAULT_MAPPING,i=nI,n=nI,g=_g,o=Ra,s=jr,r=sc,a=Rg.DEFAULT_ANISOTROPY,I=yE){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:qre++}),this.uuid=VI(),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=a,this.format=s,this.internalFormat=null,this.type=r,this.offset=new It(0,0),this.repeat=new It(1,1),this.center=new It(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new $i,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(gH).x}get height(){return this.source.getSize(gH).y}get depth(){return this.source.getSize(gH).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!==Fx)return A;if(A.applyMatrix3(this.matrix),A.x<0||A.x>1)switch(this.wrapS){case va:A.x=A.x-Math.floor(A.x);break;case nI: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 va:A.y=A.y-Math.floor(A.y);break;case nI: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++}}Rg.DEFAULT_IMAGE=null;Rg.DEFAULT_MAPPING=Fx;Rg.DEFAULT_ANISOTROPY=1;class $n{constructor(A=0,t=0,i=0,n=1){$n.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 r=A.elements,a=r[0],I=r[4],c=r[8],l=r[1],B=r[5],Q=r[9],h=r[2],d=r[6],p=r[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(a+B+p-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const m=(a+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((a+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=bi(this.x,A.x,t.x),this.y=bi(this.y,A.y,t.y),this.z=bi(this.z,A.z,t.z),this.w=bi(this.w,A.w,t.w),this}clampScalar(A,t){return this.x=bi(this.x,A,t),this.y=bi(this.y,A,t),this.z=bi(this.z,A,t),this.w=bi(this.w,A,t),this}clampLength(A,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(bi(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 TW extends UB{constructor(A=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:_g,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 $n(0,0,A,t),this.scissorTest=!1,this.viewport=new $n(0,0,A,t);const n={width:A,height:t,depth:i.depth},g=new Rg(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:_g,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 el extends TW{constructor(A=1,t=1,i={}){super(A,t,i),this.isWebGLRenderTarget=!0}}class Hx extends Rg{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=Ds,this.minFilter=Ds,this.wrapR=nI,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(A){this.layerUpdates.add(A)}clearLayerUpdates(){this.layerUpdates.clear()}}class Yre extends el{constructor(A=1,t=1,i=1,n={}){super(A,t,n),this.isWebGLArrayRenderTarget=!0,this.depth=i,this.texture=new Hx(null,A,t,i),this._setTextureOptions(n),this.texture.isRenderTargetTexture=!0}}class Ox extends Rg{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=Ds,this.minFilter=Ds,this.wrapR=nI,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Hre extends el{constructor(A=1,t=1,i=1,n={}){super(A,t,n),this.isWebGL3DRenderTarget=!0,this.depth=i,this.texture=new Ox(null,A,t,i),this._setTextureOptions(n),this.texture.isRenderTargetTexture=!0}}class Vn{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(mc.fromArray(A,t));return this}setFromBufferAttribute(A){this.makeEmpty();for(let t=0,i=A.count;t<i;t++)this.expandByPoint(mc.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=mc.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,mc):mc.fromBufferAttribute(g,o),mc.applyMatrix4(A.matrixWorld),this.expandByPoint(mc);else A.boundingBox!==void 0?(A.boundingBox===null&&A.computeBoundingBox(),sU.copy(A.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),sU.copy(i.boundingBox)),sU.applyMatrix4(A.matrixWorld),this.union(sU)}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,mc),mc.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(x0),rU.subVectors(this.max,x0),$y.subVectors(A.a,x0),AD.subVectors(A.b,x0),eD.subVectors(A.c,x0),vQ.subVectors(AD,$y),KQ.subVectors(eD,AD),hh.subVectors($y,eD);let t=[0,-vQ.z,vQ.y,0,-KQ.z,KQ.y,0,-hh.z,hh.y,vQ.z,0,-vQ.x,KQ.z,0,-KQ.x,hh.z,0,-hh.x,-vQ.y,vQ.x,0,-KQ.y,KQ.x,0,-hh.y,hh.x,0];return!oH(t,$y,AD,eD,rU)||(t=[1,0,0,0,1,0,0,0,1],!oH(t,$y,AD,eD,rU))?!1:(aU.crossVectors(vQ,KQ),t=[aU.x,aU.y,aU.z],oH(t,$y,AD,eD,rU))}clampPoint(A,t){return t.copy(A).clamp(this.min,this.max)}distanceToPoint(A){return this.clampPoint(A,mc).distanceTo(A)}getBoundingSphere(A){return this.isEmpty()?A.makeEmpty():(this.getCenter(A.center),A.radius=this.getSize(mc).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:(VB[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(A),VB[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(A),VB[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(A),VB[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(A),VB[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(A),VB[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(A),VB[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(A),VB[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(A),this.setFromPoints(VB),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 VB=[new SA,new SA,new SA,new SA,new SA,new SA,new SA,new SA],mc=new SA,sU=new Vn,$y=new SA,AD=new SA,eD=new SA,vQ=new SA,KQ=new SA,hh=new SA,x0=new SA,rU=new SA,aU=new SA,ph=new SA;function oH(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),r=A.dot(ph),a=t.dot(ph),I=i.dot(ph);if(Math.max(-Math.max(r,a,I),Math.min(r,a,I))>s)return!1}return!0}const Ore=new Vn,T0=new SA,sH=new SA;class vs{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):Ore.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;T0.subVectors(A,this.center);const t=T0.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),n=(i-this.radius)*.5;this.center.addScaledVector(T0,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):(sH.subVectors(A.center,this.center).setLength(A.radius),this.expandByPoint(T0.copy(A.center).add(sH)),this.expandByPoint(T0.copy(A.center).sub(sH))),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 XB=new SA,rH=new SA,IU=new SA,FQ=new SA,aH=new SA,CU=new SA,IH=new SA;class Jw{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,XB)),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=XB.subVectors(A,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(A):(XB.copy(this.origin).addScaledVector(this.direction,t),XB.distanceToSquared(A))}distanceSqToSegment(A,t,i,n){rH.copy(A).add(t).multiplyScalar(.5),IU.copy(t).sub(A).normalize(),FQ.copy(this.origin).sub(rH);const g=A.distanceTo(t)*.5,o=-this.direction.dot(IU),s=FQ.dot(this.direction),r=-FQ.dot(IU),a=FQ.lengthSq(),I=Math.abs(1-o*o);let c,l,B,Q;if(I>0)if(c=o*r-s,l=o*s-r,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*r)+a}else l=g,c=Math.max(0,-(o*l+s)),B=-c*c+l*(l+2*r)+a;else l=-g,c=Math.max(0,-(o*l+s)),B=-c*c+l*(l+2*r)+a;else l<=-Q?(c=Math.max(0,-(-o*g+s)),l=c>0?-g:Math.min(Math.max(-g,-r),g),B=-c*c+l*(l+2*r)+a):l<=Q?(c=0,l=Math.min(Math.max(-g,-r),g),B=l*(l+2*r)+a):(c=Math.max(0,-(o*g+s)),l=c>0?g:Math.min(Math.max(-g,-r),g),B=-c*c+l*(l+2*r)+a);else l=o>0?-g:g,c=Math.max(0,-(o*l+s)),B=-c*c+l*(l+2*r)+a;return i&&i.copy(this.origin).addScaledVector(this.direction,c),n&&n.copy(rH).addScaledVector(IU,l),B}intersectSphere(A,t){XB.subVectors(A.center,this.origin);const i=XB.dot(this.direction),n=XB.dot(XB)-i*i,g=A.radius*A.radius;if(n>g)return null;const o=Math.sqrt(g-n),s=i-o,r=i+o;return r<0?null:s<0?this.at(r,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,r;const a=1/this.direction.x,I=1/this.direction.y,c=1/this.direction.z,l=this.origin;return a>=0?(i=(A.min.x-l.x)*a,n=(A.max.x-l.x)*a):(i=(A.max.x-l.x)*a,n=(A.min.x-l.x)*a),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,r=(A.max.z-l.z)*c):(s=(A.max.z-l.z)*c,r=(A.min.z-l.z)*c),i>r||s>n)||((s>i||i!==i)&&(i=s),(r<n||n!==n)&&(n=r),n<0)?null:this.at(i>=0?i:n,t)}intersectsBox(A){return this.intersectBox(A,XB)!==null}intersectTriangle(A,t,i,n,g){aH.subVectors(t,A),CU.subVectors(i,A),IH.crossVectors(aH,CU);let o=this.direction.dot(IH),s;if(o>0){if(n)return null;s=1}else if(o<0)s=-1,o=-o;else return null;FQ.subVectors(this.origin,A);const r=s*this.direction.dot(CU.crossVectors(FQ,CU));if(r<0)return null;const a=s*this.direction.dot(aH.cross(FQ));if(a<0||r+a>o)return null;const I=-s*FQ.dot(IH);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 ii{constructor(A,t,i,n,g,o,s,r,a,I,c,l,B,Q,h,d){ii.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,r,a,I,c,l,B,Q,h,d)}set(A,t,i,n,g,o,s,r,a,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]=r,p[2]=a,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 ii().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),r=Math.cos(n),a=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]=r*I,t[4]=-r*c,t[8]=a,t[1]=B+Q*a,t[5]=l-h*a,t[9]=-s*r,t[2]=h-l*a,t[6]=Q+B*a,t[10]=o*r}else if(A.order==="YXZ"){const l=r*I,B=r*c,Q=a*I,h=a*c;t[0]=l+h*s,t[4]=Q*s-B,t[8]=o*a,t[1]=o*c,t[5]=o*I,t[9]=-s,t[2]=B*s-Q,t[6]=h+l*s,t[10]=o*r}else if(A.order==="ZXY"){const l=r*I,B=r*c,Q=a*I,h=a*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*a,t[6]=s,t[10]=o*r}else if(A.order==="ZYX"){const l=o*I,B=o*c,Q=s*I,h=s*c;t[0]=r*I,t[4]=Q*a-B,t[8]=l*a+h,t[1]=r*c,t[5]=h*a+l,t[9]=B*a-Q,t[2]=-a,t[6]=s*r,t[10]=o*r}else if(A.order==="YZX"){const l=o*r,B=o*a,Q=s*r,h=s*a;t[0]=r*I,t[4]=h-l*c,t[8]=Q*c+B,t[1]=c,t[5]=o*I,t[9]=-s*I,t[2]=-a*I,t[6]=B*c+Q,t[10]=l-h*c}else if(A.order==="XZY"){const l=o*r,B=o*a,Q=s*r,h=s*a;t[0]=r*I,t[4]=-c,t[8]=a*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(Pre,A,jre)}lookAt(A,t,i){const n=this.elements;return RI.subVectors(A,t),RI.lengthSq()===0&&(RI.z=1),RI.normalize(),_Q.crossVectors(i,RI),_Q.lengthSq()===0&&(Math.abs(i.z)===1?RI.x+=1e-4:RI.z+=1e-4,RI.normalize(),_Q.crossVectors(i,RI)),_Q.normalize(),cU.crossVectors(RI,_Q),n[0]=_Q.x,n[4]=cU.x,n[8]=RI.x,n[1]=_Q.y,n[5]=cU.y,n[9]=RI.y,n[2]=_Q.z,n[6]=cU.z,n[10]=RI.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],r=i[8],a=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],T=n[6],v=n[10],U=n[14],x=n[3],q=n[7],z=n[11],Z=n[15];return g[0]=o*k+s*w+r*J+a*x,g[4]=o*N+s*b+r*T+a*q,g[8]=o*G+s*_+r*v+a*z,g[12]=o*M+s*K+r*U+a*Z,g[1]=I*k+c*w+l*J+B*x,g[5]=I*N+c*b+l*T+B*q,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*T+p*q,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*T+S*q,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],r=A[9],a=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*r*c-n*a*c-g*s*l+i*a*l+n*s*B-i*r*B)+h*(+t*r*B-t*a*l+g*o*l-n*o*B+n*a*I-g*r*I)+d*(+t*a*c-t*s*B-g*o*c+i*o*B+g*s*I-i*a*I)+p*(-n*s*I-t*r*c+t*s*l+n*o*c-i*o*l+i*r*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],r=A[6],a=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*a-h*l*a+h*r*B-s*d*B-c*r*p+s*l*p,m=Q*l*a-I*d*a-Q*r*B+o*d*B+I*r*p-o*l*p,D=I*h*a-Q*c*a+Q*s*B-o*h*B-I*s*p+o*c*p,S=Q*c*r-I*h*r-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*r*g+h*n*a-i*d*a-s*n*p+i*r*p)*N,A[3]=(c*r*g-s*l*g-c*n*a+i*l*a+s*n*B-i*r*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*r*g-o*d*g-Q*n*a+t*d*a+o*n*p-t*r*p)*N,A[7]=(o*l*g-I*r*g+I*n*a-t*l*a-o*n*B+t*r*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*a-t*h*a-o*i*p+t*s*p)*N,A[11]=(I*s*g-o*c*g-I*i*a+t*c*a+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*r+t*h*r+o*i*d-t*s*d)*N,A[15]=(o*c*n-I*s*n+I*i*r-t*c*r-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,r=A.z,a=g*o,I=g*s;return this.set(a*o+i,a*s-n*r,a*r+n*s,0,a*s+n*r,I*s+i,I*r-n*o,0,a*r-n*s,I*r+n*o,g*r*r+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,r=t._w,a=g+g,I=o+o,c=s+s,l=g*a,B=g*I,Q=g*c,h=o*I,d=o*c,p=s*c,y=r*a,m=r*I,D=r*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],Sc.copy(this);const a=1/g,I=1/o,c=1/s;return Sc.elements[0]*=a,Sc.elements[1]*=a,Sc.elements[2]*=a,Sc.elements[4]*=I,Sc.elements[5]*=I,Sc.elements[6]*=I,Sc.elements[8]*=c,Sc.elements[9]*=c,Sc.elements[10]*=c,t.setFromRotationMatrix(Sc),i.x=g,i.y=o,i.z=s,this}makePerspective(A,t,i,n,g,o,s=OI,r=!1){const a=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(r)Q=g/(o-g),h=o*g/(o-g);else if(s===OI)Q=-(o+g)/(o-g),h=-2*o*g/(o-g);else if(s===OS)Q=-o/(o-g),h=-o*g/(o-g);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+s);return a[0]=I,a[4]=0,a[8]=l,a[12]=0,a[1]=0,a[5]=c,a[9]=B,a[13]=0,a[2]=0,a[6]=0,a[10]=Q,a[14]=h,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(A,t,i,n,g,o,s=OI,r=!1){const a=this.elements,I=2/(t-A),c=2/(i-n),l=-(t+A)/(t-A),B=-(i+n)/(i-n);let Q,h;if(r)Q=1/(o-g),h=o/(o-g);else if(s===OI)Q=-2/(o-g),h=-(o+g)/(o-g);else if(s===OS)Q=-1/(o-g),h=-g/(o-g);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+s);return a[0]=I,a[4]=0,a[8]=0,a[12]=l,a[1]=0,a[5]=c,a[9]=0,a[13]=B,a[2]=0,a[6]=0,a[10]=Q,a[14]=h,a[3]=0,a[7]=0,a[11]=0,a[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,Sc=new ii,Pre=new SA(0,0,0),jre=new SA(1,1,1),_Q=new SA,cU=new SA,RI=new SA,xiA=new ii,TiA=new Ao;class or{constructor(A=0,t=0,i=0,n=or.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],r=n[1],a=n[5],I=n[9],c=n[2],l=n[6],B=n[10];switch(t){case"XYZ":this._y=Math.asin(bi(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-I,B),this._z=Math.atan2(-o,g)):(this._x=Math.atan2(l,a),this._z=0);break;case"YXZ":this._x=Math.asin(-bi(I,-1,1)),Math.abs(I)<.9999999?(this._y=Math.atan2(s,B),this._z=Math.atan2(r,a)):(this._y=Math.atan2(-c,g),this._z=0);break;case"ZXY":this._x=Math.asin(bi(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(-c,B),this._z=Math.atan2(-o,a)):(this._y=0,this._z=Math.atan2(r,g));break;case"ZYX":this._y=Math.asin(-bi(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(l,B),this._z=Math.atan2(r,g)):(this._x=0,this._z=Math.atan2(-o,a));break;case"YZX":this._z=Math.asin(bi(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(-I,a),this._y=Math.atan2(-c,g)):(this._x=0,this._y=Math.atan2(s,B));break;case"XZY":this._z=Math.asin(-bi(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(l,a),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 xiA.makeRotationFromQuaternion(A),this.setFromRotationMatrix(xiA,t,i)}setFromVector3(A,t=this._order){return this.set(A.x,A.y,A.z,t)}reorder(A){return TiA.setFromEuler(this),this.setFromQuaternion(TiA,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}}or.DEFAULT_ORDER="XYZ";class jS{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 zre=0;const qiA=new SA,iD=new Ao,$B=new ii,lU=new SA,q0=new SA,Zre=new SA,Wre=new Ao,YiA=new SA(1,0,0),HiA=new SA(0,1,0),OiA=new SA(0,0,1),PiA={type:"added"},Vre={type:"removed"},nD={type:"childadded",child:null},CH={type:"childremoved",child:null};class cn extends UB{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:zre++}),this.uuid=VI(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=cn.DEFAULT_UP.clone();const A=new SA,t=new or,i=new Ao,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 ii},normalMatrix:{value:new $i}}),this.matrix=new ii,this.matrixWorld=new ii,this.matrixAutoUpdate=cn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=cn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new jS,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(YiA,A)}rotateY(A){return this.rotateOnAxis(HiA,A)}rotateZ(A){return this.rotateOnAxis(OiA,A)}translateOnAxis(A,t){return qiA.copy(A).applyQuaternion(this.quaternion),this.position.add(qiA.multiplyScalar(t)),this}translateX(A){return this.translateOnAxis(YiA,A)}translateY(A){return this.translateOnAxis(HiA,A)}translateZ(A){return this.translateOnAxis(OiA,A)}localToWorld(A){return this.updateWorldMatrix(!0,!1),A.applyMatrix4(this.matrixWorld)}worldToLocal(A){return this.updateWorldMatrix(!0,!1),A.applyMatrix4($B.copy(this.matrixWorld).invert())}lookAt(A,t,i){A.isVector3?lU.copy(A):lU.set(A,t,i);const n=this.parent;this.updateWorldMatrix(!0,!1),q0.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?$B.lookAt(q0,lU,this.up):$B.lookAt(lU,q0,this.up),this.quaternion.setFromRotationMatrix($B),n&&($B.extractRotation(n.matrixWorld),iD.setFromRotationMatrix($B),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(PiA),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(Vre),CH.child=A,this.dispatchEvent(CH),CH.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),$B.copy(this.matrixWorld).invert(),A.parent!==null&&(A.parent.updateWorldMatrix(!0,!1),$B.multiply(A.parent.matrixWorld)),A.applyMatrix4($B),A.removeFromParent(),A.parent=this,this.children.push(A),A.updateWorldMatrix(!1,!0),A.dispatchEvent(PiA),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(q0,A,Zre),A}getWorldScale(A){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(q0,Wre,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,r){return s[r.uuid]===void 0&&(s[r.uuid]=r.toJSON(A)),r.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 r=s.shapes;if(Array.isArray(r))for(let a=0,I=r.length;a<I;a++){const c=r[a];g(A.shapes,c)}else g(A.shapes,r)}}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 r=0,a=this.material.length;r<a;r++)s.push(g(A.materials,this.material[r]));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 r=this.animations[s];n.animations.push(g(A.animations,r))}}if(t){const s=o(A.geometries),r=o(A.materials),a=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),r.length>0&&(i.materials=r),a.length>0&&(i.textures=a),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 r=[];for(const a in s){const I=s[a];delete I.metadata,r.push(I)}return r}}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}}cn.DEFAULT_UP=new SA(0,1,0);cn.DEFAULT_MATRIX_AUTO_UPDATE=!0;cn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const wc=new SA,AE=new SA,cH=new SA,eE=new SA,gD=new SA,oD=new SA,jiA=new SA,lH=new SA,BH=new SA,EH=new SA,QH=new $n,uH=new $n,dH=new $n;class $a{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),wc.subVectors(A,t),n.cross(wc);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){wc.subVectors(n,t),AE.subVectors(i,t),cH.subVectors(A,t);const o=wc.dot(wc),s=wc.dot(AE),r=wc.dot(cH),a=AE.dot(AE),I=AE.dot(cH),c=o*a-s*s;if(c===0)return g.set(0,0,0),null;const l=1/c,B=(a*r-s*I)*l,Q=(o*I-s*r)*l;return g.set(1-B-Q,Q,B)}static containsPoint(A,t,i,n){return this.getBarycoord(A,t,i,n,eE)===null?!1:eE.x>=0&&eE.y>=0&&eE.x+eE.y<=1}static getInterpolation(A,t,i,n,g,o,s,r){return this.getBarycoord(A,t,i,n,eE)===null?(r.x=0,r.y=0,"z"in r&&(r.z=0),"w"in r&&(r.w=0),null):(r.setScalar(0),r.addScaledVector(g,eE.x),r.addScaledVector(o,eE.y),r.addScaledVector(s,eE.z),r)}static getInterpolatedAttribute(A,t,i,n,g,o){return QH.setScalar(0),uH.setScalar(0),dH.setScalar(0),QH.fromBufferAttribute(A,t),uH.fromBufferAttribute(A,i),dH.fromBufferAttribute(A,n),o.setScalar(0),o.addScaledVector(QH,g.x),o.addScaledVector(uH,g.y),o.addScaledVector(dH,g.z),o}static isFrontFacing(A,t,i,n){return wc.subVectors(i,t),AE.subVectors(A,t),wc.cross(AE).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 wc.subVectors(this.c,this.b),AE.subVectors(this.a,this.b),wc.cross(AE).length()*.5}getMidpoint(A){return A.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(A){return $a.getNormal(this.a,this.b,this.c,A)}getPlane(A){return A.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(A,t){return $a.getBarycoord(A,this.a,this.b,this.c,t)}getInterpolation(A,t,i,n,g){return $a.getInterpolation(A,this.a,this.b,this.c,t,i,n,g)}containsPoint(A){return $a.containsPoint(A,this.a,this.b,this.c)}isFrontFacing(A){return $a.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),lH.subVectors(A,i);const r=gD.dot(lH),a=oD.dot(lH);if(r<=0&&a<=0)return t.copy(i);BH.subVectors(A,n);const I=gD.dot(BH),c=oD.dot(BH);if(I>=0&&c<=I)return t.copy(n);const l=r*c-I*a;if(l<=0&&r>=0&&I<=0)return o=r/(r-I),t.copy(i).addScaledVector(gD,o);EH.subVectors(A,g);const B=gD.dot(EH),Q=oD.dot(EH);if(Q>=0&&B<=Q)return t.copy(g);const h=B*a-r*Q;if(h<=0&&a>=0&&Q<=0)return s=a/(a-Q),t.copy(i).addScaledVector(oD,s);const d=I*Q-B*c;if(d<=0&&c-I>=0&&B-Q>=0)return jiA.subVectors(g,n),s=(c-I)/(c-I+(B-Q)),t.copy(n).addScaledVector(jiA,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 IyA={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},JQ={h:0,s:0,l:0},BU={h:0,s:0,l:0};function hH(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 lt{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=sn){return A=Math.floor(A),this.r=(A>>16&255)/255,this.g=(A>>8&255)/255,this.b=(A&255)/255,Rn.colorSpaceToWorking(this,t),this}setRGB(A,t,i,n=Rn.workingColorSpace){return this.r=A,this.g=t,this.b=i,Rn.colorSpaceToWorking(this,n),this}setHSL(A,t,i,n=Rn.workingColorSpace){if(A=xW(A,1),t=bi(t,0,1),i=bi(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=hH(o,g,A+1/3),this.g=hH(o,g,A),this.b=hH(o,g,A-1/3)}return Rn.colorSpaceToWorking(this,n),this}setStyle(A,t=sn){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=sn){const i=IyA[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=TE(A.r),this.g=TE(A.g),this.b=TE(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=sn){return Rn.workingToColorSpace(xr.copy(this),A),Math.round(bi(xr.r*255,0,255))*65536+Math.round(bi(xr.g*255,0,255))*256+Math.round(bi(xr.b*255,0,255))}getHexString(A=sn){return("000000"+this.getHex(A).toString(16)).slice(-6)}getHSL(A,t=Rn.workingColorSpace){Rn.workingToColorSpace(xr.copy(this),t);const i=xr.r,n=xr.g,g=xr.b,o=Math.max(i,n,g),s=Math.min(i,n,g);let r,a;const I=(s+o)/2;if(s===o)r=0,a=0;else{const c=o-s;switch(a=I<=.5?c/(o+s):c/(2-o-s),o){case i:r=(n-g)/c+(n<g?6:0);break;case n:r=(g-i)/c+2;break;case g:r=(i-n)/c+4;break}r/=6}return A.h=r,A.s=a,A.l=I,A}getRGB(A,t=Rn.workingColorSpace){return Rn.workingToColorSpace(xr.copy(this),t),A.r=xr.r,A.g=xr.g,A.b=xr.b,A}getStyle(A=sn){Rn.workingToColorSpace(xr.copy(this),A);const t=xr.r,i=xr.g,n=xr.b;return A!==sn?`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(JQ),this.setHSL(JQ.h+A,JQ.s+t,JQ.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(JQ),A.getHSL(BU);const i=NM(JQ.h,BU.h,t),n=NM(JQ.s,BU.s,t),g=NM(JQ.l,BU.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 xr=new lt;lt.NAMES=IyA;let Xre=0;class co extends UB{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Xre++}),this.uuid=VI(),this.name="",this.type="Material",this.blending=Yp,this.side=Al,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=F_,this.blendDst=__,this.blendEquation=au,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new lt(0,0,0),this.blendAlpha=0,this.depthFunc=pf,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=r4,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!==Al&&(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!==F_&&(i.blendSrc=this.blendSrc),this.blendDst!==__&&(i.blendDst=this.blendDst),this.blendEquation!==au&&(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!==r4&&(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 r=g[s];delete r.metadata,o.push(r)}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 yg extends co{constructor(A){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new lt(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 or,this.combine=gG,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 DE=$re();function $re(){const e=new ArrayBuffer(4),A=new Float32Array(e),t=new Uint32Array(e),i=new Uint32Array(512),n=new Uint32Array(512);for(let r=0;r<256;++r){const a=r-127;a<-27?(i[r]=0,i[r|256]=32768,n[r]=24,n[r|256]=24):a<-14?(i[r]=1024>>-a-14,i[r|256]=1024>>-a-14|32768,n[r]=-a-1,n[r|256]=-a-1):a<=15?(i[r]=a+15<<10,i[r|256]=a+15<<10|32768,n[r]=13,n[r|256]=13):a<128?(i[r]=31744,i[r|256]=64512,n[r]=24,n[r|256]=24):(i[r]=31744,i[r|256]=64512,n[r]=13,n[r|256]=13)}const g=new Uint32Array(2048),o=new Uint32Array(64),s=new Uint32Array(64);for(let r=1;r<1024;++r){let a=r<<13,I=0;for(;!(a&8388608);)a<<=1,I-=8388608;a&=-8388609,I+=947912704,g[r]=a|I}for(let r=1024;r<2048;++r)g[r]=939524096+(r-1024<<13);for(let r=1;r<31;++r)o[r]=r<<23;o[31]=1199570944,o[32]=2147483648;for(let r=33;r<63;++r)o[r]=2147483648+(r-32<<23);o[63]=3347054592;for(let r=1;r<64;++r)r!==32&&(s[r]=1024);return{floatView:A,uint32View:t,baseTable:i,shiftTable:n,mantissaTable:g,exponentTable:o,offsetTable:s}}function Pa(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=bi(e,-65504,65504),DE.floatView[0]=e;const A=DE.uint32View[0],t=A>>23&511;return DE.baseTable[t]+((A&8388607)>>DE.shiftTable[t])}function Gk(e){const A=e>>10;return DE.uint32View[0]=DE.mantissaTable[DE.offsetTable[A]+(e&1023)]+DE.exponentTable[A],DE.floatView[0]}class Aae{static toHalfFloat(A){return Pa(A)}static fromHalfFloat(A){return Gk(A)}}const os=new SA,EU=new It;let eae=0;class Yi{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:eae++}),this.name="",this.array=A,this.itemSize=t,this.count=A!==void 0?A.length/t:0,this.normalized=i,this.usage=KN,this.updateRanges=[],this.gpuType=Ga,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++)EU.fromBufferAttribute(this,t),EU.applyMatrix3(A),this.setXY(t,EU.x,EU.y);else if(this.itemSize===3)for(let t=0,i=this.count;t<i;t++)os.fromBufferAttribute(this,t),os.applyMatrix3(A),this.setXYZ(t,os.x,os.y,os.z);return this}applyMatrix4(A){for(let t=0,i=this.count;t<i;t++)os.fromBufferAttribute(this,t),os.applyMatrix4(A),this.setXYZ(t,os.x,os.y,os.z);return this}applyNormalMatrix(A){for(let t=0,i=this.count;t<i;t++)os.fromBufferAttribute(this,t),os.applyNormalMatrix(A),this.setXYZ(t,os.x,os.y,os.z);return this}transformDirection(A){for(let t=0,i=this.count;t<i;t++)os.fromBufferAttribute(this,t),os.transformDirection(A),this.setXYZ(t,os.x,os.y,os.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=Sa(i,this.array)),i}setComponent(A,t,i){return this.normalized&&(i=on(i,this.array)),this.array[A*this.itemSize+t]=i,this}getX(A){let t=this.array[A*this.itemSize];return this.normalized&&(t=Sa(t,this.array)),t}setX(A,t){return this.normalized&&(t=on(t,this.array)),this.array[A*this.itemSize]=t,this}getY(A){let t=this.array[A*this.itemSize+1];return this.normalized&&(t=Sa(t,this.array)),t}setY(A,t){return this.normalized&&(t=on(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=Sa(t,this.array)),t}setZ(A,t){return this.normalized&&(t=on(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=Sa(t,this.array)),t}setW(A,t){return this.normalized&&(t=on(t,this.array)),this.array[A*this.itemSize+3]=t,this}setXY(A,t,i){return A*=this.itemSize,this.normalized&&(t=on(t,this.array),i=on(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=on(t,this.array),i=on(i,this.array),n=on(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=on(t,this.array),i=on(i,this.array),n=on(n,this.array),g=on(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!==KN&&(A.usage=this.usage),A}}class tae extends Yi{constructor(A,t,i){super(new Int8Array(A),t,i)}}class iae extends Yi{constructor(A,t,i){super(new Uint8Array(A),t,i)}}class nae extends Yi{constructor(A,t,i){super(new Uint8ClampedArray(A),t,i)}}class gae extends Yi{constructor(A,t,i){super(new Int16Array(A),t,i)}}class qW extends Yi{constructor(A,t,i){super(new Uint16Array(A),t,i)}}class oae extends Yi{constructor(A,t,i){super(new Int32Array(A),t,i)}}class YW extends Yi{constructor(A,t,i){super(new Uint32Array(A),t,i)}}class sae extends Yi{constructor(A,t,i){super(new Uint16Array(A),t,i),this.isFloat16BufferAttribute=!0}getX(A){let t=Gk(this.array[A*this.itemSize]);return this.normalized&&(t=Sa(t,this.array)),t}setX(A,t){return this.normalized&&(t=on(t,this.array)),this.array[A*this.itemSize]=Pa(t),this}getY(A){let t=Gk(this.array[A*this.itemSize+1]);return this.normalized&&(t=Sa(t,this.array)),t}setY(A,t){return this.normalized&&(t=on(t,this.array)),this.array[A*this.itemSize+1]=Pa(t),this}getZ(A){let t=Gk(this.array[A*this.itemSize+2]);return this.normalized&&(t=Sa(t,this.array)),t}setZ(A,t){return this.normalized&&(t=on(t,this.array)),this.array[A*this.itemSize+2]=Pa(t),this}getW(A){let t=Gk(this.array[A*this.itemSize+3]);return this.normalized&&(t=Sa(t,this.array)),t}setW(A,t){return this.normalized&&(t=on(t,this.array)),this.array[A*this.itemSize+3]=Pa(t),this}setXY(A,t,i){return A*=this.itemSize,this.normalized&&(t=on(t,this.array),i=on(i,this.array)),this.array[A+0]=Pa(t),this.array[A+1]=Pa(i),this}setXYZ(A,t,i,n){return A*=this.itemSize,this.normalized&&(t=on(t,this.array),i=on(i,this.array),n=on(n,this.array)),this.array[A+0]=Pa(t),this.array[A+1]=Pa(i),this.array[A+2]=Pa(n),this}setXYZW(A,t,i,n,g){return A*=this.itemSize,this.normalized&&(t=on(t,this.array),i=on(i,this.array),n=on(n,this.array),g=on(g,this.array)),this.array[A+0]=Pa(t),this.array[A+1]=Pa(i),this.array[A+2]=Pa(n),this.array[A+3]=Pa(g),this}}class Vt extends Yi{constructor(A,t,i){super(new Float32Array(A),t,i)}}let rae=0;const fC=new ii,pH=new cn,sD=new SA,GI=new Vn,Y0=new Vn,Os=new SA;class ki extends UB{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:rae++}),this.uuid=VI(),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(syA(A)?YW:qW)(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 $i().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 fC.makeRotationFromQuaternion(A),this.applyMatrix4(fC),this}rotateX(A){return fC.makeRotationX(A),this.applyMatrix4(fC),this}rotateY(A){return fC.makeRotationY(A),this.applyMatrix4(fC),this}rotateZ(A){return fC.makeRotationZ(A),this.applyMatrix4(fC),this}translate(A,t,i){return fC.makeTranslation(A,t,i),this.applyMatrix4(fC),this}scale(A,t,i){return fC.makeScale(A,t,i),this.applyMatrix4(fC),this}lookAt(A){return pH.lookAt(A),pH.updateMatrix(),this.applyMatrix4(pH.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 Vt(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 Vn);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];GI.setFromBufferAttribute(g),this.morphTargetsRelative?(Os.addVectors(this.boundingBox.min,GI.min),this.boundingBox.expandByPoint(Os),Os.addVectors(this.boundingBox.max,GI.max),this.boundingBox.expandByPoint(Os)):(this.boundingBox.expandByPoint(GI.min),this.boundingBox.expandByPoint(GI.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 vs);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(GI.setFromBufferAttribute(A),t)for(let g=0,o=t.length;g<o;g++){const s=t[g];Y0.setFromBufferAttribute(s),this.morphTargetsRelative?(Os.addVectors(GI.min,Y0.min),GI.expandByPoint(Os),Os.addVectors(GI.max,Y0.max),GI.expandByPoint(Os)):(GI.expandByPoint(Y0.min),GI.expandByPoint(Y0.max))}GI.getCenter(i);let n=0;for(let g=0,o=A.count;g<o;g++)Os.fromBufferAttribute(A,g),n=Math.max(n,i.distanceToSquared(Os));if(t)for(let g=0,o=t.length;g<o;g++){const s=t[g],r=this.morphTargetsRelative;for(let a=0,I=s.count;a<I;a++)Os.fromBufferAttribute(s,a),r&&(sD.fromBufferAttribute(A,a),Os.add(sD)),n=Math.max(n,i.distanceToSquared(Os))}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 Yi(new Float32Array(4*i.count),4));const o=this.getAttribute("tangent"),s=[],r=[];for(let G=0;G<i.count;G++)s[G]=new SA,r[G]=new SA;const a=new SA,I=new SA,c=new SA,l=new It,B=new It,Q=new It,h=new SA,d=new SA;function p(G,M,w){a.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(a),c.sub(a),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),r[G].add(d),r[M].add(d),r[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(r[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 Yi(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,r=new SA,a=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),r.fromBufferAttribute(i,h),a.fromBufferAttribute(i,d),s.add(I),r.add(I),a.add(I),i.setXYZ(Q,s.x,s.y,s.z),i.setXYZ(h,r.x,r.y,r.z),i.setXYZ(d,a.x,a.y,a.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++)Os.fromBufferAttribute(A,t),Os.normalize(),A.setXYZ(t,Os.x,Os.y,Os.z)}toNonIndexed(){function A(s,r){const a=s.array,I=s.itemSize,c=s.normalized,l=new a.constructor(r.length*I);let B=0,Q=0;for(let h=0,d=r.length;h<d;h++){s.isInterleavedBufferAttribute?B=r[h]*s.data.stride+s.offset:B=r[h]*I;for(let p=0;p<I;p++)l[Q++]=a[B++]}return new Yi(l,I,c)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ki,i=this.index.array,n=this.attributes;for(const s in n){const r=n[s],a=A(r,i);t.setAttribute(s,a)}const g=this.morphAttributes;for(const s in g){const r=[],a=g[s];for(let I=0,c=a.length;I<c;I++){const l=a[I],B=A(l,i);r.push(B)}t.morphAttributes[s]=r}t.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let s=0,r=o.length;s<r;s++){const a=o[s];t.addGroup(a.start,a.count,a.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 r=this.parameters;for(const a in r)r[a]!==void 0&&(A[a]=r[a]);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 r in i){const a=i[r];A.data.attributes[r]=a.toJSON(A.data)}const n={};let g=!1;for(const r in this.morphAttributes){const a=this.morphAttributes[r],I=[];for(let c=0,l=a.length;c<l;c++){const B=a[c];I.push(B.toJSON(A.data))}I.length>0&&(n[r]=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 a in n){const I=n[a];this.setAttribute(a,I.clone(t))}const g=A.morphAttributes;for(const a in g){const I=[],c=g[a];for(let l=0,B=c.length;l<B;l++)I.push(c[l].clone(t));this.morphAttributes[a]=I}this.morphTargetsRelative=A.morphTargetsRelative;const o=A.groups;for(let a=0,I=o.length;a<I;a++){const c=o[a];this.addGroup(c.start,c.count,c.materialIndex)}const s=A.boundingBox;s!==null&&(this.boundingBox=s.clone());const r=A.boundingSphere;return r!==null&&(this.boundingSphere=r.clone()),this.drawRange.start=A.drawRange.start,this.drawRange.count=A.drawRange.count,this.userData=A.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const ziA=new ii,fh=new Jw,QU=new vs,ZiA=new SA,uU=new SA,dU=new SA,hU=new SA,fH=new SA,pU=new SA,WiA=new SA,fU=new SA;class hn extends cn{constructor(A=new ki,t=new yg){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){pU.set(0,0,0);for(let r=0,a=g.length;r<a;r++){const I=s[r],c=g[r];I!==0&&(fH.fromBufferAttribute(c,A),o?pU.addScaledVector(fH,I):pU.addScaledVector(fH.sub(t),I))}t.add(pU)}return t}raycast(A,t){const i=this.geometry,n=this.material,g=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),QU.copy(i.boundingSphere),QU.applyMatrix4(g),fh.copy(A.ray).recast(A.near),!(QU.containsPoint(fh.origin)===!1&&(fh.intersectSphere(QU,ZiA)===null||fh.origin.distanceToSquared(ZiA)>(A.far-A.near)**2))&&(ziA.copy(g).invert(),fh.copy(A.ray).applyMatrix4(ziA),!(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,r=g.attributes.position,a=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=yU(this,p,A,i,a,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=yU(this,o,A,i,a,I,c,y,m,D),n&&(n.faceIndex=Math.floor(d/3),t.push(n))}}else if(r!==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(r.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=yU(this,p,A,i,a,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(r.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=yU(this,o,A,i,a,I,c,y,m,D),n&&(n.faceIndex=Math.floor(d/3),t.push(n))}}}}function aae(e,A,t,i,n,g,o,s){let r;if(A.side===kr?r=i.intersectTriangle(o,g,n,!0,s):r=i.intersectTriangle(n,g,o,A.side===Al,s),r===null)return null;fU.copy(s),fU.applyMatrix4(e.matrixWorld);const a=t.ray.origin.distanceTo(fU);return a<t.near||a>t.far?null:{distance:a,point:fU.clone(),object:e}}function yU(e,A,t,i,n,g,o,s,r,a){e.getVertexPosition(s,uU),e.getVertexPosition(r,dU),e.getVertexPosition(a,hU);const I=aae(e,A,t,i,uU,dU,hU,WiA);if(I){const c=new SA;$a.getBarycoord(WiA,uU,dU,hU,c),n&&(I.uv=$a.getInterpolatedAttribute(n,s,r,a,c,new It)),g&&(I.uv1=$a.getInterpolatedAttribute(g,s,r,a,c,new It)),o&&(I.normal=$a.getInterpolatedAttribute(o,s,r,a,c,new SA),I.normal.dot(i.direction)>0&&I.normal.multiplyScalar(-1));const l={a:s,b:r,c:a,normal:new SA,materialIndex:0};$a.getNormal(uU,dU,hU,l.normal),I.face=l,I.barycoord=c}return I}class gI extends ki{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 r=[],a=[],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(r),this.setAttribute("position",new Vt(a,3)),this.setAttribute("normal",new Vt(I,3)),this.setAttribute("uv",new Vt(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,T=N+1,v=G+1;let U=0,x=0;const q=new SA;for(let z=0;z<v;z++){const Z=z*b-K;for(let eA=0;eA<T;eA++){const aA=eA*w-_;q[h]=aA*y,q[d]=Z*m,q[p]=J,a.push(q.x,q.y,q.z),q[h]=0,q[d]=0,q[p]=k>0?1:-1,I.push(q.x,q.y,q.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+T*z,aA=l+Z+T*(z+1),sA=l+(Z+1)+T*(z+1),pA=l+(Z+1)+T*z;r.push(eA,aA,pA),r.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 gI(A.width,A.height,A.depth,A.widthSegments,A.heightSegments,A.depthSegments)}}function zS(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 Ba(e){const A={};for(let t=0;t<e.length;t++){const i=zS(e[t]);for(const n in i)A[n]=i[n]}return A}function Iae(e){const A=[];for(let t=0;t<e.length;t++)A.push(e[t].clone());return A}function CyA(e){const A=e.getRenderTarget();return A===null?e.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Rn.workingColorSpace}const HW={clone:zS,merge:Ba};var Cae=`void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,cae=`void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;class rc extends co{constructor(A){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Cae,this.fragmentShader=cae,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=zS(A.uniforms),this.uniformsGroups=Iae(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 Px extends cn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ii,this.projectionMatrix=new ii,this.projectionMatrixInverse=new ii,this.coordinateSystem=OI,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 LQ=new SA,ViA=new It,XiA=new It;class zo extends Px{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=PS*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const A=Math.tan(Op*.5*this.fov);return .5*this.getFilmHeight()/A}getEffectiveFOV(){return PS*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){LQ.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(LQ.x,LQ.y).multiplyScalar(-A/LQ.z),LQ.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(LQ.x,LQ.y).multiplyScalar(-A/LQ.z)}getViewSize(A,t){return this.getViewBounds(A,ViA,XiA),t.subVectors(XiA,ViA)}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 r=o.fullWidth,a=o.fullHeight;g+=o.offsetX*n/r,t-=o.offsetY*i/a,n*=o.width/r,i*=o.height/a}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 rD=-90,aD=1;class cyA extends cn{constructor(A,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new zo(rD,aD,A,t);n.layers=this.layers,this.add(n);const g=new zo(rD,aD,A,t);g.layers=this.layers,this.add(g);const o=new zo(rD,aD,A,t);o.layers=this.layers,this.add(o);const s=new zo(rD,aD,A,t);s.layers=this.layers,this.add(s);const r=new zo(rD,aD,A,t);r.layers=this.layers,this.add(r);const a=new zo(rD,aD,A,t);a.layers=this.layers,this.add(a)}updateCoordinateSystem(){const A=this.coordinateSystem,t=this.children.concat(),[i,n,g,o,s,r]=t;for(const a of t)this.remove(a);if(A===OI)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),r.up.set(0,1,0),r.lookAt(0,0,-1);else if(A===OS)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),r.up.set(0,-1,0),r.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+A);for(const a of t)this.add(a),a.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,r,a,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,r),A.setRenderTarget(i,4,n),A.render(t,a),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 aG extends Rg{constructor(A=[],t=rQ,i,n,g,o,s,r,a,I){super(A,t,i,n,g,o,s,r,a,I),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(A){this.image=A}}class lyA extends el{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 aG(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 gI(5,5,5),g=new rc({name:"CubemapFromEquirect",uniforms:zS(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:kr,blending:xE});g.uniforms.tEquirect.value=t;const o=new hn(n,g),s=t.minFilter;return t.minFilter===Ra&&(t.minFilter=_g),new cyA(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 er extends cn{constructor(){super(),this.isGroup=!0,this.type="Group"}}const lae={type:"move"};class KK{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new er,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 er,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 er,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,r=this._grip,a=this._hand;if(A&&t.session.visibilityState!=="visible-blurred"){if(a&&A.hand){o=!0;for(const h of A.hand.values()){const d=t.getJointPose(h,i),p=this._getHandJoint(a,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=a.joints["index-finger-tip"],c=a.joints["thumb-tip"],l=I.position.distanceTo(c.position),B=.02,Q=.005;a.inputState.pinching&&l>B+Q?(a.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:A.handedness,target:this})):!a.inputState.pinching&&l<=B-Q&&(a.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:A.handedness,target:this}))}else r!==null&&A.gripSpace&&(g=t.getPose(A.gripSpace,i),g!==null&&(r.matrix.fromArray(g.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,g.linearVelocity?(r.hasLinearVelocity=!0,r.linearVelocity.copy(g.linearVelocity)):r.hasLinearVelocity=!1,g.angularVelocity?(r.hasAngularVelocity=!0,r.angularVelocity.copy(g.angularVelocity)):r.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(lae)))}return s!==null&&(s.visible=n!==null),r!==null&&(r.visible=g!==null),a!==null&&(a.visible=o!==null),this}_getHandJoint(A,t){if(A.joints[t.jointName]===void 0){const i=new er;i.matrixAutoUpdate=!1,i.visible=!1,A.joints[t.jointName]=i,A.add(i)}return A.joints[t.jointName]}}class jx{constructor(A,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new lt(A),this.density=t}clone(){return new jx(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class IG{constructor(A,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new lt(A),this.near=t,this.far=i}clone(){return new IG(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}let CG=class extends cn{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 or,this.environmentIntensity=1,this.environmentRotation=new or,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 Lw{constructor(A,t){this.isInterleavedBuffer=!0,this.array=A,this.stride=t,this.count=A!==void 0?A.length/t:0,this.usage=KN,this.updateRanges=[],this.version=0,this.uuid=VI()}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=VI()),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=VI()),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 la=new SA;class IQ{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++)la.fromBufferAttribute(this,t),la.applyMatrix4(A),this.setXYZ(t,la.x,la.y,la.z);return this}applyNormalMatrix(A){for(let t=0,i=this.count;t<i;t++)la.fromBufferAttribute(this,t),la.applyNormalMatrix(A),this.setXYZ(t,la.x,la.y,la.z);return this}transformDirection(A){for(let t=0,i=this.count;t<i;t++)la.fromBufferAttribute(this,t),la.transformDirection(A),this.setXYZ(t,la.x,la.y,la.z);return this}getComponent(A,t){let i=this.array[A*this.data.stride+this.offset+t];return this.normalized&&(i=Sa(i,this.array)),i}setComponent(A,t,i){return this.normalized&&(i=on(i,this.array)),this.data.array[A*this.data.stride+this.offset+t]=i,this}setX(A,t){return this.normalized&&(t=on(t,this.array)),this.data.array[A*this.data.stride+this.offset]=t,this}setY(A,t){return this.normalized&&(t=on(t,this.array)),this.data.array[A*this.data.stride+this.offset+1]=t,this}setZ(A,t){return this.normalized&&(t=on(t,this.array)),this.data.array[A*this.data.stride+this.offset+2]=t,this}setW(A,t){return this.normalized&&(t=on(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=Sa(t,this.array)),t}getY(A){let t=this.data.array[A*this.data.stride+this.offset+1];return this.normalized&&(t=Sa(t,this.array)),t}getZ(A){let t=this.data.array[A*this.data.stride+this.offset+2];return this.normalized&&(t=Sa(t,this.array)),t}getW(A){let t=this.data.array[A*this.data.stride+this.offset+3];return this.normalized&&(t=Sa(t,this.array)),t}setXY(A,t,i){return A=A*this.data.stride+this.offset,this.normalized&&(t=on(t,this.array),i=on(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=on(t,this.array),i=on(i,this.array),n=on(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=on(t,this.array),i=on(i,this.array),n=on(n,this.array),g=on(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 Yi(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 IQ(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 JN extends co{constructor(A){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new lt(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 H0=new SA,CD=new SA,cD=new SA,lD=new It,O0=new It,ByA=new ii,DU=new SA,P0=new SA,mU=new SA,$iA=new It,yH=new It,AnA=new It;class pJ extends cn{constructor(A=new JN){if(super(),this.isSprite=!0,this.type="Sprite",ID===void 0){ID=new ki;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 Lw(t,5);ID.setIndex([0,1,2,0,2,3]),ID.setAttribute("position",new IQ(i,3,0,!1)),ID.setAttribute("uv",new IQ(i,2,3,!1))}this.geometry=ID,this.material=A,this.center=new It(.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),ByA.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;SU(DU.set(-.5,-.5,0),cD,o,CD,n,g),SU(P0.set(.5,-.5,0),cD,o,CD,n,g),SU(mU.set(.5,.5,0),cD,o,CD,n,g),$iA.set(0,0),yH.set(1,0),AnA.set(1,1);let s=A.ray.intersectTriangle(DU,P0,mU,!1,H0);if(s===null&&(SU(P0.set(-.5,.5,0),cD,o,CD,n,g),yH.set(0,1),s=A.ray.intersectTriangle(DU,mU,P0,!1,H0),s===null))return;const r=A.ray.origin.distanceTo(H0);r<A.near||r>A.far||t.push({distance:r,point:H0.clone(),uv:$a.getInterpolation(H0,DU,P0,mU,$iA,yH,AnA,new It),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 SU(e,A,t,i,n,g){lD.subVectors(e,t).addScalar(.5).multiply(i),n!==void 0?(O0.x=g*lD.x-n*lD.y,O0.y=n*lD.x+g*lD.y):O0.copy(lD),e.copy(A),e.x+=O0.x,e.y+=O0.y,e.applyMatrix4(ByA)}const wU=new SA,enA=new SA;class EyA extends cn{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){wU.setFromMatrixPosition(this.matrixWorld);const n=A.ray.origin.distanceTo(wU);this.getObjectForDistance(n).raycast(A,t)}}update(A){const t=this.levels;if(t.length>1){wU.setFromMatrixPosition(A.matrixWorld),enA.setFromMatrixPosition(this.matrixWorld);const i=wU.distanceTo(enA)/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 tnA=new SA,inA=new $n,nnA=new $n,Bae=new SA,gnA=new ii,kU=new SA,DH=new vs,onA=new ii,mH=new Jw;class zx extends hn{constructor(A,t){super(A,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=s4,this.bindMatrix=new ii,this.bindMatrixInverse=new ii,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const A=this.geometry;this.boundingBox===null&&(this.boundingBox=new Vn),this.boundingBox.makeEmpty();const t=A.getAttribute("position");for(let i=0;i<t.count;i++)this.getVertexPosition(i,kU),this.boundingBox.expandByPoint(kU)}computeBoundingSphere(){const A=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new vs),this.boundingSphere.makeEmpty();const t=A.getAttribute("position");for(let i=0;i<t.count;i++)this.getVertexPosition(i,kU),this.boundingSphere.expandByPoint(kU)}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(),DH.copy(this.boundingSphere),DH.applyMatrix4(n),A.ray.intersectsSphere(DH)!==!1&&(onA.copy(n).invert(),mH.copy(A.ray).applyMatrix4(onA),!(this.boundingBox!==null&&mH.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(A,t,mH)))}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 $n,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===s4?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===zfA?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(A,t){const i=this.skeleton,n=this.geometry;inA.fromBufferAttribute(n.attributes.skinIndex,A),nnA.fromBufferAttribute(n.attributes.skinWeight,A),tnA.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let g=0;g<4;g++){const o=nnA.getComponent(g);if(o!==0){const s=inA.getComponent(g);gnA.multiplyMatrices(i.bones[s].matrixWorld,i.boneInverses[s]),t.addScaledVector(Bae.copy(tnA).applyMatrix4(gnA),o)}}return t.applyMatrix4(this.bindMatrixInverse)}}class cG extends cn{constructor(){super(),this.isBone=!0,this.type="Bone"}}class dB extends Rg{constructor(A=null,t=1,i=1,n,g,o,s,r,a=Ds,I=Ds,c,l){super(null,o,s,r,a,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 snA=new ii,Eae=new ii;class xw{constructor(A=[],t=[]){this.uuid=VI(),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 ii)}}calculateInverses(){this.boneInverses.length=0;for(let A=0,t=this.bones.length;A<t;A++){const i=new ii;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:Eae;snA.multiplyMatrices(s,t[g]),snA.toArray(i,g*16)}n!==null&&(n.needsUpdate=!0)}clone(){return new xw(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 dB(t,A,A,jr,Ga);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 cG),this.bones.push(o),this.boneInverses.push(new ii().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 Yi{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 ii,rnA=new ii,MU=[],anA=new Vn,Qae=new ii,j0=new hn,z0=new vs;class lG extends hn{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,Qae)}computeBoundingBox(){const A=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Vn),A.boundingBox===null&&A.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,BD),anA.copy(A.boundingBox).applyMatrix4(BD),this.boundingBox.union(anA)}computeBoundingSphere(){const A=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new vs),A.boundingSphere===null&&A.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,BD),z0.copy(A.boundingSphere).applyMatrix4(BD),this.boundingSphere.union(z0)}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(j0.geometry=this.geometry,j0.material=this.material,j0.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),z0.copy(this.boundingSphere),z0.applyMatrix4(i),A.ray.intersectsSphere(z0)!==!1))for(let g=0;g<n;g++){this.getMatrixAt(g,BD),rnA.multiplyMatrices(i,BD),j0.matrixWorld=rnA,j0.raycast(A,MU);for(let o=0,s=MU.length;o<s;o++){const r=MU[o];r.instanceId=g,r.object=this,t.push(r)}MU.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 dB(new Float32Array(n*this.count),n,this.count,xx,Ga));const g=this.morphTexture.source.data.data;let o=0;for(let a=0;a<i.length;a++)o+=i[a];const s=this.geometry.morphTargetsRelative?1:1-o,r=n*A;g[r]=s,g.set(i,r+1)}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}}const SH=new SA,uae=new SA,dae=new $i;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=SH.subVectors(i,t).cross(uae.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(SH),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||dae.getNormalMatrix(A),n=this.coplanarPoint(SH).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 vs,hae=new It(.5,.5),NU=new SA;class Tw{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=OI,i=!1){const n=this.planes,g=A.elements,o=g[0],s=g[1],r=g[2],a=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(a-o,B-I,p-Q,S-y).normalize(),n[1].setComponents(a+o,B+I,p+Q,S+y).normalize(),n[2].setComponents(a+s,B+c,p+h,S+m).normalize(),n[3].setComponents(a-s,B-c,p-h,S-m).normalize(),i)n[4].setComponents(r,l,d,D).normalize(),n[5].setComponents(a-r,B-l,p-d,S-D).normalize();else if(n[4].setComponents(a-r,B-l,p-d,S-D).normalize(),t===OI)n[5].setComponents(a+r,B+l,p+d,S+D).normalize();else if(t===OS)n[5].setComponents(r,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=hae.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(NU.x=n.normal.x>0?A.max.x:A.min.x,NU.y=n.normal.y>0?A.max.y:A.min.y,NU.z=n.normal.z>0?A.max.z:A.min.z,n.distanceToPoint(NU)<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 Ul=new ii,vl=new Tw;class Zx{constructor(){this.coordinateSystem=OI}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(Ul.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),vl.setFromProjectionMatrix(Ul,n.coordinateSystem,n.reversedDepth),vl.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(Ul.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),vl.setFromProjectionMatrix(Ul,n.coordinateSystem,n.reversedDepth),vl.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(Ul.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),vl.setFromProjectionMatrix(Ul,n.coordinateSystem,n.reversedDepth),vl.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(Ul.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),vl.setFromProjectionMatrix(Ul,n.coordinateSystem,n.reversedDepth),vl.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(Ul.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),vl.setFromProjectionMatrix(Ul,n.coordinateSystem,n.reversedDepth),vl.containsPoint(A))return!0}return!1}clone(){return new Zx}}function wH(e,A){return e-A}function pae(e,A){return e.z-A.z}function fae(e,A){return A.z-e.z}class yae{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 Ya=new ii,Dae=new lt(1,1,1),InA=new Tw,mae=new Zx,RU=new Vn,Dh=new vs,Z0=new SA,CnA=new SA,Sae=new SA,kH=new yae,Tr=new hn,GU=[];function wae(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 QyA extends hn{constructor(A,t,i=t*2,n){super(new ki,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 dB(t,A,A,jr,Ga);this._matricesTexture=i}_initIndirectTexture(){let A=Math.sqrt(this._maxInstanceCount);A=Math.ceil(A);const t=new Uint32Array(A*A),i=new dB(t,A,A,sG,aQ);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 dB(t,A,A,jr,Ga);i.colorSpace=Rn.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:r,normalized:a}=o,I=new s.constructor(i*r),c=new Yi(I,r,a);t.setAttribute(g,c)}if(A.getIndex()!==null){const g=i>65535?new Uint32Array(n):new Uint16Array(n);t.setIndex(new Yi(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 Vn);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,Ya),this.getBoundingBoxAt(g,RU).applyMatrix4(Ya),A.union(RU)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new vs);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,Ya),this.getBoundingSphereAt(g,Dh).applyMatrix4(Ya),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(wH),n=this._availableInstanceIds.shift(),this._instanceInfo[n]=i):(n=this._instanceInfo.length,this._instanceInfo.push(i));const g=this._matricesTexture;Ya.identity().toArray(g.image.data,n*16),g.needsUpdate=!0;const o=this._colorsTexture;return o&&(Dae.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 r;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(wH),r=this._availableGeometryIds.shift(),g[r]=n):(r=this._geometryCount,this._geometryCount++,g.push(n)),this.setGeometryAt(r,A),this._nextIndexStart=n.indexStart+n.reservedIndexCount,this._nextVertexStart=n.vertexStart+n.reservedVertexCount,r}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 r=s.vertexStart,a=s.reservedVertexCount;s.vertexCount=t.getAttribute("position").count;for(const I in i.attributes){const c=t.getAttribute(I),l=i.getAttribute(I);wae(c,l,r);const B=c.itemSize;for(let Q=c.count,h=a;Q<h;Q++){const d=r+Q;for(let p=0;p<B;p++)l.setComponent(d,p,0)}l.needsUpdate=!0,l.addUpdateRange(r*B,a*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,r+o.getX(l));for(let l=o.count,B=c;l<B;l++)g.setX(I+l,r);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 r=n[o],a=i[r];if(a.active!==!1){if(g.index!==null){if(a.indexStart!==t){const{indexStart:I,vertexStart:c,reservedIndexCount:l}=a,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),a.indexStart=t}t+=a.reservedIndexCount}if(a.vertexStart!==A){const{vertexStart:I,reservedVertexCount:c}=a,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)}a.vertexStart=A}A+=a.reservedVertexCount,a.start=g.index?a.indexStart:a.vertexStart,this._nextIndexStart=g.index?a.indexStart+a.reservedIndexCount:0,this._nextVertexStart=a.vertexStart+a.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 Vn,o=i.index,s=i.attributes.position;for(let r=n.start,a=n.start+n.count;r<a;r++){let I=r;o&&(I=o.getX(I)),g.expandByPoint(Z0.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 vs;this.getBoundingBoxAt(A,RU),RU.getCenter(g.center);const o=i.index,s=i.attributes.position;let r=0;for(let a=n.start,I=n.start+n.count;a<I;a++){let c=a;o&&(c=o.getX(c)),Z0.fromBufferAttribute(s,c),r=Math.max(r,g.center.distanceToSquared(Z0))}g.radius=Math.sqrt(r),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(wH);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,r=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),r&&(r.dispose(),this._initColorsTexture(),mh(r.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(r=>r.indexStart+r.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 ki,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;Tr.material=this.material,Tr.geometry.index=o.index,Tr.geometry.attributes=o.attributes,Tr.geometry.boundingBox===null&&(Tr.geometry.boundingBox=new Vn),Tr.geometry.boundingSphere===null&&(Tr.geometry.boundingSphere=new vs);for(let s=0,r=i.length;s<r;s++){if(!i[s].visible||!i[s].active)continue;const a=i[s].geometryIndex,I=n[a];Tr.geometry.setDrawRange(I.start,I.count),this.getMatrixAt(s,Tr.matrixWorld).premultiply(g),this.getBoundingBoxAt(a,Tr.geometry.boundingBox),this.getBoundingSphereAt(a,Tr.geometry.boundingSphere),Tr.raycast(A,GU);for(let c=0,l=GU.length;c<l;c++){const B=GU[c];B.object=this,B.batchId=s,t.push(B)}GU.length=0}Tr.material=null,Tr.geometry.index=null,Tr.geometry.attributes={},Tr.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,r=this._instanceInfo,a=this._multiDrawStarts,I=this._multiDrawCounts,c=this._geometryInfo,l=this.perObjectFrustumCulled,B=this._indirectTexture,Q=B.image.data,h=i.isArrayCamera?mae:InA;l&&!i.isArrayCamera&&(Ya.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),InA.setFromProjectionMatrix(Ya,i.coordinateSystem,i.reversedDepth));let d=0;if(this.sortObjects){Ya.copy(this.matrixWorld).invert(),Z0.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Ya),CnA.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Ya);for(let m=0,D=r.length;m<D;m++)if(r[m].visible&&r[m].active){const S=r[m].geometryIndex;this.getMatrixAt(m,Ya),this.getBoundingSphereAt(S,Dh).applyMatrix4(Ya);let k=!1;if(l&&(k=!h.intersectsSphere(Dh,i)),!k){const N=c[S],G=Sae.subVectors(Dh.center,Z0).dot(CnA);kH.push(N.start,N.count,G,m)}}const p=kH.list,y=this.customSort;y===null?p.sort(g.transparent?fae:pae):y.call(this,p,i);for(let m=0,D=p.length;m<D;m++){const S=p[m];a[d]=S.start*s,I[d]=S.count,Q[d]=S.index,d++}kH.reset()}else for(let p=0,y=r.length;p<y;p++)if(r[p].visible&&r[p].active){const m=r[p].geometryIndex;let D=!1;if(l&&(this.getMatrixAt(p,Ya),this.getBoundingSphereAt(m,Dh).applyMatrix4(Ya),D=!h.intersectsSphere(Dh,i)),!D){const S=c[m];a[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 $o extends co{constructor(A){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new lt(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 fJ=new SA,yJ=new SA,cnA=new ii,W0=new Jw,bU=new vs,MH=new SA,lnA=new SA;class DB extends cn{constructor(A=new ki,t=new $o){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++)fJ.fromBufferAttribute(t,n-1),yJ.fromBufferAttribute(t,n),i[n]=i[n-1],i[n]+=fJ.distanceTo(yJ);A.setAttribute("lineDistance",new Vt(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(),bU.copy(i.boundingSphere),bU.applyMatrix4(n),bU.radius+=g,A.ray.intersectsSphere(bU)===!1)return;cnA.copy(n).invert(),W0.copy(A.ray).applyMatrix4(cnA);const s=g/((this.scale.x+this.scale.y+this.scale.z)/3),r=s*s,a=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+=a){const p=I.getX(h),y=I.getX(h+1),m=UU(this,A,W0,r,p,y,h);m&&t.push(m)}if(this.isLineLoop){const h=I.getX(Q-1),d=I.getX(B),p=UU(this,A,W0,r,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+=a){const p=UU(this,A,W0,r,h,h+1,h);p&&t.push(p)}if(this.isLineLoop){const h=UU(this,A,W0,r,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 UU(e,A,t,i,n,g,o){const s=e.geometry.attributes.position;if(fJ.fromBufferAttribute(s,n),yJ.fromBufferAttribute(s,g),t.distanceSqToSegment(fJ,yJ,MH,lnA)>i)return;MH.applyMatrix4(e.matrixWorld);const a=A.ray.origin.distanceTo(MH);if(!(a<A.near||a>A.far))return{distance:a,point:lnA.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}const BnA=new SA,EnA=new SA;class BI extends DB{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)BnA.fromBufferAttribute(t,n),EnA.fromBufferAttribute(t,n+1),i[n]=n===0?0:i[n-1],i[n+1]=i[n]+BnA.distanceTo(EnA);A.setAttribute("lineDistance",new Vt(i,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class Wx extends DB{constructor(A,t){super(A,t),this.isLineLoop=!0,this.type="LineLoop"}}class ME extends co{constructor(A){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new lt(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 QnA=new ii,I4=new Jw,vU=new vs,KU=new SA;class Pp extends cn{constructor(A=new ki,t=new ME){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(),vU.copy(i.boundingSphere),vU.applyMatrix4(n),vU.radius+=g,A.ray.intersectsSphere(vU)===!1)return;QnA.copy(n).invert(),I4.copy(A.ray).applyMatrix4(QnA);const s=g/((this.scale.x+this.scale.y+this.scale.z)/3),r=s*s,a=i.index,c=i.attributes.position;if(a!==null){const l=Math.max(0,o.start),B=Math.min(a.count,o.start+o.count);for(let Q=l,h=B;Q<h;Q++){const d=a.getX(Q);KU.fromBufferAttribute(c,d),unA(KU,d,r,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++)KU.fromBufferAttribute(c,Q),unA(KU,Q,r,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 unA(e,A,t,i,n,g,o){const s=I4.distanceSqToPoint(e);if(s<t){const r=new SA;I4.closestPointToPoint(e,r),r.applyMatrix4(i);const a=n.ray.origin.distanceTo(r);if(a<n.near||a>n.far)return;g.push({distance:a,distanceToRay:Math.sqrt(s),point:r,index:A,face:null,faceIndex:null,barycoord:null,object:o})}}class uyA extends Rg{constructor(A,t,i,n,g=_g,o=_g,s,r,a){super(A,t,i,n,g,o,s,r,a),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 kae extends uyA{constructor(A,t,i,n,g,o,s,r){super({},A,t,i,n,g,o,s,r),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(A){this.image=A,this.needsUpdate=!0}}class Mae extends Rg{constructor(A,t){super({width:A,height:t}),this.isFramebufferTexture=!0,this.magFilter=Ds,this.minFilter=Ds,this.generateMipmaps=!1,this.needsUpdate=!0}}class Vx extends Rg{constructor(A,t,i,n,g,o,s,r,a,I,c,l){super(null,o,s,r,a,I,n,g,c,l),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=A,this.flipY=!1,this.generateMipmaps=!1}}class Nae extends Vx{constructor(A,t,i,n,g,o){super(A,t,i,g,o),this.isCompressedArrayTexture=!0,this.image.depth=n,this.wrapR=nI,this.layerUpdates=new Set}addLayerUpdate(A){this.layerUpdates.add(A)}clearLayerUpdates(){this.layerUpdates.clear()}}class Rae extends Vx{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 Rg{constructor(A,t,i,n,g,o,s,r,a){super(A,t,i,n,g,o,s,r,a),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Xx extends Rg{constructor(A,t,i=aQ,n,g,o,s=Ds,r=Ds,a,I=YS,c=1){if(I!==YS&&I!==HS)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,r,I,i,a),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 OW extends Rg{constructor(A=null){super(),this.sourceTexture=A,this.isExternalTexture=!0}copy(A){return super.copy(A),this.sourceTexture=A.sourceTexture,this}}class $x extends ki{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=[],r=[],a=[],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(),r.push(d.x,d.y,d.z),a.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 Vt(s,3)),this.setAttribute("normal",new Vt(r,3)),this.setAttribute("uv",new Vt(a,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new $x(A.radius,A.height,A.capSegments,A.radialSegments,A.heightSegments)}}class AT extends ki{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=[],r=[],a=new SA,I=new It;o.push(0,0,0),s.push(0,0,1),r.push(.5,.5);for(let c=0,l=3;c<=t;c++,l+=3){const B=i+c/t*n;a.x=A*Math.cos(B),a.y=A*Math.sin(B),o.push(a.x,a.y,a.z),s.push(0,0,1),I.x=(o[l]/A+1)/2,I.y=(o[l+1]/A+1)/2,r.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 Vt(o,3)),this.setAttribute("normal",new Vt(s,3)),this.setAttribute("uv",new Vt(r,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new AT(A.radius,A.segments,A.thetaStart,A.thetaLength)}}class ny extends ki{constructor(A=1,t=1,i=1,n=32,g=1,o=!1,s=0,r=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:A,radiusBottom:t,height:i,radialSegments:n,heightSegments:g,openEnded:o,thetaStart:s,thetaLength:r};const a=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 Vt(c,3)),this.setAttribute("normal",new Vt(l,3)),this.setAttribute("uv",new Vt(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*r+s,T=Math.sin(J),v=Math.cos(J);S.x=b*T,S.y=-w*i+d,S.z=b*v,c.push(S.x,S.y,S.z),D.set(T,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)}a.addGroup(p,k,0),p+=k}function m(D){const S=Q,k=new It,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*r+s,T=Math.cos(J),v=Math.sin(J);N.x=M*v,N.y=d*w,N.z=M*T,c.push(N.x,N.y,N.z),l.push(0,w,0),k.x=T*.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}a.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 ny(A.radiusTop,A.radiusBottom,A.height,A.radialSegments,A.heightSegments,A.openEnded,A.thetaStart,A.thetaLength)}}class BG extends ny{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 BG(A.radius,A.height,A.radialSegments,A.heightSegments,A.openEnded,A.thetaStart,A.thetaLength)}}class xd extends ki{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),a(i),I(),this.setAttribute("position",new Vt(g,3)),this.setAttribute("normal",new Vt(g.slice(),3)),this.setAttribute("uv",new Vt(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),r(m,D,S,y)}function r(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 a(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 It,N=new It,G=new It;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 xd(A.vertices,A.indices,A.radius,A.details)}}class eT extends xd{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 eT(A.radius,A.detail)}}const FU=new SA,_U=new SA,NH=new SA,JU=new $a;class dyA extends ki{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"),r=o?o.count:s.count,a=[0,0,0],I=["a","b","c"],c=new Array(3),l={},B=[];for(let Q=0;Q<r;Q+=3){o?(a[0]=o.getX(Q),a[1]=o.getX(Q+1),a[2]=o.getX(Q+2)):(a[0]=Q,a[1]=Q+1,a[2]=Q+2);const{a:h,b:d,c:p}=JU;if(h.fromBufferAttribute(s,a[0]),d.fromBufferAttribute(s,a[1]),p.fromBufferAttribute(s,a[2]),JU.getNormal(NH),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=JU[I[y]],N=JU[I[m]],G=`${D}_${S}`,M=`${S}_${D}`;M in l&&l[M]?(NH.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:a[y],index1:a[m],normal:NH.clone()})}}for(const Q in l)if(l[Q]){const{index0:h,index1:d}=l[Q];FU.fromBufferAttribute(s,h),_U.fromBufferAttribute(s,d),B.push(FU.x,FU.y,FU.z),B.push(_U.x,_U.y,_U.z)}this.setAttribute("position",new Vt(B,3))}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}}class Il{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,r=g-1,a;for(;s<=r;)if(n=Math.floor(s+(r-s)/2),a=i[n]-o,a<0)s=n+1;else if(a>0)r=n-1;else{r=n;break}if(n=r,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),r=t||(o.isVector2?new It:new SA);return r.copy(s).sub(o).normalize(),r}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,r=new ii;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 a=Number.MAX_VALUE;const I=Math.abs(n[0].x),c=Math.abs(n[0].y),l=Math.abs(n[0].z);I<=a&&(a=I,i.set(1,0,0)),c<=a&&(a=c,i.set(0,1,0)),l<=a&&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(bi(n[B-1].dot(n[B]),-1,1));g[B].applyMatrix4(r.makeRotationAxis(s,Q))}o[B].crossVectors(n[B],g[B])}if(t===!0){let B=Math.acos(bi(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(r.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 tT extends Il{constructor(A=0,t=0,i=1,n=1,g=0,o=Math.PI*2,s=!1,r=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=r}getPoint(A,t=new It){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 r=this.aX+this.xRadius*Math.cos(s),a=this.aY+this.yRadius*Math.sin(s);if(this.aRotation!==0){const I=Math.cos(this.aRotation),c=Math.sin(this.aRotation),l=r-this.aX,B=a-this.aY;r=l*I-B*c+this.aX,a=l*c+B*I+this.aY}return i.set(r,a)}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 hyA extends tT{constructor(A,t,i,n,g,o){super(A,t,i,i,n,g,o),this.isArcCurve=!0,this.type="ArcCurve"}}function PW(){let e=0,A=0,t=0,i=0;function n(g,o,s,r){e=g,A=s,t=-3*g+3*o-2*s-r,i=2*g-2*o+s+r}return{initCatmullRom:function(g,o,s,r,a){n(o,s,a*(s-g),a*(r-o))},initNonuniformCatmullRom:function(g,o,s,r,a,I,c){let l=(o-g)/a-(s-g)/(a+I)+(s-o)/I,B=(s-o)/I-(r-o)/(I+c)+(r-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 LU=new SA,RH=new PW,GH=new PW,bH=new PW;class jW extends Il{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),r=o-s;this.closed?s+=s>0?0:(Math.floor(Math.abs(s)/g)+1)*g:r===0&&s===g-1&&(s=g-2,r=1);let a,I;this.closed||s>0?a=n[(s-1)%g]:(LU.subVectors(n[0],n[1]).add(n[0]),a=LU);const c=n[s%g],l=n[(s+1)%g];if(this.closed||s+2<g?I=n[(s+2)%g]:(LU.subVectors(n[g-1],n[g-2]).add(n[g-1]),I=LU),this.curveType==="centripetal"||this.curveType==="chordal"){const B=this.curveType==="chordal"?.5:.25;let Q=Math.pow(a.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),RH.initNonuniformCatmullRom(a.x,c.x,l.x,I.x,Q,h,d),GH.initNonuniformCatmullRom(a.y,c.y,l.y,I.y,Q,h,d),bH.initNonuniformCatmullRom(a.z,c.z,l.z,I.z,Q,h,d)}else this.curveType==="catmullrom"&&(RH.initCatmullRom(a.x,c.x,l.x,I.x,this.tension),GH.initCatmullRom(a.y,c.y,l.y,I.y,this.tension),bH.initCatmullRom(a.z,c.z,l.z,I.z,this.tension));return i.set(RH.calc(r),GH.calc(r),bH.calc(r)),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 dnA(e,A,t,i,n){const g=(i-A)*.5,o=(n-t)*.5,s=e*e,r=e*s;return(2*t-2*i+g+o)*r+(-3*t+3*i-2*g-o)*s+g*e+t}function Gae(e,A){const t=1-e;return t*t*A}function bae(e,A){return 2*(1-e)*e*A}function Uae(e,A){return e*e*A}function RM(e,A,t,i){return Gae(e,A)+bae(e,t)+Uae(e,i)}function vae(e,A){const t=1-e;return t*t*t*A}function Kae(e,A){const t=1-e;return 3*t*t*e*A}function Fae(e,A){return 3*(1-e)*e*e*A}function _ae(e,A){return e*e*e*A}function GM(e,A,t,i,n){return vae(e,A)+Kae(e,t)+Fae(e,i)+_ae(e,n)}class zW extends Il{constructor(A=new It,t=new It,i=new It,n=new It){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=A,this.v1=t,this.v2=i,this.v3=n}getPoint(A,t=new It){const i=t,n=this.v0,g=this.v1,o=this.v2,s=this.v3;return i.set(GM(A,n.x,g.x,o.x,s.x),GM(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 pyA extends Il{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(GM(A,n.x,g.x,o.x,s.x),GM(A,n.y,g.y,o.y,s.y),GM(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 ZW extends Il{constructor(A=new It,t=new It){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=A,this.v2=t}getPoint(A,t=new It){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 It){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 fyA extends Il{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 WW extends Il{constructor(A=new It,t=new It,i=new It){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=A,this.v1=t,this.v2=i}getPoint(A,t=new It){const i=t,n=this.v0,g=this.v1,o=this.v2;return i.set(RM(A,n.x,g.x,o.x),RM(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 VW extends Il{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(RM(A,n.x,g.x,o.x),RM(A,n.y,g.y,o.y),RM(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 XW extends Il{constructor(A=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=A}getPoint(A,t=new It){const i=t,n=this.points,g=(n.length-1)*A,o=Math.floor(g),s=g-o,r=n[o===0?o:o-1],a=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(dnA(s,r.x,a.x,I.x,c.x),dnA(s,r.y,a.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 It().fromArray(n))}return this}}var DJ=Object.freeze({__proto__:null,ArcCurve:hyA,CatmullRomCurve3:jW,CubicBezierCurve:zW,CubicBezierCurve3:pyA,EllipseCurve:tT,LineCurve:ZW,LineCurve3:fyA,QuadraticBezierCurve:WW,QuadraticBezierCurve3:VW,SplineCurve:XW});class yyA extends Il{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 DJ[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],r=s.getLength(),a=r===0?0:1-o/r;return s.getPointAt(a,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,r=o.getPoints(s);for(let a=0;a<r.length;a++){const I=r[a];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 DJ[n.type]().fromJSON(n))}return this}}class mJ extends yyA{constructor(A){super(),this.type="Path",this.currentPoint=new It,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 ZW(this.currentPoint.clone(),new It(A,t));return this.curves.push(i),this.currentPoint.set(A,t),this}quadraticCurveTo(A,t,i,n){const g=new WW(this.currentPoint.clone(),new It(A,t),new It(i,n));return this.curves.push(g),this.currentPoint.set(i,n),this}bezierCurveTo(A,t,i,n,g,o){const s=new zW(this.currentPoint.clone(),new It(A,t),new It(i,n),new It(g,o));return this.curves.push(s),this.currentPoint.set(g,o),this}splineThru(A){const t=[this.currentPoint.clone()].concat(A),i=new XW(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,r=this.currentPoint.y;return this.absarc(A+s,t+r,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,r){const a=this.currentPoint.x,I=this.currentPoint.y;return this.absellipse(A+a,t+I,i,n,g,o,s,r),this}absellipse(A,t,i,n,g,o,s,r){const a=new tT(A,t,i,n,g,o,s,r);if(this.curves.length>0){const c=a.getPoint(0);c.equals(this.currentPoint)||this.lineTo(c.x,c.y)}this.curves.push(a);const I=a.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 mJ{constructor(A){super(A),this.uuid=VI(),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 mJ().fromJSON(n))}return this}}function Jae(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,r,a;if(i&&(g=Yae(e,A,g,t)),e.length>80*t){s=1/0,r=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<r&&(r=Q),B>I&&(I=B),Q>c&&(c=Q)}a=Math.max(I-s,c-r),a=a!==0?32767/a:0}return LN(g,o,t,s,r,a,0),o}function DyA(e,A,t,i,n){let g;if(n===AIe(e,A,t,i)>0)for(let o=A;o<t;o+=i)g=hnA(o/i|0,e[o],e[o+1],g);else for(let o=t-i;o>=A;o-=i)g=hnA(o/i|0,e[o],e[o+1],g);return g&&ZS(g,g.next)&&(TN(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)||mo(t.prev,t,t.next)===0)){if(TN(t),t=A=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==A);return A}function LN(e,A,t,i,n,g,o){if(!e)return;!o&&g&&zae(e,i,n,g);let s=e;for(;e.prev!==e.next;){const r=e.prev,a=e.next;if(g?xae(e,i,n,g):Lae(e)){A.push(r.i,e.i,a.i),TN(e),e=a.next,s=a.next;continue}if(e=a,e===s){o?o===1?(e=Tae(mf(e),A),LN(e,A,t,i,n,g,2)):o===2&&qae(e,A,t,i,n,g):LN(mf(e),A,t,i,n,g,1);break}}}function Lae(e){const A=e.prev,t=e,i=e.next;if(mo(A,t,i)>=0)return!1;const n=A.x,g=t.x,o=i.x,s=A.y,r=t.y,a=i.y,I=Math.min(n,g,o),c=Math.min(s,r,a),l=Math.max(n,g,o),B=Math.max(s,r,a);let Q=i.next;for(;Q!==A;){if(Q.x>=I&&Q.x<=l&&Q.y>=c&&Q.y<=B&&bk(n,s,g,r,o,a,Q.x,Q.y)&&mo(Q.prev,Q,Q.next)>=0)return!1;Q=Q.next}return!0}function xae(e,A,t,i){const n=e.prev,g=e,o=e.next;if(mo(n,g,o)>=0)return!1;const s=n.x,r=g.x,a=o.x,I=n.y,c=g.y,l=o.y,B=Math.min(s,r,a),Q=Math.min(I,c,l),h=Math.max(s,r,a),d=Math.max(I,c,l),p=C4(B,Q,A,t,i),y=C4(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&&bk(s,I,r,c,a,l,m.x,m.y)&&mo(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&&bk(s,I,r,c,a,l,D.x,D.y)&&mo(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&&bk(s,I,r,c,a,l,m.x,m.y)&&mo(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&&bk(s,I,r,c,a,l,D.x,D.y)&&mo(D.prev,D,D.next)>=0)return!1;D=D.nextZ}return!0}function Tae(e,A){let t=e;do{const i=t.prev,n=t.next.next;!ZS(i,n)&&SyA(i,t,t.next,n)&&xN(i,n)&&xN(n,i)&&(A.push(i.i,t.i,n.i),TN(t),TN(t.next),t=e=n),t=t.next}while(t!==e);return mf(t)}function qae(e,A,t,i,n,g){let o=e;do{let s=o.next.next;for(;s!==o.prev;){if(o.i!==s.i&&Vae(o,s)){let r=wyA(o,s);o=mf(o,o.next),r=mf(r,r.next),LN(o,A,t,i,n,g,0),LN(r,A,t,i,n,g,0);return}s=s.next}o=o.next}while(o!==e)}function Yae(e,A,t,i){const n=[];for(let g=0,o=A.length;g<o;g++){const s=A[g]*i,r=g<o-1?A[g+1]*i:e.length,a=DyA(e,s,r,i,!1);a===a.next&&(a.steiner=!0),n.push(Wae(a))}n.sort(Hae);for(let g=0;g<n.length;g++)t=Oae(n[g],t);return t}function Hae(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 Oae(e,A){const t=Pae(e,A);if(!t)return A;const i=wyA(t,e);return mf(i,i.next),mf(t,t.next)}function Pae(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,r=o.x,a=o.y;let I=1/0;t=o;do{if(i>=t.x&&t.x>=r&&i!==t.x&&myA(n<a?i:g,n,r,a,n<a?g:i,n,t.x,t.y)){const c=Math.abs(n-t.y)/(i-t.x);xN(t,e)&&(c<I||c===I&&(t.x>o.x||t.x===o.x&&jae(o,t)))&&(o=t,I=c)}t=t.next}while(t!==s);return o}function jae(e,A){return mo(e.prev,e,A.prev)<0&&mo(A.next,e,e.next)<0}function zae(e,A,t,i){let n=e;do n.z===0&&(n.z=C4(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,Zae(n)}function Zae(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 a=0;a<t&&(s++,o=o.nextZ,!!o);a++);let r=t;for(;s>0||r>0&&o;)s!==0&&(r===0||!o||i.z<=o.z)?(n=i,i=i.nextZ,s--):(n=o,o=o.nextZ,r--),g?g.nextZ=n:e=n,n.prevZ=g,g=n;i=o}g.nextZ=null,t*=2}while(A>1);return e}function C4(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 Wae(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 myA(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 bk(e,A,t,i,n,g,o,s){return!(e===o&&A===s)&&myA(e,A,t,i,n,g,o,s)}function Vae(e,A){return e.next.i!==A.i&&e.prev.i!==A.i&&!Xae(e,A)&&(xN(e,A)&&xN(A,e)&&$ae(e,A)&&(mo(e.prev,e,A.prev)||mo(e,A.prev,A))||ZS(e,A)&&mo(e.prev,e,e.next)>0&&mo(A.prev,A,A.next)>0)}function mo(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 SyA(e,A,t,i){const n=TU(mo(e,A,t)),g=TU(mo(e,A,i)),o=TU(mo(t,i,e)),s=TU(mo(t,i,A));return!!(n!==g&&o!==s||n===0&&xU(e,t,A)||g===0&&xU(e,i,A)||o===0&&xU(t,e,i)||s===0&&xU(t,A,i))}function xU(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 TU(e){return e>0?1:e<0?-1:0}function Xae(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&&SyA(t,t.next,e,A))return!0;t=t.next}while(t!==e);return!1}function xN(e,A){return mo(e.prev,e,e.next)<0?mo(e,A,e.next)>=0&&mo(e,e.prev,A)>=0:mo(e,A,e.prev)<0||mo(e,e.next,A)<0}function $ae(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 wyA(e,A){const t=c4(e.i,e.x,e.y),i=c4(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 hnA(e,A,t,i){const n=c4(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 TN(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 c4(e,A,t){return{i:e,x:A,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function AIe(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 eIe{static triangulate(A,t,i=2){return Jae(A,t,i)}}class Pc{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 Pc.area(A)<0}static triangulateShape(A,t){const i=[],n=[],g=[];pnA(A),fnA(i,A);let o=A.length;t.forEach(pnA);for(let r=0;r<t.length;r++)n.push(o),o+=t[r].length,fnA(i,t[r]);const s=eIe.triangulate(i,n);for(let r=0;r<s.length;r+=3)g.push(s.slice(r,r+3));return g}}function pnA(e){const A=e.length;A>2&&e[A-1].equals(e[0])&&e.pop()}function fnA(e,A){for(let t=0;t<A.length;t++)e.push(A[t].x),e.push(A[t].y)}class iT extends ki{constructor(A=new jp([new It(.5,.5),new It(-.5,.5),new It(-.5,-.5),new It(.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,r=A.length;s<r;s++){const a=A[s];o(a)}this.setAttribute("position",new Vt(n,3)),this.setAttribute("uv",new Vt(g,2)),this.computeVertexNormals();function o(s){const r=[],a=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:tIe;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(a);let w=M.shape;const b=M.holes;if(!Pc.isClockWise(w)){w=w.reverse();for(let H=0,P=b.length;H<P;H++){const tA=b[H];Pc.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 CA=oA%H.length,cA=H[CA],_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)),lA=tA*O*O;if(X<=lA){H.splice(CA,1),oA--;continue}iA=cA}}K(w),b.forEach(K);const J=b.length,T=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,CA;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,lA=cA*X-_A*uA;if(Math.abs(lA)>Number.EPSILON){const wA=Math.sqrt(O),xA=Math.sqrt(uA*uA+X*X),HA=P.x-_A/wA,zA=P.y+cA/wA,ne=tA.x-X/xA,ye=tA.y+uA/xA,Ee=((ne-HA)*X-(ye-zA)*uA)/(cA*X-_A*uA);iA=HA+cA*Ee-H.x,oA=zA+_A*Ee-H.y;const NA=iA*iA+oA*oA;if(NA<=2)return new It(iA,oA);CA=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,CA=Math.sqrt(O)):(iA=cA,oA=_A,CA=Math.sqrt(O/2))}return new It(iA/CA,oA/CA)}const q=[];for(let H=0,P=T.length,tA=P-1,iA=H+1;H<P;H++,tA++,iA++)tA===P&&(tA=0),iA===P&&(iA=0),q[H]=x(T[H],T[tA],T[iA]);const z=[];let Z,eA=q.concat();for(let H=0,P=J;H<P;H++){const tA=b[H];Z=[];for(let iA=0,oA=tA.length,CA=oA-1,cA=iA+1;iA<oA;iA++,CA++,cA++)CA===oA&&(CA=0),cA===oA&&(cA=0),Z[iA]=x(tA[iA],tA[CA],tA[cA]);z.push(Z),eA=eA.concat(Z)}let aA;if(d===0)aA=Pc.triangulateShape(T,b);else{const H=[],P=[];for(let tA=0;tA<d;tA++){const iA=tA/d,oA=B*Math.cos(iA*Math.PI/2),CA=Q*Math.sin(iA*Math.PI/2)+h;for(let cA=0,_A=T.length;cA<_A;cA++){const uA=v(T[cA],q[cA],CA);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,lA=uA.length;O<lA;O++){const wA=v(uA[O],Z[O],CA);RA(wA.x,wA.y,-oA),iA===0&&X.push(wA)}iA===0&&P.push(X)}}aA=Pc.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,CA=T.length;oA<CA;oA++){const cA=v(T[oA],q[oA],iA);RA(cA.x,cA.y,c+tA)}for(let oA=0,CA=b.length;oA<CA;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];YA(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];YA(oA[0]+tA,oA[1]+tA,oA[2]+tA)}}else{for(let P=0;P<sA;P++){const tA=aA[P];YA(tA[2],tA[1],tA[0])}for(let P=0;P<sA;P++){const tA=aA[P];YA(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(T,P),P+=T.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 CA=0,cA=I+d*2;CA<cA;CA++){const _A=U*CA,uA=U*(CA+1),X=P+iA+_A,O=P+oA+_A,lA=P+oA+uA,wA=P+iA+uA;W(X,O,lA,wA)}}}function RA(H,P,tA){r.push(H),r.push(P),r.push(tA)}function YA(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,CA=y.generateSideWallUV(i,n,oA-6,oA-3,oA-2,oA-1);L(CA[0]),L(CA[1]),L(CA[3]),L(CA[1]),L(CA[2]),L(CA[3])}function $(H){n.push(r[H*3+0]),n.push(r[H*3+1]),n.push(r[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 iIe(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 DJ[n.type]().fromJSON(n)),new iT(i,A.options)}}const tIe={generateTopUV:function(e,A,t,i,n){const g=A[t*3],o=A[t*3+1],s=A[i*3],r=A[i*3+1],a=A[n*3],I=A[n*3+1];return[new It(g,o),new It(s,r),new It(a,I)]},generateSideWallUV:function(e,A,t,i,n,g){const o=A[t*3],s=A[t*3+1],r=A[t*3+2],a=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-a)?[new It(o,1-r),new It(a,1-c),new It(l,1-Q),new It(h,1-p)]:[new It(s,1-r),new It(I,1-c),new It(B,1-Q),new It(d,1-p)]}};function iIe(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 nT extends xd{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 nT(A.radius,A.detail)}}class gT extends ki{constructor(A=[new It(0,-.5),new It(.5,0),new It(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=bi(n,0,Math.PI*2);const g=[],o=[],s=[],r=[],a=[],I=1/t,c=new SA,l=new It,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(),r.push(B.x,B.y,B.z);break;case A.length-1:r.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(),r.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=r[3*k+0]*D,G=r[3*k+1],M=r[3*k+0]*S;a.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 Vt(o,3)),this.setAttribute("uv",new Vt(s,2)),this.setAttribute("normal",new Vt(a,3))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new gT(A.points,A.segments,A.phiStart,A.phiLength)}}class EG extends xd{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 EG(A.radius,A.detail)}}class sB extends ki{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),r=Math.floor(n),a=s+1,I=r+1,c=A/s,l=t/r,B=[],Q=[],h=[],d=[];for(let p=0;p<I;p++){const y=p*l-o;for(let m=0;m<a;m++){const D=m*c-g;Q.push(D,-y,0),h.push(0,0,1),d.push(m/s),d.push(1-p/r)}}for(let p=0;p<r;p++)for(let y=0;y<s;y++){const m=y+a*p,D=y+a*(p+1),S=y+1+a*(p+1),k=y+1+a*p;B.push(m,D,k),B.push(D,S,k)}this.setIndex(B),this.setAttribute("position",new Vt(Q,3)),this.setAttribute("normal",new Vt(h,3)),this.setAttribute("uv",new Vt(d,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new sB(A.width,A.height,A.widthSegments,A.heightSegments)}}class oT extends ki{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=[],r=[],a=[],I=[];let c=A;const l=(t-A)/n,B=new SA,Q=new It;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),r.push(B.x,B.y,B.z),a.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 Vt(r,3)),this.setAttribute("normal",new Vt(a,3)),this.setAttribute("uv",new Vt(I,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new oT(A.innerRadius,A.outerRadius,A.thetaSegments,A.phiSegments,A.thetaStart,A.thetaLength)}}class sT extends ki{constructor(A=new jp([new It(0,.5),new It(-.5,-.5),new It(.5,-.5)]),t=12){super(),this.type="ShapeGeometry",this.parameters={shapes:A,curveSegments:t};const i=[],n=[],g=[],o=[];let s=0,r=0;if(Array.isArray(A)===!1)a(A);else for(let I=0;I<A.length;I++)a(A[I]),this.addGroup(s,r,I),s+=r,r=0;this.setIndex(i),this.setAttribute("position",new Vt(n,3)),this.setAttribute("normal",new Vt(g,3)),this.setAttribute("uv",new Vt(o,2));function a(I){const c=n.length/3,l=I.extractPoints(t);let B=l.shape;const Q=l.holes;Pc.isClockWise(B)===!1&&(B=B.reverse());for(let d=0,p=Q.length;d<p;d++){const y=Q[d];Pc.isClockWise(y)===!0&&(Q[d]=y.reverse())}const h=Pc.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),r+=3}}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}toJSON(){const A=super.toJSON(),t=this.parameters.shapes;return nIe(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 sT(i,A.curveSegments)}}function nIe(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 ki{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 r=Math.min(o+s,Math.PI);let a=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&&r===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(a++)}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||r<Math.PI)&&B.push(D,S,k)}this.setIndex(B),this.setAttribute("position",new Vt(Q,3)),this.setAttribute("normal",new Vt(h,3)),this.setAttribute("uv",new Vt(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 rT extends xd{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 rT(A.radius,A.detail)}}class aT extends ki{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=[],r=[],a=[],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(),r.push(l.x,l.y,l.z),a.push(Q/n),a.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 Vt(s,3)),this.setAttribute("normal",new Vt(r,3)),this.setAttribute("uv",new Vt(a,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 IT extends ki{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=[],r=[],a=[],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),r.push(c.x,c.y,c.z),l.subVectors(c,B).normalize(),a.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 Vt(r,3)),this.setAttribute("normal",new Vt(a,3)),this.setAttribute("uv",new Vt(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 IT(A.radius,A.tube,A.tubularSegments,A.radialSegments,A.p,A.q)}}class CT extends ki{constructor(A=new VW(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,r=new SA,a=new It;let I=new SA;const c=[],l=[],B=[],Q=[];h(),this.setIndex(Q),this.setAttribute("position",new Vt(c,3)),this.setAttribute("normal",new Vt(l,3)),this.setAttribute("uv",new Vt(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);r.x=M*D.x+G*S.x,r.y=M*D.y+G*S.y,r.z=M*D.z+G*S.z,r.normalize(),l.push(r.x,r.y,r.z),s.x=I.x+i*r.x,s.y=I.y+i*r.y,s.z=I.z+i*r.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++)a.x=m/t,a.y=D/n,B.push(a.x,a.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 CT(new DJ[A.path.type]().fromJSON(A.path),A.tubularSegments,A.radius,A.radialSegments,A.closed)}}class kyA extends ki{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 r=A.groups;r.length===0&&(r=[{start:0,count:s.count,materialIndex:0}]);for(let a=0,I=r.length;a<I;++a){const c=r[a],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),ynA(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,r=o.count/3;s<r;s++)for(let a=0;a<3;a++){const I=3*s+a,c=3*s+(a+1)%3;n.fromBufferAttribute(o,I),g.fromBufferAttribute(o,c),ynA(n,g,i)===!0&&(t.push(n.x,n.y,n.z),t.push(g.x,g.y,g.z))}}this.setAttribute("position",new Vt(t,3))}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}}function ynA(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 DnA=Object.freeze({__proto__:null,BoxGeometry:gI,CapsuleGeometry:$x,CircleGeometry:AT,ConeGeometry:BG,CylinderGeometry:ny,DodecahedronGeometry:eT,EdgesGeometry:dyA,ExtrudeGeometry:iT,IcosahedronGeometry:nT,LatheGeometry:gT,OctahedronGeometry:EG,PlaneGeometry:sB,PolyhedronGeometry:xd,RingGeometry:oT,ShapeGeometry:sT,SphereGeometry:Sf,TetrahedronGeometry:rT,TorusGeometry:aT,TorusKnotGeometry:IT,TubeGeometry:CT,WireframeGeometry:kyA});class MyA extends co{constructor(A){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new lt(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 NyA extends rc{constructor(A){super(A),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Kg extends co{constructor(A){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new lt(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 lt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ld,this.normalScale=new It(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 or,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 Lo extends Kg{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 It(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return bi(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 lt(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 lt(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new lt(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 $W extends co{constructor(A){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new lt(16777215),this.specular=new lt(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new lt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ld,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new or,this.combine=gG,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 RyA extends co{constructor(A){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new lt(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new lt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ld,this.normalScale=new It(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 GyA extends co{constructor(A){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ld,this.normalScale=new It(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 AV extends co{constructor(A){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new lt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new lt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ld,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new or,this.combine=gG,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 eV extends co{constructor(A){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=WfA,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 tV extends co{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 byA extends co{constructor(A){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new lt(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ld,this.normalScale=new It(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 UyA extends $o{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 vyA(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function KyA(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 l4(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 r=0;r!==A;++r)n[o++]=e[s+r]}return n}function iV(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 gIe(e,A,t,i,n=30){const g=e.clone();g.name=A;const o=[];for(let r=0;r<g.tracks.length;++r){const a=g.tracks[r],I=a.getValueSize(),c=[],l=[];for(let B=0;B<a.times.length;++B){const Q=a.times[B]*n;if(!(Q<t||Q>=i)){c.push(a.times[B]);for(let h=0;h<I;++h)l.push(a.values[B*I+h])}}c.length!==0&&(a.times=Ep(c,a.times.constructor),a.values=Ep(l,a.values.constructor),o.push(a))}g.tracks=o;let s=1/0;for(let r=0;r<g.tracks.length;++r)s>g.tracks[r].times[0]&&(s=g.tracks[r].times[0]);for(let r=0;r<g.tracks.length;++r)g.tracks[r].shift(-1*s);return g.resetDuration(),g}function oIe(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],r=s.ValueTypeName;if(r==="bool"||r==="string")continue;const a=e.tracks.find(function(p){return p.name===s.name&&p.ValueTypeName===r});if(a===void 0)continue;let I=0;const c=s.getValueSize();s.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(I=c/3);let l=0;const B=a.getValueSize();a.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)}r==="quaternion"&&new Ao().fromArray(h).normalize().conjugate().toArray(h);const d=a.times.length;for(let p=0;p<d;++p){const y=p*B+l;if(r==="quaternion")Ao.multiplyQuaternionsFlat(a.values,y,h,0,a.values,y);else{const m=B-l*2;for(let D=0;D<m;++D)a.values[y+D]-=h[D]}}}return e.blendMode=_W,e}class sIe{static convertArray(A,t){return Ep(A,t)}static isTypedArray(A){return vyA(A)}static getKeyframeOrder(A){return KyA(A)}static sortedArray(A,t,i){return l4(A,t,i)}static flattenJSON(A,t,i,n){iV(A,t,i,n)}static subclip(A,t,i,n,g=30){return gIe(A,t,i,n,g)}static makeClipAdditive(A,t=0,i=A,n=30){return oIe(A,t,i,n)}}class gy{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 r=i-2;;){if(g===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===r)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 FyA extends gy{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],r=n[o];if(s===void 0)switch(this.getSettings_().endingStart){case Bp:g=A,s=2*t-i;break;case UN:g=n.length-2,s=t+n[g]-n[g+1];break;default:g=A,s=i}if(r===void 0)switch(this.getSettings_().endingEnd){case Bp:o=A,r=2*i-t;break;case UN:o=1,r=i+n[1]-n[0];break;default:o=A-1,r=t}const a=(i-t)*.5,I=this.valueSize;this._weightPrev=a/(t-s),this._weightNext=a/(r-i),this._offsetPrev=g*I,this._offsetNext=o*I}interpolate_(A,t,i,n){const g=this.resultBuffer,o=this.sampleValues,s=this.valueSize,r=A*s,a=r-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[a+S]+m*o[r+S]+D*o[c+S];return g}}class nV extends gy{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,r=A*s,a=r-s,I=(i-t)/(n-t),c=1-I;for(let l=0;l!==s;++l)g[l]=o[a+l]*c+o[r+l]*I;return g}}class _yA extends gy{constructor(A,t,i,n){super(A,t,i,n)}interpolate_(A){return this.copySampleValue_(A-1)}}class cc{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 _yA(this.times,this.values,this.getValueSize(),A)}InterpolantFactoryMethodLinear(A){return new nV(this.times,this.values,this.getValueSize(),A)}InterpolantFactoryMethodSmooth(A){return new FyA(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 vK: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 vK}}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 r=i[s];if(typeof r=="number"&&isNaN(r)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,s,r),A=!1;break}if(o!==null&&o>r){console.error("THREE.KeyframeTrack: Out of order keys.",this,s,r,o),A=!1;break}o=r}if(n!==void 0&&vyA(n))for(let s=0,r=n.length;s!==r;++s){const a=n[s];if(isNaN(a)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,s,a),A=!1;break}}return A}optimize(){const A=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),n=this.getInterpolation()===vK,g=A.length-1;let o=1;for(let s=1;s<g;++s){let r=!1;const a=A[s],I=A[s+1];if(a!==I&&(s!==1||a!==A[0]))if(n)r=!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]){r=!0;break}}}if(r){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,r=o*i,a=0;a!==i;++a)t[r+a]=t[s+a];++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}}cc.prototype.ValueTypeName="";cc.prototype.TimeBufferType=Float32Array;cc.prototype.ValueBufferType=Float32Array;cc.prototype.DefaultInterpolation=dd;class oy extends cc{constructor(A,t,i){super(A,t,i)}}oy.prototype.ValueTypeName="bool";oy.prototype.ValueBufferType=Array;oy.prototype.DefaultInterpolation=yf;oy.prototype.InterpolantFactoryMethodLinear=void 0;oy.prototype.InterpolantFactoryMethodSmooth=void 0;class gV extends cc{constructor(A,t,i,n){super(A,t,i,n)}}gV.prototype.ValueTypeName="color";class CQ extends cc{constructor(A,t,i,n){super(A,t,i,n)}}CQ.prototype.ValueTypeName="number";class JyA extends gy{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,r=(i-t)/(n-t);let a=A*s;for(let I=a+s;a!==I;a+=4)Ao.slerpFlat(g,0,o,a-s,o,a,r);return g}}class mB extends cc{constructor(A,t,i,n){super(A,t,i,n)}InterpolantFactoryMethodLinear(A){return new JyA(this.times,this.values,this.getValueSize(),A)}}mB.prototype.ValueTypeName="quaternion";mB.prototype.InterpolantFactoryMethodSmooth=void 0;class sy extends cc{constructor(A,t,i){super(A,t,i)}}sy.prototype.ValueTypeName="string";sy.prototype.ValueBufferType=Array;sy.prototype.DefaultInterpolation=yf;sy.prototype.InterpolantFactoryMethodLinear=void 0;sy.prototype.InterpolantFactoryMethodSmooth=void 0;class SB extends cc{constructor(A,t,i,n){super(A,t,i,n)}}SB.prototype.ValueTypeName="vector";class fd{constructor(A="",t=-1,i=[],n=Yx){this.name=A,this.tracks=i,this.duration=t,this.blendMode=n,this.uuid=VI(),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(aIe(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(cc.toJSON(i[g]));return n}static CreateFromMorphTargetSequence(A,t,i,n){const g=t.length,o=[];for(let s=0;s<g;s++){let r=[],a=[];r.push((s+g-1)%g,s,(s+1)%g),a.push(0,1,0);const I=KyA(r);r=l4(r,1,I),a=l4(a,1,I),!n&&r[0]===0&&(r.push(g),a.push(a[0])),o.push(new CQ(".morphTargetInfluences["+t[s].name+"]",r,a).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,r=A.length;s<r;s++){const a=A[s],I=a.name.match(g);if(I&&I.length>1){const c=I[1];let l=n[c];l||(n[c]=l=[]),l.push(a)}}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=[];iV(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 r=A.length||-1;const a=A.hierarchy||[];for(let c=0;c<a.length;c++){const l=a[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))}r=B.length*o}else{const B=".bones["+t[c].name+"]";i(SB,B+".position",l,"pos",n),i(mB,B+".quaternion",l,"rot",n),i(SB,B+".scale",l,"scl",n)}}return n.length===0?null:new this(g,r,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 rIe(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 SB;case"color":return gV;case"quaternion":return mB;case"bool":case"boolean":return oy;case"string":return sy}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}function aIe(e){if(e.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const A=rIe(e.type);if(e.times===void 0){const t=[],i=[];iV(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 rB={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 oV{constructor(A,t,i){const n=this;let g=!1,o=0,s=0,r;const a=[];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 r?r(I):I},this.setURLModifier=function(I){return r=I,this},this.addHandler=function(I,c){return a.push(I,c),this},this.removeHandler=function(I){const c=a.indexOf(I);return c!==-1&&a.splice(c,2),this},this.getHandler=function(I){for(let c=0,l=a.length;c<l;c+=2){const B=a[c],Q=a[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 LyA=new oV;class sr{constructor(A){this.manager=A!==void 0?A:LyA,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}}sr.DEFAULT_MATERIAL_NAME="__DEFAULT";const tE={};class IIe extends Error{constructor(A,t){super(A),this.response=t}}class Aa extends sr{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=rB.get(`file:${A}`);if(g!==void 0)return this.manager.itemStart(A),setTimeout(()=>{t&&t(g),this.manager.itemEnd(A)},0),g;if(tE[A]!==void 0){tE[A].push({onLoad:t,onProgress:i,onError:n});return}tE[A]=[],tE[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,r=this.responseType;fetch(o).then(a=>{if(a.status===200||a.status===0){if(a.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||a.body===void 0||a.body.getReader===void 0)return a;const I=tE[A],c=a.body.getReader(),l=a.headers.get("X-File-Size")||a.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 IIe(`fetch for "${a.url}" responded with ${a.status}: ${a.statusText}`,a)}).then(a=>{switch(r){case"arraybuffer":return a.arrayBuffer();case"blob":return a.blob();case"document":return a.text().then(I=>new DOMParser().parseFromString(I,s));case"json":return a.json();default:if(s==="")return a.text();{const c=/charset="?([^;"\s]*)"?/i.exec(s),l=c&&c[1]?c[1].toLowerCase():void 0,B=new TextDecoder(l);return a.arrayBuffer().then(Q=>B.decode(Q))}}}).then(a=>{rB.add(`file:${A}`,a);const I=tE[A];delete tE[A];for(let c=0,l=I.length;c<l;c++){const B=I[c];B.onLoad&&B.onLoad(a)}}).catch(a=>{const I=tE[A];if(I===void 0)throw this.manager.itemError(A),a;delete tE[A];for(let c=0,l=I.length;c<l;c++){const B=I[c];B.onError&&B.onError(a)}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 CIe extends sr{constructor(A){super(A)}load(A,t,i,n){const g=this,o=new Aa(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(r){n?n(r):console.error(r),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 cIe extends sr{constructor(A){super(A)}load(A,t,i,n){const g=this,o=[],s=new Vx,r=new Aa(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(g.withCredentials);let a=0;function I(c){r.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},a+=1,a===6&&(B.mipmapCount===1&&(s.minFilter=_g),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 r.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=_g),s.format=l.format,s.needsUpdate=!0,t&&t(s)},i,n);return s}}const ED=new WeakMap;class qN extends sr{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=rB.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=FN("img");function r(){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 a(c){I(),n&&n(c),rB.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",r,!1),s.removeEventListener("error",a,!1)}return s.addEventListener("load",r,!1),s.addEventListener("error",a,!1),A.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(s.crossOrigin=this.crossOrigin),rB.add(`image:${A}`,s),g.manager.itemStart(A),s.src=A,s}}class lIe extends sr{constructor(A){super(A)}load(A,t,i,n){const g=new aG;g.colorSpace=sn;const o=new qN(this.manager);o.setCrossOrigin(this.crossOrigin),o.setPath(this.path);let s=0;function r(a){o.load(A[a],function(I){g.images[a]=I,s++,s===6&&(g.needsUpdate=!0,t&&t(g))},void 0,n)}for(let a=0;a<A.length;++a)r(a);return g}}class BIe extends sr{constructor(A){super(A)}load(A,t,i,n){const g=this,o=new dB,s=new Aa(this.manager);return s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setPath(this.path),s.setWithCredentials(g.withCredentials),s.load(A,function(r){let a;try{a=g.parse(r)}catch(I){if(n!==void 0)n(I);else{console.error(I);return}}a.image!==void 0?o.image=a.image:a.data!==void 0&&(o.image.width=a.width,o.image.height=a.height,o.image.data=a.data),o.wrapS=a.wrapS!==void 0?a.wrapS:nI,o.wrapT=a.wrapT!==void 0?a.wrapT:nI,o.magFilter=a.magFilter!==void 0?a.magFilter:_g,o.minFilter=a.minFilter!==void 0?a.minFilter:_g,o.anisotropy=a.anisotropy!==void 0?a.anisotropy:1,a.colorSpace!==void 0&&(o.colorSpace=a.colorSpace),a.flipY!==void 0&&(o.flipY=a.flipY),a.format!==void 0&&(o.format=a.format),a.type!==void 0&&(o.type=a.type),a.mipmaps!==void 0&&(o.mipmaps=a.mipmaps,o.minFilter=Ra),a.mipmapCount===1&&(o.minFilter=_g),a.generateMipmaps!==void 0&&(o.generateMipmaps=a.generateMipmaps),o.needsUpdate=!0,t&&t(o,a)},i,n),o}}class Td extends sr{constructor(A){super(A)}load(A,t,i,n){const g=new Rg,o=new qN(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 qd extends cn{constructor(A,t=1){super(),this.isLight=!0,this.type="Light",this.color=new lt(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 sV extends qd{constructor(A,t,i){super(A,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(cn.DEFAULT_UP),this.updateMatrix(),this.groundColor=new lt(t)}copy(A,t){return super.copy(A,t),this.groundColor.copy(A.groundColor),this}}const UH=new ii,mnA=new SA,SnA=new SA;class rV{constructor(A){this.camera=A,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new It(512,512),this.mapType=sc,this.map=null,this.mapPass=null,this.matrix=new ii,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Tw,this._frameExtents=new It(1,1),this._viewportCount=1,this._viewports=[new $n(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(A){const t=this.camera,i=this.matrix;mnA.setFromMatrixPosition(A.matrixWorld),t.position.copy(mnA),SnA.setFromMatrixPosition(A.target.matrixWorld),t.lookAt(SnA),t.updateMatrixWorld(),UH.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(UH,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(UH)}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 EIe extends rV{constructor(){super(new zo(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(A){const t=this.camera,i=PS*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 qd{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(cn.DEFAULT_UP),this.updateMatrix(),this.target=new cn,this.distance=i,this.angle=n,this.penumbra=g,this.decay=o,this.map=null,this.shadow=new EIe}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 wnA=new ii,V0=new SA,vH=new SA;class QIe extends rV{constructor(){super(new zo(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new It(4,2),this._viewportCount=6,this._viewports=[new $n(2,1,1,1),new $n(0,1,1,1),new $n(3,1,1,1),new $n(1,1,1,1),new $n(3,0,1,1),new $n(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()),V0.setFromMatrixPosition(A.matrixWorld),i.position.copy(V0),vH.copy(i.position),vH.add(this._cubeDirections[t]),i.up.copy(this._cubeUps[t]),i.lookAt(vH),i.updateMatrixWorld(),n.makeTranslation(-V0.x,-V0.y,-V0.z),wnA.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),this._frustum.setFromProjectionMatrix(wnA,i.coordinateSystem,i.reversedDepth)}}class QG extends qd{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 QIe}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 Yd=class extends Px{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,r=n-t;if(this.view!==null&&this.view.enabled){const a=(this.right-this.left)/this.view.fullWidth/this.zoom,I=(this.top-this.bottom)/this.view.fullHeight/this.zoom;g+=a*this.view.offsetX,o=g+a*this.view.width,s-=I*this.view.offsetY,r=s-I*this.view.height}this.projectionMatrix.makeOrthographic(g,o,s,r,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 uIe extends rV{constructor(){super(new Yd(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class zp extends qd{constructor(A,t){super(A,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(cn.DEFAULT_UP),this.updateMatrix(),this.target=new cn,this.shadow=new uIe}dispose(){this.shadow.dispose()}copy(A){return super.copy(A),this.target=A.target.clone(),this.shadow=A.shadow.clone(),this}}class aV extends qd{constructor(A,t){super(A,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class xyA extends qd{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 TyA{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 qyA extends qd{constructor(A=new TyA,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 lT extends sr{constructor(A){super(A),this.textures={}}load(A,t,i,n){const g=this,o=new Aa(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(r){n?n(r):console.error(r),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 lt().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 lt().setHex(o.value);break;case"v2":n.uniforms[g].value=new It().fromArray(o.value);break;case"v3":n.uniforms[g].value=new SA().fromArray(o.value);break;case"v4":n.uniforms[g].value=new $n().fromArray(o.value);break;case"m3":n.uniforms[g].value=new $i().fromArray(o.value);break;case"m4":n.uniforms[g].value=new ii().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 It().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 It().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 lT.createMaterialFromType(A)}static createMaterialFromType(A){const t={ShadowMaterial:MyA,SpriteMaterial:JN,RawShaderMaterial:NyA,ShaderMaterial:rc,PointsMaterial:ME,MeshPhysicalMaterial:Lo,MeshStandardMaterial:Kg,MeshPhongMaterial:$W,MeshToonMaterial:RyA,MeshNormalMaterial:GyA,MeshLambertMaterial:AV,MeshDepthMaterial:eV,MeshDistanceMaterial:tV,MeshBasicMaterial:yg,MeshMatcapMaterial:byA,LineDashedMaterial:UyA,LineBasicMaterial:$o,Material:co};return new t[A]}}class XI{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 YyA extends ki{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 HyA extends sr{constructor(A){super(A)}load(A,t,i,n){const g=this,o=new Aa(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(r){n?n(r):console.error(r),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=rm(d.type,p),m=new Lw(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 YyA:new ki,s=A.data.index;if(s!==void 0){const B=rm(s.type,s.array);o.setIndex(new Yi(B,1))}const r=A.data.attributes;for(const B in r){const Q=r[B];let h;if(Q.isInterleavedBufferAttribute){const d=n(A.data,Q.data);h=new IQ(d,Q.itemSize,Q.offset,Q.normalized)}else{const d=rm(Q.type,Q.array),p=Q.isInstancedBufferAttribute?hd:Yi;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 a=A.data.morphAttributes;if(a)for(const B in a){const Q=a[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 IQ(D,y.itemSize,y.offset,y.normalized)}else{const D=rm(y.type,y.array);m=new Yi(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 vs().fromJSON(l)),A.name&&(o.name=A.name),A.userData&&(o.userData=A.userData),o}}class dIe extends sr{constructor(A){super(A)}load(A,t,i,n){const g=this,o=this.path===""?XI.extractUrlBase(A):this.path;this.resourcePath=this.resourcePath||o;const s=new Aa(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(A,function(r){let a=null;try{a=JSON.parse(r)}catch(c){n!==void 0&&n(c),console.error("THREE:ObjectLoader: Can't parse "+A+".",c.message);return}const I=a.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(a,t)},i,n)}async loadAsync(A,t){const i=this,n=this.path===""?XI.extractUrlBase(A):this.path;this.resourcePath=this.resourcePath||n;const g=new Aa(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),r=s.metadata;if(r===void 0||r.type===void 0||r.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(a)}),s=this.parseTextures(A.textures,o),r=this.parseMaterials(A.materials,s),a=this.parseObject(A.object,g,r,s,i),I=this.parseSkeletons(A.skeletons,a);if(this.bindSkeletons(a,I),this.bindLightTargets(a),t!==void 0){let c=!1;for(const l in o)if(o[l].data instanceof HTMLImageElement){c=!0;break}c===!1&&t(a)}return a}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),r=this.parseObject(A.object,n,s,o,t),a=this.parseSkeletons(A.skeletons,r);return this.bindSkeletons(r,a),this.bindLightTargets(r),r}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 xw().fromJSON(A[g],n);i[s.uuid]=s}return i}parseGeometries(A,t){const i={};if(A!==void 0){const n=new HyA;for(let g=0,o=A.length;g<o;g++){let s;const r=A[g];switch(r.type){case"BufferGeometry":case"InstancedBufferGeometry":s=n.parse(r);break;default:r.type in DnA?s=DnA[r.type].fromJSON(r,t):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${r.type}"`)}s.uuid=r.uuid,r.name!==void 0&&(s.name=r.name),r.userData!==void 0&&(s.userData=r.userData),i[r.uuid]=s}}return i}parseMaterials(A,t){const i={},n={};if(A!==void 0){const g=new lT;g.setTextures(t);for(let o=0,s=A.length;o<s;o++){const r=A[o];i[r.uuid]===void 0&&(i[r.uuid]=g.parse(r)),n[r.uuid]=i[r.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(r){return i.manager.itemStart(r),g.load(r,function(){i.manager.itemEnd(r)},void 0,function(){i.manager.itemError(r),i.manager.itemEnd(r)})}function s(r){if(typeof r=="string"){const a=r,I=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(a)?a:i.resourcePath+a;return o(I)}else return r.data?{data:rm(r.type,r.data),width:r.width,height:r.height}:null}if(A!==void 0&&A.length>0){const r=new oV(t);g=new qN(r),g.setCrossOrigin(this.crossOrigin);for(let a=0,I=A.length;a<I;a++){const c=A[a],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 dB(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,r=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(s)?s:t.resourcePath+s;return await n.loadAsync(r)}else return o.data?{data:rm(o.type,o.data),width:o.width,height:o.height}:null}if(A!==void 0&&A.length>0){n=new qN(this.manager),n.setCrossOrigin(this.crossOrigin);for(let o=0,s=A.length;o<s;o++){const r=A[o],a=r.url;if(Array.isArray(a)){const I=[];for(let c=0,l=a.length;c<l;c++){const B=a[c],Q=await g(B);Q!==null&&(Q instanceof HTMLImageElement?I.push(Q):I.push(new dB(Q.data,Q.width,Q.height)))}i[r.uuid]=new Ru(I)}else{const I=await g(r.url);i[r.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 r=t[s.image],a=r.data;let I;Array.isArray(a)?(I=new aG,a.length===6&&(I.needsUpdate=!0)):(a&&a.data?I=new dB:I=new Rg,a&&(I.needsUpdate=!0)),I.source=r,I.uuid=s.uuid,s.name!==void 0&&(I.name=s.name),s.mapping!==void 0&&(I.mapping=i(s.mapping,hIe)),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],knA),I.wrapT=i(s.wrap[1],knA)),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 r(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 a(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 CG,A.background!==void 0&&(Number.isInteger(A.background)?o.background=new lt(A.background):o.background=a(A.background)),A.environment!==void 0&&(o.environment=a(A.environment)),A.fog!==void 0&&(A.fog.type==="Fog"?o.fog=new IG(A.fog.color,A.fog.near,A.fog.far):A.fog.type==="FogExp2"&&(o.fog=new jx(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 zo(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 Yd(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 aV(A.color,A.intensity);break;case"DirectionalLight":o=new zp(A.color,A.intensity),o.target=A.target||"";break;case"PointLight":o=new QG(A.color,A.intensity,A.distance,A.decay);break;case"RectAreaLight":o=new xyA(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 sV(A.color,A.groundColor,A.intensity);break;case"LightProbe":o=new qyA().fromJSON(A);break;case"SkinnedMesh":I=s(A.geometry),c=r(A.material),o=new zx(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=r(A.material),o=new hn(I,c);break;case"InstancedMesh":I=s(A.geometry),c=r(A.material);const l=A.count,B=A.instanceMatrix,Q=A.instanceColor;o=new lG(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=r(A.material),o=new QyA(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 Vn().fromJSON(h.boundingBox)),h.boundingSphere!==void 0&&(p=new vs().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=a(A.matricesTexture.uuid),o._indirectTexture=a(A.indirectTexture.uuid),A.colorsTexture!==void 0&&(o._colorsTexture=a(A.colorsTexture.uuid)),A.boundingSphere!==void 0&&(o.boundingSphere=new vs().fromJSON(A.boundingSphere)),A.boundingBox!==void 0&&(o.boundingBox=new Vn().fromJSON(A.boundingBox));break;case"LOD":o=new EyA;break;case"Line":o=new DB(s(A.geometry),r(A.material));break;case"LineLoop":o=new Wx(s(A.geometry),r(A.material));break;case"LineSegments":o=new BI(s(A.geometry),r(A.material));break;case"PointCloud":case"Points":o=new Pp(s(A.geometry),r(A.material));break;case"Sprite":o=new pJ(r(A.material));break;case"Group":o=new er;break;case"Bone":o=new cG;break;default:o=new cn}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 cn}})}}const hIe={UVMapping:Fx,CubeReflectionMapping:rQ,CubeRefractionMapping:ud,EquirectangularReflectionMapping:GN,EquirectangularRefractionMapping:bN,CubeUVReflectionMapping:_w},knA={RepeatWrapping:va,ClampToEdgeWrapping:nI,MirroredRepeatWrapping:ff},MnA={NearestFilter:Ds,NearestMipmapNearestFilter:oG,NearestMipmapLinearFilter:Nu,LinearFilter:_g,LinearMipmapNearestFilter:Hp,LinearMipmapLinearFilter:Ra},KH=new WeakMap;class IV extends sr{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=rB.get(`image-bitmap:${A}`);if(o!==void 0){if(g.manager.itemStart(A),o.then){o.then(a=>{if(KH.has(o)===!0)n&&n(KH.get(o)),g.manager.itemError(A),g.manager.itemEnd(A);else return t&&t(a),g.manager.itemEnd(A),a});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 r=fetch(A,s).then(function(a){return a.blob()}).then(function(a){return createImageBitmap(a,Object.assign(g.options,{colorSpaceConversion:"none"}))}).then(function(a){return rB.add(`image-bitmap:${A}`,a),t&&t(a),g.manager.itemEnd(A),a}).catch(function(a){n&&n(a),KH.set(r,a),rB.remove(`image-bitmap:${A}`),g.manager.itemError(A),g.manager.itemEnd(A)});rB.add(`image-bitmap:${A}`,r),g.manager.itemStart(A)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let qU,CV=class{static getContext(){return qU===void 0&&(qU=new(window.AudioContext||window.webkitAudioContext)),qU}static setContext(A){qU=A}};class pIe extends sr{constructor(A){super(A)}load(A,t,i,n){const g=this,o=new Aa(this.manager);o.setResponseType("arraybuffer"),o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(A,function(r){try{const a=r.slice(0);CV.getContext().decodeAudioData(a,function(c){t(c)}).catch(s)}catch(a){s(a)}},i,n);function s(r){n?n(r):console.error(r),g.manager.itemError(A)}}}const NnA=new ii,RnA=new ii,Sh=new ii;class fIe{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new zo,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new zo,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,r;RnA.elements[12]=-n,NnA.elements[12]=n,s=-o*t.aspect+g,r=o*t.aspect+g,Sh.elements[0]=2*t.near/(r-s),Sh.elements[8]=(r+s)/(r-s),this.cameraL.projectionMatrix.copy(Sh),s=-o*t.aspect-g,r=o*t.aspect-g,Sh.elements[0]=2*t.near/(r-s),Sh.elements[8]=(r+s)/(r-s),this.cameraR.projectionMatrix.copy(Sh)}this.cameraL.matrixWorld.copy(A.matrixWorld).multiply(RnA),this.cameraR.matrixWorld.copy(A.matrixWorld).multiply(NnA)}}class OyA extends zo{constructor(A=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=A}}class cV{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,FH=new Ao,yIe=new SA,kh=new SA,Mh=new SA;class DIe extends cn{constructor(){super(),this.type="AudioListener",this.context=CV.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new cV}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,FH,yIe),kh.set(0,0,-1).applyQuaternion(FH),Mh.set(0,1,0).applyQuaternion(FH),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 PyA=class extends cn{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,GnA=new Ao,mIe=new SA,Rh=new SA;class SIe extends PyA{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,GnA,mIe),Rh.set(0,0,1).applyQuaternion(GnA);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 wIe{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 jyA{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 r=t*this._origIndex;this._mixBufferRegion(i,n,r,1-g,t)}o>0&&this._mixBufferRegionAdditive(i,n,this._addIndex*t,1,t);for(let r=t,a=t+t;r!==a;++r)if(i[r]!==i[r+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){Ao.slerpFlat(A,t,A,t,A,i,n)}_slerpAdditive(A,t,i,n,g){const o=this._workIndex*g;Ao.multiplyQuaternionsFlat(A,o,A,t,A,i),Ao.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 r=t+s;A[r]=A[r]*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 lV="\\[\\]\\.:\\/",kIe=new RegExp("["+lV+"]","g"),BV="[^"+lV+"]",MIe="[^"+lV.replace("\\.","")+"]",NIe=/((?:WC+[\/:])*)/.source.replace("WC",BV),RIe=/(WCOD+)?/.source.replace("WCOD",MIe),GIe=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",BV),bIe=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",BV),UIe=new RegExp("^"+NIe+RIe+GIe+bIe+"$"),vIe=["material","materials","bones","map"];class KIe{constructor(A,t,i){const n=i||On.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 On{constructor(A,t,i){this.path=t,this.parsedPath=i||On.parseTrackName(t),this.node=On.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 On.Composite(A,t,i):new On(A,t,i)}static sanitizeNodeName(A){return A.replace(/\s/g,"_").replace(kIe,"")}static parseTrackName(A){const t=UIe.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);vIe.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 r=i(s.children);if(r)return r}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=On.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 a=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===a){a=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(a!==void 0){if(A[a]===void 0){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,A);return}A=A[a]}}const o=A[n];if(o===void 0){const a=t.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+a+"."+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 r=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])}r=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=g}else o.fromArray!==void 0&&o.toArray!==void 0?(r=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(r=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=n;this.getValue=this.GetterByBindingType[r],this.setValue=this.SetterByBindingTypeAndVersioning[r][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}On.Composite=KIe;On.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};On.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};On.prototype.GetterByBindingType=[On.prototype._getValue_direct,On.prototype._getValue_array,On.prototype._getValue_arrayElement,On.prototype._getValue_toArray];On.prototype.SetterByBindingTypeAndVersioning=[[On.prototype._setValue_direct,On.prototype._setValue_direct_setNeedsUpdate,On.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[On.prototype._setValue_array,On.prototype._setValue_array_setNeedsUpdate,On.prototype._setValue_array_setMatrixWorldNeedsUpdate],[On.prototype._setValue_arrayElement,On.prototype._setValue_arrayElement_setNeedsUpdate,On.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[On.prototype._setValue_fromArray,On.prototype._setValue_fromArray_setNeedsUpdate,On.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class FIe{constructor(){this.isAnimationObjectGroup=!0,this.uuid=VI(),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,r=A.length,a=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=r++,t[B]=Q,A.push(l);for(let h=0,d=o;h!==d;++h)g[h].push(new On(l,i[h],n[h]))}else if(Q<a){s=A[Q];const h=--a,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 On(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_=a}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 r=arguments[o],a=r.uuid,I=t[a];if(I!==void 0&&I>=g){const c=g++,l=A[c];t[l.uuid]=I,A[I]=l,t[a]=c,A[c]=r;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,r=arguments.length;s!==r;++s){const a=arguments[s],I=a.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,r=this._objects,a=r.length,I=this.nCachedObjects_,c=new Array(a);n=g.length,i[A]=n,o.push(A),s.push(t),g.push(c);for(let l=I,B=r.length;l!==B;++l){const Q=r[l];c[l]=new On(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,r=o[s],a=A[s];t[a]=i,o[i]=r,o.pop(),g[i]=g[s],g.pop(),n[i]=n[s],n.pop()}}}class zyA{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),r={endingStart:lp,endingEnd:lp};for(let a=0;a!==o;++a){const I=g[a].createInterpolant(null);s[a]=I,I.settings=r}this._interpolantSettings=r,this._interpolants=s,this._propertyBindings=new Array(o),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=hJ,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 r=s.parameterPositions,a=s.sampleValues;return r[0]=g,r[1]=g+i,a[0]=A/o,a[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 r=(A-g)*i;r<0||i===0?t=0:(this._startTime=null,t=i*r)}t*=this._updateTimeScale(A);const o=this._updateTime(t),s=this._updateWeight(A);if(s>0){const r=this._interpolants,a=this._propertyBindings;switch(this.blendMode){case _W:for(let I=0,c=r.length;I!==c;++I)r[I].evaluate(o),a[I].accumulateAdditive(s);break;case Yx:default:for(let I=0,c=r.length;I!==c;++I)r[I].evaluate(o),a[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===ZfA;if(A===0)return g===-1?n:o&&(g&1)===1?t-n:n;if(i===FW){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 r=this.repetitions-g;if(r<=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(r===1){const a=A<0;this._setEndings(a,!a,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=UN,t?n.endingEnd=this.zeroSlopeAtEnd?Bp:lp:n.endingEnd=UN)}_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,r=o.sampleValues;return s[0]=g,r[0]=t,s[1]=g+A,r[1]=i,this}}const _Ie=new Float32Array(1);class EV extends UB{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,r=i.uuid,a=this._bindingsByRootAndName;let I=a[r];I===void 0&&(I={},a[r]=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,r,B));continue}const h=t&&t._propertyBindings[c].binding.parsedPath;Q=new jyA(On.create(i,B,h),l.ValueTypeName,l.getValueSize()),++Q.referenceCount,this._addInactiveBinding(Q,r,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],r=s.knownActions,a=r[r.length-1],I=A._byClipCacheIndex;a._byClipCacheIndex=I,r[I]=a,r.pop(),A._byClipCacheIndex=null;const c=s.actionByRoot,l=(A._localRoot||this._root).uuid;delete c[l],r.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],r=t[t.length-1],a=A._cacheIndex;r._cacheIndex=a,t[a]=r,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 nV(new Float32Array(2),new Float32Array(2),1,_Ie),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,r=this._actionsByClip[s];let a=null;if(i===void 0&&(o!==null?i=o.blendMode:i=Yx),r!==void 0){const c=r.actionByRoot[g];if(c!==void 0&&c.blendMode===i)return c;a=r.knownActions[0],o===null&&(o=a._clip)}if(o===null)return null;const I=new zyA(this,o,t,i);return this._bindAction(I,a),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 a=0;a!==i;++a)t[a]._update(n,A,g,o);const s=this._bindings,r=this._nActiveBindings;for(let a=0;a!==r;++a)s[a].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,r=o.length;s!==r;++s){const a=o[s];this._deactivateAction(a);const I=a._cacheIndex,c=t[t.length-1];a._cacheIndex=null,a._byClipCacheIndex=null,c._cacheIndex=I,t[I]=c,t.pop(),this._removeInactiveBindingsForAction(a)}delete n[i]}}uncacheRoot(A){const t=A.uuid,i=this._actionsByClip;for(const o in i){const s=i[o].actionByRoot,r=s[t];r!==void 0&&(this._deactivateAction(r),this._removeInactiveAction(r))}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 JIe extends TW{constructor(A=1,t=1,i=1,n={}){super(A,t,n),this.isRenderTarget3D=!0,this.depth=i,this.texture=new Ox(null,A,t,i),this._setTextureOptions(n),this.texture.isRenderTargetTexture=!0}}class QV{constructor(A){this.value=A}clone(){return new QV(this.value.clone===void 0?this.value:this.value.clone())}}let LIe=0;class xIe extends UB{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:LIe++}),this.name="",this.usage=KN,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 TIe extends Lw{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 qIe{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 bnA=new ii;class uV{constructor(A,t,i=0,n=1/0){this.ray=new Jw(A,t),this.near=i,this.far=n,this.camera=null,this.layers=new jS,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 bnA.identity().extractRotation(A.matrixWorld),this.ray.origin.setFromMatrixPosition(A.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(bnA),this}intersectObject(A,t=!0,i=[]){return B4(A,this,i,t),i.sort(UnA),i}intersectObjects(A,t=!0,i=[]){for(let n=0,g=A.length;n<g;n++)B4(A[n],this,i,t);return i.sort(UnA),i}}function UnA(e,A){return e.distance-A.distance}function B4(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++)B4(g[o],A,t,!0)}}class YIe{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=HIe.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 HIe(){this._document.hidden===!1&&this.reset()}class OIe{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=bi(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(bi(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}class PIe{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 dV{constructor(A,t,i,n){dV.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 vnA=new It;class jIe{constructor(A=new It(1/0,1/0),t=new It(-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=vnA.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,vnA).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 KnA=new SA,YU=new SA,QD=new SA,uD=new SA,_H=new SA,zIe=new SA,ZIe=new SA;class WIe{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){KnA.subVectors(A,this.start),YU.subVectors(this.end,this.start);const i=YU.dot(YU);let g=YU.dot(KnA)/i;return t&&(g=bi(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=zIe,i=ZIe){const n=10000000000000001e-32;let g,o;const s=this.start,r=A.start,a=this.end,I=A.end;QD.subVectors(a,s),uD.subVectors(I,r),_H.subVectors(s,r);const c=QD.dot(QD),l=uD.dot(uD),B=uD.dot(_H);if(c<=n&&l<=n)return t.copy(s),i.copy(r),t.sub(i),t.dot(t);if(c<=n)g=0,o=B/l,o=bi(o,0,1);else{const Q=QD.dot(_H);if(l<=n)o=0,g=bi(-Q/c,0,1);else{const h=QD.dot(uD),d=c*l-h*h;d!==0?g=bi((h*B-Q*l)/d,0,1):g=0,o=(h*g+B)/l,o<0?(o=0,g=bi(-Q/c,0,1)):o>1&&(o=1,g=bi((h-Q)/c,0,1))}}return t.copy(s).add(QD.multiplyScalar(g)),i.copy(r).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 FnA=new SA;class VIe extends cn{constructor(A,t){super(),this.light=A,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new ki,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,r=32;o<r;o++,s++){const a=o/r*Math.PI*2,I=s/r*Math.PI*2;n.push(Math.cos(a),Math.sin(a),1,Math.cos(I),Math.sin(I),1)}i.setAttribute("position",new Vt(n,3));const g=new $o({fog:!1,toneMapped:!1});this.cone=new BI(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),FnA.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(FnA),this.color!==void 0?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}}const xQ=new SA,HU=new ii,JH=new ii;class ZyA extends BI{constructor(A){const t=WyA(A),i=new ki,n=[],g=[];for(let a=0;a<t.length;a++){const I=t[a];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 Vt(n,3)),i.setAttribute("color",new Vt(g,3));const o=new $o({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 lt(255),r=new lt(65280);this.setColors(s,r)}updateMatrixWorld(A){const t=this.bones,i=this.geometry,n=i.getAttribute("position");JH.copy(this.root.matrixWorld).invert();for(let g=0,o=0;g<t.length;g++){const s=t[g];s.parent&&s.parent.isBone&&(HU.multiplyMatrices(JH,s.matrixWorld),xQ.setFromMatrixPosition(HU),n.setXYZ(o,xQ.x,xQ.y,xQ.z),HU.multiplyMatrices(JH,s.parent.matrixWorld),xQ.setFromMatrixPosition(HU),n.setXYZ(o+1,xQ.x,xQ.y,xQ.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 WyA(e){const A=[];e.isBone===!0&&A.push(e);for(let t=0;t<e.children.length;t++)A.push(...WyA(e.children[t]));return A}class XIe extends hn{constructor(A,t,i){const n=new Sf(t,4,2),g=new yg({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 $Ie=new SA,_nA=new lt,JnA=new lt;class ACe extends cn{constructor(A,t,i){super(),this.light=A,this.matrix=A.matrixWorld,this.matrixAutoUpdate=!1,this.color=i,this.type="HemisphereLightHelper";const n=new EG(t);n.rotateY(Math.PI*.5),this.material=new yg({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 Yi(o,3)),this.add(new hn(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");_nA.copy(this.light.color),JnA.copy(this.light.groundColor);for(let i=0,n=t.count;i<n;i++){const g=i<n/2?_nA:JnA;t.setXYZ(i,g.r,g.g,g.b)}t.needsUpdate=!0}this.light.updateWorldMatrix(!0,!1),A.lookAt($Ie.setFromMatrixPosition(this.light.matrixWorld).negate())}}class eCe extends BI{constructor(A=10,t=10,i=4473924,n=8947848){i=new lt(i),n=new lt(n);const g=t/2,o=A/t,s=A/2,r=[],a=[];for(let l=0,B=0,Q=-s;l<=t;l++,Q+=o){r.push(-s,0,Q,s,0,Q),r.push(Q,0,-s,Q,0,s);const h=l===g?i:n;h.toArray(a,B),B+=3,h.toArray(a,B),B+=3,h.toArray(a,B),B+=3,h.toArray(a,B),B+=3}const I=new ki;I.setAttribute("position",new Vt(r,3)),I.setAttribute("color",new Vt(a,3));const c=new $o({vertexColors:!0,toneMapped:!1});super(I,c),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class tCe extends BI{constructor(A=10,t=16,i=8,n=64,g=4473924,o=8947848){g=new lt(g),o=new lt(o);const s=[],r=[];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;r.push(h.r,h.g,h.b),r.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),r.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),r.push(l.r,l.g,l.b)}}const a=new ki;a.setAttribute("position",new Vt(s,3)),a.setAttribute("color",new Vt(r,3));const I=new $o({vertexColors:!0,toneMapped:!1});super(a,I),this.type="PolarGridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}const LnA=new SA,OU=new SA,xnA=new SA;class iCe extends cn{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 ki;n.setAttribute("position",new Vt([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));const g=new $o({fog:!1,toneMapped:!1});this.lightPlane=new DB(n,g),this.add(this.lightPlane),n=new ki,n.setAttribute("position",new Vt([0,0,0,0,0,1],3)),this.targetLine=new DB(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),LnA.setFromMatrixPosition(this.light.matrixWorld),OU.setFromMatrixPosition(this.light.target.matrixWorld),xnA.subVectors(OU,LnA),this.lightPlane.lookAt(OU),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(OU),this.targetLine.scale.z=xnA.length()}}const PU=new SA,Ro=new Px;class nCe extends BI{constructor(A){const t=new ki,i=new $o({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){r(Q),r(h)}function r(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 Vt(n,3)),t.setAttribute("color",new Vt(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 a=new lt(16755200),I=new lt(16711680),c=new lt(43775),l=new lt(16777215),B=new lt(3355443);this.setColors(a,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(Ro.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),this.camera.reversedDepth===!0)g=1,o=0;else if(this.camera.coordinateSystem===OI)g=-1,o=1;else if(this.camera.coordinateSystem===OS)g=0,o=1;else throw new Error("THREE.CameraHelper.update(): Invalid coordinate system: "+this.camera.coordinateSystem);Yo("c",t,A,Ro,0,0,g),Yo("t",t,A,Ro,0,0,o),Yo("n1",t,A,Ro,-i,-n,g),Yo("n2",t,A,Ro,i,-n,g),Yo("n3",t,A,Ro,-i,n,g),Yo("n4",t,A,Ro,i,n,g),Yo("f1",t,A,Ro,-i,-n,o),Yo("f2",t,A,Ro,i,-n,o),Yo("f3",t,A,Ro,-i,n,o),Yo("f4",t,A,Ro,i,n,o),Yo("u1",t,A,Ro,i*.7,n*1.1,g),Yo("u2",t,A,Ro,-i*.7,n*1.1,g),Yo("u3",t,A,Ro,0,n*2,g),Yo("cf1",t,A,Ro,-i,0,o),Yo("cf2",t,A,Ro,i,0,o),Yo("cf3",t,A,Ro,0,-n,o),Yo("cf4",t,A,Ro,0,n,o),Yo("cn1",t,A,Ro,-i,0,g),Yo("cn2",t,A,Ro,i,0,g),Yo("cn3",t,A,Ro,0,-n,g),Yo("cn4",t,A,Ro,0,n,g),A.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}}function Yo(e,A,t,i,n,g,o){PU.set(n,g,o).unproject(i);const s=A[e];if(s!==void 0){const r=t.getAttribute("position");for(let a=0,I=s.length;a<I;a++)r.setXYZ(s[a],PU.x,PU.y,PU.z)}}const jU=new Vn;class gCe extends BI{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 ki;g.setIndex(new Yi(i,1)),g.setAttribute("position",new Yi(n,3)),super(g,new $o({color:t,toneMapped:!1})),this.object=A,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(){if(this.object!==void 0&&jU.setFromObject(this.object),jU.isEmpty())return;const A=jU.min,t=jU.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 oCe extends BI{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 ki;g.setIndex(new Yi(i,1)),g.setAttribute("position",new Vt(n,3)),super(g,new $o({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 sCe extends DB{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 ki;o.setAttribute("position",new Vt(g,3)),o.computeBoundingSphere(),super(o,new $o({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],r=new ki;r.setAttribute("position",new Vt(s,3)),r.computeBoundingSphere(),this.add(new hn(r,new yg({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 TnA=new SA;let zU,LH;class rCe extends cn{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",zU===void 0&&(zU=new ki,zU.setAttribute("position",new Vt([0,0,0,0,1,0],3)),LH=new BG(.5,1,5,1),LH.translate(0,-.5,0)),this.position.copy(t),this.line=new DB(zU,new $o({color:n,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new hn(LH,new yg({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{TnA.set(A.z,0,-A.x).normalize();const t=Math.acos(A.y);this.quaternion.setFromAxisAngle(TnA,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 aCe extends BI{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 ki;n.setAttribute("position",new Vt(t,3)),n.setAttribute("color",new Vt(i,3));const g=new $o({vertexColors:!0,toneMapped:!1});super(n,g),this.type="AxesHelper"}setColors(A,t,i){const n=new lt,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 ICe{constructor(){this.type="ShapePath",this.color=new lt,this.subPaths=[],this.currentPath=null}moveTo(A,t){return this.currentPath=new mJ,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=Pc.isClockWise,g=this.subPaths;if(g.length===0)return[];let o,s,r;const a=[];if(g.length===1)return s=g[0],r=new jp,r.curves=s.curves,a.push(r),a;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++){r=l[p].s,a.push(r),d=B[p];for(let m=0,D=d.length;m<D;m++)r.holes.push(d[m].h)}return a}}class CCe extends UB{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 cCe(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 lCe(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 BCe(e){return e.repeat.x=1,e.repeat.y=1,e.offset.x=0,e.offset.y=0,e}function E4(e,A,t,i){const n=ECe(i);switch(t){case UW:return e*A;case xx:return e*A/n.components*n.byteLength;case sG:return e*A/n.components*n.byteLength;case KW:return e*A*2/n.components*n.byteLength;case Tx:return e*A*2/n.components*n.byteLength;case vW:return e*A*3/n.components*n.byteLength;case jr:return e*A*4/n.components*n.byteLength;case qx:return e*A*4/n.components*n.byteLength;case SM:case wM:return Math.floor((e+3)/4)*Math.floor((A+3)/4)*8;case kM:case MM:return Math.floor((e+3)/4)*Math.floor((A+3)/4)*16;case P_:case z_:return Math.max(e,16)*Math.max(A,8)/4;case O_:case j_:return Math.max(e,8)*Math.max(A,8)/2;case Z_:case W_:return Math.floor((e+3)/4)*Math.floor((A+3)/4)*8;case V_:return Math.floor((e+3)/4)*Math.floor((A+3)/4)*16;case X_:return Math.floor((e+3)/4)*Math.floor((A+3)/4)*16;case $_:return Math.floor((e+4)/5)*Math.floor((A+3)/4)*16;case AJ:return Math.floor((e+4)/5)*Math.floor((A+4)/5)*16;case eJ:return Math.floor((e+5)/6)*Math.floor((A+4)/5)*16;case tJ:return Math.floor((e+5)/6)*Math.floor((A+5)/6)*16;case iJ:return Math.floor((e+7)/8)*Math.floor((A+4)/5)*16;case nJ:return Math.floor((e+7)/8)*Math.floor((A+5)/6)*16;case gJ:return Math.floor((e+7)/8)*Math.floor((A+7)/8)*16;case oJ:return Math.floor((e+9)/10)*Math.floor((A+4)/5)*16;case sJ:return Math.floor((e+9)/10)*Math.floor((A+5)/6)*16;case rJ: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 IJ:return Math.floor((e+11)/12)*Math.floor((A+9)/10)*16;case CJ:return Math.floor((e+11)/12)*Math.floor((A+11)/12)*16;case cJ:case lJ:case BJ:return Math.ceil(e/4)*Math.ceil(A/4)*16;case EJ:case QJ:return Math.ceil(e/4)*Math.ceil(A/4)*8;case uJ:case dJ:return Math.ceil(e/4)*Math.ceil(A/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function ECe(e){switch(e){case sc:case NW:return{byteLength:1,components:1};case TS:case RW:case iy:return{byteLength:2,components:1};case Jx:case Lx:return{byteLength:2,components:4};case aQ:case _x:case Ga:return{byteLength:4,components:1};case GW:case bW:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}class QCe{static contain(A,t){return cCe(A,t)}static cover(A,t){return lCe(A,t)}static fill(A){return BCe(A)}static getByteLength(A,t,i,n){return E4(A,t,i,n)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:nG}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=nG);/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */function VyA(){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 uCe(e){const A=new WeakMap;function t(s,r){const a=s.array,I=s.usage,c=a.byteLength,l=e.createBuffer();e.bindBuffer(r,l),e.bufferData(r,a,I),s.onUploadCallback();let B;if(a instanceof Float32Array)B=e.FLOAT;else if(typeof Float16Array<"u"&&a instanceof Float16Array)B=e.HALF_FLOAT;else if(a instanceof Uint16Array)s.isFloat16BufferAttribute?B=e.HALF_FLOAT:B=e.UNSIGNED_SHORT;else if(a instanceof Int16Array)B=e.SHORT;else if(a instanceof Uint32Array)B=e.UNSIGNED_INT;else if(a instanceof Int32Array)B=e.INT;else if(a instanceof Int8Array)B=e.BYTE;else if(a instanceof Uint8Array)B=e.UNSIGNED_BYTE;else if(a instanceof Uint8ClampedArray)B=e.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+a);return{buffer:l,type:B,bytesPerElement:a.BYTES_PER_ELEMENT,version:s.version,size:c}}function i(s,r,a){const I=r.array,c=r.updateRanges;if(e.bindBuffer(a,s),c.length===0)e.bufferSubData(a,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(a,h.start*I.BYTES_PER_ELEMENT,I,h.start,h.count)}r.clearUpdateRanges()}r.onUploadCallback()}function n(s){return s.isInterleavedBufferAttribute&&(s=s.data),A.get(s)}function g(s){s.isInterleavedBufferAttribute&&(s=s.data);const r=A.get(s);r&&(e.deleteBuffer(r.buffer),A.delete(s))}function o(s,r){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 a=A.get(s);if(a===void 0)A.set(s,t(s,r));else if(a.version<s.version){if(a.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(a.buffer,s,r),a.version=s.version}}return{get:n,remove:g,update:o}}var dCe=`#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,hCe=`#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`,pCe=`#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`,fCe=`#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,yCe=`#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`,DCe=`#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`,mCe=`#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`,SCe=`#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`,wCe=`#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`,kCe=`#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`,MCe=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`,NCe=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`,RCe=`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`,GCe=`#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`,bCe=`#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`,UCe=`#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`,vCe=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,KCe=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`,FCe=`#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`,_Ce=`#if defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#elif defined( USE_COLOR )
	diffuseColor.rgb *= vColor;
#endif`,JCe=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR )
	varying vec3 vColor;
#endif`,LCe=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	varying vec3 vColor;
#endif`,xCe=`#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`,TCe=`#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`,qCe=`#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`,YCe=`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`,HCe=`#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`,OCe=`#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,PCe=`#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
		emissiveColor = sRGBTransferEOTF( emissiveColor );
	#endif
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,jCe=`#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`,zCe="gl_FragColor = linearToOutputTexel( gl_FragColor );",ZCe=`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 );
}`,WCe=`#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`,VCe=`#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`,XCe=`#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`,$Ce=`#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`,Ace=`#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`,ece=`#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`,tce=`#ifdef USE_FOG
	varying float vFogDepth;
#endif`,ice=`#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`,nce=`#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`,gce=`#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
}`,oce=`#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`,sce=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,rce=`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`,ace=`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`,Ice=`#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`,Cce=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,cce=`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`,lce=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,Bce=`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`,Ece=`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`,Qce=`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 );
}`,uce=`
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`,dce=`#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`,hce=`#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`,pce=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,fce=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,yce=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,Dce=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,mce=`#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`,Sce=`#ifdef USE_MAP
	uniform sampler2D map;
#endif`,wce=`#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`,kce=`#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`,Mce=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`,Nce=`#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`,Rce=`#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`,Gce=`#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`,bce=`#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`,Uce=`#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`,vce=`#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`,Kce=`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;`,Fce=`#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`,_ce=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,Jce=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,Lce=`#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`,xce=`#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`,Tce=`#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,qce=`#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,Yce=`#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`,Hce=`#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`,Oce=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Pce=`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 );
}`,jce=`#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`,zce=`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;`,Zce=`#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,Wce=`#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`,Vce=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`,Xce=`#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`,$ce=`#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`,Ale=`#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`,ele=`#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`,tle=`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;
}`,ile=`#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,nle=`#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`,gle=`#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`,ole=`#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`,sle=`float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`,rle=`#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`,ale=`#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,Ile=`#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; }`,Cle=`#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`,cle=`#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`,lle=`#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`,Ble=`#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`,Ele=`#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`,Qle=`#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 ule=`varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,dle=`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>
}`,hle=`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`,ple=`#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>
}`,fle=`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`,yle=`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>
}`,Dle=`#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;
}`,mle=`#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
}`,Sle=`#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;
}`,wle=`#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 );
}`,kle=`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
}`,Mle=`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>
}`,Nle=`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>
}`,Rle=`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>
}`,Gle=`#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>
}`,ble=`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>
}`,Ule=`#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>
}`,vle=`#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>
}`,Kle=`#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;
}`,Fle=`#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>
}`,_le=`#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
}`,Jle=`#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
}`,Lle=`#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>
}`,xle=`#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>
}`,Tle=`#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
}`,qle=`#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>
}`,Yle=`#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>
}`,Hle=`#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>
}`,Ole=`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>
}`,Ple=`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>
}`,jle=`#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>
}`,zle=`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>
}`,Zle=`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>
}`,Wle=`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>
}`,In={alphahash_fragment:dCe,alphahash_pars_fragment:hCe,alphamap_fragment:pCe,alphamap_pars_fragment:fCe,alphatest_fragment:yCe,alphatest_pars_fragment:DCe,aomap_fragment:mCe,aomap_pars_fragment:SCe,batching_pars_vertex:wCe,batching_vertex:kCe,begin_vertex:MCe,beginnormal_vertex:NCe,bsdfs:RCe,iridescence_fragment:GCe,bumpmap_pars_fragment:bCe,clipping_planes_fragment:UCe,clipping_planes_pars_fragment:vCe,clipping_planes_pars_vertex:KCe,clipping_planes_vertex:FCe,color_fragment:_Ce,color_pars_fragment:JCe,color_pars_vertex:LCe,color_vertex:xCe,common:TCe,cube_uv_reflection_fragment:qCe,defaultnormal_vertex:YCe,displacementmap_pars_vertex:HCe,displacementmap_vertex:OCe,emissivemap_fragment:PCe,emissivemap_pars_fragment:jCe,colorspace_fragment:zCe,colorspace_pars_fragment:ZCe,envmap_fragment:WCe,envmap_common_pars_fragment:VCe,envmap_pars_fragment:XCe,envmap_pars_vertex:$Ce,envmap_physical_pars_fragment:Ice,envmap_vertex:Ace,fog_vertex:ece,fog_pars_vertex:tce,fog_fragment:ice,fog_pars_fragment:nce,gradientmap_pars_fragment:gce,lightmap_pars_fragment:oce,lights_lambert_fragment:sce,lights_lambert_pars_fragment:rce,lights_pars_begin:ace,lights_toon_fragment:Cce,lights_toon_pars_fragment:cce,lights_phong_fragment:lce,lights_phong_pars_fragment:Bce,lights_physical_fragment:Ece,lights_physical_pars_fragment:Qce,lights_fragment_begin:uce,lights_fragment_maps:dce,lights_fragment_end:hce,logdepthbuf_fragment:pce,logdepthbuf_pars_fragment:fce,logdepthbuf_pars_vertex:yce,logdepthbuf_vertex:Dce,map_fragment:mce,map_pars_fragment:Sce,map_particle_fragment:wce,map_particle_pars_fragment:kce,metalnessmap_fragment:Mce,metalnessmap_pars_fragment:Nce,morphinstance_vertex:Rce,morphcolor_vertex:Gce,morphnormal_vertex:bce,morphtarget_pars_vertex:Uce,morphtarget_vertex:vce,normal_fragment_begin:Kce,normal_fragment_maps:Fce,normal_pars_fragment:_ce,normal_pars_vertex:Jce,normal_vertex:Lce,normalmap_pars_fragment:xce,clearcoat_normal_fragment_begin:Tce,clearcoat_normal_fragment_maps:qce,clearcoat_pars_fragment:Yce,iridescence_pars_fragment:Hce,opaque_fragment:Oce,packing:Pce,premultiplied_alpha_fragment:jce,project_vertex:zce,dithering_fragment:Zce,dithering_pars_fragment:Wce,roughnessmap_fragment:Vce,roughnessmap_pars_fragment:Xce,shadowmap_pars_fragment:$ce,shadowmap_pars_vertex:Ale,shadowmap_vertex:ele,shadowmask_pars_fragment:tle,skinbase_vertex:ile,skinning_pars_vertex:nle,skinning_vertex:gle,skinnormal_vertex:ole,specularmap_fragment:sle,specularmap_pars_fragment:rle,tonemapping_fragment:ale,tonemapping_pars_fragment:Ile,transmission_fragment:Cle,transmission_pars_fragment:cle,uv_pars_fragment:lle,uv_pars_vertex:Ble,uv_vertex:Ele,worldpos_vertex:Qle,background_vert:ule,background_frag:dle,backgroundCube_vert:hle,backgroundCube_frag:ple,cube_vert:fle,cube_frag:yle,depth_vert:Dle,depth_frag:mle,distanceRGBA_vert:Sle,distanceRGBA_frag:wle,equirect_vert:kle,equirect_frag:Mle,linedashed_vert:Nle,linedashed_frag:Rle,meshbasic_vert:Gle,meshbasic_frag:ble,meshlambert_vert:Ule,meshlambert_frag:vle,meshmatcap_vert:Kle,meshmatcap_frag:Fle,meshnormal_vert:_le,meshnormal_frag:Jle,meshphong_vert:Lle,meshphong_frag:xle,meshphysical_vert:Tle,meshphysical_frag:qle,meshtoon_vert:Yle,meshtoon_frag:Hle,points_vert:Ole,points_frag:Ple,shadow_vert:jle,shadow_frag:zle,sprite_vert:Zle,sprite_frag:Wle},Pt={common:{diffuse:{value:new lt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new $i},alphaMap:{value:null},alphaMapTransform:{value:new $i},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new $i}},envmap:{envMap:{value:null},envMapRotation:{value:new $i},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new $i}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new $i}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new $i},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new $i},normalScale:{value:new It(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new $i},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new $i}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new $i}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new $i}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new lt(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 lt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new $i},alphaTest:{value:0},uvTransform:{value:new $i}},sprite:{diffuse:{value:new lt(16777215)},opacity:{value:1},center:{value:new It(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new $i},alphaMap:{value:null},alphaMapTransform:{value:new $i},alphaTest:{value:0}}},Jc={basic:{uniforms:Ba([Pt.common,Pt.specularmap,Pt.envmap,Pt.aomap,Pt.lightmap,Pt.fog]),vertexShader:In.meshbasic_vert,fragmentShader:In.meshbasic_frag},lambert:{uniforms:Ba([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 lt(0)}}]),vertexShader:In.meshlambert_vert,fragmentShader:In.meshlambert_frag},phong:{uniforms:Ba([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 lt(0)},specular:{value:new lt(1118481)},shininess:{value:30}}]),vertexShader:In.meshphong_vert,fragmentShader:In.meshphong_frag},standard:{uniforms:Ba([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 lt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:In.meshphysical_vert,fragmentShader:In.meshphysical_frag},toon:{uniforms:Ba([Pt.common,Pt.aomap,Pt.lightmap,Pt.emissivemap,Pt.bumpmap,Pt.normalmap,Pt.displacementmap,Pt.gradientmap,Pt.fog,Pt.lights,{emissive:{value:new lt(0)}}]),vertexShader:In.meshtoon_vert,fragmentShader:In.meshtoon_frag},matcap:{uniforms:Ba([Pt.common,Pt.bumpmap,Pt.normalmap,Pt.displacementmap,Pt.fog,{matcap:{value:null}}]),vertexShader:In.meshmatcap_vert,fragmentShader:In.meshmatcap_frag},points:{uniforms:Ba([Pt.points,Pt.fog]),vertexShader:In.points_vert,fragmentShader:In.points_frag},dashed:{uniforms:Ba([Pt.common,Pt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:In.linedashed_vert,fragmentShader:In.linedashed_frag},depth:{uniforms:Ba([Pt.common,Pt.displacementmap]),vertexShader:In.depth_vert,fragmentShader:In.depth_frag},normal:{uniforms:Ba([Pt.common,Pt.bumpmap,Pt.normalmap,Pt.displacementmap,{opacity:{value:1}}]),vertexShader:In.meshnormal_vert,fragmentShader:In.meshnormal_frag},sprite:{uniforms:Ba([Pt.sprite,Pt.fog]),vertexShader:In.sprite_vert,fragmentShader:In.sprite_frag},background:{uniforms:{uvTransform:{value:new $i},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:In.background_vert,fragmentShader:In.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new $i}},vertexShader:In.backgroundCube_vert,fragmentShader:In.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:In.cube_vert,fragmentShader:In.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:In.equirect_vert,fragmentShader:In.equirect_frag},distanceRGBA:{uniforms:Ba([Pt.common,Pt.displacementmap,{referencePosition:{value:new SA},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:In.distanceRGBA_vert,fragmentShader:In.distanceRGBA_frag},shadow:{uniforms:Ba([Pt.lights,Pt.fog,{color:{value:new lt(0)},opacity:{value:1}}]),vertexShader:In.shadow_vert,fragmentShader:In.shadow_frag}};Jc.physical={uniforms:Ba([Jc.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new $i},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new $i},clearcoatNormalScale:{value:new It(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new $i},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new $i},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new $i},sheen:{value:0},sheenColor:{value:new lt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new $i},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new $i},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new $i},transmissionSamplerSize:{value:new It},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new $i},attenuationDistance:{value:0},attenuationColor:{value:new lt(0)},specularColor:{value:new lt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new $i},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new $i},anisotropyVector:{value:new It},anisotropyMap:{value:null},anisotropyMapTransform:{value:new $i}}]),vertexShader:In.meshphysical_vert,fragmentShader:In.meshphysical_frag};const ZU={r:0,b:0,g:0},Gh=new or,Vle=new ii;function Xle(e,A,t,i,n,g,o){const s=new lt(0);let r=g===!0?0:1,a,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,r):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===_w)?(I===void 0&&(I=new hn(new gI(1,1,1),new rc({name:"BackgroundCubeMaterial",uniforms:zS(Jc.backgroundCube.uniforms),vertexShader:Jc.backgroundCube.vertexShader,fragmentShader:Jc.backgroundCube.fragmentShader,side:kr,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(Vle.makeRotationFromEuler(Gh)),I.material.toneMapped=Rn.getTransfer(S.colorSpace)!==hg,(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&&(a===void 0&&(a=new hn(new sB(2,2),new rc({name:"BackgroundMaterial",uniforms:zS(Jc.background.uniforms),vertexShader:Jc.background.vertexShader,fragmentShader:Jc.background.fragmentShader,side:Al,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),a.geometry.deleteAttribute("normal"),Object.defineProperty(a.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(a)),a.material.uniforms.t2D.value=S,a.material.uniforms.backgroundIntensity.value=D.backgroundIntensity,a.material.toneMapped=Rn.getTransfer(S.colorSpace)!==hg,S.matrixAutoUpdate===!0&&S.updateMatrix(),a.material.uniforms.uvTransform.value.copy(S.matrix),(c!==S||l!==S.version||B!==e.toneMapping)&&(a.material.needsUpdate=!0,c=S,l=S.version,B=e.toneMapping),a.layers.enableAll(),m.unshift(a,a.geometry,a.material,0,0,null))}function p(m,D){m.getRGB(ZU,CyA(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),a!==void 0&&(a.geometry.dispose(),a.material.dispose(),a=void 0)}return{getClearColor:function(){return s},setClearColor:function(m,D=1){s.set(m),r=D,p(s,r)},getClearAlpha:function(){return r},setClearAlpha:function(m){r=m,p(s,r)},render:h,addToRenderList:d,dispose:y}}function $le(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 T=!1;const v=c(K,_,b);g!==v&&(g=v,a(g.object)),T=B(w,K,_,J),T&&Q(w,K,_,J),J!==null&&A.update(J,e.ELEMENT_ARRAY_BUFFER),(T||o)&&(o=!1,D(w,b,_,K),J!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,A.get(J).buffer))}function r(){return e.createVertexArray()}function a(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 T=J[b.id];T===void 0&&(T={},J[b.id]=T);let v=T[K];return v===void 0&&(v=l(r()),T[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,T=b.attributes;let v=0;const U=_.getAttributes();for(const x in U)if(U[x].location>=0){const z=J[x];let Z=T[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={},T=b.attributes;let v=0;const U=_.getAttributes();for(const x in U)if(U[x].location>=0){let z=T[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,T,v){v===!0?e.vertexAttribIPointer(w,b,_,J,T):e.vertexAttribPointer(w,b,_,K,J,T)}function D(w,b,_,K){h();const J=K.attributes,T=_.getAttributes(),v=b.defaultAttributeValues;for(const U in T){const x=T[U];if(x.location>=0){let q=J[U];if(q===void 0&&(U==="instanceMatrix"&&w.instanceMatrix&&(q=w.instanceMatrix),U==="instanceColor"&&w.instanceColor&&(q=w.instanceColor)),q!==void 0){const z=q.normalized,Z=q.itemSize,eA=A.get(q);if(eA===void 0)continue;const aA=eA.buffer,sA=eA.type,pA=eA.bytesPerElement,gA=sA===e.INT||sA===e.UNSIGNED_INT||q.gpuType===_x;if(q.isInterleavedBufferAttribute){const yA=q.data,fA=yA.stride,RA=q.offset;if(yA.isInstancedInterleavedBuffer){for(let YA=0;YA<x.locationSize;YA++)p(x.location+YA,yA.meshPerAttribute);w.isInstancedMesh!==!0&&K._maxInstanceCount===void 0&&(K._maxInstanceCount=yA.meshPerAttribute*yA.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,fA*pA,(RA+Z/x.locationSize*YA)*pA,gA)}else{if(q.isInstancedBufferAttribute){for(let yA=0;yA<x.locationSize;yA++)p(x.location+yA,q.meshPerAttribute);w.isInstancedMesh!==!0&&K._maxInstanceCount===void 0&&(K._maxInstanceCount=q.meshPerAttribute*q.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,a(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 ABe(e,A,t){let i;function n(a){i=a}function g(a,I){e.drawArrays(i,a,I),t.update(I,i,1)}function o(a,I,c){c!==0&&(e.drawArraysInstanced(i,a,I,c),t.update(I,i,c))}function s(a,I,c){if(c===0)return;A.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,a,0,I,0,c);let B=0;for(let Q=0;Q<c;Q++)B+=I[Q];t.update(B,i,1)}function r(a,I,c,l){if(c===0)return;const B=A.get("WEBGL_multi_draw");if(B===null)for(let Q=0;Q<a.length;Q++)o(a[Q],I[Q],l[Q]);else{B.multiDrawArraysInstancedWEBGL(i,a,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=r}function eBe(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!==jr&&i.convert(N)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))}function s(N){const G=N===iy&&(A.has("EXT_color_buffer_half_float")||A.has("EXT_color_buffer_float"));return!(N!==sc&&i.convert(N)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&N!==Ga&&!G)}function r(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 a=t.precision!==void 0?t.precision:"highp";const I=r(a);I!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",I,"instead."),a=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:r,textureFormatReadable:o,textureTypeReadable:s,precision:a,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 tBe(e){const A=this;let t=null,i=0,n=!1,g=!1;const o=new eu,s=new $i,r={value:null,needsUpdate:!1};this.uniform=r,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):a();else{const y=g?0:i,m=y*4;let D=p.clippingState||null;r.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 a(){r.value!==t&&(r.value=t,r.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=r.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}r.value=d,r.needsUpdate=!0}return A.numPlanes=h,A.numIntersection=0,d}}function iBe(e){let A=new WeakMap;function t(o,s){return s===GN?o.mapping=rQ:s===bN&&(o.mapping=ud),o}function i(o){if(o&&o.isTexture){const s=o.mapping;if(s===GN||s===bN)if(A.has(o)){const r=A.get(o).texture;return t(r,o.mapping)}else{const r=o.image;if(r&&r.height>0){const a=new lyA(r.height);return a.fromEquirectangularTexture(e,o),A.set(o,a),o.addEventListener("dispose",n),t(a.texture,o.mapping)}else return null}}return o}function n(o){const s=o.target;s.removeEventListener("dispose",n);const r=A.get(s);r!==void 0&&(A.delete(s),r.dispose())}function g(){A=new WeakMap}return{get:i,dispose:g}}const am=4,qnA=[.125,.215,.35,.446,.526,.582],sp=20,xH=new Yd,YnA=new lt;let TH=null,qH=0,YH=0,HH=!1;const $h=(1+Math.sqrt(5))/2,dD=1/$h,HnA=[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)],nBe=new SA;class SJ{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=nBe}=g;TH=this._renderer.getRenderTarget(),qH=this._renderer.getActiveCubeFace(),YH=this._renderer.getActiveMipmapLevel(),HH=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(A,i,n,r,s),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(A,t=null){return this._fromTexture(A,t)}fromCubemap(A,t=null){return this._fromTexture(A,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=jnA(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=PnA(),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(TH,qH,YH),this._renderer.xr.enabled=HH,A.scissorTest=!1,WU(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),TH=this._renderer.getRenderTarget(),qH=this._renderer.getActiveCubeFace(),YH=this._renderer.getActiveMipmapLevel(),HH=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:_g,minFilter:_g,generateMipmaps:!1,type:iy,format:jr,colorSpace:Mr,depthBuffer:!1},n=OnA(A,t,i);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==A||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=OnA(A,t,i);const{_lodMax:g}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=gBe(g)),this._blurMaterial=oBe(g,A,t)}return n}_compileMaterial(A){const t=new hn(this._lodPlanes[0],A);this._renderer.compile(t,xH)}_sceneToCubeUV(A,t,i,n,g){const r=new zo(90,1,t,i),a=[1,-1,1,1,1,1],I=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,B=c.toneMapping;c.getClearColor(YnA),c.toneMapping=uB,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(n),c.clearDepth(),c.setRenderTarget(null));const h=new yg({name:"PMREM.Background",side:kr,depthWrite:!1,depthTest:!1}),d=new hn(new gI,h);let p=!1;const y=A.background;y?y.isColor&&(h.color.copy(y),A.background=null,p=!0):(h.color.copy(YnA),p=!0);for(let m=0;m<6;m++){const D=m%3;D===0?(r.up.set(0,a[m],0),r.position.set(g.x,g.y,g.z),r.lookAt(g.x+I[m],g.y,g.z)):D===1?(r.up.set(0,0,a[m]),r.position.set(g.x,g.y,g.z),r.lookAt(g.x,g.y+I[m],g.z)):(r.up.set(0,a[m],0),r.position.set(g.x,g.y,g.z),r.lookAt(g.x,g.y,g.z+I[m]));const S=this._cubeSize;WU(n,D*S,m>2?S:0,S,S),c.setRenderTarget(n),p&&c.render(d,r),c.render(A,r)}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=jnA()),this._cubemapMaterial.uniforms.flipEnvMap.value=A.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=PnA());const g=n?this._cubemapMaterial:this._equirectMaterial,o=new hn(this._lodPlanes[0],g),s=g.uniforms;s.envMap.value=A;const r=this._cubeSize;WU(t,0,0,3*r,2*r),i.setRenderTarget(t),i.render(o,xH)}_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=HnA[(n-g-1)%HnA.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 r=this._renderer,a=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const I=3,c=new hn(this._lodPlanes[n],a),l=a.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-am?n-m+am:0),k=4*(this._cubeSize-D);WU(t,S,k,3*D,2*D),r.setRenderTarget(t),r.render(c,xH)}}function gBe(e){const A=[],t=[],i=[];let n=e;const g=e-am+1+qnA.length;for(let o=0;o<g;o++){const s=Math.pow(2,n);t.push(s);let r=1/s;o>e-am?r=qnA[o-e+am-1]:o===0&&(r=0),i.push(r);const a=1/(s-2),I=-a,c=1+a,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 ki;S.setAttribute("position",new Yi(y,h)),S.setAttribute("uv",new Yi(m,d)),S.setAttribute("faceIndex",new Yi(D,p)),A.push(S),n>am&&n--}return{lodPlanes:A,sizeLods:t,sigmas:i}}function OnA(e,A,t){const i=new el(e,A,t);return i.texture.mapping=_w,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function WU(e,A,t,i,n){e.viewport.set(A,t,i,n),e.scissor.set(A,t,i,n)}function oBe(e,A,t){const i=new Float32Array(sp),n=new SA(0,1,0);return new rc({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:hV(),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:xE,depthTest:!1,depthWrite:!1})}function PnA(){return new rc({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:hV(),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:xE,depthTest:!1,depthWrite:!1})}function jnA(){return new rc({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:hV(),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:xE,depthTest:!1,depthWrite:!1})}function hV(){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 sBe(e){let A=new WeakMap,t=null;function i(s){if(s&&s.isTexture){const r=s.mapping,a=r===GN||r===bN,I=r===rQ||r===ud;if(a||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 SJ(e)),c=a?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 a&&B&&B.height>0||I&&B&&n(B)?(t===null&&(t=new SJ(e)),c=a?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 r=0;const a=6;for(let I=0;I<a;I++)s[I]!==void 0&&r++;return r===a}function g(s){const r=s.target;r.removeEventListener("dispose",g);const a=A.get(r);a!==void 0&&(A.delete(r),a.dispose())}function o(){A=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:i,dispose:o}}function rBe(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&&_N("THREE.WebGLRenderer: "+i+" extension not supported."),n}}}function aBe(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 r(c){const l=c.attributes;for(const B in l)A.update(l[B],e.ARRAY_BUFFER)}function a(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(syA(l)?YW:qW)(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&&a(c)}else a(c);return g.get(c)}return{get:s,update:r,getWireframeAttribute:I}}function IBe(e,A,t){let i;function n(l){i=l}let g,o;function s(l){g=l.type,o=l.bytesPerElement}function r(l,B){e.drawElements(i,B,g,l*o),t.update(B,i,1)}function a(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++)a(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=r,this.renderInstances=a,this.renderMultiDraw=I,this.renderMultiDrawInstances=c}function CBe(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 cBe(e,A,t){const i=new WeakMap,n=new $n;function g(o,s,r){const a=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 Hx(k,D,S,c);N.type=Ga,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 T=0;T<b.count;T++){const v=T*G;B===!0&&(n.fromBufferAttribute(b,T),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(_,T),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,T),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 It(D,S)},i.set(s,l),s.addEventListener("dispose",M)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)r.getUniforms().setValue(e,"morphTexture",o.morphTexture,t);else{let B=0;for(let h=0;h<a.length;h++)B+=a[h];const Q=s.morphTargetsRelative?1:1-B;r.getUniforms().setValue(e,"morphTargetBaseInfluence",Q),r.getUniforms().setValue(e,"morphTargetInfluences",a)}r.getUniforms().setValue(e,"morphTargetsTexture",l.texture,t),r.getUniforms().setValue(e,"morphTargetsTextureSize",l.size)}return{update:g}}function lBe(e,A,t,i){let n=new WeakMap;function g(r){const a=i.render.frame,I=r.geometry,c=A.get(r,I);if(n.get(c)!==a&&(A.update(c),n.set(c,a)),r.isInstancedMesh&&(r.hasEventListener("dispose",s)===!1&&r.addEventListener("dispose",s),n.get(r)!==a&&(t.update(r.instanceMatrix,e.ARRAY_BUFFER),r.instanceColor!==null&&t.update(r.instanceColor,e.ARRAY_BUFFER),n.set(r,a))),r.isSkinnedMesh){const l=r.skeleton;n.get(l)!==a&&(l.update(),n.set(l,a))}return c}function o(){n=new WeakMap}function s(r){const a=r.target;a.removeEventListener("dispose",s),t.remove(a.instanceMatrix),a.instanceColor!==null&&t.remove(a.instanceColor)}return{update:g,dispose:o}}const XyA=new Rg,znA=new Xx(1,1),$yA=new Hx,ADA=new Ox,eDA=new aG,ZnA=[],WnA=[],VnA=new Float32Array(16),XnA=new Float32Array(9),$nA=new Float32Array(4);function qw(e,A,t){const i=e[0];if(i<=0||i>0)return e;const n=A*t;let g=ZnA[n];if(g===void 0&&(g=new Float32Array(n),ZnA[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 Js(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 Ls(e,A){for(let t=0,i=A.length;t<i;t++)e[t]=A[t]}function BT(e,A){let t=WnA[A];t===void 0&&(t=new Int32Array(A),WnA[A]=t);for(let i=0;i!==A;++i)t[i]=e.allocateTextureUnit();return t}function BBe(e,A){const t=this.cache;t[0]!==A&&(e.uniform1f(this.addr,A),t[0]=A)}function EBe(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(Js(t,A))return;e.uniform2fv(this.addr,A),Ls(t,A)}}function QBe(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(Js(t,A))return;e.uniform3fv(this.addr,A),Ls(t,A)}}function uBe(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(Js(t,A))return;e.uniform4fv(this.addr,A),Ls(t,A)}}function dBe(e,A){const t=this.cache,i=A.elements;if(i===void 0){if(Js(t,A))return;e.uniformMatrix2fv(this.addr,!1,A),Ls(t,A)}else{if(Js(t,i))return;$nA.set(i),e.uniformMatrix2fv(this.addr,!1,$nA),Ls(t,i)}}function hBe(e,A){const t=this.cache,i=A.elements;if(i===void 0){if(Js(t,A))return;e.uniformMatrix3fv(this.addr,!1,A),Ls(t,A)}else{if(Js(t,i))return;XnA.set(i),e.uniformMatrix3fv(this.addr,!1,XnA),Ls(t,i)}}function pBe(e,A){const t=this.cache,i=A.elements;if(i===void 0){if(Js(t,A))return;e.uniformMatrix4fv(this.addr,!1,A),Ls(t,A)}else{if(Js(t,i))return;VnA.set(i),e.uniformMatrix4fv(this.addr,!1,VnA),Ls(t,i)}}function fBe(e,A){const t=this.cache;t[0]!==A&&(e.uniform1i(this.addr,A),t[0]=A)}function yBe(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(Js(t,A))return;e.uniform2iv(this.addr,A),Ls(t,A)}}function DBe(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(Js(t,A))return;e.uniform3iv(this.addr,A),Ls(t,A)}}function mBe(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(Js(t,A))return;e.uniform4iv(this.addr,A),Ls(t,A)}}function SBe(e,A){const t=this.cache;t[0]!==A&&(e.uniform1ui(this.addr,A),t[0]=A)}function wBe(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(Js(t,A))return;e.uniform2uiv(this.addr,A),Ls(t,A)}}function kBe(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(Js(t,A))return;e.uniform3uiv(this.addr,A),Ls(t,A)}}function MBe(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(Js(t,A))return;e.uniform4uiv(this.addr,A),Ls(t,A)}}function NBe(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?(znA.compareFunction=LW,g=znA):g=XyA,t.setTexture2D(A||g,n)}function RBe(e,A,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),t.setTexture3D(A||ADA,n)}function GBe(e,A,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),t.setTextureCube(A||eDA,n)}function bBe(e,A,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),t.setTexture2DArray(A||$yA,n)}function UBe(e){switch(e){case 5126:return BBe;case 35664:return EBe;case 35665:return QBe;case 35666:return uBe;case 35674:return dBe;case 35675:return hBe;case 35676:return pBe;case 5124:case 35670:return fBe;case 35667:case 35671:return yBe;case 35668:case 35672:return DBe;case 35669:case 35673:return mBe;case 5125:return SBe;case 36294:return wBe;case 36295:return kBe;case 36296:return MBe;case 35678:case 36198:case 36298:case 36306:case 35682:return NBe;case 35679:case 36299:case 36307:return RBe;case 35680:case 36300:case 36308:case 36293:return GBe;case 36289:case 36303:case 36311:case 36292:return bBe}}function vBe(e,A){e.uniform1fv(this.addr,A)}function KBe(e,A){const t=qw(A,this.size,2);e.uniform2fv(this.addr,t)}function FBe(e,A){const t=qw(A,this.size,3);e.uniform3fv(this.addr,t)}function _Be(e,A){const t=qw(A,this.size,4);e.uniform4fv(this.addr,t)}function JBe(e,A){const t=qw(A,this.size,4);e.uniformMatrix2fv(this.addr,!1,t)}function LBe(e,A){const t=qw(A,this.size,9);e.uniformMatrix3fv(this.addr,!1,t)}function xBe(e,A){const t=qw(A,this.size,16);e.uniformMatrix4fv(this.addr,!1,t)}function TBe(e,A){e.uniform1iv(this.addr,A)}function qBe(e,A){e.uniform2iv(this.addr,A)}function YBe(e,A){e.uniform3iv(this.addr,A)}function HBe(e,A){e.uniform4iv(this.addr,A)}function OBe(e,A){e.uniform1uiv(this.addr,A)}function PBe(e,A){e.uniform2uiv(this.addr,A)}function jBe(e,A){e.uniform3uiv(this.addr,A)}function zBe(e,A){e.uniform4uiv(this.addr,A)}function ZBe(e,A,t){const i=this.cache,n=A.length,g=BT(t,n);Js(i,g)||(e.uniform1iv(this.addr,g),Ls(i,g));for(let o=0;o!==n;++o)t.setTexture2D(A[o]||XyA,g[o])}function WBe(e,A,t){const i=this.cache,n=A.length,g=BT(t,n);Js(i,g)||(e.uniform1iv(this.addr,g),Ls(i,g));for(let o=0;o!==n;++o)t.setTexture3D(A[o]||ADA,g[o])}function VBe(e,A,t){const i=this.cache,n=A.length,g=BT(t,n);Js(i,g)||(e.uniform1iv(this.addr,g),Ls(i,g));for(let o=0;o!==n;++o)t.setTextureCube(A[o]||eDA,g[o])}function XBe(e,A,t){const i=this.cache,n=A.length,g=BT(t,n);Js(i,g)||(e.uniform1iv(this.addr,g),Ls(i,g));for(let o=0;o!==n;++o)t.setTexture2DArray(A[o]||$yA,g[o])}function $Be(e){switch(e){case 5126:return vBe;case 35664:return KBe;case 35665:return FBe;case 35666:return _Be;case 35674:return JBe;case 35675:return LBe;case 35676:return xBe;case 5124:case 35670:return TBe;case 35667:case 35671:return qBe;case 35668:case 35672:return YBe;case 35669:case 35673:return HBe;case 5125:return OBe;case 36294:return PBe;case 36295:return jBe;case 36296:return zBe;case 35678:case 36198:case 36298:case 36306:case 35682:return ZBe;case 35679:case 36299:case 36307:return WBe;case 35680:case 36300:case 36308:case 36293:return VBe;case 36289:case 36303:case 36311:case 36292:return XBe}}class AEe{constructor(A,t,i){this.id=A,this.addr=i,this.cache=[],this.type=t.type,this.setValue=UBe(t.type)}}class eEe{constructor(A,t,i){this.id=A,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=$Be(t.type)}}class tEe{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 OH=/(\w+)(\])?(\[|\.)?/g;function AgA(e,A){e.seq.push(A),e.map[A.id]=A}function iEe(e,A,t){const i=e.name,n=i.length;for(OH.lastIndex=0;;){const g=OH.exec(i),o=OH.lastIndex;let s=g[1];const r=g[2]==="]",a=g[3];if(r&&(s=s|0),a===void 0||a==="["&&o+2===n){AgA(t,a===void 0?new AEe(s,e,A):new eEe(s,e,A));break}else{let c=t.map[s];c===void 0&&(c=new tEe(s),AgA(t,c)),t=c}}}class FK{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);iEe(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],r=i[s.id];r.needsUpdate!==!1&&s.setValue(A,r.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 egA(e,A,t){const i=e.createShader(A);return e.shaderSource(i,t),e.compileShader(i),i}const nEe=37297;let gEe=0;function oEe(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 tgA=new $i;function sEe(e){Rn._getMatrix(tgA,Rn.workingColorSpace,e);const A=`mat3( ${tgA.elements.map(t=>t.toFixed(4))} )`;switch(Rn.getTransfer(e)){case vN:return[A,"LinearTransferOETF"];case hg:return[A,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",e),[A,"LinearTransferOETF"]}}function igA(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+`

`+oEe(e.getShaderSource(A),s)}else return g}function rEe(e,A){const t=sEe(A);return[`vec4 ${e}( vec4 value ) {`,`	return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(`
`)}function aEe(e,A){let t;switch(A){case qfA:t="Linear";break;case YfA:t="Reinhard";break;case HfA:t="Cineon";break;case ty:t="ACESFilmic";break;case PfA:t="AgX";break;case jfA:t="Neutral";break;case OfA:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",A),t="Linear"}return"vec3 "+e+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const VU=new SA;function IEe(){Rn.getLuminanceCoefficients(VU);const e=VU.x.toFixed(4),A=VU.y.toFixed(4),t=VU.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",`	const vec3 weights = vec3( ${e}, ${A}, ${t} );`,"	return dot( weights, rgb );","}"].join(`
`)}function CEe(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Uk).join(`
`)}function cEe(e){const A=[];for(const t in e){const i=e[t];i!==!1&&A.push("#define "+t+" "+i)}return A.join(`
`)}function lEe(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 Uk(e){return e!==""}function ngA(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 ggA(e,A){return e.replace(/NUM_CLIPPING_PLANES/g,A.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,A.numClippingPlanes-A.numClipIntersection)}const BEe=/^[ \t]*#include +<([\w\d./]+)>/gm;function Q4(e){return e.replace(BEe,QEe)}const EEe=new Map;function QEe(e,A){let t=In[A];if(t===void 0){const i=EEe.get(A);if(i!==void 0)t=In[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 Q4(t)}const uEe=/#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 ogA(e){return e.replace(uEe,dEe)}function dEe(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 sgA(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 hEe(e){let A="SHADOWMAP_TYPE_BASIC";return e.shadowMapType===Kx?A="SHADOWMAP_TYPE_PCF":e.shadowMapType===mM?A="SHADOWMAP_TYPE_PCF_SOFT":e.shadowMapType===Nc&&(A="SHADOWMAP_TYPE_VSM"),A}function pEe(e){let A="ENVMAP_TYPE_CUBE";if(e.envMap)switch(e.envMapMode){case rQ:case ud:A="ENVMAP_TYPE_CUBE";break;case _w:A="ENVMAP_TYPE_CUBE_UV";break}return A}function fEe(e){let A="ENVMAP_MODE_REFLECTION";if(e.envMap)switch(e.envMapMode){case ud:A="ENVMAP_MODE_REFRACTION";break}return A}function yEe(e){let A="ENVMAP_BLENDING_NONE";if(e.envMap)switch(e.combine){case gG:A="ENVMAP_BLENDING_MULTIPLY";break;case xfA:A="ENVMAP_BLENDING_MIX";break;case TfA:A="ENVMAP_BLENDING_ADD";break}return A}function DEe(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 mEe(e,A,t,i){const n=e.getContext(),g=t.defines;let o=t.vertexShader,s=t.fragmentShader;const r=hEe(t),a=pEe(t),I=fEe(t),c=yEe(t),l=DEe(t),B=CEe(t),Q=cEe(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(Uk).join(`
`),d.length>0&&(d+=`
`),p=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,Q].filter(Uk).join(`
`),p.length>0&&(p+=`
`)):(d=[sgA(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 "+r:"",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(Uk).join(`
`),p=[sgA(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 "+a:"",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 "+r:"",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!==uB?"#define TONE_MAPPING":"",t.toneMapping!==uB?In.tonemapping_pars_fragment:"",t.toneMapping!==uB?aEe("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",In.colorspace_pars_fragment,rEe("linearToOutputTexel",t.outputColorSpace),IEe(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
`].filter(Uk).join(`
`)),o=Q4(o),o=ngA(o,t),o=ggA(o,t),s=Q4(s),s=ngA(s,t),s=ggA(s,t),o=ogA(o),s=ogA(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===a4?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===a4?"":"#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=egA(n,n.VERTEX_SHADER,m),k=egA(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)||"",T=_.trim(),v=K.trim(),U=J.trim();let x=!0,q=!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=igA(n,S,"vertex"),Z=igA(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: `+T+`
`+z+`
`+Z)}else T!==""?console.warn("THREE.WebGLProgram: Program Info Log:",T):(v===""||U==="")&&(q=!1);q&&(b.diagnostics={runnable:x,programLog:T,vertexShader:{log:v,prefix:d},fragmentShader:{log:U,prefix:p}})}n.deleteShader(S),n.deleteShader(k),G=new FK(n,h),M=lEe(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,nEe)),w},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(h),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=gEe++,this.cacheKey=A,this.usedTimes=1,this.program=h,this.vertexShader=S,this.fragmentShader=k,this}let SEe=0;class wEe{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 kEe(A),t.set(A,i)),i}}class kEe{constructor(A){this.id=SEe++,this.code=A,this.usedTimes=0}}function MEe(e,A,t,i,n,g,o){const s=new jS,r=new wEe,a=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 a.add(M),M===0?"uv":`uv${M}`}function d(M,w,b,_,K){const J=_.fog,T=K.geometry,v=M.isMeshStandardMaterial?_.environment:null,U=(M.isMeshStandardMaterial?t:A).get(M.envMap||v),x=U&&U.mapping===_w?U.image.height:null,q=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=T.morphAttributes.position||T.morphAttributes.normal||T.morphAttributes.color,Z=z!==void 0?z.length:0;let eA=0;T.morphAttributes.position!==void 0&&(eA=1),T.morphAttributes.normal!==void 0&&(eA=2),T.morphAttributes.color!==void 0&&(eA=3);let aA,sA,pA,gA;if(q){const Ne=Jc[q];aA=Ne.vertexShader,sA=Ne.fragmentShader}else aA=M.vertexShader,sA=M.fragmentShader,r.update(M),pA=r.getVertexShaderID(M),gA=r.getFragmentShaderID(M);const yA=e.getRenderTarget(),fA=e.state.buffers.depth.getReversed(),RA=K.isInstancedMesh===!0,YA=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,CA=!!M.emissiveMap,cA=!!M.metalnessMap,_A=!!M.roughnessMap,uA=M.anisotropy>0,X=M.clearcoat>0,O=M.dispersion>0,lA=M.iridescence>0,wA=M.sheen>0,xA=M.transmission>0,HA=uA&&!!M.anisotropyMap,zA=X&&!!M.clearcoatMap,ne=X&&!!M.clearcoatNormalMap,ye=X&&!!M.clearcoatRoughnessMap,Ee=lA&&!!M.iridescenceMap,NA=lA&&!!M.iridescenceThicknessMap,QA=wA&&!!M.sheenColorMap,PA=wA&&!!M.sheenRoughnessMap,VA=!!M.specularMap,KA=!!M.specularColorMap,Ie=!!M.specularIntensityMap,DA=xA&&!!M.transmissionMap,IA=xA&&!!M.thicknessMap,EA=!!M.gradientMap,j=!!M.alphaMap,dA=M.alphaTest>0,hA=!!M.alphaHash,UA=!!M.extensions;let TA=uB;M.toneMapped&&(yA===null||yA.isXRRenderTarget===!0)&&(TA=e.toneMapping);const se={shaderID:q,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:YA,batchingColor:YA&&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:Mr,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:CA,normalMapObjectSpace:iA&&M.normalMapType===XfA,normalMapTangentSpace:iA&&M.normalMapType===Ld,metalnessMap:cA,roughnessMap:_A,anisotropy:uA,anisotropyMap:HA,clearcoat:X,clearcoatMap:zA,clearcoatNormalMap:ne,clearcoatRoughnessMap:ye,dispersion:O,iridescence:lA,iridescenceMap:Ee,iridescenceThicknessMap:NA,sheen:wA,sheenColorMap:QA,sheenRoughnessMap:PA,specularMap:VA,specularColorMap:KA,specularIntensityMap:Ie,transmission:xA,transmissionMap:DA,thicknessMap:IA,gradientMap:EA,opaque:M.transparent===!1&&M.blending===Yp&&M.alphaToCoverage===!1,alphaMap:j,alphaTest:dA,alphaHash:hA,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:CA&&h(M.emissiveMap.channel),metalnessMapUv:cA&&h(M.metalnessMap.channel),roughnessMapUv:_A&&h(M.roughnessMap.channel),anisotropyMapUv:HA&&h(M.anisotropyMap.channel),clearcoatMapUv:zA&&h(M.clearcoatMap.channel),clearcoatNormalMapUv:ne&&h(M.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ye&&h(M.clearcoatRoughnessMap.channel),iridescenceMapUv:Ee&&h(M.iridescenceMap.channel),iridescenceThicknessMapUv:NA&&h(M.iridescenceThicknessMap.channel),sheenColorMapUv:QA&&h(M.sheenColorMap.channel),sheenRoughnessMapUv:PA&&h(M.sheenRoughnessMap.channel),specularMapUv:VA&&h(M.specularMap.channel),specularColorMapUv:KA&&h(M.specularColorMap.channel),specularIntensityMapUv:Ie&&h(M.specularIntensityMap.channel),transmissionMapUv:DA&&h(M.transmissionMap.channel),thicknessMapUv:IA&&h(M.thicknessMap.channel),alphaMapUv:j&&h(M.alphaMap.channel),vertexTangents:!!T.attributes.tangent&&(iA||uA),vertexColors:M.vertexColors,vertexAlphas:M.vertexColors===!0&&!!T.attributes.color&&T.attributes.color.itemSize===4,pointsUvs:K.isPoints===!0&&!!T.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:T.morphAttributes.position!==void 0,morphNormals:T.morphAttributes.normal!==void 0,morphColors:T.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&&Rn.getTransfer(M.map.colorSpace)===hg,decodeVideoTextureEmissive:CA&&M.emissiveMap.isVideoTexture===!0&&Rn.getTransfer(M.emissiveMap.colorSpace)===hg,premultipliedAlpha:M.premultipliedAlpha,doubleSided:M.side===Xa,flipSided:M.side===kr,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||YA)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:M.customProgramCacheKey()};return se.vertexUv1s=a.has(1),se.vertexUv2s=a.has(2),se.vertexUv3s=a.has(3),a.clear(),se}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 _=Jc[w];b=HW.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 mEe(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){r.remove(M)}function G(){r.dispose()}return{getParameters:d,getProgramCacheKey:p,getUniforms:D,acquireProgram:S,releaseProgram:k,releaseShaderCache:N,programs:I,dispose:G}}function NEe(){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,r){e.get(o)[s]=r}function g(){e=new WeakMap}return{has:A,get:t,remove:i,update:n,dispose:g}}function REe(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 rgA(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 agA(){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 r(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 a(c,l){t.length>1&&t.sort(c||REe),i.length>1&&i.sort(l||rgA),n.length>1&&n.sort(l||rgA)}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:r,finish:I,sort:a}}function GEe(){let e=new WeakMap;function A(i,n){const g=e.get(i);let o;return g===void 0?(o=new agA,e.set(i,[o])):n>=g.length?(o=new agA,g.push(o)):o=g[n],o}function t(){e=new WeakMap}return{get:A,dispose:t}}function bEe(){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 lt};break;case"SpotLight":t={position:new SA,direction:new SA,color:new lt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new SA,color:new lt,distance:0,decay:0};break;case"HemisphereLight":t={direction:new SA,skyColor:new lt,groundColor:new lt};break;case"RectAreaLight":t={color:new lt,position:new SA,halfWidth:new SA,halfHeight:new SA};break}return e[A.id]=t,t}}}function UEe(){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 It};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[A.id]=t,t}}}let vEe=0;function KEe(e,A){return(A.castShadow?2:0)-(e.castShadow?2:0)+(A.map?1:0)-(e.map?1:0)}function FEe(e){const A=new bEe,t=UEe(),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 a=0;a<9;a++)i.probe.push(new SA);const n=new SA,g=new ii,o=new ii;function s(a){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;a.sort(KEe);for(let M=0,w=a.length;M<w;M++){const b=a[M],_=b.color,K=b.intensity,J=b.distance,T=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]=T,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]=T,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]=T,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=vEe++)}function r(a,I){let c=0,l=0,B=0,Q=0,h=0;const d=I.matrixWorldInverse;for(let p=0,y=a.length;p<y;p++){const m=a[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:r,state:i}}function IgA(e){const A=new FEe(e),t=[],i=[];function n(I){a.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 r(I){A.setupView(t,I)}const a={lightsArray:t,shadowsArray:i,camera:null,lights:A,transmissionRenderTarget:{}};return{init:n,state:a,setupLights:s,setupLightsView:r,pushLight:g,pushShadow:o}}function _Ee(e){let A=new WeakMap;function t(n,g=0){const o=A.get(n);let s;return o===void 0?(s=new IgA(e),A.set(n,[s])):g>=o.length?(s=new IgA(e),o.push(s)):s=o[g],s}function i(){A=new WeakMap}return{get:t,dispose:i}}const JEe=`void main() {
	gl_Position = vec4( position, 1.0 );
}`,LEe=`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 xEe(e,A,t){let i=new Tw;const n=new It,g=new It,o=new $n,s=new eV({depthPacking:VfA}),r=new tV,a={},I=t.maxTextureSize,c={[Al]:kr,[kr]:Al,[Xa]:Xa},l=new rc({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new It},radius:{value:4}},vertexShader:JEe,fragmentShader:LEe}),B=l.clone();B.defines.HORIZONTAL_PASS=1;const Q=new ki;Q.setAttribute("position",new Yi(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const h=new hn(Q,l),d=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Kx;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(xE),_.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!==Nc&&this.type===Nc,J=p===Nc&&this.type!==Nc;for(let T=0,v=k.length;T<v;T++){const U=k[T],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 q=x.getFrameExtents();if(n.multiply(q),g.copy(x.mapSize),(n.x>I||n.y>I)&&(n.x>I&&(g.x=Math.floor(I/q.x),n.x=g.x*q.x,x.mapSize.x=g.x),n.y>I&&(g.y=Math.floor(I/q.y),n.y=g.y*q.y,x.mapSize.y=g.y)),x.map===null||K===!0||J===!0){const Z=this.type!==Nc?{minFilter:Ds,magFilter:Ds}:{};x.map!==null&&x.map.dispose(),x.map=new el(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===Nc&&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 el(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?r: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=a[_];J===void 0&&(J={},a[_]=J);let T=J[K];T===void 0&&(T=w.clone(),J[K]=T,N.addEventListener("dispose",S)),w=T}if(w.visible=N.visible,w.wireframe=N.wireframe,M===Nc?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===Nc)&&(!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 T=K.groups;for(let v=0,U=T.length;v<U;v++){const x=T[v],q=J[x.materialIndex];if(q&&q.visible){const z=m(k,q,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 T=m(k,J,M,w);k.onBeforeShadow(e,k,N,G,K,T,null),e.renderBufferDirect(G,null,K,T,k,null),k.onAfterShadow(e,k,N,G,K,T,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 a){const M=a[G],w=k.target.uuid;w in M&&(M[w].dispose(),delete M[w])}}}const TEe={[J_]:L_,[x_]:Y_,[T_]:H_,[pf]:q_,[L_]:J_,[Y_]:x_,[H_]:T_,[q_]:pf};function qEe(e,A){function t(){let DA=!1;const IA=new $n;let EA=null;const j=new $n(0,0,0,0);return{setMask:function(dA){EA!==dA&&!DA&&(e.colorMask(dA,dA,dA,dA),EA=dA)},setLocked:function(dA){DA=dA},setClear:function(dA,hA,UA,TA,se){se===!0&&(dA*=TA,hA*=TA,UA*=TA),IA.set(dA,hA,UA,TA),j.equals(IA)===!1&&(e.clearColor(dA,hA,UA,TA),j.copy(IA))},reset:function(){DA=!1,EA=null,j.set(-1,0,0,0)}}}function i(){let DA=!1,IA=!1,EA=null,j=null,dA=null;return{setReversed:function(hA){if(IA!==hA){const UA=A.get("EXT_clip_control");hA?UA.clipControlEXT(UA.LOWER_LEFT_EXT,UA.ZERO_TO_ONE_EXT):UA.clipControlEXT(UA.LOWER_LEFT_EXT,UA.NEGATIVE_ONE_TO_ONE_EXT),IA=hA;const TA=dA;dA=null,this.setClear(TA)}},getReversed:function(){return IA},setTest:function(hA){hA?yA(e.DEPTH_TEST):fA(e.DEPTH_TEST)},setMask:function(hA){EA!==hA&&!DA&&(e.depthMask(hA),EA=hA)},setFunc:function(hA){if(IA&&(hA=TEe[hA]),j!==hA){switch(hA){case J_:e.depthFunc(e.NEVER);break;case L_:e.depthFunc(e.ALWAYS);break;case x_:e.depthFunc(e.LESS);break;case pf:e.depthFunc(e.LEQUAL);break;case T_:e.depthFunc(e.EQUAL);break;case q_:e.depthFunc(e.GEQUAL);break;case Y_:e.depthFunc(e.GREATER);break;case H_:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}j=hA}},setLocked:function(hA){DA=hA},setClear:function(hA){dA!==hA&&(IA&&(hA=1-hA),e.clearDepth(hA),dA=hA)},reset:function(){DA=!1,EA=null,j=null,dA=null,IA=!1}}}function n(){let DA=!1,IA=null,EA=null,j=null,dA=null,hA=null,UA=null,TA=null,se=null;return{setTest:function(Ne){DA||(Ne?yA(e.STENCIL_TEST):fA(e.STENCIL_TEST))},setMask:function(Ne){IA!==Ne&&!DA&&(e.stencilMask(Ne),IA=Ne)},setFunc:function(Ne,Ke,At){(EA!==Ne||j!==Ke||dA!==At)&&(e.stencilFunc(Ne,Ke,At),EA=Ne,j=Ke,dA=At)},setOp:function(Ne,Ke,At){(hA!==Ne||UA!==Ke||TA!==At)&&(e.stencilOp(Ne,Ke,At),hA=Ne,UA=Ke,TA=At)},setLocked:function(Ne){DA=Ne},setClear:function(Ne){se!==Ne&&(e.clearStencil(Ne),se=Ne)},reset:function(){DA=!1,IA=null,EA=null,j=null,dA=null,hA=null,UA=null,TA=null,se=null}}}const g=new t,o=new i,s=new n,r=new WeakMap,a=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 lt(0,0,0),G=0,M=!1,w=null,b=null,_=null,K=null,J=null;const T=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 q=null,z={};const Z=e.getParameter(e.SCISSOR_BOX),eA=e.getParameter(e.VIEWPORT),aA=new $n().fromArray(Z),sA=new $n().fromArray(eA);function pA(DA,IA,EA,j){const dA=new Uint8Array(4),hA=e.createTexture();e.bindTexture(DA,hA),e.texParameteri(DA,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(DA,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let UA=0;UA<EA;UA++)DA===e.TEXTURE_3D||DA===e.TEXTURE_2D_ARRAY?e.texImage3D(IA,0,e.RGBA,1,1,j,0,e.RGBA,e.UNSIGNED_BYTE,dA):e.texImage2D(IA+UA,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,dA);return hA}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(n4),yA(e.CULL_FACE),H(xE);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,IA){return c[DA]!==IA?(e.bindFramebuffer(DA,IA),c[DA]=IA,DA===e.DRAW_FRAMEBUFFER&&(c[e.FRAMEBUFFER]=IA),DA===e.FRAMEBUFFER&&(c[e.DRAW_FRAMEBUFFER]=IA),!0):!1}function YA(DA,IA){let EA=B,j=!1;if(DA){EA=l.get(IA),EA===void 0&&(EA=[],l.set(IA,EA));const dA=DA.textures;if(EA.length!==dA.length||EA[0]!==e.COLOR_ATTACHMENT0){for(let hA=0,UA=dA.length;hA<UA;hA++)EA[hA]=e.COLOR_ATTACHMENT0+hA;EA.length=dA.length,j=!0}}else EA[0]!==e.BACK&&(EA[0]=e.BACK,j=!0);j&&e.drawBuffers(EA)}function W(DA){return Q!==DA?(e.useProgram(DA),Q=DA,!0):!1}const $={[au]:e.FUNC_ADD,[DfA]:e.FUNC_SUBTRACT,[mfA]:e.FUNC_REVERSE_SUBTRACT};$[SfA]=e.MIN,$[wfA]=e.MAX;const L={[kfA]:e.ZERO,[MfA]:e.ONE,[NfA]:e.SRC_COLOR,[F_]:e.SRC_ALPHA,[KfA]:e.SRC_ALPHA_SATURATE,[UfA]:e.DST_COLOR,[GfA]:e.DST_ALPHA,[RfA]:e.ONE_MINUS_SRC_COLOR,[__]:e.ONE_MINUS_SRC_ALPHA,[vfA]:e.ONE_MINUS_DST_COLOR,[bfA]:e.ONE_MINUS_DST_ALPHA,[FfA]:e.CONSTANT_COLOR,[_fA]:e.ONE_MINUS_CONSTANT_COLOR,[JfA]:e.CONSTANT_ALPHA,[LfA]:e.ONE_MINUS_CONSTANT_ALPHA};function H(DA,IA,EA,j,dA,hA,UA,TA,se,Ne){if(DA===xE){h===!0&&(fA(e.BLEND),h=!1);return}if(h===!1&&(yA(e.BLEND),h=!0),DA!==yfA){if(DA!==d||Ne!==M){if((p!==au||D!==au)&&(e.blendEquation(e.FUNC_ADD),p=au,D=au),Ne)switch(DA){case Yp:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case Vg:e.blendFunc(e.ONE,e.ONE);break;case g4:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case o4: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 Vg:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case g4:console.error("THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case o4: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=Ne}return}dA=dA||IA,hA=hA||EA,UA=UA||j,(IA!==p||dA!==D)&&(e.blendEquationSeparate($[IA],$[dA]),p=IA,D=dA),(EA!==y||j!==m||hA!==S||UA!==k)&&(e.blendFuncSeparate(L[EA],L[j],L[hA],L[UA]),y=EA,m=j,S=hA,k=UA),(TA.equals(N)===!1||se!==G)&&(e.blendColor(TA.r,TA.g,TA.b,se),N.copy(TA),G=se),d=DA,M=!1}function P(DA,IA){DA.side===Xa?fA(e.CULL_FACE):yA(e.CULL_FACE);let EA=DA.side===kr;IA&&(EA=!EA),tA(EA),DA.blending===Yp&&DA.transparent===!1?H(xE):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)),CA(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!==hfA?(yA(e.CULL_FACE),DA!==b&&(DA===n4?e.cullFace(e.BACK):DA===pfA?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 CA(DA,IA,EA){DA?(yA(e.POLYGON_OFFSET_FILL),(K!==IA||J!==EA)&&(e.polygonOffset(IA,EA),K=IA,J=EA)):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+T-1),q!==DA&&(e.activeTexture(DA),q=DA)}function uA(DA,IA,EA){EA===void 0&&(q===null?EA=e.TEXTURE0+T-1:EA=q);let j=z[EA];j===void 0&&(j={type:void 0,texture:void 0},z[EA]=j),(j.type!==DA||j.texture!==IA)&&(q!==EA&&(e.activeTexture(EA),q=EA),e.bindTexture(DA,IA||gA[DA]),j.type=DA,j.texture=IA)}function X(){const DA=z[q];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 lA(){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 HA(){try{e.compressedTexSubImage2D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function zA(){try{e.compressedTexSubImage3D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function ne(){try{e.texStorage2D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function ye(){try{e.texStorage3D(...arguments)}catch(DA){console.error("THREE.WebGLState:",DA)}}function Ee(){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 QA(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 VA(DA,IA){let EA=a.get(IA);EA===void 0&&(EA=new WeakMap,a.set(IA,EA));let j=EA.get(DA);j===void 0&&(j=e.getUniformBlockIndex(IA,DA.name),EA.set(DA,j))}function KA(DA,IA){const j=a.get(IA).get(DA);r.get(IA)!==j&&(e.uniformBlockBinding(IA,j,DA.__bindingPointIndex),r.set(IA,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={},q=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 lt(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:YA,useProgram:W,setBlending:H,setMaterial:P,setFlipSided:tA,setCullFace:iA,setLineWidth:oA,setPolygonOffset:CA,setScissorTest:cA,activeTexture:_A,bindTexture:uA,unbindTexture:X,compressedTexImage2D:O,compressedTexImage3D:lA,texImage2D:Ee,texImage3D:NA,updateUBOMapping:VA,uniformBlockBinding:KA,texStorage2D:ne,texStorage3D:ye,texSubImage2D:wA,texSubImage3D:xA,compressedTexSubImage2D:HA,compressedTexSubImage3D:zA,scissor:QA,viewport:PA,reset:Ie}}function YEe(e,A,t,i,n,g,o){const s=A.has("WEBGL_multisampled_render_to_texture")?A.get("WEBGL_multisampled_render_to_texture"):null,r=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),a=new It,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):FN("canvas")}function h(X,O,lA){let wA=1;const xA=uA(X);if((xA.width>lA||xA.height>lA)&&(wA=lA/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 HA=Math.floor(wA*xA.width),zA=Math.floor(wA*xA.height);c===void 0&&(c=Q(HA,zA));const ne=O?Q(HA,zA):c;return ne.width=HA,ne.height=zA,ne.getContext("2d").drawImage(X,0,0,HA,zA),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+xA.width+"x"+xA.height+") to ("+HA+"x"+zA+")."),ne}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,lA,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 HA=O;if(O===e.RED&&(lA===e.FLOAT&&(HA=e.R32F),lA===e.HALF_FLOAT&&(HA=e.R16F),lA===e.UNSIGNED_BYTE&&(HA=e.R8)),O===e.RED_INTEGER&&(lA===e.UNSIGNED_BYTE&&(HA=e.R8UI),lA===e.UNSIGNED_SHORT&&(HA=e.R16UI),lA===e.UNSIGNED_INT&&(HA=e.R32UI),lA===e.BYTE&&(HA=e.R8I),lA===e.SHORT&&(HA=e.R16I),lA===e.INT&&(HA=e.R32I)),O===e.RG&&(lA===e.FLOAT&&(HA=e.RG32F),lA===e.HALF_FLOAT&&(HA=e.RG16F),lA===e.UNSIGNED_BYTE&&(HA=e.RG8)),O===e.RG_INTEGER&&(lA===e.UNSIGNED_BYTE&&(HA=e.RG8UI),lA===e.UNSIGNED_SHORT&&(HA=e.RG16UI),lA===e.UNSIGNED_INT&&(HA=e.RG32UI),lA===e.BYTE&&(HA=e.RG8I),lA===e.SHORT&&(HA=e.RG16I),lA===e.INT&&(HA=e.RG32I)),O===e.RGB_INTEGER&&(lA===e.UNSIGNED_BYTE&&(HA=e.RGB8UI),lA===e.UNSIGNED_SHORT&&(HA=e.RGB16UI),lA===e.UNSIGNED_INT&&(HA=e.RGB32UI),lA===e.BYTE&&(HA=e.RGB8I),lA===e.SHORT&&(HA=e.RGB16I),lA===e.INT&&(HA=e.RGB32I)),O===e.RGBA_INTEGER&&(lA===e.UNSIGNED_BYTE&&(HA=e.RGBA8UI),lA===e.UNSIGNED_SHORT&&(HA=e.RGBA16UI),lA===e.UNSIGNED_INT&&(HA=e.RGBA32UI),lA===e.BYTE&&(HA=e.RGBA8I),lA===e.SHORT&&(HA=e.RGBA16I),lA===e.INT&&(HA=e.RGBA32I)),O===e.RGB&&(lA===e.UNSIGNED_INT_5_9_9_9_REV&&(HA=e.RGB9_E5),lA===e.UNSIGNED_INT_10F_11F_11F_REV&&(HA=e.R11F_G11F_B10F)),O===e.RGBA){const zA=xA?vN:Rn.getTransfer(wA);lA===e.FLOAT&&(HA=e.RGBA32F),lA===e.HALF_FLOAT&&(HA=e.RGBA16F),lA===e.UNSIGNED_BYTE&&(HA=zA===hg?e.SRGB8_ALPHA8:e.RGBA8),lA===e.UNSIGNED_SHORT_4_4_4_4&&(HA=e.RGBA4),lA===e.UNSIGNED_SHORT_5_5_5_1&&(HA=e.RGB5_A1)}return(HA===e.R16F||HA===e.R32F||HA===e.RG16F||HA===e.RG32F||HA===e.RGBA16F||HA===e.RGBA32F)&&A.get("EXT_color_buffer_float"),HA}function D(X,O){let lA;return X?O===null||O===aQ||O===qS?lA=e.DEPTH24_STENCIL8:O===Ga?lA=e.DEPTH32F_STENCIL8:O===TS&&(lA=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):O===null||O===aQ||O===qS?lA=e.DEPTH_COMPONENT24:O===Ga?lA=e.DEPTH_COMPONENT32F:O===TS&&(lA=e.DEPTH_COMPONENT16),lA}function S(X,O){return d(X)===!0||X.isFramebufferTexture&&X.minFilter!==Ds&&X.minFilter!==_g?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 lA=X.source,wA=l.get(lA);if(wA){const xA=wA[O.__cacheKey];xA.usedTimes--,xA.usedTimes===0&&M(X),Object.keys(wA).length===0&&l.delete(lA)}i.remove(X)}function M(X){const O=i.get(X);e.deleteTexture(O.__webglTexture);const lA=X.source,wA=l.get(lA);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 lA=X.textures;for(let wA=0,xA=lA.length;wA<xA;wA++){const HA=i.get(lA[wA]);HA.__webglTexture&&(e.deleteTexture(HA.__webglTexture),o.memory.textures--),i.remove(lA[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 T(X,O){const lA=i.get(X);if(X.isVideoTexture&&cA(X),X.isRenderTargetTexture===!1&&X.isExternalTexture!==!0&&X.version>0&&lA.__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(lA,X,O);return}}else X.isExternalTexture&&(lA.__webglTexture=X.sourceTexture?X.sourceTexture:null);t.bindTexture(e.TEXTURE_2D,lA.__webglTexture,e.TEXTURE0+O)}function v(X,O){const lA=i.get(X);if(X.isRenderTargetTexture===!1&&X.version>0&&lA.__version!==X.version){gA(lA,X,O);return}t.bindTexture(e.TEXTURE_2D_ARRAY,lA.__webglTexture,e.TEXTURE0+O)}function U(X,O){const lA=i.get(X);if(X.isRenderTargetTexture===!1&&X.version>0&&lA.__version!==X.version){gA(lA,X,O);return}t.bindTexture(e.TEXTURE_3D,lA.__webglTexture,e.TEXTURE0+O)}function x(X,O){const lA=i.get(X);if(X.version>0&&lA.__version!==X.version){yA(lA,X,O);return}t.bindTexture(e.TEXTURE_CUBE_MAP,lA.__webglTexture,e.TEXTURE0+O)}const q={[va]:e.REPEAT,[nI]:e.CLAMP_TO_EDGE,[ff]:e.MIRRORED_REPEAT},z={[Ds]:e.NEAREST,[oG]:e.NEAREST_MIPMAP_NEAREST,[Nu]:e.NEAREST_MIPMAP_LINEAR,[_g]:e.LINEAR,[Hp]:e.LINEAR_MIPMAP_NEAREST,[Ra]:e.LINEAR_MIPMAP_LINEAR},Z={[$fA]:e.NEVER,[gyA]:e.ALWAYS,[AyA]:e.LESS,[LW]:e.LEQUAL,[eyA]:e.EQUAL,[nyA]:e.GEQUAL,[tyA]:e.GREATER,[iyA]:e.NOTEQUAL};function eA(X,O){if(O.type===Ga&&A.has("OES_texture_float_linear")===!1&&(O.magFilter===_g||O.magFilter===Hp||O.magFilter===Nu||O.magFilter===Ra||O.minFilter===_g||O.minFilter===Hp||O.minFilter===Nu||O.minFilter===Ra)&&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,q[O.wrapS]),e.texParameteri(X,e.TEXTURE_WRAP_T,q[O.wrapT]),(X===e.TEXTURE_3D||X===e.TEXTURE_2D_ARRAY)&&e.texParameteri(X,e.TEXTURE_WRAP_R,q[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===Ds||O.minFilter!==Nu&&O.minFilter!==Ra||O.type===Ga&&A.has("OES_texture_float_linear")===!1)return;if(O.anisotropy>1||i.get(O).__currentAnisotropy){const lA=A.get("EXT_texture_filter_anisotropic");e.texParameterf(X,lA.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(O.anisotropy,n.getMaxAnisotropy())),i.get(O).__currentAnisotropy=O.anisotropy}}}function aA(X,O){let lA=!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 HA=J(O);if(HA!==X.__cacheKey){xA[HA]===void 0&&(xA[HA]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,lA=!0),xA[HA].usedTimes++;const zA=xA[X.__cacheKey];zA!==void 0&&(xA[X.__cacheKey].usedTimes--,zA.usedTimes===0&&M(O)),X.__cacheKey=HA,X.__webglTexture=xA[HA].texture}return lA}function sA(X,O,lA){return Math.floor(Math.floor(X/lA)/O)}function pA(X,O,lA,wA){const HA=X.updateRanges;if(HA.length===0)t.texSubImage2D(e.TEXTURE_2D,0,0,0,O.width,O.height,lA,wA,O.data);else{HA.sort((NA,QA)=>NA.start-QA.start);let zA=0;for(let NA=1;NA<HA.length;NA++){const QA=HA[zA],PA=HA[NA],VA=QA.start+QA.count,KA=sA(PA.start,O.width,4),Ie=sA(QA.start,O.width,4);PA.start<=VA+1&&KA===Ie&&sA(PA.start+PA.count-1,O.width,4)===KA?QA.count=Math.max(QA.count,PA.start+PA.count-QA.start):(++zA,HA[zA]=PA)}HA.length=zA+1;const ne=e.getParameter(e.UNPACK_ROW_LENGTH),ye=e.getParameter(e.UNPACK_SKIP_PIXELS),Ee=e.getParameter(e.UNPACK_SKIP_ROWS);e.pixelStorei(e.UNPACK_ROW_LENGTH,O.width);for(let NA=0,QA=HA.length;NA<QA;NA++){const PA=HA[NA],VA=Math.floor(PA.start/4),KA=Math.ceil(PA.count/4),Ie=VA%O.width,DA=Math.floor(VA/O.width),IA=KA,EA=1;e.pixelStorei(e.UNPACK_SKIP_PIXELS,Ie),e.pixelStorei(e.UNPACK_SKIP_ROWS,DA),t.texSubImage2D(e.TEXTURE_2D,0,Ie,DA,IA,EA,lA,wA,O.data)}X.clearUpdateRanges(),e.pixelStorei(e.UNPACK_ROW_LENGTH,ne),e.pixelStorei(e.UNPACK_SKIP_PIXELS,ye),e.pixelStorei(e.UNPACK_SKIP_ROWS,Ee)}}function gA(X,O,lA){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),HA=O.source;t.bindTexture(wA,X.__webglTexture,e.TEXTURE0+lA);const zA=i.get(HA);if(HA.version!==zA.__version||xA===!0){t.activeTexture(e.TEXTURE0+lA);const ne=Rn.getPrimaries(Rn.workingColorSpace),ye=O.colorSpace===yE?null:Rn.getPrimaries(O.colorSpace),Ee=O.colorSpace===yE||ne===ye?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,Ee);let NA=h(O.image,!1,n.maxTextureSize);NA=_A(O,NA);const QA=g.convert(O.format,O.colorSpace),PA=g.convert(O.type);let VA=m(O.internalFormat,QA,PA,O.colorSpace,O.isVideoTexture);eA(wA,O);let KA;const Ie=O.mipmaps,DA=O.isVideoTexture!==!0,IA=zA.__version===void 0||xA===!0,EA=HA.dataReady,j=S(O,NA);if(O.isDepthTexture)VA=D(O.format===HS,O.type),IA&&(DA?t.texStorage2D(e.TEXTURE_2D,1,VA,NA.width,NA.height):t.texImage2D(e.TEXTURE_2D,0,VA,NA.width,NA.height,0,QA,PA,null));else if(O.isDataTexture)if(Ie.length>0){DA&&IA&&t.texStorage2D(e.TEXTURE_2D,j,VA,Ie[0].width,Ie[0].height);for(let dA=0,hA=Ie.length;dA<hA;dA++)KA=Ie[dA],DA?EA&&t.texSubImage2D(e.TEXTURE_2D,dA,0,0,KA.width,KA.height,QA,PA,KA.data):t.texImage2D(e.TEXTURE_2D,dA,VA,KA.width,KA.height,0,QA,PA,KA.data);O.generateMipmaps=!1}else DA?(IA&&t.texStorage2D(e.TEXTURE_2D,j,VA,NA.width,NA.height),EA&&pA(O,NA,QA,PA)):t.texImage2D(e.TEXTURE_2D,0,VA,NA.width,NA.height,0,QA,PA,NA.data);else if(O.isCompressedTexture)if(O.isCompressedArrayTexture){DA&&IA&&t.texStorage3D(e.TEXTURE_2D_ARRAY,j,VA,Ie[0].width,Ie[0].height,NA.depth);for(let dA=0,hA=Ie.length;dA<hA;dA++)if(KA=Ie[dA],O.format!==jr)if(QA!==null)if(DA){if(EA)if(O.layerUpdates.size>0){const UA=E4(KA.width,KA.height,O.format,O.type);for(const TA of O.layerUpdates){const se=KA.data.subarray(TA*UA/KA.data.BYTES_PER_ELEMENT,(TA+1)*UA/KA.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,dA,0,0,TA,KA.width,KA.height,1,QA,se)}O.clearLayerUpdates()}else t.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,dA,0,0,0,KA.width,KA.height,NA.depth,QA,KA.data)}else t.compressedTexImage3D(e.TEXTURE_2D_ARRAY,dA,VA,KA.width,KA.height,NA.depth,0,KA.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else DA?EA&&t.texSubImage3D(e.TEXTURE_2D_ARRAY,dA,0,0,0,KA.width,KA.height,NA.depth,QA,PA,KA.data):t.texImage3D(e.TEXTURE_2D_ARRAY,dA,VA,KA.width,KA.height,NA.depth,0,QA,PA,KA.data)}else{DA&&IA&&t.texStorage2D(e.TEXTURE_2D,j,VA,Ie[0].width,Ie[0].height);for(let dA=0,hA=Ie.length;dA<hA;dA++)KA=Ie[dA],O.format!==jr?QA!==null?DA?EA&&t.compressedTexSubImage2D(e.TEXTURE_2D,dA,0,0,KA.width,KA.height,QA,KA.data):t.compressedTexImage2D(e.TEXTURE_2D,dA,VA,KA.width,KA.height,0,KA.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):DA?EA&&t.texSubImage2D(e.TEXTURE_2D,dA,0,0,KA.width,KA.height,QA,PA,KA.data):t.texImage2D(e.TEXTURE_2D,dA,VA,KA.width,KA.height,0,QA,PA,KA.data)}else if(O.isDataArrayTexture)if(DA){if(IA&&t.texStorage3D(e.TEXTURE_2D_ARRAY,j,VA,NA.width,NA.height,NA.depth),EA)if(O.layerUpdates.size>0){const dA=E4(NA.width,NA.height,O.format,O.type);for(const hA of O.layerUpdates){const UA=NA.data.subarray(hA*dA/NA.data.BYTES_PER_ELEMENT,(hA+1)*dA/NA.data.BYTES_PER_ELEMENT);t.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,hA,NA.width,NA.height,1,QA,PA,UA)}O.clearLayerUpdates()}else t.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,NA.width,NA.height,NA.depth,QA,PA,NA.data)}else t.texImage3D(e.TEXTURE_2D_ARRAY,0,VA,NA.width,NA.height,NA.depth,0,QA,PA,NA.data);else if(O.isData3DTexture)DA?(IA&&t.texStorage3D(e.TEXTURE_3D,j,VA,NA.width,NA.height,NA.depth),EA&&t.texSubImage3D(e.TEXTURE_3D,0,0,0,0,NA.width,NA.height,NA.depth,QA,PA,NA.data)):t.texImage3D(e.TEXTURE_3D,0,VA,NA.width,NA.height,NA.depth,0,QA,PA,NA.data);else if(O.isFramebufferTexture){if(IA)if(DA)t.texStorage2D(e.TEXTURE_2D,j,VA,NA.width,NA.height);else{let dA=NA.width,hA=NA.height;for(let UA=0;UA<j;UA++)t.texImage2D(e.TEXTURE_2D,UA,VA,dA,hA,0,QA,PA,null),dA>>=1,hA>>=1}}else if(Ie.length>0){if(DA&&IA){const dA=uA(Ie[0]);t.texStorage2D(e.TEXTURE_2D,j,VA,dA.width,dA.height)}for(let dA=0,hA=Ie.length;dA<hA;dA++)KA=Ie[dA],DA?EA&&t.texSubImage2D(e.TEXTURE_2D,dA,0,0,QA,PA,KA):t.texImage2D(e.TEXTURE_2D,dA,VA,QA,PA,KA);O.generateMipmaps=!1}else if(DA){if(IA){const dA=uA(NA);t.texStorage2D(e.TEXTURE_2D,j,VA,dA.width,dA.height)}EA&&t.texSubImage2D(e.TEXTURE_2D,0,0,0,QA,PA,NA)}else t.texImage2D(e.TEXTURE_2D,0,VA,QA,PA,NA);d(O)&&p(wA),zA.__version=HA.version,O.onUpdate&&O.onUpdate(O)}X.__version=O.version}function yA(X,O,lA){if(O.image.length!==6)return;const wA=aA(X,O),xA=O.source;t.bindTexture(e.TEXTURE_CUBE_MAP,X.__webglTexture,e.TEXTURE0+lA);const HA=i.get(xA);if(xA.version!==HA.__version||wA===!0){t.activeTexture(e.TEXTURE0+lA);const zA=Rn.getPrimaries(Rn.workingColorSpace),ne=O.colorSpace===yE?null:Rn.getPrimaries(O.colorSpace),ye=O.colorSpace===yE||zA===ne?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,ye);const Ee=O.isCompressedTexture||O.image[0].isCompressedTexture,NA=O.image[0]&&O.image[0].isDataTexture,QA=[];for(let hA=0;hA<6;hA++)!Ee&&!NA?QA[hA]=h(O.image[hA],!0,n.maxCubemapSize):QA[hA]=NA?O.image[hA].image:O.image[hA],QA[hA]=_A(O,QA[hA]);const PA=QA[0],VA=g.convert(O.format,O.colorSpace),KA=g.convert(O.type),Ie=m(O.internalFormat,VA,KA,O.colorSpace),DA=O.isVideoTexture!==!0,IA=HA.__version===void 0||wA===!0,EA=xA.dataReady;let j=S(O,PA);eA(e.TEXTURE_CUBE_MAP,O);let dA;if(Ee){DA&&IA&&t.texStorage2D(e.TEXTURE_CUBE_MAP,j,Ie,PA.width,PA.height);for(let hA=0;hA<6;hA++){dA=QA[hA].mipmaps;for(let UA=0;UA<dA.length;UA++){const TA=dA[UA];O.format!==jr?VA!==null?DA?EA&&t.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,UA,0,0,TA.width,TA.height,VA,TA.data):t.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,UA,Ie,TA.width,TA.height,0,TA.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):DA?EA&&t.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,UA,0,0,TA.width,TA.height,VA,KA,TA.data):t.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,UA,Ie,TA.width,TA.height,0,VA,KA,TA.data)}}}else{if(dA=O.mipmaps,DA&&IA){dA.length>0&&j++;const hA=uA(QA[0]);t.texStorage2D(e.TEXTURE_CUBE_MAP,j,Ie,hA.width,hA.height)}for(let hA=0;hA<6;hA++)if(NA){DA?EA&&t.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,0,0,0,QA[hA].width,QA[hA].height,VA,KA,QA[hA].data):t.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,0,Ie,QA[hA].width,QA[hA].height,0,VA,KA,QA[hA].data);for(let UA=0;UA<dA.length;UA++){const se=dA[UA].image[hA].image;DA?EA&&t.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,UA+1,0,0,se.width,se.height,VA,KA,se.data):t.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,UA+1,Ie,se.width,se.height,0,VA,KA,se.data)}}else{DA?EA&&t.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,0,0,0,VA,KA,QA[hA]):t.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,0,Ie,VA,KA,QA[hA]);for(let UA=0;UA<dA.length;UA++){const TA=dA[UA];DA?EA&&t.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,UA+1,0,0,VA,KA,TA.image[hA]):t.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+hA,UA+1,Ie,VA,KA,TA.image[hA])}}}d(O)&&p(e.TEXTURE_CUBE_MAP),HA.__version=xA.version,O.onUpdate&&O.onUpdate(O)}X.__version=O.version}function fA(X,O,lA,wA,xA,HA){const zA=g.convert(lA.format,lA.colorSpace),ne=g.convert(lA.type),ye=m(lA.internalFormat,zA,ne,lA.colorSpace),Ee=i.get(O),NA=i.get(lA);if(NA.__renderTarget=O,!Ee.__hasExternalTextures){const QA=Math.max(1,O.width>>HA),PA=Math.max(1,O.height>>HA);xA===e.TEXTURE_3D||xA===e.TEXTURE_2D_ARRAY?t.texImage3D(xA,HA,ye,QA,PA,O.depth,0,zA,ne,null):t.texImage2D(xA,HA,ye,QA,PA,0,zA,ne,null)}t.bindFramebuffer(e.FRAMEBUFFER,X),CA(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,HA),t.bindFramebuffer(e.FRAMEBUFFER,null)}function RA(X,O,lA){if(e.bindRenderbuffer(e.RENDERBUFFER,X),O.depthBuffer){const wA=O.depthTexture,xA=wA&&wA.isDepthTexture?wA.type:null,HA=D(O.stencilBuffer,xA),zA=O.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ne=oA(O);CA(O)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,ne,HA,O.width,O.height):lA?e.renderbufferStorageMultisample(e.RENDERBUFFER,ne,HA,O.width,O.height):e.renderbufferStorage(e.RENDERBUFFER,HA,O.width,O.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,zA,e.RENDERBUFFER,X)}else{const wA=O.textures;for(let xA=0;xA<wA.length;xA++){const HA=wA[xA],zA=g.convert(HA.format,HA.colorSpace),ne=g.convert(HA.type),ye=m(HA.internalFormat,zA,ne,HA.colorSpace),Ee=oA(O);lA&&CA(O)===!1?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ee,ye,O.width,O.height):CA(O)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ee,ye,O.width,O.height):e.renderbufferStorage(e.RENDERBUFFER,ye,O.width,O.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function YA(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),T(O.depthTexture,0);const xA=wA.__webglTexture,HA=oA(O);if(O.depthTexture.format===YS)CA(O)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,xA,0,HA):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,xA,0);else if(O.depthTexture.format===HS)CA(O)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,xA,0,HA):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),lA=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(lA)throw new Error("target.depthTexture not supported in Cube render targets");const wA=X.texture.mipmaps;wA&&wA.length>0?YA(O.__webglFramebuffer[0],X):YA(O.__webglFramebuffer,X)}else if(lA){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,HA=O.__webglDepthbuffer[wA];e.bindRenderbuffer(e.RENDERBUFFER,HA),e.framebufferRenderbuffer(e.FRAMEBUFFER,xA,e.RENDERBUFFER,HA)}}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,HA=O.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,HA),e.framebufferRenderbuffer(e.FRAMEBUFFER,xA,e.RENDERBUFFER,HA)}}t.bindFramebuffer(e.FRAMEBUFFER,null)}function $(X,O,lA){const wA=i.get(X);O!==void 0&&fA(wA.__webglFramebuffer,X,X.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),lA!==void 0&&W(X)}function L(X){const O=X.texture,lA=i.get(X),wA=i.get(O);X.addEventListener("dispose",N);const xA=X.textures,HA=X.isWebGLCubeRenderTarget===!0,zA=xA.length>1;if(zA||(wA.__webglTexture===void 0&&(wA.__webglTexture=e.createTexture()),wA.__version=O.version,o.memory.textures++),HA){lA.__webglFramebuffer=[];for(let ne=0;ne<6;ne++)if(O.mipmaps&&O.mipmaps.length>0){lA.__webglFramebuffer[ne]=[];for(let ye=0;ye<O.mipmaps.length;ye++)lA.__webglFramebuffer[ne][ye]=e.createFramebuffer()}else lA.__webglFramebuffer[ne]=e.createFramebuffer()}else{if(O.mipmaps&&O.mipmaps.length>0){lA.__webglFramebuffer=[];for(let ne=0;ne<O.mipmaps.length;ne++)lA.__webglFramebuffer[ne]=e.createFramebuffer()}else lA.__webglFramebuffer=e.createFramebuffer();if(zA)for(let ne=0,ye=xA.length;ne<ye;ne++){const Ee=i.get(xA[ne]);Ee.__webglTexture===void 0&&(Ee.__webglTexture=e.createTexture(),o.memory.textures++)}if(X.samples>0&&CA(X)===!1){lA.__webglMultisampledFramebuffer=e.createFramebuffer(),lA.__webglColorRenderbuffer=[],t.bindFramebuffer(e.FRAMEBUFFER,lA.__webglMultisampledFramebuffer);for(let ne=0;ne<xA.length;ne++){const ye=xA[ne];lA.__webglColorRenderbuffer[ne]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,lA.__webglColorRenderbuffer[ne]);const Ee=g.convert(ye.format,ye.colorSpace),NA=g.convert(ye.type),QA=m(ye.internalFormat,Ee,NA,ye.colorSpace,X.isXRRenderTarget===!0),PA=oA(X);e.renderbufferStorageMultisample(e.RENDERBUFFER,PA,QA,X.width,X.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+ne,e.RENDERBUFFER,lA.__webglColorRenderbuffer[ne])}e.bindRenderbuffer(e.RENDERBUFFER,null),X.depthBuffer&&(lA.__webglDepthRenderbuffer=e.createRenderbuffer(),RA(lA.__webglDepthRenderbuffer,X,!0)),t.bindFramebuffer(e.FRAMEBUFFER,null)}}if(HA){t.bindTexture(e.TEXTURE_CUBE_MAP,wA.__webglTexture),eA(e.TEXTURE_CUBE_MAP,O);for(let ne=0;ne<6;ne++)if(O.mipmaps&&O.mipmaps.length>0)for(let ye=0;ye<O.mipmaps.length;ye++)fA(lA.__webglFramebuffer[ne][ye],X,O,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+ne,ye);else fA(lA.__webglFramebuffer[ne],X,O,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+ne,0);d(O)&&p(e.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(zA){for(let ne=0,ye=xA.length;ne<ye;ne++){const Ee=xA[ne],NA=i.get(Ee);let QA=e.TEXTURE_2D;(X.isWebGL3DRenderTarget||X.isWebGLArrayRenderTarget)&&(QA=X.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),t.bindTexture(QA,NA.__webglTexture),eA(QA,Ee),fA(lA.__webglFramebuffer,X,Ee,e.COLOR_ATTACHMENT0+ne,QA,0),d(Ee)&&p(QA)}t.unbindTexture()}else{let ne=e.TEXTURE_2D;if((X.isWebGL3DRenderTarget||X.isWebGLArrayRenderTarget)&&(ne=X.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),t.bindTexture(ne,wA.__webglTexture),eA(ne,O),O.mipmaps&&O.mipmaps.length>0)for(let ye=0;ye<O.mipmaps.length;ye++)fA(lA.__webglFramebuffer[ye],X,O,e.COLOR_ATTACHMENT0,ne,ye);else fA(lA.__webglFramebuffer,X,O,e.COLOR_ATTACHMENT0,ne,0);d(O)&&p(ne),t.unbindTexture()}X.depthBuffer&&W(X)}function H(X){const O=X.textures;for(let lA=0,wA=O.length;lA<wA;lA++){const xA=O[lA];if(d(xA)){const HA=y(X),zA=i.get(xA).__webglTexture;t.bindTexture(HA,zA),p(HA),t.unbindTexture()}}}const P=[],tA=[];function iA(X){if(X.samples>0){if(CA(X)===!1){const O=X.textures,lA=X.width,wA=X.height;let xA=e.COLOR_BUFFER_BIT;const HA=X.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,zA=i.get(X),ne=O.length>1;if(ne)for(let Ee=0;Ee<O.length;Ee++)t.bindFramebuffer(e.FRAMEBUFFER,zA.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ee,e.RENDERBUFFER,null),t.bindFramebuffer(e.FRAMEBUFFER,zA.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ee,e.TEXTURE_2D,null,0);t.bindFramebuffer(e.READ_FRAMEBUFFER,zA.__webglMultisampledFramebuffer);const ye=X.texture.mipmaps;ye&&ye.length>0?t.bindFramebuffer(e.DRAW_FRAMEBUFFER,zA.__webglFramebuffer[0]):t.bindFramebuffer(e.DRAW_FRAMEBUFFER,zA.__webglFramebuffer);for(let Ee=0;Ee<O.length;Ee++){if(X.resolveDepthBuffer&&(X.depthBuffer&&(xA|=e.DEPTH_BUFFER_BIT),X.stencilBuffer&&X.resolveStencilBuffer&&(xA|=e.STENCIL_BUFFER_BIT)),ne){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,zA.__webglColorRenderbuffer[Ee]);const NA=i.get(O[Ee]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,NA,0)}e.blitFramebuffer(0,0,lA,wA,0,0,lA,wA,xA,e.NEAREST),r===!0&&(P.length=0,tA.length=0,P.push(e.COLOR_ATTACHMENT0+Ee),X.depthBuffer&&X.resolveDepthBuffer===!1&&(P.push(HA),tA.push(HA),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),ne)for(let Ee=0;Ee<O.length;Ee++){t.bindFramebuffer(e.FRAMEBUFFER,zA.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ee,e.RENDERBUFFER,zA.__webglColorRenderbuffer[Ee]);const NA=i.get(O[Ee]).__webglTexture;t.bindFramebuffer(e.FRAMEBUFFER,zA.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ee,e.TEXTURE_2D,NA,0)}t.bindFramebuffer(e.DRAW_FRAMEBUFFER,zA.__webglMultisampledFramebuffer)}else if(X.depthBuffer&&X.resolveDepthBuffer===!1&&r){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 CA(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 lA=X.colorSpace,wA=X.format,xA=X.type;return X.isCompressedTexture===!0||X.isVideoTexture===!0||lA!==Mr&&lA!==yE&&(Rn.getTransfer(lA)===hg?(wA!==jr||xA!==sc)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",lA)),O}function uA(X){return typeof HTMLImageElement<"u"&&X instanceof HTMLImageElement?(a.width=X.naturalWidth||X.width,a.height=X.naturalHeight||X.height):typeof VideoFrame<"u"&&X instanceof VideoFrame?(a.width=X.displayWidth,a.height=X.displayHeight):(a.width=X.width,a.height=X.height),a}this.allocateTextureUnit=K,this.resetTextureUnits=_,this.setTexture2D=T,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=CA}function tDA(e,A){function t(i,n=yE){let g;const o=Rn.getTransfer(n);if(i===sc)return e.UNSIGNED_BYTE;if(i===Jx)return e.UNSIGNED_SHORT_4_4_4_4;if(i===Lx)return e.UNSIGNED_SHORT_5_5_5_1;if(i===GW)return e.UNSIGNED_INT_5_9_9_9_REV;if(i===bW)return e.UNSIGNED_INT_10F_11F_11F_REV;if(i===NW)return e.BYTE;if(i===RW)return e.SHORT;if(i===TS)return e.UNSIGNED_SHORT;if(i===_x)return e.INT;if(i===aQ)return e.UNSIGNED_INT;if(i===Ga)return e.FLOAT;if(i===iy)return e.HALF_FLOAT;if(i===UW)return e.ALPHA;if(i===vW)return e.RGB;if(i===jr)return e.RGBA;if(i===YS)return e.DEPTH_COMPONENT;if(i===HS)return e.DEPTH_STENCIL;if(i===xx)return e.RED;if(i===sG)return e.RED_INTEGER;if(i===KW)return e.RG;if(i===Tx)return e.RG_INTEGER;if(i===qx)return e.RGBA_INTEGER;if(i===SM||i===wM||i===kM||i===MM)if(o===hg)if(g=A.get("WEBGL_compressed_texture_s3tc_srgb"),g!==null){if(i===SM)return g.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===wM)return g.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===kM)return g.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===MM)return g.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(g=A.get("WEBGL_compressed_texture_s3tc"),g!==null){if(i===SM)return g.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===wM)return g.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===kM)return g.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===MM)return g.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===O_||i===P_||i===j_||i===z_)if(g=A.get("WEBGL_compressed_texture_pvrtc"),g!==null){if(i===O_)return g.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===P_)return g.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===j_)return g.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===z_)return g.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===Z_||i===W_||i===V_)if(g=A.get("WEBGL_compressed_texture_etc"),g!==null){if(i===Z_||i===W_)return o===hg?g.COMPRESSED_SRGB8_ETC2:g.COMPRESSED_RGB8_ETC2;if(i===V_)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:g.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===X_||i===$_||i===AJ||i===eJ||i===tJ||i===iJ||i===nJ||i===gJ||i===oJ||i===sJ||i===rJ||i===aJ||i===IJ||i===CJ)if(g=A.get("WEBGL_compressed_texture_astc"),g!==null){if(i===X_)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:g.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===$_)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:g.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===AJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:g.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===eJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:g.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===tJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:g.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===iJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:g.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===nJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:g.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===gJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:g.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===oJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:g.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===sJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:g.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===rJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:g.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===aJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:g.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===IJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:g.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===CJ)return o===hg?g.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:g.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===cJ||i===lJ||i===BJ)if(g=A.get("EXT_texture_compression_bptc"),g!==null){if(i===cJ)return o===hg?g.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:g.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===lJ)return g.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===BJ)return g.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===EJ||i===QJ||i===uJ||i===dJ)if(g=A.get("EXT_texture_compression_rgtc"),g!==null){if(i===EJ)return g.COMPRESSED_RED_RGTC1_EXT;if(i===QJ)return g.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===uJ)return g.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===dJ)return g.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===qS?e.UNSIGNED_INT_24_8:e[i]!==void 0?e[i]:null}return{convert:t}}const HEe=`
void main() {

	gl_Position = vec4( position, 1.0 );

}`,OEe=`
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 PEe{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(A,t){if(this.texture===null){const i=new OW(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 rc({vertexShader:HEe,fragmentShader:OEe,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new hn(new sB(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class jEe extends UB{constructor(A,t){super();const i=this;let n=null,g=1,o=null,s="local-floor",r=1,a=null,I=null,c=null,l=null,B=null,Q=null;const h=typeof XRWebGLBinding<"u",d=new PEe,p={},y=t.getContextAttributes();let m=null,D=null;const S=[],k=[],N=new It;let G=null;const M=new zo;M.viewport=new $n;const w=new zo;w.viewport=new $n;const b=[M,w],_=new OyA;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 KK,S[gA]=yA),yA.getTargetRaySpace()},this.getControllerGrip=function(gA){let yA=S[gA];return yA===void 0&&(yA=new KK,S[gA]=yA),yA.getGripSpace()},this.getHand=function(gA){let yA=S[gA];return yA===void 0&&(yA=new KK,S[gA]=yA),yA.getHandSpace()};function T(gA){const yA=k.indexOf(gA.inputSource);if(yA===-1)return;const fA=S[yA];fA!==void 0&&(fA.update(gA.inputSource,gA.frame,a||o),fA.dispatchEvent({type:gA.type,data:gA.inputSource}))}function v(){n.removeEventListener("select",T),n.removeEventListener("selectstart",T),n.removeEventListener("selectend",T),n.removeEventListener("squeeze",T),n.removeEventListener("squeezestart",T),n.removeEventListener("squeezeend",T),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 a||o},this.setReferenceSpace=function(gA){a=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",T),n.addEventListener("selectstart",T),n.addEventListener("selectend",T),n.addEventListener("squeeze",T),n.addEventListener("squeezestart",T),n.addEventListener("squeezeend",T),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,YA=null;y.depth&&(YA=y.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,fA=y.stencil?HS:YS,RA=y.stencil?qS:aQ);const W={colorFormat:t.RGBA8,depthFormat:YA,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 el(l.textureWidth,l.textureHeight,{format:jr,type:sc,depthTexture:new Xx(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 el(B.framebufferWidth,B.framebufferHeight,{format:jr,type:sc,colorSpace:A.outputColorSpace,stencilBuffer:y.stencil,resolveDepthBuffer:B.ignoreDepthValues===!1,resolveStencilBuffer:B.ignoreDepthValues===!1})}D.isXRRenderTarget=!0,this.setFoveation(r),a=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 YA=S[RA];YA&&YA.connect(fA)}}const x=new SA,q=new SA;function z(gA,yA,fA){x.setFromMatrixPosition(yA.matrixWorld),q.setFromMatrixPosition(fA.matrixWorld);const RA=x.distanceTo(q),YA=yA.projectionMatrix.elements,W=fA.projectionMatrix.elements,$=YA[14]/(YA[10]-1),L=YA[14]/(YA[10]+1),H=(YA[9]+1)/YA[5],P=(YA[9]-1)/YA[5],tA=(YA[8]-1)/YA[0],iA=(W[8]+1)/W[0],oA=$*tA,CA=$*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(),YA[10]===-1)gA.projectionMatrix.copy(yA.projectionMatrix),gA.projectionMatrixInverse.copy(yA.projectionMatrixInverse);else{const uA=$+cA,X=L+cA,O=oA-_A,lA=CA+(RA-_A),wA=H*L/X*uA,xA=P*L/X*uA;gA.projectionMatrix.makePerspective(O,lA,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,YA=_.cameras;Z(_,RA);for(let W=0;W<YA.length;W++)Z(YA[W],RA);YA.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=PS*2*Math.atan(1/gA.projectionMatrix.elements[5]),gA.zoom=1)}this.getCamera=function(){return _},this.getFoveation=function(){if(!(l===null&&B===null))return r},this.setFoveation=function(gA){r=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(a||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 zo,tA.layers.enable(L),tA.viewport=new $n,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 YA=n.enabledFeatures;if(YA&&YA.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(YA&&YA.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 OW,p[H]=P);const tA=c.getCameraImage(H);P.sourceTexture=tA}}}}for(let fA=0;fA<S.length;fA++){const RA=k[fA],YA=S[fA];RA!==null&&YA!==void 0&&YA.update(RA,yA,a||o)}aA&&aA(gA,yA),yA.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:yA}),Q=null}const pA=new VyA;pA.setAnimationLoop(sA),this.setAnimationLoop=function(gA){aA=gA},this.dispose=function(){}}}const bh=new or,zEe=new ii;function ZEe(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,CyA(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?r(d,p,y,m):p.isSpriteMaterial?a(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===kr&&(d.bumpScale.value*=-1)),p.normalMap&&(d.normalMap.value=p.normalMap,t(p.normalMap,d.normalMapTransform),d.normalScale.value.copy(p.normalScale),p.side===kr&&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(zEe.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 r(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 a(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===kr&&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 WEe(e,A,t,i){let n={},g={},o=[];const s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function r(y,m){const D=m.program;i.uniformBlockBinding(y,D)}function a(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 T=0;T<K.length;T++){const v=K[T],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,T=K.length;J<T;J++){const v=K[J],U=h(v),x=D%S,q=x%U.boundary,z=x+q;D+=q,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:r,update:a,dispose:p}}class pV{constructor(A={}){const{canvas:t=ryA(),context:i=null,depth:n=!0,stencil:g=!1,alpha:o=!1,antialias:s=!1,premultipliedAlpha:r=!0,preserveDrawingBuffer:a=!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=uB,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const D=this;let S=!1;this._outputColorSpace=sn;let k=0,N=0,G=null,M=-1,w=null;const b=new $n,_=new $n;let K=null;const J=new lt(0);let T=0,v=t.width,U=t.height,x=1,q=null,z=null;const Z=new $n(0,0,v,U),eA=new $n(0,0,v,U);let aA=!1;const sA=new Tw;let pA=!1,gA=!1;const yA=new ii,fA=new SA,RA=new $n,YA={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:r,preserveDrawingBuffer:a,powerPreference:I,failIfMajorPerformanceCaveat:c};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${nG}`),t.addEventListener("webglcontextlost",EA,!1),t.addEventListener("webglcontextrestored",j,!1),t.addEventListener("webglcontextcreationerror",dA,!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,CA,cA,_A,uA,X,O,lA,wA,xA,HA,zA,ne,ye,Ee,NA,QA,PA,VA,KA,Ie;function DA(){P=new rBe(L),P.init(),VA=new tDA(L,P),tA=new eBe(L,P,A,VA),iA=new qEe(L,P),tA.reversedDepthBuffer&&l&&iA.buffers.depth.setReversed(!0),oA=new CBe(L),CA=new NEe,cA=new YEe(L,P,iA,CA,tA,VA,oA),_A=new iBe(D),uA=new sBe(D),X=new uCe(L),KA=new $le(L,X),O=new aBe(L,X,oA,KA),lA=new lBe(L,O,X,oA),NA=new cBe(L,tA,cA),ne=new tBe(CA),wA=new MEe(D,_A,uA,P,tA,KA,ne),xA=new ZEe(D,CA),HA=new GEe,zA=new _Ee(P),Ee=new Xle(D,_A,uA,iA,lA,B,r),ye=new xEe(D,lA,tA),Ie=new WEe(L,oA,tA,iA),QA=new ABe(L,P,oA),PA=new IBe(L,P,oA),oA.programs=wA.programs,D.capabilities=tA,D.extensions=P,D.properties=CA,D.renderLists=HA,D.shadowMap=ye,D.state=iA,D.info=oA}DA();const IA=new jEe(D,L);this.xr=IA,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,FA=!0){if(IA.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),FA===!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,FA){v=nA,U=vA,x=FA,t.width=Math.floor(nA*FA),t.height=Math.floor(vA*FA),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,FA,te){nA.isVector4?Z.set(nA.x,nA.y,nA.z,nA.w):Z.set(nA,vA,FA,te),iA.viewport(b.copy(Z).multiplyScalar(x).round())},this.getScissor=function(nA){return nA.copy(eA)},this.setScissor=function(nA,vA,FA,te){nA.isVector4?eA.set(nA.x,nA.y,nA.z,nA.w):eA.set(nA,vA,FA,te),iA.scissor(_.copy(eA).multiplyScalar(x).round())},this.getScissorTest=function(){return aA},this.setScissorTest=function(nA){iA.setScissorTest(aA=nA)},this.setOpaqueSort=function(nA){q=nA},this.setTransparentSort=function(nA){z=nA},this.getClearColor=function(nA){return nA.copy(Ee.getClearColor())},this.setClearColor=function(){Ee.setClearColor(...arguments)},this.getClearAlpha=function(){return Ee.getClearAlpha()},this.setClearAlpha=function(){Ee.setClearAlpha(...arguments)},this.clear=function(nA=!0,vA=!0,FA=!0){let te=0;if(nA){let bA=!1;if(G!==null){const De=G.texture.format;bA=De===qx||De===Tx||De===sG}if(bA){const De=G.texture.type,jA=De===sc||De===aQ||De===TS||De===qS||De===Jx||De===Lx,me=Ee.getClearColor(),le=Ee.getClearAlpha(),qA=me.r,WA=me.g,Se=me.b;jA?(Q[0]=qA,Q[1]=WA,Q[2]=Se,Q[3]=le,L.clearBufferuiv(L.COLOR,0,Q)):(h[0]=qA,h[1]=WA,h[2]=Se,h[3]=le,L.clearBufferiv(L.COLOR,0,h))}else te|=L.COLOR_BUFFER_BIT}vA&&(te|=L.DEPTH_BUFFER_BIT),FA&&(te|=L.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),L.clear(te)},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",EA,!1),t.removeEventListener("webglcontextrestored",j,!1),t.removeEventListener("webglcontextcreationerror",dA,!1),Ee.dispose(),HA.dispose(),zA.dispose(),CA.dispose(),_A.dispose(),uA.dispose(),lA.dispose(),KA.dispose(),Ie.dispose(),wA.dispose(),IA.dispose(),IA.removeEventListener("sessionstart",At),IA.removeEventListener("sessionend",ni),Ge.stop()};function EA(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=ye.enabled,FA=ye.autoUpdate,te=ye.needsUpdate,bA=ye.type;DA(),oA.autoReset=nA,ye.enabled=vA,ye.autoUpdate=FA,ye.needsUpdate=te,ye.type=bA}function dA(nA){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",nA.statusMessage)}function hA(nA){const vA=nA.target;vA.removeEventListener("dispose",hA),UA(vA)}function UA(nA){TA(nA),CA.remove(nA)}function TA(nA){const vA=CA.get(nA).programs;vA!==void 0&&(vA.forEach(function(FA){wA.releaseProgram(FA)}),nA.isShaderMaterial&&wA.releaseShaderCache(nA))}this.renderBufferDirect=function(nA,vA,FA,te,bA,De){vA===null&&(vA=YA);const jA=bA.isMesh&&bA.matrixWorld.determinant()<0,me=We(nA,vA,FA,te,bA);iA.setMaterial(te,jA);let le=FA.index,qA=1;if(te.wireframe===!0){if(le=O.getWireframeAttribute(FA),le===void 0)return;qA=2}const WA=FA.drawRange,Se=FA.attributes.position;let Qe=WA.start*qA,ce=(WA.start+WA.count)*qA;De!==null&&(Qe=Math.max(Qe,De.start*qA),ce=Math.min(ce,(De.start+De.count)*qA)),le!==null?(Qe=Math.max(Qe,0),ce=Math.min(ce,le.count)):Se!=null&&(Qe=Math.max(Qe,0),ce=Math.min(ce,Se.count));const Ve=ce-Qe;if(Ve<0||Ve===1/0)return;KA.setup(bA,te,me,FA,le);let Dt,Mt=QA;if(le!==null&&(Dt=X.get(le),Mt=PA,Mt.setIndex(Dt)),bA.isMesh)te.wireframe===!0?(iA.setLineWidth(te.wireframeLinewidth*$()),Mt.setMode(L.LINES)):Mt.setMode(L.TRIANGLES);else if(bA.isLine){let ct=te.linewidth;ct===void 0&&(ct=1),iA.setLineWidth(ct*$()),bA.isLineSegments?Mt.setMode(L.LINES):bA.isLineLoop?Mt.setMode(L.LINE_LOOP):Mt.setMode(L.LINE_STRIP)}else bA.isPoints?Mt.setMode(L.POINTS):bA.isSprite&&Mt.setMode(L.TRIANGLES);if(bA.isBatchedMesh)if(bA._multiDrawInstances!==null)_N("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Mt.renderMultiDrawInstances(bA._multiDrawStarts,bA._multiDrawCounts,bA._multiDrawCount,bA._multiDrawInstances);else if(P.get("WEBGL_multi_draw"))Mt.renderMultiDraw(bA._multiDrawStarts,bA._multiDrawCounts,bA._multiDrawCount);else{const ct=bA._multiDrawStarts,gt=bA._multiDrawCounts,et=bA._multiDrawCount,Li=le?X.get(le).bytesPerElement:1,Ri=CA.get(te).currentProgram.getUniforms();for(let gi=0;gi<et;gi++)Ri.setValue(L,"_gl_DrawID",gi),Mt.render(ct[gi]/Li,gt[gi])}else if(bA.isInstancedMesh)Mt.renderInstances(Qe,Ve,bA.count);else if(FA.isInstancedBufferGeometry){const ct=FA._maxInstanceCount!==void 0?FA._maxInstanceCount:1/0,gt=Math.min(FA.instanceCount,ct);Mt.renderInstances(Qe,Ve,gt)}else Mt.render(Qe,Ve)};function se(nA,vA,FA){nA.transparent===!0&&nA.side===Xa&&nA.forceSinglePass===!1?(nA.side=kr,nA.needsUpdate=!0,xt(nA,vA,FA),nA.side=Al,nA.needsUpdate=!0,xt(nA,vA,FA),nA.side=Xa):xt(nA,vA,FA)}this.compile=function(nA,vA,FA=null){FA===null&&(FA=nA),p=zA.get(FA),p.init(vA),m.push(p),FA.traverseVisible(function(bA){bA.isLight&&bA.layers.test(vA.layers)&&(p.pushLight(bA),bA.castShadow&&p.pushShadow(bA))}),nA!==FA&&nA.traverseVisible(function(bA){bA.isLight&&bA.layers.test(vA.layers)&&(p.pushLight(bA),bA.castShadow&&p.pushShadow(bA))}),p.setupLights();const te=new Set;return nA.traverse(function(bA){if(!(bA.isMesh||bA.isPoints||bA.isLine||bA.isSprite))return;const De=bA.material;if(De)if(Array.isArray(De))for(let jA=0;jA<De.length;jA++){const me=De[jA];se(me,FA,bA),te.add(me)}else se(De,FA,bA),te.add(De)}),p=m.pop(),te},this.compileAsync=function(nA,vA,FA=null){const te=this.compile(nA,vA,FA);return new Promise(bA=>{function De(){if(te.forEach(function(jA){CA.get(jA).currentProgram.isReady()&&te.delete(jA)}),te.size===0){bA(nA);return}setTimeout(De,10)}P.get("KHR_parallel_shader_compile")!==null?De():setTimeout(De,10)})};let Ne=null;function Ke(nA){Ne&&Ne(nA)}function At(){Ge.stop()}function ni(){Ge.start()}const Ge=new VyA;Ge.setAnimationLoop(Ke),typeof self<"u"&&Ge.setContext(self),this.setAnimationLoop=function(nA){Ne=nA,IA.setAnimationLoop(nA),nA===null?Ge.stop():Ge.start()},IA.addEventListener("sessionstart",At),IA.addEventListener("sessionend",ni),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(),IA.enabled===!0&&IA.isPresenting===!0&&(IA.cameraAutoUpdate===!0&&IA.updateCamera(vA),vA=IA.getCamera()),nA.isScene===!0&&nA.onBeforeRender(D,nA,vA,G),p=zA.get(nA,m.length),p.init(vA),m.push(p),yA.multiplyMatrices(vA.projectionMatrix,vA.matrixWorldInverse),sA.setFromProjectionMatrix(yA,OI,vA.reversedDepth),gA=this.localClippingEnabled,pA=ne.init(this.clippingPlanes,gA),d=HA.get(nA,y.length),d.init(),y.push(d),IA.enabled===!0&&IA.isPresenting===!0){const De=D.xr.getDepthSensingMesh();De!==null&&st(De,vA,-1/0,D.sortObjects)}st(nA,vA,0,D.sortObjects),d.finish(),D.sortObjects===!0&&d.sort(q,z),W=IA.enabled===!1||IA.isPresenting===!1||IA.hasDepthSensing()===!1,W&&Ee.addToRenderList(d,nA),this.info.render.frame++,pA===!0&&ne.beginShadows();const FA=p.state.shadowsArray;ye.render(FA,nA,vA),pA===!0&&ne.endShadows(),this.info.autoReset===!0&&this.info.reset();const te=d.opaque,bA=d.transmissive;if(p.setupLights(),vA.isArrayCamera){const De=vA.cameras;if(bA.length>0)for(let jA=0,me=De.length;jA<me;jA++){const le=De[jA];Et(te,bA,nA,le)}W&&Ee.render(nA);for(let jA=0,me=De.length;jA<me;jA++){const le=De[jA];Rt(d,nA,le,le.viewport)}}else bA.length>0&&Et(te,bA,nA,vA),W&&Ee.render(nA),Rt(d,nA,vA);G!==null&&N===0&&(cA.updateMultisampleRenderTarget(G),cA.updateRenderTargetMipmap(G)),nA.isScene===!0&&nA.onAfterRender(D,nA,vA),KA.resetDefaultState(),M=-1,w=null,m.pop(),m.length>0?(p=m[m.length-1],pA===!0&&ne.setGlobalState(D.clippingPlanes,p.state.camera)):p=null,y.pop(),y.length>0?d=y[y.length-1]:d=null};function st(nA,vA,FA,te){if(nA.visible===!1)return;if(nA.layers.test(vA.layers)){if(nA.isGroup)FA=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)){te&&RA.setFromMatrixPosition(nA.matrixWorld).applyMatrix4(yA);const jA=lA.update(nA),me=nA.material;me.visible&&d.push(nA,jA,me,FA,RA.z,null)}}else if((nA.isMesh||nA.isLine||nA.isPoints)&&(!nA.frustumCulled||sA.intersectsObject(nA))){const jA=lA.update(nA),me=nA.material;if(te&&(nA.boundingSphere!==void 0?(nA.boundingSphere===null&&nA.computeBoundingSphere(),RA.copy(nA.boundingSphere.center)):(jA.boundingSphere===null&&jA.computeBoundingSphere(),RA.copy(jA.boundingSphere.center)),RA.applyMatrix4(nA.matrixWorld).applyMatrix4(yA)),Array.isArray(me)){const le=jA.groups;for(let qA=0,WA=le.length;qA<WA;qA++){const Se=le[qA],Qe=me[Se.materialIndex];Qe&&Qe.visible&&d.push(nA,jA,Qe,FA,RA.z,Se)}}else me.visible&&d.push(nA,jA,me,FA,RA.z,null)}}const De=nA.children;for(let jA=0,me=De.length;jA<me;jA++)st(De[jA],vA,FA,te)}function Rt(nA,vA,FA,te){const bA=nA.opaque,De=nA.transmissive,jA=nA.transparent;p.setupLightsView(FA),pA===!0&&ne.setGlobalState(D.clippingPlanes,FA),te&&iA.viewport(b.copy(te)),bA.length>0&&_t(bA,vA,FA),De.length>0&&_t(De,vA,FA),jA.length>0&&_t(jA,vA,FA),iA.buffers.depth.setTest(!0),iA.buffers.depth.setMask(!0),iA.buffers.color.setMask(!0),iA.setPolygonOffset(!1)}function Et(nA,vA,FA,te){if((FA.isScene===!0?FA.overrideMaterial:null)!==null)return;p.state.transmissionRenderTarget[te.id]===void 0&&(p.state.transmissionRenderTarget[te.id]=new el(1,1,{generateMipmaps:!0,type:P.has("EXT_color_buffer_half_float")||P.has("EXT_color_buffer_float")?iy:sc,minFilter:Ra,samples:4,stencilBuffer:g,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Rn.workingColorSpace}));const De=p.state.transmissionRenderTarget[te.id],jA=te.viewport||b;De.setSize(jA.z*D.transmissionResolutionScale,jA.w*D.transmissionResolutionScale);const me=D.getRenderTarget(),le=D.getActiveCubeFace(),qA=D.getActiveMipmapLevel();D.setRenderTarget(De),D.getClearColor(J),T=D.getClearAlpha(),T<1&&D.setClearColor(16777215,.5),D.clear(),W&&Ee.render(FA);const WA=D.toneMapping;D.toneMapping=uB;const Se=te.viewport;if(te.viewport!==void 0&&(te.viewport=void 0),p.setupLightsView(te),pA===!0&&ne.setGlobalState(D.clippingPlanes,te),_t(nA,FA,te),cA.updateMultisampleRenderTarget(De),cA.updateRenderTargetMipmap(De),P.has("WEBGL_multisampled_render_to_texture")===!1){let Qe=!1;for(let ce=0,Ve=vA.length;ce<Ve;ce++){const Dt=vA[ce],Mt=Dt.object,ct=Dt.geometry,gt=Dt.material,et=Dt.group;if(gt.side===Xa&&Mt.layers.test(te.layers)){const Li=gt.side;gt.side=kr,gt.needsUpdate=!0,vt(Mt,FA,te,ct,gt,et),gt.side=Li,gt.needsUpdate=!0,Qe=!0}}Qe===!0&&(cA.updateMultisampleRenderTarget(De),cA.updateRenderTargetMipmap(De))}D.setRenderTarget(me,le,qA),D.setClearColor(J,T),Se!==void 0&&(te.viewport=Se),D.toneMapping=WA}function _t(nA,vA,FA){const te=vA.isScene===!0?vA.overrideMaterial:null;for(let bA=0,De=nA.length;bA<De;bA++){const jA=nA[bA],me=jA.object,le=jA.geometry,qA=jA.group;let WA=jA.material;WA.allowOverride===!0&&te!==null&&(WA=te),me.layers.test(FA.layers)&&vt(me,vA,FA,le,WA,qA)}}function vt(nA,vA,FA,te,bA,De){nA.onBeforeRender(D,vA,FA,te,bA,De),nA.modelViewMatrix.multiplyMatrices(FA.matrixWorldInverse,nA.matrixWorld),nA.normalMatrix.getNormalMatrix(nA.modelViewMatrix),bA.onBeforeRender(D,vA,FA,te,nA,De),bA.transparent===!0&&bA.side===Xa&&bA.forceSinglePass===!1?(bA.side=kr,bA.needsUpdate=!0,D.renderBufferDirect(FA,vA,te,bA,nA,De),bA.side=Al,bA.needsUpdate=!0,D.renderBufferDirect(FA,vA,te,bA,nA,De),bA.side=Xa):D.renderBufferDirect(FA,vA,te,bA,nA,De),nA.onAfterRender(D,vA,FA,te,bA,De)}function xt(nA,vA,FA){vA.isScene!==!0&&(vA=YA);const te=CA.get(nA),bA=p.state.lights,De=p.state.shadowsArray,jA=bA.state.version,me=wA.getParameters(nA,bA.state,De,vA,FA),le=wA.getProgramCacheKey(me);let qA=te.programs;te.environment=nA.isMeshStandardMaterial?vA.environment:null,te.fog=vA.fog,te.envMap=(nA.isMeshStandardMaterial?uA:_A).get(nA.envMap||te.environment),te.envMapRotation=te.environment!==null&&nA.envMap===null?vA.environmentRotation:nA.envMapRotation,qA===void 0&&(nA.addEventListener("dispose",hA),qA=new Map,te.programs=qA);let WA=qA.get(le);if(WA!==void 0){if(te.currentProgram===WA&&te.lightsStateVersion===jA)return Oe(nA,me),WA}else me.uniforms=wA.getUniforms(nA),nA.onBeforeCompile(me,D),WA=wA.acquireProgram(me,le),qA.set(le,WA),te.uniforms=me.uniforms;const Se=te.uniforms;return(!nA.isShaderMaterial&&!nA.isRawShaderMaterial||nA.clipping===!0)&&(Se.clippingPlanes=ne.uniform),Oe(nA,me),te.needsLights=kA(nA),te.lightsStateVersion=jA,te.needsLights&&(Se.ambientLightColor.value=bA.state.ambient,Se.lightProbe.value=bA.state.probe,Se.directionalLights.value=bA.state.directional,Se.directionalLightShadows.value=bA.state.directionalShadow,Se.spotLights.value=bA.state.spot,Se.spotLightShadows.value=bA.state.spotShadow,Se.rectAreaLights.value=bA.state.rectArea,Se.ltc_1.value=bA.state.rectAreaLTC1,Se.ltc_2.value=bA.state.rectAreaLTC2,Se.pointLights.value=bA.state.point,Se.pointLightShadows.value=bA.state.pointShadow,Se.hemisphereLights.value=bA.state.hemi,Se.directionalShadowMap.value=bA.state.directionalShadowMap,Se.directionalShadowMatrix.value=bA.state.directionalShadowMatrix,Se.spotShadowMap.value=bA.state.spotShadowMap,Se.spotLightMatrix.value=bA.state.spotLightMatrix,Se.spotLightMap.value=bA.state.spotLightMap,Se.pointShadowMap.value=bA.state.pointShadowMap,Se.pointShadowMatrix.value=bA.state.pointShadowMatrix),te.currentProgram=WA,te.uniformsList=null,WA}function ee(nA){if(nA.uniformsList===null){const vA=nA.currentProgram.getUniforms();nA.uniformsList=FK.seqWithValue(vA.seq,nA.uniforms)}return nA.uniformsList}function Oe(nA,vA){const FA=CA.get(nA);FA.outputColorSpace=vA.outputColorSpace,FA.batching=vA.batching,FA.batchingColor=vA.batchingColor,FA.instancing=vA.instancing,FA.instancingColor=vA.instancingColor,FA.instancingMorph=vA.instancingMorph,FA.skinning=vA.skinning,FA.morphTargets=vA.morphTargets,FA.morphNormals=vA.morphNormals,FA.morphColors=vA.morphColors,FA.morphTargetsCount=vA.morphTargetsCount,FA.numClippingPlanes=vA.numClippingPlanes,FA.numIntersection=vA.numClipIntersection,FA.vertexAlphas=vA.vertexAlphas,FA.vertexTangents=vA.vertexTangents,FA.toneMapping=vA.toneMapping}function We(nA,vA,FA,te,bA){vA.isScene!==!0&&(vA=YA),cA.resetTextureUnits();const De=vA.fog,jA=te.isMeshStandardMaterial?vA.environment:null,me=G===null?D.outputColorSpace:G.isXRRenderTarget===!0?G.texture.colorSpace:Mr,le=(te.isMeshStandardMaterial?uA:_A).get(te.envMap||jA),qA=te.vertexColors===!0&&!!FA.attributes.color&&FA.attributes.color.itemSize===4,WA=!!FA.attributes.tangent&&(!!te.normalMap||te.anisotropy>0),Se=!!FA.morphAttributes.position,Qe=!!FA.morphAttributes.normal,ce=!!FA.morphAttributes.color;let Ve=uB;te.toneMapped&&(G===null||G.isXRRenderTarget===!0)&&(Ve=D.toneMapping);const Dt=FA.morphAttributes.position||FA.morphAttributes.normal||FA.morphAttributes.color,Mt=Dt!==void 0?Dt.length:0,ct=CA.get(te),gt=p.state.lights;if(pA===!0&&(gA===!0||nA!==w)){const si=nA===w&&te.id===M;ne.setState(te,nA,si)}let et=!1;te.version===ct.__version?(ct.needsLights&&ct.lightsStateVersion!==gt.state.version||ct.outputColorSpace!==me||bA.isBatchedMesh&&ct.batching===!1||!bA.isBatchedMesh&&ct.batching===!0||bA.isBatchedMesh&&ct.batchingColor===!0&&bA.colorTexture===null||bA.isBatchedMesh&&ct.batchingColor===!1&&bA.colorTexture!==null||bA.isInstancedMesh&&ct.instancing===!1||!bA.isInstancedMesh&&ct.instancing===!0||bA.isSkinnedMesh&&ct.skinning===!1||!bA.isSkinnedMesh&&ct.skinning===!0||bA.isInstancedMesh&&ct.instancingColor===!0&&bA.instanceColor===null||bA.isInstancedMesh&&ct.instancingColor===!1&&bA.instanceColor!==null||bA.isInstancedMesh&&ct.instancingMorph===!0&&bA.morphTexture===null||bA.isInstancedMesh&&ct.instancingMorph===!1&&bA.morphTexture!==null||ct.envMap!==le||te.fog===!0&&ct.fog!==De||ct.numClippingPlanes!==void 0&&(ct.numClippingPlanes!==ne.numPlanes||ct.numIntersection!==ne.numIntersection)||ct.vertexAlphas!==qA||ct.vertexTangents!==WA||ct.morphTargets!==Se||ct.morphNormals!==Qe||ct.morphColors!==ce||ct.toneMapping!==Ve||ct.morphTargetsCount!==Mt)&&(et=!0):(et=!0,ct.__version=te.version);let Li=ct.currentProgram;et===!0&&(Li=xt(te,vA,bA));let Ri=!1,gi=!1,Jt=!1;const jt=Li.getUniforms(),Ci=ct.uniforms;if(iA.useProgram(Li.program)&&(Ri=!0,gi=!0,Jt=!0),te.id!==M&&(M=te.id,gi=!0),Ri||w!==nA){iA.buffers.depth.getReversed()&&nA.reversedDepth!==!0&&(nA._reversedDepth=!0,nA.updateProjectionMatrix()),jt.setValue(L,"projectionMatrix",nA.projectionMatrix),jt.setValue(L,"viewMatrix",nA.matrixWorldInverse);const pi=jt.map.cameraPosition;pi!==void 0&&pi.setValue(L,fA.setFromMatrixPosition(nA.matrixWorld)),tA.logarithmicDepthBuffer&&jt.setValue(L,"logDepthBufFC",2/(Math.log(nA.far+1)/Math.LN2)),(te.isMeshPhongMaterial||te.isMeshToonMaterial||te.isMeshLambertMaterial||te.isMeshBasicMaterial||te.isMeshStandardMaterial||te.isShaderMaterial)&&jt.setValue(L,"isOrthographic",nA.isOrthographicCamera===!0),w!==nA&&(w=nA,gi=!0,Jt=!0)}if(bA.isSkinnedMesh){jt.setOptional(L,bA,"bindMatrix"),jt.setOptional(L,bA,"bindMatrixInverse");const si=bA.skeleton;si&&(si.boneTexture===null&&si.computeBoneTexture(),jt.setValue(L,"boneTexture",si.boneTexture,cA))}bA.isBatchedMesh&&(jt.setOptional(L,bA,"batchingTexture"),jt.setValue(L,"batchingTexture",bA._matricesTexture,cA),jt.setOptional(L,bA,"batchingIdTexture"),jt.setValue(L,"batchingIdTexture",bA._indirectTexture,cA),jt.setOptional(L,bA,"batchingColorTexture"),bA._colorsTexture!==null&&jt.setValue(L,"batchingColorTexture",bA._colorsTexture,cA));const Pi=FA.morphAttributes;if((Pi.position!==void 0||Pi.normal!==void 0||Pi.color!==void 0)&&NA.update(bA,FA,Li),(gi||ct.receiveShadow!==bA.receiveShadow)&&(ct.receiveShadow=bA.receiveShadow,jt.setValue(L,"receiveShadow",bA.receiveShadow)),te.isMeshGouraudMaterial&&te.envMap!==null&&(Ci.envMap.value=le,Ci.flipEnvMap.value=le.isCubeTexture&&le.isRenderTargetTexture===!1?-1:1),te.isMeshStandardMaterial&&te.envMap===null&&vA.environment!==null&&(Ci.envMapIntensity.value=vA.environmentIntensity),gi&&(jt.setValue(L,"toneMappingExposure",D.toneMappingExposure),ct.needsLights&&pt(Ci,Jt),De&&te.fog===!0&&xA.refreshFogUniforms(Ci,De),xA.refreshMaterialUniforms(Ci,te,x,U,p.state.transmissionRenderTarget[nA.id]),FK.upload(L,ee(ct),Ci,cA)),te.isShaderMaterial&&te.uniformsNeedUpdate===!0&&(FK.upload(L,ee(ct),Ci,cA),te.uniformsNeedUpdate=!1),te.isSpriteMaterial&&jt.setValue(L,"center",bA.center),jt.setValue(L,"modelViewMatrix",bA.modelViewMatrix),jt.setValue(L,"normalMatrix",bA.normalMatrix),jt.setValue(L,"modelMatrix",bA.matrixWorld),te.isShaderMaterial||te.isRawShaderMaterial){const si=te.uniformsGroups;for(let pi=0,Ai=si.length;pi<Ai;pi++){const xi=si[pi];Ie.update(xi,Li),Ie.bind(xi,Li)}}return Li}function pt(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,FA){const te=CA.get(nA);te.__autoAllocateDepthBuffer=nA.resolveDepthBuffer===!1,te.__autoAllocateDepthBuffer===!1&&(te.__useRenderToTexture=!1),CA.get(nA.texture).__webglTexture=vA,CA.get(nA.depthTexture).__webglTexture=te.__autoAllocateDepthBuffer?void 0:FA,te.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(nA,vA){const FA=CA.get(nA);FA.__webglFramebuffer=vA,FA.__useDefaultFramebuffer=vA===void 0};const oe=L.createFramebuffer();this.setRenderTarget=function(nA,vA=0,FA=0){G=nA,k=vA,N=FA;let te=!0,bA=null,De=!1,jA=!1;if(nA){const le=CA.get(nA);if(le.__useDefaultFramebuffer!==void 0)iA.bindFramebuffer(L.FRAMEBUFFER,null),te=!1;else if(le.__webglFramebuffer===void 0)cA.setupRenderTarget(nA);else if(le.__hasExternalTextures)cA.rebindTextures(nA,CA.get(nA.texture).__webglTexture,CA.get(nA.depthTexture).__webglTexture);else if(nA.depthBuffer){const Se=nA.depthTexture;if(le.__boundDepthTexture!==Se){if(Se!==null&&CA.has(Se)&&(nA.width!==Se.image.width||nA.height!==Se.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");cA.setupDepthRenderbuffer(nA)}}const qA=nA.texture;(qA.isData3DTexture||qA.isDataArrayTexture||qA.isCompressedArrayTexture)&&(jA=!0);const WA=CA.get(nA).__webglFramebuffer;nA.isWebGLCubeRenderTarget?(Array.isArray(WA[vA])?bA=WA[vA][FA]:bA=WA[vA],De=!0):nA.samples>0&&cA.useMultisampledRTT(nA)===!1?bA=CA.get(nA).__webglMultisampledFramebuffer:Array.isArray(WA)?bA=WA[FA]:bA=WA,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(FA!==0&&(bA=oe),iA.bindFramebuffer(L.FRAMEBUFFER,bA)&&te&&iA.drawBuffers(nA,bA),iA.viewport(b),iA.scissor(_),iA.setScissorTest(K),De){const le=CA.get(nA.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+vA,le.__webglTexture,FA)}else if(jA){const le=vA;for(let qA=0;qA<nA.textures.length;qA++){const WA=CA.get(nA.textures[qA]);L.framebufferTextureLayer(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0+qA,WA.__webglTexture,FA,le)}}else if(nA!==null&&FA!==0){const le=CA.get(nA.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,le.__webglTexture,FA)}M=-1},this.readRenderTargetPixels=function(nA,vA,FA,te,bA,De,jA,me=0){if(!(nA&&nA.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let le=CA.get(nA).__webglFramebuffer;if(nA.isWebGLCubeRenderTarget&&jA!==void 0&&(le=le[jA]),le){iA.bindFramebuffer(L.FRAMEBUFFER,le);try{const qA=nA.textures[me],WA=qA.format,Se=qA.type;if(!tA.textureFormatReadable(WA)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!tA.textureTypeReadable(Se)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}vA>=0&&vA<=nA.width-te&&FA>=0&&FA<=nA.height-bA&&(nA.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+me),L.readPixels(vA,FA,te,bA,VA.convert(WA),VA.convert(Se),De))}finally{const qA=G!==null?CA.get(G).__webglFramebuffer:null;iA.bindFramebuffer(L.FRAMEBUFFER,qA)}}},this.readRenderTargetPixelsAsync=async function(nA,vA,FA,te,bA,De,jA,me=0){if(!(nA&&nA.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let le=CA.get(nA).__webglFramebuffer;if(nA.isWebGLCubeRenderTarget&&jA!==void 0&&(le=le[jA]),le)if(vA>=0&&vA<=nA.width-te&&FA>=0&&FA<=nA.height-bA){iA.bindFramebuffer(L.FRAMEBUFFER,le);const qA=nA.textures[me],WA=qA.format,Se=qA.type;if(!tA.textureFormatReadable(WA))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!tA.textureTypeReadable(Se))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Qe=L.createBuffer();L.bindBuffer(L.PIXEL_PACK_BUFFER,Qe),L.bufferData(L.PIXEL_PACK_BUFFER,De.byteLength,L.STREAM_READ),nA.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+me),L.readPixels(vA,FA,te,bA,VA.convert(WA),VA.convert(Se),0);const ce=G!==null?CA.get(G).__webglFramebuffer:null;iA.bindFramebuffer(L.FRAMEBUFFER,ce);const Ve=L.fenceSync(L.SYNC_GPU_COMMANDS_COMPLETE,0);return L.flush(),await Lre(L,Ve,4),L.bindBuffer(L.PIXEL_PACK_BUFFER,Qe),L.getBufferSubData(L.PIXEL_PACK_BUFFER,0,De),L.deleteBuffer(Qe),L.deleteSync(Ve),De}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(nA,vA=null,FA=0){const te=Math.pow(2,-FA),bA=Math.floor(nA.image.width*te),De=Math.floor(nA.image.height*te),jA=vA!==null?vA.x:0,me=vA!==null?vA.y:0;cA.setTexture2D(nA,0),L.copyTexSubImage2D(L.TEXTURE_2D,FA,0,0,jA,me,bA,De),iA.unbindTexture()};const ae=L.createFramebuffer(),$A=L.createFramebuffer();this.copyTextureToTexture=function(nA,vA,FA=null,te=null,bA=0,De=null){De===null&&(bA!==0?(_N("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),De=bA,bA=0):De=0);let jA,me,le,qA,WA,Se,Qe,ce,Ve;const Dt=nA.isCompressedTexture?nA.mipmaps[De]:nA.image;if(FA!==null)jA=FA.max.x-FA.min.x,me=FA.max.y-FA.min.y,le=FA.isBox3?FA.max.z-FA.min.z:1,qA=FA.min.x,WA=FA.min.y,Se=FA.isBox3?FA.min.z:0;else{const Pi=Math.pow(2,-bA);jA=Math.floor(Dt.width*Pi),me=Math.floor(Dt.height*Pi),nA.isDataArrayTexture?le=Dt.depth:nA.isData3DTexture?le=Math.floor(Dt.depth*Pi):le=1,qA=0,WA=0,Se=0}te!==null?(Qe=te.x,ce=te.y,Ve=te.z):(Qe=0,ce=0,Ve=0);const Mt=VA.convert(vA.format),ct=VA.convert(vA.type);let gt;vA.isData3DTexture?(cA.setTexture3D(vA,0),gt=L.TEXTURE_3D):vA.isDataArrayTexture||vA.isCompressedArrayTexture?(cA.setTexture2DArray(vA,0),gt=L.TEXTURE_2D_ARRAY):(cA.setTexture2D(vA,0),gt=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 et=L.getParameter(L.UNPACK_ROW_LENGTH),Li=L.getParameter(L.UNPACK_IMAGE_HEIGHT),Ri=L.getParameter(L.UNPACK_SKIP_PIXELS),gi=L.getParameter(L.UNPACK_SKIP_ROWS),Jt=L.getParameter(L.UNPACK_SKIP_IMAGES);L.pixelStorei(L.UNPACK_ROW_LENGTH,Dt.width),L.pixelStorei(L.UNPACK_IMAGE_HEIGHT,Dt.height),L.pixelStorei(L.UNPACK_SKIP_PIXELS,qA),L.pixelStorei(L.UNPACK_SKIP_ROWS,WA),L.pixelStorei(L.UNPACK_SKIP_IMAGES,Se);const jt=nA.isDataArrayTexture||nA.isData3DTexture,Ci=vA.isDataArrayTexture||vA.isData3DTexture;if(nA.isDepthTexture){const Pi=CA.get(nA),si=CA.get(vA),pi=CA.get(Pi.__renderTarget),Ai=CA.get(si.__renderTarget);iA.bindFramebuffer(L.READ_FRAMEBUFFER,pi.__webglFramebuffer),iA.bindFramebuffer(L.DRAW_FRAMEBUFFER,Ai.__webglFramebuffer);for(let xi=0;xi<le;xi++)jt&&(L.framebufferTextureLayer(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,CA.get(nA).__webglTexture,bA,Se+xi),L.framebufferTextureLayer(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,CA.get(vA).__webglTexture,De,Ve+xi)),L.blitFramebuffer(qA,WA,jA,me,Qe,ce,jA,me,L.DEPTH_BUFFER_BIT,L.NEAREST);iA.bindFramebuffer(L.READ_FRAMEBUFFER,null),iA.bindFramebuffer(L.DRAW_FRAMEBUFFER,null)}else if(bA!==0||nA.isRenderTargetTexture||CA.has(nA)){const Pi=CA.get(nA),si=CA.get(vA);iA.bindFramebuffer(L.READ_FRAMEBUFFER,ae),iA.bindFramebuffer(L.DRAW_FRAMEBUFFER,$A);for(let pi=0;pi<le;pi++)jt?L.framebufferTextureLayer(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,Pi.__webglTexture,bA,Se+pi):L.framebufferTexture2D(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,Pi.__webglTexture,bA),Ci?L.framebufferTextureLayer(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,si.__webglTexture,De,Ve+pi):L.framebufferTexture2D(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,si.__webglTexture,De),bA!==0?L.blitFramebuffer(qA,WA,jA,me,Qe,ce,jA,me,L.COLOR_BUFFER_BIT,L.NEAREST):Ci?L.copyTexSubImage3D(gt,De,Qe,ce,Ve+pi,qA,WA,jA,me):L.copyTexSubImage2D(gt,De,Qe,ce,qA,WA,jA,me);iA.bindFramebuffer(L.READ_FRAMEBUFFER,null),iA.bindFramebuffer(L.DRAW_FRAMEBUFFER,null)}else Ci?nA.isDataTexture||nA.isData3DTexture?L.texSubImage3D(gt,De,Qe,ce,Ve,jA,me,le,Mt,ct,Dt.data):vA.isCompressedArrayTexture?L.compressedTexSubImage3D(gt,De,Qe,ce,Ve,jA,me,le,Mt,Dt.data):L.texSubImage3D(gt,De,Qe,ce,Ve,jA,me,le,Mt,ct,Dt):nA.isDataTexture?L.texSubImage2D(L.TEXTURE_2D,De,Qe,ce,jA,me,Mt,ct,Dt.data):nA.isCompressedTexture?L.compressedTexSubImage2D(L.TEXTURE_2D,De,Qe,ce,Dt.width,Dt.height,Mt,Dt.data):L.texSubImage2D(L.TEXTURE_2D,De,Qe,ce,jA,me,Mt,ct,Dt);L.pixelStorei(L.UNPACK_ROW_LENGTH,et),L.pixelStorei(L.UNPACK_IMAGE_HEIGHT,Li),L.pixelStorei(L.UNPACK_SKIP_PIXELS,Ri),L.pixelStorei(L.UNPACK_SKIP_ROWS,gi),L.pixelStorei(L.UNPACK_SKIP_IMAGES,Jt),De===0&&vA.generateMipmaps&&L.generateMipmap(gt),iA.unbindTexture()},this.initRenderTarget=function(nA){CA.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(),KA.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return OI}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(A){this._outputColorSpace=A;const t=this.getContext();t.drawingBufferColorSpace=Rn._getDrawingBufferColorSpace(A),t.unpackColorSpace=Rn._getUnpackColorSpace()}}const VEe=Object.freeze(Object.defineProperty({__proto__:null,ACESFilmicToneMapping:ty,AddEquation:au,AddOperation:TfA,AdditiveAnimationBlendMode:_W,AdditiveBlending:Vg,AgXToneMapping:PfA,AlphaFormat:UW,AlwaysCompare:gyA,AlwaysDepth:L_,AlwaysStencilFunc:r4,AmbientLight:aV,AnimationAction:zyA,AnimationClip:fd,AnimationLoader:CIe,AnimationMixer:EV,AnimationObjectGroup:FIe,AnimationUtils:sIe,ArcCurve:hyA,ArrayCamera:OyA,ArrowHelper:rCe,AttachedBindMode:s4,Audio:PyA,AudioAnalyser:wIe,AudioContext:CV,AudioListener:DIe,AudioLoader:pIe,AxesHelper:aCe,BackSide:kr,BasicDepthPacking:WfA,BasicShadowMap:ffA,BatchedMesh:QyA,Bone:cG,BooleanKeyframeTrack:oy,Box2:jIe,Box3:Vn,Box3Helper:oCe,BoxGeometry:gI,BoxHelper:gCe,BufferAttribute:Yi,BufferGeometry:ki,BufferGeometryLoader:HyA,ByteType:NW,Cache:rB,Camera:Px,CameraHelper:nCe,CanvasTexture:pd,CapsuleGeometry:$x,CatmullRomCurve3:jW,CineonToneMapping:HfA,CircleGeometry:AT,ClampToEdgeWrapping:nI,Clock:cV,Color:lt,ColorKeyframeTrack:gV,ColorManagement:Rn,CompressedArrayTexture:Nae,CompressedCubeTexture:Rae,CompressedTexture:Vx,CompressedTextureLoader:cIe,ConeGeometry:BG,ConstantAlphaFactor:JfA,ConstantColorFactor:FfA,Controls:CCe,CubeCamera:cyA,CubeReflectionMapping:rQ,CubeRefractionMapping:ud,CubeTexture:aG,CubeTextureLoader:lIe,CubeUVReflectionMapping:_w,CubicBezierCurve:zW,CubicBezierCurve3:pyA,CubicInterpolant:FyA,CullFaceBack:n4,CullFaceFront:pfA,CullFaceFrontBack:Yse,CullFaceNone:hfA,Curve:Il,CurvePath:yyA,CustomBlending:yfA,CustomToneMapping:OfA,CylinderGeometry:ny,Cylindrical:PIe,Data3DTexture:Ox,DataArrayTexture:Hx,DataTexture:dB,DataTextureLoader:BIe,DataUtils:Aae,DecrementStencilOp:Are,DecrementWrapStencilOp:tre,DefaultLoadingManager:LyA,DepthFormat:YS,DepthStencilFormat:HS,DepthTexture:Xx,DetachedBindMode:zfA,DirectionalLight:zp,DirectionalLightHelper:iCe,DiscreteInterpolant:_yA,DodecahedronGeometry:eT,DoubleSide:Xa,DstAlphaFactor:GfA,DstColorFactor:UfA,DynamicCopyUsage:Qre,DynamicDrawUsage:oyA,DynamicReadUsage:lre,EdgesGeometry:dyA,EllipseCurve:tT,EqualCompare:eyA,EqualDepth:T_,EqualStencilFunc:ore,EquirectangularReflectionMapping:GN,EquirectangularRefractionMapping:bN,Euler:or,EventDispatcher:UB,ExternalTexture:OW,ExtrudeGeometry:iT,FileLoader:Aa,Float16BufferAttribute:sae,Float32BufferAttribute:Vt,FloatType:Ga,Fog:IG,FogExp2:jx,FramebufferTexture:Mae,FrontSide:Al,Frustum:Tw,FrustumArray:Zx,GLBufferAttribute:qIe,GLSL1:dre,GLSL3:a4,GreaterCompare:tyA,GreaterDepth:Y_,GreaterEqualCompare:nyA,GreaterEqualDepth:q_,GreaterEqualStencilFunc:Ire,GreaterStencilFunc:rre,GridHelper:eCe,Group:er,HalfFloatType:iy,HemisphereLight:sV,HemisphereLightHelper:ACe,IcosahedronGeometry:nT,ImageBitmapLoader:IV,ImageLoader:qN,ImageUtils:ayA,IncrementStencilOp:$se,IncrementWrapStencilOp:ere,InstancedBufferAttribute:hd,InstancedBufferGeometry:YyA,InstancedInterleavedBuffer:TIe,InstancedMesh:lG,Int16BufferAttribute:gae,Int32BufferAttribute:oae,Int8BufferAttribute:tae,IntType:_x,InterleavedBuffer:Lw,InterleavedBufferAttribute:IQ,Interpolant:gy,InterpolateDiscrete:yf,InterpolateLinear:dd,InterpolateSmooth:vK,InterpolationSamplingMode:fre,InterpolationSamplingType:pre,InvertStencilOp:ire,KeepStencilOp:Xh,KeyframeTrack:cc,LOD:EyA,LatheGeometry:gT,Layers:jS,LessCompare:AyA,LessDepth:x_,LessEqualCompare:LW,LessEqualDepth:pf,LessEqualStencilFunc:sre,LessStencilFunc:gre,Light:qd,LightProbe:qyA,Line:DB,Line3:WIe,LineBasicMaterial:$o,LineCurve:ZW,LineCurve3:fyA,LineDashedMaterial:UyA,LineLoop:Wx,LineSegments:BI,LinearFilter:_g,LinearInterpolant:nV,LinearMipMapLinearFilter:jse,LinearMipMapNearestFilter:Pse,LinearMipmapLinearFilter:Ra,LinearMipmapNearestFilter:Hp,LinearSRGBColorSpace:Mr,LinearToneMapping:qfA,LinearTransfer:vN,Loader:sr,LoaderUtils:XI,LoadingManager:oV,LoopOnce:FW,LoopPingPong:ZfA,LoopRepeat:hJ,MOUSE:Tse,Material:co,MaterialLoader:lT,MathUtils:zC,Matrix2:dV,Matrix3:$i,Matrix4:ii,MaxEquation:wfA,Mesh:hn,MeshBasicMaterial:yg,MeshDepthMaterial:eV,MeshDistanceMaterial:tV,MeshLambertMaterial:AV,MeshMatcapMaterial:byA,MeshNormalMaterial:GyA,MeshPhongMaterial:$W,MeshPhysicalMaterial:Lo,MeshStandardMaterial:Kg,MeshToonMaterial:RyA,MinEquation:SfA,MirroredRepeatWrapping:ff,MixOperation:xfA,MultiplyBlending:o4,MultiplyOperation:gG,NearestFilter:Ds,NearestMipMapLinearFilter:Ose,NearestMipMapNearestFilter:Hse,NearestMipmapLinearFilter:Nu,NearestMipmapNearestFilter:oG,NeutralToneMapping:jfA,NeverCompare:$fA,NeverDepth:J_,NeverStencilFunc:nre,NoBlending:xE,NoColorSpace:yE,NoToneMapping:uB,NormalAnimationBlendMode:Yx,NormalBlending:Yp,NotEqualCompare:iyA,NotEqualDepth:H_,NotEqualStencilFunc:are,NumberKeyframeTrack:CQ,Object3D:cn,ObjectLoader:dIe,ObjectSpaceNormalMap:XfA,OctahedronGeometry:EG,OneFactor:MfA,OneMinusConstantAlphaFactor:LfA,OneMinusConstantColorFactor:_fA,OneMinusDstAlphaFactor:bfA,OneMinusDstColorFactor:vfA,OneMinusSrcAlphaFactor:__,OneMinusSrcColorFactor:RfA,OrthographicCamera:Yd,PCFShadowMap:Kx,PCFSoftShadowMap:mM,PMREMGenerator:SJ,Path:mJ,PerspectiveCamera:zo,Plane:eu,PlaneGeometry:sB,PlaneHelper:sCe,PointLight:QG,PointLightHelper:XIe,Points:Pp,PointsMaterial:ME,PolarGridHelper:tCe,PolyhedronGeometry:xd,PositionalAudio:SIe,PropertyBinding:On,PropertyMixer:jyA,QuadraticBezierCurve:WW,QuadraticBezierCurve3:VW,Quaternion:Ao,QuaternionKeyframeTrack:mB,QuaternionLinearInterpolant:JyA,RED_GREEN_RGTC2_Format:uJ,RED_RGTC1_Format:EJ,REVISION:nG,RGBADepthPacking:VfA,RGBAFormat:jr,RGBAIntegerFormat:qx,RGBA_ASTC_10x10_Format:aJ,RGBA_ASTC_10x5_Format:oJ,RGBA_ASTC_10x6_Format:sJ,RGBA_ASTC_10x8_Format:rJ,RGBA_ASTC_12x10_Format:IJ,RGBA_ASTC_12x12_Format:CJ,RGBA_ASTC_4x4_Format:X_,RGBA_ASTC_5x4_Format:$_,RGBA_ASTC_5x5_Format:AJ,RGBA_ASTC_6x5_Format:eJ,RGBA_ASTC_6x6_Format:tJ,RGBA_ASTC_8x5_Format:iJ,RGBA_ASTC_8x6_Format:nJ,RGBA_ASTC_8x8_Format:gJ,RGBA_BPTC_Format:cJ,RGBA_ETC2_EAC_Format:V_,RGBA_PVRTC_2BPPV1_Format:z_,RGBA_PVRTC_4BPPV1_Format:j_,RGBA_S3TC_DXT1_Format:wM,RGBA_S3TC_DXT3_Format:kM,RGBA_S3TC_DXT5_Format:MM,RGBDepthPacking:Zse,RGBFormat:vW,RGBIntegerFormat:zse,RGB_BPTC_SIGNED_Format:lJ,RGB_BPTC_UNSIGNED_Format:BJ,RGB_ETC1_Format:Z_,RGB_ETC2_Format:W_,RGB_PVRTC_2BPPV1_Format:P_,RGB_PVRTC_4BPPV1_Format:O_,RGB_S3TC_DXT1_Format:SM,RGDepthPacking:Wse,RGFormat:KW,RGIntegerFormat:Tx,RawShaderMaterial:NyA,Ray:Jw,Raycaster:uV,RectAreaLight:xyA,RedFormat:xx,RedIntegerFormat:sG,ReinhardToneMapping:YfA,RenderTarget:TW,RenderTarget3D:JIe,RepeatWrapping:va,ReplaceStencilOp:Xse,ReverseSubtractEquation:mfA,RingGeometry:oT,SIGNED_RED_GREEN_RGTC2_Format:dJ,SIGNED_RED_RGTC1_Format:QJ,SRGBColorSpace:sn,SRGBTransfer:hg,Scene:CG,ShaderChunk:In,ShaderLib:Jc,ShaderMaterial:rc,ShadowMaterial:MyA,Shape:jp,ShapeGeometry:sT,ShapePath:ICe,ShapeUtils:Pc,ShortType:RW,Skeleton:xw,SkeletonHelper:ZyA,SkinnedMesh:zx,Source:Ru,Sphere:vs,SphereGeometry:Sf,Spherical:OIe,SphericalHarmonics3:TyA,SplineCurve:XW,SpotLight:cT,SpotLightHelper:VIe,Sprite:pJ,SpriteMaterial:JN,SrcAlphaFactor:F_,SrcAlphaSaturateFactor:KfA,SrcColorFactor:NfA,StaticCopyUsage:Ere,StaticDrawUsage:KN,StaticReadUsage:cre,StereoCamera:fIe,StreamCopyUsage:ure,StreamDrawUsage:Cre,StreamReadUsage:Bre,StringKeyframeTrack:sy,SubtractEquation:DfA,SubtractiveBlending:g4,TOUCH:qse,TangentSpaceNormalMap:Ld,TetrahedronGeometry:rT,Texture:Rg,TextureLoader:Td,TextureUtils:QCe,Timer:YIe,TimestampQuery:hre,TorusGeometry:aT,TorusKnotGeometry:IT,Triangle:$a,TriangleFanDrawMode:Df,TriangleStripDrawMode:rG,TrianglesDrawMode:JW,TubeGeometry:CT,UVMapping:Fx,Uint16BufferAttribute:qW,Uint32BufferAttribute:YW,Uint8BufferAttribute:iae,Uint8ClampedBufferAttribute:nae,Uniform:QV,UniformsGroup:xIe,UniformsLib:Pt,UniformsUtils:HW,UnsignedByteType:sc,UnsignedInt101111Type:bW,UnsignedInt248Type:qS,UnsignedInt5999Type:GW,UnsignedIntType:aQ,UnsignedShort4444Type:Jx,UnsignedShort5551Type:Lx,UnsignedShortType:TS,VSMShadowMap:Nc,Vector2:It,Vector3:SA,Vector4:$n,VectorKeyframeTrack:SB,VideoFrameTexture:kae,VideoTexture:uyA,WebGL3DRenderTarget:Hre,WebGLArrayRenderTarget:Yre,WebGLCoordinateSystem:OI,WebGLCubeRenderTarget:lyA,WebGLRenderTarget:el,WebGLRenderer:pV,WebGLUtils:tDA,WebGPUCoordinateSystem:OS,WebXRController:KK,WireframeGeometry:kyA,WrapAroundEnding:UN,ZeroCurvatureEnding:lp,ZeroFactor:kfA,ZeroSlopeEnding:Bp,ZeroStencilOp:Vse,createCanvasElement:ryA},Symbol.toStringTag,{value:"Module"}));var iDA={exports:{}},nDA={},gDA={exports:{}},oDA={};/**
 * @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 WS=E;function XEe(e,A){return e===A&&(e!==0||1/e===1/A)||e!==e&&A!==A}var $Ee=typeof Object.is=="function"?Object.is:XEe,AQe=WS.useState,eQe=WS.useEffect,tQe=WS.useLayoutEffect,iQe=WS.useDebugValue;function nQe(e,A){var t=A(),i=AQe({inst:{value:t,getSnapshot:A}}),n=i[0].inst,g=i[1];return tQe(function(){n.value=t,n.getSnapshot=A,PH(n)&&g({inst:n})},[e,t,A]),eQe(function(){return PH(n)&&g({inst:n}),e(function(){PH(n)&&g({inst:n})})},[e]),iQe(t),t}function PH(e){var A=e.getSnapshot;e=e.value;try{var t=A();return!$Ee(e,t)}catch{return!0}}function gQe(e,A){return A()}var oQe=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?gQe:nQe;oDA.useSyncExternalStore=WS.useSyncExternalStore!==void 0?WS.useSyncExternalStore:oQe;gDA.exports=oDA;var sQe=gDA.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 ET=E,rQe=sQe;function aQe(e,A){return e===A&&(e!==0||1/e===1/A)||e!==e&&A!==A}var IQe=typeof Object.is=="function"?Object.is:aQe,CQe=rQe.useSyncExternalStore,cQe=ET.useRef,lQe=ET.useEffect,BQe=ET.useMemo,EQe=ET.useDebugValue;nDA.useSyncExternalStoreWithSelector=function(e,A,t,i,n){var g=cQe(null);if(g.current===null){var o={hasValue:!1,value:null};g.current=o}else o=g.current;g=BQe(function(){function r(B){if(!a){if(a=!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,IQe(I,B))return Q;var h=i(B);return n!==void 0&&n(Q,h)?(I=B,Q):(I=B,c=h)}var a=!1,I,c,l=t===void 0?null:t;return[function(){return r(A())},l===null?void 0:function(){return r(l())}]},[A,t,i,n]);var s=CQe(e,g[0],g[1]);return lQe(function(){o.hasValue=!0,o.value=s},[s]),EQe(s),s};iDA.exports=nDA;var QQe=iDA.exports;const uQe=gw(QQe),CgA=e=>{let A;const t=new Set,i=(a,I)=>{const c=typeof a=="function"?a(A):a;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:()=>r,subscribe:a=>(t.add(a),()=>t.delete(a))},r=A=e(i,n,s);return s},sDA=e=>e?CgA(e):CgA,{useSyncExternalStoreWithSelector:dQe}=uQe,hQe=e=>e;function pQe(e,A=hQe,t){const i=dQe(e.subscribe,e.getState,e.getInitialState,A,t);return he.useDebugValue(i),i}const cgA=(e,A)=>{const t=sDA(e),i=(n,g=A)=>pQe(t,n,g);return Object.assign(i,t),i},rDA=(e,A)=>e?cgA(e,A):cgA,fQe=e=>typeof e=="object"&&typeof e.then=="function",Qp=[];function aDA(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 IDA(e,A=null,t=!1,i={}){A===null&&(A=[e]);for(const g of Qp)if(aDA(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:(fQe(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 CDA=(e,A,t)=>IDA(e,A,!1,t),yQe=(e,A,t)=>void IDA(e,A,!0,t),DQe=e=>{if(e===void 0||e.length===0)Qp.splice(0,Qp.length);else{const A=Qp.find(t=>aDA(e,t.keys,t.equal));A&&A.remove()}};var cDA={exports:{}},lDA={exports:{}},jH={exports:{}},zH={};/**
 * @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 lgA;function mQe(){return lgA||(lgA=1,function(e){function A(v,U){var x=v.length;v.push(U);A:for(;0<x;){var q=x-1>>>1,z=v[q];if(0<n(z,U))v[q]=U,v[x]=z,x=q;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 q=0,z=v.length,Z=z>>>1;q<Z;){var eA=2*(q+1)-1,aA=v[eA],sA=eA+1,pA=v[sA];if(0>n(aA,x))sA<z&&0>n(pA,aA)?(v[q]=pA,v[sA]=x,q=sA):(v[q]=aA,v[eA]=x,q=eA);else if(sA<z&&0>n(pA,x))v[q]=pA,v[sA]=x,q=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 r=[],a=[],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(a);U!==null;){if(U.callback===null)i(a);else if(U.startTime<=v)i(a),U.sortIndex=U.expirationTime,A(r,U);else break;U=t(a)}}function D(v){if(h=!1,m(v),!Q)if(t(r)!==null)Q=!0,J();else{var U=t(a);U!==null&&T(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(r);c!==null&&!(c.expirationTime>v&&M());){var q=c.callback;if(typeof q=="function"){c.callback=null,l=c.priorityLevel;var z=q(c.expirationTime<=v);if(v=e.unstable_now(),typeof z=="function"){c.callback=z,m(v),U=!0;break e}c===t(r)&&i(r),m(v)}else i(r);c=t(r)}if(c!==null)U=!0;else{var Z=t(a);Z!==null&&T(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 T(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(r)},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 q=e.unstable_now();switch(typeof x=="object"&&x!==null?(x=x.delay,x=typeof x=="number"&&0<x?q+x:q):x=q,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>q?(v.sortIndex=x,A(a,v),t(r)===null&&v===t(a)&&(h?(p(k),k=-1):h=!0,T(D,x-q))):(v.sortIndex=z,A(r,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}}}}(zH)),zH}var BgA;function SQe(){return BgA||(BgA=1,jH.exports=mQe()),jH.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 iwA(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=o9&&u[o9]||u["@@iterator"],typeof u=="function"?u:null)}function o(u){if(u==null)return null;if(typeof u=="function")return u.$$typeof===awA?null:u.displayName||u.name||null;if(typeof u=="string")return u;switch(u){case By:return"Fragment";case ly:return"Portal";case bT:return"Profiler";case i9:return"StrictMode";case vT:return"Suspense";case KT:return"SuspenseList"}if(typeof u=="object")switch(u.$$typeof){case pQ:return(u.displayName||"Context")+".Provider";case n9:return(u._context.displayName||"Context")+".Consumer";case UT:var f=u.render;return u=u.displayName,u||(u=f.displayName||f.name||"",u=u!==""?"ForwardRef("+u+")":"ForwardRef"),u;case FT:return f=u.displayName||null,f!==null?f:o(u.type)||"Memo";case fQ:f=u._payload,u=u._init;try{return o(u(f))}catch{}}return null}function s(u){if(_T===void 0)try{throw Error()}catch(R){var f=R.stack.trim().match(/\n( *(at )?)/);_T=f&&f[1]||"",s9=-1<R.stack.indexOf(`
    at`)?" (<anonymous>)":-1<R.stack.indexOf("@")?"@unknown:0:0":""}return`
`+_T+u+s9}function r(u,f){if(!u||JT)return"";JT=!0;var R=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var F={DetermineComponentFrameRoot:function(){try{if(f){var zt=function(){throw Error()};if(Object.defineProperty(zt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(zt,[])}catch(nn){var Wt=nn}Reflect.construct(u,[],zt)}else{try{zt.call()}catch(nn){Wt=nn}u.call(zt.prototype)}}else{try{throw Error()}catch(nn){Wt=nn}(zt=u())&&typeof zt.catch=="function"&&zt.catch(function(){})}}catch(nn){if(nn&&Wt&&typeof nn.stack=="string")return[nn.stack,Wt.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],ge=AA[1];if(GA&&ge){var be=GA.split(`
`),nt=ge.split(`
`);for(Y=F=0;F<be.length&&!be[F].includes("DetermineComponentFrameRoot");)F++;for(;Y<nt.length&&!nt[Y].includes("DetermineComponentFrameRoot");)Y++;if(F===be.length||Y===nt.length)for(F=be.length-1,Y=nt.length-1;1<=F&&0<=Y&&be[F]!==nt[Y];)Y--;for(;1<=F&&0<=Y;F--,Y--)if(be[F]!==nt[Y]){if(F!==1||Y!==1)do if(F--,Y--,0>Y||be[F]!==nt[Y]){var Nt=`
`+be[F].replace(" at new "," at ");return u.displayName&&Nt.includes("<anonymous>")&&(Nt=Nt.replace("<anonymous>",u.displayName)),Nt}while(1<=F&&0<=Y);break}}}finally{JT=!1,Error.prepareStackTrace=R}return(R=u?u.displayName||u.name:"")?s(R):""}function a(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=r(u.type,!1),u;case 11:return u=r(u.type.render,!1),u;case 1:return u=r(u.type,!0),u;default:return""}}function I(u){try{var f="";do f+=a(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,ge=Y.child;ge;){if(ge===R){GA=!0,R=Y,F=AA;break}if(ge===F){GA=!0,F=Y,R=AA;break}ge=ge.sibling}if(!GA){for(ge=AA.child;ge;){if(ge===R){GA=!0,R=AA,F=Y;break}if(ge===F){GA=!0,F=AA,R=Y;break}ge=ge.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=HT[Qy],HT[Qy]=null,Qy--)}function y(u,f){Qy++,HT[Qy]=u.current,u.current=f}function m(u){return u>>>=0,u===0?32:31-(m0A(u)/S0A|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 ge=R&134217727;return ge!==0?(R=ge&~Y,R!==0?F=D(R):(AA&=ge,AA!==0?F=D(AA):u||(GA=ge&~GA,GA!==0&&(F=D(GA))))):(ge=R&~Y,ge!==0?F=D(ge):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=RG;return RG<<=1,!(RG&4194176)&&(RG=128),u}function M(){var u=GG;return GG<<=1,!(GG&62914560)&&(GG=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 ge=u.entanglements,be=u.expirationTimes,nt=u.hiddenUpdates;for(R=GA&~R;0<R;){var Nt=31-SI(R),zt=1<<Nt;ge[Nt]=0,be[Nt]=-1;var Wt=nt[Nt];if(Wt!==null)for(nt[Nt]=null,Nt=0;Nt<Wt.length;Nt++){var nn=Wt[Nt];nn!==null&&(nn.lane&=-536870913)}R&=~zt}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-SI(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-SI(R),Y=1<<F;Y&f|u[F]&f&&(u[F]|=f),R&=~Y}}function T(u){return u&=-u,2<u?8<u?u&134217727?32:268435456:8:2}function v(u){if(wI&&typeof wI.onCommitFiberRoot=="function")try{wI.onCommitFiberRoot(e0,u,void 0,(u.current.flags&128)===128)}catch{}}function U(u){if(typeof R0A=="function"&&G0A(u),wI&&typeof wI.setStrictMode=="function")try{wI.setStrictMode(e0,u)}catch{}}function x(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}function q(u,f){if(typeof u=="object"&&u!==null){var R=U9.get(u);return R!==void 0?R:(f={value:u,source:f,stack:I(f)},U9.set(u,f),f)}return{value:u,source:f,stack:I(f)}}function z(u,f){dy[hy++]=vG,dy[hy++]=UG,UG=u,vG=f}function Z(u,f,R){BC[EC++]=LB,BC[EC++]=xB,BC[EC++]=eh,eh=u;var F=LB;u=xB;var Y=32-SI(F)-1;F&=~(1<<Y),R+=1;var AA=32-SI(f)+Y;if(30<AA){var GA=Y-Y%5;AA=(F&(1<<GA)-1).toString(32),F>>=GA,Y-=GA,LB=1<<32-SI(f)+Y|R<<Y|F,xB=AA+u}else LB=1<<AA|R<<Y|F,xB=u}function eA(u){u.return!==null&&(z(u,1),Z(u,1,0))}function aA(u){for(;u===UG;)UG=dy[--hy],dy[hy]=null,vG=dy[--hy],dy[hy]=null;for(;u===eh;)eh=BC[--EC],BC[EC]=null,xB=BC[--EC],BC[EC]=null,LB=BC[--EC],BC[EC]=null}function sA(u,f){y(DQ,f),y(t0,u),y(Ir,null),u=cwA(f),p(Ir),y(Ir,u)}function pA(){p(Ir),p(t0),p(DQ)}function gA(u){u.memoizedState!==null&&y(KG,u);var f=Ir.current,R=lwA(f,u.type);f!==R&&(y(t0,u),y(Ir,R))}function yA(u){t0.current===u&&(p(Ir),p(t0)),KG.current===u&&(p(KG),JB?Ah._currentValue=Ey:Ah._currentValue2=Ey)}function fA(u){var f=Error(n(418,""));throw L(q(f,u)),jT}function RA(u,f){if(!cC)throw Error(n(175));o0A(u.stateNode,u.type,u.memoizedProps,f,u)||fA(u)}function YA(u){for(ca=u.return;ca;)switch(ca.tag){case 3:case 27:dl=!0;return;case 5:case 13:dl=!1;return;default:ca=ca.return}}function W(u){if(!cC||u!==ca)return!1;if(!eg)return YA(u),eg=!0,!1;var f=!1;if(Kr?u.tag!==3&&u.tag!==27&&(u.tag!==5||y9(u.type)&&!NG(u.type,u.memoizedProps))&&(f=!0):u.tag!==3&&(u.tag!==5||y9(u.type)&&!NG(u.type,u.memoizedProps))&&(f=!0),f&&Fr&&fA(u),YA(u),u.tag===13){if(!cC)throw Error(n(316));if(u=u.memoizedState,u=u!==null?u.dehydrated:null,!u)throw Error(n(317));Fr=a0A(u)}else Fr=ca?p9(u.stateNode):null;return!0}function $(){cC&&(Fr=ca=null,eg=!1)}function L(u){hc===null?hc=[u]:hc.push(u)}function H(){for(var u=py,f=zT=py=0;f<u;){var R=QC[f];QC[f++]=null;var F=QC[f];QC[f++]=null;var Y=QC[f];QC[f++]=null;var AA=QC[f];if(QC[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){QC[py++]=u,QC[py++]=f,QC[py++]=R,QC[py++]=F,zT|=F,u.lanes|=F,u=u.alternate,u!==null&&(u.lanes|=F)}function tA(u,f,R,F){return P(u,f,R,F),CA(u)}function iA(u,f){return P(u,null,null,f),CA(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-SI(R),AA=AA.hiddenUpdates,u=AA[Y],u===null?AA[Y]=[f]:u.push(f),f.lane=R|536870912)}function CA(u){if(50<C0)throw C0=0,Iq=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?FG=fy=u:fy=fy.next=u),_G=!0,ZT||(ZT=!0,wA(uA))}function _A(u,f){if(!WT&&_G){WT=!0;do for(var R=!1,F=FG;F!==null;){if(u!==0){var Y=F.pendingLanes;if(Y===0)var AA=0;else{var GA=F.suspendedLanes,ge=F.pingedLanes;AA=(1<<31-SI(42|u)+1)-1,AA&=Y&~(GA&~ge),AA=AA&201326677?AA&201326677|1:AA?AA|2:0}AA!==0&&(R=!0,lA(F,AA))}else AA=zn,AA=S(F,F===Lg?AA:0),!(AA&3)||k(F,AA)||(R=!0,lA(F,AA));F=F.next}while(R);WT=!1}}function uA(){_G=ZT=!1;var u=0;yy!==0&&(fwA()&&(u=yy),yy=0);for(var f=dc(),R=null,F=FG;F!==null;){var Y=F.next,AA=X(F,f);AA===0?(F.next=null,R===null?FG=Y:R.next=Y,Y===null&&(fy=R)):(R=F,(u!==0||AA&3)&&(_G=!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-SI(AA),ge=1<<GA,be=Y[GA];be===-1?(!(ge&R)||ge&F)&&(Y[GA]=N(ge,f)):be<=f&&(u.expiredLanes|=ge),AA&=~ge}if(f=Lg,R=zn,R=S(u,u===f?R:0),F=u.callbackNode,R===0||u===f&&xg===2||u.cancelPendingCommit!==null)return F!==null&&F!==null&&OT(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&&OT(F),T(R)){case 2:case 8:R=M0A;break;case 32:R=PT;break;case 268435456:R=N0A;break;default:R=PT}return F=O.bind(null,u),R=bG(R,F),u.callbackPriority=f,u.callbackNode=R,f}return F!==null&&F!==null&&OT(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=zn;return F=S(u,u===Lg?F:0),F===0?null:(Ca(u,F,f),X(u,dc()),u.callbackNode!=null&&u.callbackNode===R?O.bind(null,u):null)}function lA(u,f){if(Vd())return null;Ca(u,f,!0)}function wA(u){kwA?MwA(function(){wg&6?bG(b9,u):u()}):bG(b9,u)}function xA(){return yy===0&&(yy=G()),yy}function HA(u,f){if(i0===null){var R=i0=[];VT=0,Dy=xA(),my={status:"pending",value:void 0,then:function(F){R.push(F)}}}return VT++,f.then(zA,zA),f}function zA(){if(--VT===0&&i0!==null){my!==null&&(my.status="fulfilled");var u=i0;i0=null,Dy=0,my=null;for(var f=0;f<u.length;f++)(0,u[f])()}}function ne(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 ye(u){u.updateQueue={baseState:u.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ee(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 QA(u,f,R){var F=u.updateQueue;if(F===null)return null;if(F=F.shared,wg&2){var Y=F.pending;return Y===null?f.next=f:(f.next=Y.next,Y.next=f),F.pending=f,f=CA(u),oA(u,null,R),f}return P(u,F,f,R),CA(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 VA(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 KA(){if(XT){var u=my;if(u!==null)throw u}}function Ie(u,f,R,F){XT=!1;var Y=u.updateQueue;mQ=!1;var AA=Y.firstBaseUpdate,GA=Y.lastBaseUpdate,ge=Y.shared.pending;if(ge!==null){Y.shared.pending=null;var be=ge,nt=be.next;be.next=null,GA===null?AA=nt:GA.next=nt,GA=be;var Nt=u.alternate;Nt!==null&&(Nt=Nt.updateQueue,ge=Nt.lastBaseUpdate,ge!==GA&&(ge===null?Nt.firstBaseUpdate=nt:ge.next=nt,Nt.lastBaseUpdate=be))}if(AA!==null){var zt=Y.baseState;GA=0,Nt=nt=be=null,ge=AA;do{var Wt=ge.lane&-536870913,nn=Wt!==ge.lane;if(nn?(zn&Wt)===Wt:(F&Wt)===Wt){Wt!==0&&Wt===Dy&&(XT=!0),Nt!==null&&(Nt=Nt.next={lane:0,tag:ge.tag,payload:ge.payload,callback:null,next:null});A:{var hC=u,c0=ge;Wt=f;var Ih=R;switch(c0.tag){case 1:if(hC=c0.payload,typeof hC=="function"){zt=hC.call(Ih,zt,Wt);break A}zt=hC;break A;case 3:hC.flags=hC.flags&-65537|128;case 0:if(hC=c0.payload,Wt=typeof hC=="function"?hC.call(Ih,zt,Wt):hC,Wt==null)break A;zt=GT({},zt,Wt);break A;case 2:mQ=!0}}Wt=ge.callback,Wt!==null&&(u.flags|=64,nn&&(u.flags|=8192),nn=Y.callbacks,nn===null?Y.callbacks=[Wt]:nn.push(Wt))}else nn={lane:Wt,tag:ge.tag,payload:ge.payload,callback:ge.callback,next:null},Nt===null?(nt=Nt=nn,be=zt):Nt=Nt.next=nn,GA|=Wt;if(ge=ge.next,ge===null){if(ge=Y.shared.pending,ge===null)break;nn=ge,ge=nn.next,nn.next=null,Y.lastBaseUpdate=nn,Y.shared.pending=null}}while(!0);Nt===null&&(be=zt),Y.baseState=be,Y.firstBaseUpdate=nt,Y.lastBaseUpdate=Nt,AA===null&&(Y.shared.lanes=0),kQ|=GA,u.lanes=GA,u.memoizedState=zt}}function DA(u,f){if(typeof u!="function")throw Error(n(191,u));u.call(f)}function IA(u,f){var R=u.callbacks;if(R!==null)for(u.callbacks=null,u=0;u<R.length;u++)DA(R[u],f)}function EA(u,f){if(kI(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(!b0A.call(f,Y)||!kI(u[Y],f[Y]))return!1}return!0}function j(u){return u=u.status,u==="fulfilled"||u==="rejected"}function dA(){}function hA(u,f,R){switch(R=u[R],R===void 0?u.push(f):R!==f&&(f.then(dA,dA),f=R),f.status){case"fulfilled":return f.value;case"rejected":throw u=f.reason,u===n0?Error(n(483)):u;default:if(typeof f.status=="string")f.then(dA,dA);else{if(u=Lg,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===n0?Error(n(483)):u}throw Sy=f,n0}}function UA(){if(Sy===null)throw Error(n(459));var u=Sy;return Sy=null,u}function TA(u){var f=g0;return g0+=1,wy===null&&(wy=[]),hA(wy,u,f)}function se(u,f){f=f.props.ref,u.ref=f!==void 0?f:null}function Ne(u,f){throw f.$$typeof===owA?Error(n(525)):(u=Object.prototype.toString.call(f),Error(n(31,u==="[object Object]"?"object with keys {"+Object.keys(f).join(", ")+"}":u)))}function Ke(u){var f=u._init;return f(u._payload)}function At(u){function f(Je,Re){if(u){var qe=Je.deletions;qe===null?(Je.deletions=[Re],Je.flags|=16):qe.push(Re)}}function R(Je,Re){if(!u)return null;for(;Re!==null;)f(Je,Re),Re=Re.sibling;return null}function F(Je){for(var Re=new Map;Je!==null;)Je.key!==null?Re.set(Je.key,Je):Re.set(Je.index,Je),Je=Je.sibling;return Re}function Y(Je,Re){return Je=hQ(Je,Re),Je.index=0,Je.sibling=null,Je}function AA(Je,Re,qe){return Je.index=qe,u?(qe=Je.alternate,qe!==null?(qe=qe.index,qe<Re?(Je.flags|=33554434,Re):qe):(Je.flags|=33554434,Re)):(Je.flags|=1048576,Re)}function GA(Je){return u&&Je.alternate===null&&(Je.flags|=33554434),Je}function ge(Je,Re,qe,mt){return Re===null||Re.tag!==6?(Re=MT(qe,Je.mode,mt),Re.return=Je,Re):(Re=Y(Re,qe),Re.return=Je,Re)}function be(Je,Re,qe,mt){var Bi=qe.type;return Bi===By?Nt(Je,Re,qe.props.children,mt,qe.key):Re!==null&&(Re.elementType===Bi||typeof Bi=="object"&&Bi!==null&&Bi.$$typeof===fQ&&Ke(Bi)===Re.type)?(Re=Y(Re,qe.props),se(Re,qe),Re.return=Je,Re):(Re=wG(qe.type,qe.key,qe.props,null,Je.mode,mt),se(Re,qe),Re.return=Je,Re)}function nt(Je,Re,qe,mt){return Re===null||Re.tag!==4||Re.stateNode.containerInfo!==qe.containerInfo||Re.stateNode.implementation!==qe.implementation?(Re=NT(qe,Je.mode,mt),Re.return=Je,Re):(Re=Y(Re,qe.children||[]),Re.return=Je,Re)}function Nt(Je,Re,qe,mt,Bi){return Re===null||Re.tag!==7?(Re=Xd(qe,Je.mode,mt,Bi),Re.return=Je,Re):(Re=Y(Re,qe),Re.return=Je,Re)}function zt(Je,Re,qe){if(typeof Re=="string"&&Re!==""||typeof Re=="number"||typeof Re=="bigint")return Re=MT(""+Re,Je.mode,qe),Re.return=Je,Re;if(typeof Re=="object"&&Re!==null){switch(Re.$$typeof){case kG:return qe=wG(Re.type,Re.key,Re.props,null,Je.mode,qe),se(qe,Re),qe.return=Je,qe;case ly:return Re=NT(Re,Je.mode,qe),Re.return=Je,Re;case fQ:var mt=Re._init;return Re=mt(Re._payload),zt(Je,Re,qe)}if(MG(Re)||g(Re))return Re=Xd(Re,Je.mode,qe,null),Re.return=Je,Re;if(typeof Re.then=="function")return zt(Je,TA(Re),qe);if(Re.$$typeof===pQ)return zt(Je,re(Je,Re),qe);Ne(Je,Re)}return null}function Wt(Je,Re,qe,mt){var Bi=Re!==null?Re.key:null;if(typeof qe=="string"&&qe!==""||typeof qe=="number"||typeof qe=="bigint")return Bi!==null?null:ge(Je,Re,""+qe,mt);if(typeof qe=="object"&&qe!==null){switch(qe.$$typeof){case kG:return qe.key===Bi?be(Je,Re,qe,mt):null;case ly:return qe.key===Bi?nt(Je,Re,qe,mt):null;case fQ:return Bi=qe._init,qe=Bi(qe._payload),Wt(Je,Re,qe,mt)}if(MG(qe)||g(qe))return Bi!==null?null:Nt(Je,Re,qe,mt,null);if(typeof qe.then=="function")return Wt(Je,Re,TA(qe),mt);if(qe.$$typeof===pQ)return Wt(Je,Re,re(Je,qe),mt);Ne(Je,qe)}return null}function nn(Je,Re,qe,mt,Bi){if(typeof mt=="string"&&mt!==""||typeof mt=="number"||typeof mt=="bigint")return Je=Je.get(qe)||null,ge(Re,Je,""+mt,Bi);if(typeof mt=="object"&&mt!==null){switch(mt.$$typeof){case kG:return Je=Je.get(mt.key===null?qe:mt.key)||null,be(Re,Je,mt,Bi);case ly:return Je=Je.get(mt.key===null?qe:mt.key)||null,nt(Re,Je,mt,Bi);case fQ:var jg=mt._init;return mt=jg(mt._payload),nn(Je,Re,qe,mt,Bi)}if(MG(mt)||g(mt))return Je=Je.get(qe)||null,Nt(Re,Je,mt,Bi,null);if(typeof mt.then=="function")return nn(Je,Re,qe,TA(mt),Bi);if(mt.$$typeof===pQ)return nn(Je,Re,qe,re(Re,mt),Bi);Ne(Re,mt)}return null}function hC(Je,Re,qe,mt){for(var Bi=null,jg=null,_i=Re,tg=Re=0,Hs=null;_i!==null&&tg<qe.length;tg++){_i.index>tg?(Hs=_i,_i=null):Hs=_i.sibling;var ig=Wt(Je,_i,qe[tg],mt);if(ig===null){_i===null&&(_i=Hs);break}u&&_i&&ig.alternate===null&&f(Je,_i),Re=AA(ig,Re,tg),jg===null?Bi=ig:jg.sibling=ig,jg=ig,_i=Hs}if(tg===qe.length)return R(Je,_i),eg&&z(Je,tg),Bi;if(_i===null){for(;tg<qe.length;tg++)_i=zt(Je,qe[tg],mt),_i!==null&&(Re=AA(_i,Re,tg),jg===null?Bi=_i:jg.sibling=_i,jg=_i);return eg&&z(Je,tg),Bi}for(_i=F(_i);tg<qe.length;tg++)Hs=nn(_i,Je,tg,qe[tg],mt),Hs!==null&&(u&&Hs.alternate!==null&&_i.delete(Hs.key===null?tg:Hs.key),Re=AA(Hs,Re,tg),jg===null?Bi=Hs:jg.sibling=Hs,jg=Hs);return u&&_i.forEach(function(NQ){return f(Je,NQ)}),eg&&z(Je,tg),Bi}function c0(Je,Re,qe,mt){if(qe==null)throw Error(n(151));for(var Bi=null,jg=null,_i=Re,tg=Re=0,Hs=null,ig=qe.next();_i!==null&&!ig.done;tg++,ig=qe.next()){_i.index>tg?(Hs=_i,_i=null):Hs=_i.sibling;var NQ=Wt(Je,_i,ig.value,mt);if(NQ===null){_i===null&&(_i=Hs);break}u&&_i&&NQ.alternate===null&&f(Je,_i),Re=AA(NQ,Re,tg),jg===null?Bi=NQ:jg.sibling=NQ,jg=NQ,_i=Hs}if(ig.done)return R(Je,_i),eg&&z(Je,tg),Bi;if(_i===null){for(;!ig.done;tg++,ig=qe.next())ig=zt(Je,ig.value,mt),ig!==null&&(Re=AA(ig,Re,tg),jg===null?Bi=ig:jg.sibling=ig,jg=ig);return eg&&z(Je,tg),Bi}for(_i=F(_i);!ig.done;tg++,ig=qe.next())ig=nn(_i,Je,tg,ig.value,mt),ig!==null&&(u&&ig.alternate!==null&&_i.delete(ig.key===null?tg:ig.key),Re=AA(ig,Re,tg),jg===null?Bi=ig:jg.sibling=ig,jg=ig);return u&&_i.forEach(function(L0A){return f(Je,L0A)}),eg&&z(Je,tg),Bi}function Ih(Je,Re,qe,mt){if(typeof qe=="object"&&qe!==null&&qe.type===By&&qe.key===null&&(qe=qe.props.children),typeof qe=="object"&&qe!==null){switch(qe.$$typeof){case kG:A:{for(var Bi=qe.key;Re!==null;){if(Re.key===Bi){if(Bi=qe.type,Bi===By){if(Re.tag===7){R(Je,Re.sibling),mt=Y(Re,qe.props.children),mt.return=Je,Je=mt;break A}}else if(Re.elementType===Bi||typeof Bi=="object"&&Bi!==null&&Bi.$$typeof===fQ&&Ke(Bi)===Re.type){R(Je,Re.sibling),mt=Y(Re,qe.props),se(mt,qe),mt.return=Je,Je=mt;break A}R(Je,Re);break}else f(Je,Re);Re=Re.sibling}qe.type===By?(mt=Xd(qe.props.children,Je.mode,mt,qe.key),mt.return=Je,Je=mt):(mt=wG(qe.type,qe.key,qe.props,null,Je.mode,mt),se(mt,qe),mt.return=Je,Je=mt)}return GA(Je);case ly:A:{for(Bi=qe.key;Re!==null;){if(Re.key===Bi)if(Re.tag===4&&Re.stateNode.containerInfo===qe.containerInfo&&Re.stateNode.implementation===qe.implementation){R(Je,Re.sibling),mt=Y(Re,qe.children||[]),mt.return=Je,Je=mt;break A}else{R(Je,Re);break}else f(Je,Re);Re=Re.sibling}mt=NT(qe,Je.mode,mt),mt.return=Je,Je=mt}return GA(Je);case fQ:return Bi=qe._init,qe=Bi(qe._payload),Ih(Je,Re,qe,mt)}if(MG(qe))return hC(Je,Re,qe,mt);if(g(qe)){if(Bi=g(qe),typeof Bi!="function")throw Error(n(150));return qe=Bi.call(qe),c0(Je,Re,qe,mt)}if(typeof qe.then=="function")return Ih(Je,Re,TA(qe),mt);if(qe.$$typeof===pQ)return Ih(Je,Re,re(Je,qe),mt);Ne(Je,qe)}return typeof qe=="string"&&qe!==""||typeof qe=="number"||typeof qe=="bigint"?(qe=""+qe,Re!==null&&Re.tag===6?(R(Je,Re.sibling),mt=Y(Re,qe),mt.return=Je,Je=mt):(R(Je,Re),mt=MT(qe,Je.mode,mt),mt.return=Je,Je=mt),GA(Je)):R(Je,Re)}return function(Je,Re,qe,mt){try{g0=0;var Bi=Ih(Je,Re,qe,mt);return wy=null,Bi}catch(_i){if(_i===n0)throw _i;var jg=t(29,_i,null,Je.mode);return jg.lanes=mt,jg.return=Je,jg}finally{}}}function ni(u,f){u=HB,y(LG,u),y(ky,f),HB=u|f.baseLanes}function Ge(){y(LG,HB),y(ky,ky.current)}function st(){HB=LG.current,p(ky),p(LG)}function Rt(u){var f=u.alternate;y(Ms,Ms.current&1),y(uC,u),hl===null&&(f===null||ky.current!==null||f.memoizedState!==null)&&(hl=u)}function Et(u){if(u.tag===22){if(y(Ms,Ms.current),y(uC,u),hl===null){var f=u.alternate;f!==null&&f.memoizedState!==null&&(hl=u)}}else _t()}function _t(){y(Ms,Ms.current),y(uC,uC.current)}function vt(u){p(uC),hl===u&&(hl=null),p(Ms)}function xt(u){for(var f=u;f!==null;){if(f.tag===13){var R=f.memoizedState;if(R!==null&&(R=R.dehydrated,R===null||TT(R)||qT(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 ee(){throw Error(n(321))}function Oe(u,f){if(f===null)return!1;for(var R=0;R<f.length&&R<u.length;R++)if(!kI(u[R],f[R]))return!1;return!0}function We(u,f,R,F,Y,AA){return SQ=AA,fn=f,f.memoizedState=null,f.updateQueue=null,f.lanes=0,Oi.H=u===null||u.memoizedState===null?nh:wQ,ih=!1,AA=R(F,Y),ih=!1,My&&(AA=kA(f,R,F,Y)),pt(u),AA}function pt(u){Oi.H=pl;var f=Sg!==null&&Sg.next!==null;if(SQ=0,ns=Sg=fn=null,xG=!1,o0=0,Ny=null,f)throw Error(n(300));u===null||qs||(u=u.dependencies,u!==null&&sC(u)&&(qs=!0))}function kA(u,f,R,F){fn=u;var Y=0;do{if(My&&(Ny=null),o0=0,My=!1,25<=Y)throw Error(n(301));if(Y+=1,ns=Sg=null,u.updateQueue!=null){var AA=u.updateQueue;AA.lastEffect=null,AA.events=null,AA.stores=null,AA.memoCache!=null&&(AA.memoCache.index=0)}Oi.H=gh,AA=f(R,F)}while(My);return AA}function oe(){var u=Oi.H,f=u.useState()[0];return f=typeof f.then=="function"?te(f):f,u=u.useState()[0],(Sg!==null?Sg.memoizedState:null)!==u&&(fn.flags|=1024),f}function ae(){var u=TG!==0;return TG=0,u}function $A(u,f,R){f.updateQueue=u.updateQueue,f.flags&=-2053,u.lanes&=~R}function nA(u){if(xG){for(u=u.memoizedState;u!==null;){var f=u.queue;f!==null&&(f.pending=null),u=u.next}xG=!1}SQ=0,ns=Sg=fn=null,My=!1,o0=TG=0,Ny=null}function vA(){var u={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return ns===null?fn.memoizedState=ns=u:ns=ns.next=u,ns}function FA(){if(Sg===null){var u=fn.alternate;u=u!==null?u.memoizedState:null}else u=Sg.next;var f=ns===null?fn.memoizedState:ns.next;if(f!==null)ns=f,Sg=u;else{if(u===null)throw fn.alternate===null?Error(n(467)):Error(n(310));Sg=u,u={memoizedState:Sg.memoizedState,baseState:Sg.baseState,baseQueue:Sg.baseQueue,queue:Sg.queue,next:null},ns===null?fn.memoizedState=ns=u:ns=ns.next=u}return ns}function te(u){var f=o0;return o0+=1,Ny===null&&(Ny=[]),u=hA(Ny,u,f),f=fn,(ns===null?f.memoizedState:ns.next)===null&&(f=f.alternate,Oi.H=f===null||f.memoizedState===null?nh:wQ),u}function bA(u){if(u!==null&&typeof u=="object"){if(typeof u.then=="function")return te(u);if(u.$$typeof===pQ)return LA(u)}throw Error(n(438,String(u)))}function De(u){var f=null,R=fn.updateQueue;if(R!==null&&(f=R.memoCache),f==null){var F=fn.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=Aq(),fn.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]=rwA;return f.index++,R}function jA(u,f){return typeof f=="function"?f(u):f}function me(u){var f=FA();return le(f,Sg,u)}function le(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 ge=GA=null,be=null,nt=f,Nt=!1;do{var zt=nt.lane&-536870913;if(zt!==nt.lane?(zn&zt)===zt:(SQ&zt)===zt){var Wt=nt.revertLane;if(Wt===0)be!==null&&(be=be.next={lane:0,revertLane:0,action:nt.action,hasEagerState:nt.hasEagerState,eagerState:nt.eagerState,next:null}),zt===Dy&&(Nt=!0);else if((SQ&Wt)===Wt){nt=nt.next,Wt===Dy&&(Nt=!0);continue}else zt={lane:0,revertLane:nt.revertLane,action:nt.action,hasEagerState:nt.hasEagerState,eagerState:nt.eagerState,next:null},be===null?(ge=be=zt,GA=AA):be=be.next=zt,fn.lanes|=Wt,kQ|=Wt;zt=nt.action,ih&&R(AA,zt),AA=nt.hasEagerState?nt.eagerState:R(AA,zt)}else Wt={lane:zt,revertLane:nt.revertLane,action:nt.action,hasEagerState:nt.hasEagerState,eagerState:nt.eagerState,next:null},be===null?(ge=be=Wt,GA=AA):be=be.next=Wt,fn.lanes|=zt,kQ|=zt;nt=nt.next}while(nt!==null&&nt!==f);if(be===null?GA=AA:be.next=ge,!kI(AA,u.memoizedState)&&(qs=!0,Nt&&(R=my,R!==null)))throw R;u.memoizedState=AA,u.baseState=GA,u.baseQueue=be,F.lastRenderedState=AA}return Y===null&&(F.lanes=0),[u.memoizedState,F.dispatch]}function qA(u){var f=FA(),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);kI(AA,f.memoizedState)||(qs=!0),f.memoizedState=AA,f.baseQueue===null&&(f.baseState=AA),R.lastRenderedState=AA}return[AA,F]}function WA(u,f,R){var F=fn,Y=FA(),AA=eg;if(AA){if(R===void 0)throw Error(n(407));R=R()}else R=f();var GA=!kI((Sg||Y).memoizedState,R);if(GA&&(Y.memoizedState=R,qs=!0),Y=Y.queue,lo(ce.bind(null,F,Y,u),[u]),Y.getSnapshot!==f||GA||ns!==null&&ns.memoizedState.tag&1){if(F.flags|=2048,xi(9,Qe.bind(null,F,Y,R,f),{destroy:void 0},null),Lg===null)throw Error(n(349));AA||SQ&60||Se(F,f,R)}return R}function Se(u,f,R){u.flags|=16384,u={getSnapshot:f,value:R},f=fn.updateQueue,f===null?(f=Aq(),fn.updateQueue=f,f.stores=[u]):(R=f.stores,R===null?f.stores=[u]:R.push(u))}function Qe(u,f,R,F){f.value=R,f.getSnapshot=F,Ve(f)&&Dt(u)}function ce(u,f,R){return R(function(){Ve(f)&&Dt(u)})}function Ve(u){var f=u.getSnapshot;u=u.value;try{var R=f();return!kI(u,R)}catch{return!0}}function Dt(u){var f=iA(u,2);f!==null&&uo(f,u,2)}function Mt(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:jA,lastRenderedState:u},f}function ct(u,f,R,F){return u.baseState=R,le(u,Sg,typeof F=="function"?F:jA)}function gt(u,f,R,F,Y){if(qt(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)}};Oi.T!==null?R(!0):AA.isTransition=!1,F(AA),R=f.pending,R===null?(AA.next=f.pending=AA,et(f,AA)):(AA.next=R.next,f.pending=R.next=AA)}}function et(u,f){var R=f.action,F=f.payload,Y=u.state;if(f.isTransition){var AA=Oi.T,GA={};Oi.T=GA;try{var ge=R(Y,F),be=Oi.S;be!==null&&be(GA,ge),Li(u,f,ge)}catch(nt){gi(u,f,nt)}finally{Oi.T=AA}}else try{AA=R(Y,F),Li(u,f,AA)}catch(nt){gi(u,f,nt)}}function Li(u,f,R){R!==null&&typeof R=="object"&&typeof R.then=="function"?R.then(function(F){Ri(u,f,F)},function(F){return gi(u,f,F)}):Ri(u,f,R)}function Ri(u,f,R){f.status="fulfilled",f.value=R,Jt(f),u.state=R,f=u.pending,f!==null&&(R=f.next,R===f?u.pending=null:(R=R.next,f.next=R,et(u,R)))}function gi(u,f,R){var F=u.pending;if(u.pending=null,F!==null){F=F.next;do f.status="rejected",f.reason=R,Jt(f),f=f.next;while(f!==F)}u.action=null}function Jt(u){u=u.listeners;for(var f=0;f<u.length;f++)(0,u[f])()}function jt(u,f){return f}function Ci(u,f){if(eg){var R=Lg.formState;if(R!==null){A:{var F=fn;if(eg){if(Fr){var Y=$wA(Fr,dl);if(Y){Fr=p9(Y),F=A0A(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:jt,lastRenderedState:f},R.queue=F,R=$e.bind(null,fn,F),F.dispatch=R,F=Mt(!1);var AA=Ot.bind(null,fn,!1,F.queue);return F=vA(),Y={state:f,dispatch:null,action:u,pending:null},F.queue=Y,R=gt.bind(null,fn,Y,AA,R),Y.dispatch=R,F.memoizedState=u,[f,R,!1]}function Pi(u){var f=FA();return si(f,Sg,u)}function si(u,f,R){f=le(u,f,jt)[0],u=me(jA)[0],f=typeof f=="object"&&f!==null&&typeof f.then=="function"?te(f):f;var F=FA(),Y=F.queue,AA=Y.dispatch;return R!==F.memoizedState&&(fn.flags|=2048,xi(9,pi.bind(null,Y,R),{destroy:void 0},null)),[f,AA,u]}function pi(u,f){u.action=f}function Ai(u){var f=FA(),R=Sg;if(R!==null)return si(f,R,u);FA(),f=f.memoizedState,R=FA();var F=R.queue.dispatch;return R.memoizedState=u,[f,F,!1]}function xi(u,f,R,F){return u={tag:u,create:f,inst:R,deps:F,next:null},f=fn.updateQueue,f===null&&(f=Aq(),fn.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 ui(){return FA().memoizedState}function ie(u,f,R,F){var Y=vA();fn.flags|=u,Y.memoizedState=xi(1|f,R,{destroy:void 0},F===void 0?null:F)}function ln(u,f,R,F){var Y=FA();F=F===void 0?null:F;var AA=Y.memoizedState.inst;Sg!==null&&F!==null&&Oe(F,Sg.memoizedState.deps)?Y.memoizedState=xi(f,R,AA,F):(fn.flags|=u,Y.memoizedState=xi(1|f,R,AA,F))}function Zt(u,f){ie(8390656,8,u,f)}function lo(u,f){ln(2048,8,u,f)}function Hg(u,f){return ln(4,2,u,f)}function xo(u,f){return ln(4,4,u,f)}function Cg(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 Dg(u,f,R){R=R!=null?R.concat([u]):null,ln(4,4,Cg.bind(null,f,u),R)}function ng(){}function wo(u,f){var R=FA();f=f===void 0?null:f;var F=R.memoizedState;return f!==null&&Oe(f,F[1])?F[0]:(R.memoizedState=[u,f],u)}function fe(u,f){var R=FA();f=f===void 0?null:f;var F=R.memoizedState;if(f!==null&&Oe(f,F[1]))return F[0];if(F=u(),ih){U(!0);try{u()}finally{U(!1)}}return R.memoizedState=[F,f],F}function Pe(u,f,R){return R===void 0||SQ&1073741824?u.memoizedState=f:(u.memoizedState=R,u=ul(),fn.lanes|=u,kQ|=u,R)}function OA(u,f,R,F){return kI(R,f)?R:ky.current!==null?(u=Pe(u,R,F),kI(u,f)||(qs=!0),u):SQ&42?(u=ul(),fn.lanes|=u,kQ|=u,f):(qs=!0,u.memoizedState=R)}function XA(u,f,R,F,Y){var AA=$d();xa(AA!==0&&8>AA?AA:8);var GA=Oi.T,ge={};Oi.T=ge,Ot(u,!1,f,R);try{var be=Y(),nt=Oi.S;if(nt!==null&&nt(ge,be),be!==null&&typeof be=="object"&&typeof be.then=="function"){var Nt=ne(be,F);Gt(u,f,Nt,Pg(u))}else Gt(u,f,F,Pg(u))}catch(zt){Gt(u,f,{then:function(){},status:"rejected",reason:zt},Pg())}finally{xa(AA),Oi.T=GA}}function _e(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:jA,lastRenderedState:Ey},next:null};var R={};return f.next={memoizedState:R,baseState:R,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jA,lastRenderedState:R},next:null},u.memoizedState=f,u=u.alternate,u!==null&&(u.memoizedState=f),f}function xe(){return LA(Ah)}function rA(){return FA().memoizedState}function pe(){return FA().memoizedState}function Fe(u){for(var f=u.return;f!==null;){switch(f.tag){case 24:case 3:var R=Pg();u=NA(R);var F=QA(f,u,R);F!==null&&(uo(F,f,R),PA(F,f,R)),f={cache:ue()},u.payload=f;return}f=f.return}}function je(u,f,R){var F=Pg();R={lane:F,revertLane:0,action:R,hasEagerState:!1,eagerState:null,next:null},qt(u)?ei(f,R):(R=tA(u,f,R,F),R!==null&&(uo(R,u,F),Yt(R,f,F)))}function $e(u,f,R){var F=Pg();Gt(u,f,R,F)}function Gt(u,f,R,F){var Y={lane:F,revertLane:0,action:R,hasEagerState:!1,eagerState:null,next:null};if(qt(u))ei(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,ge=AA(GA,R);if(Y.hasEagerState=!0,Y.eagerState=ge,kI(ge,GA))return P(u,f,Y,0),Lg===null&&H(),!1}catch{}finally{}if(R=tA(u,f,Y,F),R!==null)return uo(R,u,F),Yt(R,f,F),!0}return!1}function Ot(u,f,R,F){if(F={lane:2,revertLane:xA(),action:F,hasEagerState:!1,eagerState:null,next:null},qt(u)){if(f)throw Error(n(479))}else f=tA(u,R,F,2),f!==null&&uo(f,u,2)}function qt(u){var f=u.alternate;return u===fn||f!==null&&f===fn}function ei(u,f){My=xG=!0;var R=u.pending;R===null?f.next=f:(f.next=R.next,R.next=f),u.pending=f}function Yt(u,f,R){if(R&4194176){var F=f.lanes;F&=u.pendingLanes,R|=F,f.lanes=R,J(u,R)}}function Ce(u,f,R,F){f=u.memoizedState,R=R(F,f),R=R==null?f:GT({},f,R),u.memoizedState=R,u.lanes===0&&(u.updateQueue.baseState=R)}function it(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?!EA(R,F)||!EA(Y,AA):!0}function dt(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&&eq.enqueueReplaceState(f,f.state,null)}function ft(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=GT({},R));for(var Y in u)R[Y]===void 0&&(R[Y]=u[Y])}return R}function ci(u,f){try{var R=u.onUncaughtError;R(f.value,{componentStack:f.stack})}catch(F){setTimeout(function(){throw F})}}function Hi(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 Wi(u,f,R){return R=NA(R),R.tag=3,R.payload={element:null},R.callback=function(){ci(u,f)},R}function Vi(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(){Hi(f,R,F)}}var GA=R.stateNode;GA!==null&&typeof GA.componentDidCatch=="function"&&(u.callback=function(){Hi(f,R,F),typeof Y!="function"&&(MQ===null?MQ=new Set([this]):MQ.add(this));var ge=F.stack;this.componentDidCatch(F.value,{componentStack:ge!==null?ge:""})})}function Bo(u,f,R,F,Y){if(R.flags|=32768,F!==null&&typeof F=="object"&&typeof F.then=="function"){if(f=R.alternate,f!==null&&Bc(f,R,Y,!0),R=uC.current,R!==null){switch(R.tag){case 13:return hl===null?mT():R.alternate===null&&No===0&&(No=3),R.flags&=-257,R.flags|=65536,R.lanes=Y,F===JG?R.flags|=16384:(f=R.updateQueue,f===null?R.updateQueue=new Set([F]):f.add(F),wT(u,F,Y)),!1;case 22:return R.flags|=65536,F===JG?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)),wT(u,F,Y)),!1}throw Error(n(435,R.tag))}return wT(u,F,Y),mT(),!1}if(eg)return f=uC.current,f!==null?(!(f.flags&65536)&&(f.flags|=256),f.flags|=65536,f.lanes=Y,F!==jT&&(u=Error(n(422),{cause:F}),L(q(u,R)))):(F!==jT&&(f=Error(n(423),{cause:F}),L(q(f,R))),u=u.current.alternate,u.flags|=65536,Y&=-Y,u.lanes|=Y,F=q(F,R),Y=Wi(u.stateNode,F,Y),VA(u,Y),No!==4&&(No=2)),!1;var AA=Error(n(520),{cause:F});if(AA=q(AA,R),r0===null?r0=[AA]:r0.push(AA),No!==4&&(No=2),f===null)return!0;F=q(F,R),R=f;do{switch(R.tag){case 3:return R.flags|=65536,u=Y&-Y,R.lanes|=u,u=Wi(R.stateNode,F,u),VA(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"&&(MQ===null||!MQ.has(AA))))return R.flags|=65536,Y&=-Y,R.lanes|=Y,Y=Vi(Y),hi(Y,u,R,F),VA(R,Y),!1}R=R.return}while(R!==null);return!1}function Fn(u,f,R,F){f.child=u===null?v9(f,null,R,F):th(f,u.child,R,F)}function ea(u,f,R,F,Y){R=R.render;var AA=f.ref;if("ref"in F){var GA={};for(var ge in F)ge!=="ref"&&(GA[ge]=F[ge])}else GA=F;return BA(f),F=We(u,f,R,GA,AA,Y),ge=ae(),u!==null&&!qs?($A(u,f,Y),To(u,f,Y)):(eg&&ge&&eA(f),f.flags|=1,Fn(u,f,F,Y),f.child)}function ta(u,f,R,F,Y){if(u===null){var AA=R.type;return typeof AA=="function"&&!kT(AA)&&AA.defaultProps===void 0&&R.compare===null?(f.tag=15,f.type=AA,ia(u,f,AA,F,Y)):(u=wG(R.type,null,F,f,f.mode,Y),u.ref=f.ref,u.return=f,f.child=u)}if(AA=u.child,!pI(u,Y)){var GA=AA.memoizedProps;if(R=R.compare,R=R!==null?R:EA,R(GA,F)&&u.ref===f.ref)return To(u,f,Y)}return f.flags|=1,u=hQ(AA,F),u.ref=f.ref,u.return=f,f.child=u}function ia(u,f,R,F,Y){if(u!==null){var AA=u.memoizedProps;if(EA(AA,F)&&u.ref===f.ref)if(qs=!1,f.pendingProps=F=AA,pI(u,Y))u.flags&131072&&(qs=!0);else return f.lanes=u.lanes,To(u,f,Y)}return Og(u,f,R,F,Y)}function na(u,f,R){var F=f.pendingProps,Y=F.children,AA=(f.stateNode._pendingVisibility&2)!==0,GA=u!==null?u.memoizedState:null;if(Eo(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 hI(u,f,F,R)}if(R&536870912)f.memoizedState={baseLanes:0,cachePool:null},u!==null&&rt(f,GA!==null?GA.cachePool:null),GA!==null?ni(f,GA):Ge(),Et(f);else return f.lanes=f.childLanes=536870912,hI(u,f,GA!==null?GA.baseLanes|R:R,R)}else GA!==null?(rt(f,GA.cachePool),ni(f,GA),_t(),f.memoizedState=null):(u!==null&&rt(f,null),Ge(),_t());return Fn(u,f,Y,R),f.child}function hI(u,f,R,F){var Y=Te();return Y=Y===null?null:{parent:JB?ko._currentValue:ko._currentValue2,pool:Y},f.memoizedState={baseLanes:R,cachePool:Y},u!==null&&rt(f,null),Ge(),Et(f),u!==null&&Bc(u,f,F,!0),null}function Eo(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 Og(u,f,R,F,Y){return BA(f),R=We(u,f,R,F,void 0,Y),F=ae(),u!==null&&!qs?($A(u,f,Y),To(u,f,Y)):(eg&&F&&eA(f),f.flags|=1,Fn(u,f,R,Y),f.child)}function cl(u,f,R,F,Y,AA){return BA(f),f.updateQueue=null,R=kA(f,F,R,Y),pt(u),F=ae(),u!==null&&!qs?($A(u,f,AA),To(u,f,AA)):(eg&&F&&eA(f),f.flags|=1,Fn(u,f,R,AA),f.child)}function ga(u,f,R,F,Y){if(BA(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=eq,f.stateNode=AA,AA._reactInternals=f,AA=f.stateNode,AA.props=F,AA.state=f.memoizedState,AA.refs={},ye(f),GA=R.contextType,AA.context=typeof GA=="object"&&GA!==null?LA(GA):uy,AA.state=f.memoizedState,GA=R.getDerivedStateFromProps,typeof GA=="function"&&(Ce(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&&eq.enqueueReplaceState(AA,AA.state,null),Ie(f,F,AA,Y),KA(),AA.state=f.memoizedState),typeof AA.componentDidMount=="function"&&(f.flags|=4194308),F=!0}else if(u===null){AA=f.stateNode;var ge=f.memoizedProps,be=ft(R,ge);AA.props=be;var nt=AA.context,Nt=R.contextType;GA=uy,typeof Nt=="object"&&Nt!==null&&(GA=LA(Nt));var zt=R.getDerivedStateFromProps;Nt=typeof zt=="function"||typeof AA.getSnapshotBeforeUpdate=="function",ge=f.pendingProps!==ge,Nt||typeof AA.UNSAFE_componentWillReceiveProps!="function"&&typeof AA.componentWillReceiveProps!="function"||(ge||nt!==GA)&&dt(f,AA,F,GA),mQ=!1;var Wt=f.memoizedState;AA.state=Wt,Ie(f,F,AA,Y),KA(),nt=f.memoizedState,ge||Wt!==nt||mQ?(typeof zt=="function"&&(Ce(f,R,zt,F),nt=f.memoizedState),(be=mQ||it(f,R,be,F,Wt,nt,GA))?(Nt||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=nt),AA.props=F,AA.state=nt,AA.context=GA,F=be):(typeof AA.componentDidMount=="function"&&(f.flags|=4194308),F=!1)}else{AA=f.stateNode,Ee(u,f),GA=f.memoizedProps,Nt=ft(R,GA),AA.props=Nt,zt=f.pendingProps,Wt=AA.context,nt=R.contextType,be=uy,typeof nt=="object"&&nt!==null&&(be=LA(nt)),ge=R.getDerivedStateFromProps,(nt=typeof ge=="function"||typeof AA.getSnapshotBeforeUpdate=="function")||typeof AA.UNSAFE_componentWillReceiveProps!="function"&&typeof AA.componentWillReceiveProps!="function"||(GA!==zt||Wt!==be)&&dt(f,AA,F,be),mQ=!1,Wt=f.memoizedState,AA.state=Wt,Ie(f,F,AA,Y),KA();var nn=f.memoizedState;GA!==zt||Wt!==nn||mQ||u!==null&&u.dependencies!==null&&sC(u.dependencies)?(typeof ge=="function"&&(Ce(f,R,ge,F),nn=f.memoizedState),(Nt=mQ||it(f,R,Nt,F,Wt,nn,be)||u!==null&&u.dependencies!==null&&sC(u.dependencies))?(nt||typeof AA.UNSAFE_componentWillUpdate!="function"&&typeof AA.componentWillUpdate!="function"||(typeof AA.componentWillUpdate=="function"&&AA.componentWillUpdate(F,nn,be),typeof AA.UNSAFE_componentWillUpdate=="function"&&AA.UNSAFE_componentWillUpdate(F,nn,be)),typeof AA.componentDidUpdate=="function"&&(f.flags|=4),typeof AA.getSnapshotBeforeUpdate=="function"&&(f.flags|=1024)):(typeof AA.componentDidUpdate!="function"||GA===u.memoizedProps&&Wt===u.memoizedState||(f.flags|=4),typeof AA.getSnapshotBeforeUpdate!="function"||GA===u.memoizedProps&&Wt===u.memoizedState||(f.flags|=1024),f.memoizedProps=F,f.memoizedState=nn),AA.props=F,AA.state=nn,AA.context=be,F=Nt):(typeof AA.componentDidUpdate!="function"||GA===u.memoizedProps&&Wt===u.memoizedState||(f.flags|=4),typeof AA.getSnapshotBeforeUpdate!="function"||GA===u.memoizedProps&&Wt===u.memoizedState||(f.flags|=1024),F=!1)}return AA=F,Eo(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)):Fn(u,f,R,Y),f.memoizedState=AA.state,u=f.child):u=To(u,f,Y),u}function Od(u,f,R,F){return $(),f.flags|=256,Fn(u,f,R,F),f.child}function lc(u){return{baseLanes:u,cachePool:Qt()}}function ll(u,f,R){return u=u!==null?u.childLanes&~R:0,f&&(u|=dC),u}function ry(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:(Ms.current&2)!==0),GA&&(Y=!0,f.flags&=-129),GA=(f.flags&32)!==0,f.flags&=-33,u===null){if(eg){if(Y?Rt(f):_t(),eg){var ge=Fr,be;(be=ge)&&(ge=g0A(ge,dl),ge!==null?(f.memoizedState={dehydrated:ge,treeContext:eh!==null?{id:LB,overflow:xB}:null,retryLane:536870912},be=t(18,null,null,0),be.stateNode=ge,be.return=f,f.child=be,ca=f,Fr=null,be=!0):be=!1),be||fA(f)}if(ge=f.memoizedState,ge!==null&&(ge=ge.dehydrated,ge!==null))return qT(ge)?f.lanes=16:f.lanes=536870912,null;vt(f)}return ge=F.children,F=F.fallback,Y?(_t(),Y=f.mode,ge=Bl({mode:"hidden",children:ge},Y),F=Xd(F,Y,R,null),ge.return=f,F.return=f,ge.sibling=F,f.child=ge,Y=f.child,Y.memoizedState=lc(R),Y.childLanes=ll(u,GA,R),f.memoizedState=tq,F):(Rt(f),oa(f,ge))}if(be=u.memoizedState,be!==null&&(ge=be.dehydrated,ge!==null)){if(AA)f.flags&256?(Rt(f),f.flags&=-257,f=Pd(u,f,R)):f.memoizedState!==null?(_t(),f.child=u.child,f.flags|=128,f=null):(_t(),Y=F.fallback,ge=f.mode,F=Bl({mode:"visible",children:F.children},ge),Y=Xd(Y,ge,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=lc(R),F.childLanes=ll(u,GA,R),f.memoizedState=tq,f=Y);else if(Rt(f),qT(ge))GA=VwA(ge).digest,F=Error(n(419)),F.stack="",F.digest=GA,L({value:F,source:null,stack:null}),f=Pd(u,f,R);else if(qs||Bc(u,f,R,!1),GA=(R&u.childLanes)!==0,qs||GA){if(GA=Lg,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!==be.retryLane)throw be.retryLane=F,iA(u,F),uo(GA,u,F),F9}TT(ge)||mT(),f=Pd(u,f,R)}else TT(ge)?(f.flags|=128,f.child=u.child,f=AwA.bind(null,u),XwA(ge,f),f=null):(u=be.treeContext,cC&&(Fr=t0A(ge),ca=f,eg=!0,hc=null,dl=!1,u!==null&&(BC[EC++]=LB,BC[EC++]=xB,BC[EC++]=eh,LB=u.id,xB=u.overflow,eh=f)),f=oa(f,F.children),f.flags|=4096);return f}return Y?(_t(),Y=F.fallback,ge=f.mode,be=u.child,AA=be.sibling,F=hQ(be,{mode:"hidden",children:F.children}),F.subtreeFlags=be.subtreeFlags&31457280,AA!==null?Y=hQ(AA,Y):(Y=Xd(Y,ge,R,null),Y.flags|=2),Y.return=f,F.return=f,F.sibling=Y,f.child=F,F=Y,Y=f.child,ge=u.child.memoizedState,ge===null?ge=lc(R):(be=ge.cachePool,be!==null?(AA=JB?ko._currentValue:ko._currentValue2,be=be.parent!==AA?{parent:AA,pool:AA}:be):be=Qt(),ge={baseLanes:ge.baseLanes|R,cachePool:be}),Y.memoizedState=ge,Y.childLanes=ll(u,GA,R),f.memoizedState=tq,F):(Rt(f),R=u.child,u=R.sibling,R=hQ(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 oa(u,f){return f=Bl({mode:"visible",children:f},u.mode),f.return=u,u.child=f}function Bl(u,f){return VV(u,f,0,null)}function Pd(u,f,R){return th(f,u.child,null,R),u=oa(f,f.pendingProps.children),u.flags|=2,f.memoizedState=null,u}function vB(u,f,R){u.lanes|=f;var F=u.alternate;F!==null&&(F.lanes|=f),ra(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 ay(u,f,R){var F=f.pendingProps,Y=F.revealOrder,AA=F.tail;if(Fn(u,f,F.children,R),F=Ms.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&&vB(u,R,f);else if(u.tag===19)vB(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(Ms,F),Y){case"forwards":for(R=f.child,Y=null;R!==null;)u=R.alternate,u!==null&&xt(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&&xt(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 To(u,f,R){if(u!==null&&(f.dependencies=u.dependencies),kQ|=f.lanes,!(R&f.childLanes))if(u!==null){if(Bc(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=hQ(u,u.pendingProps),f.child=R,R.return=f;u.sibling!==null;)u=u.sibling,R=R.sibling=hQ(u,u.pendingProps),R.return=f;R.sibling=null}return f.child}function pI(u,f){return u.lanes&f?!0:(u=u.dependencies,!!(u!==null&&sC(u)))}function Pw(u,f,R){switch(f.tag){case 3:sA(f,f.stateNode.containerInfo),sa(f,ko,u.memoizedState.cache),$();break;case 27:case 5:gA(f);break;case 4:sA(f,f.stateNode.containerInfo);break;case 10:sa(f,f.type,f.memoizedProps.value);break;case 13:var F=f.memoizedState;if(F!==null)return F.dehydrated!==null?(Rt(f),f.flags|=128,null):R&f.child.childLanes?ry(u,f,R):(Rt(f),u=To(u,f,R),u!==null?u.sibling:null);Rt(f);break;case 19:var Y=(u.flags&128)!==0;if(F=(R&f.childLanes)!==0,F||(Bc(u,f,R,!1),F=(R&f.childLanes)!==0),Y){if(F)return ay(u,f,R);f.flags|=128}if(Y=f.memoizedState,Y!==null&&(Y.rendering=null,Y.tail=null,Y.lastEffect=null),y(Ms,Ms.current),F)break;return null;case 22:case 23:return f.lanes=0,na(u,f,R);case 24:sa(f,ko,u.memoizedState.cache)}return To(u,f,R)}function fI(u,f,R){if(u!==null)if(u.memoizedProps!==f.pendingProps)qs=!0;else{if(!pI(u,R)&&!(f.flags&128))return qs=!1,Pw(u,f,R);qs=!!(u.flags&131072)}else qs=!1,eg&&f.flags&1048576&&Z(f,vG,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")kT(F)?(u=ft(F,u),f.tag=1,f=ga(null,f,F,u,R)):(f.tag=0,f=Og(null,f,F,u,R));else{if(F!=null){if(Y=F.$$typeof,Y===UT){f.tag=11,f=ea(null,f,F,u,R);break A}else if(Y===FT){f.tag=14,f=ta(null,f,F,u,R);break A}}throw f=o(F)||F,Error(n(306,f,""))}}return f;case 0:return Og(u,f,f.type,f.pendingProps,R);case 1:return F=f.type,Y=ft(F,f.pendingProps),ga(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,Ee(u,f),Ie(f,AA,null,R);var GA=f.memoizedState;if(AA=GA.cache,sa(f,ko,AA),AA!==Y.cache&&yI(f,[ko],R,!0),KA(),AA=GA.element,cC&&Y.isDehydrated)if(Y={element:AA,isDehydrated:!1,cache:GA.cache},f.updateQueue.baseState=Y,f.memoizedState=Y,f.flags&256){f=Od(u,f,AA,R);break A}else if(AA!==F){F=q(Error(n(424)),f),L(F),f=Od(u,f,AA,R);break A}else for(cC&&(Fr=e0A(f.stateNode.containerInfo),ca=f,eg=!0,hc=null,dl=!0),R=v9(f,null,AA,R),f.child=R;R;)R.flags=R.flags&-3|4096,R=R.sibling;else{if($(),AA===F){f=To(u,f,R);break A}Fn(u,f,AA,R)}f=f.child}return f;case 26:if(lC)return Eo(u,f),u===null?(R=m9(f.type,null,f.pendingProps,null))?f.memoizedState=R:eg||(f.stateNode=u0A(f.type,f.pendingProps,DQ.current,f)):f.memoizedState=m9(f.type,u.memoizedProps,f.pendingProps,u.memoizedState),null;case 27:if(Kr)return gA(f),u===null&&Kr&&eg&&(F=f.stateNode=R9(f.type,f.pendingProps,DQ.current,Ir.current,!1),ca=f,dl=!0,Fr=f9(F)),F=f.pendingProps.children,u!==null||eg?Fn(u,f,F,R):f.child=th(f,null,F,R),Eo(u,f),f.child;case 5:return u===null&&eg&&(B0A(f.type,f.pendingProps,Ir.current),(Y=F=Fr)&&(F=i0A(F,f.type,f.pendingProps,dl),F!==null?(f.stateNode=F,ca=f,Fr=f9(F),dl=!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,NG(Y,AA)?F=null:GA!==null&&NG(Y,GA)&&(f.flags|=32),f.memoizedState!==null&&(Y=We(u,f,oe,null,null,R),JB?Ah._currentValue=Y:Ah._currentValue2=Y),Eo(u,f),Fn(u,f,F,R),f.child;case 6:return u===null&&eg&&(E0A(f.pendingProps,Ir.current),(u=R=Fr)&&(R=n0A(R,f.pendingProps,dl),R!==null?(f.stateNode=R,ca=f,Fr=null,u=!0):u=!1),u||fA(f)),null;case 13:return ry(u,f,R);case 4:return sA(f,f.stateNode.containerInfo),F=f.pendingProps,u===null?f.child=th(f,null,F,R):Fn(u,f,F,R),f.child;case 11:return ea(u,f,f.type,f.pendingProps,R);case 7:return Fn(u,f,f.pendingProps,R),f.child;case 8:return Fn(u,f,f.pendingProps.children,R),f.child;case 12:return Fn(u,f,f.pendingProps.children,R),f.child;case 10:return F=f.pendingProps,sa(f,f.type,F.value),Fn(u,f,F.children,R),f.child;case 9:return Y=f.type._context,F=f.pendingProps.children,BA(f),Y=LA(Y),F=F(Y),f.flags|=1,Fn(u,f,F,R),f.child;case 14:return ta(u,f,f.type,f.pendingProps,R);case 15:return ia(u,f,f.type,f.pendingProps,R);case 19:return ay(u,f,R);case 22:return na(u,f,R);case 24:return BA(f),F=LA(ko),u===null?(Y=Te(),Y===null&&(Y=Lg,AA=ue(),Y.pooledCache=AA,AA.refCount++,AA!==null&&(Y.pooledCacheLanes|=R),Y=AA),f.memoizedState={parent:F,cache:Y},ye(f),sa(f,ko,Y)):(u.lanes&R&&(Ee(u,f),Ie(f,null,null,R),KA()),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),sa(f,ko,F)):(F=AA.cache,sa(f,ko,F),F!==Y.cache&&yI(f,[ko],R,!0))),Fn(u,f,f.pendingProps.children,R),f.child;case 29:throw f.pendingProps}throw Error(n(156,f.tag))}function sa(u,f,R){JB?(y(qG,f._currentValue),f._currentValue=R):(y(qG,f._currentValue2),f._currentValue2=R)}function Nr(u){var f=qG.current;JB?u._currentValue=f:u._currentValue2=f,p(qG)}function ra(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 yI(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 ge=AA;AA=Y;for(var be=0;be<f.length;be++)if(ge.context===f[be]){AA.lanes|=R,ge=AA.alternate,ge!==null&&(ge.lanes|=R),ra(AA.return,R,u),F||(GA=null);break A}AA=ge.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),ra(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 Bc(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 ge=Y.type;kI(Y.pendingProps.value,GA.value)||(u!==null?u.push(ge):u=[ge])}}else if(Y===KG.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&&yI(f,u,R,F),f.flags|=262144}function sC(u){for(u=u.firstContext;u!==null;){var f=u.context;if(!kI(JB?f._currentValue:f._currentValue2,u.memoizedValue))return!0;u=u.next}return!1}function BA(u){oh=u,TB=null,u=u.dependencies,u!==null&&(u.firstContext=null)}function LA(u){return ke(oh,u)}function re(u,f){return oh===null&&BA(u),ke(u,f)}function ke(u,f){var R=JB?f._currentValue:f._currentValue2;if(f={context:f,memoizedValue:R,next:null},TB===null){if(u===null)throw Error(n(308));TB=f,u.dependencies={lanes:0,firstContext:f},u.flags|=524288}else TB=TB.next=f;return R}function ue(){return{controller:new v0A,data:new Map,refCount:0}}function Le(u){u.refCount--,u.refCount===0&&K0A(F0A,function(){u.controller.abort()})}function Te(){var u=sh.current;return u!==null?u:Lg.pooledCache}function rt(u,f){f===null?y(sh,sh.current):y(sh,f.pool)}function Qt(){var u=Te();return u===null?null:{parent:JB?ko._currentValue:ko._currentValue2,pool:u}}function Bn(u){u.flags|=4}function gg(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 Ln(u,f,R,F){if(vr)for(R=f.child;R!==null;){if(R.tag===5||R.tag===6)LT(u,R.stateNode);else if(!(R.tag===4||Kr&&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(yQ)for(var Y=f.child;Y!==null;){if(Y.tag===5){var AA=Y.stateNode;R&&F&&(AA=d9(AA,Y.type,Y.memoizedProps)),LT(u,AA)}else if(Y.tag===6)AA=Y.stateNode,R&&F&&(AA=h9(AA,Y.memoizedProps)),LT(u,AA);else if(Y.tag!==4){if(Y.tag===22&&Y.memoizedState!==null)AA=Y.child,AA!==null&&(AA.return=Y),Ln(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 og(u,f,R,F){if(yQ)for(var Y=f.child;Y!==null;){if(Y.tag===5){var AA=Y.stateNode;R&&F&&(AA=d9(AA,Y.type,Y.memoizedProps)),Q9(u,AA)}else if(Y.tag===6)AA=Y.stateNode,R&&F&&(AA=h9(AA,Y.memoizedProps)),Q9(u,AA);else if(Y.tag!==4){if(Y.tag===22&&Y.memoizedState!==null)AA=Y.child,AA!==null&&(AA.return=Y),og(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 ks(u,f){if(yQ&&gg(u,f)){u=f.stateNode;var R=u.containerInfo,F=E9();og(F,f,!1,!1),u.pendingChildren=F,Bn(f),WwA(R,F)}}function to(u,f,R,F){if(vr)u.memoizedProps!==F&&Bn(f);else if(yQ){var Y=u.stateNode,AA=u.memoizedProps;if((u=gg(u,f))||AA!==F){var GA=Ir.current;AA=ZwA(Y,R,AA,F,!u,null),AA===Y?f.stateNode=Y:(a9(AA,R,F,GA)&&Bn(f),f.stateNode=AA,u?Ln(AA,f,!1,!1):Bn(f))}else f.stateNode=Y}}function xn(u,f,R){if(DwA(f,R)){if(u.flags|=16777216,!c9(f,R))if(dQ())u.flags|=8192;else throw Sy=JG,$T}else u.flags&=-16777217}function En(u,f){if(h0A(f)){if(u.flags|=16777216,!N9(f))if(dQ())u.flags|=8192;else throw Sy=JG,$T}else u.flags&=-16777217}function mg(u,f){f!==null&&(u.flags|=4),u.flags&16384&&(f=u.tag!==22?M():536870912,u.lanes|=f,by|=f)}function Qo(u,f){if(!eg)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 yi(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 fi(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 yi(f),null;case 1:return yi(f),null;case 3:return R=f.stateNode,F=null,u!==null&&(F=u.memoizedState.cache),f.memoizedState.cache!==F&&(f.flags|=2048),Nr(ko),pA(),R.pendingContext&&(R.context=R.pendingContext,R.pendingContext=null),(u===null||u.child===null)&&(W(f)?Bn(f):u===null||u.memoizedState.isDehydrated&&!(f.flags&256)||(f.flags|=1024,hc!==null&&(IC(hc),hc=null))),ks(u,f),yi(f),null;case 26:if(lC){R=f.type;var Y=f.memoizedState;return u===null?(Bn(f),Y!==null?(yi(f),En(f,Y)):(yi(f),xn(f,R,F))):Y?Y!==u.memoizedState?(Bn(f),yi(f),En(f,Y)):(yi(f),f.flags&=-16777217):(vr?u.memoizedProps!==F&&Bn(f):to(u,f,R,F),yi(f),xn(f,R,F)),null}case 27:if(Kr){if(yA(f),R=DQ.current,Y=f.type,u!==null&&f.stateNode!=null)vr?u.memoizedProps!==F&&Bn(f):to(u,f,Y,F);else{if(!F){if(f.stateNode===null)throw Error(n(166));return yi(f),null}u=Ir.current,W(f)?RA(f,u):(u=R9(Y,F,R,u,!0),f.stateNode=u,Bn(f))}return yi(f),null}case 5:if(yA(f),R=f.type,u!==null&&f.stateNode!=null)to(u,f,R,F);else{if(!F){if(f.stateNode===null)throw Error(n(166));return yi(f),null}u=Ir.current,W(f)?RA(f,u):(Y=QwA(R,F,DQ.current,u,f),Ln(Y,f,!1,!1),f.stateNode=Y,a9(Y,R,F,u)&&Bn(f))}return yi(f),xn(f,f.type,f.pendingProps),null;case 6:if(u&&f.stateNode!=null)R=u.memoizedProps,vr?R!==F&&Bn(f):yQ&&(R!==F?(f.stateNode=I9(F,DQ.current,Ir.current,f),Bn(f)):f.stateNode=u.stateNode);else{if(typeof F!="string"&&f.stateNode===null)throw Error(n(166));if(u=DQ.current,R=Ir.current,W(f)){if(!cC)throw Error(n(176));if(u=f.stateNode,R=f.memoizedProps,F=null,Y=ca,Y!==null)switch(Y.tag){case 27:case 5:F=Y.memoizedProps}s0A(u,R,f,F)||fA(f)}else f.stateNode=I9(F,u,R,f)}return yi(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(!cC)throw Error(n(344));if(Y=f.memoizedState,Y=Y!==null?Y.dehydrated:null,!Y)throw Error(n(317));r0A(Y,f)}else $(),!(f.flags&128)&&(f.memoizedState=null),f.flags|=4;yi(f),Y=!1}else hc!==null&&(IC(hc),hc=null),Y=!0;if(!Y)return f.flags&256?(vt(f),f):(vt(f),null)}if(vt(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),mg(f,f.updateQueue),yi(f),null;case 4:return pA(),ks(u,f),u===null&&hwA(f.stateNode.containerInfo),yi(f),null;case 10:return Nr(f.type),yi(f),null;case 19:if(p(Ms),Y=f.memoizedState,Y===null)return yi(f),null;if(F=(f.flags&128)!==0,AA=Y.rendering,AA===null)if(F)Qo(Y,!1);else{if(No!==0||u!==null&&u.flags&128)for(u=f.child;u!==null;){if(AA=xt(u),AA!==null){for(f.flags|=128,Qo(Y,!1),u=AA.updateQueue,f.updateQueue=u,mg(f,u),f.subtreeFlags=0,u=R,R=f.child;R!==null;)WV(R,u),R=R.sibling;return y(Ms,Ms.current&1|2),f.child}u=u.sibling}Y.tail!==null&&dc()>a0&&(f.flags|=128,F=!0,Qo(Y,!1),f.lanes=4194304)}else{if(!F)if(u=xt(AA),u!==null){if(f.flags|=128,F=!0,u=u.updateQueue,f.updateQueue=u,mg(f,u),Qo(Y,!0),Y.tail===null&&Y.tailMode==="hidden"&&!AA.alternate&&!eg)return yi(f),null}else 2*dc()-Y.renderingStartTime>a0&&R!==536870912&&(f.flags|=128,F=!0,Qo(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=dc(),f.sibling=null,u=Ms.current,y(Ms,F?u&1|2:u&1),f):(yi(f),null);case 22:case 23:return vt(f),st(),F=f.memoizedState!==null,u!==null?u.memoizedState!==null!==F&&(f.flags|=8192):F&&(f.flags|=8192),F?R&536870912&&!(f.flags&128)&&(yi(f),f.subtreeFlags&6&&(f.flags|=8192)):yi(f),R=f.updateQueue,R!==null&&mg(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),Nr(ko),yi(f),null;case 25:return null}throw Error(n(156,f.tag))}function Di(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 Nr(ko),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(vt(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(Ms),null;case 4:return pA(),null;case 10:return Nr(f.type),null;case 22:case 23:return vt(f),st(),u!==null&&p(sh),u=f.flags,u&65536?(f.flags=u&-65537|128,f):null;case 24:return Nr(ko),null;case 25:return null;default:return null}}function Qn(u,f){switch(aA(f),f.tag){case 3:Nr(ko),pA();break;case 26:case 27:case 5:yA(f);break;case 4:pA();break;case 13:vt(f);break;case 19:p(Ms);break;case 10:Nr(f.type);break;case 22:case 23:vt(f),st(),u!==null&&p(sh);break;case 24:Nr(ko)}}function Fi(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(ge){ug(f,f.return,ge)}}function qo(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,ge=GA.destroy;if(ge!==void 0){GA.destroy=void 0,Y=f;var be=R;try{ge()}catch(nt){ug(Y,be,nt)}}}F=F.next}while(F!==AA)}}catch(nt){ug(f,f.return,nt)}}function Ec(u){var f=u.updateQueue;if(f!==null){var R=u.stateNode;try{IA(f,R)}catch(F){ug(u,u.return,F)}}}function ar(u,f,R){R.props=ft(u.type,u.memoizedProps),R.state=u.memoizedState;try{R.componentWillUnmount()}catch(F){ug(u,f,F)}}function rC(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=Xw(F);break;default:Y=F}typeof R=="function"?u.refCleanup=R(Y):R.current=Y}}catch(AA){ug(u,f,AA)}}function Rr(u,f){var R=u.ref,F=u.refCleanup;if(R!==null)if(typeof F=="function")try{F()}catch(Y){ug(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){ug(u,f,Y)}else R.current=null}function io(u){var f=u.type,R=u.memoizedProps,F=u.stateNode;try{JwA(F,f,R,u)}catch(Y){ug(u,u.return,Y)}}function El(u,f,R){try{LwA(u.stateNode,u.type,R,f,u)}catch(F){ug(u,u.return,F)}}function BQ(u){return u.tag===5||u.tag===3||(lC?u.tag===26:!1)||(Kr?u.tag===27:!1)||u.tag===4}function aa(u){A:for(;;){for(;u.sibling===null;){if(u.return===null||BQ(u.return))return null;u=u.return}for(u.sibling.return=u.return,u=u.sibling;u.tag!==5&&u.tag!==6&&(!Kr||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 Ql(u,f,R){var F=u.tag;if(F===5||F===6)u=u.stateNode,f?TwA(R,u,f):FwA(R,u);else if(!(F===4||Kr&&F===27)&&(u=u.child,u!==null))for(Ql(u,f,R),u=u.sibling;u!==null;)Ql(u,f,R),u=u.sibling}function zd(u,f,R){var F=u.tag;if(F===5||F===6)u=u.stateNode,f?xwA(R,u,f):KwA(R,u);else if(!(F===4||Kr&&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 pG(u,f,R){u=u.containerInfo;try{u9(u,R)}catch(F){ug(f,f.return,F)}}function jw(u,f){for(BwA(u.containerInfo),Ys=f;Ys!==null;)if(u=Ys,f=u.child,(u.subtreeFlags&1028)!==0&&f!==null)f.return=u,Ys=f;else for(;Ys!==null;){u=Ys;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=ft(F.type,Y,F.elementType===F.type);f=AA.getSnapshotBeforeUpdate(GA,R),AA.__reactInternalSnapshotBeforeUpdate=f}catch(ge){ug(F,F.return,ge)}}break;case 3:f&1024&&vr&&zwA(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,Ys=f;break}Ys=u.return}return GA=L9,L9=!1,GA}function zw(u,f,R){var F=R.flags;switch(R.tag){case 0:case 11:case 15:aC(u,R),F&4&&Fi(5,R);break;case 1:if(aC(u,R),F&4)if(u=R.stateNode,f===null)try{u.componentDidMount()}catch(ge){ug(R,R.return,ge)}else{var Y=ft(R.type,f.memoizedProps);f=f.memoizedState;try{u.componentDidUpdate(Y,f,u.__reactInternalSnapshotBeforeUpdate)}catch(ge){ug(R,R.return,ge)}}F&64&&Ec(R),F&512&&rC(R,R.return);break;case 3:if(aC(u,R),F&64&&(F=R.updateQueue,F!==null)){if(u=null,R.child!==null)switch(R.child.tag){case 27:case 5:u=Xw(R.child.stateNode);break;case 1:u=R.child.stateNode}try{IA(F,u)}catch(ge){ug(R,R.return,ge)}}break;case 26:if(lC){aC(u,R),F&512&&rC(R,R.return);break}case 27:case 5:aC(u,R),f===null&&F&4&&io(R),F&512&&rC(R,R.return);break;case 12:aC(u,R);break;case 13:aC(u,R),F&4&&Zw(u,R);break;case 22:if(Y=R.memoizedState!==null||qB,!Y){f=f!==null&&f.memoizedState!==null||Mo;var AA=qB,GA=Mo;qB=Y,(Mo=f)&&!GA?Qc(u,R,(R.subtreeFlags&8772)!==0):aC(u,R),qB=AA,Mo=GA}F&512&&(R.memoizedProps.mode==="manual"?rC(R,R.return):Rr(R,R.return));break;default:aC(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&&ywA(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 DI(u,f,R){for(R=R.child;R!==null;)EQ(u,f,R),R=R.sibling}function EQ(u,f,R){if(wI&&typeof wI.onCommitFiberUnmount=="function")try{wI.onCommitFiberUnmount(e0,R)}catch{}switch(R.tag){case 26:if(lC){Mo||Rr(R,f),DI(u,f,R),R.memoizedState?w9(R.memoizedState):R.stateNode&&M9(R.stateNode);break}case 27:if(Kr){Mo||Rr(R,f);var F=gs,Y=MI;gs=R.stateNode,DI(u,f,R),D0A(R.stateNode),gs=F,MI=Y;break}case 5:Mo||Rr(R,f);case 6:if(vr){if(F=gs,Y=MI,gs=null,DI(u,f,R),gs=F,MI=Y,gs!==null)if(MI)try{YwA(gs,R.stateNode)}catch(AA){ug(R,f,AA)}else try{qwA(gs,R.stateNode)}catch(AA){ug(R,f,AA)}}else DI(u,f,R);break;case 18:vr&&gs!==null&&(MI?l0A(gs,R.stateNode):c0A(gs,R.stateNode));break;case 4:vr?(F=gs,Y=MI,gs=R.stateNode.containerInfo,MI=!0,DI(u,f,R),gs=F,MI=Y):(yQ&&pG(R.stateNode,R,E9()),DI(u,f,R));break;case 0:case 11:case 14:case 15:Mo||qo(2,R,f),Mo||qo(4,R,f),DI(u,f,R);break;case 1:Mo||(Rr(R,f),F=R.stateNode,typeof F.componentWillUnmount=="function"&&ar(R,f,F)),DI(u,f,R);break;case 21:DI(u,f,R);break;case 22:Mo||Rr(R,f),Mo=(F=Mo)||R.memoizedState!==null,DI(u,f,R),Mo=F;break;default:DI(u,f,R)}}function Zw(u,f){if(cC&&f.memoizedState===null&&(u=f.alternate,u!==null&&(u=u.memoizedState,u!==null&&(u=u.dehydrated,u!==null))))try{C0A(u)}catch(R){ug(f,f.return,R)}}function fG(u){switch(u.tag){case 13:case 19:var f=u.stateNode;return f===null&&(f=u.stateNode=new J9),f;case 22:return u=u.stateNode,f=u._retryCache,f===null&&(f=u._retryCache=new J9),f;default:throw Error(n(435,u.tag))}}function Ia(u,f){var R=fG(u);f.forEach(function(F){var Y=ewA.bind(null,u,F);R.has(F)||(R.add(F),F.then(Y,Y))})}function Gr(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(vr){var ge=GA;A:for(;ge!==null;){switch(ge.tag){case 27:case 5:gs=ge.stateNode,MI=!1;break A;case 3:gs=ge.stateNode.containerInfo,MI=!0;break A;case 4:gs=ge.stateNode.containerInfo,MI=!0;break A}ge=ge.return}if(gs===null)throw Error(n(160));EQ(AA,GA,Y),gs=null,MI=!1}else EQ(AA,GA,Y);AA=Y.alternate,AA!==null&&(AA.return=null),Y.return=null}if(f.subtreeFlags&13878)for(f=f.child;f!==null;)yG(f,u),f=f.sibling}function yG(u,f){var R=u.alternate,F=u.flags;switch(u.tag){case 0:case 11:case 14:case 15:Gr(f,u),La(u),F&4&&(qo(3,u,u.return),Fi(3,u),qo(5,u,u.return));break;case 1:Gr(f,u),La(u),F&512&&(Mo||R===null||Rr(R,R.return)),F&64&&qB&&(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(lC){var Y=pc;Gr(f,u),La(u),F&512&&(Mo||R===null||Rr(R,R.return)),F&4&&(F=R!==null?R.memoizedState:null,f=u.memoizedState,R===null?f===null?u.stateNode===null?u.stateNode=Q0A(Y,u.type,u.memoizedProps,u):k9(Y,u.type,u.stateNode):u.stateNode=S9(Y,f,u.memoizedProps):F!==f?(F===null?R.stateNode!==null&&M9(R.stateNode):w9(F),f===null?k9(Y,u.type,u.stateNode):S9(Y,f,u.memoizedProps)):f===null&&u.stateNode!==null&&El(u,u.memoizedProps,R.memoizedProps));break}case 27:if(Kr&&F&4&&u.alternate===null){Y=u.stateNode;var AA=u.memoizedProps;try{f0A(Y),y0A(u.type,AA,Y,u)}catch(Nt){ug(u,u.return,Nt)}}case 5:if(Gr(f,u),La(u),F&512&&(Mo||R===null||Rr(R,R.return)),vr){if(u.flags&32){f=u.stateNode;try{B9(f)}catch(Nt){ug(u,u.return,Nt)}}F&4&&u.stateNode!=null&&(f=u.memoizedProps,El(u,f,R!==null?R.memoizedProps:f)),F&1024&&(iq=!0)}break;case 6:if(Gr(f,u),La(u),F&4&&vr){if(u.stateNode===null)throw Error(n(162));F=u.memoizedProps,R=R!==null?R.memoizedProps:F,f=u.stateNode;try{_wA(f,R,F)}catch(Nt){ug(u,u.return,Nt)}}break;case 3:if(lC?(d0A(),Y=pc,pc=YT(f.containerInfo),Gr(f,u),pc=Y):Gr(f,u),La(u),F&4){if(vr&&cC&&R!==null&&R.memoizedState.isDehydrated)try{I0A(f.containerInfo)}catch(Nt){ug(u,u.return,Nt)}if(yQ){F=f.containerInfo,R=f.pendingChildren;try{u9(F,R)}catch(Nt){ug(u,u.return,Nt)}}}iq&&(iq=!1,Ww(u));break;case 4:lC?(R=pc,pc=YT(u.stateNode.containerInfo),Gr(f,u),La(u),pc=R):(Gr(f,u),La(u)),F&4&&yQ&&pG(u.stateNode,u,u.stateNode.pendingChildren);break;case 12:Gr(f,u),La(u);break;case 13:Gr(f,u),La(u),u.child.flags&8192&&u.memoizedState!==null!=(R!==null&&R.memoizedState!==null)&&(sq=dc()),F&4&&(F=u.updateQueue,F!==null&&(u.updateQueue=null,Ia(u,F)));break;case 22:F&512&&(Mo||R===null||Rr(R,R.return)),Y=u.memoizedState!==null;var GA=R!==null&&R.memoizedState!==null,ge=qB,be=Mo;if(qB=ge||Y,Mo=be||GA,Gr(f,u),Mo=be,qB=ge,La(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=qB||Mo,R===null||GA||f||KB(u)),vr&&(u.memoizedProps===null||u.memoizedProps.mode!=="manual"))){A:if(R=null,vr)for(f=u;;){if(f.tag===5||lC&&f.tag===26||Kr&&f.tag===27){if(R===null){GA=R=f;try{AA=GA.stateNode,Y?HwA(AA):PwA(GA.stateNode,GA.memoizedProps)}catch(Nt){ug(GA,GA.return,Nt)}}}else if(f.tag===6){if(R===null){GA=f;try{var nt=GA.stateNode;Y?OwA(nt):jwA(nt,GA.memoizedProps)}catch(Nt){ug(GA,GA.return,Nt)}}}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,Ia(u,R))));break;case 19:Gr(f,u),La(u),F&4&&(F=u.updateQueue,F!==null&&(u.updateQueue=null,Ia(u,F)));break;case 21:break;default:Gr(f,u),La(u)}}function La(u){var f=u.flags;if(f&2){try{if(vr&&(!Kr||u.tag!==27)){A:{for(var R=u.return;R!==null;){if(BQ(R)){var F=R;break A}R=R.return}throw Error(n(160))}switch(F.tag){case 27:if(Kr){var Y=F.stateNode,AA=aa(u);zd(u,AA,Y);break}case 5:var GA=F.stateNode;F.flags&32&&(B9(GA),F.flags&=-33);var ge=aa(u);zd(u,ge,GA);break;case 3:case 4:var be=F.stateNode.containerInfo,nt=aa(u);Ql(u,nt,be);break;default:throw Error(n(161))}}}catch(Nt){ug(u,u.return,Nt)}u.flags&=-3}f&4096&&(u.flags&=-4097)}function Ww(u){if(u.subtreeFlags&1024)for(u=u.child;u!==null;){var f=u;Ww(f),f.tag===5&&f.flags&1024&&wwA(f.stateNode),u=u.sibling}}function aC(u,f){if(f.subtreeFlags&8772)for(f=f.child;f!==null;)zw(u,f.alternate,f),f=f.sibling}function KB(u){for(u=u.child;u!==null;){var f=u;switch(f.tag){case 0:case 11:case 14:case 15:qo(4,f,f.return),KB(f);break;case 1:Rr(f,f.return);var R=f.stateNode;typeof R.componentWillUnmount=="function"&&ar(f,f.return,R),KB(f);break;case 26:case 27:case 5:Rr(f,f.return),KB(f);break;case 22:Rr(f,f.return),f.memoizedState===null&&KB(f);break;default:KB(f)}u=u.sibling}}function Qc(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:Qc(Y,AA,R),Fi(4,AA);break;case 1:if(Qc(Y,AA,R),F=AA,Y=F.stateNode,typeof Y.componentDidMount=="function")try{Y.componentDidMount()}catch(nt){ug(F,F.return,nt)}if(F=AA,Y=F.updateQueue,Y!==null){var ge=F.stateNode;try{var be=Y.shared.hiddenCallbacks;if(be!==null)for(Y.shared.hiddenCallbacks=null,Y=0;Y<be.length;Y++)DA(be[Y],ge)}catch(nt){ug(F,F.return,nt)}}R&&GA&64&&Ec(AA),rC(AA,AA.return);break;case 26:case 27:case 5:Qc(Y,AA,R),R&&F===null&&GA&4&&io(AA),rC(AA,AA.return);break;case 12:Qc(Y,AA,R);break;case 13:Qc(Y,AA,R),R&&GA&4&&Zw(Y,AA);break;case 22:AA.memoizedState===null&&Qc(Y,AA,R),rC(AA,AA.return);break;default:Qc(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&&Le(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&&Le(u))}function uc(u,f,R,F){if(f.subtreeFlags&10256)for(f=f.child;f!==null;)Vw(u,f,R,F),f=f.sibling}function Vw(u,f,R,F){var Y=f.flags;switch(f.tag){case 0:case 11:case 15:uc(u,f,R,F),Y&2048&&Fi(9,f);break;case 3:uc(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&&Le(u)));break;case 12:if(Y&2048){uc(u,f,R,F),u=f.stateNode;try{var AA=f.memoizedProps,GA=AA.id,ge=AA.onPostCommit;typeof ge=="function"&&ge(GA,f.alternate===null?"mount":"update",u.passiveEffectDuration,-0)}catch(be){ug(f,f.return,be)}}else uc(u,f,R,F);break;case 23:break;case 22:AA=f.stateNode,f.memoizedState!==null?AA._visibility&4?uc(u,f,R,F):mA(u,f):AA._visibility&4?uc(u,f,R,F):(AA._visibility|=4,FB(u,f,R,F,(f.subtreeFlags&10256)!==0)),Y&2048&&Iy(f.alternate,f);break;case 24:uc(u,f,R,F),Y&2048&&Cy(f.alternate,f);break;default:uc(u,f,R,F)}}function FB(u,f,R,F,Y){for(Y=Y&&(f.subtreeFlags&10256)!==0,f=f.child;f!==null;){var AA=u,GA=f,ge=R,be=F,nt=GA.flags;switch(GA.tag){case 0:case 11:case 15:FB(AA,GA,ge,be,Y),Fi(8,GA);break;case 23:break;case 22:var Nt=GA.stateNode;GA.memoizedState!==null?Nt._visibility&4?FB(AA,GA,ge,be,Y):mA(AA,GA):(Nt._visibility|=4,FB(AA,GA,ge,be,Y)),Y&&nt&2048&&Iy(GA.alternate,GA);break;case 24:FB(AA,GA,ge,be,Y),Y&&nt&2048&&Cy(GA.alternate,GA);break;default:FB(AA,GA,ge,be,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;)Me(u),u=u.sibling}function Me(u){switch(u.tag){case 26:JA(u),u.flags&Ry&&(u.memoizedState!==null?p0A(pc,u.memoizedState,u.memoizedProps):l9(u.type,u.memoizedProps));break;case 5:JA(u),u.flags&Ry&&l9(u.type,u.memoizedProps);break;case 3:case 4:if(lC){var f=pc;pc=YT(u.stateNode.containerInfo),JA(u),pc=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 Ye(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 He(u){var f=u.deletions;if(u.flags&16){if(f!==null)for(var R=0;R<f.length;R++){var F=f[R];Ys=F,mi(F,u)}Ye(u)}if(u.subtreeFlags&10256)for(u=u.child;u!==null;)Ze(u),u=u.sibling}function Ze(u){switch(u.tag){case 0:case 11:case 15:He(u),u.flags&2048&&qo(9,u,u.return);break;case 3:He(u);break;case 12:He(u);break;case 22:var f=u.stateNode;u.memoizedState!==null&&f._visibility&4&&(u.return===null||u.return.tag!==13)?(f._visibility&=-5,ht(u)):He(u);break;default:He(u)}}function ht(u){var f=u.deletions;if(u.flags&16){if(f!==null)for(var R=0;R<f.length;R++){var F=f[R];Ys=F,mi(F,u)}Ye(u)}for(u=u.child;u!==null;){switch(f=u,f.tag){case 0:case 11:case 15:qo(8,f,f.return),ht(f);break;case 22:R=f.stateNode,R._visibility&4&&(R._visibility&=-5,ht(f));break;default:ht(f)}u=u.sibling}}function mi(u,f){for(;Ys!==null;){var R=Ys;switch(R.tag){case 0:case 11:case 15:qo(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:Le(R.memoizedState.cache)}if(F=R.child,F!==null)F.return=R,Ys=F;else A:for(R=u;Ys!==null;){F=Ys;var Y=F.sibling,AA=F.return;if(Zd(F),F===R){Ys=null;break A}if(Y!==null){Y.return=AA,Ys=Y;break A}Ys=AA}}}function ji(u){var f=C9(u);if(f!=null){if(typeof f.memoizedProps["data-testname"]!="string")throw Error(n(364));return f}if(u=NwA(u),u===null)throw Error(n(362));return u.stateNode.current}function is(u,f){var R=u.tag;switch(f.$$typeof){case YG:if(u.type===f.value)return!0;break;case HG: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||!A0(F)){for(;GA!=null&&is(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 OG:if((R===5||R===26||R===27)&&bwA(u.stateNode,f.value))return!0;break;case jG:if((R===5||R===6||R===26||R===27)&&(u=GwA(u),u!==null&&0<=u.indexOf(f.value)))return!0;break;case PG: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 no(u){switch(u.$$typeof){case YG:return"<"+(o(u.value)||"Unknown")+">";case HG:return":has("+(no(u)||"")+")";case OG:return'[role="'+u.value+'"]';case jG:return'"'+u.value+'"';case PG:return'[data-testname="'+u.value+'"]';default:throw Error(n(365))}}function br(u,f){var R=[];u=[u,0];for(var F=0;F<u.length;){var Y=u[F++],AA=Y.tag,GA=u[F++],ge=f[GA];if(AA!==5&&AA!==26&&AA!==27||!A0(Y)){for(;ge!=null&&is(Y,ge);)GA++,ge=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 Ts(u,f){if(!$w)throw Error(n(363));u=ji(u),u=br(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)A0(F)||f.push(F.stateNode);else for(F=F.child;F!==null;)u.push(F),F=F.sibling}return f}function Pg(){if(wg&2&&zn!==0)return zn&-zn;if(Oi.T!==null){var u=Dy;return u!==0?u:xA()}return pwA()}function ul(){dC===0&&(dC=!(zn&536870912)||eg?G():536870912);var u=uC.current;return u!==null&&(u.flags|=32),dC}function uo(u,f,R){(u===Lg&&xg===2||u.cancelPendingCommit!==null)&&(uQ(u,0),Ur(u,zn,dC,!1)),b(u,R),(!(wg&2)||u!==Lg)&&(u===Lg&&(!(wg&2)&&(rh|=R),No===4&&Ur(u,zn,dC,!1)),cA(u))}function Ca(u,f,R){if(wg&6)throw Error(n(327));var F=!R&&(f&60)===0&&(f&u.expiredLanes)===0||k(u,f),Y=F?WSA(u,f):ST(u,f,!0),AA=F;do{if(Y===0){Gy&&!F&&Ur(u,f,0,!1);break}else if(Y===6)Ur(u,f,0,!YB);else{if(R=u.current.alternate,AA&&!QQ(R)){Y=ST(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 ge=u;Y=r0;var be=cC&&ge.current.memoizedState.isDehydrated;if(be&&(uQ(ge,GA).flags|=256),GA=ST(ge,GA,!1),GA!==2){if(nq&&!be){ge.errorRecoveryDisabledLanes|=AA,rh|=AA,Y=4;break A}AA=fl,fl=Y,AA!==null&&IC(AA)}Y=GA}if(AA=!1,Y!==2)continue}}if(Y===1){uQ(u,0),Ur(u,f,0,!0);break}A:{switch(F=u,Y){case 0:case 1:throw Error(n(345));case 4:if((f&4194176)===f){Ur(F,f,dC,!YB);break A}break;case 2:fl=null;break;case 3:case 5:break;default:throw Error(n(329))}if(F.finishedWork=R,F.finishedLanes=f,(f&62914560)===f&&(AA=sq+300-dc(),10<AA)){if(Ur(F,f,dC,!YB),S(F,0)!==0)break A;F.timeoutHandle=uwA(CC.bind(null,F,R,fl,zG,oq,f,dC,rh,by,YB,2,-0,0),AA);break A}CC(F,R,fl,zG,oq,f,dC,rh,by,YB,0,-0,0)}}break}while(!0);cA(u)}function IC(u){fl===null?fl=u:fl.push.apply(fl,u)}function CC(u,f,R,F,Y,AA,GA,ge,be,nt,Nt,zt,Wt){var nn=f.subtreeFlags;if((nn&8192||(nn&16785408)===16785408)&&(mwA(),Me(f),f=SwA(),f!==null)){u.cancelPendingCommit=f(PV.bind(null,u,R,F,Y,GA,ge,be,1,zt,Wt)),Ur(u,AA,GA,!nt);return}PV(u,R,F,Y,GA,ge,be,Nt,zt,Wt)}function QQ(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(!kI(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 Ur(u,f,R,F){f&=~gq,f&=~rh,u.suspendedLanes|=f,u.pingedLanes&=~f,F&&(u.warmLanes|=f),F=u.expirationTimes;for(var Y=f;0<Y;){var AA=31-SI(Y),GA=1<<AA;F[AA]=-1,Y&=~GA}R!==0&&K(u,R,f)}function Wd(){return wg&6?!0:(_A(0),!1)}function _B(){if(kn!==null){if(xg===0)var u=kn.return;else u=kn,TB=oh=null,nA(u),wy=null,g0=0,u=kn;for(;u!==null;)Qn(u.alternate,u),u=u.return;kn=null}}function uQ(u,f){u.finishedWork=null,u.finishedLanes=0;var R=u.timeoutHandle;R!==xT&&(u.timeoutHandle=xT,dwA(R)),R=u.cancelPendingCommit,R!==null&&(u.cancelPendingCommit=null,R()),_B(),Lg=u,kn=R=hQ(u.current,null),zn=f,xg=0,NI=null,YB=!1,Gy=k(u,f),nq=!1,by=dC=gq=rh=kQ=No=0,fl=r0=null,oq=!1,f&8&&(f|=f&32);var F=u.entangledLanes;if(F!==0)for(u=u.entanglements,F&=f;0<F;){var Y=31-SI(F),AA=1<<Y;f|=u[Y],F&=~AA}return HB=f,H(),R}function DG(u,f){fn=null,Oi.H=pl,f===n0?(f=UA(),xg=3):f===$T?(f=UA(),xg=4):xg=f===F9?8:f!==null&&typeof f=="object"&&typeof f.then=="function"?6:1,NI=f,kn===null&&(No=1,ci(u,q(f,u.current)))}function dQ(){var u=uC.current;return u===null?!0:(zn&4194176)===zn?hl===null:(zn&62914560)===zn||zn&536870912?u===hl:!1}function mG(){var u=Oi.H;return Oi.H=pl,u===null?pl:u}function qV(){var u=Oi.A;return Oi.A=_0A,u}function mT(){No=4,YB||(zn&4194176)!==zn&&uC.current!==null||(Gy=!0),!(kQ&134217727)&&!(rh&134217727)||Lg===null||Ur(Lg,zn,dC,!1)}function ST(u,f,R){var F=wg;wg|=2;var Y=mG(),AA=qV();(Lg!==u||zn!==f)&&(zG=null,uQ(u,f)),f=!1;var GA=No;A:do try{if(xg!==0&&kn!==null){var ge=kn,be=NI;switch(xg){case 8:_B(),GA=6;break A;case 3:case 2:case 6:uC.current===null&&(f=!0);var nt=xg;if(xg=0,NI=null,cy(u,ge,be,nt),R&&Gy){GA=0;break A}break;default:nt=xg,xg=0,NI=null,cy(u,ge,be,nt)}}ZSA(),GA=No;break}catch(Nt){DG(u,Nt)}while(!0);return f&&u.shellSuspendCounter++,TB=oh=null,wg=F,Oi.H=Y,Oi.A=AA,kn===null&&(Lg=null,zn=0,H()),GA}function ZSA(){for(;kn!==null;)YV(kn)}function WSA(u,f){var R=wg;wg|=2;var F=mG(),Y=qV();Lg!==u||zn!==f?(zG=null,a0=dc()+500,uQ(u,f)):Gy=k(u,f);A:do try{if(xg!==0&&kn!==null){f=kn;var AA=NI;e:switch(xg){case 1:xg=0,NI=null,cy(u,f,AA,1);break;case 2:if(j(AA)){xg=0,NI=null,HV(f);break}f=function(){xg===2&&Lg===u&&(xg=7),cA(u)},AA.then(f,f);break A;case 3:xg=7;break A;case 4:xg=5;break A;case 7:j(AA)?(xg=0,NI=null,HV(f)):(xg=0,NI=null,cy(u,f,AA,7));break;case 5:var GA=null;switch(kn.tag){case 26:GA=kn.memoizedState;case 5:case 27:var ge=kn,be=ge.type,nt=ge.pendingProps;if(GA?N9(GA):c9(be,nt)){xg=0,NI=null;var Nt=ge.sibling;if(Nt!==null)kn=Nt;else{var zt=ge.return;zt!==null?(kn=zt,SG(zt)):kn=null}break e}}xg=0,NI=null,cy(u,f,AA,5);break;case 6:xg=0,NI=null,cy(u,f,AA,6);break;case 8:_B(),No=6;break A;default:throw Error(n(462))}}VSA();break}catch(Wt){DG(u,Wt)}while(!0);return TB=oh=null,Oi.H=F,Oi.A=Y,wg=R,kn!==null?0:(Lg=null,zn=0,H(),No)}function VSA(){for(;kn!==null&&!w0A();)YV(kn)}function YV(u){var f=fI(u.alternate,u,HB);u.memoizedProps=u.pendingProps,f===null?SG(u):kn=f}function HV(u){var f=u,R=f.alternate;switch(f.tag){case 15:case 0:f=cl(R,f,f.pendingProps,f.type,void 0,zn);break;case 11:f=cl(R,f,f.pendingProps,f.type.render,f.ref,zn);break;case 5:nA(f);default:Qn(R,f),f=kn=WV(f,HB),f=fI(R,f,HB)}u.memoizedProps=u.pendingProps,f===null?SG(u):kn=f}function cy(u,f,R,F){TB=oh=null,nA(f),wy=null,g0=0;var Y=f.return;try{if(Bo(u,Y,f,R,zn)){No=1,ci(u,q(R,u.current)),kn=null;return}}catch(AA){if(Y!==null)throw kn=Y,AA;No=1,ci(u,q(R,u.current)),kn=null;return}f.flags&32768?(eg||F===1?u=!0:Gy||zn&536870912?u=!1:(YB=u=!0,(F===2||F===3||F===6)&&(F=uC.current,F!==null&&F.tag===13&&(F.flags|=16384))),OV(f,u)):SG(f)}function SG(u){var f=u;do{if(f.flags&32768){OV(f,YB);return}u=f.return;var R=fi(f.alternate,f,HB);if(R!==null){kn=R;return}if(f=f.sibling,f!==null){kn=f;return}kn=f=u}while(f!==null);No===0&&(No=5)}function OV(u,f){do{var R=Di(u.alternate,u);if(R!==null){R.flags&=32767,kn=R;return}if(R=u.return,R!==null&&(R.flags|=32768,R.subtreeFlags=0,R.deletions=null),!f&&(u=u.sibling,u!==null)){kn=u;return}kn=u=R}while(u!==null);No=6,kn=null}function PV(u,f,R,F,Y,AA,GA,ge,be,nt){var Nt=Oi.T,zt=$d();try{xa(2),Oi.T=null,XSA(u,f,R,F,zt,Y,AA,GA,ge,be,nt)}finally{Oi.T=Nt,xa(zt)}}function XSA(u,f,R,F,Y,AA,GA,ge){do Vd();while(ah!==null);if(wg&6)throw Error(n(327));var be=u.finishedWork;if(F=u.finishedLanes,be===null)return null;if(u.finishedWork=null,u.finishedLanes=0,be===u.current)throw Error(n(177));u.callbackNode=null,u.callbackPriority=0,u.cancelPendingCommit=null;var nt=be.lanes|be.childLanes;if(nt|=zT,_(u,F,nt,AA,GA,ge),u===Lg&&(kn=Lg=null,zn=0),!(be.subtreeFlags&10256)&&!(be.flags&10256)||ZG||(ZG=!0,rq=nt,aq=R,twA(PT,function(){return Vd(),null})),R=(be.flags&15990)!==0,be.subtreeFlags&15990||R?(R=Oi.T,Oi.T=null,AA=$d(),xa(2),GA=wg,wg|=4,jw(u,be),yG(be,u),EwA(u.containerInfo),u.current=be,zw(u,be.alternate,be),k0A(),wg=GA,xa(AA),Oi.T=R):u.current=be,ZG?(ZG=!1,ah=u,I0=F):jV(u,nt),nt=u.pendingLanes,nt===0&&(MQ=null),v(be.stateNode),cA(u),f!==null)for(Y=u.onRecoverableError,be=0;be<f.length;be++)nt=f[be],Y(nt.value,{componentStack:nt.stack});return I0&3&&Vd(),nt=u.pendingLanes,F&4194218&&nt&42?u===Iq?C0++:(C0=0,Iq=u):C0=0,_A(0),null}function jV(u,f){(u.pooledCacheLanes&=f)===0&&(f=u.pooledCache,f!=null&&(u.pooledCache=null,Le(f)))}function Vd(){if(ah!==null){var u=ah,f=rq;rq=0;var R=T(I0),F=32>R?32:R;R=Oi.T;var Y=$d();try{if(xa(F),Oi.T=null,ah===null)var AA=!1;else{F=aq,aq=null;var GA=ah,ge=I0;if(ah=null,I0=0,wg&6)throw Error(n(331));var be=wg;if(wg|=4,Ze(GA.current),Vw(GA,GA.current,ge,F),wg=be,_A(0,!1),wI&&typeof wI.onPostCommitFiberRoot=="function")try{wI.onPostCommitFiberRoot(e0,GA)}catch{}AA=!0}return AA}finally{xa(Y),Oi.T=R,jV(u,f)}}return!1}function zV(u,f,R){f=q(R,f),f=Wi(u.stateNode,f,2),u=QA(u,f,2),u!==null&&(b(u,2),cA(u))}function ug(u,f,R){if(u.tag===3)zV(u,u,R);else for(;f!==null;){if(f.tag===3){zV(f,u,R);break}else if(f.tag===1){var F=f.stateNode;if(typeof f.type.getDerivedStateFromError=="function"||typeof F.componentDidCatch=="function"&&(MQ===null||!MQ.has(F))){u=q(R,u),R=Vi(2),F=QA(f,R,2),F!==null&&(hi(R,F,f,u),b(F,2),cA(F));break}}f=f.return}}function wT(u,f,R){var F=u.pingCache;if(F===null){F=u.pingCache=new J0A;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)||(nq=!0,Y.add(R),u=$SA.bind(null,u,f,R),f.then(u,u))}function $SA(u,f,R){var F=u.pingCache;F!==null&&F.delete(f),u.pingedLanes|=u.suspendedLanes&R,u.warmLanes&=~R,Lg===u&&(zn&R)===R&&(No===4||No===3&&(zn&62914560)===zn&&300>dc()-sq?!(wg&2)&&uQ(u,0):gq|=R,by===zn&&(by=0)),cA(u)}function ZV(u,f){f===0&&(f=M()),u=iA(u,f),u!==null&&(b(u,f),cA(u))}function AwA(u){var f=u.memoizedState,R=0;f!==null&&(R=f.retryLane),ZV(u,R)}function ewA(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),ZV(u,R)}function twA(u,f){return bG(u,f)}function iwA(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 kT(u){return u=u.prototype,!(!u||!u.isReactComponent)}function hQ(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 WV(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 wG(u,f,R,F,Y,AA){var GA=0;if(F=u,typeof u=="function")kT(u)&&(GA=1);else if(typeof u=="string")GA=lC&&Kr?D9(u,R,Ir.current)?26:G9(u)?27:5:lC?D9(u,R,Ir.current)?26:5:Kr&&G9(u)?27:5;else A:switch(u){case By:return Xd(R.children,Y,AA,f);case i9:GA=8,Y|=24;break;case bT:return u=t(12,R,f,Y|2),u.elementType=bT,u.lanes=AA,u;case vT:return u=t(13,R,f,Y),u.elementType=vT,u.lanes=AA,u;case KT:return u=t(19,R,f,Y),u.elementType=KT,u.lanes=AA,u;case g9:return VV(R,Y,AA,f);default:if(typeof u=="object"&&u!==null)switch(u.$$typeof){case swA:case pQ:GA=10;break A;case n9:GA=9;break A;case UT:GA=11;break A;case FT:GA=14;break A;case fQ: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 VV(u,f,R,F){u=t(22,u,F,f),u.elementType=g9,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,uo(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,uo(GA,AA,2))}}};return u.stateNode=Y,u}function MT(u,f,R){return u=t(6,u,null,f),u.lanes=R,u}function NT(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 nwA(u,f,R,F,Y,AA,GA,ge){this.tag=1,this.containerInfo=u,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=xT,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=ge,this.incompleteTransitions=new Map}function XV(u,f,R,F,Y,AA,GA,ge,be,nt,Nt,zt){return u=new nwA(u,f,R,GA,ge,be,nt,zt),f=1,AA===!0&&(f|=24),AA=t(3,null,null,f),u.current=AA,AA.stateNode=u,f=ue(),f.refCount++,u.pooledCache=f,f.refCount++,AA.memoizedState={element:F,isDehydrated:R,cache:f},ye(AA),u}function $V(u){return u?(u=uy,u):uy}function A9(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:Xw(u.stateNode)}function e9(u,f,R,F,Y,AA){Y=$V(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=QA(u,F,f),R!==null&&(uo(R,u,f),PA(R,u,f))}function t9(u,f){if(u=u.memoizedState,u!==null&&u.dehydrated!==null){var R=u.retryLane;u.retryLane=R!==0&&R<f?R:f}}function RT(u,f){t9(u,f),(u=u.alternate)&&t9(u,f)}var wn={},gwA=E,mI=SQe(),GT=Object.assign,owA=Symbol.for("react.element"),kG=Symbol.for("react.transitional.element"),ly=Symbol.for("react.portal"),By=Symbol.for("react.fragment"),i9=Symbol.for("react.strict_mode"),bT=Symbol.for("react.profiler"),swA=Symbol.for("react.provider"),n9=Symbol.for("react.consumer"),pQ=Symbol.for("react.context"),UT=Symbol.for("react.forward_ref"),vT=Symbol.for("react.suspense"),KT=Symbol.for("react.suspense_list"),FT=Symbol.for("react.memo"),fQ=Symbol.for("react.lazy"),g9=Symbol.for("react.offscreen"),rwA=Symbol.for("react.memo_cache_sentinel"),o9=Symbol.iterator,awA=Symbol.for("react.client.reference"),Oi=gwA.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,_T,s9,JT=!1,MG=Array.isArray,IwA=A.rendererVersion,CwA=A.rendererPackageName,r9=A.extraDevToolsConfig,Xw=A.getPublicInstance,cwA=A.getRootHostContext,lwA=A.getChildHostContext,BwA=A.prepareForCommit,EwA=A.resetAfterCommit,QwA=A.createInstance,LT=A.appendInitialChild,a9=A.finalizeInitialChildren,NG=A.shouldSetTextContent,I9=A.createTextInstance,uwA=A.scheduleTimeout,dwA=A.cancelTimeout,xT=A.noTimeout,JB=A.isPrimaryRenderer;A.warnsIfNotActing;var vr=A.supportsMutation,yQ=A.supportsPersistence,cC=A.supportsHydration,C9=A.getInstanceFromNode;A.beforeActiveInstanceBlur,A.afterActiveInstanceBlur;var hwA=A.preparePortalMount;A.prepareScopeUpdate,A.getInstanceFromScope;var xa=A.setCurrentUpdatePriority,$d=A.getCurrentUpdatePriority,pwA=A.resolveUpdatePriority;A.resolveEventType,A.resolveEventTimeStamp;var fwA=A.shouldAttemptEagerTransition,ywA=A.detachDeletedInstance;A.requestPostPaintCallback;var DwA=A.maySuspendCommit,c9=A.preloadInstance,mwA=A.startSuspendingCommit,l9=A.suspendInstance,SwA=A.waitForCommitToBeReady,Ey=A.NotPendingTransition,Ah=A.HostTransitionContext,wwA=A.resetFormInstance;A.bindToConsole;var kwA=A.supportsMicrotasks,MwA=A.scheduleMicrotask,$w=A.supportsTestSelectors,NwA=A.findFiberRoot,RwA=A.getBoundingRect,GwA=A.getTextContent,A0=A.isHiddenSubtree,bwA=A.matchAccessibilityRole,UwA=A.setFocusIfFocusable,vwA=A.setupIntersectionObserver,KwA=A.appendChild,FwA=A.appendChildToContainer,_wA=A.commitTextUpdate,JwA=A.commitMount,LwA=A.commitUpdate,xwA=A.insertBefore,TwA=A.insertInContainerBefore,qwA=A.removeChild,YwA=A.removeChildFromContainer,B9=A.resetTextContent,HwA=A.hideInstance,OwA=A.hideTextInstance,PwA=A.unhideInstance,jwA=A.unhideTextInstance,zwA=A.clearContainer,ZwA=A.cloneInstance,E9=A.createContainerChildSet,Q9=A.appendChildToContainerChildSet,WwA=A.finalizeContainerChildren,u9=A.replaceContainerChildren,d9=A.cloneHiddenInstance,h9=A.cloneHiddenTextInstance,TT=A.isSuspenseInstancePending,qT=A.isSuspenseInstanceFallback,VwA=A.getSuspenseInstanceFallbackErrorDetails,XwA=A.registerSuspenseInstanceRetry,$wA=A.canHydrateFormStateMarker,A0A=A.isFormStateMarkerMatching,p9=A.getNextHydratableSibling,f9=A.getFirstHydratableChild,e0A=A.getFirstHydratableChildWithinContainer,t0A=A.getFirstHydratableChildWithinSuspenseInstance,i0A=A.canHydrateInstance,n0A=A.canHydrateTextInstance,g0A=A.canHydrateSuspenseInstance,o0A=A.hydrateInstance,s0A=A.hydrateTextInstance,r0A=A.hydrateSuspenseInstance,a0A=A.getNextHydratableInstanceAfterSuspenseInstance,I0A=A.commitHydratedContainer,C0A=A.commitHydratedSuspenseInstance,c0A=A.clearSuspenseBoundary,l0A=A.clearSuspenseBoundaryFromContainer,y9=A.shouldDeleteUnhydratedTailInstances;A.diffHydratedPropsForDevWarnings,A.diffHydratedTextForDevWarnings,A.describeHydratableInstanceForDevWarnings;var B0A=A.validateHydratableInstance,E0A=A.validateHydratableTextInstance,lC=A.supportsResources,D9=A.isHostHoistableType,YT=A.getHoistableRoot,m9=A.getResource,S9=A.acquireResource,w9=A.releaseResource,Q0A=A.hydrateHoistable,k9=A.mountHoistable,M9=A.unmountHoistable,u0A=A.createHoistableInstance,d0A=A.prepareToCommitHoistables,h0A=A.mayResourceSuspendCommit,N9=A.preloadResource,p0A=A.suspendResource,Kr=A.supportsSingletons,R9=A.resolveSingletonInstance,f0A=A.clearSingleton,y0A=A.acquireSingletonInstance,D0A=A.releaseSingletonInstance,G9=A.isHostSingletonType,HT=[],Qy=-1,uy={},SI=Math.clz32?Math.clz32:m,m0A=Math.log,S0A=Math.LN2,RG=128,GG=4194304,bG=mI.unstable_scheduleCallback,OT=mI.unstable_cancelCallback,w0A=mI.unstable_shouldYield,k0A=mI.unstable_requestPaint,dc=mI.unstable_now,b9=mI.unstable_ImmediatePriority,M0A=mI.unstable_UserBlockingPriority,PT=mI.unstable_NormalPriority,N0A=mI.unstable_IdlePriority,R0A=mI.log,G0A=mI.unstable_setDisableYieldValue,e0=null,wI=null,kI=typeof Object.is=="function"?Object.is:x,U9=new WeakMap,dy=[],hy=0,UG=null,vG=0,BC=[],EC=0,eh=null,LB=1,xB="",Ir=d(null),t0=d(null),DQ=d(null),KG=d(null),ca=null,Fr=null,eg=!1,hc=null,dl=!1,jT=Error(n(519)),QC=[],py=0,zT=0,FG=null,fy=null,ZT=!1,_G=!1,WT=!1,yy=0,i0=null,VT=0,Dy=0,my=null,mQ=!1,XT=!1,b0A=Object.prototype.hasOwnProperty,n0=Error(n(460)),$T=Error(n(474)),JG={then:function(){}},Sy=null,wy=null,g0=0,th=At(!0),v9=At(!1),ky=d(null),LG=d(0),uC=d(null),hl=null,Ms=d(0),SQ=0,fn=null,Sg=null,ns=null,xG=!1,My=!1,ih=!1,TG=0,o0=0,Ny=null,U0A=0,Aq=function(){return{lastEffect:null,events:null,stores:null,memoCache:null}},pl={readContext:LA,use:bA,useCallback:ee,useContext:ee,useEffect:ee,useImperativeHandle:ee,useLayoutEffect:ee,useInsertionEffect:ee,useMemo:ee,useReducer:ee,useRef:ee,useState:ee,useDebugValue:ee,useDeferredValue:ee,useTransition:ee,useSyncExternalStore:ee,useId:ee};pl.useCacheRefresh=ee,pl.useMemoCache=ee,pl.useHostTransitionStatus=ee,pl.useFormState=ee,pl.useActionState=ee,pl.useOptimistic=ee;var nh={readContext:LA,use:bA,useCallback:function(u,f){return vA().memoizedState=[u,f===void 0?null:f],u},useContext:LA,useEffect:Zt,useImperativeHandle:function(u,f,R){R=R!=null?R.concat([u]):null,ie(4194308,4,Cg.bind(null,f,u),R)},useLayoutEffect:function(u,f){return ie(4194308,4,u,f)},useInsertionEffect:function(u,f){ie(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=je.bind(null,fn,u),[F.memoizedState,u]},useRef:function(u){var f=vA();return u={current:u},f.memoizedState=u},useState:function(u){u=Mt(u);var f=u.queue,R=$e.bind(null,fn,f);return f.dispatch=R,[u.memoizedState,R]},useDebugValue:ng,useDeferredValue:function(u,f){var R=vA();return Pe(R,u,f)},useTransition:function(){var u=Mt(!1);return u=XA.bind(null,fn,u.queue,!0,!1),vA().memoizedState=u,[!1,u]},useSyncExternalStore:function(u,f,R){var F=fn,Y=vA();if(eg){if(R===void 0)throw Error(n(407));R=R()}else{if(R=f(),Lg===null)throw Error(n(349));zn&60||Se(F,f,R)}Y.memoizedState=R;var AA={value:R,getSnapshot:f};return Y.queue=AA,Zt(ce.bind(null,F,AA,u),[u]),F.flags|=2048,xi(9,Qe.bind(null,F,AA,R,f),{destroy:void 0},null),R},useId:function(){var u=vA(),f=Lg.identifierPrefix;if(eg){var R=xB,F=LB;R=(F&~(1<<32-SI(F)-1)).toString(32)+R,f=":"+f+"R"+R,R=TG++,0<R&&(f+="H"+R.toString(32)),f+=":"}else R=U0A++,f=":"+f+"r"+R.toString(32)+":";return u.memoizedState=f},useCacheRefresh:function(){return vA().memoizedState=Fe.bind(null,fn)}};nh.useMemoCache=De,nh.useHostTransitionStatus=xe,nh.useFormState=Ci,nh.useActionState=Ci,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=Ot.bind(null,fn,!0,R),R.dispatch=f,[u,f]};var wQ={readContext:LA,use:bA,useCallback:wo,useContext:LA,useEffect:lo,useImperativeHandle:Dg,useInsertionEffect:Hg,useLayoutEffect:xo,useMemo:fe,useReducer:me,useRef:ui,useState:function(){return me(jA)},useDebugValue:ng,useDeferredValue:function(u,f){var R=FA();return OA(R,Sg.memoizedState,u,f)},useTransition:function(){var u=me(jA)[0],f=FA().memoizedState;return[typeof u=="boolean"?u:te(u),f]},useSyncExternalStore:WA,useId:rA};wQ.useCacheRefresh=pe,wQ.useMemoCache=De,wQ.useHostTransitionStatus=xe,wQ.useFormState=Pi,wQ.useActionState=Pi,wQ.useOptimistic=function(u,f){var R=FA();return ct(R,Sg,u,f)};var gh={readContext:LA,use:bA,useCallback:wo,useContext:LA,useEffect:lo,useImperativeHandle:Dg,useInsertionEffect:Hg,useLayoutEffect:xo,useMemo:fe,useReducer:qA,useRef:ui,useState:function(){return qA(jA)},useDebugValue:ng,useDeferredValue:function(u,f){var R=FA();return Sg===null?Pe(R,u,f):OA(R,Sg.memoizedState,u,f)},useTransition:function(){var u=qA(jA)[0],f=FA().memoizedState;return[typeof u=="boolean"?u:te(u),f]},useSyncExternalStore:WA,useId:rA};gh.useCacheRefresh=pe,gh.useMemoCache=De,gh.useHostTransitionStatus=xe,gh.useFormState=Ai,gh.useActionState=Ai,gh.useOptimistic=function(u,f){var R=FA();return Sg!==null?ct(R,Sg,u,f):(R.baseState=u,[u,R.queue.dispatch])};var eq={isMounted:function(u){return(u=u._reactInternals)?c(u)===u:!1},enqueueSetState:function(u,f,R){u=u._reactInternals;var F=Pg(),Y=NA(F);Y.payload=f,R!=null&&(Y.callback=R),f=QA(u,Y,F),f!==null&&(uo(f,u,F),PA(f,u,F))},enqueueReplaceState:function(u,f,R){u=u._reactInternals;var F=Pg(),Y=NA(F);Y.tag=1,Y.payload=f,R!=null&&(Y.callback=R),f=QA(u,Y,F),f!==null&&(uo(f,u,F),PA(f,u,F))},enqueueForceUpdate:function(u,f){u=u._reactInternals;var R=Pg(),F=NA(R);F.tag=2,f!=null&&(F.callback=f),f=QA(u,F,R),f!==null&&(uo(f,u,R),PA(f,u,R))}},K9=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)},F9=Error(n(461)),qs=!1,tq={dehydrated:null,treeContext:null,retryLane:0},qG=d(null),oh=null,TB=null,v0A=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()})}},K0A=mI.unstable_scheduleCallback,F0A=mI.unstable_NormalPriority,ko={$$typeof:pQ,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0},_9=Oi.S;Oi.S=function(u,f){typeof f=="object"&&f!==null&&typeof f.then=="function"&&HA(u,f),_9!==null&&_9(u,f)};var sh=d(null),qB=!1,Mo=!1,iq=!1,J9=typeof WeakSet=="function"?WeakSet:Set,Ys=null,L9=!1,gs=null,MI=!1,pc=null,Ry=8192,_0A={getCacheForType:function(u){var f=LA(ko),R=f.data.get(u);return R===void 0&&(R=u(),f.data.set(u,R)),R}},YG=0,HG=1,OG=2,PG=3,jG=4;if(typeof Symbol=="function"&&Symbol.for){var s0=Symbol.for;YG=s0("selector.component"),HG=s0("selector.has_pseudo_class"),OG=s0("selector.role"),PG=s0("selector.test_id"),jG=s0("selector.text")}var J0A=typeof WeakMap=="function"?WeakMap:Map,wg=0,Lg=null,kn=null,zn=0,xg=0,NI=null,YB=!1,Gy=!1,nq=!1,HB=0,No=0,kQ=0,rh=0,gq=0,dC=0,by=0,r0=null,fl=null,oq=!1,sq=0,a0=1/0,zG=null,MQ=null,ZG=!1,ah=null,I0=0,rq=0,aq=null,C0=0,Iq=null;return wn.attemptContinuousHydration=function(u){if(u.tag===13){var f=iA(u,67108864);f!==null&&uo(f,u,67108864),RT(u,67108864)}},wn.attemptHydrationAtCurrentPriority=function(u){if(u.tag===13){var f=Pg(),R=iA(u,f);R!==null&&uo(R,u,f),RT(u,f)}},wn.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-SI(f);u.entanglements[1]|=R,f&=~R}cA(u),!(wg&6)&&(a0=dc()+500,_A(0))}}break;case 13:f=iA(u,2),f!==null&&uo(f,u,2),Wd(),RT(u,2)}},wn.batchedUpdates=function(u,f){return u(f)},wn.createComponentSelector=function(u){return{$$typeof:YG,value:u}},wn.createContainer=function(u,f,R,F,Y,AA,GA,ge,be,nt){return XV(u,f,!1,null,R,F,AA,GA,ge,be,nt,null)},wn.createHasPseudoClassSelector=function(u){return{$$typeof:HG,value:u}},wn.createHydrationContainer=function(u,f,R,F,Y,AA,GA,ge,be,nt,Nt,zt,Wt){return u=XV(R,F,!0,u,Y,AA,ge,be,nt,Nt,zt,Wt),u.context=$V(null),R=u.current,F=Pg(),Y=NA(F),Y.callback=f??null,QA(R,Y,F),u.current.lanes=F,b(u,F),cA(u),u},wn.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}},wn.createRoleSelector=function(u){return{$$typeof:OG,value:u}},wn.createTestNameSelector=function(u){return{$$typeof:PG,value:u}},wn.createTextSelector=function(u){return{$$typeof:jG,value:u}},wn.defaultOnCaughtError=function(u){console.error(u)},wn.defaultOnRecoverableError=function(u){K9(u)},wn.defaultOnUncaughtError=function(u){K9(u)},wn.deferredUpdates=function(u){var f=Oi.T,R=$d();try{return xa(32),Oi.T=null,u()}finally{xa(R),Oi.T=f}},wn.discreteUpdates=function(u,f,R,F,Y){var AA=Oi.T,GA=$d();try{return xa(2),Oi.T=null,u(f,R,F,Y)}finally{xa(GA),Oi.T=AA,wg===0&&(a0=dc()+500)}},wn.findAllNodes=Ts,wn.findBoundingRects=function(u,f){if(!$w)throw Error(n(363));f=Ts(u,f),u=[];for(var R=0;R<f.length;R++)u.push(RwA(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,ge=f-1;0<=ge;ge--)if(f!==ge){var be=u[ge],nt=be.x,Nt=nt+be.width,zt=be.y,Wt=zt+be.height;if(F>=nt&&AA>=zt&&Y<=Nt&&GA<=Wt){u.splice(f,1);break}else if(F!==nt||R.width!==be.width||Wt<AA||zt>GA){if(!(AA!==zt||R.height!==be.height||Nt<F||nt>Y)){nt>F&&(be.width+=nt-F,be.x=F),Nt<Y&&(be.width=Y-nt),u.splice(f,1);break}}else{zt>AA&&(be.height+=zt-AA,be.y=AA),Wt<GA&&(be.height=GA-zt),u.splice(f,1);break}}}return u},wn.findHostInstance=A9,wn.findHostInstanceWithNoPortals=function(u){return u=B(u),u=u!==null?h(u):null,u===null?null:Xw(u.stateNode)},wn.findHostInstanceWithWarning=function(u){return A9(u)},wn.flushPassiveEffects=Vd,wn.flushSyncFromReconciler=function(u){var f=wg;wg|=1;var R=Oi.T,F=$d();try{if(xa(2),Oi.T=null,u)return u()}finally{xa(F),Oi.T=R,wg=f,!(wg&6)&&_A(0)}},wn.flushSyncWork=Wd,wn.focusWithin=function(u,f){if(!$w)throw Error(n(363));for(u=ji(u),f=br(u,f),f=Array.from(f),u=0;u<f.length;){var R=f[u++],F=R.tag;if(!A0(R)){if((F===5||F===26||F===27)&&UwA(R.stateNode))return!0;for(R=R.child;R!==null;)f.push(R),R=R.sibling}}return!1},wn.getFindAllNodesFailureDescription=function(u,f){if(!$w)throw Error(n(363));var R=0,F=[];u=[ji(u),0];for(var Y=0;Y<u.length;){var AA=u[Y++],GA=AA.tag,ge=u[Y++],be=f[ge];if((GA!==5&&GA!==26&&GA!==27||!A0(AA))&&(is(AA,be)&&(F.push(no(be)),ge++,ge>R&&(R=ge)),ge<f.length))for(AA=AA.child;AA!==null;)u.push(AA,ge),AA=AA.sibling}if(R<f.length){for(u=[];R<f.length;R++)u.push(no(f[R]));return`findAllNodes was able to match part of the selector:
  `+(F.join(" > ")+`

No matching component was found for:
  `)+u.join(" > ")}return null},wn.getPublicRootInstance=function(u){if(u=u.current,!u.child)return null;switch(u.child.tag){case 27:case 5:return Xw(u.child.stateNode);default:return u.child.stateNode}},wn.injectIntoDevTools=function(){var u={bundleType:0,version:IwA,rendererPackageName:CwA,currentDispatcherRef:Oi,findFiberByHostInstance:C9,reconcilerVersion:"19.0.0"};if(r9!==null&&(u.rendererConfig=r9),typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")u=!1;else{var f=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(f.isDisabled||!f.supportsFiber)u=!0;else{try{e0=f.inject(u),wI=f}catch{}u=!!f.checkDCE}}return u},wn.isAlreadyRendering=function(){return!1},wn.observeVisibleRects=function(u,f,R,F){if(!$w)throw Error(n(363));u=Ts(u,f);var Y=vwA(u,R,F).disconnect;return{disconnect:function(){Y()}}},wn.shouldError=function(){return null},wn.shouldSuspend=function(){return!1},wn.startHostTransition=function(u,f,R,F){if(u.tag!==5)throw Error(n(476));var Y=_e(u).queue;XA(u,Y,f,Ey,R===null?i:function(){var AA=_e(u).next.queue;return Gt(u,AA,{},Pg()),R(F)})},wn.updateContainer=function(u,f,R,F){var Y=f.current,AA=Pg();return e9(Y,AA,u,f,R,F),AA},wn.updateContainerSync=function(u,f,R,F){return f.tag===0&&Vd(),e9(f.current,2,u,f,R,F),2},wn},e.exports.default=e.exports,Object.defineProperty(e.exports,"__esModule",{value:!0})})(lDA);var wQe=lDA.exports;cDA.exports=wQe;var kQe=cDA.exports;const MQe=gw(kQe);var BDA={exports:{}},EDA={};/**
 * @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 q=x-1>>>1,z=v[q];if(0<n(z,U))v[q]=U,v[x]=z,x=q;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 q=0,z=v.length,Z=z>>>1;q<Z;){var eA=2*(q+1)-1,aA=v[eA],sA=eA+1,pA=v[sA];if(0>n(aA,x))sA<z&&0>n(pA,aA)?(v[q]=pA,v[sA]=x,q=sA):(v[q]=aA,v[eA]=x,q=eA);else if(sA<z&&0>n(pA,x))v[q]=pA,v[sA]=x,q=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 r=[],a=[],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(a);U!==null;){if(U.callback===null)i(a);else if(U.startTime<=v)i(a),U.sortIndex=U.expirationTime,A(r,U);else break;U=t(a)}}function D(v){if(h=!1,m(v),!Q)if(t(r)!==null)Q=!0,J();else{var U=t(a);U!==null&&T(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(r);c!==null&&!(c.expirationTime>v&&M());){var q=c.callback;if(typeof q=="function"){c.callback=null,l=c.priorityLevel;var z=q(c.expirationTime<=v);if(v=e.unstable_now(),typeof z=="function"){c.callback=z,m(v),U=!0;break e}c===t(r)&&i(r),m(v)}else i(r);c=t(r)}if(c!==null)U=!0;else{var Z=t(a);Z!==null&&T(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 T(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(r)},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 q=e.unstable_now();switch(typeof x=="object"&&x!==null?(x=x.delay,x=typeof x=="number"&&0<x?q+x:q):x=q,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>q?(v.sortIndex=x,A(a,v),t(r)===null&&v===t(a)&&(h?(p(k),k=-1):h=!0,T(D,x-q))):(v.sortIndex=z,A(r,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}}}})(EDA);BDA.exports=EDA;var EgA=BDA.exports;function fV(e,A,t){if(!e)return;if(t(e)===!0)return e;let i=A?e.return:e.child;for(;i;){const n=fV(i,A,t);if(n)return n;i=A?null:i.sibling}}function QDA(e){try{return Object.defineProperties(e,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return e}}const yV=QDA(E.createContext(null));class uDA extends E.Component{render(){return E.createElement(yV.Provider,{value:this._reactInternals},this.props.children)}}function dDA(){const e=E.useContext(yV);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=fV(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 NQe=Symbol.for("react.context"),RQe=e=>e!==null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===NQe;function GQe(){const e=dDA(),[A]=E.useState(()=>new Map);A.clear();let t=e;for(;t;){const i=t.type;RQe(i)&&i!==yV&&!A.has(i)&&A.set(i,E.use(QDA(i))),t=t.return}return A}function bQe(){const e=GQe();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(uDA,{...A})),[e])}function hDA(e){let A=e.root;for(;A.getState().previousRoot;)A=A.getState().previousRoot;return A}const pDA=e=>e&&e.isOrthographicCamera,UQe=e=>e&&e.hasOwnProperty("current"),vQe=e=>e!=null&&(typeof e=="string"||typeof e=="number"||e.isColor),uG=((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 DV(e){const A=E.useRef(e);return uG(()=>void(A.current=e),[e]),A}function KQe(){const e=dDA(),A=bQe();return E.useMemo(()=>({children:t})=>{const n=!!fV(e,!0,g=>g.type===E.StrictMode)?E.StrictMode:E.Fragment;return C.jsx(n,{children:C.jsx(A,{children:t})})},[e,A])}function FQe({set:e}){return uG(()=>(e(new Promise(()=>null)),()=>e(!1)),[e]),null}const _Qe=(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 fDA(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 so={obj:e=>e===Object(e)&&!so.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(so.str(e)||so.num(e)||so.boo(e))return e===A;const g=so.obj(e);if(g&&i==="reference")return e===A;const o=so.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(!so.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(so.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 JQe(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 LQe(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 yDA=["children","key","ref"];function xQe(e){const A={};for(const t in e)yDA.includes(t)||(A[t]=e[t]);return A}function wJ(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:xQe(i),object:n,eventCount:0,handlers:{},isHidden:!1},n&&(n.__r3f=g)),g}function YN(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 QgA=/-\d+$/;function kJ(e,A){if(so.str(A.props.attach)){if(QgA.test(A.props.attach)){const n=A.props.attach.replace(QgA,""),{root:g,key:o}=YN(e.object,n);Array.isArray(g[o])||(g[o]=[])}const{root:t,key:i}=YN(e.object,A.props.attach);A.previousAttach=t[i],t[i]=A.object}else so.fun(A.props.attach)&&(A.previousAttach=A.props.attach(e.object,A.object))}function MJ(e,A){if(so.str(A.props.attach)){const{root:t,key:i}=YN(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 u4=[...yDA,"args","dispose","attach","object","onUpdate","dispose"],ugA=new Map;function TQe(e){let A=ugA.get(e.constructor);try{A||(A=new e.constructor,ugA.set(e.constructor,A))}catch{}return A}function qQe(e,A){const t={};for(const i in A)if(!u4.includes(i)&&!so.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(u4.includes(i)||A.hasOwnProperty(i))continue;const{root:n,key:g}=YN(e.object,i);if(n.constructor&&n.constructor.length===0){const o=TQe(n);so.und(o)||(t[g]=o[g])}else t[g]=0}return t}const YQe=["map","emissiveMap","sheenColorMap","specularColorMap","envMap"],HQe=/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/;function Iu(e,A){var t;const i=e.__r3f,n=i&&hDA(i).getState(),g=i==null?void 0:i.eventCount;for(const s in A){let r=A[s];if(u4.includes(s))continue;if(i&&HQe.test(s)){typeof r=="function"?i.handlers[s]=r:delete i.handlers[s],i.eventCount=Object.keys(i.handlers).length;continue}if(r===void 0)continue;let{root:a,key:I,target:c}=YN(e,s);if(c instanceof jS&&r instanceof jS)c.mask=r.mask;else if(c instanceof lt&&vQe(r))c.set(r);else if(c!==null&&typeof c=="object"&&typeof c.set=="function"&&typeof c.copy=="function"&&r!=null&&r.constructor&&c.constructor===r.constructor)c.copy(r);else if(c!==null&&typeof c=="object"&&typeof c.set=="function"&&Array.isArray(r))typeof c.fromArray=="function"?c.fromArray(r):c.set(...r);else if(c!==null&&typeof c=="object"&&typeof c.set=="function"&&typeof r=="number")typeof c.setScalar=="function"?c.setScalar(r):c.set(r);else{var o;a[I]=r,n&&!n.linear&&YQe.includes(I)&&(o=a[I])!=null&&o.isTexture&&a[I].format===jr&&a[I].type===sc&&(a[I].colorSpace=sn)}}if(i!=null&&i.parent&&n!=null&&n.internal&&(t=i.object)!=null&&t.isObject3D&&g!==i.eventCount){const s=i.object,r=n.internal.interaction.indexOf(s);r>-1&&n.internal.interaction.splice(r,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&&Yw(i),e}function Yw(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||(pDA(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 ha=e=>e==null?void 0:e.isObject3D;function XU(e){return(e.eventObject||e.object).uuid+"/"+e.index+e.instanceId}function mDA(e,A,t,i){const n=t.get(A);n&&(t.delete(A),t.size===0&&(e.delete(i),n.target.releasePointerCapture(i)))}function OQe(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)=>{mDA(t.capturedMap,A,i,n)})}function PQe(e){function A(r){const{internal:a}=e.getState(),I=r.offsetX-a.initialClick[0],c=r.offsetY-a.initialClick[1];return Math.round(Math.sqrt(I*I+c*c))}function t(r){return r.filter(a=>["Move","Over","Enter","Out","Leave"].some(I=>{var c;return(c=a.__r3f)==null?void 0:c.handlers["onPointer"+I]}))}function i(r,a){const I=e.getState(),c=new Set,l=[],B=a?a(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(r,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(r,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=XU(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 r&&I.internal.capturedMap.has(r.pointerId))for(let p of I.internal.capturedMap.get(r.pointerId).values())c.has(XU(p.intersection))||l.push(p.intersection);return l}function n(r,a,I,c){if(r.length){const l={stopped:!1};for(const B of r){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:a.target};y.capturedMap.has(M)?y.capturedMap.get(M).set(B.eventObject,w):y.capturedMap.set(M,new Map([[B.eventObject,w]])),a.target.setPointerCapture(M)},k=M=>{const w=y.capturedMap.get(M);w&&mDA(y.capturedMap,B.eventObject,w,M)};let N={};for(let M in a){let w=a[M];typeof w!="function"&&(N[M]=w)}let G={...B,...N,pointer:d,intersections:r,stopped:l.stopped,delta:I,unprojectedPoint:m,ray:h.ray,camera:p,stopPropagation(){const M="pointerId"in a&&y.capturedMap.get(a.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=r.slice(0,r.indexOf(B));g([...w,B])}},target:{hasPointerCapture:D,setPointerCapture:S,releasePointerCapture:k},currentTarget:{hasPointerCapture:D,setPointerCapture:S,releasePointerCapture:k},nativeEvent:a};if(c(G),l.stopped===!0)break}}}return r}function g(r){const{internal:a}=e.getState();for(const I of a.hovered.values())if(!r.length||!r.find(c=>c.object===I.object&&c.index===I.index&&c.instanceId===I.instanceId)){const l=I.eventObject.__r3f;if(a.hovered.delete(XU(I)),l!=null&&l.eventCount){const B=l.handlers,Q={...I,intersections:r};B.onPointerOut==null||B.onPointerOut(Q),B.onPointerLeave==null||B.onPointerLeave(Q)}}}function o(r,a){for(let I=0;I<a.length;I++){const c=a[I].__r3f;c==null||c.handlers.onPointerMissed==null||c.handlers.onPointerMissed(r)}}function s(r){switch(r){case"onPointerLeave":case"onPointerCancel":return()=>g([]);case"onLostPointerCapture":return a=>{const{internal:I}=e.getState();"pointerId"in a&&I.capturedMap.has(a.pointerId)&&requestAnimationFrame(()=>{I.capturedMap.has(a.pointerId)&&(I.capturedMap.delete(a.pointerId),g([]))})}}return function(I){const{onPointerMissed:c,internal:l}=e.getState();l.lastEvent.current=I;const B=r==="onPointerMove",Q=r==="onClick"||r==="onContextMenu"||r==="onDoubleClick",d=i(I,B?t:void 0),p=Q?A(I):0;r==="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=XU(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[r];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 dgA=e=>!!(e!=null&&e.render),mV=E.createContext(null),jQe=(e,A)=>{const t=rDA((s,r)=>{const a=new SA,I=new SA,c=new SA;function l(p=r().camera,y=I,m=r().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(a).distanceTo(c);if(pDA(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 It;return{set:s,get:r,gl:null,camera:null,raycaster:null,events:{priority:1,enabled:!0,connected:!1},scene:null,xr:null,invalidate:(p=1)=>e(r(),p),advance:(p,y)=>A(p,y,r()),legacy:!1,linear:!1,flat:!1,controls:null,clock:new cV,pointer:h,mouse:h,frameloop:"always",onPointerMissed:void 0,performance:{current:1,min:.5,max:1,debounce:200,regress:()=>{const p=r();B&&clearTimeout(B),p.performance.current!==p.performance.min&&Q(p.performance.min),B=setTimeout(()=>Q(r().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=r().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=fDA(p);return{viewport:{...y.viewport,dpr:m,initialDpr:y.viewport.initialDpr||m}}}),setFrameloop:(p="always")=>{const y=r().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=r().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=r().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:r,viewport:a,gl:I,set:c}=t.getState();if(r.width!==n.width||r.height!==n.height||a.dpr!==g){n=r,g=a.dpr,DDA(s,r),a.dpr>0&&I.setPixelRatio(a.dpr);const l=typeof HTMLCanvasElement<"u"&&I.domElement instanceof HTMLCanvasElement;I.setSize(r.width,r.height,l)}s!==o&&(o=s,c(l=>({viewport:{...l.viewport,...l.viewport.getCurrentViewport(s)}})))}),t.subscribe(s=>e(s)),t};function SV(){const e=E.useContext(mV);if(!e)throw new Error("R3F: Hooks can only be used within the Canvas component!");return e}function Ac(e=t=>t,A){return SV()(e,A)}function rr(e,A=0){const t=SV(),i=t.getState().internal.subscribe,n=DV(e);return uG(()=>i(n,A,t),[A,i,t]),null}const hgA=new WeakMap,zQe=e=>{var A;return typeof e=="function"&&(e==null||(A=e.prototype)==null?void 0:A.constructor)===e};function SDA(e,A){return function(t,...i){let n;return zQe(t)?(n=hgA.get(t),n||(n=new t,hgA.set(t,n))):n=t,e&&e(n),Promise.all(i.map(g=>new Promise((o,s)=>n.load(g,r=>{ha(r==null?void 0:r.scene)&&Object.assign(r,JQe(r.scene)),o(r)},A,r=>s(new Error(`Could not load ${g}: ${r==null?void 0:r.message}`))))))}}function Hd(e,A,t,i){const n=Array.isArray(A)?A:[A],g=CDA(SDA(t,i),[e,...n],{equal:so.equ});return Array.isArray(A)?g:g[0]}Hd.preload=function(e,A,t){const i=Array.isArray(A)?A:[A];return yQe(SDA(t),[e,...i])};Hd.clear=function(e,A){const t=Array.isArray(A)?A:[A];return DQe([e,...t])};function ZQe(e){const A=MQe(e);return A.injectIntoDevTools({bundleType:0,rendererPackageName:"@react-three/fiber",version:E.version}),A}const wDA=0,VS={},WQe=/^three(?=[A-Z])/,QT=e=>`${e[0].toUpperCase()}${e.slice(1)}`;let VQe=0;const XQe=e=>typeof e=="function";function $Qe(e){if(XQe(e)){const A=`${VQe++}`;return VS[A]=e,A}else Object.assign(VS,e)}function kDA(e,A){const t=QT(e),i=VS[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 Aue(e,A,t){var i;return e=QT(e)in VS?e:e.replace(WQe,""),kDA(e,A),e==="primitive"&&(i=A.object)!=null&&i.__r3f&&delete A.object.__r3f,wJ(A.object,t,e,A)}function eue(e){if(!e.isHidden){var A;e.props.attach&&(A=e.parent)!=null&&A.object?MJ(e.parent,e):ha(e.object)&&(e.object.visible=!1),e.isHidden=!0,Yw(e)}}function MDA(e){if(e.isHidden){var A;e.props.attach&&(A=e.parent)!=null&&A.object?kJ(e.parent,e):ha(e.object)&&e.props.visible!==!1&&(e.object.visible=!0),e.isHidden=!1,Yw(e)}}function wV(e,A,t){const i=A.root.getState();if(!(!e.parent&&e.object!==i.scene)){if(!A.object){var n,g;const o=VS[QT(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)kJ(e,A);else if(ha(A.object)&&ha(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 r=s<o?o-1:o;e.object.children.splice(r,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)wV(A,o);Yw(A)}}function ZH(e,A){A&&(A.parent=e,e.children.push(A),wV(e,A))}function pgA(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),wV(e,A,t)}function NDA(e){if(typeof e.dispose=="function"){const A=()=>{try{e.dispose()}catch{}};typeof IS_REACT_ACT_ENVIRONMENT<"u"?A():EgA.unstable_scheduleCallback(EgA.unstable_IdlePriority,A)}}function d4(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?MJ(e,A):ha(A.object)&&ha(e.object)&&(e.object.remove(A.object),OQe(hDA(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];d4(A,o,n)}A.children.length=0,delete A.object.__r3f,n&&A.type!=="primitive"&&A.object.type!=="Scene"&&NDA(A.object),t===void 0&&Yw(A)}function tue(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 _K=[];function iue(){for(const[t]of _K){const i=t.parent;if(i){t.props.attach?MJ(i,t):ha(t.object)&&ha(i.object)&&i.object.remove(t.object);for(const n of t.children)n.props.attach?MJ(t,n):ha(n.object)&&ha(t.object)&&t.object.remove(n.object)}t.isHidden&&MDA(t),t.object.__r3f&&delete t.object.__r3f,t.type!=="primitive"&&NDA(t.object)}for(const[t,i,n]of _K){t.props=i;const g=t.parent;if(g){var e,A;const o=VS[QT(t.type)];t.object=(e=t.props.object)!=null?e:new o(...(A=t.props.args)!=null?A:[]),t.object.__r3f=t,tue(n,t.object),Iu(t.object,t.props),t.props.attach?kJ(g,t):ha(t.object)&&ha(g.object)&&g.object.add(t.object);for(const s of t.children)s.props.attach?kJ(t,s):ha(s.object)&&ha(t.object)&&t.object.add(s.object);Yw(t)}}_K.length=0}const WH=()=>{},fgA={};let $U=wDA;const nue=0,gue=4,NJ=ZQe({isPrimaryRenderer:!1,warnsIfNotActing:!1,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,createInstance:Aue,removeChild:d4,appendChild:ZH,appendInitialChild:ZH,insertBefore:pgA,appendChildToContainer(e,A){const t=e.getState().scene.__r3f;!A||!t||ZH(t,A)},removeChildFromContainer(e,A){const t=e.getState().scene.__r3f;!A||!t||d4(t,A)},insertInContainerBefore(e,A,t){const i=e.getState().scene.__r3f;!A||!t||!i||pgA(i,A,t)},getRootHostContext:()=>fgA,getChildHostContext:()=>fgA,commitUpdate(e,A,t,i,n){var g,o,s;kDA(A,i);let r=!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])}))&&(r=!0),r)_K.push([e,{...i},n]);else{const I=qQe(e,i);Object.keys(I).length&&(Object.assign(e.props,I),Iu(e.object,I))}(n.sibling===null||(n.flags&gue)===nue)&&iue()},finalizeInitialChildren:()=>!1,commitMount(){},getPublicInstance:e=>e==null?void 0:e.object,prepareForCommit:()=>null,preparePortalMount:e=>wJ(e.getState().scene,e,"",{}),resetAfterCommit:()=>{},shouldSetTextContent:()=>!1,clearContainer:()=>!1,hideInstance:eue,unhideInstance:MDA,createTextInstance:WH,hideTextInstance:WH,unhideTextInstance:WH,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){$U=e},getCurrentUpdatePriority(){return $U},resolveUpdatePriority(){var e;if($U!==wDA)return $U;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 UK.DiscreteEventPriority;case"pointermove":case"pointerout":case"pointerover":case"pointerenter":case"pointerleave":case"wheel":return UK.ContinuousEventPriority;default:return UK.DefaultEventPriority}},resetFormInstance(){}}),wf=new Map,pD={objects:"shallow",strict:!1};function oue(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 sue(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||jQe(f4,DgA),o=t||NJ.createContainer(g,UK.ConcurrentRoot,null,!1,null,"",n,n,n,null);A||wf.set(e,{fiber:o,store:g});let s,r,a=!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;dgA(eA)?J=eA:J=new pV({...Z,...B}),K.set({gl:J})}let T=K.raycaster;T||K.set({raycaster:T=new uV});const{params:v,...U}=w||{};if(so.equ(U,T,pD)||Iu(T,{...U}),so.equ(v,T.params,pD)||Iu(T,{params:{...T.params,...v}}),!K.camera||K.camera===r&&!so.equ(r,b,pD)){r=b;const Z=b==null?void 0:b.isCamera,eA=Z?b:k?new Yd(0,0,0,0,.1,1e3):new zo(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}),T.camera=eA}if(!K.scene){let Z;h!=null&&h.isScene?(Z=h,wJ(Z,g,"",{})):(Z=new CG,wJ(Z,g,"",{}),h&&Iu(Z,h)),K.set({scene:Z})}d&&!K.events.handlers&&K.set({events:d(g)});const x=oue(e,Q);if(so.equ(x,K.size,pD)||K.setSize(x.width,x.height,x.top,x.left),G&&K.viewport.dpr!==fDA(G)&&K.setDpr(G),K.frameloop!==N&&K.setFrameloop(N),K.onPointerMissed||K.set({onPointerMissed:_}),M&&!so.equ(M,K.performance,pD)&&K.set(Z=>({performance:{...Z.performance,...M}})),!K.xr){var q;const Z=(sA,pA)=>{const gA=g.getState();gA.frameloop!=="never"&&DgA(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||f4(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((q=J.xr)==null?void 0:q.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,so.boo(y))J.shadowMap.type=mM;else if(so.str(y)){var z;const aA={basic:ffA,percentage:Kx,soft:mM,variance:Nc};J.shadowMap.type=(z=aA[y])!=null?z:mM}else so.obj(y)&&Object.assign(J.shadowMap,y);(Z!==J.shadowMap.enabled||eA!==J.shadowMap.type)&&(J.shadowMap.needsUpdate=!0)}return Rn.enabled=!S,a||(J.outputColorSpace=m?Mr:sn,J.toneMapping=D?uB:ty),K.legacy!==S&&K.set(()=>({legacy:S})),K.linear!==m&&K.set(()=>({linear:m})),K.flat!==D&&K.set(()=>({flat:D})),B&&!so.fun(B)&&!dgA(B)&&!so.equ(B,J,pD)&&Iu(J,B),s=p,a=!0,l(),this},render(c){return!a&&!I&&this.configure(),I.then(()=>{NJ.updateContainer(C.jsx(rue,{store:g,children:c,onCreated:s,rootElement:e}),o,null,()=>{})}),g},unmount(){RDA(e)}}}function rue({store:e,children:A,onCreated:t,rootElement:i}){return uG(()=>{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(mV.Provider,{value:e,children:A})}function RDA(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),NJ.updateContainer(null,i,null,()=>{n&&setTimeout(()=>{try{var g,o,s,r;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(),(r=n.gl)!=null&&r.xr&&n.xr.disconnect(),LQe(n.scene),wf.delete(e)}catch{}},500)})}}function DGe(e,A,t){return C.jsx(aue,{children:e,container:A,state:t})}function aue({state:e={},children:A,container:t}){const{events:i,size:n,...g}=e,o=SV(),[s]=E.useState(()=>new uV),[r]=E.useState(()=>new It),a=DV((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:r,mouse:r,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=rDA((B,Q)=>({...g,set:B,get:Q})),l=B=>c.setState(Q=>a.current(B,Q));return l(o.getState()),o.subscribe(l),c},[o,t]);return C.jsx(C.Fragment,{children:NJ.createPortal(C.jsx(mV.Provider,{value:I,children:A}),I,null)})}const Iue=new Set,Cue=new Set,cue=new Set;function VH(e,A){if(e.size)for(const{callback:t}of e.values())t(A)}function bM(e,A){switch(e){case"before":return VH(Iue,A);case"after":return VH(Cue,A);case"tail":return VH(cue,A)}}let XH,$H;function h4(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),XH=A.internal.subscribers;for(let n=0;n<XH.length;n++)$H=XH[n],$H.ref.current($H.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 RJ=!1,p4=!1,AO,ygA,fD;function GDA(e){ygA=requestAnimationFrame(GDA),RJ=!0,AO=0,bM("before",e),p4=!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)&&(AO+=h4(e,fD))}if(p4=!1,bM("after",e),AO===0)return bM("tail",e),RJ=!1,cancelAnimationFrame(ygA)}function f4(e,A=1){var t;if(!e)return wf.forEach(i=>f4(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):p4?e.internal.frames=2:e.internal.frames=1,RJ||(RJ=!0,requestAnimationFrame(GDA)))}function DgA(e,A=!0,t,i){if(A&&bM("before",e),t)h4(e,t,i);else for(const n of wf.values())h4(e,n.store.getState());A&&bM("after",e)}const eO={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 lue(e){const{handlePointer:A}=PQe(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(eO).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,r]=eO[g];t.addEventListener(s,o,{passive:r})}},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]=eO[n];i.connected.removeEventListener(o,g)}t(n=>({events:{...n.events,connected:void 0}}))}}}}function mgA(e,A){let t;return(...i)=>{window.clearTimeout(t),t=window.setTimeout(()=>e(...i),A)}}function Bue({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}),r=e?typeof e=="number"?e:e.scroll:null,a=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&&!due(s.current.lastBounds,w)&&o(s.current.lastBounds=w)};return[p,a?mgA(p,a):p,r?mgA(p,r):p]},[o,i,r,a]);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=bDA(p),h())};return Que(B,!!A),Eue(l),E.useEffect(()=>{Q(),h()},[A,B,l]),E.useEffect(()=>Q,[]),[d,g,c]}function Eue(e){E.useEffect(()=>{const A=e;return window.addEventListener("resize",A),()=>void window.removeEventListener("resize",A)},[e])}function Que(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 bDA(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,...bDA(e.parentElement)]}const uue=["x","y","top","bottom","left","right","width","height"],due=(e,A)=>uue.every(t=>e[t]===A[t]);function hue({ref:e,children:A,fallback:t,resize:i,style:n,gl:g,events:o=lue,eventSource:s,eventPrefix:r,shadows:a,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(()=>$Qe(VEe),[]);const N=KQe(),[G,M]=Bue({scroll:!0,debounce:{scroll:50,resize:0},...i}),w=E.useRef(null),b=E.useRef(null);E.useImperativeHandle(e,()=>w.current);const _=DV(D),[K,J]=E.useState(!1),[T,v]=E.useState(!1);if(K)throw K;if(T)throw T;const U=E.useRef(null);uG(()=>{const q=w.current;if(M.width>0&&M.height>0&&q){U.current||(U.current=sue(q));async function z(){await U.current.configure({gl:g,scene:m,events:o,shadows:a,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?UQe(s)?s.current:s:b.current),r&&Z.setEvents({compute:(eA,aA)=>{const sA=eA[r+"X"],pA=eA[r+"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(_Qe,{set:v,children:C.jsx(E.Suspense,{fallback:C.jsx(FQe,{set:J}),children:A??null})})}))}z()}}),E.useEffect(()=>{const q=w.current;if(q)return()=>RDA(q)},[]);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 dG(e){return C.jsx(uDA,{children:C.jsx(hue,{...e})})}const pue=parseInt(nG.replace(/\D+/g,""));function fue(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),r={},a={},I=[],c=["getX","getY","getZ","getW"];for(let h=0,d=s.length;h<d;h++){const p=s[h];r[p]=[];const y=e.morphAttributes[p];y&&(a[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=r[D],M=a[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(r[p]),D=new Yi(m,y.itemSize,y.normalized);if(Q.setAttribute(p,D),p in a)for(let S=0;S<a[p].length;S++){const k=e.morphAttributes[p][S],N=new k.array.constructor(a[p][S]),G=new Yi(N,k.itemSize,k.normalized);Q.morphAttributes[p][S]=G}}return Q.setIndex(I),Q}function SgA(e,A){if(A===JW)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(A===Df||A===rG){let t=e.getIndex();if(t===null){const o=[],s=e.getAttribute("position");if(s!==void 0){for(let r=0;r<s.count;r++)o.push(r);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 UDA(e,A,t={}){const i=new SA,n=new Ao,g=new SA,o=new ii,s=new ii,r=new ii;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 a=A.isObject3D?A.skeleton.bones:GJ(A),I=e.isObject3D?e.skeleton.bones:GJ(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=vDA(B,a),r.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)),r.makeRotationFromQuaternion(n.setFromRotationMatrix(s)),e.isObject3D){const p=I.indexOf(l),y=c?c[p]:o.copy(e.skeleton.boneInverses[p]).invert();r.multiply(y)}r.copyPosition(s)}l.parent&&l.parent.isBone?(l.matrix.copy(l.parent.matrixWorld).invert(),l.matrix.multiply(r)):l.matrix.copy(r),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 yue(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=mue(A));const n=Math.round(t.duration*(i.fps/1e3)*1e3),g=1/i.fps,o=[],s=new EV(A),r=GJ(e.skeleton),a=[];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;UDA(e,A,i);for(let p=0;p<r.length;++p)Q=i.names[r[p].name]||r[p].name,l=vDA(Q,A.skeleton),l&&(c=r[p],B=a[p]=a[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<a.length;++h)B=a[h],B&&(B.pos&&o.push(new SB(".bones["+B.bone.name+"].position",B.pos.times,B.pos.values)),o.push(new mB(".bones["+B.bone.name+"].quaternion",B.quat.times,B.quat.values)));return s.uncacheAction(t),new fd(t.name,-1,o)}function Due(e){const A=new Map,t=new Map,i=e.clone();return KDA(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(r){return t.get(r)}),g.bind(g.skeleton,g.bindMatrix)}),i}function vDA(e,A){for(let t=0,i=GJ(A);t<i.length;t++)if(e===i[t].name)return i[t]}function GJ(e){return Array.isArray(e)?e:e.bones}function mue(e){const A=new ZyA(e.bones[0]);return A.skeleton=e,A}function KDA(e,A,t){t(e,A);for(let i=0;i<e.children.length;i++)KDA(e.children[i],A.children[i],t)}const Sue={retarget:UDA,retargetClip:yue,clone:Due};function bJ(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",qE="srgb-linear",wgA=3001,wue=3e3;let kV=class extends sr{constructor(A){super(A),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Gue(t)}),this.register(function(t){return new bue(t)}),this.register(function(t){return new Tue(t)}),this.register(function(t){return new que(t)}),this.register(function(t){return new Yue(t)}),this.register(function(t){return new vue(t)}),this.register(function(t){return new Kue(t)}),this.register(function(t){return new Fue(t)}),this.register(function(t){return new _ue(t)}),this.register(function(t){return new Rue(t)}),this.register(function(t){return new Jue(t)}),this.register(function(t){return new Uue(t)}),this.register(function(t){return new xue(t)}),this.register(function(t){return new Lue(t)}),this.register(function(t){return new Mue(t)}),this.register(function(t){return new Hue(t)}),this.register(function(t){return new Oue(t)})}load(A,t,i,n){const g=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const a=XI.extractUrlBase(A);o=XI.resolveURL(a,this.path)}else o=XI.extractUrlBase(A);this.manager.itemStart(A);const s=function(a){n?n(a):console.error(a),g.manager.itemError(A),g.manager.itemEnd(A)},r=new Aa(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(A,function(a){try{g.parse(a,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(bJ(new Uint8Array(A.slice(0,4)))===FDA){try{o[bn.KHR_BINARY_GLTF]=new Pue(A)}catch(I){n&&n(I);return}g=JSON.parse(o[bn.KHR_BINARY_GLTF].content)}else g=JSON.parse(bJ(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 r=new gde(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 a=0;a<this.pluginCallbacks.length;a++){const I=this.pluginCallbacks[a](r);I.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),s[I.name]=I,o[I.name]=!0}if(g.extensionsUsed)for(let a=0;a<g.extensionsUsed.length;++a){const I=g.extensionsUsed[a],c=g.extensionsRequired||[];switch(I){case bn.KHR_MATERIALS_UNLIT:o[I]=new Nue;break;case bn.KHR_DRACO_MESH_COMPRESSION:o[I]=new jue(g,this.dracoLoader);break;case bn.KHR_TEXTURE_TRANSFORM:o[I]=new zue;break;case bn.KHR_MESH_QUANTIZATION:o[I]=new Zue;break;default:c.indexOf(I)>=0&&s[I]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+I+'".')}}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 kue(){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 bn={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 Mue=class{constructor(A){this.parser=A,this.name=bn.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,r=((g.extensions&&g.extensions[this.name]||{}).lights||[])[A];let a;const I=new lt(16777215);r.color!==void 0&&I.setRGB(r.color[0],r.color[1],r.color[2],qE);const c=r.range!==void 0?r.range:0;switch(r.type){case"directional":a=new zp(I),a.target.position.set(0,0,-1),a.add(a.target);break;case"point":a=new QG(I),a.distance=c;break;case"spot":a=new cT(I),a.distance=c,r.spot=r.spot||{},r.spot.innerConeAngle=r.spot.innerConeAngle!==void 0?r.spot.innerConeAngle:0,r.spot.outerConeAngle=r.spot.outerConeAngle!==void 0?r.spot.outerConeAngle:Math.PI/4,a.angle=r.spot.outerConeAngle,a.penumbra=1-r.spot.innerConeAngle/r.spot.outerConeAngle,a.target.position.set(0,0,-1),a.add(a.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+r.type)}return a.position.set(0,0,0),a.decay=2,aE(a,r),r.intensity!==void 0&&(a.intensity=r.intensity),a.name=t.createUniqueName(r.name||"light_"+A),n=Promise.resolve(a),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(r){return i._getNodeRef(t.cache,s,r)})}},Nue=class{constructor(){this.name=bn.KHR_MATERIALS_UNLIT}getMaterialType(){return yg}extendParams(A,t,i){const n=[];A.color=new lt(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],qE),A.opacity=o[3]}g.baseColorTexture!==void 0&&n.push(i.assignTexture(A,"map",g.baseColorTexture,up))}return Promise.all(n)}},Rue=class{constructor(A){this.parser=A,this.name=bn.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()}},Gue=class{constructor(A){this.parser=A,this.name=bn.KHR_MATERIALS_CLEARCOAT}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 It(s,s)}return Promise.all(g)}},bue=class{constructor(A){this.parser=A,this.name=bn.KHR_MATERIALS_DISPERSION}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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()}},Uue=class{constructor(A){this.parser=A,this.name=bn.KHR_MATERIALS_IRIDESCENCE}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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)}},vue=class{constructor(A){this.parser=A,this.name=bn.KHR_MATERIALS_SHEEN}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 lt(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],qE)}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)}},Kue=class{constructor(A){this.parser=A,this.name=bn.KHR_MATERIALS_TRANSMISSION}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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)}},Fue=class{constructor(A){this.parser=A,this.name=bn.KHR_MATERIALS_VOLUME}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 lt().setRGB(s[0],s[1],s[2],qE),Promise.all(g)}},_ue=class{constructor(A){this.parser=A,this.name=bn.KHR_MATERIALS_IOR}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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()}},Jue=class{constructor(A){this.parser=A,this.name=bn.KHR_MATERIALS_SPECULAR}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 lt().setRGB(s[0],s[1],s[2],qE),o.specularColorTexture!==void 0&&g.push(i.assignTexture(t,"specularColorMap",o.specularColorTexture,up)),Promise.all(g)}},Lue=class{constructor(A){this.parser=A,this.name=bn.EXT_MATERIALS_BUMP}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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)}},xue=class{constructor(A){this.parser=A,this.name=bn.KHR_MATERIALS_ANISOTROPY}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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)}},Tue=class{constructor(A){this.parser=A,this.name=bn.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)}},que=class{constructor(A){this.parser=A,this.name=bn.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 r=i.textureLoader;if(s.uri){const a=i.options.manager.getHandler(s.uri);a!==null&&(r=a)}return this.detectSupport().then(function(a){if(a)return i.loadTextureImage(A,o.source,r);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}},Yue=class{constructor(A){this.parser=A,this.name=bn.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 r=i.textureLoader;if(s.uri){const a=i.options.manager.getHandler(s.uri);a!==null&&(r=a)}return this.detectSupport().then(function(a){if(a)return i.loadTextureImage(A,o.source,r);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}},Hue=class{constructor(A){this.name=bn.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 r=n.byteOffset||0,a=n.byteLength||0,I=n.count,c=n.byteStride,l=new Uint8Array(s,r,a);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}},Oue=class{constructor(A){this.name=bn.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 a of n.primitives)if(a.mode!==NC.TRIANGLES&&a.mode!==NC.TRIANGLE_STRIP&&a.mode!==NC.TRIANGLE_FAN&&a.mode!==void 0)return null;const o=i.extensions[this.name].attributes,s=[],r={};for(const a in o)s.push(this.parser.getDependency("accessor",o[a]).then(I=>(r[a]=I,r[a])));return s.length<1?null:(s.push(this.parser.createNodeMesh(A)),Promise.all(s).then(a=>{const I=a.pop(),c=I.isGroup?I.children:[I],l=a[0].count,B=[];for(const Q of c){const h=new ii,d=new SA,p=new Ao,y=new SA(1,1,1),m=new lG(Q.geometry,Q.material,l);for(let D=0;D<l;D++)r.TRANSLATION&&d.fromBufferAttribute(r.TRANSLATION,D),r.ROTATION&&p.fromBufferAttribute(r.ROTATION,D),r.SCALE&&y.fromBufferAttribute(r.SCALE,D),m.setMatrixAt(D,h.compose(d,p,y));for(const D in r)if(D==="_COLOR_0"){const S=r[D];m.instanceColor=new hd(S.array,S.itemSize,S.normalized)}else D!=="TRANSLATION"&&D!=="ROTATION"&&D!=="SCALE"&&Q.geometry.setAttribute(D,r[D]);cn.prototype.copy.call(m,Q),this.parser.assignFinalMaterial(m),B.push(m)}return I.isGroup?(I.clear(),I.add(...B),I):B[0]}))}};const FDA="glTF",X0=12,kgA={JSON:1313821514,BIN:5130562};let Pue=class{constructor(A){this.name=bn.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(A,0,X0);if(this.header={magic:bJ(new Uint8Array(A.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==FDA)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-X0,n=new DataView(A,X0);let g=0;for(;g<i;){const o=n.getUint32(g,!0);g+=4;const s=n.getUint32(g,!0);if(g+=4,s===kgA.JSON){const r=new Uint8Array(A,X0+g,o);this.content=bJ(r)}else if(s===kgA.BIN){const r=X0+g;this.body=A.slice(r,r+o)}g+=o}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}},jue=class{constructor(A,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=bn.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={},r={},a={};for(const I in o){const c=y4[I]||I.toLowerCase();s[c]=o[I]}for(const I in A.attributes){const c=y4[I]||I.toLowerCase();if(o[I]!==void 0){const l=i.accessors[A.attributes[I]],B=zm[l.componentType];a[c]=B.name,r[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=r[Q];d!==void 0&&(h.normalized=d)}c(B)},s,a,qE,l)})})}},zue=class{constructor(){this.name=bn.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}},Zue=class{constructor(){this.name=bn.KHR_MESH_QUANTIZATION}},_DA=class extends gy{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,r=s*2,a=s*3,I=n-t,c=(i-t)/I,l=c*c,B=l*c,Q=A*a,h=Q-a,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+r]*I,N=o[Q+D+s],G=o[Q+D]*I;g[D]=y*S+m*k+d*N+p*G}return g}};const Wue=new Ao;let Vue=class extends _DA{interpolate_(A,t,i,n){const g=super.interpolate_(A,t,i,n);return Wue.fromArray(g).normalize().toArray(g),g}};const NC={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:Ds,9729:_g,9984:oG,9985:Hp,9986:Nu,9987:Ra},NgA={33071:nI,33648:ff,10497:va},tO={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},y4={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",...pue>=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"},TQ={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Xue={CUBICSPLINE:void 0,LINEAR:dd,STEP:yf},iO={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function $ue(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new Kg({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Al})),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 aE(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 Ade(e,A,t){let i=!1,n=!1,g=!1;for(let a=0,I=A.length;a<I;a++){const c=A[a];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=[],r=[];for(let a=0,I=A.length;a<I;a++){const c=A[a];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;r.push(l)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(r)]).then(function(a){const I=a[0],c=a[1],l=a[2];return i&&(e.morphAttributes.position=I),n&&(e.morphAttributes.normal=c),g&&(e.morphAttributes.color=l),e.morphTargetsRelative=!0,e})}function ede(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 tde(e){let A;const t=e.extensions&&e.extensions[bn.KHR_DRACO_MESH_COMPRESSION];if(t?A="draco:"+t.bufferView+":"+t.indices+":"+nO(t.attributes):A=e.indices+":"+nO(e.attributes)+":"+e.mode,e.targets!==void 0)for(let i=0,n=e.targets.length;i<n;i++)A+=":"+nO(e.targets[i]);return A}function nO(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 D4(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 ide(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 nde=new ii;let gde=class{constructor(A={},t={}){this.json=A,this.extensions={},this.plugins={},this.options=t,this.cache=new kue,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 Td(this.options.manager):this.textureLoader=new IV(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Aa(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),aE(s,n),Promise.all(i._invokeAll(function(r){return r.afterRoot&&r.afterRoot(s)})).then(function(){for(const r of s.scenes)r.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,r=o.length;s<r;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 r=this.associations.get(o);r!=null&&this.associations.set(s,r);for(const[a,I]of o.children.entries())g(I,s.children[a])};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[bn.KHR_BINARY_GLTF].body);const n=this.options;return new Promise(function(g,o){i.load(XI.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=tO[n.type],s=zm[n.componentType],r=n.normalized===!0,a=new s(n.count*o);return Promise.resolve(new Yi(a,o,r))}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],r=tO[n.type],a=zm[n.componentType],I=a.BYTES_PER_ELEMENT,c=I*r,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 a(s,p*B,n.count*B/I),m=new Lw(h,B/I),t.cache.add(y,m)),d=new IQ(m,r,l%B/I,Q)}else s===null?h=new a(n.count*r):h=new a(s,l,n.count*r),d=new Yi(h,r,Q);if(n.sparse!==void 0){const p=tO.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 a(o[2],D,n.sparse.count*r);s!==null&&(d=new Yi(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*r]),r>=2&&d.setY(M,k[N*r+1]),r>=3&&d.setZ(M,k[N*r+2]),r>=4&&d.setW(M,k[N*r+3]),r>=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 r=i.manager.getHandler(o.uri);r!==null&&(s=r)}return this.loadTextureImage(A,g,s)}loadTextureImage(A,t,i){const n=this,g=this.json,o=g.textures[A],s=g.images[t],r=(s.uri||s.bufferView)+":"+o.sampler;if(this.textureCache[r])return this.textureCache[r];const a=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]||_g,I.minFilter=MgA[l.minFilter]||Ra,I.wrapS=NgA[l.wrapS]||va,I.wrapT=NgA[l.wrapT]||va,n.associations.set(I,{textures:A}),I}).catch(function(){return null});return this.textureCache[r]=a,a}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 r=o.uri||"",a=!1;if(o.bufferView!==void 0)r=i.getDependency("bufferView",o.bufferView).then(function(c){a=!0;const l=new Blob([c],{type:o.mimeType});return r=s.createObjectURL(l),r});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+A+" is missing URI and bufferView");const I=Promise.resolve(r).then(function(c){return new Promise(function(l,B){let Q=l;t.isImageBitmapLoader===!0&&(Q=function(h){const d=new Rg(h);d.needsUpdate=!0,l(d)}),t.load(XI.resolveURL(c,g.path),Q,void 0,B)})}).then(function(c){return a===!0&&s.revokeObjectURL(r),aE(c,o),c.userData.mimeType=o.mimeType||ide(o.uri),c}).catch(function(c){throw console.error("THREE.GLTFLoader: Couldn't load texture",r),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[bn.KHR_TEXTURE_TRANSFORM]){const s=i.extensions!==void 0?i.extensions[bn.KHR_TEXTURE_TRANSFORM]:void 0;if(s){const r=g.associations.get(o);o=g.extensions[bn.KHR_TEXTURE_TRANSFORM].extendTexture(o,s),g.associations.set(o,r)}}return n!==void 0&&(typeof n=="number"&&(n=n===wgA?up:qE),"colorSpace"in o?o.colorSpace=n:o.encoding=n===up?wgA:wue),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 r=this.cache.get(s);r||(r=new ME,co.prototype.copy.call(r,i),r.color.copy(i.color),r.map=i.map,r.sizeAttenuation=!1,this.cache.add(s,r)),i=r}else if(A.isLine){const s="LineBasicMaterial:"+i.uuid;let r=this.cache.get(s);r||(r=new $o,co.prototype.copy.call(r,i),r.color.copy(i.color),r.map=i.map,this.cache.add(s,r)),i=r}if(n||g||o){let s="ClonedMaterial:"+i.uuid+":";n&&(s+="derivative-tangents:"),g&&(s+="vertex-colors:"),o&&(s+="flat-shading:");let r=this.cache.get(s);r||(r=i.clone(),g&&(r.vertexColors=!0),o&&(r.flatShading=!0),n&&(r.normalScale&&(r.normalScale.y*=-1),r.clearcoatNormalScale&&(r.clearcoatNormalScale.y*=-1)),this.cache.add(s,r),this.associations.set(r,this.associations.get(i))),i=r}A.material=i}getMaterialType(){return Kg}loadMaterial(A){const t=this,i=this.json,n=this.extensions,g=i.materials[A];let o;const s={},r=g.extensions||{},a=[];if(r[bn.KHR_MATERIALS_UNLIT]){const c=n[bn.KHR_MATERIALS_UNLIT];o=c.getMaterialType(),a.push(c.extendParams(s,g,t))}else{const c=g.pbrMetallicRoughness||{};if(s.color=new lt(1,1,1),s.opacity=1,Array.isArray(c.baseColorFactor)){const l=c.baseColorFactor;s.color.setRGB(l[0],l[1],l[2],qE),s.opacity=l[3]}c.baseColorTexture!==void 0&&a.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&&(a.push(t.assignTexture(s,"metalnessMap",c.metallicRoughnessTexture)),a.push(t.assignTexture(s,"roughnessMap",c.metallicRoughnessTexture))),o=this._invokeOne(function(l){return l.getMaterialType&&l.getMaterialType(A)}),a.push(Promise.all(this._invokeAll(function(l){return l.extendMaterialParams&&l.extendMaterialParams(A,s)})))}g.doubleSided===!0&&(s.side=Xa);const I=g.alphaMode||iO.OPAQUE;if(I===iO.BLEND?(s.transparent=!0,s.depthWrite=!1):(s.transparent=!1,I===iO.MASK&&(s.alphaTest=g.alphaCutoff!==void 0?g.alphaCutoff:.5)),g.normalTexture!==void 0&&o!==yg&&(a.push(t.assignTexture(s,"normalMap",g.normalTexture)),s.normalScale=new It(1,1),g.normalTexture.scale!==void 0)){const c=g.normalTexture.scale;s.normalScale.set(c,c)}if(g.occlusionTexture!==void 0&&o!==yg&&(a.push(t.assignTexture(s,"aoMap",g.occlusionTexture)),g.occlusionTexture.strength!==void 0&&(s.aoMapIntensity=g.occlusionTexture.strength)),g.emissiveFactor!==void 0&&o!==yg){const c=g.emissiveFactor;s.emissive=new lt().setRGB(c[0],c[1],c[2],qE)}return g.emissiveTexture!==void 0&&o!==yg&&a.push(t.assignTexture(s,"emissiveMap",g.emissiveTexture,up)),Promise.all(a).then(function(){const c=new o(s);return g.name&&(c.name=g.name),aE(c,g),t.associations.set(c,{materials:A}),g.extensions&&Uh(n,c,g),c})}createUniqueName(A){const t=On.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[bn.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(s,t).then(function(r){return RgA(r,s,t)})}const o=[];for(let s=0,r=A.length;s<r;s++){const a=A[s],I=tde(a),c=n[I];if(c)o.push(c.promise);else{let l;a.extensions&&a.extensions[bn.KHR_DRACO_MESH_COMPRESSION]?l=g(a):l=RgA(new ki,a,t),n[I]={primitive:a,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 r=0,a=o.length;r<a;r++){const I=o[r].material===void 0?$ue(this.cache):this.getDependency("material",o[r].material);s.push(I)}return s.push(t.loadGeometries(o)),Promise.all(s).then(function(r){const a=r.slice(0,r.length-1),I=r[r.length-1],c=[];for(let B=0,Q=I.length;B<Q;B++){const h=I[B],d=o[B];let p;const y=a[B];if(d.mode===NC.TRIANGLES||d.mode===NC.TRIANGLE_STRIP||d.mode===NC.TRIANGLE_FAN||d.mode===void 0)p=g.isSkinnedMesh===!0?new zx(h,y):new hn(h,y),p.isSkinnedMesh===!0&&p.normalizeSkinWeights(),d.mode===NC.TRIANGLE_STRIP?p.geometry=SgA(p.geometry,rG):d.mode===NC.TRIANGLE_FAN&&(p.geometry=SgA(p.geometry,Df));else if(d.mode===NC.LINES)p=new BI(h,y);else if(d.mode===NC.LINE_STRIP)p=new DB(h,y);else if(d.mode===NC.LINE_LOOP)p=new Wx(h,y);else if(d.mode===NC.POINTS)p=new Pp(h,y);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+d.mode);Object.keys(p.geometry.morphAttributes).length>0&&ede(p,g),p.name=t.createUniqueName(g.name||"mesh_"+A),aE(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 er;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 zo(zC.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):i.type==="orthographic"&&(t=new Yd(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),aE(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=[],r=[];for(let a=0,I=o.length;a<I;a++){const c=o[a];if(c){s.push(c);const l=new ii;g!==null&&l.fromArray(g.array,a*16),r.push(l)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[a])}return new xw(s,r)})}loadAnimation(A){const t=this.json,i=this,n=t.animations[A],g=n.name?n.name:"animation_"+A,o=[],s=[],r=[],a=[],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)),r.push(this.getDependency("accessor",y)),a.push(Q),I.push(h))}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(r),Promise.all(a),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 r=0,a=n.weights.length;r<a;r++)s.morphTargetInfluences[r]=n.weights[r]}),o})}loadNode(A){const t=this.json,i=this,n=t.nodes[A],g=i._loadNodeShallow(A),o=[],s=n.children||[];for(let a=0,I=s.length;a<I;a++)o.push(i.getDependency("node",s[a]));const r=n.skin===void 0?Promise.resolve(null):i.getDependency("skin",n.skin);return Promise.all([g,Promise.all(o),r]).then(function(a){const I=a[0],c=a[1],l=a[2];l!==null&&I.traverse(function(B){B.isSkinnedMesh&&B.bind(l,nde)});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=[],r=n._invokeOne(function(a){return a.createNodeMesh&&a.createNodeMesh(A)});return r&&s.push(r),g.camera!==void 0&&s.push(n.getDependency("camera",g.camera).then(function(a){return n._getNodeRef(n.cameraCache,g.camera,a)})),n._invokeAll(function(a){return a.createNodeAttachment&&a.createNodeAttachment(A)}).forEach(function(a){s.push(a)}),this.nodeCache[A]=Promise.all(s).then(function(a){let I;if(g.isBone===!0?I=new cG:a.length>1?I=new er:a.length===1?I=a[0]:I=new cn,I!==a[0])for(let c=0,l=a.length;c<l;c++)I.add(a[c]);if(g.name&&(I.userData.name=g.name,I.name=o),aE(I,g),g.extensions&&Uh(i,I,g),g.matrix!==void 0){const c=new ii;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 er;i.name&&(g.name=n.createUniqueName(i.name)),aE(g,i),i.extensions&&Uh(t,g,i);const o=i.nodes||[],s=[];for(let r=0,a=o.length;r<a;r++)s.push(n.getDependency("node",o[r]));return Promise.all(s).then(function(r){for(let I=0,c=r.length;I<c;I++)g.add(r[I]);const a=I=>{const c=new Map;for(const[l,B]of n.associations)(l instanceof co||l instanceof Rg)&&c.set(l,B);return I.traverse(l=>{const B=n.associations.get(l);B!=null&&c.set(l,B)}),c};return n.associations=a(g),g})}_createAnimationTracks(A,t,i,n,g){const o=[],s=A.name?A.name:A.uuid,r=[];TQ[g.path]===TQ.weights?A.traverse(function(l){l.morphTargetInfluences&&r.push(l.name?l.name:l.uuid)}):r.push(s);let a;switch(TQ[g.path]){case TQ.weights:a=CQ;break;case TQ.rotation:a=mB;break;case TQ.position:case TQ.scale:a=SB;break;default:switch(i.itemSize){case 1:a=CQ;break;case 2:case 3:default:a=SB;break}break}const I=n.interpolation!==void 0?Xue[n.interpolation]:dd,c=this._getArrayFromAccessor(i);for(let l=0,B=r.length;l<B;l++){const Q=new a(r[l]+"."+TQ[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=D4(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 mB?Vue:_DA;return new n(this.times,this.values,this.getValueSize()/3,i)},A.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function ode(e,A,t){const i=A.attributes,n=new Vn;if(i.POSITION!==void 0){const s=t.json.accessors[i.POSITION],r=s.min,a=s.max;if(r!==void 0&&a!==void 0){if(n.set(new SA(r[0],r[1],r[2]),new SA(a[0],a[1],a[2])),s.normalized){const I=D4(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,r=new SA;for(let a=0,I=g.length;a<I;a++){const c=g[a];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(r.setX(Math.max(Math.abs(B[0]),Math.abs(Q[0]))),r.setY(Math.max(Math.abs(B[1]),Math.abs(Q[1]))),r.setZ(Math.max(Math.abs(B[2]),Math.abs(Q[2]))),l.normalized){const h=D4(zm[l.componentType]);r.multiplyScalar(h)}s.max(r)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(s)}e.boundingBox=n;const o=new vs;n.getCenter(o.center),o.radius=n.min.distanceTo(n.max)/2,e.boundingSphere=o}function RgA(e,A,t){const i=A.attributes,n=[];function g(o,s){return t.getDependency("accessor",o).then(function(r){e.setAttribute(s,r)})}for(const o in i){const s=y4[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 aE(e,A),ode(e,A,t),Promise.all(n).then(function(){return A.targets!==void 0?Ade(e,A.targets,t):e})}const gO=new WeakMap;class sde extends sr{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 Aa(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 r in t.attributeTypes){const a=t.attributeTypes[r];a.BYTES_PER_ELEMENT!==void 0&&(t.attributeTypes[r]=a.name)}const i=JSON.stringify(t);if(gO.has(A)){const r=gO.get(A);if(r.key===i)return r.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(r=>(n=r,new Promise((a,I)=>{n._callbacks[g]={resolve:a,reject:I},n.postMessage({type:"decode",id:g,taskConfig:t,buffer:A},[A])}))).then(r=>this._createGeometry(r.geometry));return s.catch(()=>!0).then(()=>{n&&g&&this._releaseTask(n,g)}),gO.set(A,{key:i,promise:s}),s}_createGeometry(A){const t=new ki;A.index&&t.setIndex(new Yi(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 Yi(o,s))}return t}_loadLibrary(A,t){const i=new Aa(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=rde.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 rde(){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 r=s.buffer,a=s.taskConfig;A.then(I=>{const c=I.draco,l=new c.Decoder,B=new c.DecoderBuffer;B.Init(new Int8Array(r),r.byteLength);try{const Q=t(c,l,B,a),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,r,a){const I=a.attributeIDs,c=a.attributeTypes;let l,B;const Q=s.GetEncodedGeometryType(r);if(Q===o.TRIANGULAR_MESH)l=new o.Mesh,B=s.DecodeBufferToMesh(r,l);else if(Q===o.POINT_CLOUD)l=new o.PointCloud,B=s.DecodeBufferToPointCloud(r,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(a.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,r){const I=r.num_faces()*3,c=I*4,l=o._malloc(c);s.GetTrianglesUInt32Array(r,c,l);const B=new Uint32Array(o.HEAPF32.buffer,l,I).slice();return o._free(l),{array:B,itemSize:1}}function n(o,s,r,a,I,c){const l=c.num_components(),Q=r.num_points()*l,h=Q*I.BYTES_PER_ELEMENT,d=g(o,I),p=o._malloc(h);s.GetAttributeDataArrayForAllPoints(r,c,d,h,p);const y=new I(o.HEAPF32.buffer,p,Q).slice();return o._free(p),{name:a,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 Av;const oO=()=>{if(Av)return Av;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 r(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 a={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 Av={ready:o,supported:!0,decodeVertexBuffer(c,l,B,Q,h){r(g.exports.meshopt_decodeVertexBuffer,c,l,B,Q,g.exports[a[h]])},decodeIndexBuffer(c,l,B,Q){r(g.exports.meshopt_decodeIndexBuffer,c,l,B,Q)},decodeIndexSequence(c,l,B,Q){r(g.exports.meshopt_decodeIndexSequence,c,l,B,Q)},decodeGltfBuffer(c,l,B,Q,h,d){r(g.exports[I[h]],c,l,B,Q,g.exports[a[d]])}},Av};function ade(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 Ide(e){var A=ade(e,"string");return typeof A=="symbol"?A:A+""}function Cde(e,A,t){return(A=Ide(A))in e?Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[A]=t,e}function GgA(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 Eg(e){for(var A=1;A<arguments.length;A++){var t=arguments[A]!=null?arguments[A]:{};A%2?GgA(Object(t),!0).forEach(function(i){Cde(e,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):GgA(Object(t)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(t,i))})}return e}const cde=new Ao;new or;const lde=new SA;new cn;const Xu=new ii,dr=new SA,jc=new Ao,kf=new SA,Bde=e=>{const[A,t,i]=e;return new SA(A,t,i)},bgA=({x:e,y:A,z:t,w:i})=>cde.set(e,A,t,i),Ede=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)}},Qde={fixed:1,dynamic:0,kinematicPosition:2,kinematicVelocity:3},JDA=e=>Qde[e],ude=(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},LDA=e=>e?e instanceof Ao?[e.x,e.y,e.z,e.w]:e instanceof SA||e instanceof or?[e.x,e.y,e.z]:Array.isArray(e)?e:[e]:[0];function qQ(e){const A=E.useRef(void 0);return A.current===void 0&&(A.current={value:typeof e=="function"?e():e}),A.current.value}const dde=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)},[])},hde=({onStep:e,updatePriority:A})=>(rr((t,i)=>{e(i)},A),null),pde=({onStep:e})=>(dde(A=>{e(A)}),null),fde=({onStep:e,type:A,updatePriority:t})=>A==="independent"?he.createElement(pde,{onStep:e}):he.createElement(hde,{onStep:e,updatePriority:t});var yde=E.memo(fde);function Dde(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 UJ(e,A){if(e==null)return{};var t,i,n=Dde(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 mde=["mass","linearDamping","angularDamping","type","onCollisionEnter","onCollisionExit","onIntersectionEnter","onIntersectionExit","onContactForce","children","canSleep","ccd","gravityScale","softCcdPrediction","ref"],Sde=(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]=ude(i[0],t),i;const n=[t.x,t.y,t.z,t.x,t.x];return i.map((g,o)=>n[o]*g)},wde=(e,A,t,i)=>{const n=Sde(e.shape,e.args,t),g=Uo[e.shape](...n);return A.createCollider(g,i==null?void 0:i())},kde=["shape","args"],UgA="Please pick ONLY ONE of the `density`, `mass` and `massProperties` options.",Mde=(e,A)=>{if(A.density!==void 0){if(A.mass!==void 0||A.massProperties!==void 0)throw new Error(UgA);e.setDensity(A.density);return}if(A.mass!==void 0){if(A.massProperties!==void 0)throw new Error(UgA);e.setMass(A.mass);return}A.massProperties!==void 0&&e.setMassProperties(A.massProperties.mass,A.massProperties.centerOfMass,A.massProperties.principalAngularInertia,A.massProperties.angularInertiaLocalFrame)},xDA={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:()=>{}},TDA=Object.keys(xDA),Nde=(e,A,t)=>{const i=t.get(e.handle);if(i){var n;const g=i.object.parent.getWorldScale(lde),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(dr,jc,kf),e.parent()?(e.setTranslationWrtParent({x:dr.x*g.x,y:dr.y*g.y,z:dr.z*g.z}),e.setRotationWrtParent(jc)):(e.setTranslation({x:dr.x*g.x,y:dr.y*g.y,z:dr.z*g.z}),e.setRotation(jc)),TDA.forEach(s=>{if(s in A){const r=A[s];xDA[s](e,r,A)}}),Mde(e,A)}},Rde=(e,A,t)=>{const i=E.useMemo(()=>TDA.flatMap(n=>LDA(A[n])),[A]);E.useEffect(()=>{const n=e();Nde(n,A,t)},[...i,e])},Gde=e=>{let A=!1;return e.traverseAncestors(t=>{t.userData.r3RapierType==="MeshCollider"&&(A=!0)}),A},bde=(e,A,t)=>({collider:e,worldParent:t||void 0,object:A}),Ude={cuboid:"cuboid",ball:"ball",hull:"convexHull",trimesh:"trimesh"},vde=({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&&Gde(o))return;const s=o.getWorldScale(kf),r=Ude[t.colliders||"cuboid"];o.updateWorldMatrix(!0,!1),Xu.copy(o.matrixWorld).premultiply(n).decompose(dr,jc,kf);const a=new or().setFromQuaternion(jc,"XYZ"),{geometry:I}=o,{args:c,offset:l}=Kde(I,t.colliders||"cuboid"),B=Eg(Eg({},YDA(t)),{},{args:c,shape:r,rotation:[a.x,a.y,a.z],position:[dr.x+l.x*s.x,dr.y+l.y*s.y,dr.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},Kde=(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():fue(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}},qDA=e=>({collision:!!(e!=null&&e.onCollisionEnter||e!=null&&e.onCollisionExit||e!=null&&e.onIntersectionEnter||e!=null&&e.onIntersectionExit),contactForce:!!(e!=null&&e.onContactForce)}),Fde=(e,A,t,i={})=>{const{onCollisionEnter:n,onCollisionExit:g,onIntersectionEnter:o,onIntersectionExit:s,onContactForce:r}=A;E.useEffect(()=>{const a=e();if(a){const{collision:I,contactForce:c}=qDA(A),l=I||i.collision,B=c||i.contactForce;l&&B?a.setActiveEvents(kE.COLLISION_EVENTS|kE.CONTACT_FORCE_EVENTS):l?a.setActiveEvents(kE.COLLISION_EVENTS):B&&a.setActiveEvents(kE.CONTACT_FORCE_EVENTS),t.set(a.handle,{onCollisionEnter:n,onCollisionExit:g,onIntersectionEnter:o,onIntersectionExit:s,onContactForce:r})}return()=>{a&&t.delete(a.handle)}},[n,g,o,s,r,i])},YDA=(e={})=>UJ(e,mde),uT=()=>{const e=E.useContext(HDA);if(!e)throw new Error("react-three-rapier: useRapier must be used within <Physics />!");return e},MV=(e,A,t=!0)=>{const[i,n]=E.useState([]);return E.useEffect(()=>{e.current&&A.colliders!==!1&&n(vde({object:e.current,options:A,ignoreMeshColliders:t}))},[A.colliders]),i},_de=E.memo(()=>{const{world:e}=uT(),A=E.useRef(null);return rr(()=>{const t=A.current;if(!t)return;const i=e.debugRender(),n=new ki;n.setAttribute("position",new Yi(i.vertices,3)),n.setAttribute("color",new Yi(i.colors,4)),t.geometry.dispose(),t.geometry=n}),he.createElement("group",null,he.createElement("lineSegments",{ref:A,frustumCulled:!1},he.createElement("lineBasicMaterial",{color:16777215,vertexColors:!0}),he.createElement("bufferGeometry",null)))}),Jde=e=>{let A;const t={get(o,s){return A||(A=e()),Reflect.get(A,s)},set(o,s,r){return A||(A=e()),Reflect.set(A,s,r)}};return{proxy:new Proxy({},t),reset:()=>{A=void 0},set:o=>{A=o}}},HDA=E.createContext(void 0),ev=(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}},vgA=async()=>{let e=await li(()=>Promise.resolve().then(()=>xse),void 0);return await e.init(),e},Lde=e=>{const{colliders:A="cuboid",children:t,timeStep:i=1/60,paused:n=!1,interpolate:g=!0,updatePriority:o,updateLoop:s="follow",debug:r=!1,gravity:a=[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=CDA(vgA,["@react-thee/rapier",vgA]),{invalidate:D}=Ac(),S=qQ(()=>new Map),k=qQ(()=>new Map),N=qQ(()=>new Map),G=qQ(()=>new Map),M=qQ(()=>new kW(!1)),w=qQ(()=>new Set),b=qQ(()=>new Set),{proxy:_,reset:K,set:J}=qQ(()=>Jde(()=>new m.World(Bde(a))));E.useEffect(()=>()=>{_.free(),K()},[]),E.useEffect(()=>{_.gravity=Ede(a),_.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},[_,...a,l,B,Q,I,h,d,c,y,p]);const T=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=zC.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 YA;RA==null||(YA=RA.onSleep)===null||YA===void 0||YA.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,bgA(H.rotation),gA.scale).premultiply(gA.invertedWorldMatrix).decompose(dr,jc,kf),gA.meshType=="mesh"&&(gA.object.position.copy(dr),gA.object.quaternion.copy(jc))),Xu.compose($,bgA(L),gA.scale).premultiply(gA.invertedWorldMatrix).decompose(dr,jc,kf),gA.meshType=="instancedMesh"?gA.setMatrix(Xu):(gA.object.position.lerp(dr,pA),gA.object.quaternion.slerp(jc,pA))}),M.drainCollisionEvents((gA,yA,fA)=>{const RA=T(gA),YA=T(yA);if(!(RA!=null&&RA.collider.object)||!(YA!=null&&YA.collider.object))return;const W=ev(RA,YA),$=ev(YA,RA);if(fA)Z.contactPair(RA.collider.object,YA.collider.object,(KA,Ie)=>{var DA,IA,EA,j,dA,hA,UA,TA;(DA=RA.rigidBody.events)===null||DA===void 0||(IA=DA.onCollisionEnter)===null||IA===void 0||IA.call(DA,Eg(Eg({},W),{},{manifold:KA,flipped:Ie})),(EA=YA.rigidBody.events)===null||EA===void 0||(j=EA.onCollisionEnter)===null||j===void 0||j.call(EA,Eg(Eg({},$),{},{manifold:KA,flipped:Ie})),(dA=RA.collider.events)===null||dA===void 0||(hA=dA.onCollisionEnter)===null||hA===void 0||hA.call(dA,Eg(Eg({},W),{},{manifold:KA,flipped:Ie})),(UA=YA.collider.events)===null||UA===void 0||(TA=UA.onCollisionEnter)===null||TA===void 0||TA.call(UA,Eg(Eg({},$),{},{manifold:KA,flipped:Ie}))});else{var L,H,P,tA,iA,oA,CA,cA;(L=RA.rigidBody.events)===null||L===void 0||(H=L.onCollisionExit)===null||H===void 0||H.call(L,W),(P=YA.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),(CA=YA.collider.events)===null||CA===void 0||(cA=CA.onCollisionExit)===null||cA===void 0||cA.call(CA,$)}if(fA){if(Z.intersectionPair(RA.collider.object,YA.collider.object)){var _A,uA,X,O,lA,wA,xA,HA;(_A=RA.rigidBody.events)===null||_A===void 0||(uA=_A.onIntersectionEnter)===null||uA===void 0||uA.call(_A,W),(X=YA.rigidBody.events)===null||X===void 0||(O=X.onIntersectionEnter)===null||O===void 0||O.call(X,$),(lA=RA.collider.events)===null||lA===void 0||(wA=lA.onIntersectionEnter)===null||wA===void 0||wA.call(lA,W),(xA=YA.collider.events)===null||xA===void 0||(HA=xA.onIntersectionEnter)===null||HA===void 0||HA.call(xA,$)}}else{var zA,ne,ye,Ee,NA,QA,PA,VA;(zA=RA.rigidBody.events)===null||zA===void 0||(ne=zA.onIntersectionExit)===null||ne===void 0||ne.call(zA,W),(ye=YA.rigidBody.events)===null||ye===void 0||(Ee=ye.onIntersectionExit)===null||Ee===void 0||Ee.call(ye,$),(NA=RA.collider.events)===null||NA===void 0||(QA=NA.onIntersectionExit)===null||QA===void 0||QA.call(NA,W),(PA=YA.collider.events)===null||PA===void 0||(VA=PA.onIntersectionExit)===null||VA===void 0||VA.call(PA,$)}}),M.drainContactForceEvents(gA=>{var yA,fA,RA,YA,W,$,L,H;const P=T(gA.collider1()),tA=T(gA.collider2());if(!(P!=null&&P.collider.object)||!(tA!=null&&tA.collider.object))return;const iA=ev(P,tA),oA=ev(tA,P);(yA=P.rigidBody.events)===null||yA===void 0||(fA=yA.onContactForce)===null||fA===void 0||fA.call(yA,Eg(Eg({},iA),{},{totalForce:gA.totalForce(),totalForceMagnitude:gA.totalForceMagnitude(),maxForceDirection:gA.maxForceDirection(),maxForceMagnitude:gA.maxForceMagnitude()})),(RA=tA.rigidBody.events)===null||RA===void 0||(YA=RA.onContactForce)===null||YA===void 0||YA.call(RA,Eg(Eg({},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,Eg(Eg({},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,Eg(Eg({},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:a},rigidBodyStates:S,colliderStates:k,rigidBodyEvents:N,colliderEvents:G,beforeStepCallbacks:w,afterStepCallbacks:b,isPaused:n,isDebug:r,step:U}),[n,U,r,A,a]),q=E.useCallback(z=>{n||U(z)},[n,U]);return he.createElement(HDA.Provider,{value:x},he.createElement(yde,{onStep:q,type:s,updatePriority:o}),r&&he.createElement(_de,null),t)};function ir(){return ir=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},ir.apply(null,arguments)}const NV=(e,A=null)=>{const t=E.useRef(A);return e&&typeof e!="function"?(e.current||(e.current=t.current),e):t},ODA=(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},xde=e=>{var A;const t=JDA((e==null?void 0:e.type)||"dynamic"),i=new JC(t);return i.canSleep=(A=e==null?void 0:e.canSleep)!==null&&A!==void 0?A:!0,i},Tde=({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}},qde=["args","colliders","canSleep"],PDA={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(JDA(A),!0)},position:()=>{},rotation:()=>{},quaternion:()=>{},scale:()=>{}},jDA=Object.keys(PDA),Yde=(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(dr,jc,kf),e.setTranslation(dr,!1),e.setRotation(jc,!1)),jDA.forEach(g=>{g in A&&PDA[g](e,A[g])}))},Hde=(e,A,t,i=!0)=>{const n=E.useMemo(()=>jDA.flatMap(g=>LDA(A[g])),[A]);E.useEffect(()=>{const g=e();Yde(g,A,t,i)},n)},Ode=(e,A,t)=>{const{onWake:i,onSleep:n,onCollisionEnter:g,onCollisionExit:o,onIntersectionEnter:s,onIntersectionExit:r,onContactForce:a}=A,I={onWake:i,onSleep:n,onCollisionEnter:g,onCollisionExit:o,onIntersectionEnter:s,onIntersectionExit:r,onContactForce:a};E.useEffect(()=>{const c=e();return t.set(c.handle,I),()=>{t.delete(c.handle)}},[i,n,g,o,s,r,a])},Pde=({x:e,y:A,z:t}={x:0,y:0,z:0})=>new SA(e,A,t),nC=E.memo(e=>{const{children:A,position:t,rotation:i,quaternion:n,scale:g,name:o}=e,{world:s,colliderEvents:r,colliderStates:a}=uT(),I=WDA(),c=NV(e.ref),l=E.useRef(null),B=kde.flatMap(d=>Array.isArray(e[d])?e[d]:[e[d]]),Q=ODA(()=>{const d=l.current.getWorldScale(Pde()),p=wde(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 a.set(d.handle,bde(d,l.current,I==null?void 0:I.ref.current)),()=>{a.delete(d.handle)}},[Q]);const h=E.useMemo(()=>Eg(Eg({},YDA(I==null?void 0:I.options)),e),[e,I==null?void 0:I.options]);return Rde(Q,h,a),Fde(Q,h,r,qDA(I==null?void 0:I.options)),he.createElement("object3D",{position:t,rotation:i,quaternion:n,scale:g,ref:l,name:o},A)}),jde=he.forwardRef((e,A)=>he.createElement(nC,ir({},e,{shape:"cuboid",ref:A})));jde.displayName="CuboidCollider";const zde=he.forwardRef((e,A)=>he.createElement(nC,ir({},e,{shape:"roundCuboid",ref:A})));zde.displayName="RoundCuboidCollider";const Zde=he.forwardRef((e,A)=>he.createElement(nC,ir({},e,{shape:"ball",ref:A})));Zde.displayName="BallCollider";const Wde=he.forwardRef((e,A)=>he.createElement(nC,ir({},e,{shape:"capsule",ref:A})));Wde.displayName="CapsuleCollider";const Vde=he.forwardRef((e,A)=>he.createElement(nC,ir({},e,{shape:"heightfield",ref:A})));Vde.displayName="HeightfieldCollider";const Xde=he.forwardRef((e,A)=>he.createElement(nC,ir({},e,{shape:"trimesh",ref:A})));Xde.displayName="TrimeshCollider";const $de=he.forwardRef((e,A)=>he.createElement(nC,ir({},e,{shape:"cone",ref:A})));$de.displayName="ConeCollider";const Ahe=he.forwardRef((e,A)=>he.createElement(nC,ir({},e,{shape:"roundCone",ref:A})));Ahe.displayName="RoundConeCollider";const zDA=he.forwardRef((e,A)=>he.createElement(nC,ir({},e,{shape:"cylinder",ref:A})));zDA.displayName="CylinderCollider";zDA.displayName="RoundCylinderCollider";const ehe=he.forwardRef((e,A)=>he.createElement(nC,ir({},e,{shape:"convexHull",ref:A})));ehe.displayName="ConvexHullCollider";const the=["ref","children","type","position","rotation","scale","quaternion","transformState"],ZDA=E.createContext(void 0),WDA=()=>E.useContext(ZDA),NE=E.memo(e=>{const{ref:A,children:t,type:i,position:n,rotation:g,scale:o,quaternion:s,transformState:r}=e,a=UJ(e,the),I=E.useRef(null),c=NV(A),{world:l,rigidBodyStates:B,physicsOptions:Q,rigidBodyEvents:h}=uT(),d=E.useMemo(()=>Eg(Eg(Eg({},Q),e),{},{children:void 0}),[Q,e]),p=qde.flatMap(S=>Array.isArray(d[S])?[...d[S]]:d[S]),y=MV(I,d),m=ODA(()=>{const S=xde(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=Tde({rigidBody:S,object:I.current});return B.set(S.handle,e.transformState?e.transformState(k):k),()=>{B.delete(S.handle)}},[m]),Hde(m,d,B),Ode(m,d,h);const D=E.useMemo(()=>({ref:I,getRigidBody:m,options:d}),[m]);return he.createElement(ZDA.Provider,{value:D},he.createElement("object3D",ir({ref:I},a,{position:n,rotation:g,quaternion:s,scale:o}),t,y.map((S,k)=>he.createElement(nC,ir({key:k},S)))))});NE.displayName="RigidBody";const ihe=E.memo(e=>{const{children:A,type:t}=e,{physicsOptions:i}=uT(),n=E.useRef(null),{options:g}=WDA(),o=E.useMemo(()=>Eg(Eg(Eg({},i),g),{},{children:void 0,colliders:t}),[i,g]),s=MV(n,o,!1);return he.createElement("object3D",{ref:n,userData:{r3RapierType:"MeshCollider"}},A,s.map((r,a)=>he.createElement(nC,ir({key:a},r))))});ihe.displayName="MeshCollider";const nhe=["ref"],ghe=["children","instances","colliderNodes","position","rotation","quaternion","scale"],ohe=E.memo(e=>{let{ref:A}=e,t=UJ(e,nhe);const i=NV(A,[]),n=E.useRef(null),g=E.useRef(null),{children:o,instances:s,colliderNodes:r=[],position:a,rotation:I,quaternion:c,scale:l}=t,B=UJ(t,ghe),Q=MV(n,Eg(Eg({},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(oyA):console.warn("InstancedRigidBodies expects exactly one child, which must be an InstancedMesh")},[]);const d=(p,y)=>{const m=h();return m?Eg(Eg({},p),{},{getMatrix:D=>(m.getMatrixAt(y,D),D),setMatrix:D=>{m.setMatrixAt(y,D),m.instanceMatrix.needsUpdate=!0},meshType:"instancedMesh"}):p};return he.createElement("object3D",ir({ref:n},B,{position:a,rotation:I,quaternion:c,scale:l}),he.createElement("object3D",{ref:g},o),s==null?void 0:s.map((p,y)=>he.createElement(NE,ir({},B,p,{ref:m=>{i.current[y]=m},transformState:m=>d(m,y)}),he.createElement(he.Fragment,null,r.map((m,D)=>he.createElement(E.Fragment,{key:D},m)),Q.map((m,D)=>he.createElement(nC,ir({key:D},m)))))))});ohe.displayName="InstancedRigidBodies";function m4(){return m4=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},m4.apply(null,arguments)}const she=e=>e;function rhe(e,A=she){const t=he.useSyncExternalStore(e.subscribe,he.useCallback(()=>A(e.getState()),[e,A]),he.useCallback(()=>A(e.getInitialState()),[e,A]));return he.useDebugValue(t),t}const KgA=e=>{const A=sDA(e),t=i=>rhe(A,i);return Object.assign(t,A),t},ahe=e=>e?KgA(e):KgA,sO=e=>e===Object(e)&&!Array.isArray(e)&&typeof e!="function";function Hw(e,A){const t=Ac(g=>g.gl),i=Hd(Td,sO(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 Rg?g=[i]:sO(i)&&(g=Object.values(i)),g.forEach(o=>{o instanceof Rg&&t.initTexture(o)})}},[t,i]),E.useMemo(()=>{if(sO(e)){const g={};let o=0;for(const s in e)g[s]=i[o++];return g}else return i},[e,i])}Hw.preload=e=>Hd.preload(Td,e);Hw.clear=e=>Hd.clear(Td,e);let tv=null,VDA="https://www.gstatic.com/draco/versioned/decoders/1.5.5/";function XDA(e=!0,A=!0,t){return i=>{t&&t(i),e&&(tv||(tv=new sde),tv.setDecoderPath(typeof e=="string"?e:VDA),i.setDRACOLoader(tv)),A&&i.setMeshoptDecoder(typeof oO=="function"?oO():oO)}}const ba=(e,A,t,i)=>Hd(kV,e,XDA(A,t,i));ba.preload=(e,A,t,i)=>Hd.preload(kV,e,XDA(A,t,i));ba.clear=e=>Hd.clear(kV,e);ba.setDecoderPath=e=>{VDA=e};function Ihe(e,A,t){const i=Ac(B=>B.size),n=Ac(B=>B.viewport),g=typeof e=="number"?e:i.width*n.dpr,o=i.height*n.dpr,s=(typeof e=="number"?t:e)||{},{samples:r=0,depth:a,...I}=s,c=a??s.depthBuffer,l=E.useMemo(()=>{const B=new el(g,o,{minFilter:_g,magFilter:_g,type:iy,...I});return c&&(B.depthTexture=new Xx(g,o,Ga)),B.samples=r,B},[]);return E.useLayoutEffect(()=>{l.setSize(g,o),r&&(l.samples=r)},[r,l,g,o]),E.useEffect(()=>()=>l.dispose(),[]),l}const Che=e=>typeof e=="function",che=E.forwardRef(({envMap:e,resolution:A=256,frames:t=1/0,children:i,makeDefault:n,...g},o)=>{const s=Ac(({set:d})=>d),r=Ac(({camera:d})=>d),a=Ac(({size:d})=>d),I=E.useRef(null);E.useImperativeHandle(o,()=>I.current,[]);const c=E.useRef(null),l=Ihe(A);E.useLayoutEffect(()=>{g.manual||I.current.updateProjectionMatrix()},[a,g]),E.useLayoutEffect(()=>{I.current.updateProjectionMatrix()}),E.useLayoutEffect(()=>{if(n){const d=r;return s(()=>({camera:I.current})),()=>s(()=>({camera:d}))}},[I,n,s]);let B=0,Q=null;const h=Che(i);return rr(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",m4({left:a.width/-2,right:a.width/2,top:a.height/2,bottom:a.height/-2,ref:I},g),!h&&i),E.createElement("group",{ref:c},h&&i(l.texture)))});function lhe(e,A){const t=E.useRef(null),[i]=E.useState(()=>A?A instanceof cn?{current:A}:A:t),[n]=E.useState(()=>new EV(void 0));E.useLayoutEffect(()=>{A&&(i.current=A instanceof cn?A:A.current),n._root=i.current});const g=E.useRef({}),o=E.useMemo(()=>{const s={};return e.forEach(r=>Object.defineProperty(s,r.name,{enumerable:!0,get(){if(i.current)return g.current[r.name]||(g.current[r.name]=n.clipAction(r,i.current))},configurable:!0})),{ref:i,clips:e,actions:s,names:e.map(r=>r.name),mixer:n}},[e]);return rr((s,r)=>n.update(r)),E.useEffect(()=>{const s=i.current;return()=>{g.current={},n.stopAllAction(),Object.values(o.actions).forEach(r=>{s&&n.uncacheAction(r,s)})}},[e]),o}const Bhe=2e3,Ehe=5e3,FgA=.08,Ap="/models/dice.glb",_gA=new URL("/assets/dice-GytAQsgt.glb",import.meta.url).href;function iv(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?`${_gA}?${t}`:_gA;const n="/";return`${n.endsWith("/")?n:`${n}/`}${e.replace(/^\.?\//,"")}`}function JgA({result:e,position:A,rollTrigger:t,noAnimation:i=!1,active:n=!0,chargeLevel:g=0,modelOverride:o}){const[s,r]=E.useState(iv(o||Ap)),a=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 q;try{(q=ba.preload)==null||q.call(ba,iv(Ap))}catch{}},[]),E.useEffect(()=>{if(o){r(iv(o));return}let q=!1;return(async()=>{try{const z=await Wo();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`),q||r(iv(Z))}catch{}})(),()=>{q=!0}},[o]);const I=E.useMemo(()=>s.split("?")[0],[s]),c=ba(I),l=E.useMemo(()=>{const q=c.scene.clone(!0),z=a?new lt(a):null;return q.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{}}}}),q},[c.scene,a]),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 or),G=E.useRef(new Ao),M=E.useRef(null),w=E.useRef(0);w.current=g;const b=E.useCallback(q=>{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+q*.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 q=B.current;if(q)if(n)(Z=q.wakeUp)==null||Z.call(q);else{d.current=!1;try{q.setLinvel({x:0,y:0,z:0},!0),q.setAngvel({x:0,y:0,z:0},!0),(z=q.sleep)==null||z.call(q)}catch{}if(p.current){p.current=!1,y.current&&(window.clearTimeout(y.current),y.current=null);try{kC()}catch{}}}},[n]),E.useEffect(()=>()=>{try{y.current&&(window.clearTimeout(y.current),y.current=null),kC()}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 q=B.current;if(q)try{(z=q.wakeUp)==null||z.call(q),q.setLinvel({x:0,y:0,z:0},!0),q.setAngvel({x:0,y:0,z:0},!0)}catch{}if(m.current=!0,!p.current){p.current=!0;try{UvA({volume:.075,playbackRate:1})}catch{}y.current&&window.clearTimeout(y.current),y.current=window.setTimeout(()=>{if(p.current){p.current=!1;try{kC()}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{kC()}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=Vb[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 q=Date.now()-(Q.current??Date.now()),z=Math.max(0,Bhe-q);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{kC()}catch{}}const eA=B.current;if(!eA)return;try{const gA=eA.translation(),yA=4.2,fA=gA.x,RA=gA.z,YA=Math.sqrt(fA*fA+RA*RA);if(YA>yA){const W=yA/YA;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=Vb[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{kC()}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),T=E.useRef(!1),v=E.useRef(0),U=10,x=E.useRef(0);return rr((q,z)=>{var gA,yA,fA,RA,YA,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,CA=$.z;if(P>eA){const cA=(eA-.3)/P;iA=L*cA,CA=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:CA},!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 CA=.3+pA*1.2;Z.setAngvel({x:Math.sin($*H*.7)*CA,y:0,z:Math.cos($*H*.9)*CA},!0);return}if(pA===0&&x.current>0&&!d.current&&(x.current=0),d.current&&n){if(Q.current&&Date.now()-Q.current>Ehe){if(d.current=!1,p.current){p.current=!1,y.current&&(window.clearTimeout(y.current),y.current=null);try{kC()}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 CA=Vb[e];if(CA){const cA=N.current,_A=G.current;cA.set(CA[0],CA[1],CA[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,T.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 CA=P-H+15;Z.setAngvel({x:L.x+(Math.random()-.5)*CA,y:L.y+(Math.random()-.5)*CA,z:L.z+(Math.random()-.5)*CA},!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 CA={x:(Math.random()-.5)*10,y:4,z:(Math.random()-.5)*10};Z.applyImpulse(CA,!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=Vb[e];if(tA){const CA=N.current,cA=G.current;CA.set(tA[0],tA[1],tA[2]),cA.setFromEuler(CA),Z.setRotation(cA,!0)}const iA=((RA=M.current)==null?void 0:RA.x)??(A==null?void 0:A[0])??0,oA=((YA=M.current)==null?void 0:YA.z)??(A==null?void 0:A[2])??0;Z.setTranslation({x:iA,y:2,z:oA},!0),J.current=!0,H<FgA&&P<FgA?(v.current++,v.current>=U&&(T.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{kC()}catch{}}},[]),E.useEffect(()=>{const q=()=>{try{p.current&&(p.current=!1,y.current&&(window.clearTimeout(y.current),y.current=null),kC())}catch{}},z=()=>{document.visibilityState==="hidden"&&q()},Z=()=>q(),eA=()=>q();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(NE,{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 za=6.5,Qhe=za+.65,LgA=[[3,1,0],[-1.5,1,2.6],[-1.5,1,-2.6]],xgA=[[-3,1,0],[3,1,0]],Zm=24,vJ=3,uhe=1.2,dhe=1,KJ=za-dhe,hhe=2*KJ*Math.sin(Math.PI/Zm),phe=Array.from({length:Zm},(e,A)=>{const t=A*2*Math.PI/Zm;return{position:[Math.cos(t)*KJ,vJ/2,Math.sin(t)*KJ],rotation:[0,-t+Math.PI/2,0],width:hhe,height:vJ,thickness:uhe}}),rO=5,fhe=za,yhe=1,Dhe=1.4,$DA=[];for(let e=0;e<rO;e++){const A=e/rO,t=(e+1)/rO,i=(A+t)/2,n=vJ+i*(fhe-vJ),g=Math.max(.5,KJ*Math.cos(i*(Math.PI/2))),o=2*g*Math.sin(Math.PI/Zm),s=i*(Math.PI/2);for(let r=0;r<Zm;r++){const a=r*2*Math.PI/Zm;$DA.push({position:[Math.cos(a)*g,n,Math.sin(a)*g],rotation:[s,-a+Math.PI/2,0],width:o,height:Dhe,thickness:yhe})}}function TgA(){return C.jsxs(C.Fragment,{children:[phe.map((e,A)=>C.jsx(NE,{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}`)),$DA.map((e,A)=>C.jsx(NE,{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 mhe={uTime:{value:0},uShimmerColor:{value:new SA(1,1,1)}},She=`
    varying vec2 vUv;
    void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
`,whe=`
    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 qgA({shimmerColor:e}){const A=E.useMemo(()=>new rc({uniforms:HW.clone(mhe),vertexShader:She,fragmentShader:whe,transparent:!0,depthWrite:!1}),[]);return E.useEffect(()=>{if(e){const t=new lt(e);A.uniforms.uShimmerColor.value.set(t.r,t.g,t.b)}else A.uniforms.uShimmerColor.value.set(1,1,1)},[e,A]),rr((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:[Qhe,128]}),C.jsx("primitive",{object:A,attach:"material"})]})}function khe({results:e,rollTrigger:A,preRollTrigger:t,showDice:i,gameMode:n="cee-lo",gameState:g,noAnimation:o=!1,chargeLevel:s=0,feltColor:r,shimmerColor:a,numberOfDice:I,diceModels:c}){const{scheduleReveal:l}=MB(),B=t??0,Q=E.useMemo(()=>{if(!r)return!1;const k=r.trim().toLowerCase();return k==="transparent"||k==="rgba(0,0,0,0)"||k==="rgba(0, 0, 0, 0)"},[r]),h=I?LgA.slice(0,I):LgA,d=I?xgA.slice(0,I):xgA,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=Ac(),m=E.useMemo(()=>({felt:new Kg({color:Q?"#0e3a20":r??"#0e3a20",roughness:.95,metalness:.02,transparent:Q,opacity:Q?0:1,depthWrite:!Q}),rim:new Kg({color:"gold",roughness:.4,metalness:.85,envMapIntensity:.6})}),[r,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 T=J.material;T&&(Array.isArray(T)?T.forEach(v=>{v.needsUpdate=!0,v.map&&(v.map.needsUpdate=!0)}):(T.needsUpdate=!0,T.map&&(T.map.needsUpdate=!0)))});try{k.outputColorSpace=sn}catch{}try{k.toneMapping=ty}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":r??"#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(NE,{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:[za,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:[za-.15,za+.2,128]}),C.jsx("primitive",{object:m.rim,attach:"material"})]}),C.jsx(qgA,{shimmerColor:a}),C.jsx(NE,{type:"fixed",colliders:"cuboid",position:[0,-.5,0],friction:.9,restitution:.15,children:C.jsxs("mesh",{visible:!1,children:[C.jsx("boxGeometry",{args:[za*2,1,za*2]}),C.jsx("meshStandardMaterial",{transparent:!0,opacity:0})]})}),C.jsx(TgA,{}),i&&d.map((G,M)=>C.jsx(JgA,{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(NE,{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:[za,128]}),C.jsx("primitive",{object:m.felt,attach:"material"})]}),C.jsx(NE,{type:"fixed",colliders:"cuboid",position:[0,-.5,0],friction:.9,restitution:.15,children:C.jsxs("mesh",{visible:!1,children:[C.jsx("boxGeometry",{args:[za*2,1,za*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:[za-.15,za+.2,128]}),C.jsx("primitive",{object:m.rim,attach:"material"})]}),C.jsx(qgA,{shimmerColor:a}),C.jsx(TgA,{}),i&&h.map((k,N)=>C.jsx(JgA,{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 JK=null,LK=null;function YgA(e){JK=e}function HgA(e){LK=e}function aO(){try{JK==null||JK()}catch{}}function OgA(){try{LK==null||LK()}catch{}}let Im=null;const dT=typeof navigator<"u"&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1),Mhe=dT?[1,1]:[1,1.5],Nhe=!dT,AmA={alpha:!0,antialias:!dT,powerPreference:"high-performance"};function emA(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 Rhe(){if(typeof document>"u")return!1;try{const e=document.createElement("canvas");e.width=16,e.height=16;const A=AmA,t=e.getContext("webgl2",A)||e.getContext("webgl",A)||e.getContext("experimental-webgl",A);return emA(t)}catch{return!1}}const Ll=()=>{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 tmA(){Ll()}class Ghe extends he.Component{constructor(){super(...arguments);Ti(this,"state",{hasError:!1})}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t,i){var g;FI.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 bhe(){const{size:e,camera:A}=Ac();return he.useEffect(()=>{const t=Math.min(e.width,e.height)/2,i=za+.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,r=t/(i*s),a=A;a.zoom=r,a.updateProjectionMatrix()},[e.width,e.height,A]),null}function imA({isWaiting:e,rollTrigger:A,results:t,preRollTrigger:i,gameMode:n="cee-lo",gameState:g,diceSettled:o,chargeLevel:s=0,cameraAngle:r=0,feltColor:a,shimmerColor:I,numberOfDice:c,diceModels:l,rollEnabled:B=!1,onRollRequest:Q}){const h=n==="craps",[d,p]=he.useState(!0),[y,m]=he.useState(null),D=he.useRef(null),[S,k]=he.useState(0),[N,G]=he.useState(!1),[M,w]=he.useState(!1),[b,_]=he.useState(0),K=he.useRef(0),J=he.useRef(!0),T=he.useRef(null),v=he.useRef(null),U=dT?8:2,x=he.useCallback(()=>{J.current&&(Ll(),G(!0))},[]),q=he.useCallback(()=>{K.current=Math.min(K.current+1,U+1),_(K.current)},[]),z=he.useCallback(()=>{K.current=0,_(0)},[]),Z=he.useCallback(()=>{T.current!=null&&(window.clearTimeout(T.current),T.current=null)},[]),eA=he.useCallback(()=>{v.current!=null&&(window.clearTimeout(v.current),v.current=null)},[]),aA=he.useCallback(uA=>{J.current&&(Z(),w(!1),T.current=window.setTimeout(()=>{T.current=null,J.current&&k(X=>X+1)},Math.max(16,uA)))},[Z]),sA=he.useCallback(()=>{J.current&&(Z(),Ll(),z(),G(!1),w(!1),aA(50))},[Z,z,aA]);he.useEffect(()=>(J.current=!0,YgA(Ll),HgA(sA),()=>{J.current=!1,YgA(null),HgA(null),Z(),eA(),Ll()}),[eA,Z,sA]),he.useEffect(()=>{if(N)return;let uA=!1;eA();const X=()=>{var lA;if(uA||!J.current)return;if(Rhe()){w(!0),K.current>0&&z();return}w(!1);const O=K.current;try{(lA=FI.warn)==null||lA.call(FI,"DiceBoard WebGL preflight failed",{attempt:O,max:U})}catch{}if(O<U){q();const wA=Math.min(2200,350*Math.pow(1.55,O));v.current=window.setTimeout(X,wA)}else x()};return X(),()=>{uA=!0,eA()}},[q,S,eA,x,z,N]),he.useEffect(()=>{let uA=!1;const X=HA=>{var ye,Ee;if(uA)return;const zA=Im;if(!zA)return;let ne=!1;try{const NA=(ye=zA.getContext)==null?void 0:ye.call(zA);ne=!!(NA&&typeof NA.isContextLost=="function"&&NA.isContextLost())}catch{ne=!0}if(ne){try{(Ee=FI.warn)==null||Ee.call(FI,"DiceBoard probe detected lost WebGL context, forcing fresh remount",{source:HA})}catch{}Ll(),z(),aA(250)}},O=()=>{document.visibilityState==="visible"&&X("visibilitychange")},lA=()=>X("pageshow"),wA=HA=>{var ye,Ee;const zA=HA.reason,ne=zA&&(zA.message||String(zA))||"";if(!uA&&(ne.includes("reading 'precision'")||ne.includes("getShaderPrecisionFormat")||ne.includes("WebGLRenderer")||ne.includes("WebGLCapabilities")||ne.includes("initGLContext"))){try{(ye=FI.warn)==null||ye.call(FI,"DiceBoard caught WebGL init rejection, scheduling remount",{msg:ne.slice(0,200)})}catch{}Ll();const NA=K.current,QA=Math.min(1600,400*Math.pow(2,NA));NA<U?(q(),aA(QA)):!uA&&J.current&&x();try{(Ee=HA.preventDefault)==null||Ee.call(HA)}catch{}}};document.addEventListener("visibilitychange",O),window.addEventListener("pageshow",lA),window.addEventListener("unhandledrejection",wA);let xA=null;return(async()=>{var HA;try{const{App:zA}=await li(async()=>{const{App:ne}=await Promise.resolve().then(()=>UR);return{App:ne}},void 0);if(uA)return;if(xA=await zA.addListener("resume",()=>X("capacitor-resume")),uA){try{await((HA=xA==null?void 0:xA.remove)==null?void 0:HA.call(xA))}catch{}xA=null}}catch{}})(),()=>{var HA;uA=!0;try{document.removeEventListener("visibilitychange",O)}catch{}try{window.removeEventListener("pageshow",lA)}catch{}try{window.removeEventListener("unhandledrejection",wA)}catch{}try{(HA=xA==null?void 0:xA.remove)==null||HA.call(xA)}catch{}xA=null}},[q,x,z,aA]),he.useEffect(()=>{let uA=!0;return(async()=>{try{const X=await Wo();if(!uA)return;p(X.showAnimations!==!1)}catch{}})(),()=>{uA=!1}},[]),he.useCallback(async()=>{const uA=!d;p(uA);try{const X=await Wo();await _E({...X,showAnimations:uA})}catch{}},[d]);const pA=he.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=al(),yA=gA==null?void 0:gA.throttleVideoForAnimation,fA=he.useRef(A);he.useEffect(()=>{yA&&(A>fA.current&&yA(!0).catch(()=>{}),fA.current=A)},[A,yA]),he.useEffect(()=>{if(yA&&o&&t){const uA=setTimeout(()=>{yA(!1).catch(()=>{})},500);return()=>clearTimeout(uA)}},[o,t,yA]);const[RA,YA]=he.useState(0);he.useEffect(()=>{if(!h)return;const uA=X=>{var wA;const O=((wA=X.detail)==null?void 0:wA.streak)??0;let lA=0;O>=7?lA=5:O>=5?lA=4:O>=4?lA=3:O>=3?lA=2:O>=2&&(lA=1),YA(lA)};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";he.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]),lA=new Set((uA.events??[]).map(DA=>String(DA).toUpperCase())),wA=uA.resolutions??{},xA=Number(uA.point??(g==null?void 0:g.crapsPoint)??0)||null,HA=lA.has("POINT_MADE")||[...lA].some(DA=>DA.startsWith("POINTMADE:")),zA=lA.has("SEVEN_OUT")||lA.has("SEVENOUT")||O===7&&!!wA.passLineLosses,ne=lA.has("POINT_SET"),ye=!xA&&(O===7||O===11)&&!!wA.passLineWins,Ee=uA.dice[0]===uA.dice[1]&&[4,6,8,10].includes(O);let NA=`Rolled ${O}`,QA=`${uA.dice[0]} + ${uA.dice[1]}`,PA="neutral";HA?(NA="Point Made",QA=`${O} hits clean`,PA="win"):ye?(NA=O===11?"Yo Eleven":"Natural Seven",QA="Come-out winner",PA="win"):zA?(NA="Seven Out",QA="Dice pass to the next shooter",PA="loss"):ne?(NA=`Point Is ${xA??O}`,QA="Hit it again before seven",PA="point"):Ee&&(NA=`Hard ${O}`,QA=`${uA.dice[0]} the hard way`,PA="win");const VA=window.setTimeout(()=>{m({key:X,total:O,title:NA,detail:QA,tone:PA})},650),KA=window.setTimeout(()=>{m(DA=>(DA==null?void 0:DA.key)===X?null:DA)},2450);return()=>{window.clearTimeout(VA),window.clearTimeout(KA)}},[g==null?void 0:g.lastRoll,h]);const[$,L]=he.useState(null),H=he.useRef(0),[P,tA]=he.useState(0);he.useEffect(()=>{if(h)return;const uA=X=>{var lA;const O=(lA=X.detail)==null?void 0:lA.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]),he.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=he.useMemo(()=>P>=7?5:P>=5?4:P>=4?3:P>=3?2:P>=2?1:0,[P]),CA=oA>0?`dice-halo dice-halo--active dice-halo--level-${oA}`:"dice-halo",cA=he.useCallback(()=>{!B||e||!Q||Q()},[e,Q,B]),_A=he.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:CA,"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(Ghe,{onError:()=>{console.warn("[DiceBoard] Error boundary triggered, attempting recovery"),Ll(),setTimeout(()=>{K.current<U?(q(),aA(0)):x()},300)},children:C.jsxs(dG,{shadows:Nhe,orthographic:!0,dpr:Mhe,gl:AmA,style:{background:"transparent"},onCreated:({gl:uA})=>{var wA;if(Ll(),!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})`),q(),aA(300);return}console.error("[DiceBoard] Max retry attempts reached, falling back to static"),x();return}let X;try{if(X=uA.getContext(),!emA(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()):(q(),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=sn}catch{}try{sn!=null&&(uA.outputEncoding=sn)}catch{}try{uA.toneMapping=ty}catch{}try{uA.toneMappingExposure=1}catch{}try{uA.physicallyCorrectLights=!0}catch{}const O=uA==null?void 0:uA.domElement,lA=xA=>{var HA;try{(HA=xA.preventDefault)==null||HA.call(xA)}catch{}FI.error("DiceBoard WebGL context LOST",{retries:K.current}),console.warn("[DiceBoard] WebGL context lost event detected"),Ll(),z(),aA(300)};try{O==null||O.addEventListener("webglcontextlost",lA,!1)}catch{}try{const xA=()=>{try{O==null||O.removeEventListener("webglcontextlost",lA,!1)}catch{}Im===uA&&(Im=null)},HA=(wA=uA.dispose)==null?void 0:wA.bind(uA);uA.dispose=()=>{try{xA()}catch{}HA&&HA()}}catch{}},children:[C.jsx(che,{makeDefault:!0,position:[0,20*Math.cos(r),20*Math.sin(r)],near:.1,far:100,zoom:16,rotation:[-(Math.PI/2-r),0,0]}),C.jsx(bhe,{}),C.jsx("ambientLight",{intensity:.7}),C.jsx("directionalLight",{position:[6,12,6],intensity:1.1,castShadow:!0}),C.jsx(Lde,{gravity:[0,-9.8,0],children:C.jsx(khe,{rollTrigger:A,results:t,preRollTrigger:i,showDice:d,gameMode:n,gameState:g,noAnimation:!d,chargeLevel:s,feltColor:a,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(ppA,{dice:pA})})]})]})}const Uhe=Object.freeze(Object.defineProperty({__proto__:null,default:imA,disposeDiceBoardRenderer:tmA},Symbol.toStringTag,{value:"Module"})),nmA=50,nv=nmA/1200,vhe=({disabled:e,busy:A=!1,onClick:t,onPressStart:i,onChargeChange:n,label:g="ROLL"})=>{const o=e||A,s=E.useRef(!1),r=E.useRef(0),a=E.useRef(null),I=E.useRef(n);I.current=n,E.useEffect(()=>()=>{a.current&&clearInterval(a.current)},[]);const c=E.useCallback(()=>{var m;r.current=0,(m=I.current)==null||m.call(I,0),a.current&&clearInterval(a.current),a.current=window.setInterval(()=>{var D;r.current=Math.min(1,r.current+nv),(D=I.current)==null||D.call(I,r.current),r.current>=.25&&r.current<.25+nv*1.5?yo("Light"):r.current>=.6&&r.current<.6+nv*1.5?yo("Medium"):r.current>=.95&&r.current<.95+nv*1.5&&yo("Heavy")},nmA)},[]),l=E.useCallback(()=>{var m;a.current&&(clearInterval(a.current),a.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(),qn(),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 yo("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 yo("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})]})})},PgA=he.memo(vhe),Khe=420,jgA=e=>C.jsxs("span",{className:"zentara-balance-pill",children:["Balance: ",e]}),Fhe=({phase:e,pendingEffect:A,isMyTurn:t,inJail:i,onRoll:n,onRollPressStart:g,onRollChargeChange:o,onBuy:s,onSkipBuy:r,onPayRent:a,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=""},Khe);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(PgA,{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(PgA,{onClick:n,onPressStart:g,onChargeChange:o,label:"ROLL"}),C.jsx("button",{className:"zentara-btn zentara-btn--secondary",onClick:B,children:"Wake Up"}),jgA(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:r,disabled:y||m,children:"Pass"}),jgA(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},_he=he.memo(Fhe),Jhe={start:VpA,planet:XpA,station:AfA,asteroid:HZ,nebula:OZ,wormhole:$pA,tax:e4,"void-drain":e4,jail:efA,"go-to-jail":tfA,"free-parking":ifA},Lhe={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"},xhe={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."},ho={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."},The={"Alpha Centauri":ho[1],"Proxima B":ho[3],"Kepler-22b":ho[6],"Kepler-442b":ho[8],"Kepler-62f":ho[9],"Trappist-1d":ho[11],"Trappist-1e":ho[13],"Trappist-1f":ho[14],"Ross 128b":ho[16],"Tau Ceti e":ho[18],"Tau Ceti f":ho[19],"Gliese 667Cc":ho[21],"Gliese 581d":ho[23],"Gliese 581g":ho[24],"Cancri 55e":ho[26],"Cancri 55f":ho[27],"HD 40307g":ho[29],"Kapteyn b":ho[31],"Kapteyn c":ho[32],"Wolf 1061c":ho[34],Pandora:ho[37],Zentara:ho[39]},qhe=({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?cs[e.group]:"#1e3a5f",s=(n==null?void 0:n.imageUrl)??Jhe[e.type],r=xhe[e.type]??"",a=(n==null?void 0:n.lore)??(e.type==="planet"?The[e.name]:ho[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}`:r;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}),a&&C.jsx("div",{className:"zentara-tile-card__fact",children:a}),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":Lhe[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]})]})})]})]})},Yhe=he.memo(qhe),Hhe={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"},Ohe=({tile:e,property:A,ownerName:t,isOwnedByMe:i,canAffordUpgrade:n,onClose:g,onUpgrade:o,onMortgage:s,onSell:r,onSabotage:a,sabotageCost:I,credits:c,groupOwned:l,groupTotal:B,planetContent:Q})=>{if(!e)return null;const h=e.group?cs[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:Hhe[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:()=>r==null?void 0:r(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:()=>a==null?void 0:a(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"})]})})},Phe=he.memo(Ohe),gmA=({playerId:e,credits:A,properties:t,board:i,onUpgrade:n,onClose:g})=>{const o=E.useMemo(()=>{const s=[];for(const r of t){if(r.ownerId!==e||r.dormant)continue;const a=i[r.tileId];if(!(a!=null&&a.upgradeCost))continue;const I=Hm(e,r.tileId,i,t);r.upgradeLevel>=I||a.upgradeCost>A||s.push({property:r,tile:a,maxLevel:I})}return s.sort((r,a)=>(r.tile.group??"").localeCompare(a.tile.group??"")||r.tile.id-a.tile.id),s},[e,A,t,i]);return zr.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:r})=>{const a=r.group?cs[r.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:a}}),C.jsx("span",{className:"zentara-arm-row__name",children:r.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:["⚡",r.upgradeCost]})]},s.tileId)})}),C.jsx("button",{className:"zentara-arm-close",onClick:g,children:"Close"})]})}),document.body)},jhe={"crimson-dominion":Bz,"silver-pact":Ez,"azure-sovereignty":Qz,"golden-imperium":uz,"emerald-collective":dz,"void-enclave":hz};function zhe({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:cs[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 Zhe({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 r=A.getVideoTracks()[0];r&&r.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 zgA={type:"spring",stiffness:420,damping:38,mass:.6},Whe=({players:e,properties:A,tiles:t,currentPlayerId:i,localPlayerId:n,onSaveAndExit:g,onAvatarClick:o,roomId:s,onUpgradeProperty:r,upgradeableCount:a})=>{const I=Ji(),{user:c}=en(),{remoteStreams:l,myVideo:B,remoteVideoFlags:Q}=al(),{onBuyChips:h}=kw(),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{Xt("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($C,{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(WI.ul,{className:"players players--avatars",role:"list",ref:p,layout:!0,transition:zgA,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(WI.li,{layout:!0,transition:zgA,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(Zhe,{stream:_}):null})(),C.jsx("img",{src:jhe[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(zhe,{playerId:G,properties:A,tiles:t}),G===n&&b&&(a??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:Zi(M.piece)})}),(M.armorLevel>0||M.weaponLevel>0||M.heroId)&&C.jsxs("div",{className:"zentara-ship-badges",children:[M.heroId&&ys[M.heroId]&&C.jsxs("span",{className:"zentara-ship-badge zentara-ship-badge--hero",title:`${ys[M.heroId].name} (${SQA[ys[M.heroId].tier]})`,children:["🦸",ys[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&&r&&C.jsx(gmA,{playerId:n,credits:(D==null?void 0:D.credits)??0,properties:A,board:t,onUpgrade:r,onClose:()=>m(!1)})]})},Vhe=he.memo(Whe),S4=40,omA=50,smA=50,Cm=44,cm=39.5,Xhe=41.75,gv=3.8,ZgA=pB.MINIMAP_STEP_MS,WgA={cursor:"pointer",pointerEvents:"auto"},$he={"crimson-dominion":"#ff3a3a","silver-pact":"#b0c4de","azure-sovereignty":"#4488ff","golden-imperium":"#ffaa00","emerald-collective":"#39ff14","void-enclave":"#cc44ff"},Ape={purple:"#7b2ff2",cyan:"#00e5ff",orange:"#ff9100",red:"#ff1744",yellow:"#ffd600",green:"#00e676",blue:"#2979ff",magenta:"#e040fb"};function vk(e,A){const t=A*Math.PI/180;return{x:omA+e*Math.cos(t),y:smA+e*Math.sin(t)}}function epe(e,A){const t=Math.min(.55,A*.08),i=e-A/2+t,n=e+A/2-t,g=vk(Cm,i),o=vk(Cm,n),s=vk(cm,n),r=vk(cm,i),a=n-i>180?1:0;return[`M ${g.x.toFixed(3)} ${g.y.toFixed(3)}`,`A ${Cm} ${Cm} 0 ${a} 1 ${o.x.toFixed(3)} ${o.y.toFixed(3)}`,`L ${s.x.toFixed(3)} ${s.y.toFixed(3)}`,`A ${cm} ${cm} 0 ${a} 0 ${r.x.toFixed(3)} ${r.y.toFixed(3)}`,"Z"].join(" ")}function rmA(e){const A=360/e;return Array.from({length:e},(t,i)=>{const n=-90+i*A;return{...vk(Xhe,n),angleDeg:n,path:epe(n,A)}})}const tpe=rmA(S4),ipe=({players:e,currentPlayerId:A,properties:t=[],tiles:i=[],onTileClick:n})=>{const g=i.length||S4,o=g===S4?tpe:rmA(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]),r=E.useMemo(()=>e.filter(B=>!B.depleted),[e]),[a,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(r.map(Q=>Q.id));for(const Q of Object.keys(l.current))B.has(Q)||(clearTimeout(l.current[Q]),delete l.current[Q])},[r]),E.useEffect(()=>{for(const B of r){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,ZgA))};m>0&&(l.current[B.id]=setTimeout(S,ZgA))}},[r]),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:omA,cy:smA,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?Ape[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?WgA:void 0,onClick:n?()=>n(Q):void 0},Q)}),r.map(B=>{const Q=a[B.id]??B.tileIndex,h=o[Q];if(!h)return null;const d=B.id===A;return C.jsx("rect",{x:h.x-gv/2,y:h.y-gv/2,width:gv,height:gv,rx:.8,fill:$he[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?WgA:void 0,onClick:n?()=>n(B.tileIndex):void 0},B.id)})]})},npe=he.memo(ipe),gpe=({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)??""),[r,a]=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&&(r.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:[Zi(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=r.includes(M.tileId),b=D(M.tileId);return C.jsx("button",{onClick:()=>y(r,a,M.tileId),className:"zentara-trade-chip",style:{background:w?b?cs[b]:"#1e3a5f":"transparent",color:w?"#fff":"#c0d0e8",borderColor:b?cs[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?cs[b]:"#1e3a5f":"transparent",color:w?"#fff":"#c0d0e8",borderColor:b?cs[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,r,I,l,Q),className:"zentara-trade-btn zentara-trade-btn--propose",children:"Send Offer"})]})]})},ope=({trade:e,players:A,tiles:t,onAccept:i,onDecline:n})=>{const g=(()=>{const a=A.find(I=>I.id===e.offerer.playerId);return a?Zi(a.piece):"Unknown Fleet"})(),o=a=>{var I;return((I=t[a])==null?void 0:I.name)??`#${a}`},s=a=>{var I;return(I=t[a])==null?void 0:I.group},r=({propIds:a})=>C.jsx("div",{className:"zentara-trade-card__chip-row zentara-trade-card__chip-row--tight",style:{marginTop:4},children:a.map(I=>{const c=s(I);return C.jsx("span",{className:"zentara-trade-chip zentara-trade-chip--default",style:{background:c?cs[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(r,{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(r,{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"})]})]})},spe=({open:e,mode:A,localPlayer:t,players:i,properties:n,tiles:g,pendingTrade:o,onPropose:s,onAccept:r,onDecline:a,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(gpe,{localPlayer:t,otherPlayers:c,properties:n,tiles:g,onPropose:s,onClose:I}):o?C.jsx(ope,{trade:o,players:i,tiles:g,onAccept:r,onDecline:a}):null})})},rpe=he.memo(spe),ape=({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)??"")}),r=o.maxHp>0?Math.round(o.hp/o.maxHp*100):0,a=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:Zi(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:`${r}%`,background:a,boxShadow:`0 0 6px ${a}`}}),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?cs[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)})]})]}),Ipe=he.memo(ape),Cpe=({open:e,onClose:A,roomId:t,localPlayerId:i,players:n,injectedMessages:g,onLocalSend:o})=>{const s=jR(),[r,a]=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 r;const D=new Map;for(const S of r)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,r,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?Zi(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"};a(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"})]})]})]})},cpe=he.memo(Cpe),lpe=4500,Bpe=({latest:e,players:A,onOpen:t,hidden:i})=>{const[n,g]=E.useState(null);if(E.useEffect(()=>{if(!e||i)return;g(e);const a=setTimeout(()=>g(null),lpe);return()=>clearTimeout(a)},[e,i]),!n||i)return null;const o=A.find(a=>a.id===n.senderId),s=o?Zi(o.piece):"Bot",r=(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 ${r}`,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:r,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); }
                }
            `})]})},Epe=15e3,Qpe=5e3,upe=22e3,dpe=8e3,VgA=7e3,hpe=900,ppe=700,fpe=700,ype=900,xK=globalThis.__zentaraActiveBotChatSessions||new Set;globalThis.__zentaraActiveBotChatSessions=xK;const Ho=(...e)=>{console.log("[autoplay-bot-chat]",...e)},Dpe=[/\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 mpe(e){return Dpe.some(A=>A.test(e))}function Spe({enabled:e,gameMode:A,bots:t,localPlayerId:i,requireHumanEngagement:n=!0,getSituation:g,onMessage:o,getHistory:s,controlsRef:r}){const a=E.useRef(o),I=E.useRef(g),c=E.useRef(s),l=E.useRef(i);a.current=o,I.current=g,c.current=s,l.current=i;const B=E.useRef(r);B.current=r,E.useEffect(()=>{if(!e||t.length===0){Ho("skip mount",{enabled:e,botCount:t.length});return}const Q=[A,n?"quickmatch":"autoplay",...t.map(K=>K.id).sort()].join(":");if(xK.has(Q)){Ho("skip duplicate session",{sessionKey:Q});return}xK.add(Q),Ho("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=gr(),m=()=>{xK.delete(Q)};if(!n){const K=Gpe({apiBase:y,gameMode:A,bots:t,onMessageRef:a,getSituationRef:I,getHistoryRef:c,isCancelled:()=>h,scheduleNext:T=>{h||(d=setTimeout(K,T))}}),J=1500+Math.random()*1e3;return Ho(`[autoplay] first tick in ${Math.round(J)}ms`),d=setTimeout(K,J),()=>{h=!0,d&&clearTimeout(d);for(const T of p)clearTimeout(T);p.clear(),m(),Ho("unmount (autoplay)")}}let D=0,S=!1,k=!1;const N=[...t].sort(()=>Math.random()-.5),G=()=>{var T;if(k)return!0;const K=((T=c.current)==null?void 0:T.call(c))??[],J=l.current;return J&&K.some(v=>v.senderId===J&&mpe(v.text))?(k=!0,Ho("human asked bots to stop — silencing chat"),!0):!1},M=async(K,J,T,v,U)=>{var Z,eA;if(h||G())return;if(S){Ho(`[${K}] suppressed - request already in flight`);return}const x=Date.now();if(U&&x-D<VgA){Ho(`[${K}] suppressed — within ${VgA}ms of previous line`);return}D=x;const q=(Z=c.current)==null?void 0:Z.call(c);Ho(`[${K}] POST /api/bot-chat/one-liner`,{gameMode:A,style:J,speakerId:T,bots:t.length,situation:v,historyLen:(q==null?void 0:q.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:T,bots:t,situation:v,history:q})});if(h)return;const sA=Math.round(performance.now()-z);if(!aA.ok){Ho(`[${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;Ho(`[${K}] ✓ message in ${sA}ms`,{senderId:gA.senderId,text:gA.text,fallback:!!pA.fallback}),a.current({id:gA.id,senderId:gA.senderId,text:gA.text,ts:gA.ts,roomId:"autoplay"})}else Ho(`[${K}] ∅ no message in ${sA}ms`,{reason:pA==null?void 0:pA.reason})}catch(aA){Ho(`[${K}] ✗ network error`,aA)}finally{S=!1}},w=async()=>{if(h||G())return;const K=N.shift();if(!K){Ho("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=upe+Math.random()*dpe;Ho(`next intro in ${Math.round(J/1e3)}s (${N.length} remaining)`),d=setTimeout(w,J)},b=Epe+Math.random()*Qpe;Ho(`first intro in ${Math.round(b/1e3)}s`),d=setTimeout(w,b);const _={notifyGameEvent:K=>{if(h||G())return;const J=hpe+Math.random()*ppe,T=setTimeout(()=>{p.delete(T),M("event","game",void 0,K,!0)},J);p.add(T)},notifyHumanMessage:K=>{if(h||G())return;const J=fpe+Math.random()*ype,T=setTimeout(()=>{p.delete(T),M("human-reply","converse",void 0,void 0,!1)},J);p.add(T)}};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(),Ho("unmount (quickmatch)")}},[e,A,n,JSON.stringify(t.map(Q=>Q.id))])}const wpe=12e3,kpe=8e3,Mpe=15e3,Npe=12e3;function Rpe(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 Gpe(e){const{apiBase:A,gameMode:t,bots:i,onMessageRef:n,getSituationRef:g,getHistoryRef:o,isCancelled:s,scheduleNext:r}=e;let a=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=Rpe(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;a+=1;const m=a;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;Ho(`[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;Ho(`[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 Ho(`[autoplay] tick ${m} ∅`,{reason:K==null?void 0:K.reason})}}catch(_){Ho(`[autoplay] tick ${m} ✗ network error`,_)}finally{if(!s()){const _=l.length>0?wpe+Math.random()*kpe:Mpe+Math.random()*Npe;r(_)}}}}const bpe={"crimson-dominion":Bz,"silver-pact":Ez,"azure-sovereignty":Qz,"golden-imperium":uz,"emerald-collective":dz,"void-enclave":hz},Upe=({player:e,properties:A,tiles:t,isCurrentPlayer:i,onClose:n,onTileClick:g})=>{var s;if(!e)return null;const o=A.filter(r=>r.ownerId===e.id).sort((r,a)=>{var I,c;return(((I=t[r.tileId])==null?void 0:I.group)??"").localeCompare(((c=t[a.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:r=>r.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:bpe[e.piece],alt:e.piece,className:"zentara-pinfo__avatar-img"})}),C.jsxs("div",{children:[C.jsx("h3",{className:"zentara-pinfo__name",children:Zi(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"})]})]})]}),oB[e.piece]&&C.jsxs("div",{className:"zentara-pinfo__lore",children:[C.jsx("div",{className:"zentara-pinfo__lore-name",children:oB[e.piece].name}),C.jsxs("div",{className:"zentara-pinfo__lore-motto",children:['"',oB[e.piece].motto,'"']}),C.jsx("p",{className:"zentara-pinfo__lore-text",children:oB[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(r=>{const a=t[r.tileId],I=a!=null&&a.group?cs[a.group]:"#1e3a5f";return C.jsxs("span",{className:"zentara-pinfo__colony-chip",onClick:()=>g==null?void 0:g(r.tileId),style:{background:I,opacity:r.dormant?.4:1,cursor:g?"pointer":void 0},children:[(a==null?void 0:a.name)??`#${r.tileId}`,r.upgradeLevel>0&&` ★${r.upgradeLevel}`]},r.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"})]})})},vpe=he.memo(Upe);function Kpe(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 Fpe=["/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"],_pe={"/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 w4=!1;const k4=new Map,TK=new Set,XgA=new Set;let qK=0;async function Jpe(e){if(!(k4.has(e)||TK.has(e))){TK.add(e);try{const A=await fetch(e,{cache:"force-cache"});if(!A.ok)return;const t=await A.blob(),i=URL.createObjectURL(t);k4.set(e,i)}catch{}finally{TK.delete(e)}}}function amA(e){return _pe[e]??e}function Lpe(e){const A=amA(e);return k4.get(A)??A}function $gA(e){const A=amA(e);XgA.has(A)||(XgA.add(A),qK+=1,Jpe(A).finally(()=>{qK=Math.max(0,qK-1)}))}function AoA(){return qK===0&&TK.size===0}async function xpe(e=5e3){return!w4||AoA()?!0:new Promise(A=>{const t=Date.now(),i=window.setInterval(()=>{if(AoA()){window.clearInterval(i),A(!0);return}Date.now()-t>=Math.max(250,e)&&(window.clearInterval(i),A(!1))},50)})}function Tpe(e=[]){if(!(ti.isNativePlatform()&&ti.getPlatform()==="ios")){if(!w4){w4=!0;let A=0;for(const t of Fpe)window.setTimeout(()=>{$gA(t)},A*50),A+=1}for(const A of e)queueMicrotask(()=>{$gA(A)})}}const qpe=2,Ype=2500,Hpe=({src:e,onEnd:A,coatOfArms:t,caption:i})=>{const n=E.useMemo(()=>{try{return ti.getPlatform()}catch{return"web"}},[]),g=E.useRef(ti.isNativePlatform()).current,o=g&&n==="ios",s=E.useMemo(()=>Lpe(e),[e]),r=E.useRef(!1),[a,I]=E.useState(!1),c=E.useRef(null),[l,B]=E.useState("loading"),Q=E.useRef(l);Q.current=l,E.useEffect(()=>{r.current=!1,I(!1),B("loading")},[e]);const h=E.useRef(A);h.current=A;const d=E.useCallback(()=>{r.current||(r.current=!0,h.current())},[]);E.useEffect(()=>{if(l==="failed"){const D=setTimeout(()=>I(!0),400),S=setTimeout(d,Ype);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||a||D.duration&&D.currentTime>=D.duration-qpe&&I(!0)},[t,a]),y=Kpe(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&&a&&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&&a&&C.jsx("img",{src:t,alt:"",className:"zentara-cutscene-emblem"}),i&&C.jsx("div",{className:"zentara-cutscene-caption",children:i})]})},RV={"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"}}},GV="/models/zentara/ships",Ope=`${GV}/CosmicShark`,Ppe={"crimson-dominion":"18","silver-pact":"16","azure-sovereignty":"02","golden-imperium":"01","emerald-collective":"06","void-enclave":"17"};function ImA(e,A){const t=RV[e],i=t.tierVariants[A];return`${GV}/${t.pack}/${t.pack}${i}.glb`}function jpe(e){return`${Ope}/CosmicShark${Ppe[e]}.obj`}function CmA(e,A){const t=RV[e],i=`${GV}/${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 cmA={"spy-plant":4300,"hero-clash":4700,wormhole:4200,"raid-victory":4400},hT="#41d8ff";function zpe(e){return e*e*(3-2*e)}function Zpe(e){return Math.max(0,Math.min(1,e))}function M4(e,A=hT){return e!=null&&e.pieceColor&&/^#[0-9a-f]{3,8}$/i.test(e.pieceColor)?e.pieceColor:A}function Wpe(e){var A;return(e.heroId?(A=ys[e.heroId])==null?void 0:A.tier:void 0)??1}function Vpe(){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 ki;return o.setAttribute("position",new Yi(i,3)),o},[]);return E.useEffect(()=>()=>A.dispose(),[A]),rr((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 Xpe({color:e=hT}){return C.jsx("group",{children:C.jsx("pointLight",{color:e,intensity:1.7,distance:2.8})})}function $pe({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 a=s.createRadialGradient(64,64,0,64,64,64);a.addColorStop(0,"rgba(255,255,255,0.9)"),a.addColorStop(.18,"rgba(255,255,255,0.38)"),a.addColorStop(.55,"rgba(255,255,255,0.1)"),a.addColorStop(1,"rgba(255,255,255,0)"),s.fillStyle=a,s.fillRect(0,0,128,128)}const r=new pd(o);return r.colorSpace=sn,r},[]),n=E.useRef(null),g=zC.clamp(t*.38,.44,.9);return E.useEffect(()=>()=>i.dispose(),[i]),rr(({clock:o})=>{var r;const s=.96+Math.sin(o.elapsedTime*9)*.06;(r=n.current)==null||r.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:Vg,depthWrite:!1,depthTest:!1,toneMapped:!1})})]})}function Afe({piece:e,tier:A,color:t}){const i=ImA(e,A),n=ba(i),g=CmA(e),o=Hw([g.diffuse,g.normal,g.metallic,g.roughness,g.emission]),s=E.useMemo(()=>new lt(t),[t]),r=E.useMemo(()=>{const[a,I,c,l,B]=o;a.colorSpace=sn,B.colorSpace=sn;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 Kg({map:a,normalMap:I,metalnessMap:c,roughnessMap:l,emissiveMap:B,emissive:s,emissiveIntensity:.72,metalness:.74,roughness:.44,envMapIntensity:1.25}))});const d=new Vn().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 Vn().setFromObject(Q).getCenter(new SA);Q.position.sub(m),Q.updateMatrixWorld(!0);const D=new Vn().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:r.object,dispose:null}),C.jsx($pe,{color:`#${s.getHexString()}`,tailZ:r.tailZ,hullWidth:r.hullWidth})]})}function FJ({player:e,color:A}){const t=(e==null?void 0:e.piece)??"azure-sovereignty",i=e?Wpe(e):1,n=e?M4(e,A):A;return C.jsx(E.Suspense,{fallback:C.jsx(Xpe,{color:n}),children:C.jsx(Afe,{piece:t,tier:i,color:n})})}function eoA({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:Vg,depthWrite:!1})]})}function efe({player:e,color:A}){return C.jsx("group",{scale:.24,rotation:[.35,Math.PI*.56,.2],children:C.jsx(FJ,{player:e,color:A})})}function toA({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(FJ,{player:e,color:A})},s))})}function yD({color:e,start:A,end:t,opacity:i}){const n=E.useMemo(()=>new jW([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:Vg,toneMapped:!1})]})}function tfe({kind:e,attacker:A,defender:t,groupColor:i=hT}){const n=E.useRef(null),g=M4(A,"#41d8ff"),o=M4(t,"#ff4d6d"),s=i||g,r=E.useRef(null),a=E.useRef(null),I=E.useRef(null),c=E.useRef(null),l=E.useRef(null),B=E.useRef(null),{camera:Q}=Ac(),h=Hw("/zentara/planets/zentara.webp");E.useMemo(()=>(h.colorSpace=sn,h.anisotropy=4,h.needsUpdate=!0,h),[h]),rr(({clock:S})=>{n.current===null&&(n.current=S.elapsedTime);const k=S.elapsedTime-n.current,N=cmA[e]/1e3,G=Zpe(k/N),M=zpe(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),r.current&&(r.current.position.x=e==="hero-clash"?-3.35+M*1.7:-2.8+M*1.25,r.current.position.y=.25+Math.sin(k*2)*.05,r.current.rotation.y=e==="hero-clash"?-.1+Math.sin(k*.9)*.025:-.18+Math.sin(k*.9)*.04),a.current&&(a.current.position.x=e==="hero-clash"?3.35-M*1.7:2.75-M*.8,a.current.position.y=.2+Math.cos(k*1.8)*.05,a.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(Vpe,{}),C.jsxs("group",{ref:r,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(toA,{player:A,color:g,side:"left"}):C.jsx(FJ,{player:A,color:g})]}),(e==="hero-clash"||e==="raid-victory")&&C.jsxs("group",{ref:a,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(toA,{player:t,color:o,side:"right"}):C.jsx(FJ,{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:Vg})]}),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(efe,{player:A,color:g})]}),C.jsx(eoA,{color:s,progress:D}),C.jsx(eoA,{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:Vg})]},k))})]})}function ife(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 nfe({kind:e,attacker:A,defender:t,groupColor:i=hT,caption:n,onEnd:g}){const o=E.useRef(!1);E.useEffect(()=>{o.current=!1;const r=window.setTimeout(()=>{o.current||(o.current=!0,g())},cmA[e]);return()=>window.clearTimeout(r)},[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(dG,{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(tfe,{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??ife(e)})]}),C.jsx("button",{className:"zentara-realtime-cutscene__skip",type:"button",onClick:s,children:"Skip"})]})}const gfe=7600,ofe=4,ioA=[[0,.5,-1.5],[-4.2,2.5,-4.2],[4.1,2.65,-4.8],[.15,4.4,-7]];function sfe(e){var A;return(e.heroId?(A=ys[e.heroId])==null?void 0:A.tier:void 0)??1}function rfe(){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 ki;return o.setAttribute("position",new Yi(i,3)),o},[]);return rr((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 afe({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=sn,l},[]),s=zC.clamp(t*.42,.52,1.05),r=s*.28,a=zC.clamp(t*.16,.13,.34);return E.useEffect(()=>()=>o.dispose(),[o]),rr(({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(r*c,r*c,1),(Q=g.current)==null||Q.scale.set(r*c,r*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:Vg,depthWrite:!1,depthTest:!1,toneMapped:!1})}),C.jsx("sprite",{ref:n,position:[-a,0,.03],scale:[r,r,1],renderOrder:21,children:C.jsx("spriteMaterial",{map:o,color:"#f5fdff",transparent:!0,opacity:.95,blending:Vg,depthWrite:!1,depthTest:!1,toneMapped:!1})}),C.jsx("sprite",{ref:g,position:[a,0,.03],scale:[r,r,1],renderOrder:21,children:C.jsx("spriteMaterial",{map:o,color:"#f5fdff",transparent:!0,opacity:.95,blending:Vg,depthWrite:!1,depthTest:!1,toneMapped:!1})})]})}function Ife({player:e,index:A}){const t=E.useRef(null),i=sfe(e),n=ImA(e.piece,i),g=ba(n),o=CmA(e.piece),s=Hw([o.diffuse,o.normal,o.metallic,o.roughness,o.emission]),r=E.useMemo(()=>new lt(e.pieceColor||"#8fe9ff"),[e.pieceColor]),a=E.useMemo(()=>{const[I,c,l,B,Q]=s;I.colorSpace=sn,Q.colorSpace=sn;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 Kg({map:I,normalMap:c,metalnessMap:l,roughnessMap:B,emissiveMap:Q,emissive:r,emissiveIntensity:.65,metalness:.72,roughness:.46,envMapIntensity:1.35}))});const p=new Vn().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 Vn().setFromObject(h).getCenter(new SA);h.position.sub(m),h.updateMatrixWorld(!0);const D=new Vn().setFromObject(h),S=D.getSize(new SA);return{object:h,tailZ:D.max.z,hullWidth:Math.max(S.x,S.y)}},[r,g.scene,s]);return rr(({clock:I})=>{if(!t.current)return;const c=I.elapsedTime,l=zC.smoothstep(c,A*.22,2.4+A*.2),B=ioA[A]??ioA[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:a.object,dispose:null}),C.jsx(afe,{color:`#${r.getHexString()}`,tailZ:a.tailZ,hullWidth:a.hullWidth})]})}function Cfe(){const{camera:e}=Ac();return rr(({clock:A})=>{const t=A.elapsedTime,i=zC.smoothstep(t,0,6.8);e.position.set(zC.lerp(7.2,.4,i),zC.lerp(5.8,3.2,i),zC.lerp(17,12.2,i)),e.lookAt(0,1.7,-3.4)}),null}function cfe(){const e=Hw("/zentara/planets/zentara.webp");return E.useEffect(()=>{e.colorSpace=sn,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:Vg,side:kr,depthWrite:!1})]})]})}function lfe({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(rfe,{}),C.jsxs(E.Suspense,{fallback:null,children:[C.jsx(cfe,{}),e.slice(0,ofe).map((A,t)=>C.jsx(Ife,{player:A,index:t},A.id))]}),C.jsx(Cfe,{})]})}const Bfe=({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,gfe);return()=>window.clearTimeout(g)},[]),C.jsxs("div",{className:"zentara-fleet-intro",onClick:A?n:void 0,role:"presentation",children:[C.jsx(dG,{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:ty,toneMappingExposure:1.35},children:C.jsx(lfe,{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"})]})},Efe={asteroid:HZ,nebula:OZ},Qfe=({deck:e,text:A,amount:t,rollerName:i,rollerColor:n,onDismiss:g,autoDismissMs:o})=>{const s=e==="asteroid"?"Asteroid Event":"Nebula Intel",r=he.useRef(g);return he.useEffect(()=>{r.current=g},[g]),he.useEffect(()=>{if(!o||o<=0)return;const a=window.setTimeout(()=>{var I;(I=r.current)==null||I.call(r)},o);return()=>window.clearTimeout(a)},[o]),C.jsx("div",{className:"zentara-card-backdrop",onClick:g,children:C.jsxs("div",{className:"zentara-card","data-deck":e,onClick:a=>a.stopPropagation(),children:[C.jsx("div",{className:"zentara-card-art-wrap",children:C.jsx("img",{className:"zentara-card-art",src:Efe[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 ✕"})]})})},lmA="/assets/mission-briefing-BujJMjA8.webp",ufe=({factionName:e,factionColor:A,group:t,groupColor:i,cost:n,onConfirm:g,onCancel:o,autoDismissMs:s})=>{const r=he.useRef(o);he.useEffect(()=>{r.current=o},[o]),he.useEffect(()=>{if(!s||s<=0)return;const c=window.setTimeout(()=>r.current(),s);return()=>window.clearTimeout(c)},[s]);const a=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:lmA,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:[a," 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 ",a," 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 ",a," group."]}),C.jsxs("div",{className:"zentara-spy-deploy-outcome failure",children:[C.jsx("strong",{children:"Mission failure"}),"The spy is exposed. Lose ",OpA.toLocaleString()," energy against a partial holding or ",HpA.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"})]})]})})},BmA=17e3,EmA=700,QmA=2500,N4=3,umA=5,noA=30,goA=8,dfe=.12;function hfe(){return Math.floor((BmA-QmA)/EmA)}function pfe(e=Math.random){const A=hfe();let t=0;for(let i=0;i<A;i+=1)t+=N4+Math.floor(e()*(umA-N4+1));return Math.max(1,t)}function _J(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*dfe),r=Math.max(0,s+i.weaponLevel-t.weaponLevel),a=g>=r,I=g+t.weaponLevel,c=o+i.weaponLevel,l=a?Math.min(noA+g*goA,i.credits):Math.min(noA+Math.floor(g*goA*.5),t.credits);return{attackerRoll:g,defenderRoll:o,attackerTotal:I,defenderTotal:c,winnerId:a?t.id:i.id,creditsStolen:Math.max(0,l),finalHits:g,totalSpawned:n}}const ffe="/assets/fps_soundtrack-DPaQcdtT.m4a",Wm="/assets/zentara_bg_planet-D7XktRqs.webp",yfe="/assets/bogies_intro-CcVJ01Lv.webp",Dfe="/assets/raid_torpedo-uTmsDgFP.webp",mfe="/assets/enemy_crimson_bank2-BT7rb74W.webp",Sfe="/assets/enemy_crimson_bank4-BCMi3o3A.webp",wfe="/assets/enemy_crimson_bank6-CXlmAW_2.webp",kfe="/assets/enemy_silver_bank2-DvdISIck.webp",Mfe="/assets/enemy_silver_bank4-C8sYDjrv.webp",Nfe="/assets/enemy_silver_bank6-LEedzbJQ.webp",Rfe="/assets/enemy_azure_bank2-CB0VkvKZ.webp",Gfe="/assets/enemy_azure_bank4-Bz4T-snu.webp",bfe="/assets/enemy_azure_bank6-Covwy4o4.webp",Ufe="/assets/enemy_golden_bank2-D0C8kMEZ.webp",vfe="/assets/enemy_golden_bank4-Dc5WWR8O.webp",Kfe="/assets/enemy_golden_bank6-LOlFOFuT.webp",Ffe="/assets/enemy_emerald_bank2-5IgU95Qn.webp",_fe="/assets/enemy_emerald_bank4-BG8NH3Zr.webp",Jfe="/assets/enemy_emerald_bank6-C0p50Ap6.webp",Lfe="/assets/enemy_void_bank2-BOmN2a0s.webp",xfe="/assets/enemy_void_bank4-dsAjcFRS.webp",Tfe="/assets/enemy_void_bank6-D3jYjyIh.webp",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, ",$fe="data:image/webp;base64, ",Aye="data:image/webp;base64, ",eye="data:image/webp;base64, ",tye="data:image/webp;base64, ",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, ",rye="data:image/webp;base64, ",aye="data:image/webp;base64, ",Iye="data:image/webp;base64, ",Cye="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",cye="data:image/webp;base64, ",lye="data:image/webp;base64, ",Bye="/assets/enemy_azure_headon_bank5-i9H_e-T1.webp",Eye="/assets/enemy_golden_headon_bank3-BAwmOiOE.webp",Qye="data:image/webp;base64, ",uye="data:image/webp;base64, ",dye="data:image/webp;base64, ",hye="data:image/webp;base64, ",pye="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=",fye="data:image/webp;base64, ",yye="data:image/webp;base64, ",Dye="/assets/enemy_void_headon_bank5-uqlOncyY.webp",mye="/assets/cockpit_red-D9Z7CCYz.webp",Sye="/assets/cockpit_silver-CYcc-KqK.webp",wye="/assets/cockpit_blue-JbBctwkd.webp",kye="/assets/cockpit_gold-OYjriaOU.webp",Mye="/assets/cockpit_green-Bh4QHBHC.webp",Nye="/assets/cockpit_black-DplLg93u.webp",Rye="/assets/cockpit_legacy_crimson_turret_1-DrDnrMz8.png",Gye="/assets/cockpit_legacy_crimson_turret_2-VkMAD65W.png",bye="/assets/cockpit_legacy_crimson_turret_3-BW1HBR1o.png",Uye="/assets/cockpit_legacy_crimson_turret_4-BRDgMiwJ.png",vye="/assets/cockpit_legacy_crimson_turret_5-BAf9UZqT.png",Kye="/assets/cockpit_legacy_crimson_turret_6-Bdt8rLXS.png",Fye="/assets/cockpit_legacy_silver_turret_1-DSOfodaj.png",_ye="/assets/cockpit_legacy_silver_turret_2-tAnK_626.png",Jye="/assets/cockpit_legacy_silver_turret_3-BMtF9R9P.png",Lye="/assets/cockpit_legacy_silver_turret_4-pPzY36b0.png",xye="/assets/cockpit_legacy_silver_turret_5-C8OJNHF7.png",Tye="/assets/cockpit_legacy_silver_turret_6-CyE7D_WC.png",qye="/assets/cockpit_legacy_gold_turret_1-AxxZC0ic.png",Yye="/assets/cockpit_legacy_gold_turret_2-BZsPbqyX.png",Hye="/assets/cockpit_legacy_gold_turret_3-CbpKpXzT.png",Oye="/assets/cockpit_legacy_gold_turret_4-B2JEPHJw.png",Pye="/assets/cockpit_legacy_gold_turret_5-B8Secc75.png",jye="/assets/cockpit_legacy_gold_turret_6-Cv44-Nbd.png",zye="/assets/cockpit_legacy_azzure_turret_1-KU89WC9_.png",Zye="/assets/cockpit_legacy_azzure_turret_2-CC7hQ0xE.png",Wye="/assets/cockpit_legacy_azzure_turret_3-Bjzduy1w.png",Vye="/assets/cockpit_legacy_azzure_turret_4-BcUI99jC.png",Xye="/assets/cockpit_legacy_azzure_turret_5-Cv2ra0mr.png",$ye="/assets/cockpit_legacy_azzure_turret_6-CiNSaI5P.png",ADe="/assets/cockpit_legacy_void_turret_1-DhGgm8Nz.png",eDe="/assets/cockpit_legacy_void_turret_2-DCCuuayW.png",tDe="/assets/cockpit_legacy_void_turret_3-CX2YTDou.png",iDe="/assets/cockpit_legacy_void_turret_4-D_mbGRwe.png",nDe="/assets/cockpit_legacy_void_turret_5-Bktw9bbQ.png",gDe="/assets/cockpit_legacy_void_turret_6-B_CLoEvm.png",oDe="/assets/cockpit_legacy_emerald_turret_1-BqJwnLMP.png",sDe="/assets/cockpit_legacy_emerald_turret_2-CpcpGDUL.png",rDe="/assets/cockpit_legacy_emerald_turret_3-DgrTzw2E.png",aDe="/assets/cockpit_legacy_emerald_turret_4-ChFGDzar.png",IDe="/assets/cockpit_legacy_emerald_turret_5-CQQYvOlj.png",CDe="/assets/cockpit_legacy_emerald_turret_6-BA7NzSGw.png",cDe="/assets/battleship_crimson-BP8YBbHm.webp",lDe="/assets/battleship_silver-Bny1kROS.webp",BDe="/assets/battleship_azure-Bq1rJGy2.webp",EDe="/assets/battleship_golden-Aq15Jmcg.webp",QDe="/assets/battleship_emerald-CE5hNTxV.webp",uDe="/assets/battleship_void-y7zwWNtK.webp",dmA=ffe,dDe=yfe,yd=e=>{if(typeof Image>"u")return null;const A=new Image;return A.src=e,A},hDe={"crimson-dominion":[mfe,Sfe,wfe],"silver-pact":[kfe,Mfe,Nfe],"azure-sovereignty":[Rfe,Gfe,bfe],"golden-imperium":[Ufe,vfe,Kfe],"emerald-collective":[Ffe,_fe,Jfe],"void-enclave":[Lfe,xfe,Tfe]},pDe={"crimson-dominion":[qfe,Yfe,Hfe],"silver-pact":[Ofe,Pfe,jfe],"azure-sovereignty":[zfe,Zfe,Wfe],"golden-imperium":[Vfe,Xfe,$fe],"emerald-collective":[Aye,eye,tye],"void-enclave":[iye,nye,gye]},fDe={"crimson-dominion":[oye,sye,rye],"silver-pact":[aye,Iye,Cye],"azure-sovereignty":[cye,lye,Bye],"golden-imperium":[Eye,Qye,uye],"emerald-collective":[dye,hye,pye],"void-enclave":[fye,yye,Dye]},yDe={"crimson-dominion":mye,"silver-pact":Sye,"azure-sovereignty":wye,"golden-imperium":kye,"emerald-collective":Mye,"void-enclave":Nye},hmA={"crimson-dominion":"#ff1744","silver-pact":"#b0bec5","azure-sovereignty":"#448aff","golden-imperium":"#ffc400","emerald-collective":"#69f0ae","void-enclave":"#d500f9"},Kl=yd(PZ),$0=yd(Dfe),DDe=yd(Wm),pmA={};for(const[e,A]of Object.entries(yDe)){const t=yd(A);t&&(pmA[e]=t)}const mDe={"crimson-dominion":[Rye,Gye,bye,Uye,vye,Kye],"silver-pact":[Fye,_ye,Jye,Lye,xye,Tye],"azure-sovereignty":[zye,Zye,Wye,Vye,Xye,$ye],"golden-imperium":[qye,Yye,Hye,Oye,Pye,jye],"emerald-collective":[oDe,sDe,rDe,aDe,IDe,CDe],"void-enclave":[ADe,eDe,tDe,iDe,nDe,gDe]},bV={};for(const[e,A]of Object.entries(mDe))bV[e]=A.map(t=>yd(t));const SDe=bV["crimson-dominion"],wDe={"crimson-dominion":cDe,"silver-pact":lDe,"azure-sovereignty":BDe,"golden-imperium":EDe,"emerald-collective":QDe,"void-enclave":uDe},fmA={};for(const[e,A]of Object.entries(wDe))fmA[e]=yd(A);const kDe=()=>{try{return ti.getPlatform()}catch{return"web"}},JJ=kDe(),ymA=JJ==="android",UV=JJ==="ios",gC=JJ==="ios"||JJ==="android",MDe=UV?1:gC?1.25:2,ooA=UV?22:gC?16:0,NDe=()=>{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},RDe=()=>{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}},GDe=NDe(),bDe=RDe(),soA=!gC||bDe||!GDe;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 IO=null,ov=null,CO=null;function UDe(){if(IO)return IO;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(),IO=e,e}function vDe(){if(ov)return ov;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 ov={hit:e("rgba(0,255,170,0)","#00ffaa"),miss:e("rgba(255,68,68,0)","#ff4444")},ov}function KDe(){if(CO)return CO;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(),CO=e,e}const roA={};function FDe(e,A){const t=roA[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,`${hmA[e]}44`),s.addColorStop(1,"transparent"),g.fillStyle=s,g.fillRect(0,0,i,i),roA[e]={canvas:n,cachedR:A},n}const DmA=1,aoA=.012,_De=5.6,cO=e=>{const A=1-Math.max(e.z,0)/DmA,t=A*A;return(aoA+(_De-aoA)*t+(e.z<0?Math.abs(e.z)*3:0))*e.sizeScale},JDe=(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)),r=Math.sign(e.visualVx),a=Math.sign(g),I=r!==0&&r===a?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},LDe=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 mmA{constructor(A){Ti(this,"audio",null);Ti(this,"fadeTimer",null);Ti(this,"volume");Ti(this,"fadeMs");Ti(this,"fadeSteps");Ti(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 xDe(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",r=s==="bankout"?.05:s==="attack"?.7:s==="strafe"?1.2:.95,a=A()<.5?-1:1,I=A()<.7?-1:1,c=A(),l=c<.18?"vertical":c<.5?"horizontal":"lateral";let B=(.45+A()*.55)*r,Q=(.45+A()*.6)*r*.85;l==="vertical"?(B*=.1+A()*.15,Q=(.85+A()*.5)*r):l==="horizontal"&&(Q*=.1+A()*.15,B=(.85+A()*.5)*r);let h=n+a*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:a,T=D>.001?m/D:-.4*I;h=n+J*p,d=g+T*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=-a;S=n+J*t*(.55+A()*.25),k=g+(A()-.5)*i*.55}else{const J=t*e.battleshipAnchorX,T=i*e.battleshipAnchorY,v=Math.min(t,i)*.2,U=A()*Math.PI*2,x=A()*v;S=J+Math.cos(U)*x,k=T+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 IoA=(e,A)=>{const t=Math.hypot(e,A);return t<.001?null:{x:e/t,y:A/t}},TDe=(e,A,t)=>{const i=Math.hypot(e.vx,e.vy);return i>=24?{x:e.vx/i,y:e.vy/i}:IoA(e.targetX-e.x,e.targetY-e.y)??IoA(e.targetX-A,e.targetY-t)??{x:0,y:-1}},qDe=(e,A,t,i,n,g)=>{const o=t-e,s=i-A,r=Math.hypot(o,s),a=Math.max(0,n*g);if(r<=a||r<.001)return{vx:t,vy:i};const I=a/r;return{vx:e+o*I,vy:A+s*I}},YDe=(e,A,t,i,n)=>{const g=e*t.x+A*t.y,o=e-t.x*g,s=A-t.y*g,r=Math.exp(-5*i*n),a=g+380*i*n;return{vx:t.x*a+o*r,vy:t.y*a+s*r}},LJ=1e3,SmA=1800,wmA=.8,HDe=ymA?0:gC?24:50,ODe=gC?4:7,CoA=["#4a148c","#0d47a1","#004d40","#b71c1c","#1a237e","#311b92","#01579b","#1b5e20"],PDe=gC?36:100,xJ=50,kmA=160,MmA=.75,jDe=gC?130:80,zDe=gC?900:500,vh=(e,A)=>e+Math.random()*(A-e);function ZDe(){const e=Math.random()*Math.PI*2;return{angle:e,cosAngle:Math.cos(e),sinAngle:Math.sin(e),dist:Math.random()*.15,speed:LJ+Math.random()*(SmA-LJ),brightness:.3+Math.random()*.7,length:.5+Math.random()*1.5}}function WDe(){return Array.from({length:HDe},()=>{const e=ZDe();return e.dist=Math.random()*wmA,e})}function VDe(){return Array.from({length:ODe},()=>({x:Math.random(),y:Math.random(),radius:.1+Math.random()*.18,color:CoA[Math.floor(Math.random()*CoA.length)],alpha:.04+Math.random()*.06,driftX:(Math.random()-.5)*.006,driftY:(Math.random()-.5)*.006}))}function XDe(){return Array.from({length:PDe},()=>({angle:Math.random()*Math.PI*2,dist:Math.random()*MmA,speed:xJ+Math.random()*(kmA-xJ),size:.4+Math.random()*1.2,alpha:.12+Math.random()*.3}))}const coA=gC?4:6,loA=400;function $De(e,A){const t=[];for(let i=0;i<coA;i+=1){const n=Math.PI*2*i/coA+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:loA,maxLife:loA})}return t}const Ame=/^[og]\s*(.+)?/,eme=/^mtllib /,tme=/^usemtl /,ime=/^usemap /,BoA=/\s+/,EoA=new SA,lO=new SA,QoA=new SA,uoA=new SA,yC=new SA,sv=new lt;function nme(){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(r){const a={index:typeof r=="number"?r:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return a.clone=this.clone.bind(a),a}};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;EoA.fromArray(n,A),lO.fromArray(n,t),QoA.fromArray(n,i),yC.subVectors(QoA,lO),uoA.subVectors(EoA,lO),yC.cross(uoA),yC.normalize(),g.push(yC.x,yC.y,yC.z),g.push(yC.x,yC.y,yC.z),g.push(yC.x,yC.y,yC.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,r,a){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(r,Q),B=this.parseNormalIndex(a,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 gme extends sr{constructor(A){super(A),this.materials=null}load(A,t,i,n){const g=this,o=new Aa(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(r){n?n(r):console.error(r),g.manager.itemError(A)}},i,n)}setMaterials(A){return this.materials=A,this}parse(A){const t=new nme;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,r=i.length;s<r;s++){const a=i[s].trimStart();if(a.length===0)continue;const I=a.charAt(0);if(I!=="#")if(I==="v"){const c=a.split(BoA);switch(c[0]){case"v":t.vertices.push(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3])),c.length>=7?(sv.setRGB(parseFloat(c[4]),parseFloat(c[5]),parseFloat(c[6]),sn),t.colors.push(sv.r,sv.g,sv.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=a.slice(1).trim().split(BoA),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=a.substring(1).trim().split(" ");let l=[];const B=[];if(a.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=a.slice(1).trim().split(" ");t.addPointGeometry(l)}else if((n=Ame.exec(a))!==null){const c=(" "+n[0].slice(1).trim()).slice(1);t.startObject(c)}else if(tme.test(a))t.object.startMaterial(a.substring(7).trim(),t.materialLibraries);else if(eme.test(a))t.materialLibraries.push(a.substring(7).trim());else if(ime.test(a))console.warn('THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');else if(I==="s"){if(n=a.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(a==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+a+'"')}}t.finalize();const g=new er;if(g.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let s=0,r=t.objects.length;s<r;s++){const a=t.objects[s],I=a.geometry,c=a.materials,l=I.type==="Line",B=I.type==="Points";let Q=!1;if(I.vertices.length===0)continue;const h=new ki;h.setAttribute("position",new Vt(I.vertices,3)),I.normals.length>0&&h.setAttribute("normal",new Vt(I.normals,3)),I.colors.length>0&&(Q=!0,h.setAttribute("color",new Vt(I.colors,3))),I.hasUVIndices===!0&&h.setAttribute("uv",new Vt(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 $o)){const N=new $o;co.prototype.copy.call(N,k),N.color.copy(k.color),k=N}else if(B&&k&&!(k instanceof ME)){const N=new ME({size:10,sizeAttenuation:!1});co.prototype.copy.call(N,k),N.color.copy(k.color),N.map=k.map,k=N}}k===void 0&&(l?k=new $o:B?k=new ME({size:1,sizeAttenuation:!1}):k=new $W,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 BI(h,d):B?p=new Pp(h,d):p=new hn(h,d)}else l?p=new BI(h,d[0]):B?p=new Pp(h,d[0]):p=new hn(h,d[0]);p.name=a.name,g.add(p)}else if(t.vertices.length>0){const s=new ME({size:1,sizeAttenuation:!1}),r=new ki;r.setAttribute("position",new Vt(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(r.setAttribute("color",new Vt(t.colors,3)),s.vertexColors=!0);const a=new Pp(r,s);g.add(a)}return g}}function doA(e,A){if(A===JW)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(A===Df||A===rG){let t=e.getIndex();if(t===null){const o=[],s=e.getAttribute("position");if(s!==void 0){for(let r=0;r<s.count;r++)o.push(r);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 ome extends sr{constructor(A){super(A),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Cme(t)}),this.register(function(t){return new cme(t)}),this.register(function(t){return new fme(t)}),this.register(function(t){return new yme(t)}),this.register(function(t){return new Dme(t)}),this.register(function(t){return new Bme(t)}),this.register(function(t){return new Eme(t)}),this.register(function(t){return new Qme(t)}),this.register(function(t){return new ume(t)}),this.register(function(t){return new Ime(t)}),this.register(function(t){return new dme(t)}),this.register(function(t){return new lme(t)}),this.register(function(t){return new pme(t)}),this.register(function(t){return new hme(t)}),this.register(function(t){return new rme(t)}),this.register(function(t){return new mme(t)}),this.register(function(t){return new Sme(t)})}load(A,t,i,n){const g=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const a=XI.extractUrlBase(A);o=XI.resolveURL(a,this.path)}else o=XI.extractUrlBase(A);this.manager.itemStart(A);const s=function(a){n?n(a):console.error(a),g.manager.itemError(A),g.manager.itemEnd(A)},r=new Aa(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(A,function(a){try{g.parse(a,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={},r=new TextDecoder;if(typeof A=="string")g=JSON.parse(A);else if(A instanceof ArrayBuffer)if(r.decode(new Uint8Array(A,0,4))===NmA){try{o[Un.KHR_BINARY_GLTF]=new wme(A)}catch(c){n&&n(c);return}g=JSON.parse(o[Un.KHR_BINARY_GLTF].content)}else g=JSON.parse(r.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 a=new Lme(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 I=0;I<this.pluginCallbacks.length;I++){const c=this.pluginCallbacks[I](a);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 Un.KHR_MATERIALS_UNLIT:o[c]=new ame;break;case Un.KHR_DRACO_MESH_COMPRESSION:o[c]=new kme(g,this.dracoLoader);break;case Un.KHR_TEXTURE_TRANSFORM:o[c]=new Mme;break;case Un.KHR_MESH_QUANTIZATION:o[c]=new Nme;break;default:l.indexOf(c)>=0&&s[c]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+c+'".')}}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 sme(){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 Un={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 rme{constructor(A){this.parser=A,this.name=Un.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,r=((g.extensions&&g.extensions[this.name]||{}).lights||[])[A];let a;const I=new lt(16777215);r.color!==void 0&&I.setRGB(r.color[0],r.color[1],r.color[2],Mr);const c=r.range!==void 0?r.range:0;switch(r.type){case"directional":a=new zp(I),a.target.position.set(0,0,-1),a.add(a.target);break;case"point":a=new QG(I),a.distance=c;break;case"spot":a=new cT(I),a.distance=c,r.spot=r.spot||{},r.spot.innerConeAngle=r.spot.innerConeAngle!==void 0?r.spot.innerConeAngle:0,r.spot.outerConeAngle=r.spot.outerConeAngle!==void 0?r.spot.outerConeAngle:Math.PI/4,a.angle=r.spot.outerConeAngle,a.penumbra=1-r.spot.innerConeAngle/r.spot.outerConeAngle,a.target.position.set(0,0,-1),a.add(a.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+r.type)}return a.position.set(0,0,0),ql(a,r),r.intensity!==void 0&&(a.intensity=r.intensity),a.name=t.createUniqueName(r.name||"light_"+A),n=Promise.resolve(a),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(r){return i._getNodeRef(t.cache,s,r)})}}class ame{constructor(){this.name=Un.KHR_MATERIALS_UNLIT}getMaterialType(){return yg}extendParams(A,t,i){const n=[];A.color=new lt(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],Mr),A.opacity=o[3]}g.baseColorTexture!==void 0&&n.push(i.assignTexture(A,"map",g.baseColorTexture,sn))}return Promise.all(n)}}class Ime{constructor(A){this.parser=A,this.name=Un.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 Cme{constructor(A){this.parser=A,this.name=Un.KHR_MATERIALS_CLEARCOAT}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 It(s,s)}return Promise.all(g)}}class cme{constructor(A){this.parser=A,this.name=Un.KHR_MATERIALS_DISPERSION}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 lme{constructor(A){this.parser=A,this.name=Un.KHR_MATERIALS_IRIDESCENCE}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 Bme{constructor(A){this.parser=A,this.name=Un.KHR_MATERIALS_SHEEN}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 lt(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],Mr)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&g.push(i.assignTexture(t,"sheenColorMap",o.sheenColorTexture,sn)),o.sheenRoughnessTexture!==void 0&&g.push(i.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(g)}}class Eme{constructor(A){this.parser=A,this.name=Un.KHR_MATERIALS_TRANSMISSION}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 Qme{constructor(A){this.parser=A,this.name=Un.KHR_MATERIALS_VOLUME}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 lt().setRGB(s[0],s[1],s[2],Mr),Promise.all(g)}}class ume{constructor(A){this.parser=A,this.name=Un.KHR_MATERIALS_IOR}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 dme{constructor(A){this.parser=A,this.name=Un.KHR_MATERIALS_SPECULAR}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 lt().setRGB(s[0],s[1],s[2],Mr),o.specularColorTexture!==void 0&&g.push(i.assignTexture(t,"specularColorMap",o.specularColorTexture,sn)),Promise.all(g)}}class hme{constructor(A){this.parser=A,this.name=Un.EXT_MATERIALS_BUMP}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 pme{constructor(A){this.parser=A,this.name=Un.KHR_MATERIALS_ANISOTROPY}getMaterialType(A){const i=this.parser.json.materials[A];return!i.extensions||!i.extensions[this.name]?null:Lo}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 fme{constructor(A){this.parser=A,this.name=Un.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 yme{constructor(A){this.parser=A,this.name=Un.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 r=i.textureLoader;if(s.uri){const a=i.options.manager.getHandler(s.uri);a!==null&&(r=a)}return i.loadTextureImage(A,o.source,r)}}class Dme{constructor(A){this.parser=A,this.name=Un.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 r=i.textureLoader;if(s.uri){const a=i.options.manager.getHandler(s.uri);a!==null&&(r=a)}return i.loadTextureImage(A,o.source,r)}}class mme{constructor(A){this.name=Un.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 r=n.byteOffset||0,a=n.byteLength||0,I=n.count,c=n.byteStride,l=new Uint8Array(s,r,a);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 Sme{constructor(A){this.name=Un.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 a of n.primitives)if(a.mode!==RC.TRIANGLES&&a.mode!==RC.TRIANGLE_STRIP&&a.mode!==RC.TRIANGLE_FAN&&a.mode!==void 0)return null;const o=i.extensions[this.name].attributes,s=[],r={};for(const a in o)s.push(this.parser.getDependency("accessor",o[a]).then(I=>(r[a]=I,r[a])));return s.length<1?null:(s.push(this.parser.createNodeMesh(A)),Promise.all(s).then(a=>{const I=a.pop(),c=I.isGroup?I.children:[I],l=a[0].count,B=[];for(const Q of c){const h=new ii,d=new SA,p=new Ao,y=new SA(1,1,1),m=new lG(Q.geometry,Q.material,l);for(let D=0;D<l;D++)r.TRANSLATION&&d.fromBufferAttribute(r.TRANSLATION,D),r.ROTATION&&p.fromBufferAttribute(r.ROTATION,D),r.SCALE&&y.fromBufferAttribute(r.SCALE,D),m.setMatrixAt(D,h.compose(d,p,y));for(const D in r)if(D==="_COLOR_0"){const S=r[D];m.instanceColor=new hd(S.array,S.itemSize,S.normalized)}else D!=="TRANSLATION"&&D!=="ROTATION"&&D!=="SCALE"&&Q.geometry.setAttribute(D,r[D]);cn.prototype.copy.call(m,Q),this.parser.assignFinalMaterial(m),B.push(m)}return I.isGroup?(I.clear(),I.add(...B),I):B[0]}))}}const NmA="glTF",Ak=12,hoA={JSON:1313821514,BIN:5130562};class wme{constructor(A){this.name=Un.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(A,0,Ak),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!==NmA)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-Ak,g=new DataView(A,Ak);let o=0;for(;o<n;){const s=g.getUint32(o,!0);o+=4;const r=g.getUint32(o,!0);if(o+=4,r===hoA.JSON){const a=new Uint8Array(A,Ak+o,s);this.content=i.decode(a)}else if(r===hoA.BIN){const a=Ak+o;this.body=A.slice(a,a+s)}o+=s}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class kme{constructor(A,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Un.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={},r={},a={};for(const I in o){const c=R4[I]||I.toLowerCase();s[c]=o[I]}for(const I in A.attributes){const c=R4[I]||I.toLowerCase();if(o[I]!==void 0){const l=i.accessors[A.attributes[I]],B=Vm[l.componentType];a[c]=B.name,r[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=r[Q];d!==void 0&&(h.normalized=d)}c(B)},s,a,Mr,l)})})}}class Mme{constructor(){this.name=Un.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 Nme{constructor(){this.name=Un.KHR_MESH_QUANTIZATION}}class RmA extends gy{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,r=s*2,a=s*3,I=n-t,c=(i-t)/I,l=c*c,B=l*c,Q=A*a,h=Q-a,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+r]*I,N=o[Q+D+s],G=o[Q+D]*I;g[D]=y*S+m*k+d*N+p*G}return g}}const Rme=new Ao;class Gme extends RmA{interpolate_(A,t,i,n){const g=super.interpolate_(A,t,i,n);return Rme.fromArray(g).normalize().toArray(g),g}}const RC={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},poA={9728:Ds,9729:_g,9984:oG,9985:Hp,9986:Nu,9987:Ra},foA={33071:nI,33648:ff,10497:va},BO={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},R4={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"},YQ={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},bme={CUBICSPLINE:void 0,LINEAR:dd,STEP:yf},EO={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Ume(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new Kg({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Al})),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 ql(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 vme(e,A,t){let i=!1,n=!1,g=!1;for(let a=0,I=A.length;a<I;a++){const c=A[a];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=[],r=[];for(let a=0,I=A.length;a<I;a++){const c=A[a];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;r.push(l)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(r)]).then(function(a){const I=a[0],c=a[1],l=a[2];return i&&(e.morphAttributes.position=I),n&&(e.morphAttributes.normal=c),g&&(e.morphAttributes.color=l),e.morphTargetsRelative=!0,e})}function Kme(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 Fme(e){let A;const t=e.extensions&&e.extensions[Un.KHR_DRACO_MESH_COMPRESSION];if(t?A="draco:"+t.bufferView+":"+t.indices+":"+QO(t.attributes):A=e.indices+":"+QO(e.attributes)+":"+e.mode,e.targets!==void 0)for(let i=0,n=e.targets.length;i<n;i++)A+=":"+QO(e.targets[i]);return A}function QO(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 G4(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 _me(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 Jme=new ii;class Lme{constructor(A={},t={}){this.json=A,this.extensions={},this.plugins={},this.options=t,this.cache=new sme,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 r=s.match(/Version\/(\d+)/);n=i&&r?parseInt(r[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 Td(this.options.manager):this.textureLoader=new IV(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Aa(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),ql(s,n),Promise.all(i._invokeAll(function(r){return r.afterRoot&&r.afterRoot(s)})).then(function(){for(const r of s.scenes)r.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,r=o.length;s<r;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 r=this.associations.get(o);r!=null&&this.associations.set(s,r);for(const[a,I]of o.children.entries())g(I,s.children[a])};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[Un.KHR_BINARY_GLTF].body);const n=this.options;return new Promise(function(g,o){i.load(XI.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=BO[n.type],s=Vm[n.componentType],r=n.normalized===!0,a=new s(n.count*o);return Promise.resolve(new Yi(a,o,r))}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],r=BO[n.type],a=Vm[n.componentType],I=a.BYTES_PER_ELEMENT,c=I*r,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 a(s,p*B,n.count*B/I),m=new Lw(h,B/I),t.cache.add(y,m)),d=new IQ(m,r,l%B/I,Q)}else s===null?h=new a(n.count*r):h=new a(s,l,n.count*r),d=new Yi(h,r,Q);if(n.sparse!==void 0){const p=BO.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 a(o[2],D,n.sparse.count*r);s!==null&&(d=new Yi(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*r]),r>=2&&d.setY(M,k[N*r+1]),r>=3&&d.setZ(M,k[N*r+2]),r>=4&&d.setW(M,k[N*r+3]),r>=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 r=i.manager.getHandler(o.uri);r!==null&&(s=r)}return this.loadTextureImage(A,g,s)}loadTextureImage(A,t,i){const n=this,g=this.json,o=g.textures[A],s=g.images[t],r=(s.uri||s.bufferView)+":"+o.sampler;if(this.textureCache[r])return this.textureCache[r];const a=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=poA[l.magFilter]||_g,I.minFilter=poA[l.minFilter]||Ra,I.wrapS=foA[l.wrapS]||va,I.wrapT=foA[l.wrapT]||va,I.generateMipmaps=!I.isCompressedTexture&&I.minFilter!==Ds&&I.minFilter!==_g,n.associations.set(I,{textures:A}),I}).catch(function(){return null});return this.textureCache[r]=a,a}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 r=o.uri||"",a=!1;if(o.bufferView!==void 0)r=i.getDependency("bufferView",o.bufferView).then(function(c){a=!0;const l=new Blob([c],{type:o.mimeType});return r=s.createObjectURL(l),r});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+A+" is missing URI and bufferView");const I=Promise.resolve(r).then(function(c){return new Promise(function(l,B){let Q=l;t.isImageBitmapLoader===!0&&(Q=function(h){const d=new Rg(h);d.needsUpdate=!0,l(d)}),t.load(XI.resolveURL(c,g.path),Q,void 0,B)})}).then(function(c){return a===!0&&s.revokeObjectURL(r),ql(c,o),c.userData.mimeType=o.mimeType||_me(o.uri),c}).catch(function(c){throw console.error("THREE.GLTFLoader: Couldn't load texture",r),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[Un.KHR_TEXTURE_TRANSFORM]){const s=i.extensions!==void 0?i.extensions[Un.KHR_TEXTURE_TRANSFORM]:void 0;if(s){const r=g.associations.get(o);o=g.extensions[Un.KHR_TEXTURE_TRANSFORM].extendTexture(o,s),g.associations.set(o,r)}}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 r=this.cache.get(s);r||(r=new ME,co.prototype.copy.call(r,i),r.color.copy(i.color),r.map=i.map,r.sizeAttenuation=!1,this.cache.add(s,r)),i=r}else if(A.isLine){const s="LineBasicMaterial:"+i.uuid;let r=this.cache.get(s);r||(r=new $o,co.prototype.copy.call(r,i),r.color.copy(i.color),r.map=i.map,this.cache.add(s,r)),i=r}if(n||g||o){let s="ClonedMaterial:"+i.uuid+":";n&&(s+="derivative-tangents:"),g&&(s+="vertex-colors:"),o&&(s+="flat-shading:");let r=this.cache.get(s);r||(r=i.clone(),g&&(r.vertexColors=!0),o&&(r.flatShading=!0),n&&(r.normalScale&&(r.normalScale.y*=-1),r.clearcoatNormalScale&&(r.clearcoatNormalScale.y*=-1)),this.cache.add(s,r),this.associations.set(r,this.associations.get(i))),i=r}A.material=i}getMaterialType(){return Kg}loadMaterial(A){const t=this,i=this.json,n=this.extensions,g=i.materials[A];let o;const s={},r=g.extensions||{},a=[];if(r[Un.KHR_MATERIALS_UNLIT]){const c=n[Un.KHR_MATERIALS_UNLIT];o=c.getMaterialType(),a.push(c.extendParams(s,g,t))}else{const c=g.pbrMetallicRoughness||{};if(s.color=new lt(1,1,1),s.opacity=1,Array.isArray(c.baseColorFactor)){const l=c.baseColorFactor;s.color.setRGB(l[0],l[1],l[2],Mr),s.opacity=l[3]}c.baseColorTexture!==void 0&&a.push(t.assignTexture(s,"map",c.baseColorTexture,sn)),s.metalness=c.metallicFactor!==void 0?c.metallicFactor:1,s.roughness=c.roughnessFactor!==void 0?c.roughnessFactor:1,c.metallicRoughnessTexture!==void 0&&(a.push(t.assignTexture(s,"metalnessMap",c.metallicRoughnessTexture)),a.push(t.assignTexture(s,"roughnessMap",c.metallicRoughnessTexture))),o=this._invokeOne(function(l){return l.getMaterialType&&l.getMaterialType(A)}),a.push(Promise.all(this._invokeAll(function(l){return l.extendMaterialParams&&l.extendMaterialParams(A,s)})))}g.doubleSided===!0&&(s.side=Xa);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!==yg&&(a.push(t.assignTexture(s,"normalMap",g.normalTexture)),s.normalScale=new It(1,1),g.normalTexture.scale!==void 0)){const c=g.normalTexture.scale;s.normalScale.set(c,c)}if(g.occlusionTexture!==void 0&&o!==yg&&(a.push(t.assignTexture(s,"aoMap",g.occlusionTexture)),g.occlusionTexture.strength!==void 0&&(s.aoMapIntensity=g.occlusionTexture.strength)),g.emissiveFactor!==void 0&&o!==yg){const c=g.emissiveFactor;s.emissive=new lt().setRGB(c[0],c[1],c[2],Mr)}return g.emissiveTexture!==void 0&&o!==yg&&a.push(t.assignTexture(s,"emissiveMap",g.emissiveTexture,sn)),Promise.all(a).then(function(){const c=new o(s);return g.name&&(c.name=g.name),ql(c,g),t.associations.set(c,{materials:A}),g.extensions&&Kh(n,c,g),c})}createUniqueName(A){const t=On.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[Un.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(s,t).then(function(r){return yoA(r,s,t)})}const o=[];for(let s=0,r=A.length;s<r;s++){const a=A[s],I=Fme(a),c=n[I];if(c)o.push(c.promise);else{let l;a.extensions&&a.extensions[Un.KHR_DRACO_MESH_COMPRESSION]?l=g(a):l=yoA(new ki,a,t),n[I]={primitive:a,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 r=0,a=o.length;r<a;r++){const I=o[r].material===void 0?Ume(this.cache):this.getDependency("material",o[r].material);s.push(I)}return s.push(t.loadGeometries(o)),Promise.all(s).then(function(r){const a=r.slice(0,r.length-1),I=r[r.length-1],c=[];for(let B=0,Q=I.length;B<Q;B++){const h=I[B],d=o[B];let p;const y=a[B];if(d.mode===RC.TRIANGLES||d.mode===RC.TRIANGLE_STRIP||d.mode===RC.TRIANGLE_FAN||d.mode===void 0)p=g.isSkinnedMesh===!0?new zx(h,y):new hn(h,y),p.isSkinnedMesh===!0&&p.normalizeSkinWeights(),d.mode===RC.TRIANGLE_STRIP?p.geometry=doA(p.geometry,rG):d.mode===RC.TRIANGLE_FAN&&(p.geometry=doA(p.geometry,Df));else if(d.mode===RC.LINES)p=new BI(h,y);else if(d.mode===RC.LINE_STRIP)p=new DB(h,y);else if(d.mode===RC.LINE_LOOP)p=new Wx(h,y);else if(d.mode===RC.POINTS)p=new Pp(h,y);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+d.mode);Object.keys(p.geometry.morphAttributes).length>0&&Kme(p,g),p.name=t.createUniqueName(g.name||"mesh_"+A),ql(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 er;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 zo(zC.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):i.type==="orthographic"&&(t=new Yd(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),ql(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=[],r=[];for(let a=0,I=o.length;a<I;a++){const c=o[a];if(c){s.push(c);const l=new ii;g!==null&&l.fromArray(g.array,a*16),r.push(l)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[a])}return new xw(s,r)})}loadAnimation(A){const t=this.json,i=this,n=t.animations[A],g=n.name?n.name:"animation_"+A,o=[],s=[],r=[],a=[],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)),r.push(this.getDependency("accessor",y)),a.push(Q),I.push(h))}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(r),Promise.all(a),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 ql(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 r=0,a=n.weights.length;r<a;r++)s.morphTargetInfluences[r]=n.weights[r]}),o})}loadNode(A){const t=this.json,i=this,n=t.nodes[A],g=i._loadNodeShallow(A),o=[],s=n.children||[];for(let a=0,I=s.length;a<I;a++)o.push(i.getDependency("node",s[a]));const r=n.skin===void 0?Promise.resolve(null):i.getDependency("skin",n.skin);return Promise.all([g,Promise.all(o),r]).then(function(a){const I=a[0],c=a[1],l=a[2];l!==null&&I.traverse(function(B){B.isSkinnedMesh&&B.bind(l,Jme)});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=[],r=n._invokeOne(function(a){return a.createNodeMesh&&a.createNodeMesh(A)});return r&&s.push(r),g.camera!==void 0&&s.push(n.getDependency("camera",g.camera).then(function(a){return n._getNodeRef(n.cameraCache,g.camera,a)})),n._invokeAll(function(a){return a.createNodeAttachment&&a.createNodeAttachment(A)}).forEach(function(a){s.push(a)}),this.nodeCache[A]=Promise.all(s).then(function(a){let I;if(g.isBone===!0?I=new cG:a.length>1?I=new er:a.length===1?I=a[0]:I=new cn,I!==a[0])for(let c=0,l=a.length;c<l;c++)I.add(a[c]);if(g.name&&(I.userData.name=g.name,I.name=o),ql(I,g),g.extensions&&Kh(i,I,g),g.matrix!==void 0){const c=new ii;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 er;i.name&&(g.name=n.createUniqueName(i.name)),ql(g,i),i.extensions&&Kh(t,g,i);const o=i.nodes||[],s=[];for(let r=0,a=o.length;r<a;r++)s.push(n.getDependency("node",o[r]));return Promise.all(s).then(function(r){for(let I=0,c=r.length;I<c;I++)g.add(r[I]);const a=I=>{const c=new Map;for(const[l,B]of n.associations)(l instanceof co||l instanceof Rg)&&c.set(l,B);return I.traverse(l=>{const B=n.associations.get(l);B!=null&&c.set(l,B)}),c};return n.associations=a(g),g})}_createAnimationTracks(A,t,i,n,g){const o=[],s=A.name?A.name:A.uuid,r=[];YQ[g.path]===YQ.weights?A.traverse(function(l){l.morphTargetInfluences&&r.push(l.name?l.name:l.uuid)}):r.push(s);let a;switch(YQ[g.path]){case YQ.weights:a=CQ;break;case YQ.rotation:a=mB;break;case YQ.translation:case YQ.scale:a=SB;break;default:switch(i.itemSize){case 1:a=CQ;break;case 2:case 3:default:a=SB;break}break}const I=n.interpolation!==void 0?bme[n.interpolation]:dd,c=this._getArrayFromAccessor(i);for(let l=0,B=r.length;l<B;l++){const Q=new a(r[l]+"."+YQ[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=G4(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 mB?Gme:RmA;return new n(this.times,this.values,this.getValueSize()/3,i)},A.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function xme(e,A,t){const i=A.attributes,n=new Vn;if(i.POSITION!==void 0){const s=t.json.accessors[i.POSITION],r=s.min,a=s.max;if(r!==void 0&&a!==void 0){if(n.set(new SA(r[0],r[1],r[2]),new SA(a[0],a[1],a[2])),s.normalized){const I=G4(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,r=new SA;for(let a=0,I=g.length;a<I;a++){const c=g[a];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(r.setX(Math.max(Math.abs(B[0]),Math.abs(Q[0]))),r.setY(Math.max(Math.abs(B[1]),Math.abs(Q[1]))),r.setZ(Math.max(Math.abs(B[2]),Math.abs(Q[2]))),l.normalized){const h=G4(Vm[l.componentType]);r.multiplyScalar(h)}s.max(r)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(s)}e.boundingBox=n;const o=new vs;n.getCenter(o.center),o.radius=n.min.distanceTo(n.max)/2,e.boundingSphere=o}function yoA(e,A,t){const i=A.attributes,n=[];function g(o,s){return t.getDependency("accessor",o).then(function(r){e.setAttribute(s,r)})}for(const o in i){const s=R4[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 Rn.workingColorSpace!==Mr&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Rn.workingColorSpace}" not supported.`),ql(e,A),xme(e,A,t),Promise.all(n).then(function(){return A.targets!==void 0?vme(e,A.targets,t):e})}class Tme extends CG{constructor(){super();const A=new gI;A.deleteAttribute("uv");const t=new Kg({side:kr}),i=new Kg,n=new QG(16777215,900,28,2);n.position.set(.418,16.199,.3),this.add(n);const g=new hn(A,t);g.position.set(-.757,13.219,.717),g.scale.set(31.713,28.305,28.591),this.add(g);const o=new lG(A,i,6),s=new cn;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 r=new hn(A,SD(50));r.position.set(-16.116,14.37,8.208),r.scale.set(.1,2.428,2.739),this.add(r);const a=new hn(A,SD(50));a.position.set(-16.109,18.021,-8.207),a.scale.set(.1,2.425,2.751),this.add(a);const I=new hn(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 hn(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 hn(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 hn(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 AV({color:0,emissive:16777215,emissiveIntensity:e})}const qme=1,TJ={"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}},Yme=.62,Hme=320,Ome=.18,Pme=260,jme=.55,DoA=.18,zme=.75;class Zme{constructor(){Ti(this,"renderer",null);Ti(this,"scene");Ti(this,"camera");Ti(this,"ambient");Ti(this,"keyLight");Ti(this,"rimLight");Ti(this,"shipTemplate",null);Ti(this,"shipPool",[]);Ti(this,"shipMeshById",new Map);Ti(this,"freeShipMeshes",[]);Ti(this,"modelReady",!1);Ti(this,"modelPromise",null);Ti(this,"widthCss",0);Ti(this,"heightCss",0);Ti(this,"mountedCanvas",null);Ti(this,"shipMaterials",[]);Ti(this,"thrusterGlowMat",null);Ti(this,"cockpitMat",null);Ti(this,"currentScheme",TJ["crimson-dominion"]);Ti(this,"currentFaction","crimson-dominion");Ti(this,"contextLost",!1);Ti(this,"onContextLost",null);Ti(this,"onContextRestored",null);Ti(this,"_loggedFirstRender",!1);this.scene=new CG,this.camera=new Yd(-1,1,1,-1,.1,2e3),this.camera.position.set(0,0,500),this.camera.lookAt(0,0,0),this.ambient=new aV(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 sV(6983360,1053208,.65);this.scene.add(this.ambient,this.keyLight,this.rimLight,A,t),this.scene.fog=new IG(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 pV({canvas:A,alpha:!0,antialias:!0,premultipliedAlpha:!0,powerPreference:"high-performance"}),this.renderer.setClearColor(0,0),this.renderer.toneMapping=ty,this.renderer.toneMappingExposure=1.18,this.renderer.outputColorSpace=sn,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,r=n.y<-o||n.y>this.heightCss+o;if(s||r){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 a=performance.now()*.001,I=i*1.731,c=Math.max(0,Math.min(1,1-n.z/qme)),l=Math.min(c,.85),B=l*l*l,h=(.04+(8.4-.04)*B)*n.sizeScale*zme;g.scale.setScalar(h);const d=moA(n.bankVx/Hme,-1,1)*Yme,p=.012*c,y=.04*c,m=c>.55?-((c-.55)/.45)*.22:0,D=moA(n.visualVy/Pme,-1,1)*Ome+Math.sin(a*1.7+I)*p+m,S=d*jme+Math.sin(a*1.3+I*.7)*p;let k=d+Math.sin(a*.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:DoA;N.rot.p+=(D-N.rot.p)*DoA,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=TJ[A];t&&(this.currentScheme=t,this.currentFaction=A,this.applyFactionColor())}applyFactionColor(){const A=this.currentScheme,t=new lt(A.body),i=new lt(A.accent),n=new lt(A.emissive);if(this.shipMaterials.length===1&&!!this.shipMaterials[0].map){const o=new lt(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],r=this.shipMaterials.length>1&&o%2===1,a=r?i:t,I=a.clone().lerp(new lt(16777215),r?.22:.16);I.multiplyScalar(r?1.28:1.2),s.color.copy(I),s.emissive.copy(n).lerp(a,r?.5:.35),s.emissiveIntensity=r?.42:.28,s.metalness=A.metalness,s.roughness=Math.max(.32,A.roughness*.82),s.envMapIntensity=Math.max(s.envMapIntensity,r?1.05:.9),s.needsUpdate=!0}if(this.thrusterGlowMat&&(this.thrusterGlowMat.color.set(A.flame),this.thrusterGlowMat.needsUpdate=!0),this.cockpitMat){const o=new lt(A.accent);this.cockpitMat.color.copy(o).lerp(new lt(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(r=>{var a;return(a=r.dispose)==null?void 0:a.call(r)}):(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 gme;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 q=new hn(new gI(.2,.2,.2),new Kg({color:16711935,emissive:4456516})),z=new er;z.add(q),this.shipTemplate=z,this.modelReady=!0;return}const n=new Vn().setFromObject(i),g=new SA;n.getSize(g);const o=150,s=Math.max(g.x,g.y,g.z),r=s>0?o/s:1;i.scale.set(r*.7,r*1.25,r);const a=new Vn().setFromObject(i),I=new SA;a.getCenter(I),i.position.sub(I),i.rotation.x=0;const c=new er;c.add(i),this.shipMaterials=[];const l=0,B=1,Q=2,h=3,d=new Kg({color:12700640,metalness:.42,roughness:.52,emissive:1185831,emissiveIntensity:.28,envMapIntensity:.9}),p=new Kg({color:1778224,metalness:.42,roughness:.16,emissive:791072,emissiveIntensity:.8,envMapIntensity:1.1}),y=new Kg({color:10398659,metalness:.38,roughness:.56,emissive:1054506,emissiveIntensity:.42,envMapIntensity:1.05}),m=new Kg({color:5858420,metalness:.55,roughness:.42,emissive:4856325,emissiveIntensity:1,envMapIntensity:.95}),D=Wme().albedo;uO(d,D,.03,.62),uO(y,D,.03,.56),uO(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 q=x,z=q.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),CA=Z.getX($+2),cA=Z.getY($+2),_A=Z.getZ($+2),uA=(L+tA+CA)/3,X=(H+iA+cA)/3,O=(P+oA+_A)/3,lA=(uA-aA)/(sA*.5),wA=(X-eA.min.y)/pA,xA=(O-eA.min.z)/gA;let HA;xA<.22?HA=h:wA>.7&&xA>.3&&xA<.78&&Math.abs(lA)<.35?HA=B:Math.abs(lA)>.55&&wA<.55?HA=Q:HA=l,fA[HA].push($,$+1,$+2)}const RA=[],YA=[];for(let W=0;W<4;W++)if(fA[W].length!==0){YA.push({start:RA.length,count:fA[W].length,matIndex:W});for(const $ of fA[W])RA.push($)}z.setIndex(new Yi(new Uint32Array(RA),1)),z.clearGroups();for(const W of YA)z.addGroup(W.start,W.count,W.matIndex);z.computeVertexNormals(),q.material=S,q.frustumCulled=!1,k++}),this.applyFactionColor(),console.log("[Raid3D] OBJ segmented meshCount",k);const N=new Vn().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=sn;const J=new JN({map:K,color:16755268,transparent:!0,blending:Vg,depthWrite:!1,fog:!1});this.thrusterGlowMat=J;const T=new pJ(J),v=w*1.6;T.scale.set(v,v,1),T.position.set(0,0,M-w*.15),T.renderOrder=0,c.add(T),this.shipTemplate=c,this.modelReady=!0;const U=new Vn().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=RV[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 ome,r=new Td,a=(x,q)=>new Promise((z,Z)=>{r.load(x,eA=>{q&&(eA.colorSpace=sn),eA.flipY=!1,eA.anisotropy=8,eA.minFilter=Ra,eA.magFilter=_g,eA.generateMipmaps=!0,z(eA)},void 0,Z)});let I,c;try{const[x,q,z,Z,eA,aA]=await Promise.all([s.loadAsync(A),a(o.diffuse,!0),a(o.normal,!1),a(o.metallic,!1),a(o.roughness,!1),a(o.emission,!0)]);I=x.scene,c={diffuse:q,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 q=new hn(new gI(.2,.2,.2),new Kg({color:16711935,emissive:4456516})),z=new er;z.add(q),this.shipTemplate=z,this.modelReady=!0;return}const l=new lt(this.currentScheme.accent),B=new Kg({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 q=x;q.isMesh&&(q.material=B,q.frustumCulled=!1)});const Q=new SJ(this.renderer);Q.compileEquirectangularShader();const h=Q.fromScene(new Tme,.04).texture;this.scene.environment=h,Q.dispose();const d=new Vn().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 Vn().setFromObject(I),S=new SA;D.getCenter(S),I.position.sub(S);const k=new er;k.add(I);const N=new Vn().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=sn;const J=new JN({map:K,color:this.currentScheme.flame,transparent:!0,blending:Vg,depthWrite:!1,fog:!1});this.thrusterGlowMat=J;const T=new pJ(J),v=w*1.6;T.scale.set(v,v,1),T.position.set(0,0,M-w*.15),k.add(T),this.shipTemplate=k,this.modelReady=!0;const U=new Vn().setFromObject(k);console.log("[Raid3D] GLB mesh added",{bbox:{min:U.min.toArray(),max:U.max.toArray()}})}}function moA(e,A,t){return e<A?A:e>t?t:e}function uO(e,A,t,i){A.wrapS=A.wrapT=va,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 Wme(){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,r=Math.random()*512,a=30+Math.random()*80,I=t.createRadialGradient(s,r,0,s,r,a);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-a,r-a,a*2,a*2)}t.globalAlpha=.18;for(let o=0;o<60;o++){const s=Math.random()*512,r=1+Math.random()*4,a=t.createLinearGradient(s,0,s,512);a.addColorStop(0,"rgba(30,30,40,0)"),a.addColorStop(.4,"rgba(30,30,40,1)"),a.addColorStop(1,"rgba(10,10,20,0)"),t.fillStyle=a,t.fillRect(s,0,r,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,r]of n){t.strokeStyle=r,t.lineWidth=s;const a=512/o;for(let I=0;I<=o;I++){const c=Math.round(I*a)+.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,r=Math.random()*512,a=60+Math.random()*200,I=(Math.random()<.5?0:Math.PI/2)+(Math.random()-.5)*.5;t.beginPath(),t.moveTo(s,r),t.lineTo(s+Math.cos(I)*a,r+Math.sin(I)*a),t.stroke()}for(let o=0;o<200;o++){const s=Math.random()*512,r=Math.random()*512,a=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,r,a,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,r=Math.random()*512,a=8+Math.random()*30,I=Math.random()*Math.PI*2;t.beginPath(),t.moveTo(s,r),t.lineTo(s+Math.cos(I)*a,r+Math.sin(I)*a),t.stroke()}const g=new pd(A);return g.wrapS=g.wrapT=va,g.repeat.set(4,4),g.anisotropy=4,g.colorSpace=sn,{albedo:g}}const iE=BmA,Vme=EmA,SoA=N4,Xme=umA,$me=.84,ASe=.8,eSe=.28,woA=.62,koA=.34,MoA=.08,tSe=.2,iSe=20,dO=900,nSe=180,gSe=90,wD=20,NoA=30,rv=200,kD=800,hO=800,oSe=.65,sSe=.012,RoA=[1500,6e3,10500],rSe=.375,aSe=56,GoA=26,pO=2,fO=60,ISe=8,boA=450,UoA=560,av=1,CSe=.36,cSe=.9,lSe=2.4,BSe=1.1,ESe=.6,QSe=1.6,uSe=.6,dSe=1100,hSe=.68,pSe=320,fSe=.5,ySe=.5,DSe=2.4,mSe=1.8,SSe=1.3,wSe=.4,kSe=3.2,MSe=QmA,GmA=75,voA=40,NSe=1500,RSe=252,KoA=6,GSe=GmA,bSe=140,FoA=380,_oA=1200,USe=320,vSe=820,Iv=gC?11:16,Cv=18,cv=.07,KSe=1400,FSe=Math.PI*1.1,JoA=gC?12:18,_Se=900,LoA=.028,JSe=.38,LSe=18,xSe=200,xoA=e=>{const A=(e??"").match(/t(\d)$/);return A?Math.min(6,Math.max(1,parseInt(A[1],10))):null},bmA=({attacker:e,defender:A,onComplete:t,tileBackgroundImage:i,onProgress:n,isSpectator:g=!1,botPilot:o=!1,isLocalDefender:s=!1,confirmedResult:r=null})=>{const a=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(iE),[w,b]=E.useState(null),[_,K]=E.useState(!1),[J,T]=E.useState(!1),v=E.useMemo(()=>i?yd(i):DDe,[i]),U=i??Wm,[x,q]=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([]),YA=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}),CA=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),lA=E.useRef(0),wA=E.useRef(0),xA=E.useRef(0),HA=E.useRef(0),zA=E.useRef(0),ne=E.useRef(0),ye=E.useRef({x:0,y:0,untilTs:0,nextBurstTs:0,tilt:0,targetTilt:0}),Ee=E.useRef({initialized:!1,prevX:0,prevY:0,bankVel:0,pitchVel:0}),NA=E.useRef(null),QA=E.useRef(null),PA=E.useRef(!1),VA=E.useRef(-1),KA=E.useRef(-1e3),Ie=E.useRef(0),DA=E.useRef(0),IA=E.useRef(0),EA=E.useRef({w:0,h:0}),j=E.useRef(0),dA=E.useRef(_),hA=E.useRef(g),UA=E.useRef(n),TA=E.useRef(a);E.useRef(0),E.useRef(0),dA.current=_,hA.current=g,UA.current=n,TA.current=a;const se=E.useRef(1);se.current=xoA(e.heroId)??1;const Ne=E.useRef(0),Ke=E.useRef(0),At=E.useRef(0),ni=E.useRef(null),Ge=E.useRef(0),st=E.useRef({w:0,h:0}),Rt=E.useRef(null),Et=E.useRef({w:0,h:0}),_t=E.useRef(null),vt=E.useRef(0),xt=E.useRef({w:0,h:0}),ee=E.useRef([]);E.useEffect(()=>{const jA=[...hDe[I],...pDe[I],...fDe[I]];ee.current=jA.map(me=>yd(me)).filter(me=>!!me)},[I]);const Oe=E.useCallback(()=>{var Dt;const jA=l.current;if(!jA)return;const me=Math.min(window.devicePixelRatio||1,MDe),le=jA.clientWidth,qA=jA.clientHeight;if(le<=0||qA<=0)return;const WA=Math.round(le*me),Se=Math.round(qA*me),Qe=jA.width!==WA||jA.height!==Se;if(Qe&&(jA.width=WA,jA.height=Se),p.current=me,EA.current={w:le,h:qA},j.current=Math.sqrt(le/2*(le/2)+qA/2*(qA/2)),(Dt=h.current)==null||Dt.resize(le,qA,me),B.current&&!Qe){B.current.setTransform(me,0,0,me,0,0);return}const Ve=typeof navigator<"u"&&/Android/i.test(navigator.userAgent)?jA.getContext("2d"):jA.getContext("2d",{desynchronized:!0});Ve&&(Ve.setTransform(me,0,0,me,0,0),B.current=Ve)},[]),We=E.useCallback((jA,me)=>{const le=$De(jA,me);for(let qA=0;qA<le.length;qA+=1)Z.current.push(le[qA])},[]),pt=E.useCallback((jA,me)=>{const{w:le,h:qA}=EA.current;!le||!qA||z.current.push(xDe({width:le,height:qA,faction:I,factionColor:hmA[I],allocId:()=>lA.current++,now:jA,overrideZ:me,battleshipAnchorX:woA,battleshipAnchorY:koA,zSpeedMin:CSe,zSpeedMax:cSe,zFar:av}))},[I]),kA=E.useCallback(jA=>_J(jA,uA.current,e,A),[e,A]),oe=E.useCallback(()=>{if(y!=="playing"||g)return;const jA=performance.now(),me=o?voA:GmA;if(jA-zA.current<me||(zA.current=jA,jA-wA.current>=iE))return;const{x:qA,y:WA}=P.current;if(qA<=0||WA<=0)return;Lc({volume:.18}),IA.current=jA;const{w:Se,h:Qe}=EA.current;let ce=!1;const Dt=.6+(se.current-1)*.28,Mt=Se*.06,ct=Qe*.3,gt=Jt=>{const jt=Math.atan2(WA-Qe,qA-Jt);return{bx:Jt+Math.cos(jt)*ct,by:Qe+Math.sin(jt)*ct}},{bx:et,by:Li}=gt(Se/2-Mt),{bx:Ri,by:gi}=gt(Se/2+Mt);for(const Jt of z.current){if(!Jt.alive)continue;const jt=Jt.renderScale>0?Jt.renderScale:cO(Jt),Ci=Math.sqrt(Math.max(.5,jt)),Pi=NoA*Ci*Dt,si=Pi*Pi,pi=Jt.x-qA,Ai=Jt.y-WA;if(pi*pi+Ai*Ai>si)continue;Jt.alive=!1,_A.current+=1,N(_A.current),We(Jt.x,Jt.y);const xi=1-Math.max(Jt.z,0)/av,ui=1+xi*xi*4,ie=Math.max(jt,oSe);aA.current.push({x:Jt.x,y:Jt.y,vx:Jt.vx*ui,vy:Jt.vy*ui,life:kD,maxLife:kD,color:Jt.color,maxRadius:hO*ie*Dt}),Br({volume:.03}),ce=!0;break}if(!ce)for(const Jt of pA.current){if(!Jt.alive)continue;const jt=Math.max(0,1-Jt.z),Ci=GoA+(aSe-GoA)*jt,Pi=Ci*Ci*Dt,si=Jt.x-qA,pi=Jt.y-WA;if(!(si*si+pi*pi>Pi)){Jt.alive=!1,We(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:hO*.55*Dt}),Br({volume:.04}),ce=!0;break}}eA.current.push({x1:et,y1:Li,x2:qA-KoA,y2:WA,life:rv,maxLife:rv,hit:ce,width:Dt},{x1:Ri,y1:gi,x2:qA+KoA,y2:WA,life:rv,maxLife:rv,hit:ce,width:Dt})},[o,g,y,We]),ae=E.useCallback(()=>{PA.current=!1,QA.current&&(QA.current(),QA.current=null),NA.current&&(clearInterval(NA.current),NA.current=null)},[]),$A=E.useCallback(()=>{if(!(y!=="playing"||g)){if(!PA.current){PA.current=!0;const jA=()=>ae();window.addEventListener("pointerup",jA,!0),window.addEventListener("pointercancel",jA,!0),window.addEventListener("mouseup",jA,!0),window.addEventListener("touchend",jA,!0),window.addEventListener("touchcancel",jA,!0),QA.current=()=>{window.removeEventListener("pointerup",jA,!0),window.removeEventListener("pointercancel",jA,!0),window.removeEventListener("mouseup",jA,!0),window.removeEventListener("touchend",jA,!0),window.removeEventListener("touchcancel",jA,!0)}}oe(),!NA.current&&(NA.current=setInterval(()=>{oe()},GSe))}},[oe,g,y]);E.useEffect(()=>{y!=="playing"&&ae()},[y,ae]),E.useEffect(()=>{if(g||o)return;const jA=WA=>{const Se=WA,Qe=Se==null?void 0:Se.tagName;return Qe==="INPUT"||Qe==="TEXTAREA"||Qe==="SELECT"||!!(Se!=null&&Se.isContentEditable)},me=(WA,Se)=>{const Qe=cA.current;switch(WA){case"KeyW":case"ArrowUp":return Qe.up=Se,!0;case"KeyS":case"ArrowDown":return Qe.down=Se,!0;case"KeyA":case"ArrowLeft":return Qe.left=Se,!0;case"KeyD":case"ArrowRight":return Qe.right=Se,!0;default:return!1}},le=WA=>{if(!jA(WA.target)){if(me(WA.code,!0)){WA.preventDefault();return}if(WA.code==="Space"||WA.code==="KeyF"){WA.preventDefault(),WA.repeat||$A();return}WA.code==="Enter"&&(WA.preventDefault(),WA.repeat||oe())}},qA=WA=>{if(me(WA.code,!1)){WA.preventDefault();return}(WA.code==="Space"||WA.code==="KeyF")&&(WA.preventDefault(),ae())};return window.addEventListener("keydown",le),window.addEventListener("keyup",qA),()=>{window.removeEventListener("keydown",le),window.removeEventListener("keyup",qA),cA.current={up:!1,down:!1,left:!1,right:!1},ae()}},[o,oe,g,$A,ae]),E.useEffect(()=>{const jA=()=>ae(),me=()=>{document.visibilityState!=="visible"&&ae()};return window.addEventListener("blur",jA),document.addEventListener("visibilitychange",me),()=>{window.removeEventListener("blur",jA),document.removeEventListener("visibilitychange",me),ae()}},[ae]),E.useEffect(()=>{if(y!=="countdown")return;const jA=performance.now(),me=D*1e3,le=jA+me;let qA=0,WA=D,Se=!1;const Qe=()=>{Se||(Se=!0,S(0),m("playing"))},ce=()=>{if(Se)return;const Dt=Math.max(0,le-performance.now()),Mt=Math.ceil(Dt/1e3);if(Mt!==WA){if(WA=Mt,Mt<=0){Qe();return}S(Mt)}qA=requestAnimationFrame(ce)};qA=requestAnimationFrame(ce);const Ve=window.setTimeout(Qe,me+750);return()=>{cancelAnimationFrame(qA),window.clearTimeout(Ve)}},[y,g]);const nA=E.useRef(null);E.useEffect(()=>{nA.current||(nA.current=new mmA({src:dmA}));const jA=nA.current;if(y==="countdown")jA.play();else if(y==="result")return jA.stop(),()=>jA.dispose()},[y]),E.useEffect(()=>()=>{var jA;(jA=nA.current)==null||jA.dispose()},[]),E.useEffect(()=>()=>{const jA=me=>{if(me)try{me.width=0,me.height=0}catch{}};jA(l.current),jA(Q.current),jA(ni.current),jA(Rt.current),jA(_t.current),ni.current=null,Rt.current=null,_t.current=null},[]),E.useEffect(()=>{const jA=[l.current,Q.current].filter(qA=>!!qA);if(jA.length===0)return;const me=qA=>{qA.preventDefault(),T(!0)},le=()=>T(!1);for(const qA of jA)qA.addEventListener("webglcontextlost",me,!1),qA.addEventListener("webglcontextrestored",le,!1),qA.addEventListener("contextlost",me,!1),qA.addEventListener("contextrestored",le,!1);return()=>{for(const qA of jA)qA.removeEventListener("webglcontextlost",me,!1),qA.removeEventListener("webglcontextrestored",le,!1),qA.removeEventListener("contextlost",me,!1),qA.removeEventListener("contextrestored",le,!1)}},[]),E.useEffect(()=>{if(y!=="playing")return;const jA=Q.current;if(!jA)return;console.log("[Raid3D] mount effect canvas",{client:[jA.clientWidth,jA.clientHeight],offset:[jA.offsetWidth,jA.offsetHeight]});const me=new Zme;me.setFactionScheme(I),h.current=me,d.current=!1;let le=!1;return me.mount(jA,jpe(I)).then(()=>{if(le)return;d.current=!0;let{w:qA,h:WA}=EA.current;(qA<=0||WA<=0)&&(qA=jA.clientWidth,WA=jA.clientHeight),me.resize(qA,WA,p.current||window.devicePixelRatio||1),console.log("[Raid3D] scene ready",{w:qA,h:WA})}).catch(qA=>{console.warn("[Raid3D] failed to load ship model",qA)}),()=>{le=!0,d.current=!1,me.dispose(),h.current===me&&(h.current=null)}},[y,I]),E.useEffect(()=>{if(g||o)return;const jA=c.current,me=l.current;if(!jA||!me)return;const le=Qe=>{const ce=me.getBoundingClientRect();return{x:Qe.clientX-ce.left,y:Qe.clientY-ce.top}},qA=Qe=>{P.current=le(Qe)},WA=Qe=>{const ce=Qe.target;ce instanceof Element&&(ce.closest(".raid-fps-fire-btn")||ce.closest(".raid-fps-pad-zone"))||(Qe.preventDefault(),P.current=le(Qe),oe())},Se=Qe=>{const ce=Qe.changedTouches[0],Ve=le(ce),{h:Dt}=EA.current;Ve.y>Dt-RSe||(Qe.preventDefault(),P.current=Ve,oe())};return jA.addEventListener("touchstart",Se,{passive:!1}),soA&&(jA.addEventListener("mousemove",qA),jA.addEventListener("mousedown",WA)),()=>{jA.removeEventListener("touchstart",Se),soA&&(jA.removeEventListener("mousemove",qA),jA.removeEventListener("mousedown",WA))}},[oe,g,o]),E.useEffect(()=>{if(!o||y!=="playing")return;let jA=0,me=performance.now();const le=window.setInterval(()=>{oe()},voA);let qA=-1,WA=0,Se=0,Qe=0,ce=0,Ve=0,Dt=0,Mt=0,ct=Math.random()*Math.PI*2,gt=Math.random()*Math.PI*2;const et=Ri=>{const gi=!Ri&&Math.random()<.25,Jt=Ri?5:gi?70:22;WA=(Math.random()-.5)*Jt,Se=(Math.random()-.5)*Jt;const jt=Ri?60+Math.random()*60:110+Math.random()*110;Qe=performance.now()+jt,ce=0,Ve=0},Li=()=>{const Ri=performance.now(),gi=Math.min(.08,(Ri-me)/1e3);me=Ri,ct+=gi*1.8,Dt=Math.sin(ct)*1.8+Math.sin(ct*2.3)*.8,Mt=Math.cos(ct*.9)*1.5+Math.cos(ct*2.7)*.6,gt+=gi*5.2;const Jt=Math.sin(gt)*16+Math.sin(gt*.37)*9,jt=Math.cos(gt*.83)*12+Math.sin(gt*1.7)*6,{w:Ci,h:Pi}=EA.current;if(Ci>0&&Pi>0){P.current.x<=0&&P.current.y<=0&&(P.current={x:Ci/2,y:Pi/2});let si=null,pi=1/0;const Ai=P.current.x,xi=P.current.y;for(const ui of pA.current){if(!ui.alive)continue;const ie=ui.x-Ai,ln=ui.y-xi,Zt=ie*ie+ln*ln;Zt<pi&&(pi=Zt,si={x:ui.x,y:ui.y,id:-1e3-ui.id})}if(!si)for(const ui of z.current){if(!ui.alive||ui.z>.85)continue;const ie=ui.x-Ai,ln=ui.y-xi,Zt=ie*ie+ln*ln;Zt<pi&&(pi=Zt,si={x:ui.x,y:ui.y,id:ui.id})}if(si)if(si.id!==qA&&(qA=si.id,et(si.id<=-1e3)),Ri<Qe)P.current.x+=Dt*gi*.4,P.current.y+=Mt*gi*.4;else{const ui=si.id<=-1e3,ie=si.x+WA+Dt+(ui?0:Jt),ln=si.y+Se+Mt+(ui?0:jt),Zt=ie-Ai,lo=ln-xi,Hg=Math.sqrt(Zt*Zt+lo*lo),Cg=Math.min(ui?1400:1100,Hg*6),Dg=Hg>.1?Zt/Hg*Cg:0,ng=Hg>.1?lo/Hg*Cg:0,wo=Math.min(1,(ui?12:9)*gi);ce+=(Dg-ce)*wo,Ve+=(ng-Ve)*wo,P.current.x=Ai+ce*gi,P.current.y=xi+Ve*gi}else qA=-1,ce*=Math.max(0,1-3*gi),Ve*=Math.max(0,1-3*gi),P.current.x=Math.max(24,Math.min(Ci-24,P.current.x+ce*gi+Jt*gi*5)),P.current.y=Math.max(24,Math.min(Pi-24,P.current.y+Ve*gi+jt*gi*4))}jA=requestAnimationFrame(Li)};return jA=requestAnimationFrame(Li),()=>{cancelAnimationFrame(jA),window.clearInterval(le)}},[o,y,oe]),E.useEffect(()=>{if(y!=="playing")return;Oe();let jA=0;const me=()=>{jA||(jA=requestAnimationFrame(()=>{jA=0,Oe()}))};window.addEventListener("resize",me);const le=typeof window<"u"?window.visualViewport:null;le==null||le.addEventListener("resize",me),wA.current=performance.now(),xA.current=0,VA.current=-1,uA.current=0,O(0),_A.current=0,N(0),H.current=0,b(null),ye.current={x:0,y:0,untilTs:0,nextBurstTs:performance.now()+vh(FoA,_oA),tilt:0,targetTilt:0},Ee.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,q(0),fA.current=0,RA.current=WDe(),YA.current=VDe(),W.current=XDe();const{w:qA,h:WA}=EA.current;P.current.x<=0&&P.current.y<=0&&(P.current={x:qA/2,y:WA/2});let Se=performance.now();DA.current=0;const Qe=ce=>{const Ve=Math.min((ce-Se)/1e3,.05);Se=ce;const Dt=ce-wA.current;UA.current&&Dt-KA.current>=500&&(KA.current=Dt,UA.current({hits:_A.current,totalSpawned:uA.current,elapsedMs:Math.round(Dt),durationMs:iE,status:"active"}));const Mt=Math.max(0,iE-Dt),ct=Math.ceil(Mt/1e3);if(ct!==VA.current&&(VA.current=ct,M(Mt)),Dt>=iE+NSe&&(z.current=[]),Mt<=0&&z.current.length===0){m("result");return}if(Dt<100&&uA.current===0){const rA=6+Math.floor(Math.random()*3);for(let pe=0;pe<rA;pe++)pt(ce,.35+Math.random()*.5),uA.current+=1;O(uA.current)}if(Mt>MSe&&Dt-xA.current>=Vme){const rA=SoA+Math.floor(Math.random()*(Xme-SoA+1));for(let pe=0;pe<rA;pe+=1)pt(ce),uA.current+=1;O(uA.current),xA.current=Dt}const{w:gt,h:et}=EA.current;if(!g&&Mt>0)for(;gA.current<RoA.length&&Dt>=RoA[gA.current];){const rA=gt*(.15+Math.random()*.7),pe=et*(.1+Math.random()*.35),Fe=gt*.5+(Math.random()-.5)*gt*.12,je=et*.78;fA.current+=1,pA.current.push({id:fA.current,x:rA,y:pe,z:1,originX:rA,originY:pe,targetX:Fe,targetY:je,spawnMs:ce,alive:!0}),gA.current+=1}DD(pA.current,rA=>{if(!rA.alive)return!1;if(rA.z-=rSe*Ve,rA.z<=0){yA.current+=1,q(yA.current);const Fe=ye.current;return Fe.untilTs=ce+700,Fe.targetTilt=vh(-cv*2,cv*2),sA.current.push({x1:rA.targetX,y1:rA.targetY,x2:rA.targetX,y2:rA.targetY,life:380,maxLife:380,color:"#ff3344"}),We(rA.targetX,rA.targetY),aA.current.push({x:rA.targetX,y:rA.targetY,vx:0,vy:0,life:kD,maxLife:kD,color:"#ff5522",maxRadius:hO*1.2}),Br({volume:.06}),!1}const pe=1-rA.z;return rA.x=rA.originX+(rA.targetX-rA.originX)*pe,rA.y=rA.originY+(rA.targetY-rA.originY)*pe,!0});const{dx:Li,dy:Ri}=oA.current,gi=Math.sqrt(Li*Li+Ri*Ri);if(gi>ISe){const rA=Math.min(gi/fO,1);P.current.x+=Li/gi*rA*boA*Ve,P.current.y+=Ri/gi*rA*boA*Ve}const Jt=cA.current,jt=(Jt.right?1:0)-(Jt.left?1:0),Ci=(Jt.down?1:0)-(Jt.up?1:0);if(jt!==0||Ci!==0){const rA=Math.sqrt(jt*jt+Ci*Ci)||1;P.current.x+=jt/rA*UoA*Ve,P.current.y+=Ci/rA*UoA*Ve}P.current.x=Math.max(0,Math.min(gt,P.current.x)),P.current.y=Math.max(0,Math.min(et,P.current.y));{const rA=Ee.current;if(rA.initialized){const pe=(P.current.x-rA.prevX)/Math.max(Ve,.001),Fe=(P.current.y-rA.prevY)/Math.max(Ve,.001);rA.bankVel=rA.bankVel*.94+pe*.06,rA.pitchVel=rA.pitchVel*.94+Fe*.06}rA.prevX=P.current.x,rA.prevY=P.current.y,rA.initialized=!0}const Pi=Ee.current.bankVel/KSe*FSe,si=Math.cos(Pi),pi=Math.sin(Pi),Ai=gt/2*(1-si)+et/2*pi,xi=et/2*(1-si)-gt/2*pi;DD(z.current,rA=>{if(!rA.alive)return!1;const pe=rA.x,Fe=rA.y,je=1-Math.max(rA.z,0)/av,$e=1+je*.75+(rA.z<0?Math.abs(rA.z)*2:0);rA.z-=rA.zSpeed*$e*Ve;const Gt=rA.z<=hSe,Ot=Gt?0:1,qt=Gt?1:0;let ei=rA.vx;if(Gt&&(rA.commitDirX===void 0||rA.commitDirY===void 0)){const hi=TDe(rA,gt/2,et/2);rA.commitDirX=hi.x,rA.commitDirY=hi.y}if(Ot>0){const hi=rA.targetX-rA.x,Bo=rA.targetY-rA.y,Fn=Math.max(.25,rA.z/rA.zSpeed);let ea=hi/Fn,ta=Bo/Fn;if(rA.profile==="weave"){const cl=(ce-rA.spawnTime)/1e3,ga=pSe*(fSe+je*ySe);ea+=Math.sin(cl*DSe+rA.weavePhase)*ga,ta+=Math.cos(cl*mSe+rA.weavePhase*SSe)*ga*wSe}ei=ea;let ia=lSe;rA.profile==="strafe"?ia=BSe-je*ESe:rA.profile==="weave"?ia=QSe:rA.profile==="bankout"&&(ia=uSe);const na=1-Math.exp(-ia*Ve),hI=rA.vx+(ea-rA.vx)*na,Eo=rA.vy+(ta-rA.vy)*na,Og=qDe(rA.vx,rA.vy,hI,Eo,dSe,Ve);rA.vx=Og.vx,rA.vy=Og.vy}if(qt>0&&rA.commitDirX!==void 0&&rA.commitDirY!==void 0){const hi=YDe(rA.vx,rA.vy,{x:rA.commitDirX,y:rA.commitDirY},qt,Ve);rA.vx=hi.vx,rA.vy=hi.vy,ei=rA.commitDirX*Math.max(160,Math.hypot(rA.vx,rA.vy))}const Yt=1+je*je*kSe,Ce=rA.z<0?Math.abs(rA.z)*14:0,it=Yt+Ce;if(rA.x+=rA.vx*it*Ve,rA.y+=rA.vy*it*Ve,rA.z>0&&rA.profile!=="weave"){const hi=(ce-rA.spawnTime)/1e3,Bo=Math.sin(hi*rA.wobbleFreq*Math.PI*2+rA.wobblePhase)*rA.wobbleAmp*je,Fn=Math.cos(hi*rA.wobbleFreq*Math.PI*2+rA.wobblePhase*1.3)*rA.wobbleAmp*.6*je;rA.x+=Bo*Ve*1.2,rA.y+=Fn*Ve*1.2}const dt=(rA.x-pe)/Math.max(Ve,1e-4),ft=(rA.y-Fe)/Math.max(Ve,1e-4);rA.visualVx=rA.visualVx*.72+dt*.28,rA.visualVy=rA.visualVy*.72+ft*.28;const ci=1-Math.exp(-10*Ve);rA.bankVx+=(ei-rA.bankVx)*ci,rA.prevY=rA.y;{const hi=JDe(rA,gt,et);hi!==rA.spriteIndex&&(rA.prevSpriteIndex=rA.spriteIndex,rA.spriteFadeStart=ce,rA.spriteIndex=hi)}rA.renderScale=cO(rA);const Hi=LDe(rA);if(rA.renderCosR=Math.cos(Hi)*rA.renderScale,rA.renderSinR=Math.sin(Hi)*rA.renderScale,!rA.flybyPlayed&&rA.z<.12&&(rA.flybyPlayed=!0,ce-HA.current>300&&(HA.current=ce)),rA.z>.05&&rA.z<.7&&Math.random()<sSe&&sA.current.length<12&&(sA.current.push({x1:rA.x,y1:rA.y,x2:gt/2+(Math.random()-.5)*gt*.4,y2:et*(.7+Math.random()*.3),life:75+Math.random()*50,maxLife:125,color:"#00ff66"}),ce-ne.current>bSe&&(ne.current=ce,Lc({volume:.012}))),rA.z>av*.3)return!0;const Wi=nSe*rA.renderScale/2,Vi=gSe*rA.renderScale/2;return rA.x>-Wi&&rA.x<gt+Wi&&rA.y>-Vi&&rA.y<et+Vi}),DD(Z.current,rA=>(rA.life-=Ve*1e3,rA.life<=0?!1:(rA.x+=rA.vx*Ve,rA.y+=rA.vy*Ve,!0))),DD(eA.current,rA=>(rA.life-=Ve*1e3,rA.life>0)),DD(aA.current,rA=>{if(rA.life-=Ve*1e3,rA.life<=0)return!1;const Fe=2+(1-rA.life/rA.maxLife)*6;return rA.x+=rA.vx*Fe*Ve,rA.y+=rA.vy*Fe*Ve,!0}),DD(sA.current,rA=>(rA.life-=Ve*1e3,rA.life>0)),Ke.current+=1,ce-At.current>=1e3&&(Ne.current=Ke.current,Ke.current=0,At.current=ce);const ui=l.current,ie=B.current??(ui==null?void 0:ui.getContext("2d"))??null;if(!ui||!ie){Ie.current=requestAnimationFrame(Qe);return}if(B.current=ie,!(ooA<=0||ce-DA.current>=ooA)){Ie.current=requestAnimationFrame(Qe);return}DA.current=ce;const Zt=p.current;if(ie.setTransform(Zt*si,Zt*pi,Zt*-pi,Zt*si,Zt*Ai,Zt*xi),v!=null&&v.complete&&v.naturalWidth>0){const rA=ce-wA.current,pe=Math.min(1,Math.max(0,rA/iE)),Fe=1+eSe*(.45+pe*.55),je=Math.hypot(gt,et)/Math.min(gt,et)+.08,$e=je*Fe,Gt=gt*$me,Ot=et*ASe,qt=(1-je)*gt/2,ei=(1-je)*et/2,Yt=Gt+Fe*(qt-Gt),Ce=Ot+Fe*(ei-Ot),it=(P.current.x-gt/2)/gt*gt*LoA,dt=(P.current.y-et/2)/et*et*(LoA*.6);ie.drawImage(v,Yt+it,Ce+dt,$e*gt,$e*et)}else ie.fillStyle="#0a0a1a",ie.fillRect(0,0,gt,et);if(ce-Ge.current>zDe||st.current.w!==gt||st.current.h!==et){for(const pe of YA.current){const Fe=Ge.current===0?0:(ce-Ge.current)/1e3;pe.x+=pe.driftX*Fe,pe.y+=pe.driftY*Fe,pe.x<-.25&&(pe.x+=1.5),pe.x>1.25&&(pe.x-=1.5),pe.y<-.25&&(pe.y+=1.5),pe.y>1.25&&(pe.y-=1.5)}if(!ni.current||st.current.w!==gt||st.current.h!==et){const pe=document.createElement("canvas");pe.width=gt,pe.height=et,ni.current=pe,st.current={w:gt,h:et}}const rA=ni.current.getContext("2d");rA.clearRect(0,0,gt,et);for(const pe of YA.current){const Fe=pe.x*gt,je=pe.y*et,$e=pe.radius*Math.max(gt,et),Gt=rA.createRadialGradient(Fe,je,0,Fe,je,$e);Gt.addColorStop(0,pe.color),Gt.addColorStop(1,"transparent"),rA.globalAlpha=pe.alpha,rA.fillStyle=Gt,rA.fillRect(Fe-$e,je-$e,$e*2,$e*2)}rA.globalAlpha=1,Ge.current=ce}ni.current&&ie.drawImage(ni.current,0,0);const Hg=gt/2,xo=et/2,Cg=j.current;if(!ymA&&Cg>0){for(const pe of RA.current)pe.dist+=pe.speed/Cg*Ve,pe.dist>wmA&&(pe.angle=Math.random()*Math.PI*2,pe.cosAngle=Math.cos(pe.angle),pe.sinAngle=Math.sin(pe.angle),pe.speed=LJ+Math.random()*(SmA-LJ),pe.brightness=.3+Math.random()*.7,pe.length=.5+Math.random()*1.5,pe.dist=.01);for(const pe of W.current)pe.dist+=pe.speed/Cg*Ve,pe.dist>MmA&&(pe.angle=Math.random()*Math.PI*2,pe.speed=xJ+Math.random()*(kmA-xJ),pe.size=.4+Math.random()*1.2,pe.alpha=.12+Math.random()*.3,pe.dist=.01);if(ce-vt.current>jDe||xt.current.w!==gt||xt.current.h!==et){if(!_t.current||xt.current.w!==gt||xt.current.h!==et){const $e=document.createElement("canvas");$e.width=gt,$e.height=et,_t.current=$e,xt.current={w:gt,h:et}}const pe=_t.current.getContext("2d");pe.clearRect(0,0,gt,et);const Fe=$.current;Fe[0].length=0,Fe[1].length=0,Fe[2].length=0;for(const $e of RA.current){const Gt=$e.dist*Cg,Ot=$e.cosAngle,qt=$e.sinAngle,ei=Hg+Ot*Gt,Yt=xo+qt*Gt,Ce=$e.length*(3+8*$e.dist),it=$e.brightness*Math.min($e.dist/.2,1)*.6,dt=$e.dist<.3?0:$e.dist<.6?1:2;Fe[dt].push([ei,Yt,ei-Ot*Ce,Yt-qt*Ce,it])}pe.strokeStyle="#cce0ff",pe.globalAlpha=.5,[.8,1.3,2].forEach(($e,Gt)=>{if(Fe[Gt].length){pe.lineWidth=$e,pe.beginPath();for(const[Ot,qt,ei,Yt]of Fe[Gt])pe.moveTo(Ot,qt),pe.lineTo(ei,Yt);pe.stroke()}}),pe.globalAlpha=1;const je=L.current;je[0].length=0,je[1].length=0,je[2].length=0;for(const $e of W.current){const Gt=$e.dist*Cg,Ot=Hg+Math.cos($e.angle)*Gt,qt=xo+Math.sin($e.angle)*Gt,ei=$e.alpha*Math.min($e.dist/.08,1),Yt=ei<.15?0:ei<.3?1:2;je[Yt].push([Ot,qt,$e.size])}pe.fillStyle="#8899bb",[.1,.22,.38].forEach(($e,Gt)=>{if(je[Gt].length){pe.globalAlpha=$e,pe.beginPath();for(const[Ot,qt,ei]of je[Gt])pe.moveTo(Ot+ei,qt),pe.arc(Ot,qt,ei,0,Math.PI*2);pe.fill()}}),pe.globalAlpha=1,vt.current=ce}_t.current&&ie.drawImage(_t.current,0,0)}{const rA=fmA[I];if(rA!=null&&rA.complete&&rA.naturalWidth>0){const pe=Math.min(1,Math.max(0,Dt/iE)),Fe=pe*pe,je=et*(MoA+(tSe-MoA)*Fe),$e=rA.naturalWidth/rA.naturalHeight,Gt=je*$e,Ot=gt*woA,qt=et*koA;if(H.current===0){const ei=je*1.4,Yt=FDe(I,ei);ie.drawImage(Yt,Ot-ei,qt-ei,ei*2,ei*2)}if(ie.globalAlpha=.82+Fe*.18,ie.drawImage(rA,Ot-Gt/2,qt-je/2,Gt,je),ie.globalAlpha=1,H.current===0&&_A.current>=iSe&&(H.current=ce),H.current>0&&(Kl!=null&&Kl.complete)&&Kl.naturalWidth>0){const ei=ce-H.current;for(let Yt=0;Yt<3;Yt++){const Ce=(ei+Yt*(dO/3))%dO/dO,it=je*(.5+Ce*2.1),dt=(1-Ce)*(Yt===0?.9:.65);ie.globalAlpha=dt,ie.drawImage(Kl,Ot-it/2,qt-it/2,it,it)}ie.globalAlpha=1}}}const Dg=z.current;for(let rA=1;rA<Dg.length;rA++){const pe=Dg[rA];let Fe=rA-1;for(;Fe>=0&&Dg[Fe].z<pe.z;)Dg[Fe+1]=Dg[Fe],Fe--;Dg[Fe+1]=pe}const ng=h.current,wo=d.current&&ng!==null;ng&&wo&&ng.setShipPoses(Dg.map(rA=>({id:rA.id,x:rA.x,y:rA.y,z:rA.z,visualVx:rA.visualVx,bankVx:rA.bankVx,visualVy:rA.visualVy,sizeScale:rA.sizeScale,spinRate:rA.spinRate,spawnTime:rA.spawnTime}))),ng&&ng.render(),UDe(),Math.max(ee.current.length,1),ie.globalCompositeOperation="source-over";for(const rA of Dg);ie.setTransform(Zt*si,Zt*pi,Zt*-pi,Zt*si,Zt*Ai,Zt*xi),ie.globalAlpha=1,ie.globalAlpha=.7,ie.fillStyle="#ff8c00",ie.beginPath();for(const rA of Z.current){const pe=3*(rA.life/rA.maxLife)+1;ie.moveTo(rA.x+pe,rA.y),ie.arc(rA.x,rA.y,pe,0,Math.PI*2)}ie.fill(),ie.globalAlpha=1;const fe=vDe();for(const rA of eA.current){const pe=1-rA.life/rA.maxLife,Fe=rA.x1+(rA.x2-rA.x1)*pe,je=rA.y1+(rA.y2-rA.y1)*pe,$e=rA.life>rA.maxLife*.2?1:rA.life/(rA.maxLife*.2),Gt=rA.hit?"#00ffaa":"#ff4444",Ot=(rA.hit?18:13)*(rA.width??1),qt=Math.max(pe-.15,0),ei=rA.x1+(rA.x2-rA.x1)*qt,Yt=rA.y1+(rA.y2-rA.y1)*qt;ie.globalAlpha=$e*.3,ie.strokeStyle=Gt,ie.lineWidth=Ot*.8,ie.lineCap="round",ie.beginPath(),ie.moveTo(ei,Yt),ie.lineTo(Fe,je),ie.stroke(),ie.globalAlpha=$e*.25,ie.fillStyle=Gt,ie.beginPath(),ie.arc(Fe,je,Ot*2.5,0,Math.PI*2),ie.fill(),ie.globalAlpha=$e;const Ce=rA.hit?fe.hit:fe.miss;ie.drawImage(Ce,Fe-Ot,je-Ot,Ot*2,Ot*2)}ie.globalAlpha=1;for(const rA of aA.current){const pe=1-rA.life/rA.maxLife,Fe=1-(1-pe)*(1-pe)*(1-pe),je=rA.maxRadius*2*(.01+Fe*.99);ie.globalAlpha=.7*(pe<.5?1:1-(pe-.5)/.5),Kl!=null&&Kl.complete&&Kl.naturalWidth>0?ie.drawImage(Kl,rA.x-je/2,rA.y-je/2,je,je):(ie.fillStyle=rA.color,ie.beginPath(),ie.arc(rA.x,rA.y,je/2,0,Math.PI*2),ie.fill())}ie.globalAlpha=1;const Pe=KDe();for(const rA of pA.current){if(!rA.alive)continue;const pe=Math.max(0,1-rA.z),Fe=8+pe*34,je=.55+.45*Math.sin((ce-rA.spawnMs)*.018),$e=rA.x-rA.originX,Gt=rA.y-rA.originY,Ot=Math.hypot($e,Gt)||1,qt=$e/Ot,ei=Gt/Ot,Yt=-ei,Ce=qt,it=Fe*2.7,dt=Fe*.72,ft=rA.x-qt*it,ci=rA.y-ei*it,Hi=Fe*(3.8+je*1.2),Wi=ft-qt*Hi,Vi=ci-ei*Hi,hi=ie.createLinearGradient(rA.originX,rA.originY,rA.x,rA.y);if(hi.addColorStop(0,"rgba(255, 102, 51, 0)"),hi.addColorStop(.65,"rgba(255, 55, 22, 0.48)"),hi.addColorStop(1,"rgba(255, 214, 105, 0.92)"),ie.globalAlpha=.45+pe*.5,ie.fillStyle=hi,ie.beginPath(),ie.moveTo(rA.originX,rA.originY),ie.lineTo(ft+Yt*dt,ci+Ce*dt),ie.lineTo(ft-Yt*dt,ci-Ce*dt),ie.closePath(),ie.fill(),ie.globalAlpha=.72+je*.22,ie.fillStyle="#ff4a1f",ie.beginPath(),ie.moveTo(ft+Yt*dt*.55,ci+Ce*dt*.55),ie.lineTo(Wi,Vi),ie.lineTo(ft-Yt*dt*.55,ci-Ce*dt*.55),ie.closePath(),ie.fill(),ie.globalAlpha=.92,ie.strokeStyle="#fff2b0",ie.lineWidth=Math.max(1.5,Fe*.18),ie.beginPath(),ie.moveTo(ft,ci),ie.lineTo(ft-qt*Hi*.72,ci-ei*Hi*.72),ie.stroke(),ie.globalAlpha=1,$0!=null&&$0.complete&&$0.naturalWidth>0){const Bo=Fe*5,Fn=Fe*2.5;ie.save(),ie.translate(rA.x-qt*Fe*.9,rA.y-ei*Fe*.9),ie.rotate(Math.atan2(ei,qt)+Math.PI),ie.drawImage($0,-Bo/2,-Fn/2,Bo,Fn),ie.restore()}else ie.fillStyle="#4a1015",ie.strokeStyle="#ff6b39",ie.lineWidth=Math.max(1.5,Fe*.12),ie.beginPath(),ie.moveTo(rA.x+qt*Fe*.9,rA.y+ei*Fe*.9),ie.lineTo(rA.x-qt*it*.78+Yt*dt,rA.y-ei*it*.78+Ce*dt),ie.lineTo(ft+Yt*dt*1.65,ci+Ce*dt*1.65),ie.lineTo(ft-Yt*dt*1.65,ci-Ce*dt*1.65),ie.lineTo(rA.x-qt*it*.78-Yt*dt,rA.y-ei*it*.78-Ce*dt),ie.closePath(),ie.fill(),ie.stroke();ie.globalAlpha=.95,ie.fillStyle="#fff4c2",ie.beginPath(),ie.arc(rA.x+qt*Fe*.35,rA.y+ei*Fe*.35,Fe*.42,0,Math.PI*2),ie.fill(),ie.globalAlpha=(.25+pe*.35)*je,ie.strokeStyle="#ff3028",ie.lineWidth=Math.max(1.5,Fe*.08),ie.beginPath(),ie.arc(rA.x,rA.y,Fe*(1.5+je*.45),0,Math.PI*2),ie.stroke(),ie.globalAlpha*=.55,ie.beginPath(),ie.arc(rA.x,rA.y,Fe*(2.5+je*.7),0,Math.PI*2),ie.stroke()}ie.globalAlpha=1;for(const rA of sA.current){const pe=1-rA.life/rA.maxLife,Fe=rA.x1+(rA.x2-rA.x1)*pe,je=rA.y1+(rA.y2-rA.y1)*pe,$e=rA.life>rA.maxLife*.2?1:rA.life/(rA.maxLife*.2),Gt=14,Ot=Math.max(pe-.12,0),qt=rA.x1+(rA.x2-rA.x1)*Ot,ei=rA.y1+(rA.y2-rA.y1)*Ot;ie.globalAlpha=$e*.3,ie.strokeStyle=rA.color,ie.lineWidth=Gt*.7,ie.lineCap="round",ie.beginPath(),ie.moveTo(qt,ei),ie.lineTo(Fe,je),ie.stroke(),ie.globalAlpha=$e*.2,ie.fillStyle=rA.color,ie.beginPath(),ie.arc(Fe,je,Gt*3,0,Math.PI*2),ie.fill(),ie.globalAlpha=$e,ie.drawImage(Pe,Fe-Gt,je-Gt,Gt*2,Gt*2)}if(ie.globalAlpha=1,sA.current.length>0){let rA=0;for(const Fe of sA.current){const je=Fe.life/Fe.maxLife;je>rA&&(rA=je)}const pe=rA*(gC?.18:.35);ie.globalAlpha=pe,ie.fillStyle="#00ff50",ie.fillRect(0,0,gt,et),ie.globalAlpha=1}if(ie.setTransform(Zt,0,0,Zt,0,0),!Rt.current||Et.current.w!==gt||Et.current.h!==et){const rA=document.createElement("canvas");rA.width=gt,rA.height=et;const pe=rA.getContext("2d"),Fe=pe.createRadialGradient(gt/2,et/2,Math.min(gt,et)*.35,gt/2,et/2,Math.max(gt,et)*.75);Fe.addColorStop(0,"transparent"),Fe.addColorStop(1,"rgba(0,0,0,0.45)"),pe.fillStyle=Fe,pe.fillRect(0,0,gt,et),Rt.current=rA,Et.current={w:gt,h:et}}ie.drawImage(Rt.current,0,0);const{x:OA,y:XA}=P.current;if(OA>0&&XA>0&&!hA.current){ie.globalAlpha=.25,ie.strokeStyle="#00ffaa",ie.lineWidth=6,ie.beginPath(),ie.arc(OA,XA,wD,0,Math.PI*2),ie.stroke(),ie.globalAlpha=1,ie.lineWidth=1.5,ie.beginPath(),ie.arc(OA,XA,wD,0,Math.PI*2),ie.stroke();const rA=6;ie.beginPath(),ie.moveTo(OA-wD-rA,XA),ie.lineTo(OA-rA,XA),ie.moveTo(OA+rA,XA),ie.lineTo(OA+wD+rA,XA),ie.moveTo(OA,XA-wD-rA),ie.lineTo(OA,XA-rA),ie.moveTo(OA,XA+rA),ie.lineTo(OA,XA+wD+rA),ie.stroke(),ie.fillStyle="#00ffaa",ie.beginPath(),ie.arc(OA,XA,2,0,Math.PI*2),ie.fill()}if(tA.current!==null){const{x:rA,y:pe}=iA.current,{dx:Fe,dy:je}=oA.current,$e=Math.min(Math.sqrt(Fe*Fe+je*je),fO),Gt=Math.atan2(je,Fe);ie.save(),ie.globalAlpha=.25,ie.strokeStyle="#00ffaa",ie.lineWidth=2,ie.beginPath(),ie.arc(rA,pe,fO,0,Math.PI*2),ie.stroke(),ie.globalAlpha=.5,ie.fillStyle="#00ffaa",ie.beginPath(),ie.arc(rA+Math.cos(Gt)*$e,pe+Math.sin(Gt)*$e,16,0,Math.PI*2),ie.fill(),ie.restore()}const _e=pmA[TA.current];if(_e!=null&&_e.complete&&_e.naturalWidth>0){const rA=ye.current;ce>=rA.nextBurstTs&&(rA.untilTs=ce+vh(USe,vSe),rA.nextBurstTs=ce+vh(FoA,_oA),rA.targetTilt=vh(-cv,cv)),ce<=rA.untilTs?(rA.x=vh(-Iv,Iv),rA.y=vh(-Iv,Iv)):(rA.x=0,rA.y=0,rA.targetTilt=0),rA.tilt+=(rA.targetTilt-rA.tilt)*Math.min(1,Ve*3);const pe=Ee.current,Fe=Math.max(-JoA,Math.min(JoA,pe.pitchVel/_Se)),je=rA.tilt,$e=Math.cos(je),Gt=Math.sin(je),Ot=gt/2,qt=et/2;ie.setTransform(Zt*$e,Zt*Gt,Zt*-Gt,Zt*$e,Zt*(Ot*(1-$e)+qt*Gt),Zt*(qt*(1-$e)-Ot*Gt)),ie.globalAlpha=.35,ie.drawImage(_e,-Cv+rA.x,-Cv+rA.y+Fe,gt+Cv*2,et+Cv*2),ie.setTransform(Zt,0,0,Zt,0,0),ie.globalAlpha=1}{const rA=et*.3,pe=gt*.06,je=(bV[TA.current]??SDe)[se.current-1];if(je!=null&&je.complete&&je.naturalWidth>0){const $e=ce-IA.current,Gt=Math.max(0,1-$e/xSe),Ot=Math.sin(Gt*Math.PI)*LSe,qt=rA*(je.naturalWidth/je.naturalHeight),{x:ei,y:Yt}=P.current,Ce=et,it=gt/2-pe,dt=Math.atan2(Yt-Ce,ei-it)+Math.PI/2,ft=Math.cos(dt),ci=Math.sin(dt);ie.setTransform(Zt*ft,Zt*ci,Zt*-ci,Zt*ft,Zt*(it-ci*Ot),Zt*(Ce+ft*Ot)),ie.globalAlpha=JSe,ie.drawImage(je,-qt/2,-rA,qt,rA);const Hi=gt/2+pe,Wi=Math.atan2(Yt-Ce,ei-Hi)+Math.PI/2,Vi=Math.cos(Wi),hi=Math.sin(Wi);ie.setTransform(Zt*-Vi,Zt*-hi,Zt*-hi,Zt*Vi,Zt*(Hi-hi*Ot),Zt*(Ce+Vi*Ot)),ie.drawImage(je,-qt/2,-rA,qt,rA),ie.setTransform(Zt,0,0,Zt,0,0),ie.globalAlpha=1}}if(dA.current){ie.save(),ie.strokeStyle="rgba(255,255,0,0.35)",ie.lineWidth=1;for(const rA of z.current)ie.beginPath(),ie.arc(rA.x,rA.y,NoA*cO(rA),0,Math.PI*2),ie.stroke();ie.fillStyle="rgba(0,0,0,0.7)",ie.fillRect(8,et-110,220,100),ie.font="12px monospace",ie.fillStyle="#0f0",ie.fillText(`FPS: ${Ne.current}`,16,et-90),ie.fillText(`Ships: ${z.current.length}`,16,et-74),ie.fillText(`Spawned: ${uA.current}`,16,et-58),ie.fillText(`Lasers: ${eA.current.length}`,16,et-42),ie.fillText(`Hits: ${_A.current}`,16,et-26),ie.restore()}const xe=1500;Mt<xe&&(ie.fillStyle=`rgba(0,0,0,${1-Mt/xe})`,ie.fillRect(0,0,gt,et)),Ie.current=requestAnimationFrame(Qe)};return Ie.current=requestAnimationFrame(Qe),()=>{var ce;cancelAnimationFrame(Ie.current),jA&&cancelAnimationFrame(jA),window.removeEventListener("resize",me),le==null||le.removeEventListener("resize",me),(ce=CA.current)==null||ce.call(CA)}},[y,Oe,pt,v]),E.useEffect(()=>{var le;if(y!=="result")return;const jA=kA(_A.current);(le=UA.current)==null||le.call(UA,{hits:_A.current,totalSpawned:uA.current,elapsedMs:iE,durationMs:iE,status:"complete"}),b(s?r?{...jA,winnerId:r.winnerId,creditsStolen:r.creditsStolen}:null:jA);const me=window.setTimeout(()=>{t({...jA,finalHits:_A.current,totalSpawned:uA.current})},3e3);return()=>window.clearTimeout(me)},[kA,t,y,s,r,g,e.id]);const vA=E.useMemo(()=>Zi(I),[I]),FA=E.useMemo(()=>Zi(a),[a]),te=E.useMemo(()=>xoA(e.heroId),[e.heroId]),bA=w?Math.max(1,w.attackerRoll+w.defenderRoll):Math.max(1,X),De=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 ${FA}`:`Raid on ${vA}`}),te&&C.jsxs("span",{className:"raid-fps-subtitle",children:["Hero Level ",te]}),!s&&!g&&C.jsx("span",{className:"raid-fps-hull-pips","aria-label":`Hull integrity: ${pO-x} of ${pO}`,children:Array.from({length:pO}).map((jA,me)=>C.jsx("span",{className:`raid-fps-hull-pip${me<x?" raid-fps-hull-pip--lost":""}`},me))})]}),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:dDe,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"}),te&&C.jsxs("div",{className:"raid-fps-countdown-hero",children:[FA," Hero Level ",te]}),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 jA=!g,me=jA&&s?!De:De,le=jA?me?s?`${vA} defended!`:`${FA} wins the raid!`:s?`${FA} broke through!`:`${vA} defended!`:De?`${FA} wins the raid!`:`${vA} defended!`,qA=jA?me?"+":"-":De?"+":"-",WA=!s;return C.jsxs("div",{className:"raid-fps-result",children:[C.jsx("div",{className:`raid-fps-result-title ${me?"win":"lose"}`,children:le}),WA&&C.jsxs("div",{className:"raid-fps-result-stats",children:[k," / ",bA," ships destroyed"]}),C.jsxs("div",{className:"raid-fps-result-credits",children:[qA,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:jA=>{jA.stopPropagation();const me=jA.changedTouches[0];tA.current=me.identifier;const le=l.current;if(le){const Qe=le.getBoundingClientRect();iA.current={x:me.clientX-Qe.left,y:me.clientY-Qe.top}}oA.current={dx:0,dy:0};const qA=Qe=>{for(let ce=0;ce<Qe.changedTouches.length;ce+=1){const Ve=Qe.changedTouches[ce];if(Ve.identifier!==tA.current)continue;const Dt=l.current;if(!Dt)return;const Mt=Dt.getBoundingClientRect();oA.current={dx:Ve.clientX-Mt.left-iA.current.x,dy:Ve.clientY-Mt.top-iA.current.y}}},WA=()=>{tA.current=null,oA.current={dx:0,dy:0},document.removeEventListener("touchmove",qA),document.removeEventListener("touchend",Se),document.removeEventListener("touchcancel",Se),CA.current=null},Se=Qe=>{for(let ce=0;ce<Qe.changedTouches.length;ce+=1)if(Qe.changedTouches[ce].identifier===tA.current){WA();break}};CA.current=WA,document.addEventListener("touchmove",qA,{passive:!0}),document.addEventListener("touchend",Se),document.addEventListener("touchcancel",Se)},onMouseDown:jA=>{jA.stopPropagation(),jA.preventDefault(),tA.current=-1;const me=l.current;if(me){const Se=me.getBoundingClientRect();iA.current={x:jA.clientX-Se.left,y:jA.clientY-Se.top}}oA.current={dx:0,dy:0};const le=Se=>{const Qe=l.current;if(!Qe)return;const ce=Qe.getBoundingClientRect();oA.current={dx:Se.clientX-ce.left-iA.current.x,dy:Se.clientY-ce.top-iA.current.y}},qA=()=>{tA.current=null,oA.current={dx:0,dy:0},document.removeEventListener("mousemove",le),document.removeEventListener("mouseup",WA),CA.current=null},WA=()=>qA();CA.current=qA,document.addEventListener("mousemove",le),document.addEventListener("mouseup",WA)},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:jA=>{jA.stopPropagation(),jA.preventDefault();try{jA.currentTarget.setPointerCapture(jA.pointerId)}catch{}$A()},onPointerUp:jA=>{jA.stopPropagation();try{jA.currentTarget.releasePointerCapture(jA.pointerId)}catch{}ae()},onPointerCancel:jA=>{jA.stopPropagation();try{jA.currentTarget.releasePointerCapture(jA.pointerId)}catch{}ae()},onClick:jA=>{jA.stopPropagation(),y==="playing"&&!NA.current&&oe()},children:"FIRE"})]})]})},TSe=["⬡","◈","✦","⬢","◉","⧫","Δ","Ψ","Σ"],Kk=[3,4,5],yO=Kk.reduce((e,A)=>e+A,0),qSe=[350,260,190],YSe=90,HSe=2200,lv=900,ToA=1800,ek=5e3,UmA=({attacker:e,defender:A,onComplete:t,isSpectator:i=!1})=>{const[n,g]=E.useState("intro"),[o,s]=E.useState(3),[r,a]=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(ek/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=Kk[z],eA=Array.from({length:Z},()=>Math.floor(Math.random()*9));a(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")},HSe);return()=>clearTimeout(z)},[n]),E.useEffect(()=>{n==="countdown"&&(b(),_(()=>s(2),lv),_(()=>s(1),lv*2),_(()=>s("GO!"),lv*3),_(()=>K(0),lv*3+600))},[n,b,_,K]),E.useEffect(()=>{if(n!=="reveal"||I.length===0)return;N(ek/1e3),b();const z=qSe[r];let Z=500;for(let eA=0;eA<I.length;eA++){const aA=I[eA];_(()=>B(aA),Z),Z+=z,_(()=>B(null),Z),Z+=YSe}_(()=>g("input"),Z+100)},[n,r,I,b,_]);const J=E.useRef([]);E.useEffect(()=>{J.current=Q},[Q]),E.useEffect(()=>{if(n!=="input"||i)return;N(ek/1e3);const z=Date.now(),Z=window.setInterval(()=>{const aA=Date.now()-z,sA=Math.max(0,Math.ceil((ek-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=r+1;return _(()=>{if(gA>=Kk.length){const yA=_J(G.current,yO,e,A);S(yA),g("result"),M.current(yA)}else K(gA)},ToA),"roundResult"})},ek);return()=>{window.clearInterval(Z),window.clearTimeout(eA)}},[n,i,I,r,e,A,_,K]);const T=E.useCallback(z=>{if(n!=="input"||i)return;const Z=[...Q,z],eA=Z.length-1,aA=I[eA]===z;if(yo(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"),yo(pA?"Heavy":"Medium").catch(()=>{});const gA=r+1;_(()=>{if(gA>=Kk.length){const yA=_J(G.current,yO,e,A);S(yA),g("result"),yo(yA.winnerId===e.id?"Heavy":"Medium").catch(()=>{}),M.current(yA)}else K(gA)},ToA)}else h(Z)},[n,i,Q,I,r,e,A,_,K]),v=z=>z.piece.replace(/-/g," ").replace(/\b\w/g,Z=>Z.toUpperCase()),U=v(e),x=v(A),q=(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 ",r+1," / ",Kk.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:TSe.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:()=>T(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${q?" zcb-result-win":" zcb-result-lose"}`,children:q?`BREACH
SUCCESSFUL`:`ENCRYPTION
HELD`}),C.jsxs("div",{className:"zcb-result-score",children:[G.current," / ",yO," sequences cracked"]}),C.jsx("div",{className:"zcb-result-credits",children:q?`${U} extracted ✦${D.creditsStolen}`:`${x} repelled the breach`})]})]})},qoA="/assets/zentara_bg_station-CAwho_RD.webp",OSe="/assets/zentara_bg_asteroid-JpVBwON4.webp",PSe="/assets/zentara_bg_wormhole-ByrGMZDT.webp",YoA="/assets/zentara_bg_tax-D9cuUCQx.webp",jSe="/assets/zentara_bg_jail-CSIhqvMO.webp",zSe="/assets/zentara_bg_go-to-jail-Cn-gffQl.webp",ZSe="/assets/zentara_bg_free-parking-BZgv5fD7.webp",WSe="/assets/galaxy_bg-EkKFwwxn.webp",VSe=9e4,XSe=1800,$Se=2400,Awe=900,vmA=200,Xm=120,ewe=240,HoA=1200,twe=2400,iwe=1.4,KmA=1200,XS=2e3,hp=5,nwe=9,gwe=-14,owe=-26,Bv=2.2,swe=4,rwe=9,awe=-1.5,Iwe=-7,OoA=55,Cwe=7,cwe=2200,lwe=800,DO=110,Bwe=18,Ewe=3,Qwe=380,uwe=950,dwe=14,hwe=.32,pwe=3.2,fwe=.62,ywe=18,Dwe=24,mO=.08,PoA=-3.4,joA=3.4,zoA=-50,ZoA=3,Ev=100,mwe=UV?1:gC?1.25:1.75;function WoA(e,A,t,i){const n=t?e.id:A.id,o=i?Math.min(vmA,(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 Qv={muzzle:{x:0,y:40,z:0},weapon:{x:0,y:0,z:0,tiltX:-.08,tiltY:0,tiltZ:0},forceMuzzle:!1},FmA="/zentara/soldier/enemy-soldier.glb?v=7";ba.preload(FmA);const Swe=({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),r=E.useRef(null),a=E.useRef({x:0,y:0,leanZ:0}),I=E.useRef(null),c=E.useMemo(()=>{const _=new lt(e.color).multiplyScalar(2.6);return new yg({color:_,transparent:!0,opacity:0,blending:Vg,depthWrite:!1,toneMapped:!1})},[e.color]),{scene:l,animations:B}=ba(FmA),Q=E.useMemo(()=>Sue.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 T=K.geometry,v=T.getAttribute("skinIndex"),U=T.getAttribute("skinWeight");if(!v||!U)return;const x=T.getAttribute("position").count,q=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;q[z*3+0]=eA?0:1,q[z*3+1]=eA?0:1,q[z*3+2]=eA?0:1}T.setAttribute("color",new Yi(q,3))})},[Q]),E.useLayoutEffect(()=>{const _=new Sf(3.5,12,8),K=new yg({color:16734746,toneMapped:!1}),J=[];return Q.traverse(T=>{if(/shoulder/i.test(T.name)&&!/end/i.test(T.name)){const v=new hn(_,K);v.position.set(0,0,4),v.renderOrder=5,T.add(v),J.push(v)}}),()=>{J.forEach(T=>{var v;return(v=T.parent)==null?void 0:v.remove(T)}),_.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,T=t.current.scale.y||1,v=(J-_)/T;Q.position.y+=v}else Q.position.y+=1},[Q]);const{actions:p,names:y}=lhe(d,Q),m=E.useMemo(()=>{const _=new lt(e.color),K=[];return Q.traverse(J=>{const T=J;if(!T.isMesh)return;const v=x=>{const q=x.clone();q.color&&(q.color.lerp(_,.45),q.color.multiplyScalar(.55)),q.emissive||(q.emissive=new lt(0)),q.emissive.copy(_).multiplyScalar(.22),q.emissiveIntensity=.1,q.metalness=Math.min(1,(q.metalness??0)+.25),q.roughness=Math.max(.25,(q.roughness??.6)-.1),q.vertexColors=!0;const z={value:_.clone()};return q.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;
                            `)},q.needsUpdate=!0,K.push(q),q},U=T.material;T.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,T)=>{if(_==="dead")return S.length===0?null:((!r.current||!S.includes(r.current))&&(r.current=S[Math.random()*S.length|0]),r.current);r.current&&(r.current=null);const v=K*Math.cos(T),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,T=_?p[_]:null;if(!(_!==null&&!T)){if(s.current=_,T){T.enabled=!0;const v=T.time,U=T.getClip();T.reset();const x=!!_&&(_==="die"||_.startsWith("die-")||_.startsWith("die_")||/^die\d+$/.test(_));v>0&&U.duration>0&&!x&&(T.time=v%U.duration),x?(T.setLoop(FW,1),T.clampWhenFinished=!0,T.timeScale=1):(T.setLoop(hJ,1/0),T.clampWhenFinished=!1,_==="walk-left"||_==="walk-right"?T.timeScale=U.duration>0?U.duration/.68:2.5:_==="run"?T.timeScale=.8:_==="walk"?T.timeScale=1.05:T.timeScale=1),T.fadeIn(.22).play()}J&&J!==T&&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(hJ,1/0),K.fadeIn(.05).play(),s.current=_))},[y,p]);const G=E.useMemo(()=>new yg({color:1114112,transparent:!0,opacity:.75,depthTest:!1}),[]),M=E.useMemo(()=>new yg({color:16729173,transparent:!0,opacity:.95,depthTest:!1}),[]),w=E.useMemo(()=>_mA(),[]),b=E.useMemo(()=>new yg({color:16767078,transparent:!0,opacity:0,blending:Vg,depthWrite:!1}),[]);return E.useLayoutEffect(()=>{const _=[],K=new er;K.name="enemy-weapon",K.frustumCulled=!1,o.current=K;const J=new Kg({color:1710621,metalness:.7,roughness:.45,emissive:0}),T=new Kg({color:2763312,metalness:.6,roughness:.55}),v=new gI(5,22,5.5),U=new hn(v,J);U.position.set(0,12,0),K.add(U);const x=new ny(1.3,1.3,18,10),q=new hn(x,J);q.position.set(0,30,.5),K.add(q);const z=new gI(4,11,5),Z=new hn(z,T);Z.position.set(0,-5,.2),K.add(Z);const eA=new gI(3.6,5,9),aA=new hn(eA,T);aA.position.set(0,8,-6),K.add(aA);const sA=new gI(3.4,3.4,7),pA=new hn(sA,T);pA.position.set(0,0,-4.2),K.add(pA),K.rotation.x=Qv.weapon.tiltX,_.push(()=>{v.dispose(),x.dispose(),z.dispose(),eA.dispose(),sA.dispose(),J.dispose(),T.dispose()});const gA=new Sf(1.2,12,10),yA=new hn(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]),rr((_,K)=>{const J=t.current;if(!J)return;const T=performance.now(),v=e.spawnedAt?T-e.spawnedAt:1/0,U=v<XS,x=U?Math.max(0,Math.min(1,v/XS)):1;if(I.current)if(U){I.current.visible=!0;const iA=Math.sin(x*Math.PI),oA=.85+.15*Math.sin(T*.05);c.opacity=Math.min(.5,(iA*oA+.15)*.5);const CA=Math.min(1,x*2);I.current.scale.y=CA,I.current.position.y=3+(1-CA)*3}else I.current.visible&&(I.current.visible=!1);const q=.9,z=U?x<q?0:Math.min(1,(x-q)/(1-q)):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>=q;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=T*.006,gA=-aA*.08,yA=Math.sin(pA*8)*.012*sA,fA=Math.sin(pA*6)*.012*sA,RA=1-Math.exp(-10*K);a.current.leanZ+=(gA-a.current.leanZ)*RA,a.current.y+=(yA-a.current.y)*RA,a.current.x+=(fA-a.current.x)*RA;const YA=e.pos[0]+a.current.x,W=e.pos[1]+a.current.y,$=e.pos[2];if(J.position.x=YA,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+=(a.current.leanZ-J.rotation.z)*RA}e.state==="dead"&&(J.position.y=-.95);const L=!!(e.flashUntilAt&&e.flashUntilAt>T),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>T)||Qv.forceMuzzle;b.opacity=oA?.95:0;const CA=oA?1+Math.sin(T*.08)*.2:.001;g.current.scale.setScalar(CA);const cA=Qv.muzzle;g.current.position.set(cA.x,cA.y,cA.z)}if(o.current){const iA=Qv.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]})})]})]})},SO=[-3,-1.5,0,1.5,3],wwe=.35,kwe=.35,Mwe=.4,Nwe=1,uv=160,VoA=280,XoA=600,Rwe=1400,Gwe=1400,bwe=200;function $oA(e,A){return e*(1+(Math.random()*2-1)*A)}function AsA(e){return Math.max(0,Math.min(1,e))}function esA(e,A,t){return e<A?Math.min(A,e+t):e>A?Math.max(A,e-t):A}const tsA=2.2,Uwe=3.2,vwe=7.5,Kwe=10,Fwe=6.5,_we=9,Jwe=.9,Lwe=1.8,isA=-6,xwe=2.6,Twe=1.2,nsA=.45,qwe=.35;function Ywe(e,A){if(A.length!==0)for(const t of A){const i=t.hx+nsA,n=qwe+nsA,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),r=n-Math.abs(o);s<r?e[0]=t.x+(g>=0?i:-i):e[2]=t.z+(o>=0?n:-n)}}class gsA{constructor(){Ti(this,"nextLaneSwapAt",0);Ti(this,"firstShotArmedAt",0);Ti(this,"targetX",0);Ti(this,"engageZ",isA);Ti(this,"velX",0);Ti(this,"velZ",0);Ti(this,"burstRemaining",0)}init(A){const t=A+XS;this.firstShotArmedAt=t+ewe+bwe+Math.random()*Gwe,this.nextLaneSwapAt=A,this.targetX=Number.NaN,this.engageZ=isA+(Math.random()-.5)*2*xwe,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<XS)return this.velX=0,this.velZ=0,n.strafeDirX=0,n.isAdvancing=!1,null;const s=n.team==="ally",r=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=SO.filter(b=>{if(Math.abs(b-n.pos[0])<=.5)return!1;for(const _ of G)if(Math.abs(b-_.pos[0])<Twe)return!1;return!0});let w;if(M.length>0)w=M[Math.floor(Math.random()*M.length)]??0;else{let b=SO[0]??0,_=-1/0;for(const K of SO){if(Math.abs(K-n.pos[0])<=.5)continue;let J=1/0;for(const T of G){const v=Math.abs(K-T.pos[0]);v<J&&(J=v)}J>_&&(_=J,b=K)}w=b}this.targetX=w,this.nextLaneSwapAt=A+HoA+Math.random()*(twe-HoA)}const p=this.engageZ-n.pos[2],y=p>.03?Uwe*AsA(p/Lwe):0,m=Math.abs(y)>Math.abs(this.velZ)?Fwe:_we;this.velZ=esA(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||!r&&p>.35;const D=this.targetX-n.pos[0],S=Math.abs(D)>.03?Math.sign(D)*tsA*AsA(Math.abs(D)/Jwe):0,k=Math.abs(S)>Math.abs(this.velX)?vwe:Kwe;this.velX=esA(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/tsA))}if(o&&o.length>0){const p=n.pos[0],y=n.pos[2];Ywe(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 a=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,a=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)*hwe,a=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,a=D.id,I=new SA(D.pos[0],D.pos[1]+1.05,D.pos[2]))}}if(!I)return null;const Q=s?lwe:Qwe,h=s?cwe:uwe,d=s?Cwe:dwe;if(n.state==="patrol"&&A>=n.nextActionAt){n.state="aim";const y=this.burstRemaining>0?Q*.25:Q;return n.aimEndsAt=A+$oA(y,wwe),null}if(n.state==="aim"&&A>=n.aimEndsAt){n.state="fire",n.muzzleUntilAt=A+90;let p;this.burstRemaining>0?(this.burstRemaining-=1,p=uv+Math.random()*(VoA-uv)):Math.random()<Mwe?(this.burstRemaining=1+Math.floor(Math.random()*Nwe),p=uv+Math.random()*(VoA-uv)):p=$oA(h,kwe),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=iwe*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:a}}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+XoA+Math.random()*(Rwe-XoA):n.nextActionAt=A+300+Math.random()*500),null}}const Hwe=Math.cos(Ewe*Math.PI/180),wO=2.4,osA=1.4,ssA=new SA,rsA=new SA,Owe=900,Pwe=140,tk=140,HQ=16,asA=2200,kO=16;let ik=null;function jwe(){if(ik)return ik;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),ik=new pd(A),ik.colorSpace=sn,ik}let dv=null;function zwe(){if(dv)return dv;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),dv=new pd(A),dv}let hv=null;function _mA(){return hv||(hv=new yg({map:zwe(),color:0,transparent:!0,opacity:.65,depthWrite:!1,toneMapped:!1,fog:!1}),hv)}const JmA=new Td,LmA="/zentara/soldier";function Zwe(e,A){const t=JmA.load(`${LmA}/${e}`);return t.wrapS=va,t.wrapT=va,t.repeat.set(A[0],A[1]),t.anisotropy=4,t.colorSpace=sn,t}function Wwe({position:e}){const A=E.useRef(null);return rr(()=>{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 Vwe=E.forwardRef(function({yawRef:A,pitchRef:t,killsRef:i,totalSpawnedRef:n,playerHpRef:g,botHpRef:o,enemyAccent:s,allyAccent:r,enemyEmpire:a,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}=Ac(),M=E.useMemo(()=>{const KA=new lt(s),Ie={h:0,s:0,l:0};return KA.getHSL(Ie),KA.setHSL(Ie.h,Math.min(.55,Ie.s*.7),.04),KA},[s]);E.useEffect(()=>{},[N,M]);const w=E.useRef([]),b=E.useRef([]),[,_]=he.useReducer(KA=>KA+1,0),K=E.useRef(1),J=E.useRef(0),T=E.useRef(!1);E.useRef(null);const v=E.useRef(new Map),U=E.useRef(null),x=E.useRef(!1),q=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((KA,Ie)=>{const DA=performance.now(),IA=Math.max(0,aA.current+sA.current-DA);KA>=eA.current*(IA/Math.max(1,sA.current))&&(eA.current=KA,aA.current=DA,sA.current=Ie)},[]),gA=E.useRef([]),yA=E.useRef(null),fA=E.useRef(new Float32Array(HQ*6)),RA=E.useRef(new Float32Array(HQ*6));if(!yA.current){const KA=new ki;KA.setAttribute("position",new Yi(fA.current,3)),KA.setAttribute("color",new Yi(RA.current,3)),KA.setDrawRange(0,HQ*2),yA.current=KA}const YA=E.useMemo(()=>new $o({vertexColors:!0,transparent:!0,opacity:1,blending:Vg,depthWrite:!1,linewidth:2}),[]),W=E.useRef(null),$=E.useMemo(()=>{const KA=new ny(1,1,1,8,1,!0);return KA.translate(0,.5,0),KA},[]),L=E.useMemo(()=>new yg({transparent:!0,opacity:1,blending:Vg,depthWrite:!1,toneMapped:!1,fog:!1}),[]);function H(KA,Ie,DA,IA=tk,EA=null){const j=performance.now(),dA={a:KA.clone(),aLocal:EA?EA.clone():null,b:Ie.clone(),length:Math.max(.5,KA.distanceTo(Ie)),color:new lt(DA),bornAt:j,untilAt:j+IA},hA=gA.current;hA.length<HQ?hA.push(dA):hA[K.current++%HQ]=dA}const P=E.useRef([]),tA=E.useRef(null),iA=E.useRef(0),oA=E.useMemo(()=>new sB(1,1),[]),CA=E.useMemo(()=>new yg({map:jwe(),transparent:!0,depthWrite:!1,blending:Vg,toneMapped:!1}),[]);function cA(KA,Ie){const DA=iA.current++%kO;P.current[DA]={pos:KA.clone(),bornAt:performance.now(),color:new lt(Ie)}}function _A(KA,Ie,DA=80){if(Ie.y>=-1e-4)return null;const IA=-KA.y/Ie.y;return IA<=0||IA>DA?null:KA.clone().add(Ie.clone().multiplyScalar(IA))}const uA=E.useMemo(()=>Zwe("corridor-floor.webp",[6,40]),[]),X=E.useMemo(()=>new Kg({color:16777215,map:uA,metalness:.35,roughness:.7,emissive:2238513,emissiveIntensity:.12}),[uA]),O=E.useMemo(()=>new Kg({color:2106930,metalness:.5,roughness:.5,emissive:s,emissiveIntensity:.06}),[s]),lA=E.useMemo(()=>new Kg({color:1448483,metalness:.45,roughness:.55,emissive:10466559,emissiveIntensity:.1}),[]),wA=E.useMemo(()=>new yg({color:s,transparent:!0,opacity:.9,blending:Vg,depthWrite:!1,toneMapped:!1}),[s]),xA=E.useMemo(()=>new Kg({color:1185312,metalness:.55,roughness:.35,emissive:s,emissiveIntensity:.55}),[s]),HA=E.useMemo(()=>new yg({color:s,transparent:!0,opacity:.55,blending:Vg,depthWrite:!1,toneMapped:!1,fog:!1}),[s]),zA=E.useMemo(()=>{const KA=JmA.load(`${LmA}/cover/cover-barricade-low.webp`);return KA.anisotropy=4,KA.colorSpace=sn,KA},[]),ne=E.useMemo(()=>new Kg({map:zA,transparent:!0,alphaTest:.12,depthWrite:!0,side:Xa,metalness:.55,roughness:.6,emissive:1711914,emissiveIntensity:.45}),[zA]),ye=E.useMemo(()=>new sB(wO,osA),[]),Ee=E.useMemo(()=>new sB(wO*.92,.06),[]),NA=E.useMemo(()=>new yg({color:10478847,transparent:!0,opacity:.85,blending:Vg,depthWrite:!1,toneMapped:!1,side:Xa}),[]),QA=E.useMemo(()=>new sB(1,1),[]),PA=E.useMemo(()=>_mA(),[]);E.useEffect(()=>()=>{ne.dispose(),zA.dispose(),ye.dispose(),Ee.dispose(),NA.dispose(),QA.dispose()},[ne,zA,ye,Ee,NA,QA]);const VA=E.useCallback((KA,Ie)=>{const DA=b.current;if(!DA.length)return null;const IA=Ie.z-KA.z;if(Math.abs(IA)<1e-4)return null;let EA=1/0,j=null;for(let dA=0;dA<DA.length;dA++){const hA=DA[dA],UA=(hA.z-KA.z)/IA;if(UA<=.001||UA>=.999)continue;const TA=KA.x+(Ie.x-KA.x)*UA,se=KA.y+(Ie.y-KA.y)*UA;TA<hA.x-hA.hx||TA>hA.x+hA.hx||se<0||se>2*hA.hy||UA<EA&&(EA=UA,j=new SA(TA,se,hA.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(),lA.dispose(),wA.dispose(),xA.dispose(),HA.dispose()}),[k,X,O,lA,wA,xA,HA,uA]),E.useImperativeHandle(S,()=>({fire:()=>{if(!c.current||x.current)return;const KA=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(),IA=k.position,EA=[[.55,.45],[1.05,.55],[1.65,.38]];let dA=80,hA=null;for(const ee of w.current)if(!(ee.state==="dead"||ee.team!=="enemy")&&!(ee.spawnedAt&&KA-ee.spawnedAt<XS))for(let Oe=0;Oe<EA.length;Oe++){const[We,pt]=EA[Oe],kA=ee.pos[0]-IA.x,oe=ee.pos[1]+We-IA.y,ae=ee.pos[2]-IA.z,$A=DA.x*kA+DA.y*oe+DA.z*ae;if($A<=0||$A>=dA)continue;const nA=kA-DA.x*$A,vA=oe-DA.y*$A,FA=ae-DA.z*$A;nA*nA+vA*vA+FA*FA>pt*pt||(dA=$A,hA=ee)}const UA=new SA(0,0,-1).applyQuaternion(k.quaternion),TA=!!B.current;let se=TA?0:.55,Ne=TA?-.08:-.2;const Ke=G.domElement,At=Ke==null?void 0:Ke.getBoundingClientRect();if(!TA&&At&&At.width>0&&At.height>0){const ee=document.querySelector(".soldier-weapon-wrap");if(ee){const Oe=ee.getBoundingClientRect();if(Oe.width>0&&Oe.height>0){const We=Oe.right-.97*Oe.width,pt=Oe.bottom-.875*Oe.height;se=(We-At.left)/At.width*2-1,Ne=-((pt-At.top)/At.height*2-1)}}}const Ge=new SA(se,Ne,-1).unproject(k).sub(k.position).normalize(),st=k.position.clone().add(Ge.multiplyScalar(1.2)),Rt=st.clone().sub(k.position).applyQuaternion(k.quaternion.clone().invert()),Et=UA.clone().normalize(),_t=ee=>{const Oe=Math.max(.5,ee.x*Et.x+ee.y*Et.y+ee.z*Et.z-(k.position.x*Et.x+k.position.y*Et.y+k.position.z*Et.z));return st.clone().add(Et.clone().multiplyScalar(Oe))};if(!hA){const ee=_A(k.position,Et,80),Oe=ee||k.position.clone().add(Et.clone().multiplyScalar(40)),We=VA(k.position,Oe);We?(H(st,_t(We),r,tk,Rt),cA(We,r)):(H(st,_t(Oe),r,tk,Rt),ee&&cA(ee,r)),h==null||h(!1);return}const vt=new SA(hA.pos[0],hA.pos[1]+1.05,hA.pos[2]),xt=VA(IA,vt);if(xt){H(st,_t(xt),r,tk,Rt),cA(xt,r),h==null||h(!1);return}H(st,_t(vt),r,tk,Rt),hA.hp-=Bwe,hA.flashUntilAt=KA+Pwe,hA.hp<=0&&(hA.state="dead",hA.nextActionAt=KA+Owe,i.current+=1,U.current=null,v.current.delete(hA.id),y==null||y()),h==null||h(!0),_()}}),[c,k,i,h,y,VA]),rr((KA,Ie)=>{if(!c.current||x.current){for(const ae of w.current)ae.state!=="dead"&&(ae.strafeDirX!==0&&(ae.strafeDirX=0),ae.isAdvancing&&(ae.isAdvancing=!1));z.current.x=0,z.current.z=0;return}const DA=Math.min(Ie,.05),IA=performance.now(),EA=IA-J.current;if(!T.current&&EA>=KmA){T.current=!0;const ae=[],$A=(Se,Qe,ce,Ve=[])=>{const Mt=Math.min(Qe,ce),ct=Math.max(Qe,ce);let gt=[0,(Mt+ct)*.5];for(let et=0;et<24;et++){const Li=(Math.random()*2-1)*Se,Ri=Mt+Math.random()*(ct-Mt);gt=[Li,Ri];let gi=!0;for(let Jt=0;Jt<ae.length;Jt++){const jt=ae[Jt][0]-Li,Ci=ae[Jt][1]-Ri;if(jt*jt+Ci*Ci<Bv*Bv){gi=!1;break}}if(gi)for(let Jt=0;Jt<Ve.length;Jt++){const jt=Ve[Jt][0]-Li,Ci=Ve[Jt][1]-Ri;if(jt*jt+Ci*Ci<Bv*Bv){gi=!1;break}}if(gi)break}return ae.push(gt),gt},nA=4,vA=-9,FA=-13,te=8.5,bA=3.2,De=[],jA=[];for(let Se=0;Se<nA;Se++){let Qe=0,ce=(vA+FA)*.5;for(let Ve=0;Ve<24;Ve++){const Dt=(Math.random()*2-1)*te,Mt=FA+Math.random()*(vA-FA);let ct=!0;for(let gt=0;gt<De.length;gt++){const et=De[gt][0]-Dt,Li=De[gt][1]-Mt;if(et*et+Li*Li<bA*bA){ct=!1;break}}if(Qe=Dt,ce=Mt,ct)break}De.push([Qe,ce]),jA.push({x:Qe,z:ce,hx:wO*.5,hy:osA*.5})}b.current=jA;const me=jA.map(Se=>[Se.x,Se.z]);for(let Se=0;Se<hp;Se++){const[Qe,ce]=$A(nwe,gwe,owe,me),Ve={id:K.current++,pos:[Qe,0,ce],hp:Xm,maxHp:Xm,state:"patrol",aimEndsAt:0,nextActionAt:IA+600+Math.random()*2400,color:s,lane:0,spawnedAt:IA,team:"enemy"};w.current.push(Ve);const Dt=new gsA;Dt.init(IA),v.current.set(Ve.id,Dt)}const le=k.position.x,qA=k.position.z,WA=[[le,qA],...me];ae.length=0;for(let Se=0;Se<swe;Se++){const[Qe,ce]=$A(rwe,awe,Iwe,WA),Ve={id:K.current++,pos:[le+Qe,0,qA+ce],hp:OoA,maxHp:OoA,state:"patrol",aimEndsAt:0,nextActionAt:IA+800+Math.random()*2600,color:r,lane:0,spawnedAt:IA,team:"ally"};w.current.push(Ve);const Dt=new gsA;Dt.init(IA),v.current.set(Ve.id,Dt)}n.current=hp,o.current=hp*Xm,_()}const j=w.current;let dA=0;for(const ae of j){if(ae.state==="dead")continue;const $A=v.current.get(ae.id);if(!$A)continue;const nA=$A.tick({now:IA,dt:DA,camera:k,self:ae,combatants:j,cover:b.current});if(nA){const vA=ae.team==="ally";p==null||p(vA);const FA=vA?6750105:6741503,te=VA(nA.muzzle,nA.aimEnd);if(te){H(nA.muzzle,te,FA,80),cA(te,vA?4521864:5623039);continue}if(H(nA.muzzle,nA.aimEnd,FA,80),nA.targetId===null){const De=nA.aimEnd.clone().sub(nA.muzzle),jA=De.length()||1;De.divideScalar(jA);const le=k.position.clone().sub(nA.muzzle).dot(De);nA.muzzle.clone().add(De.multiplyScalar(le)).distanceTo(k.position)<=.55&&le>0&&le<=jA+.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(De=>De.id===nA.targetId);bA&&bA.state!=="dead"&&(bA.hp-=nA.damage,bA.flashUntilAt=IA+110,bA.hp<=0&&(bA.state="dead",bA.nextActionAt=IA+9999e3,v.current.delete(bA.id),bA.team==="enemy"&&(i.current+=1,U.current===bA.id&&(U.current=null),y==null||y())))}}if(ae.team==="ally"){let vA=1/0,FA=ae.pos[0],te=ae.pos[2]-1;for(const bA of j){if(bA.team!=="enemy"||bA.state==="dead")continue;const De=bA.pos[0]-ae.pos[0],jA=bA.pos[2]-ae.pos[2],me=De*De+jA*jA;me<vA&&(vA=me,FA=bA.pos[0],te=bA.pos[2])}ae.yaw=Math.atan2(FA-ae.pos[0],te-ae.pos[2])}else ae.yaw=Math.atan2(k.position.x-ae.pos[0],k.position.z-ae.pos[2]);ae.team==="enemy"&&(dA+=Math.max(0,ae.hp))}if(T.current&&(o.current=dA),Z.current*=Math.exp(-14*DA),D){let ae=null,$A=1/0;for(const nA of w.current){if(nA.team!=="enemy"||nA.state==="dead")continue;const vA=nA.pos[0]-k.position.x,FA=nA.pos[2]-k.position.z,te=vA*vA+FA*FA;te<$A&&($A=te,ae=nA)}if(ae){const nA=ae.pos[0],vA=(ae.pos[1]??0)+1.5,FA=ae.pos[2],te=nA-k.position.x,bA=vA-k.position.y,De=FA-k.position.z,jA=Math.sqrt(te*te+De*De),me=Math.atan2(-te,-De),le=Math.atan2(bA,Math.max(.001,jA)),qA=1-Math.exp(-14*DA);let WA=me-A.current;for(;WA>Math.PI;)WA-=2*Math.PI;for(;WA<-Math.PI;)WA+=2*Math.PI;Math.abs(WA)<.018&&Math.abs(le-t.current)<.018?(A.current=me,t.current=le):(A.current=A.current+WA*qA,t.current=t.current+(le-t.current)*qA)}}let hA=0,UA=0;if(sA.current>0){const ae=(IA-aA.current)/sA.current;if(ae<1){const $A=eA.current*(1-ae);hA=(Math.random()-.5)*$A,UA=(Math.random()-.5)*$A}else sA.current=0,eA.current=0}if(k.rotation.y=A.current+UA,k.rotation.x=t.current+Z.current+hA,k instanceof zo){const ae=B.current?45:70,$A=1-Math.exp(-8*DA),nA=k.fov+(ae-k.fov)*$A;Math.abs(nA-k.fov)>.01&&(k.fov=nA,k.updateProjectionMatrix())}const TA=l.current,se=z.current;let Ne=0,Ke=0;if(TA&&(TA.x!==0||TA.z!==0)){const ae=A.current,$A=-Math.sin(ae),nA=-Math.cos(ae),vA=Math.cos(ae),FA=-Math.sin(ae),te=Math.hypot(TA.x,TA.z),bA=te<=mO?0:Math.min(1,(te-mO)/(1-mO)),De=te||1,jA=TA.x/De,me=TA.z/De,le=pwe*(B.current?fwe:1)*bA;Ne=($A*me+vA*jA)*le,Ke=(nA*me+FA*jA)*le}const At=Ne-se.x,ni=Ke-se.z,Ge=Math.hypot(At,ni),st=(Ne===0&&Ke===0?Dwe:ywe)*DA;if(Ge<=st||Ge<1e-4)se.x=Ne,se.z=Ke;else{const ae=st/Ge;se.x+=At*ae,se.z+=ni*ae}(Math.abs(se.x)>1e-4||Math.abs(se.z)>1e-4)&&(k.position.x+=se.x*DA,k.position.z+=se.z*DA,k.position.x=Math.max(PoA,Math.min(joA,k.position.x)),k.position.z=Math.max(zoA,Math.min(ZoA,k.position.z)),(k.position.x<=PoA&&se.x<0||k.position.x>=joA&&se.x>0)&&(se.x=0),(k.position.z<=zoA&&se.z<0||k.position.z>=ZoA&&se.z>0)&&(se.z=0));const Rt=new SA(0,0,-1).applyQuaternion(k.quaternion);let Et=null,_t=Hwe;const vt=k.position;for(const ae of w.current){if(ae.state==="dead"||ae.team==="ally"||ae.spawnedAt&&IA-ae.spawnedAt<XS)continue;const $A=ae.pos[0]-vt.x,nA=ae.pos[1]+1-vt.y,vA=ae.pos[2]-vt.z,FA=Math.hypot($A,nA,vA)||1,te=(Rt.x*$A+Rt.y*nA+Rt.z*vA)/FA;if(te>_t){if(ssA.copy(vt),rsA.set(ae.pos[0],ae.pos[1]+1,ae.pos[2]),VA(ssA,rsA))continue;_t=te,Et=ae.id}}U.current=Et;const xt=Et!==null;xt!==q.current&&(q.current=xt,m==null||m(xt));const ee=fA.current,Oe=RA.current,We=gA.current;for(let ae=0;ae<HQ;ae++){const $A=We[ae],nA=ae*6;$A&&$A.untilAt>IA?(ee[nA+0]=$A.a.x,ee[nA+1]=$A.a.y,ee[nA+2]=$A.a.z,ee[nA+3]=$A.b.x,ee[nA+4]=$A.b.y,ee[nA+5]=$A.b.z,Oe[nA+0]=$A.color.r,Oe[nA+1]=$A.color.g,Oe[nA+2]=$A.color.b,Oe[nA+3]=$A.color.r,Oe[nA+4]=$A.color.g,Oe[nA+5]=$A.color.b):(ee[nA+0]=0,ee[nA+1]=-1e3,ee[nA+2]=0,ee[nA+3]=0,ee[nA+4]=-1e3,ee[nA+5]=0,Oe[nA+0]=0,Oe[nA+1]=0,Oe[nA+2]=0,Oe[nA+3]=0,Oe[nA+4]=0,Oe[nA+5]=0)}const pt=yA.current;pt&&(pt.getAttribute("position").needsUpdate=!0,pt.getAttribute("color").needsUpdate=!0);const kA=W.current;if(kA){const ae=new SA,$A=new Ao,nA=new SA(0,1,0),vA=new lt,FA=new ii().makeTranslation(0,-1e4,0);for(let te=0;te<HQ;te++){const bA=We[te];if(!bA||bA.untilAt<=IA){kA.setMatrixAt(te,FA),kA.instanceColor&&vA.setRGB(0,0,0).toArray(kA.instanceColor.array,te*3);continue}const De=Math.max(1,bA.untilAt-bA.bornAt),jA=Math.min(1,(IA-bA.bornAt)/De);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)),ae.subVectors(bA.b,bA.a);const me=ae.length()||1e-4;ae.divideScalar(me);const le=Math.min(me,1.2),qA=Math.min(me,jA*(me+le)),WA=Math.max(0,qA-le),Se=bA.a.clone().add(ae.clone().multiplyScalar(WA)),Qe=Math.max(1e-4,qA-WA);$A.setFromUnitVectors(nA,ae);const ce=.02,Ve=new ii().compose(Se,$A,new SA(ce,Qe,ce));kA.setMatrixAt(te,Ve);const Dt=1-jA*jA;kA.setColorAt(te,vA.copy(bA.color).multiplyScalar(Dt))}kA.instanceMatrix.needsUpdate=!0,kA.instanceColor&&(kA.instanceColor.needsUpdate=!0)}const oe=tA.current;if(oe){const ae=new ii,$A=new lt,nA=new ii().makeTranslation(0,-1e4,0);for(let vA=0;vA<kO;vA++){const FA=P.current[vA],te=FA?IA-FA.bornAt:1/0;if(!FA||te>asA){oe.setMatrixAt(vA,nA),oe.instanceColor&&$A.setRGB(0,0,0).toArray(oe.instanceColor.array,vA*3);continue}const bA=te/asA,De=.05+bA*.07;ae.makeRotationX(-Math.PI/2).setPosition(FA.pos.x,.02,FA.pos.z).scale(new SA(De,De,De));const jA=new ii().compose(new SA(FA.pos.x,.02,FA.pos.z),new Ao().setFromEuler(new or(-Math.PI/2,0,0)),new SA(De,De,De));oe.setMatrixAt(vA,jA);const me=1-bA;oe.setColorAt(vA,$A.copy(FA.color).multiplyScalar(me))}oe.instanceMatrix.needsUpdate=!0,oe.instanceColor&&(oe.instanceColor.needsUpdate=!0)}}),E.useEffect(()=>()=>{var KA;w.current=[],gA.current=[],P.current=[],YA.dispose(),(KA=yA.current)==null||KA.dispose(),L.dispose(),$.dispose(),CA.dispose(),oA.dispose()},[YA,CA,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(Wwe,{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(KA=>C.jsx(Swe,{enemy:KA,empireId:KA.team==="ally"?I:a},KA.id)),b.current.map((KA,Ie)=>C.jsxs("group",{children:[C.jsx("mesh",{position:[KA.x,.015,KA.z+.02],rotation:[-Math.PI/2,0,0],geometry:QA,material:PA,scale:[KA.hx*2*1.35,KA.hy*1.2,1],renderOrder:-1}),C.jsx("mesh",{position:[KA.x,KA.hy,KA.z],geometry:ye,material:ne}),C.jsx("mesh",{position:[KA.x,KA.hy*2-.04,KA.z+.01],geometry:Ee,material:NA})]},`cover-${Ie}`)),C.jsx("instancedMesh",{ref:W,args:[$,L,HQ],frustumCulled:!1}),C.jsx("instancedMesh",{ref:tA,args:[oA,CA,kO],frustumCulled:!1})]})}),Xwe=new URL("/assets/rifle-viewmodel-C29ujLaF.webp",import.meta.url).href,$we=new URL("/assets/rifle-muzzle-flash-B8EJ_3SY.webp",import.meta.url).href,A0e=new URL("/assets/blood-burst-DiPNfQU_.webp",import.meta.url).href,IsA=.0042,CsA=.0034,pv=.55,fv=.85,xmA=({attacker:e,defender:A,onComplete:t,botPilot:i=!1,previewMode:n=!1,tileBackgroundImage:g,skipBonus:o=!1})=>{const[s,r]=E.useState(n?"playing":"intro"),[a,I]=E.useState({playerHp:Ev,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(Ev),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(Ev),_=E.useRef(0),[,K]=E.useState(0),J=E.useRef(null),[T,v]=E.useState(!1),U=E.useRef(0),[,x]=E.useState(0),q=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(ee=>{gA.current=ee,pA(ee)},[]),fA=E.useRef(null),RA=E.useRef(null),YA=E.useRef(new Set),W=E.useCallback((ee,Oe)=>{const We=window.setTimeout(()=>{YA.current.delete(We),ee()},Oe);return YA.current.add(We),We},[]);E.useEffect(()=>()=>{for(const We of YA.current)window.clearTimeout(We);YA.current.clear(),J.current!=null&&(window.clearInterval(J.current),J.current=null);const ee=RA.current;if(ee)for(ee.traverse(We=>{const pt=We;if(pt.geometry&&typeof pt.geometry.dispose=="function")try{pt.geometry.dispose()}catch{}const kA=pt.material;if(kA){const oe=Array.isArray(kA)?kA:[kA];for(const ae of oe)try{ae.dispose()}catch{}}});ee.children.length;)ee.remove(ee.children[0]);const Oe=fA.current;if(Oe){try{Oe.dispose()}catch{}try{const pt=Oe.getContext();pt&&!pt.isContextLost()&&Oe.forceContextLoss()}catch{}const We=Oe.domElement;We&&We.parentElement&&(We.width=1,We.height=1),fA.current=null}RA.current=null},[]);const $=E.useRef(null);E.useEffect(()=>{var Oe;if(n){(Oe=$.current)==null||Oe.stop();return}$.current||($.current=new mmA({src:dmA}));const ee=$.current;s==="intro"||s==="playing"?ee.play():s==="result"&&ee.stop()},[s,n]),E.useEffect(()=>()=>{var ee;(ee=$.current)==null||ee.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,CA=E.useRef(null),[cA,_A]=E.useState(0),[uA,X]=E.useState(!1),O=E.useCallback(()=>{const ee=H.current,Oe=(ee.d?1:0)+(ee.a?-1:0),We=(ee.w?1:0)+(ee.s?-1:0);L.current={x:Oe,z:We}},[]);E.useEffect(()=>{if(s!=="playing"||tA){_A(0);return}const ee=.97,Oe=.875,We=-137,pt=()=>{const ae=CA.current;if(!ae)return;const $A=ae.getBoundingClientRect();if($A.width<=0||$A.height<=0)return;const nA=$A.right-ee*$A.width,vA=$A.bottom-Oe*$A.height,FA=window.innerWidth*.5,te=window.innerHeight*.5,bA=Math.atan2(te-vA,FA-nA)*(180/Math.PI);_A(bA-We)},kA=window.requestAnimationFrame(pt),oe=new ResizeObserver(pt);return CA.current&&oe.observe(CA.current),window.addEventListener("resize",pt),window.addEventListener("orientationchange",pt),()=>{window.cancelAnimationFrame(kA),oe.disconnect(),window.removeEventListener("resize",pt),window.removeEventListener("orientationchange",pt)}},[s,tA]);const[lA,wA]=E.useState({active:!1,baseX:0,baseY:0,knobX:0,knobY:0}),xA=E.useRef(null),HA=E.useMemo(()=>{const ee=TJ[A.piece];return(ee==null?void 0:ee.accent)??16724804},[A.piece]),zA=E.useMemo(()=>{const ee=TJ[e.piece];return(ee==null?void 0:ee.accent)??6750105},[e.piece]),ne=E.useCallback(ee=>{if(!G.current){G.current=!0,S.current=!1,l(ee),r("result");try{Br({volume:.5})}catch{}W(()=>N.current(ee),$Se)}},[e,W]),ye=E.useCallback(()=>{ne(WoA(e,A,!1,!0))},[e,A,ne]),Ee=E.useCallback(ee=>{ne(WoA(e,A,!0,ee))},[e,A,ne]),NA=E.useCallback(ee=>{B.current===null&&(B.current=ee,S.current=!1,r("kill-cam"),W(()=>{ee?o||i?Ee(i?Math.random()<.6:!0):r("codebreaker"):ye()},Awe))},[ye,Ee,W,o,i]);E.useCallback(ee=>{G.current||B.current!==null||NA(ee)},[NA]),E.useEffect(()=>{if(!i||s!=="playing")return;L.current={x:0,z:0};const ee=window.setInterval(()=>{var Oe;if(S.current&&gA.current){(Oe=Q.current)==null||Oe.fire();try{Lc({volume:.22})}catch{}}},DO);return()=>{window.clearInterval(ee),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 ee=window.setTimeout(()=>{k.current=performance.now(),S.current=!0,r("playing")},XSe);return()=>window.clearTimeout(ee)},[s,n]),E.useEffect(()=>{if(s!=="playing")return;let ee=0;const Oe=()=>{const We=m.current,pt=D.current;We<b.current&&(_.current=performance.now()+280,K(vA=>vA+1)),b.current=We,I({playerHp:We,botHp:pt,kills:p.current});const kA=L.current,oe=!!(kA&&(kA.x!==0||kA.z!==0));X(vA=>vA!==oe?oe:vA);const ae=performance.now()-k.current,$A=KmA+200;if(!n&&ae>=$A&&pt<=0&&B.current===null){NA(!0);return}const nA=performance.now()-k.current;if(!n&&nA>=VSe&&B.current===null){NA(We>=pt);return}ee=requestAnimationFrame(Oe)};return ee=requestAnimationFrame(Oe),()=>cancelAnimationFrame(ee)},[s,NA]);const QA=E.useRef({active:!1,lastX:0,lastY:0}),PA=E.useCallback(ee=>{var Oe,We;S.current&&(QA.current={active:!0,lastX:ee.clientX,lastY:ee.clientY},(We=(Oe=ee.target).setPointerCapture)==null||We.call(Oe,ee.pointerId))},[]),VA=E.useCallback(ee=>{const Oe=QA.current;if(!Oe.active)return;const We=ee.clientX-Oe.lastX,pt=ee.clientY-Oe.lastY;Oe.lastX=ee.clientX,Oe.lastY=ee.clientY;const kA=P.current?oA:1;h.current=Math.max(-fv,Math.min(fv,h.current-We*IsA*kA)),d.current=Math.max(-pv,Math.min(pv,d.current-pt*CsA*kA))},[]),KA=E.useCallback(()=>{QA.current.active=!1},[]),Ie=E.useCallback(()=>{var ee;if(S.current){(ee=Q.current)==null||ee.fire();try{Lc({volume:.28})}catch{}}},[]),DA=E.useRef(null),IA=E.useCallback(ee=>{var Oe,We;if(ee.preventDefault(),!!S.current){Ie(),v(!0),J.current!=null&&window.clearInterval(J.current),J.current=window.setInterval(Ie,DO);try{(We=(Oe=ee.target).setPointerCapture)==null||We.call(Oe,ee.pointerId)}catch{}DA.current={id:ee.pointerId,lastX:ee.clientX,lastY:ee.clientY}}},[Ie]),EA=E.useCallback(ee=>{const Oe=DA.current;if(!Oe||Oe.id!==ee.pointerId)return;const We=ee.clientX-Oe.lastX,pt=ee.clientY-Oe.lastY;Oe.lastX=ee.clientX,Oe.lastY=ee.clientY;const kA=P.current?oA:1;h.current=Math.max(-fv,Math.min(fv,h.current-We*IsA*kA)),d.current=Math.max(-pv,Math.min(pv,d.current-pt*CsA*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 dA=E.useCallback(()=>{if(!S.current)return;const ee=!P.current;P.current=ee,iA(ee)},[]),hA=E.useCallback(ee=>{!S.current&&ee||P.current!==ee&&(P.current=ee,iA(ee))},[]);E.useEffect(()=>{const ee=pt=>{pt.button===2&&hA(!0)},Oe=pt=>{pt.button===2&&hA(!1)},We=pt=>{pt.preventDefault()};return window.addEventListener("mousedown",ee),window.addEventListener("mouseup",Oe),window.addEventListener("contextmenu",We),()=>{window.removeEventListener("mousedown",ee),window.removeEventListener("mouseup",Oe),window.removeEventListener("contextmenu",We)}},[hA]),E.useEffect(()=>{const ee=kA=>{const oe=kA,ae=oe==null?void 0:oe.tagName;return ae==="INPUT"||ae==="TEXTAREA"||ae==="SELECT"||!!(oe!=null&&oe.isContentEditable)},Oe=(kA,oe)=>{const ae=H.current;switch(kA){case"KeyW":case"ArrowUp":ae.w=oe;break;case"KeyS":case"ArrowDown":ae.s=oe;break;case"KeyA":case"ArrowLeft":ae.a=oe;break;case"KeyD":case"ArrowRight":ae.d=oe;break;default:return}return O(),!0},We=kA=>{if(!S.current||ee(kA.target))return;if(Oe(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,DO);return}(kA.code==="ShiftLeft"||kA.code==="ShiftRight")&&(kA.preventDefault(),hA(!0))},pt=kA=>{if(Oe(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(),hA(!1))};return window.addEventListener("keydown",We),window.addEventListener("keyup",pt),()=>{window.removeEventListener("keydown",We),window.removeEventListener("keyup",pt),j(),hA(!1)}},[Ie,j,O,hA]);const UA=56,TA=E.useCallback(ee=>{var Oe,We;S.current&&xA.current==null&&(xA.current=ee.pointerId,(We=(Oe=ee.target).setPointerCapture)==null||We.call(Oe,ee.pointerId),wA({active:!0,baseX:ee.clientX,baseY:ee.clientY,knobX:ee.clientX,knobY:ee.clientY}),L.current={x:0,z:0})},[]),se=E.useCallback(ee=>{xA.current===ee.pointerId&&wA(Oe=>{if(!Oe.active)return Oe;const We=ee.clientX-Oe.baseX,pt=ee.clientY-Oe.baseY,kA=Math.hypot(We,pt),oe=Math.min(kA,UA),ae=kA>0?We/kA:0,$A=kA>0?pt/kA:0,nA=oe/UA;return L.current={x:ae*nA,z:-$A*nA},{...Oe,knobX:Oe.baseX+ae*oe,knobY:Oe.baseY+$A*oe}})},[]),Ne=E.useCallback(ee=>{xA.current===ee.pointerId&&(xA.current=null,wA({active:!1,baseX:0,baseY:0,knobX:0,knobY:0}),O())},[O]),Ke=(c==null?void 0:c.winnerId)===e.id,At=performance.now(),ni=M.current>At,Ge=_.current>At,st=U.current>At,Rt=q.current>At,Et="/zentara/soldier/intro-key-art.webp",_t=Ke?"/zentara/soldier/result-win.webp":"/zentara/soldier/result-loss.webp",vt=`#${zA.toString(16).padStart(6,"0")}`,xt=`#${HA.toString(16).padStart(6,"0")}`;return C.jsxs("div",{className:`soldier-raid-root${tA?" ads":""}`,style:{"--soldier-ally":vt,"--soldier-enemy":xt},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(dG,{dpr:[1,mwe],camera:{fov:70,near:.1,far:80,position:[0,1.6,0]},gl:{antialias:!1,powerPreference:"low-power",alpha:!0},onCreated:({gl:ee,scene:Oe})=>{fA.current=ee,RA.current=Oe,ee.setClearColor(new lt(0),0),ee.shadowMap.enabled=!1},children:C.jsx(Vwe,{ref:Q,yawRef:h,pitchRef:d,killsRef:p,totalSpawnedRef:y,playerHpRef:m,botHpRef:D,activeRef:S,moveRef:L,adsRef:P,enemyAccent:HA,allyAccent:zA,allyEmpire:e.piece,enemyEmpire:A.piece,botPilot:i,onPlayerDied:()=>{n||NA(!1)},onShotFired:ee=>{M.current=performance.now()+90,w(Oe=>Oe+1),ee&&(q.current=performance.now()+180,z(Oe=>Oe+1))},onEnemyFired:()=>{_.current=performance.now()+200,K(ee=>ee+1)},onCombatantFired:ee=>{try{Lc({volume:ee?.14:.18})}catch{}},onEnemyKilled:()=>{U.current=performance.now()+320,x(We=>We+1);const ee=++aA.current,Oe=performance.now();eA(We=>[...We,{id:ee,bornAt:Oe}]),W(()=>{eA(We=>We.filter(pt=>pt.id!==ee))},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:CA,children:C.jsxs("div",{className:`soldier-weapon-pivot${tA?" ads":""}`,style:{transform:tA?"none":`rotate(${cA.toFixed(3)}deg)`},children:[C.jsx("img",{src:Xwe,alt:"","aria-hidden":"true",className:`soldier-viewmodel${tA?" ads":""}${T?" firing":""}${ni?" recoil":""}${uA?" walking":""}`,draggable:!1}),ni&&!tA&&C.jsx("img",{src:$we,alt:"","aria-hidden":"true",className:"soldier-muzzle-flash",draggable:!1})]})}),st&&C.jsx("img",{src:A0e,alt:"","aria-hidden":"true",className:"soldier-blood-burst",draggable:!1})]}),Ge&&C.jsx("div",{className:"soldier-damage-vignette"})]}),!i&&C.jsx("div",{className:"soldier-look-pad",onPointerDown:PA,onPointerMove:VA,onPointerUp:KA,onPointerCancel:KA}),!i&&C.jsx("div",{className:"soldier-move-pad",onPointerDown:TA,onPointerMove:se,onPointerUp:Ne,onPointerCancel:Ne,children:lA.active&&C.jsxs(C.Fragment,{children:[C.jsx("div",{className:"soldier-move-stick-base",style:{left:lA.baseX,top:lA.baseY}}),C.jsx("div",{className:"soldier-move-stick-knob",style:{left:lA.knobX,top:lA.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:Zi(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,a.botHp/(Xm*hp)*100))}%`}})}),C.jsx("span",{className:"soldier-duel-hp-value",children:Math.max(0,Math.ceil(a.botHp))})]})}),s==="playing"&&C.jsx("div",{className:`soldier-reticle${sA?" locked":""}`}),s==="playing"&&Rt&&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:a.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(ee=>C.jsx("span",{className:"soldier-kill-toast",children:"ENEMY DOWN"},ee.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:Zi(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,a.playerHp/Ev*100))}%`}})}),C.jsx("span",{className:"soldier-duel-hp-value",children:Math.max(0,Math.ceil(a.playerHp))})]})]}),s==="playing"&&!i&&C.jsxs("button",{type:"button",className:`soldier-fire-btn${T?" active":""}`,onPointerDown:IA,onPointerMove:EA,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:ee=>{ee.preventDefault(),dA()},"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(${Et})`},children:[C.jsx("span",{className:"soldier-splash-kicker",children:"Tactical encounter"}),C.jsx("h2",{children:"Faction Duel"}),C.jsxs("p",{children:[Zi(e.piece)," vs. ",Zi(A.piece)]}),C.jsxs("p",{children:["1v1 — eliminate your opponent to claim ",vmA," 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(UmA,{attacker:e,defender:A,onComplete:ee=>Ee(ee.winnerId===e.id)}),s==="result"&&c&&C.jsxs("div",{className:`soldier-splash ${Ke?"win":"loss"}`,style:{backgroundImage:`linear-gradient(180deg, rgba(2,5,10,0.24), rgba(2,5,10,0.82)), url(${_t})`},children:[C.jsx("span",{className:"soldier-splash-kicker",children:"Combat report"}),C.jsx("h2",{children:Ke?"Duel Won":"Duel Lost"}),c.creditsStolen>0&&C.jsxs("p",{children:["✦ ",c.creditsStolen.toLocaleString()," energy ",Ke?"seized":"forfeited"]})]})]})},e0e=Object.freeze(Object.defineProperty({__proto__:null,default:xmA},Symbol.toStringTag,{value:"Module"})),TmA="/models/zentara_ship.glb",MO=2.4,t0e=.4,i0e=6;function n0e({tint:e}){const A=E.useRef(null),t=E.useRef(performance.now()),i=ba(TmA),n=E.useMemo(()=>{const g=i.scene.clone(!0),o=new Vn().setFromObject(g),s=new SA;o.getSize(s);const a=2/(Math.max(s.x,s.y,s.z)||1);g.scale.setScalar(a);const I=new Vn().setFromObject(g),c=new SA;if(I.getCenter(c),g.position.sub(c),e){const l=new lt(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 rr(()=>{if(!A.current)return;const g=(performance.now()-t.current)/1e3,o=Math.min(1,g/i0e),s=1-Math.pow(1-o,3),r=MO+(t0e-MO)*s;A.current.scale.setScalar(r);const a=g,I=Math.sin(a*.55)*.55+Math.sin(a*1.7)*.12;A.current.rotation.z=I,A.current.rotation.y=Math.PI+Math.sin(a*.45)*.18,A.current.position.y=Math.sin(a*.6)*.08,A.current.position.x=Math.sin(a*.33)*.18+I*.12}),C.jsxs("group",{ref:A,rotation:[-.18,Math.PI,0],scale:MO,children:[C.jsx("primitive",{object:n}),C.jsx(csA,{tint:e,offsetX:-.35}),C.jsx(csA,{tint:e,offsetX:.35})]})}function csA({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),r=E.useMemo(()=>new lt("#e6f4ff"),[]),a=E.useMemo(()=>{const I=new lt("#6cb8ff");return e&&I.lerp(new lt(e),.5),I},[e]);return rr(()=>{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:a,transparent:!0,opacity:.95,blending:Vg,depthWrite:!1,toneMapped:!1})]}),C.jsxs("mesh",{ref:t,children:[C.jsx("planeGeometry",{args:[.8,.8]}),C.jsx("meshBasicMaterial",{ref:i,color:r,transparent:!0,opacity:1,blending:Vg,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:a,transparent:!0,opacity:.7,blending:Vg,depthWrite:!1,toneMapped:!1})]})]})}const qmA=({tint:e,size:A=140})=>C.jsx("div",{style:{width:A,height:A,pointerEvents:"none"},children:C.jsxs(dG,{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(n0e,{tint:e})})]})});var drA;try{(drA=ba.preload)==null||drA.call(ba,TmA)}catch{}const HN=18,yv=26,Dv=3,lsA=1100,BsA=3500,mv=22,g0e=.16,o0e=.24,s0e={1:1,2:1.2,3:1.4,4:1.6,5:1.8,6:2},Sv=1e4,NO=2,EsA=5e3,wv=2e3,r0e=600,OQ=["READY","3","2","1","FIRE"],QsA="zentara.sniper.coachmark.v1",a0e=Ym.bullseye*HN,I0e=Ym.hit*HN,RO=Ym.graze*HN,YmA=({defender:e,onComplete:A,groupColor:t="#9d4edd",botPilot:i=!1})=>{const[n,g]=E.useState(!1),[o,s]=E.useState(null),[r,a]=E.useState(!1),[I,c]=E.useState(null),[l,B]=E.useState(!1),[Q,h]=E.useState(NO),d=E.useRef("miss"),p=E.useMemo(()=>{const zA=e.heroId?ys[e.heroId]:void 0,ne=(zA==null?void 0:zA.tier)??1;return g0e*s0e[ne]},[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(QsA)!=="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),T=E.useRef(null),v=E.useRef(null),U=E.useRef(null),x=E.useRef(performance.now()),q=E.useRef({x:0,y:0}),z=E.useRef({x:0,y:0}),Z=E.useRef(0),eA=E.useRef((Math.random()-.5)*mv),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,YA=E.useCallback((zA,ne)=>{const ye=Math.sqrt(zA*zA+ne*ne);if(ye>fA){const Ee=fA/ye;aA.current={x:zA*Ee,y:ne*Ee}}else aA.current={x:zA,y:ne}},[]);E.useEffect(()=>{if(M.current){k.current=!0,S(OQ.length-1);return}let zA=0;S(zA);const ne=window.setInterval(()=>{if(zA+=1,zA>=OQ.length){window.clearInterval(ne),k.current=!0,x.current=performance.now(),S(OQ.length);return}S(zA),yo("Light").catch(()=>{})},r0e);return()=>window.clearInterval(ne)},[]),E.useEffect(()=>{tM({volume:.35})},[]),E.useEffect(()=>{let zA=0;const ne=()=>{const ye=performance.now(),Ee=(ye-x.current)/1e3,NA=J.current;if(!NA){zA=requestAnimationFrame(ne);return}const QA=NA.clientWidth,PA=NA.clientHeight,VA=QA/2+Math.sin(Ee*Math.PI*2*p)*QA*o0e,KA=PA/2+Math.cos(Ee*Math.PI*2*p*.6)*30;q.current={x:VA,y:KA};const Ie=_.current;Ie&&(Ie.style.left=`${VA}px`,Ie.style.top=`${KA}px`);const DA=K.current;if(DA){const Et=VA-Z.current,_t=Math.max(-18,Math.min(18,Et*1.2));DA.style.transform=`rotate(${_t}deg)`}Z.current=VA;let IA=yv;if(o!==null){const Et=ye-o;Et<=lsA?IA=yv-(yv-Dv)*(Et/lsA):Et<=BsA?IA=Dv:IA=Dv+(yv-Dv)*Math.min(1,(Et-BsA)/600)}const EA=Math.sin(Ee*1.7)*IA+Math.cos(Ee*.9)*IA*.4+eA.current,j=Math.cos(Ee*1.3)*IA+Math.sin(Ee*2.1)*IA*.3,dA=aA.current,hA=EA+dA.x,UA=j+dA.y;z.current={x:QA/2+hA,y:PA/2+UA};const TA=w.current;TA&&(TA.style.transform=`translate(calc(-50% + ${hA}px), calc(-50% + ${UA}px))`);const se=b.current;if(se){const Et=Math.max(20,IA*4);se.style.width=`${Et}px`,se.style.height=`${Et}px`}const Ne=z.current.x-VA,Ke=z.current.y-KA,At=Math.sqrt(Ne*Ne+Ke*Ke);let ni="none";if(At<=a0e?ni="bullseye":At<=I0e?ni="hit":At<=RO&&(ni="graze"),ni!==gA.current){const Et=gA.current;gA.current=ni,TA&&(TA.classList.toggle("locked-graze",ni==="graze"),TA.classList.toggle("locked-hit",ni==="hit"),TA.classList.toggle("locked-bullseye",ni==="bullseye")),r||(ni==="bullseye"&&Et!=="bullseye"?yo("Medium").catch(()=>{}):ni==="hit"&&(Et==="none"||Et==="graze")&&yo("Light").catch(()=>{}))}const Ge=U.current;Ge&&(Ge.textContent=`RANGE ▸ ${(At/HN).toFixed(1)}°`);const st=k.current?Math.max(0,Sv-(ye-x.current)):Sv,Rt=v.current;if(Rt){Rt.textContent=`⏱ ${(st/1e3).toFixed(1)}s`;const Et=st<wv;Rt.classList.toggle("zentara-sniper-hud-block--urgent",Et)}if(NA){let Et=0;st<wv?Et=1:st<EsA&&(Et=.5*(1-(st-wv)/(EsA-wv))),NA.style.setProperty("--pressure",Et.toFixed(3))}r||(zA=requestAnimationFrame(ne))};return zA=requestAnimationFrame(ne),()=>cancelAnimationFrame(zA)},[o,r,p]);const W=E.useCallback(()=>{r||(g(!0),s(performance.now()),yo("Light").catch(()=>{}))},[r]),$=E.useCallback(()=>{g(!1),setTimeout(()=>s(null),50)},[]),L=E.useCallback(zA=>{pA.current={x:zA.clientX,y:zA.clientY,ax:aA.current.x,ay:aA.current.y};try{zA.currentTarget.setPointerCapture(zA.pointerId)}catch{}},[]),H=E.useCallback(zA=>{const ne=pA.current;if(!ne)return;const ye=ne.ax+(zA.clientX-ne.x)*yA,Ee=ne.ay+(zA.clientY-ne.y)*yA;YA(ye,Ee)},[YA]),P=E.useCallback(zA=>{pA.current=null;try{zA.currentTarget.releasePointerCapture(zA.pointerId)}catch{}},[]),tA=E.useCallback(zA=>{r||zA.target.closest(".zentara-sniper-btn, .zentara-sniper-controls, .zentara-sniper-pad-zone, .zentara-sniper-fire-btn")||L(zA)},[r,L]),iA=H,oA=P,CA=E.useCallback(zA=>{r||(zA.stopPropagation(),W(),L(zA))},[r,W,L]),cA=E.useCallback(zA=>{pA.current&&(zA.stopPropagation(),H(zA))},[H]),_A=E.useCallback(zA=>{!pA.current&&!n||(zA.stopPropagation(),P(zA),$())},[n,P,$]),uA=E.useCallback(()=>{const zA=T.current;zA&&zA.classList.remove("active");const ne=J.current;ne&&ne.classList.remove("zentara-sniper-overlay--slowmo");const ye=_.current;ye&&ye.classList.remove("zentara-sniper-target--hit"),aA.current={x:0,y:0},pA.current=null,eA.current=(Math.random()-.5)*mv,x.current=performance.now(),d.current="miss",h(NO),g(!1),s(null),B(!1),c(null),a(!1),m(null)},[]),X={miss:0,graze:1,hit:2,bullseye:3},O=E.useCallback(()=>{const zA=T.current;zA&&zA.classList.remove("active");const ne=J.current;ne&&ne.classList.remove("zentara-sniper-overlay--slowmo");const ye=_.current;ye&&ye.classList.remove("zentara-sniper-target--hit"),aA.current={x:0,y:0},pA.current=null,eA.current=(Math.random()-.5)*mv,x.current=performance.now(),g(!1),s(null),B(!1),c(null),a(!1),m(null)},[]),lA=E.useCallback(()=>{if(r||!k.current&&!M.current)return;a(!0),B(!0),yo("Heavy").catch(()=>{}),Lc({volume:.8}),setTimeout(()=>B(!1),120);const zA=z.current.x-q.current.x,ne=z.current.y-q.current.y,Ee=Math.sqrt(zA*zA+ne*ne)/HN;let NA="miss";Ee<=Ym.bullseye?NA="bullseye":Ee<=Ym.hit?NA="hit":Ee<=Ym.graze&&(NA="graze");const QA=T.current,PA=J.current;if(QA&&PA){const VA=PA.getBoundingClientRect(),KA=VA.width/2,Ie=VA.height-8,DA=q.current.x,IA=q.current.y;QA.setAttribute("x1",String(KA)),QA.setAttribute("y1",String(Ie)),QA.setAttribute("x2",String(DA)),QA.setAttribute("y2",String(IA));const EA=NA==="miss"?"#ff4d4d":NA==="graze"?"#ffa500":NA==="hit"?"#41e077":"#ffd700";QA.setAttribute("stroke",EA),QA.classList.add("active")}X[NA]>X[d.current]&&(d.current=NA),setTimeout(()=>{if(c(NA),NA!=="miss"){Br({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:q.current.x,y:q.current.y})}const VA=Q-1;h(VA);const KA=VA<=0||NA!=="miss";M.current?KA||setTimeout(O,1200):KA?setTimeout(()=>A(d.current),NA==="miss"?1500:2e3):setTimeout(O,1200)},250)},[r,A,Q,O,X]),wA=E.useRef(null),xA=E.useRef(lA);xA.current=lA,E.useEffect(()=>{if(!i||r||!k.current)return;const zA=String(Q);if(wA.current===zA)return;wA.current=zA;const ne=setTimeout(()=>{const Ee=q.current,NA=z.current,QA=(Math.random()-.5)*RO*1.8,PA=(Math.random()-.5)*RO*1.8;aA.current.x+=Ee.x-NA.x+QA,aA.current.y+=Ee.y-NA.y+PA},500),ye=setTimeout(()=>xA.current(),1400);return()=>{clearTimeout(ne),clearTimeout(ye)}},[i,r,D,Q]),E.useEffect(()=>{let zA=0,ne=performance.now();const ye=VA=>{const KA=VA,Ie=KA==null?void 0:KA.tagName;return Ie==="INPUT"||Ie==="TEXTAREA"||Ie==="SELECT"||!!(KA!=null&&KA.isContentEditable)},Ee=(VA,KA)=>{const Ie=sA.current;switch(VA){case"KeyW":case"ArrowUp":return Ie.up=KA,!0;case"KeyS":case"ArrowDown":return Ie.down=KA,!0;case"KeyA":case"ArrowLeft":return Ie.left=KA,!0;case"KeyD":case"ArrowRight":return Ie.right=KA,!0;default:return!1}},NA=()=>{const VA=performance.now(),KA=Math.min(.05,Math.max(0,(VA-ne)/1e3));if(ne=VA,!r){const Ie=sA.current,DA=(Ie.right?1:0)-(Ie.left?1:0),IA=(Ie.down?1:0)-(Ie.up?1:0);if(DA!==0||IA!==0){const EA=Math.sqrt(DA*DA+IA*IA)||1,j=aA.current;YA(j.x+DA/EA*RA*KA,j.y+IA/EA*RA*KA)}}zA=requestAnimationFrame(NA)},QA=VA=>{if(!ye(VA.target)){if(Ee(VA.code,!0)){VA.preventDefault();return}if(VA.code==="ShiftLeft"||VA.code==="ShiftRight"){VA.preventDefault(),VA.repeat||W();return}(VA.code==="Space"||VA.code==="Enter"||VA.code==="KeyF")&&(VA.preventDefault(),!VA.repeat&&!r&&lA())}},PA=VA=>{if(Ee(VA.code,!1)){VA.preventDefault();return}(VA.code==="ShiftLeft"||VA.code==="ShiftRight")&&(VA.preventDefault(),$())};return zA=requestAnimationFrame(NA),window.addEventListener("keydown",QA),window.addEventListener("keyup",PA),()=>{cancelAnimationFrame(zA),window.removeEventListener("keydown",QA),window.removeEventListener("keyup",PA),sA.current={up:!1,down:!1,left:!1,right:!1},$()}},[$,lA,r,YA,W]),E.useEffect(()=>{if(r||M.current)return;const zA=window.setInterval(()=>{if(k.current&&performance.now()-x.current>=Sv&&(window.clearInterval(zA),!r)){a(!0),c("miss");const ne=Q-1;h(ne),ne<=0?setTimeout(()=>A(d.current),1500):setTimeout(O,1200)}},100);return()=>window.clearInterval(zA)},[r,A,Q,O]);const HA=E.useCallback(()=>{G(!1);try{window.localStorage.setItem(QsA,"seen")}catch{}},[]);return E.useEffect(()=>{if(!N||D<OQ.length)return;const zA=window.setTimeout(HA,2e3);return()=>window.clearTimeout(zA)},[N,HA,D]),C.jsxs("div",{className:"zentara-sniper-overlay",ref:J,onPointerDown:tA,onPointerMove:iA,onPointerUp:oA,onPointerCancel:oA,style:{touchAction:"none",cursor:r?"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(qmA,{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:T,x1:"0",y1:"0",x2:"0",y2:"0"})}),y&&C.jsx("img",{src:PZ,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)/mv}`,"--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,"/",NO]}),C.jsxs("div",{className:"zentara-sniper-hud-block",ref:v,style:{color:t,borderColor:t},children:["⏱ ",(Sv/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 ▸ —"})}),!r&&C.jsxs(C.Fragment,{children:[C.jsx("div",{"data-no-global-haptic":!0,className:`zentara-sniper-pad-zone${n?" active":""}`,onPointerDown:CA,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:zA=>{zA.stopPropagation(),lA()},children:"FIRE"})]}),r&&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<OQ.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--${OQ[D].toLowerCase()}`,children:OQ[D]},D)}),N&&D>=OQ.length&&C.jsxs("div",{className:"zentara-sniper-coachmark",onClick:zA=>{zA.stopPropagation(),HA()},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"]})]})},C0e=2400,c0e=({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 a=!1;return fetch("/zentara/spy-strike/sniper-intro.mp4",{method:"HEAD"}).then(I=>{a||g(I.ok)}).catch(()=>{a||g(!1)}),()=>{a=!0}},[]),E.useEffect(()=>{tM({volume:.5})},[]);const r=()=>{o.current||(o.current=!0,i())};return E.useEffect(()=>{if(n)return;const a=window.setTimeout(r,C0e);return()=>window.clearTimeout(a)},[n]),C.jsx("div",{className:"zentara-sniper-intro",style:{"--group-color":t},onClick:r,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:r,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(qmA,{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"})]})})},l0e="/assets/breach-success-B5KvPAf1.webp",B0e="/assets/spy-exposed-j5AkCokU.webp",E0e=Object.assign({"../../assets/heroes/azure-sovereignty-t1.webp":R5,"../../assets/heroes/azure-sovereignty-t2.webp":G5,"../../assets/heroes/azure-sovereignty-t3.webp":b5,"../../assets/heroes/azure-sovereignty-t4.webp":U5,"../../assets/heroes/azure-sovereignty-t5.webp":v5,"../../assets/heroes/azure-sovereignty-t6.webp":K5,"../../assets/heroes/crimson-dominion-t1.webp":F5,"../../assets/heroes/crimson-dominion-t2.webp":_5,"../../assets/heroes/crimson-dominion-t3.webp":J5,"../../assets/heroes/crimson-dominion-t4.webp":L5,"../../assets/heroes/crimson-dominion-t5.webp":x5,"../../assets/heroes/crimson-dominion-t6.webp":T5,"../../assets/heroes/emerald-collective-t1.webp":q5,"../../assets/heroes/emerald-collective-t2.webp":Y5,"../../assets/heroes/emerald-collective-t3.webp":H5,"../../assets/heroes/emerald-collective-t4.webp":O5,"../../assets/heroes/emerald-collective-t5.webp":P5,"../../assets/heroes/emerald-collective-t6.webp":j5,"../../assets/heroes/golden-imperium-t1.webp":z5,"../../assets/heroes/golden-imperium-t2.webp":Z5,"../../assets/heroes/golden-imperium-t3.webp":W5,"../../assets/heroes/golden-imperium-t4.webp":V5,"../../assets/heroes/golden-imperium-t5.webp":X5,"../../assets/heroes/golden-imperium-t6.webp":$5,"../../assets/heroes/silver-pact-t1.webp":Az,"../../assets/heroes/silver-pact-t2.webp":ez,"../../assets/heroes/silver-pact-t3.webp":tz,"../../assets/heroes/silver-pact-t4.webp":iz,"../../assets/heroes/silver-pact-t5.webp":nz,"../../assets/heroes/silver-pact-t6.webp":gz,"../../assets/heroes/void-enclave-t1.webp":oz,"../../assets/heroes/void-enclave-t2.webp":sz,"../../assets/heroes/void-enclave-t3.webp":rz,"../../assets/heroes/void-enclave-t4.webp":az,"../../assets/heroes/void-enclave-t5.webp":Iz,"../../assets/heroes/void-enclave-t6.webp":Cz}),HmA={};var hrA;for(const[e,A]of Object.entries(E0e)){const t=(hrA=e.split("/").pop())==null?void 0:hrA.replace(".webp","");t&&(HmA[t]=A.default)}const vV=e=>e.trim().toLowerCase()==="you";function Q0e(e,A=!0){return vV(e)?A?"You":"you":e}function u0e(e,A){return vV(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 usA(e){return vV(e)?"your":/s$/i.test(e)?`${e}'`:`${e}'s`}function d0e(e){return e.charAt(0).toUpperCase()+e.slice(1)}const h0e=1500,p0e=2200;function dsA({player:e,role:A,align:t}){const i=e.heroId?HmA[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 hsA({attacker:e,defender:A}){return C.jsxs(C.Fragment,{children:[C.jsx(dsA,{player:e,role:"Operative",align:"left"}),C.jsx(dsA,{player:A,role:"Target",align:"right"})]})}const psA=({pendingEffect:e,attacker:A,defender:t,groupColor:i="#9d4edd",onPuzzleResult:n,onShotResult:g,botPilot:o=!1})=>{var d,p;const s=e.step??"puzzle",[r,a]=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"&&r==="puzzle-result"&&I&&a("sniper-intro")},[s,r,I]),E.useEffect(()=>{if(r!=="puzzle-result"||I===null||Q.current)return;const y=setTimeout(()=>{Q.current=!0,n(I)},h0e);return()=>clearTimeout(y)},[r,I,n]),E.useEffect(()=>{if(r!=="shot-result"||l===null||h.current)return;const y=setTimeout(()=>{h.current=!0,g(l)},p0e);return()=>clearTimeout(y)},[r,l,g]),E.useEffect(()=>{if(!o)return;let y=!1;const m=D=>new Promise(S=>setTimeout(S,D));return(async()=>{if(r==="intro"){if(await m(1800),y)return;a("puzzle");return}})(),()=>{y=!0}},[o,r]),r==="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("${lmA}")`},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(hsA,{attacker:A,defender:t}),C.jsxs("div",{className:"zentara-spystrike-body",children:[C.jsx("p",{children:u0e(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 ",usA(t.displayName)," hero"]})," + seize the entire group."]})]}),C.jsx("button",{className:"zentara-spystrike-cta",style:{background:i},onClick:()=>a("puzzle"),children:"BEGIN SOLDIER STRIKE →"})]})});if(r==="puzzle")return C.jsx(xmA,{attacker:A,defender:t,botPilot:o,skipBonus:!0,onComplete:y=>{const m=y.winnerId===A.id;c(m),a("puzzle-result")}});if(r==="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?l0e:B0e}")`},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(hsA,{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(r==="sniper-intro")return C.jsx(c0e,{attacker:A,defender:t,groupColor:i,onComplete:()=>a("sniper")});if(r==="sniper")return C.jsx(YmA,{defender:t,groupColor:i,botPilot:o,onComplete:y=>{B(y),a("shot-result")}});if(r==="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:d0e(usA(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:Q0e(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},f0e=(()=>{try{return ti.isNativePlatform()}catch{return!1}})(),b4="onb_zentara_v4",GO=[{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!"]}],y0e=({open:e,onClose:A})=>{const[t,i]=E.useState(0),[n,g]=E.useState(!1),[o,s]=E.useState(!1),r=E.useRef(null),a=GO.length,I=E.useCallback(()=>{nr.set({key:b4,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<a-1?c(t+1):I()},[t,a,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=r.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")&&(nr.set({key:b4,value:"1"}),setTimeout(A,0))}catch{}},[e,A]),!e)return null;const Q=GO[t],h=t===a-1,d=(t+1)/a*100;return C.jsxs("div",{className:"z-onb-vid",role:"dialog","aria-modal":"true","aria-label":"Zentara Tutorial",onClick:()=>{var p;(p=r.current)==null||p.play().catch(()=>{})},children:[C.jsx("video",{ref:r,className:"z-onb-vid__bg",src:Q.video,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"auto",controls:!1,onCanPlay:()=>{var p;(p=r.current)==null||p.play().catch(()=>{})},onError:()=>s(!0),onPlaying:()=>{setTimeout(()=>s(!0),f0e?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," / ",a]}),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:GO.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 D0e(){const[e,A]=E.useState(!1),[t,i]=E.useState(!1);return E.useEffect(()=>{(async()=>{try{const{value:n}=await nr.get({key:b4});A(n!=="1")}catch{A(!0)}i(!0)})()},[]),{showOnboardingVideo:e&&t,onboardingReady:t,dismissOnboardingVideo:()=>A(!1)}}const m0e="/assets/logo-Ds4ViVZo.webp",OmA={version:1,generatedAt:null,planets:{}};let pp=null,kv=null;function nk(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function S0e(){const e="".trim();return e?e.endsWith(".json")?e:`${e.replace(/\/$/,"")}/manifest.json`:"/zentara/planets/manifest.json"}function w0e(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 k0e(){return pp||(kv||(kv=fetch(S0e(),{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:w0e(n.imageUrl)}]));return pp={...A,planets:t},pp}).catch(()=>OmA).finally(()=>{kv=null})),kv)}function M0e(){const[e,A]=E.useState((pp==null?void 0:pp.planets)??OmA.planets);return E.useEffect(()=>{let t=!0;return k0e().then(i=>{t&&A(i.planets)}),()=>{t=!1}},[]),e}const PmA=/^#[0-9a-f]{3,8}$/i,bO=(e,A)=>e&&PmA.test(e)?e:A,fsA="/models/dice.glb";function N0e(e){const A=e!=null&&e.pieceColor&&PmA.test(e.pieceColor)?e.pieceColor:null;return A?`${fsA}?tint=${encodeURIComponent(A)}`:fsA}const Mv={start:qoA,planet:Wm,station:qoA,asteroid:OSe,nebula:WSe,wormhole:PSe,tax:YoA,"void-drain":YoA,jail:jSe,"go-to-jail":zSe,"free-parking":ZSe},R0e=he.lazy(()=>li(()=>Promise.resolve().then(()=>e0e),void 0)),G0e=new Set(["start","jail","go-to-jail","free-parking"]),b0e=3e3,U0e=1200,v0e=450,K0e=2400,F0e=700,UO=pB.FLIGHT_DURATION_MS/4,_0e=650,Fh=["/videos/space-conquest-1.mp4","/videos/space-conquest-2.mp4","/videos/planet-capture.mp4"],ysA=["/videos/team-destroyed-2.mp4","/videos/team-destroyed-1.mp4","/videos/team-destroyed-3.mp4"],J0e=20,U4=({players:e,localPlayerId:A,savedState:t,onSaveAndExit:i,multiplayerActions:n,multiplayerEvents:g,multiplayerPendingEffect:o,multiplayerPendingTrade:s,multiplayerRollTrigger:r,multiplayerRaidActivity:a,roomId:I,boardSize:c,autoplay:l=!1,botChatEnabled:B=!1,gameRules:Q})=>{var Ww,aC,KB,Qc,Iy,Cy,uc,Vw,FB;const h=Ji(),d=E.useRef(new Set),p=E.useRef((mA,JA)=>{const Me=globalThis.setTimeout(()=>{d.current.delete(Me),mA()},JA);return d.current.add(Me),Me}),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=Vge(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?r??0:m.rollTrigger,w=D?n:m.actions,b=E.useRef(w);b.current=w;const _=M0e(),{showAdNow:K,onZentaraTurnEnd:J,isAdShowing:T}=qf(),v=E.useRef(T);v.current=T;const U=Fa(),{showOnboardingVideo:x,onboardingReady:q,dismissOnboardingVideo:z}=D0e(),[Z,eA]=E.useState(null),[aA,sA]=E.useState(null),pA=E.useRef(null),gA=E.useCallback(()=>{try{Xt("Light")}catch{}},[]),yA=Cx();E.useEffect(()=>(yA.acquire(),()=>{yA.release()}),[yA]),E.useEffect(()=>()=>{try{tmA()}catch{}},[]),E.useEffect(()=>{var Ye;const mA=fA.current,JA=mA==null?void 0:mA.matchId;if(!JA)return;const Me=toe(k,mA,(mA==null?void 0:mA.board)??[],{roundNumber:mA==null?void 0:mA.roundNumber,phase:((Ye=mA==null?void 0:mA.currentTurn)==null?void 0:Ye.phase)??null});Xge(JA,"zentara",Me)},[k]),E.useEffect(()=>{var JA,Me;if(D)return;const mA=S==null?void 0:S.matchId;if(mA)return $ge(mA,"zentara",{name:"Zentara · SP",playerCount:((JA=S==null?void 0:S.players)==null?void 0:JA.length)??1,phase:((Me=S==null?void 0:S.currentTurn)==null?void 0:Me.phase)??null}),()=>{Aoe(mA)}},[D,S==null?void 0:S.matchId,(Ww=S==null?void 0:S.players)==null?void 0:Ww.length,(aC=S==null?void 0:S.currentTurn)==null?void 0:aC.phase]);const fA=E.useRef(S);fA.current=S,E.useEffect(()=>{if(D)return;const mA=()=>{const Ye=fA.current;Ye&&!Ye.finished&&yQA(Ye)},JA=()=>{document.visibilityState==="hidden"&&mA()};document.addEventListener("visibilitychange",JA);let Me;return(async()=>{try{const{App:Ye}=await li(async()=>{const{App:Ze}=await Promise.resolve().then(()=>UR);return{App:Ze}},void 0),He=await Ye.addListener("appStateChange",Ze=>{Ze.isActive||mA()});Me=()=>{try{He.remove()}catch{}}}catch{}})(),()=>{mA(),document.removeEventListener("visibilitychange",JA),Me==null||Me()}},[D]),E.useEffect(()=>(GvA(),()=>{nN()}),[]),E.useEffect(()=>(document.body.classList.add("page-zentara"),()=>{document.body.classList.remove("page-zentara")}),[]);const[RA,YA]=E.useState(null),[W,$]=E.useState(!1),[L,H]=E.useState(!1),[P,tA]=E.useState(!1),[iA,oA]=E.useState(!1),[CA,cA]=E.useState([]),[_A,uA]=E.useState(0),[X,O]=E.useState(null),lA=B&&!l&&!D,wA=E.useMemo(()=>lA?e.filter(mA=>mA.id!==A).map(mA=>({id:mA.id,name:mA.name})):[],[lA,e,A]),xA=E.useRef(!1),HA=E.useRef(null);Spe({enabled:lA,gameMode:"zentara",bots:wA,localPlayerId:A,requireHumanEngagement:!0,controlsRef:HA,getSituation:()=>{var Me,Ye;const mA=(Me=S==null?void 0:S.players)==null?void 0:Me.find(He=>{var Ze;return He.id===((Ze=S==null?void 0:S.currentTurn)==null?void 0:Ze.playerId)}),JA=((Ye=S==null?void 0:S.currentTurn)==null?void 0:Ye.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:()=>CA.slice(-8).map(mA=>{var JA;return{author:((JA=e.find(Me=>Me.id===mA.senderId))==null?void 0:JA.name)||"Bot",text:mA.text,senderId:mA.senderId}}),onMessage:mA=>{cA(JA=>{var He;if(JA.some(Ze=>Ze.id===mA.id))return console.log("[zentara-autoplay-chat] dropped duplicate id",mA.id),JA;const Me=8e3;return JA.some(Ze=>Ze.senderId===mA.senderId&&Ze.text===mA.text&&Math.abs(Ze.ts-mA.ts)<Me)?(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:((He=e.find(Ze=>Ze.id===mA.senderId))==null?void 0:He.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 zA=E.useRef(0);E.useEffect(()=>{if(!lA){zA.current=k.length;return}if(k.length<=zA.current){zA.current=k.length;return}const mA=k.slice(zA.current);zA.current=k.length;const JA=HA.current;if(!JA)return;const Me=He=>{var Ze;return He&&((Ze=S.players.find(ht=>ht.id===He))==null?void 0:Ze.displayName)||"someone"},Ye=He=>{var Ze;return((Ze=S.board[He])==null?void 0:Ze.name)??`planet ${He}`};for(const He of mA){let Ze=null;switch(He.type){case"buy":{const ht=He.cost??0;ht>=200&&(Ze=`${Me(He.playerId)} just captured ${Ye(He.tileId)} for ${ht} energy — a high-value pickup.`);break}case"upgrade":{const ht=He.level??0;ht>=3&&(Ze=`${Me(He.playerId)} just armed ${Ye(He.tileId)} to Arms Level ${ht}.`);break}case"strike":Ze=`${Me(He.playerId)} struck ${Ye(He.tileId)}.`;break;case"seizure":Ze=`${Me(He.attackerId)} seized ${Ye(He.tileId)} from ${Me(He.defenderId)}.`;break;case"hero-clash":{const ht=He.finalDamage??0;ht>=30&&(Ze=`Hero clash between ${Me(He.attackerId)} and ${Me(He.defenderId)} — ${ht} damage dealt.`);break}case"hero-vanquished":Ze=`${Me(He.vanquisherId)} vanquished ${Me(He.victimId)}'s hero!`;break;case"hero-restored":Ze=`${Me(He.playerId)}'s hero rejoined the fleet.`;break;case"raid":{const ht=He.creditsStolen??0;Ze=`Raid: ${Me(He.winnerId)} took ${ht} energy.`;break}case"spy-shot-result":{const ht=He.outcome,mi=Me(He.spyOwnerId),ji=Me(He.defenderId);ht==="bullseye"?Ze=`${mi}'s spy bullseyed ${ji}.`:ht==="hit"?Ze=`${mi}'s spy hit ${ji}.`:ht==="graze"?Ze=`${mi}'s spy grazed ${ji}.`:ht==="miss"&&(Ze=`${mi}'s spy missed ${ji}.`);break}case"bankrupt":Ze=`${Me(He.playerId)} just went bankrupt.`;break;case"win":Ze=`${Me(He.playerId)} just won the match!`;break}if(Ze){JA.notifyGameEvent(Ze);break}}},[k,lA,l,S.players,S.board]);const[ne,ye]=E.useState(!1),[Ee,NA]=E.useState(null),[QA,PA]=E.useState(!1),VA=E.useRef(0),KA=E.useRef(void 0),[Ie,DA]=E.useState(null),[IA,EA]=E.useState(void 0),j=E.useCallback(mA=>{EA(mA),b.current.upgradeProperty(mA)},[]),[dA,hA]=E.useState(!1),[UA,TA]=E.useState(null),[se,Ne]=E.useState(0),[Ke,At]=E.useState(50),ni=E.useRef(void 0),Ge=E.useCallback((mA,JA=1400)=>{TA(mA),Ne(Me=>Me+1),y.current(ni.current),ni.current=p.current(()=>TA(null),JA)},[]),[st,Rt]=E.useState("idle"),[Et,_t]=E.useState(void 0),[vt,xt]=E.useState(0),[ee,Oe]=E.useState(""),[We,pt]=E.useState(null),kA=E.useRef(void 0),oe=E.useRef(void 0),ae=E.useRef(void 0),[$A,nA]=E.useState(!1),[vA,FA]=E.useState(!1),[te,bA]=E.useState(!1),[De,jA]=E.useState(!1),me=E.useRef(!1),[le,qA]=E.useState(null),[WA,Se]=E.useState(null),[Qe,ce]=E.useState(null),[Ve,Dt]=E.useState(null),[Mt,ct]=E.useState(null),gt=E.useRef([]),et=E.useRef(Math.floor(Math.random()*Fh.length)),Li=200,Ri=1800,gi=400,Jt=E.useCallback((mA,JA=_0e)=>{mA&&p.current(mA,JA)},[]),jt=E.useCallback(mA=>{y.current(oe.current),y.current(ae.current),Se(null),nA(!1),FA(!1),me.current=!1,jA(!1),Rt("attack"),Oe(`⚔️ ${mA.attackerName} — Attack`),_t([mA.attackDice[0],mA.attackDice[1],0]),xt(JA=>JA+1),y.current(kA.current),kA.current=p.current(()=>{Rt("defense"),Oe(`🛡 ${mA.defenderName} — Defense`),_t([mA.defenseDice[0],mA.defenseDice[1],0]),xt(JA=>JA+1),kA.current=p.current(()=>{Rt("result"),Oe(""),_t(void 0),qA({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)},[]),Ci=E.useCallback((mA,JA,Me)=>{const Ye=mA.filter(Boolean);if(Ye.length){if(Qe){gt.current.push(...Ye),Jt(Me);return}gt.current=Ye.slice(1),Dt(JA??null),ce(Ye[0]),Jt(Me)}},[Qe,Jt]),Pi=E.useCallback(()=>{if(!le||me.current)return;me.current=!0,Rt("idle"),qA(null),jA(!1),pt(null);const mA=le.finalDamage;At(mA),mA<Li&&hA(!0),Ge(le.tileId,1200),Lc(),p.current(()=>Br(),400),mA>=100&&p.current(()=>Br(),700),mA>=250&&p.current(()=>Br(),1e3),mA>=400&&p.current(()=>Br(),1300),mA>=Li&&(y.current(Eo.current),Eo.current=p.current(()=>{const JA=(le==null?void 0:le.attackerName)??"Attacker",Me=(le==null?void 0:le.defenderName)??"Defender",Ye=`${JA} dealt ${mA} damage to ${Me}`;Ci(["/videos/fleet-ambush.mp4"],Ye)},1200))},[le,Ci]);E.useEffect(()=>{if(!l||st!=="result"||!le)return;const mA=p.current(()=>{Pi()},3500);return()=>y.current(mA)},[l,st,le,Pi]);const si=E.useCallback((mA,JA,Me)=>{const Ye=!!(Me!=null&&Me.manualRoll);if(pt(mA),Rt("intro"),nA(!1),FA(Ye),qA(null),_t(void 0),Oe(""),Se(JA),y.current(kA.current),y.current(oe.current),y.current(ae.current),Ye){oe.current=p.current(()=>{nA(!0)},Ri);return}oe.current=p.current(()=>{jt({...JA,attackHeroId:mA.atk.heroId,defendHeroId:mA.def.heroId})},Ri+gi)},[Ri,gi,jt]),pi=E.useCallback(()=>{!vA||!$A||!WA||!We||(y.current(oe.current),bA(!0),p.current(()=>{jt({...WA,attackHeroId:We.atk.heroId,defendHeroId:We.def.heroId}),bA(!1)},300))},[vA,$A,WA,We,jt]),[Ai,xi]=E.useState(null),[ui,ie]=E.useState(null),[ln,Zt]=E.useState(null),[lo,Hg]=E.useState(!1),xo=E.useRef(!1),Cg=E.useRef(!1),Dg=E.useRef(void 0),ng=E.useRef(void 0),[wo,fe]=E.useState(!1),[Pe,OA]=E.useState(null);E.useEffect(()=>{const mA=()=>{VA.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 XA=E.useCallback(()=>Date.now()-VA.current<v0e,[]),_e=E.useCallback(()=>{XA()||i==null||i()},[i,XA]);E.useEffect(()=>(window.__explode=(mA=(Me=>(Me=S.players[S.currentPlayerIndex])==null?void 0:Me.tileIndex)()??0,JA=100)=>{console.log("[EXPLOSION] 💥 tile",mA,"damage",JA),At(JA),Ge(mA,1400)},window.__fireLasers=window.__explode,window.__debugBlast=()=>fe(mA=>!mA),window.__testLasers=mA=>{const JA=S.properties,Me=JA.filter(mi=>mi.upgradeLevel>0);if(Me.length===0){console.warn("[LASERS] No upgraded turrets on the board — buy & upgrade a property first");return}const Ye=mA??(new Set(Me.map(ji=>ji.ownerId)),Me[0].tileId),He=JA.find(mi=>mi.tileId===Ye),Ze=He==null?void 0:He.ownerId,ht=Ze?Me.filter(mi=>mi.ownerId===Ze).length:0;console.log(`[LASERS] 🔫 Firing ${ht} turret beam(s) at tile ${Ye}`+(Ze?` (owner has ${ht} armed properties)`:" (unowned — no beams will render)")),At(200),Ge(Ye,2e3)},window.__raid=mA=>{var ht;const JA=S.players[S.currentPlayerIndex],Me=mA??(S.currentPlayerIndex+1)%S.players.length,Ye=S.players[Me];if(!JA||!Ye){console.warn("[RAID] invalid player indices");return}console.log(`[RAID] 🎯 ${Zi(JA.piece)} → ${Zi(Ye.piece)}`);const He=S.board[JA.tileIndex],Ze=(He==null?void 0:He.type)==="planet"?((ht=_[nk(He.name)])==null?void 0:ht.imageUrl)??Wm:Mv[(He==null?void 0:He.type)??"start"];xi({attacker:JA,defender:Ye,miniGame:"fps",tileImage:Ze})},window.__codebreaker=mA=>{const JA=S.players[S.currentPlayerIndex],Me=mA??(S.currentPlayerIndex+1)%S.players.length,Ye=S.players[Me];if(!JA||!Ye){console.warn("[CODEBREAKER] invalid player indices");return}console.log(`[CODEBREAKER] 🔓 ${Zi(JA.piece)} → ${Zi(Ye.piece)}`),xi({attacker:JA,defender:Ye,miniGame:"codebreaker"})},window.__soldier=(mA,JA,Me)=>{const Ye=S.players[S.currentPlayerIndex],He=mA??(S.currentPlayerIndex+1)%S.players.length,Ze=S.players[He];if(!Ye||!Ze){console.warn("[SOLDIER FPS] invalid player indices");return}const ht=S.board[Ye.tileIndex],mi=JA??(ht&&ht.type!=="planet"?ht.type:"station"),ji=Mv[mi];console.log(`[SOLDIER FPS] 🪖 ${Zi(Ye.piece)} → ${Zi(Ze.piece)} (bg=${mi}${Me?", no codebreaker":""})`),xi({attacker:Ye,defender:Ze,miniGame:"soldier-fps",tileImage:ji,skipBonus:!!Me})},window.__spystrike=(mA,JA,Me="puzzle")=>{var mi;const Ye=S.players[S.currentPlayerIndex],He=mA??(S.currentPlayerIndex+1)%S.players.length,Ze=S.players[He];if(!Ye||!Ze){console.warn("[SPY STRIKE] invalid player indices");return}const ht=JA??((mi=S.board.find(ji=>ji.type==="planet"&&ji.group))==null?void 0:mi.group)??"orion";console.log(`[SPY STRIKE] 🕵️ ${Zi(Ye.piece)} → ${Zi(Ze.piece)} (group: ${ht}, step: ${Me})`),ie({attacker:Ye,defender:Ze,group:ht,step:Me})},window.__sniper=(mA,JA)=>{var mi;const Me=S.players[S.currentPlayerIndex],Ye=mA??(S.currentPlayerIndex+1)%S.players.length,He=S.players[Ye];if(!Me||!He){console.warn("[SNIPER] invalid player indices");return}const Ze=JA??((mi=S.board.find(ji=>ji.type==="planet"&&ji.group))==null?void 0:mi.group),ht=Ze&&cs[Ze]||"#9d4edd";window.__sniperDebug!==!1&&(window.__sniperDebug=!0),console.log(`[SNIPER] 🎯 ${Zi(Me.piece)} → ${Zi(He.piece)} (color: ${ht}, debug: ${!!window.__sniperDebug})`),Zt({attacker:Me,defender:He,groupColor:ht,runKey:0})},window.__testHeroClash=(mA,JA,Me)=>{const Ye=mA??S.currentPlayerIndex,He=JA??(Ye+1)%S.players.length,Ze=S.players[Ye],ht=S.players[He];if(!Ze||!ht){console.warn("[HERO CLASH] invalid player indices");return}const mi=Ze.heroId?ys[Ze.heroId]:null,ji=ht.heroId?ys[ht.heroId]:null,is=Math.ceil(Math.random()*6),no=Math.ceil(Math.random()*6),br=is+no,Ts=Math.ceil(Math.random()*6),Pg=Math.ceil(Math.random()*6),ul=Ts+Pg,uo=mi?mu(mi.empire,mi.tier):{attack:0},Ca=ji?mu(ji.empire,ji.tier):{defense:0},IC=Math.min(uo.attack*br,3),CC=Math.min(Ca.defense*ul,.9),QQ=100,Ur=Math.round(QQ*(1+IC)),Wd=Math.max(1,Math.round(Ur*(1-CC))),_B=Me??Ze.tileIndex;console.log(`[HERO CLASH] ⚔️ ${Zi(Ze.piece)} (${(mi==null?void 0:mi.name)??"no hero"} T${(mi==null?void 0:mi.tier)??0}) 🎲${is}+${no}=${br} → atk ${(IC*100).toFixed(0)}% vs ${Zi(ht.piece)} (${(ji==null?void 0:ji.name)??"no hero"} T${(ji==null?void 0:ji.tier)??0}) 🎲${Ts}+${Pg}=${ul} → def ${(CC*100).toFixed(0)}% | base ${QQ} → boosted ${Ur} → final ${Wd}`),si({atk:Ze,def:ht},{attackerName:Zi(Ze.piece),defenderName:Zi(ht.piece),attackDice:[is,no],defenseDice:[Ts,Pg],attackBoostPct:Math.round(IC*100),defenseReducePct:Math.round(CC*100),baseDamage:QQ,finalDamage:Wd,tileId:_B},{manualRoll:!0})},window.__cutscene=(mA="victory",JA)=>{const Me=JA??null;if(mA==="destroyed"){Ci(ysA,Me??"Fleet destroyed!");return}if(mA==="ambush"){Ci(["/videos/fleet-ambush.mp4"],Me??"Fleet ambush!");return}if(mA==="conquest"||mA==="victory"){Ci(Fh,Me??"Victory!");return}if(mA.startsWith("/videos/")){Ci([mA],Me);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 Ye=S.players[S.currentPlayerIndex]??null,He=S.players.find(ht=>ht.id!==(Ye==null?void 0:Ye.id)&&!ht.depleted)??null,Ze=Ye?S.board[Ye.tileIndex]:null;ct({kind:mA,caption:JA??void 0,attacker:Ye,defender:He,groupColor:Ze!=null&&Ze.group?cs[Ze.group]??(Ye==null?void 0:Ye.pieceColor):Ye==null?void 0:Ye.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,Ci]);const[xe,rA]=E.useState(!1),[pe,Fe]=E.useState(!1),[je,$e]=E.useState("idle"),[Gt,Ot]=E.useState(null),[qt,ei]=E.useState(null),Yt=E.useRef(!1);E.useEffect(()=>()=>y.current(Ce.current),[]);const Ce=E.useRef(void 0),[it,dt]=E.useState(!1),ft=E.useRef(!1);E.useEffect(()=>{if(IA!=null){const mA=p.current(()=>EA(void 0),400);return()=>y.current(mA)}},[IA]);const ci=E.useRef(void 0),Hi=E.useRef(0),Wi=E.useRef(null);E.useEffect(()=>{if(!S.finished||Wi.current===S.matchId||Qe||Mt)return;const mA=p.current(()=>{Wi.current!==S.matchId&&(Wi.current=S.matchId,K({ignoreMinInterval:!0}).catch(()=>{}))},400);return()=>y.current(mA)},[S.matchId,S.finished,Qe,Mt,K]),E.useEffect(()=>{if(!l||!S.finished)return;const mA=p.current(()=>{try{A3()}catch{}const JA=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID().slice(0,8):Math.random().toString(36).slice(2,10),Ye=new URLSearchParams(window.location.search).get("bots"),He=Ye?`?autoplay=1&bots=${encodeURIComponent(Ye)}`:"?autoplay=1";h(`/zentara/match/${JA}${He}`,{replace:!0})},12e3);return()=>y.current(mA)},[l,S.finished,h]);const Vi=E.useCallback(mA=>{const JA=S.players.find(Me=>Me.id===mA);return JA?Zi(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<=Hi.current){Hi.current=k.length;return}const mA=k.slice(Hi.current);Hi.current=k.length;for(const JA of mA){const Me="playerId"in JA?JA.playerId:"payerId"in JA?JA.payerId:null,Ye=Me?Vi(Me):"Player",He=!Qe;switch(JA.type){case"move":"passedStart"in JA&&JA.passedStart&&He&&U.info(`${Ye} passed Command Base`,"+200 energy");break;case"buy":if(Me!==A&&!Qe){X6(),et.current=(et.current+1)%Fh.length;const Ze=S.board[JA.tileId],ht=Ze!=null&&Ze.group?cs[Ze.group]:void 0;Dt(C.jsxs(C.Fragment,{children:[C.jsx("span",{style:ht?{color:ht}:void 0,children:hi(JA.tileId)})," captured by ",Ye]})),ce(Fh[et.current])}else He&&U.info(`${Ye} captured ${hi(JA.tileId)}`,`-${JA.cost} energy`);break;case"energy-toll":{const Ze=Vi(JA.ownerId);He&&U.info(`${Ye} took damage!`,`-${JA.amount} energy · ${Ze} gained ✦${JA.amount}`);break}case"void-drain":He&&U.info(`${Ye} paid supply levy`,`-${JA.amount} energy`);break;case"card":He&&U.info(`${Ye} received intel`,JA.text),tM();break;case"jail":He&&U.info(`${Ye} entered cryosleep!`,JA.reason==="triple-doubles"?"Triple doubles":""),m8();break;case"jail-free":He&&U.info(`${Ye} woke from cryosleep`,JA.method==="pay"?"Paid wake-up fee":JA.method==="roll-doubles"?"Rolled doubles":"Used intel");break;case"upgrade":EA(JA.tileId),He&&U.info(`${Ye} armed ${hi(JA.tileId)}`,`Arms Level ${JA.level}`);break;case"depleted":Ci(ysA,`${Ye}'s fleet destroyed!`),Br();break;case"repossess":He&&U.info(`${Ye} lost ${hi(JA.tileId)}`,`+${JA.amount} energy (seized by command)`);break;case"sell":He&&U.info(`${Ye} sold ${hi(JA.tileId)}`,`+${JA.amount} energy`);break;case"debt-sell":He&&U.info(`${Ye} evacuated ${hi(JA.tileId)}`,`+${JA.amount} energy (debt recovery)`);break;case"debt-liquidate-arm":He&&U.info(`${Ye} liquidated arms at ${hi(JA.tileId)}`,`Arms Level ${JA.level} (+${JA.refund} energy)`);break;case"trade":{const Ze=Vi(JA.offererId),ht=Vi(JA.recipientId);He&&(JA.offererId===A?U.info("Trade accepted",`${ht} accepted your offer`):JA.recipientId===A?U.info("Trade completed",`You accepted ${Ze}'s offer`):U.info(`${Ze} traded with ${ht}`));break}case"trade-declined":{const Ze=Vi(JA.offererId),ht=Vi(JA.recipientId);He&&(JA.offererId===A?U.info("Trade declined",`${ht} declined your offer`):JA.recipientId===A&&U.info("Trade declined",`You declined ${Ze}'s offer`));break}case"upgrade-armor":He&&U.info(`${Ye} reinforced armor`,`Shield Level ${JA.level} (-${JA.cost} energy)`);break;case"upgrade-weapon":He&&U.info(`${Ye} upgraded weapons`,`Weapon Level ${JA.level} (-${JA.cost} energy)`),Lc();break;case"liquidate-armor":He&&Me!==A&&U.info(`${Ye} sold armor`,`Shield Level ${JA.level} (+${JA.refund} energy)`);break;case"liquidate-weapon":He&&Me!==A&&U.info(`${Ye} sold weapons`,`Weapon Level ${JA.level} (+${JA.refund} energy)`);break;case"strike":He&&U.info(`${Ye} struck ${hi(JA.tileId)}!`,`Arms reduced to Level ${JA.newLevel}`),Lc(),p.current(()=>Br(),300);break;case"hero-clash":{const Ze=Vi(JA.attackerId),ht=Vi(JA.defenderId),mi=JA.attackDice[0]+JA.attackDice[1],ji=JA.defenseDice[0]+JA.defenseDice[1],is=ys[JA.attackHeroId],no=ys[JA.defenseHeroId],br=is?mu(is.empire,is.tier).attack:0,Ts=no?mu(no.empire,no.tier).defense:0,Pg=Math.round(Math.min(br*mi/7,3)*100),ul=Math.round(Math.min(Ts*ji/7,.9)*100),uo=S.players.find(CC=>CC.id===JA.attackerId)??null,Ca=S.players.find(CC=>CC.id===JA.defenderId)??null,IC=JA.attackerId===A||JA.defenderId===A;uo&&Ca&&si({atk:uo,def:Ca},{attackerName:Ze,defenderName:ht,attackDice:JA.attackDice,defenseDice:JA.defenseDice,attackBoostPct:Pg,defenseReducePct:ul,baseDamage:JA.baseDamage,finalDamage:JA.finalDamage,tileId:JA.tileId},{manualRoll:IC});break}case"raid":{const Ze=Vi(JA.attackerId),ht=Vi(JA.defenderId),mi=Vi(JA.winnerId);He&&U.info(`${mi} won the raid!`,`Stole ✦${JA.creditsStolen} from ${JA.winnerId===JA.attackerId?ht:Ze}`);break}case"spy-shot-result":{const Ze=Vi(JA.spyOwnerId),ht=Vi(JA.defenderId),mi=(JA.group??"").toUpperCase();if(He)switch(JA.outcome){case"bullseye":U.info(`🎯 ${Ze}'s sniper — BULLSEYE`,`${ht}'s hero down · ${mi} group seized`);break;case"hit":U.info(`✅ ${Ze}'s sniper — CLEAN HIT`,`${ht}'s hero down · ${mi} group seized`);break;case"graze":U.info(`↘ ${Ze}'s sniper — GRAZING SHOT`,`${ht}'s hero down · ${mi} group seized`);break;case"miss":U.info(`❌ ${Ze}'s sniper — MISSED`,"Spy exposed · penalty + rent + hero clash");break}break}case"spy-plant":{const Ze=S.players.find(ht=>ht.id===JA.playerId)??null;ct({kind:"spy-plant",attacker:Ze,groupColor:cs[JA.group]??(Ze==null?void 0:Ze.pieceColor),caption:`${Ze?Zi(Ze.piece):Vi(JA.playerId)} deployed a covert asset`}),tM();break}case"win":{const Ze=S.players.find(ht=>ht.id===JA.playerId)??null;bvA(),Ci(Fh,`${Ze?Zi(Ze.piece):Vi(JA.playerId)} claims victory!`);break}}}},[k,A,Vi,hi,U,Qe,si,Ci,S.players]),E.useEffect(()=>()=>{y.current(kA.current),y.current(oe.current),y.current(ae.current)},[]);const Bo=E.useRef(!1);E.useEffect(()=>{if(S.currentTurn.phase!=="done"){Bo.current=!1;return}if(!(S.finished||!xe||Ai)&&!Bo.current){Bo.current=!0;try{J()}catch{}}},[S.currentTurn.phase,S.finished,xe,Ai,J]),E.useEffect(()=>{if(S.currentTurn.phase==="done"&&!S.finished&&xe&&!Ai&&!T&&!aA){if(y.current(ci.current),Cg.current){ci.current=p.current(()=>{Cg.current=!1,b.current.endTurn()},2e3);return}ci.current=p.current(()=>{b.current.endTurn()},b0e)}return()=>{y.current(ci.current)}},[S.currentTurn.phase,S.finished,xe,Ai,T,aA]);const Fn=E.useRef(void 0);E.useEffect(()=>{if(!(!xe||!S.pendingTeleport))return y.current(Fn.current),Fn.current=p.current(()=>{ft.current=!1,rA(!1),b.current.applyTeleport()},600),()=>{y.current(Fn.current)}},[xe,S.pendingTeleport]);const ea=E.useRef(void 0),ta=E.useRef(void 0);E.useEffect(()=>(xe||(y.current(ta.current),ta.current=p.current(()=>{ft.current=!0,rA(!0)},J0e*300+800)),()=>{y.current(ta.current)}),[xe]),E.useEffect(()=>{if(Ai){y.current(ng.current),Hg(!0);return}Hg(!1)},[Ai]),E.useEffect(()=>()=>{y.current(ng.current)},[]);const ia=E.useRef(!1),na=["Unfortified","Shield I","Shield II","Shield III","Shield IV","Fortress"];E.useEffect(()=>{var Ze;if(!xe){ia.current=!1;return}if(ia.current)return;ia.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 Me=S.properties.find(ht=>ht.tileId===JA.id),Ye=Me!=null&&Me.ownerId?S.players.find(ht=>ht.id===Me.ownerId):null;let He;if(Ye&&Ye.id===mA.id){const ht=Me.upgradeLevel,mi=na[ht]??"Unfortified",ji="⬢".repeat(ht)+"⬡".repeat(5-ht);He=`Your Territory · ${mi} ${ji}`}else if(Ye){const ht=Me.upgradeLevel,mi=na[ht]??"Unfortified",ji="⬢".repeat(ht)+"⬡".repeat(5-ht),is=(Ze=JA.rent)==null?void 0:Ze[ht];He=`Captured by ${Zi(Ye.piece)} · ${mi} ${ji}`+(is!=null?` · Damage ✦${is}`:"")+(Me.dormant?" · Decommissioned":"")}else JA.cost!=null?He=`Uncontrolled · Capture ✦${JA.cost}`:He={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("-"," ");Qe||U.info(`Landed on ${JA.name}!`,He)},[xe,S.players,S.currentPlayerIndex,S.board,S.properties,N,Qe]),E.useEffect(()=>{xo.current=!1},[M]),E.useEffect(()=>{var br,Ts,Pg,ul,uo;if(Ai||xo.current||!xe||S.finished||N)return;const mA=S.currentTurn.phase;if(mA!=="done"&&mA!=="pre-roll"||(xo.current=!0,(br=S.gameRules)!=null&&br.disableRaid))return;const JA=S.players[S.currentPlayerIndex];if(!JA||JA.depleted||JA.inJail)return;const Me=S.board[JA.tileIndex];if(!Me||G0e.has(Me.type))return;const Ye=S.players.find(Ca=>Ca.id!==JA.id&&!Ca.depleted&&!Ca.inJail&&Ca.tileIndex===JA.tileIndex);if(!Ye)return;const He=S.players.find(Ca=>Ca.id===A),Ze=He==null?void 0:He.piece,ht=JA.id===A||JA.id.startsWith("zentara_bot_")&&S.botControllerId===A;if(D&&!ht)return;if(l?!0:!!Ze&&Ze!==JA.piece&&Ze!==Ye.piece){if(l&&!D){const dQ=Me.type==="planet"?"fps":"soldier-fps",mG=Me.type==="planet"?((Ts=_[nk(Me.name)])==null?void 0:Ts.imageUrl)??Wm:Mv[Me.type];xi({attacker:JA,defender:Ye,miniGame:dQ,botPilot:!0,tileImage:mG});return}const IC=pfe(),CC=Math.floor(Math.random()*(IC+1)),QQ=_J(CC,IC,JA,Ye),Ur=QQ.winnerId,Wd=Ur===JA.id?Ye.id:JA.id,_B=QQ.creditsStolen;y.current(ng.current),Hg(!0),ng.current=p.current(()=>Hg(!1),K0e),_B>0&&(!D||ht)&&b.current.resolveRaid({attackerId:JA.id,defenderId:Ye.id,winnerId:Ur,creditsStolen:_B});const uQ=Zi(((Pg=S.players.find(dQ=>dQ.id===Ur))==null?void 0:Pg.piece)??"crimson-dominion"),DG=Zi(((ul=S.players.find(dQ=>dQ.id===Wd))==null?void 0:ul.piece)??"crimson-dominion");U.info(`${uQ} won the raid!`,`Stole ✦${_B} from ${DG}`),Cg.current=!0,y.current(Dg.current),Dg.current=p.current(()=>{Cg.current=!1},2e3);return}const ji=Me.type==="planet"?"fps":"soldier-fps",is=Me.type==="planet"?((uo=_[nk(Me.name)])==null?void 0:uo.imageUrl)??Wm:Mv[Me.type],no=Ye.id===A;xi(no?{attacker:Ye,defender:JA,miniGame:ji,tileImage:is}:{attacker:JA,defender:Ye,miniGame:ji,tileImage:is})},[xe,N,S.currentTurn.phase,S.finished,Ai,S.players,S.currentPlayerIndex,S.board,S.botControllerId,A,U,l,D,_]);const hI=E.useCallback(mA=>{var Ye,He;if(!Ai)return;const JA=(Ye=S.players[S.currentPlayerIndex])==null?void 0:Ye.id,Me=JA===A||!!(JA!=null&&JA.startsWith("zentara_bot_"))&&S.botControllerId===A;if(!D||Me){const Ze=(He=S.players[S.currentPlayerIndex])==null?void 0:He.id,ht=Ze?Ai.attacker.id===Ze?Ai.defender.id:Ai.attacker.id:Ai.defender.id;b.current.resolveRaid({attackerId:Ze,defenderId:ht,winnerId:mA.winnerId,creditsStolen:mA.creditsStolen,finalHits:mA.finalHits,totalSpawned:mA.totalSpawned,mode:Ai.miniGame==="soldier-fps"?"soldier":"space"})}p.current(()=>Br(),300),xi(null),Cg.current=!0,y.current(Dg.current),Dg.current=p.current(()=>{Cg.current=!1},2e3)},[Ai,S.players,S.currentPlayerIndex,S.botControllerId,A,D]),Eo=E.useRef(void 0);E.useEffect(()=>{var mA;if(!(S.currentTurn.phase!=="action"||!N||!xe||!ft.current)){if(N.action==="energy-toll"){const JA=N.amount??50,Me=S.players[S.currentPlayerIndex];return(()=>{console.log("[BLAST] Firing turret beams at tile",N.tileId,"damage",JA),At(JA),Ge(N.tileId,1200),JA<Li&&hA(!0),Lc(),p.current(()=>Br(),400),JA>=100&&p.current(()=>Br(),700),JA>=250&&p.current(()=>Br(),1e3),JA>=400&&p.current(()=>Br(),1300),JA>=Li?(y.current(Eo.current),Eo.current=p.current(()=>{const He=S.properties.find(ji=>ji.tileId===N.tileId),Ze=He!=null&&He.ownerId?S.players.find(ji=>ji.id===He.ownerId):null,ht=Ze?Zi(Ze.piece):"Enemy",mi=Me?Zi(Me.piece):"Fleet";Dt(`${ht} dealt ${JA} damage to ${mi}`),ce("/videos/fleet-ambush.mp4"),Jt(()=>b.current.payRent())},1200)):(y.current(Eo.current),Eo.current=p.current(()=>{b.current.payRent()},1400))})(),()=>{y.current(Eo.current),y.current(ni.current)}}else if(N.action==="void-drain")hA(!0),y.current(ea.current),ea.current=p.current(()=>b.current.payTax(),U0e);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(ea.current),y.current(Eo.current)}}},[S.currentTurn.phase,N,xe]);const[Og,cl]=E.useState(S),ga=E.useRef(M),[Od,lc]=E.useState(void 0),[ll,ry]=E.useState(1),[oa,Bl]=E.useState(!1),[Pd,vB]=E.useState(!1),[jd,ay]=E.useState(0),To=E.useRef(!1),pI=E.useRef(!1),Pw=E.useCallback(()=>{To.current=!0,pI.current=!0,Bl(!1)},[]);E.useEffect(()=>(window.__intro=()=>{console.log("[ZENTARA] Replaying fleet intro"),To.current=!1,pI.current=!0,vB(!1),ay(mA=>mA+1),Bl(!0)},()=>{delete window.__intro}),[]),E.useEffect(()=>{if(q){if(x){oa&&Bl(!1);return}l||To.current||pI.current||oa||Bl(!0)}},[q,x,l,oa]),E.useEffect(()=>{if(!oa){vB(!1);return}pI.current=!0,vB(!1);const mA=p.current(()=>vB(!0),700);return()=>y.current(mA)},[oa]),E.useEffect(()=>{if(oa||!l&&!pI.current)return;To.current||(To.current=!0,EA(0),lc(2));const mA=p.current(()=>lc(void 0),3500);return()=>y.current(mA)},[oa,l]);const{reveal:fI}=MB(),[sa,Nr]=E.useState(0),[ra,yI]=E.useState("idle"),Bc=E.useRef(M),sC=E.useRef(setTimeout(()=>{})),BA=E.useCallback(()=>{yI("charging"),tM({volume:.12})},[]),LA=E.useCallback(mA=>{Nr(mA),mA===0&&yI(JA=>JA==="charging"?"idle":JA)},[]),re=E.useCallback(()=>{Nr(0),yI("launch"),b.current.roll()},[]),ke=E.useRef(null),ue=E.useRef(!1);if(M!==ga.current){ga.current=M,ue.current=!0,ke.current=S,rA(!1),Fe(!1),dt(!0),y.current(Ce.current);const mA=Og.players[Og.currentPlayerIndex],JA=mA?Og.board[mA.tileIndex]:void 0;Ot((mA==null?void 0:mA.tileIndex)??null);const Me=mA?S.players.find(Ye=>Ye.id===mA.id):S.players[S.currentPlayerIndex];ei((Me==null?void 0:Me.tileIndex)??null),Yt.current=(mA==null?void 0:mA.inJail)===!0||(JA==null?void 0:JA.type)==="jail",Yt.current?$e("idle"):$e("liftoff")}E.useEffect(()=>{if(M!==ga.current){ga.current=M,rA(!1),Fe(!1),dt(!0);const mA=Og.players[Og.currentPlayerIndex];mA&&(EA(mA.tileIndex),Ot(mA.tileIndex)),ke.current=S}else ke.current?ke.current=S:cl(S)},[S,M]),E.useEffect(()=>{if(fI&&ke.current){const mA=ke.current,JA=p.current(()=>{ke.current=null,ue.current=!1,cl(mA)},1e3);return()=>y.current(JA)}},[fI]),E.useEffect(()=>{M!==Bc.current&&(Bc.current=M,y.current(sC.current),Nr(0),yI("launch"))},[M]);const Le=S.players[S.currentPlayerIndex],Te=(Le==null?void 0:Le.id)===A,rt=Ee!=null&&(N==null?void 0:N.action)==="buy-prompt"&&N.tileId===Ee;E.useEffect(()=>{Ee!=null&&((N==null?void 0:N.action)!=="buy-prompt"||N.tileId!==Ee)&&NA(null)},[N,Ee]);const Qt=S.players.find(mA=>mA.id===A),Bn=E.useMemo(()=>Qt?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,Qt,A]),gg=E.useMemo(()=>Qt?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)<=Qt.credits}).length:0,[S.properties,S.board,Qt,A]),Ln=E.useMemo(()=>{var ji,is;if(!Te||!Qt||Qt.depleted||(ji=S.gameRules)!=null&&ji.disableSpyStrike||N||S.currentTurn.phase==="in-debt"||(Qt.heroLockoutTurnsRemaining??0)>0)return null;const mA=S.board[Qt.tileIndex];if(!mA||mA.type!=="planet"||!mA.group)return null;const JA=mA.group,Me=S.spies;if(Me!=null&&Me[JA])return null;const Ye=S.siegeCooldowns,He=(Ye==null?void 0:Ye[JA])??0;if(S.roundNumber<He)return null;const Ze=S.board.filter(no=>no.group===JA).map(no=>no.id);if(Ze.length===0)return null;let ht=0;const mi=[];for(const no of Ze){const br=S.properties.find(Ts=>Ts.tileId===no);if(!(br!=null&&br.ownerId))return null;br.ownerId===A?ht+=1:mi.push(no)}if(ht===0){const no=(is=S.properties.find(Ts=>Ts.tileId===Ze[0]))==null?void 0:is.ownerId;return!no||no===A||!Ze.every(Ts=>S.properties.some(Pg=>Pg.tileId===Ts&&Pg.ownerId===no))||Qt.credits<Tp?null:{group:JA,cost:Tp}}return mi.length===0||Qt.credits<qp?null:{group:JA,cost:qp}},[D,Te,Qt,A,N,S]),og=(Ln==null?void 0:Ln.group)??null,ks=(Ln==null?void 0:Ln.cost)??Tp,to=E.useCallback(mA=>{!Qt||(Ln==null?void 0:Ln.group)!==mA||sA({factionName:Zi(Qt.piece),factionColor:bO(Qt.pieceColor,"#9d4edd"),group:mA,groupColor:cs[mA]??"#9d4edd",cost:Ln.cost})},[Qt,Ln]),xn=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]),En=E.useMemo(()=>S.winnerId?S.players.find(mA=>mA.id===S.winnerId)??null:null,[S.players,S.winnerId]),mg=E.useMemo(()=>{if(!En)return null;let mA=0;for(const Ye of S.properties.filter(He=>He.ownerId===En.id)){const He=S.board[Ye.tileId];mA+=(He==null?void 0:He.cost)??0,Ye.upgradeLevel>0&&(He!=null&&He.upgradeCost)&&(mA+=Ye.upgradeLevel*He.upgradeCost)}const JA=En.weaponLevel*un.weaponUpgradeCost,Me=En.armorLevel*un.armorUpgradeCost;return{credits:En.credits,propertyValue:mA,weaponValue:JA,armorValue:Me,total:Math.max(0,En.credits+mA+JA+Me)}},[En,S.properties,S.board]);roe({isMyTurn:Te,phase:S.currentTurn.phase,pendingEffect:N,pendingTrade:G,inJail:(Le==null?void 0:Le.inJail)??!1,credits:(Le==null?void 0:Le.credits)??0,botPlayerIds:xn,currentPlayerId:(Le==null?void 0:Le.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 Qo=E.useCallback(mA=>{const JA=S.board[mA]??null;YA(JA)},[S.board]),yi=fI&&!ue.current,fi=yi?S:Og,Di=fi.players[fi.currentPlayerIndex],Qn=RA??fi.board[(Di==null?void 0:Di.tileIndex)??0]??null,Fi=Qn?fi.properties.find(mA=>mA.tileId===Qn.id)??null:null,qo=Fi?fi.players.find(mA=>mA.id===Fi.ownerId)??null:null,Ec=qo?Zi(qo.piece):null,ar=qo?bO(qo.pieceColor,"#fff"):null,rC=E.useCallback(()=>{if(!N||ne)return;ye(!0),NA(N.tileId),KA.current&&y.current(KA.current),KA.current=p.current(()=>{ye(!1),KA.current=void 0},5e3),et.current=(et.current+1)%Fh.length;const mA=Fh[et.current],JA=S.players[S.currentPlayerIndex],Me=S.board[N.tileId],Ye=(Me==null?void 0:Me.name)??`Tile ${N.tileId}`,He=Me!=null&&Me.group?cs[Me.group]:void 0;Dt(JA?C.jsxs(C.Fragment,{children:[C.jsx("span",{style:He?{color:He}:void 0,children:Ye})," captured by ",Zi(JA.piece)]}):null),ce(mA),Jt(()=>b.current.buyProperty(N.tileId)),X6()},[N,S.players,S.currentPlayerIndex,ne,Jt]);E.useEffect(()=>{(S.currentTurn.phase!=="action"||(N==null?void 0:N.action)!=="buy-prompt")&&(ye(!1),KA.current&&(y.current(KA.current),KA.current=void 0))},[S.currentTurn.phase,N]);const Rr=E.useCallback(()=>{ne||((N==null?void 0:N.action)==="buy-prompt"&&NA(N.tileId),b.current.skipBuy())},[ne,N]),[io,El]=E.useState(void 0),BQ=E.useRef(M);E.useEffect(()=>{M!==BQ.current&&(BQ.current=M,El(void 0))},[M]),E.useEffect(()=>{const mA=S.currentTurn.diceValues;mA&&El([mA[0],mA[1],0])},[S.currentTurn.diceValues]);const aa=io;E.useEffect(()=>{!fI||!io||ra!=="launch"||(yI("impact"),Xl({volume:.05,rate:.85}),y.current(sC.current),sC.current=p.current(()=>{yI("idle"),sC.current=setTimeout(()=>{})},1400))},[fI,io,ra]);const Ql=st==="attack"||st==="defense",zd=Ql?vt:M,pG=Ql?Et:aa,jw=je!=="idle"&&qt!=null?qt:Di==null?void 0:Di.tileIndex,zw=jw!=null?fi.board[jw]??S.board[jw]??null:null,Zd=je==="liftoff"&&Gt!=null?fi.board[Gt]??zw:zw,DI=(Zd==null?void 0:Zd.type)??"start",EQ=Zd,Zw=(EQ==null?void 0:EQ.type)==="planet"?_[nk(EQ.name)]??null:null,fG=(Qn==null?void 0:Qn.type)==="planet"?_[nk(Qn.name)]??null:null,Ia=RA?S.properties.find(mA=>mA.tileId===RA.id)??null:null,Gr=Ia?(()=>{const mA=S.players.find(JA=>JA.id===Ia.ownerId);return mA?Zi(mA.piece):null})():null,yG=!l&&!x&&!To.current&&!pI.current;if(q&&oa&&!x||!q&&yG){const mA=q&&oa;return C.jsx("div",{className:"zentara-screen","data-intro-active":"true",children:mA&&C.jsx(Bfe,{players:S.players,skipEnabled:Pd,onComplete:Pw},jd)})}return C.jsxs("div",{className:"zentara-screen","data-tile-type":DI,"data-pieces-moving":it&&!xe||void 0,"data-ship-bg-phase":je,"data-cutscene-active":Qe||Mt?"true":void 0,"data-raid-active":lo?"true":void 0,"data-raid-mini":Ai?"true":void 0,style:Zw?{"--zentara-tile-bg":`url("${Zw.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",{})]})]}),lo&&!Ai&&!Qe&&!Mt&&C.jsx("video",{className:"zentara-raid-bg-video",src:"/videos/empire-strike.mp4",autoPlay:!0,muted:!0,playsInline:!0,loop:!0,preload:"auto"}),a&&!Ai&&C.jsxs("div",{className:"zentara-raid-live",role:"status","aria-live":"polite",children:[C.jsx("div",{className:"zentara-raid-live__label",children:a.status==="complete"?"RAID COMPLETE":"LIVE RAID"}),C.jsxs("strong",{children:[((KB=S.players.find(mA=>mA.id===a.attackerId))==null?void 0:KB.displayName)??"Attacker"," vs ",((Qc=S.players.find(mA=>mA.id===a.defenderId))==null?void 0:Qc.displayName)??"Defender"]}),C.jsxs("span",{children:[a.hits," hits · ",a.totalSpawned>0?Math.round(a.hits/a.totalSpawned*100):0,"% accuracy"]}),C.jsx("div",{className:"zentara-raid-live__track",children:C.jsx("i",{style:{width:`${Math.min(100,a.elapsedMs/a.durationMs*100)}%`}})})]}),Qe&&C.jsx(Hpe,{src:Qe,onEnd:()=>{const mA=gt.current.shift();if(mA){ce(mA);return}ce(null),Dt(null)}}),Qe&&Ve&&C.jsx("div",{className:"zentara-cutscene-caption zentara-cutscene-caption--top",children:Ve}),Mt&&zr.createPortal(C.jsx(nfe,{...Mt,onEnd:()=>ct(null)}),document.body),C.jsx("img",{src:m0e,alt:"Zentara",className:"zentara-game-logo"}),C.jsxs("div",{className:"zentara-main-row",children:[C.jsx("div",{className:"zentara-player-col",children:C.jsx(Vhe,{players:S.players,properties:S.properties,tiles:S.board,currentPlayerId:(Le==null?void 0:Le.id)??"",localPlayerId:A,onSaveAndExit:i?_e:void 0,roomId:I,onAvatarClick:mA=>{DA(mA);const JA=S.players.find(Me=>Me.id===mA);JA&&EA(JA.tileIndex)},onUpgradeProperty:j,upgradeableCount:gg})}),C.jsx("div",{className:"zentara-board-col",children:C.jsxs("div",{className:"zentara-board-area",children:[C.jsx(mse,{gameState:Og,onTileClick:Qo,zoomOverride:Od,onPieceArrival:()=>{if(ft.current=!0,rA(!0),Fe(!1),Ot(null),y.current(Ce.current),Yt.current?$e("idle"):($e("landing"),Ce.current=p.current(()=>{$e("idle"),ei(null)},F0e)),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 Me=JA.tileIndex;mA[Me%mA.length]!==JA.piece&&(At(80),Lc(),p.current(()=>Br(),200),Ge(Me,1400))}}},onPieceMoveStart:()=>{Fe(!0),y.current(Ce.current);const mA=Og.players[Og.currentPlayerIndex];mA&&ei(mA.tileIndex),Yt.current?$e("idle"):($e("liftoff"),Ce.current=p.current(()=>{$e("warp"),Ce.current=p.current(()=>{$e("warp-exit"),Ce.current=p.current(()=>{Ot(null),$e("landing")},UO)},UO)},UO))},onZoomChange:ry,focusTileIndex:IA,toggleZoomRef:pA,laserBeamTile:UA,laserBeamSeq:se,blastDamage:Ke,suppressDarkOverlay:!!Qe||!!Mt||lo}),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(npe,{players:Og.players,currentPlayerId:((Iy=Og.players[Og.currentPlayerIndex])==null?void 0:Iy.id)??"",properties:Og.properties,tiles:Og.board,onTileClick:EA})}),C.jsxs("div",{className:`zentara-dice-center zentara-dice-center--${ra}`,"data-roll-phase":ra,style:{"--player-color":bO(Le==null?void 0:Le.pieceColor,"#fff"),"--roll-charge":sa},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=st==="attack"&&We?We.atk:st==="defense"&&We?We.def:Le,JA=N0e(mA);return C.jsx(imA,{isWaiting:!1,rollTrigger:zd,results:pG,chargeLevel:Ql?0:sa,gameMode:"craps",feltColor:"transparent",shimmerColor:"#7ec8f0",diceModels:[JA,JA]})})(),!Ql&&Te&&(ra==="charging"||ra==="launch")&&C.jsxs("div",{className:"zentara-roll-status","aria-live":"polite",children:[C.jsx("span",{className:"zentara-roll-status__eyebrow",children:ra==="charging"?"COMMAND LINK":"VECTOR CAST"}),C.jsx("strong",{children:ra==="charging"?`${Math.max(1,Math.round(sa*100))}%`:"ROLLING"})]}),(st==="attack"||st==="defense")&&ee&&C.jsx("div",{className:"zentara-clash-roll-label",children:ee})]})]})}),st==="intro"&&We&&zr.createPortal(C.jsxs("div",{className:`zentara-clash-intro-overlay${vA?" zentara-clash-intro-overlay--manual-roll":""}${te?" zentara-clash-intro-overlay--closing":""}`,children:[C.jsxs("div",{className:"zentara-clash-intro-side zentara-clash-intro-side--left",style:{"--clash-faction-color":zu[We.atk.piece]},children:[We.atk.heroId&&lE[We.atk.heroId]?C.jsx("img",{className:"zentara-clash-intro-portrait",src:lE[We.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:Zi(We.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[We.def.piece]},children:[We.def.heroId&&lE[We.def.heroId]?C.jsx("img",{className:"zentara-clash-intro-portrait zentara-clash-intro-portrait--flip",src:lE[We.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:Zi(We.def.piece)})]}),vA&&C.jsx("button",{className:"zentara-btn zentara-btn--primary zentara-clash-intro-roll-btn",onClick:pi,disabled:!$A,children:$A?"⚔️ Hero Roll Dice":"⚔️ Preparing Clash..."})]}),document.body),st==="result"&&le&&(()=>{const mA=le.attackDice[0]+le.attackDice[1],JA=le.defenseDice[0]+le.defenseDice[1],Me=mA>JA,Ye=Me?le.attackHeroId:le.defendHeroId,He=Me?le.attackBoostPct:le.defenseReducePct,Ze=Me?"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:Pi,children:C.jsxs("div",{className:"zentara-clash-result-panel",onClick:ht=>ht.stopPropagation(),children:[C.jsx("div",{className:"zentara-clash-result-title",children:"⚔️ Hero Clash Result"}),Ye&&lE[Ye]&&C.jsxs("div",{className:"zentara-clash-result-hero-display",children:[C.jsx("img",{className:"zentara-clash-result-hero-image",src:lE[Ye],alt:"Winner Hero"}),C.jsxs("div",{className:"zentara-clash-result-hero-impact",children:[C.jsx("div",{className:"zentara-clash-result-hero-impact-label",children:Ze}),C.jsxs("div",{className:"zentara-clash-result-hero-impact-value",children:["+",He,"%"]})]})]}),C.jsxs("div",{className:`zentara-clash-result-row zentara-clash-result-row--attack ${Me?"active":"inactive"}`,children:[C.jsx("span",{className:"zentara-clash-result-icon",children:"⚔️"}),C.jsxs("span",{className:"zentara-clash-result-name",children:[le.attackerName,Me?" 🏆":""]}),C.jsxs("span",{className:"zentara-clash-result-dice",children:["🎲 ",le.attackDice[0]," + ",le.attackDice[1]," = ",mA]}),C.jsxs("span",{className:"zentara-clash-result-pct",children:["+",le.attackBoostPct,"% boost"]})]}),C.jsxs("div",{className:`zentara-clash-result-row zentara-clash-result-row--defense ${Me?"inactive":"active"}`,children:[C.jsx("span",{className:"zentara-clash-result-icon",children:"🛡"}),C.jsxs("span",{className:"zentara-clash-result-name",children:[le.defenderName,Me?"":" 🏆"]}),C.jsxs("span",{className:"zentara-clash-result-dice",children:["🎲 ",le.defenseDice[0]," + ",le.defenseDice[1]," = ",JA]}),C.jsxs("span",{className:"zentara-clash-result-pct",children:["−",le.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:["✦",le.finalDamage]}),C.jsx("button",{className:"zentara-clash-calc-toggle",onClick:ht=>{ht.stopPropagation(),jA(!De)},children:"i"}),De&&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:["✦",le.baseDamage]})]}),C.jsxs("div",{className:"zentara-clash-calculation-row zentara-clash-calculation-row--boost",children:[C.jsxs("span",{children:["+ Attack Boost (",le.attackBoostPct,"%)"]}),C.jsxs("span",{children:["+✦",Math.round(le.baseDamage*le.attackBoostPct/100)]})]}),C.jsxs("div",{className:"zentara-clash-calculation-row zentara-clash-calculation-row--block",children:[C.jsxs("span",{children:["- Defense Block (",le.defenseReducePct,"%)"]}),C.jsxs("span",{children:["−✦",Math.round(le.baseDamage*le.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:["✦",le.finalDamage]})]})]})]})})]}),C.jsx("div",{className:"zentara-clash-result-continue",onClick:Pi,children:"Click to continue…"})]})})]})})(),wo&&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: ",Ke," ",C.jsxs("span",{style:{opacity:.5},children:["(scale ",Math.min(3,Math.max(.35,Ke/100)).toFixed(2),"×)"]}),C.jsx("input",{type:"range",min:2,max:1500,step:1,value:Ke,onChange:mA=>At(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 Me;At(mA);const JA=Number(((Me=document.getElementById("__blast-tile"))==null?void 0:Me.value)??0);Ge(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);Ge(mA,1200)},style:{padding:"4px 10px",fontSize:12,background:"#2563eb",color:"#fff",border:"none",borderRadius:4,cursor:"pointer"},children:"Fire 💥"}),C.jsx("button",{onClick:()=>fe(!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(mpA,{roomId:I,singlePlayer:!I})}),C.jsxs("div",{className:`zentara-sidebar ${QA?"zentara-sidebar--folded":""}`,"data-moving":!xe||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:!Qt||Qt.depleted,onClick:()=>{gA(),$(!0)},children:"Trade"}),C.jsxs("button",{onClick:()=>{XA()||(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(),!XA()&&(gA(),w.saveGame(),_e())},children:"Save & Exit"})]}),C.jsx("button",{type:"button",className:"zentara-sidebar__toggle",onClick:()=>{gA(),PA(!QA)},title:QA?"Expand":"Fold","aria-label":QA?"Expand sidebar":"Fold sidebar",children:QA?"◀":"▶"}),Te&&C.jsx("div",{className:"zentara-your-turn",children:"Your Turn"}),xe&&C.jsx(Yhe,{tile:Qn,property:Fi,ownerName:Ec,ownerColor:ar,planetContent:fG,onClick:()=>{gA(),Qn&&YA(Qn)}}),Te&&S.currentTurn.phase==="pre-roll"&&Qt&&C.jsxs("div",{className:"zentara-ship-upgrade-row",children:[C.jsxs("button",{className:"zentara-menu-btn zentara-menu-btn--ship",disabled:Qt.armorLevel>=un.maxArmorLevel||Qt.credits<un.armorUpgradeCost,onClick:()=>{gA(),OA("armor")},children:[C.jsx("span",{className:"ship-btn__icon",children:"🛡"}),C.jsxs("span",{className:"ship-btn__label",children:["Armor ",Qt.armorLevel,"/",un.maxArmorLevel]}),C.jsxs("span",{className:"ship-btn__cost",children:[un.armorUpgradeCost,"c"]})]}),C.jsxs("button",{className:"zentara-menu-btn zentara-menu-btn--ship",disabled:Qt.weaponLevel>=un.maxWeaponLevel||Qt.credits<un.weaponUpgradeCost,onClick:()=>{gA(),OA("weapon")},children:[C.jsx("span",{className:"ship-btn__icon",children:"🚀"}),C.jsxs("span",{className:"ship-btn__label",children:["Weapons ",Qt.weaponLevel,"/",un.maxWeaponLevel]}),C.jsxs("span",{className:"ship-btn__cost",children:[un.weaponUpgradeCost,"c"]})]}),Qt.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(un.armorUpgradeCost/2),"c"]})]}),Qt.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(un.weaponUpgradeCost/2),"c"]})]})]}),Pe&&Qt&&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:[Pe==="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 ",Qt.armorLevel," → ",Qt.armorLevel+1]}),C.jsxs("p",{className:"zentara-ship-confirm__desc",children:["Each armor level reduces incoming hull damage by 15%. At level ",Qt.armorLevel+1,", you'll absorb ",C.jsxs("strong",{children:[(Qt.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:[un.armorUpgradeCost," energy"]})]}),C.jsxs("p",{className:"zentara-ship-confirm__balance",children:["Balance after: ",Qt.credits-un.armorUpgradeCost," energy"]})]}):Pe==="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 ",Qt.weaponLevel," → ",Qt.weaponLevel+1]}),C.jsx("p",{className:"zentara-ship-confirm__desc",children:Qt.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:[un.weaponUpgradeCost," energy"]})]}),C.jsxs("p",{className:"zentara-ship-confirm__balance",children:["Balance after: ",Qt.credits-un.weaponUpgradeCost," energy"]})]}):Pe==="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 ",Qt.armorLevel," → ",Qt.armorLevel-1]}),C.jsxs("p",{className:"zentara-ship-confirm__desc",children:["Downgrade armor by one level. You'll lose 15% damage reduction (",Qt.armorLevel*15,"% → ",(Qt.armorLevel-1)*15,"%)."]}),C.jsxs("p",{className:"zentara-ship-confirm__cost",children:["Refund: ",C.jsxs("strong",{children:[Math.floor(un.armorUpgradeCost/2)," energy"]})]}),C.jsxs("p",{className:"zentara-ship-confirm__balance",children:["Balance after: ",Qt.credits+Math.floor(un.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 ",Qt.weaponLevel," → ",Qt.weaponLevel-1]}),C.jsx("p",{className:"zentara-ship-confirm__desc",children:Qt.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(un.weaponUpgradeCost/2)," energy"]})]}),C.jsxs("p",{className:"zentara-ship-confirm__balance",children:["Balance after: ",Qt.credits+Math.floor(un.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 ${Pe.startsWith("liquidate")?"zentara-ship-confirm__btn--sell":"zentara-ship-confirm__btn--confirm"}`,onClick:()=>{gA(),Pe==="armor"?w.upgradeArmor():Pe==="weapon"?w.upgradeWeapon():Pe==="liquidate-armor"?(w.liquidateArmor(),U.info(`${Vi(A)} sold armor`,`Shield Level ${Qt.armorLevel-1} (+${Math.floor(un.armorUpgradeCost/2)} energy)`)):(w.liquidateWeapon(),U.info(`${Vi(A)} sold weapons`,`Weapon Level ${Qt.weaponLevel-1} (+${Math.floor(un.weaponUpgradeCost/2)} energy)`)),OA(null)},children:Pe.startsWith("liquidate")?"Confirm Sale":"Confirm Upgrade"})]})]})}),C.jsx("div",{className:"zentara-sidebar-spacer"}),C.jsx(_he,{phase:yi&&xe?S.currentTurn.phase:yi?"landed":"rolling",pendingEffect:yi&&xe?N:null,suppressBuyPrompt:rt,buyInProgress:ne,tileOwnedByMe:!!((N==null?void 0:N.tileId)!=null&&S.properties.some(mA=>mA.tileId===N.tileId&&mA.ownerId===A)),isMyTurn:Te,inJail:(Le==null?void 0:Le.inJail)??!1,onRoll:re,onRollPressStart:BA,onRollChargeChange:LA,onBuy:rC,onSkipBuy:Rr,onPayRent:w.payRent,onHeroClashRoll:w.heroClashRoll,onPayTax:w.payTax,onResolveCard:w.resolveCard,onPayBail:w.payBailAction,onPlantSpy:to,plantSpyEligibleGroup:og,plantSpyCost:ks,onArmPlanets:()=>oA(!0),credits:((Cy=S.players.find(mA=>mA.id===A))==null?void 0:Cy.credits)??0,upgradeableCount:gg,armableCount:Bn})]})]}),C.jsx(Phe,{tile:RA,property:Ia,ownerName:Gr,isOwnedByMe:(Ia==null?void 0:Ia.ownerId)===A,canAffordUpgrade:!!((RA==null?void 0:RA.upgradeCost)!=null&&Ia&&(((uc=S.players.find(mA=>mA.id===A))==null?void 0:uc.credits)??0)>=RA.upgradeCost&&Ia.upgradeLevel<Hm(A,RA.id,S.board,S.properties)),onClose:()=>YA(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||!Ia||Ia.ownerId===A||Ia.upgradeLevel<=0)return null;const mA=S.board.filter(Me=>Me.group===RA.group).map(Me=>Me.id),JA=S.properties.filter(Me=>mA.includes(Me.tileId)&&Me.ownerId===A&&!Me.dormant).length;return JA<=0?null:RA.upgradeCost*(mA.length-JA+1)})(),credits:((Vw=S.players.find(mA=>mA.id===A))==null?void 0:Vw.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:fG}),C.jsx(vpe,{player:Ie?S.players.find(mA=>mA.id===Ie)??null:null,properties:S.properties,tiles:S.board,isCurrentPlayer:Ie===(Le==null?void 0:Le.id),onClose:()=>DA(null),onTileClick:mA=>{YA(S.board[mA]??null),DA(null)}}),iA&&C.jsx(gmA,{playerId:A,credits:((FB=S.players.find(mA=>mA.id===A))==null?void 0:FB.credits)??0,properties:S.properties,board:S.board,onUpgrade:j,onClose:()=>oA(!1)}),C.jsx(rpe,{open:W&&!!Qt||!!G&&G.recipient.playerId===A,mode:G&&G.recipient.playerId===A?"review":"propose",localPlayer:Qt??Le,players:S.players,properties:S.properties,tiles:S.board,pendingTrade:G,onPropose:(mA,JA,Me,Ye,He)=>{var ht;const Ze=((ht=Qt??Le)==null?void 0:ht.id)??A;w.proposeTrade(Ze,mA,JA,Me,Ye,He),$(!1)},onAccept:()=>{w.acceptTrade(),$(!1)},onDecline:()=>{w.declineTrade(),$(!1)},onClose:()=>$(!1)}),S.currentTurn.phase==="in-debt"&&Te&&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:["✦",(Le==null?void 0:Le.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 Me=Math.floor(JA.cost/2),Ye=JA.upgradeCost?Math.floor(JA.upgradeCost/2):0,He=JA.group?cs[JA.group]:void 0;return C.jsxs("div",{className:"zentara-debt-prop-row",children:[C.jsxs("div",{className:"zentara-debt-prop-info",children:[He&&C.jsx("span",{className:"zentara-debt-prop-dot",style:{"--prop-color":He}}),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 +✦",Ye]}),C.jsxs("button",{className:"zentara-debt-sell-btn",onClick:()=>w.debtSell(mA.tileId),disabled:mA.upgradeLevel>0,children:["Sell Planet +✦",Me]})]})]},mA.tileId)})}),C.jsx("button",{className:"zentara-debt-done-btn",onClick:()=>w.debtResolve(),disabled:((Le==null?void 0:Le.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&&!Qe&&!Mt&&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:[En?Zi(En.piece):"Unknown"," claims victory!"]}),C.jsxs("div",{className:"zentara-win-total",children:["Total Net Worth: ✦",(mg==null?void 0:mg.total)??(En==null?void 0:En.credits)??0]}),mg&&C.jsxs("div",{className:"zentara-win-breakdown",children:[C.jsxs("span",{children:["⚡ Energy: ✦",mg.credits]}),mg.propertyValue>0&&C.jsxs("span",{children:["🌍 Planets: ✦",mg.propertyValue]}),mg.weaponValue>0&&C.jsxs("span",{children:["🚀 Weapons: ✦",mg.weaponValue]}),mg.armorValue>0&&C.jsxs("span",{children:["🛡 Armor: ✦",mg.armorValue]})]}),C.jsxs("div",{className:"zentara-win-actions",children:[C.jsx("button",{className:"zentara-win-btn zentara-win-btn--primary",onClick:()=>{A3();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(aEA,{gameMode:"zentara"})})]}),Z&&C.jsx(Qfe,{deck:Z.deck,text:Z.text,amount:Z.amount,rollerName:Le?Zi(Le.piece):"Unknown Fleet",rollerColor:(Le==null?void 0:Le.pieceColor)??"#888",onDismiss:()=>{eA(null),b.current.resolveCard()},autoDismissMs:Z.autoDismissMs}),aA&&C.jsx(ufe,{...aA,onConfirm:()=>{b.current.plantSpy(aA.group),sA(null)},onCancel:()=>sA(null)}),Ai&&Ai.miniGame==="fps"&&C.jsx(bmA,{attacker:Ai.attacker,defender:Ai.defender,onComplete:hI,tileBackgroundImage:Ai.tileImage,botPilot:!!Ai.botPilot,onProgress:D?mA=>{var JA,Me;return(Me=(JA=b.current).reportRaidProgress)==null?void 0:Me.call(JA,{attackerId:Ai.attacker.id,defenderId:Ai.defender.id,...mA})}:void 0}),Ai&&Ai.miniGame==="codebreaker"&&C.jsx(UmA,{attacker:Ai.attacker,defender:Ai.defender,onComplete:hI}),Ai&&Ai.miniGame==="soldier-fps"&&C.jsx(he.Suspense,{fallback:null,children:C.jsx(R0e,{attacker:Ai.attacker,defender:Ai.defender,onComplete:hI,botPilot:!!Ai.botPilot,tileBackgroundImage:Ai.tileImage,skipBonus:!!Ai.skipBonus})}),(N==null?void 0:N.action)==="spy-clash"&&(xe||l)&&(N.spyOwnerId===A||l)&&(()=>{const mA=S.players.find(He=>He.id===N.spyOwnerId),JA=S.players.find(He=>He.id===N.defenderId);if(!mA||!JA)return null;const Me=S.board[N.tileId],Ye=l&&N.spyOwnerId!==A;return zr.createPortal(C.jsx(psA,{pendingEffect:N,attacker:mA,defender:JA,groupColor:Me!=null&&Me.group?cs[Me.group]??"#9d4edd":"#9d4edd",onPuzzleResult:He=>{var Ze;return(Ze=w.spyPuzzleResult)==null?void 0:Ze.call(w,He)},onShotResult:He=>{var Ze;return(Ze=w.spyShotResult)==null?void 0:Ze.call(w,He)},botPilot:Ye}),document.body)})(),ui&&(()=>{var JA;const mA={tileId:((JA=S.board.find(Me=>Me.group===ui.group))==null?void 0:JA.id)??0,action:"spy-clash",group:ui.group,spyOwnerId:ui.attacker.id,defenderId:ui.defender.id,step:ui.step};return C.jsx(psA,{pendingEffect:mA,attacker:ui.attacker,defender:ui.defender,groupColor:cs[ui.group]??"#9d4edd",onPuzzleResult:Me=>{console.log(`[SPY STRIKE DEBUG] puzzle result: ${Me?"PASS → advancing to shot":"FAIL"}`),Me?ie(Ye=>Ye&&{...Ye,step:"shot"}):p.current(()=>ie(null),1800)},onShotResult:Me=>{console.log(`[SPY STRIKE DEBUG] shot result: ${Me}`),p.current(()=>ie(null),1800)}})})(),ln&&C.jsxs(C.Fragment,{children:[C.jsx(YmA,{defender:ln.defender,groupColor:ln.groupColor,onComplete:mA=>{console.log(`[SNIPER DEBUG] outcome: ${mA}`),p.current(()=>Zt(null),1500)}},ln.runKey),C.jsxs("div",{className:"zentara-sniper-debug-toolbar",children:[C.jsx("button",{type:"button",className:"zentara-sniper-debug-btn",onClick:()=>Zt(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:()=>Zt(null),children:"✕ CLOSE"})]})]}),C.jsx(y0e,{open:x,onClose:z}),dA&&!Qe&&!Mt&&C.jsx("div",{className:"zentara-laser-flash",onAnimationEnd:()=>hA(!1)}),C.jsx(Ipe,{players:S.players,properties:S.properties,tiles:S.board,currentPlayerId:(Le==null?void 0:Le.id)??"",open:L,onClose:()=>H(!1)}),C.jsx(cpe,{open:P,onClose:()=>tA(!1),roomId:I,localPlayerId:A,players:S.players,injectedMessages:lA?CA:void 0,onLocalSend:lA&&!l?mA=>{var JA;cA(Me=>Me.some(Ye=>Ye.id===mA.id)?Me:[...Me,mA]),(JA=HA.current)==null||JA.notifyHumanMessage(mA.text)}:void 0}),lA&&C.jsx(Bpe,{latest:X,players:S.players,onOpen:()=>tA(!0),hidden:P})]})},zi={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 Nv(){return crypto.randomUUID()}function DsA(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 msA(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 L0e(e){const A=Ss(),{meId:t,user:i}=en(),n=t??(i==null?void 0:i.id),{info:g}=LL(),[o,s]=E.useState(null),[r,a]=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),DsA(A,zi.GET_STATE,{roomId:e,eventId:Nv()}).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:msA(X.state.pendingEffect),board:$F(X.state.boardSize).tiles};for(const lA of O.players)lA.armorLevel==null&&(lA.armorLevel=0),lA.weaponLevel==null&&(lA.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 HA,zA;console.log("[Zentara] STATE_UPDATE received",{phase:wA.state.currentTurn.phase,currentPlayerIdx:wA.state.currentPlayerIndex,pendingEffect:(HA=wA.state.pendingEffect)==null?void 0:HA.action,playersCount:wA.state.players.length});const xA={...wA.state,pendingEffect:msA(wA.state.pendingEffect),board:$F(wA.state.boardSize).tiles};for(const ne of xA.players)ne.armorLevel==null&&(ne.armorLevel=0),ne.weaponLevel==null&&(ne.weaponLevel=0);s(xA),(zA=wA.events)!=null&&zA.length&&(a(ne=>[...ne,...wA.events]),wA.events.some(ne=>ne.type==="roll")&&B(ne=>ne+1))},_A=wA=>{c(wA.trade),y.current=wA.trade},uA=wA=>{const xA=y.current,HA=!!xA&&xA.id===wA.tradeId,zA=wA.offererId??(HA?xA.offerer.playerId:void 0),ne=wA.recipientId??(HA?xA.recipient.playerId:void 0),ye=zA===n,Ee=ne===n;wA.accepted?ye&&g("Trade accepted","Your offer was accepted"):ye?g("Trade declined","Your offer was declined"):Ee&&g("Trade declined","You declined the offer"),HA&&(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(zi.STATE_UPDATE,cA),A.on(zi.TRADE_PROPOSED,_A),A.on(zi.TRADE_RESOLVED,uA),A.on(zi.GAME_OVER,X),A.on(zi.RAID_PROGRESS,O);const lA=wA=>{D(xA=>({...xA,[wA.playerId]:wA.piece}))};return A.on(zi.PIECE_SELECTED,lA),()=>{console.log("[Zentara] Cleaning up socket listeners for room",e),A.off(zi.STATE_UPDATE,cA),A.off(zi.TRADE_PROPOSED,_A),A.off(zi.TRADE_RESOLVED,uA),A.off(zi.GAME_OVER,X),A.off(zi.RAID_PROGRESS,O),A.off(zi.PIECE_SELECTED,lA)}},[A,e,n,g]);const k=E.useCallback((cA,_A)=>{A!=null&&A.connected&&A.emit(cA,{roomId:e,eventId:Nv(),..._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 DsA(A,zi.START_MATCH,{roomId:e,players:cA,boardSize:_A,eventId:Nv()});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(zi.SELECT_PIECE,{roomId:e,piece:cA,eventId:Nv()})},[A,e]),M=E.useCallback(()=>k(zi.ROLL),[k]),w=E.useCallback(cA=>k(zi.BUY,{tileId:cA}),[k]),b=E.useCallback(()=>k(zi.SKIP_BUY),[k]),_=E.useCallback(()=>k(zi.PAY_RENT),[k]),K=E.useCallback(()=>k(zi.HERO_CLASH_ROLL),[k]),J=E.useCallback(()=>k(zi.PAY_TAX),[k]),T=E.useCallback(()=>k(zi.RESOLVE_CARD),[k]),v=E.useCallback(()=>k(zi.APPLY_TELEPORT),[k]),U=E.useCallback(()=>k(zi.PAY_BAIL),[k]),x=E.useCallback(()=>k(zi.END_TURN),[k]),q=E.useCallback(cA=>k(zi.UPGRADE,{tileId:cA}),[k]),z=E.useCallback(cA=>k(zi.MORTGAGE,{tileId:cA}),[k]),Z=E.useCallback(cA=>k(zi.SELL,{tileId:cA}),[k]),eA=E.useCallback(cA=>k(zi.SABOTAGE,{tileId:cA}),[k]),aA=E.useCallback(cA=>k(zi.DEBT_SELL,{tileId:cA}),[k]),sA=E.useCallback(cA=>k(zi.DEBT_LIQUIDATE_ARM,{tileId:cA}),[k]),pA=E.useCallback(()=>k(zi.DEBT_RESOLVE),[k]),gA=E.useCallback(()=>{},[]),yA=E.useCallback(()=>{},[]),fA=E.useCallback((cA,_A,uA,X,O)=>{k(zi.PROPOSE_TRADE,{recipientId:cA,offererPropertyIds:_A,offererCredits:uA,recipientPropertyIds:X,recipientCredits:O})},[k]),RA=E.useCallback(()=>{const cA=y.current;cA&&k(zi.ACCEPT_TRADE,{tradeId:cA.id})},[k]),YA=E.useCallback(()=>{const cA=y.current;cA&&k(zi.DECLINE_TRADE,{tradeId:cA.id})},[k]),W=E.useCallback(()=>k(zi.UPGRADE_ARMOR,{}),[k]),$=E.useCallback(()=>k(zi.UPGRADE_WEAPON,{}),[k]),L=E.useCallback(()=>k(zi.LIQUIDATE_ARMOR,{}),[k]),H=E.useCallback(()=>k(zi.LIQUIDATE_WEAPON,{}),[k]),P=E.useCallback(cA=>{k(zi.RESOLVE_RAID,cA??{})},[k]),tA=E.useCallback(cA=>{k(zi.RAID_PROGRESS,cA)},[k]),iA=E.useCallback(cA=>k(zi.PLANT_SPY,{group:cA}),[k]),oA=E.useCallback(cA=>k(zi.SPY_PUZZLE_RESULT,{success:cA}),[k]),CA=E.useCallback(cA=>k(zi.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:r.length}:{ts:Date.now(),roomId:e,meId:t??null,phase:null,finished:!1,players:[]})},[o,r.length,e,t]),{gameState:o,events:r,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:T,goToJail:gA,payBailAction:U,endTurn:x,skipBuy:b,upgradeProperty:q,mortgageProperty:z,sellProperty:Z,sabotageProperty:eA,debtSell:aA,debtLiquidateArm:sA,debtResolve:pA,proposeTrade:fA,acceptTrade:RA,declineTrade:YA,saveGame:yA,applyTeleport:v,upgradeArmor:W,upgradeWeapon:$,liquidateArmor:L,liquidateWeapon:H,resolveRaid:P,reportRaidProgress:tA,plantSpy:iA,spyPuzzleResult:oA,spyShotResult:CA}}}const x0e=({roomId:e})=>{var x;const{user:A,meId:t}=en(),i=Ji(),[n]=dw(),{room:g,joinRoom:o,leaveRoom:s}=tI(),{gameState:r,events:a,pendingEffect:I,pendingTrade:c,rollTrigger:l,raidActivity:B,connected:Q,takenPieces:h,piecesMap:d,selectPiece:p,startMatch:y,actions:m}=L0e(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}=lz(),_=E.useCallback(q=>{N(q),p(q)},[p]),K=E.useCallback(()=>{var q;(q=s==null?void 0:s(e))==null||q.catch(()=>{}),i("/zentara")},[s,e,i]);E.useEffect(()=>{!e||w.current===e||(w.current=e,o(e).catch(q=>console.warn("[Zentara] joinRoom failed",q)))},[e,o]);const J=he.useMemo(()=>g!=null&&g.players?g.players.map(q=>({id:q.id||q.playerId||q.userId,name:q.displayName||q.name||q.username||"Player",avatarUrl:q.avatarUrl||void 0})):[],[g==null?void 0:g.players]),T=((x=g==null?void 0:g.players)==null?void 0:x[0])&&g.players[0].id===t,v=E.useCallback(async()=>{if(D||!T||J.length<2||!k)return;S(!0);const q=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(q,G),S(!1)},[D,T,J,y,k,t,d,b,G]);if(!r)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: ",oB[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"]}),T&&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(q=>C.jsxs("div",{className:"zentara-match-player-item",children:[q.name," ",q.id===t?"(you)":""]},q.id))}),C.jsx("button",{onClick:K,className:"zentara-match-back-btn",children:"Back"}),C.jsx(kpA,{roomId:e,gameMode:"zentara"}),T&&J.length>=2&&C.jsx(C.Fragment,{children:C.jsx("div",{className:"zentara-match-size-selector",children:["standard","full"].map(q=>C.jsx("button",{onClick:()=>M(q),className:`zentara-match-size-btn zentara-match-size-btn--compact ${G===q?"zentara-match-size-btn--active":""}`,children:q==="standard"?"Standard (20 tiles)":"Full (40 tiles)"},q))})}),!Q&&C.jsx("div",{className:"zentara-match-reconnect-notice",children:"Reconnecting..."})]}):C.jsx(bQA,{taken:h,onSelect:_,bestHeroForEmpire:b,onBack:K});const U=r.players.map(q=>({id:q.id,name:q.displayName}));return C.jsx(U4,{players:U,localPlayerId:t,savedState:r,onSaveAndExit:K,multiplayerActions:m,multiplayerEvents:a,multiplayerPendingEffect:I,multiplayerPendingTrade:c,multiplayerRollTrigger:l,multiplayerRaidActivity:B,roomId:e},e)},T0e=["Rival","Nemesis","Warden","Phantom","Tyrant","Specter","Vortex","Hydra","Onyx","Ravager","Cipher","Hex","Eclipse","Talon","Vanguard","Reaper","Wraith","Sable","Khaos","Drake"],vO=["crimson-dominion","silver-pact","azure-sovereignty","golden-imperium","emerald-collective","void-enclave"],q0e=({matchId:e})=>{const A=Ji(),[t]=dw(),i=t.get("autoplay")==="1",n=t.get("qm")==="1",[g,o]=E.useState(null),[s,r]=E.useState(!1),[a,I]=E.useState(!1),[c,l]=E.useState(null),[B,Q]=E.useState("standard"),[h,d]=E.useState(!1),{bestHeroForEmpire:p}=lz(),y=he.useMemo(()=>[...vO.filter(G=>G!==c)].sort(()=>Math.random()-.5),[c]),m=he.useMemo(()=>[...T0e].sort(()=>Math.random()-.5),[e]),D=he.useMemo(()=>{if(!i)return null;const N=parseInt(t.get("bots")??"",10),G=Number.isFinite(N)?Math.max(2,Math.min(vO.length,N)):5,M=[...vO].sort(()=>Math.random()-.5).slice(0,G),w=["Vega","Orion","Lyra","Rigel","Nova","Cygnus"];return M.map((b,_)=>{const K=e3(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(()=>{Wo().then(N=>{o(Math.max(1,Math.min(5,N.zentaraBotCount??Qs.zentaraBotCount??1))),r(!!N.zentaraDisableRaid),I(!!N.zentaraDisableSpyStrike)}).catch(()=>o(Qs.zentaraBotCount??1))},[]),i&&D)return C.jsx(U4,{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(bQA,{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],_=e3(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(U4,{players:k,localPlayerId:"local-p1",savedState:S,onSaveAndExit:()=>A("/lobby"),boardSize:S?void 0:B,botChatEnabled:n,gameRules:{disableRaid:s,disableSpyStrike:a}},e)},$S=()=>{const{matchId:e,roomId:A}=uw(),[t]=dw(),i=A||t.get("roomId");return i?C.jsx(x0e,{roomId:i}):C.jsx(q0e,{matchId:e})},Y0e=E.lazy(()=>li(()=>import("./TurretPreview--d2p2lLC.js"),__vite__mapDeps([14,1])));E.lazy(()=>li(()=>import("./ShipPackPreview-DSd-Jms-.js"),__vite__mapDeps([15,1,16])));function H0e(){const e=Ji(),A=ms();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),aI()},[e]),E.useEffect(()=>{aI(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 r=document.getElementById("root");r&&(r.scrollTop=0,r.style.removeProperty("overflow"),r.style.removeProperty("overflow-y"));const a=document.querySelector(".home-fixed-root");a&&(a.scrollTop=0,a.style.removeProperty("overflow"),a.style.removeProperty("overflow-y"),a.style.removeProperty("height"),a.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(we,{element:C.jsx(xf,{}),children:[C.jsx(we,{path:"/verify",element:C.jsx(zf,{})}),C.jsx(we,{path:"/review-login",element:C.jsx(Zf,{})}),C.jsx(we,{path:"/qa-login",element:C.jsx(Wf,{})}),C.jsx(we,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(we,{path:"/add-chips",element:C.jsx(jf,{})}),C.jsxs(we,{element:C.jsx(vf,{}),children:[C.jsx(we,{path:"/profile",element:C.jsx(Yf,{})}),C.jsx(we,{path:"/player/:playerId",element:C.jsx(Hf,{})}),C.jsx(we,{path:"/messages",element:C.jsx(Of,{})}),C.jsx(we,{path:"/settings",element:C.jsx(Pf,{})}),C.jsx(we,{path:"/admin",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/lobby",element:C.jsx(Lf,{})}),C.jsx(we,{path:"/room/:roomId",element:C.jsx($R,{})}),C.jsx(we,{path:"/poker",element:C.jsx(xZ,{})}),C.jsx(we,{path:"/poker/mock",element:C.jsx(TZ,{})}),C.jsx(we,{path:"/poker/room/:roomId",element:C.jsx(LZ,{})}),C.jsx(we,{path:"/zentara",element:C.jsx(Fg,{to:"/",replace:!0})}),C.jsx(we,{path:"/zentara/match/:matchId",element:C.jsx($S,{})}),C.jsx(we,{path:"/zentara/room/:roomId",element:C.jsx($S,{})})]}),C.jsx(we,{path:"/disclaimer",element:C.jsx(Vf,{})}),C.jsx(we,{path:"/support",element:C.jsx(Xf,{})}),C.jsx(we,{path:"/privacy",element:C.jsx($f,{})}),C.jsx(we,{path:"/terms",element:C.jsx(Ay,{})}),C.jsx(we,{path:"/button-sandbox",element:C.jsx(AG,{})}),C.jsx(we,{path:"/how-to-play",element:C.jsx(Ud,{})}),C.jsx(we,{path:"/turret-preview",element:C.jsx(E.Suspense,{fallback:null,children:C.jsx(Y0e,{})})}),C.jsx(we,{path:"/ship-pack-preview",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"*",element:C.jsx(Fg,{to:"/lobby",replace:!0})})]})}function O0e(){const e=Ji(),A=ms();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),aI()},[e]),E.useEffect(()=>{aI(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(we,{element:C.jsx(xf,{}),children:[C.jsx(we,{path:"/verify",element:C.jsx(zf,{})}),C.jsx(we,{path:"/review-login",element:C.jsx(Zf,{})}),C.jsx(we,{path:"/qa-login",element:C.jsx(Wf,{})}),C.jsx(we,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(we,{path:"/add-chips",element:C.jsx(jf,{})}),C.jsxs(we,{element:C.jsx(vf,{}),children:[C.jsx(we,{path:"/profile",element:C.jsx(Yf,{})}),C.jsx(we,{path:"/player/:playerId",element:C.jsx(Hf,{})}),C.jsx(we,{path:"/messages",element:C.jsx(Of,{})}),C.jsx(we,{path:"/settings",element:C.jsx(Pf,{})}),C.jsx(we,{path:"/admin",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/lobby",element:C.jsx(Lf,{})}),C.jsx(we,{path:"/room/:roomId",element:C.jsx($R,{})})]}),C.jsx(we,{path:"/disclaimer",element:C.jsx(Vf,{})}),C.jsx(we,{path:"/support",element:C.jsx(Xf,{})}),C.jsx(we,{path:"/privacy",element:C.jsx($f,{})}),C.jsx(we,{path:"/terms",element:C.jsx(Ay,{})}),C.jsx(we,{path:"/button-sandbox",element:C.jsx(AG,{})}),C.jsx(we,{path:"/how-to-play",element:C.jsx(Ud,{})}),C.jsx(we,{path:"*",element:C.jsx(Fg,{to:"/lobby",replace:!0})})]})}function P0e(){const e=Ji(),A=ms();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),aI()},[e]),E.useEffect(()=>{aI(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(we,{element:C.jsx(xf,{}),children:[C.jsx(we,{path:"/verify",element:C.jsx(zf,{})}),C.jsx(we,{path:"/review-login",element:C.jsx(Zf,{})}),C.jsx(we,{path:"/qa-login",element:C.jsx(Wf,{})}),C.jsx(we,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(we,{path:"/add-chips",element:C.jsx(jf,{})}),C.jsxs(we,{element:C.jsx(vf,{}),children:[C.jsx(we,{path:"/profile",element:C.jsx(Yf,{})}),C.jsx(we,{path:"/player/:playerId",element:C.jsx(Hf,{})}),C.jsx(we,{path:"/messages",element:C.jsx(Of,{})}),C.jsx(we,{path:"/settings",element:C.jsx(Pf,{})}),C.jsx(we,{path:"/admin",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/lobby",element:C.jsx(Lf,{})}),C.jsx(we,{path:"/room/:roomId",element:C.jsx($R,{})})]}),C.jsx(we,{path:"/disclaimer",element:C.jsx(Vf,{})}),C.jsx(we,{path:"/support",element:C.jsx(Xf,{})}),C.jsx(we,{path:"/privacy",element:C.jsx($f,{})}),C.jsx(we,{path:"/terms",element:C.jsx(Ay,{})}),C.jsx(we,{path:"/button-sandbox",element:C.jsx(AG,{})}),C.jsx(we,{path:"/how-to-play",element:C.jsx(Ud,{})}),C.jsx(we,{path:"*",element:C.jsx(Fg,{to:"/lobby",replace:!0})})]})}function j0e(){const e=Ji(),A=ms();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),aI()},[e]),E.useEffect(()=>{aI(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(we,{element:C.jsx(xf,{}),children:[C.jsx(we,{path:"/verify",element:C.jsx(zf,{})}),C.jsx(we,{path:"/review-login",element:C.jsx(Zf,{})}),C.jsx(we,{path:"/qa-login",element:C.jsx(Wf,{})}),C.jsx(we,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(we,{path:"/add-chips",element:C.jsx(jf,{})}),C.jsxs(we,{element:C.jsx(vf,{}),children:[C.jsx(we,{path:"/profile",element:C.jsx(Yf,{})}),C.jsx(we,{path:"/player/:playerId",element:C.jsx(Hf,{})}),C.jsx(we,{path:"/messages",element:C.jsx(Of,{})}),C.jsx(we,{path:"/settings",element:C.jsx(Pf,{})}),C.jsx(we,{path:"/admin",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/lobby",element:C.jsx(Lf,{})}),C.jsx(we,{path:"/poker",element:C.jsx(xZ,{})}),C.jsx(we,{path:"/poker/mock",element:C.jsx(TZ,{})})]}),C.jsx(we,{path:"/disclaimer",element:C.jsx(Vf,{})}),C.jsx(we,{path:"/support",element:C.jsx(Xf,{})}),C.jsx(we,{path:"/privacy",element:C.jsx($f,{})}),C.jsx(we,{path:"/terms",element:C.jsx(Ay,{})}),C.jsx(we,{path:"/button-sandbox",element:C.jsx(AG,{})}),C.jsx(we,{path:"/how-to-play",element:C.jsx(Ud,{})}),C.jsx(we,{path:"/poker/room/:roomId",element:C.jsx(LZ,{})}),C.jsx(we,{path:"*",element:C.jsx(Fg,{to:"/poker",replace:!0})})]})}const v4=ahe(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 jmA({letters:e,onSubmit:A,disabled:t,cellSize:i=64,onTap:n,feedback:g,shakeKey:o,botTrail:s}){var T;const r=e.length,a=((T=e[0])==null?void 0:T.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&&Xl({volume:.6});for(let q=1;q<s.path.length;q++)U.push(window.setTimeout(()=>{h(q),x&&Xl({volume:.6})},q*v));return U.push(window.setTimeout(()=>h(-1),s.path.length*v+900)),()=>{U.forEach(q=>window.clearTimeout(q))}},[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),q=Math.abs(v.c-U.c);return x<=1&&q<=1&&!(x===0&&q===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 q=x.getBoundingClientRect(),z=q.width/a,Z=q.height/r,eA=(v-q.left)/z,aA=(U-q.top)/Z,sA=Math.floor(eA),pA=Math.floor(aA);if(pA<0||pA>=r||sA<0||sA>=a)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]),Xl({volume:.3}),Xt("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(q=>q.slice(0,-1)),Xt("Light"));return}y(U,v)?(c(q=>[...q,v]),Xl({volume:.3}),Xt("Light"),n==null||n(v)):(c(q=>{const z=[...q];let Z=z[z.length-1];const eA=r+a;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}),Xl({volume:.3}),Xt("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)&&(Xt("Medium"),A(I)),S())},b=(a-1)*3,_=(r-1)*3,K=`min(calc((100vw - 48px - ${b}px) / ${a}), calc((100vh - 180px - ${_}px) / ${r}), calc((100dvh - 180px - ${_}px) / ${r}), ${i}px)`,J=E.useMemo(()=>({gridTemplateColumns:`repeat(${a}, ${K})`,gridTemplateRows:`repeat(${r}, ${K})`,touchAction:"none"}),[a,r,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,q)=>{const z=D({r:U,c:q}),Z=z>=0,eA=p({r:U,c:q}),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}-${q}`)}))}),g&&C.jsxs("span",{className:["skillsPointsBubble",g.points>=25?"skillsPointsBubble--big":""].join(" "),style:{left:`${(g.col+.5)/a*100}%`,top:`${(g.row+.5)/r*100}%`},children:["+",g.points]},g.nonce)]},o?`wrap-${o}`:"wrap")}function z0e({letters:e,foundWords:A,onSubmit:t,disabled:i,myScore:n=0}){const[g,o]=E.useState(""),[s,r]=E.useState([]),[a,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);r(s.slice(0,m)),o(D=>D.slice(0,m))}else r([...s,p]),o(m=>m+e[p]);I(null)},h=()=>{r([]),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&&(r(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&&(r(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"})}),a&&C.jsx("div",{className:"anagrams-error",children:a})]}),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 Z0e({questions:e,currentQuestionIndex:A,onAnswer:t,myAnswers:i={},disabled:n,myScore:g=0}){const[o,s]=E.useState(null),[r,a]=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),a(!1)},[A]);const p=async D=>{n||r||h||(s(D),a(!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),a(!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||r||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:SsA})]}):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:SsA})]})}const SsA=`
    .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); }
    }
`,W0e={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:"🧠"}]},V0e=[{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 X0e({open:e,onClose:A,gameMode:t="wordsearch"}){const[i,n]=E.useState(0),g=[...W0e[t],...V0e],o=g.length,s=E.useCallback(()=>{nr.set({key:`skillsOnboarding_${t}`,value:"1"}),n(0),A()},[A,t]),r=E.useCallback(()=>{i<o-1?n(B=>B+1):s()},[i,o,s]),a=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")&&r(),Q.key==="ArrowLeft"&&a()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[e,s,r,a]),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")})()&&(nr.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:a,children:"Back"}),C.jsx("button",{className:"skills-onb-btn skills-onb-btn--primary",onClick:r,children:c?"Let's Play!":"Next"})]})]})]})}function $0e(e){const[A,t]=E.useState(!1),[i,n]=E.useState(!1);E.useEffect(()=>{(async()=>{try{const{value:o}=await nr.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 Ake=[50,100,250,500],eke=[30,60,90];function wsA(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 zmA=["Toy Box","Cowboys","Surfers","Speed Demons","Beach Club","Rookies","Wave Riders","Regulars","High Rollers"],nE=5,ksA=zmA.length;function ZmA({level:e,levelName:A,winStreak:t,variant:i="expanded",previousWinStreak:n}){const g=Math.max(1,Math.min(ksA,Math.floor(e||1))),o=g>=ksA,s=A??zmA[g-1],r=Math.max(0,t)%nE,a=t>0&&r===0?nE:r,I=o?100:a/nE*100,[c,l]=E.useState(()=>{if(n===void 0)return I;const Q=Math.max(0,n)%nE,h=n>0&&Q===0?nE:Q;return o?100:h/nE*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:[a," / ",nE," wins to next league"]})]})]}),C.jsx("div",{className:`skillsLevelBadge__bar${o?" skillsLevelBadge__bar--max":""}`,role:"progressbar","aria-valuemin":0,"aria-valuemax":nE,"aria-valuenow":o?nE:a,"aria-label":`Level ${g} ${s} progress`,children:C.jsx("div",{className:"skillsLevelBadge__barFill",style:{width:`${c}%`}})})]})}function tke({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 ike=3e3;function nke({isMultiplayer:e,activeGameMode:A,selectedStake:t,setSelectedStake:i,selectedDuration:n,setSelectedDuration:g,myBalance:o,stakeError:s,hasStarted:r,onStart:a,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),ike);return()=>clearTimeout(G)},[D]);const N=async G=>{g(G);try{const{Preferences:M}=await li(async()=>{const{Preferences:w}=await Promise.resolve().then(()=>Yc);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(ZmA,{level:d,levelName:p,winStreak:y,variant:"expanded"}),m&&C.jsx(tke,{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:Ake.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:eke.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:a,disabled:S||r||!e&&o<t,style:S?{opacity:.5,pointerEvents:"none"}:void 0,children:e?"Ready Up":`Play for ${t} Credits`})})})]})}const gke=3e3,oke=0,lm=new Map,UM=new Map;async function ske(e){var t,i,n,g,o,s,r;const A=encodeURIComponent(e);try{const a=await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${A}`);if(a.ok){const I=await a.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 a=await fetch(`https://en.wiktionary.org/api/rest_v1/page/definition/${A}`);if(a.ok){const I=await a.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:(r=l==null?void 0:l.partOfSpeech)==null?void 0:r.toLowerCase()}}}catch{}throw new Error("no definition found")}function rke(e,A){const t=e.toLowerCase();if(lm.has(t))return;lm.set(t,"loading");const i=new Set;UM.set(t,i),i.add(A),ske(t).then(n=>lm.set(t,n)).catch(()=>lm.set(t,"error")).finally(()=>{var n;(n=UM.get(t))==null||n.forEach(g=>g()),UM.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),r=e.toLowerCase();E.useEffect(()=>{var Q;const B=()=>g(h=>h+1);return(Q=UM.get(r))==null||Q.add(B),()=>{var h;(h=UM.get(r))==null||h.delete(B)}},[r]);const a=E.useCallback(()=>{if(i){n(!1);return}n(!0),lm.has(r)||rke(r,()=>g(B=>B+1))},[i,r]),I=E.useCallback(B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),a())},[a]);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(r)??null;return C.jsxs("span",{ref:o,className:`${c} wordDefWrapper`,onClick:a,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 ake({myScore:e,players:A,scores:t,winnerId:i,iWon:n,isDraw:g,winnings:o,selectedStake:s,isMultiplayer:r,meId:a,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?gke:oke,[m,D]=E.useState(y>0);E.useEffect(()=>{if(y<=0){D(!1);return}const T=setTimeout(()=>D(!1),y);return()=>clearTimeout(T)},[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=T=>{if(T===a)return"You";const v=A.find(U=>U.id===T);return(v==null?void 0:v.name)||"Bot"},G=[...A].sort((T,v)=>T.id===a?-1:v.id===a?1:(t[v.id]??0)-(t[T.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(a&&((J=(K=I==null?void 0:I.playerWords)==null?void 0:K[a])!=null&&J.length))for(const T of I.playerWords[a])(!b||T.points>b.points)&&(b=T);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(ZmA,{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(T=>C.jsxs("span",{className:"roundEndScore",style:T.id===i?{color:"var(--gold, #f5c542)"}:void 0,children:[N(T.id),": ",C.jsx("strong",{children:t[T.id]??0})]},T.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((T,v)=>C.jsxs("div",{className:"skillsXpBreakdown__row",children:[C.jsx("span",{className:"skillsXpBreakdown__label",children:T.label}),C.jsx("span",{className:"skillsXpBreakdown__value",children:T.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:r?"Ready Up":"Play Again"})}),S&&C.jsxs("div",{className:"roundSummaryScrollable",children:[C.jsx("p",{className:"roundSummaryTitle",children:"Words Found"}),(()=>{const T=new Set([...Object.keys((I==null?void 0:I.playerWords)||{}),...Object.keys((I==null?void 0:I.rejectedWords)||{})]);return Array.from(T).map(v=>{var z,Z;const U=N(v),x=((z=I==null?void 0:I.playerWords)==null?void 0:z[v])||[],q=((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)):!q.length&&C.jsx("span",{className:"roundSummaryNone",children:"No words"}),q.length>0&&q.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(([T,v])=>{const U=N(T);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,q)=>C.jsxs("span",{className:`roundSummaryAnswer ${x.correct?"roundSummaryAnswerCorrect":"roundSummaryAnswerWrong"}`,children:["Q",x.questionIndex+1,": ",x.correct?"✓":"✗"]},q)):C.jsx("span",{className:"roundSummaryNone",children:"No answers"})})]},T)})]})]})}function Ike({countdown:e}){return C.jsx("div",{className:"skillsCountdownOverlay",children:C.jsx("div",{className:"skillsCountdownNumber",children:e})})}function Cke({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 cke({message:e}){return C.jsx("div",{className:"skillsInvalidWord",children:C.jsx("span",{className:"skillsInvalidWordText",children:e})})}function lke({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 Bke(e){const{meId:A,setConnected:t,setScores:i,setRoundEnded:n,setWinnerId:g,setPlayers:o,setGameState:s,setHasStarted:r,setWinnings:a,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}=v4(),{win:k,lose:N}=Fa(),{onHandEnd:G}=qf(),M=E.useCallback(w=>{const b=new Set;return w.filter(_=>!(_!=null&&_.id)||b.has(_.id)?!1:(b.add(_.id),!0))},[]);xs({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,q,z,Z,eA,aA,sA,pA,gA,yA,fA,RA,YA;const b=new Set(["skills","wordsearch","anagrams","trivia"]),_=((x=w.room)==null?void 0:x.gameMode)||((q=w.gameState)==null?void 0:q.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 T=w.gameState||{};s(T),T.phase==="playing"&&T.seed&&!v4.getState().seed&&(console.log("[SkillsSocketListeners] Recovering session from room:update_state",{seed:T.seed,gameMode:T.gameMode}),S({roomId:(aA=w.room)==null?void 0:aA.id,seed:T.seed,startAt:T.startAt,endAt:T.endAt,gameMode:T.gameMode,letters:(sA=T.anagramsData)==null?void 0:sA.letters,questions:(gA=(pA=T.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),a(0),U||r(!1),i({}),c(null),B([]),l([]),Q({}),h(0)),v!=="playing"&&!y&&((YA=w.gameState)!=null&&YA.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&&(r(!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){tP();const b=typeof w.winnings=="number"?w.winnings:0;k("Winner!",b>0?`+Z$${b.toLocaleString()}`:void 0)}else iP(),N("Better Luck Next Time");typeof w.winnings=="number"&&a(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(),T=J[K];return typeof(T==null?void 0:T.balance)=="number"&&T.balance===b?_:(J[K]={...T,balance:b},J)})},onOtherPlayerJoined:w=>{var T,v,U,x,q;if(!((T=w==null?void 0:w.room)!=null&&T.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)||((q=(x=w.room)==null?void 0:x.gameState)==null?void 0:q.gameMode);if(!_||!b.has(_))return;const K=w.room.players||[],J=M(K);o(J)},onOtherLeft:w=>{var T,v,U,x,q;if(!((T=w==null?void 0:w.room)!=null&&T.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)||((q=(x=w.room)==null?void 0:x.gameState)==null?void 0:q.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 K4="skills:dailyChallenge:";function WmA(){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 Eke(){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 NsA=[{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 Qke(){return NsA[Eke()%NsA.length]}function RsA(){const e=WmA(),A=`${K4}${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(K4)&&g!==A)try{localStorage.removeItem(g)}catch{}}}catch{}return{...Qke(),progress:0,completed:!1,dateKey:e}}function uke(e){try{localStorage.setItem(`${K4}${e.dateKey}`,JSON.stringify(e))}catch{}}function dke(){const[e,A]=E.useState(()=>RsA()),t=E.useRef(e);E.useEffect(()=>{t.current=e},[e]),E.useEffect(()=>{const o=window.setInterval(()=>{if(t.current.dateKey!==WmA()){const s=RsA();A(s)}},6e4);return()=>window.clearInterval(o)},[]);const i=E.useCallback(o=>{A(s=>{if(s.completed)return s;const r=o(s);if(r===s)return s;const a=Math.min(r.goal,Math.max(s.progress,r.progress)),I=a>=r.goal,c={...r,progress:a,completed:I};return uke(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 hke=!1;function GsA(e,A){try{hke||o8()}catch{}}const pke=new Set(["room.ready","tapAck","score","roundEnd"]),bsA=512,fke=50;let Gu=null,VmA=1;const ep=new Set;let F4=0;function pT(){return Gu||(Gu=$k(VM||"",{path:"/socket.io",transports:["websocket","polling"],autoConnect:!1,reconnection:!0,reconnectionAttempts:1/0,reconnectionDelayMax:1e4,auth:{platform:"web"}}),Gu)}async function XmA(){const e=pT();let A;try{A=await Co()}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 yke(){if(Gu){try{Gu.removeAllListeners()}catch{}try{Gu.disconnect()}catch{}Gu=null}VmA=1,ep.clear(),F4=0}function Dke(e){const A=pT(),t=(i,n)=>{pke.has(i)&&e({type:i,payload:n})};return A.on("message",t),()=>{A.off("message",t)}}function mke(e){const A=pT();if(e.type==="tap"){const t=Date.now();if(t-F4<fke)return"throttled";F4=t}if(e.type==="tap"||e.type==="submit"){if(ep.has(e.payload.seq))return"duplicate";if(ep.add(e.payload.seq),ep.size>bsA){const t=ep.size-bsA,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 $mA(){return VmA++}function Ske(e,A){return e-A}const wke=Object.freeze(Object.defineProperty({__proto__:null,computeDrift:Ske,connectSocket:XmA,disconnectSocket:yke,getSocket:pT,nextSeq:$mA,onMessage:Dke,send:mke},Symbol.toStringTag,{value:"Module"}));function kke(){return VM}const UsA=kke();async function Mke(){if(!UsA)return null;try{let e;try{e=await Co()}catch{}const A={Accept:"application/json"};e&&(A.Authorization=`Bearer ${e}`);const t=await fetch(`${UsA}/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 wd()}catch{}return null}return null}catch{return null}}function Nke({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,r=i<=5,a=i/t*100;return C.jsxs("div",{className:["poker-turn-timer",o?"":"poker-turn-timer--hidden",s?"poker-turn-timer--urgent":"",r?"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:`${a} 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 Rke(e){const{endAt:A,isRoundActive:t,scores:i,meId:n}=e,g=E.useMemo(()=>C.jsx(Nke,{endAt:A,isActive:!!t&&!!A,totalSeconds:30}),[A,t]),o=E.useMemo(()=>{if(!(!i||!t))return s=>{const r=i[s.id]??0,a=s.id===n;return C.jsxs("div",{className:`skills-player-score ${a?"skills-player-score--me":""}`,children:[C.jsx("span",{className:"skills-score-value",children:r}),C.jsx("span",{className:"skills-score-label",children:"pts"})]})}},[i,t,n]);return C.jsx(Ix,{...e,className:"skills-player-panel",hideDiceResults:!0,disableBankerFlash:!0,hideSideBets:!0,headerCommsLeftSlot:g,renderFacesOverride:o})}function qJ(){var qt,ei,Yt;const{roomId:e,seed:A,startAt:t,endAt:i,driftMs:n,setSession:g,set:o,user:s,gameMode:r,letters:a,questions:I}=v4(),{meId:c,user:l}=en(),B=Ss(),{cancelAd:Q,isAdEnabled:h}=qf(),d=Ji(),p=Cx();E.useEffect(()=>(p.acquire(),()=>{p.release()}),[p]);const[y]=dw(),{roomId:m}=uw(),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),[T,v]=E.useState(),[U,x]=E.useState([]),[q,z]=E.useState({}),[Z,eA]=E.useState(!1),[aA,sA]=E.useState(null),[pA,gA]=E.useState(null),[yA,fA]=E.useState(null),[RA,YA]=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),[CA,cA]=E.useState(null),[_A,uA]=E.useState(0),[X,O]=E.useState(0),[lA,wA]=E.useState(0),[xA,HA]=E.useState(),[zA,ne]=E.useState(),[ye,Ee]=E.useState(!1),[NA,QA]=E.useState(void 0),[PA,VA]=E.useState(null),{active:KA,fire:Ie,onComplete:DA}=KZ(),{challenge:IA,recordRoundResult:EA,recordWord:j}=dke(),dA=E.useRef(0),hA=["loss-a","loss-b","loss-c"],UA=()=>{const Ce=hA[dA.current%hA.length];return dA.current+=1,Ce},[TA,se]=E.useState(S||"wordsearch"),[Ne,Ke]=E.useState([]),[At,ni]=E.useState(0),[Ge,st]=E.useState({}),[Rt,Et]=E.useState([]),_t=E.useRef(null);E.useRef(null);const vt=E.useRef({});vt.current=w;const xt=E.useRef(null),ee=E.useRef(null),{skillsSubmit:Oe,skillsSingleStart:We,skillsReady:pt,skillsJoinRoom:kA,anagramsSubmit:oe,triviaAnswer:ae}=So(),{joinRoom:$A,leaveRoom:nA}=al(),vA=E.useRef(nA);vA.current=nA;const FA=c||(s==null?void 0:s.id);E.useEffect(()=>{o({seed:null,startAt:null,endAt:null,roomId:null,letters:void 0,questions:void 0}),xt.current=null,ee.current=null},[]),E.useEffect(()=>{if(!B)return;const Ce=()=>{console.log("[SkillsPlay] socket reconnected — resetting guards"),xt.current=null,Zt.current=!1};return B.on("connect",Ce),()=>{B.off("connect",Ce)}},[B]),E.useEffect(()=>{if(!D)return;const Ce=()=>{console.log("[SkillsPlay] ad:complete — resetting join guard for room",D),xt.current=null};return window.addEventListener("ad:complete",Ce),()=>{window.removeEventListener("ad:complete",Ce)}},[D]),E.useEffect(()=>{if(S){se(S);return}(async()=>{try{const{Preferences:Ce}=await li(async()=>{const{Preferences:dt}=await Promise.resolve().then(()=>Yc);return{Preferences:dt}},void 0),{value:it}=await Ce.get({key:"selectedSkillsGameMode"});(it==="wordsearch"||it==="anagrams"||it==="trivia")&&se(it)}catch{}})()},[S]),E.useEffect(()=>{(async()=>{try{const{Preferences:Ce}=await li(async()=>{const{Preferences:ft}=await Promise.resolve().then(()=>Yc);return{Preferences:ft}},void 0),{value:it}=await Ce.get({key:"selectedSkillsDuration"}),dt=parseInt(it||"",10);(dt===30||dt===60||dt===90)&&oA(dt)}catch{}})()},[]),E.useEffect(()=>{(async()=>{try{const Ce=await Wo();Ce.botDifficultyLevel&&Ce.botDifficultyLevel>=1&&Ce.botDifficultyLevel<=9&&QA(Ce.botDifficultyLevel)}catch{}})()},[]);const te=(l==null?void 0:l.balance)??0,bA=!!l,De=(()=>{try{return(l==null?void 0:l.isGuest)===!0}catch{return!1}})(),jA=!bA||De,me=E.useCallback(()=>d("/lobby"),[d]),le=FA?w[FA]??0:0,qA=U.find(Ce=>Ce.id!==FA),WA=qA==null?void 0:qA.id,Se=(qA==null?void 0:qA.name)||"Bot";WA&&w[WA];const Qe=!!D,ce=U.find(Ce=>Ce.id===FA);ce!=null&&ce.isReady||(qt=q==null?void 0:q.readyMap)!=null&&qt[FA||""];const Ve=E.useMemo(()=>{const Ce=new Set;let it=U.filter(ft=>!(ft!=null&&ft.id)||Ce.has(ft.id)?!1:(Ce.add(ft.id),!0)).map(ft=>ft.id===FA&&typeof ft.balance!="number"&&typeof(l==null?void 0:l.balance)=="number"?{...ft,balance:l.balance}:ft);const dt=typeof FA=="string"&&FA.length>0;return it.length===0&&dt&&l&&(it=[{id:FA,name:l.name||l.email||"You",balance:l.balance??0,avatarUrl:l.avatarUrl??void 0}]),it},[U,FA,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]),Dt=(q==null?void 0:q.everyoneReady)||!1,Mt=(q==null?void 0:q.phase)||"waiting",ct=S||(q==null?void 0:q.gameMode)||r||TA,{showOnboarding:gt,closeOnboarding:et}=$0e(ct),Li=k?"demo-screenshot-seed-12345":null,Ri=A||(q==null?void 0:q.seed)||Li,gi=k?"playing":Mt,Jt=a||((ei=q==null?void 0:q.anagramsData)==null?void 0:ei.letters),jt=I||((Yt=q==null?void 0:q.triviaData)==null?void 0:Yt.questions),Ci=gi==="playing"&&!!Ri&&!K&&ct==="wordsearch",Pi=gi==="playing"&&!K&&ct==="anagrams"&&(((Jt==null?void 0:Jt.length)??0)>0||k),si=gi==="playing"&&!K&&ct==="trivia"&&(((jt==null?void 0:jt.length)??0)>0||k),[pi,Ai]=E.useState(null),xi=E.useCallback(Ce=>{Et(ft=>ft.some(ci=>ci.word===Ce.word)?ft:[...ft,{word:Ce.word,playerId:Ce.playerId,path:Ce.path}]);const it=Ce.playerId===FA,dt=Array.isArray(Ce.path)&&Ce.path.length>0;if(dt&&it&&N&&Ai({path:Ce.path,nonce:Date.now(),mine:!0}),N&&dt&&it){const ft=Ce.word||"",ci=Math.max(220,Math.min(320,Math.floor(2e3/Ce.path.length))),Hi=Ce.path.length*ci+900,Wi=Ce.path[Ce.path.length-1],Vi=ft.length*ft.length;L.current=Math.min(L.current+1,8);const hi=1+(L.current-1)*.07;window.setTimeout(()=>{fA("valid");try{AP({volume:.6,rate:hi})}catch{}setTimeout(()=>fA(null),400),Wi&&(YA({row:Wi.r,col:Wi.c,points:Vi,nonce:Date.now()}),H.current&&window.clearTimeout(H.current),H.current=window.setTimeout(()=>YA(null),950)),(ft.length>=6||L.current>=4)&&$(Date.now())},Hi)}},[FA,N]);Bke({meId:FA,setConnected:M,setScores:b,setRoundEnded:J,setWinnerId:v,setPlayers:x,setGameState:z,setHasStarted:eA,setWinnings:uA,setWinStreak:O,setRoundSummary:VA,setMyAnagramWords:Ke,setClaimedWordPaths:Et,setMyTriviaAnswers:st,setCurrentTriviaQuestion:ni,setCountdown:sA,onWordClaimed:xi,isMultiplayer:Qe,roundEnded:K,endRef:_t}),E.useEffect(()=>{if(K||!FA)return;const Ce=w[FA]??0,it=Object.entries(w).filter(([ft])=>ft!==FA).map(([,ft])=>ft),dt=Math.max(0,...it);dt>0&&Ce<dt&&(_.current=!0)},[w,FA,K]),E.useEffect(()=>{if(!K||!T||!FA)return;const Ce=T===FA;if(wA(Ce?X:0),EA({iWon:Ce,myScore:w[FA]??0}),!Ce){Ie(UA(),{displayMs:2e3});return}const it=w[FA]??0,dt=Object.entries(w).filter(([ci])=>ci!==FA).map(([,ci])=>ci),ft=Math.max(0,...dt);ft===0&&it>0?Ie("skills-perfect",{displayMs:3e3}):X>0&&X%5===0?Ie("streak-5",{displayMs:3500}):ft>0&&it>=ft*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,T,FA,w,X,Ie,EA]),E.useEffect(()=>{const Ce=q;(Ce==null?void 0:Ce.phase)==="playing"&&Array.isArray(Ce==null?void 0:Ce.claimedWords)&&Ce.claimedWords.length>0&&Et(Ce.claimedWords)},[q]),E.useEffect(()=>{Z||A?Yu():K||kL({volume:.0125})},[Z,K,A]);const ui=E.useRef(D);E.useEffect(()=>{ui.current!==D&&(VA(null),J(!1),v(void 0),uA(0),b({}),_.current=!1,Et([]),Ke([]),ni(0),st({}),ui.current=D)},[D]),E.useEffect(()=>{D&&xt.current!==D&&(xt.current=D,kA(D).then(async Ce=>{var it,dt;if(Ce!=null&&Ce.ok&&(Ce!=null&&Ce.data)){if(o({roomId:Ce.data.roomId}),(it=Ce.data.room)!=null&&it.players){const ft=Ce.data.room.players,ci=new Set,Hi=ft.filter(Wi=>!(Wi!=null&&Wi.id)||ci.has(Wi.id)?!1:(ci.add(Wi.id),!0));x(Hi)}if((dt=Ce.data.room)!=null&&dt.gameState&&z(Ce.data.room.gameState),ee.current!==D)try{console.log("[SkillsPlay] Joining RTC room:",D),await $A(D),ee.current=D,console.log("[SkillsPlay] RTC room joined successfully:",D)}catch(ft){console.error("[SkillsPlay] Failed to join RTC room:",ft)}}else xt.current=null}).catch(()=>{xt.current=null}))},[D,kA,o,$A]),E.useEffect(()=>()=>{ee.current&&(console.log("[SkillsPlay] Leaving RTC room on unmount"),vA.current())},[]),E.useEffect(()=>{o8(),Mke().then(Ce=>o({user:Ce}))},[o]),E.useEffect(()=>{if(!i||K||!Z)return;const Ce=()=>{Date.now()+n>=i&&!K&&Z&&(console.log("[SkillsPlay] Timer expired locally, triggering round end"),J(!0))};Ce();const it=i-(Date.now()+n);if(it>0){const dt=setTimeout(Ce,it+3e3);return()=>clearTimeout(dt)}},[i,n,K,Z]),E.useEffect(()=>{if(!Z)return;let Ce;(async()=>{try{const{App:dt}=await li(async()=>{const{App:ci}=await Promise.resolve().then(()=>UR);return{App:ci}},void 0),ft=await dt.addListener("appStateChange",ci=>{if(ci.isActive){const Hi=Date.now()+n;i&&Hi>=i&&!K&&Z&&(console.log("[SkillsPlay] App resumed after timer expired, triggering round end"),J(!0))}});Ce=()=>{try{ft.remove()}catch{}}}catch{}})();const it=()=>{if(document.visibilityState==="visible"){const dt=Date.now()+n;i&&dt>=i&&!K&&Z&&(console.log("[SkillsPlay] Tab visible after timer expired, triggering round end"),J(!0))}};return document.addEventListener("visibilitychange",it),()=>{Ce==null||Ce(),document.removeEventListener("visibilitychange",it)}},[i,n,K,Z]);const ie=Date.now()+n,ln=!!i&&ie<(i??0),Zt=E.useRef(!1),lo=E.useCallback(async()=>{if(!Zt.current){Zt.current=!0;try{console.log("[SkillsPlay] startGame() called",{selectedStake:P,activeGameMode:ct,selectedDuration:iA,myBalance:te});const Ce=await We(P,ct,iA,NA,N);console.log("[SkillsPlay] startGame() result",{ok:Ce==null?void 0:Ce.ok,error:Ce==null?void 0:Ce.error,hasData:!!(Ce!=null&&Ce.data)}),Ce&&!Ce.ok?(console.log("[SkillsPlay] startGame() failed",{error:Ce.error,balance:Ce.balance,stake:Ce.stake}),Zt.current=!1,eA(!1),sA(null),Ce.error!=="insufficient_balance"&&Ce.error!=="already_starting"&&cA(Ce.error||"Failed to start game")):Ce!=null&&Ce.data?(Zt.current=!1,Ce.data.spLevel&&HA(Ce.data.spLevel),Ce.data.levelName&&ne(Ce.data.levelName),g({...Ce.data,gameMode:Ce.data.gameMode||ct}),z(it=>({...it,phase:"playing",gameMode:Ce.data.gameMode||ct,stake:Ce.data.stake,pot:Ce.data.pot}))):Zt.current=!1}catch{Zt.current=!1}}},[We,P,iA,ct,NA,N]),Hg=E.useCallback(async()=>{if(cA(null),console.log("[SkillsPlay] handleStart",{activeGameMode:ct,urlGameMode:S,preferredGameMode:TA,gameMode:r,gameStateMode:q==null?void 0:q.gameMode,isMultiplayer:Qe}),Qe){const Ce=D||e;Ce&&(console.log("[skills:ready] sending immediately on handleStart",{effectiveRoomId:Ce}),Q(),eA(!0),await pt(Ce));return}if(console.log("[SkillsPlay] handleStart() balance check",{hasStarted:Z,myBalance:te,selectedStake:P,passes:te>=P}),!Z&&te<P){console.log("[SkillsPlay] handleStart() CLIENT BALANCE CHECK FAILED",{myBalance:te,selectedStake:P}),cA(`Insufficient balance. Need ${P} credits.`);return}console.log("[SkillsPlay] handleStart() starting countdown"),Yu(),eA(!0),sA(3)},[Qe,P,ct,S,TA,r,q==null?void 0:q.gameMode,te,D,e,pt,Q]),xo=E.useCallback(async()=>{Zt.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,Et([]),v(void 0),VA(null),Ke([]),ni(0),st({}),L.current=0,YA(null),$(0),Qe&&D?(Q(),await pt(D)):(eA(!1),x([]),z({}))},[o,Qe,D,pt,Q]),Cg=E.useRef(0);E.useEffect(()=>{N&&(P!==500&&tA(500),iA!==90&&oA(90))},[N,P,iA]),E.useEffect(()=>{if(!N||Qe)return;const Ce=()=>{if(Z||K||aA!==null)return;if(!bA){console.log("[SkillsPlay autoplay] waiting for auth before starting");return}const ft=Date.now();ft-Cg.current<5e3||(Cg.current=ft,console.log("[SkillsPlay autoplay] kicking countdown",{selectedStake:P,activeGameMode:ct,selectedDuration:iA,myBalance:te}),Yu(),eA(!0),sA(3))},it=window.setTimeout(Ce,1200),dt=window.setInterval(Ce,3e3);return()=>{window.clearTimeout(it),window.clearInterval(dt)}},[N,Qe,Z,K,aA,bA,P,ct,iA,te]),E.useEffect(()=>{if(!N||Qe||!K)return;const Ce=window.setTimeout(()=>{Cg.current=0,xo()},4e3);return()=>window.clearTimeout(Ce)},[N,Qe,K,xo]),E.useEffect(()=>{if(aA===null)return;if(aA>0&&Xl({volume:.3}),aA===0){Xl({volume:.5}),sA(null),Qe||lo();return}const Ce=setTimeout(()=>{sA(it=>it!==null&&it>0?it-1:null)},1e3);return()=>clearTimeout(Ce)},[aA,lo,Qe]);const Dg=E.useMemo(()=>A?wsA(A):[],[A]),ng=E.useMemo(()=>Rt.filter(Ce=>Ce.playerId===FA).map(Ce=>Ce.word),[Rt,FA]),wo=E.useMemo(()=>Rt.filter(Ce=>Ce.playerId!==FA).map(Ce=>Ce.word),[Rt,FA]),fe=E.useCallback(async Ce=>{!ln||!e||K||Ce.length<3||await oe(e,Ce.toUpperCase())},[ln,e,K,oe]),Pe=E.useCallback(async(Ce,it)=>{!ln||!e||K||(st(dt=>({...dt,[Ce]:{answer:it,isCorrect:void 0,correctIndex:void 0}})),await ae(e,Ce,it))},[ln,e,K,ae]),OA=async Ce=>{if(!ln||!e||K||Ce.length<3)return;const it=Ce.map(({r:ci,c:Hi})=>{var Wi;return((Wi=Dg[ci])==null?void 0:Wi[Hi])||""}).join("").toUpperCase();if(it.length<3)return;const dt=$mA();GsA("word_submit",{len:Ce.length});const ft=await Oe(e,Ce,it,Date.now(),dt);if(ft&&ft.valid){L.current=Math.min(L.current+1,8);const ci=1+(L.current-1)*.07;fA("valid"),AP({volume:.4,rate:ci}),setTimeout(()=>fA(null),400);const Hi=Ce[Ce.length-1],Wi=typeof ft.points=="number"?ft.points:it.length*it.length;Hi&&(YA({row:Hi.r,col:Hi.c,points:Wi,nonce:Date.now()}),H.current&&window.clearTimeout(H.current),H.current=window.setTimeout(()=>YA(null),950)),(it.length>=6||L.current>=4)&&$(Date.now()),j(it)}else ft&&!ft.valid&&(L.current=0,fA("invalid"),setTimeout(()=>fA(null),400),ft.error==="invalid_word"?gA(`"${it}" is not a word`):ft.error==="word_already_used"?gA(`"${it}" already used`):ft.error==="word_claimed"?gA(`"${it}" already taken`):(ft.error==="path_not_contiguous"||ft.error==="path_has_duplicates")&&gA("Invalid path"),setTimeout(()=>gA(null),800))},XA=Ce=>{GsA()},_e=!Ci&&!Pi&&!si&&!Z&&!K,xe=Z&&!Ci&&!Pi&&!si&&Qe&&!Dt&&!K,rA=U.filter(Ce=>{var it;return(it=q==null?void 0:q.readyMap)==null?void 0:it[Ce.id]}).length,pe=U.length,Fe=T===FA,je=!T&&K,$e=E.useMemo(()=>({...q,gameMode:"skills"}),[q]),Gt=E.useMemo(()=>{var Hi;if(Qe)return;const Ce=Number(xA??(l==null?void 0:l.spLevelSkills)??1),it=Number.isFinite(Ce)&&Ce>0?Ce:1,dt=Math.max(0,lA)%5,ft=lA>0&&dt===0?5:dt,ci=zA??((Hi=iQ.find(Wi=>Wi.level===it))==null?void 0:Hi.name)??`Level ${it}`;return{level:it,levelName:ci,current:ft,total:5,progressLabel:`${ft}/5 consecutive wins`,goalLabel:`Win 5 rounds in a row to reach Level ${it+1}`,isMaxLevel:it>=iQ.length}},[Qe,xA,zA,l==null?void 0:l.spLevelSkills,lA]),Ot=`skillsPage${yA==="valid"?" skillsFlashValid":""}${yA==="invalid"?" skillsFlashInvalid":""}`;return C.jsxs("main",{className:Ot,children:[C.jsx(Rke,{players:Ve,gameState:$e,roomId:e||D||"",meId:FA||"",endAt:i??void 0,isRoundActive:ln,scores:w,hideAvatars:_e,singlePlayer:!Qe,campaignProgress:Gt}),C.jsx("div",{className:"skillsBody",children:C.jsxs("div",{className:"skillsContainer",children:[!G&&C.jsx(lke,{onRetry:()=>XmA()}),_e&&C.jsx(nke,{isMultiplayer:Qe,activeGameMode:ct,selectedStake:P,setSelectedStake:tA,selectedDuration:iA,setSelectedDuration:oA,myBalance:te,stakeError:CA,hasStarted:Z,onStart:Hg,onShowHelp:()=>Ee(!0),isAuthenticated:!jA,onLogin:me,isAdEnabled:h,roomStake:q==null?void 0:q.stake,roomDuration:q==null?void 0:q.duration,spLevel:xA??(l==null?void 0:l.spLevelSkills),spLevelName:zA,winStreak:lA,dailyChallenge:IA}),xe&&C.jsx(Cke,{readyCount:rA,totalPlayers:pe}),aA!==null&&C.jsx(Ike,{countdown:aA}),pA&&C.jsx(cke,{message:pA}),Ci&&C.jsx("section",{className:"card gridCard",children:C.jsx(jmA,{letters:wsA(Ri),onSubmit:OA,onTap:XA,disabled:!ln||K||k,feedback:RA,shakeKey:W,botTrail:pi})}),Ci&&(ng.length>0||wo.length>0)&&C.jsxs("div",{className:"foundWordsList",children:[ng.length>0&&C.jsxs("div",{className:"foundWordsColumn foundWordsColumn--me",children:[C.jsx("span",{className:"foundWordsLabel",children:"You"}),C.jsx("div",{className:"foundWordsTags",children:ng.map(Ce=>C.jsx("span",{className:"foundWordTag foundWordTag--me",children:Ce},Ce))})]}),wo.length>0&&C.jsxs("div",{className:"foundWordsColumn foundWordsColumn--opp",children:[C.jsx("span",{className:"foundWordsLabel",children:Se}),C.jsx("div",{className:"foundWordsTags",children:wo.map(Ce=>C.jsx("span",{className:"foundWordTag foundWordTag--opp",children:Ce},Ce))})]})]}),Pi&&Jt&&C.jsx(z0e,{letters:Jt,foundWords:Ne,onSubmit:fe,disabled:!ln||K,myScore:le}),si&&jt&&C.jsx(Z0e,{questions:jt,currentQuestionIndex:At,onAnswer:Pe,myAnswers:Ge,disabled:!ln||K,myScore:le}),K&&C.jsx(ake,{myScore:le,players:Ve,scores:w,winnerId:T,iWon:Fe,isDraw:je,winnings:_A,selectedStake:P,isMultiplayer:Qe,roundSummary:PA,meId:FA,winStreak:X,isAdEnabled:h,spLevel:xA??(l==null?void 0:l.spLevelSkills),spLevelName:zA,onPlayAgain:xo})]})}),C.jsx(X0e,{open:gt||ye,onClose:()=>{et(),Ee(!1)},gameMode:ct}),KA&&C.jsx(vZ,{show:!0,contained:!0,variant:KA.variant,displayMs:KA.displayMs,zoomDurationMs:KA.zoomDurationMs,fadeDurationMs:KA.fadeDurationMs,ariaLabel:KA.ariaLabel,onComplete:DA})]})}function Gke({startAt:e,endAt:A,driftMs:t=0}){const[i,n]=E.useState(()=>Date.now());E.useEffect(()=>{const r=setInterval(()=>n(Date.now()),100);return()=>clearInterval(r)},[]);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 bke(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 ASA(){var Z,eA,aA,sA,pA,gA,yA;const{roomId:e}=uw(),A=Ji(),{meId:t}=en(),[i,n]=E.useState(null),[g,o]=E.useState(null),[s,r]=E.useState([]),[a,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}=So(),N=E.useRef(!1);xs({onSkillsSpectatorState:fA=>{var RA,YA;console.log("[spectator] Got initial state:",fA),fA.roomId===e&&(n(fA.room),o(fA.gameState),r(((RA=fA.room)==null?void 0:RA.players)||[]),I(((YA=fA.room)==null?void 0:YA.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&&r(fA.players),fA.spectators&&I(fA.spectators))},onSkillsSpectatorJoined:fA=>{console.log("[spectator] Spectator joined:",fA),fA.roomId===e&&fA.spectator&&!a.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(YA=>YA.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?bke(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])||[],T=((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",q=(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"})]}),a.length>0&&C.jsxs("div",{className:"spectator-count",children:[a.length," spectator",a.length!==1?"s":""," watching"]}),q&&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(Gke,{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(T).length]})})]}),C.jsxs("div",{className:"skills-spectate-center",children:[U==="wordsearch"&&G&&x&&C.jsx("div",{className:"spectator-grid",children:C.jsx(jmA,{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 Uke(){const e=Ji(),A=ms();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),aI()},[e]),E.useEffect(()=>{aI(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(we,{element:C.jsx(xf,{}),children:[C.jsx(we,{path:"/verify",element:C.jsx(zf,{})}),C.jsx(we,{path:"/review-login",element:C.jsx(Zf,{})}),C.jsx(we,{path:"/qa-login",element:C.jsx(Wf,{})}),C.jsx(we,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(we,{path:"/add-chips",element:C.jsx(jf,{})}),C.jsxs(we,{element:C.jsx(vf,{}),children:[C.jsx(we,{path:"/profile",element:C.jsx(Yf,{})}),C.jsx(we,{path:"/player/:playerId",element:C.jsx(Hf,{})}),C.jsx(we,{path:"/messages",element:C.jsx(Of,{})}),C.jsx(we,{path:"/settings",element:C.jsx(Pf,{})}),C.jsx(we,{path:"/",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/lobby",element:C.jsx(Lf,{})}),C.jsx(we,{path:"/room/:roomId",element:C.jsx($R,{})}),C.jsx(we,{path:"/skills/play",element:C.jsx(qJ,{})}),C.jsx(we,{path:"/skills/room/:roomId",element:C.jsx(qJ,{})}),C.jsx(we,{path:"/skills/spectate/:roomId",element:C.jsx(ASA,{})})]}),C.jsx(we,{path:"/disclaimer",element:C.jsx(Vf,{})}),C.jsx(we,{path:"/support",element:C.jsx(Xf,{})}),C.jsx(we,{path:"/privacy",element:C.jsx($f,{})}),C.jsx(we,{path:"/terms",element:C.jsx(Ay,{})}),C.jsx(we,{path:"/how-to-play",element:C.jsx(Ud,{defaultMode:"skills"})}),C.jsx(we,{path:"*",element:C.jsx(Fg,{to:"/lobby",replace:!0})})]})}const vke=E.lazy(()=>li(()=>import("./BroadcasterLive-ubUjlwKi.js"),__vite__mapDeps([17,1,18]))),Kke=E.lazy(()=>li(()=>import("./TurretPreview--d2p2lLC.js"),__vite__mapDeps([14,1])));E.lazy(()=>li(()=>import("./ShipPackPreview-DSd-Jms-.js"),__vite__mapDeps([15,1,16])));function Fke(){const e=Ji(),A=ms();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),aI()},[e]),E.useEffect(()=>{aI(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(we,{element:C.jsx(xf,{}),children:[C.jsx(we,{path:"/verify",element:C.jsx(zf,{})}),C.jsx(we,{path:"/review-login",element:C.jsx(Zf,{})}),C.jsx(we,{path:"/qa-login",element:C.jsx(Wf,{})}),C.jsx(we,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(we,{path:"/add-chips",element:C.jsx(jf,{})}),C.jsxs(we,{element:C.jsx(vf,{}),children:[C.jsx(we,{path:"/profile",element:C.jsx(Yf,{})}),C.jsx(we,{path:"/player/:playerId",element:C.jsx(Hf,{})}),C.jsx(we,{path:"/messages",element:C.jsx(Of,{})}),C.jsx(we,{path:"/settings",element:C.jsx(Pf,{})}),C.jsx(we,{path:"/admin",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/broadcaster",element:C.jsx(E.Suspense,{fallback:null,children:C.jsx(vke,{})})}),C.jsx(we,{path:"/",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/lobby",element:C.jsx(Lf,{})}),C.jsx(we,{path:"/room/:roomId",element:C.jsx($R,{})}),C.jsx(we,{path:"/poker",element:C.jsx(xZ,{})}),C.jsx(we,{path:"/poker/mock",element:C.jsx(TZ,{})}),C.jsx(we,{path:"/poker/room/:roomId",element:C.jsx(LZ,{})}),C.jsx(we,{path:"/skills/play",element:C.jsx(qJ,{})}),C.jsx(we,{path:"/skills/room/:roomId",element:C.jsx(qJ,{})}),C.jsx(we,{path:"/skills/spectate/:roomId",element:C.jsx(ASA,{})}),C.jsx(we,{path:"/zentara",element:C.jsx(Fg,{to:"/",replace:!0})}),C.jsx(we,{path:"/zentara/match/:matchId",element:C.jsx($S,{})}),C.jsx(we,{path:"/zentara/room/:roomId",element:C.jsx($S,{})})]}),C.jsx(we,{path:"/disclaimer",element:C.jsx(Vf,{})}),C.jsx(we,{path:"/support",element:C.jsx(Xf,{})}),C.jsx(we,{path:"/privacy",element:C.jsx($f,{})}),C.jsx(we,{path:"/terms",element:C.jsx(Ay,{})}),C.jsx(we,{path:"/button-sandbox",element:C.jsx(AG,{})}),C.jsx(we,{path:"/how-to-play",element:C.jsx(Ud,{})}),C.jsx(we,{path:"/turret-preview",element:C.jsx(E.Suspense,{fallback:null,children:C.jsx(Kke,{})})}),C.jsx(we,{path:"/ship-pack-preview",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"*",element:C.jsx(Fg,{to:"/lobby",replace:!0})})]})}const _ke=E.lazy(()=>li(()=>import("./BroadcasterLive-ubUjlwKi.js"),__vite__mapDeps([17,1,18]))),Jke=E.lazy(()=>li(()=>import("./TurretPreview--d2p2lLC.js"),__vite__mapDeps([14,1])));E.lazy(()=>li(()=>import("./ShipPackPreview-DSd-Jms-.js"),__vite__mapDeps([15,1,16])));function Lke(){const e=Ji(),A=ms();return E.useEffect(()=>{const i=new URLSearchParams(window.location.search).get("redirect");i&&e(i),aI()},[e]),E.useEffect(()=>{aI(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(we,{element:C.jsx(xf,{}),children:[C.jsx(we,{path:"/verify",element:C.jsx(zf,{})}),C.jsx(we,{path:"/review-login",element:C.jsx(Zf,{})}),C.jsx(we,{path:"/qa-login",element:C.jsx(Wf,{})}),C.jsx(we,{path:"/verification-failed",element:C.jsx(Kf,{})})]}),C.jsx(we,{path:"/add-chips",element:C.jsx(jf,{})}),C.jsxs(we,{element:C.jsx(vf,{}),children:[C.jsx(we,{path:"/profile",element:C.jsx(Yf,{})}),C.jsx(we,{path:"/player/:playerId",element:C.jsx(Hf,{})}),C.jsx(we,{path:"/messages",element:C.jsx(Of,{})}),C.jsx(we,{path:"/settings",element:C.jsx(Pf,{})}),C.jsx(we,{path:"/admin",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/broadcaster",element:C.jsx(E.Suspense,{fallback:null,children:C.jsx(_ke,{})})}),C.jsx(we,{path:"/",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"/lobby",element:C.jsx(Lf,{})}),C.jsx(we,{path:"/zentara/match/:matchId",element:C.jsx($S,{})}),C.jsx(we,{path:"/zentara/room/:roomId",element:C.jsx($S,{})})]}),C.jsx(we,{path:"/disclaimer",element:C.jsx(Vf,{})}),C.jsx(we,{path:"/support",element:C.jsx(Xf,{})}),C.jsx(we,{path:"/privacy",element:C.jsx($f,{})}),C.jsx(we,{path:"/terms",element:C.jsx(Ay,{})}),C.jsx(we,{path:"/how-to-play",element:C.jsx(Ud,{})}),C.jsx(we,{path:"/turret-preview",element:C.jsx(E.Suspense,{fallback:null,children:C.jsx(Jke,{})})}),C.jsx(we,{path:"/ship-pack-preview",element:C.jsx(Fg,{to:"/lobby",replace:!0})}),C.jsx(we,{path:"*",element:C.jsx(Fg,{to:"/lobby",replace:!0})})]})}const xke="ceelolounge",vsA=_GA.toLowerCase(),Tke=new Set(["","verify","auth","ceelolounge","review-login","qa-login"]);function KO(e){return!e||e.length===0||e.length>2048||!/^[A-Za-z0-9._-]+$/.test(e)?null:e}function qke(e){try{const A=new URL(e),t=A.protocol.replace(":","").toLowerCase(),i=(A.hostname||"").toLowerCase(),n=(A.pathname||"").toLowerCase(),g=t===xke,o=A.protocol==="https:",s=n.endsWith("/verify")||n.includes("/auth/verify"),r=n.endsWith("/review-login")||n.includes("/review-login"),a=n.endsWith("/qa-login")||n.includes("/qa-login");if(g){if(!Tke.has(i)||!s&&!r&&!a&&!(i==="verify"||i==="review-login"||i==="qa-login")&&!((i===""||i==="ceelolounge")&&(n==="/"||n==="")))return null}else if(o){if(vsA&&i!==vsA||!s&&!r&&!a)return null}else return null;const I=KO(A.searchParams.get("token"));if(I)return I;const c=n.split("/").filter(Boolean),l=c.lastIndexOf("verify");return l>=0&&c[l+1]?KO(c[l+1]):c.length===1&&!["verify","auth","review-login","qa-login"].includes(c[0])?KO(c[0]):null}catch{return null}}function Yke(){const e=Ji(),A=E.useRef(null);return E.useEffect(()=>{let t;const i=n=>{if(!n||A.current===n)return;const g=qke(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(),r=(o.hostname||"").toLowerCase(),a=s.includes("/review-login")||r==="review-login"?"/review-login":s.includes("/qa-login")||r==="qa-login"?"/qa-login":"/verify";e(`${a}?token=${encodeURIComponent(g)}`,{replace:!0})}catch{e(`/verify?token=${encodeURIComponent(g)}`,{replace:!0})}};return Ma.getLaunchUrl().then(n=>i(n==null?void 0:n.url)).catch(()=>{}),(async()=>t=await Ma.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 eSA="dl_invited_by_v1",tSA="dl_invited_by_ts_v1",_4=/^[A-Za-z0-9_-]{16,64}$/;function KsA(e,A){try{window.localStorage.setItem(e,A)}catch{}}function FsA(e){try{window.localStorage.removeItem(e)}catch{}}function J4(e){!e||!_4.test(e)||(KsA(eSA,e),KsA(tSA,String(Date.now())))}function Hke(){FsA(eSA),FsA(tSA)}function iSA(){try{const e=new URL(window.location.href),A=e.searchParams.get("inviter");if(A&&_4.test(A))return J4(A),A;const t=e.pathname.match(/(?:^|\/)i\/([^/?#]+)/i);if(t&&t[1]&&_4.test(t[1]))return J4(t[1]),t[1]}catch{}return null}const Oke=Object.freeze(Object.defineProperty({__proto__:null,captureInviterFromLocation:iSA,clearInviter:Hke,rememberInviter:J4},Symbol.toStringTag,{value:"Module"}));function Pke(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 jke(){const{info:e}=Fa();return xs({onCrapsBetError:A=>{try{const{title:t,subtitle:i}=Pke(A);e(t,i)}catch{}}}),null}function KV(e,{strict:A=!0}={}){return!e||typeof e!="string"?!1:A?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function _sA(e){return KV(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const nSA="2.37.9";let gk={getDocsUrl:({docsBaseUrl:e,docsPath:A="",docsSlug:t})=>A?`${e??"https://viem.sh"}${A}${t?`#${t}`:""}`:void 0,version:`viem@${nSA}`},Cl=class L4 extends Error{constructor(A,t={}){var s;const i=(()=>{var r;return t.cause instanceof L4?t.cause.details:(r=t.cause)!=null&&r.message?t.cause.message:t.details})(),n=t.cause instanceof L4&&t.cause.docsPath||t.docsPath,g=(s=gk.getDocsUrl)==null?void 0:s.call(gk,{...t,docsPath:n}),o=[A||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...g?[`Docs: ${g}`]:[],...i?[`Details: ${i}`]:[],...gk.version?[`Version: ${gk.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=nSA}walk(A){return gSA(this,A)}};function gSA(e,A){return A!=null&&A(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?gSA(e.cause,A):A?null:e}class zke 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 oSA 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 Ow(e,{dir:A,size:t=32}={}){return typeof e=="string"?Zke(e,{dir:A,size:t}):Wke(e,{dir:A,size:t})}function Zke(e,{dir:A,size:t=32}={}){if(t===null)return e;const i=e.replace("0x","");if(i.length>t*2)throw new oSA({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[A==="right"?"padEnd":"padStart"](t*2,"0")}`}function Wke(e,{dir:A,size:t=32}={}){if(t===null)return e;if(e.length>t)throw new oSA({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 Vke 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 Xke extends Cl{constructor({givenSize:A,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${A} bytes.`,{name:"SizeOverflowError"})}}function hG(e,{size:A}){if(_sA(e)>A)throw new Xke({givenSize:_sA(e),maxSize:A})}const $ke=Array.from({length:256},(e,A)=>A.toString(16).padStart(2,"0"));function WGe(e,A={}){return typeof e=="number"||typeof e=="bigint"?Aw(e,A):typeof e=="string"?rSA(e,A):typeof e=="boolean"?AMe(e,A):sSA(e,A)}function AMe(e,A={}){const t=`0x${Number(e)}`;return typeof A.size=="number"?(hG(t,{size:A.size}),Ow(t,{size:A.size})):t}function sSA(e,A={}){let t="";for(let n=0;n<e.length;n++)t+=$ke[e[n]];const i=`0x${t}`;return typeof A.size=="number"?(hG(i,{size:A.size}),Ow(i,{dir:"right",size:A.size})):i}function Aw(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 r=typeof e=="bigint"?"n":"";throw new Vke({max:g?`${g}${r}`:void 0,min:`${o}${r}`,signed:t,size:i,value:`${e}${r}`})}const s=`0x${(t&&n<0?(1n<<BigInt(i*8))+BigInt(n):n).toString(16)}`;return i?Ow(s,{size:i}):s}const eMe=new TextEncoder;function rSA(e,A={}){const t=eMe.encode(e);return sSA(t,A)}const tMe=new TextEncoder;function iMe(e,A={}){return typeof e=="number"||typeof e=="bigint"?gMe(e,A):typeof e=="boolean"?nMe(e,A):KV(e)?aSA(e,A):ISA(e,A)}function nMe(e,A={}){const t=new Uint8Array(1);return t[0]=Number(e),typeof A.size=="number"?(hG(t,{size:A.size}),Ow(t,{size:A.size})):t}const gE={zero:48,nine:57,A:65,F:70,a:97,f:102};function JsA(e){if(e>=gE.zero&&e<=gE.nine)return e-gE.zero;if(e>=gE.A&&e<=gE.F)return e-(gE.A-10);if(e>=gE.a&&e<=gE.f)return e-(gE.a-10)}function aSA(e,A={}){let t=e;A.size&&(hG(t,{size:A.size}),t=Ow(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 r=JsA(i.charCodeAt(s++)),a=JsA(i.charCodeAt(s++));if(r===void 0||a===void 0)throw new Cl(`Invalid byte sequence ("${i[s-2]}${i[s-1]}" in "${i}").`);g[o]=r*16+a}return g}function gMe(e,A){const t=Aw(e,A);return aSA(t)}function ISA(e,A={}){const t=tMe.encode(e);return typeof A.size=="number"?(hG(t,{size:A.size}),Ow(t,{dir:"right",size:A.size})):t}const Rv=BigInt(2**32-1),LsA=BigInt(32);function oMe(e,A=!1){return A?{h:Number(e&Rv),l:Number(e>>LsA&Rv)}:{h:Number(e>>LsA&Rv)|0,l:Number(e&Rv)|0}}function sMe(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}=oMe(e[g],A);[i[g],n[g]]=[o,s]}return[i,n]}const rMe=(e,A,t)=>e<<t|A>>>32-t,aMe=(e,A,t)=>A<<t|e>>>32-t,IMe=(e,A,t)=>A<<t-32|e>>>64-t,CMe=(e,A,t)=>e<<t-32|A>>>64-t;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function cMe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function xsA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function YJ(e,...A){if(!cMe(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 TsA(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 lMe(e,A){YJ(e);const t=A.outputLen;if(e.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function BMe(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function CSA(...e){for(let A=0;A<e.length;A++)e[A].fill(0)}const EMe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function QMe(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function uMe(e){for(let A=0;A<e.length;A++)e[A]=QMe(e[A]);return e}const qsA=EMe?e=>e:uMe;function dMe(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function cSA(e){return typeof e=="string"&&(e=dMe(e)),YJ(e),e}class hMe{}function pMe(e){const A=i=>e().update(cSA(i)).digest(),t=e();return A.outputLen=t.outputLen,A.blockLen=t.blockLen,A.create=()=>e(),A}const fMe=BigInt(0),ok=BigInt(1),yMe=BigInt(2),DMe=BigInt(7),mMe=BigInt(256),SMe=BigInt(113),lSA=[],BSA=[],ESA=[];for(let e=0,A=ok,t=1,i=0;e<24;e++){[t,i]=[i,(2*t+3*i)%5],lSA.push(2*(5*i+t)),BSA.push((e+1)*(e+2)/2%64);let n=fMe;for(let g=0;g<7;g++)A=(A<<ok^(A>>DMe)*SMe)%mMe,A&yMe&&(n^=ok<<(ok<<BigInt(g))-ok);ESA.push(n)}const QSA=sMe(ESA,!0),wMe=QSA[0],kMe=QSA[1],YsA=(e,A,t)=>t>32?IMe(e,A,t):rMe(e,A,t),HsA=(e,A,t)=>t>32?CMe(e,A,t):aMe(e,A,t);function MMe(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,r=(o+2)%10,a=t[r],I=t[r+1],c=YsA(a,I,1)^t[s],l=HsA(a,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=BSA[o],r=YsA(n,g,s),a=HsA(n,g,s),I=lSA[o];n=e[I],g=e[I+1],e[I]=r,e[I+1]=a}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]^=wMe[i],e[1]^=kMe[i]}CSA(t)}class FV extends hMe{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,xsA(i),!(0<A&&A<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=BMe(this.state)}clone(){return this._cloneInto()}keccak(){qsA(this.state32),MMe(this.state32,this.rounds),qsA(this.state32),this.posOut=0,this.pos=0}update(A){TsA(this),A=cSA(A),YJ(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){TsA(this,!1),YJ(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 xsA(A),this.xofInto(new Uint8Array(A))}digestInto(A){if(lMe(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,CSA(this.state)}_cloneInto(A){const{blockLen:t,suffix:i,outputLen:n,rounds:g,enableXOF:o}=this;return A||(A=new FV(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 NMe=(e,A,t)=>pMe(()=>new FV(A,e,t)),RMe=NMe(1,136,256/8);function GMe(e,A){return RMe(KV(e,{strict:!1})?iMe(e):e)}class _V 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 bMe=/^0x[a-fA-F0-9]{40}$/,FO=new _V(8192);function UMe(e,A){const{strict:t=!0}=A??{},i=`${e}.${t}`;if(FO.has(i))return FO.get(i);const n=bMe.test(e)?e.toLowerCase()===e?!0:t?uSA(e)===e:!0:!1;return FO.set(i,n),n}const _O=new _V(8192);function uSA(e,A){if(_O.has(`${e}.${A}`))return _O.get(`${e}.${A}`);const t=e.substring(2).toLowerCase(),i=GMe(ISA(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 _O.set(`${e}.${A}`,g),g}function fp(e,A){if(!UMe(e,{strict:!1}))throw new zke({address:e});return uSA(e,A)}function vMe(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),JV=e=>e;class vM 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: ${JV(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 dSA extends Cl{constructor({body:A,error:t,url:i}){super("RPC Request failed.",{cause:t,details:t.message,metaMessages:[`URL: ${JV(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 OsA extends Cl{constructor({body:A,url:t}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${JV(t)}`,`Request body: ${Zp(A)}`],name:"TimeoutError"})}}const KMe=-1;class dI 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 dSA?A.code:t??KMe}}class oC extends dI{constructor(A,t){super(A,t),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t.data}}class ON extends dI{constructor(A){super(A,{code:ON.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(ON,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class PN extends dI{constructor(A){super(A,{code:PN.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(PN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class jN extends dI{constructor(A,{method:t}={}){super(A,{code:jN.code,name:"MethodNotFoundRpcError",shortMessage:`The method${t?` "${t}"`:""} does not exist / is not available.`})}}Object.defineProperty(jN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class zN extends dI{constructor(A){super(A,{code:zN.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
`)})}}Object.defineProperty(zN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class ew extends dI{constructor(A){super(A,{code:ew.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(ew,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class ZN extends dI{constructor(A){super(A,{code:ZN.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
`)})}}Object.defineProperty(ZN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class WN extends dI{constructor(A){super(A,{code:WN.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(WN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class $u extends dI{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 VN extends dI{constructor(A){super(A,{code:VN.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(VN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class yp extends dI{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 tw extends dI{constructor(A){super(A,{code:tw.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(tw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class XN extends dI{constructor(A){super(A,{code:XN.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(XN,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Gs extends oC{constructor(A){super(A,{code:Gs.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Gs,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class $N extends oC{constructor(A){super(A,{code:$N.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty($N,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class AR extends oC{constructor(A,{method:t}={}){super(A,{code:AR.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}}Object.defineProperty(AR,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class eR extends oC{constructor(A){super(A,{code:eR.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(eR,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class tR extends oC{constructor(A){super(A,{code:tR.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(tR,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Dd extends oC{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 iR extends oC{constructor(A){super(A,{code:iR.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(iR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class nR extends oC{constructor(A){super(A,{code:nR.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(nR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class gR extends oC{constructor(A){super(A,{code:gR.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(gR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class oR extends oC{constructor(A){super(A,{code:oR.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(oR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class sR extends oC{constructor(A){super(A,{code:sR.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(sR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class rR extends oC{constructor(A){super(A,{code:rR.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(rR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class aR extends oC{constructor(A){super(A,{code:aR.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(aR,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class FMe extends dI{constructor(A){super(A,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}function _Me(){let e=()=>{},A=()=>{};return{promise:new Promise((i,n)=>{e=i,A=n}),resolve:e,reject:A}}const JO=new Map;function JMe({fn:e,id:A,shouldSplitBatch:t,wait:i=0,sort:n}){const g=async()=>{const I=r();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=()=>JO.delete(A),s=()=>r().map(({args:I})=>I),r=()=>JO.get(A)||[],a=I=>JO.set(A,[...r(),I]);return{flush:o,async schedule(I){const{promise:c,resolve:l,reject:B}=_Me();return(t==null?void 0:t([...s(),I]))&&g(),r().length>0?(a({args:I,resolve:l,reject:B}),c):(a({args:I,resolve:l,reject:B}),setTimeout(g,i),c)}}}const Gv=new _V(8192);function LMe(e,{enabled:A=!0,id:t}){if(!A||!t)return e();if(Gv.get(t))return Gv.get(t);const i=e().finally(()=>Gv.delete(t));return Gv.set(t,i),i}async function xMe(e){return new Promise(A=>setTimeout(A,e))}function hSA(e,{delay:A=100,retryCount:t=2,shouldRetry:i=()=>!0}={}){return new Promise((n,g)=>{const o=async({count:s=0}={})=>{const r=async({error:a})=>{const I=typeof A=="function"?A({count:s,error:a}):A;I&&await xMe(I),o({count:s+1})};try{const a=await e();n(a)}catch(a){if(s<t&&await i({count:s,error:a}))return r({error:a});g(a)}};o()})}function TMe(e,A={}){return async(t,i={})=>{var c;const{dedupe:n=!1,methods:g,retryDelay:o=150,retryCount:s=3,uid:r}={...A,...i},{method:a}=t;if((c=g==null?void 0:g.exclude)!=null&&c.includes(a))throw new yp(new Error("method not supported"),{method:a});if(g!=null&&g.include&&!g.include.includes(a))throw new yp(new Error("method not supported"),{method:a});const I=n?rSA(`${r}.${Zp(t)}`):void 0;return LMe(()=>hSA(async()=>{try{return await e(t)}catch(l){const B=l;switch(B.code){case ON.code:throw new ON(B);case PN.code:throw new PN(B);case jN.code:throw new jN(B,{method:t.method});case zN.code:throw new zN(B);case ew.code:throw new ew(B);case ZN.code:throw new ZN(B);case WN.code:throw new WN(B);case $u.code:throw new $u(B);case VN.code:throw new VN(B);case yp.code:throw new yp(B,{method:t.method});case tw.code:throw new tw(B);case XN.code:throw new XN(B);case Gs.code:throw new Gs(B);case $N.code:throw new $N(B);case AR.code:throw new AR(B);case eR.code:throw new eR(B);case tR.code:throw new tR(B);case Dd.code:throw new Dd(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 rR.code:throw new rR(B);case aR.code:throw new aR(B);case 5e3:throw new Gs(B);default:throw l instanceof Cl?l:new FMe(B)}}},{delay:({count:l,error:B})=>{var Q;if(B&&B instanceof vM){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})=>qMe(l)}),{enabled:n,id:I})}}function qMe(e){return"code"in e&&typeof e.code=="number"?e.code===-1||e.code===tw.code||e.code===ew.code:e instanceof vM&&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 pSA(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}function fSA(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 YMe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const PsA=YMe();function HMe(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,r={...A.fetchOptions??{},...t.fetchOptions??{}},{headers:a,method:I,signal:c}=r;try{const B=await fSA(async({signal:h})=>{const d={...r,body:Array.isArray(i)?Zp(i.map(D=>({jsonrpc:"2.0",id:D.id??PsA.take(),...D}))):Zp({jsonrpc:"2.0",id:i.id??PsA.take(),...i}),headers:{"Content-Type":"application/json",...a},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 OsA({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 vM({body:i,details:Zp(Q.error)||B.statusText,headers:B.headers,status:B.status,url:e});return Q}catch(B){throw B instanceof vM||B instanceof OsA?B:new vM({body:i,cause:B,url:e})}}}}const YK="2.21.2",OMe=()=>`@wagmi/core@${YK}`;var ySA=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)},HJ,DSA;class IR extends Error{get docsBaseUrl(){return"https://wagmi.sh/core"}get version(){return OMe()}constructor(A,t={}){var g;super(),HJ.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 IR?t.cause.details:(g=t.cause)!=null&&g.message?t.cause.message:t.details,n=t.cause instanceof IR&&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 ySA(this,HJ,"m",DSA).call(this,this,A)}}HJ=new WeakSet,DSA=function e(A,t){return t!=null&&t(A)?A:A.cause?ySA(this,HJ,"m",e).call(this,A.cause,t):A};class OJ extends IR{constructor(){super("Chain not configured."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ChainNotConfiguredError"})}}const x4=256;let bv=x4,Uv;function mSA(e=11){if(!Uv||bv+e>x4*2){Uv="",bv=0;for(let A=0;A<x4;A++)Uv+=(256+Math.random()*256|0).toString(16).substring(1)}return Uv.substring(bv,bv+++e)}function PMe(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),r=(t==null?void 0:t.blockTime)??12e3,a=Math.min(Math.max(Math.floor(r/2),500),4e3),I=e.pollingInterval??a,c=e.cacheTime??I,l=e.account?vMe(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:mSA(),...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 jMe({key:e,methods:A,name:t,request:i,retryCount:n=3,retryDelay:g=150,timeout:o,type:s},r){const a=mSA();return{config:{key:e,methods:A,name:t,request:i,retryCount:n,retryDelay:g,timeout:o,type:s},request:TMe(i,{methods:A,retryCount:n,retryDelay:g,uid:a}),value:r}}class zMe 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 jsA(e,A={}){const{batch:t,fetchFn:i,fetchOptions:n,key:g="http",methods:o,name:s="HTTP JSON-RPC",onFetchRequest:r,onFetchResponse:a,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 zMe;const D=HMe(m,{fetchFn:i,fetchOptions:n,onRequest:r,onResponse:a,timeout:y});return jMe({key:g,methods:o,name:s,async request({method:S,params:k}){const N={method:S,params:k},{schedule:G}=JMe({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 dSA({body:N,error:w,url:m});return b},retryCount:p,retryDelay:I,timeout:y,type:"http"},{fetchOptions:n,url:m})}}let LO=!1;async function ZMe(e,A={}){var a,I;if(LO)return[];LO=!0,e.setState(c=>({...c,status:c.current?"reconnecting":"connecting"}));const t=[];if((a=A.connectors)!=null&&a.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=[],r=[];for(const c of g){const l=await c.getProvider().catch(()=>{});if(!l||r.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}),r.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"}))),LO=!1,s}class tu extends IR{constructor(){super("Provider not found."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ProviderNotFoundError"})}}fT.type="injected";function fT(e={}){const{shimDisconnect:A=!0,unstable_shimAsyncInject:t}=e;function i(){const r=e.target;if(typeof r=="function"){const a=r();if(a)return a}return typeof r=="object"?r:typeof r=="string"?{...WMe[r]??{id:r,name:`${r[0].toUpperCase()}${r.slice(1)}`,provider:`is${r[0].toUpperCase()}${r.slice(1)}`}}:{id:"injected",name:"Injected",provider(a){return a==null?void 0:a.ethereum}}}let n,g,o,s;return r=>({get icon(){return i().icon},get id(){return i().id},get name(){return i().name},get supportsSimulation(){return!0},type:fT.type,async setup(){const a=await this.getProvider();a!=null&&a.on&&e.target&&(o||(o=this.onConnect.bind(this),a.on("connect",o)),n||(n=this.onAccountsChanged.bind(this),a.on("accountsChanged",n)))},async connect({chainId:a,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===Gs.code)throw new Gs(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(a&&D!==a){const S=await this.switchChain({chainId:a}).catch(k=>{if(k.code===Gs.code)throw k;return{id:D}});D=(S==null?void 0:S.id)??D}return A&&await((y=r.storage)==null?void 0:y.removeItem(`${this.id}.disconnected`)),e.target||await((m=r.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===Gs.code?new Gs(S):S.code===$u.code?new $u(S):S}},async disconnect(){var I,c;const a=await this.getProvider();if(!a)throw new tu;g&&(a.removeListener("chainChanged",g),g=void 0),s&&(a.removeListener("disconnect",s),s=void 0),o||(o=this.onConnect.bind(this),a.on("connect",o));try{await fSA(()=>a.request({method:"wallet_revokePermissions",params:[{eth_accounts:{}}]}),{timeout:100})}catch{}A&&await((I=r.storage)==null?void 0:I.setItem(`${this.id}.disconnected`,!0)),e.target||await((c=r.storage)==null?void 0:c.removeItem("injected.connected"))},async getAccounts(){const a=await this.getProvider();if(!a)throw new tu;return(await a.request({method:"eth_accounts"})).map(c=>fp(c))},async getChainId(){const a=await this.getProvider();if(!a)throw new tu;const I=await a.request({method:"eth_chainId"});return Number(I)},async getProvider(){if(typeof window>"u")return;let a;const I=i();return typeof I.provider=="function"?a=I.provider(window):typeof I.provider=="string"?a=HK(window,I.provider):a=I.provider,a&&!a.removeListener&&("off"in a&&typeof a.off=="function"?a.removeListener=a.off:a.removeListener=()=>{}),a},async isAuthorized(){var a,I;try{if(A&&await((a=r.storage)==null?void 0:a.getItem(`${this.id}.disconnected`))||!e.target&&!await((I=r.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 hSA(()=>this.getAccounts())).length}catch{return!1}},async switchChain({addEthereumChainParameter:a,chainId:I}){var Q,h,d,p;const c=await this.getProvider();if(!c)throw new tu;const l=r.chains.find(y=>y.id===I);if(!l)throw new Dd(new OJ);const B=new Promise(y=>{const m=D=>{"chainId"in D&&D.chainId===I&&(r.emitter.off("change",m),y())};r.emitter.on("change",m)});try{return await Promise.all([c.request({method:"wallet_switchEthereumChain",params:[{chainId:Aw(I)}]}).then(async()=>{await this.getChainId()===I&&r.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;a!=null&&a.blockExplorerUrls?k=a.blockExplorerUrls:D&&(k=[D.url,...Object.values(S).map(M=>M.url)]);let N;(d=a==null?void 0:a.rpcUrls)!=null&&d.length?N=a.rpcUrls:N=[((p=l.rpcUrls.default)==null?void 0:p.http[0])??""];const G={blockExplorerUrls:k,chainId:Aw(I),chainName:(a==null?void 0:a.chainName)??l.name,iconUrls:a==null?void 0:a.iconUrls,nativeCurrency:(a==null?void 0:a.nativeCurrency)??l.nativeCurrency,rpcUrls:N};return await Promise.all([c.request({method:"wallet_addEthereumChain",params:[G]}).then(async()=>{if(await this.getChainId()===I)r.emitter.emit("change",{chainId:I});else throw new Gs(new Error("User rejected switch after adding network."))}),B]),l}catch(D){throw new Gs(D)}throw m.code===Gs.code?new Gs(m):new Dd(m)}},async onAccountsChanged(a){var I;if(a.length===0)this.onDisconnect();else if(r.emitter.listenerCount("connect")){const c=(await this.getChainId()).toString();this.onConnect({chainId:c}),A&&await((I=r.storage)==null?void 0:I.removeItem(`${this.id}.disconnected`))}else r.emitter.emit("change",{accounts:a.map(c=>fp(c))})},onChainChanged(a){const I=Number(a);r.emitter.emit("change",{chainId:I})},async onConnect(a){const I=await this.getAccounts();if(I.length===0)return;const c=Number(a.chainId);r.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(a){const I=await this.getProvider();a&&a.code===1013&&I&&(await this.getAccounts()).length||(r.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 WMe={coinbaseWallet:{id:"coinbaseWallet",name:"Coinbase Wallet",provider(e){return e!=null&&e.coinbaseWalletExtension?e.coinbaseWalletExtension:HK(e,"isCoinbaseWallet")}},metaMask:{id:"metaMask",name:"MetaMask",provider(e){return HK(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:HK(e,"isPhantom")}}};function HK(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 VMe(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 XMe(){const e=new Set;let A=[];const t=()=>VMe(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 $Me=e=>(A,t,i)=>{const n=i.subscribe;return i.subscribe=(o,s,r)=>{let a=o;if(s){const I=(r==null?void 0:r.equalityFn)||Object.is;let c=o(i.getState());a=l=>{const B=o(l);if(!I(c,B)){const Q=c;s(c=B,Q)}},r!=null&&r.fireImmediately&&s(c,c)}return n(a)},e(A,t,i)},ANe=$Me;function eNe(e,A){let t;try{t=e()}catch{return}return{getItem:n=>{var g;const o=r=>r===null?null:JSON.parse(r,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 T4=e=>A=>{try{const t=e(A);return t instanceof Promise?t:{then(i){return T4(i)(t)},catch(i){return this}}}catch(t){return{then(i){return this},catch(i){return T4(i)(t)}}}},tNe=(e,A)=>(t,i,n)=>{let g={storage:eNe(()=>localStorage),partialize:h=>h,version:0,merge:(h,d)=>({...d,...h}),...A},o=!1;const s=new Set,r=new Set;let a=g.storage;if(!a)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 a.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(!a)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 T4(a.getItem.bind(a))(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,r.forEach(y=>y(B))}).catch(y=>{p==null||p(void 0,y)})};return n.persist={setOptions:h=>{g={...g,...h},h.storage&&(a=h.storage)},clearStorage:()=>{a==null||a.removeItem(g.name)},getOptions:()=>g,rehydrate:()=>Q(),hasHydrated:()=>o,onHydrate:h=>(s.add(h),()=>{s.delete(h)}),onFinishHydration:h=>(r.add(h),()=>{r.delete(h)})},g.skipHydration||Q(),B||l},iNe=tNe,zsA=e=>{let A;const t=new Set,i=(a,I)=>{const c=typeof a=="function"?a(A):a;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:()=>r,subscribe:a=>(t.add(a),()=>t.delete(a))},r=A=e(i,n,s);return s},xO=e=>e?zsA(e):zsA;var SSA={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(r,a,I){this.fn=r,this.context=a,this.once=I||!1}function g(r,a,I,c,l){if(typeof I!="function")throw new TypeError("The listener must be a function");var B=new n(I,c||r,l),Q=t?t+a:a;return r._events[Q]?r._events[Q].fn?r._events[Q]=[r._events[Q],B]:r._events[Q].push(B):(r._events[Q]=B,r._eventsCount++),r}function o(r,a){--r._eventsCount===0?r._events=new i:delete r._events[a]}function s(){this._events=new i,this._eventsCount=0}s.prototype.eventNames=function(){var a=[],I,c;if(this._eventsCount===0)return a;for(c in I=this._events)A.call(I,c)&&a.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(I)):a},s.prototype.listeners=function(a){var I=t?t+a:a,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(a){var I=t?t+a:a,c=this._events[I];return c?c.fn?1:c.length:0},s.prototype.emit=function(a,I,c,l,B,Q){var h=t?t+a:a;if(!this._events[h])return!1;var d=this._events[h],p=arguments.length,y,m;if(d.fn){switch(d.once&&this.removeListener(a,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(a,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(a,I,c){return g(this,a,I,c,!1)},s.prototype.once=function(a,I,c){return g(this,a,I,c,!0)},s.prototype.removeListener=function(a,I,c,l){var B=t?t+a:a;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(a){var I;return a?(I=t?t+a:a,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})(SSA);var nNe=SSA.exports;class gNe{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 nNe.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 oNe(e){return new gNe(e)}function sNe(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 ZsA(e,A){return e.slice(0,A).join(".")||"."}function WsA(e,A){const{length:t}=e;for(let i=0;i<t;++i)if(e[i]===A)return i+1;return 0}function rNe(e,A){const t=typeof e=="function",i=typeof A=="function",n=[],g=[];return function(s,r){if(typeof r=="object")if(n.length){const a=WsA(n,this);a===0?n[n.length]=this:(n.splice(a),g.splice(a)),g[g.length]=s;const I=WsA(n,r);if(I!==0)return i?A.call(this,s,r,ZsA(g,I)):`[ref=${ZsA(g,I)}]`}else n[0]=r,g[0]=s;return t?e.call(this,s,r):r}}function aNe(e,A,t,i){return JSON.stringify(e,rNe((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 wSA(e){const{deserialize:A=sNe,key:t="wagmi",serialize:i=aNe,storage:n=kSA}=e;function g(o){return o instanceof Promise?o.then(s=>s).catch(()=>null):o}return{...n,key:t,async getItem(o,s){const r=n.getItem(`${t}.${o}`),a=await g(r);return a?A(a)??null:s??null},async setItem(o,s){const r=`${t}.${o}`;s===null?await g(n.removeItem(r)):await g(n.setItem(r,i(s)))},async removeItem(o){await g(n.removeItem(`${t}.${o}`))}}}const kSA={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function INe(){const e=typeof window<"u"&&window.localStorage?window.localStorage:kSA;return{getItem(A){return e.getItem(A)},removeItem(A){e.removeItem(A)},setItem(A,t){try{e.setItem(A,t)}catch{}}}}const q4=256;let vv=q4,Kv;function CNe(e=11){if(!Kv||vv+e>q4*2){Kv="",vv=0;for(let A=0;A<q4;A++)Kv+=(256+Math.random()*256|0).toString(16).substring(1)}return Kv.substring(vv,vv+++e)}function cNe(e){const{multiInjectedProviderDiscovery:A=!0,storage:t=wSA({storage:INe()}),syncConnectedChain:i=!0,ssr:n=!1,...g}=e,o=typeof window<"u"&&A?XMe():void 0,s=xO(()=>g.chains),r=xO(()=>{const S=[],k=new Set;for(const N of g.connectors??[]){const G=a(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(a(I(G)))}return S});function a(S){var G;const k=oNe(CNe()),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 fT({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 OJ;{const M=c.get(d.getState().chainId);if(M&&!N)return M;if(!N)throw new OJ}{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=PMe({...b,chain:N,batch:b.batch??{multicall:!0},transport:K=>g.transports[M]({...K,connectors:r})})}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-";YK.startsWith(h)?Q=Number.parseInt(YK.replace(h,""),10):Q=Number.parseInt(YK.split(".")[0]??"0",10);const d=xO(ANe(t?iNe(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 r.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=a(I(M));k.has(w.id)||G.push(w)}t&&!d.persist.hasHydrated()||r.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=r.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 r.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:a,setState(S){return r.setState(typeof S=="function"?S(r.getState()):S,!0)},subscribe(S){return r.subscribe(S)}},events:{change:y,connect:m,disconnect:D}}}}function lNe(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 r;const g=new Set;for(const a of n??[])if(a.rdns){const I=Array.isArray(a.rdns)?a.rdns:[a.rdns];for(const c of I)g.add(c)}const o=[],s=((r=e._internal.mipd)==null?void 0:r.getProviders())??[];for(const a of s){if(g.has(a.info.rdns))continue;const I=e._internal.connectors.providerDetailToConnector(a),c=e._internal.connectors.setup(I);o.push(c)}return[...n,...o]})),i?ZMe(e):e.storage&&e.setState(n=>({...n,connections:new Map}))}}}const BNe={getItem(e){return typeof window>"u"?null:ENe(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 ENe(e,A){const t=e.split("; ").find(i=>i.startsWith(`${A}=`));if(t)return t.substring(A.length+1)}function QNe(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:r})=>(r==null?void 0:r.url)||t)}function uNe(e){const{children:A,config:t,initialState:i,reconnectOnMount:n=!0}=e,{onMount:g}=lNe(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 dNe=E.createContext(void 0);function hNe(e){const{children:A,config:t}=e,i={value:t};return E.createElement(uNe,e,E.createElement(dNe.Provider,i,A))}var yT=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(){}},pNe={setTimeout:(e,A)=>setTimeout(e,A),clearTimeout:e=>clearTimeout(e),setInterval:(e,A)=>setInterval(e,A),clearInterval:e=>clearInterval(e)},Cu,Z4,prA,fNe=(prA=class{constructor(){Tn(this,Cu,pNe);Tn(this,Z4,!1)}setTimeoutProvider(e){qi(this,Cu,e)}setTimeout(e,A){return tt(this,Cu).setTimeout(e,A)}clearTimeout(e){tt(this,Cu).clearTimeout(e)}setInterval(e,A){return tt(this,Cu).setInterval(e,A)}clearInterval(e){tt(this,Cu).clearInterval(e)}},Cu=new WeakMap,Z4=new WeakMap,prA),Y4=new fNe;function yNe(e){setTimeout(e,0)}var DT=typeof window>"u"||"Deno"in globalThis;function Rc(){}function DNe(e,A){return typeof e=="function"?e(A):e}function mNe(e){return typeof e=="number"&&e>=0&&e!==1/0}function SNe(e,A){return Math.max(e+(A||0)-Date.now(),0)}function H4(e,A){return typeof e=="function"?e(A):e}function wNe(e,A){return typeof e=="function"?e(A):e}function VsA(e,A){const{type:t="all",exact:i,fetchStatus:n,predicate:g,queryKey:o,stale:s}=e;if(o){if(i){if(A.queryHash!==LV(o,A.options))return!1}else if(!cR(A.queryKey,o))return!1}if(t!=="all"){const r=A.isActive();if(t==="active"&&!r||t==="inactive"&&r)return!1}return!(typeof s=="boolean"&&A.isStale()!==s||n&&n!==A.state.fetchStatus||g&&!g(A))}function XsA(e,A){const{exact:t,status:i,predicate:n,mutationKey:g}=e;if(g){if(!A.options.mutationKey)return!1;if(t){if(CR(A.options.mutationKey)!==CR(g))return!1}else if(!cR(A.options.mutationKey,g))return!1}return!(i&&A.state.status!==i||n&&!n(A))}function LV(e,A){return((A==null?void 0:A.queryKeyHashFn)||CR)(e)}function CR(e){return JSON.stringify(e,(A,t)=>O4(t)?Object.keys(t).sort().reduce((i,n)=>(i[n]=t[n],i),{}):t)}function cR(e,A){return e===A?!0:typeof e!=typeof A?!1:e&&A&&typeof e=="object"&&typeof A=="object"?Object.keys(A).every(t=>cR(e[t],A[t])):!1}var kNe=Object.prototype.hasOwnProperty;function MSA(e,A){if(e===A)return e;const t=$sA(e)&&$sA(A);if(!t&&!(O4(e)&&O4(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 r=0;for(let a=0;a<o;a++){const I=t?a:g[a],c=e[I],l=A[I];if(c===l){s[I]=c,(t?a<n:kNe.call(e,I))&&r++;continue}if(c===null||l===null||typeof c!="object"||typeof l!="object"){s[I]=l;continue}const B=MSA(c,l);s[I]=B,B===c&&r++}return n===o&&r===n?e:s}function $sA(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function O4(e){if(!ArA(e))return!1;const A=e.constructor;if(A===void 0)return!0;const t=A.prototype;return!(!ArA(t)||!t.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ArA(e){return Object.prototype.toString.call(e)==="[object Object]"}function MNe(e){return new Promise(A=>{Y4.setTimeout(A,e)})}function NNe(e,A,t){return typeof t.structuralSharing=="function"?t.structuralSharing(e,A):t.structuralSharing!==!1?MSA(e,A):A}function RNe(e,A,t=0){const i=[...e,A];return t&&i.length>t?i.slice(1):i}function GNe(e,A,t=0){const i=[A,...e];return t&&i.length>t?i.slice(0,-1):i}var xV=Symbol();function NSA(e,A){return!e.queryFn&&(A!=null&&A.initialPromise)?()=>A.initialPromise:!e.queryFn||e.queryFn===xV?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Dp,cu,$m,frA,bNe=(frA=class extends yT{constructor(){super();Tn(this,Dp);Tn(this,cu);Tn(this,$m);qi(this,$m,A=>{if(!DT&&window.addEventListener){const t=()=>A();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}})}onSubscribe(){tt(this,cu)||this.setEventListener(tt(this,$m))}onUnsubscribe(){var A;this.hasListeners()||((A=tt(this,cu))==null||A.call(this),qi(this,cu,void 0))}setEventListener(A){var t;qi(this,$m,A),(t=tt(this,cu))==null||t.call(this),qi(this,cu,A(i=>{typeof i=="boolean"?this.setFocused(i):this.onFocus()}))}setFocused(A){tt(this,Dp)!==A&&(qi(this,Dp,A),this.onFocus())}onFocus(){const A=this.isFocused();this.listeners.forEach(t=>{t(A)})}isFocused(){var A;return typeof tt(this,Dp)=="boolean"?tt(this,Dp):((A=globalThis.document)==null?void 0:A.visibilityState)!=="hidden"}},Dp=new WeakMap,cu=new WeakMap,$m=new WeakMap,frA),RSA=new bNe;function UNe(){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 vNe=yNe;function KNe(){let e=[],A=0,t=s=>{s()},i=s=>{s()},n=vNe;const g=s=>{A?e.push(s):n(()=>{t(s)})},o=()=>{const s=e;e=[],s.length&&n(()=>{i(()=>{s.forEach(r=>{t(r)})})})};return{batch:s=>{let r;A++;try{r=s()}finally{A--,A||o()}return r},batchCalls:s=>(...r)=>{g(()=>{s(...r)})},schedule:g,setNotifyFunction:s=>{t=s},setBatchNotifyFunction:s=>{i=s},setScheduler:s=>{n=s}}}var ma=KNe(),AS,lu,eS,yrA,FNe=(yrA=class extends yT{constructor(){super();Tn(this,AS,!0);Tn(this,lu);Tn(this,eS);qi(this,eS,A=>{if(!DT&&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(){tt(this,lu)||this.setEventListener(tt(this,eS))}onUnsubscribe(){var A;this.hasListeners()||((A=tt(this,lu))==null||A.call(this),qi(this,lu,void 0))}setEventListener(A){var t;qi(this,eS,A),(t=tt(this,lu))==null||t.call(this),qi(this,lu,A(this.setOnline.bind(this)))}setOnline(A){tt(this,AS)!==A&&(qi(this,AS,A),this.listeners.forEach(i=>{i(A)}))}isOnline(){return tt(this,AS)}},AS=new WeakMap,lu=new WeakMap,eS=new WeakMap,yrA),PJ=new FNe;function _Ne(e){return Math.min(1e3*2**e,3e4)}function GSA(e){return(e??"online")==="online"?PJ.isOnline():!0}var P4=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function bSA(e){let A=!1,t=0,i;const n=UNe(),g=()=>n.status!=="pending",o=h=>{var d;if(!g()){const p=new P4(h);l(p),(d=e.onCancel)==null||d.call(e,p)}},s=()=>{A=!0},r=()=>{A=!1},a=()=>RSA.isFocused()&&(e.networkMode==="always"||PJ.isOnline())&&e.canRun(),I=()=>GSA(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()||a())&&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??(DT?0:3),m=e.retryDelay??_Ne,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),MNe(D).then(()=>a()?void 0:B()).then(()=>{A?l(p):Q()})})};return{promise:n,status:()=>n.status,cancel:o,continue:()=>(i==null||i(),n),cancelRetry:s,continueRetry:r,canStart:I,start:()=>(I()?Q():B().then(Q),n)}}var mp,DrA,USA=(DrA=class{constructor(){Tn(this,mp)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),mNe(this.gcTime)&&qi(this,mp,Y4.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(DT?1/0:5*60*1e3))}clearGcTimeout(){tt(this,mp)&&(Y4.clearTimeout(tt(this,mp)),qi(this,mp,void 0))}},mp=new WeakMap,DrA),Sp,tS,GC,wp,Ps,lR,kp,Gc,rE,mrA,JNe=(mrA=class extends USA{constructor(A){super();Tn(this,Gc);Tn(this,Sp);Tn(this,tS);Tn(this,GC);Tn(this,wp);Tn(this,Ps);Tn(this,lR);Tn(this,kp);qi(this,kp,!1),qi(this,lR,A.defaultOptions),this.setOptions(A.options),this.observers=[],qi(this,wp,A.client),qi(this,GC,tt(this,wp).getQueryCache()),this.queryKey=A.queryKey,this.queryHash=A.queryHash,qi(this,Sp,erA(this.options)),this.state=A.state??tt(this,Sp),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var A;return(A=tt(this,Ps))==null?void 0:A.promise}setOptions(A){if(this.options={...tt(this,lR),...A},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=erA(this.options);t.data!==void 0&&(this.setData(t.data,{updatedAt:t.dataUpdatedAt,manual:!0}),qi(this,Sp,t))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&tt(this,GC).remove(this)}setData(A,t){const i=NNe(this.state.data,A,this.options);return _r(this,Gc,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){_r(this,Gc,rE).call(this,{type:"setState",state:A,setStateOptions:t})}cancel(A){var i,n;const t=(i=tt(this,Ps))==null?void 0:i.promise;return(n=tt(this,Ps))==null||n.cancel(A),t?t.then(Rc).catch(Rc):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(tt(this,Sp))}isActive(){return this.observers.some(A=>wNe(A.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===xV||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(A=>H4(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:!SNe(this.state.dataUpdatedAt,A)}onFocus(){var t;const A=this.observers.find(i=>i.shouldFetchOnWindowFocus());A==null||A.refetch({cancelRefetch:!1}),(t=tt(this,Ps))==null||t.continue()}onOnline(){var t;const A=this.observers.find(i=>i.shouldFetchOnReconnect());A==null||A.refetch({cancelRefetch:!1}),(t=tt(this,Ps))==null||t.continue()}addObserver(A){this.observers.includes(A)||(this.observers.push(A),this.clearGcTimeout(),tt(this,GC).notify({type:"observerAdded",query:this,observer:A}))}removeObserver(A){this.observers.includes(A)&&(this.observers=this.observers.filter(t=>t!==A),this.observers.length||(tt(this,Ps)&&(tt(this,kp)?tt(this,Ps).cancel({revert:!0}):tt(this,Ps).cancelRetry()),this.scheduleGc()),tt(this,GC).notify({type:"observerRemoved",query:this,observer:A}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||_r(this,Gc,rE).call(this,{type:"invalidate"})}async fetch(A,t){var r,a,I,c,l,B,Q,h,d,p,y,m;if(this.state.fetchStatus!=="idle"&&((r=tt(this,Ps))==null?void 0:r.status())!=="rejected"){if(this.state.data!==void 0&&(t!=null&&t.cancelRefetch))this.cancel({silent:!0});else if(tt(this,Ps))return tt(this,Ps).continueRetry(),tt(this,Ps).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:()=>(qi(this,kp,!0),i.signal)})},g=()=>{const D=NSA(this.options,t),k=(()=>{const N={client:tt(this,wp),queryKey:this.queryKey,meta:this.meta};return n(N),N})();return qi(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:tt(this,wp),state:this.state,fetchFn:g};return n(D),D})();(a=this.options.behavior)==null||a.onFetch(s,this),qi(this,tS,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((I=s.fetchOptions)==null?void 0:I.meta))&&_r(this,Gc,rE).call(this,{type:"fetch",meta:(c=s.fetchOptions)==null?void 0:c.meta}),qi(this,Ps,bSA({initialPromise:t==null?void 0:t.initialPromise,fn:s.fetchFn,onCancel:D=>{D instanceof P4&&D.revert&&this.setState({...tt(this,tS),fetchStatus:"idle"}),i.abort()},onFail:(D,S)=>{_r(this,Gc,rE).call(this,{type:"failed",failureCount:D,error:S})},onPause:()=>{_r(this,Gc,rE).call(this,{type:"pause"})},onContinue:()=>{_r(this,Gc,rE).call(this,{type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}));try{const D=await tt(this,Ps).start();if(D===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(D),(B=(l=tt(this,GC).config).onSuccess)==null||B.call(l,D,this),(h=(Q=tt(this,GC).config).onSettled)==null||h.call(Q,D,this.state.error,this),D}catch(D){if(D instanceof P4){if(D.silent)return tt(this,Ps).promise;if(D.revert){if(this.state.data===void 0)throw D;return this.state.data}}throw _r(this,Gc,rE).call(this,{type:"error",error:D}),(p=(d=tt(this,GC).config).onError)==null||p.call(d,D,this),(m=(y=tt(this,GC).config).onSettled)==null||m.call(y,this.state.data,D,this),D}finally{this.scheduleGc()}}},Sp=new WeakMap,tS=new WeakMap,GC=new WeakMap,wp=new WeakMap,Ps=new WeakMap,lR=new WeakMap,kp=new WeakMap,Gc=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,...LNe(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 qi(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),ma.batch(()=>{this.observers.forEach(i=>{i.onQueryUpdate()}),tt(this,GC).notify({query:this,type:"updated",action:A})})},mrA);function LNe(e,A){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GSA(A.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function erA(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 trA(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:[]},r=0;const a=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=NSA(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?GNe:RNe;return{pages:w(m.pages,G,M),pageParams:w(m.pageParams,D,M)}};if(n&&g.length){const m=n==="backward",D=m?xNe:irA,S={pages:g,pageParams:o},k=D(i,S);s=await y(S,k,m)}else{const m=e??g.length;do{const D=r===0?o[0]??i.initialPageParam:irA(i,s);if(r>0&&D==null)break;s=await y(s,D),r++}while(r<m)}return s};A.options.persister?A.fetchFn=()=>{var h,d;return(d=(h=A.options).persister)==null?void 0:d.call(h,a,{client:A.client,queryKey:A.queryKey,meta:A.options.meta,signal:A.signal},t)}:A.fetchFn=a}}}function irA(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 xNe(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 BR,Pl,Ea,Mp,jl,WQ,SrA,TNe=(SrA=class extends USA{constructor(A){super();Tn(this,jl);Tn(this,BR);Tn(this,Pl);Tn(this,Ea);Tn(this,Mp);qi(this,BR,A.client),this.mutationId=A.mutationId,qi(this,Ea,A.mutationCache),qi(this,Pl,[]),this.state=A.state||qNe(),this.setOptions(A.options),this.scheduleGc()}setOptions(A){this.options=A,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(A){tt(this,Pl).includes(A)||(tt(this,Pl).push(A),this.clearGcTimeout(),tt(this,Ea).notify({type:"observerAdded",mutation:this,observer:A}))}removeObserver(A){qi(this,Pl,tt(this,Pl).filter(t=>t!==A)),this.scheduleGc(),tt(this,Ea).notify({type:"observerRemoved",mutation:this,observer:A})}optionalRemove(){tt(this,Pl).length||(this.state.status==="pending"?this.scheduleGc():tt(this,Ea).remove(this))}continue(){var A;return((A=tt(this,Mp))==null?void 0:A.continue())??this.execute(this.state.variables)}async execute(A){var o,s,r,a,I,c,l,B,Q,h,d,p,y,m,D,S,k,N,G,M;const t=()=>{_r(this,jl,WQ).call(this,{type:"continue"})},i={client:tt(this,BR),meta:this.options.meta,mutationKey:this.options.mutationKey};qi(this,Mp,bSA({fn:()=>this.options.mutationFn?this.options.mutationFn(A,i):Promise.reject(new Error("No mutationFn found")),onFail:(w,b)=>{_r(this,jl,WQ).call(this,{type:"failed",failureCount:w,error:b})},onPause:()=>{_r(this,jl,WQ).call(this,{type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>tt(this,Ea).canRun(this)}));const n=this.state.status==="pending",g=!tt(this,Mp).canStart();try{if(n)t();else{_r(this,jl,WQ).call(this,{type:"pending",variables:A,isPaused:g}),await((s=(o=tt(this,Ea).config).onMutate)==null?void 0:s.call(o,A,this,i));const b=await((a=(r=this.options).onMutate)==null?void 0:a.call(r,A,i));b!==this.state.context&&_r(this,jl,WQ).call(this,{type:"pending",context:b,variables:A,isPaused:g})}const w=await tt(this,Mp).start();return await((c=(I=tt(this,Ea).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=tt(this,Ea).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)),_r(this,jl,WQ).call(this,{type:"success",data:w}),w}catch(w){try{throw await((m=(y=tt(this,Ea).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=tt(this,Ea).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{_r(this,jl,WQ).call(this,{type:"error",error:w})}}finally{tt(this,Ea).runNext(this)}}},BR=new WeakMap,Pl=new WeakMap,Ea=new WeakMap,Mp=new WeakMap,jl=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),ma.batch(()=>{tt(this,Pl).forEach(i=>{i.onMutationUpdate(A)}),tt(this,Ea).notify({mutation:this,type:"updated",action:A})})},SrA);function qNe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var EE,bc,ER,wrA,YNe=(wrA=class extends yT{constructor(A={}){super();Tn(this,EE);Tn(this,bc);Tn(this,ER);this.config=A,qi(this,EE,new Set),qi(this,bc,new Map),qi(this,ER,0)}build(A,t,i){const n=new TNe({client:A,mutationCache:this,mutationId:++WG(this,ER)._,options:A.defaultMutationOptions(t),state:i});return this.add(n),n}add(A){tt(this,EE).add(A);const t=Fv(A);if(typeof t=="string"){const i=tt(this,bc).get(t);i?i.push(A):tt(this,bc).set(t,[A])}this.notify({type:"added",mutation:A})}remove(A){if(tt(this,EE).delete(A)){const t=Fv(A);if(typeof t=="string"){const i=tt(this,bc).get(t);if(i)if(i.length>1){const n=i.indexOf(A);n!==-1&&i.splice(n,1)}else i[0]===A&&tt(this,bc).delete(t)}}this.notify({type:"removed",mutation:A})}canRun(A){const t=Fv(A);if(typeof t=="string"){const i=tt(this,bc).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=Fv(A);if(typeof t=="string"){const n=(i=tt(this,bc).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(){ma.batch(()=>{tt(this,EE).forEach(A=>{this.notify({type:"removed",mutation:A})}),tt(this,EE).clear(),tt(this,bc).clear()})}getAll(){return Array.from(tt(this,EE))}find(A){const t={exact:!0,...A};return this.getAll().find(i=>XsA(t,i))}findAll(A={}){return this.getAll().filter(t=>XsA(A,t))}notify(A){ma.batch(()=>{this.listeners.forEach(t=>{t(A)})})}resumePausedMutations(){const A=this.getAll().filter(t=>t.state.isPaused);return ma.batch(()=>Promise.all(A.map(t=>t.continue().catch(Rc))))}},EE=new WeakMap,bc=new WeakMap,ER=new WeakMap,wrA);function Fv(e){var A;return(A=e.options.scope)==null?void 0:A.id}var zl,krA,HNe=(krA=class extends yT{constructor(A={}){super();Tn(this,zl);this.config=A,qi(this,zl,new Map)}build(A,t,i){const n=t.queryKey,g=t.queryHash??LV(n,t);let o=this.get(g);return o||(o=new JNe({client:A,queryKey:n,queryHash:g,options:A.defaultQueryOptions(t),state:i,defaultOptions:A.getQueryDefaults(n)}),this.add(o)),o}add(A){tt(this,zl).has(A.queryHash)||(tt(this,zl).set(A.queryHash,A),this.notify({type:"added",query:A}))}remove(A){const t=tt(this,zl).get(A.queryHash);t&&(A.destroy(),t===A&&tt(this,zl).delete(A.queryHash),this.notify({type:"removed",query:A}))}clear(){ma.batch(()=>{this.getAll().forEach(A=>{this.remove(A)})})}get(A){return tt(this,zl).get(A)}getAll(){return[...tt(this,zl).values()]}find(A){const t={exact:!0,...A};return this.getAll().find(i=>VsA(t,i))}findAll(A={}){const t=this.getAll();return Object.keys(A).length>0?t.filter(i=>VsA(A,i)):t}notify(A){ma.batch(()=>{this.listeners.forEach(t=>{t(A)})})}onFocus(){ma.batch(()=>{this.getAll().forEach(A=>{A.onFocus()})})}onOnline(){ma.batch(()=>{this.getAll().forEach(A=>{A.onOnline()})})}},zl=new WeakMap,krA),bo,Bu,Eu,iS,nS,Qu,gS,oS,MrA,ONe=(MrA=class{constructor(e={}){Tn(this,bo);Tn(this,Bu);Tn(this,Eu);Tn(this,iS);Tn(this,nS);Tn(this,Qu);Tn(this,gS);Tn(this,oS);qi(this,bo,e.queryCache||new HNe),qi(this,Bu,e.mutationCache||new YNe),qi(this,Eu,e.defaultOptions||{}),qi(this,iS,new Map),qi(this,nS,new Map),qi(this,Qu,0)}mount(){WG(this,Qu)._++,tt(this,Qu)===1&&(qi(this,gS,RSA.subscribe(async e=>{e&&(await this.resumePausedMutations(),tt(this,bo).onFocus())})),qi(this,oS,PJ.subscribe(async e=>{e&&(await this.resumePausedMutations(),tt(this,bo).onOnline())})))}unmount(){var e,A;WG(this,Qu)._--,tt(this,Qu)===0&&((e=tt(this,gS))==null||e.call(this),qi(this,gS,void 0),(A=tt(this,oS))==null||A.call(this),qi(this,oS,void 0))}isFetching(e){return tt(this,bo).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return tt(this,Bu).findAll({...e,status:"pending"}).length}getQueryData(e){var t;const A=this.defaultQueryOptions({queryKey:e});return(t=tt(this,bo).get(A.queryHash))==null?void 0:t.state.data}ensureQueryData(e){const A=this.defaultQueryOptions(e),t=tt(this,bo).build(this,A),i=t.state.data;return i===void 0?this.fetchQuery(e):(e.revalidateIfStale&&t.isStaleByTime(H4(A.staleTime,t))&&this.prefetchQuery(A),Promise.resolve(i))}getQueriesData(e){return tt(this,bo).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=tt(this,bo).get(i.queryHash),g=n==null?void 0:n.state.data,o=DNe(A,g);if(o!==void 0)return tt(this,bo).build(this,i).setData(o,{...t,manual:!0})}setQueriesData(e,A,t){return ma.batch(()=>tt(this,bo).findAll(e).map(({queryKey:i})=>[i,this.setQueryData(i,A,t)]))}getQueryState(e){var t;const A=this.defaultQueryOptions({queryKey:e});return(t=tt(this,bo).get(A.queryHash))==null?void 0:t.state}removeQueries(e){const A=tt(this,bo);ma.batch(()=>{A.findAll(e).forEach(t=>{A.remove(t)})})}resetQueries(e,A){const t=tt(this,bo);return ma.batch(()=>(t.findAll(e).forEach(i=>{i.reset()}),this.refetchQueries({type:"active",...e},A)))}cancelQueries(e,A={}){const t={revert:!0,...A},i=ma.batch(()=>tt(this,bo).findAll(e).map(n=>n.cancel(t)));return Promise.all(i).then(Rc).catch(Rc)}invalidateQueries(e,A={}){return ma.batch(()=>(tt(this,bo).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=ma.batch(()=>tt(this,bo).findAll(e).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let g=n.fetch(void 0,t);return t.throwOnError||(g=g.catch(Rc)),n.state.fetchStatus==="paused"?Promise.resolve():g}));return Promise.all(i).then(Rc)}fetchQuery(e){const A=this.defaultQueryOptions(e);A.retry===void 0&&(A.retry=!1);const t=tt(this,bo).build(this,A);return t.isStaleByTime(H4(A.staleTime,t))?t.fetch(A):Promise.resolve(t.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Rc).catch(Rc)}fetchInfiniteQuery(e){return e.behavior=trA(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Rc).catch(Rc)}ensureInfiniteQueryData(e){return e.behavior=trA(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return PJ.isOnline()?tt(this,Bu).resumePausedMutations():Promise.resolve()}getQueryCache(){return tt(this,bo)}getMutationCache(){return tt(this,Bu)}getDefaultOptions(){return tt(this,Eu)}setDefaultOptions(e){qi(this,Eu,e)}setQueryDefaults(e,A){tt(this,iS).set(CR(e),{queryKey:e,defaultOptions:A})}getQueryDefaults(e){const A=[...tt(this,iS).values()],t={};return A.forEach(i=>{cR(e,i.queryKey)&&Object.assign(t,i.defaultOptions)}),t}setMutationDefaults(e,A){tt(this,nS).set(CR(e),{mutationKey:e,defaultOptions:A})}getMutationDefaults(e){const A=[...tt(this,nS).values()],t={};return A.forEach(i=>{cR(e,i.mutationKey)&&Object.assign(t,i.defaultOptions)}),t}defaultQueryOptions(e){if(e._defaulted)return e;const A={...tt(this,Eu).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return A.queryHash||(A.queryHash=LV(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===xV&&(A.enabled=!1),A}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...tt(this,Eu).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){tt(this,bo).clear(),tt(this,Bu).clear()}},bo=new WeakMap,Bu=new WeakMap,Eu=new WeakMap,iS=new WeakMap,nS=new WeakMap,Qu=new WeakMap,gS=new WeakMap,oS=new WeakMap,MrA),PNe=E.createContext(void 0),jNe=({client:e,children:A})=>(E.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),C.jsx(PNe.Provider,{value:e,children:A}));const vSA=pSA({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}}}),KSA=pSA({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}}});TV.type="walletConnect";function TV(e){const A=e.isNewChainsStale??!0;let t,i;const n="eip155";let g,o,s,r,a,I;return c=>({id:"walletConnect",name:"WalletConnect",type:TV.type,async setup(){const l=await this.getProvider().catch(()=>null);l&&(s||(s=this.onConnect.bind(this),l.on("connect",s)),a||(a=this.onSessionDelete.bind(this),l.on("session_delete",a)))},async connect({chainId:l,withCapabilities:B,...Q}={}){var h,d;try{const p=await this.getProvider();if(!p)throw new tu;r||(r=this.onDisplayUri,p.on("display_uri",r));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===Gs.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 r&&(p.removeListener("display_uri",r),r=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)),a||(a=this.onSessionDelete.bind(this),p.on("session_delete",a)),{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 Gs(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),a&&(l==null||l.removeListener("session_delete",a),a=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 li(async()=>{const{EthereumProvider:p}=await import("./index.es-BiYYXYFK.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]=QNe({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 OJ);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:Aw(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 Gs(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:Aw(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 Gs(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),a&&(B.removeListener("session_delete",a),a=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 TO={};const zNe=[vSA,KSA],ZNe=new ONe,WNe=wSA({storage:BNe});function VNe(){const e=!!(import.meta.vitest||typeof process<"u"&&(TO!=null&&TO.VITEST_WORKER_ID)),A=[fT({shimDisconnect:!0})];if(e)console.info("[wallet] test environment detected – skipping walletConnect connector");else try{A.push(TV({projectId:"demo",showQrModal:!0}))}catch(t){console.warn("[wallet] walletConnect initialization skipped:",(t==null?void 0:t.message)||t)}return cNe({chains:zNe,multiInjectedProviderDiscovery:!0,transports:{[vSA.id]:jsA(),[KSA.id]:jsA()},connectors:A,ssr:!1,storage:WNe,syncConnectedChain:!0})}function XNe({children:e}){const A=VNe();return C.jsx(hNe,{config:A,children:C.jsx(jNe,{client:ZNe,children:e})})}E.createContext(void 0);const FSA=E.createContext(void 0);async function $Ne(){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 ARe({children:e}){const[A,t]=E.useState(!1),[i,n]=E.useState(!1),g=async()=>{var s;const o=await $Ne();n(!!((s=o==null?void 0:o.features)!=null&&s.wallet)),t(!0)};return E.useEffect(()=>{const o=g(),s=window.setTimeout(()=>{t(r=>(r||console.warn("[features] fallback timeout - forcing loaded"),!0))},6e3);return o.finally(()=>clearTimeout(s)),()=>clearTimeout(s)},[]),C.jsx(FSA.Provider,{value:{loaded:A,walletEnabled:i,refresh:g},children:e})}function eRe(){return E.useContext(FSA)??{loaded:!0,walletEnabled:!1,refresh:()=>{}}}var nrA;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(nrA||(nrA={}));var grA;(function(e){e.StatusBar="STATUS_BAR",e.NavigationBar="NAVIGATION_BAR"})(grA||(grA={}));const PQ=nl("SafeArea",{web:()=>li(()=>import("./web-CKj7sOmP.js"),__vite__mapDeps([20,1])).then(e=>new e.SafeAreaWeb)});class _SA extends he.Component{constructor(){super(...arguments);Ti(this,"state",{hasError:!1});Ti(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,r;(o=(g=this.props).onError)==null||o.call(g,t,i),X1.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:(r=i==null?void 0:i.componentStack)==null?void 0:r.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 orA;(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"})(orA||(orA={}));const rp=nl("LocalNotifications",{web:()=>li(()=>import("./web-DwQT5qhV.js"),__vite__mapDeps([21,1])).then(e=>new e.LocalNotificationsWeb)});let j4=null,srA=!1,_v=null;function tRe(){return j4||srA?Promise.resolve():_v||(srA=!0,_v=li(()=>import("./index-aO2K69ae.js"),__vite__mapDeps([22,1])).then(e=>{const A=e.FirebaseMessaging;A&&typeof A.getToken=="function"?(j4=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)}),_v)}function iRe(){return j4}let rrA=!1,iw=null;async function JSA(e={}){if(rrA)return;rrA=!0;const A=ti.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 nRe()}catch{}if(n)try{await gRe(e.onPushToken)}catch(g){console.warn("[Push] Setup failed:",g)}}async function nRe(){var e;try{if((await rp.requestPermissions()).display!=="granted")return}catch{}try{await((e=rp.createChannel)==null?void 0:e.call(rp,{id:"default",name:"General",description:"General notifications",importance:4,visibility:1,sound:void 0,lights:!0,vibration:!0}))}catch{}try{rp.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&&LSA({notification:{data:t}})})}catch{}}async function gRe(e){console.info("[Push] setupPushNotifications starting..."),await tRe();const A=iRe();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)+"..."),iw=t;try{e==null||e(t)}catch{}nw(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)+"..."),iw=t;try{e==null||e(t)}catch{}nw(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;xSA(n,g||"",o).catch(()=>{})}),A.addListener("notificationActionPerformed",t=>{console.info("[Push] action performed",t),LSA(t)})}let OK=!1,qO=!1,tp=0,z4=0;const YO=10,oRe=5e3;function sRe(){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 nw(e){const A=e||iw;if(!A){console.warn("[Push] registerPushTokenWithServer called but no token available");return}if(OK&&A===iw){console.info("[Push] Token already registered, skipping");return}if(qO){console.info("[Push] Token registration already pending, skipping");return}const t=ti.getPlatform();if(t==="web"){console.info("[Push] Web platform, skipping token registration");return}const i=pw();if(console.info(`[Push] Socket state: exists=${!!i} connected=${i==null?void 0:i.connected}`),!(i!=null&&i.connected)){tp++,tp<=YO?(console.info(`[Push] Socket not connected, will retry (${tp}/${YO})`),setTimeout(()=>nw(A),2e3)):console.warn("[Push] Max registration retries reached, giving up");return}const n=sRe(),g=A.substring(0,20)+"..."+A.substring(A.length-10);console.info(`[Push] Registering token: ${g} platform=${t} appId=${n}`),qO=!0,i.emit("push:register_token",{token:A,platform:t,appId:n},o=>{qO=!1,o!=null&&o.success?(OK=!0,tp=0,z4=Date.now(),console.info("[Push] ✅ Token registered with server successfully")):(console.warn("[Push] ❌ Token registration failed:",o==null?void 0:o.error),!OK&&tp<YO&&(tp++,setTimeout(()=>nw(A),3e3)))})}function rRe(){if(iw){const e=Date.now();if(e-z4<oRe){console.info("[Push] Skipping re-register (debounce)");return}z4=e,OK=!1,tp=0,console.info("[Push] Re-registering token after reconnect"),nw(iw)}}function LSA(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 xSA(e,A,t){if(!(ti.getPlatform()==="ios"||ti.getPlatform()==="android"))return;try{if((await rp.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 rp.schedule(g)}catch{}}const aRe=Object.freeze(Object.defineProperty({__proto__:null,initNotifications:JSA,reRegisterPushToken:rRe,registerPushTokenWithServer:nw,scheduleLocalNow:xSA},Symbol.toStringTag,{value:"Module"}));function IRe({cooldownMs:e=5e3,initialGraceMs:A=900}){const t=Ss(),{room:i}=tI(),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 r=Date.now();try{window.__fgMountedAt=r}catch{}try{console.log("[fg] BotNudgeOnForeground mounted",{t:r,hint:"enable logs via ?debugForeground=1 or localStorage.setItem('debug:foreground','1')"})}catch{}},[]),E.useEffect(()=>{let r=[],a=!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(a)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 sP(t,Kt.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 xcA(t,Kt.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(a)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 iM(t)}catch{}try{const S=await sP(t,Kt.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 Ma.addListener("appStateChange",y=>{if(!a)if(y.isActive)I&&console.log("[fg] appStateChange: active"),(async()=>{try{await iM(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{}r.push(()=>{try{p.remove()}catch{}})}catch{I&&console.log("[fg] appStateChange not available (web or plugin missing)")}})(),(async()=>{try{const p=await Ma.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{}r.push(()=>{try{p.remove()}catch{}})}catch{I&&console.log("[fg] pause not available")}})(),(async()=>{try{const p=await Ma.addListener("resume",async()=>{I&&console.log("[fg] resume");try{await iM(t)}catch{}c("native_resume",!0),l("native_resume")});I&&console.log("[fg] resume listener attached");try{window.__fgResumeListener=!0}catch{}r.push(()=>{try{p.remove()}catch{}})}catch{I&&console.log("[fg] resume not available")}})();const B=()=>{a||document.visibilityState==="visible"&&(I&&console.log("[fg] visibility: visible"),c("web_visibility"),l("web_visibility"))};document.addEventListener("visibilitychange",B),r.push(()=>document.removeEventListener("visibilitychange",B));const Q=()=>{a||(I&&console.log("[fg] window focus"),c("web_focus"),l("web_focus"))},h=()=>{a||(I&&console.log("[fg] window pageshow"),c("web_pageshow"),l("web_pageshow"))};window.addEventListener("focus",Q),window.addEventListener("pageshow",h),r.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 r.push(()=>clearTimeout(d)),()=>{a=!0,r.forEach(p=>{try{p()}catch{}})}},[t,i==null?void 0:i.id,e]),null}function cr(){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 CRe(){const e=Ss(),A=E.useRef(Date.now());return E.useEffect(()=>{let t=!1;const i=[];Ns.info("NativeCrashLogger mounted",{mem:cr()});async function n(){const g=[Ma.addListener("appStateChange",s=>{t||(s.isActive?Ns.info("appStateChange → ACTIVE",{mem:cr(),since:Date.now()-A.current}):Ns.warn("appStateChange → INACTIVE",{mem:cr()}))}),Ma.addListener("pause",()=>{t||Ns.warn("PAUSE (backgrounded)",{mem:cr()})}),Ma.addListener("resume",()=>{t||Ns.info("RESUME (foregrounded)",{mem:cr()})}),Ma.addListener("backButton",()=>{t||Ns.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"?Ns.warn("visibility → HIDDEN",{mem:cr()}):Ns.info("visibility → VISIBLE",{mem:cr()})},i=()=>Ns.info("network → ONLINE"),n=()=>Ns.warn("network → OFFLINE"),g=()=>Ns.error("PAGE FREEZE (frozen)",{mem:cr()}),o=r=>Ns.warn("pagehide",{persisted:r.persisted,mem:cr()}),s=r=>Ns.info("pageshow",{persisted:r.persisted,mem:cr()});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 UC.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=>UC.warn("DISCONNECTED",{reason:y,mem:cr()}),g=y=>{const m=String((y==null?void 0:y.message)||"");if(m==="NO_AUTH_TOKEN"){UC.info("CONNECT_SKIPPED_NO_AUTH",{message:m,type:y==null?void 0:y.type});return}UC.error("CONNECT_ERROR",{message:m,type:y==null?void 0:y.type})},o=y=>UC.info("RECONNECTED",{attempt:y}),s=y=>UC.debug("reconnect_attempt",{attempt:y}),r=y=>UC.warn("reconnect_error",{message:y==null?void 0:y.message}),a=()=>UC.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",r),(p=(d=t.io)==null?void 0:d.on)==null||p.call(d,"reconnect_failed",a),()=>{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",r),(M=(G=t.io)==null?void 0:G.off)==null||M.call(G,"reconnect_failed",a)}},[e]),E.useEffect(()=>{const t=n=>{var g;FI.error("WebGL CONTEXT LOST",{tagName:(g=n.target)==null?void 0:g.tagName,mem:cr()})},i=n=>{var g;FI.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 r=n.message||"";if(r.includes("websocket error")||r.includes("WebSocket"))return;X1.error("window.error",{message:r,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:cr()})}catch{}},i=n=>{var g,o,s,r;try{const a=n.reason,I=typeof a=="string"?a:(a==null?void 0:a.message)||"unhandledrejection";if((a==null?void 0:a.name)==="AbortError"||(g=I==null?void 0:I.includes)!=null&&g.call(I,"aborted")||I==="NO_AUTH_TOKEN")return;X1.error("unhandledrejection",{message:(o=I==null?void 0:I.slice)==null?void 0:o.call(I,0,500),stack:(r=(s=(a==null?void 0:a.stack)||"").slice)==null?void 0:r.call(s,0,1e3),mem:cr()})}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=cr();i&&i.usedJSHeapMB>150&&Ns.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&&Ns.warn("LONG_TASK",{durationMs:g,name:n.name,startTime:Math.round(n.startTime),mem:cr()})}}),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&&Ns.error("EVENT_LOOP_STALL",{gapMs:s,expectedMs:2e3,mem:cr()}),n=o},2e3);return()=>clearInterval(g)},[]),E.useEffect(()=>{try{window.__dumpLogs=()=>{const t=$M();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=l8();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 cRe(){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=r=>{try{const a=r.detail;i(I=>{const c=[...I,a];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 a=[new Date(s.t||Date.now()).toLocaleTimeString(),s.kind];return s.key&&a.push(s.key),s.volume!=null&&a.push(`v=${s.volume}`),s.rate!=null&&a.push(`r=${s.rate}`),s.reason&&a.push(`(${s.reason})`),a.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,r)=>C.jsx("div",{children:s},r))})]})}function lRe(){const[e,A]=E.useState(()=>{var s;try{const a=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 a||I||c}catch{return!1}}),[t,i]=E.useState(()=>{try{return $M().filter(s=>(s==null?void 0:s.tag)==="RTC")}catch{return[]}}),n=400,g=E.useRef(null);if(E.useEffect(()=>{const s=a=>{a.key==="rtcDebug"&&A(a.newValue==="1")};window.addEventListener("storage",s),window.rtcDebugOpen=()=>A(!0),window.rtcDebugClose=()=>A(!1);const r=()=>{try{new URL(window.location.href).searchParams.get("rtcDebug")==="1"&&A(!0)}catch{}};return window.addEventListener("popstate",r),()=>{window.removeEventListener("storage",s),window.removeEventListener("popstate",r);try{delete window.rtcDebugOpen,delete window.rtcDebugClose}catch{}}},[]),E.useEffect(()=>{if(!e)return;const s=r=>{try{const a=r.detail;if(!a||a.tag!=="RTC")return;i(I=>{const c=[...I,a];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 r=new Date(s.t||Date.now()).toLocaleTimeString(),a=((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`${r} ${a} ${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,r)=>C.jsx("div",{children:s},r))})]})}function BRe(){const{meId:e}=en(),A=Ji(),t=ms(),{info:i,onIdle:n}=Fa(),g=tI(),o=(g==null?void 0:g.room)??null,s=(g==null?void 0:g.setRoom)??null,{leaveRoom:r}=al(),a=he.useRef(!1);return he.useEffect(()=>{const I=t.pathname||"";/^\/(room|poker\/room)\//.test(I)||(a.current=!1)},[t.pathname]),xs({onPlayerBalanceUpdated:({playerId:I,balance:c})=>{if(!(!e||I!==e)&&typeof c=="number"&&!(c>0)&&!a.current&&!RR){a.current=!0;try{o!=null&&o.id&&typeof r=="function"&&r(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 ERe(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 QRe(){const e=wpA(),A=Ji(),t=E.useRef(null),{getGameRoute:i}=S8(),n=e==null?void 0:e.currentInvite;if(E.useEffect(()=>{if(!n)return;const r=I=>{I.key==="Escape"&&(e==null||e.dismissCurrentInvite())},a=I=>{t.current&&!t.current.contains(I.target)&&(e==null||e.dismissCurrentInvite())};return document.addEventListener("keydown",r),document.addEventListener("mousedown",a),()=>{document.removeEventListener("keydown",r),document.removeEventListener("mousedown",a)}},[n,e]),!n)return null;const g=async()=>{const r=await(e==null?void 0:e.acceptInvite(n.inviteId));if(r!=null&&r.ok&&r.roomId){const a=i(n.gameMode,r.roomId);A(a)}},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:ERe(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 zr.createPortal(s,document.body)}function uRe(){const e=Ss(),A=E.useRef(0);return E.useEffect(()=>{let t;const i=()=>{var n;try{const g=Fl(),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 r=!!(e!=null&&e.__allowCookieAuth);qr(e,"SocketWatchdog",{allowCookieSession:r})}catch{}}}catch{}t=setTimeout(i,2e3),(n=t.unref)==null||n.call(t)};return i(),()=>clearTimeout(t)},[e]),null}function dRe({children:e,skip:A=!1,maxWaitMs:t=4e3,appTarget:i=""}){const[n,g]=E.useState(!1),[o,s]=E.useState({loaded:0,total:0}),[r,a]=E.useState(!1),I=E.useRef(!1),c=ti.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,a(!0);try{await qn()}catch{}Tpe();const[h,d]=await Promise.all([mvA(t),xpe(t)]);(h||C2())&&d||console.warn("[SoundPreloadScreen] Preload timeout, showing app",{audioReady:h||C2(),videosReady:d}),g(!0)},[t]);return E.useEffect(()=>{if(!r||n)return;const h=setInterval(()=>{const d=DvA();s(d),C2()&&g(!0)},50);return()=>clearInterval(h)},[r,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:r?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(uQA,{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 hRe(){const e=NB();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 pRe(){return UpA(),null}const arA=["#ffd700","#f4c430","#ff6b6b","#4ecdc4","#45b7d1","#96ceb4","#ff9ff3","#54a0ff","#5f27cd","#ee5a24","#0abde3","#10ac84"],fRe=6e3;function yRe(e=40){return E.useMemo(()=>Array.from({length:e},(A,t)=>({left:`${Math.random()*100}%`,background:arA[t%arA.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 DRe(){var a;const e=Ss(),{refreshUser:A,meId:t}=en(),[i,n]=E.useState(null),g=yRe();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),fRe);return()=>window.clearTimeout(I)},[i]);const o=E.useCallback(()=>n(null),[]);if(!i)return null;const s=i.levelName||((a=iQ.find(I=>I.level===i.newLevel))==null?void 0:a.name)||`Level ${i.newLevel}`,r=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 zr.createPortal(r,document.body)}const ip=FUA(),mRe=ip==="skills"?Uke:ip==="ceelo"?O0e:ip==="craps"?P0e:ip==="poker"?j0e:ip==="zentara"?Lke:ip==="unified"?Fke:H0e;var NrA,RrA;try{const e=ti.getPlatform();if((e==="ios"||e==="android")&&(Promise.resolve((NrA=PQ.enable)==null?void 0:NrA.call(PQ,{config:{customColorsForSystemBars:!0,statusBarColor:"#00000000",statusBarContent:"light",navigationBarColor:"#00000000",navigationBarContent:"light"}})).catch(()=>{}),Uw().then(A=>{A&&(ru().catch(t=>console.warn("[App] AdMob interstitial warmup failed:",t)),CpA().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 a,I;try{const c=PQ.getSafeAreaInsets;if(typeof c!="function")return;const l=await c.call(PQ),B=Math.round(((a=l==null?void 0:l.insets)==null?void 0:a.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 r=()=>{setTimeout(s,50),setTimeout(s,150),setTimeout(s,300),setTimeout(s,500)};window.addEventListener("orientationchange",r),window.addEventListener("resize",s);try{(RrA=PQ.addListener)==null||RrA.call(PQ,"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(ti.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 SRe(){const{loaded:e,walletEnabled:A}=eRe(),t=Ji(),i=ms(),n=E.useRef(null),g=E.useRef(Date.now()),o=E.useCallback(r=>/^\/room\//.test(r)||/^\/poker\/room\//.test(r)||/^\/zentara\/(match|room)\//.test(r)||/^\/match\//.test(r),[]);return E.useEffect(()=>{const r=i.pathname||"";o(r)||aO()},[o,i.pathname]),E.useEffect(()=>{const r=()=>{if(document.visibilityState==="hidden"){aO();return}document.visibilityState==="visible"&&o(i.pathname||"")&&OgA()};document.addEventListener("visibilitychange",r);let a=null,I=null,c=!1;return(async()=>{var l,B;try{const{App:Q}=await li(async()=>{const{App:h}=await Promise.resolve().then(()=>UR);return{App:h}},void 0);if(c)return;if(a=await Q.addListener("pause",()=>{aO()}),I=await Q.addListener("resume",()=>{o(i.pathname||"")&&OgA()}),c){try{await((l=a==null?void 0:a.remove)==null?void 0:l.call(a))}catch{}try{await((B=I==null?void 0:I.remove)==null?void 0:B.call(I))}catch{}a=null,I=null}}catch{}})(),()=>{var l,B;c=!0;try{document.removeEventListener("visibilitychange",r)}catch{}try{(l=a==null?void 0:a.remove)==null||l.call(a)}catch{}try{(B=I==null?void 0:I.remove)==null||B.call(I)}catch{}a=null,I=null}},[o,i.pathname]),E.useEffect(()=>{try{iSA()}catch{}},[i.pathname,i.search]),E.useEffect(()=>{const a=()=>{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(),a()};a();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?(r=>A?C.jsx(XNe,{children:r}):C.jsx(C.Fragment,{children:r}))(C.jsx(bUA,{children:C.jsx(vYA,{children:C.jsxs(die,{children:[C.jsx(Yke,{}),C.jsx(JvA,{children:C.jsx($YA,{children:C.jsxs(RUA,{children:[C.jsx(jke,{}),C.jsx(uXA,{children:C.jsx(cXA,{children:C.jsx(f8A,{children:C.jsx(Hie,{children:C.jsx(y8A,{children:C.jsx(hXA,{children:C.jsxs(_UA,{children:[C.jsx(hRe,{}),C.jsxs(_SA,{children:[C.jsx(mRe,{}),C.jsx(QRe,{}),C.jsx(BRe,{}),C.jsx(IRe,{}),C.jsx(CRe,{}),C.jsx(cRe,{}),C.jsx(lRe,{}),C.jsx(uRe,{}),C.jsx(DRe,{})]})]})})})})})})})]})})})]})})})):C.jsxs("div",{className:"HomeScreen theme-casino home-fixed-root",children:[C.jsx(Zr,{className:"page-home-screen"}),C.jsx("div",{className:"home-preloader",children:C.jsx("div",{className:"home-preloader__spinner"})})]})}function wRe(){return E.useEffect(()=>{const e={current:null};return e.current=()=>{try{qn()}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{JSA()}catch{}},[]),C.jsxs(dRe,{maxWaitMs:5e3,appTarget:ip,children:[C.jsx(pRe,{}),C.jsx(dUA,{children:C.jsx(VRA,{children:C.jsx(ARe,{children:C.jsx(SRe,{})})})})]})}function kRe(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),[r,a]=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{B2==null||B2(),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 A7=="function"&&(A7(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)??r;let w=0;const b=()=>new Promise(_=>{let K=!1;const J=T=>{K||(K=!0,_(T))};try{const T=E2==null?void 0:E2(N,{volume:M,rate:G==null?void 0:G.rate,loop:G==null?void 0:G.loop});T&&typeof T.then=="function"?T.then(()=>J(!0)).catch(()=>J(!1)):setTimeout(()=>J(!0),0)}catch(T){h("play throw",N,T),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,r,t,h]),m=E.useCallback(N=>{try{Q2==null||Q2(N)}catch{}},[]),D=E.useCallback(N=>{s(N)},[]),S=E.useCallback(N=>{a(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:r,stats:I.current}}function MRe({children:e,config:A}){return kRe(A),C.jsx(C.Fragment,{children:e})}const NRe=[{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 RRe({id:e,variant:A}){const t=NRe.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 GRe(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 bRe=[{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"}],TSA={"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 URe(e){const A=/^\/capture\/cee-lo\/([a-z0-9-]+)$/i.exec(e);if(!A)return null;const t=A[1];return TSA[t]?{scene:t}:null}function qSA({scene:e}){const A=TSA[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(vRe,{banker:A.banker,results:A.results,chipDeltas:A.chipDeltas}),C.jsx(KRe,{dice:A.dice,rolling:A.rolling}),A.point!=null&&A.point!==void 0&&C.jsx(_Re,{point:A.point}),A.showRoll&&C.jsx(JRe,{}),A.roundSummary&&C.jsx(LRe,{text:A.roundSummary})]})}):C.jsx("div",{style:{color:"#fff"},children:"Scene not found"})}function vRe({banker:e,results:A,chipDeltas:t}){return C.jsx("div",{className:"cl-seats",children:bRe.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 KRe({dice:e,rolling:A}){return C.jsx("div",{className:"cl-dice","aria-label":"dice",children:e.map((t,i)=>C.jsx(FRe,{value:t,rolling:A},i))})}function FRe({value:e,rolling:A}){const t=e===0?"?":String(e);return C.jsx("div",{className:"cl-die"+(A?" is-rolling":""),children:t})}function _Re({point:e}){return C.jsxs("div",{className:"cl-point",children:["POINT: ",e]})}function JRe(){return C.jsx("div",{className:"cl-roll-btn",children:"ROLL"})}function LRe({text:e}){return C.jsx("div",{className:"cl-summary",children:e})}const Fk={on:()=>Fk,off:()=>Fk,once:()=>Fk,emit:()=>Fk,connected:!1,id:"ad-stub"};function xRe(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 r=0;const a=[...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<a.length&&a[Q].at<=c;Q++)B.push(a[Q].state),l=Q;B.length>0&&(o.current=l,n(Q=>B.reduce((h,d)=>({...h,...d}),Q))),r=requestAnimationFrame(I)};return r=requestAnimationFrame(I),()=>cancelAnimationFrame(r)},[]),i}const TRe={phase:"comeOut",point:null,pendingBets:[],balance:5e3,everyoneReady:!1,showReadyButton:!0,canRoll:!1,shooterName:"You",othersTotals:{},flashLabel:null},qg=(e,A)=>({id:`${e}-${A}-${Math.random().toString(36).slice(2,7)}`,type:e,amount:A}),YSA={comeout:[{at:.5,state:{pendingBets:[qg("pass",100)]}},{at:1.6,state:{pendingBets:[qg("pass",100),qg("pass",100)]}},{at:2.4,state:{pendingBets:[qg("pass",200),qg("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:[qg("pass",200)]}},{at:1,state:{pendingBets:[qg("pass",200),qg("place6",60)]}},{at:1.8,state:{pendingBets:[qg("pass",200),qg("place6",60),qg("place8",60)]}},{at:2.6,state:{pendingBets:[qg("pass",200),qg("place6",60),qg("place8",60),qg("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:[qg("pass",100)]}},{at:1.2,state:{pendingBets:[qg("pass",100),qg("atsAll",25)]}},{at:2,state:{phase:"point",point:8,pendingBets:[qg("pass",100),qg("atsAll",25),qg("oddsPass",100)]}},{at:2.8,state:{pendingBets:[qg("pass",100),qg("atsAll",25),qg("oddsPass",100),qg("place6",60),qg("place8",60)]}},{at:3.6,state:{everyoneReady:!0,showReadyButton:!1,canRoll:!0,othersTotals:{pass:400,place6:120}}}]};function qRe(e,A){const t=/^\/capture\/craps-ad\/([a-z0-9-]+)$/i.exec(e);if(!t)return null;const i=t[1];return YSA[i]?{scene:i}:null}function YRe({scene:e}){const A=YSA[e],t=xRe(TRe,A),i=E.useMemo(()=>({onChangeBets:()=>{},onClearAll:()=>{},onRoll:()=>{},onPassTurn:()=>{},onReadyClick:()=>{},onBetDelta:()=>{},onBetsBatch:()=>{},onChargeChange:()=>{}}),[]);return C.jsx(B8.Provider,{value:Fk,children:C.jsxs("div",{className:"craps-ad-stage","data-scene":e,children:[C.jsx("div",{className:"craps-ad-stage__panel",children:C.jsx(gpA,{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 HSA={"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 HRe(e){const A=/^\/capture\/cee-lo-ad\/([a-z0-9-]+)$/i.exec(e);return A&&HSA[A[1]]?{scene:A[1]}:null}function ORe({scene:e}){var o;const A=HSA[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 r=0;const a=()=>{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),r=requestAnimationFrame(a)};return r=requestAnimationFrame(a),()=>cancelAnimationFrame(r)},[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(qSA,{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 IrA=(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}),OSA={"raid-win":{confirmed:{winner:"attacker",attackerHits:28,defenderHits:4,credits:1200}},"raid-loss":{confirmed:{winner:"defender",attackerHits:6,defenderHits:22,credits:-800}}};function PRe(e){const A=/^\/capture\/zentara-ad\/([a-z0-9-]+)$/i.exec(e);return A&&OSA[A[1]]?{scene:A[1]}:null}function jRe({scene:e}){const A=OSA[e],t=E.useMemo(()=>IrA("ad-att","Commander","crimson-dominion","#ff3a3a"),[]),i=E.useMemo(()=>IrA("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(bmA,{attacker:t,defender:i,onComplete:()=>{},isSpectator:!1,confirmedResult:A.confirmed})}):C.jsx("div",{style:{color:"#fff"},children:"Scene not found"})}const PSA={"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 zRe(e){const A=/^\/capture\/poker-ad\/([a-z0-9-]+)$/i.exec(e);return A&&PSA[A[1]]?{scene:A[1]}:null}const ZRe={hole:[],holeRevealed:{first:!1,both:!1},board:[],pot:0,flash:null,win:null};function WRe({scene:e}){const A=PSA[e],[t,i]=E.useState(ZRe);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((a,I)=>a.at-I.at),r=()=>{const a=(performance.now()-n)/1e3;for(let I=o+1;I<s.length&&s[I].at<=a;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(r)};return g=requestAnimationFrame(r),()=>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(VRe,{value:t.board[n]},n))}),C.jsx("div",{className:"poker-ad__hero",children:C.jsx(_pA,{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 VRe({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 jSA={"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 XRe(e){const A=/^\/capture\/skills-ad\/([a-z0-9-]+)$/i.exec(e);return A&&jSA[A[1]]?{scene:A[1]}:null}const HO=320;function $Re({scene:e}){var I;const A=jSA[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*HO));c.push(window.setTimeout(()=>g(!0),A.path.length*HO+400)),c.push(window.setTimeout(()=>{i(0),g(!1)},A.path.length*HO+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,r=((I=A.grid[0])==null?void 0:I.length)??0,a=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(${r}, 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:a.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 AGe(){var e,A,t,i,n,g;try{const o=window.location.protocol;if(!(o==="capacitor:"||o==="ionic:"))return;let r=null;try{r=((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(r)try{await r.setResizeMode({mode:"none"})}catch{}const a=()=>{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=r==null?void 0:r.addListener)==null||t.call(r,"keyboardWillShow",a)}catch{}try{(i=r==null?void 0:r.addListener)==null||i.call(r,"keyboardDidShow",a)}catch{}try{(n=r==null?void 0:r.addListener)==null||n.call(r,"keyboardWillHide",I)}catch{}try{(g=r==null?void 0:r.addListener)==null||g.call(r,"keyboardDidHide",I)}catch{}}catch{}}const CrA="fe:crashlog:sent_ts";function eGe(){try{return ti.getPlatform()}catch{return"web"}}function tGe(){try{return"craps"}catch{return"unknown"}}async function iGe(){try{const e=l8();if(!e.length)return;const A=Number(localStorage.getItem(CrA)||"0"),t=Math.max(...e.map(g=>g.t));if(t<=A)return;const i=gr(),n=await fetch(`${i}/api/telemetry/logs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({logs:e.slice(-80),platform:eGe(),userAgent:navigator.userAgent,appTarget:tGe(),sessionId:sessionStorage.getItem("sid")||void 0})});n.ok?(localStorage.setItem(CrA,String(t)),pUA(),Ns.info("crash logs uploaded",{count:e.length})):Ns.warn("crash log upload failed",{status:n.status})}catch(e){try{Ns.warn("crash log upload error",{err:String(e)})}catch{}}}var GrA;try{const e=window.Capacitor,A=(GrA=e==null?void 0:e.getPlatform)==null?void 0:GrA.call(e);(A==="ios"||A==="android")&&Promise.resolve().then(()=>{try{xl.notifyAppReady()}catch{}})}catch{}try{iGe()}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{Xt("Light")}catch{}},{passive:!0});try{o8()}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";zc.get(e).then(A=>{if(!A)return zc.clearSessionKeys().then(()=>zc.set(e,"1"))}).catch(()=>{})}catch{}function nGe(){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")&&$CA().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{xl.notifyAppReady()}catch{}})}catch{}return C.jsx(wRe,{})}function OO(){try{const e=GRe(window.location.pathname,window.location.search);if(e){document.body.classList.add("ad-capture"),GQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(RRe,{id:e.id,variant:e.variant})}));return}const A=URe(window.location.pathname);if(A){document.body.classList.add("ad-capture"),GQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(qSA,{scene:A.scene})}));return}const t=qRe(window.location.pathname,window.location.search);if(t){document.body.classList.add("ad-capture"),GQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(YRe,{scene:t.scene})}));return}const i=HRe(window.location.pathname);if(i){document.body.classList.add("ad-capture"),GQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(ORe,{scene:i.scene})}));return}const n=PRe(window.location.pathname);if(n){document.body.classList.add("ad-capture"),GQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(jRe,{scene:n.scene})}));return}const g=zRe(window.location.pathname);if(g){document.body.classList.add("ad-capture"),GQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(WRe,{scene:g.scene})}));return}const o=XRe(window.location.pathname);if(o){document.body.classList.add("ad-capture"),GQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx($Re,{scene:o.scene})}));return}}catch{}GQ.createRoot(document.getElementById("root")).render(C.jsx(E.StrictMode,{children:C.jsx(_SA,{children:C.jsx(MRe,{config:{debug:!1},children:C.jsx(nGe,{})})})}))}function zSA(){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 fa.init()}catch{}OO();try{await AGe()}catch{}try{fa.healthCheck().catch(()=>{})}catch{}})():OO()}catch{OO()}}function gGe(){zSA()}window.APP_TARGET||zSA();const VGe=Object.freeze(Object.defineProperty({__proto__:null,default:gGe},Symbol.toStringTag,{value:"Module"}));export{jse as $,yg as A,kr as B,lt as C,Xa as D,_x as E,Ga as F,RW as G,iy as H,nT as I,NW as J,aQ as K,_g as L,hn as M,sc as N,Yd as O,zo as P,Ao as Q,Jw as R,rc as S,qse as T,QV as U,SA as V,ZCA as W,Aa as X,sr as Y,oV as Z,m4 as _,Tse as a,sn as a0,xE as a1,Hd as a2,rQ as a3,GN as a4,lIe as a5,lyA as a6,DGe as a7,Iu as a8,dG as a9,cn as aA,Yi as aB,oyA as aC,ki as aD,DB as aE,zx as aF,qIe as aG,xw as aH,aCe as aI,Lw as aJ,IQ as aK,he as aL,ome as aM,Cl as aN,jMe as aO,VN as aP,Gs as aQ,xMe as aR,jsA as aS,WGe as aT,Yc as aU,VGe as aV,ty as aa,gme as ab,er as ac,Kg as ad,gI as ae,Vn as af,gr as ag,Co as ah,$k as ai,QGe as aj,gw as ak,rGe as al,ti as am,nl as an,rM as ao,H7 as ap,aGe as aq,co as ar,or as as,$o as at,BI as au,qN as av,Ld as aw,Pt as ax,$i as ay,ii as az,OIe as b,It as c,eu as d,BIe as e,Aae as f,jr as g,xx as h,HW as i,C as j,zC as k,nG as l,rr as m,$Qe as n,nI as o,CG as p,sB as q,E as r,el as s,Fx as t,Ac as u,pue as v,pV as w,dB as x,Mr as y,Rg as z};
