@balancy/bridge 1.2.4 → 1.2.5
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.
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// Balancy WebView Bridge
|
|
2
2
|
// Generated by esbuild
|
|
3
3
|
|
|
4
|
-
"use strict";var balancy=(()=>{var u={None:0,GetProfile:1,SetProfile:2,GetDocument:3,GetLocalization:10,GetImageUrl:11,GetInfo:12,CanBuyGroupOffer:13,GetFileLocation:14,GetPrefabContent:15,GetBattlePassProgress:20,GetCustomEventInfo:21,SetCustomEventInfo:22,GetTasksInfoForTheEvent:23,ActivateTasksForTheEvent:24,DeactivateTasksForTheEvent:25,ClaimTaskReward:26,GetCustomDocumentInfo:27,SetCustomDocumentInfo:28,StopEventManually:29,GetInventoryItemsCount:30,AddInventoryItems:31,RemoveInventoryItems:32,WatchRewardedAd:40,RestoreFailedTask:41,GetRewardedAdsWatched:42,HaveEnoughResources:43,BuyOffer:101,BuyGroupOffer:102,BuyShopSlot:103,BattlePassClaim:104,CloseWindow:200,BalancyIsReady:201,BatchRequest:399,CustomMessage:1e3},B={Currency:1,Item:2,Event:4},ge={Hard:0,Soft:1,Ads:2},ye={None:0,InProgress:1,Completed:2,Claimed:3,Failed:4},T={None:0,OfferPrice:1,OfferGroupPrice:2,TimeLeft:3,OwnerLocalizedKey:4,OwnerCustom:5,CustomPrice:9,Custom:10},C={OnNewEventActivated:100,OnEventDeactivated:101,OnNewOfferActivated:102,OnOfferDeactivated:103,OnNewOfferGroupActivated:104,OnOfferGroupDeactivated:105,OnShopSlotWasPurchased:120,OnOfferWasPurchased:121,OnOfferGroupWasPurchased:122},be={Available:0,Unavailable:1,Cooldown:2,Locked:3},he={Default:0,ChainDeals:1,OnePurchase:2,OnceForEach:3},P={Plain:0,PlainSpaced:1,WithPrefix:2,WithPrefixSpaced:3,Shortened:4,ShortenedWithPrefix:5},O={Localized:0,Colon:1,LocalizedCompact:2},y={Auto:0,DaysHours:1,HoursMinutes:2,HoursMinutesSeconds:3,MinutesSeconds:4,Full:5};var D=class{constructor(){this.pendingBatch=new Map;this.batchTimeout=null;this.BATCH_DELAY=16}addToBatch(e,t,a,r,o,i,c,s){let l=e.toString(),d={type:"request",sender:t,id:l,action:a,params:r};return this.pendingBatch.set(l,{requestData:d,resolve:o,reject:i}),this.scheduleBatch(c,s),l}scheduleBatch(e,t){this.batchTimeout||(this.batchTimeout=setTimeout(()=>{this.sendBatch(e,t)},this.BATCH_DELAY))}sendBatch(e,t){if(this.pendingBatch.size===0){this.batchTimeout=null;return}let a=[];this.pendingBatch.forEach((o,i)=>{a.push(o.requestData),e[i]={resolve:o.resolve,reject:o.reject,timestamp:Date.now(),message:o.requestData}}),console.log(`[BatchManager] Sending batch with ${this.pendingBatch.size} requests`),t(JSON.stringify({type:"batch",requests:a})),this.pendingBatch.clear(),this.batchTimeout=null}getStats(){return{pendingCount:this.pendingBatch.size,isScheduled:this.batchTimeout!==null}}};function ve(){return function(e){if(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.BalancyWebView)return typeof e!="string"&&(e=JSON.stringify(e)),window.webkit.messageHandlers.BalancyWebView.postMessage(e),!0;if(typeof window.SendMessage=="function"){typeof e!="string"&&(e=JSON.stringify(e));try{return window.SendMessage("BalancyView","OnWebGLMessageReceived",e),!0}catch(t){return console.error("[postMessage] \u274C Error calling SendMessage:",t),!1}}return window.BalancyWebView&&window.BalancyWebView.sendMessageToUnity?(typeof e!="string"&&(e=JSON.stringify(e)),window.BalancyWebView.sendMessageToUnity(e),!0):window.parent&&window.parent!==window&&window.parent.postMessage?(window.parent.postMessage(e,"*"),!0):(console.warn("BalancyWebView: No message handler available for platform"),window.BalancyWebView&&window.BalancyWebView.log&&window.BalancyWebView.log("warn","No message handler available for platform"),!1)}}function we(n){return function(t){window.BalancyWebView&&window.BalancyWebView.log?window.BalancyWebView.log("info","Received message from Unity: "+t.substring(0,100)+"..."):console.log("BalancyWebView: Received message from Unity:",t.substring(0,100)+"..."),n(t)}}function Ee(n,e,t){return function(r){try{let o=JSON.parse(r);if(o.type==="response"){let i=n[o.id];i&&(o.error?i.reject(new Error(o.error+" : "+JSON.stringify(i.message))):i.resolve(o.result),delete n[o.id])}else if(o.type==="batch-response")o.responses&&Array.isArray(o.responses)&&o.responses.forEach(i=>{let c=n[i.id];c&&(i.error?c.reject(new Error(i.error+" : "+JSON.stringify(c.message))):c.resolve(i.result),delete n[i.id])});else if(o.type==="notification"){let i=o.data?JSON.parse(o.data):null;e(i)}else o.type==="custom-message"&&t(o.data)}catch(o){console.error("Error handling response:",o)}}}function Pe(n,e,t,a){return function(o,i,c={}){return new Promise((s,l)=>{let d=n().toString();e();let m={type:"request",sender:o,id:d,action:i,params:c};t[d]={resolve:s,reject:l,timestamp:Date.now(),message:m},a(JSON.stringify(m))})}}function Te(n,e,t,a,r,o){return function(c,s,l={}){return[u.BuyOffer,u.BuyGroupOffer,u.BuyShopSlot,u.BattlePassClaim,u.CloseWindow,u.CustomMessage,u.BalancyIsReady,u.StopEventManually,u.WatchRewardedAd].includes(s)?e(c,s,l):new Promise((m,p)=>{let g=n.addToBatch(t(),c,s,l,m,p,r,o);a()})}}var $=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,a){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let r=t(null,a,{id:e}).then(o=>(this.cache[e]=o,delete this.pendingRequests[e],o)).catch(o=>{throw delete this.pendingRequests[e],o});return this.pendingRequests[e]=r,r}};var N=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,a){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let r=t(null,a,{key:e}).then(o=>(this.cache[e]=o,delete this.pendingRequests[e],o)).catch(o=>{throw delete this.pendingRequests[e],o});return this.pendingRequests[e]=r,r}getCached(e){return this.cache[e]??null}};var G=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,a){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let r=t(null,a,{id:e}).then(o=>(this.cache[e]=o,delete this.pendingRequests[e],o)).catch(o=>{throw delete this.pendingRequests[e],o});return this.pendingRequests[e]=r,r}};var F=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,a){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let r=t(null,a,{id:e}).then(o=>(this.cache[e]=o,delete this.pendingRequests[e],o)).catch(o=>{throw delete this.pendingRequests[e],o});return this.pendingRequests[e]=r,r}};function Me(n){return{getProfileValue(e,t){return n(null,u.GetProfile,{profile:e,path:t})},getSystemProfileValue(e){return n(null,u.GetProfile,{profile:"UnnyProfile",path:e})},getDocumentValue(e,t){return n(null,u.GetDocument,{id:e,depth:t}).then(a=>JSON.parse(a))}}}function Ie(n,e,t){return{async getActiveOffers(a=3){let r=await e("SmartInfo.GameOffers");if(!Array.isArray(r)||r.length===0)return r||[];let o=[];for(let l of r)o.includes(l.unnyIdGameOffer)||o.push(l.unnyIdGameOffer);let i=o.map(l=>t(l,a)),c=await Promise.all(i),s={};for(let l=0;l<o.length;l++)s[o[l]]=c[l];for(let l of r){let d=l?.unnyIdGameOffer;d!=null&&s.hasOwnProperty(d)&&(l.gameOffer=s[d])}return r},async getActiveGroupOffers(a=3){let r=await e("SmartInfo.GameOfferGroups");if(!Array.isArray(r)||r.length===0)return r||[];let o=[];for(let l of r)o.includes(l.unnyIdGameOfferGroup)||o.push(l.unnyIdGameOfferGroup);let i=o.map(l=>t(l,a)),c=await Promise.all(i),s={};for(let l=0;l<o.length;l++)s[o[l]]=c[l];for(let l of r){let d=l?.unnyIdGameOfferGroup;d!=null&&s.hasOwnProperty(d)&&(l.gameOfferGroup=s[d])}return r},canBuyGroupOffer(a){return n(null,u.CanBuyGroupOffer,{instanceId:window.balancyViewOwner.instanceId,index:a})},buyGroupOffer(a,r={}){return!window.balancyViewOwner||!window.balancyViewOwner.instanceId?Promise.resolve(null):(r||(r={}),r.instanceId=window.balancyViewOwner.instanceId,r.index=a,n("buyGroupOfferButton",u.BuyGroupOffer,r))},buyOffer(a={}){return!window.balancyViewOwner||!window.balancyViewOwner.instanceId?Promise.resolve(null):(a||(a={}),a.instanceId=window.balancyViewOwner.instanceId,n("buyOfferButton",u.BuyOffer,a))},buyShopSlot(a,r={}){return r||(r={}),a?.unnyIdSlot&&(r.slotId=a.unnyIdSlot),n("buyShopSlotButton",u.BuyShopSlot,r)},getRewardedAdsWatchedForStoreItem(a){return a?.unnyId?n(null,u.GetRewardedAdsWatched,{id:a.unnyId}):Promise.resolve(0)},haveEnoughResources(a){return a?.unnyId?n(null,u.HaveEnoughResources,{id:a.unnyId}):Promise.resolve(!1)}}}function Se(n){return{getTasks(){return n(null,u.GetTasksInfoForTheEvent,{id:window.balancyViewOwner.unnyIdGameEvent}).then(e=>JSON.parse(e))},activateTasks(e){return n(null,u.ActivateTasksForTheEvent,{id:window.balancyViewOwner.unnyIdGameEvent,tasks:e}).then(t=>JSON.parse(t))},deactivateTasks(e){return n(null,u.DeactivateTasksForTheEvent,{id:window.balancyViewOwner.unnyIdGameEvent,tasks:e})},restoreFailedTask(e){return n(null,u.RestoreFailedTask,{id:e?e.unnyIdTask:""})},claimTaskReward(e){return n(null,u.ClaimTaskReward,{id:e}).then(t=>t&&t==="ok")}}}function Le(n){return{getInventoryItemsCount(e){return n(null,u.GetInventoryItemsCount,{id:e})},addInventoryItems(e,t){return n(null,u.AddInventoryItems,{id:e,count:t})},removeInventoryItems(e,t){return n(null,u.RemoveInventoryItems,{id:e,count:t})}}}function Ae(n,e){return{getBattlePassConfig(){return e(window.balancyViewOwner.unnyIdGameEvent,3).then(t=>t.config)},getBattlePassProgress(){return n(null,u.GetBattlePassProgress,{id:window.balancyViewOwner.unnyIdGameEvent}).then(t=>JSON.parse(t))},claimBattlePassReward(t,a){return n(null,u.BattlePassClaim,{id:window.balancyViewOwner.unnyIdGameEvent,lineId:t,index:a}).then(r=>r&&r==="ok")}}}function Ce(n){return{getCustomEventInfo(){return n(null,u.GetCustomEventInfo,{id:window.balancyViewOwner.instanceId}).then(e=>e?JSON.parse(e):{})},setCustomEventInfo(e){let t=JSON.stringify(e);return n(null,u.SetCustomEventInfo,{id:window.balancyViewOwner.instanceId,data:t})},stopEventManually(e=-1){return n(null,u.StopEventManually,{id:window.balancyViewOwner.unnyIdGameEvent,cooldown:e}).then(t=>t)},watchRewardedAd(e){return n(null,u.WatchRewardedAd,{}).then(t=>{e(!!t.success)})},getProductInfo(e){return n("offerGroupPrice",u.GetInfo,{type:T.CustomPrice,productId:e})},closeView(e){return n(null,u.CloseWindow,{id:e})},sendCustomMessage(e,t){return n(e,u.CustomMessage,t)}}}function Oe(n){return{async setLocalizedText(e,t){if(t){let a=await n(t);e.textContent=a}e.classList.add("balancy-text-prepared")},async localizeAllElements(e=document){let t=e.querySelectorAll('[data-text-type="localized"]'),a=Array.from(t).map(async r=>{if(r.classList.contains("balancy-text-prepared"))return;let o=r.getAttribute("data-localization-key");await this.setLocalizedText(r,o)});await Promise.all(a),e===document&&document.dispatchEvent(new CustomEvent("balancy-localization-complete"))}}}function xe(n){async function e(t,a){t.classList.add("balancy-image-prepared");let r=await n(a);r&&(t.tagName==="IMG"?t.src=r:t.hasAttribute("data-use-nineslice")&&t.getAttribute("data-use-nineslice")==="false"?t.style.backgroundImage=`url('${r}')`:t.style.borderImageSource=`url('${r}')`)}return{setImage(t,a){a?.id&&(t.setAttribute("data-image-id",a.id),e(t,a.id))},async prepareAllSprites(t=document){let a=t.querySelectorAll("[data-image-id]"),r=Array.from(a).map(async o=>{if(o.classList.contains("balancy-image-prepared"))return;let i=o.getAttribute("data-image-id");i&&await e(o,i)});await Promise.all(r),t===document&&document.dispatchEvent(new CustomEvent("balancy-images-complete"))}}}function Be(n,e){return{async prepareAllFonts(t=document){let a=t.querySelectorAll("[data-font-id]"),r=Array.from(a).map(async o=>{if(o.classList.contains("balancy-font-prepared"))return;let i=o.getAttribute("data-font-name"),c=o.getAttribute("data-font-id");if(i&&c){let s=await n(c);e(i,s)}});await Promise.all(r),t===document&&document.dispatchEvent(new CustomEvent("balancy-fonts-complete"))}}}function Re(n,e,t){function a(i){let c=i.getAttribute("data-button-action");if(!c)return;switch(parseInt(c,10)){case u.BuyGroupOffer:let l=parseInt(i.getAttribute("data-index")||"0",10)||0;e(l).then(d=>{i.disabled=!d});break}}async function r(i){let c=i.getAttribute("data-button-audio-id");if(!c)return;let s=await t(c);if(!s)return;let l=document.createElement("audio");l.autoplay=!0,l.src=s,l.addEventListener("ended",()=>{l.remove()}),l.addEventListener("error",()=>{l.remove()}),document.body.appendChild(l)}function o(i,c){let s=c?.action??i.getAttribute("data-button-action");if(!s){console.warn("Button missing data-button-action attribute",i);return}let l=parseInt(s,10);if(isNaN(l)||l===u.None){console.warn("Invalid action ID:",s,i);return}let d=i.id||"unknown-button",m=i.getAttribute("data-button-params"),p={};if(m&&m.trim()!=="")try{p=JSON.parse(m)}catch(b){console.error("Error parsing button params JSON:",b,"Raw params:",m),i.dispatchEvent(new CustomEvent("balancyButtonError",{detail:{actionId:l,error:"Invalid JSON in data-button-params",paramsAttr:m}})),p={}}switch(l){case u.BuyOffer:p.instanceId=c?.instanceId??window.balancyViewOwner.instanceId;break;case u.BuyGroupOffer:p.instanceId=window.balancyViewOwner.instanceId,p.index=parseInt(i.getAttribute("data-index")||"0",10)||0;break;case u.BuyShopSlot:p.slotId=i.getAttribute("data-index")||0;break}let g=i.disabled;i.disabled=!0,i.classList.add("balancy-button-processing"),n(d,l,p).then(b=>{console.log(`Button action ${l} executed successfully`,b),i.dispatchEvent(new CustomEvent("balancyButtonResponse",{detail:{actionId:l,result:b,success:!0,senderId:d}}))}).catch(b=>{console.error(`Error executing button action ${l}:`,b),i.dispatchEvent(new CustomEvent("balancyButtonResponse",{detail:{actionId:l,error:b.message,success:!1,senderId:d}}))}).finally(()=>{i.disabled=g,i.classList.remove("balancy-button-processing")})}return{balancyButtonClicked:o,prepareAllButtons(i=document){let c=i.querySelectorAll("[data-button-action]"),s=i.querySelectorAll("[data-button-audio-id]"),l=[...Array.from(c),...Array.from(s)],d=0;l.forEach(m=>{m.classList.contains("balancy-button-prepared")||(m._balancyClickHandler&&m.removeEventListener("click",m._balancyClickHandler),m._balancyClickHandler=function(p){p.preventDefault(),p.stopPropagation(),m.hasAttribute("data-button-action")&&o(m),m.hasAttribute("data-button-audio-id")&&r(m)},a(m),m.addEventListener("click",m._balancyClickHandler),m.classList.add("balancy-button-prepared"),d++)}),i===document&&document.dispatchEvent(new CustomEvent("balancy-buttons-complete",{detail:{preparedCount:d,totalFound:l.length}}))}}}function ke(n,e,t,a,r){return{prepareAllTexts(o=document){let i=o.querySelectorAll('[data-text-type="dynamic"]'),c=[];i.forEach(s=>{if(s.classList.contains("balancy-text-prepared"))return;s.classList.add("balancy-text-prepared");let l=s.id||"unknown-text",d=parseInt(s.getAttribute("data-info-type")||"0",10)||0,m=parseInt(s.getAttribute("data-index")||"0",10)||0,p=s.getAttribute("data-custom")||"",g=s.getAttribute("data-product-id")||"",b="";if(d===T.OfferPrice?(g=window.balancyViewOwner.productId,d=T.CustomPrice):d===T.OfferGroupPrice&&(b=window.balancyViewOwner.instanceId),d===T.TimeLeft){let w=function(){E.textContent=t(a())};var S=w;let E=s;setInterval(w,1e3),w();return}if(d===T.OwnerCustom){let E=s.getAttribute("data-text-format");E&&e(E,window.balancyViewOwner).then(w=>{s.textContent=w});return}if(d===T.OwnerLocalizedKey){let E=s.getAttribute("data-text-format");E&&e(E,window.balancyViewOwner).then(w=>r(s,w));return}let H=n(l,u.GetInfo,{type:d,productId:g,index:m,instanceId:b,custom:p}).then(E=>{try{let w=s.getAttribute("data-text-format");w&&e(w,E).then(fe=>{s.textContent=fe})}catch(w){console.error("Error formatting text:",w,"Result:",E)}});c.push(H)}),Promise.all(c).then(()=>{o===document&&document.dispatchEvent(new CustomEvent("balancy-text-complete"))})}}}function W(n){return n>=1e9?`${parseFloat((n/1e9).toFixed(1))}B`:n>=1e6?`${parseFloat((n/1e6).toFixed(1))}M`:n>=1e3?`${parseFloat((n/1e3).toFixed(1))}k`:n.toString()}function j(n){if(n&&!n.hasOwnProperty("unnyIdComponents"))return console.error("Item has no components, probably you need to increase depth when fetching item data: ",n),!1;let e=n?.components;if(!e)return!1;for(let t of e)if(t.$type==="SmartObjects.ItemComponent.Decay")return!0;return!1}function Ne(n){let e=n?.components;if(!e)return null;for(let t of e)if(t.$type==="SmartObjects.ItemComponent.Bundle")return t.reward;return null}function Ge(n,e=!1){let t=j(n.item),a=n.item.type===B.Currency,r;if(t){let o=n.count,i=Math.floor(o/3600),c=Math.floor(o%3600/60);r=`${i>0?`${i}h `:""}${c>0?`${c}m`:""}`}else{let o=e?W(n.count):n.count.toString();r=a?`${n.count}`:`x${o}`}return{text:r,isDuration:t,isCurrency:a}}function Y(n){if(n>3600*24*365)return"oo";if(window.customFormatTime)return window.customFormatTime(n);let e=Math.floor(n/86400),t=Math.floor(n%86400/3600),a=Math.floor(n%3600/60),r=n%60;return e>0?t>0?`${e}d ${t}h`:`${e}d`:`${t.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}function Fe(n,...e){return n.replace(/{(\d+)}/g,(t,a)=>e[a]!==void 0?e[a]:t)}function _(){let e=Math.floor(Date.now()/1e3)-window.balancySettings.launchTime;return window.balancySettings.secondsLeft-e}var je=["BALANCY/TIME_DAY","BALANCY/TIME_HOUR","BALANCY/TIME_MINUTE","BALANCY/TIME_SECOND","BALANCY/NUMBER_THOUSAND","BALANCY/NUMBER_MILLION","BALANCY/NUMBER_BILLION"],f={};function ze(n){f={day:n("BALANCY/TIME_DAY")||"d",hour:n("BALANCY/TIME_HOUR")||"h",minute:n("BALANCY/TIME_MINUTE")||"m",second:n("BALANCY/TIME_SECOND")||"s",thousand:n("BALANCY/NUMBER_THOUSAND")||"k",million:n("BALANCY/NUMBER_MILLION")||"M",billion:n("BALANCY/NUMBER_BILLION")||"B"}}function He(n){return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g," ")}function De(n){return n>=1e9?`${parseFloat((n/1e9).toFixed(1))}${f.billion||"B"}`:n>=1e6?`${parseFloat((n/1e6).toFixed(1))}${f.million||"M"}`:n>=1e3?`${parseFloat((n/1e3).toFixed(1))}${f.thousand||"k"}`:n.toString()}function ft(n,e){switch(e){case P.Plain:return n.toString();case P.PlainSpaced:return He(n);case P.WithPrefix:return`x${n}`;case P.WithPrefixSpaced:return`x${He(n)}`;case P.Shortened:return De(n);case P.ShortenedWithPrefix:return`x${De(n)}`;default:return n.toString()}}function gt(n,e){let t=Math.floor(n/86400),a=Math.floor(n%86400/3600),r=Math.floor(n%3600/60),o=n%60;switch(e){case y.DaysHours:return t>0?`${t}:${a.toString().padStart(2,"0")}`:`${a}:00`;case y.HoursMinutes:return`${a}:${r.toString().padStart(2,"0")}`;case y.HoursMinutesSeconds:return`${a}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`;case y.MinutesSeconds:return`${r}:${o.toString().padStart(2,"0")}`;case y.Full:return t>0?`${t}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`:`${a}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`;case y.Auto:default:return t>0?`${t}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${a}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`}}function $e(n,e,t){let a=Math.floor(n/86400),r=Math.floor(n%86400/3600),o=Math.floor(n%3600/60),i=n%60,c=[],s=(l,d)=>{t?l>0&&c.push(`${l}${d}`):c.push(`${l}${d}`)};switch(e){case y.DaysHours:s(a,f.day||"d"),s(r,f.hour||"h");break;case y.HoursMinutes:s(r,f.hour||"h"),s(o,f.minute||"m");break;case y.HoursMinutesSeconds:s(r,f.hour||"h"),s(o,f.minute||"m"),s(i,f.second||"s");break;case y.MinutesSeconds:s(o,f.minute||"m"),s(i,f.second||"s");break;case y.Full:s(a,f.day||"d"),s(r,f.hour||"h"),s(o,f.minute||"m"),s(i,f.second||"s");break;case y.Auto:default:a>0?(s(a,f.day||"d"),s(r,f.hour||"h")):r>0?(s(r,f.hour||"h"),s(o,f.minute||"m")):(s(o,f.minute||"m"),(!t||i>0)&&s(i,f.second||"s"));break}return c.join(" ")}function Ue(n,e={}){let t=e.currencyFormat??P.Plain,a=e.regularItemFormat??P.WithPrefix,r=e.timeFormat??O.LocalizedCompact,o=e.timePrecision??y.Auto,i=j(n.item),c=n.item.type===B.Currency,s;if(i){let l=n.count;r===O.Colon?s=gt(l,o):r===O.Localized?s=$e(l,o,!1):s=$e(l,o,!0)}else{let l=c?t:a;s=ft(n.count,l)}return{text:s,isDuration:i,isCurrency:c}}function qe(n){function e(a){return a.charAt(0).toUpperCase()+a.slice(1)}async function t(a,r){let o=r.split("."),i=a;for(let c=0;c<o.length;c++){let s=o[c].trim();if(i&&i[s]!==void 0&&i[s]!==null)i=i[s];else{let l="unnyId"+e(s);if(i&&i[l]!==void 0)try{let d=await n(i[l],0);if(c+1<o.length){let m=o.slice(c+1).join(".");return await t(d,m)}else return d}catch(d){console.error(`Failed to get document for ID ${i[l]}:`,d);return}return}}return i}return async function(r,o){if(!r.includes("{")||!r.includes("}"))return r;let i=[],c=/\{([^}]+)\}/g,s;for(;(s=c.exec(r))!==null;)i.push({fullMatch:s[0],path:s[1].trim(),index:s.index});if(i.length===0)return r;let l=i.map(async p=>{let g=await t(o,p.path);return{placeholder:p.fullMatch,value:g!==void 0?String(g):p.fullMatch}}),d=await Promise.all(l),m=r;for(let p of d)m=m.replace(p.placeholder,p.value);return m}}function J(n,e){let t=document.createElement("style");t.type="text/css",t.textContent=`
|
|
4
|
+
"use strict";var balancy=(()=>{var u={None:0,GetProfile:1,SetProfile:2,GetDocument:3,GetLocalization:10,GetImageUrl:11,GetInfo:12,CanBuyGroupOffer:13,GetFileLocation:14,GetPrefabContent:15,GetBattlePassProgress:20,GetCustomEventInfo:21,SetCustomEventInfo:22,GetTasksInfoForTheEvent:23,ActivateTasksForTheEvent:24,DeactivateTasksForTheEvent:25,ClaimTaskReward:26,GetCustomDocumentInfo:27,SetCustomDocumentInfo:28,StopEventManually:29,GetInventoryItemsCount:30,AddInventoryItems:31,RemoveInventoryItems:32,WatchRewardedAd:40,RestoreFailedTask:41,GetRewardedAdsWatched:42,HaveEnoughResources:43,BuyOffer:101,BuyGroupOffer:102,BuyShopSlot:103,BattlePassClaim:104,CloseWindow:200,BalancyIsReady:201,BatchRequest:399,CustomMessage:1e3},B={Currency:1,Item:2,Event:4},be={Hard:0,Soft:1,Ads:2},he={None:0,InProgress:1,Completed:2,Claimed:3,Failed:4},T={None:0,OfferPrice:1,OfferGroupPrice:2,TimeLeft:3,OwnerLocalizedKey:4,OwnerCustom:5,CustomPrice:9,Custom:10},C={OnNewEventActivated:100,OnEventDeactivated:101,OnNewOfferActivated:102,OnOfferDeactivated:103,OnNewOfferGroupActivated:104,OnOfferGroupDeactivated:105,OnShopSlotWasPurchased:120,OnOfferWasPurchased:121,OnOfferGroupWasPurchased:122},ve={Available:0,Unavailable:1,Cooldown:2,Locked:3},we={Default:0,ChainDeals:1,OnePurchase:2,OnceForEach:3},P={Plain:0,PlainSpaced:1,WithPrefix:2,WithPrefixSpaced:3,Shortened:4,ShortenedWithPrefix:5},O={Localized:0,Colon:1,LocalizedCompact:2},y={Auto:0,DaysHours:1,HoursMinutes:2,HoursMinutesSeconds:3,MinutesSeconds:4,Full:5};var D=class{constructor(){this.pendingBatch=new Map;this.batchTimeout=null;this.BATCH_DELAY=16}addToBatch(e,t,a,r,o,i,c,s){let l=e.toString(),d={type:"request",sender:t,id:l,action:a,params:r};return this.pendingBatch.set(l,{requestData:d,resolve:o,reject:i}),this.scheduleBatch(c,s),l}scheduleBatch(e,t){this.batchTimeout||(this.batchTimeout=setTimeout(()=>{this.sendBatch(e,t)},this.BATCH_DELAY))}sendBatch(e,t){if(this.pendingBatch.size===0){this.batchTimeout=null;return}let a=[];this.pendingBatch.forEach((o,i)=>{a.push(o.requestData),e[i]={resolve:o.resolve,reject:o.reject,timestamp:Date.now(),message:o.requestData}}),console.log(`[BatchManager] Sending batch with ${this.pendingBatch.size} requests`),t(JSON.stringify({type:"batch",requests:a})),this.pendingBatch.clear(),this.batchTimeout=null}getStats(){return{pendingCount:this.pendingBatch.size,isScheduled:this.batchTimeout!==null}}};function Ee(){return function(e){if(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.BalancyWebView)return typeof e!="string"&&(e=JSON.stringify(e)),window.webkit.messageHandlers.BalancyWebView.postMessage(e),!0;if(typeof window.SendMessage=="function"){typeof e!="string"&&(e=JSON.stringify(e));try{return window.SendMessage("BalancyView","OnWebGLMessageReceived",e),!0}catch(t){return console.error("[postMessage] \u274C Error calling SendMessage:",t),!1}}return window.BalancyWebView&&window.BalancyWebView.sendMessageToUnity?(typeof e!="string"&&(e=JSON.stringify(e)),window.BalancyWebView.sendMessageToUnity(e),!0):window.parent&&window.parent!==window&&window.parent.postMessage?(window.parent.postMessage(e,"*"),!0):(console.warn("BalancyWebView: No message handler available for platform"),window.BalancyWebView&&window.BalancyWebView.log&&window.BalancyWebView.log("warn","No message handler available for platform"),!1)}}function Pe(n){return function(t){window.BalancyWebView&&window.BalancyWebView.log?window.BalancyWebView.log("info","Received message from Unity: "+t.substring(0,100)+"..."):console.log("BalancyWebView: Received message from Unity:",t.substring(0,100)+"..."),n(t)}}function Te(n,e,t){return function(r){try{let o=JSON.parse(r);if(o.type==="response"){let i=n[o.id];i&&(o.error?i.reject(new Error(o.error+" : "+JSON.stringify(i.message))):i.resolve(o.result),delete n[o.id])}else if(o.type==="batch-response")o.responses&&Array.isArray(o.responses)&&o.responses.forEach(i=>{let c=n[i.id];c&&(i.error?c.reject(new Error(i.error+" : "+JSON.stringify(c.message))):c.resolve(i.result),delete n[i.id])});else if(o.type==="notification"){let i=o.data?JSON.parse(o.data):null;e(i)}else o.type==="custom-message"&&t(o.data)}catch(o){console.error("Error handling response:",o)}}}function Me(n,e,t,a){return function(o,i,c={}){return new Promise((s,l)=>{let d=n().toString();e();let m={type:"request",sender:o,id:d,action:i,params:c};t[d]={resolve:s,reject:l,timestamp:Date.now(),message:m},a(JSON.stringify(m))})}}function Ie(n,e,t,a,r,o){return function(c,s,l={}){return[u.BuyOffer,u.BuyGroupOffer,u.BuyShopSlot,u.BattlePassClaim,u.CloseWindow,u.CustomMessage,u.BalancyIsReady,u.StopEventManually,u.WatchRewardedAd].includes(s)?e(c,s,l):new Promise((m,p)=>{let g=n.addToBatch(t(),c,s,l,m,p,r,o);a()})}}var $=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,a){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let r=t(null,a,{id:e}).then(o=>(this.cache[e]=o,delete this.pendingRequests[e],o)).catch(o=>{throw delete this.pendingRequests[e],o});return this.pendingRequests[e]=r,r}};var N=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,a){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let r=t(null,a,{key:e}).then(o=>(this.cache[e]=o,delete this.pendingRequests[e],o)).catch(o=>{throw delete this.pendingRequests[e],o});return this.pendingRequests[e]=r,r}getCached(e){return this.cache[e]??null}};var G=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,a){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let r=t(null,a,{id:e}).then(o=>(this.cache[e]=o,delete this.pendingRequests[e],o)).catch(o=>{throw delete this.pendingRequests[e],o});return this.pendingRequests[e]=r,r}};var F=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,a){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let r=t(null,a,{id:e}).then(o=>(this.cache[e]=o,delete this.pendingRequests[e],o)).catch(o=>{throw delete this.pendingRequests[e],o});return this.pendingRequests[e]=r,r}};function Se(n){return{getProfileValue(e,t){return n(null,u.GetProfile,{profile:e,path:t})},getSystemProfileValue(e){return n(null,u.GetProfile,{profile:"UnnyProfile",path:e})},getDocumentValue(e,t){return n(null,u.GetDocument,{id:e,depth:t}).then(a=>JSON.parse(a))}}}function Le(n,e,t){return{async getActiveOffers(a=3){let r=await e("SmartInfo.GameOffers");if(!Array.isArray(r)||r.length===0)return r||[];let o=[];for(let l of r)o.includes(l.unnyIdGameOffer)||o.push(l.unnyIdGameOffer);let i=o.map(l=>t(l,a)),c=await Promise.all(i),s={};for(let l=0;l<o.length;l++)s[o[l]]=c[l];for(let l of r){let d=l?.unnyIdGameOffer;d!=null&&s.hasOwnProperty(d)&&(l.gameOffer=s[d])}return r},async getActiveGroupOffers(a=3){let r=await e("SmartInfo.GameOfferGroups");if(!Array.isArray(r)||r.length===0)return r||[];let o=[];for(let l of r)o.includes(l.unnyIdGameOfferGroup)||o.push(l.unnyIdGameOfferGroup);let i=o.map(l=>t(l,a)),c=await Promise.all(i),s={};for(let l=0;l<o.length;l++)s[o[l]]=c[l];for(let l of r){let d=l?.unnyIdGameOfferGroup;d!=null&&s.hasOwnProperty(d)&&(l.gameOfferGroup=s[d])}return r},canBuyGroupOffer(a){return n(null,u.CanBuyGroupOffer,{instanceId:window.balancyViewOwner.instanceId,index:a})},buyGroupOffer(a,r={}){return!window.balancyViewOwner||!window.balancyViewOwner.instanceId?Promise.resolve(null):(r||(r={}),r.instanceId=window.balancyViewOwner.instanceId,r.index=a,n("buyGroupOfferButton",u.BuyGroupOffer,r))},buyOffer(a={}){return!window.balancyViewOwner||!window.balancyViewOwner.instanceId?Promise.resolve(null):(a||(a={}),a.instanceId=window.balancyViewOwner.instanceId,n("buyOfferButton",u.BuyOffer,a))},buyShopSlot(a,r={}){return r||(r={}),a?.unnyIdSlot&&(r.slotId=a.unnyIdSlot),n("buyShopSlotButton",u.BuyShopSlot,r)},getRewardedAdsWatchedForStoreItem(a){return a?.unnyId?n(null,u.GetRewardedAdsWatched,{id:a.unnyId}):Promise.resolve(0)},haveEnoughResources(a){return a?.unnyId?n(null,u.HaveEnoughResources,{id:a.unnyId}):Promise.resolve(!1)}}}function Ae(n){return{getTasks(){return n(null,u.GetTasksInfoForTheEvent,{id:window.balancyViewOwner.unnyIdGameEvent}).then(e=>JSON.parse(e))},activateTasks(e){return n(null,u.ActivateTasksForTheEvent,{id:window.balancyViewOwner.unnyIdGameEvent,tasks:e}).then(t=>JSON.parse(t))},deactivateTasks(e){return n(null,u.DeactivateTasksForTheEvent,{id:window.balancyViewOwner.unnyIdGameEvent,tasks:e})},restoreFailedTask(e){return n(null,u.RestoreFailedTask,{id:e?e.unnyIdTask:""})},claimTaskReward(e){return n(null,u.ClaimTaskReward,{id:e}).then(t=>t&&t==="ok")}}}function Ce(n){return{getInventoryItemsCount(e){return n(null,u.GetInventoryItemsCount,{id:e})},addInventoryItems(e,t){return n(null,u.AddInventoryItems,{id:e,count:t})},removeInventoryItems(e,t){return n(null,u.RemoveInventoryItems,{id:e,count:t})}}}function Oe(n,e){return{getBattlePassConfig(){return e(window.balancyViewOwner.unnyIdGameEvent,3).then(t=>t.config)},getBattlePassProgress(){return n(null,u.GetBattlePassProgress,{id:window.balancyViewOwner.unnyIdGameEvent}).then(t=>JSON.parse(t))},claimBattlePassReward(t,a){return n(null,u.BattlePassClaim,{id:window.balancyViewOwner.unnyIdGameEvent,lineId:t,index:a}).then(r=>r&&r==="ok")}}}function xe(n){return{getCustomEventInfo(){return n(null,u.GetCustomEventInfo,{id:window.balancyViewOwner.instanceId}).then(e=>e?JSON.parse(e):{})},setCustomEventInfo(e){let t=JSON.stringify(e);return n(null,u.SetCustomEventInfo,{id:window.balancyViewOwner.instanceId,data:t})},stopEventManually(e=-1){return n(null,u.StopEventManually,{id:window.balancyViewOwner.unnyIdGameEvent,cooldown:e}).then(t=>t)},watchRewardedAd(e){return n(null,u.WatchRewardedAd,{}).then(t=>{e(!!t.success)})},getProductInfo(e){return n("offerGroupPrice",u.GetInfo,{type:T.CustomPrice,productId:e})},closeView(e){return n(null,u.CloseWindow,{id:e})},sendCustomMessage(e,t){return n(e,u.CustomMessage,t)}}}function Be(n){return{async setLocalizedText(e,t){if(t){let a=await n(t);e.textContent=a}e.classList.add("balancy-text-prepared")},async localizeAllElements(e=document){let t=e.querySelectorAll('[data-text-type="localized"]'),a=Array.from(t).map(async r=>{if(r.classList.contains("balancy-text-prepared"))return;let o=r.getAttribute("data-localization-key");await this.setLocalizedText(r,o)});await Promise.all(a),e===document&&document.dispatchEvent(new CustomEvent("balancy-localization-complete"))}}}function Re(n){async function e(t,a){t.classList.add("balancy-image-prepared");let r=await n(a);r&&(t.tagName==="IMG"?t.src=r:t.hasAttribute("data-use-nineslice")&&t.getAttribute("data-use-nineslice")==="false"?t.style.backgroundImage=`url('${r}')`:t.style.borderImageSource=`url('${r}')`)}return{setImage(t,a){a?.id&&(t.setAttribute("data-image-id",a.id),e(t,a.id))},async prepareAllSprites(t=document){let a=t.querySelectorAll("[data-image-id]"),r=Array.from(a).map(async o=>{if(o.classList.contains("balancy-image-prepared"))return;let i=o.getAttribute("data-image-id");i&&await e(o,i)});await Promise.all(r),t===document&&document.dispatchEvent(new CustomEvent("balancy-images-complete"))}}}function ke(n,e){return{async prepareAllFonts(t=document){let a=t.querySelectorAll("[data-font-id]"),r=Array.from(a).map(async o=>{if(o.classList.contains("balancy-font-prepared"))return;let i=o.getAttribute("data-font-name"),c=o.getAttribute("data-font-id");if(i&&c){let s=await n(c);e(i,s)}});await Promise.all(r),t===document&&document.dispatchEvent(new CustomEvent("balancy-fonts-complete"))}}}function He(n,e,t){function a(i){let c=i.getAttribute("data-button-action");if(!c)return;switch(parseInt(c,10)){case u.BuyGroupOffer:let l=parseInt(i.getAttribute("data-index")||"0",10)||0;e(l).then(d=>{i.disabled=!d});break}}async function r(i){let c=i.getAttribute("data-button-audio-id");if(!c)return;let s=await t(c);if(!s)return;let l=document.createElement("audio");l.autoplay=!0,l.src=s,l.addEventListener("ended",()=>{l.remove()}),l.addEventListener("error",()=>{l.remove()}),document.body.appendChild(l)}function o(i,c){let s=c?.action??i.getAttribute("data-button-action");if(!s){console.warn("Button missing data-button-action attribute",i);return}let l=parseInt(s,10);if(isNaN(l)||l===u.None){console.warn("Invalid action ID:",s,i);return}let d=i.id||"unknown-button",m=i.getAttribute("data-button-params"),p={};if(m&&m.trim()!=="")try{p=JSON.parse(m)}catch(b){console.error("Error parsing button params JSON:",b,"Raw params:",m),i.dispatchEvent(new CustomEvent("balancyButtonError",{detail:{actionId:l,error:"Invalid JSON in data-button-params",paramsAttr:m}})),p={}}switch(l){case u.BuyOffer:p.instanceId=c?.instanceId??window.balancyViewOwner.instanceId;break;case u.BuyGroupOffer:p.instanceId=window.balancyViewOwner.instanceId,p.index=parseInt(i.getAttribute("data-index")||"0",10)||0;break;case u.BuyShopSlot:p.slotId=i.getAttribute("data-index")||0;break}let g=i.disabled;i.disabled=!0,i.classList.add("balancy-button-processing"),n(d,l,p).then(b=>{console.log(`Button action ${l} executed successfully`,b),i.dispatchEvent(new CustomEvent("balancyButtonResponse",{detail:{actionId:l,result:b,success:!0,senderId:d}}))}).catch(b=>{console.error(`Error executing button action ${l}:`,b),i.dispatchEvent(new CustomEvent("balancyButtonResponse",{detail:{actionId:l,error:b.message,success:!1,senderId:d}}))}).finally(()=>{i.disabled=g,i.classList.remove("balancy-button-processing")})}return{balancyButtonClicked:o,prepareAllButtons(i=document){let c=i.querySelectorAll("[data-button-action]"),s=i.querySelectorAll("[data-button-audio-id]"),l=[...Array.from(c),...Array.from(s)],d=0;l.forEach(m=>{m.classList.contains("balancy-button-prepared")||(m._balancyClickHandler&&m.removeEventListener("click",m._balancyClickHandler),m._balancyClickHandler=function(p){p.preventDefault(),p.stopPropagation(),m.hasAttribute("data-button-action")&&o(m),m.hasAttribute("data-button-audio-id")&&r(m)},a(m),m.addEventListener("click",m._balancyClickHandler),m.classList.add("balancy-button-prepared"),d++)}),i===document&&document.dispatchEvent(new CustomEvent("balancy-buttons-complete",{detail:{preparedCount:d,totalFound:l.length}}))}}}function De(n,e,t,a,r){return{prepareAllTexts(o=document){let i=o.querySelectorAll('[data-text-type="dynamic"]'),c=[];i.forEach(s=>{if(s.classList.contains("balancy-text-prepared"))return;s.classList.add("balancy-text-prepared");let l=s.id||"unknown-text",d=parseInt(s.getAttribute("data-info-type")||"0",10)||0,m=parseInt(s.getAttribute("data-index")||"0",10)||0,p=s.getAttribute("data-custom")||"",g=s.getAttribute("data-product-id")||"",b="";if(d===T.OfferPrice?(g=window.balancyViewOwner.productId,d=T.CustomPrice):d===T.OfferGroupPrice&&(b=window.balancyViewOwner.instanceId),d===T.TimeLeft){let w=function(){E.textContent=t(a())};var S=w;let E=s;setInterval(w,1e3),w();return}if(d===T.OwnerCustom){let E=s.getAttribute("data-text-format");E&&e(E,window.balancyViewOwner).then(w=>{s.textContent=w});return}if(d===T.OwnerLocalizedKey){let E=s.getAttribute("data-text-format");E&&e(E,window.balancyViewOwner).then(w=>r(s,w));return}let H=n(l,u.GetInfo,{type:d,productId:g,index:m,instanceId:b,custom:p}).then(E=>{try{let w=s.getAttribute("data-text-format");w&&e(w,E).then(ye=>{s.textContent=ye})}catch(w){console.error("Error formatting text:",w,"Result:",E)}});c.push(H)}),Promise.all(c).then(()=>{o===document&&document.dispatchEvent(new CustomEvent("balancy-text-complete"))})}}}function _(n){return n>=1e9?`${parseFloat((n/1e9).toFixed(1))}B`:n>=1e6?`${parseFloat((n/1e6).toFixed(1))}M`:n>=1e3?`${parseFloat((n/1e3).toFixed(1))}k`:n.toString()}function j(n){if(n&&!n.hasOwnProperty("unnyIdComponents"))return console.error("Item has no components, probably you need to increase depth when fetching item data: ",n),!1;let e=n?.components;if(!e)return!1;for(let t of e)if(t.$type==="SmartObjects.ItemComponent.Decay")return!0;return!1}function Fe(n){let e=n?.components;if(!e)return null;for(let t of e)if(t.$type==="SmartObjects.ItemComponent.Bundle")return t.reward;return null}function je(n,e=!1){let t=j(n.item),a=n.item.type===B.Currency,r;if(t){let o=n.count,i=Math.floor(o/3600),c=Math.floor(o%3600/60);r=`${i>0?`${i}h `:""}${c>0?`${c}m`:""}`}else{let o=e?_(n.count):n.count.toString();r=a?`${n.count}`:`x${o}`}return{text:r,isDuration:t,isCurrency:a}}function J(n){if(n>3600*24*365)return"oo";if(window.customFormatTime)return window.customFormatTime(n);let e=Math.floor(n/86400),t=Math.floor(n%86400/3600),a=Math.floor(n%3600/60),r=n%60;return e>0?t>0?`${e}d ${t}h`:`${e}d`:`${t.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}function ze(n,...e){return n.replace(/{(\d+)}/g,(t,a)=>e[a]!==void 0?e[a]:t)}function K(){let e=Math.floor(Date.now()/1e3)-window.balancySettings.launchTime;return window.balancySettings.secondsLeft-e}var Ue=["BALANCY/TIME_DAY","BALANCY/TIME_HOUR","BALANCY/TIME_MINUTE","BALANCY/TIME_SECOND","BALANCY/NUMBER_THOUSAND","BALANCY/NUMBER_MILLION","BALANCY/NUMBER_BILLION"],f={};function qe(n){f={day:n("BALANCY/TIME_DAY")||"d",hour:n("BALANCY/TIME_HOUR")||"h",minute:n("BALANCY/TIME_MINUTE")||"m",second:n("BALANCY/TIME_SECOND")||"s",thousand:n("BALANCY/NUMBER_THOUSAND")||"k",million:n("BALANCY/NUMBER_MILLION")||"M",billion:n("BALANCY/NUMBER_BILLION")||"B"}}function $e(n){return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g," ")}function Ne(n){return n>=1e9?`${parseFloat((n/1e9).toFixed(1))}${f.billion||"B"}`:n>=1e6?`${parseFloat((n/1e6).toFixed(1))}${f.million||"M"}`:n>=1e3?`${parseFloat((n/1e3).toFixed(1))}${f.thousand||"k"}`:n.toString()}function ft(n,e){switch(e){case P.Plain:return n.toString();case P.PlainSpaced:return $e(n);case P.WithPrefix:return`x${n}`;case P.WithPrefixSpaced:return`x${$e(n)}`;case P.Shortened:return Ne(n);case P.ShortenedWithPrefix:return`x${Ne(n)}`;default:return n.toString()}}function gt(n,e){let t=Math.floor(n/86400),a=Math.floor(n%86400/3600),r=Math.floor(n%3600/60),o=n%60;switch(e){case y.DaysHours:return t>0?`${t}:${a.toString().padStart(2,"0")}`:`${a}:00`;case y.HoursMinutes:return`${a}:${r.toString().padStart(2,"0")}`;case y.HoursMinutesSeconds:return`${a}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`;case y.MinutesSeconds:return`${r}:${o.toString().padStart(2,"0")}`;case y.Full:return t>0?`${t}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`:`${a}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`;case y.Auto:default:return t>0?`${t}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${a}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`}}function Ge(n,e,t){let a=Math.floor(n/86400),r=Math.floor(n%86400/3600),o=Math.floor(n%3600/60),i=n%60,c=[],s=(l,d)=>{t?l>0&&c.push(`${l}${d}`):c.push(`${l}${d}`)};switch(e){case y.DaysHours:s(a,f.day||"d"),s(r,f.hour||"h");break;case y.HoursMinutes:s(r,f.hour||"h"),s(o,f.minute||"m");break;case y.HoursMinutesSeconds:s(r,f.hour||"h"),s(o,f.minute||"m"),s(i,f.second||"s");break;case y.MinutesSeconds:s(o,f.minute||"m"),s(i,f.second||"s");break;case y.Full:s(a,f.day||"d"),s(r,f.hour||"h"),s(o,f.minute||"m"),s(i,f.second||"s");break;case y.Auto:default:a>0?(s(a,f.day||"d"),s(r,f.hour||"h")):r>0?(s(r,f.hour||"h"),s(o,f.minute||"m")):(s(o,f.minute||"m"),(!t||i>0)&&s(i,f.second||"s"));break}return c.join(" ")}function Ve(n,e={}){let t=e.currencyFormat??P.Plain,a=e.regularItemFormat??P.WithPrefix,r=e.timeFormat??O.LocalizedCompact,o=e.timePrecision??y.Auto,i=j(n.item),c=n.item.type===B.Currency,s;if(i){let l=n.count;r===O.Colon?s=gt(l,o):r===O.Localized?s=Ge(l,o,!1):s=Ge(l,o,!0)}else{let l=c?t:a;s=ft(n.count,l)}return{text:s,isDuration:i,isCurrency:c}}function We(n){function e(a){return a.charAt(0).toUpperCase()+a.slice(1)}async function t(a,r){let o=r.split("."),i=a;for(let c=0;c<o.length;c++){let s=o[c].trim();if(i&&i[s]!==void 0&&i[s]!==null)i=i[s];else{let l="unnyId"+e(s);if(i&&i[l]!==void 0)try{let d=await n(i[l],0);if(c+1<o.length){let m=o.slice(c+1).join(".");return await t(d,m)}else return d}catch(d){console.error(`Failed to get document for ID ${i[l]}:`,d);return}return}}return i}return async function(r,o){if(!r.includes("{")||!r.includes("}"))return r;let i=[],c=/\{([^}]+)\}/g,s;for(;(s=c.exec(r))!==null;)i.push({fullMatch:s[0],path:s[1].trim(),index:s.index});if(i.length===0)return r;let l=i.map(async p=>{let g=await t(o,p.path);return{placeholder:p.fullMatch,value:g!==void 0?String(g):p.fullMatch}}),d=await Promise.all(l),m=r;for(let p of d)m=m.replace(p.placeholder,p.value);return m}}function X(n,e){let t=document.createElement("style");t.type="text/css",t.textContent=`
|
|
5
5
|
@font-face {
|
|
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 C.OnOfferDeactivated:case C.OnOfferGroupDeactivated:break;case C.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 a=n.indexOf(e);a>-1&&n.splice(a,1)})},dispatchCustomMessage(e){n.forEach(t=>{try{t(e)}catch(a){console.error("Error in custom message subscriber:",a)}}),window.dispatchEvent(new CustomEvent("balancy-custom-message",{detail:e}))}}}function _e(n,e,t,a,r){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")),a||t())}i.forEach(l=>{document.addEventListener(l,s,{once:!0})})}(),(async()=>(await e(),r&&await r()))()}function yt(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(yt(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 a=t.querySelectorAll("audio[data-button-audio-id]"),r=0;for(let o of a){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"),r++}t===document&&document.dispatchEvent(new CustomEvent("balancy-audio-complete",{detail:{preparedCount:r,totalFound:a.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 a of this.elementObject.components)a.scriptInstance instanceof e&&t.push(a.scriptInstance);return t}getComponentInChildren(e){if(!this.elementObject)return null;let t=this.elementObject.element.querySelectorAll("[data-guid]");for(let a=0;a<t.length;a++){let r=t[a];r===this.elementObject.element||r.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(a){let r=a.getAttribute("data-guid");if(r){let i=Xe();a.setAttribute("data-guid",i),e.set(r,i)}let o=a.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,a,r){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=a||n.constructor.name||"Unknown",d=r?.getAttribute("data-script-id"),m=r?.id||r?.getAttribute("data-guid")||"Unknown",p=r?.tagName.toLowerCase()||"unknown",g=document.querySelector(`[data-guid="${c}"]`),b=g?.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: ${g?"YES":"NO"}${g?` <${g.tagName.toLowerCase()} id="${g.id}">`:""}`),console.error(` \u2192 Is prefab placeholder: ${b?"YES (data-prefab-id="+g?.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,t){return(a,r)=>vt(a,n,e,r,t)}function vt(n,e,t,a,r){if(!n||n===""||n==="null")return null;let o=t?x(n,t):null;if(!o&&t&&(o=x(n)),!o&&!t&&(o=x(n)),!o&&r&&(o=r.findElementInCachedPrefabs(n),o&&console.log(`[ElementResolver] Resolved "${n}" by data-guid in cached prefab template`),o||(o=r.getCachedPrefabRoot(n),o&&console.log(`[ElementResolver] Resolved "${n}" as cached prefab root (prefab ID reference)`))),!o)return a||console.error(`[ElementResolver] Element not found for GUID: "${n}"`),null;let i=e.getElementByGuid(n);return i||(i=e.createElementObjectFromElement(o,n)),i||(console.error(`[ElementResolver] Failed to create ElementObject for GUID: "${n}"`),null)}function nt(n,e){let t=n.querySelectorAll("[data-script-params]"),a=[];n.hasAttribute("data-script-params")&&a.push(n),a.push(...Array.from(t));for(let r of a)try{wt(r,e)}catch(o){console.error("[ParameterCloner] Error updating parameters:",o),console.error(" Script element:",r)}}function wt(n,e){let t=U(n);if(!t)return;let a=!1;for(let[r,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,a=!0}}if(a){let r=et(t);n.setAttribute("data-script-params",r)}}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.prefabsManagerRef=null;this.updateLoop=e=>{let t=(e-this.lastFrameTime)/1e3;if(this.lastFrameTime=e,!this.isPaused){for(let a of this.elementObjects.values())if(a.isActive){for(let r of a.components)if(!(!r.enabled||!r.scriptInstance.activeInHierarchy)){r.hasStarted||this.invokeStart(r);try{r.scriptInstance.update(t)}catch(o){console.error(`[ElementsManager] Error in update() for ${r.scriptId}:`,o)}}}}this.updateLoopRunning&&(this.animationFrameId=requestAnimationFrame(this.updateLoop))}}registerScript(e,t){Z.register(e,t)}setPrepareSpritesFunction(e){this.prepareSpritesFunction=e}setPrefabsManager(e){this.prefabsManagerRef=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 a=[];for(let r=0;r<e.children.length;r++){let o=e.children[r];o instanceof HTMLElement&&o.hasAttribute("data-script-id")&&a.push(o)}a.length>0&&this.processScriptDivs(e,a,t);for(let r=0;r<e.children.length;r++){let o=e.children[r];o instanceof HTMLElement&&this.scanElement(o,t)}}processScriptDivs(e,t,a){let r=Q(e),o=this.elementObjects.get(r);o||(o=new I(e,r),this.elementObjects.set(r,o));for(let i of t)this.createComponent(o,i,a)}createComponent(e,t,a){let r=t.getAttribute("data-script-id");if(!r)return console.error("[ElementsManager] Script div missing data-script-id",t),null;let o=Z.get(r);if(!o)return null;Q(t);try{let i=new o,c={elementObject:e,scriptElement:t,scriptInstance:i,scriptId:r,enabled:!0,hasStarted:!1};i.elementObject=e,i.scriptElement=t,e.addComponent(c);let s=U(t);if(s){let l=tt(this,a,this.prefabsManagerRef||void 0),d=o.name||r;Qe(i,s,l,d,t)}return c}catch(i){return console.error(`[ElementsManager] Error creating component "${r}":`,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 a=e.scriptInstance[t];typeof a=="function"&&a.call(e.scriptInstance)}catch(a){console.error(`[ElementsManager] Error in ${t}() for ${e.scriptId}:`,a)}}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 a=new I(e,t);return this.elementObjects.set(t,a),a}getOrCreateElementObject(e){if(this.elementObjects.has(e))return this.elementObjects.get(e);let t=x(e);if(!t)return null;let a=new I(t,e);this.elementObjects.set(e,a);let r=[];for(let o=0;o<t.children.length;o++){let i=t.children[o];i instanceof HTMLElement&&i.hasAttribute("data-script-id")&&r.push(i)}if(r.length>0)for(let o of r)this.createComponent(a,o,t);return a}setActive(e,t){let a=e.getAttribute("data-guid");if(!a){console.error("[ElementsManager] Element has no GUID:",e);return}let r=this.elementObjects.get(a);if(!r){console.warn("[ElementsManager] Element not managed:",e);return}if(r.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";r.isActive=t;let o=this.getComponentsInElementAndChildren(e);for(let i of o)i.scriptInstance.updateActiveState()}getComponentsInElementAndChildren(e){let t=[],a=e.getAttribute("data-guid");if(a){let o=this.elementObjects.get(a);o&&t.push(...o.components)}let r=e.querySelectorAll("[data-guid]");for(let o of r){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 r=this.getComponentsInElementAndChildren(e);for(let i of r)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 a=Ze(t);nt(t,a),this.scanElement(t,t);let r=this.getComponentsInElementAndChildren(t);for(let o of r)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 a=e.children,r=t.children;for(let o=0;o<a.length&&o<r.length;o++)a[o]instanceof HTMLElement&&r[o]instanceof HTMLElement&&this.copyInlineStyles(a[o],r[o])}cleanup(){this.stopUpdateLoop(),this.elementObjects.clear(),this.initialized=!1}},h=new ee;var I=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 a of this.components)a.scriptInstance instanceof e&&t.push(a.scriptInstance);return t}getEnabledComponents(){return this.components.filter(e=>e.enabled&&e.scriptInstance.activeInHierarchy)}instantiate(){let t=h.instantiate(this.element).getAttribute("data-guid");if(!t)throw new Error("[ElementObject] Cloned element has no GUID");let a=h.getElementByGuid(t);if(!a)throw new Error("[ElementObject] Cloned element not found in ElementsManager");return a}};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 a=this.prefabCache.get(e);console.log(`[PrefabsManager] Using cached prefab: ${e}`);let r=a.cloneNode(!0);return this.copyInlineStyles(a,r),r}if(this.pendingLoads.has(e)){if(console.log(`[PrefabsManager] Waiting for pending load: ${e}`),await this.pendingLoads.get(e),this.prefabCache.has(e)){let a=this.prefabCache.get(e),r=a.cloneNode(!0);return this.copyInlineStyles(a,r),r}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 a=await this.loaderFunction(e);if(!a)return console.error(`[PrefabsManager] Failed to load prefab: ${e}`),null;this.prefabCache.set(e,a),console.log(`[PrefabsManager] Prefab cached: ${e}`);let r=a.cloneNode(!0);return this.copyInlineStyles(a,r),r}catch(a){return console.error(`[PrefabsManager] Error loading prefab "${e}":`,a),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 a=e.children,r=t.children;for(let o=0;o<a.length&&o<r.length;o++)a[o]instanceof HTMLElement&&r[o]instanceof HTMLElement&&this.copyInlineStyles(a[o],r[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 a=e.querySelectorAll("[data-prefab-id]");console.log(`[PrefabsManager] Found ${a.length} placeholders in scope`);for(let r of a)r.hasAttribute("data-prefab-id")&&await this.processPlaceholder(r);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 a=await this.load(t);if(!a){console.error(`[PrefabsManager] Failed to load prefab for placeholder: ${t}`);return}let r=e.getAttribute("data-guid");console.log(`[PrefabsManager] Processing placeholder for ${t}:`),console.log(` - Placeholder: <${e.tagName.toLowerCase()} id="${e.id}">`),console.log(` - Placeholder GUID: ${r}`),console.log(` - Prefab root: <${a.tagName.toLowerCase()} id="${a.id}">`),console.log(` - Children to move: ${a.children.length}`),this.validatePrefabReferences(a,t);let o=0;for(;a.firstChild;)e.appendChild(a.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&&a.className&&(e.className=a.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(a){console.error(`[PrefabsManager] Error processing placeholder for "${t}":`,a)}}clearCache(){this.prefabCache.clear()}async preload(e){console.log(`[PrefabsManager] Preloading ${e.length} prefabs...`);let t=e.map(a=>this.load(a));await Promise.all(t),console.log("[PrefabsManager] Preload complete")}getCacheStats(){return{size:this.prefabCache.size,prefabIds:Array.from(this.prefabCache.keys())}}findElementInCachedPrefabs(e){for(let[t,a]of this.prefabCache.entries()){if(a.getAttribute("data-guid")===e)return console.log(`[PrefabsManager] Found GUID "${e}" as root of cached prefab ${t}`),a;let r=a.querySelector(`[data-guid="${e}"]`);if(r)return console.log(`[PrefabsManager] Found GUID "${e}" inside cached prefab ${t}`),r}return null}getCachedPrefabRoot(e){let t=this.prefabCache.get(e);return t?(console.log(`[PrefabsManager] Found cached prefab root by prefab ID: ${e}`),t):null}validatePrefabReferences(e,t){let a=e.querySelectorAll("[data-guid]"),r=new Set,o=e.getAttribute("data-guid");o&&r.add(o),a.forEach(s=>{let l=s.getAttribute("data-guid");l&&r.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,'"'),g=JSON.parse(p);for(let[b,H]of Object.entries(g))if(H.type==="element"){let S=String(H.value);S&&S!==""&&S!=="null"&&!r.has(S)&&(this.findElementInCachedPrefabs(S)||c.push({scriptId:d,elementId:m,param:b,guid:S}))}}catch{}}),c.length>0&&(console.warn(`[PrefabsManager] 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(" Tip: Re-save the prefab in the editor to fix stale references"))}},M=new te;h.instantiatePrefab=async function(n){let e=await M.load(n);return e?(console.info("INSTY +> ",e),this.instantiate(e)):null};h.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 a=this.getElementByGuid(t);return a||(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,a=e.children;for(let r=0;r<t.length&&r<a.length;r++)t[r]instanceof HTMLElement&&a[r]instanceof HTMLElement&&ne(t[r],a[r])}var V={},le={},it=0,st=new D,Et=new $,lt=new N,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),v=Te(st,dt,ct,ut,le,ce),Mt=we(ie),A=Me(v),{getActiveOffers:It,getActiveGroupOffers:St,canBuyGroupOffer:de,buyGroupOffer:Lt,buyOffer:At,buyShopSlot:Ct,getRewardedAdsWatchedForStoreItem:Ot,haveEnoughResources:xt}=Ie(v,A.getSystemProfileValue,A.getDocumentValue),R=Se(v),re=Le(v),oe=Ae(v,A.getDocumentValue),L=Ce(v),se=n=>lt.get(n,v,u.GetLocalization),k=n=>Et.get(n,v,u.GetImageUrl),Bt=n=>Pt.get(n,v,u.GetFileLocation),rt=n=>Tt.get(n,v,u.GetPrefabContent),mt=qe(A.getDocumentValue),me=Oe(se),pe=xe(k),Rt=Be(k,J);h.setPrepareSpritesFunction(pe.prepareAllSprites);var pt=Re(v,de,k),kt=ke(v,mt,Y,_,me.setLocalizedText),Ht=Ke(k),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 M.processPrefabPlaceholdersInScope(n),await me.localizeAllElements(n),await Rt.prepareAllFonts(n),await pe.prepareAllSprites(n),await pt.prepareAllButtons(n),await kt.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(a=>{e.disabled=!a})})};ue=We(Dt);var ot=!1,at=()=>dt(null,u.BalancyIsReady,{id:"none"});Object.assign(V,{NotificationType:C,PriceType:ge,ItemType:B,TaskStatus:ye,RequestAction:u,BuyButtonState:be,OfferGroupType:he,NumberDisplayFormat:P,TimeDisplayFormat:O,TimePrecision:y,postMessage:ce,_receiveMessageFromUnity:Mt,handleResponse:ie,sendRequest:v,batchManager:st,getProfileValue:A.getProfileValue,getSystemProfileValue:A.getSystemProfileValue,getDocumentValue:A.getDocumentValue,getActiveOffers:It,getActiveGroupOffers:St,canBuyGroupOffer:de,buyGroupOffer:Lt,buyOffer:At,buyShopSlot:Ct,getRewardedAdsWatchedForStoreItem:Ot,haveEnoughResources:xt,getTasks:R.getTasks,activateTasks:R.activateTasks,deactivateTasks:R.deactivateTasks,restoreFailedTask:R.restoreFailedTask,claimTaskReward:R.claimTaskReward,getInventoryItemsCount:re.getInventoryItemsCount,addInventoryItems:re.addInventoryItems,removeInventoryItems:re.removeInventoryItems,getBattlePassConfig:oe.getBattlePassConfig,getBattlePassProgress:oe.getBattlePassProgress,claimBattlePassReward:oe.claimBattlePassReward,getCustomEventInfo:L.getCustomEventInfo,setCustomEventInfo:L.setCustomEventInfo,stopEventManually:L.stopEventManually,watchRewardedAd:L.watchRewardedAd,getProductInfo:L.getProductInfo,closeView:L.closeView,sendCustomMessage:L.sendCustomMessage,getLocalizedText:se,getImageUrl:k,getFileLocation:Bt,getPrefabContent:rt,setLocalizedText:me.setLocalizedText,setImage:pe.setImage,formatTime:Y,formatString:Fe,formatItemsCount:Ge,formatItemCount:Ue,shortenCount:W,itemHasDecayEffect:j,itemGetBundleReward:Ne,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:I,ElementsManager:h,PrefabsManager:M,instantiatePrefabById:n=>h.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(r=>se(r))),ze(r=>lt.getCached(r)),console.info("[Balancy] Mandatory localization keys preloaded"),M.setUIProcessor(async r=>{await q(r)}),M.setLoader(async r=>{try{if(n.has(r)){console.info(`[Balancy] Using cached prefab: ${r}`);let d=n.get(r),m=d.cloneNode(!0);return ne(d,m),m}console.info(`[Balancy] Loading prefab for the first time: ${r}`);let o=await rt(r);if(console.info(`[Balancy] Received HTML content (length: ${o?.length||0})`),!o)return console.error(`[Balancy] No HTML content returned for prefab: ${r}`),null;let c=new DOMParser().parseFromString(o,"text/html"),s=c.body.firstElementChild;if(!s)return console.error(`[Balancy] No root element found in prefab body for: ${r}`),null;let l=c.head.querySelectorAll("style");return l.length>0&&l.forEach(d=>{let p=(d.textContent||"").replace(/\*\s*\{[^}]*\}/g,"").replace(/body\s*\{[^}]*\}/g,"").replace(/html\s*\{[^}]*\}/g,"");if(p=p.trim(),p){let g=document.createElement("style");g.textContent=p,g.setAttribute("data-prefab-id",r),document.head.appendChild(g)}else console.warn(`[Balancy] No styles left after filtering for prefab: ${r}`)}),console.info(`[Balancy] Processing UI elements for prefab ${r}...`),await q(s),console.info(`[Balancy] UI elements processed for prefab ${r}`),n.set(r,s),console.info("[Balancy] Prefab loaded and cached successfully:"),console.info(` - Root element: <${s.tagName.toLowerCase()} id="${s.id}">`),console.info(` - Children count: ${s.children.length}`),console.info(" - Full element:",s),s}catch(o){return console.error(`[Balancy] Error in prefab loader for "${r}":`,o),null}}),await M.processPrefabPlaceholders(),h.setPrefabsManager(M);let t=new Set,a=document.querySelectorAll("[data-script-params]");for(let r of Array.from(a)){let o=r.getAttribute("data-script-params");if(o)try{let i=o.replace(/'/g,'"'),c=JSON.parse(i);for(let[,s]of Object.entries(c))if(s.type==="element"){let l=String(s.value);l&&l!==""&&l!=="null"&&(document.querySelector(`[data-guid="${l}"]`)||t.add(l))}}catch{}}t.size>0&&(console.log(`[Balancy] Preloading ${t.size} prefab(s) referenced by script parameters:`,Array.from(t)),await M.preload(Array.from(t))),h.initialize();try{let r=document.body.querySelector("[data-guid]");if(r){let o=r.getAttribute("data-guid");console.info(`[Balancy] Found root element with GUID: ${o}`);let i=h.getElementByGuid(o);if(i){let c=i.components;if(c.length>0){console.info(`[Balancy] Root element has ${c.length} component(s)`);let s=c[0].scriptInstance;if(typeof s.init=="function"){console.info("[Balancy] Calling init() on root script with balancyViewOwner");let l=window.balancyViewOwner;l?s.init(l):(console.warn("[Balancy] window.balancyViewOwner is not defined, calling init() without arguments"),s.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(r){console.error("[Balancy] Error auto-initializing root script:",r)}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 Ye(n,e){let t=(e??document).querySelector(`[data-id=${n}]`);return t instanceof HTMLElement?t:null}function _e(n){return function(t){if(!(!t||typeof t!="object")){switch(console.log(">>>notificationReceived ",t),t.type){case C.OnOfferDeactivated:case C.OnOfferGroupDeactivated:break;case C.OnOfferGroupWasPurchased:n();break}window.dispatchEvent(new CustomEvent("balancy-notification",{detail:t}))}}}function Je(){let n=[];return{subscribeToCustomMessages(e){return typeof e!="function"?(console.error("subscribeToCustomMessages: callback must be a function"),()=>{}):(n.push(e),function(){let a=n.indexOf(e);a>-1&&n.splice(a,1)})},dispatchCustomMessage(e){n.forEach(t=>{try{t(e)}catch(a){console.error("Error in custom message subscriber:",a)}}),window.dispatchEvent(new CustomEvent("balancy-custom-message",{detail:e}))}}}function Ke(n,e,t,a,r){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")),a||t())}i.forEach(l=>{document.addEventListener(l,s,{once:!0})})}(),(async()=>(await e(),r&&await r()))()}function yt(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 Xe(n){let e=n;for(;e&&e!==document.body&&e!==document.documentElement;){if(yt(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)||Xe(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){!Xe(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 Z(){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 Ze(n){async function e(t=document){let a=t.querySelectorAll("audio[data-button-audio-id]"),r=0;for(let o of a){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"),r++}t===document&&document.dispatchEvent(new CustomEvent("balancy-audio-complete",{detail:{preparedCount:r,totalFound:a.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 a of this.elementObject.components)a.scriptInstance instanceof e&&t.push(a.scriptInstance);return t}getComponentInChildren(e){if(!this.elementObject)return null;let t=this.elementObject.element.querySelectorAll("[data-guid]");for(let a=0;a<t.length;a++){let r=t[a];r===this.elementObject.element||r.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 Q=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()}},ee=new Q;function Qe(){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 U(n){let e=new Map;function t(a){let r=a.getAttribute("data-guid");if(r){let i=Qe();a.setAttribute("data-guid",i),e.set(r,i)}let o=a.children;for(let i=0;i<o.length;i++){let c=o[i];c instanceof HTMLElement&&t(c)}}return t(n),e}function te(n){let e=n.getAttribute("data-guid");return e||(e=Qe(),n.setAttribute("data-guid",e)),e}function x(n,e){return(e||document.body).querySelector(`[data-guid="${n}"]`)}function q(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 et(n,e,t,a,r){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=a||n.constructor.name||"Unknown",d=r?.getAttribute("data-script-id"),m=r?.id||r?.getAttribute("data-guid")||"Unknown",p=r?.tagName.toLowerCase()||"unknown",g=document.querySelector(`[data-guid="${c}"]`),b=g?.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: ${g?"YES":"NO"}${g?` <${g.tagName.toLowerCase()} id="${g.id}">`:""}`),console.error(` \u2192 Is prefab placeholder: ${b?"YES (data-prefab-id="+g?.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 tt(n){return JSON.stringify(n).replace(/"/g,"'")}function nt(n,e,t){return(a,r)=>vt(a,n,e,r,t)}function vt(n,e,t,a,r){if(!n||n===""||n==="null")return null;let o=t?x(n,t):null;if(!o&&t&&(o=x(n)),!o&&!t&&(o=x(n)),!o&&r&&(o=r.findElementInCachedPrefabs(n),o&&console.log(`[ElementResolver] Resolved "${n}" by data-guid in cached prefab template`),o||(o=r.getCachedPrefabRoot(n),o&&console.log(`[ElementResolver] Resolved "${n}" as cached prefab root (prefab ID reference)`))),!o)return a||console.error(`[ElementResolver] Element not found for GUID: "${n}"`),null;let i=e.getElementByGuid(n);return i||(i=e.createElementObjectFromElement(o,n)),i||(console.error(`[ElementResolver] Failed to create ElementObject for GUID: "${n}"`),null)}function V(n,e){let t=n.querySelectorAll("[data-script-params]"),a=[];n.hasAttribute("data-script-params")&&a.push(n),a.push(...Array.from(t));for(let r of a)try{wt(r,e)}catch(o){console.error("[ParameterCloner] Error updating parameters:",o),console.error(" Script element:",r)}}function wt(n,e){let t=q(n);if(!t)return;let a=!1;for(let[r,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,a=!0}}if(a){let r=tt(t);n.setAttribute("data-script-params",r)}}var ne=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.prefabsManagerRef=null;this.updateLoop=e=>{let t=(e-this.lastFrameTime)/1e3;if(this.lastFrameTime=e,!this.isPaused){for(let a of this.elementObjects.values())if(a.isActive){for(let r of a.components)if(!(!r.enabled||!r.scriptInstance.activeInHierarchy)){r.hasStarted||this.invokeStart(r);try{r.scriptInstance.update(t)}catch(o){console.error(`[ElementsManager] Error in update() for ${r.scriptId}:`,o)}}}}this.updateLoopRunning&&(this.animationFrameId=requestAnimationFrame(this.updateLoop))}}registerScript(e,t){ee.register(e,t)}setPrepareSpritesFunction(e){this.prepareSpritesFunction=e}setPrefabsManager(e){this.prefabsManagerRef=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 a=[];for(let r=0;r<e.children.length;r++){let o=e.children[r];o instanceof HTMLElement&&o.hasAttribute("data-script-id")&&a.push(o)}a.length>0&&this.processScriptDivs(e,a,t);for(let r=0;r<e.children.length;r++){let o=e.children[r];o instanceof HTMLElement&&this.scanElement(o,t)}}processScriptDivs(e,t,a){let r=te(e),o=this.elementObjects.get(r);o||(o=new I(e,r),this.elementObjects.set(r,o));for(let i of t)this.createComponent(o,i,a)}createComponent(e,t,a){let r=t.getAttribute("data-script-id");if(!r)return console.error("[ElementsManager] Script div missing data-script-id",t),null;let o=ee.get(r);if(!o)return null;te(t);try{let i=new o,c={elementObject:e,scriptElement:t,scriptInstance:i,scriptId:r,enabled:!0,hasStarted:!1};i.elementObject=e,i.scriptElement=t,e.addComponent(c);let s=q(t);if(s){let l=nt(this,a,this.prefabsManagerRef||void 0),d=o.name||r;et(i,s,l,d,t)}return c}catch(i){return console.error(`[ElementsManager] Error creating component "${r}":`,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 a=e.scriptInstance[t];typeof a=="function"&&a.call(e.scriptInstance)}catch(a){console.error(`[ElementsManager] Error in ${t}() for ${e.scriptId}:`,a)}}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 a=new I(e,t);return this.elementObjects.set(t,a),a}getOrCreateElementObject(e){if(this.elementObjects.has(e))return this.elementObjects.get(e);let t=x(e);if(!t)return null;let a=new I(t,e);this.elementObjects.set(e,a);let r=[];for(let o=0;o<t.children.length;o++){let i=t.children[o];i instanceof HTMLElement&&i.hasAttribute("data-script-id")&&r.push(i)}if(r.length>0)for(let o of r)this.createComponent(a,o,t);return a}setActive(e,t){let a=e.getAttribute("data-guid");if(!a){console.error("[ElementsManager] Element has no GUID:",e);return}let r=this.elementObjects.get(a);if(!r){console.warn("[ElementsManager] Element not managed:",e);return}if(r.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";r.isActive=t;let o=this.getComponentsInElementAndChildren(e);for(let i of o)i.scriptInstance.updateActiveState()}getComponentsInElementAndChildren(e){let t=[],a=e.getAttribute("data-guid");if(a){let o=this.elementObjects.get(a);o&&t.push(...o.components)}let r=e.querySelectorAll("[data-guid]");for(let o of r){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 r=this.getComponentsInElementAndChildren(e);for(let i of r)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 a=U(t);V(t,a),this.scanElement(t,t);let r=this.getComponentsInElementAndChildren(t);for(let o of r)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 a=e.children,r=t.children;for(let o=0;o<a.length&&o<r.length;o++)a[o]instanceof HTMLElement&&r[o]instanceof HTMLElement&&this.copyInlineStyles(a[o],r[o])}cleanup(){this.stopUpdateLoop(),this.elementObjects.clear(),this.initialized=!1}},h=new ne;var I=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 a of this.components)a.scriptInstance instanceof e&&t.push(a.scriptInstance);return t}getEnabledComponents(){return this.components.filter(e=>e.enabled&&e.scriptInstance.activeInHierarchy)}instantiate(){let t=h.instantiate(this.element).getAttribute("data-guid");if(!t)throw new Error("[ElementObject] Cloned element has no GUID");let a=h.getElementByGuid(t);if(!a)throw new Error("[ElementObject] Cloned element not found in ElementsManager");return a}};var re=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 a=this.prefabCache.get(e);console.log(`[PrefabsManager] Using cached prefab: ${e}`);let r=a.cloneNode(!0);return this.copyInlineStyles(a,r),r}if(this.pendingLoads.has(e)){if(console.log(`[PrefabsManager] Waiting for pending load: ${e}`),await this.pendingLoads.get(e),this.prefabCache.has(e)){let a=this.prefabCache.get(e),r=a.cloneNode(!0);return this.copyInlineStyles(a,r),r}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 a=await this.loaderFunction(e);if(!a)return console.error(`[PrefabsManager] Failed to load prefab: ${e}`),null;this.prefabCache.set(e,a),console.log(`[PrefabsManager] Prefab cached: ${e}`);let r=a.cloneNode(!0);return this.copyInlineStyles(a,r),r}catch(a){return console.error(`[PrefabsManager] Error loading prefab "${e}":`,a),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 a=e.children,r=t.children;for(let o=0;o<a.length&&o<r.length;o++)a[o]instanceof HTMLElement&&r[o]instanceof HTMLElement&&this.copyInlineStyles(a[o],r[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 a=e.querySelectorAll("[data-prefab-id]");console.log(`[PrefabsManager] Found ${a.length} placeholders in scope`);for(let r of a)r.hasAttribute("data-prefab-id")&&await this.processPlaceholder(r);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 a=await this.load(t);if(!a){console.error(`[PrefabsManager] Failed to load prefab for placeholder: ${t}`);return}let r=e.getAttribute("data-guid");console.log(`[PrefabsManager] Processing placeholder for ${t}:`),console.log(` - Placeholder: <${e.tagName.toLowerCase()} id="${e.id}">`),console.log(` - Placeholder GUID: ${r}`),console.log(` - Prefab root: <${a.tagName.toLowerCase()} id="${a.id}">`),console.log(` - Children to move: ${a.children.length}`);let o=U(a);V(a,o),console.log(` - Regenerated ${o.size} GUIDs for unique instance`),this.validatePrefabReferences(a,t);let i=0;for(;a.firstChild;)e.appendChild(a.firstChild),i++;console.log(` - Moved ${i} children to placeholder`),console.log(` - Placeholder now has ${e.children.length} children`),e.removeAttribute("data-prefab-id"),!e.className&&a.className&&(e.className=a.className);let c=e.querySelectorAll(".balancy-button-prepared");c.forEach(s=>{s.classList.remove("balancy-button-prepared")}),c.length>0&&console.log(` - Removed button markers from ${c.length} cloned buttons`),this.uiProcessor&&(console.log(" - Processing UI elements in placeholder..."),await this.uiProcessor(e),console.log(" - UI elements processed for placeholder"))}catch(a){console.error(`[PrefabsManager] Error processing placeholder for "${t}":`,a)}}clearCache(){this.prefabCache.clear()}async preload(e){console.log(`[PrefabsManager] Preloading ${e.length} prefabs...`);let t=e.map(a=>this.load(a));await Promise.all(t),console.log("[PrefabsManager] Preload complete")}getCacheStats(){return{size:this.prefabCache.size,prefabIds:Array.from(this.prefabCache.keys())}}findElementInCachedPrefabs(e){for(let[t,a]of this.prefabCache.entries()){if(a.getAttribute("data-guid")===e)return console.log(`[PrefabsManager] Found GUID "${e}" as root of cached prefab ${t}`),a;let r=a.querySelector(`[data-guid="${e}"]`);if(r)return console.log(`[PrefabsManager] Found GUID "${e}" inside cached prefab ${t}`),r}return null}getCachedPrefabRoot(e){let t=this.prefabCache.get(e);return t?(console.log(`[PrefabsManager] Found cached prefab root by prefab ID: ${e}`),t):null}validatePrefabReferences(e,t){let a=e.querySelectorAll("[data-guid]"),r=new Set,o=e.getAttribute("data-guid");o&&r.add(o),a.forEach(s=>{let l=s.getAttribute("data-guid");l&&r.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,'"'),g=JSON.parse(p);for(let[b,H]of Object.entries(g))if(H.type==="element"){let S=String(H.value);S&&S!==""&&S!=="null"&&!r.has(S)&&(this.findElementInCachedPrefabs(S)||c.push({scriptId:d,elementId:m,param:b,guid:S}))}}catch{}}),c.length>0&&(console.warn(`[PrefabsManager] 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(" Tip: Re-save the prefab in the editor to fix stale references"))}},M=new re;h.instantiatePrefab=async function(n){let e=await M.load(n);return e?(console.info("INSTY +> ",e),this.instantiate(e)):null};h.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 a=this.getElementByGuid(t);return a||(console.error("[ElementsManager] ElementObject not found after instantiation"),null)};function oe(n,e){n.style.cssText&&(e.style.cssText=n.style.cssText);let t=n.children,a=e.children;for(let r=0;r<t.length&&r<a.length;r++)t[r]instanceof HTMLElement&&a[r]instanceof HTMLElement&&oe(t[r],a[r])}var Y={},ue={},it=0,st=new D,Et=new $,lt=new N,Pt=new G,Tt=new F,ct=()=>it,ut=()=>{it++},de=Ee(),se=Je(),me=()=>{},le=Te(ue,n=>me(n),se.dispatchCustomMessage),dt=Me(ct,ut,ue,de),v=Ie(st,dt,ct,ut,ue,de),Mt=Pe(le),A=Se(v),{getActiveOffers:It,getActiveGroupOffers:St,canBuyGroupOffer:pe,buyGroupOffer:Lt,buyOffer:At,buyShopSlot:Ct,getRewardedAdsWatchedForStoreItem:Ot,haveEnoughResources:xt}=Le(v,A.getSystemProfileValue,A.getDocumentValue),R=Ae(v),ae=Ce(v),ie=Oe(v,A.getDocumentValue),L=xe(v),ce=n=>lt.get(n,v,u.GetLocalization),k=n=>Et.get(n,v,u.GetImageUrl),Bt=n=>Pt.get(n,v,u.GetFileLocation),rt=n=>Tt.get(n,v,u.GetPrefabContent),mt=We(A.getDocumentValue),fe=Be(ce),ge=Re(k),Rt=ke(k,X);h.setPrepareSpritesFunction(ge.prepareAllSprites);var pt=He(v,pe,k),kt=De(v,mt,J,K,fe.setLocalizedText),Ht=Ze(k),W=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 M.processPrefabPlaceholdersInScope(n),await fe.localizeAllElements(n),await Rt.prepareAllFonts(n),await ge.prepareAllSprites(n),await pt.prepareAllButtons(n),await kt.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;pe(t).then(a=>{e.disabled=!a})})};me=_e(Dt);var ot=!1,at=()=>dt(null,u.BalancyIsReady,{id:"none"});Object.assign(Y,{NotificationType:C,PriceType:be,ItemType:B,TaskStatus:he,RequestAction:u,BuyButtonState:ve,OfferGroupType:we,NumberDisplayFormat:P,TimeDisplayFormat:O,TimePrecision:y,postMessage:de,_receiveMessageFromUnity:Mt,handleResponse:le,sendRequest:v,batchManager:st,getProfileValue:A.getProfileValue,getSystemProfileValue:A.getSystemProfileValue,getDocumentValue:A.getDocumentValue,getActiveOffers:It,getActiveGroupOffers:St,canBuyGroupOffer:pe,buyGroupOffer:Lt,buyOffer:At,buyShopSlot:Ct,getRewardedAdsWatchedForStoreItem:Ot,haveEnoughResources:xt,getTasks:R.getTasks,activateTasks:R.activateTasks,deactivateTasks:R.deactivateTasks,restoreFailedTask:R.restoreFailedTask,claimTaskReward:R.claimTaskReward,getInventoryItemsCount:ae.getInventoryItemsCount,addInventoryItems:ae.addInventoryItems,removeInventoryItems:ae.removeInventoryItems,getBattlePassConfig:ie.getBattlePassConfig,getBattlePassProgress:ie.getBattlePassProgress,claimBattlePassReward:ie.claimBattlePassReward,getCustomEventInfo:L.getCustomEventInfo,setCustomEventInfo:L.setCustomEventInfo,stopEventManually:L.stopEventManually,watchRewardedAd:L.watchRewardedAd,getProductInfo:L.getProductInfo,closeView:L.closeView,sendCustomMessage:L.sendCustomMessage,getLocalizedText:ce,getImageUrl:k,getFileLocation:Bt,getPrefabContent:rt,setLocalizedText:fe.setLocalizedText,setImage:ge.setImage,formatTime:J,formatString:ze,formatItemsCount:je,formatItemCount:Ve,shortenCount:_,itemHasDecayEffect:j,itemGetBundleReward:Fe,getTimeLeft:K,formatDataTemplate:mt,injectFontFace:X,findDomElement:Ye,balancyButtonClicked:pt.balancyButtonClicked,notificationReceived:me,subscribeToCustomMessages:se.subscribeToCustomMessages,dispatchCustomMessage:se.dispatchCustomMessage,sendIsReady:at,delayIsReady:()=>{ot=!0},ElementBehaviour:z,ElementObject:I,ElementsManager:h,PrefabsManager:M,instantiatePrefabById:n=>h.instantiatePrefabById(n),prepareAllUIElements:W,initResponseHandler:()=>{if(Y._responseHandlerInitialized)return;Y._responseHandlerInitialized=!0;let n=new Map;Ke(le,()=>W(),at,ot,async()=>{try{console.info("[Balancy] Preloading mandatory localization keys..."),await Promise.all(Ue.map(r=>ce(r))),qe(r=>lt.getCached(r)),console.info("[Balancy] Mandatory localization keys preloaded"),M.setUIProcessor(async r=>{await W(r)}),M.setLoader(async r=>{try{if(n.has(r)){console.info(`[Balancy] Using cached prefab: ${r}`);let d=n.get(r),m=d.cloneNode(!0);return oe(d,m),m}console.info(`[Balancy] Loading prefab for the first time: ${r}`);let o=await rt(r);if(console.info(`[Balancy] Received HTML content (length: ${o?.length||0})`),!o)return console.error(`[Balancy] No HTML content returned for prefab: ${r}`),null;let c=new DOMParser().parseFromString(o,"text/html"),s=c.body.firstElementChild;if(!s)return console.error(`[Balancy] No root element found in prefab body for: ${r}`),null;let l=c.head.querySelectorAll("style");return l.length>0&&l.forEach(d=>{let p=(d.textContent||"").replace(/\*\s*\{[^}]*\}/g,"").replace(/body\s*\{[^}]*\}/g,"").replace(/html\s*\{[^}]*\}/g,"");if(p=p.trim(),p){let g=document.createElement("style");g.textContent=p,g.setAttribute("data-prefab-id",r),document.head.appendChild(g)}else console.warn(`[Balancy] No styles left after filtering for prefab: ${r}`)}),console.info(`[Balancy] Processing UI elements for prefab ${r}...`),await W(s),console.info(`[Balancy] UI elements processed for prefab ${r}`),n.set(r,s),console.info("[Balancy] Prefab loaded and cached successfully:"),console.info(` - Root element: <${s.tagName.toLowerCase()} id="${s.id}">`),console.info(` - Children count: ${s.children.length}`),console.info(" - Full element:",s),s}catch(o){return console.error(`[Balancy] Error in prefab loader for "${r}":`,o),null}}),await M.processPrefabPlaceholders(),h.setPrefabsManager(M);let t=new Set,a=document.querySelectorAll("[data-script-params]");for(let r of Array.from(a)){let o=r.getAttribute("data-script-params");if(o)try{let i=o.replace(/'/g,'"'),c=JSON.parse(i);for(let[,s]of Object.entries(c))if(s.type==="element"){let l=String(s.value);l&&l!==""&&l!=="null"&&(document.querySelector(`[data-guid="${l}"]`)||t.add(l))}}catch{}}t.size>0&&(console.log(`[Balancy] Preloading ${t.size} prefab(s) referenced by script parameters:`,Array.from(t)),await M.preload(Array.from(t))),h.initialize();try{let r=document.body.querySelector("[data-guid]");if(r){let o=r.getAttribute("data-guid");console.info(`[Balancy] Found root element with GUID: ${o}`);let i=h.getElementByGuid(o);if(i){let c=i.components;if(c.length>0){console.info(`[Balancy] Root element has ${c.length} component(s)`);let s=c[0].scriptInstance;if(typeof s.init=="function"){console.info("[Balancy] Calling init() on root script with balancyViewOwner");let l=window.balancyViewOwner;l?s.init(l):(console.warn("[Balancy] window.balancyViewOwner is not defined, calling init() without arguments"),s.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(r){console.error("[Balancy] Error auto-initializing root script:",r)}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",Z):Z());typeof window<"u"&&(window.balancy=Y);console.log("\u{1F389} [BRIDGE] Balancy WebView Bridge loaded successfully!");return balancy;})();
|