@balancy/bridge 1.3.3 → 1.3.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,GetShopInfo:105,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},O={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},C={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,r,o,a,i,c,s){let l=e.toString(),d={type:"request",sender:t,id:l,action:r,params:o};return this.pendingBatch.set(l,{requestData:d,resolve:a,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 r=[];this.pendingBatch.forEach((a,i)=>{r.push(a.requestData),e[i]={resolve:a.resolve,reject:a.reject,timestamp:Date.now(),message:a.requestData}}),console.log(`[BatchManager] Sending batch with ${this.pendingBatch.size} requests`),t(JSON.stringify({type:"batch",requests:r})),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){n(t)}}function Te(n,e,t){return function(o){try{let a=JSON.parse(o);if(a.type==="response"){let i=n[a.id];i&&(a.error?i.reject(new Error(a.error+" : "+JSON.stringify(i.message))):i.resolve(a.result),delete n[a.id])}else if(a.type==="batch-response")a.responses&&Array.isArray(a.responses)&&a.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(a.type==="notification"){let i=a.data?JSON.parse(a.data):null;e(i)}else a.type==="custom-message"&&t(a.data)}catch(a){console.error("Error handling response:",a)}}}function Me(n,e,t,r){return function(a,i,c={}){return new Promise((s,l)=>{let d=n().toString();e();let m={type:"request",sender:a,id:d,action:i,params:c};t[d]={resolve:s,reject:l,timestamp:Date.now(),message:m},r(JSON.stringify(m))})}}function Ie(n,e,t,r,o,a){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,o,a);r()})}}var $=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,r){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let o=t(null,r,{id:e}).then(a=>(this.cache[e]=a,delete this.pendingRequests[e],a)).catch(a=>{throw delete this.pendingRequests[e],a});return this.pendingRequests[e]=o,o}};var N=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,r){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let o=t(null,r,{key:e}).then(a=>(this.cache[e]=a,delete this.pendingRequests[e],a)).catch(a=>{throw delete this.pendingRequests[e],a});return this.pendingRequests[e]=o,o}getCached(e){return this.cache[e]??null}};var G=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,r){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let o=t(null,r,{id:e}).then(a=>(this.cache[e]=a,delete this.pendingRequests[e],a)).catch(a=>{throw delete this.pendingRequests[e],a});return this.pendingRequests[e]=o,o}};var F=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,r){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let o=t(null,r,{id:e}).then(a=>(this.cache[e]=a,delete this.pendingRequests[e],a)).catch(a=>{throw delete this.pendingRequests[e],a});return this.pendingRequests[e]=o,o}};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(r=>JSON.parse(r))}}}function Le(n,e,t){return{async getActiveOffers(r=3){let o=await e("SmartInfo.GameOffers");if(!Array.isArray(o)||o.length===0)return o||[];let a=[];for(let l of o)a.includes(l.unnyIdGameOffer)||a.push(l.unnyIdGameOffer);let i=a.map(l=>t(l,r)),c=await Promise.all(i),s={};for(let l=0;l<a.length;l++)s[a[l]]=c[l];for(let l of o){let d=l?.unnyIdGameOffer;d!=null&&s.hasOwnProperty(d)&&(l.gameOffer=s[d])}return o},async getActiveGroupOffers(r=3){let o=await e("SmartInfo.GameOfferGroups");if(!Array.isArray(o)||o.length===0)return o||[];let a=[];for(let l of o)a.includes(l.unnyIdGameOfferGroup)||a.push(l.unnyIdGameOfferGroup);let i=a.map(l=>t(l,r)),c=await Promise.all(i),s={};for(let l=0;l<a.length;l++)s[a[l]]=c[l];for(let l of o){let d=l?.unnyIdGameOfferGroup;d!=null&&s.hasOwnProperty(d)&&(l.gameOfferGroup=s[d])}return o},canBuyGroupOffer(r){return n(null,u.CanBuyGroupOffer,{instanceId:window.balancyViewOwner.instanceId,index:r})},buyGroupOffer(r,o={}){return!window.balancyViewOwner||!window.balancyViewOwner.instanceId?Promise.resolve(null):(o||(o={}),o.instanceId=window.balancyViewOwner.instanceId,o.index=r,n("buyGroupOfferButton",u.BuyGroupOffer,o))},buyOffer(r={}){return!window.balancyViewOwner||!window.balancyViewOwner.instanceId?Promise.resolve(null):(r||(r={}),r.instanceId=window.balancyViewOwner.instanceId,n("buyOfferButton",u.BuyOffer,r))},buyShopSlot(r,o={}){return o||(o={}),r?.unnyIdSlot&&(o.slotId=r.unnyIdSlot),n("buyShopSlotButton",u.BuyShopSlot,o)},getRewardedAdsWatchedForStoreItem(r){return r?.unnyId?n(null,u.GetRewardedAdsWatched,{id:r.unnyId}):Promise.resolve(0)},haveEnoughResources(r){return r?.unnyId?n(null,u.HaveEnoughResources,{id:r.unnyId}):Promise.resolve(!1)},getShopInfo(r){return r?.unnyId?n(null,u.GetShopInfo,{id:r.unnyId}).then(o=>JSON.parse(o)):Promise.resolve(0)}}}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 Oe(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 Ce(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,r){return n(null,u.BattlePassClaim,{id:window.balancyViewOwner.unnyIdGameEvent,lineId:t,index:r}).then(o=>o&&o==="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})},getCustomDocumentInfo(e){return n(null,u.GetCustomDocumentInfo,{id:e}).then(t=>t?JSON.parse(t):{})},setCustomDocumentInfo(e,t){let r=JSON.stringify(t);return n(null,u.SetCustomDocumentInfo,{id:e,data:r})},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 r=await n(t);e.textContent=r}e.classList.add("balancy-text-prepared")},async localizeAllElements(e=document){let t=e.querySelectorAll('[data-text-type="localized"]'),r=Array.from(t).map(async o=>{if(o.classList.contains("balancy-text-prepared"))return;let a=o.getAttribute("data-localization-key");await this.setLocalizedText(o,a)});await Promise.all(r),e===document&&document.dispatchEvent(new CustomEvent("balancy-localization-complete"))}}}function Re(n){async function e(t,r){t.classList.add("balancy-image-prepared");let o=await n(r);o&&(t.tagName==="IMG"?t.src=o:t.hasAttribute("data-use-nineslice")&&t.getAttribute("data-use-nineslice")==="false"?t.style.backgroundImage=`url('${o}')`:t.style.borderImageSource=`url('${o}')`)}return{setImage(t,r){r?.id&&(t.setAttribute("data-image-id",r.id),e(t,r.id))},async prepareAllSprites(t=document){let r=t.querySelectorAll("[data-image-id]"),o=Array.from(r).map(async a=>{if(a.classList.contains("balancy-image-prepared"))return;let i=a.getAttribute("data-image-id");i&&await e(a,i)});await Promise.all(o),t===document&&document.dispatchEvent(new CustomEvent("balancy-images-complete"))}}}function ke(n,e){return{async prepareAllFonts(t=document){let r=t.querySelectorAll("[data-font-id]"),o=Array.from(r).map(async a=>{if(a.classList.contains("balancy-font-prepared"))return;let i=a.getAttribute("data-font-name"),c=a.getAttribute("data-font-id");if(i&&c){let s=await n(c);e(i,s)}});await Promise.all(o),t===document&&document.dispatchEvent(new CustomEvent("balancy-fonts-complete"))}}}function He(n,e,t){function r(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 o(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 a(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:a,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")&&a(m),m.hasAttribute("data-button-audio-id")&&o(m)},r(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,r,o){return{prepareAllTexts(a=document){let i=a.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(r())};var L=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=>o(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(()=>{a===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),r=n.item.type===B.Currency,o;if(t){let a=n.count,i=Math.floor(a/3600),c=Math.floor(a%3600/60);o=`${i>0?`${i}h `:""}${c>0?`${c}m`:""}`}else{let a=e?_(n.count):n.count.toString();o=r?`${n.count}`:`x${a}`}return{text:o,isDuration:t,isCurrency:r}}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),r=Math.floor(n%3600/60),o=n%60;return e>0?t>0?`${e}d ${t}h`:`${e}d`:`${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`}function ze(n,...e){return n.replace(/{(\d+)}/g,(t,r)=>e[r]!==void 0?e[r]: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),r=Math.floor(n%86400/3600),o=Math.floor(n%3600/60),a=n%60;switch(e){case y.DaysHours:return t>0?`${t}:${r.toString().padStart(2,"0")}`:`${r}:00`;case y.HoursMinutes:return`${r}:${o.toString().padStart(2,"0")}`;case y.HoursMinutesSeconds:return`${r}:${o.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`;case y.MinutesSeconds:return`${o}:${a.toString().padStart(2,"0")}`;case y.Full:return t>0?`${t}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`:`${r}:${o.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`;case y.Auto:default:return t>0?`${t}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`:`${r}:${o.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`}}function Ge(n,e,t){let r=Math.floor(n/86400),o=Math.floor(n%86400/3600),a=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(r,f.day||"d"),s(o,f.hour||"h");break;case y.HoursMinutes:s(o,f.hour||"h"),s(a,f.minute||"m");break;case y.HoursMinutesSeconds:s(o,f.hour||"h"),s(a,f.minute||"m"),s(i,f.second||"s");break;case y.MinutesSeconds:s(a,f.minute||"m"),s(i,f.second||"s");break;case y.Full:s(r,f.day||"d"),s(o,f.hour||"h"),s(a,f.minute||"m"),s(i,f.second||"s");break;case y.Auto:default:r>0?(s(r,f.day||"d"),s(o,f.hour||"h")):o>0?(s(o,f.hour||"h"),s(a,f.minute||"m")):(s(a,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,r=e.regularItemFormat??P.WithPrefix,o=e.timeFormat??C.LocalizedCompact,a=e.timePrecision??y.Auto,i=j(n.item),c=n.item.type===B.Currency,s;if(i){let l=n.count;o===C.Colon?s=gt(l,a):o===C.Localized?s=Ge(l,a,!1):s=Ge(l,a,!0)}else{let l=c?t:r;s=ft(n.count,l)}return{text:s,isDuration:i,isCurrency:c}}function We(n){function e(r){return r.charAt(0).toUpperCase()+r.slice(1)}async function t(r,o){let a=o.split("."),i=r;for(let c=0;c<a.length;c++){let s=a[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<a.length){let m=a.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(o,a){if(!o.includes("{")||!o.includes("}"))return o;let i=[],c=/\{([^}]+)\}/g,s;for(;(s=c.exec(o))!==null;)i.push({fullMatch:s[0],path:s[1].trim(),index:s.index});if(i.length===0)return o;let l=i.map(async p=>{let g=await t(a,p.path);return{placeholder:p.fullMatch,value:g!==void 0?String(g):p.fullMatch}}),d=await Promise.all(l),m=o;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=`
|
|
4
|
+
"use strict";var balancy=(()=>{var d={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,GetShopInfo:105,CloseWindow:200,BalancyIsReady:201,BatchRequest:399,CustomMessage:1e3},R={Currency:1,Item:2,Event:4},he={Hard:0,Soft:1,Ads:2},be={None:0,InProgress:1,Completed:2,Claimed:3,Failed:4},M={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},Ee={Available:0,Unavailable:1,Cooldown:2,Locked:3},ve={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},h={Auto:0,DaysHours:1,HoursMinutes:2,HoursMinutesSeconds:3,MinutesSeconds:4,Full:5};var N=class{constructor(){this.pendingBatch=new Map;this.batchTimeout=null;this.BATCH_DELAY=16}addToBatch(e,t,o,a,r,s,l,i){let c=e.toString(),u={type:"request",sender:t,id:c,action:o,params:a};return this.pendingBatch.set(c,{requestData:u,resolve:r,reject:s}),this.scheduleBatch(l,i),c}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 o=[];this.pendingBatch.forEach((r,s)=>{o.push(r.requestData),e[s]={resolve:r.resolve,reject:r.reject,timestamp:Date.now(),message:r.requestData}}),console.log(`[BatchManager] Sending batch with ${this.pendingBatch.size} requests`),t(JSON.stringify({type:"batch",requests:o})),this.pendingBatch.clear(),this.batchTimeout=null}getStats(){return{pendingCount:this.pendingBatch.size,isScheduled:this.batchTimeout!==null}}};function we(){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){n(t)}}function Te(n,e,t){return function(a){try{let r=JSON.parse(a);if(r.type==="response"){let s=n[r.id];s&&(r.error?s.reject(new Error(r.error+" : "+JSON.stringify(s.message))):s.resolve(r.result),delete n[r.id])}else if(r.type==="batch-response")r.responses&&Array.isArray(r.responses)&&r.responses.forEach(s=>{let l=n[s.id];l&&(s.error?l.reject(new Error(s.error+" : "+JSON.stringify(l.message))):l.resolve(s.result),delete n[s.id])});else if(r.type==="notification"){let s=r.data?JSON.parse(r.data):null;e(s)}else r.type==="custom-message"&&t(r.data)}catch(r){console.error("Error handling response:",r)}}}function Me(n,e,t,o){return function(r,s,l={}){return new Promise((i,c)=>{let u=n().toString();e();let m={type:"request",sender:r,id:u,action:s,params:l};t[u]={resolve:i,reject:c,timestamp:Date.now(),message:m},o(JSON.stringify(m))})}}function Ie(n,e,t,o,a,r){return function(l,i,c={}){return[d.BuyOffer,d.BuyGroupOffer,d.BuyShopSlot,d.BattlePassClaim,d.CloseWindow,d.CustomMessage,d.BalancyIsReady,d.StopEventManually,d.WatchRewardedAd].includes(i)?e(l,i,c):new Promise((m,p)=>{let g=n.addToBatch(t(),l,i,c,m,p,a,r);o()})}}var G=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,o){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let a=t(null,o,{id:e}).then(r=>(this.cache[e]=r,delete this.pendingRequests[e],r)).catch(r=>{throw delete this.pendingRequests[e],r});return this.pendingRequests[e]=a,a}};var D=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,o){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let a=t(null,o,{key:e}).then(r=>(this.cache[e]=r,delete this.pendingRequests[e],r)).catch(r=>{throw delete this.pendingRequests[e],r});return this.pendingRequests[e]=a,a}getCached(e){return this.cache[e]??null}};var k=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,o){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let a=t(null,o,{id:e}).then(r=>(this.cache[e]=r,delete this.pendingRequests[e],r)).catch(r=>{throw delete this.pendingRequests[e],r});return this.pendingRequests[e]=a,a}};var j=class{constructor(){this.cache={};this.pendingRequests={}}async get(e,t,o){if(this.cache[e]!==void 0)return this.cache[e];if(this.pendingRequests[e])return this.pendingRequests[e];let a=t(null,o,{id:e}).then(r=>(this.cache[e]=r,delete this.pendingRequests[e],r)).catch(r=>{throw delete this.pendingRequests[e],r});return this.pendingRequests[e]=a,a}};function Se(n){return{getProfileValue(e,t){return n(null,d.GetProfile,{profile:e,path:t})},getSystemProfileValue(e){return n(null,d.GetProfile,{profile:"UnnyProfile",path:e})},getDocumentValue(e,t){return n(null,d.GetDocument,{id:e,depth:t}).then(o=>JSON.parse(o))}}}function Ae(n,e,t){return{async getActiveOffers(o=3){let a=await e("SmartInfo.GameOffers");if(!Array.isArray(a)||a.length===0)return a||[];let r=[];for(let c of a)r.includes(c.unnyIdGameOffer)||r.push(c.unnyIdGameOffer);let s=r.map(c=>t(c,o)),l=await Promise.all(s),i={};for(let c=0;c<r.length;c++)i[r[c]]=l[c];for(let c of a){let u=c?.unnyIdGameOffer;u!=null&&i.hasOwnProperty(u)&&(c.gameOffer=i[u])}return a},async getActiveGroupOffers(o=3){let a=await e("SmartInfo.GameOfferGroups");if(!Array.isArray(a)||a.length===0)return a||[];let r=[];for(let c of a)r.includes(c.unnyIdGameOfferGroup)||r.push(c.unnyIdGameOfferGroup);let s=r.map(c=>t(c,o)),l=await Promise.all(s),i={};for(let c=0;c<r.length;c++)i[r[c]]=l[c];for(let c of a){let u=c?.unnyIdGameOfferGroup;u!=null&&i.hasOwnProperty(u)&&(c.gameOfferGroup=i[u])}return a},canBuyGroupOffer(o){return n(null,d.CanBuyGroupOffer,{instanceId:window.balancyViewOwner.instanceId,index:o})},buyGroupOffer(o,a={}){return!window.balancyViewOwner||!window.balancyViewOwner.instanceId?Promise.resolve(null):(a||(a={}),a.instanceId=window.balancyViewOwner.instanceId,a.index=o,n("buyGroupOfferButton",d.BuyGroupOffer,a))},buyOffer(o={}){return!window.balancyViewOwner||!window.balancyViewOwner.instanceId?Promise.resolve(null):(o||(o={}),o.instanceId=window.balancyViewOwner.instanceId,n("buyOfferButton",d.BuyOffer,o))},buyShopSlot(o,a={}){return a||(a={}),o?.unnyIdSlot&&(a.slotId=o.unnyIdSlot),n("buyShopSlotButton",d.BuyShopSlot,a)},getRewardedAdsWatchedForStoreItem(o){return o?.unnyId?n(null,d.GetRewardedAdsWatched,{id:o.unnyId}):Promise.resolve(0)},haveEnoughResources(o){return o?.unnyId?n(null,d.HaveEnoughResources,{id:o.unnyId}):Promise.resolve(!1)},getShopInfo(o){return o?.unnyId?n(null,d.GetShopInfo,{id:o.unnyId}).then(a=>JSON.parse(a)):Promise.resolve(0)}}}function Le(n){return{getTasks(){return n(null,d.GetTasksInfoForTheEvent,{id:window.balancyViewOwner.unnyIdGameEvent}).then(e=>JSON.parse(e))},activateTasks(e){return n(null,d.ActivateTasksForTheEvent,{id:window.balancyViewOwner.unnyIdGameEvent,tasks:e}).then(t=>JSON.parse(t))},deactivateTasks(e){return n(null,d.DeactivateTasksForTheEvent,{id:window.balancyViewOwner.unnyIdGameEvent,tasks:e})},restoreFailedTask(e){return n(null,d.RestoreFailedTask,{id:e?e.unnyIdTask:""})},claimTaskReward(e){return n(null,d.ClaimTaskReward,{id:e}).then(t=>t&&t==="ok")}}}function Ce(n){return{getInventoryItemsCount(e){return n(null,d.GetInventoryItemsCount,{id:e})},addInventoryItems(e,t){return n(null,d.AddInventoryItems,{id:e,count:t})},removeInventoryItems(e,t){return n(null,d.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,d.GetBattlePassProgress,{id:window.balancyViewOwner.unnyIdGameEvent}).then(t=>JSON.parse(t))},claimBattlePassReward(t,o){return n(null,d.BattlePassClaim,{id:window.balancyViewOwner.unnyIdGameEvent,lineId:t,index:o}).then(a=>a&&a==="ok")}}}function Be(n){return{getCustomEventInfo(){return n(null,d.GetCustomEventInfo,{id:window.balancyViewOwner.instanceId}).then(e=>e?JSON.parse(e):{})},setCustomEventInfo(e){let t=JSON.stringify(e);return n(null,d.SetCustomEventInfo,{id:window.balancyViewOwner.instanceId,data:t})},getCustomDocumentInfo(e){return n(null,d.GetCustomDocumentInfo,{id:e}).then(t=>t?JSON.parse(t):{})},setCustomDocumentInfo(e,t){let o=JSON.stringify(t);return n(null,d.SetCustomDocumentInfo,{id:e,data:o})},stopEventManually(e=-1){return n(null,d.StopEventManually,{id:window.balancyViewOwner.unnyIdGameEvent,cooldown:e}).then(t=>t)},watchRewardedAd(e){return n(null,d.WatchRewardedAd,{}).then(t=>{e(!!t.success)})},getProductInfo(e){return n("offerGroupPrice",d.GetInfo,{type:M.CustomPrice,productId:e})},closeView(e){return n(null,d.CloseWindow,{id:e})},sendCustomMessage(e,t){return n(e,d.CustomMessage,t)}}}function Re(n){return{async setLocalizedText(e,t){if(t){let o=await n(t);e.textContent=o}e.classList.add("balancy-text-prepared")},async localizeAllElements(e=document){let t=e.querySelectorAll('[data-text-type="localized"]'),o=Array.from(t).map(async a=>{if(a.classList.contains("balancy-text-prepared"))return;let r=a.getAttribute("data-localization-key");await this.setLocalizedText(a,r)});await Promise.all(o),e===document&&document.dispatchEvent(new CustomEvent("balancy-localization-complete"))}}}function xe(n){async function e(t,o){t.classList.add("balancy-image-prepared");let a=await n(o);a&&(t.tagName==="IMG"?t.src=a:t.hasAttribute("data-use-nineslice")&&t.getAttribute("data-use-nineslice")==="false"?t.style.backgroundImage=`url('${a}')`:t.style.borderImageSource=`url('${a}')`)}return{setImage(t,o){o?.id&&(t.setAttribute("data-image-id",o.id),e(t,o.id))},async prepareAllSprites(t=document){let o=t.querySelectorAll("[data-image-id]"),a=Array.from(o).map(async r=>{if(r.classList.contains("balancy-image-prepared"))return;let s=r.getAttribute("data-image-id");s&&await e(r,s)});await Promise.all(a),t===document&&document.dispatchEvent(new CustomEvent("balancy-images-complete"))}}}function He(n,e){return{async prepareAllFonts(t=document){let o=t.querySelectorAll("[data-font-id]"),a=Array.from(o).map(async r=>{if(r.classList.contains("balancy-font-prepared"))return;let s=r.getAttribute("data-font-name"),l=r.getAttribute("data-font-id");if(s&&l){let i=await n(l);e(s,i)}});await Promise.all(a),t===document&&document.dispatchEvent(new CustomEvent("balancy-fonts-complete"))}}}function $e(n,e,t){function o(s){let l=s.getAttribute("data-button-action");if(!l)return;switch(parseInt(l,10)){case d.BuyGroupOffer:let c=parseInt(s.getAttribute("data-index")||"0",10)||0;e(c).then(u=>{s.disabled=!u});break}}async function a(s){let l=s.getAttribute("data-button-audio-id");if(!l)return;let i=await t(l);if(!i)return;let c=document.createElement("audio");c.autoplay=!0,c.src=i,c.addEventListener("ended",()=>{c.remove()}),c.addEventListener("error",()=>{c.remove()}),document.body.appendChild(c)}function r(s,l){let i=l?.action??s.getAttribute("data-button-action");if(!i){console.warn("Button missing data-button-action attribute",s);return}let c=parseInt(i,10);if(isNaN(c)||c===d.None){console.warn("Invalid action ID:",i,s);return}let u=s.id||"unknown-button",m=s.getAttribute("data-button-params"),p={};if(m&&m.trim()!=="")try{p=JSON.parse(m)}catch(y){console.error("Error parsing button params JSON:",y,"Raw params:",m),s.dispatchEvent(new CustomEvent("balancyButtonError",{detail:{actionId:c,error:"Invalid JSON in data-button-params",paramsAttr:m}})),p={}}switch(c){case d.BuyOffer:p.instanceId=l?.instanceId??window.balancyViewOwner.instanceId;break;case d.BuyGroupOffer:p.instanceId=window.balancyViewOwner.instanceId,p.index=parseInt(s.getAttribute("data-index")||"0",10)||0;break;case d.BuyShopSlot:p.slotId=s.getAttribute("data-index")||0;break}let g=s.disabled;s.disabled=!0,s.classList.add("balancy-button-processing"),n(u,c,p).then(y=>{console.log(`Button action ${c} executed successfully`,y),s.dispatchEvent(new CustomEvent("balancyButtonResponse",{detail:{actionId:c,result:y,success:!0,senderId:u}}))}).catch(y=>{console.error(`Error executing button action ${c}:`,y),s.dispatchEvent(new CustomEvent("balancyButtonResponse",{detail:{actionId:c,error:y.message,success:!1,senderId:u}}))}).finally(()=>{s.disabled=g,s.classList.remove("balancy-button-processing")})}return{balancyButtonClicked:r,prepareAllButtons(s=document){let l=s.querySelectorAll("[data-button-action]"),i=s.querySelectorAll("[data-button-audio-id]"),c=[...Array.from(l),...Array.from(i)],u=0;c.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")&&r(m),m.hasAttribute("data-button-audio-id")&&a(m)},o(m),m.addEventListener("click",m._balancyClickHandler),m.classList.add("balancy-button-prepared"),u++)}),s===document&&document.dispatchEvent(new CustomEvent("balancy-buttons-complete",{detail:{preparedCount:u,totalFound:c.length}}))}}}function Ne(n,e,t,o,a){return{prepareAllTexts(r=document){let s=r.querySelectorAll('[data-text-type="dynamic"]'),l=[];s.forEach(i=>{if(i.classList.contains("balancy-text-prepared"))return;i.classList.add("balancy-text-prepared");let c=i.id||"unknown-text",u=parseInt(i.getAttribute("data-info-type")||"0",10)||0,m=parseInt(i.getAttribute("data-index")||"0",10)||0,p=i.getAttribute("data-custom")||"",g=i.getAttribute("data-product-id")||"",y="";if(u===M.OfferPrice?(g=window.balancyViewOwner.productId,u=M.CustomPrice):u===M.OfferGroupPrice&&(y=window.balancyViewOwner.instanceId),u===M.TimeLeft){let v=function(){w.textContent=t(o())};var A=v;let w=i;setInterval(v,1e3),v();return}if(u===M.OwnerCustom){let w=i.getAttribute("data-text-format");w&&e(w,window.balancyViewOwner).then(v=>{i.textContent=v});return}if(u===M.OwnerLocalizedKey){let w=i.getAttribute("data-text-format");w&&e(w,window.balancyViewOwner).then(v=>a(i,v));return}let $=n(c,d.GetInfo,{type:u,productId:g,index:m,instanceId:y,custom:p}).then(w=>{try{let v=i.getAttribute("data-text-format");v&&e(v,w).then(ye=>{i.textContent=ye})}catch(v){console.error("Error formatting text:",v,"Result:",w)}});l.push($)}),Promise.all(l).then(()=>{r===document&&document.dispatchEvent(new CustomEvent("balancy-text-complete"))})}}}function Y(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 F(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 je(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 Fe(n,e=!1){let t=F(n.item),o=n.item.type===R.Currency,a;if(t){let r=n.count,s=Math.floor(r/3600),l=Math.floor(r%3600/60);a=`${s>0?`${s}h `:""}${l>0?`${l}m`:""}`}else{let r=e?Y(n.count):n.count.toString();a=o?`${n.count}`:`x${r}`}return{text:a,isDuration:t,isCurrency:o}}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),o=Math.floor(n%3600/60),a=n%60;return e>0?t>0?`${e}d ${t}h`:`${e}d`:`${t.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`}function Ue(n,...e){return n.replace(/{(\d+)}/g,(t,o)=>e[o]!==void 0?e[o]:t)}function K(){let e=Math.floor(Date.now()/1e3)-window.balancySettings.launchTime;return window.balancySettings.secondsLeft-e}var qe=["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 Ge(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 pt(n,e){switch(e){case P.Plain:return n.toString();case P.PlainSpaced:return Ge(n);case P.WithPrefix:return`x${n}`;case P.WithPrefixSpaced:return`x${Ge(n)}`;case P.Shortened:return De(n);case P.ShortenedWithPrefix:return`x${De(n)}`;default:return n.toString()}}function ft(n,e){let t=Math.floor(n/86400),o=Math.floor(n%86400/3600),a=Math.floor(n%3600/60),r=n%60;switch(e){case h.DaysHours:return t>0?`${t}:${o.toString().padStart(2,"0")}`:`${o}:00`;case h.HoursMinutes:return`${o}:${a.toString().padStart(2,"0")}`;case h.HoursMinutesSeconds:return`${o}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`;case h.MinutesSeconds:return`${a}:${r.toString().padStart(2,"0")}`;case h.Full:return t>0?`${t}:${o.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${o}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`;case h.Auto:default:return t>0?`${t}:${o.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`:`${o}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}}function ke(n,e,t){let o=Math.floor(n/86400),a=Math.floor(n%86400/3600),r=Math.floor(n%3600/60),s=n%60,l=[],i=(c,u)=>{t?c>0&&l.push(`${c}${u}`):l.push(`${c}${u}`)};switch(e){case h.DaysHours:i(o,f.day||"d"),i(a,f.hour||"h");break;case h.HoursMinutes:i(a,f.hour||"h"),i(r,f.minute||"m");break;case h.HoursMinutesSeconds:i(a,f.hour||"h"),i(r,f.minute||"m"),i(s,f.second||"s");break;case h.MinutesSeconds:i(r,f.minute||"m"),i(s,f.second||"s");break;case h.Full:i(o,f.day||"d"),i(a,f.hour||"h"),i(r,f.minute||"m"),i(s,f.second||"s");break;case h.Auto:default:o>0?(i(o,f.day||"d"),i(a,f.hour||"h")):a>0?(i(a,f.hour||"h"),i(r,f.minute||"m")):(i(r,f.minute||"m"),(!t||s>0)&&i(s,f.second||"s"));break}return l.join(" ")}function Ve(n,e={}){let t=e.currencyFormat??P.Plain,o=e.regularItemFormat??P.WithPrefix,a=e.timeFormat??O.LocalizedCompact,r=e.timePrecision??h.Auto,s=F(n.item),l=n.item.type===R.Currency,i;if(s){let c=n.count;a===O.Colon?i=ft(c,r):a===O.Localized?i=ke(c,r,!1):i=ke(c,r,!0)}else{let c=l?t:o;i=pt(n.count,c)}return{text:i,isDuration:s,isCurrency:l}}function _e(n){function e(o){return o.charAt(0).toUpperCase()+o.slice(1)}async function t(o,a){let r=a.split("."),s=o;for(let l=0;l<r.length;l++){let i=r[l].trim();if(s&&s[i]!==void 0&&s[i]!==null)s=s[i];else{let c="unnyId"+e(i);if(s&&s[c]!==void 0)try{let u=await n(s[c],0);if(l+1<r.length){let m=r.slice(l+1).join(".");return await t(u,m)}else return u}catch(u){console.error(`Failed to get document for ID ${s[c]}:`,u);return}return}}return s}return async function(a,r){if(!a.includes("{")||!a.includes("}"))return a;let s=[],l=/\{([^}]+)\}/g,i;for(;(i=l.exec(a))!==null;)s.push({fullMatch:i[0],path:i[1].trim(),index:i.index});if(s.length===0)return a;let c=s.map(async p=>{let g=await t(r,p.path);return{placeholder:p.fullMatch,value:g!==void 0?String(g):p.fullMatch}}),u=await Promise.all(c),m=a;for(let p of u)m=m.replace(p.placeholder,p.value);return m}}function Z(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 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 O.OnOfferDeactivated:case O.OnOfferGroupDeactivated:break;case O.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 r=n.indexOf(e);r>-1&&n.splice(r,1)})},dispatchCustomMessage(e){n.forEach(t=>{try{t(e)}catch(r){console.error("Error in custom message subscriber:",r)}}),window.dispatchEvent(new CustomEvent("balancy-custom-message",{detail:e}))}}}function Ke(n,e,t,r,o){window.addEventListener("message",function(a){if(a.source!==window.parent||a.source===window)return;let i=a.data;i&&typeof i=="object"&&i.payload&&n(i.payload)}),function(){let i=new Set(["balancy-buttons-complete","balancy-localization-complete","balancy-text-complete","balancy-images-complete","balancy-fonts-complete","balancy-components-complete","balancy-audio-complete"]),c=new Set;function s(l){c.add(l.type),[...i].every(d=>c.has(d))&&(console.log("ALL IS READY"),window.dispatchEvent(new CustomEvent("balancy-ready")),r||t())}i.forEach(l=>{document.addEventListener(l,s,{once:!0})})}(),(async()=>(await e(),o&&await o()))()}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 r=t.querySelectorAll("audio[data-button-audio-id]"),o=0;for(let a of r){if(a.classList.contains("balancy-audio-prepared"))return;let i=a.getAttribute("data-button-audio-id");if(!i)return;let c=await n(i);if(!c)return;a.src=c,a.classList.add("balancy-audio-prepared"),o++}t===document&&document.dispatchEvent(new CustomEvent("balancy-audio-complete",{detail:{preparedCount:o,totalFound:r.length}}))}return{prepareAllAudio:e}}var z=class{constructor(){this._enabled=!0;this._activeInHierarchy=!0}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this.updateActiveState())}get activeInHierarchy(){return this._activeInHierarchy}awake(){}onEnable(){}start(){}update(e){}onDisable(){}onDestroy(){}getComponent(e){if(!this.elementObject)return null;for(let t of this.elementObject.components)if(t.scriptInstance instanceof e)return t.scriptInstance;return null}getComponents(e){if(!this.elementObject)return[];let t=[];for(let r of this.elementObject.components)r.scriptInstance instanceof e&&t.push(r.scriptInstance);return t}getComponentInChildren(e){if(!this.elementObject)return null;let t=this.elementObject.element.querySelectorAll("[data-guid]");for(let r=0;r<t.length;r++){let o=t[r];o===this.elementObject.element||o.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(r){let o=r.getAttribute("data-guid");if(o){let i=Qe();r.setAttribute("data-guid",i),e.set(o,i)}let a=r.children;for(let i=0;i<a.length;i++){let c=a[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,r,o){for(let[a,i]of Object.entries(e))try{if(!(a in n))continue;switch(i.type){case"number":n[a]=Number(i.value);break;case"string":n[a]=String(i.value);break;case"boolean":n[a]=i.value===!0||i.value==="true";break;case"element":let c=String(i.value);if(c===""||c==="null")n[a]=null;else{let s=t(c,a);if(n[a]=s,!s){let l=r||n.constructor.name||"Unknown",d=o?.getAttribute("data-script-id"),m=o?.id||o?.getAttribute("data-guid")||"Unknown",p=o?.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: "${a}"`),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 "${a}":`,c)}}function tt(n){return JSON.stringify(n).replace(/"/g,"'")}function nt(n,e,t){return(r,o)=>vt(r,n,e,o,t)}function vt(n,e,t,r,o){if(!n||n===""||n==="null")return null;let a=t?x(n,t):null;if(!a&&t&&(a=x(n)),!a&&!t&&(a=x(n)),!a&&o&&(a=o.findElementInCachedPrefabs(n),a&&console.log(`[ElementResolver] Resolved "${n}" by data-guid in cached prefab template`),a||(a=o.getCachedPrefabRoot(n),a&&console.log(`[ElementResolver] Resolved "${n}" as cached prefab root (prefab ID reference)`))),!a)return r||console.error(`[ElementResolver] Element not found for GUID: "${n}"`),null;let i=e.getElementByGuid(n);return i||(i=e.createElementObjectFromElement(a,n)),i||(console.error(`[ElementResolver] Failed to create ElementObject for GUID: "${n}"`),null)}function V(n,e){let t=n.querySelectorAll("[data-script-params]"),r=[];n.hasAttribute("data-script-params")&&r.push(n),r.push(...Array.from(t));for(let o of r)try{wt(o,e)}catch(a){console.error("[ParameterCloner] Error updating parameters:",a),console.error(" Script element:",o)}}function wt(n,e){let t=q(n);if(!t)return;let r=!1;for(let[o,a]of Object.entries(t))if(a.type==="element"){let i=String(a.value);if(e.has(i)){let c=e.get(i);a.value=c,r=!0}}if(r){let o=tt(t);n.setAttribute("data-script-params",o)}}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 r of this.elementObjects.values())if(r.isActive){for(let o of r.components)if(!(!o.enabled||!o.scriptInstance.activeInHierarchy)){o.hasStarted||this.invokeStart(o);try{o.scriptInstance.update(t)}catch(a){console.error(`[ElementsManager] Error in update() for ${o.scriptId}:`,a)}}}}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 r=e.getAttribute("data-guid");r&&this.getOrRegisterElementObject(e,r);let o=[];for(let a=0;a<e.children.length;a++){let i=e.children[a];i instanceof HTMLElement&&i.hasAttribute("data-script-id")&&o.push(i)}o.length>0&&this.processScriptDivs(e,o,t);for(let a=0;a<e.children.length;a++){let i=e.children[a];i instanceof HTMLElement&&this.scanElement(i,t)}}getOrRegisterElementObject(e,t){let r=this.elementObjects.get(t);return r||(r=new S(e,t),this.elementObjects.set(t,r)),r}processScriptDivs(e,t,r){let o=te(e),a=this.getOrRegisterElementObject(e,o);for(let i of t)this.createComponent(a,i,r)}createComponent(e,t,r){let o=t.getAttribute("data-script-id");if(!o)return console.error("[ElementsManager] Script div missing data-script-id",t),null;let a=ee.get(o);if(!a)return null;te(t);try{let i=new a,c={elementObject:e,scriptElement:t,scriptInstance:i,scriptId:o,enabled:!0,hasStarted:!1};i.elementObject=e,i.scriptElement=t,e.addComponent(c);let s=q(t);if(s){let l=nt(this,r,this.prefabsManagerRef||void 0),d=a.name||o;et(i,s,l,d,t)}return c}catch(i){return console.error(`[ElementsManager] Error creating component "${o}":`,i),null}}invokeInitialLifecycleMethods(){for(let e of this.elementObjects.values())for(let t of e.components)this.callLifecycleMethod(t,"awake"),e.isActive&&t.enabled&&this.callLifecycleMethod(t,"onEnable")}callLifecycleMethod(e,t){try{let r=e.scriptInstance[t];typeof r=="function"&&r.call(e.scriptInstance)}catch(r){console.error(`[ElementsManager] Error in ${t}() for ${e.scriptId}:`,r)}}invokeStart(e){e.hasStarted||(this.callLifecycleMethod(e,"start"),e.hasStarted=!0)}startUpdateLoop(){this.updateLoopRunning||(this.updateLoopRunning=!0,this.lastFrameTime=performance.now(),this.updateLoop(this.lastFrameTime))}pause(){this.isPaused=!0}resume(){this.isPaused=!1}stopUpdateLoop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.updateLoopRunning=!1}getElementByGuid(e){return this.elementObjects.get(e)||null}createElementObjectFromElement(e,t){if(this.elementObjects.has(t))return this.elementObjects.get(t);let r=new S(e,t);return this.elementObjects.set(t,r),r}getOrCreateElementObject(e){if(this.elementObjects.has(e))return this.elementObjects.get(e);let t=x(e);if(!t)return null;let r=new S(t,e);this.elementObjects.set(e,r);let o=[];for(let a=0;a<t.children.length;a++){let i=t.children[a];i instanceof HTMLElement&&i.hasAttribute("data-script-id")&&o.push(i)}if(o.length>0)for(let a of o)this.createComponent(r,a,t);return r}setActive(e,t){let r=e.getAttribute("data-guid");if(!r){console.error("[ElementsManager] Element has no GUID:",e);return}let o=this.elementObjects.get(r);if(!o){console.warn("[ElementsManager] Element not managed:",e);return}if(o.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";o.isActive=t;let a=this.getComponentsInElementAndChildren(e);for(let i of a)i.scriptInstance.updateActiveState()}getComponentsInElementAndChildren(e){let t=[],r=e.getAttribute("data-guid");if(r){let a=this.elementObjects.get(r);a&&t.push(...a.components)}let o=e.querySelectorAll("[data-guid]");for(let a of o){let i=a.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 o=this.getComponentsInElementAndChildren(e);for(let i of o)i.scriptInstance.activeInHierarchy&&this.callLifecycleMethod(i,"onDisable"),this.callLifecycleMethod(i,"onDestroy");this.elementObjects.delete(t);let a=e.querySelectorAll("[data-guid]");for(let i of a){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(a=>{console.error("[ElementsManager] Error preparing sprites for clone:",a)});let r=U(t);V(t,r),this.scanElement(t,t);let o=this.getComponentsInElementAndChildren(t);for(let a of o)this.callLifecycleMethod(a,"awake"),a.enabled&&a.scriptInstance.activeInHierarchy&&this.callLifecycleMethod(a,"onEnable"),this.invokeStart(a);return t}copyInlineStyles(e,t){e.style.cssText&&(t.style.cssText=e.style.cssText);let r=e.children,o=t.children;for(let a=0;a<r.length&&a<o.length;a++)r[a]instanceof HTMLElement&&o[a]instanceof HTMLElement&&this.copyInlineStyles(r[a],o[a])}cleanup(){this.stopUpdateLoop(),this.elementObjects.clear(),this.initialized=!1}},h=new ne;var S=class{constructor(e,t){this.components=[];this.isActive=!0;this.element=e,this.guid=t}addComponent(e){this.components.includes(e)||(this.components.push(e),e.elementObject=this)}removeComponent(e){let t=this.components.indexOf(e);t!==-1&&this.components.splice(t,1)}getComponent(e){for(let t of this.components)if(t.scriptInstance instanceof e)return t.scriptInstance;return null}getComponents(e){let t=[];for(let r of this.components)r.scriptInstance instanceof e&&t.push(r.scriptInstance);return t}getEnabledComponents(){return this.components.filter(e=>e.enabled&&e.scriptInstance.activeInHierarchy)}setActive(e){h.setActive(this.element,e)}instantiate(){let t=h.instantiate(this.element).getAttribute("data-guid");if(!t)throw new Error("[ElementObject] Cloned element has no GUID");let r=h.getElementByGuid(t);if(!r)throw new Error("[ElementObject] Cloned element not found in ElementsManager");return r}};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 r=this.prefabCache.get(e);console.log(`[PrefabsManager] Using cached prefab: ${e}`);let o=r.cloneNode(!0);return this.copyInlineStyles(r,o),o}if(this.pendingLoads.has(e)){if(console.log(`[PrefabsManager] Waiting for pending load: ${e}`),await this.pendingLoads.get(e),this.prefabCache.has(e)){let r=this.prefabCache.get(e),o=r.cloneNode(!0);return this.copyInlineStyles(r,o),o}return console.error(`[PrefabsManager] Prefab not in cache after pending load: ${e}`),null}if(!this.loaderFunction)return console.error("[PrefabsManager] No loader function set. Call setLoader() first."),null;console.log(`[PrefabsManager] Loading prefab: ${e}`);let t=(async()=>{try{let r=await this.loaderFunction(e);if(!r)return console.error(`[PrefabsManager] Failed to load prefab: ${e}`),null;this.prefabCache.set(e,r),console.log(`[PrefabsManager] Prefab cached: ${e}`);let o=r.cloneNode(!0);return this.copyInlineStyles(r,o),o}catch(r){return console.error(`[PrefabsManager] Error loading prefab "${e}":`,r),null}finally{this.pendingLoads.delete(e)}})();return this.pendingLoads.set(e,t),t}copyInlineStyles(e,t){e.style.cssText&&(t.style.cssText=e.style.cssText);let r=e.children,o=t.children;for(let a=0;a<r.length&&a<o.length;a++)r[a]instanceof HTMLElement&&o[a]instanceof HTMLElement&&this.copyInlineStyles(r[a],o[a])}async processPrefabPlaceholdersInScope(e=document){let t=e===document?"whole page":`<${e.tagName?.toLowerCase()||"element"} id="${e.id||"unknown"}">`;console.log(`[PrefabsManager] Processing prefab placeholders in: ${t}`);let r=e.querySelectorAll("[data-prefab-id]");console.log(`[PrefabsManager] Found ${r.length} placeholders in scope`);for(let o of r)o.hasAttribute("data-prefab-id")&&await this.processPlaceholder(o);console.log(`[PrefabsManager] All prefab placeholders processed in: ${t}`)}async processPrefabPlaceholders(){await this.processPrefabPlaceholdersInScope(document)}async processPlaceholder(e){let t=e.getAttribute("data-prefab-id");if(!t){console.warn("[PrefabsManager] Skipping placeholder - data-prefab-id attribute missing or already processed",e);return}try{let r=await this.load(t);if(!r){console.error(`[PrefabsManager] Failed to load prefab for placeholder: ${t}`);return}let o=e.getAttribute("data-guid");console.log(`[PrefabsManager] Processing placeholder for ${t}:`),console.log(` - Placeholder: <${e.tagName.toLowerCase()} id="${e.id}">`),console.log(` - Placeholder GUID: ${o}`),console.log(` - Prefab root: <${r.tagName.toLowerCase()} id="${r.id}">`),console.log(` - Children to move: ${r.children.length}`);let a=U(r);V(r,a),console.log(` - Regenerated ${a.size} GUIDs for unique instance`),this.validatePrefabReferences(r,t);let i=0;for(;r.firstChild;)e.appendChild(r.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&&r.className&&(e.className=r.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(r){console.error(`[PrefabsManager] Error processing placeholder for "${t}":`,r)}}clearCache(){this.prefabCache.clear()}async preload(e){console.log(`[PrefabsManager] Preloading ${e.length} prefabs...`);let t=e.map(r=>this.load(r));await Promise.all(t),console.log("[PrefabsManager] Preload complete")}getCacheStats(){return{size:this.prefabCache.size,prefabIds:Array.from(this.prefabCache.keys())}}findElementInCachedPrefabs(e){for(let[t,r]of this.prefabCache.entries()){if(r.getAttribute("data-guid")===e)return console.log(`[PrefabsManager] Found GUID "${e}" as root of cached prefab ${t}`),r;let o=r.querySelector(`[data-guid="${e}"]`);if(o)return console.log(`[PrefabsManager] Found GUID "${e}" inside cached prefab ${t}`),o}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 r=e.querySelectorAll("[data-guid]"),o=new Set,a=e.getAttribute("data-guid");a&&o.add(a),r.forEach(s=>{let l=s.getAttribute("data-guid");l&&o.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 L=String(H.value);L&&L!==""&&L!=="null"&&!o.has(L)&&(this.findElementInCachedPrefabs(L)||c.push({scriptId:d,elementId:m,param:b,guid:L}))}}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 r=this.getElementByGuid(t);return r||(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,r=e.children;for(let o=0;o<t.length&&o<r.length;o++)t[o]instanceof HTMLElement&&r[o]instanceof HTMLElement&&oe(t[o],r[o])}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:Ot,getRewardedAdsWatchedForStoreItem:Ct,haveEnoughResources:xt,getShopInfo:Bt}=Le(v,A.getSystemProfileValue,A.getDocumentValue),R=Ae(v),ae=Oe(v),ie=Ce(v,A.getDocumentValue),I=xe(v),ce=n=>lt.get(n,v,u.GetLocalization),k=n=>Et.get(n,v,u.GetImageUrl),Rt=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),kt=ke(k,X);h.setPrepareSpritesFunction(ge.prepareAllSprites);var pt=He(v,pe,k),Ht=De(v,mt,J,K,fe.setLocalizedText),Dt=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 kt.prepareAllFonts(n),await ge.prepareAllSprites(n),await pt.prepareAllButtons(n),await Ht.prepareAllTexts(n),await Dt.prepareAllAudio(n),console.info(`[Balancy] All UI elements prepared for: ${e}`)},$t=()=>{document.querySelectorAll(`[data-button-action="${u.BuyGroupOffer}"]`).forEach(e=>{let t=parseInt(e.getAttribute("data-index")||"0",10)||0;pe(t).then(r=>{e.disabled=!r})})};me=_e($t);var ot=!1,at=()=>dt(null,u.BalancyIsReady,{id:"none"});Object.assign(Y,{NotificationType:O,PriceType:be,ItemType:B,TaskStatus:he,RequestAction:u,BuyButtonState:ve,OfferGroupType:we,NumberDisplayFormat:P,TimeDisplayFormat:C,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:Ot,getRewardedAdsWatchedForStoreItem:Ct,haveEnoughResources:xt,getShopInfo:Bt,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:I.getCustomEventInfo,setCustomEventInfo:I.setCustomEventInfo,getCustomDocumentInfo:I.getCustomDocumentInfo,setCustomDocumentInfo:I.setCustomDocumentInfo,stopEventManually:I.stopEventManually,watchRewardedAd:I.watchRewardedAd,getProductInfo:I.getProductInfo,closeView:I.closeView,sendCustomMessage:I.sendCustomMessage,getLocalizedText:ce,getImageUrl:k,getFileLocation:Rt,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:S,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(o=>ce(o))),qe(o=>lt.getCached(o)),console.info("[Balancy] Mandatory localization keys preloaded"),M.setUIProcessor(async o=>{await W(o)}),M.setLoader(async o=>{try{if(n.has(o)){console.info(`[Balancy] Using cached prefab: ${o}`);let d=n.get(o),m=d.cloneNode(!0);return oe(d,m),m}console.info(`[Balancy] Loading prefab for the first time: ${o}`);let a=await rt(o);if(console.info(`[Balancy] Received HTML content (length: ${a?.length||0})`),!a)return console.error(`[Balancy] No HTML content returned for prefab: ${o}`),null;let c=new DOMParser().parseFromString(a,"text/html"),s=c.body.firstElementChild;if(!s)return console.error(`[Balancy] No root element found in prefab body for: ${o}`),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",o),document.head.appendChild(g)}else console.warn(`[Balancy] No styles left after filtering for prefab: ${o}`)}),console.info(`[Balancy] Processing UI elements for prefab ${o}...`),await W(s),console.info(`[Balancy] UI elements processed for prefab ${o}`),n.set(o,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(a){return console.error(`[Balancy] Error in prefab loader for "${o}":`,a),null}}),await M.processPrefabPlaceholders(),h.setPrefabsManager(M);let t=new Set,r=document.querySelectorAll("[data-script-params]");for(let o of Array.from(r)){let a=o.getAttribute("data-script-params");if(a)try{let i=a.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 o=document.body.querySelector("[data-guid]");if(o){let a=o.getAttribute("data-guid");console.info(`[Balancy] Found root element with GUID: ${a}`);let i=h.getElementByGuid(a);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(o){console.error("[Balancy] Error auto-initializing root script:",o)}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;})();
|
|
9
|
+
`,document.head.appendChild(t)}function We(n,e){let t=(e??document).querySelector(`[data-id=${n}]`);return t instanceof HTMLElement?t:null}function Ye(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 o=n.indexOf(e);o>-1&&n.splice(o,1)})},dispatchCustomMessage(e){n.forEach(t=>{try{t(e)}catch(o){console.error("Error in custom message subscriber:",o)}}),window.dispatchEvent(new CustomEvent("balancy-custom-message",{detail:e}))}}}function Ke(n,e,t,o,a){window.addEventListener("message",function(r){if(r.source!==window.parent||r.source===window)return;let s=r.data;s&&typeof s=="object"&&s.payload&&n(s.payload)}),function(){let s=new Set(["balancy-buttons-complete","balancy-localization-complete","balancy-text-complete","balancy-images-complete","balancy-fonts-complete","balancy-components-complete","balancy-audio-complete"]),l=new Set;function i(c){l.add(c.type),[...s].every(u=>l.has(u))&&(console.log("ALL IS READY"),window.dispatchEvent(new CustomEvent("balancy-ready")),o||t())}s.forEach(c=>{document.addEventListener(c,i,{once:!0})})}(),(async()=>(await e(),a&&await a()))()}function Q(){if(window.__balancyGameUIInjected)return;if(window.__balancyGameUIInjected=!0,console.log("[BalancyWebView] Initializing game UI optimizations"),!document.querySelector('meta[name="viewport"]')){let e=document.createElement("meta");e.name="viewport",e.content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",document.head.appendChild(e),console.log("[BalancyWebView] Viewport meta tag added")}let n=/iPad|iPhone|iPod/.test(navigator.userAgent)?"iOS":/Android/.test(navigator.userAgent)?"Android":"Desktop";console.log(`[BalancyWebView] Game UI ready (${n})`),document.dispatchEvent(new CustomEvent("balancyGameUIReady",{detail:{platform:n,timestamp:Date.now()}}))}function Ze(n){async function e(t=document){let o=t.querySelectorAll("audio[data-button-audio-id]"),a=0;for(let r of o){if(r.classList.contains("balancy-audio-prepared"))return;let s=r.getAttribute("data-button-audio-id");if(!s)return;let l=await n(s);if(!l)return;r.src=l,r.classList.add("balancy-audio-prepared"),a++}t===document&&document.dispatchEvent(new CustomEvent("balancy-audio-complete",{detail:{preparedCount:a,totalFound:o.length}}))}return{prepareAllAudio:e}}var U=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 o of this.elementObject.components)o.scriptInstance instanceof e&&t.push(o.scriptInstance);return t}getComponentInChildren(e){if(!this.elementObject)return null;let t=this.elementObject.element.querySelectorAll("[data-guid]");for(let o=0;o<t.length;o++){let a=t[o];a===this.elementObject.element||a.getAttribute("data-guid")}return null}updateActiveState(){let e=this._enabled&&this.isParentActive();if(this._activeInHierarchy!==e){this._activeInHierarchy=e;try{e?this.onEnable():this.onDisable()}catch(t){console.error("[ElementBehaviour] Error in lifecycle hook:",t)}}}isParentActive(){if(!this.elementObject||!this.elementObject.element)return!0;let e=this.elementObject.element.parentElement;for(;e&&e!==document.body;){if(window.getComputedStyle(e).display==="none")return!1;e=e.parentElement}return!0}};var X=class{constructor(){this.scripts=new Map}register(e,t){this.scripts.has(e)&&console.warn(`[ScriptRegistry] Script ID "${e}" is already registered. Overwriting.`),this.scripts.set(e,t)}get(e){let t=this.scripts.get(e);return t||(console.error(`[ScriptRegistry] Script class not found for ID: "${e}". Did you forget to register it?`),null)}has(e){return this.scripts.has(e)}getAllScriptIds(){return Array.from(this.scripts.keys())}clear(){this.scripts.clear()}},ee=new X;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 q(n){let e=new Map;function t(o){let a=o.getAttribute("data-guid");if(a){let s=Qe();o.setAttribute("data-guid",s),e.set(a,s)}let r=o.children;for(let s=0;s<r.length;s++){let l=r[s];l instanceof HTMLElement&&t(l)}}return t(n),e}function te(n){let e=n.getAttribute("data-guid");return e||(e=Qe(),n.setAttribute("data-guid",e)),e}function B(n,e){return(e||document.body).querySelector(`[data-guid="${n}"]`)}function z(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 Xe(n,e,t,o,a){for(let[r,s]of Object.entries(e))try{if(!(r in n))continue;switch(s.type){case"number":n[r]=Number(s.value);break;case"string":n[r]=String(s.value);break;case"boolean":n[r]=s.value===!0||s.value==="true";break;case"element":let l=String(s.value);if(l===""||l==="null")n[r]=null;else{let i=t(l,r);if(n[r]=i,!i){let c=o||n.constructor.name||"Unknown",u=a?.getAttribute("data-script-id"),m=a?.id||a?.getAttribute("data-guid")||"Unknown",p=a?.tagName.toLowerCase()||"unknown",g=document.querySelector(`[data-guid="${l}"]`),y=g?.hasAttribute("data-prefab-id");console.error("[ParameterSerializer] \u274C Element reference not found:"),console.error(` \u2192 Parameter: "${r}"`),console.error(` \u2192 Script: "${c}"${u?` (id: ${u})`:""}`),console.error(` \u2192 Owner Element: <${p} id="${m}">`),console.error(` \u2192 Missing GUID: "${l}"`),console.error(` \u2192 Element in DOM: ${g?"YES":"NO"}${g?` <${g.tagName.toLowerCase()} id="${g.id}">`:""}`),console.error(` \u2192 Is prefab placeholder: ${y?"YES (data-prefab-id="+g?.getAttribute("data-prefab-id")+")":"NO"}`)}}break;default:console.warn(`[ParameterSerializer] Unknown parameter type: ${s.type}`)}}catch(l){console.error(`[ParameterSerializer] Error applying parameter "${r}":`,l)}}function et(n){return JSON.stringify(n).replace(/"/g,"'")}function tt(n,e,t){return(o,a)=>gt(o,n,e,a,t)}function gt(n,e,t,o,a){if(!n||n===""||n==="null")return null;let r=t?B(n,t):null;if(!r&&t&&(r=B(n)),!r&&!t&&(r=B(n)),!r&&a&&(r=a.findElementInCachedPrefabs(n),r&&console.log(`[ElementResolver] Resolved "${n}" by data-guid in cached prefab template`),r||(r=a.getCachedPrefabRoot(n),r&&console.log(`[ElementResolver] Resolved "${n}" as cached prefab root (prefab ID reference)`))),!r)return o||console.error(`[ElementResolver] Element not found for GUID: "${n}"`),null;let s=e.getElementByGuid(n);return s||(s=e.createElementObjectFromElement(r,n)),s||(console.error(`[ElementResolver] Failed to create ElementObject for GUID: "${n}"`),null)}function V(n,e){let t=n.querySelectorAll("[data-script-params]"),o=[];n.hasAttribute("data-script-params")&&o.push(n),o.push(...Array.from(t));for(let a of o)try{yt(a,e)}catch(r){console.error("[ParameterCloner] Error updating parameters:",r),console.error(" Script element:",a)}}function yt(n,e){let t=z(n);if(!t)return;let o=!1;for(let[a,r]of Object.entries(t))if(r.type==="element"){let s=String(r.value);if(e.has(s)){let l=e.get(s);r.value=l,o=!0}}if(o){let a=et(t);n.setAttribute("data-script-params",a)}}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 o of this.elementObjects.values())if(o.isActive){for(let a of o.components)if(!(!a.enabled||!a.scriptInstance.activeInHierarchy)){a.hasStarted||this.invokeStart(a);try{a.scriptInstance.update(t)}catch(r){console.error(`[ElementsManager] Error in update() for ${a.scriptId}:`,r)}}}}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 o=e.getAttribute("data-guid");o&&this.getOrRegisterElementObject(e,o);let a=[];for(let r=0;r<e.children.length;r++){let s=e.children[r];s instanceof HTMLElement&&s.hasAttribute("data-script-id")&&a.push(s)}a.length>0&&this.processScriptDivs(e,a,t);for(let r=0;r<e.children.length;r++){let s=e.children[r];s instanceof HTMLElement&&this.scanElement(s,t)}}getOrRegisterElementObject(e,t){let o=this.elementObjects.get(t);return o||(o=new S(e,t),this.elementObjects.set(t,o)),o}processScriptDivs(e,t,o){let a=te(e),r=this.getOrRegisterElementObject(e,a);for(let s of t)this.createComponent(r,s,o)}createComponent(e,t,o){let a=t.getAttribute("data-script-id");if(!a)return console.error("[ElementsManager] Script div missing data-script-id",t),null;let r=ee.get(a);if(!r)return null;te(t);try{let s=new r,l={elementObject:e,scriptElement:t,scriptInstance:s,scriptId:a,enabled:!0,hasStarted:!1};s.elementObject=e,s.scriptElement=t,e.addComponent(l);let i=z(t);if(i){let c=tt(this,o,this.prefabsManagerRef||void 0),u=r.name||a;Xe(s,i,c,u,t)}return l}catch(s){return console.error(`[ElementsManager] Error creating component "${a}":`,s),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 o=e.scriptInstance[t];typeof o=="function"&&o.call(e.scriptInstance)}catch(o){console.error(`[ElementsManager] Error in ${t}() for ${e.scriptId}:`,o)}}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 o=new S(e,t);return this.elementObjects.set(t,o),o}getOrCreateElementObject(e){if(this.elementObjects.has(e))return this.elementObjects.get(e);let t=B(e);if(!t)return null;let o=new S(t,e);this.elementObjects.set(e,o);let a=[];for(let r=0;r<t.children.length;r++){let s=t.children[r];s instanceof HTMLElement&&s.hasAttribute("data-script-id")&&a.push(s)}if(a.length>0)for(let r of a)this.createComponent(o,r,t);return o}setActive(e,t){let o=e.getAttribute("data-guid");if(!o){console.error("[ElementsManager] Element has no GUID:",e);return}let a=this.elementObjects.get(o);if(!a){console.warn("[ElementsManager] Element not managed:",e);return}if(a.isActive===t)return;if(t){let s=this.displayValues.get(e)||"";e.style.display=s}else this.displayValues.set(e,e.style.display),e.style.display="none";a.isActive=t;let r=this.getComponentsInElementAndChildren(e);for(let s of r)s.scriptInstance.updateActiveState()}getComponentsInElementAndChildren(e){let t=[],o=e.getAttribute("data-guid");if(o){let r=this.elementObjects.get(o);r&&t.push(...r.components)}let a=e.querySelectorAll("[data-guid]");for(let r of a){let s=r.getAttribute("data-guid");if(s){let l=this.elementObjects.get(s);l&&t.push(...l.components)}}return t}destroy(e){let t=e.getAttribute("data-guid");if(!t){e.remove();return}if(!this.elementObjects.get(t)){e.remove();return}let a=this.getComponentsInElementAndChildren(e);for(let s of a)s.scriptInstance.activeInHierarchy&&this.callLifecycleMethod(s,"onDisable"),this.callLifecycleMethod(s,"onDestroy");this.elementObjects.delete(t);let r=e.querySelectorAll("[data-guid]");for(let s of r){let l=s.getAttribute("data-guid");l&&this.elementObjects.delete(l)}e.remove()}instantiate(e){let t=e.cloneNode(!0);this.copyInlineStyles(e,t),this.prepareSpritesFunction&&this.prepareSpritesFunction(t).catch(r=>{console.error("[ElementsManager] Error preparing sprites for clone:",r)});let o=q(t);V(t,o),this.scanElement(t,t);let a=this.getComponentsInElementAndChildren(t);for(let r of a)this.callLifecycleMethod(r,"awake"),r.enabled&&r.scriptInstance.activeInHierarchy&&this.callLifecycleMethod(r,"onEnable"),this.invokeStart(r);return t}copyInlineStyles(e,t){e.style.cssText&&(t.style.cssText=e.style.cssText);let o=e.children,a=t.children;for(let r=0;r<o.length&&r<a.length;r++)o[r]instanceof HTMLElement&&a[r]instanceof HTMLElement&&this.copyInlineStyles(o[r],a[r])}cleanup(){this.stopUpdateLoop(),this.elementObjects.clear(),this.initialized=!1}},b=new ne;var S=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 o of this.components)o.scriptInstance instanceof e&&t.push(o.scriptInstance);return t}getEnabledComponents(){return this.components.filter(e=>e.enabled&&e.scriptInstance.activeInHierarchy)}setActive(e){b.setActive(this.element,e)}instantiate(){let t=b.instantiate(this.element).getAttribute("data-guid");if(!t)throw new Error("[ElementObject] Cloned element has no GUID");let o=b.getElementByGuid(t);if(!o)throw new Error("[ElementObject] Cloned element not found in ElementsManager");return o}};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 o=this.prefabCache.get(e);console.log(`[PrefabsManager] Using cached prefab: ${e}`);let a=o.cloneNode(!0);return this.copyInlineStyles(o,a),a}if(this.pendingLoads.has(e)){if(console.log(`[PrefabsManager] Waiting for pending load: ${e}`),await this.pendingLoads.get(e),this.prefabCache.has(e)){let o=this.prefabCache.get(e),a=o.cloneNode(!0);return this.copyInlineStyles(o,a),a}return console.error(`[PrefabsManager] Prefab not in cache after pending load: ${e}`),null}if(!this.loaderFunction)return console.error("[PrefabsManager] No loader function set. Call setLoader() first."),null;console.log(`[PrefabsManager] Loading prefab: ${e}`);let t=(async()=>{try{let o=await this.loaderFunction(e);if(!o)return console.error(`[PrefabsManager] Failed to load prefab: ${e}`),null;this.prefabCache.set(e,o),console.log(`[PrefabsManager] Prefab cached: ${e}`);let a=o.cloneNode(!0);return this.copyInlineStyles(o,a),a}catch(o){return console.error(`[PrefabsManager] Error loading prefab "${e}":`,o),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 o=e.children,a=t.children;for(let r=0;r<o.length&&r<a.length;r++)o[r]instanceof HTMLElement&&a[r]instanceof HTMLElement&&this.copyInlineStyles(o[r],a[r])}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 o=e.querySelectorAll("[data-prefab-id]");console.log(`[PrefabsManager] Found ${o.length} placeholders in scope`);for(let a of o)a.hasAttribute("data-prefab-id")&&await this.processPlaceholder(a);console.log(`[PrefabsManager] All prefab placeholders processed in: ${t}`)}async processPrefabPlaceholders(){await this.processPrefabPlaceholdersInScope(document)}async processPlaceholder(e){let t=e.getAttribute("data-prefab-id");if(!t){console.warn("[PrefabsManager] Skipping placeholder - data-prefab-id attribute missing or already processed",e);return}try{let o=await this.load(t);if(!o){console.error(`[PrefabsManager] Failed to load prefab for placeholder: ${t}`);return}let a=e.getAttribute("data-guid");console.log(`[PrefabsManager] Processing placeholder for ${t}:`),console.log(` - Placeholder: <${e.tagName.toLowerCase()} id="${e.id}">`),console.log(` - Placeholder GUID: ${a}`),console.log(` - Prefab root: <${o.tagName.toLowerCase()} id="${o.id}">`),console.log(` - Children to move: ${o.children.length}`);let r=q(o);V(o,r),console.log(` - Regenerated ${r.size} GUIDs for unique instance`),this.validatePrefabReferences(o,t);let s=0;for(;o.firstChild;)e.appendChild(o.firstChild),s++;console.log(` - Moved ${s} children to placeholder`),console.log(` - Placeholder now has ${e.children.length} children`),e.removeAttribute("data-prefab-id"),!e.className&&o.className&&(e.className=o.className);let l=e.querySelectorAll(".balancy-button-prepared");l.forEach(i=>{i.classList.remove("balancy-button-prepared")}),l.length>0&&console.log(` - Removed button markers from ${l.length} cloned buttons`),this.uiProcessor&&(console.log(" - Processing UI elements in placeholder..."),await this.uiProcessor(e),console.log(" - UI elements processed for placeholder"))}catch(o){console.error(`[PrefabsManager] Error processing placeholder for "${t}":`,o)}}clearCache(){this.prefabCache.clear()}async preload(e){console.log(`[PrefabsManager] Preloading ${e.length} prefabs...`);let t=e.map(o=>this.load(o));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,o]of this.prefabCache.entries()){if(o.getAttribute("data-guid")===e)return console.log(`[PrefabsManager] Found GUID "${e}" as root of cached prefab ${t}`),o;let a=o.querySelector(`[data-guid="${e}"]`);if(a)return console.log(`[PrefabsManager] Found GUID "${e}" inside cached prefab ${t}`),a}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}findPrefabReferencesInCache(e){let t=new Set;for(let[,o]of this.prefabCache.entries()){let a=o.querySelectorAll("[data-script-params]");for(let r of Array.from(a)){let s=r.getAttribute("data-script-params");if(s)try{let l=s.replace(/'/g,'"'),i=JSON.parse(l);for(let[,c]of Object.entries(i))if(c.type==="element"){let u=String(c.value);if(u&&u!==""&&u!=="null"){if(e.has(u)||o.getAttribute("data-guid")===u||o.querySelector(`[data-guid="${u}"]`))continue;t.add(u)}}}catch{}}}return Array.from(t)}validatePrefabReferences(e,t){let o=e.querySelectorAll("[data-guid]"),a=new Set,r=e.getAttribute("data-guid");r&&a.add(r),o.forEach(i=>{let c=i.getAttribute("data-guid");c&&a.add(c)});let s=e.querySelectorAll("[data-script-params]"),l=[];s.forEach(i=>{let c=i.getAttribute("data-script-params"),u=i.getAttribute("data-script-id")||"unknown",m=i.id||i.getAttribute("data-guid")||"unknown";if(c)try{let p=c.replace(/'/g,'"'),g=JSON.parse(p);for(let[y,$]of Object.entries(g))if($.type==="element"){let A=String($.value);A&&A!==""&&A!=="null"&&!a.has(A)&&(this.findElementInCachedPrefabs(A)||l.push({scriptId:u,elementId:m,param:y,guid:A}))}}catch{}}),l.length>0&&(console.warn(`[PrefabsManager] Prefab ${t} has ${l.length} broken element reference(s):`),l.forEach(i=>{console.warn(` \u2192 Script ${i.scriptId} (element: ${i.elementId})`),console.warn(` Parameter: "${i.param}" \u2192 Missing GUID: "${i.guid}"`)}),console.warn(" Tip: Re-save the prefab in the editor to fix stale references"))}},T=new re;b.instantiatePrefab=async function(n){let e=await T.load(n);return e?(console.info("INSTY +> ",e),this.instantiate(e)):null};b.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 o=this.getElementByGuid(t);return o||(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,o=e.children;for(let a=0;a<t.length&&a<o.length;a++)t[a]instanceof HTMLElement&&o[a]instanceof HTMLElement&&oe(t[a],o[a])}var W={},ue={},at=0,st=new N,ht=new G,it=new D,bt=new k,Et=new j,ct=()=>at,lt=()=>{at++},de=we(),ie=Je(),me=()=>{},ce=Te(ue,n=>me(n),ie.dispatchCustomMessage),ut=Me(ct,lt,ue,de),E=Ie(st,ut,ct,lt,ue,de),vt=Pe(ce),L=Se(E),{getActiveOffers:wt,getActiveGroupOffers:Pt,canBuyGroupOffer:pe,buyGroupOffer:Tt,buyOffer:Mt,buyShopSlot:It,getRewardedAdsWatchedForStoreItem:St,haveEnoughResources:At,getShopInfo:Lt}=Ae(E,L.getSystemProfileValue,L.getDocumentValue),x=Le(E),ae=Ce(E),se=Oe(E,L.getDocumentValue),I=Be(E),le=n=>it.get(n,E,d.GetLocalization),H=n=>ht.get(n,E,d.GetImageUrl),Ct=n=>bt.get(n,E,d.GetFileLocation),nt=n=>Et.get(n,E,d.GetPrefabContent),dt=_e(L.getDocumentValue),fe=Re(le),ge=xe(H),Ot=He(H,Z);b.setPrepareSpritesFunction(ge.prepareAllSprites);var mt=$e(E,pe,H),Bt=Ne(E,dt,J,K,fe.setLocalizedText),Rt=Ze(H),_=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 T.processPrefabPlaceholdersInScope(n),await fe.localizeAllElements(n),await Ot.prepareAllFonts(n),await ge.prepareAllSprites(n),await mt.prepareAllButtons(n),await Bt.prepareAllTexts(n),await Rt.prepareAllAudio(n),console.info(`[Balancy] All UI elements prepared for: ${e}`)},xt=()=>{document.querySelectorAll(`[data-button-action="${d.BuyGroupOffer}"]`).forEach(e=>{let t=parseInt(e.getAttribute("data-index")||"0",10)||0;pe(t).then(o=>{e.disabled=!o})})};me=Ye(xt);var rt=!1,ot=()=>ut(null,d.BalancyIsReady,{id:"none"});Object.assign(W,{NotificationType:C,PriceType:he,ItemType:R,TaskStatus:be,RequestAction:d,BuyButtonState:Ee,OfferGroupType:ve,NumberDisplayFormat:P,TimeDisplayFormat:O,TimePrecision:h,postMessage:de,_receiveMessageFromUnity:vt,handleResponse:ce,sendRequest:E,batchManager:st,getProfileValue:L.getProfileValue,getSystemProfileValue:L.getSystemProfileValue,getDocumentValue:L.getDocumentValue,getActiveOffers:wt,getActiveGroupOffers:Pt,canBuyGroupOffer:pe,buyGroupOffer:Tt,buyOffer:Mt,buyShopSlot:It,getRewardedAdsWatchedForStoreItem:St,haveEnoughResources:At,getShopInfo:Lt,getTasks:x.getTasks,activateTasks:x.activateTasks,deactivateTasks:x.deactivateTasks,restoreFailedTask:x.restoreFailedTask,claimTaskReward:x.claimTaskReward,getInventoryItemsCount:ae.getInventoryItemsCount,addInventoryItems:ae.addInventoryItems,removeInventoryItems:ae.removeInventoryItems,getBattlePassConfig:se.getBattlePassConfig,getBattlePassProgress:se.getBattlePassProgress,claimBattlePassReward:se.claimBattlePassReward,getCustomEventInfo:I.getCustomEventInfo,setCustomEventInfo:I.setCustomEventInfo,getCustomDocumentInfo:I.getCustomDocumentInfo,setCustomDocumentInfo:I.setCustomDocumentInfo,stopEventManually:I.stopEventManually,watchRewardedAd:I.watchRewardedAd,getProductInfo:I.getProductInfo,closeView:I.closeView,sendCustomMessage:I.sendCustomMessage,getLocalizedText:le,getImageUrl:H,getFileLocation:Ct,getPrefabContent:nt,setLocalizedText:fe.setLocalizedText,setImage:ge.setImage,formatTime:J,formatString:Ue,formatItemsCount:Fe,formatItemCount:Ve,shortenCount:Y,itemHasDecayEffect:F,itemGetBundleReward:je,getTimeLeft:K,formatDataTemplate:dt,injectFontFace:Z,findDomElement:We,balancyButtonClicked:mt.balancyButtonClicked,notificationReceived:me,subscribeToCustomMessages:ie.subscribeToCustomMessages,dispatchCustomMessage:ie.dispatchCustomMessage,sendIsReady:ot,delayIsReady:()=>{rt=!0},ElementBehaviour:U,ElementObject:S,ElementsManager:b,PrefabsManager:T,instantiatePrefabById:n=>b.instantiatePrefabById(n),prepareAllUIElements:_,initResponseHandler:()=>{if(W._responseHandlerInitialized)return;W._responseHandlerInitialized=!0;let n=new Map;Ke(ce,()=>_(),ot,rt,async()=>{try{console.info("[Balancy] Preloading mandatory localization keys..."),await Promise.all(qe.map(r=>le(r))),ze(r=>it.getCached(r)),console.info("[Balancy] Mandatory localization keys preloaded"),T.setUIProcessor(async r=>{await _(r)}),T.setLoader(async r=>{try{if(n.has(r)){console.info(`[Balancy] Using cached prefab: ${r}`);let m=n.get(r),p=m.cloneNode(!0);return oe(m,p),p}console.info(`[Balancy] Loading prefab for the first time: ${r}`);let s=await nt(r);if(console.info(`[Balancy] Received HTML content (length: ${s?.length||0})`),!s)return console.error(`[Balancy] No HTML content returned for prefab: ${r}`),null;let i=new DOMParser().parseFromString(s,"text/html"),c=i.body.firstElementChild;if(!c)return console.error(`[Balancy] No root element found in prefab body for: ${r}`),null;let u=i.head.querySelectorAll("style");return u.length>0&&u.forEach(m=>{let g=(m.textContent||"").replace(/\*\s*\{[^}]*\}/g,"").replace(/body\s*\{[^}]*\}/g,"").replace(/html\s*\{[^}]*\}/g,"");if(g=g.trim(),g){let y=document.createElement("style");y.textContent=g,y.setAttribute("data-prefab-id",r),document.head.appendChild(y)}else console.warn(`[Balancy] No styles left after filtering for prefab: ${r}`)}),console.info(`[Balancy] Processing UI elements for prefab ${r}...`),await _(c),console.info(`[Balancy] UI elements processed for prefab ${r}`),n.set(r,c),console.info("[Balancy] Prefab loaded and cached successfully:"),console.info(` - Root element: <${c.tagName.toLowerCase()} id="${c.id}">`),console.info(` - Children count: ${c.children.length}`),console.info(" - Full element:",c),c}catch(s){return console.error(`[Balancy] Error in prefab loader for "${r}":`,s),null}}),await T.processPrefabPlaceholders(),b.setPrefabsManager(T);let t=new Set,o=new Set,a=document.querySelectorAll("[data-script-params]");for(let r of Array.from(a)){let s=r.getAttribute("data-script-params");if(s)try{let l=s.replace(/'/g,'"'),i=JSON.parse(l);for(let[,c]of Object.entries(i))if(c.type==="element"){let u=String(c.value);u&&u!==""&&u!=="null"&&(document.querySelector(`[data-guid="${u}"]`)||o.add(u))}}catch{}}if(o.size>0){console.log(`[Balancy] Preloading ${o.size} prefab(s) referenced by script parameters:`,Array.from(o)),await T.preload(Array.from(o));for(let l of o)t.add(l);let r=0,s=5;for(;r<s;){let l=T.findPrefabReferencesInCache(t);if(l.length===0)break;console.log(`[Balancy] Preloading ${l.length} nested prefab dependency(ies) (depth ${r+1}):`,l),await T.preload(l);for(let i of l)t.add(i);r++}}b.initialize();try{let r=document.body.querySelector("[data-guid]");if(r){let s=r.getAttribute("data-guid");console.info(`[Balancy] Found root element with GUID: ${s}`);let l=b.getElementByGuid(s);if(l){let i=l.components;if(i.length>0){console.info(`[Balancy] Root element has ${i.length} component(s)`);let c=i[0].scriptInstance;if(typeof c.init=="function"){console.info("[Balancy] Calling init() on root script with balancyViewOwner");let u=window.balancyViewOwner;u?c.init(u):(console.warn("[Balancy] window.balancyViewOwner is not defined, calling init() without arguments"),c.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",Q):Q());typeof window<"u"&&(window.balancy=W);console.log("\u{1F389} [BRIDGE] Balancy WebView Bridge loaded successfully!");return balancy;})();
|