handler-playable-sdk 1.0.6 → 1.0.8

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,4 +1,4 @@
1
- import{c as Xi,d as we,e as Ji}from"./chunk-I5OOVR5U.js";import{i as Gt}from"./chunk-PW2FGMCO.js";import{c as Re,d as Bt,e as Ke,g as ba,h as Zi,j as va,k as ya,n as Qi,o as Ut,p as et,q as wa,r as en,s as xa}from"./chunk-HVKF2KYL.js";import{a as us}from"./chunk-JXBG6UFL.js";import{Application as jo}from"pixi.js";var De={};function qt(s,e,t=!1){De[s]||(De[s]=[]),De[s].push({fn:e,once:t})}function tn(s,e){if(De[s]){if(!e){delete De[s];return}De[s]=De[s].filter(t=>t.fn!==e)}}function Vt(s,...e){let t=De[s];if(t)for(let i of[...t])i.fn(...e),i.once&&tn(s,i.fn)}function pe(s,e){qt(s,e,!0)}var J=null,me=[],tt=null;function Ca(s){J=s,me=[],tt!==null&&(clearTimeout(tt),tt=null)}function Aa(){var s,e,t;return{endpoint:(J==null?void 0:J.endpoint)||"",transport:(J==null?void 0:J.transport)||"beacon",batchSize:(s=J==null?void 0:J.batchSize)!=null?s:10,flushIntervalMs:(e=J==null?void 0:J.flushIntervalMs)!=null?e:300,maxQueue:(t=J==null?void 0:J.maxQueue)!=null?t:200,debug:!!(J!=null&&J.debug)}}async function Sa(s,e,t,i){let n=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(s,new Blob([n],{type:"application/json"}));i&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){i&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0}),i&&console.log("[handler.telemetry] fetch",e)}catch(a){i&&console.warn("[handler.telemetry] fetch failed",a)}}function nn(s,e){let t=Aa();if(e&&t.endpoint){if(me.push(s),me.length>t.maxQueue&&(me=me.slice(me.length-t.maxQueue)),me.length>=t.batchSize){Ea();return}tt===null&&(tt=window.setTimeout(()=>{tt=null,Ea()},t.flushIntervalMs))}}async function Ea(){let s=Aa();if(!s.endpoint||me.length===0)return;let e=me.splice(0,s.batchSize);await Sa(s.endpoint,{events:e},s.transport,s.debug),me.length>0&&await Sa(s.endpoint,{events:me.splice(0,s.batchSize)},s.transport,s.debug)}function La(s){return Math.max(0,Math.min(1,s))}function gs(s){let e=String(s!=null?s:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),i=t?Number(t[1]):1.8;return n=>1+(i+1)*Math.pow(n-1,3)+i*Math.pow(n-1,2)}return t=>1-(1-t)*(1-t)}function wt(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function hs(s,e){let t=s==null?void 0:s[e];return typeof t=="number"?t:0}function Ta(s,e,t){try{s[e]=t}catch{}}function ms(s){let e=s==null?void 0:s.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,i=typeof e.y=="number"?e.y:1;return{x:t,y:i}}function ka(s,e){let t=s==null?void 0:s.scale;if(t)try{typeof t.set=="function"?t.set(e.x,e.y):(typeof t.x=="number"&&(t.x=e.x),typeof t.y=="number"&&(t.y=e.y))}catch{}}function Pa(s,e){let t=ms(s);if(!t)return{from:null,to:null};let i=null,n=null;return typeof e.scale=="number"?(i=e.scale,n=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(i=e.scale.x),typeof e.scale.y=="number"&&(n=e.scale.y)),typeof e.scaleX=="number"&&(i=e.scaleX),typeof e.scaleY=="number"&&(n=e.scaleY),i===null&&n===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:i!=null?i:t.x,y:n!=null?n:t.y}}}function Ma(){let s=new Set,e=new WeakMap,t=null,i=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),s.size>0&&i()})},n=d=>{var u;s.add(d);let p=(u=e.get(d.target))!=null?u:new Set;p.add(d),e.set(d.target,p),i()},a=d=>{s.delete(d);let p=e.get(d.target);p&&(p.delete(d),p.size===0&&e.delete(d.target))},r=d=>{d.killed||(d.killed=!0,a(d))},o=()=>{var p,u;let d=wt();for(let g of Array.from(s)){if(g.killed||g.paused)continue;let h=d-g.startMs-g.delayMs;if(h<0)continue;let m=g.durationMs>0?h/g.durationMs:1,f=La(m),b=g.repeat>=0?g.repeat+1:1,v=g.repeat>0?Math.min(Math.floor(m),b-1):0;if(g.repeat>0&&m>=1){let w=m-v;f=La(w)}let x=g.ease(f);g.yoyo&&v%2===1&&(x=1-x);for(let w of g.props)Ta(g.target,w.key,w.from+(w.to-w.from)*x);g.scaleFrom&&g.scaleTo&&ka(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*x,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*x});try{(p=g.onUpdate)==null||p.call(g)}catch{}if(m>=b){r(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(d,p,u)=>{var w;let g=Math.max(0,(typeof p.duration=="number"?p.duration:.5)*1e3),h=Math.max(0,(typeof p.delay=="number"?p.delay:0)*1e3+((w=u==null?void 0:u.delayMsOverride)!=null?w:0)),m=gs(p.ease),f=typeof p.repeat=="number"?Math.max(0,p.repeat|0):0,b=p.yoyo===!0,v=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),x=[];for(let T of Object.keys(p)){if(v.has(T))continue;let j=p[T];typeof j=="number"&&x.push({key:T,from:hs(d,T),to:j})}let y=Pa(d,p);return{target:d,startMs:wt(),delayMs:h,durationMs:g,ease:m,props:x,scaleFrom:y.from,scaleTo:y.to,repeat:f,yoyo:b,onUpdate:typeof p.onUpdate=="function"?p.onUpdate:void 0,onComplete:typeof p.onComplete=="function"?p.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(d,p){let u=l(d,p);return n(u),{kill:()=>r(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=wt())},resume:()=>{var m;if(!u.paused)return;let g=(m=u.pauseAtMs)!=null?m:wt(),h=wt()-g;u.startMs+=h,u.paused=!1,u.pauseAtMs=null},isActive:()=>!u.killed&&!u.paused}},fromTo(d,p,u){return c.set(d,p),c.to(d,u)},set(d,p){if(!d||!p)return;for(let g of Object.keys(p)){let h=p[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof h=="number"&&Ta(d,g,h)}let u=Pa(d,p);u.to&&ka(d,u.to)},killTweensOf(d){let p=e.get(d);if(p)for(let u of Array.from(p))r(u)},timeline(d={}){let p=[],u=0,g=!1,h=[],m=v=>{if(typeof v=="number")return Math.max(0,v*1e3);let x=typeof v=="string"?v.trim():"";return x.startsWith("+=")?u+Math.max(0,Number(x.slice(2))*1e3||0):x?Math.max(0,Number(x)*1e3||0):u},f=v=>{p.push(v);let x=Math.max(0,(typeof v.vars.duration=="number"?v.vars.duration:.5)*1e3);u=Math.max(u,v.atMs+x)},b={to(v,x,y){return f({kind:"to",target:v,vars:x,atMs:m(y)}),b},fromTo(v,x,y,w){return f({kind:"fromTo",target:v,vars:y,from:x,atMs:m(w)}),b},play(){var v,x;if(g)return b;g=!0,h=[];for(let y of p)y.kind==="fromTo"&&c.set(y.target,(v=y.from)!=null?v:{}),h.push(c.to(y.target,{...y.vars,delay:y.atMs/1e3+((x=y.vars.delay)!=null?x:0)}));return b},pause(){for(let v of h)v.pause();return b},kill(){for(let v of h)v.kill();h=[],g=!1}};return d.paused||b.play(),b}};return c}function Ia(){if(typeof window=="undefined")return;let s=window;if(!s.gsap)try{s.gsap=Ma()}catch{}}var ja={name:"handler-playable-sdk",version:"1.0.6",type:"module",description:"Handler Playable SDK v0.1 with contract-aligned surface (root sandbox, canonical event envelope).",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./pixi":{types:"./dist/pixi/index.d.ts",import:"./dist/pixi/index.js",require:"./dist/pixi/index.cjs"},"./pixi/index.css":{import:"./dist/pixi/index.css",require:"./dist/pixi/index.css"},"./three":{types:"./dist/three/index.d.ts",import:"./dist/three/index.js",require:"./dist/three/index.cjs"},"./cli":{types:"./dist/cli/index.d.ts",import:"./dist/cli/index.js",require:"./dist/cli/index.cjs"}},bin:{"handler-student-helper":"./bin/student-helper.mjs","handler-validate":"./bin/validate.mjs","handler-sync-screens":"./bin/sync-screens.mjs","handler-brand-dna":"./bin/brand-dna.mjs","handler-setup-library":"./bin/setup-library.mjs","handler-screen-helper":"./bin/screen-helper.mjs"},scripts:{prebuild:"python3 src/preview/build-css.py",build:"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --minify --external lottie-web --external jszip && npm run create-mjs-symlinks && npm run postbuild-cli && npm run obfuscate && npm run postbuild",postbuild:"python3 src/preview/copy-css-to-dist.py","postbuild-cli":"cp src/cli/*.mjs dist/cli/ && chmod +x dist/cli/*.mjs && chmod +x bin/*.mjs","create-mjs-symlinks":"cd dist && ln -sf index.js index.mjs && cd pixi && ln -sf index.js index.mjs && cd ../three && ln -sf index.js index.mjs","build:dev":"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --external lottie-web --external jszip && npm run create-mjs-symlinks && npm run postbuild-cli",obfuscate:"javascript-obfuscator dist/pixi/index.js --output dist/pixi/index.js --config obfuscator.config.json && javascript-obfuscator dist/three/index.js --output dist/three/index.js --config obfuscator.config.json && javascript-obfuscator dist/cli/index.js --output dist/cli/index.js --config obfuscator.config.json && npm run obfuscate-cli","obfuscate-cli":'for file in dist/cli/*.mjs; do javascript-obfuscator "$file" --output "$file" --config obfuscator.config.json; done',lint:"eslint 'src/**/*.{ts,tsx}'",typecheck:"tsc --noEmit",prepublishOnly:"npm run build","publish:update":"node scripts/publish-and-update.cjs patch","publish:update:minor":"node scripts/publish-and-update.cjs minor","publish:update:major":"node scripts/publish-and-update.cjs major"},author:"Handler",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/HandlerAIGames/handler-playable-sdk.git"},files:["dist","bin","LICENSE","README.md"],peerDependencies:{"lottie-web":"^5.0.0","pixi.js":"^8.0.0",three:"^0.182.0"},peerDependenciesMeta:{"pixi.js":{optional:!0},three:{optional:!0},"lottie-web":{optional:!0}},devDependencies:{"@types/three":"^0.182.0",eslint:"^9.39.2","javascript-obfuscator":"^5.1.0","pixi.js":"8.8.1",three:"^0.182.0","ts-node":"^10.9.2",tsup:"^8.4.0",typescript:"^5.7.2","typescript-eslint":"^8.53.0"},dependencies:{"@google/genai":"^1.35.0","@google/generative-ai":"^0.24.1",jszip:"^3.10.1",sharp:"^0.34.5"}};var ue=0,bs=ue++,_a=ue++,Oa=ue++,za=ue++,Ra=ue++,Da=ue++,$a=ue++,Ha=ue++,Na=ue++,Fa=ue++,Ba=ue++,Ua=ue++,Y=bs;function Ga(){return Y===_a}function qa(){return Y===Oa}function Va(){return Y===za}function Wa(){return Y===Ra}function it(){return Y===Da}function nt(){return Y===$a}function Ya(){return Y===Ha}function Ka(){return Y===Na}function Xa(){return Y===Fa}function an(){return Y===Ba}function rn(){return Y===Ua}function Ja(){let s=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(s==="mraid")try{mraid.getState(),Y=_a;return}catch{}else if(s==="dapi")try{dapi.isReady(),Y=Oa;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(Y=za)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(Y=Ra)}catch{}else if(e==="mintegral")window.gameReady&&(Y=Da);else if(e==="tapjoy")window.TJ_API&&(Y=$a);else if(e==="tiktok")window.openAppStore&&(Y=Ha);else if(e==="smadex")try{window.smxTracking&&(Y=Na)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(Y=Fa)}catch{}else e==="vungle"?Y=Ba:(s==="nucleo"||e==="nucleo")&&(Y=Ua)}import sn from"lottie-web";var Za=sn;typeof window!="undefined"&&(window.lottie=sn,window.__baseLottie=sn);function Z(s,e){let t=(n,a)=>a===0?n:t(a,n%a),i=t(s,e);return`${s/i}:${e/i}`}var sl=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:Z(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:Z(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:Z(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:Z(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:Z(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:Z(360,780)}],ol=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:Z(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:Z(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:Z(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:Z(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:Z(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:Z(412,915)}],ll=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:Z(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:Z(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:Z(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:Z(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:Z(800,1280)}],on=[{id:"playable-portrait",label:"Playable Portrait",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"mraid-320x480",label:"MRAID 320\xD7480",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"playable",ratio:Z(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:Z(768,1024),mraidScale:.7}];var Qa=[...on],er=[{category:"playable",label:"Playable Ad",devices:on}],ln=on[0];function at(s){return Qa.find(e=>e.id===s)||ln}function cl(s){return Qa.filter(e=>e.category===s)}var $e=class{async updateProperty(e,t,i,n={}){var l,c,d;console.log("[PropertyUpdateManager] Updating:",e,t,i);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let r=a(e);if(!r){console.error("[PropertyUpdateManager] Config not found for:",e);return}Re({objectId:e,path:t,value:i},{persist:!0});let o=window.applyEditableObjectConfig;if(typeof o=="function"){let p=window.__editableConfig,u=(d=(c=(l=p==null?void 0:p.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:r;await o(e,u),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(e),n.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let i=t.split("."),n=e;for(let a of i)if(n&&typeof n=="object"&&a in n)n=n[a];else return;return n}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function cn(s){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let i=(a=t.target.files)==null?void 0:a[0];if(!i)return;let n=new FileReader;n.onload=async()=>{let r=n.result,o=s.category||"misc",c=`${(s.objectId||"new_asset").replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")||"new_asset"}_uploaded`;try{let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:o,filename:`${c}.png`,data:r,overwrite:!0})})).json();if(!(p!=null&&p.success)){alert(`Upload failed: ${(p==null?void 0:p.error)||"Unknown error"}`);return}let u=window.addAssetToRegistry;typeof u=="function"&&u(o,`${c}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch{}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),await s.onApply(p.path)}catch(d){console.error("[QuickActionsBar] Upload error:",d),alert("Upload failed. Check console.")}},n.readAsDataURL(i)},e.click()}var Wt=class{constructor(){this.updateManager=new $e}async handleAction(e,t,i){console.log("[QuickActionsBar] Action:",e,t,i);let n=window.getEditableObjectConfig;if(typeof n!="function")return;let a=n(t);if(!a)return;let r=this.updateManager.getNestedProperty(a,i);if(e==="ai-convert"||e==="upload"||e==="library"){let o=i==="ui.text"||i==="render.asset.path",l=i==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&i!=="render.asset.path"&&(i="render.asset.path"))}switch(e){case"library":this.openLibrary(t,i,r);break;case"ai-edit":this.openAIEditor(t,i,r);break;case"upload":this.openUpload(t,i);break;case"reset":await this.resetToDefault(t,i);break;case"ai-convert":this.handleAiConvert(t,i,r);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var i,n;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let r=((n=(i=t.transform)==null?void 0:i.scale)!=null?n:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",r),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",r)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let i=window.getEditableAssets;if(typeof i!="function")return;let n=i();if(!n||!n.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!n.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),n.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),n.categories&&!n.categories.includes(d)&&n.categories.push(d),n.libraryAssets&&!n.libraryAssets[d]&&(n.libraryAssets[d]=[]);let p=window.reRenderAssetLibrary;typeof p=="function"&&p()}}openLibrary(e,t,i){var a;let n=window.__debugContext;if(n){if(n.activeTab!=="library"){n.activeTab="library";let r=window.__updateWorkbenchTabs;typeof r=="function"&&r()}if(n.libraryPanel){let r=window.getEditableObjectConfig,o=r==null?void 0:r(e),l=(a=o==null?void 0:o.identity)==null?void 0:a.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),n.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let a=t.split(".").pop()||t;n(a,`Edit ${a} for ${e}`,i,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var r;let i=window.getEditableObjectConfig,n=i==null?void 0:i(e),a=((r=n==null?void 0:n.identity)==null?void 0:r.category)||(t.split(".")[0]==="render"?"environment":"ui");cn({objectId:e,category:a,onApply:async o=>{var d,p;await this.updateManager.updateProperty(e,t,o);let l=window.__debugContext;(p=(d=l==null?void 0:l.options)==null?void 0:d.onPropertyChange)==null||p.call(d,e,t,o);let c=window.__highlightLibrarySlot;typeof c=="function"&&setTimeout(()=>{c(e,a)},500),window.dispatchEvent(new CustomEvent("inspector:refresh"))}})}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let i=await this.getDefaultValue(e,t);i!==void 0?(await this.updateManager.updateProperty(e,t,i),console.log("[QuickActionsBar] Reset to default value:",i)):alert("No default value found for this property.")}catch(i){console.error("[QuickActionsBar] Failed to reset to default:",i),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let i=t.split(".");if(i.length<2)return;let n=i[0],a=i.slice(1),r=window.__editableConfig;if(!(r!=null&&r.schemas))return;let o=null;if(r.schemas instanceof Map?o=r.schemas.get(n):typeof r.schemas=="object"&&(o=r.schemas[n]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of a)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let r=`A single, high-quality, high-detail game UI icon/asset representing "${String(i||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",o),n(e,r,"",{objectId:e,path:o});let l=window.__debugContext;if(l){l.activeTab="ai";let c=window.__updateWorkbenchTabs;typeof c=="function"&&c()}}else console.warn("[QuickActionsBar] AI Editor not available")}};var vs=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],ys=["environment","ui","character","system","backgrounds"],ws=["bg","world","ui"],tr={SwerveMove:{speed:5,sensitivity:1,directionMode:"dominantAxis",axis:"both",bounds:{left:-400,right:400,top:-300,bottom:300}},DragToWin:{targetId:"",successDistance:80},DragSnap:{snapTargetId:"",snapDistance:40},JoystickMove:{speed:6,bounds:{left:-400,right:400,top:-300,bottom:300}}},Yt=class{constructor(){this.modal=null;this.state=null}open(e){this.state=this.createInitialState(e),this.createModal(),document.body.appendChild(this.modal),this.attachEventListeners(),this.updateStepUI()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),window.__wizardAssetPicker=null,this.modal=null,this.state=null}createInitialState(e){return{step:1,objectType:"sprite",instanceId:"",displayName:"",category:"environment",screenId:e.screenId,layer:"world",positionMode:"static",anchorPreset:"center",anchorX:.5,anchorY:.5,positionX:0,positionY:0,offsetX:0,offsetY:0,scale:.2,rotation:0,zIndex:0,assetPath:"",tint:"",alpha:1,text:"",font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",graphicsWidth:200,graphicsHeight:200,graphicsFill:"#FFFFFF",graphicsAlpha:1,interactionEnabled:!1,dragEnabled:!1,hoverEnabled:!1,clickEnabled:!1,logicId:"",logicPropsRaw:""}}createModal(){let e=document.createElement("div");e.className="wizard-modal",e.innerHTML=`
1
+ import{c as Xi,d as we,e as Ji}from"./chunk-I5OOVR5U.js";import{i as Gt}from"./chunk-PW2FGMCO.js";import{c as Re,d as Bt,e as Ke,g as ba,h as Zi,j as va,k as ya,n as Qi,o as Ut,p as et,q as wa,r as en,s as xa}from"./chunk-HVKF2KYL.js";import{a as us}from"./chunk-JXBG6UFL.js";import{Application as jo}from"pixi.js";var De={};function qt(s,e,t=!1){De[s]||(De[s]=[]),De[s].push({fn:e,once:t})}function tn(s,e){if(De[s]){if(!e){delete De[s];return}De[s]=De[s].filter(t=>t.fn!==e)}}function Vt(s,...e){let t=De[s];if(t)for(let i of[...t])i.fn(...e),i.once&&tn(s,i.fn)}function pe(s,e){qt(s,e,!0)}var J=null,me=[],tt=null;function Ca(s){J=s,me=[],tt!==null&&(clearTimeout(tt),tt=null)}function Aa(){var s,e,t;return{endpoint:(J==null?void 0:J.endpoint)||"",transport:(J==null?void 0:J.transport)||"beacon",batchSize:(s=J==null?void 0:J.batchSize)!=null?s:10,flushIntervalMs:(e=J==null?void 0:J.flushIntervalMs)!=null?e:300,maxQueue:(t=J==null?void 0:J.maxQueue)!=null?t:200,debug:!!(J!=null&&J.debug)}}async function Sa(s,e,t,i){let n=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(s,new Blob([n],{type:"application/json"}));i&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){i&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0}),i&&console.log("[handler.telemetry] fetch",e)}catch(a){i&&console.warn("[handler.telemetry] fetch failed",a)}}function nn(s,e){let t=Aa();if(e&&t.endpoint){if(me.push(s),me.length>t.maxQueue&&(me=me.slice(me.length-t.maxQueue)),me.length>=t.batchSize){Ea();return}tt===null&&(tt=window.setTimeout(()=>{tt=null,Ea()},t.flushIntervalMs))}}async function Ea(){let s=Aa();if(!s.endpoint||me.length===0)return;let e=me.splice(0,s.batchSize);await Sa(s.endpoint,{events:e},s.transport,s.debug),me.length>0&&await Sa(s.endpoint,{events:me.splice(0,s.batchSize)},s.transport,s.debug)}function La(s){return Math.max(0,Math.min(1,s))}function gs(s){let e=String(s!=null?s:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),i=t?Number(t[1]):1.8;return n=>1+(i+1)*Math.pow(n-1,3)+i*Math.pow(n-1,2)}return t=>1-(1-t)*(1-t)}function wt(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function hs(s,e){let t=s==null?void 0:s[e];return typeof t=="number"?t:0}function Ta(s,e,t){try{s[e]=t}catch{}}function ms(s){let e=s==null?void 0:s.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,i=typeof e.y=="number"?e.y:1;return{x:t,y:i}}function ka(s,e){let t=s==null?void 0:s.scale;if(t)try{typeof t.set=="function"?t.set(e.x,e.y):(typeof t.x=="number"&&(t.x=e.x),typeof t.y=="number"&&(t.y=e.y))}catch{}}function Pa(s,e){let t=ms(s);if(!t)return{from:null,to:null};let i=null,n=null;return typeof e.scale=="number"?(i=e.scale,n=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(i=e.scale.x),typeof e.scale.y=="number"&&(n=e.scale.y)),typeof e.scaleX=="number"&&(i=e.scaleX),typeof e.scaleY=="number"&&(n=e.scaleY),i===null&&n===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:i!=null?i:t.x,y:n!=null?n:t.y}}}function Ma(){let s=new Set,e=new WeakMap,t=null,i=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),s.size>0&&i()})},n=d=>{var u;s.add(d);let p=(u=e.get(d.target))!=null?u:new Set;p.add(d),e.set(d.target,p),i()},a=d=>{s.delete(d);let p=e.get(d.target);p&&(p.delete(d),p.size===0&&e.delete(d.target))},r=d=>{d.killed||(d.killed=!0,a(d))},o=()=>{var p,u;let d=wt();for(let g of Array.from(s)){if(g.killed||g.paused)continue;let h=d-g.startMs-g.delayMs;if(h<0)continue;let m=g.durationMs>0?h/g.durationMs:1,f=La(m),b=g.repeat>=0?g.repeat+1:1,v=g.repeat>0?Math.min(Math.floor(m),b-1):0;if(g.repeat>0&&m>=1){let w=m-v;f=La(w)}let x=g.ease(f);g.yoyo&&v%2===1&&(x=1-x);for(let w of g.props)Ta(g.target,w.key,w.from+(w.to-w.from)*x);g.scaleFrom&&g.scaleTo&&ka(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*x,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*x});try{(p=g.onUpdate)==null||p.call(g)}catch{}if(m>=b){r(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(d,p,u)=>{var w;let g=Math.max(0,(typeof p.duration=="number"?p.duration:.5)*1e3),h=Math.max(0,(typeof p.delay=="number"?p.delay:0)*1e3+((w=u==null?void 0:u.delayMsOverride)!=null?w:0)),m=gs(p.ease),f=typeof p.repeat=="number"?Math.max(0,p.repeat|0):0,b=p.yoyo===!0,v=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),x=[];for(let T of Object.keys(p)){if(v.has(T))continue;let j=p[T];typeof j=="number"&&x.push({key:T,from:hs(d,T),to:j})}let y=Pa(d,p);return{target:d,startMs:wt(),delayMs:h,durationMs:g,ease:m,props:x,scaleFrom:y.from,scaleTo:y.to,repeat:f,yoyo:b,onUpdate:typeof p.onUpdate=="function"?p.onUpdate:void 0,onComplete:typeof p.onComplete=="function"?p.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(d,p){let u=l(d,p);return n(u),{kill:()=>r(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=wt())},resume:()=>{var m;if(!u.paused)return;let g=(m=u.pauseAtMs)!=null?m:wt(),h=wt()-g;u.startMs+=h,u.paused=!1,u.pauseAtMs=null},isActive:()=>!u.killed&&!u.paused}},fromTo(d,p,u){return c.set(d,p),c.to(d,u)},set(d,p){if(!d||!p)return;for(let g of Object.keys(p)){let h=p[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof h=="number"&&Ta(d,g,h)}let u=Pa(d,p);u.to&&ka(d,u.to)},killTweensOf(d){let p=e.get(d);if(p)for(let u of Array.from(p))r(u)},timeline(d={}){let p=[],u=0,g=!1,h=[],m=v=>{if(typeof v=="number")return Math.max(0,v*1e3);let x=typeof v=="string"?v.trim():"";return x.startsWith("+=")?u+Math.max(0,Number(x.slice(2))*1e3||0):x?Math.max(0,Number(x)*1e3||0):u},f=v=>{p.push(v);let x=Math.max(0,(typeof v.vars.duration=="number"?v.vars.duration:.5)*1e3);u=Math.max(u,v.atMs+x)},b={to(v,x,y){return f({kind:"to",target:v,vars:x,atMs:m(y)}),b},fromTo(v,x,y,w){return f({kind:"fromTo",target:v,vars:y,from:x,atMs:m(w)}),b},play(){var v,x;if(g)return b;g=!0,h=[];for(let y of p)y.kind==="fromTo"&&c.set(y.target,(v=y.from)!=null?v:{}),h.push(c.to(y.target,{...y.vars,delay:y.atMs/1e3+((x=y.vars.delay)!=null?x:0)}));return b},pause(){for(let v of h)v.pause();return b},kill(){for(let v of h)v.kill();h=[],g=!1}};return d.paused||b.play(),b}};return c}function Ia(){if(typeof window=="undefined")return;let s=window;if(!s.gsap)try{s.gsap=Ma()}catch{}}var ja={name:"handler-playable-sdk",version:"1.0.8",type:"module",description:"Handler Playable SDK v0.1 with contract-aligned surface (root sandbox, canonical event envelope).",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./pixi":{types:"./dist/pixi/index.d.ts",import:"./dist/pixi/index.js",require:"./dist/pixi/index.cjs"},"./pixi/index.css":{import:"./dist/pixi/index.css",require:"./dist/pixi/index.css"},"./three":{types:"./dist/three/index.d.ts",import:"./dist/three/index.js",require:"./dist/three/index.cjs"},"./cli":{types:"./dist/cli/index.d.ts",import:"./dist/cli/index.js",require:"./dist/cli/index.cjs"}},bin:{"handler-student-helper":"./bin/student-helper.mjs","handler-validate":"./bin/validate.mjs","handler-sync-screens":"./bin/sync-screens.mjs","handler-brand-dna":"./bin/brand-dna.mjs","handler-setup-library":"./bin/setup-library.mjs","handler-screen-helper":"./bin/screen-helper.mjs"},scripts:{prebuild:"python3 src/preview/build-css.py",build:"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --minify --external lottie-web --external jszip && npm run create-mjs-symlinks && npm run postbuild-cli && npm run obfuscate && npm run postbuild",postbuild:"python3 src/preview/copy-css-to-dist.py","postbuild-cli":"cp src/cli/*.mjs dist/cli/ && chmod +x dist/cli/*.mjs && chmod +x bin/*.mjs","create-mjs-symlinks":"cd dist && ln -sf index.js index.mjs && cd pixi && ln -sf index.js index.mjs && cd ../three && ln -sf index.js index.mjs","build:dev":"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --external lottie-web --external jszip && npm run create-mjs-symlinks && npm run postbuild-cli",obfuscate:"javascript-obfuscator dist/pixi/index.js --output dist/pixi/index.js --config obfuscator.config.json && javascript-obfuscator dist/three/index.js --output dist/three/index.js --config obfuscator.config.json && javascript-obfuscator dist/cli/index.js --output dist/cli/index.js --config obfuscator.config.json && npm run obfuscate-cli","obfuscate-cli":'for file in dist/cli/*.mjs; do javascript-obfuscator "$file" --output "$file" --config obfuscator.config.json; done',lint:"eslint 'src/**/*.{ts,tsx}'",typecheck:"tsc --noEmit",prepublishOnly:"npm run build","publish:update":"node scripts/publish-and-update.cjs patch","publish:update:minor":"node scripts/publish-and-update.cjs minor","publish:update:major":"node scripts/publish-and-update.cjs major"},author:"Handler",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/HandlerAIGames/handler-playable-sdk.git"},files:["dist","bin","LICENSE","README.md"],peerDependencies:{"lottie-web":"^5.0.0","pixi.js":"^8.0.0",three:"^0.182.0"},peerDependenciesMeta:{"pixi.js":{optional:!0},three:{optional:!0},"lottie-web":{optional:!0}},devDependencies:{"@types/three":"^0.182.0",eslint:"^9.39.2","javascript-obfuscator":"^5.1.0","pixi.js":"8.8.1",three:"^0.182.0","ts-node":"^10.9.2",tsup:"^8.4.0",typescript:"^5.7.2","typescript-eslint":"^8.53.0"},dependencies:{"@google/genai":"^1.35.0","@google/generative-ai":"^0.24.1",jszip:"^3.10.1",sharp:"^0.34.5"}};var ue=0,bs=ue++,_a=ue++,Oa=ue++,za=ue++,Ra=ue++,Da=ue++,$a=ue++,Ha=ue++,Na=ue++,Fa=ue++,Ba=ue++,Ua=ue++,Y=bs;function Ga(){return Y===_a}function qa(){return Y===Oa}function Va(){return Y===za}function Wa(){return Y===Ra}function it(){return Y===Da}function nt(){return Y===$a}function Ya(){return Y===Ha}function Ka(){return Y===Na}function Xa(){return Y===Fa}function an(){return Y===Ba}function rn(){return Y===Ua}function Ja(){let s=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(s==="mraid")try{mraid.getState(),Y=_a;return}catch{}else if(s==="dapi")try{dapi.isReady(),Y=Oa;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(Y=za)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(Y=Ra)}catch{}else if(e==="mintegral")window.gameReady&&(Y=Da);else if(e==="tapjoy")window.TJ_API&&(Y=$a);else if(e==="tiktok")window.openAppStore&&(Y=Ha);else if(e==="smadex")try{window.smxTracking&&(Y=Na)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(Y=Fa)}catch{}else e==="vungle"?Y=Ba:(s==="nucleo"||e==="nucleo")&&(Y=Ua)}import sn from"lottie-web";var Za=sn;typeof window!="undefined"&&(window.lottie=sn,window.__baseLottie=sn);function Z(s,e){let t=(n,a)=>a===0?n:t(a,n%a),i=t(s,e);return`${s/i}:${e/i}`}var sl=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:Z(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:Z(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:Z(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:Z(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:Z(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:Z(360,780)}],ol=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:Z(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:Z(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:Z(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:Z(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:Z(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:Z(412,915)}],ll=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:Z(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:Z(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:Z(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:Z(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:Z(800,1280)}],on=[{id:"playable-portrait",label:"Playable Portrait",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"mraid-320x480",label:"MRAID 320\xD7480",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"playable",ratio:Z(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:Z(768,1024),mraidScale:.7}];var Qa=[...on],er=[{category:"playable",label:"Playable Ad",devices:on}],ln=on[0];function at(s){return Qa.find(e=>e.id===s)||ln}function cl(s){return Qa.filter(e=>e.category===s)}var $e=class{async updateProperty(e,t,i,n={}){var l,c,d;console.log("[PropertyUpdateManager] Updating:",e,t,i);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let r=a(e);if(!r){console.error("[PropertyUpdateManager] Config not found for:",e);return}Re({objectId:e,path:t,value:i},{persist:!0});let o=window.applyEditableObjectConfig;if(typeof o=="function"){let p=window.__editableConfig,u=(d=(c=(l=p==null?void 0:p.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:r;await o(e,u),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(e),n.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let i=t.split("."),n=e;for(let a of i)if(n&&typeof n=="object"&&a in n)n=n[a];else return;return n}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function cn(s){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let i=(a=t.target.files)==null?void 0:a[0];if(!i)return;let n=new FileReader;n.onload=async()=>{let r=n.result,o=s.category||"misc",c=`${(s.objectId||"new_asset").replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")||"new_asset"}_uploaded`;try{let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:o,filename:`${c}.png`,data:r,overwrite:!0})})).json();if(!(p!=null&&p.success)){alert(`Upload failed: ${(p==null?void 0:p.error)||"Unknown error"}`);return}let u=window.addAssetToRegistry;typeof u=="function"&&u(o,`${c}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch{}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),await s.onApply(p.path)}catch(d){console.error("[QuickActionsBar] Upload error:",d),alert("Upload failed. Check console.")}},n.readAsDataURL(i)},e.click()}var Wt=class{constructor(){this.updateManager=new $e}async handleAction(e,t,i){console.log("[QuickActionsBar] Action:",e,t,i);let n=window.getEditableObjectConfig;if(typeof n!="function")return;let a=n(t);if(!a)return;let r=this.updateManager.getNestedProperty(a,i);if(e==="ai-convert"||e==="upload"||e==="library"){let o=i==="ui.text"||i==="render.asset.path",l=i==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&i!=="render.asset.path"&&(i="render.asset.path"))}switch(e){case"library":this.openLibrary(t,i,r);break;case"ai-edit":this.openAIEditor(t,i,r);break;case"upload":this.openUpload(t,i);break;case"reset":await this.resetToDefault(t,i);break;case"ai-convert":this.handleAiConvert(t,i,r);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var i,n;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let r=((n=(i=t.transform)==null?void 0:i.scale)!=null?n:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",r),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",r)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let i=window.getEditableAssets;if(typeof i!="function")return;let n=i();if(!n||!n.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!n.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),n.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),n.categories&&!n.categories.includes(d)&&n.categories.push(d),n.libraryAssets&&!n.libraryAssets[d]&&(n.libraryAssets[d]=[]);let p=window.reRenderAssetLibrary;typeof p=="function"&&p()}}openLibrary(e,t,i){var a;let n=window.__debugContext;if(n){if(n.activeTab!=="library"){n.activeTab="library";let r=window.__updateWorkbenchTabs;typeof r=="function"&&r()}if(n.libraryPanel){let r=window.getEditableObjectConfig,o=r==null?void 0:r(e),l=(a=o==null?void 0:o.identity)==null?void 0:a.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),n.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let a=t.split(".").pop()||t;n(a,`Edit ${a} for ${e}`,i,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var r;let i=window.getEditableObjectConfig,n=i==null?void 0:i(e),a=((r=n==null?void 0:n.identity)==null?void 0:r.category)||(t.split(".")[0]==="render"?"environment":"ui");cn({objectId:e,category:a,onApply:async o=>{var d,p;await this.updateManager.updateProperty(e,t,o);let l=window.__debugContext;(p=(d=l==null?void 0:l.options)==null?void 0:d.onPropertyChange)==null||p.call(d,e,t,o);let c=window.__highlightLibrarySlot;typeof c=="function"&&setTimeout(()=>{c(e,a)},500),window.dispatchEvent(new CustomEvent("inspector:refresh"))}})}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let i=await this.getDefaultValue(e,t);i!==void 0?(await this.updateManager.updateProperty(e,t,i),console.log("[QuickActionsBar] Reset to default value:",i)):alert("No default value found for this property.")}catch(i){console.error("[QuickActionsBar] Failed to reset to default:",i),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let i=t.split(".");if(i.length<2)return;let n=i[0],a=i.slice(1),r=window.__editableConfig;if(!(r!=null&&r.schemas))return;let o=null;if(r.schemas instanceof Map?o=r.schemas.get(n):typeof r.schemas=="object"&&(o=r.schemas[n]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of a)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let r=`A single, high-quality, high-detail game UI icon/asset representing "${String(i||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",o),n(e,r,"",{objectId:e,path:o});let l=window.__debugContext;if(l){l.activeTab="ai";let c=window.__updateWorkbenchTabs;typeof c=="function"&&c()}}else console.warn("[QuickActionsBar] AI Editor not available")}};var vs=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],ys=["environment","ui","character","system","backgrounds"],ws=["bg","world","ui"],tr={SwerveMove:{speed:5,sensitivity:1,directionMode:"dominantAxis",axis:"both",bounds:{left:-400,right:400,top:-300,bottom:300}},DragToWin:{targetId:"",successDistance:80},DragSnap:{snapTargetId:"",snapDistance:40},JoystickMove:{speed:6,bounds:{left:-400,right:400,top:-300,bottom:300}}},Yt=class{constructor(){this.modal=null;this.state=null}open(e){this.state=this.createInitialState(e),this.createModal(),document.body.appendChild(this.modal),this.attachEventListeners(),this.updateStepUI()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),window.__wizardAssetPicker=null,this.modal=null,this.state=null}createInitialState(e){return{step:1,objectType:"sprite",instanceId:"",displayName:"",category:"environment",screenId:e.screenId,layer:"world",positionMode:"static",anchorPreset:"center",anchorX:.5,anchorY:.5,positionX:0,positionY:0,offsetX:0,offsetY:0,scale:.2,rotation:0,zIndex:0,assetPath:"",tint:"",alpha:1,text:"",font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",graphicsWidth:200,graphicsHeight:200,graphicsFill:"#FFFFFF",graphicsAlpha:1,interactionEnabled:!1,dragEnabled:!1,hoverEnabled:!1,clickEnabled:!1,logicId:"",logicPropsRaw:""}}createModal(){let e=document.createElement("div");e.className="wizard-modal",e.innerHTML=`
2
2
  <div class="wizard-card">
3
3
  <div class="wizard-header">
4
4
  <div class="wizard-title">
@@ -2234,7 +2234,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
2234
2234
  <button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
2235
2235
  </div>
2236
2236
  </div>
2237
- `,this.modal=e,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var i;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(i=this.options)!=null&&i.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,i=this.cropX+this.cropWidth/2,n=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,i-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,n-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let e=this.panX,t=this.panY,i=this.cropWidth*this.scale,n=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,i,n),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,i,n),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+i-a,t],[e,t+n-a],[e+i-a,t+n-a]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,a,a)})}updatePreview(){if(!this.modal||!this.image)return;let e=this.modal.querySelector(".asset-crop-preview-canvas");if(!e)return;let t=e.getContext("2d");if(!t)return;let i=150;e.width=i,e.height=i;let n=i/this.cropWidth,a=i/this.cropHeight,r=Math.min(n,a),o=this.cropWidth*r,l=this.cropHeight*r,c=(i-o)/2,d=(i-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,d,o,l)}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let e=this.modal.querySelector(".asset-crop-zoom-slider");e==null||e.addEventListener("input",i=>{let n=parseFloat(i.target.value);this.setZoom(n)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",i=>{let n=i.target.value;this.setAspectRatio(n)}),this.modal.addEventListener("click",i=>{switch(i.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",i=>{i.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,i=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,i=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var n;if(!this.image||!((n=this.options)!=null&&n.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let i=e.toDataURL("image/png");this.options.onCrop(i),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(s){new Dn().open(s)};import{Application as uo,Container as Ge,Graphics as Ee,Point as q,Rectangle as Fr,Text as go,TextStyle as ho}from"pixi.js";import{Sprite as Fs,Container as Hr}from"pixi.js";var Bs=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",$n=Bs;if(typeof window!="undefined")try{let s=new XMLHttpRequest;if(s.open("GET","./build-settings.json",!1),s.send(),s.status===200&&s.responseText){let e=JSON.parse(s.responseText);e!=null&&e.buildMode&&($n=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${$n}`))}}catch{}function Us(s){var t,i,n,a,r;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(s);let e={center:{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};if(Array.isArray(s))return{x:(t=s[0])!=null?t:.5,y:(i=s[1])!=null?i:.5};if(s&&typeof s=="object"&&"x"in s&&"y"in s)return{x:(n=s.x)!=null?n:.5,y:(a=s.y)!=null?a:.5};if(typeof s=="string"){let o=s.trim().toLowerCase();return(r=e[o])!=null?r:{x:.5,y:.5}}return null}var xe=class{static async create(e,t,i){var l,c,d,p,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${$n}`);let n=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!n){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let m=new Hr;return this.applyTransform(m,t==null?void 0:t.transform,t),m}let a=(c=t==null?void 0:t.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${e}, configId: ${a}, type: ${n.type}, path: ${n.path}`);let r=await Xi.load(e,n,i,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(d=r==null?void 0:r.constructor)==null?void 0:d.name}`);let o;if(n.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",r,"for object:",e),o=new Fs(r),console.log("[ObjectFactory] Created object:",o,"type:",(p=o==null?void 0:o.constructor)==null?void 0:p.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(n.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=r==null?void 0:r.constructor)==null?void 0:u.name,r),r&&(((g=r.constructor)==null?void 0:g.name)==="Container"||r instanceof Hr)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let m=[n.path,`/assets/${n.path}`,`assets/${n.path}`,`../assets/${n.path}`],f=!1;for(let b of m)try{let v=await fetch(b);if(v.ok){o=await v.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(h=o==null?void 0:o.constructor)==null?void 0:h.name),f=!0;break}}catch{continue}f||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=r)}else o=r;else o=r,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,i){var n,a,r,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(n=t.position.x)!=null?n:0,e.y=(a=t.position.y)!=null?a:0):"position"in e&&e.position&&e.position.set((r=t.position.x)!=null?r:0,(o=t.position.y)!=null?o:0)),t.scale!==void 0&&"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(t.scale):e.scale=t.scale),t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor)){let l=Us(t.anchor);l&&("set"in e.anchor?e.anchor.set(l.x,l.y):(e.anchor.x=l.x,e.anchor.y=l.y))}}};import{Graphics as Gs,Point as qs}from"pixi.js";var Pe={width:400,height:600,designWidth:400,scaleFactor:1},ji={scale:1,position:1},_i=[];function Vs(s,e,t,i,n,a,r){_i.push({element:s,originalScale:a,positionHelper:e,heightPercent:n}),e(s,t,i,n,a,r,!1)}function Ws(){_i.forEach(({element:s,originalScale:e,positionHelper:t,heightPercent:i})=>{let n=e*Pe.scaleFactor;t(s,Pe.width,Pe.height,i,n,!0,!1)})}function Ys(){_i.length=0,console.log("[LAYOUT] Cleared all responsive elements")}function Hn(s,e){console.log(`[SCREEN] updateScreenState called: ${s}x${e}`),Pe.width=s,Pe.height=e,Pe.scaleFactor=Math.min(s/Pe.designWidth,1.15),ji.scale=Pe.scaleFactor,ji.position=1,console.log(`[SCREEN] Global multipliers - scale: ${ji.scale.toFixed(3)}`),Ws()}var B={layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}};function Ks(s,e,t){let i=B[s];i&&i[e]!==void 0&&(i[e]=t,console.log(`Updated ${s}.${e} = ${t}`))}function Xs(){return B}var Js={center:{x:.5,y:.5},"center-center":{x:.5,y:.5},middle:{x:.5,y:.5},"middle-center":{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},"left-center":{x:0,y:.5},"right-center":{x:1,y:.5},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};function Ii(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Fe(s,e={x:.5,y:.5}){var t;if(Array.isArray(s))return{x:Ii(s[0],e.x),y:Ii(s[1],e.y)};if(s&&typeof s=="object"){let i=s;return{x:Ii(i.x,e.x),y:Ii(i.y,e.y)}}if(typeof s=="string"){let i=s.trim().toLowerCase();return(t=Js[i])!=null?t:e}return e}function Be(s,e,t,i={}){var g,h,m,f,b,v;let n=Fe(t),a=(g=i.inset)!=null?g:{},r=(h=i.padding)!=null?h:{x:0,y:0},o=((m=a.left)!=null?m:0)+r.x,l=((f=a.right)!=null?f:0)+r.x,c=((b=a.top)!=null?b:0)+r.y,d=((v=a.bottom)!=null?v:0)+r.y,p=Math.max(0,s-o-l),u=Math.max(0,e-c-d);return{x:o+p*n.x,y:c+u*n.y}}function Ue(s,e,t,i={}){var m,f,b,v,x,y;let n=(m=i.inset)!=null?m:{},a=(f=i.padding)!=null?f:{x:0,y:0},r=((b=n.left)!=null?b:0)+a.x,o=((v=n.right)!=null?v:0)+a.x,l=((x=n.top)!=null?x:0)+a.y,c=((y=n.bottom)!=null?y:0)+a.y,d=Math.max(0,s-r-o),p=Math.max(0,e-l-c),u=Fe(t,{x:.5,y:.5}),g=Math.min(Math.max(u.x,0),1),h=Math.min(Math.max(u.y,0),1);return{x:r+d*g,y:l+p*h}}function Nn(s,e,t,i={}){var d,p,u;if(!s)return;let n=i.positionRatio?Ue(e,t,i.positionRatio,{inset:i.inset,padding:i.screenPadding}):Be(e,t,i.anchor,{inset:i.inset,padding:i.screenPadding}),a=(d=i.offset)!=null?d:{x:0,y:0},r=n.x+a.x,o=n.y+a.y;s.anchor&&i.renderAnchor&&s.anchor.set(i.renderAnchor.x,i.renderAnchor.y),be(s,r,o);let l=(p=i.scale)!=null?p:1,c=(u=i.scaleMultiplier)!=null?u:1;(i.scale!==void 0||i.scaleMultiplier!==void 0)&&Se(s,l*c)}if(typeof window!="undefined"){let s=window.innerWidth,e=window.innerHeight,t=()=>{let i=window.innerWidth,n=window.innerHeight;(i!==s||n!==e)&&(s=i,e=n,Hn(i,n))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),Hn(window.innerWidth,window.innerHeight),window.updateDebugConfig=Ks,window.getDebugConfig=Xs,window.copyConfig=lo,window.applyConfig=Lt,window.applyConfigForRatio=co,window.positionAtBottom=Nr,window.positionAtTop=eo,window.positionAtCenter=to,window.positionAtLeft=io,window.positionAtRight=no,window.positionAtBottomLeft=ao,window.positionAtBottomRight=ro,window.positionAtTopLeft=so,window.positionAtTopRight=oo,window.applyPositionContract=Qs,console.log("\u{1F3AE} Debug Config Functions Available:"),console.log("\u2022 updateDebugConfig(category, key, value)"),console.log("\u2022 getDebugConfig()"),console.log("\u2022 copyConfig(presetName)"),console.log("\u2022 applyConfig(config)"),console.log("\u2022 applyConfigForRatio(width, height)"),console.log("\u{1F4CD} Positioning Helpers Available (with scale):"),console.log("\u2022 positionAtBottom(element, w, h, percent, scale)"),console.log("\u2022 positionAtTop(element, w, h, percent, scale)"),console.log("\u2022 positionAtCenter(element, w, h, offsetX, offsetY, scale)"),console.log("\u2022 positionAtLeft/Right(element, w, h, percent, scale)"),console.log("\u2022 Corner positions: BottomLeft/Right, TopLeft/Right (all with scale)"),console.log("\u2022 applyPositionContract(element, w, h, contract)"),console.log("Example: positionAtCenter(mySprite, 400, 600, 0, -50, 1.2)")}function Oi(s,e,t=0){return s*e+t}function zi(s,e,t=0){return s*(1-e)+t}function Ri(s,e,t=0){return s*e+t}function Di(s,e,t=0){return s*(1-e)+t}function ge(s,e=0){return s/2+e}function Zs(s,e){return s*e}function Qs(s,e,t,i){var r,o,l,c,d,p,u,g,h,m,f,b,v,x,y,w,T,j,P,_;let n=0,a=0;switch(i.type){case"top":n=ge(e,(o=(r=i.offset)==null?void 0:r.x)!=null?o:0),a=Oi(t,i.percent,(c=(l=i.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":n=ge(e,(p=(d=i.offset)==null?void 0:d.x)!=null?p:0),a=zi(t,i.percent,(g=(u=i.offset)==null?void 0:u.y)!=null?g:0);break;case"left":n=Ri(e,i.percent,(m=(h=i.offset)==null?void 0:h.x)!=null?m:0),a=ge(t,(b=(f=i.offset)==null?void 0:f.y)!=null?b:0);break;case"right":n=Di(e,i.percent,(x=(v=i.offset)==null?void 0:v.x)!=null?x:0),a=ge(t,(w=(y=i.offset)==null?void 0:y.y)!=null?w:0);break;case"center":n=ge(e,(j=(T=i.offset)==null?void 0:T.x)!=null?j:0),a=ge(t,(_=(P=i.offset)==null?void 0:P.y)!=null?_:0);break}s.position?s.position.set(n,a):(s.x=n,s.y=a),i.scale!==void 0&&i.scale!==1&&s.scale&&(typeof s.scale.set=="function"?s.scale.set(i.scale,i.scale):(s.scale.x=i.scale,s.scale.y=i.scale))}function Nr(s,e,t,i=.2,n=1,a=!0,r=!1){let o=Zs(t,i),l=zi(t,i/2);be(s,ge(e),l);let c=a?n*Pe.scaleFactor:n;Se(s,c),r&&!_i.find(d=>d.element===s)&&Vs(s,Nr,e,t,i,n,a)}function eo(s,e,t,i=.1,n=1){be(s,ge(e),Oi(t,i)),Se(s,n)}function to(s,e,t,i=0,n=0,a=1){be(s,ge(e,i),ge(t,n)),Se(s,a)}function io(s,e,t,i=.1,n=1){be(s,Ri(e,i),ge(t)),Se(s,n)}function no(s,e,t,i=.1,n=1){be(s,Di(e,i),ge(t)),Se(s,n)}function ao(s,e,t,i=.05,n=.05,a=1){be(s,Ri(e,n),zi(t,i)),Se(s,a)}function ro(s,e,t,i=.05,n=.05,a=1){be(s,Di(e,n),zi(t,i)),Se(s,a)}function so(s,e,t,i=.05,n=.05,a=1){be(s,Ri(e,n),Oi(t,i)),Se(s,a)}function oo(s,e,t,i=.05,n=.05,a=1){be(s,Di(e,n),Oi(t,i)),Se(s,a)}function be(s,e,t){s&&s.position?typeof s.position.set=="function"?s.position.set(e,t):(s.position.x=e,s.position.y=t):s&&(s.x=e,s.y=t)}function Se(s,e){e!==1&&s&&s.scale&&(typeof s.scale.set=="function"?s.scale.set(e,e):s.scale.x!==void 0&&s.scale.y!==void 0&&(s.scale.x=e,s.scale.y=e))}var Ze={default:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}},wide:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.9,screen_scale_y:1.1},engine:{scale:1,background_scale:1.1,background_offset_y:0,background_alpha:.95,label_pulse_speed:3,label_pulse_intensity:.03}},square:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.85,screen_scale_y:.85},engine:{scale:1,background_scale:1,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}},tall:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1.1,screen_scale_y:.9},engine:{scale:1,background_scale:.95,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}}};function lo(s){return s&&Ze[s]?JSON.parse(JSON.stringify(Ze[s])):JSON.parse(JSON.stringify(B))}function Lt(s){Object.keys(s).forEach(e=>{let t=e;B[t]&&s[t]&&Object.assign(B[t],s[t])}),console.log("Config applied:",s)}function co(s,e){let t=s/e;t>1.6?(Lt(Ze.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(Lt(Ze.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(Lt(Ze.square),console.log("Applied SQUARE config for ratio:",t)):(Lt(Ze.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let s=window;s.configPresets=Ze,s.resolveAnchorVec2=s.resolveAnchorVec2||Fe,s.resolveScreenAnchorPoint=s.resolveScreenAnchorPoint||Be,s.resolveScreenRatioPoint=s.resolveScreenRatioPoint||Ue}var oe=null;function po(s,e,t,i,n,a={}){var I,M,z,R,N,H,F,G,K,ee,ne,le,$,Q,ce,he,de,ve,Le,Te,V,te,X,re,Oe,We,ca,da,pa,ua,ga,ha,ma,fa;let r=(I=a.enableDebugLogs)!=null?I:!1;r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== STARTING LAYOUT CALCULATION ====="),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Screen dimensions:",{width:i.width,height:i.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Time:",t),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Options:",a));let{mainContainer:o,label:l,background:c,backgroundTexture:d,app:p}=s;if(!p||!p.renderer){r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] \u274C No app or renderer, skipping layout");return}r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] App renderer dimensions:",{width:p.renderer.width,height:p.renderer.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] App screen dimensions:",{width:p.screen.width,height:p.screen.height}));let u=i.width,g=i.height;r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Base dimensions:",{baseWidth:u,baseHeight:g});let h=u*B.layout.screen_scale_x,m=g*B.layout.screen_scale_y,f=u/2,b=e.engine.runtime||{},v=b.layout||{};r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug config:",{screen_scale_x:B.layout.screen_scale_x,screen_scale_y:B.layout.screen_scale_y}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Calculated dimensions:",{width:h,height:m,midX:f}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Engine runtime:",b),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Layout config:",v));let x=v.design_width_portrait||400,y=h/x;y=Math.min(y,1.15);let w=y*((M=B.engine.scale)!=null?M:1),T=(z=a.skipMainContainerTransform)!=null?z:!1;!T&&o&&o.scale&&(typeof o.scale.set=="function"?o.scale.set(w):(o.scale.x=w,o.scale.y=w));let j=(R=v.main_container_anchor)!=null?R:"center",P=(N=v.main_container_position_ratio)!=null?N:{x:.5,y:.5},_=(H=v.main_container_offset)!=null?H:{x:0,y:0},O=v.main_container_position_ratio?Ue(u,g,P):Be(u,g,j),L=O.x+_.x+B.layout.position_offset.x,A=O.y+_.y+B.layout.position_offset.y;if(!T&&o&&o.position&&(typeof o.position.set=="function"?o.position.set(L,A):(o.position.x=L,o.position.y=A)),n&&(o!=null&&o.toLocal))for(let[se,ae]of e.objects.entries()){let W=ae==null?void 0:ae.transform;if(!W||((F=W.position_mode)!=null?F:"static")!=="static")continue;let U=(G=n.get)==null?void 0:G.call(n,se),ye=((K=U==null?void 0:U.getDisplayObject)==null?void 0:K.call(U))||(U==null?void 0:U.pixiObject)||U;if(!ye||ye.parent!==o)continue;let Ht=W.position_ratio!=null?Ue(u,g,W.position_ratio):Be(u,g,(ee=W.anchor)!=null?ee:"center"),Nt=o.toLocal(new qs(Ht.x,Ht.y)),Ft=(ne=W.position)!=null?ne:{x:0,y:0},Ye=Nt.x+Ft.x,Ki=Nt.y+Ft.y;typeof(U==null?void 0:U.setPosition)=="function"?U.setPosition(Ye,Ki):(be(ye,Ye,Ki),(le=U==null?void 0:U.transform)!=null&&le.position&&(U.transform.position.x=Ye,U.transform.position.y=Ki))}let k=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,S=((k==null?void 0:k.buildMode)||(typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"dev"))==="dev";if(B.layout.debug_rect_visible&&S){(!oe||oe.parent!==p.stage)&&(oe==null||oe.destroy(),oe=new Gs,oe.zIndex=9999,p.stage.addChild(oe)),oe.clear();let se=B.layout.debug_rect_scale_x,ae=B.layout.debug_rect_scale_y,W=(u-4)*se,ze=(g-4)*ae,U=(u-W)/2,ye=(g-ze)/2;r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== DEBUG RECT POSITIONING ====="),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug rect calculations:",{baseWidth:u,baseHeight:g,rectW:W,rectH:ze,offsetX:U,offsetY:ye}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug rect final position:",{x:2+U,y:2+ye,width:W,height:ze})),oe.rect(2+U,2+ye,W,ze).stroke({width:B.layout.debug_rect_thickness,color:B.layout.debug_rect_color})}else oe&&(oe.destroy(),oe=null);let E=(($=s.label)==null?void 0:$.config)||e.objects.get("label_1")||e.objects.get("ui_tutorial_1");if(l&&l.position&&E){let se=(ce=(Q=E==null?void 0:E.transform)==null?void 0:Q.anchor)!=null?ce:"center",ae=(he=E==null?void 0:E.transform)==null?void 0:he.position_ratio,W=((de=E==null?void 0:E.transform)==null?void 0:de.offset)||{x:0,y:0};Nn(l,u,g,{anchor:se,positionRatio:ae,offset:{x:W.x*w,y:W.y*w},renderAnchor:Fe(se)})}if(l&&l.alpha>0){let se=1+Math.sin(t*B.engine.label_pulse_speed)*B.engine.label_pulse_intensity,ae=(Le=(ve=E==null?void 0:E.transform)==null?void 0:ve.scale)!=null?Le:1,W=se*w*ae;l.scale&&(typeof l.scale.set=="function"?l.scale.set(W):(l.scale.x=W,l.scale.y=W))}if(r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== BACKGROUND POSITIONING ====="),c){r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background object exists:",!!c),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background type:",(Te=c.constructor)==null?void 0:Te.name)),c.alpha=((te=(V=b.background)==null?void 0:V.alpha)!=null?te:.98)*B.engine.background_alpha,r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background alpha set to:",c.alpha);let se=e.objects.get("background_1");r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background config:",se);let ae=(se==null?void 0:se.transform)||{};r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background transform:",ae);let W=ae.offset||{x:0,y:0},ze=((re=(X=b.background)==null?void 0:X.offset_y)!=null?re:0)+B.engine.background_offset_y,U=(Oe=ae.anchor)!=null?Oe:"center",ye=ae.position_ratio;if(r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background positioning params:",{bgOffset:W,bgRuntimeOffsetY:ze,bgScreenAnchor:U,bgPositionRatio:ye,baseWidth:u,baseHeight:g,finalScale:w}),Nn(c,u,g,{anchor:U,positionRatio:ye,offset:{x:W.x*w,y:W.y*w+ze},renderAnchor:Fe(U)}),r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background position after applyScreenAnchor:",{x:c.x,y:c.y,scaleX:(We=c.scale)==null?void 0:We.x,scaleY:(ca=c.scale)==null?void 0:ca.y,anchorX:(da=c.anchor)==null?void 0:da.x,anchorY:(pa=c.anchor)==null?void 0:pa.y,pivotX:(ua=c.pivot)==null?void 0:ua.x,pivotY:(ga=c.pivot)==null?void 0:ga.y,width:c.width,height:c.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background texture dimensions:",{textureWidth:d==null?void 0:d.width,textureHeight:d==null?void 0:d.height})),d){let Ht=Math.max(h/d.width,m/d.height),Nt=(ma=(ha=b.background)==null?void 0:ha.scale_multiplier)!=null?ma:1.05,Ft=(fa=ae.scale)!=null?fa:1,Ye=Ht*Nt*B.engine.background_scale*Ft;c.scale&&(typeof c.scale.set=="function"?c.scale.set(Ye):(c.scale.x=Ye,c.scale.y=Ye))}else c&&typeof c.clear=="function"&&(c.clear(),c.rect(-h/2,-m/2,h,m).fill({color:1444375}))}}var $i=class{constructor(e){this.app=null;this.camera=new Ge;this.mainContainer=new Ge;this.uiContainer=new Ge;this.gizmoLayer=new Ge;this.screenFrame=new Ee;this.gameFrame=new Ee;this.gridLayer=new Ee;this.spawnPointLayer=new Ge;this.objectMap=new Map;this.selectedId=null;this.dragMode=null;this.dragStartPointer=null;this.dragStartPos=null;this.dragStartScale=1;this.dragStartRotation=0;this.dragStartAngle=0;this.dragStartDistance=1;this.dragAnchorLocal=null;this.dragStartValue=null;this.dragContainer=null;this.spawnPointDrag=null;this.lastGameFrameSize=null;this.cameraScale=1;this.isPanning=!1;this.panStart=null;this.panStartCamera=null;this.hasUserCamera=!1;this.resizeObserver=null;this.screenSyncRaf=null;this.gizmoOutline=new Ee;this.moveHandle=new Ee;this.scaleHandle=new Ee;this.rotateHandle=new Ee;this.isVisible=!0;this.applyQueued=!1;this.applyQueuedId=null;this.gridEnabled=!1;this.gridGap=50;this.lastPickPoint=null;this.lastPickIds=[];this.lastPickIndex=0;this.lastPickTime=0;this.playModeEnabled=!1;this.handleScreenChange=e=>{if(!(e!=null&&e.detail))return;let{width:t,height:i}=e.detail;!t||!i||(this.hasUserCamera=!1,this.updateLayout({width:t,height:i}),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid(),this.schedulePostScreenSync({width:t,height:i}))};this.handleActiveScreenChanged=()=>{this.isVisible&&this.syncFromConfig()};this.handleConfigChanged=e=>{if(!this.isVisible)return;this.updateLayout(),this.updateGrid();let t=e==null?void 0:e.detail;if(!t){this.syncFromConfig();return}let i=t.objectId,n=t.objectIds;if(i){this.syncFromConfig([i]);return}if(Array.isArray(n)&&n.length>0){this.syncFromConfig(n);return}this.syncFromConfig()};this.handleSceneRefresh=()=>{this.isVisible&&this.syncFromConfig()};this.handlePreviewSelect=e=>{var i,n;let t=(n=(i=e==null?void 0:e.detail)==null?void 0:i.objectId)!=null?n:null;this.setSelected(t,{silent:!0})};this.onStagePointerDown=e=>{if(!this.app||!this.isVisible||this.getPointerButton(e)!==0||this.isGizmoTarget(e==null?void 0:e.target))return;let i=this.getEventGlobalPoint(e);if(!i)return;let n=new q(i.x,i.y),a=this.getPickCandidates(n);if(a.length===0){this.setSelected(null),this.lastPickIds=[],this.lastPickIndex=0,this.lastPickPoint=n,this.lastPickTime=performance.now();return}let r=performance.now(),o=this.areSameIds(a,this.lastPickIds),l=this.lastPickPoint&&this.distance(n,this.lastPickPoint)<=6,c=r-this.lastPickTime<1200,d=o&&l&&c?(this.lastPickIndex+1)%a.length:0,p=a[d];this.lastPickIds=a,this.lastPickIndex=d,this.lastPickPoint=n,this.lastPickTime=r,this.setSelected(p),this.playModeEnabled||this.startDrag("move",e)};this.handleGridSettings=e=>{var n,a;let t=(n=e==null?void 0:e.detail)==null?void 0:n.enabled,i=(a=e==null?void 0:e.detail)==null?void 0:a.gap;typeof t=="boolean"&&(this.gridEnabled=t),typeof i=="number"&&Number.isFinite(i)&&i>2&&(this.gridGap=i),this.updateGrid()};this.handlePlayMode=e=>{var i;let t=(i=e==null?void 0:e.detail)==null?void 0:i.enabled;typeof t=="boolean"&&this.setPlayMode(t)};this.syncFromGameObjects=()=>{this.syncFromGameObjectsInternal(!1)};this.onSpawnPointDragMove=e=>{if(!this.spawnPointDrag)return;let t=this.getPointerInContainer(e.clientX,e.clientY,this.mainContainer);if(!t)return;let i=t.x+this.spawnPointDrag.offset.x,n=t.y+this.spawnPointDrag.offset.y;this.updateLiveSpawnPoint(this.spawnPointDrag.objectId,this.spawnPointDrag.index,i,n)};this.onSpawnPointDragEnd=()=>{if(!this.spawnPointDrag)return;let{objectId:e,startPoints:t}=this.spawnPointDrag,i=this.getEditableObjectConfig(e),n=i?this.getSpawnPoints(i):null;i&&n&&(this.setNestedValue(i,"logic.props.spawnPoints",t),Re({objectId:e,path:"logic.props.spawnPoints",value:n},{persist:!0,emitEvent:!0,trackHistory:!0}),this.queueLiveApply(e)),this.spawnPointDrag=null,window.dispatchEvent(new CustomEvent("inspector:refresh")),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd)};this.onDragMove=e=>{var a;if(!this.dragMode||!this.selectedId||!this.app||this.playModeEnabled)return;let t=this.objectMap.get(this.selectedId);if(!t)return;let i=(a=this.dragContainer)!=null?a:this.mainContainer,n=this.getPointerInContainer(e.clientX,e.clientY,i);if(!(!n||!this.dragStartPointer||!this.dragStartPos)){if(this.dragMode==="move"){let r=n.x-this.dragStartPointer.x,o=n.y-this.dragStartPointer.y,l=this.dragStartPos.x+r,c=this.dragStartPos.y+o;t.displayObject.position.set(l,c),this.updateLiveConfigPosition(l,c)}else if(this.dragMode==="scale"){let r=new q(this.dragStartPos.x,this.dragStartPos.y),o=Math.max(1,this.distance(n,r)),l=Math.max(.05,this.dragStartScale*(o/this.dragStartDistance));t.displayObject.scale.set(l),this.updateLiveConfigScale(l)}else if(this.dragMode==="rotate"){let r=new q(this.dragStartPos.x,this.dragStartPos.y),l=Math.atan2(n.y-r.y,n.x-r.x)-this.dragStartAngle,c=this.dragStartRotation+l;t.displayObject.rotation=c,this.updateLiveConfigRotation(c)}this.updateGizmos(),this.queueLiveApply(this.selectedId)}};this.onDragEnd=()=>{var i,n,a,r,o,l,c;if(!this.dragMode||!this.selectedId)return;let e=this.selectedId,t=this.getEditableObjectConfig(e);if(t){let d=(i=t.transform)!=null?i:{};if(t.transform||(t.transform=d),this.dragMode==="move"&&this.dragStartValue){let p=d.position,u=Array.isArray(p)?[Number((n=p[0])!=null?n:0),Number((a=p[1])!=null?a:0)]:{x:Number((r=p==null?void 0:p.x)!=null?r:0),y:Number((o=p==null?void 0:p.y)!=null?o:0)};this.applyFinalOverride(e,"transform.position",u,this.dragStartValue)}else this.dragMode==="scale"?this.applyFinalOverride(e,"transform.scale",(l=d.scale)!=null?l:1,this.dragStartValue):this.dragMode==="rotate"&&this.applyFinalOverride(e,"transform.rotation",(c=d.rotation)!=null?c:0,this.dragStartValue);this.queueLiveApply(e)}window.dispatchEvent(new CustomEvent("inspector:refresh")),this.dragMode=null,this.dragStartPointer=null,this.dragStartPos=null,this.dragAnchorLocal=null,this.dragStartValue=null,this.dragContainer=null,window.removeEventListener("pointermove",this.onDragMove),window.removeEventListener("pointerup",this.onDragEnd)};this.onWheel=e=>{if(!this.app||!this.isVisible)return;e.preventDefault();let i=Math.sign(e.deltaY)<0?1.1:.9,n=Math.min(6,Math.max(.1,this.cameraScale*i)),a=new q(this.app.renderer.width/2,this.app.renderer.height/2),r=this.camera.toLocal(a);this.cameraScale=n,this.camera.scale.set(n);let o=this.camera.toGlobal(r);this.camera.position.set(this.camera.position.x+(a.x-o.x),this.camera.position.y+(a.y-o.y)),this.hasUserCamera=!0,this.updateGizmos(),this.updateGrid()};this.onPanStart=e=>{e.button===2&&(this.isPanning=!0,this.panStart={x:e.clientX,y:e.clientY},this.panStartCamera={x:this.camera.position.x,y:this.camera.position.y},this.hasUserCamera=!0)};this.onPanMove=e=>{if(!this.isPanning||!this.panStart||!this.panStartCamera)return;let t=e.clientX-this.panStart.x,i=e.clientY-this.panStart.y;this.camera.position.set(this.panStartCamera.x+t,this.panStartCamera.y+i),this.updateGrid()};this.onPanEnd=()=>{this.isPanning=!1,this.panStart=null,this.panStartCamera=null};this.root=e.root,this.getScreen=e.getScreen}async mount(){this.app||(this.app=new uo,await this.app.init({resizeTo:this.root,autoDensity:!0,resolution:window.devicePixelRatio||1,antialias:!0,backgroundAlpha:0}),this.root.innerHTML="",this.root.appendChild(this.app.canvas),this.root.style.position="relative",this.root.style.overflow="hidden",this.app.stage.sortableChildren=!0,this.app.stage.eventMode="static",this.camera.sortableChildren=!0,this.mainContainer.sortableChildren=!0,this.uiContainer.sortableChildren=!0,this.spawnPointLayer.sortableChildren=!0,this.gizmoLayer.sortableChildren=!0,this.app.stage.addChild(this.camera),this.camera.addChild(this.gridLayer),this.camera.addChild(this.screenFrame),this.camera.addChild(this.mainContainer),this.camera.addChild(this.uiContainer),this.camera.addChild(this.spawnPointLayer),this.camera.addChild(this.gameFrame),this.camera.addChild(this.gizmoLayer),this.gridLayer.zIndex=-2,this.gridLayer.eventMode="none",this.screenFrame.zIndex=-1,this.screenFrame.eventMode="none",this.mainContainer.zIndex=0,this.uiContainer.zIndex=5e4,this.spawnPointLayer.zIndex=8e4,this.spawnPointLayer.eventMode="passive",this.gameFrame.zIndex=85e3,this.gameFrame.eventMode="none",this.gizmoLayer.zIndex=1e5,this.gizmoLayer.addChild(this.gizmoOutline),this.gizmoLayer.addChild(this.moveHandle),this.gizmoLayer.addChild(this.scaleHandle),this.gizmoLayer.addChild(this.rotateHandle),this.gizmoOutline.eventMode="none",this.setupInteractions(),this.setupObservers(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.restoreScenePreferences(),this.refresh(),!this.isVisible&&this.app.ticker&&this.app.ticker.stop())}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.screenSyncRaf&&(cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=null),window.removeEventListener("handler-preview:screen",this.handleScreenChange),window.removeEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.removeEventListener("config:changed",this.handleConfigChanged),window.removeEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.removeEventListener("preview:select",this.handlePreviewSelect),window.removeEventListener("scene-editor:grid",this.handleGridSettings),window.removeEventListener("scene-editor:play-mode",this.handlePlayMode),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd),this.app&&(this.app.stage.off("pointerdown",this.onStagePointerDown),this.app.destroy(!0),this.app=null)}setVisible(e){this.isVisible=e,!(!this.app||!this.app.ticker)&&(e?(this.app.ticker.start(),this.refresh(),this.updateGrid()):this.app.ticker.stop())}refresh(){this.syncFromConfig()}setupObservers(){window.addEventListener("handler-preview:screen",this.handleScreenChange),window.addEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.addEventListener("config:changed",this.handleConfigChanged),window.addEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.addEventListener("preview:select",this.handlePreviewSelect),window.addEventListener("scene-editor:grid",this.handleGridSettings),window.addEventListener("scene-editor:play-mode",this.handlePlayMode),this.resizeObserver=new ResizeObserver(()=>{this.handleResize()}),this.resizeObserver.observe(this.root)}setupInteractions(){if(!this.app)return;let e=this.app.canvas;e.addEventListener("contextmenu",t=>t.preventDefault()),e.addEventListener("wheel",this.onWheel,{passive:!1}),e.addEventListener("pointerdown",this.onPanStart),window.addEventListener("pointermove",this.onPanMove),window.addEventListener("pointerup",this.onPanEnd),this.app.stage.on("pointerdown",this.onStagePointerDown),this.moveHandle.eventMode="static",this.moveHandle.cursor="move",this.scaleHandle.eventMode="static",this.scaleHandle.cursor="nwse-resize",this.rotateHandle.eventMode="static",this.rotateHandle.cursor="crosshair",this.moveHandle.on("pointerdown",t=>this.startDrag("move",t)),this.scaleHandle.on("pointerdown",t=>this.startDrag("scale",t)),this.rotateHandle.on("pointerdown",t=>this.startDrag("rotate",t))}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}getPickCandidates(e){var i;let t=[];for(let[n,a]of this.objectMap.entries()){let r=a.displayObject;if(!r||r.visible===!1)continue;let o=(i=r.getBounds)==null?void 0:i.call(r);if(!o||o.width<=0||o.height<=0||e.x<o.x||e.x>o.x+o.width||e.y<o.y||e.y>o.y+o.height)continue;let l=r.parent,c=typeof(l==null?void 0:l.zIndex)=="number"?l.zIndex:0,d=typeof r.zIndex=="number"?r.zIndex:0,p=typeof(l==null?void 0:l.getChildIndex)=="function"?l.getChildIndex(r):0,u=c*1e6+d*1e3+p;t.push({id:n,order:u})}return t.sort((n,a)=>a.order-n.order),t.map(n=>n.id)}areSameIds(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}isGizmoTarget(e){return e&&this.spawnPointLayer.children.indexOf(e)!==-1?!0:e===this.moveHandle||e===this.scaleHandle||e===this.rotateHandle||e===this.gizmoOutline}restoreScenePreferences(){if(typeof window!="undefined"){try{let e=window.localStorage.getItem(this.getSceneStorageKey("grid_enabled")),t=window.localStorage.getItem(this.getSceneStorageKey("grid_gap")),i=window.localStorage.getItem(this.getSceneStorageKey("play_mode"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let n=Number(t);Number.isFinite(n)&&n>2&&(this.gridGap=n)}i!==null&&this.setPlayMode(i==="true")}catch{}this.updateGrid()}}getSceneStorageKey(e){let t=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${e}::${t}`}schedulePostScreenSync(e){this.screenSyncRaf&&cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=requestAnimationFrame(()=>{this.runPostScreenSync(e)})}async runPostScreenSync(e){this.screenSyncRaf=null,this.isVisible&&(this.updateLayout(e),this.hasUserCamera||this.centerCamera(),await this.syncFromConfig(),this.syncFromGameObjectsInternal(!0),this.updateGizmos(),this.updateGrid())}getRuntimeScreenSize(){var a,r,o,l,c,d,p;let e=window.gameApp;if(e!=null&&e.renderer){let u=e.renderer.screen,g=Number((a=u==null?void 0:u.width)!=null?a:0),h=Number((r=u==null?void 0:u.height)!=null?r:0);if(Number.isFinite(g)&&g>0&&Number.isFinite(h)&&h>0)return{width:g,height:h};let m=Number((o=e.renderer.resolution)!=null?o:1)||1,f=Number((l=e.renderer.width)!=null?l:0)/m,b=Number((c=e.renderer.height)!=null?c:0)/m;if(Number.isFinite(f)&&f>0&&Number.isFinite(b)&&b>0)return{width:f,height:b}}let t=document.querySelector(".game-container"),i=Number((d=t==null?void 0:t.dataset)==null?void 0:d.screenWidth),n=Number((p=t==null?void 0:t.dataset)==null?void 0:p.screenHeight);return Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:null}getRuntimeLayoutReference(){var i;let e=window.__mainContainer;if(e)return e;let t=window.gameApp;return(i=t==null?void 0:t.stage)!=null?i:null}getRuntimeParentContainer(e){var l,c;let t=window.gameObjectManager;if(!(t!=null&&t.get))return null;let i=t.get(e),n=((l=i==null?void 0:i.getDisplayObject)==null?void 0:l.call(i))||(i==null?void 0:i.pixiObject)||i,a=n==null?void 0:n.parent;if(!a)return null;let r=this.getRuntimeLayoutReference(),o=(c=window.gameApp)==null?void 0:c.stage;return r&&o&&r===o?this.mainContainer:r&&typeof r.contains=="function"&&r.contains(a)?this.mainContainer:a===r||a===o?this.mainContainer:this.uiContainer}applyRuntimeTransform(e){var r,o,l,c,d,p,u,g,h,m,f,b,v,x;if(!e)return!1;let t=Number((o=(r=e.scale)==null?void 0:r.x)!=null?o:1),i=Number((c=(l=e.scale)==null?void 0:l.y)!=null?c:t),n=Number((p=(d=e.position)==null?void 0:d.x)!=null?p:0),a=Number((g=(u=e.position)==null?void 0:u.y)!=null?g:0);if(!Number.isFinite(t)||!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(a))return!1;if(this.mainContainer.scale.set(t,i),this.uiContainer.scale.set(t,i),this.mainContainer.position.set(n,a),this.uiContainer.position.set(n,a),e.pivot&&((h=this.mainContainer.pivot)!=null&&h.set)&&((m=this.uiContainer.pivot)!=null&&m.set)){let y=Number((b=(f=e.pivot)==null?void 0:f.x)!=null?b:0),w=Number((x=(v=e.pivot)==null?void 0:v.y)!=null?x:0);Number.isFinite(y)&&Number.isFinite(w)&&(this.mainContainer.pivot.set(y,w),this.uiContainer.pivot.set(y,w))}return typeof e.rotation=="number"&&(this.mainContainer.rotation=e.rotation,this.uiContainer.rotation=e.rotation),!0}getEditableConfig(){return window.__editableConfig||null}getEditableObjectConfig(e){var n,a;let t=window.getEditableObjectConfig;if(typeof t=="function")return t(e);let i=this.getEditableConfig();return i!=null&&i.objects?typeof i.objects.get=="function"?(n=i.objects.get(e))!=null?n:null:(a=i.objects[e])!=null?a:null:null}getEditableObjectIds(){let e=window.getEditableObjectList;if(typeof e=="function"){let i=e();if(Array.isArray(i))return i}let t=this.getEditableConfig();return t!=null&&t.objects?typeof t.objects.keys=="function"?Array.from(t.objects.keys()):Object.keys(t.objects):[]}async syncFromConfig(e){if(!this.app)return;let t=this.getEditableConfig();if(!(t!=null&&t.objects))return;let i=e!=null&&e.length?e:this.getEditableObjectIds(),n=new Set(i);if(!e)for(let a of Array.from(this.objectMap.keys()))n.has(a)||this.removeObject(a);for(let a of i){let r=this.getEditableObjectConfig(a);if(!r){this.removeObject(a);continue}await this.upsertObject(a,r)}this.updateGizmos(),this.updateSpawnPointHandles(),this.updateGameFrame(this.getScreen())}removeObject(e){var i,n;let t=this.objectMap.get(e);if(t){try{(n=(i=t.displayObject)==null?void 0:i.destroy)==null||n.call(i)}catch{}this.objectMap.delete(e),this.selectedId===e&&this.setSelected(null,{silent:!0})}}async upsertObject(e,t){let i=this.getAssetKey(t),n=this.objectMap.get(e),a=this.isUiConfig(e,t),r=this.getRuntimeParentContainer(e),o=a?this.uiContainer:this.mainContainer,l=r!=null?r:o;if(!n||n.assetKey!==i||n.isUi!==a){n&&this.removeObject(e);let d=await this.createDisplayObject(e,t);if(!d)return;l.addChild(d),this.objectMap.set(e,{id:e,displayObject:d,assetKey:i,isUi:a}),this.attachObjectInteraction(d,e)}let c=this.objectMap.get(e);c&&(c.displayObject.parent!==l&&l.addChild(c.displayObject),this.applyVisualConfig(c.displayObject,t),this.updateObjectTransform(c.displayObject,t))}async createDisplayObject(e,t){var o,l,c,d,p,u,g,h,m,f,b,v,x,y,w;if((o=t==null?void 0:t.render)!=null&&o.asset)try{if(((c=(l=t==null?void 0:t.render)==null?void 0:l.asset)==null?void 0:c.type)!=="json"){let j=await xe.create(e,t,this.app);if(j instanceof Ge)return j}}catch(T){console.warn("[SceneEditor] ObjectFactory failed for",e,T)}let i=t==null?void 0:t.ui,n=(d=t==null?void 0:t.render)!=null?d:{},a=(i==null?void 0:i.text)||(i==null?void 0:i.kind)==="text";if(!!n.background_color){let T=this.getScreen(),j=(p=T==null?void 0:T.width)!=null?p:0,P=(u=T==null?void 0:T.height)!=null?u:0,_=new Ee,O=this.parseColor(n.background_color,0),L=typeof n.background_alpha=="number"?n.background_alpha:1;j>0&&P>0&&_.rect(0,0,j,P).fill({color:O,alpha:L});let A=new Ge;return A.addChild(_),A}if(a){let T=(h=(g=i==null?void 0:i.color)!=null?g:n==null?void 0:n.tint)!=null?h:"#ffffff",j=new ho({fontFamily:"Arial, sans-serif",fontSize:(m=i==null?void 0:i.fontSize)!=null?m:16,fill:T,align:(f=i==null?void 0:i.align)!=null?f:"center",letterSpacing:(b=i==null?void 0:i.letterSpacing)!=null?b:0});return new go({text:(v=i==null?void 0:i.text)!=null?v:"",style:j})}if((x=t==null?void 0:t.effects)!=null&&x.width||(y=t==null?void 0:t.effects)!=null&&y.height){let T=new Ee,j=typeof t.effects.width=="number"?t.effects.width:100,P=typeof t.effects.height=="number"?t.effects.height:100,_=(w=t.effects.fill_color)!=null?w:"#ffffff",O=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,L=Number.parseInt(String(_).replace("#",""),16);return T.rect(0,0,j,P).fill({color:Number.isFinite(L)?L:16777215,alpha:O}),T}return new Ge}attachObjectInteraction(e,t){if(e&&(e.eventMode="static",e.cursor="pointer",!e.hitArea&&typeof e.getLocalBounds=="function")){let i=e.getLocalBounds();i&&i.width>0&&i.height>0&&(e.hitArea=new Fr(i.x,i.y,i.width,i.height))}}getAssetKey(e){var i;let t=(i=e==null?void 0:e.render)==null?void 0:i.asset;return t?`${t.type||"asset"}::${t.path||""}`:null}isUiConfig(e,t){var a,r;let i=(((a=t==null?void 0:t.identity)==null?void 0:a.category)||"").toString().toLowerCase(),n=(((r=t==null?void 0:t.identity)==null?void 0:r.id)||e||"").toString().toLowerCase();return i.includes("ui")||n.startsWith("ui")||n.includes("label")}applyVisualConfig(e,t){var r,o,l,c,d,p,u;if(!e)return;let i=(r=t==null?void 0:t.render)!=null?r:{};typeof i.alpha=="number"&&(e.alpha=i.alpha),e.visible=i.visible!==!1,e.zIndex=typeof i.z_index=="number"?i.z_index:0;let n=(d=(c=(o=t==null?void 0:t.render)==null?void 0:o.anchor)!=null?c:(l=t==null?void 0:t.transform)==null?void 0:l.anchor)!=null?d:"center",a=Fe(n,{x:.5,y:.5});if((p=e.anchor)!=null&&p.set)e.anchor.set(a.x,a.y);else if(e.pivot){let g=(u=e.getLocalBounds)==null?void 0:u.call(e);g&&e.pivot.set(g.width*a.x,g.height*a.y)}}updateObjectTransform(e,t){var c;if(!e||this.playModeEnabled)return;let i=(c=t==null?void 0:t.transform)!=null?c:{},n=e.parent===this.uiContainer?this.uiContainer:this.mainContainer,a=this.getAnchorLocalPoint(i,n),r=this.getPositionOffset(i);a&&e.position.set(a.x+r.x,a.y+r.y);let o=typeof i.scale=="number"?i.scale:void 0;typeof o=="number"&&e.scale&&e.scale.set(o);let l=typeof i.rotation=="number"?i.rotation:0;typeof e.rotation=="number"&&(e.rotation=l)}getAnchorLocalPoint(e,t=this.mainContainer){var r;let i=this.getScreen();if(!(i!=null&&i.width)||!(i!=null&&i.height))return null;let n=(e==null?void 0:e.position_ratio)!=null?Ue(i.width,i.height,e.position_ratio):Be(i.width,i.height,(r=e==null?void 0:e.anchor)!=null?r:"center"),a=new q;return t.toLocal(new q(n.x,n.y),void 0,a),a}getPositionOffset(e){var l,c,d,p,u,g,h,m;let t=e==null?void 0:e.position,i=e==null?void 0:e.offset,n=Array.isArray(t)?Number((l=t[0])!=null?l:0):Number((c=t==null?void 0:t.x)!=null?c:0),a=Array.isArray(t)?Number((d=t[1])!=null?d:0):Number((p=t==null?void 0:t.y)!=null?p:0),r=Array.isArray(i)?Number((u=i[0])!=null?u:0):Number((g=i==null?void 0:i.x)!=null?g:0),o=Array.isArray(i)?Number((h=i[1])!=null?h:0):Number((m=i==null?void 0:i.y)!=null?m:0);return{x:n+r,y:a+o}}updateLayout(e){var a,r,o,l,c,d,p,u;let t=e!=null?e:this.getScreen();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;let i=this.getRuntimeLayoutReference();if(!this.applyRuntimeTransform(i)){let h=(((r=(a=this.getEditableConfig())==null?void 0:a.engine)==null?void 0:r.runtime)||{}).layout||{},m=t.width*((o=B.layout.screen_scale_x)!=null?o:1),f=h.design_width_portrait||400,b=m/f;b=Math.min(b,1.15);let v=b*((l=B.engine.scale)!=null?l:1);this.mainContainer.scale.set(v),this.uiContainer.scale.set(v);let x=(c=h.main_container_anchor)!=null?c:"center",y=(d=h.main_container_position_ratio)!=null?d:{x:.5,y:.5},w=(p=h.main_container_offset)!=null?p:{x:0,y:0},T=h.main_container_position_ratio?Ue(t.width,t.height,y):Be(t.width,t.height,x),j=T.x+w.x+B.layout.position_offset.x,P=T.y+w.y+B.layout.position_offset.y;this.mainContainer.position.set(j,P),this.uiContainer.position.set(j,P)}this.screenFrame.clear(),this.screenFrame.rect(0,0,t.width,t.height),this.screenFrame.stroke({width:2,color:2894892,alpha:.5}),this.updateGameFrame(t),(u=this.app)!=null&&u.stage&&(this.app.stage.hitArea=new Fr(0,0,this.app.renderer.width,this.app.renderer.height)),this.updateSpawnPointHandles()}updateGrid(){if(!this.app)return;if(!this.gridEnabled){this.gridLayer.clear();return}let e=Math.max(4,this.gridGap),t=this.app.renderer,i=this.camera.toLocal(new q(0,0)),n=this.camera.toLocal(new q(t.width,t.height)),a=Math.min(i.x,n.x),r=Math.max(i.x,n.x),o=Math.min(i.y,n.y),l=Math.max(i.y,n.y),c=400,d=Math.ceil((r-a)/e),p=Math.ceil((l-o)/e),u=e*Math.max(1,Math.ceil(d/c)),g=e*Math.max(1,Math.ceil(p/c)),h=Math.floor(a/u)*u,m=Math.floor(o/g)*g;this.gridLayer.clear();for(let f=h;f<=r;f+=u)this.gridLayer.moveTo(f,o),this.gridLayer.lineTo(f,l);for(let f=m;f<=l;f+=g)this.gridLayer.moveTo(a,f),this.gridLayer.lineTo(r,f);this.gridLayer.stroke({width:1,color:16777215,alpha:.08})}updateGameFrame(e){var i;let t=(i=this.getRuntimeScreenSize())!=null?i:e;!(t!=null&&t.width)||!(t!=null&&t.height)||this.lastGameFrameSize&&this.lastGameFrameSize.width===t.width&&this.lastGameFrameSize.height===t.height||(this.lastGameFrameSize={width:t.width,height:t.height},this.gameFrame.clear(),this.gameFrame.rect(0,0,t.width,t.height),this.gameFrame.stroke({width:2,color:6333946,alpha:.35}))}setPlayMode(e){var t,i,n,a;this.playModeEnabled!==e&&(this.playModeEnabled=e,e?(this.moveHandle.eventMode="none",this.scaleHandle.eventMode="none",this.rotateHandle.eventMode="none",(i=(t=this.app)==null?void 0:t.ticker)==null||i.add(this.syncFromGameObjects)):(this.moveHandle.eventMode="static",this.scaleHandle.eventMode="static",this.rotateHandle.eventMode="static",(a=(n=this.app)==null?void 0:n.ticker)==null||a.remove(this.syncFromGameObjects),this.syncFromConfig()),this.updateGizmos(),this.updateSpawnPointHandles())}syncFromGameObjectsInternal(e){var n,a,r,o,l,c,d,p;if(!this.app||!this.isVisible||!e&&!this.playModeEnabled)return;let t=window.gameObjectManager;if(!(t!=null&&t.get))return;let i=this.dragMode?this.selectedId:null;for(let[u,g]of this.objectMap.entries()){if(i&&u===i)continue;let h=t.get(u),m=((n=h==null?void 0:h.getDisplayObject)==null?void 0:n.call(h))||(h==null?void 0:h.pixiObject)||h;if(!m)continue;let f=(r=(a=g.displayObject)==null?void 0:a.parent)!=null?r:this.mainContainer,b=new q;if(typeof m.getGlobalPosition=="function"){m.getGlobalPosition(b);let y=f.toLocal(b);g.displayObject.position.set(y.x,y.y)}else if(m.worldTransform){b.set(m.worldTransform.tx,m.worldTransform.ty);let y=f.toLocal(b);g.displayObject.position.set(y.x,y.y)}let v=this.getWorldScale(m);if(v){let y=Number((l=(o=f.scale)==null?void 0:o.x)!=null?l:1)||1,w=Number((d=(c=f.scale)==null?void 0:c.y)!=null?d:1)||1,T=v.x/y,j=v.y/w;(p=g.displayObject.scale)!=null&&p.set?g.displayObject.scale.set(T,j):g.displayObject.scale&&(g.displayObject.scale.x=T,g.displayObject.scale.y=j)}let x=this.getWorldRotation(m);typeof x=="number"&&(g.displayObject.rotation=x),typeof m.zIndex=="number"&&(g.displayObject.zIndex=m.zIndex)}this.updateGizmos()}getWorldScale(e){var a,r;let t=(r=e==null?void 0:e.worldTransform)!=null?r:(a=e==null?void 0:e.transform)==null?void 0:a.worldTransform;if(!t)return null;let i=Math.sqrt(t.a*t.a+t.b*t.b),n=Math.sqrt(t.c*t.c+t.d*t.d);return!Number.isFinite(i)||!Number.isFinite(n)?null:{x:i,y:n}}getWorldRotation(e){var i,n;let t=(n=e==null?void 0:e.worldTransform)!=null?n:(i=e==null?void 0:e.transform)==null?void 0:i.worldTransform;if(t){let a=Math.atan2(t.b,t.a);return Number.isFinite(a)?a:null}return typeof(e==null?void 0:e.rotation)=="number"?e.rotation:null}centerCamera(){var a;if(!this.app)return;let e=(a=this.getRuntimeScreenSize())!=null?a:this.getScreen();if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=this.app.renderer.width,i=this.app.renderer.height,n=Math.max(.01,Math.min(t/e.width,i/e.height));this.cameraScale=n,this.camera.scale.set(n),this.camera.position.set((t-e.width*n)/2,(i-e.height*n)/2)}updateGizmos(){var d,p;if(!this.selectedId||!this.isVisible){this.clearGizmos();return}let e=this.objectMap.get(this.selectedId);if(!(e!=null&&e.displayObject)){this.clearGizmos();return}let t=(p=(d=e.displayObject).getBounds)==null?void 0:p.call(d);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let i=this.camera.toLocal(new q(t.x,t.y)),n=this.camera.toLocal(new q(t.x+t.width,t.y+t.height)),a=n.x-i.x,r=n.y-i.y,o=i.x+a/2,l=i.y+r/2;if(this.gizmoOutline.clear(),this.gizmoOutline.rect(i.x,i.y,a,r),this.gizmoOutline.stroke({width:2,color:16752394,alpha:.9}),this.playModeEnabled){this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear();return}let c=10;this.moveHandle.clear(),this.moveHandle.circle(0,0,c/2),this.moveHandle.fill({color:16752394,alpha:.9}),this.moveHandle.position.set(o,l),this.scaleHandle.clear(),this.scaleHandle.rect(-c/2,-c/2,c,c),this.scaleHandle.fill({color:3900150,alpha:.9}),this.scaleHandle.position.set(n.x,n.y),this.rotateHandle.clear(),this.rotateHandle.circle(0,0,c/2),this.rotateHandle.fill({color:1096065,alpha:.9}),this.rotateHandle.position.set(o,i.y-20)}clearGizmos(){this.gizmoOutline.clear(),this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear()}updateSpawnPointHandles(){if(this.clearSpawnPointHandles(),!this.selectedId)return;let e=this.getEditableObjectConfig(this.selectedId);if(!e||!this.isSpawnerConfig(e))return;let t=this.getSpawnPoints(e);!t||t.length===0||t.forEach((i,n)=>{let a=new Ee;a.circle(0,0,5).fill({color:16096779,alpha:.9}),a.circle(0,0,9).stroke({width:1,color:16096779,alpha:.45});let r=this.toCameraFromMain(i);a.position.set(r.x,r.y),a.cursor="move",a.eventMode=this.playModeEnabled?"none":"static",a.on("pointerdown",o=>this.startSpawnPointDrag(n,o)),this.spawnPointLayer.addChild(a)})}clearSpawnPointHandles(){this.spawnPointLayer.removeChildren().forEach(t=>{var i;(i=t.destroy)==null||i.call(t)})}isSpawnerConfig(e){var i,n;return((i=e==null?void 0:e.logic)==null?void 0:i.id)==="Spawner"?!0:String(((n=e==null?void 0:e.identity)==null?void 0:n.system_role)||"").toLowerCase().includes("spawner")}getSpawnPoints(e){var i,n;let t=(n=(i=e==null?void 0:e.logic)==null?void 0:i.props)==null?void 0:n.spawnPoints;return Array.isArray(t)?t.map(a=>{var r,o;return{x:Number((r=a==null?void 0:a.x)!=null?r:0),y:Number((o=a==null?void 0:a.y)!=null?o:0)}}):null}toCameraFromMain(e){let t=this.mainContainer.toGlobal(new q(e.x,e.y)),i=new q;return this.camera.toLocal(t,void 0,i),i}startSpawnPointDrag(e,t){var o,l;if(!this.selectedId||this.playModeEnabled)return;let i=this.getEditableObjectConfig(this.selectedId);if(!i)return;let n=this.getSpawnPoints(i);if(!n||!n[e])return;(o=t==null?void 0:t.stopPropagation)==null||o.call(t),(l=t==null?void 0:t.stopImmediatePropagation)==null||l.call(t);let a=this.getEventLocalPoint(t,this.mainContainer);if(!a)return;let r=n[e];this.spawnPointDrag={objectId:this.selectedId,index:e,offset:new q(r.x-a.x,r.y-a.y),startPoints:n.map(c=>({x:c.x,y:c.y}))},window.addEventListener("pointermove",this.onSpawnPointDragMove),window.addEventListener("pointerup",this.onSpawnPointDragEnd)}updateLiveSpawnPoint(e,t,i,n){let a=this.getEditableObjectConfig(e);if(!a)return;let r=this.getSpawnPoints(a);if(!r||!r[t])return;let o=r.map((l,c)=>c===t?{x:i,y:n}:{x:l.x,y:l.y});this.setNestedValue(a,"logic.props.spawnPoints",o),this.queueLiveApply(e),this.updateSpawnPointHandles()}setSelected(e,t={}){if(this.selectedId!==e&&(this.selectedId=e,this.updateGizmos(),this.updateSpawnPointHandles(),!t.silent&&e)){let i=window.__previewSelectObject;typeof i=="function"&&i(e)}}startDrag(e,t){var d,p,u,g;if(!this.selectedId||!e||!this.app||this.playModeEnabled||this.getPointerButton(t)!==0)return;let n=this.objectMap.get(this.selectedId);if(!n)return;this.dragContainer=(p=(d=n.displayObject)==null?void 0:d.parent)!=null?p:this.mainContainer;let a=this.getEventLocalPoint(t,this.dragContainer);if(!a)return;let r=n.displayObject;this.dragMode=e,this.dragStartPointer=new q(a.x,a.y),this.dragStartPos=new q(r.position.x,r.position.y),this.dragStartScale=typeof((u=r.scale)==null?void 0:u.x)=="number"?r.scale.x:1;let o=this.getEditableObjectConfig(this.selectedId),l=(g=o==null?void 0:o.transform)!=null?g:{};this.dragStartRotation=typeof l.rotation=="number"?l.rotation:0,this.dragAnchorLocal=this.getAnchorLocalPoint(l,this.dragContainer),this.dragStartValue=this.getDragStartValue(e,l);let c=new q(r.position.x,r.position.y);this.dragStartAngle=Math.atan2(a.y-c.y,a.x-c.x),this.dragStartDistance=Math.max(1,this.distance(a,c)),window.addEventListener("pointermove",this.onDragMove),window.addEventListener("pointerup",this.onDragEnd)}getDragStartValue(e,t){var i,n,a;return e==="move"?(i=t==null?void 0:t.position)!=null?i:{x:0,y:0}:e==="scale"?(n=t==null?void 0:t.scale)!=null?n:1:e==="rotate"?(a=t==null?void 0:t.rotation)!=null?a:0:null}updateLiveConfigPosition(e,t){var p,u,g,h,m,f;if(!this.selectedId||!this.dragAnchorLocal)return;let i=e-this.dragAnchorLocal.x,n=t-this.dragAnchorLocal.y,a=this.getEditableObjectConfig(this.selectedId);if(!a)return;let r=(p=a.transform)!=null?p:{};a.transform||(a.transform=r);let o=(u=r.offset)!=null?u:{x:0,y:0},l=Array.isArray(o)?Number((g=o[0])!=null?g:0):Number((h=o==null?void 0:o.x)!=null?h:0),c=Array.isArray(o)?Number((m=o[1])!=null?m:0):Number((f=o==null?void 0:o.y)!=null?f:0),d=this.buildPositionValue(r,{x:i-l,y:n-c});this.setNestedValue(r,"position",d)}updateLiveConfigScale(e){var n;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(n=t.transform)!=null?n:{};t.transform||(t.transform=i),i.scale=e}updateLiveConfigRotation(e){var n;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(n=t.transform)!=null?n:{};t.transform||(t.transform=i),i.rotation=e}applyFinalOverride(e,t,i,n){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),n),Re({objectId:e,path:t,value:i},{persist:!0,emitEvent:!0,trackHistory:!0})}queueLiveApply(e){this.applyQueuedId=e,!this.applyQueued&&(this.applyQueued=!0,requestAnimationFrame(()=>{this.applyQueued=!1;let t=this.applyQueuedId;if(!t)return;let i=this.getEditableObjectConfig(t),n=window.applyEditableObjectConfig;typeof n=="function"&&i&&n(t,i)}))}setNestedValue(e,t,i){let n=t.split("."),a=e;for(let r=0;r<n.length-1;r+=1){let o=n[r];(!a[o]||typeof a[o]!="object")&&(a[o]={}),a=a[o]}a[n[n.length-1]]=i}buildPositionValue(e,t){let i=e==null?void 0:e.position;return Array.isArray(i)?[t.x,t.y]:{x:t.x,y:t.y}}distance(e,t){let i=e.x-t.x,n=e.y-t.y;return Math.sqrt(i*i+n*n)}getPointerButton(e){var t,i,n;return typeof(e==null?void 0:e.button)=="number"?e.button:typeof((t=e==null?void 0:e.data)==null?void 0:t.button)=="number"?e.data.button:typeof((n=(i=e==null?void 0:e.data)==null?void 0:i.originalEvent)==null?void 0:n.button)=="number"?e.data.originalEvent.button:0}getEventGlobalPoint(e){var l,c;let t=(c=e==null?void 0:e.global)!=null?c:(l=e==null?void 0:e.data)==null?void 0:l.global;if(t)return new q(t.x,t.y);if(!this.app)return null;let i=e==null?void 0:e.clientX,n=e==null?void 0:e.clientY;if(typeof i!="number"||typeof n!="number")return null;let a=this.app.canvas.getBoundingClientRect(),r=(i-a.left)*(this.app.renderer.width/a.width),o=(n-a.top)*(this.app.renderer.height/a.height);return new q(r,o)}getEventLocalPoint(e,t=this.mainContainer){var a,r;if(!this.app)return null;if(typeof(e==null?void 0:e.getLocalPosition)=="function"){let o=e.getLocalPosition(t);return new q(o.x,o.y)}let i=(r=e==null?void 0:e.global)!=null?r:(a=e==null?void 0:e.data)==null?void 0:a.global;if(!i)return null;let n=new q;return t.toLocal(new q(i.x,i.y),void 0,n),n}getPointerInContainer(e,t,i){if(!this.app)return null;let n=this.app.canvas.getBoundingClientRect(),a=(e-n.left)*(this.app.renderer.width/n.width),r=(t-n.top)*(this.app.renderer.height/n.height),o=new q;return i.toLocal(new q(a,r),void 0,o),o}parseColor(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=e.trim().replace("#",""),n=Number.parseInt(i,16);if(Number.isFinite(n))return n}return t}};var Fn=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[at("playable-portrait"),at("iphone-14"),at("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.isSpaceKeyPressed=!1;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.originalConsole={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console)};this.sceneEditor=null;this.sceneVisiblePreference=!0;this.sceneVisible=!0;this.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.hasUnsavedChanges=!1;this.onWindowResize=e=>{if(this.ignoreNextWindowResize){this.ignoreNextWindowResize=!1;return}this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()};this.onFrameDragMove=e=>{if(!this.frameDragActive)return;let t=e.clientX-this.frameDragStartX,i=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+i,this.applyFrameDrag(),this.updateDragCursor()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd),this.updateDragCursor())};this.options=e,this.currentPreset=at(e.defaultDevice||ln.id),this.debugPanel=new Mi,this.container=this.createShell(),this.previewContainer=this.mustQuery(".preview-container"),this.singleStage=this.mustQuery('[data-preview-stage="single"]'),this.compareStage=this.mustQuery('[data-preview-stage="compare"]'),this.frameDragger=this.mustQuery(".frame-dragger"),this.frameWrapper=this.mustQuery(".frame-wrapper"),this.deviceFrame=this.mustQuery(".device-frame"),this.gameContainer=this.mustQuery(".game-container"),this.scenePane=this.mustQuery("[data-scene-pane]"),this.sceneRoot=this.mustQuery("#scene-editor-root"),this.sceneSplitter=this.mustQuery("[data-scene-splitter]"),this.gameViewPane=this.mustQuery("[data-game-pane]"),this.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners();try{let t=window.localStorage.getItem(this.getSceneVisibilityStorageKey());this.sceneVisiblePreference=t===null?!0:t==="true"}catch{}this.sceneEditor=new $i({root:this.sceneRoot,getScreen:()=>this.getScreen()}),this.sceneEditor.mount(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setupShortcutListeners(),this.setupUnsavedChangesIndicator(),this.setupScenePaneInteractions(),this.updateSceneVisibility(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.updateDockState(),this.isInitialized=!0}getShortcutKey(){return typeof navigator!="undefined"&&navigator.platform.toUpperCase().indexOf("MAC")>=0?"CMD":"CTRL"}mount(e=document.body){e.innerHTML="",e.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1,this.sceneEditor&&(this.sceneEditor.destroy(),this.sceneEditor=null)}getGameContainer(){return this.gameContainer}getScreen(){let e=this.getEffectivePreset();return{width:e.width,height:e.height}}getEffectivePreset(){var e;return this.isLandscape?{...this.currentPreset,width:this.currentPreset.height,height:this.currentPreset.width,ratio:((e=this.currentPreset.ratio)==null?void 0:e.split(":").reverse().join(":"))||this.currentPreset.ratio}:this.currentPreset}notifyGameLoaded(){var e;this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh(),(e=this.sceneEditor)==null||e.refresh(),requestAnimationFrame(()=>this.updatePanelPositions())}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(e,t={}){var n,a;let i=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=at(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:i}),t.suppressCallback||(a=(n=this.options).onDeviceChange)==null||a.call(n,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark"),requestAnimationFrame(()=>this.updatePanelPositions())}setLayoutMode(e){if(this.layoutMode===e)return;this.layoutMode=e,this.container.classList.toggle("layout-fixed",e==="fixed"),this.container.classList.toggle("layout-draggable",e==="draggable"),Array.from(this.container.querySelectorAll("[data-layout-toggle]")).forEach(n=>n.classList.toggle("active",n.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(n=>{n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),this.updateSceneVisibility(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}updateDockState(){let e=this.container.querySelector("#bottom-dock");e==null||e.classList.remove("hidden");let t=this.container.querySelector("#console-messages"),i=this.container.querySelector("#dock-console-content");t&&i&&t.parentElement!==i&&i.appendChild(t)}makeBottomDockResizable(e,t){let i,n,a=o=>{let l=o.clientY-i,c=Math.max(100,Math.min(800,n-l));e.style.height=`${c}px`;let d=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:d})},r=()=>{document.removeEventListener("pointermove",a),document.removeEventListener("pointerup",r),e.classList.remove("resizing")};t.addEventListener("pointerdown",o=>{o.preventDefault(),i=o.clientY,n=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",r),e.classList.add("resizing")})}makeSidebarResizable(e,t,i){let n,a,r=l=>{let c=i==="left"?l.clientX-n:n-l.clientX,d=Math.max(200,Math.min(600,a+c));e.style.width=`${d}px`;let p=this.container.querySelector(".preview-main");if(p){let g=i==="left"?`${d}px`:p.style.gridTemplateColumns.split(" ")[0]||"300px",h=i==="right"?`${d}px`:p.style.gridTemplateColumns.split(" ")[2]||"350px";p.style.gridTemplateColumns=`${g} 1fr ${h}`}let u=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:u})},o=()=>{document.removeEventListener("pointermove",r),document.removeEventListener("pointerup",o),e.classList.remove("resizing")};t.addEventListener("pointerdown",l=>{l.preventDefault(),n=l.clientX,a=e.offsetWidth,document.addEventListener("pointermove",r),document.addEventListener("pointerup",o),e.classList.add("resizing")})}getSceneVisibilityStorageKey(){return`handler_preview_scene_visible::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getSceneWidthStorageKey(){return`handler_preview_scene_width::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}setupScenePaneInteractions(){let e=this.scenePane.querySelector("[data-scene-drag-handle]"),t=this.scenePane.querySelector("[data-scene-resize]"),i=this.container.querySelector("[data-preview-split]");e&&Xe(this.scenePane,e,i!=null?i:this.previewContainer),t&&Ti(this.scenePane,t,void 0,260,200);let n=this.getStoredSceneWidth();n&&(this.scenePane.style.width=`${n}px`),this.sceneSplitter.addEventListener("pointerdown",a=>{if(this.layoutMode!=="fixed"||!this.sceneVisible)return;a.preventDefault();let r=a.clientX,o=this.scenePane.offsetWidth,l=Math.max(260,Math.min(720,this.previewContainer.clientWidth*.6)),c=p=>{let u=p.clientX-r,g=Math.max(240,Math.min(l,o+u));this.scenePane.style.width=`${g}px`;let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},d=()=>{document.removeEventListener("pointermove",c),document.removeEventListener("pointerup",d),this.storeSceneWidth(this.scenePane.offsetWidth)};document.addEventListener("pointermove",c),document.addEventListener("pointerup",d)})}storeSceneWidth(e){try{window.localStorage.setItem(this.getSceneWidthStorageKey(),String(e))}catch{}}getStoredSceneWidth(){try{let e=window.localStorage.getItem(this.getSceneWidthStorageKey()),t=e?Number(e):null;return Number.isFinite(t)&&t?t:null}catch{return null}}updateSceneVisibility(){let e=this.viewMode==="single"&&this.sceneVisiblePreference;this.setSceneVisible(e,{persist:!1});let t=this.container.querySelector("#scene-toggle");t&&(t.classList.toggle("active",this.sceneVisiblePreference),t.setAttribute("aria-pressed",String(this.sceneVisiblePreference)))}setSceneVisible(e,t={}){var i;if(this.sceneVisible=e,this.container.classList.toggle("scene-hidden",!e),(i=this.sceneEditor)==null||i.setVisible(e),t.persist!==!1){this.sceneVisiblePreference=e;try{window.localStorage.setItem(this.getSceneVisibilityStorageKey(),String(e))}catch{}}this.scheduleFit()}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell layout-fixed",e.innerHTML=`
2237
+ `,this.modal=e,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var i;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(i=this.options)!=null&&i.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,i=this.cropX+this.cropWidth/2,n=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,i-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,n-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let e=this.panX,t=this.panY,i=this.cropWidth*this.scale,n=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,i,n),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,i,n),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+i-a,t],[e,t+n-a],[e+i-a,t+n-a]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,a,a)})}updatePreview(){if(!this.modal||!this.image)return;let e=this.modal.querySelector(".asset-crop-preview-canvas");if(!e)return;let t=e.getContext("2d");if(!t)return;let i=150;e.width=i,e.height=i;let n=i/this.cropWidth,a=i/this.cropHeight,r=Math.min(n,a),o=this.cropWidth*r,l=this.cropHeight*r,c=(i-o)/2,d=(i-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,d,o,l)}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let e=this.modal.querySelector(".asset-crop-zoom-slider");e==null||e.addEventListener("input",i=>{let n=parseFloat(i.target.value);this.setZoom(n)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",i=>{let n=i.target.value;this.setAspectRatio(n)}),this.modal.addEventListener("click",i=>{switch(i.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",i=>{i.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,i=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,i=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var n;if(!this.image||!((n=this.options)!=null&&n.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let i=e.toDataURL("image/png");this.options.onCrop(i),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(s){new Dn().open(s)};import{Application as uo,Container as Ge,Graphics as Ee,Point as q,Rectangle as Fr,Text as go,TextStyle as ho}from"pixi.js";import{Sprite as Fs,Container as Hr}from"pixi.js";var Bs=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",$n=Bs;if(typeof window!="undefined")try{let s=new XMLHttpRequest;if(s.open("GET","./build-settings.json",!1),s.send(),s.status===200&&s.responseText){let e=JSON.parse(s.responseText);e!=null&&e.buildMode&&($n=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${$n}`))}}catch{}function Us(s){var t,i,n,a,r;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(s);let e={center:{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};if(Array.isArray(s))return{x:(t=s[0])!=null?t:.5,y:(i=s[1])!=null?i:.5};if(s&&typeof s=="object"&&"x"in s&&"y"in s)return{x:(n=s.x)!=null?n:.5,y:(a=s.y)!=null?a:.5};if(typeof s=="string"){let o=s.trim().toLowerCase();return(r=e[o])!=null?r:{x:.5,y:.5}}return null}var xe=class{static async create(e,t,i){var l,c,d,p,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${$n}`);let n=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!n){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let m=new Hr;return this.applyTransform(m,t==null?void 0:t.transform,t),m}let a=(c=t==null?void 0:t.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${e}, configId: ${a}, type: ${n.type}, path: ${n.path}`);let r=await Xi.load(e,n,i,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(d=r==null?void 0:r.constructor)==null?void 0:d.name}`);let o;if(n.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",r,"for object:",e),o=new Fs(r),console.log("[ObjectFactory] Created object:",o,"type:",(p=o==null?void 0:o.constructor)==null?void 0:p.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(n.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=r==null?void 0:r.constructor)==null?void 0:u.name,r),r&&(((g=r.constructor)==null?void 0:g.name)==="Container"||r instanceof Hr)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let m=[n.path,`/assets/${n.path}`,`assets/${n.path}`,`../assets/${n.path}`],f=!1;for(let b of m)try{let v=await fetch(b);if(v.ok){o=await v.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(h=o==null?void 0:o.constructor)==null?void 0:h.name),f=!0;break}}catch{continue}f||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=r)}else o=r;else o=r,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,i){var n,a,r,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(n=t.position.x)!=null?n:0,e.y=(a=t.position.y)!=null?a:0):"position"in e&&e.position&&e.position.set((r=t.position.x)!=null?r:0,(o=t.position.y)!=null?o:0)),t.scale!==void 0&&"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(t.scale):e.scale=t.scale),t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor)){let l=Us(t.anchor);l&&("set"in e.anchor?e.anchor.set(l.x,l.y):(e.anchor.x=l.x,e.anchor.y=l.y))}}};import{Graphics as Gs,Point as qs}from"pixi.js";var Pe={width:400,height:600,designWidth:400,scaleFactor:1},ji={scale:1,position:1},_i=[];function Vs(s,e,t,i,n,a,r){_i.push({element:s,originalScale:a,positionHelper:e,heightPercent:n}),e(s,t,i,n,a,r,!1)}function Ws(){_i.forEach(({element:s,originalScale:e,positionHelper:t,heightPercent:i})=>{let n=e*Pe.scaleFactor;t(s,Pe.width,Pe.height,i,n,!0,!1)})}function Ys(){_i.length=0,console.log("[LAYOUT] Cleared all responsive elements")}function Hn(s,e){console.log(`[SCREEN] updateScreenState called: ${s}x${e}`),Pe.width=s,Pe.height=e,Pe.scaleFactor=Math.min(s/Pe.designWidth,1.15),ji.scale=Pe.scaleFactor,ji.position=1,console.log(`[SCREEN] Global multipliers - scale: ${ji.scale.toFixed(3)}`),Ws()}var B={layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}};function Ks(s,e,t){let i=B[s];i&&i[e]!==void 0&&(i[e]=t,console.log(`Updated ${s}.${e} = ${t}`))}function Xs(){return B}var Js={center:{x:.5,y:.5},"center-center":{x:.5,y:.5},middle:{x:.5,y:.5},"middle-center":{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},"left-center":{x:0,y:.5},"right-center":{x:1,y:.5},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};function Ii(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Fe(s,e={x:.5,y:.5}){var t;if(Array.isArray(s))return{x:Ii(s[0],e.x),y:Ii(s[1],e.y)};if(s&&typeof s=="object"){let i=s;return{x:Ii(i.x,e.x),y:Ii(i.y,e.y)}}if(typeof s=="string"){let i=s.trim().toLowerCase();return(t=Js[i])!=null?t:e}return e}function Be(s,e,t,i={}){var g,h,m,f,b,v;let n=Fe(t),a=(g=i.inset)!=null?g:{},r=(h=i.padding)!=null?h:{x:0,y:0},o=((m=a.left)!=null?m:0)+r.x,l=((f=a.right)!=null?f:0)+r.x,c=((b=a.top)!=null?b:0)+r.y,d=((v=a.bottom)!=null?v:0)+r.y,p=Math.max(0,s-o-l),u=Math.max(0,e-c-d);return{x:o+p*n.x,y:c+u*n.y}}function Ue(s,e,t,i={}){var m,f,b,v,x,y;let n=(m=i.inset)!=null?m:{},a=(f=i.padding)!=null?f:{x:0,y:0},r=((b=n.left)!=null?b:0)+a.x,o=((v=n.right)!=null?v:0)+a.x,l=((x=n.top)!=null?x:0)+a.y,c=((y=n.bottom)!=null?y:0)+a.y,d=Math.max(0,s-r-o),p=Math.max(0,e-l-c),u=Fe(t,{x:.5,y:.5}),g=Math.min(Math.max(u.x,0),1),h=Math.min(Math.max(u.y,0),1);return{x:r+d*g,y:l+p*h}}function Nn(s,e,t,i={}){var d,p,u;if(!s)return;let n=i.positionRatio?Ue(e,t,i.positionRatio,{inset:i.inset,padding:i.screenPadding}):Be(e,t,i.anchor,{inset:i.inset,padding:i.screenPadding}),a=(d=i.offset)!=null?d:{x:0,y:0},r=n.x+a.x,o=n.y+a.y;s.anchor&&i.renderAnchor&&s.anchor.set(i.renderAnchor.x,i.renderAnchor.y),be(s,r,o);let l=(p=i.scale)!=null?p:1,c=(u=i.scaleMultiplier)!=null?u:1;(i.scale!==void 0||i.scaleMultiplier!==void 0)&&Se(s,l*c)}if(typeof window!="undefined"){let s=window.innerWidth,e=window.innerHeight,t=()=>{let i=window.innerWidth,n=window.innerHeight;(i!==s||n!==e)&&(s=i,e=n,Hn(i,n))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),Hn(window.innerWidth,window.innerHeight),window.updateDebugConfig=Ks,window.getDebugConfig=Xs,window.copyConfig=lo,window.applyConfig=Lt,window.applyConfigForRatio=co,window.positionAtBottom=Nr,window.positionAtTop=eo,window.positionAtCenter=to,window.positionAtLeft=io,window.positionAtRight=no,window.positionAtBottomLeft=ao,window.positionAtBottomRight=ro,window.positionAtTopLeft=so,window.positionAtTopRight=oo,window.applyPositionContract=Qs,console.log("\u{1F3AE} Debug Config Functions Available:"),console.log("\u2022 updateDebugConfig(category, key, value)"),console.log("\u2022 getDebugConfig()"),console.log("\u2022 copyConfig(presetName)"),console.log("\u2022 applyConfig(config)"),console.log("\u2022 applyConfigForRatio(width, height)"),console.log("\u{1F4CD} Positioning Helpers Available (with scale):"),console.log("\u2022 positionAtBottom(element, w, h, percent, scale)"),console.log("\u2022 positionAtTop(element, w, h, percent, scale)"),console.log("\u2022 positionAtCenter(element, w, h, offsetX, offsetY, scale)"),console.log("\u2022 positionAtLeft/Right(element, w, h, percent, scale)"),console.log("\u2022 Corner positions: BottomLeft/Right, TopLeft/Right (all with scale)"),console.log("\u2022 applyPositionContract(element, w, h, contract)"),console.log("Example: positionAtCenter(mySprite, 400, 600, 0, -50, 1.2)")}function Oi(s,e,t=0){return s*e+t}function zi(s,e,t=0){return s*(1-e)+t}function Ri(s,e,t=0){return s*e+t}function Di(s,e,t=0){return s*(1-e)+t}function ge(s,e=0){return s/2+e}function Zs(s,e){return s*e}function Qs(s,e,t,i){var r,o,l,c,d,p,u,g,h,m,f,b,v,x,y,w,T,j,P,_;let n=0,a=0;switch(i.type){case"top":n=ge(e,(o=(r=i.offset)==null?void 0:r.x)!=null?o:0),a=Oi(t,i.percent,(c=(l=i.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":n=ge(e,(p=(d=i.offset)==null?void 0:d.x)!=null?p:0),a=zi(t,i.percent,(g=(u=i.offset)==null?void 0:u.y)!=null?g:0);break;case"left":n=Ri(e,i.percent,(m=(h=i.offset)==null?void 0:h.x)!=null?m:0),a=ge(t,(b=(f=i.offset)==null?void 0:f.y)!=null?b:0);break;case"right":n=Di(e,i.percent,(x=(v=i.offset)==null?void 0:v.x)!=null?x:0),a=ge(t,(w=(y=i.offset)==null?void 0:y.y)!=null?w:0);break;case"center":n=ge(e,(j=(T=i.offset)==null?void 0:T.x)!=null?j:0),a=ge(t,(_=(P=i.offset)==null?void 0:P.y)!=null?_:0);break}s.position?s.position.set(n,a):(s.x=n,s.y=a),i.scale!==void 0&&i.scale!==1&&s.scale&&(typeof s.scale.set=="function"?s.scale.set(i.scale,i.scale):(s.scale.x=i.scale,s.scale.y=i.scale))}function Nr(s,e,t,i=.2,n=1,a=!0,r=!1){let o=Zs(t,i),l=zi(t,i/2);be(s,ge(e),l);let c=a?n*Pe.scaleFactor:n;Se(s,c),r&&!_i.find(d=>d.element===s)&&Vs(s,Nr,e,t,i,n,a)}function eo(s,e,t,i=.1,n=1){be(s,ge(e),Oi(t,i)),Se(s,n)}function to(s,e,t,i=0,n=0,a=1){be(s,ge(e,i),ge(t,n)),Se(s,a)}function io(s,e,t,i=.1,n=1){be(s,Ri(e,i),ge(t)),Se(s,n)}function no(s,e,t,i=.1,n=1){be(s,Di(e,i),ge(t)),Se(s,n)}function ao(s,e,t,i=.05,n=.05,a=1){be(s,Ri(e,n),zi(t,i)),Se(s,a)}function ro(s,e,t,i=.05,n=.05,a=1){be(s,Di(e,n),zi(t,i)),Se(s,a)}function so(s,e,t,i=.05,n=.05,a=1){be(s,Ri(e,n),Oi(t,i)),Se(s,a)}function oo(s,e,t,i=.05,n=.05,a=1){be(s,Di(e,n),Oi(t,i)),Se(s,a)}function be(s,e,t){s&&s.position?typeof s.position.set=="function"?s.position.set(e,t):(s.position.x=e,s.position.y=t):s&&(s.x=e,s.y=t)}function Se(s,e){e!==1&&s&&s.scale&&(typeof s.scale.set=="function"?s.scale.set(e,e):s.scale.x!==void 0&&s.scale.y!==void 0&&(s.scale.x=e,s.scale.y=e))}var Ze={default:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}},wide:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.9,screen_scale_y:1.1},engine:{scale:1,background_scale:1.1,background_offset_y:0,background_alpha:.95,label_pulse_speed:3,label_pulse_intensity:.03}},square:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.85,screen_scale_y:.85},engine:{scale:1,background_scale:1,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}},tall:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1.1,screen_scale_y:.9},engine:{scale:1,background_scale:.95,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}}};function lo(s){return s&&Ze[s]?JSON.parse(JSON.stringify(Ze[s])):JSON.parse(JSON.stringify(B))}function Lt(s){Object.keys(s).forEach(e=>{let t=e;B[t]&&s[t]&&Object.assign(B[t],s[t])}),console.log("Config applied:",s)}function co(s,e){let t=s/e;t>1.6?(Lt(Ze.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(Lt(Ze.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(Lt(Ze.square),console.log("Applied SQUARE config for ratio:",t)):(Lt(Ze.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let s=window;s.configPresets=Ze,s.resolveAnchorVec2=s.resolveAnchorVec2||Fe,s.resolveScreenAnchorPoint=s.resolveScreenAnchorPoint||Be,s.resolveScreenRatioPoint=s.resolveScreenRatioPoint||Ue}var oe=null;function po(s,e,t,i,n,a={}){var I,M,z,R,N,H,F,G,K,ee,ne,le,$,Q,ce,he,de,ve,Le,Te,V,te,X,re,Oe,We,ca,da,pa,ua,ga,ha,ma,fa;let r=(I=a.enableDebugLogs)!=null?I:!1;r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== STARTING LAYOUT CALCULATION ====="),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Screen dimensions:",{width:i.width,height:i.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Time:",t),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Options:",a));let{mainContainer:o,label:l,background:c,backgroundTexture:d,app:p}=s;if(!p||!p.renderer){r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] \u274C No app or renderer, skipping layout");return}r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] App renderer dimensions:",{width:p.renderer.width,height:p.renderer.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] App screen dimensions:",{width:p.screen.width,height:p.screen.height}));let u=i.width,g=i.height;r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Base dimensions:",{baseWidth:u,baseHeight:g});let h=u*B.layout.screen_scale_x,m=g*B.layout.screen_scale_y,f=u/2,b=e.engine.runtime||{},v=b.layout||{};r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug config:",{screen_scale_x:B.layout.screen_scale_x,screen_scale_y:B.layout.screen_scale_y}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Calculated dimensions:",{width:h,height:m,midX:f}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Engine runtime:",b),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Layout config:",v));let x=v.design_width_portrait||400,y=h/x;y=Math.min(y,1.15);let w=y*((M=B.engine.scale)!=null?M:1),T=(z=a.skipMainContainerTransform)!=null?z:!1;!T&&o&&o.scale&&(typeof o.scale.set=="function"?o.scale.set(w):(o.scale.x=w,o.scale.y=w));let j=(R=v.main_container_anchor)!=null?R:"center",P=(N=v.main_container_position_ratio)!=null?N:{x:.5,y:.5},_=(H=v.main_container_offset)!=null?H:{x:0,y:0},O=v.main_container_position_ratio?Ue(u,g,P):Be(u,g,j),L=O.x+_.x+B.layout.position_offset.x,A=O.y+_.y+B.layout.position_offset.y;if(!T&&o&&o.position&&(typeof o.position.set=="function"?o.position.set(L,A):(o.position.x=L,o.position.y=A)),n&&(o!=null&&o.toLocal))for(let[se,ae]of e.objects.entries()){let W=ae==null?void 0:ae.transform;if(!W||((F=W.position_mode)!=null?F:"static")!=="static")continue;let U=(G=n.get)==null?void 0:G.call(n,se),ye=((K=U==null?void 0:U.getDisplayObject)==null?void 0:K.call(U))||(U==null?void 0:U.pixiObject)||U;if(!ye||ye.parent!==o)continue;let Ht=W.position_ratio!=null?Ue(u,g,W.position_ratio):Be(u,g,(ee=W.anchor)!=null?ee:"center"),Nt=o.toLocal(new qs(Ht.x,Ht.y)),Ft=(ne=W.position)!=null?ne:{x:0,y:0},Ye=Nt.x+Ft.x,Ki=Nt.y+Ft.y;typeof(U==null?void 0:U.setPosition)=="function"?U.setPosition(Ye,Ki):(be(ye,Ye,Ki),(le=U==null?void 0:U.transform)!=null&&le.position&&(U.transform.position.x=Ye,U.transform.position.y=Ki))}let k=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,S=((k==null?void 0:k.buildMode)||(typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"dev"))==="dev";if(B.layout.debug_rect_visible&&S){(!oe||oe.parent!==p.stage)&&(oe==null||oe.destroy(),oe=new Gs,oe.zIndex=9999,p.stage.addChild(oe)),oe.clear();let se=B.layout.debug_rect_scale_x,ae=B.layout.debug_rect_scale_y,W=(u-4)*se,ze=(g-4)*ae,U=(u-W)/2,ye=(g-ze)/2;r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== DEBUG RECT POSITIONING ====="),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug rect calculations:",{baseWidth:u,baseHeight:g,rectW:W,rectH:ze,offsetX:U,offsetY:ye}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug rect final position:",{x:2+U,y:2+ye,width:W,height:ze})),oe.rect(2+U,2+ye,W,ze).stroke({width:B.layout.debug_rect_thickness,color:B.layout.debug_rect_color})}else oe&&(oe.destroy(),oe=null);let E=(($=s.label)==null?void 0:$.config)||e.objects.get("label_1")||e.objects.get("ui_tutorial_1");if(l&&l.position&&E){let se=(ce=(Q=E==null?void 0:E.transform)==null?void 0:Q.anchor)!=null?ce:"center",ae=(he=E==null?void 0:E.transform)==null?void 0:he.position_ratio,W=((de=E==null?void 0:E.transform)==null?void 0:de.offset)||{x:0,y:0};Nn(l,u,g,{anchor:se,positionRatio:ae,offset:{x:W.x*w,y:W.y*w},renderAnchor:Fe(se)})}if(l&&l.alpha>0){let se=1+Math.sin(t*B.engine.label_pulse_speed)*B.engine.label_pulse_intensity,ae=(Le=(ve=E==null?void 0:E.transform)==null?void 0:ve.scale)!=null?Le:1,W=se*w*ae;l.scale&&(typeof l.scale.set=="function"?l.scale.set(W):(l.scale.x=W,l.scale.y=W))}if(r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== BACKGROUND POSITIONING ====="),c){r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background object exists:",!!c),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background type:",(Te=c.constructor)==null?void 0:Te.name)),c.alpha=((te=(V=b.background)==null?void 0:V.alpha)!=null?te:.98)*B.engine.background_alpha,r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background alpha set to:",c.alpha);let se=e.objects.get("background_1");r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background config:",se);let ae=(se==null?void 0:se.transform)||{};r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background transform:",ae);let W=ae.offset||{x:0,y:0},ze=((re=(X=b.background)==null?void 0:X.offset_y)!=null?re:0)+B.engine.background_offset_y,U=(Oe=ae.anchor)!=null?Oe:"center",ye=ae.position_ratio;if(r&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background positioning params:",{bgOffset:W,bgRuntimeOffsetY:ze,bgScreenAnchor:U,bgPositionRatio:ye,baseWidth:u,baseHeight:g,finalScale:w}),Nn(c,u,g,{anchor:U,positionRatio:ye,offset:{x:W.x*w,y:W.y*w+ze},renderAnchor:Fe(U)}),r&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background position after applyScreenAnchor:",{x:c.x,y:c.y,scaleX:(We=c.scale)==null?void 0:We.x,scaleY:(ca=c.scale)==null?void 0:ca.y,anchorX:(da=c.anchor)==null?void 0:da.x,anchorY:(pa=c.anchor)==null?void 0:pa.y,pivotX:(ua=c.pivot)==null?void 0:ua.x,pivotY:(ga=c.pivot)==null?void 0:ga.y,width:c.width,height:c.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background texture dimensions:",{textureWidth:d==null?void 0:d.width,textureHeight:d==null?void 0:d.height})),d){let Ht=Math.max(h/d.width,m/d.height),Nt=(ma=(ha=b.background)==null?void 0:ha.scale_multiplier)!=null?ma:1.05,Ft=(fa=ae.scale)!=null?fa:1,Ye=Ht*Nt*B.engine.background_scale*Ft;c.scale&&(typeof c.scale.set=="function"?c.scale.set(Ye):(c.scale.x=Ye,c.scale.y=Ye))}else c&&typeof c.clear=="function"&&(c.clear(),c.rect(-h/2,-m/2,h,m).fill({color:1444375}))}}var $i=class{constructor(e){this.app=null;this.camera=new Ge;this.mainContainer=new Ge;this.uiContainer=new Ge;this.gizmoLayer=new Ge;this.screenFrame=new Ee;this.gameFrame=new Ee;this.gridLayer=new Ee;this.spawnPointLayer=new Ge;this.objectMap=new Map;this.selectedId=null;this.dragMode=null;this.dragStartPointer=null;this.dragStartPos=null;this.dragStartScale=1;this.dragStartRotation=0;this.dragStartAngle=0;this.dragStartDistance=1;this.dragAnchorLocal=null;this.dragStartValue=null;this.dragContainer=null;this.spawnPointDrag=null;this.lastGameFrameSize=null;this.cameraScale=1;this.isPanning=!1;this.panStart=null;this.panStartCamera=null;this.hasUserCamera=!1;this.resizeObserver=null;this.screenSyncRaf=null;this.gizmoOutline=new Ee;this.moveHandle=new Ee;this.scaleHandle=new Ee;this.rotateHandle=new Ee;this.isVisible=!0;this.applyQueued=!1;this.applyQueuedId=null;this.gridEnabled=!1;this.gridGap=50;this.lastPickPoint=null;this.lastPickIds=[];this.lastPickIndex=0;this.lastPickTime=0;this.playModeEnabled=!1;this.handleScreenChange=e=>{if(!(e!=null&&e.detail))return;let{width:t,height:i}=e.detail;!t||!i||(this.hasUserCamera=!1,this.updateLayout({width:t,height:i}),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid(),this.schedulePostScreenSync({width:t,height:i}))};this.handleActiveScreenChanged=()=>{this.isVisible&&this.syncFromConfig()};this.handleConfigChanged=e=>{if(!this.isVisible)return;this.updateLayout(),this.updateGrid();let t=e==null?void 0:e.detail;if(!t){this.syncFromConfig();return}let i=t.objectId,n=t.objectIds;if(i){this.syncFromConfig([i]);return}if(Array.isArray(n)&&n.length>0){this.syncFromConfig(n);return}this.syncFromConfig()};this.handleSceneRefresh=()=>{this.isVisible&&this.syncFromConfig()};this.handleLayoutApplied=e=>{var r;if(!this.isVisible)return;let t=(r=e==null?void 0:e.detail)!=null?r:{},i=Number(t.width),n=Number(t.height),a=Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:this.getScreen();this.updateLayout(a),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.syncFromGameObjectsInternal(!0),this.updateGizmos(),this.updateGrid()})};this.handlePreviewSelect=e=>{var i,n;let t=(n=(i=e==null?void 0:e.detail)==null?void 0:i.objectId)!=null?n:null;this.setSelected(t,{silent:!0})};this.onStagePointerDown=e=>{if(!this.app||!this.isVisible||this.getPointerButton(e)!==0||this.isGizmoTarget(e==null?void 0:e.target))return;let i=this.getEventGlobalPoint(e);if(!i)return;let n=new q(i.x,i.y),a=this.getPickCandidates(n);if(a.length===0){this.setSelected(null),this.lastPickIds=[],this.lastPickIndex=0,this.lastPickPoint=n,this.lastPickTime=performance.now();return}let r=performance.now(),o=this.areSameIds(a,this.lastPickIds),l=this.lastPickPoint&&this.distance(n,this.lastPickPoint)<=6,c=r-this.lastPickTime<1200,d=o&&l&&c?(this.lastPickIndex+1)%a.length:0,p=a[d];this.lastPickIds=a,this.lastPickIndex=d,this.lastPickPoint=n,this.lastPickTime=r,this.setSelected(p),this.playModeEnabled||this.startDrag("move",e)};this.handleGridSettings=e=>{var n,a;let t=(n=e==null?void 0:e.detail)==null?void 0:n.enabled,i=(a=e==null?void 0:e.detail)==null?void 0:a.gap;typeof t=="boolean"&&(this.gridEnabled=t),typeof i=="number"&&Number.isFinite(i)&&i>2&&(this.gridGap=i),this.updateGrid()};this.handlePlayMode=e=>{var i;let t=(i=e==null?void 0:e.detail)==null?void 0:i.enabled;typeof t=="boolean"&&this.setPlayMode(t)};this.syncFromGameObjects=()=>{this.syncFromGameObjectsInternal(!1)};this.onSpawnPointDragMove=e=>{if(!this.spawnPointDrag)return;let t=this.getPointerInContainer(e.clientX,e.clientY,this.mainContainer);if(!t)return;let i=t.x+this.spawnPointDrag.offset.x,n=t.y+this.spawnPointDrag.offset.y;this.updateLiveSpawnPoint(this.spawnPointDrag.objectId,this.spawnPointDrag.index,i,n)};this.onSpawnPointDragEnd=()=>{if(!this.spawnPointDrag)return;let{objectId:e,startPoints:t}=this.spawnPointDrag,i=this.getEditableObjectConfig(e),n=i?this.getSpawnPoints(i):null;i&&n&&(this.setNestedValue(i,"logic.props.spawnPoints",t),Re({objectId:e,path:"logic.props.spawnPoints",value:n},{persist:!0,emitEvent:!0,trackHistory:!0}),this.queueLiveApply(e)),this.spawnPointDrag=null,window.dispatchEvent(new CustomEvent("inspector:refresh")),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd)};this.onDragMove=e=>{var a;if(!this.dragMode||!this.selectedId||!this.app||this.playModeEnabled)return;let t=this.objectMap.get(this.selectedId);if(!t)return;let i=(a=this.dragContainer)!=null?a:this.mainContainer,n=this.getPointerInContainer(e.clientX,e.clientY,i);if(!(!n||!this.dragStartPointer||!this.dragStartPos)){if(this.dragMode==="move"){let r=n.x-this.dragStartPointer.x,o=n.y-this.dragStartPointer.y,l=this.dragStartPos.x+r,c=this.dragStartPos.y+o;t.displayObject.position.set(l,c),this.updateLiveConfigPosition(l,c)}else if(this.dragMode==="scale"){let r=new q(this.dragStartPos.x,this.dragStartPos.y),o=Math.max(1,this.distance(n,r)),l=Math.max(.05,this.dragStartScale*(o/this.dragStartDistance));t.displayObject.scale.set(l),this.updateLiveConfigScale(l)}else if(this.dragMode==="rotate"){let r=new q(this.dragStartPos.x,this.dragStartPos.y),l=Math.atan2(n.y-r.y,n.x-r.x)-this.dragStartAngle,c=this.dragStartRotation+l;t.displayObject.rotation=c,this.updateLiveConfigRotation(c)}this.updateGizmos(),this.queueLiveApply(this.selectedId)}};this.onDragEnd=()=>{var i,n,a,r,o,l,c;if(!this.dragMode||!this.selectedId)return;let e=this.selectedId,t=this.getEditableObjectConfig(e);if(t){let d=(i=t.transform)!=null?i:{};if(t.transform||(t.transform=d),this.dragMode==="move"&&this.dragStartValue){let p=d.position,u=Array.isArray(p)?[Number((n=p[0])!=null?n:0),Number((a=p[1])!=null?a:0)]:{x:Number((r=p==null?void 0:p.x)!=null?r:0),y:Number((o=p==null?void 0:p.y)!=null?o:0)};this.applyFinalOverride(e,"transform.position",u,this.dragStartValue)}else this.dragMode==="scale"?this.applyFinalOverride(e,"transform.scale",(l=d.scale)!=null?l:1,this.dragStartValue):this.dragMode==="rotate"&&this.applyFinalOverride(e,"transform.rotation",(c=d.rotation)!=null?c:0,this.dragStartValue);this.queueLiveApply(e)}window.dispatchEvent(new CustomEvent("inspector:refresh")),this.dragMode=null,this.dragStartPointer=null,this.dragStartPos=null,this.dragAnchorLocal=null,this.dragStartValue=null,this.dragContainer=null,window.removeEventListener("pointermove",this.onDragMove),window.removeEventListener("pointerup",this.onDragEnd)};this.onWheel=e=>{if(!this.app||!this.isVisible)return;e.preventDefault();let i=Math.sign(e.deltaY)<0?1.1:.9,n=Math.min(6,Math.max(.1,this.cameraScale*i)),a=new q(this.app.renderer.width/2,this.app.renderer.height/2),r=this.camera.toLocal(a);this.cameraScale=n,this.camera.scale.set(n);let o=this.camera.toGlobal(r);this.camera.position.set(this.camera.position.x+(a.x-o.x),this.camera.position.y+(a.y-o.y)),this.hasUserCamera=!0,this.updateGizmos(),this.updateGrid()};this.onPanStart=e=>{e.button===2&&(this.isPanning=!0,this.panStart={x:e.clientX,y:e.clientY},this.panStartCamera={x:this.camera.position.x,y:this.camera.position.y},this.hasUserCamera=!0)};this.onPanMove=e=>{if(!this.isPanning||!this.panStart||!this.panStartCamera)return;let t=e.clientX-this.panStart.x,i=e.clientY-this.panStart.y;this.camera.position.set(this.panStartCamera.x+t,this.panStartCamera.y+i),this.updateGrid()};this.onPanEnd=()=>{this.isPanning=!1,this.panStart=null,this.panStartCamera=null};this.root=e.root,this.getScreen=e.getScreen}async mount(){this.app||(this.app=new uo,await this.app.init({resizeTo:this.root,autoDensity:!0,resolution:window.devicePixelRatio||1,antialias:!0,backgroundAlpha:0}),this.root.innerHTML="",this.root.appendChild(this.app.canvas),this.root.style.position="relative",this.root.style.overflow="hidden",this.app.stage.sortableChildren=!0,this.app.stage.eventMode="static",this.camera.sortableChildren=!0,this.mainContainer.sortableChildren=!0,this.uiContainer.sortableChildren=!0,this.spawnPointLayer.sortableChildren=!0,this.gizmoLayer.sortableChildren=!0,this.app.stage.addChild(this.camera),this.camera.addChild(this.gridLayer),this.camera.addChild(this.screenFrame),this.camera.addChild(this.mainContainer),this.camera.addChild(this.uiContainer),this.camera.addChild(this.spawnPointLayer),this.camera.addChild(this.gameFrame),this.camera.addChild(this.gizmoLayer),this.gridLayer.zIndex=-2,this.gridLayer.eventMode="none",this.screenFrame.zIndex=-1,this.screenFrame.eventMode="none",this.mainContainer.zIndex=0,this.uiContainer.zIndex=5e4,this.spawnPointLayer.zIndex=8e4,this.spawnPointLayer.eventMode="passive",this.gameFrame.zIndex=85e3,this.gameFrame.eventMode="none",this.gizmoLayer.zIndex=1e5,this.gizmoLayer.addChild(this.gizmoOutline),this.gizmoLayer.addChild(this.moveHandle),this.gizmoLayer.addChild(this.scaleHandle),this.gizmoLayer.addChild(this.rotateHandle),this.gizmoOutline.eventMode="none",this.setupInteractions(),this.setupObservers(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.restoreScenePreferences(),this.refresh(),!this.isVisible&&this.app.ticker&&this.app.ticker.stop())}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.screenSyncRaf&&(cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=null),window.removeEventListener("handler-preview:screen",this.handleScreenChange),window.removeEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.removeEventListener("config:changed",this.handleConfigChanged),window.removeEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.removeEventListener("handler:layout-applied",this.handleLayoutApplied),window.removeEventListener("preview:select",this.handlePreviewSelect),window.removeEventListener("scene-editor:grid",this.handleGridSettings),window.removeEventListener("scene-editor:play-mode",this.handlePlayMode),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd),this.app&&(this.app.stage.off("pointerdown",this.onStagePointerDown),this.app.destroy(!0),this.app=null)}setVisible(e){this.isVisible=e,!(!this.app||!this.app.ticker)&&(e?(this.app.ticker.start(),this.refresh(),this.updateGrid()):this.app.ticker.stop())}refresh(){this.syncFromConfig()}setupObservers(){window.addEventListener("handler-preview:screen",this.handleScreenChange),window.addEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.addEventListener("config:changed",this.handleConfigChanged),window.addEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.addEventListener("handler:layout-applied",this.handleLayoutApplied),window.addEventListener("preview:select",this.handlePreviewSelect),window.addEventListener("scene-editor:grid",this.handleGridSettings),window.addEventListener("scene-editor:play-mode",this.handlePlayMode),this.resizeObserver=new ResizeObserver(()=>{this.handleResize()}),this.resizeObserver.observe(this.root)}setupInteractions(){if(!this.app)return;let e=this.app.canvas;e.addEventListener("contextmenu",t=>t.preventDefault()),e.addEventListener("wheel",this.onWheel,{passive:!1}),e.addEventListener("pointerdown",this.onPanStart),window.addEventListener("pointermove",this.onPanMove),window.addEventListener("pointerup",this.onPanEnd),this.app.stage.on("pointerdown",this.onStagePointerDown),this.moveHandle.eventMode="static",this.moveHandle.cursor="move",this.scaleHandle.eventMode="static",this.scaleHandle.cursor="nwse-resize",this.rotateHandle.eventMode="static",this.rotateHandle.cursor="crosshair",this.moveHandle.on("pointerdown",t=>this.startDrag("move",t)),this.scaleHandle.on("pointerdown",t=>this.startDrag("scale",t)),this.rotateHandle.on("pointerdown",t=>this.startDrag("rotate",t))}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}getPickCandidates(e){var i;let t=[];for(let[n,a]of this.objectMap.entries()){let r=a.displayObject;if(!r||r.visible===!1)continue;let o=(i=r.getBounds)==null?void 0:i.call(r);if(!o||o.width<=0||o.height<=0||e.x<o.x||e.x>o.x+o.width||e.y<o.y||e.y>o.y+o.height)continue;let l=r.parent,c=typeof(l==null?void 0:l.zIndex)=="number"?l.zIndex:0,d=typeof r.zIndex=="number"?r.zIndex:0,p=typeof(l==null?void 0:l.getChildIndex)=="function"?l.getChildIndex(r):0,u=c*1e6+d*1e3+p;t.push({id:n,order:u})}return t.sort((n,a)=>a.order-n.order),t.map(n=>n.id)}areSameIds(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}isGizmoTarget(e){return e&&this.spawnPointLayer.children.indexOf(e)!==-1?!0:e===this.moveHandle||e===this.scaleHandle||e===this.rotateHandle||e===this.gizmoOutline}restoreScenePreferences(){if(typeof window!="undefined"){try{let e=window.localStorage.getItem(this.getSceneStorageKey("grid_enabled")),t=window.localStorage.getItem(this.getSceneStorageKey("grid_gap")),i=window.localStorage.getItem(this.getSceneStorageKey("play_mode"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let n=Number(t);Number.isFinite(n)&&n>2&&(this.gridGap=n)}i!==null&&this.setPlayMode(i==="true")}catch{}this.updateGrid()}}getSceneStorageKey(e){let t=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${e}::${t}`}schedulePostScreenSync(e){this.screenSyncRaf&&cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=requestAnimationFrame(()=>{this.runPostScreenSync(e)})}async runPostScreenSync(e){this.screenSyncRaf=null,this.isVisible&&(this.updateLayout(e),this.hasUserCamera||this.centerCamera(),await this.syncFromConfig(),this.syncFromGameObjectsInternal(!0),this.updateGizmos(),this.updateGrid())}getRuntimeScreenSize(){var a,r,o,l,c,d,p;let e=window.gameApp;if(e!=null&&e.renderer){let u=e.renderer.screen,g=Number((a=u==null?void 0:u.width)!=null?a:0),h=Number((r=u==null?void 0:u.height)!=null?r:0);if(Number.isFinite(g)&&g>0&&Number.isFinite(h)&&h>0)return{width:g,height:h};let m=Number((o=e.renderer.resolution)!=null?o:1)||1,f=Number((l=e.renderer.width)!=null?l:0)/m,b=Number((c=e.renderer.height)!=null?c:0)/m;if(Number.isFinite(f)&&f>0&&Number.isFinite(b)&&b>0)return{width:f,height:b}}let t=document.querySelector(".game-container"),i=Number((d=t==null?void 0:t.dataset)==null?void 0:d.screenWidth),n=Number((p=t==null?void 0:t.dataset)==null?void 0:p.screenHeight);return Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:null}getRuntimeLayoutReference(){var i;let e=window.__mainContainer;if(e)return e;let t=window.gameApp;return(i=t==null?void 0:t.stage)!=null?i:null}getRuntimeParentContainer(e){var l,c;let t=window.gameObjectManager;if(!(t!=null&&t.get))return null;let i=t.get(e),n=((l=i==null?void 0:i.getDisplayObject)==null?void 0:l.call(i))||(i==null?void 0:i.pixiObject)||i,a=n==null?void 0:n.parent;if(!a)return null;let r=this.getRuntimeLayoutReference(),o=(c=window.gameApp)==null?void 0:c.stage;return r&&o&&r===o?this.mainContainer:r&&typeof r.contains=="function"&&r.contains(a)?this.mainContainer:a===r||a===o?this.mainContainer:this.uiContainer}applyRuntimeTransform(e){var r,o,l,c,d,p,u,g,h,m,f,b,v,x;if(!e)return!1;let t=Number((o=(r=e.scale)==null?void 0:r.x)!=null?o:1),i=Number((c=(l=e.scale)==null?void 0:l.y)!=null?c:t),n=Number((p=(d=e.position)==null?void 0:d.x)!=null?p:0),a=Number((g=(u=e.position)==null?void 0:u.y)!=null?g:0);if(!Number.isFinite(t)||!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(a))return!1;if(this.mainContainer.scale.set(t,i),this.uiContainer.scale.set(t,i),this.mainContainer.position.set(n,a),this.uiContainer.position.set(n,a),e.pivot&&((h=this.mainContainer.pivot)!=null&&h.set)&&((m=this.uiContainer.pivot)!=null&&m.set)){let y=Number((b=(f=e.pivot)==null?void 0:f.x)!=null?b:0),w=Number((x=(v=e.pivot)==null?void 0:v.y)!=null?x:0);Number.isFinite(y)&&Number.isFinite(w)&&(this.mainContainer.pivot.set(y,w),this.uiContainer.pivot.set(y,w))}return typeof e.rotation=="number"&&(this.mainContainer.rotation=e.rotation,this.uiContainer.rotation=e.rotation),!0}getEditableConfig(){return window.__editableConfig||null}getEditableObjectConfig(e){var n,a;let t=window.getEditableObjectConfig;if(typeof t=="function")return t(e);let i=this.getEditableConfig();return i!=null&&i.objects?typeof i.objects.get=="function"?(n=i.objects.get(e))!=null?n:null:(a=i.objects[e])!=null?a:null:null}getEditableObjectIds(){let e=window.getEditableObjectList;if(typeof e=="function"){let i=e();if(Array.isArray(i))return i}let t=this.getEditableConfig();return t!=null&&t.objects?typeof t.objects.keys=="function"?Array.from(t.objects.keys()):Object.keys(t.objects):[]}async syncFromConfig(e){if(!this.app)return;let t=this.getEditableConfig();if(!(t!=null&&t.objects))return;let i=e!=null&&e.length?e:this.getEditableObjectIds(),n=new Set(i);if(!e)for(let a of Array.from(this.objectMap.keys()))n.has(a)||this.removeObject(a);for(let a of i){let r=this.getEditableObjectConfig(a);if(!r){this.removeObject(a);continue}await this.upsertObject(a,r)}this.updateGizmos(),this.updateSpawnPointHandles(),this.updateGameFrame(this.getScreen())}removeObject(e){var i,n;let t=this.objectMap.get(e);if(t){try{(n=(i=t.displayObject)==null?void 0:i.destroy)==null||n.call(i)}catch{}this.objectMap.delete(e),this.selectedId===e&&this.setSelected(null,{silent:!0})}}async upsertObject(e,t){let i=this.getAssetKey(t),n=this.objectMap.get(e),a=this.isUiConfig(e,t),r=this.getRuntimeParentContainer(e),o=a?this.uiContainer:this.mainContainer,l=r!=null?r:o;if(!n||n.assetKey!==i||n.isUi!==a){n&&this.removeObject(e);let d=await this.createDisplayObject(e,t);if(!d)return;l.addChild(d),this.objectMap.set(e,{id:e,displayObject:d,assetKey:i,isUi:a}),this.attachObjectInteraction(d,e)}let c=this.objectMap.get(e);c&&(c.displayObject.parent!==l&&l.addChild(c.displayObject),this.applyVisualConfig(c.displayObject,t),this.updateObjectTransform(c.displayObject,t))}async createDisplayObject(e,t){var o,l,c,d,p,u,g,h,m,f,b,v,x,y,w;if((o=t==null?void 0:t.render)!=null&&o.asset)try{if(((c=(l=t==null?void 0:t.render)==null?void 0:l.asset)==null?void 0:c.type)!=="json"){let j=await xe.create(e,t,this.app);if(j instanceof Ge)return j}}catch(T){console.warn("[SceneEditor] ObjectFactory failed for",e,T)}let i=t==null?void 0:t.ui,n=(d=t==null?void 0:t.render)!=null?d:{},a=(i==null?void 0:i.text)||(i==null?void 0:i.kind)==="text";if(!!n.background_color){let T=this.getScreen(),j=(p=T==null?void 0:T.width)!=null?p:0,P=(u=T==null?void 0:T.height)!=null?u:0,_=new Ee,O=this.parseColor(n.background_color,0),L=typeof n.background_alpha=="number"?n.background_alpha:1;j>0&&P>0&&_.rect(0,0,j,P).fill({color:O,alpha:L});let A=new Ge;return A.addChild(_),A}if(a){let T=(h=(g=i==null?void 0:i.color)!=null?g:n==null?void 0:n.tint)!=null?h:"#ffffff",j=new ho({fontFamily:"Arial, sans-serif",fontSize:(m=i==null?void 0:i.fontSize)!=null?m:16,fill:T,align:(f=i==null?void 0:i.align)!=null?f:"center",letterSpacing:(b=i==null?void 0:i.letterSpacing)!=null?b:0});return new go({text:(v=i==null?void 0:i.text)!=null?v:"",style:j})}if((x=t==null?void 0:t.effects)!=null&&x.width||(y=t==null?void 0:t.effects)!=null&&y.height){let T=new Ee,j=typeof t.effects.width=="number"?t.effects.width:100,P=typeof t.effects.height=="number"?t.effects.height:100,_=(w=t.effects.fill_color)!=null?w:"#ffffff",O=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,L=Number.parseInt(String(_).replace("#",""),16);return T.rect(0,0,j,P).fill({color:Number.isFinite(L)?L:16777215,alpha:O}),T}return new Ge}attachObjectInteraction(e,t){if(e&&(e.eventMode="static",e.cursor="pointer",!e.hitArea&&typeof e.getLocalBounds=="function")){let i=e.getLocalBounds();i&&i.width>0&&i.height>0&&(e.hitArea=new Fr(i.x,i.y,i.width,i.height))}}getAssetKey(e){var i;let t=(i=e==null?void 0:e.render)==null?void 0:i.asset;return t?`${t.type||"asset"}::${t.path||""}`:null}isUiConfig(e,t){var a,r;let i=(((a=t==null?void 0:t.identity)==null?void 0:a.category)||"").toString().toLowerCase(),n=(((r=t==null?void 0:t.identity)==null?void 0:r.id)||e||"").toString().toLowerCase();return i.includes("ui")||n.startsWith("ui")||n.includes("label")}applyVisualConfig(e,t){var r,o,l,c,d,p,u;if(!e)return;let i=(r=t==null?void 0:t.render)!=null?r:{};typeof i.alpha=="number"&&(e.alpha=i.alpha),e.visible=i.visible!==!1,e.zIndex=typeof i.z_index=="number"?i.z_index:0;let n=(d=(c=(o=t==null?void 0:t.render)==null?void 0:o.anchor)!=null?c:(l=t==null?void 0:t.transform)==null?void 0:l.anchor)!=null?d:"center",a=Fe(n,{x:.5,y:.5});if((p=e.anchor)!=null&&p.set)e.anchor.set(a.x,a.y);else if(e.pivot){let g=(u=e.getLocalBounds)==null?void 0:u.call(e);g&&e.pivot.set(g.width*a.x,g.height*a.y)}}updateObjectTransform(e,t){var c;if(!e||this.playModeEnabled)return;let i=(c=t==null?void 0:t.transform)!=null?c:{},n=e.parent===this.uiContainer?this.uiContainer:this.mainContainer,a=this.getAnchorLocalPoint(i,n),r=this.getPositionOffset(i);a&&e.position.set(a.x+r.x,a.y+r.y);let o=typeof i.scale=="number"?i.scale:void 0;typeof o=="number"&&e.scale&&e.scale.set(o);let l=typeof i.rotation=="number"?i.rotation:0;typeof e.rotation=="number"&&(e.rotation=l)}getAnchorLocalPoint(e,t=this.mainContainer){var r;let i=this.getScreen();if(!(i!=null&&i.width)||!(i!=null&&i.height))return null;let n=(e==null?void 0:e.position_ratio)!=null?Ue(i.width,i.height,e.position_ratio):Be(i.width,i.height,(r=e==null?void 0:e.anchor)!=null?r:"center"),a=new q;return t.toLocal(new q(n.x,n.y),this.camera,a),a}getPositionOffset(e){var l,c,d,p,u,g,h,m;let t=e==null?void 0:e.position,i=e==null?void 0:e.offset,n=Array.isArray(t)?Number((l=t[0])!=null?l:0):Number((c=t==null?void 0:t.x)!=null?c:0),a=Array.isArray(t)?Number((d=t[1])!=null?d:0):Number((p=t==null?void 0:t.y)!=null?p:0),r=Array.isArray(i)?Number((u=i[0])!=null?u:0):Number((g=i==null?void 0:i.x)!=null?g:0),o=Array.isArray(i)?Number((h=i[1])!=null?h:0):Number((m=i==null?void 0:i.y)!=null?m:0);return{x:n+r,y:a+o}}updateLayout(e){var a,r,o,l,c,d,p,u;let t=e!=null?e:this.getScreen();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;let i=this.getRuntimeLayoutReference();if(!this.applyRuntimeTransform(i)){let h=(((r=(a=this.getEditableConfig())==null?void 0:a.engine)==null?void 0:r.runtime)||{}).layout||{},m=t.width*((o=B.layout.screen_scale_x)!=null?o:1),f=h.design_width_portrait||400,b=m/f;b=Math.min(b,1.15);let v=b*((l=B.engine.scale)!=null?l:1);this.mainContainer.scale.set(v),this.uiContainer.scale.set(v);let x=(c=h.main_container_anchor)!=null?c:"center",y=(d=h.main_container_position_ratio)!=null?d:{x:.5,y:.5},w=(p=h.main_container_offset)!=null?p:{x:0,y:0},T=h.main_container_position_ratio?Ue(t.width,t.height,y):Be(t.width,t.height,x),j=T.x+w.x+B.layout.position_offset.x,P=T.y+w.y+B.layout.position_offset.y;this.mainContainer.position.set(j,P),this.uiContainer.position.set(j,P)}this.screenFrame.clear(),this.screenFrame.rect(0,0,t.width,t.height),this.screenFrame.stroke({width:2,color:2894892,alpha:.5}),this.updateGameFrame(t),(u=this.app)!=null&&u.stage&&(this.app.stage.hitArea=new Fr(0,0,this.app.renderer.width,this.app.renderer.height)),this.updateSpawnPointHandles()}updateGrid(){if(!this.app)return;if(!this.gridEnabled){this.gridLayer.clear();return}let e=Math.max(4,this.gridGap),t=this.app.renderer,i=this.camera.toLocal(new q(0,0)),n=this.camera.toLocal(new q(t.width,t.height)),a=Math.min(i.x,n.x),r=Math.max(i.x,n.x),o=Math.min(i.y,n.y),l=Math.max(i.y,n.y),c=400,d=Math.ceil((r-a)/e),p=Math.ceil((l-o)/e),u=e*Math.max(1,Math.ceil(d/c)),g=e*Math.max(1,Math.ceil(p/c)),h=Math.floor(a/u)*u,m=Math.floor(o/g)*g;this.gridLayer.clear();for(let f=h;f<=r;f+=u)this.gridLayer.moveTo(f,o),this.gridLayer.lineTo(f,l);for(let f=m;f<=l;f+=g)this.gridLayer.moveTo(a,f),this.gridLayer.lineTo(r,f);this.gridLayer.stroke({width:1,color:16777215,alpha:.08})}updateGameFrame(e){var i;let t=(i=this.getRuntimeScreenSize())!=null?i:e;!(t!=null&&t.width)||!(t!=null&&t.height)||this.lastGameFrameSize&&this.lastGameFrameSize.width===t.width&&this.lastGameFrameSize.height===t.height||(this.lastGameFrameSize={width:t.width,height:t.height},this.gameFrame.clear(),this.gameFrame.rect(0,0,t.width,t.height),this.gameFrame.stroke({width:2,color:6333946,alpha:.35}))}setPlayMode(e){var t,i,n,a;this.playModeEnabled!==e&&(this.playModeEnabled=e,e?(this.moveHandle.eventMode="none",this.scaleHandle.eventMode="none",this.rotateHandle.eventMode="none",(i=(t=this.app)==null?void 0:t.ticker)==null||i.add(this.syncFromGameObjects)):(this.moveHandle.eventMode="static",this.scaleHandle.eventMode="static",this.rotateHandle.eventMode="static",(a=(n=this.app)==null?void 0:n.ticker)==null||a.remove(this.syncFromGameObjects),this.syncFromConfig()),this.updateGizmos(),this.updateSpawnPointHandles())}syncFromGameObjectsInternal(e){var n,a,r,o,l,c,d,p;if(!this.app||!this.isVisible||!e&&!this.playModeEnabled)return;let t=window.gameObjectManager;if(!(t!=null&&t.get))return;let i=this.dragMode?this.selectedId:null;for(let[u,g]of this.objectMap.entries()){if(i&&u===i)continue;let h=t.get(u),m=((n=h==null?void 0:h.getDisplayObject)==null?void 0:n.call(h))||(h==null?void 0:h.pixiObject)||h;if(!m)continue;let f=(r=(a=g.displayObject)==null?void 0:a.parent)!=null?r:this.mainContainer,b=new q;if(typeof m.getGlobalPosition=="function"){m.getGlobalPosition(b);let y=f.toLocal(b,this.camera);g.displayObject.position.set(y.x,y.y)}else if(m.worldTransform){b.set(m.worldTransform.tx,m.worldTransform.ty);let y=f.toLocal(b,this.camera);g.displayObject.position.set(y.x,y.y)}let v=this.getWorldScale(m);if(v){let y=Number((l=(o=f.scale)==null?void 0:o.x)!=null?l:1)||1,w=Number((d=(c=f.scale)==null?void 0:c.y)!=null?d:1)||1,T=v.x/y,j=v.y/w;(p=g.displayObject.scale)!=null&&p.set?g.displayObject.scale.set(T,j):g.displayObject.scale&&(g.displayObject.scale.x=T,g.displayObject.scale.y=j)}let x=this.getWorldRotation(m);typeof x=="number"&&(g.displayObject.rotation=x),typeof m.zIndex=="number"&&(g.displayObject.zIndex=m.zIndex)}this.updateGizmos()}getWorldScale(e){var a,r;let t=(r=e==null?void 0:e.worldTransform)!=null?r:(a=e==null?void 0:e.transform)==null?void 0:a.worldTransform;if(!t)return null;let i=Math.sqrt(t.a*t.a+t.b*t.b),n=Math.sqrt(t.c*t.c+t.d*t.d);return!Number.isFinite(i)||!Number.isFinite(n)?null:{x:i,y:n}}getWorldRotation(e){var i,n;let t=(n=e==null?void 0:e.worldTransform)!=null?n:(i=e==null?void 0:e.transform)==null?void 0:i.worldTransform;if(t){let a=Math.atan2(t.b,t.a);return Number.isFinite(a)?a:null}return typeof(e==null?void 0:e.rotation)=="number"?e.rotation:null}centerCamera(){var a;if(!this.app)return;let e=(a=this.getRuntimeScreenSize())!=null?a:this.getScreen();if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=this.app.renderer.width,i=this.app.renderer.height,n=Math.max(.01,Math.min(t/e.width,i/e.height));this.cameraScale=n,this.camera.scale.set(n),this.camera.position.set((t-e.width*n)/2,(i-e.height*n)/2)}updateGizmos(){var d,p;if(!this.selectedId||!this.isVisible){this.clearGizmos();return}let e=this.objectMap.get(this.selectedId);if(!(e!=null&&e.displayObject)){this.clearGizmos();return}let t=(p=(d=e.displayObject).getBounds)==null?void 0:p.call(d);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let i=this.camera.toLocal(new q(t.x,t.y)),n=this.camera.toLocal(new q(t.x+t.width,t.y+t.height)),a=n.x-i.x,r=n.y-i.y,o=i.x+a/2,l=i.y+r/2;if(this.gizmoOutline.clear(),this.gizmoOutline.rect(i.x,i.y,a,r),this.gizmoOutline.stroke({width:2,color:16752394,alpha:.9}),this.playModeEnabled){this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear();return}let c=10;this.moveHandle.clear(),this.moveHandle.circle(0,0,c/2),this.moveHandle.fill({color:16752394,alpha:.9}),this.moveHandle.position.set(o,l),this.scaleHandle.clear(),this.scaleHandle.rect(-c/2,-c/2,c,c),this.scaleHandle.fill({color:3900150,alpha:.9}),this.scaleHandle.position.set(n.x,n.y),this.rotateHandle.clear(),this.rotateHandle.circle(0,0,c/2),this.rotateHandle.fill({color:1096065,alpha:.9}),this.rotateHandle.position.set(o,i.y-20)}clearGizmos(){this.gizmoOutline.clear(),this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear()}updateSpawnPointHandles(){if(this.clearSpawnPointHandles(),!this.selectedId)return;let e=this.getEditableObjectConfig(this.selectedId);if(!e||!this.isSpawnerConfig(e))return;let t=this.getSpawnPoints(e);!t||t.length===0||t.forEach((i,n)=>{let a=new Ee;a.circle(0,0,5).fill({color:16096779,alpha:.9}),a.circle(0,0,9).stroke({width:1,color:16096779,alpha:.45});let r=this.toCameraFromMain(i);a.position.set(r.x,r.y),a.cursor="move",a.eventMode=this.playModeEnabled?"none":"static",a.on("pointerdown",o=>this.startSpawnPointDrag(n,o)),this.spawnPointLayer.addChild(a)})}clearSpawnPointHandles(){this.spawnPointLayer.removeChildren().forEach(t=>{var i;(i=t.destroy)==null||i.call(t)})}isSpawnerConfig(e){var i,n;return((i=e==null?void 0:e.logic)==null?void 0:i.id)==="Spawner"?!0:String(((n=e==null?void 0:e.identity)==null?void 0:n.system_role)||"").toLowerCase().includes("spawner")}getSpawnPoints(e){var i,n;let t=(n=(i=e==null?void 0:e.logic)==null?void 0:i.props)==null?void 0:n.spawnPoints;return Array.isArray(t)?t.map(a=>{var r,o;return{x:Number((r=a==null?void 0:a.x)!=null?r:0),y:Number((o=a==null?void 0:a.y)!=null?o:0)}}):null}toCameraFromMain(e){let t=this.mainContainer.toGlobal(new q(e.x,e.y)),i=new q;return this.camera.toLocal(t,void 0,i),i}startSpawnPointDrag(e,t){var o,l;if(!this.selectedId||this.playModeEnabled)return;let i=this.getEditableObjectConfig(this.selectedId);if(!i)return;let n=this.getSpawnPoints(i);if(!n||!n[e])return;(o=t==null?void 0:t.stopPropagation)==null||o.call(t),(l=t==null?void 0:t.stopImmediatePropagation)==null||l.call(t);let a=this.getEventLocalPoint(t,this.mainContainer);if(!a)return;let r=n[e];this.spawnPointDrag={objectId:this.selectedId,index:e,offset:new q(r.x-a.x,r.y-a.y),startPoints:n.map(c=>({x:c.x,y:c.y}))},window.addEventListener("pointermove",this.onSpawnPointDragMove),window.addEventListener("pointerup",this.onSpawnPointDragEnd)}updateLiveSpawnPoint(e,t,i,n){let a=this.getEditableObjectConfig(e);if(!a)return;let r=this.getSpawnPoints(a);if(!r||!r[t])return;let o=r.map((l,c)=>c===t?{x:i,y:n}:{x:l.x,y:l.y});this.setNestedValue(a,"logic.props.spawnPoints",o),this.queueLiveApply(e),this.updateSpawnPointHandles()}setSelected(e,t={}){if(this.selectedId!==e&&(this.selectedId=e,this.updateGizmos(),this.updateSpawnPointHandles(),!t.silent&&e)){let i=window.__previewSelectObject;typeof i=="function"&&i(e)}}startDrag(e,t){var d,p,u,g;if(!this.selectedId||!e||!this.app||this.playModeEnabled||this.getPointerButton(t)!==0)return;let n=this.objectMap.get(this.selectedId);if(!n)return;this.dragContainer=(p=(d=n.displayObject)==null?void 0:d.parent)!=null?p:this.mainContainer;let a=this.getEventLocalPoint(t,this.dragContainer);if(!a)return;let r=n.displayObject;this.dragMode=e,this.dragStartPointer=new q(a.x,a.y),this.dragStartPos=new q(r.position.x,r.position.y),this.dragStartScale=typeof((u=r.scale)==null?void 0:u.x)=="number"?r.scale.x:1;let o=this.getEditableObjectConfig(this.selectedId),l=(g=o==null?void 0:o.transform)!=null?g:{};this.dragStartRotation=typeof l.rotation=="number"?l.rotation:0,this.dragAnchorLocal=this.getAnchorLocalPoint(l,this.dragContainer),this.dragStartValue=this.getDragStartValue(e,l);let c=new q(r.position.x,r.position.y);this.dragStartAngle=Math.atan2(a.y-c.y,a.x-c.x),this.dragStartDistance=Math.max(1,this.distance(a,c)),window.addEventListener("pointermove",this.onDragMove),window.addEventListener("pointerup",this.onDragEnd)}getDragStartValue(e,t){var i,n,a;return e==="move"?(i=t==null?void 0:t.position)!=null?i:{x:0,y:0}:e==="scale"?(n=t==null?void 0:t.scale)!=null?n:1:e==="rotate"?(a=t==null?void 0:t.rotation)!=null?a:0:null}updateLiveConfigPosition(e,t){var p,u,g,h,m,f;if(!this.selectedId||!this.dragAnchorLocal)return;let i=e-this.dragAnchorLocal.x,n=t-this.dragAnchorLocal.y,a=this.getEditableObjectConfig(this.selectedId);if(!a)return;let r=(p=a.transform)!=null?p:{};a.transform||(a.transform=r);let o=(u=r.offset)!=null?u:{x:0,y:0},l=Array.isArray(o)?Number((g=o[0])!=null?g:0):Number((h=o==null?void 0:o.x)!=null?h:0),c=Array.isArray(o)?Number((m=o[1])!=null?m:0):Number((f=o==null?void 0:o.y)!=null?f:0),d=this.buildPositionValue(r,{x:i-l,y:n-c});this.setNestedValue(r,"position",d)}updateLiveConfigScale(e){var n;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(n=t.transform)!=null?n:{};t.transform||(t.transform=i),i.scale=e}updateLiveConfigRotation(e){var n;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(n=t.transform)!=null?n:{};t.transform||(t.transform=i),i.rotation=e}applyFinalOverride(e,t,i,n){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),n),Re({objectId:e,path:t,value:i},{persist:!0,emitEvent:!0,trackHistory:!0})}queueLiveApply(e){this.applyQueuedId=e,!this.applyQueued&&(this.applyQueued=!0,requestAnimationFrame(()=>{this.applyQueued=!1;let t=this.applyQueuedId;if(!t)return;let i=this.getEditableObjectConfig(t),n=window.applyEditableObjectConfig;typeof n=="function"&&i&&n(t,i)}))}setNestedValue(e,t,i){let n=t.split("."),a=e;for(let r=0;r<n.length-1;r+=1){let o=n[r];(!a[o]||typeof a[o]!="object")&&(a[o]={}),a=a[o]}a[n[n.length-1]]=i}buildPositionValue(e,t){let i=e==null?void 0:e.position;return Array.isArray(i)?[t.x,t.y]:{x:t.x,y:t.y}}distance(e,t){let i=e.x-t.x,n=e.y-t.y;return Math.sqrt(i*i+n*n)}getPointerButton(e){var t,i,n;return typeof(e==null?void 0:e.button)=="number"?e.button:typeof((t=e==null?void 0:e.data)==null?void 0:t.button)=="number"?e.data.button:typeof((n=(i=e==null?void 0:e.data)==null?void 0:i.originalEvent)==null?void 0:n.button)=="number"?e.data.originalEvent.button:0}getEventGlobalPoint(e){var l,c;let t=(c=e==null?void 0:e.global)!=null?c:(l=e==null?void 0:e.data)==null?void 0:l.global;if(t)return new q(t.x,t.y);if(!this.app)return null;let i=e==null?void 0:e.clientX,n=e==null?void 0:e.clientY;if(typeof i!="number"||typeof n!="number")return null;let a=this.app.canvas.getBoundingClientRect(),r=(i-a.left)*(this.app.renderer.width/a.width),o=(n-a.top)*(this.app.renderer.height/a.height);return new q(r,o)}getEventLocalPoint(e,t=this.mainContainer){var a,r;if(!this.app)return null;if(typeof(e==null?void 0:e.getLocalPosition)=="function"){let o=e.getLocalPosition(t);return new q(o.x,o.y)}let i=(r=e==null?void 0:e.global)!=null?r:(a=e==null?void 0:e.data)==null?void 0:a.global;if(!i)return null;let n=new q;return t.toLocal(new q(i.x,i.y),void 0,n),n}getPointerInContainer(e,t,i){if(!this.app)return null;let n=this.app.canvas.getBoundingClientRect(),a=(e-n.left)*(this.app.renderer.width/n.width),r=(t-n.top)*(this.app.renderer.height/n.height),o=new q;return i.toLocal(new q(a,r),void 0,o),o}parseColor(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=e.trim().replace("#",""),n=Number.parseInt(i,16);if(Number.isFinite(n))return n}return t}};var Fn=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[at("playable-portrait"),at("iphone-14"),at("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.isSpaceKeyPressed=!1;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.originalConsole={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console)};this.sceneEditor=null;this.sceneVisiblePreference=!0;this.sceneVisible=!0;this.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.hasUnsavedChanges=!1;this.onWindowResize=e=>{if(this.ignoreNextWindowResize){this.ignoreNextWindowResize=!1;return}this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()};this.onFrameDragMove=e=>{if(!this.frameDragActive)return;let t=e.clientX-this.frameDragStartX,i=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+i,this.applyFrameDrag(),this.updateDragCursor()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd),this.updateDragCursor())};this.options=e,this.currentPreset=at(e.defaultDevice||ln.id),this.debugPanel=new Mi,this.container=this.createShell(),this.previewContainer=this.mustQuery(".preview-container"),this.singleStage=this.mustQuery('[data-preview-stage="single"]'),this.compareStage=this.mustQuery('[data-preview-stage="compare"]'),this.frameDragger=this.mustQuery(".frame-dragger"),this.frameWrapper=this.mustQuery(".frame-wrapper"),this.deviceFrame=this.mustQuery(".device-frame"),this.gameContainer=this.mustQuery(".game-container"),this.scenePane=this.mustQuery("[data-scene-pane]"),this.sceneRoot=this.mustQuery("#scene-editor-root"),this.sceneSplitter=this.mustQuery("[data-scene-splitter]"),this.gameViewPane=this.mustQuery("[data-game-pane]"),this.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners();try{let t=window.localStorage.getItem(this.getSceneVisibilityStorageKey());this.sceneVisiblePreference=t===null?!0:t==="true"}catch{}this.sceneEditor=new $i({root:this.sceneRoot,getScreen:()=>this.getScreen()}),this.sceneEditor.mount(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setupShortcutListeners(),this.setupUnsavedChangesIndicator(),this.setupScenePaneInteractions(),this.updateSceneVisibility(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.updateDockState(),this.isInitialized=!0}getShortcutKey(){return typeof navigator!="undefined"&&navigator.platform.toUpperCase().indexOf("MAC")>=0?"CMD":"CTRL"}mount(e=document.body){e.innerHTML="",e.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1,this.sceneEditor&&(this.sceneEditor.destroy(),this.sceneEditor=null)}getGameContainer(){return this.gameContainer}getScreen(){let e=this.getEffectivePreset();return{width:e.width,height:e.height}}getEffectivePreset(){var e;return this.isLandscape?{...this.currentPreset,width:this.currentPreset.height,height:this.currentPreset.width,ratio:((e=this.currentPreset.ratio)==null?void 0:e.split(":").reverse().join(":"))||this.currentPreset.ratio}:this.currentPreset}notifyGameLoaded(){var e;this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh(),(e=this.sceneEditor)==null||e.refresh(),requestAnimationFrame(()=>this.updatePanelPositions())}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(e,t={}){var n,a;let i=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=at(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:i}),t.suppressCallback||(a=(n=this.options).onDeviceChange)==null||a.call(n,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark"),requestAnimationFrame(()=>this.updatePanelPositions())}setLayoutMode(e){if(this.layoutMode===e)return;this.layoutMode=e,this.container.classList.toggle("layout-fixed",e==="fixed"),this.container.classList.toggle("layout-draggable",e==="draggable"),Array.from(this.container.querySelectorAll("[data-layout-toggle]")).forEach(n=>n.classList.toggle("active",n.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(n=>{n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),this.updateSceneVisibility(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}updateDockState(){let e=this.container.querySelector("#bottom-dock");e==null||e.classList.remove("hidden");let t=this.container.querySelector("#console-messages"),i=this.container.querySelector("#dock-console-content");t&&i&&t.parentElement!==i&&i.appendChild(t)}makeBottomDockResizable(e,t){let i,n,a=o=>{let l=o.clientY-i,c=Math.max(100,Math.min(800,n-l));e.style.height=`${c}px`;let d=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:d})},r=()=>{document.removeEventListener("pointermove",a),document.removeEventListener("pointerup",r),e.classList.remove("resizing")};t.addEventListener("pointerdown",o=>{o.preventDefault(),i=o.clientY,n=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",r),e.classList.add("resizing")})}makeSidebarResizable(e,t,i){let n,a,r=l=>{let c=i==="left"?l.clientX-n:n-l.clientX,d=Math.max(200,Math.min(600,a+c));e.style.width=`${d}px`;let p=this.container.querySelector(".preview-main");if(p){let g=i==="left"?`${d}px`:p.style.gridTemplateColumns.split(" ")[0]||"300px",h=i==="right"?`${d}px`:p.style.gridTemplateColumns.split(" ")[2]||"350px";p.style.gridTemplateColumns=`${g} 1fr ${h}`}let u=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:u})},o=()=>{document.removeEventListener("pointermove",r),document.removeEventListener("pointerup",o),e.classList.remove("resizing")};t.addEventListener("pointerdown",l=>{l.preventDefault(),n=l.clientX,a=e.offsetWidth,document.addEventListener("pointermove",r),document.addEventListener("pointerup",o),e.classList.add("resizing")})}getSceneVisibilityStorageKey(){return`handler_preview_scene_visible::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getSceneWidthStorageKey(){return`handler_preview_scene_width::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}setupScenePaneInteractions(){let e=this.scenePane.querySelector("[data-scene-drag-handle]"),t=this.scenePane.querySelector("[data-scene-resize]"),i=this.container.querySelector("[data-preview-split]");e&&Xe(this.scenePane,e,i!=null?i:this.previewContainer),t&&Ti(this.scenePane,t,void 0,260,200);let n=this.getStoredSceneWidth();n&&(this.scenePane.style.width=`${n}px`),this.sceneSplitter.addEventListener("pointerdown",a=>{if(this.layoutMode!=="fixed"||!this.sceneVisible)return;a.preventDefault();let r=a.clientX,o=this.scenePane.offsetWidth,l=Math.max(260,Math.min(720,this.previewContainer.clientWidth*.6)),c=p=>{let u=p.clientX-r,g=Math.max(240,Math.min(l,o+u));this.scenePane.style.width=`${g}px`;let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},d=()=>{document.removeEventListener("pointermove",c),document.removeEventListener("pointerup",d),this.storeSceneWidth(this.scenePane.offsetWidth)};document.addEventListener("pointermove",c),document.addEventListener("pointerup",d)})}storeSceneWidth(e){try{window.localStorage.setItem(this.getSceneWidthStorageKey(),String(e))}catch{}}getStoredSceneWidth(){try{let e=window.localStorage.getItem(this.getSceneWidthStorageKey()),t=e?Number(e):null;return Number.isFinite(t)&&t?t:null}catch{return null}}updateSceneVisibility(){let e=this.viewMode==="single"&&this.sceneVisiblePreference;this.setSceneVisible(e,{persist:!1});let t=this.container.querySelector("#scene-toggle");t&&(t.classList.toggle("active",this.sceneVisiblePreference),t.setAttribute("aria-pressed",String(this.sceneVisiblePreference)))}setSceneVisible(e,t={}){var i;if(this.sceneVisible=e,this.container.classList.toggle("scene-hidden",!e),(i=this.sceneEditor)==null||i.setVisible(e),t.persist!==!1){this.sceneVisiblePreference=e;try{window.localStorage.setItem(this.getSceneVisibilityStorageKey(),String(e))}catch{}}this.scheduleFit()}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell layout-fixed",e.innerHTML=`
2238
2238
  <div class="preview-toolbar">
2239
2239
  <div class="preview-toolbar-left">
2240
2240
  <span class="preview-logo">PREVIEWER</span>