@balancy/bridge 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,4 +6,4 @@
6
6
  font-family: '${n}';
7
7
  src: url('${e}') format('truetype');
8
8
  }
9
- `,document.head.appendChild(t)}function Ve(n,e){let t=(e??document).querySelector(`[data-id=${n}]`);return t instanceof HTMLElement?t:null}function We(n){return function(t){if(!(!t||typeof t!="object")){switch(console.log(">>>notificationReceived ",t),t.type){case O.OnOfferDeactivated:case O.OnOfferGroupDeactivated:break;case O.OnOfferGroupWasPurchased:n();break}window.dispatchEvent(new CustomEvent("balancy-notification",{detail:t}))}}}function Ye(){let n=[];return{subscribeToCustomMessages(e){return typeof e!="function"?(console.error("subscribeToCustomMessages: callback must be a function"),()=>{}):(n.push(e),function(){let r=n.indexOf(e);r>-1&&n.splice(r,1)})},dispatchCustomMessage(e){n.forEach(t=>{try{t(e)}catch(r){console.error("Error in custom message subscriber:",r)}}),window.dispatchEvent(new CustomEvent("balancy-custom-message",{detail:e}))}}}function _e(n,e,t,r,a){window.addEventListener("message",function(o){if(o.source!==window.parent||o.source===window)return;let i=o.data;i&&typeof i=="object"&&i.payload&&n(i.payload)}),function(){let i=new Set(["balancy-buttons-complete","balancy-localization-complete","balancy-text-complete","balancy-images-complete","balancy-fonts-complete","balancy-components-complete","balancy-audio-complete"]),c=new Set;function s(l){c.add(l.type),[...i].every(d=>c.has(d))&&(console.log("ALL IS READY"),window.dispatchEvent(new CustomEvent("balancy-ready")),r||t())}i.forEach(l=>{document.addEventListener(l,s,{once:!0})})}(),(async()=>(await e(),a&&await a()))()}function gt(n){if(!n||n===document.body||n===document.documentElement)return!1;let e=window.getComputedStyle(n),t=e.overflow||e.overflowY||e.overflowX;return t==="auto"||t==="scroll"||n.classList.contains("scrollable")||n.classList.contains("scroll-container")||n.classList.contains("overflow-auto")||n.classList.contains("overflow-scroll")||n.scrollHeight>n.clientHeight||n.scrollWidth>n.clientWidth}function Je(n){let e=n;for(;e&&e!==document.body&&e!==document.documentElement;){if(gt(e))return e;e=e.parentElement}return null}function bt(){if(document.getElementById("balancy-game-ui-styles"))return;let n=document.createElement("style");n.id="balancy-game-ui-styles",n.textContent=`*{-webkit-user-select:none !important;-moz-user-select:none !important;-ms-user-select:none !important;user-select:none !important;-webkit-touch-callout:none !important;-webkit-context-menu:none !important;outline:none !important;-webkit-user-drag:none !important;user-drag:none !important}body,div,span,p,h1,h2,h3,h4,h5,h6,a,button{cursor:default !important}img{-webkit-user-drag:none !important;user-drag:none !important;pointer-events:none !important;-webkit-touch-callout:none !important}input,textarea{-webkit-autocorrect:off !important;-webkit-autocapitalize:off !important;autocomplete:off !important;spellcheck:false !important;font-size:16px !important;-webkit-appearance:none !important;-moz-appearance:none !important;appearance:none !important}body{-webkit-tap-highlight-color:transparent !important;overscroll-behavior:none !important;overscroll-behavior-x:none !important;overscroll-behavior-y:none !important;-webkit-text-size-adjust:100% !important;-ms-text-size-adjust:100% !important;text-size-adjust:100% !important;touch-action:manipulation !important;-webkit-overflow-scrolling:auto !important;-webkit-user-drag:none !important;-ms-content-zooming:none !important;-ms-touch-action:manipulation !important;position:fixed !important;top:0 !important;left:0 !important;width:100% !important;height:100% !important;overflow:hidden !important}html{position:fixed !important;top:0 !important;left:0 !important;width:100% !important;height:100% !important;overflow:hidden !important;-ms-touch-action:manipulation !important;touch-action:manipulation !important;scrollbar-width:none !important;-ms-overflow-style:none !important}::-webkit-scrollbar{width:0px !important;height:0px !important;display:none !important;background:transparent !important}::-webkit-scrollbar-track{display:none !important}::-webkit-scrollbar-thumb{display:none !important}[style*="overflow:auto"],[style*="overflow:scroll"],[style*="overflow-y:auto"],[style*="overflow-y:scroll"],[style*="overflow-x:auto"],[style*="overflow-x:scroll"],.scrollable,.scroll-container,.overflow-auto,.overflow-scroll{-webkit-overflow-scrolling:touch !important;touch-action:pan-y !important;overscroll-behavior:contain !important}@supports (-webkit-touch-callout:none){body{-webkit-overflow-scrolling:auto !important;-webkit-touch-callout:none !important;-webkit-user-select:none !important}input,textarea,select{font-size:16px !important;transform:translateZ(0) !important}html{-webkit-text-size-adjust:100% !important}[style*="overflow:auto"],[style*="overflow:scroll"],[style*="overflow-y:auto"],[style*="overflow-y:scroll"],.scrollable,.scroll-container,.overflow-auto,.overflow-scroll{-webkit-overflow-scrolling:touch !important;touch-action:pan-y !important;overscroll-behavior:contain !important}}@media screen and (-webkit-device-pixel-ratio:1),screen and (-webkit-device-pixel-ratio:1.5),screen and (-webkit-device-pixel-ratio:2),screen and (-webkit-device-pixel-ratio:3){body{overscroll-behavior-y:none !important;-webkit-overflow-scrolling:auto !important}input,textarea{font-size:16px !important;-webkit-appearance:none !important}}@media (hover:hover) and (pointer:fine){body{overflow-x:hidden !important;-ms-overflow-style:none !important}*{-webkit-context-menu:none !important;context-menu:none !important}}.unity-webgl-canvas{body{margin:0 !important;padding:0 !important;overflow:hidden !important}}button,input[type="button"],input[type="submit"],input[type="reset"],.btn,[role="button"]{-webkit-transition-duration:0.1s !important;transition-duration:0.1s !important;-webkit-transition-property:transform,-webkit-transform !important;transition-property:transform,-webkit-transform !important;-webkit-transition-timing-function:ease-out !important;transition-timing-function:ease-out !important;transform:scale(1) !important;-webkit-transform:scale(1) !important;transform-origin:center center !important;-webkit-transform-origin:center center !important;will-change:transform !important}button:active,input[type="button"]:active,input[type="submit"]:active,input[type="reset"]:active,.btn:active,[role="button"]:active{transform:scale(0.95) !important;-webkit-transform:scale(0.95) !important;-webkit-transition-duration:0.05s !important;transition-duration:0.05s !important}button:not(:active),input[type="button"]:not(:active),input[type="submit"]:not(:active),input[type="reset"]:not(:active),.btn:not(:active),[role="button"]:not(:active){transform:scale(1) !important;-webkit-transform:scale(1) !important;-webkit-transition-duration:0.1s !important;transition-duration:0.1s !important}a[role="button"],div[role="button"],span[role="button"],.button,.ui-button,.clickable{-webkit-transition-duration:0.1s !important;transition-duration:0.1s !important;-webkit-transition-property:transform,-webkit-transform !important;transition-property:transform,-webkit-transform !important;-webkit-transition-timing-function:ease-out !important;transition-timing-function:ease-out !important;transform:scale(1) !important;-webkit-transform:scale(1) !important;transform-origin:center center !important;-webkit-transform-origin:center center !important;will-change:transform !important}a[role="button"]:active,div[role="button"]:active,span[role="button"]:active,.button:active,.ui-button:active,.clickable:active{transform:scale(0.95) !important;-webkit-transform:scale(0.95) !important;-webkit-transition-duration:0.05s !important;transition-duration:0.05s !important}button:disabled,input[type="button"]:disabled,input[type="submit"]:disabled,input[type="reset"]:disabled,.btn:disabled,.btn.disabled,[role="button"][disabled],[role="button"].disabled,[role="button"][aria-disabled="true"],a[role="button"].disabled,a[aria-disabled="true"],div[role="button"].disabled,div[aria-disabled="true"],span[role="button"].disabled,span[aria-disabled="true"],.button:disabled,.button.disabled,.ui-button:disabled,.ui-button.disabled,.clickable:disabled,.clickable.disabled,.balancy-button-processing{opacity:0.5 !important;filter:grayscale(0.7) !important;cursor:not-allowed !important;pointer-events:none !important;transform:scale(1) !important;-webkit-transform:scale(1) !important;-webkit-transition:none !important;transition:none !important;box-shadow:none !important;-webkit-box-shadow:none !important}button:disabled:active,input[type="button"]:disabled:active,input[type="submit"]:disabled:active,input[type="reset"]:disabled:active,.btn:disabled:active,.btn.disabled:active,[role="button"][disabled]:active,[role="button"].disabled:active,[role="button"][aria-disabled="true"]:active,a[role="button"].disabled:active,a[aria-disabled="true"]:active,div[role="button"].disabled:active,div[aria-disabled="true"]:active,span[role="button"].disabled:active,span[aria-disabled="true"]:active,.button:disabled:active,.button.disabled:active,.ui-button:disabled:active,.ui-button.disabled:active,.clickable:disabled:active,.clickable.disabled:active,.balancy-button-processing:active{transform:scale(1) !important;-webkit-transform:scale(1) !important;-webkit-transition:none !important;transition:none !important;opacity:0.5 !important;pointer-events:none !important}.balancy-button-processing{position:relative !important}.balancy-button-processing::after{content:'' !important;position:absolute !important;top:50% !important;left:50% !important;width:16px !important;height:16px !important;margin:-8px 0 0 -8px !important;border:2px solid transparent !important;border-top:2px solid currentColor !important;border-radius:50% !important;animation:balancy-spin 1s linear infinite !important;-webkit-animation:balancy-spin 1s linear infinite !important}@keyframes balancy-spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@-webkit-keyframes balancy-spin{0%{-webkit-transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg)}}*:focus{outline:none !important;-webkit-tap-highlight-color:transparent !important}::selection{background:transparent !important}::-moz-selection{background:transparent !important}html{-ms-touch-action:manipulation !important;touch-action:manipulation !important}input:-webkit-autofill,input:-webkit-autofill:hover,input:-webkit-autofill:focus{-webkit-box-shadow:0 0 0 1000px transparent inset !important;-webkit-text-fill-color:inherit !important}`,(document.head||document.documentElement).appendChild(n),console.log("[BalancyWebView] Game UI styles injected successfully")}function ht(){if(document.addEventListener("contextmenu",function(n){return n.preventDefault(),n.stopPropagation(),!1},{passive:!1,capture:!0}),document.addEventListener("selectstart",function(n){return n.preventDefault(),n.stopPropagation(),!1},{passive:!1,capture:!0}),document.addEventListener("dragstart",function(n){return n.preventDefault(),n.stopPropagation(),!1},{passive:!1,capture:!0}),/iPad|iPhone|iPod/.test(navigator.userAgent)){console.log("[BalancyWebView] Applying iOS-specific optimizations"),document.addEventListener("touchmove",function(e){["INPUT","TEXTAREA"].includes(e.target.tagName)||Je(e.target)||e.preventDefault()},{passive:!1});let n=0;document.addEventListener("touchend",function(e){let t=Date.now();t-n<=300&&e.preventDefault(),n=t},{passive:!1}),document.addEventListener("touchstart",function(e){e.target.style.webkitTouchCallout="none"},{passive:!0})}if(/Android/.test(navigator.userAgent)){console.log("[BalancyWebView] Applying Android-specific optimizations"),document.addEventListener("touchstart",function(e){(e.touches[0].clientX<20||e.touches[0].clientX>window.innerWidth-20||e.touches[0].clientY<20||e.touches[0].clientY>window.innerHeight-20)&&e.preventDefault()},{passive:!1});let n=0;document.addEventListener("touchstart",function(e){n=e.touches[0].pageY},{passive:!0}),document.addEventListener("touchmove",function(e){!Je(e.target)&&e.touches[0].pageY>n&&window.pageYOffset===0&&e.preventDefault()},{passive:!1})}/Mobi|Android/i.test(navigator.userAgent)||(console.log("[BalancyWebView] Applying Desktop-specific optimizations"),document.addEventListener("keydown",function(n){if((n.ctrlKey||n.metaKey)&&["a","c","v","x","s","p","f","h","r","n","w","t"].includes(n.key.toLowerCase())||[112,113,114,115,116,117,118,119,120,121,122,123,116,123].includes(n.keyCode))return n.preventDefault(),n.stopPropagation(),!1},{passive:!1,capture:!0}),document.addEventListener("mousedown",function(n){if(n.button===1)return n.preventDefault(),!1},{passive:!1})),console.log("[BalancyWebView] Game UI behavior applied successfully")}function K(){if(!window.balancyPerformanceInjected){if(window.balancyPerformanceInjected=!0,console.log("[BalancyWebView] Injecting universal performance optimizations for game-like WebView"),bt(),ht(),!document.querySelector('meta[name="viewport"]')){let n=document.createElement("meta");n.name="viewport",n.content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, viewport-fit=cover",document.head.appendChild(n),console.log("[BalancyWebView] Viewport meta tag added")}console.log("[BalancyWebView] Game UI initialization completed"),document.dispatchEvent(new CustomEvent("balancyGameUIReady",{detail:{platform:/iPad|iPhone|iPod/.test(navigator.userAgent)?"iOS":/Android/.test(navigator.userAgent)?"Android":"Desktop",timestamp:Date.now()}}))}}function Ke(n){async function e(t=document){let r=t.querySelectorAll("audio[data-button-audio-id]"),a=0;for(let o of r){if(o.classList.contains("balancy-audio-prepared"))return;let i=o.getAttribute("data-button-audio-id");if(!i)return;let c=await n(i);if(!c)return;o.src=c,o.classList.add("balancy-audio-prepared"),a++}t===document&&document.dispatchEvent(new CustomEvent("balancy-audio-complete",{detail:{preparedCount:a,totalFound:r.length}}))}return{prepareAllAudio:e}}var z=class{constructor(){this._enabled=!0;this._activeInHierarchy=!0}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this.updateActiveState())}get activeInHierarchy(){return this._activeInHierarchy}awake(){}onEnable(){}start(){}update(e){}onDisable(){}onDestroy(){}getComponent(e){if(!this.elementObject)return null;for(let t of this.elementObject.components)if(t.scriptInstance instanceof e)return t.scriptInstance;return null}getComponents(e){if(!this.elementObject)return[];let t=[];for(let r of this.elementObject.components)r.scriptInstance instanceof e&&t.push(r.scriptInstance);return t}getComponentInChildren(e){if(!this.elementObject)return null;let t=this.elementObject.element.querySelectorAll("[data-guid]");for(let r=0;r<t.length;r++){let a=t[r];a===this.elementObject.element||a.getAttribute("data-guid")}return null}updateActiveState(){let e=this._enabled&&this.isParentActive();if(this._activeInHierarchy!==e){this._activeInHierarchy=e;try{e?this.onEnable():this.onDisable()}catch(t){console.error("[ElementBehaviour] Error in lifecycle hook:",t)}}}isParentActive(){if(!this.elementObject||!this.elementObject.element)return!0;let e=this.elementObject.element.parentElement;for(;e&&e!==document.body;){if(window.getComputedStyle(e).display==="none")return!1;e=e.parentElement}return!0}};var X=class{constructor(){this.scripts=new Map}register(e,t){this.scripts.has(e)&&console.warn(`[ScriptRegistry] Script ID "${e}" is already registered. Overwriting.`),this.scripts.set(e,t)}get(e){let t=this.scripts.get(e);return t||(console.error(`[ScriptRegistry] Script class not found for ID: "${e}". Did you forget to register it?`),null)}has(e){return this.scripts.has(e)}getAllScriptIds(){return Array.from(this.scripts.keys())}clear(){this.scripts.clear()}},Z=new X;function Xe(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID().replace(/-/g,"");let n="abcdef0123456789",e="";for(let t=0;t<32;t++)e+=n.charAt(Math.floor(Math.random()*n.length));return e}function Ze(n){let e=new Map;function t(r){let a=r.getAttribute("data-guid");if(a){let i=Xe();r.setAttribute("data-guid",i),e.set(a,i)}let o=r.children;for(let i=0;i<o.length;i++){let c=o[i];c instanceof HTMLElement&&t(c)}}return t(n),e}function Q(n){let e=n.getAttribute("data-guid");return e||(e=Xe(),n.setAttribute("data-guid",e)),e}function x(n,e){return(e||document.body).querySelector(`[data-guid="${n}"]`)}function U(n){let e=n.getAttribute("data-script-params");if(!e)return null;try{let t=e.replace(/'/g,'"');return JSON.parse(t)}catch(t){return console.error("[ParameterSerializer] Failed to parse data-script-params:",t),console.error(" Script element:",n),console.error(" Raw params:",e),null}}function Qe(n,e,t,r,a){for(let[o,i]of Object.entries(e))try{if(!(o in n))continue;switch(i.type){case"number":n[o]=Number(i.value);break;case"string":n[o]=String(i.value);break;case"boolean":n[o]=i.value===!0||i.value==="true";break;case"element":let c=String(i.value);if(c===""||c==="null")n[o]=null;else{let s=t(c,o);if(n[o]=s,!s){let l=r||n.constructor.name||"Unknown",d=a?.getAttribute("data-script-id"),m=a?.id||a?.getAttribute("data-guid")||"Unknown",p=a?.tagName.toLowerCase()||"unknown",y=document.querySelector(`[data-guid="${c}"]`),b=y?.hasAttribute("data-prefab-id");console.error("[ParameterSerializer] \u274C Element reference not found:"),console.error(` \u2192 Parameter: "${o}"`),console.error(` \u2192 Script: "${l}"${d?` (id: ${d})`:""}`),console.error(` \u2192 Owner Element: <${p} id="${m}">`),console.error(` \u2192 Missing GUID: "${c}"`),console.error(` \u2192 Element in DOM: ${y?"YES":"NO"}${y?` <${y.tagName.toLowerCase()} id="${y.id}">`:""}`),console.error(` \u2192 Is prefab placeholder: ${b?"YES (data-prefab-id="+y?.getAttribute("data-prefab-id")+")":"NO"}`)}}break;default:console.warn(`[ParameterSerializer] Unknown parameter type: ${i.type}`)}}catch(c){console.error(`[ParameterSerializer] Error applying parameter "${o}":`,c)}}function et(n){return JSON.stringify(n).replace(/"/g,"'")}function tt(n,e){return(t,r)=>vt(t,n,e,r)}function vt(n,e,t,r){if(!n||n===""||n==="null")return null;let a=t?x(n,t):null;if(!a&&t&&(a=x(n)),!a&&!t&&(a=x(n)),!a)return r||console.error(`[ElementResolver] Element not found for GUID: "${n}"`),null;let o=e.getElementByGuid(n);return o||(o=e.createElementObjectFromElement(a,n)),o||(console.error(`[ElementResolver] Failed to create ElementObject for GUID: "${n}"`),null)}function nt(n,e){let t=n.querySelectorAll("[data-script-params]"),r=[];n.hasAttribute("data-script-params")&&r.push(n),r.push(...Array.from(t));for(let a of r)try{wt(a,e)}catch(o){console.error("[ParameterCloner] Error updating parameters:",o),console.error(" Script element:",a)}}function wt(n,e){let t=U(n);if(!t)return;let r=!1;for(let[a,o]of Object.entries(t))if(o.type==="element"){let i=String(o.value);if(e.has(i)){let c=e.get(i);o.value=c,r=!0}}if(r){let a=et(t);n.setAttribute("data-script-params",a)}}var ee=class{constructor(){this.elementObjects=new Map;this.updateLoopRunning=!1;this.isPaused=!1;this.lastFrameTime=0;this.animationFrameId=null;this.initialized=!1;this.displayValues=new WeakMap;this.prepareSpritesFunction=null;this.updateLoop=e=>{let t=(e-this.lastFrameTime)/1e3;if(this.lastFrameTime=e,!this.isPaused){for(let r of this.elementObjects.values())if(r.isActive){for(let a of r.components)if(!(!a.enabled||!a.scriptInstance.activeInHierarchy)){a.hasStarted||this.invokeStart(a);try{a.scriptInstance.update(t)}catch(o){console.error(`[ElementsManager] Error in update() for ${a.scriptId}:`,o)}}}}this.updateLoopRunning&&(this.animationFrameId=requestAnimationFrame(this.updateLoop))}}registerScript(e,t){Z.register(e,t)}setPrepareSpritesFunction(e){this.prepareSpritesFunction=e}initialize(){if(this.initialized){console.warn("[ElementsManager] Already initialized");return}console.log("[ElementsManager] Initializing component system..."),this.scanAllElements(),this.invokeInitialLifecycleMethods(),this.startUpdateLoop(),this.initialized=!0,console.log(`[ElementsManager] Initialization complete. ${this.elementObjects.size} ElementObjects created.`)}scanAllElements(){this.scanElement(document.body)}scanElement(e,t){let r=[];for(let a=0;a<e.children.length;a++){let o=e.children[a];o instanceof HTMLElement&&o.hasAttribute("data-script-id")&&r.push(o)}r.length>0&&this.processScriptDivs(e,r,t);for(let a=0;a<e.children.length;a++){let o=e.children[a];o instanceof HTMLElement&&this.scanElement(o,t)}}processScriptDivs(e,t,r){let a=Q(e),o=this.elementObjects.get(a);o||(o=new M(e,a),this.elementObjects.set(a,o));for(let i of t)this.createComponent(o,i,r)}createComponent(e,t,r){let a=t.getAttribute("data-script-id");if(!a)return console.error("[ElementsManager] Script div missing data-script-id",t),null;let o=Z.get(a);if(!o)return null;Q(t);try{let i=new o,c={elementObject:e,scriptElement:t,scriptInstance:i,scriptId:a,enabled:!0,hasStarted:!1};i.elementObject=e,i.scriptElement=t,e.addComponent(c);let s=U(t);if(s){let l=tt(this,r),d=o.name||a;Qe(i,s,l,d,t)}return c}catch(i){return console.error(`[ElementsManager] Error creating component "${a}":`,i),null}}invokeInitialLifecycleMethods(){for(let e of this.elementObjects.values())for(let t of e.components)this.callLifecycleMethod(t,"awake"),e.isActive&&t.enabled&&this.callLifecycleMethod(t,"onEnable")}callLifecycleMethod(e,t){try{let r=e.scriptInstance[t];typeof r=="function"&&r.call(e.scriptInstance)}catch(r){console.error(`[ElementsManager] Error in ${t}() for ${e.scriptId}:`,r)}}invokeStart(e){e.hasStarted||(this.callLifecycleMethod(e,"start"),e.hasStarted=!0)}startUpdateLoop(){this.updateLoopRunning||(this.updateLoopRunning=!0,this.lastFrameTime=performance.now(),this.updateLoop(this.lastFrameTime))}pause(){this.isPaused=!0}resume(){this.isPaused=!1}stopUpdateLoop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.updateLoopRunning=!1}getElementByGuid(e){return this.elementObjects.get(e)||null}createElementObjectFromElement(e,t){if(this.elementObjects.has(t))return this.elementObjects.get(t);let r=new M(e,t);return this.elementObjects.set(t,r),r}getOrCreateElementObject(e){if(this.elementObjects.has(e))return this.elementObjects.get(e);let t=x(e);if(!t)return null;let r=new M(t,e);this.elementObjects.set(e,r);let a=[];for(let o=0;o<t.children.length;o++){let i=t.children[o];i instanceof HTMLElement&&i.hasAttribute("data-script-id")&&a.push(i)}if(a.length>0)for(let o of a)this.createComponent(r,o,t);return r}setActive(e,t){let r=e.getAttribute("data-guid");if(!r){console.error("[ElementsManager] Element has no GUID:",e);return}let a=this.elementObjects.get(r);if(!a){console.warn("[ElementsManager] Element not managed:",e);return}if(a.isActive===t)return;if(t){let i=this.displayValues.get(e)||"";e.style.display=i}else this.displayValues.set(e,e.style.display),e.style.display="none";a.isActive=t;let o=this.getComponentsInElementAndChildren(e);for(let i of o)i.scriptInstance.updateActiveState()}getComponentsInElementAndChildren(e){let t=[],r=e.getAttribute("data-guid");if(r){let o=this.elementObjects.get(r);o&&t.push(...o.components)}let a=e.querySelectorAll("[data-guid]");for(let o of a){let i=o.getAttribute("data-guid");if(i){let c=this.elementObjects.get(i);c&&t.push(...c.components)}}return t}destroy(e){let t=e.getAttribute("data-guid");if(!t){e.remove();return}if(!this.elementObjects.get(t)){e.remove();return}let a=this.getComponentsInElementAndChildren(e);for(let i of a)i.scriptInstance.activeInHierarchy&&this.callLifecycleMethod(i,"onDisable"),this.callLifecycleMethod(i,"onDestroy");this.elementObjects.delete(t);let o=e.querySelectorAll("[data-guid]");for(let i of o){let c=i.getAttribute("data-guid");c&&this.elementObjects.delete(c)}e.remove()}instantiate(e){let t=e.cloneNode(!0);this.copyInlineStyles(e,t),this.prepareSpritesFunction&&this.prepareSpritesFunction(t).catch(o=>{console.error("[ElementsManager] Error preparing sprites for clone:",o)});let r=Ze(t);nt(t,r),this.scanElement(t,t);let a=this.getComponentsInElementAndChildren(t);for(let o of a)this.callLifecycleMethod(o,"awake"),o.enabled&&o.scriptInstance.activeInHierarchy&&this.callLifecycleMethod(o,"onEnable"),this.invokeStart(o);return t}copyInlineStyles(e,t){e.style.cssText&&(t.style.cssText=e.style.cssText);let r=e.children,a=t.children;for(let o=0;o<r.length&&o<a.length;o++)r[o]instanceof HTMLElement&&a[o]instanceof HTMLElement&&this.copyInlineStyles(r[o],a[o])}cleanup(){this.stopUpdateLoop(),this.elementObjects.clear(),this.initialized=!1}},w=new ee;var M=class{constructor(e,t){this.components=[];this.isActive=!0;this.element=e,this.guid=t}addComponent(e){this.components.includes(e)||(this.components.push(e),e.elementObject=this)}removeComponent(e){let t=this.components.indexOf(e);t!==-1&&this.components.splice(t,1)}getComponent(e){for(let t of this.components)if(t.scriptInstance instanceof e)return t.scriptInstance;return null}getComponents(e){let t=[];for(let r of this.components)r.scriptInstance instanceof e&&t.push(r.scriptInstance);return t}getEnabledComponents(){return this.components.filter(e=>e.enabled&&e.scriptInstance.activeInHierarchy)}instantiate(){let t=w.instantiate(this.element).getAttribute("data-guid");if(!t)throw new Error("[ElementObject] Cloned element has no GUID");let r=w.getElementByGuid(t);if(!r)throw new Error("[ElementObject] Cloned element not found in ElementsManager");return r}};var te=class{constructor(){this.prefabCache=new Map;this.pendingLoads=new Map;this.loaderFunction=null;this.uiProcessor=null}setLoader(e){this.loaderFunction=e}setUIProcessor(e){this.uiProcessor=e}async load(e){if(this.prefabCache.has(e)){let r=this.prefabCache.get(e);console.log(`[PrefabsManager] Using cached prefab: ${e}`);let a=r.cloneNode(!0);return this.copyInlineStyles(r,a),a}if(this.pendingLoads.has(e)){if(console.log(`[PrefabsManager] Waiting for pending load: ${e}`),await this.pendingLoads.get(e),this.prefabCache.has(e)){let r=this.prefabCache.get(e),a=r.cloneNode(!0);return this.copyInlineStyles(r,a),a}return console.error(`[PrefabsManager] Prefab not in cache after pending load: ${e}`),null}if(!this.loaderFunction)return console.error("[PrefabsManager] No loader function set. Call setLoader() first."),null;console.log(`[PrefabsManager] Loading prefab: ${e}`);let t=(async()=>{try{let r=await this.loaderFunction(e);if(!r)return console.error(`[PrefabsManager] Failed to load prefab: ${e}`),null;this.prefabCache.set(e,r),console.log(`[PrefabsManager] Prefab cached: ${e}`);let a=r.cloneNode(!0);return this.copyInlineStyles(r,a),a}catch(r){return console.error(`[PrefabsManager] Error loading prefab "${e}":`,r),null}finally{this.pendingLoads.delete(e)}})();return this.pendingLoads.set(e,t),t}copyInlineStyles(e,t){e.style.cssText&&(t.style.cssText=e.style.cssText);let r=e.children,a=t.children;for(let o=0;o<r.length&&o<a.length;o++)r[o]instanceof HTMLElement&&a[o]instanceof HTMLElement&&this.copyInlineStyles(r[o],a[o])}async processPrefabPlaceholdersInScope(e=document){let t=e===document?"whole page":`<${e.tagName?.toLowerCase()||"element"} id="${e.id||"unknown"}">`;console.log(`[PrefabsManager] Processing prefab placeholders in: ${t}`);let r=e.querySelectorAll("[data-prefab-id]");console.log(`[PrefabsManager] Found ${r.length} placeholders in scope`);for(let a of r)a.hasAttribute("data-prefab-id")&&await this.processPlaceholder(a);console.log(`[PrefabsManager] All prefab placeholders processed in: ${t}`)}async processPrefabPlaceholders(){await this.processPrefabPlaceholdersInScope(document)}async processPlaceholder(e){let t=e.getAttribute("data-prefab-id");if(!t){console.warn("[PrefabsManager] Skipping placeholder - data-prefab-id attribute missing or already processed",e);return}try{let r=await this.load(t);if(!r){console.error(`[PrefabsManager] Failed to load prefab for placeholder: ${t}`);return}let a=e.getAttribute("data-guid");console.log(`[PrefabsManager] Processing placeholder for ${t}:`),console.log(` - Placeholder: <${e.tagName.toLowerCase()} id="${e.id}">`),console.log(` - Placeholder GUID: ${a}`),console.log(` - Prefab root: <${r.tagName.toLowerCase()} id="${r.id}">`),console.log(` - Children to move: ${r.children.length}`),this.validatePrefabReferences(r,t);let o=0;for(;r.firstChild;)e.appendChild(r.firstChild),o++;console.log(` - Moved ${o} children to placeholder`),console.log(` - Placeholder now has ${e.children.length} children`),e.removeAttribute("data-prefab-id"),!e.className&&r.className&&(e.className=r.className),this.uiProcessor&&(console.log(" - Processing UI elements in placeholder..."),await this.uiProcessor(e),console.log(" - UI elements processed for placeholder"))}catch(r){console.error(`[PrefabsManager] Error processing placeholder for "${t}":`,r)}}clearCache(){this.prefabCache.clear()}async preload(e){console.log(`[PrefabsManager] Preloading ${e.length} prefabs...`);let t=e.map(r=>this.load(r));await Promise.all(t),console.log("[PrefabsManager] Preload complete")}getCacheStats(){return{size:this.prefabCache.size,prefabIds:Array.from(this.prefabCache.keys())}}validatePrefabReferences(e,t){let r=e.querySelectorAll("[data-guid]"),a=new Set,o=e.getAttribute("data-guid");o&&a.add(o),r.forEach(s=>{let l=s.getAttribute("data-guid");l&&a.add(l)});let i=e.querySelectorAll("[data-script-params]"),c=[];i.forEach(s=>{let l=s.getAttribute("data-script-params"),d=s.getAttribute("data-script-id")||"unknown",m=s.id||s.getAttribute("data-guid")||"unknown";if(l)try{let p=l.replace(/'/g,'"'),y=JSON.parse(p);for(let[b,H]of Object.entries(y))if(H.type==="element"){let A=String(H.value);A&&A!==""&&A!=="null"&&!a.has(A)&&c.push({scriptId:d,elementId:m,param:b,guid:A})}}catch{}}),c.length>0&&(console.warn(`[PrefabsManager] \u26A0\uFE0F Prefab ${t} has ${c.length} broken element reference(s):`),c.forEach(s=>{console.warn(` \u2192 Script ${s.scriptId} (element: ${s.elementId})`),console.warn(` Parameter: "${s.param}" \u2192 Missing GUID: "${s.guid}"`)}),console.warn(" \u{1F4A1} Tip: Re-save the prefab in the editor to fix stale references"))}},S=new te;w.instantiatePrefab=async function(n){let e=await S.load(n);return e?(console.info("INSTY +> ",e),this.instantiate(e)):null};w.instantiatePrefabById=async function(n){let e=await this.instantiatePrefab(n);if(!e)return null;let t=e.getAttribute("data-guid");if(!t)return console.error("[ElementsManager] Instantiated prefab has no GUID"),null;let r=this.getElementByGuid(t);return r||(console.error("[ElementsManager] ElementObject not found after instantiation"),null)};function ne(n,e){n.style.cssText&&(e.style.cssText=n.style.cssText);let t=n.children,r=e.children;for(let a=0;a<t.length&&a<r.length;a++)t[a]instanceof HTMLElement&&r[a]instanceof HTMLElement&&ne(t[a],r[a])}var V={},le={},it=0,st=new D,Et=new N,lt=new $,Pt=new G,Tt=new F,ct=()=>it,ut=()=>{it++},ce=ve(),ae=Ye(),ue=()=>{},ie=Ee(le,n=>ue(n),ae.dispatchCustomMessage),dt=Pe(ct,ut,le,ce),h=Te(st,dt,ct,ut,le,ce),Mt=we(ie),L=Me(h),{getActiveOffers:St,getActiveGroupOffers:It,canBuyGroupOffer:de,buyGroupOffer:Lt,buyOffer:At,buyShopSlot:Ot,getRewardedAdsWatchedForStoreItem:Ct,haveEnoughResources:xt}=Se(h,L.getSystemProfileValue,L.getDocumentValue),k=Ie(h),re=Le(h),oe=Ae(h,L.getDocumentValue),I=Oe(h),se=n=>lt.get(n,h,u.GetLocalization),R=n=>Et.get(n,h,u.GetImageUrl),Bt=n=>Pt.get(n,h,u.GetFileLocation),rt=n=>Tt.get(n,h,u.GetPrefabContent),mt=qe(L.getDocumentValue),me=Ce(se),pe=xe(R),kt=Be(R,J);w.setPrepareSpritesFunction(pe.prepareAllSprites);var pt=ke(h,de,R),Rt=Re(h,mt,Y,_,me.setLocalizedText),Ht=Ke(R),q=async(n=document)=>{let e=n===document?"whole page":`<${n.tagName?.toLowerCase()||"element"} id="${n.id||"unknown"}">`;console.info(`[Balancy] Preparing all UI elements for: ${e}`),n!==document&&await S.processPrefabPlaceholdersInScope(n),await me.localizeAllElements(n),await kt.prepareAllFonts(n),await pe.prepareAllSprites(n),await pt.prepareAllButtons(n),await Rt.prepareAllTexts(n),await Ht.prepareAllAudio(n),console.info(`[Balancy] All UI elements prepared for: ${e}`)},Dt=()=>{document.querySelectorAll(`[data-button-action="${u.BuyGroupOffer}"]`).forEach(e=>{let t=parseInt(e.getAttribute("data-index")||"0",10)||0;de(t).then(r=>{e.disabled=!r})})};ue=We(Dt);var ot=!1,at=()=>dt(null,u.BalancyIsReady,{id:"none"});Object.assign(V,{NotificationType:O,PriceType:ye,ItemType:B,TaskStatus:ge,RequestAction:u,BuyButtonState:be,OfferGroupType:he,NumberDisplayFormat:E,TimeDisplayFormat:C,TimePrecision:g,postMessage:ce,_receiveMessageFromUnity:Mt,handleResponse:ie,sendRequest:h,batchManager:st,getProfileValue:L.getProfileValue,getSystemProfileValue:L.getSystemProfileValue,getDocumentValue:L.getDocumentValue,getActiveOffers:St,getActiveGroupOffers:It,canBuyGroupOffer:de,buyGroupOffer:Lt,buyOffer:At,buyShopSlot:Ot,getRewardedAdsWatchedForStoreItem:Ct,haveEnoughResources:xt,getTasks:k.getTasks,activateTasks:k.activateTasks,deactivateTasks:k.deactivateTasks,restoreFailedTask:k.restoreFailedTask,claimTaskReward:k.claimTaskReward,getInventoryItemsCount:re.getInventoryItemsCount,addInventoryItems:re.addInventoryItems,removeInventoryItems:re.removeInventoryItems,getBattlePassConfig:oe.getBattlePassConfig,getBattlePassProgress:oe.getBattlePassProgress,claimBattlePassReward:oe.claimBattlePassReward,getCustomEventInfo:I.getCustomEventInfo,setCustomEventInfo:I.setCustomEventInfo,stopEventManually:I.stopEventManually,watchRewardedAd:I.watchRewardedAd,getProductInfo:I.getProductInfo,closeView:I.closeView,sendCustomMessage:I.sendCustomMessage,getLocalizedText:se,getImageUrl:R,getFileLocation:Bt,getPrefabContent:rt,setLocalizedText:me.setLocalizedText,setImage:pe.setImage,formatTime:Y,formatString:Fe,formatItemsCount:Ge,formatItemCount:Ue,shortenCount:W,itemHasDecayEffect:j,itemGetBundleReward:$e,getTimeLeft:_,formatDataTemplate:mt,injectFontFace:J,findDomElement:Ve,balancyButtonClicked:pt.balancyButtonClicked,notificationReceived:ue,subscribeToCustomMessages:ae.subscribeToCustomMessages,dispatchCustomMessage:ae.dispatchCustomMessage,sendIsReady:at,delayIsReady:()=>{ot=!0},ElementBehaviour:z,ElementObject:M,ElementsManager:w,PrefabsManager:S,instantiatePrefabById:n=>w.instantiatePrefabById(n),prepareAllUIElements:q,initResponseHandler:()=>{if(V._responseHandlerInitialized)return;V._responseHandlerInitialized=!0;let n=new Map;_e(ie,()=>q(),at,ot,async()=>{try{console.info("[Balancy] Preloading mandatory localization keys..."),await Promise.all(je.map(t=>se(t))),ze(t=>lt.getCached(t)),console.info("[Balancy] Mandatory localization keys preloaded"),S.setUIProcessor(async t=>{await q(t)}),S.setLoader(async t=>{try{if(n.has(t)){console.info(`[Balancy] Using cached prefab: ${t}`);let s=n.get(t),l=s.cloneNode(!0);return ne(s,l),l}console.info(`[Balancy] Loading prefab for the first time: ${t}`);let r=await rt(t);if(console.info(`[Balancy] Received HTML content (length: ${r?.length||0})`),!r)return console.error(`[Balancy] No HTML content returned for prefab: ${t}`),null;let o=new DOMParser().parseFromString(r,"text/html"),i=o.body.firstElementChild;if(!i)return console.error(`[Balancy] No root element found in prefab body for: ${t}`),null;let c=o.head.querySelectorAll("style");return c.length>0&&c.forEach(s=>{let d=(s.textContent||"").replace(/\*\s*\{[^}]*\}/g,"").replace(/body\s*\{[^}]*\}/g,"").replace(/html\s*\{[^}]*\}/g,"");if(d=d.trim(),d){let m=document.createElement("style");m.textContent=d,m.setAttribute("data-prefab-id",t),document.head.appendChild(m)}else console.warn(`[Balancy] No styles left after filtering for prefab: ${t}`)}),console.info(`[Balancy] Processing UI elements for prefab ${t}...`),await q(i),console.info(`[Balancy] UI elements processed for prefab ${t}`),n.set(t,i),console.info("[Balancy] Prefab loaded and cached successfully:"),console.info(` - Root element: <${i.tagName.toLowerCase()} id="${i.id}">`),console.info(` - Children count: ${i.children.length}`),console.info(" - Full element:",i),i}catch(r){return console.error(`[Balancy] Error in prefab loader for "${t}":`,r),null}}),await S.processPrefabPlaceholders(),w.initialize();try{let t=document.body.querySelector("[data-guid]");if(t){let r=t.getAttribute("data-guid");console.info(`[Balancy] Found root element with GUID: ${r}`);let a=w.getElementByGuid(r);if(a){let o=a.components;if(o.length>0){console.info(`[Balancy] Root element has ${o.length} component(s)`);let i=o[0].scriptInstance;if(typeof i.init=="function"){console.info("[Balancy] Calling init() on root script with balancyViewOwner");let c=window.balancyViewOwner;c?i.init(c):(console.warn("[Balancy] window.balancyViewOwner is not defined, calling init() without arguments"),i.init())}else console.info("[Balancy] Root script does not have an init() method")}else console.info("[Balancy] Root element has no script components")}}else console.info("[Balancy] No root element found with data-guid attribute")}catch(t){console.error("[Balancy] Error auto-initializing root script:",t)}document.dispatchEvent(new CustomEvent("balancy-components-complete"))}catch(t){console.error("[Balancy] Error initializing component system:",t),document.dispatchEvent(new CustomEvent("balancy-components-complete"))}})}});typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",K):K());typeof window<"u"&&(window.balancy=V);console.log("\u{1F389} [BRIDGE] Balancy WebView Bridge loaded successfully!");return balancy;})();
9
+ `,document.head.appendChild(t)}function Ve(n,e){let t=(e??document).querySelector(`[data-id=${n}]`);return t instanceof HTMLElement?t:null}function We(n){return function(t){if(!(!t||typeof t!="object")){switch(console.log(">>>notificationReceived ",t),t.type){case O.OnOfferDeactivated:case O.OnOfferGroupDeactivated:break;case O.OnOfferGroupWasPurchased:n();break}window.dispatchEvent(new CustomEvent("balancy-notification",{detail:t}))}}}function Ye(){let n=[];return{subscribeToCustomMessages(e){return typeof e!="function"?(console.error("subscribeToCustomMessages: callback must be a function"),()=>{}):(n.push(e),function(){let r=n.indexOf(e);r>-1&&n.splice(r,1)})},dispatchCustomMessage(e){n.forEach(t=>{try{t(e)}catch(r){console.error("Error in custom message subscriber:",r)}}),window.dispatchEvent(new CustomEvent("balancy-custom-message",{detail:e}))}}}function _e(n,e,t,r,a){window.addEventListener("message",function(o){if(o.source!==window.parent||o.source===window)return;let i=o.data;i&&typeof i=="object"&&i.payload&&n(i.payload)}),function(){let i=new Set(["balancy-buttons-complete","balancy-localization-complete","balancy-text-complete","balancy-images-complete","balancy-fonts-complete","balancy-components-complete","balancy-audio-complete"]),c=new Set;function s(l){c.add(l.type),[...i].every(d=>c.has(d))&&(console.log("ALL IS READY"),window.dispatchEvent(new CustomEvent("balancy-ready")),r||t())}i.forEach(l=>{document.addEventListener(l,s,{once:!0})})}(),(async()=>(await e(),a&&await a()))()}function gt(n){if(!n||n===document.body||n===document.documentElement)return!1;let e=window.getComputedStyle(n),t=e.overflow||e.overflowY||e.overflowX;return t==="auto"||t==="scroll"||n.classList.contains("scrollable")||n.classList.contains("scroll-container")||n.classList.contains("overflow-auto")||n.classList.contains("overflow-scroll")||n.scrollHeight>n.clientHeight||n.scrollWidth>n.clientWidth}function Je(n){let e=n;for(;e&&e!==document.body&&e!==document.documentElement;){if(gt(e))return e;e=e.parentElement}return null}function bt(){if(document.getElementById("balancy-game-ui-styles"))return;let n=document.createElement("style");n.id="balancy-game-ui-styles",n.textContent=`*{-webkit-user-select:none !important;-moz-user-select:none !important;-ms-user-select:none !important;user-select:none !important;-webkit-touch-callout:none !important;-webkit-context-menu:none !important;outline:none !important;-webkit-user-drag:none !important;user-drag:none !important}body,div,span,p,h1,h2,h3,h4,h5,h6,a,button{cursor:default !important}img{-webkit-user-drag:none !important;user-drag:none !important;pointer-events:none !important;-webkit-touch-callout:none !important}input,textarea{-webkit-autocorrect:off !important;-webkit-autocapitalize:off !important;autocomplete:off !important;spellcheck:false !important;font-size:16px !important;-webkit-appearance:none !important;-moz-appearance:none !important;appearance:none !important}body{-webkit-tap-highlight-color:transparent !important;overscroll-behavior:none !important;overscroll-behavior-x:none !important;overscroll-behavior-y:none !important;-webkit-text-size-adjust:100% !important;-ms-text-size-adjust:100% !important;text-size-adjust:100% !important;touch-action:manipulation !important;-webkit-overflow-scrolling:auto !important;-webkit-user-drag:none !important;-ms-content-zooming:none !important;-ms-touch-action:manipulation !important;position:fixed !important;top:0 !important;left:0 !important;width:100% !important;height:100% !important;overflow:hidden !important}html{position:fixed !important;top:0 !important;left:0 !important;width:100% !important;height:100% !important;overflow:hidden !important;-ms-touch-action:manipulation !important;touch-action:manipulation !important;scrollbar-width:none !important;-ms-overflow-style:none !important}::-webkit-scrollbar{width:0px !important;height:0px !important;display:none !important;background:transparent !important}::-webkit-scrollbar-track{display:none !important}::-webkit-scrollbar-thumb{display:none !important}[style*="overflow:auto"],[style*="overflow:scroll"],[style*="overflow-y:auto"],[style*="overflow-y:scroll"],[style*="overflow-x:auto"],[style*="overflow-x:scroll"],.scrollable,.scroll-container,.overflow-auto,.overflow-scroll{-webkit-overflow-scrolling:touch !important;touch-action:pan-y !important;overscroll-behavior:contain !important}@supports (-webkit-touch-callout:none){body{-webkit-overflow-scrolling:auto !important;-webkit-touch-callout:none !important;-webkit-user-select:none !important}input,textarea,select{font-size:16px !important;transform:translateZ(0) !important}html{-webkit-text-size-adjust:100% !important}[style*="overflow:auto"],[style*="overflow:scroll"],[style*="overflow-y:auto"],[style*="overflow-y:scroll"],.scrollable,.scroll-container,.overflow-auto,.overflow-scroll{-webkit-overflow-scrolling:touch !important;touch-action:pan-y !important;overscroll-behavior:contain !important}}@media screen and (-webkit-device-pixel-ratio:1),screen and (-webkit-device-pixel-ratio:1.5),screen and (-webkit-device-pixel-ratio:2),screen and (-webkit-device-pixel-ratio:3){body{overscroll-behavior-y:none !important;-webkit-overflow-scrolling:auto !important}input,textarea{font-size:16px !important;-webkit-appearance:none !important}}@media (hover:hover) and (pointer:fine){body{overflow-x:hidden !important;-ms-overflow-style:none !important}*{-webkit-context-menu:none !important;context-menu:none !important}}.unity-webgl-canvas{body{margin:0 !important;padding:0 !important;overflow:hidden !important}}button,input[type="button"],input[type="submit"],input[type="reset"],.btn,[role="button"]{-webkit-transition-duration:0.1s !important;transition-duration:0.1s !important;-webkit-transition-property:transform,-webkit-transform !important;transition-property:transform,-webkit-transform !important;-webkit-transition-timing-function:ease-out !important;transition-timing-function:ease-out !important;transform:scale(1) !important;-webkit-transform:scale(1) !important;transform-origin:center center !important;-webkit-transform-origin:center center !important;will-change:transform !important}button:active,input[type="button"]:active,input[type="submit"]:active,input[type="reset"]:active,.btn:active,[role="button"]:active{transform:scale(0.95) !important;-webkit-transform:scale(0.95) !important;-webkit-transition-duration:0.05s !important;transition-duration:0.05s !important}button:not(:active),input[type="button"]:not(:active),input[type="submit"]:not(:active),input[type="reset"]:not(:active),.btn:not(:active),[role="button"]:not(:active){transform:scale(1) !important;-webkit-transform:scale(1) !important;-webkit-transition-duration:0.1s !important;transition-duration:0.1s !important}a[role="button"],div[role="button"],span[role="button"],.button,.ui-button,.clickable{-webkit-transition-duration:0.1s !important;transition-duration:0.1s !important;-webkit-transition-property:transform,-webkit-transform !important;transition-property:transform,-webkit-transform !important;-webkit-transition-timing-function:ease-out !important;transition-timing-function:ease-out !important;transform:scale(1) !important;-webkit-transform:scale(1) !important;transform-origin:center center !important;-webkit-transform-origin:center center !important;will-change:transform !important}a[role="button"]:active,div[role="button"]:active,span[role="button"]:active,.button:active,.ui-button:active,.clickable:active{transform:scale(0.95) !important;-webkit-transform:scale(0.95) !important;-webkit-transition-duration:0.05s !important;transition-duration:0.05s !important}button:disabled,input[type="button"]:disabled,input[type="submit"]:disabled,input[type="reset"]:disabled,.btn:disabled,.btn.disabled,[role="button"][disabled],[role="button"].disabled,[role="button"][aria-disabled="true"],a[role="button"].disabled,a[aria-disabled="true"],div[role="button"].disabled,div[aria-disabled="true"],span[role="button"].disabled,span[aria-disabled="true"],.button:disabled,.button.disabled,.ui-button:disabled,.ui-button.disabled,.clickable:disabled,.clickable.disabled,.balancy-button-processing{opacity:0.5 !important;filter:grayscale(0.7) !important;cursor:not-allowed !important;pointer-events:none !important;transform:scale(1) !important;-webkit-transform:scale(1) !important;-webkit-transition:none !important;transition:none !important;box-shadow:none !important;-webkit-box-shadow:none !important}button:disabled:active,input[type="button"]:disabled:active,input[type="submit"]:disabled:active,input[type="reset"]:disabled:active,.btn:disabled:active,.btn.disabled:active,[role="button"][disabled]:active,[role="button"].disabled:active,[role="button"][aria-disabled="true"]:active,a[role="button"].disabled:active,a[aria-disabled="true"]:active,div[role="button"].disabled:active,div[aria-disabled="true"]:active,span[role="button"].disabled:active,span[aria-disabled="true"]:active,.button:disabled:active,.button.disabled:active,.ui-button:disabled:active,.ui-button.disabled:active,.clickable:disabled:active,.clickable.disabled:active,.balancy-button-processing:active{transform:scale(1) !important;-webkit-transform:scale(1) !important;-webkit-transition:none !important;transition:none !important;opacity:0.5 !important;pointer-events:none !important}.balancy-button-processing{position:relative !important}.balancy-button-processing::after{content:'' !important;position:absolute !important;top:50% !important;left:50% !important;width:16px !important;height:16px !important;margin:-8px 0 0 -8px !important;border:2px solid transparent !important;border-top:2px solid currentColor !important;border-radius:50% !important;animation:balancy-spin 1s linear infinite !important;-webkit-animation:balancy-spin 1s linear infinite !important}@keyframes balancy-spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@-webkit-keyframes balancy-spin{0%{-webkit-transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg)}}*:focus{outline:none !important;-webkit-tap-highlight-color:transparent !important}::selection{background:transparent !important}::-moz-selection{background:transparent !important}html{-ms-touch-action:manipulation !important;touch-action:manipulation !important}input:-webkit-autofill,input:-webkit-autofill:hover,input:-webkit-autofill:focus{-webkit-box-shadow:0 0 0 1000px transparent inset !important;-webkit-text-fill-color:inherit !important}`,(document.head||document.documentElement).appendChild(n),console.log("[BalancyWebView] Game UI styles injected successfully")}function ht(){if(document.addEventListener("contextmenu",function(n){return n.preventDefault(),n.stopPropagation(),!1},{passive:!1,capture:!0}),document.addEventListener("selectstart",function(n){return n.preventDefault(),n.stopPropagation(),!1},{passive:!1,capture:!0}),document.addEventListener("dragstart",function(n){return n.preventDefault(),n.stopPropagation(),!1},{passive:!1,capture:!0}),/iPad|iPhone|iPod/.test(navigator.userAgent)){console.log("[BalancyWebView] Applying iOS-specific optimizations"),document.addEventListener("touchmove",function(e){["INPUT","TEXTAREA"].includes(e.target.tagName)||Je(e.target)||e.preventDefault()},{passive:!1});let n=0;document.addEventListener("touchend",function(e){let t=Date.now();t-n<=300&&e.preventDefault(),n=t},{passive:!1}),document.addEventListener("touchstart",function(e){e.target.style.webkitTouchCallout="none"},{passive:!0})}if(/Android/.test(navigator.userAgent)){console.log("[BalancyWebView] Applying Android-specific optimizations"),document.addEventListener("touchstart",function(e){(e.touches[0].clientX<20||e.touches[0].clientX>window.innerWidth-20||e.touches[0].clientY<20||e.touches[0].clientY>window.innerHeight-20)&&e.preventDefault()},{passive:!1});let n=0;document.addEventListener("touchstart",function(e){n=e.touches[0].pageY},{passive:!0}),document.addEventListener("touchmove",function(e){!Je(e.target)&&e.touches[0].pageY>n&&window.pageYOffset===0&&e.preventDefault()},{passive:!1})}/Mobi|Android/i.test(navigator.userAgent)||(console.log("[BalancyWebView] Applying Desktop-specific optimizations"),document.addEventListener("keydown",function(n){if((n.ctrlKey||n.metaKey)&&["a","c","v","x","s","p","f","h","r","n","w","t"].includes(n.key.toLowerCase())||[112,113,114,115,116,117,118,119,120,121,122,123,116,123].includes(n.keyCode))return n.preventDefault(),n.stopPropagation(),!1},{passive:!1,capture:!0}),document.addEventListener("mousedown",function(n){if(n.button===1)return n.preventDefault(),!1},{passive:!1})),console.log("[BalancyWebView] Game UI behavior applied successfully")}function K(){if(!window.balancyPerformanceInjected){if(window.balancyPerformanceInjected=!0,console.log("[BalancyWebView] Injecting universal performance optimizations for game-like WebView"),bt(),ht(),!document.querySelector('meta[name="viewport"]')){let n=document.createElement("meta");n.name="viewport",n.content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, viewport-fit=cover",document.head.appendChild(n),console.log("[BalancyWebView] Viewport meta tag added")}console.log("[BalancyWebView] Game UI initialization completed"),document.dispatchEvent(new CustomEvent("balancyGameUIReady",{detail:{platform:/iPad|iPhone|iPod/.test(navigator.userAgent)?"iOS":/Android/.test(navigator.userAgent)?"Android":"Desktop",timestamp:Date.now()}}))}}function Ke(n){async function e(t=document){let r=t.querySelectorAll("audio[data-button-audio-id]"),a=0;for(let o of r){if(o.classList.contains("balancy-audio-prepared"))return;let i=o.getAttribute("data-button-audio-id");if(!i)return;let c=await n(i);if(!c)return;o.src=c,o.classList.add("balancy-audio-prepared"),a++}t===document&&document.dispatchEvent(new CustomEvent("balancy-audio-complete",{detail:{preparedCount:a,totalFound:r.length}}))}return{prepareAllAudio:e}}var z=class{constructor(){this._enabled=!0;this._activeInHierarchy=!0}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this.updateActiveState())}get activeInHierarchy(){return this._activeInHierarchy}awake(){}onEnable(){}start(){}update(e){}onDisable(){}onDestroy(){}getComponent(e){if(!this.elementObject)return null;for(let t of this.elementObject.components)if(t.scriptInstance instanceof e)return t.scriptInstance;return null}getComponents(e){if(!this.elementObject)return[];let t=[];for(let r of this.elementObject.components)r.scriptInstance instanceof e&&t.push(r.scriptInstance);return t}getComponentInChildren(e){if(!this.elementObject)return null;let t=this.elementObject.element.querySelectorAll("[data-guid]");for(let r=0;r<t.length;r++){let a=t[r];a===this.elementObject.element||a.getAttribute("data-guid")}return null}updateActiveState(){let e=this._enabled&&this.isParentActive();if(this._activeInHierarchy!==e){this._activeInHierarchy=e;try{e?this.onEnable():this.onDisable()}catch(t){console.error("[ElementBehaviour] Error in lifecycle hook:",t)}}}isParentActive(){if(!this.elementObject||!this.elementObject.element)return!0;let e=this.elementObject.element.parentElement;for(;e&&e!==document.body;){if(window.getComputedStyle(e).display==="none")return!1;e=e.parentElement}return!0}};var X=class{constructor(){this.scripts=new Map}register(e,t){this.scripts.has(e)&&console.warn(`[ScriptRegistry] Script ID "${e}" is already registered. Overwriting.`),this.scripts.set(e,t)}get(e){let t=this.scripts.get(e);return t||(console.error(`[ScriptRegistry] Script class not found for ID: "${e}". Did you forget to register it?`),null)}has(e){return this.scripts.has(e)}getAllScriptIds(){return Array.from(this.scripts.keys())}clear(){this.scripts.clear()}},Z=new X;function Xe(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID().replace(/-/g,"");let n="abcdef0123456789",e="";for(let t=0;t<32;t++)e+=n.charAt(Math.floor(Math.random()*n.length));return e}function Ze(n){let e=new Map;function t(r){let a=r.getAttribute("data-guid");if(a){let i=Xe();r.setAttribute("data-guid",i),e.set(a,i)}let o=r.children;for(let i=0;i<o.length;i++){let c=o[i];c instanceof HTMLElement&&t(c)}}return t(n),e}function Q(n){let e=n.getAttribute("data-guid");return e||(e=Xe(),n.setAttribute("data-guid",e)),e}function x(n,e){return(e||document.body).querySelector(`[data-guid="${n}"]`)}function U(n){let e=n.getAttribute("data-script-params");if(!e)return null;try{let t=e.replace(/'/g,'"');return JSON.parse(t)}catch(t){return console.error("[ParameterSerializer] Failed to parse data-script-params:",t),console.error(" Script element:",n),console.error(" Raw params:",e),null}}function Qe(n,e,t,r,a){for(let[o,i]of Object.entries(e))try{if(!(o in n))continue;switch(i.type){case"number":n[o]=Number(i.value);break;case"string":n[o]=String(i.value);break;case"boolean":n[o]=i.value===!0||i.value==="true";break;case"element":let c=String(i.value);if(c===""||c==="null")n[o]=null;else{let s=t(c,o);if(n[o]=s,!s){let l=r||n.constructor.name||"Unknown",d=a?.getAttribute("data-script-id"),m=a?.id||a?.getAttribute("data-guid")||"Unknown",p=a?.tagName.toLowerCase()||"unknown",y=document.querySelector(`[data-guid="${c}"]`),b=y?.hasAttribute("data-prefab-id");console.error("[ParameterSerializer] \u274C Element reference not found:"),console.error(` \u2192 Parameter: "${o}"`),console.error(` \u2192 Script: "${l}"${d?` (id: ${d})`:""}`),console.error(` \u2192 Owner Element: <${p} id="${m}">`),console.error(` \u2192 Missing GUID: "${c}"`),console.error(` \u2192 Element in DOM: ${y?"YES":"NO"}${y?` <${y.tagName.toLowerCase()} id="${y.id}">`:""}`),console.error(` \u2192 Is prefab placeholder: ${b?"YES (data-prefab-id="+y?.getAttribute("data-prefab-id")+")":"NO"}`)}}break;default:console.warn(`[ParameterSerializer] Unknown parameter type: ${i.type}`)}}catch(c){console.error(`[ParameterSerializer] Error applying parameter "${o}":`,c)}}function et(n){return JSON.stringify(n).replace(/"/g,"'")}function tt(n,e){return(t,r)=>vt(t,n,e,r)}function vt(n,e,t,r){if(!n||n===""||n==="null")return null;let a=t?x(n,t):null;if(!a&&t&&(a=x(n)),!a&&!t&&(a=x(n)),!a)return r||console.error(`[ElementResolver] Element not found for GUID: "${n}"`),null;let o=e.getElementByGuid(n);return o||(o=e.createElementObjectFromElement(a,n)),o||(console.error(`[ElementResolver] Failed to create ElementObject for GUID: "${n}"`),null)}function nt(n,e){let t=n.querySelectorAll("[data-script-params]"),r=[];n.hasAttribute("data-script-params")&&r.push(n),r.push(...Array.from(t));for(let a of r)try{wt(a,e)}catch(o){console.error("[ParameterCloner] Error updating parameters:",o),console.error(" Script element:",a)}}function wt(n,e){let t=U(n);if(!t)return;let r=!1;for(let[a,o]of Object.entries(t))if(o.type==="element"){let i=String(o.value);if(e.has(i)){let c=e.get(i);o.value=c,r=!0}}if(r){let a=et(t);n.setAttribute("data-script-params",a)}}var ee=class{constructor(){this.elementObjects=new Map;this.updateLoopRunning=!1;this.isPaused=!1;this.lastFrameTime=0;this.animationFrameId=null;this.initialized=!1;this.displayValues=new WeakMap;this.prepareSpritesFunction=null;this.updateLoop=e=>{let t=(e-this.lastFrameTime)/1e3;if(this.lastFrameTime=e,!this.isPaused){for(let r of this.elementObjects.values())if(r.isActive){for(let a of r.components)if(!(!a.enabled||!a.scriptInstance.activeInHierarchy)){a.hasStarted||this.invokeStart(a);try{a.scriptInstance.update(t)}catch(o){console.error(`[ElementsManager] Error in update() for ${a.scriptId}:`,o)}}}}this.updateLoopRunning&&(this.animationFrameId=requestAnimationFrame(this.updateLoop))}}registerScript(e,t){Z.register(e,t)}setPrepareSpritesFunction(e){this.prepareSpritesFunction=e}initialize(){if(this.initialized){console.warn("[ElementsManager] Already initialized");return}console.log("[ElementsManager] Initializing component system..."),this.scanAllElements(),this.invokeInitialLifecycleMethods(),this.startUpdateLoop(),this.initialized=!0,console.log(`[ElementsManager] Initialization complete. ${this.elementObjects.size} ElementObjects created.`)}scanAllElements(){this.scanElement(document.body)}scanElement(e,t){let r=[];for(let a=0;a<e.children.length;a++){let o=e.children[a];o instanceof HTMLElement&&o.hasAttribute("data-script-id")&&r.push(o)}r.length>0&&this.processScriptDivs(e,r,t);for(let a=0;a<e.children.length;a++){let o=e.children[a];o instanceof HTMLElement&&this.scanElement(o,t)}}processScriptDivs(e,t,r){let a=Q(e),o=this.elementObjects.get(a);o||(o=new M(e,a),this.elementObjects.set(a,o));for(let i of t)this.createComponent(o,i,r)}createComponent(e,t,r){let a=t.getAttribute("data-script-id");if(!a)return console.error("[ElementsManager] Script div missing data-script-id",t),null;let o=Z.get(a);if(!o)return null;Q(t);try{let i=new o,c={elementObject:e,scriptElement:t,scriptInstance:i,scriptId:a,enabled:!0,hasStarted:!1};i.elementObject=e,i.scriptElement=t,e.addComponent(c);let s=U(t);if(s){let l=tt(this,r),d=o.name||a;Qe(i,s,l,d,t)}return c}catch(i){return console.error(`[ElementsManager] Error creating component "${a}":`,i),null}}invokeInitialLifecycleMethods(){for(let e of this.elementObjects.values())for(let t of e.components)this.callLifecycleMethod(t,"awake"),e.isActive&&t.enabled&&this.callLifecycleMethod(t,"onEnable")}callLifecycleMethod(e,t){try{let r=e.scriptInstance[t];typeof r=="function"&&r.call(e.scriptInstance)}catch(r){console.error(`[ElementsManager] Error in ${t}() for ${e.scriptId}:`,r)}}invokeStart(e){e.hasStarted||(this.callLifecycleMethod(e,"start"),e.hasStarted=!0)}startUpdateLoop(){this.updateLoopRunning||(this.updateLoopRunning=!0,this.lastFrameTime=performance.now(),this.updateLoop(this.lastFrameTime))}pause(){this.isPaused=!0}resume(){this.isPaused=!1}stopUpdateLoop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.updateLoopRunning=!1}getElementByGuid(e){return this.elementObjects.get(e)||null}createElementObjectFromElement(e,t){if(this.elementObjects.has(t))return this.elementObjects.get(t);let r=new M(e,t);return this.elementObjects.set(t,r),r}getOrCreateElementObject(e){if(this.elementObjects.has(e))return this.elementObjects.get(e);let t=x(e);if(!t)return null;let r=new M(t,e);this.elementObjects.set(e,r);let a=[];for(let o=0;o<t.children.length;o++){let i=t.children[o];i instanceof HTMLElement&&i.hasAttribute("data-script-id")&&a.push(i)}if(a.length>0)for(let o of a)this.createComponent(r,o,t);return r}setActive(e,t){let r=e.getAttribute("data-guid");if(!r){console.error("[ElementsManager] Element has no GUID:",e);return}let a=this.elementObjects.get(r);if(!a){console.warn("[ElementsManager] Element not managed:",e);return}if(a.isActive===t)return;if(t){let i=this.displayValues.get(e)||"";e.style.display=i}else this.displayValues.set(e,e.style.display),e.style.display="none";a.isActive=t;let o=this.getComponentsInElementAndChildren(e);for(let i of o)i.scriptInstance.updateActiveState()}getComponentsInElementAndChildren(e){let t=[],r=e.getAttribute("data-guid");if(r){let o=this.elementObjects.get(r);o&&t.push(...o.components)}let a=e.querySelectorAll("[data-guid]");for(let o of a){let i=o.getAttribute("data-guid");if(i){let c=this.elementObjects.get(i);c&&t.push(...c.components)}}return t}destroy(e){let t=e.getAttribute("data-guid");if(!t){e.remove();return}if(!this.elementObjects.get(t)){e.remove();return}let a=this.getComponentsInElementAndChildren(e);for(let i of a)i.scriptInstance.activeInHierarchy&&this.callLifecycleMethod(i,"onDisable"),this.callLifecycleMethod(i,"onDestroy");this.elementObjects.delete(t);let o=e.querySelectorAll("[data-guid]");for(let i of o){let c=i.getAttribute("data-guid");c&&this.elementObjects.delete(c)}e.remove()}instantiate(e){let t=e.cloneNode(!0);this.copyInlineStyles(e,t),this.prepareSpritesFunction&&this.prepareSpritesFunction(t).catch(o=>{console.error("[ElementsManager] Error preparing sprites for clone:",o)});let r=Ze(t);nt(t,r),this.scanElement(t,t);let a=this.getComponentsInElementAndChildren(t);for(let o of a)this.callLifecycleMethod(o,"awake"),o.enabled&&o.scriptInstance.activeInHierarchy&&this.callLifecycleMethod(o,"onEnable"),this.invokeStart(o);return t}copyInlineStyles(e,t){e.style.cssText&&(t.style.cssText=e.style.cssText);let r=e.children,a=t.children;for(let o=0;o<r.length&&o<a.length;o++)r[o]instanceof HTMLElement&&a[o]instanceof HTMLElement&&this.copyInlineStyles(r[o],a[o])}cleanup(){this.stopUpdateLoop(),this.elementObjects.clear(),this.initialized=!1}},w=new ee;var M=class{constructor(e,t){this.components=[];this.isActive=!0;this.element=e,this.guid=t}addComponent(e){this.components.includes(e)||(this.components.push(e),e.elementObject=this)}removeComponent(e){let t=this.components.indexOf(e);t!==-1&&this.components.splice(t,1)}getComponent(e){for(let t of this.components)if(t.scriptInstance instanceof e)return t.scriptInstance;return null}getComponents(e){let t=[];for(let r of this.components)r.scriptInstance instanceof e&&t.push(r.scriptInstance);return t}getEnabledComponents(){return this.components.filter(e=>e.enabled&&e.scriptInstance.activeInHierarchy)}instantiate(){let t=w.instantiate(this.element).getAttribute("data-guid");if(!t)throw new Error("[ElementObject] Cloned element has no GUID");let r=w.getElementByGuid(t);if(!r)throw new Error("[ElementObject] Cloned element not found in ElementsManager");return r}};var te=class{constructor(){this.prefabCache=new Map;this.pendingLoads=new Map;this.loaderFunction=null;this.uiProcessor=null}setLoader(e){this.loaderFunction=e}setUIProcessor(e){this.uiProcessor=e}async load(e){if(this.prefabCache.has(e)){let r=this.prefabCache.get(e);console.log(`[PrefabsManager] Using cached prefab: ${e}`);let a=r.cloneNode(!0);return this.copyInlineStyles(r,a),a}if(this.pendingLoads.has(e)){if(console.log(`[PrefabsManager] Waiting for pending load: ${e}`),await this.pendingLoads.get(e),this.prefabCache.has(e)){let r=this.prefabCache.get(e),a=r.cloneNode(!0);return this.copyInlineStyles(r,a),a}return console.error(`[PrefabsManager] Prefab not in cache after pending load: ${e}`),null}if(!this.loaderFunction)return console.error("[PrefabsManager] No loader function set. Call setLoader() first."),null;console.log(`[PrefabsManager] Loading prefab: ${e}`);let t=(async()=>{try{let r=await this.loaderFunction(e);if(!r)return console.error(`[PrefabsManager] Failed to load prefab: ${e}`),null;this.prefabCache.set(e,r),console.log(`[PrefabsManager] Prefab cached: ${e}`);let a=r.cloneNode(!0);return this.copyInlineStyles(r,a),a}catch(r){return console.error(`[PrefabsManager] Error loading prefab "${e}":`,r),null}finally{this.pendingLoads.delete(e)}})();return this.pendingLoads.set(e,t),t}copyInlineStyles(e,t){e.style.cssText&&(t.style.cssText=e.style.cssText);let r=e.children,a=t.children;for(let o=0;o<r.length&&o<a.length;o++)r[o]instanceof HTMLElement&&a[o]instanceof HTMLElement&&this.copyInlineStyles(r[o],a[o])}async processPrefabPlaceholdersInScope(e=document){let t=e===document?"whole page":`<${e.tagName?.toLowerCase()||"element"} id="${e.id||"unknown"}">`;console.log(`[PrefabsManager] Processing prefab placeholders in: ${t}`);let r=e.querySelectorAll("[data-prefab-id]");console.log(`[PrefabsManager] Found ${r.length} placeholders in scope`);for(let a of r)a.hasAttribute("data-prefab-id")&&await this.processPlaceholder(a);console.log(`[PrefabsManager] All prefab placeholders processed in: ${t}`)}async processPrefabPlaceholders(){await this.processPrefabPlaceholdersInScope(document)}async processPlaceholder(e){let t=e.getAttribute("data-prefab-id");if(!t){console.warn("[PrefabsManager] Skipping placeholder - data-prefab-id attribute missing or already processed",e);return}try{let r=await this.load(t);if(!r){console.error(`[PrefabsManager] Failed to load prefab for placeholder: ${t}`);return}let a=e.getAttribute("data-guid");console.log(`[PrefabsManager] Processing placeholder for ${t}:`),console.log(` - Placeholder: <${e.tagName.toLowerCase()} id="${e.id}">`),console.log(` - Placeholder GUID: ${a}`),console.log(` - Prefab root: <${r.tagName.toLowerCase()} id="${r.id}">`),console.log(` - Children to move: ${r.children.length}`),this.validatePrefabReferences(r,t);let o=0;for(;r.firstChild;)e.appendChild(r.firstChild),o++;console.log(` - Moved ${o} children to placeholder`),console.log(` - Placeholder now has ${e.children.length} children`),e.removeAttribute("data-prefab-id"),!e.className&&r.className&&(e.className=r.className);let i=e.querySelectorAll(".balancy-button-prepared");i.forEach(c=>{c.classList.remove("balancy-button-prepared")}),i.length>0&&console.log(` - Removed button markers from ${i.length} cloned buttons`),this.uiProcessor&&(console.log(" - Processing UI elements in placeholder..."),await this.uiProcessor(e),console.log(" - UI elements processed for placeholder"))}catch(r){console.error(`[PrefabsManager] Error processing placeholder for "${t}":`,r)}}clearCache(){this.prefabCache.clear()}async preload(e){console.log(`[PrefabsManager] Preloading ${e.length} prefabs...`);let t=e.map(r=>this.load(r));await Promise.all(t),console.log("[PrefabsManager] Preload complete")}getCacheStats(){return{size:this.prefabCache.size,prefabIds:Array.from(this.prefabCache.keys())}}validatePrefabReferences(e,t){let r=e.querySelectorAll("[data-guid]"),a=new Set,o=e.getAttribute("data-guid");o&&a.add(o),r.forEach(s=>{let l=s.getAttribute("data-guid");l&&a.add(l)});let i=e.querySelectorAll("[data-script-params]"),c=[];i.forEach(s=>{let l=s.getAttribute("data-script-params"),d=s.getAttribute("data-script-id")||"unknown",m=s.id||s.getAttribute("data-guid")||"unknown";if(l)try{let p=l.replace(/'/g,'"'),y=JSON.parse(p);for(let[b,H]of Object.entries(y))if(H.type==="element"){let A=String(H.value);A&&A!==""&&A!=="null"&&!a.has(A)&&c.push({scriptId:d,elementId:m,param:b,guid:A})}}catch{}}),c.length>0&&(console.warn(`[PrefabsManager] \u26A0\uFE0F Prefab ${t} has ${c.length} broken element reference(s):`),c.forEach(s=>{console.warn(` \u2192 Script ${s.scriptId} (element: ${s.elementId})`),console.warn(` Parameter: "${s.param}" \u2192 Missing GUID: "${s.guid}"`)}),console.warn(" \u{1F4A1} Tip: Re-save the prefab in the editor to fix stale references"))}},S=new te;w.instantiatePrefab=async function(n){let e=await S.load(n);return e?(console.info("INSTY +> ",e),this.instantiate(e)):null};w.instantiatePrefabById=async function(n){let e=await this.instantiatePrefab(n);if(!e)return null;let t=e.getAttribute("data-guid");if(!t)return console.error("[ElementsManager] Instantiated prefab has no GUID"),null;let r=this.getElementByGuid(t);return r||(console.error("[ElementsManager] ElementObject not found after instantiation"),null)};function ne(n,e){n.style.cssText&&(e.style.cssText=n.style.cssText);let t=n.children,r=e.children;for(let a=0;a<t.length&&a<r.length;a++)t[a]instanceof HTMLElement&&r[a]instanceof HTMLElement&&ne(t[a],r[a])}var V={},le={},it=0,st=new D,Et=new N,lt=new $,Pt=new G,Tt=new F,ct=()=>it,ut=()=>{it++},ce=ve(),ae=Ye(),ue=()=>{},ie=Ee(le,n=>ue(n),ae.dispatchCustomMessage),dt=Pe(ct,ut,le,ce),h=Te(st,dt,ct,ut,le,ce),Mt=we(ie),L=Me(h),{getActiveOffers:St,getActiveGroupOffers:It,canBuyGroupOffer:de,buyGroupOffer:Lt,buyOffer:At,buyShopSlot:Ot,getRewardedAdsWatchedForStoreItem:Ct,haveEnoughResources:xt}=Se(h,L.getSystemProfileValue,L.getDocumentValue),k=Ie(h),re=Le(h),oe=Ae(h,L.getDocumentValue),I=Oe(h),se=n=>lt.get(n,h,u.GetLocalization),R=n=>Et.get(n,h,u.GetImageUrl),Bt=n=>Pt.get(n,h,u.GetFileLocation),rt=n=>Tt.get(n,h,u.GetPrefabContent),mt=qe(L.getDocumentValue),me=Ce(se),pe=xe(R),kt=Be(R,J);w.setPrepareSpritesFunction(pe.prepareAllSprites);var pt=ke(h,de,R),Rt=Re(h,mt,Y,_,me.setLocalizedText),Ht=Ke(R),q=async(n=document)=>{let e=n===document?"whole page":`<${n.tagName?.toLowerCase()||"element"} id="${n.id||"unknown"}">`;console.info(`[Balancy] Preparing all UI elements for: ${e}`),n!==document&&await S.processPrefabPlaceholdersInScope(n),await me.localizeAllElements(n),await kt.prepareAllFonts(n),await pe.prepareAllSprites(n),await pt.prepareAllButtons(n),await Rt.prepareAllTexts(n),await Ht.prepareAllAudio(n),console.info(`[Balancy] All UI elements prepared for: ${e}`)},Dt=()=>{document.querySelectorAll(`[data-button-action="${u.BuyGroupOffer}"]`).forEach(e=>{let t=parseInt(e.getAttribute("data-index")||"0",10)||0;de(t).then(r=>{e.disabled=!r})})};ue=We(Dt);var ot=!1,at=()=>dt(null,u.BalancyIsReady,{id:"none"});Object.assign(V,{NotificationType:O,PriceType:ye,ItemType:B,TaskStatus:ge,RequestAction:u,BuyButtonState:be,OfferGroupType:he,NumberDisplayFormat:E,TimeDisplayFormat:C,TimePrecision:g,postMessage:ce,_receiveMessageFromUnity:Mt,handleResponse:ie,sendRequest:h,batchManager:st,getProfileValue:L.getProfileValue,getSystemProfileValue:L.getSystemProfileValue,getDocumentValue:L.getDocumentValue,getActiveOffers:St,getActiveGroupOffers:It,canBuyGroupOffer:de,buyGroupOffer:Lt,buyOffer:At,buyShopSlot:Ot,getRewardedAdsWatchedForStoreItem:Ct,haveEnoughResources:xt,getTasks:k.getTasks,activateTasks:k.activateTasks,deactivateTasks:k.deactivateTasks,restoreFailedTask:k.restoreFailedTask,claimTaskReward:k.claimTaskReward,getInventoryItemsCount:re.getInventoryItemsCount,addInventoryItems:re.addInventoryItems,removeInventoryItems:re.removeInventoryItems,getBattlePassConfig:oe.getBattlePassConfig,getBattlePassProgress:oe.getBattlePassProgress,claimBattlePassReward:oe.claimBattlePassReward,getCustomEventInfo:I.getCustomEventInfo,setCustomEventInfo:I.setCustomEventInfo,stopEventManually:I.stopEventManually,watchRewardedAd:I.watchRewardedAd,getProductInfo:I.getProductInfo,closeView:I.closeView,sendCustomMessage:I.sendCustomMessage,getLocalizedText:se,getImageUrl:R,getFileLocation:Bt,getPrefabContent:rt,setLocalizedText:me.setLocalizedText,setImage:pe.setImage,formatTime:Y,formatString:Fe,formatItemsCount:Ge,formatItemCount:Ue,shortenCount:W,itemHasDecayEffect:j,itemGetBundleReward:$e,getTimeLeft:_,formatDataTemplate:mt,injectFontFace:J,findDomElement:Ve,balancyButtonClicked:pt.balancyButtonClicked,notificationReceived:ue,subscribeToCustomMessages:ae.subscribeToCustomMessages,dispatchCustomMessage:ae.dispatchCustomMessage,sendIsReady:at,delayIsReady:()=>{ot=!0},ElementBehaviour:z,ElementObject:M,ElementsManager:w,PrefabsManager:S,instantiatePrefabById:n=>w.instantiatePrefabById(n),prepareAllUIElements:q,initResponseHandler:()=>{if(V._responseHandlerInitialized)return;V._responseHandlerInitialized=!0;let n=new Map;_e(ie,()=>q(),at,ot,async()=>{try{console.info("[Balancy] Preloading mandatory localization keys..."),await Promise.all(je.map(t=>se(t))),ze(t=>lt.getCached(t)),console.info("[Balancy] Mandatory localization keys preloaded"),S.setUIProcessor(async t=>{await q(t)}),S.setLoader(async t=>{try{if(n.has(t)){console.info(`[Balancy] Using cached prefab: ${t}`);let s=n.get(t),l=s.cloneNode(!0);return ne(s,l),l}console.info(`[Balancy] Loading prefab for the first time: ${t}`);let r=await rt(t);if(console.info(`[Balancy] Received HTML content (length: ${r?.length||0})`),!r)return console.error(`[Balancy] No HTML content returned for prefab: ${t}`),null;let o=new DOMParser().parseFromString(r,"text/html"),i=o.body.firstElementChild;if(!i)return console.error(`[Balancy] No root element found in prefab body for: ${t}`),null;let c=o.head.querySelectorAll("style");return c.length>0&&c.forEach(s=>{let d=(s.textContent||"").replace(/\*\s*\{[^}]*\}/g,"").replace(/body\s*\{[^}]*\}/g,"").replace(/html\s*\{[^}]*\}/g,"");if(d=d.trim(),d){let m=document.createElement("style");m.textContent=d,m.setAttribute("data-prefab-id",t),document.head.appendChild(m)}else console.warn(`[Balancy] No styles left after filtering for prefab: ${t}`)}),console.info(`[Balancy] Processing UI elements for prefab ${t}...`),await q(i),console.info(`[Balancy] UI elements processed for prefab ${t}`),n.set(t,i),console.info("[Balancy] Prefab loaded and cached successfully:"),console.info(` - Root element: <${i.tagName.toLowerCase()} id="${i.id}">`),console.info(` - Children count: ${i.children.length}`),console.info(" - Full element:",i),i}catch(r){return console.error(`[Balancy] Error in prefab loader for "${t}":`,r),null}}),await S.processPrefabPlaceholders(),w.initialize();try{let t=document.body.querySelector("[data-guid]");if(t){let r=t.getAttribute("data-guid");console.info(`[Balancy] Found root element with GUID: ${r}`);let a=w.getElementByGuid(r);if(a){let o=a.components;if(o.length>0){console.info(`[Balancy] Root element has ${o.length} component(s)`);let i=o[0].scriptInstance;if(typeof i.init=="function"){console.info("[Balancy] Calling init() on root script with balancyViewOwner");let c=window.balancyViewOwner;c?i.init(c):(console.warn("[Balancy] window.balancyViewOwner is not defined, calling init() without arguments"),i.init())}else console.info("[Balancy] Root script does not have an init() method")}else console.info("[Balancy] Root element has no script components")}}else console.info("[Balancy] No root element found with data-guid attribute")}catch(t){console.error("[Balancy] Error auto-initializing root script:",t)}document.dispatchEvent(new CustomEvent("balancy-components-complete"))}catch(t){console.error("[Balancy] Error initializing component system:",t),document.dispatchEvent(new CustomEvent("balancy-components-complete"))}})}});typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",K):K());typeof window<"u"&&(window.balancy=V);console.log("\u{1F389} [BRIDGE] Balancy WebView Bridge loaded successfully!");return balancy;})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@balancy/bridge",
3
- "version": "1.2.2",
3
+ "version": "1.2.3",
4
4
  "description": "Balancy WebView Bridge - Unity-like component system for HTML/JavaScript",
5
5
  "author": {
6
6
  "name": "Balancy Team"